From 6ad5d7070a0ddc5ccd6b9d47329b247733ea38ad Mon Sep 17 00:00:00 2001 From: Petr Vanek Date: Wed, 22 Jun 2011 13:12:21 +0200 Subject: [PATCH] merge changes from the experimental "bundle" repository --- CMakeLists.txt | 11 +- cmake/cmake_uninstall.cmake.in | 23 + lib/CMakeLists.txt | 63 +- lib/Character.h | 164 +- lib/CharacterColor.h | 304 +- lib/ColorScheme.cpp | 775 ++++ lib/ColorScheme.h | 346 ++ lib/ColorTables.h | 6 +- lib/Emulation.cpp | 431 +-- lib/Emulation.h | 661 ++-- lib/Filter.cpp | 309 +- lib/Filter.h | 255 +- lib/History.cpp | 812 +++-- lib/History.h | 500 ++- lib/KeyboardTranslator.cpp | 778 ++--- lib/KeyboardTranslator.h | 395 +-- lib/Pty.cpp | 377 +- lib/Pty.h | 181 +- lib/Screen.cpp | 1335 +++---- lib/Screen.h | 546 +-- lib/ScreenWindow.cpp | 94 +- lib/ScreenWindow.h | 106 +- lib/Session.cpp | 56 +- lib/Session.h | 8 +- lib/TerminalCharacterDecoder.cpp | 94 +- lib/TerminalCharacterDecoder.h | 42 +- lib/TerminalDisplay.cpp | 3107 +++++++++-------- lib/TerminalDisplay.h | 353 +- lib/Vt102Emulation.cpp | 2186 +++++------- lib/Vt102Emulation.h | 243 +- lib/color-schemes/BlackOnLightYellow.schema | 42 + .../BlackOnRandomLight.colorscheme | 104 + lib/color-schemes/BlackOnWhite.schema | 42 + lib/color-schemes/CMakeLists.txt | 13 + lib/color-schemes/DarkPastels.colorscheme | 103 + lib/color-schemes/GreenOnBlack.colorscheme | 104 + lib/color-schemes/Linux.colorscheme | 100 + lib/color-schemes/WhiteOnBlack.schema | 42 + .../historic/BlackOnLightColor.schema | 42 + lib/color-schemes/historic/DarkPicture.schema | 44 + lib/color-schemes/historic/Example.Schema | 47 + .../historic/GreenOnBlack.schema | 42 + lib/color-schemes/historic/GreenTint.schema | 49 + .../historic/GreenTint_MC.schema | 49 + .../historic/LightPicture.schema | 44 + lib/color-schemes/historic/Linux.schema | 47 + lib/color-schemes/historic/README.Schema | 132 + .../historic/README.default.Schema | 44 + lib/color-schemes/historic/Transparent.schema | 49 + .../historic/Transparent_MC.schema | 51 + .../historic/Transparent_darkbg.schema | 42 + .../historic/Transparent_lightbg.schema | 51 + lib/color-schemes/historic/XTerm.schema | 46 + lib/color-schemes/historic/syscolor.schema | 44 + lib/color-schemes/historic/vim.schema | 40 + lib/k3process.cpp | 1095 ------ lib/k3process.h | 891 ----- lib/k3processcontroller.cpp | 338 -- lib/k3processcontroller.h | 136 - lib/kb-layouts/macbook.keytab | 175 + lib/kprocess.cpp | 412 +++ lib/kprocess.h | 372 ++ lib/kpty.cpp | 62 + lib/kpty.h | 3 + lib/kpty_p.h | 2 + lib/kptydevice.cpp | 422 +++ lib/kptydevice.h | 360 ++ lib/kptyprocess.cpp | 129 + lib/kptyprocess.h | 178 + lib/qtermwidget.cpp | 42 +- lib/qtermwidget.h | 7 +- lib/tools.cpp | 80 + lib/tools.h | 10 + 73 files changed, 11223 insertions(+), 9465 deletions(-) create mode 100644 cmake/cmake_uninstall.cmake.in create mode 100644 lib/ColorScheme.cpp create mode 100644 lib/ColorScheme.h create mode 100644 lib/color-schemes/BlackOnLightYellow.schema create mode 100644 lib/color-schemes/BlackOnRandomLight.colorscheme create mode 100644 lib/color-schemes/BlackOnWhite.schema create mode 100644 lib/color-schemes/CMakeLists.txt create mode 100644 lib/color-schemes/DarkPastels.colorscheme create mode 100644 lib/color-schemes/GreenOnBlack.colorscheme create mode 100644 lib/color-schemes/Linux.colorscheme create mode 100644 lib/color-schemes/WhiteOnBlack.schema create mode 100644 lib/color-schemes/historic/BlackOnLightColor.schema create mode 100644 lib/color-schemes/historic/DarkPicture.schema create mode 100644 lib/color-schemes/historic/Example.Schema create mode 100644 lib/color-schemes/historic/GreenOnBlack.schema create mode 100644 lib/color-schemes/historic/GreenTint.schema create mode 100644 lib/color-schemes/historic/GreenTint_MC.schema create mode 100644 lib/color-schemes/historic/LightPicture.schema create mode 100644 lib/color-schemes/historic/Linux.schema create mode 100644 lib/color-schemes/historic/README.Schema create mode 100644 lib/color-schemes/historic/README.default.Schema create mode 100644 lib/color-schemes/historic/Transparent.schema create mode 100644 lib/color-schemes/historic/Transparent_MC.schema create mode 100644 lib/color-schemes/historic/Transparent_darkbg.schema create mode 100644 lib/color-schemes/historic/Transparent_lightbg.schema create mode 100644 lib/color-schemes/historic/XTerm.schema create mode 100644 lib/color-schemes/historic/syscolor.schema create mode 100644 lib/color-schemes/historic/vim.schema delete mode 100644 lib/k3process.cpp delete mode 100644 lib/k3process.h delete mode 100644 lib/k3processcontroller.cpp delete mode 100644 lib/k3processcontroller.h create mode 100644 lib/kb-layouts/macbook.keytab create mode 100644 lib/kprocess.cpp create mode 100644 lib/kprocess.h create mode 100644 lib/kptydevice.cpp create mode 100644 lib/kptydevice.h create mode 100644 lib/kptyprocess.cpp create mode 100644 lib/kptyprocess.h create mode 100644 lib/tools.cpp create mode 100644 lib/tools.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 580ba6b..272f37f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -11,7 +11,7 @@ project( qtermwidget ) #| Library Versioning #| Libraries are not versioned by default set ( qtermwidget_VERSION_MAJOR "0" ) -set ( qtermwidget_VERSION_MINOR "2" ) +set ( qtermwidget_VERSION_MINOR "4" ) set ( qtermwidget_VERSION_PATCH "0" ) set ( qtermwidget_VERSION "${qtermwidget_VERSION_MAJOR}.${qtermwidget_VERSION_MINOR}.${qtermwidget_VERSION_PATCH}" @@ -29,6 +29,15 @@ IF (WANT_UNIVERSAL) ENDIF (WANT_UNIVERSAL) +CONFIGURE_FILE( + "${CMAKE_CURRENT_SOURCE_DIR}/cmake/cmake_uninstall.cmake.in" + "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake" + IMMEDIATE @ONLY +) +ADD_CUSTOM_TARGET(uninstall + "${CMAKE_COMMAND}" -P "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake") + + # make dist custom target SET(CPACK_PACKAGE_NAME "qtermwidget") # TODO/FIXME: versioning from player subdir... I don't know why it's separated... diff --git a/cmake/cmake_uninstall.cmake.in b/cmake/cmake_uninstall.cmake.in new file mode 100644 index 0000000..02cb12d --- /dev/null +++ b/cmake/cmake_uninstall.cmake.in @@ -0,0 +1,23 @@ +IF(NOT EXISTS "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt") + MESSAGE(FATAL_ERROR "Cannot find install manifest: \"@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt\"") +ENDIF(NOT EXISTS "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt") + +# this works on Linux, but not on mac. +#FILE(READ "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt" files) +#STRING(REGEX REPLACE "\n" ";" files "${files}") +#FOREACH(file ${files}) +# MESSAGE(STATUS "Uninstalling \"${file}\"") +# IF(NOT EXISTS "${file}") +# MESSAGE(FATAL_ERROR "File \"${file}\" does not exists.") +# ENDIF(NOT EXISTS "${file}") +# EXEC_PROGRAM("@CMAKE_COMMAND@" ARGS "-E remove \"${file}\"" +# OUTPUT_VARIABLE rm_out +# RETURN_VARIABLE rm_retval) +# IF("${rm_retval}" GREATER 0) +# MESSAGE(FATAL_ERROR "Problem when removing \"${file}\"") +# ENDIF("${rm_retval}" GREATER 0) +#ENDFOREACH(file) + +EXEC_PROGRAM("xargs rm < @CMAKE_BINARY_DIR@/install_manifest.txt" + OUTPUT_VARIABLE rm_out + RETURN_VARIABLE rm_ret) diff --git a/lib/CMakeLists.txt b/lib/CMakeLists.txt index a0ba5f9..0d0aab0 100644 --- a/lib/CMakeLists.txt +++ b/lib/CMakeLists.txt @@ -38,49 +38,48 @@ ENDIF (NOT LIB_SUFFIX) #| Sources set ( SRCS - TerminalCharacterDecoder.cpp - KeyboardTranslator.cpp - Screen.cpp History.cpp BlockArray.cpp - konsole_wcwidth.cpp - ScreenWindow.cpp - Emulation.cpp - Vt102Emulation.cpp - TerminalDisplay.cpp + ColorScheme.cpp + Emulation.cpp Filter.cpp - Pty.cpp kpty.cpp - k3process.cpp - k3processcontroller.cpp - Session.cpp + History.cpp + KeyboardTranslator.cpp + konsole_wcwidth.cpp + kprocess.cpp + kpty.cpp + kptydevice.cpp + kptyprocess.cpp + Pty.cpp + qtermwidget.cpp + Screen.cpp + ScreenWindow.cpp + Session.cpp ShellCommand.cpp - qtermwidget.cpp + TerminalCharacterDecoder.cpp + TerminalDisplay.cpp + tools.cpp + Vt102Emulation.cpp ) #| Headers #| Only the Headers that need to be moc'd go here set ( HDRS - ScreenWindow.h - Emulation.h - Vt102Emulation.h - TerminalDisplay.h + Emulation.h Filter.h - Pty.h - k3process.h - k3processcontroller.h - Session.h - qtermwidget.h + kprocess.h + kptydevice.h + kptyprocess.h + Pty.h + qtermwidget.h + ScreenWindow.h + Session.h + TerminalDisplay.h + Vt102Emulation.h ) set ( HDRS_DISTRIB ${CMAKE_SOURCE_DIR}/lib/qtermwidget.h ) -#| Library Output -#| CMake supports out-of-source builds, so the binary dir is not -#| necessarily the same as the source directory -set ( LIBRARY_OUTPUT_PATH - ${PROJECT_BINARY_DIR}/../. -) - #| Qt4 Required Options add_definitions ( -Wall ) @@ -101,6 +100,10 @@ set ( KB_LAYOUT_DIR ${CMAKE_INSTALL_PREFIX}/share/qtermwidget/kb-layouts/ ) message ( STATUS "Keyboard layouts will be installed in: ${KB_LAYOUT_DIR}" ) add_definitions( -DKB_LAYOUT_DIR="\\"${KB_LAYOUT_DIR}\\"" ) +set ( COLORSCHEMES_DIR ${CMAKE_INSTALL_PREFIX}/share/qtermwidget/color-schemes/ ) +message ( STATUS "Color schemes will be insatlled in: ${COLORSCHEMES_DIR}" ) +add_definitions( -DCOLORSCHEMES_DIR="\\"${COLORSCHEMES_DIR}\\"" ) + #| Defines add_definitions ( -DHAVE_POSIX_OPENPT ) #add_definitions( -DHAVE_GETPT ) @@ -152,6 +155,8 @@ install(FILES ${HDRS_DISTRIB} DESTINATION include) # keyboard layouts install(DIRECTORY kb-layouts/ DESTINATION ${KB_LAYOUT_DIR} FILES_MATCHING PATTERN "*.keytab" ) +# color schemes +install(DIRECTORY color-schemes/ DESTINATION ${COLORSCHEMES_DIR} FILES_MATCHING PATTERN "*.*schem*") # diff --git a/lib/Character.h b/lib/Character.h index 2825704..4088def 100644 --- a/lib/Character.h +++ b/lib/Character.h @@ -1,6 +1,6 @@ /* This file is part of Konsole, KDE's terminal. - + Copyright 2007-2008 by Robert Knight Copyright 1997,1998 by Lars Doelle @@ -29,7 +29,8 @@ // Local #include "CharacterColor.h" -namespace Konsole { +namespace Konsole +{ typedef unsigned char LineProperty; @@ -52,103 +53,105 @@ static const int LINE_DOUBLEHEIGHT = (1 << 2); * value, foreground and background colors and a set of rendition attributes * which specify how it should be drawn. */ -class Character { +class Character +{ public: - /** - * Constructs a new character. + /** + * Constructs a new character. + * + * @param _c The unicode character value of this character. + * @param _f The foreground color used to draw the character. + * @param _b The color used to draw the character's background. + * @param _r A set of rendition flags which specify how this character is to be drawn. + */ + inline Character(quint16 _c = ' ', + CharacterColor _f = CharacterColor(COLOR_SPACE_DEFAULT,DEFAULT_FORE_COLOR), + CharacterColor _b = CharacterColor(COLOR_SPACE_DEFAULT,DEFAULT_BACK_COLOR), + quint8 _r = DEFAULT_RENDITION) + : character(_c), rendition(_r), foregroundColor(_f), backgroundColor(_b) {} + + union + { + /** The unicode character value for this character. */ + quint16 character; + /** + * Experimental addition which allows a single Character instance to contain more than + * one unicode character. * - * @param _c The unicode character value of this character. - * @param _f The foreground color used to draw the character. - * @param _b The color used to draw the character's background. - * @param _r A set of rendition flags which specify how this character is to be drawn. + * charSequence is a hash code which can be used to look up the unicode + * character sequence in the ExtendedCharTable used to create the sequence. */ - inline Character(quint16 _c = ' ', - CharacterColor _f = CharacterColor(COLOR_SPACE_DEFAULT,DEFAULT_FORE_COLOR), - CharacterColor _b = CharacterColor(COLOR_SPACE_DEFAULT,DEFAULT_BACK_COLOR), - quint8 _r = DEFAULT_RENDITION) - : character(_c), rendition(_r), foregroundColor(_f), backgroundColor(_b) {} + quint16 charSequence; + }; - union { - /** The unicode character value for this character. */ - quint16 character; - /** - * Experimental addition which allows a single Character instance to contain more than - * one unicode character. - * - * charSequence is a hash code which can be used to look up the unicode - * character sequence in the ExtendedCharTable used to create the sequence. - */ - quint16 charSequence; - }; + /** A combination of RENDITION flags which specify options for drawing the character. */ + quint8 rendition; - /** A combination of RENDITION flags which specify options for drawing the character. */ - quint8 rendition; + /** The foreground color used to draw this character. */ + CharacterColor foregroundColor; + /** The color used to draw this character's background. */ + CharacterColor backgroundColor; - /** The foreground color used to draw this character. */ - CharacterColor foregroundColor; - /** The color used to draw this character's background. */ - CharacterColor backgroundColor; + /** + * Returns true if this character has a transparent background when + * it is drawn with the specified @p palette. + */ + bool isTransparent(const ColorEntry* palette) const; + /** + * Returns true if this character should always be drawn in bold when + * it is drawn with the specified @p palette, independent of whether + * or not the character has the RE_BOLD rendition flag. + */ + ColorEntry::FontWeight fontWeight(const ColorEntry* base) const; + + /** + * returns true if the format (color, rendition flag) of the compared characters is equal + */ + bool equalsFormat(const Character &other) const; - /** - * Returns true if this character has a transparent background when - * it is drawn with the specified @p palette. - */ - bool isTransparent(const ColorEntry* palette) const; - /** - * Returns true if this character should always be drawn in bold when - * it is drawn with the specified @p palette, independent of whether - * or not the character has the RE_BOLD rendition flag. - */ - ColorEntry::FontWeight fontWeight(const ColorEntry* base) const; - - /** - * returns true if the format (color, rendition flag) of the compared characters is equal - */ - bool equalsFormat(const Character &other) const; - - /** - * Compares two characters and returns true if they have the same unicode character value, - * rendition and colors. - */ - friend bool operator == (const Character& a, const Character& b); - /** - * Compares two characters and returns true if they have different unicode character values, - * renditions or colors. - */ - friend bool operator != (const Character& a, const Character& b); + /** + * Compares two characters and returns true if they have the same unicode character value, + * rendition and colors. + */ + friend bool operator == (const Character& a, const Character& b); + /** + * Compares two characters and returns true if they have different unicode character values, + * renditions or colors. + */ + friend bool operator != (const Character& a, const Character& b); }; inline bool operator == (const Character& a, const Character& b) -{ - return a.character == b.character && - a.rendition == b.rendition && - a.foregroundColor == b.foregroundColor && - a.backgroundColor == b.backgroundColor; +{ + return a.character == b.character && + a.rendition == b.rendition && + a.foregroundColor == b.foregroundColor && + a.backgroundColor == b.backgroundColor; } inline bool operator != (const Character& a, const Character& b) { - return a.character != b.character || - a.rendition != b.rendition || - a.foregroundColor != b.foregroundColor || - a.backgroundColor != b.backgroundColor; + return a.character != b.character || + a.rendition != b.rendition || + a.foregroundColor != b.foregroundColor || + a.backgroundColor != b.backgroundColor; } inline bool Character::isTransparent(const ColorEntry* base) const { - return ((backgroundColor._colorSpace == COLOR_SPACE_DEFAULT) && - base[backgroundColor._u+0+(backgroundColor._v?BASE_COLORS:0)].transparent) - || ((backgroundColor._colorSpace == COLOR_SPACE_SYSTEM) && - base[backgroundColor._u+2+(backgroundColor._v?BASE_COLORS:0)].transparent); + return ((backgroundColor._colorSpace == COLOR_SPACE_DEFAULT) && + base[backgroundColor._u+0+(backgroundColor._v?BASE_COLORS:0)].transparent) + || ((backgroundColor._colorSpace == COLOR_SPACE_SYSTEM) && + base[backgroundColor._u+2+(backgroundColor._v?BASE_COLORS:0)].transparent); } inline bool Character::equalsFormat(const Character& other) const { - return - backgroundColor==other.backgroundColor && - foregroundColor==other.foregroundColor && - rendition==other.rendition; -} + return + backgroundColor==other.backgroundColor && + foregroundColor==other.foregroundColor && + rendition==other.rendition; +} inline ColorEntry::FontWeight Character::fontWeight(const ColorEntry* base) const { @@ -169,7 +172,8 @@ extern unsigned short vt100_graphics[32]; * character ( ushort ) so that it can occupy the same space in * a structure. */ -class ExtendedCharTable { +class ExtendedCharTable +{ public: /** Constructs a new character table. */ ExtendedCharTable(); @@ -192,7 +196,7 @@ public: * which was added to the table using createExtendedChar(). * * @param hash The hash key returned by createExtendedChar() - * @param length This variable is set to the length of the + * @param length This variable is set to the length of the * character sequence. * * @return A unicode character sequence of size @p length. @@ -204,7 +208,7 @@ public: private: // calculates the hash key of a sequence of unicode points of size 'length' ushort extendedCharHash(ushort* unicodePoints , ushort length) const; - // tests whether the entry in the table specified by 'hash' matches the + // tests whether the entry in the table specified by 'hash' matches the // character sequence 'unicodePoints' of size 'length' bool extendedCharMatch(ushort hash , ushort* unicodePoints , ushort length) const; // internal, maps hash keys to character sequence buffers. The first ushort diff --git a/lib/CharacterColor.h b/lib/CharacterColor.h index d9f81ad..8e82a66 100644 --- a/lib/CharacterColor.h +++ b/lib/CharacterColor.h @@ -1,6 +1,6 @@ /* This file is part of Konsole, KDE's terminal. - + Copyright 2007-2008 by Robert Knight Copyright 1997,1998 by Lars Doelle @@ -26,75 +26,81 @@ // Qt #include +//#include +#define KDE_NO_EXPORT -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 * system color indexes (from 0 to 15) into actual colors. * * Each entry can be set as bold, in which case any text - * drawn using the color should be drawn in bold. + * drawn using the color should be drawn in bold. * * Each entry can also be transparent, in which case the terminal * display should avoid drawing the background for any characters * using the entry as a background. */ -class ColorEntry { +class ColorEntry +{ public: - /** Specifies the weight to use when drawing text with this color. */ - enum FontWeight { - /** Always draw text in this color with a bold weight. */ - Bold, - /** Always draw text in this color with a normal weight. */ - Normal, - /** - * Use the current font weight set by the terminal application. - * This is the default behavior. - */ - UseCurrentFormat - }; - - /** - * Constructs a new color palette entry. - * - * @param c The color value for this entry. - * @param tr Specifies that the color should be transparent when used as a background color. - * @param weight Specifies the font weight to use when drawing text with this color. + /** Specifies the weight to use when drawing text with this color. */ + enum FontWeight + { + /** Always draw text in this color with a bold weight. */ + Bold, + /** Always draw text in this color with a normal weight. */ + Normal, + /** + * Use the current font weight set by the terminal application. + * This is the default behavior. */ - ColorEntry(QColor c, bool tr, FontWeight weight = UseCurrentFormat) - : color(c), transparent(tr), fontWeight(weight) {} + UseCurrentFormat + }; - /** - * Constructs a new color palette entry with an undefined color, and - * with the transparent and bold flags set to false. - */ - ColorEntry() : transparent(false), fontWeight(UseCurrentFormat) {} + /** + * Constructs a new color palette entry. + * + * @param c The color value for this entry. + * @param tr Specifies that the color should be transparent when used as a background color. + * @param weight Specifies the font weight to use when drawing text with this color. + */ + ColorEntry(QColor c, bool tr, FontWeight weight = UseCurrentFormat) + : color(c), transparent(tr), fontWeight(weight) {} - /** - * Sets the color, transparency and boldness of this color to those of @p rhs. - */ - void operator=(const ColorEntry& rhs) { - color = rhs.color; - transparent = rhs.transparent; - fontWeight = rhs.fontWeight; - } + /** + * Constructs a new color palette entry with an undefined color, and + * with the transparent and bold flags set to false. + */ + ColorEntry() : transparent(false), fontWeight(UseCurrentFormat) {} + + /** + * Sets the color, transparency and boldness of this color to those of @p rhs. + */ + void operator=(const ColorEntry& rhs) + { + color = rhs.color; + transparent = rhs.transparent; + fontWeight = rhs.fontWeight; + } - /** The color value of this entry for display. */ - QColor color; + /** The color value of this entry for display. */ + QColor color; - /** - * If true character backgrounds using this color should be transparent. - * This is not applicable when the color is used to render text. - */ - bool transparent; - /** - * Specifies the font weight to use when drawing text with this color. - * This is not applicable when the color is used to draw a character's background. - */ - FontWeight fontWeight; + /** + * If true character backgrounds using this color should be transparent. + * This is not applicable when the color is used to render text. + */ + bool transparent; + /** + * Specifies the font weight to use when drawing text with this color. + * This is not applicable when the color is used to draw a character's background. + */ + FontWeight fontWeight; }; @@ -112,7 +118,7 @@ public: //a standard set of colors using black text on a white background. //defined in TerminalDisplay.cpp -extern const ColorEntry base_color_table[TABLE_COLORS]; +extern const ColorEntry base_color_table[TABLE_COLORS] KDE_NO_EXPORT; /* CharacterColor is a union of the various color spaces. @@ -139,33 +145,37 @@ extern const ColorEntry base_color_table[TABLE_COLORS]; /** * Describes the color of a single character in the terminal. */ -class CharacterColor { +class CharacterColor +{ friend class Character; public: - /** Constructs a new CharacterColor whoose color and color space are undefined. */ - CharacterColor() - : _colorSpace(COLOR_SPACE_UNDEFINED), - _u(0), - _v(0), - _w(0) {} + /** Constructs a new CharacterColor whoose color and color space are undefined. */ + CharacterColor() + : _colorSpace(COLOR_SPACE_UNDEFINED), + _u(0), + _v(0), + _w(0) + {} - /** - * Constructs a new CharacterColor using the specified @p colorSpace and with - * color value @p co - * - * The meaning of @p co depends on the @p colorSpace used. - * - * TODO : Document how @p co relates to @p colorSpace - * - * TODO : Add documentation about available color spaces. - */ - CharacterColor(quint8 colorSpace, int co) - : _colorSpace(colorSpace), - _u(0), - _v(0), - _w(0) { - switch (colorSpace) { + /** + * Constructs a new CharacterColor using the specified @p colorSpace and with + * color value @p co + * + * The meaning of @p co depends on the @p colorSpace used. + * + * TODO : Document how @p co relates to @p colorSpace + * + * TODO : Add documentation about available color spaces. + */ + CharacterColor(quint8 colorSpace, int co) + : _colorSpace(colorSpace), + _u(0), + _v(0), + _w(0) + { + switch (colorSpace) + { case COLOR_SPACE_DEFAULT: _u = co & 1; break; @@ -173,7 +183,7 @@ public: _u = co & 7; _v = (co >> 3) & 1; break; - case COLOR_SPACE_256: + case COLOR_SPACE_256: _u = co & 255; break; case COLOR_SPACE_RGB: @@ -183,59 +193,60 @@ public: break; default: _colorSpace = COLOR_SPACE_UNDEFINED; - } } + } - /** - * Returns true if this character color entry is valid. - */ - bool isValid() { + /** + * Returns true if this character color entry is valid. + */ + bool isValid() + { return _colorSpace != COLOR_SPACE_UNDEFINED; - } + } + + /** + * Toggles the value of this color between a normal system color and the corresponding intensive + * system color. + * + * This is only applicable if the color is using the COLOR_SPACE_DEFAULT or COLOR_SPACE_SYSTEM + * color spaces. + */ + void toggleIntensive(); - /** - * Toggles the value of this color between a normal system color and the corresponding intensive - * system color. - * - * This is only applicable if the color is using the COLOR_SPACE_DEFAULT or COLOR_SPACE_SYSTEM - * color spaces. - */ - void toggleIntensive(); - - /** - * Returns the color within the specified color @p palette - * - * The @p palette is only used if this color is one of the 16 system colors, otherwise - * it is ignored. - */ - QColor color(const ColorEntry* palette) const; - - /** - * Compares two colors and returns true if they represent the same color value and - * use the same color space. - */ - friend bool operator == (const CharacterColor& a, const CharacterColor& b); - /** - * Compares two colors and returns true if they represent different color values - * or use different color spaces. - */ - friend bool operator != (const CharacterColor& a, const CharacterColor& b); + /** + * Returns the color within the specified color @p palette + * + * The @p palette is only used if this color is one of the 16 system colors, otherwise + * it is ignored. + */ + QColor color(const ColorEntry* palette) const; + + /** + * Compares two colors and returns true if they represent the same color value and + * use the same color space. + */ + friend bool operator == (const CharacterColor& a, const CharacterColor& b); + /** + * Compares two colors and returns true if they represent different color values + * or use different color spaces. + */ + friend bool operator != (const CharacterColor& a, const CharacterColor& b); private: - quint8 _colorSpace; + quint8 _colorSpace; - // bytes storing the character color - quint8 _u; - quint8 _v; - quint8 _w; + // bytes storing the character color + quint8 _u; + quint8 _v; + quint8 _w; }; inline bool operator == (const CharacterColor& a, const CharacterColor& b) -{ +{ return a._colorSpace == b._colorSpace && - a._u == b._u && - a._v == b._v && - a._w == b._w; + a._u == b._u && + a._v == b._v && + a._w == b._w; } inline bool operator != (const CharacterColor& a, const CharacterColor& b) { @@ -244,48 +255,41 @@ inline bool operator != (const CharacterColor& a, const CharacterColor& b) inline const QColor color256(quint8 u, const ColorEntry* base) { - // 0.. 16: system colors - if (u < 8) return base[u+2 ].color; - u -= 8; - if (u < 8) return base[u+2+BASE_COLORS].color; - u -= 8; + // 0.. 16: system colors + if (u < 8) return base[u+2 ].color; u -= 8; + if (u < 8) return base[u+2+BASE_COLORS].color; u -= 8; - // 16..231: 6x6x6 rgb color cube - if (u < 216) return QColor(((u/36)%6) ? (40*((u/36)%6)+55) : 0, - ((u/ 6)%6) ? (40*((u/ 6)%6)+55) : 0, - ((u/ 1)%6) ? (40*((u/ 1)%6)+55) : 0); - u -= 216; - - // 232..255: gray, leaving out black and white - int gray = u*10+8; - return QColor(gray,gray,gray); + // 16..231: 6x6x6 rgb color cube + if (u < 216) return QColor(((u/36)%6) ? (40*((u/36)%6)+55) : 0, + ((u/ 6)%6) ? (40*((u/ 6)%6)+55) : 0, + ((u/ 1)%6) ? (40*((u/ 1)%6)+55) : 0); u -= 216; + + // 232..255: gray, leaving out black and white + int gray = u*10+8; return QColor(gray,gray,gray); } inline QColor CharacterColor::color(const ColorEntry* base) const { - switch (_colorSpace) { - case COLOR_SPACE_DEFAULT: - return base[_u+0+(_v?BASE_COLORS:0)].color; - case COLOR_SPACE_SYSTEM: - return base[_u+2+(_v?BASE_COLORS:0)].color; - case COLOR_SPACE_256: - return color256(_u,base); - case COLOR_SPACE_RGB: - return QColor(_u,_v,_w); - case COLOR_SPACE_UNDEFINED: - return QColor(); - } + switch (_colorSpace) + { + case COLOR_SPACE_DEFAULT: return base[_u+0+(_v?BASE_COLORS:0)].color; + case COLOR_SPACE_SYSTEM: return base[_u+2+(_v?BASE_COLORS:0)].color; + case COLOR_SPACE_256: return color256(_u,base); + case COLOR_SPACE_RGB: return QColor(_u,_v,_w); + case COLOR_SPACE_UNDEFINED: return QColor(); + } - Q_ASSERT(false); // invalid color space + Q_ASSERT(false); // invalid color space - return QColor(); + return QColor(); } inline void CharacterColor::toggleIntensive() { - if (_colorSpace == COLOR_SPACE_SYSTEM || _colorSpace == COLOR_SPACE_DEFAULT) { - _v = !_v; - } + if (_colorSpace == COLOR_SPACE_SYSTEM || _colorSpace == COLOR_SPACE_DEFAULT) + { + _v = !_v; + } } diff --git a/lib/ColorScheme.cpp b/lib/ColorScheme.cpp new file mode 100644 index 0000000..0a84d74 --- /dev/null +++ b/lib/ColorScheme.cpp @@ -0,0 +1,775 @@ +/* + This source file is part of Konsole, a terminal emulator. + + Copyright 2007-2008 by Robert Knight + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. +*/ + +// Own +#include "ColorScheme.h" +#include "tools.h" + +// Qt +#include +#include +#include +#include +#include +#include + + +// KDE +//#include +//#include +//#include +//#include +//#include +//#include + +using namespace Konsole; + +const ColorEntry ColorScheme::defaultTable[TABLE_COLORS] = + // The following are almost IBM standard color codes, with some slight + // gamma correction for the dim colors to compensate for bright X screens. + // It contains the 8 ansiterm/xterm colors in 2 intensities. +{ + ColorEntry( QColor(0x00,0x00,0x00), 0), ColorEntry( +QColor(0xFF,0xFF,0xFF), 1), // Dfore, Dback + ColorEntry( QColor(0x00,0x00,0x00), 0), ColorEntry( +QColor(0xB2,0x18,0x18), 0), // Black, Red + ColorEntry( QColor(0x18,0xB2,0x18), 0), ColorEntry( +QColor(0xB2,0x68,0x18), 0), // Green, Yellow + ColorEntry( QColor(0x18,0x18,0xB2), 0), ColorEntry( +QColor(0xB2,0x18,0xB2), 0), // Blue, Magenta + ColorEntry( QColor(0x18,0xB2,0xB2), 0), ColorEntry( +QColor(0xB2,0xB2,0xB2), 0), // Cyan, White + // intensive + ColorEntry( QColor(0x00,0x00,0x00), 0), ColorEntry( +QColor(0xFF,0xFF,0xFF), 1), + ColorEntry( QColor(0x68,0x68,0x68), 0), ColorEntry( +QColor(0xFF,0x54,0x54), 0), + ColorEntry( QColor(0x54,0xFF,0x54), 0), ColorEntry( +QColor(0xFF,0xFF,0x54), 0), + ColorEntry( QColor(0x54,0x54,0xFF), 0), ColorEntry( +QColor(0xFF,0x54,0xFF), 0), + ColorEntry( QColor(0x54,0xFF,0xFF), 0), ColorEntry( +QColor(0xFF,0xFF,0xFF), 0) +}; + +const char* const ColorScheme::colorNames[TABLE_COLORS] = +{ + "Foreground", + "Background", + "Color0", + "Color1", + "Color2", + "Color3", + "Color4", + "Color5", + "Color6", + "Color7", + "ForegroundIntense", + "BackgroundIntense", + "Color0Intense", + "Color1Intense", + "Color2Intense", + "Color3Intense", + "Color4Intense", + "Color5Intense", + "Color6Intense", + "Color7Intense" +}; +// dummy silently comment out the tr_NOOP +#define tr_NOOP +const char* const ColorScheme::translatedColorNames[TABLE_COLORS] = +{ + tr_NOOP("Foreground"), + tr_NOOP("Background"), + tr_NOOP("Color 1"), + tr_NOOP("Color 2"), + tr_NOOP("Color 3"), + tr_NOOP("Color 4"), + tr_NOOP("Color 5"), + tr_NOOP("Color 6"), + tr_NOOP("Color 7"), + tr_NOOP("Color 8"), + tr_NOOP("Foreground (Intense)"), + tr_NOOP("Background (Intense)"), + tr_NOOP("Color 1 (Intense)"), + tr_NOOP("Color 2 (Intense)"), + tr_NOOP("Color 3 (Intense)"), + tr_NOOP("Color 4 (Intense)"), + tr_NOOP("Color 5 (Intense)"), + tr_NOOP("Color 6 (Intense)"), + tr_NOOP("Color 7 (Intense)"), + tr_NOOP("Color 8 (Intense)") +}; + +ColorScheme::ColorScheme() +{ + _table = 0; + _randomTable = 0; + _opacity = 1.0; +} +ColorScheme::ColorScheme(const ColorScheme& other) + : _opacity(other._opacity) + ,_table(0) + ,_randomTable(0) +{ + setName(other.name()); + setDescription(other.description()); + + if ( other._table != 0 ) + { + for ( int i = 0 ; i < TABLE_COLORS ; i++ ) + setColorTableEntry(i,other._table[i]); + } + + if ( other._randomTable != 0 ) + { + for ( int i = 0 ; i < TABLE_COLORS ; i++ ) + { + const RandomizationRange& range = other._randomTable[i]; + setRandomizationRange(i,range.hue,range.saturation,range.value); + } + } +} +ColorScheme::~ColorScheme() +{ + delete[] _table; + delete[] _randomTable; +} + +void ColorScheme::setDescription(const QString& description) { _description = description; } +QString ColorScheme::description() const { return _description; } + +void ColorScheme::setName(const QString& name) { _name = name; } +QString ColorScheme::name() const { return _name; } + +void ColorScheme::setColorTableEntry(int index , const ColorEntry& entry) +{ + Q_ASSERT( index >= 0 && index < TABLE_COLORS ); + + if ( !_table ) + { + _table = new ColorEntry[TABLE_COLORS]; + + for (int i=0;i= 0 && index < TABLE_COLORS ); + + if ( randomSeed != 0 ) + qsrand(randomSeed); + + ColorEntry entry = colorTable()[index]; + + if ( randomSeed != 0 && + _randomTable != 0 && + !_randomTable[index].isNull() ) + { + const RandomizationRange& range = _randomTable[index]; + + + int hueDifference = range.hue ? (qrand() % range.hue) - range.hue/2 : 0; + int saturationDifference = range.saturation ? (qrand() % range.saturation) - range.saturation/2 : 0; + int valueDifference = range.value ? (qrand() % range.value) - range.value/2 : 0; + + QColor& color = entry.color; + + int newHue = qAbs( (color.hue() + hueDifference) % MAX_HUE ); + int newValue = qMin( qAbs(color.value() + valueDifference) , 255 ); + int newSaturation = qMin( qAbs(color.saturation() + saturationDifference) , 255 ); + + color.setHsv(newHue,newSaturation,newValue); + } + + return entry; +} +void ColorScheme::getColorTable(ColorEntry* table , uint randomSeed) const +{ + for ( int i = 0 ; i < TABLE_COLORS ; i++ ) + table[i] = colorEntry(i,randomSeed); +} +bool ColorScheme::randomizedBackgroundColor() const +{ + return _randomTable == 0 ? false : !_randomTable[1].isNull(); +} +void ColorScheme::setRandomizedBackgroundColor(bool randomize) +{ + // the hue of the background colour is allowed to be randomly + // adjusted as much as possible. + // + // the value and saturation are left alone to maintain read-ability + if ( randomize ) + { + setRandomizationRange( 1 /* background color index */ , MAX_HUE , 255 , 0 ); + } + else + { + if ( _randomTable ) + setRandomizationRange( 1 /* background color index */ , 0 , 0 , 0 ); + } +} + +void ColorScheme::setRandomizationRange( int index , quint16 hue , quint8 saturation , + quint8 value ) +{ + Q_ASSERT( hue <= MAX_HUE ); + Q_ASSERT( index >= 0 && index < TABLE_COLORS ); + + if ( _randomTable == 0 ) + _randomTable = new RandomizationRange[TABLE_COLORS]; + + _randomTable[index].hue = hue; + _randomTable[index].value = value; + _randomTable[index].saturation = saturation; +} + +const ColorEntry* ColorScheme::colorTable() const +{ + if ( _table ) + return _table; + else + return defaultTable; +} +QColor ColorScheme::foregroundColor() const +{ + return colorTable()[0].color; +} +QColor ColorScheme::backgroundColor() const +{ + return colorTable()[1].color; +} +bool ColorScheme::hasDarkBackground() const +{ + // value can range from 0 - 255, with larger values indicating higher brightness. + // so 127 is in the middle, anything less is deemed 'dark' + return backgroundColor().value() < 127; +} +void ColorScheme::setOpacity(qreal opacity) { _opacity = opacity; } +qreal ColorScheme::opacity() const { return _opacity; } + +void ColorScheme::read(const QString & fileName) +{ + QSettings s(fileName, QSettings::IniFormat); + s.beginGroup("General"); + + _description = s.value("Description", QObject::tr("Un-named Color Scheme")).toString(); + _opacity = s.value("Opacity",qreal(1.0)).toDouble(); + s.endGroup(); + + for (int i=0 ; i < TABLE_COLORS ; i++) + { + readColorEntry(&s, i); + } +} +#if 0 +// implemented upstream - user apps +void ColorScheme::read(KConfig& config) +{ + KConfigGroup configGroup = config.group("General"); + + QString description = configGroup.readEntry("Description", QObject::tr("Un-named Color Scheme")); + + _description = tr(description.toUtf8()); + _opacity = configGroup.readEntry("Opacity",qreal(1.0)); + + for (int i=0 ; i < TABLE_COLORS ; i++) + { + readColorEntry(config,i); + } +} +void ColorScheme::write(KConfig& config) const +{ + KConfigGroup configGroup = config.group("General"); + + configGroup.writeEntry("Description",_description); + configGroup.writeEntry("Opacity",_opacity); + + for (int i=0 ; i < TABLE_COLORS ; i++) + { + RandomizationRange random = _randomTable != 0 ? _randomTable[i] : RandomizationRange(); + writeColorEntry(config,colorNameForIndex(i),colorTable()[i],random); + } +} +#endif + +QString ColorScheme::colorNameForIndex(int index) +{ + Q_ASSERT( index >= 0 && index < TABLE_COLORS ); + + return QString(colorNames[index]); +} +QString ColorScheme::translatedColorNameForIndex(int index) +{ + Q_ASSERT( index >= 0 && index < TABLE_COLORS ); + + return translatedColorNames[index]; +} + +void ColorScheme::readColorEntry(QSettings * s , int index) +{ + s->beginGroup(colorNameForIndex(index)); + + ColorEntry entry; + + QStringList rgbList = s->value("Color", QStringList()).toStringList(); + if (rgbList.count() != 3) + { + Q_ASSERT(0); + } + int r, g, b; + r = rgbList[0].toInt(); + g = rgbList[1].toInt(); + b = rgbList[2].toInt(); + entry.color = QColor(r, g, b); + + entry.transparent = s->value("Transparent",false).toBool(); + + // Deprecated key from KDE 4.0 which set 'Bold' to true to force + // a color to be bold or false to use the current format + // + // TODO - Add a new tri-state key which allows for bold, normal or + // current format + if (s->contains("Bold")) + entry.fontWeight = s->value("Bold",false).toBool() ? ColorEntry::Bold : + ColorEntry::UseCurrentFormat; + + quint16 hue = s->value("MaxRandomHue",0).toInt(); + quint8 value = s->value("MaxRandomValue",0).toInt(); + quint8 saturation = s->value("MaxRandomSaturation",0).toInt(); + + setColorTableEntry( index , entry ); + + if ( hue != 0 || value != 0 || saturation != 0 ) + setRandomizationRange( index , hue , saturation , value ); + + s->endGroup(); +} +#if 0 +// implemented upstream - user apps +void ColorScheme::writeColorEntry(KConfig& config , const QString& colorName, const ColorEntry& entry , const RandomizationRange& random) const +{ + KConfigGroup configGroup(&config,colorName); + + configGroup.writeEntry("Color",entry.color); + configGroup.writeEntry("Transparency",(bool)entry.transparent); + if (entry.fontWeight != ColorEntry::UseCurrentFormat) + { + configGroup.writeEntry("Bold",entry.fontWeight == ColorEntry::Bold); + } + + // record randomization if this color has randomization or + // if one of the keys already exists + if ( !random.isNull() || configGroup.hasKey("MaxRandomHue") ) + { + configGroup.writeEntry("MaxRandomHue",(int)random.hue); + configGroup.writeEntry("MaxRandomValue",(int)random.value); + configGroup.writeEntry("MaxRandomSaturation",(int)random.saturation); + } +} +#endif + +// +// Work In Progress - A color scheme for use on KDE setups for users +// with visual disabilities which means that they may have trouble +// reading text with the supplied color schemes. +// +// This color scheme uses only the 'safe' colors defined by the +// KColorScheme class. +// +// A complication this introduces is that each color provided by +// KColorScheme is defined as a 'background' or 'foreground' color. +// Only foreground colors are allowed to be used to render text and +// only background colors are allowed to be used for backgrounds. +// +// The ColorEntry and TerminalDisplay classes do not currently +// support this restriction. +// +// Requirements: +// - A color scheme which uses only colors from the KColorScheme class +// - Ability to restrict which colors the TerminalDisplay widget +// uses as foreground and background color +// - Make use of KGlobalSettings::allowDefaultBackgroundImages() as +// a hint to determine whether this accessible color scheme should +// be used by default. +// +// +// -- Robert Knight 21/07/2007 +// +AccessibleColorScheme::AccessibleColorScheme() + : ColorScheme() +{ +#if 0 +// It's not finished in konsole and it breaks Qt4 compilation as well + // basic attributes + setName("accessible"); + setDescription(QObject::tr("Accessible Color Scheme")); + + // setup colors + const int ColorRoleCount = 8; + + const KColorScheme colorScheme(QPalette::Active); + + QBrush colors[ColorRoleCount] = + { + colorScheme.foreground( colorScheme.NormalText ), + colorScheme.background( colorScheme.NormalBackground ), + + colorScheme.foreground( colorScheme.InactiveText ), + colorScheme.foreground( colorScheme.ActiveText ), + colorScheme.foreground( colorScheme.LinkText ), + colorScheme.foreground( colorScheme.VisitedText ), + colorScheme.foreground( colorScheme.NegativeText ), + colorScheme.foreground( colorScheme.NeutralText ) + }; + + for ( int i = 0 ; i < TABLE_COLORS ; i++ ) + { + ColorEntry entry; + entry.color = colors[ i % ColorRoleCount ].color(); + + setColorTableEntry( i , entry ); + } +#endif +} + +KDE3ColorSchemeReader::KDE3ColorSchemeReader( QIODevice* device ) : + _device(device) +{ +} +ColorScheme* KDE3ColorSchemeReader::read() +{ + Q_ASSERT( _device->openMode() == QIODevice::ReadOnly || + _device->openMode() == QIODevice::ReadWrite ); + + ColorScheme* scheme = new ColorScheme(); + + QRegExp comment("#.*$"); + while ( !_device->atEnd() ) + { + QString line(_device->readLine()); + line.remove(comment); + line = line.simplified(); + + if ( line.isEmpty() ) + continue; + + if ( line.startsWith(QLatin1String("color")) ) + { + if (!readColorLine(line,scheme)) + qDebug() << "Failed to read KDE 3 color scheme line" << line; + } + else if ( line.startsWith(QLatin1String("title")) ) + { + if (!readTitleLine(line,scheme)) + qDebug() << "Failed to read KDE 3 color scheme title line" << line; + } + else + { + qDebug() << "KDE 3 color scheme contains an unsupported feature, '" << + line << "'"; + } + } + + return scheme; +} +bool KDE3ColorSchemeReader::readColorLine(const QString& line,ColorScheme* scheme) +{ + QStringList list = line.split(QChar(' ')); + + if (list.count() != 7) + return false; + if (list.first() != "color") + return false; + + int index = list[1].toInt(); + int red = list[2].toInt(); + int green = list[3].toInt(); + int blue = list[4].toInt(); + int transparent = list[5].toInt(); + int bold = list[6].toInt(); + + const int MAX_COLOR_VALUE = 255; + + if( (index < 0 || index >= TABLE_COLORS ) + || (red < 0 || red > MAX_COLOR_VALUE ) + || (blue < 0 || blue > MAX_COLOR_VALUE ) + || (green < 0 || green > MAX_COLOR_VALUE ) + || (transparent != 0 && transparent != 1 ) + || (bold != 0 && bold != 1) ) + return false; + + ColorEntry entry; + entry.color = QColor(red,green,blue); + entry.transparent = ( transparent != 0 ); + entry.fontWeight = ( bold != 0 ) ? ColorEntry::Bold : ColorEntry::UseCurrentFormat; + + scheme->setColorTableEntry(index,entry); + return true; +} +bool KDE3ColorSchemeReader::readTitleLine(const QString& line,ColorScheme* scheme) +{ + if( !line.startsWith(QLatin1String("title")) ) + return false; + + int spacePos = line.indexOf(' '); + if( spacePos == -1 ) + return false; + + QString description = line.mid(spacePos+1); + + scheme->setDescription(description.toUtf8()); + return true; +} +ColorSchemeManager::ColorSchemeManager() + : _haveLoadedAll(false) +{ +} +ColorSchemeManager::~ColorSchemeManager() +{ + QHashIterator iter(_colorSchemes); + while (iter.hasNext()) + { + iter.next(); + delete iter.value(); + } +} +void ColorSchemeManager::loadAllColorSchemes() +{ + qDebug() << "loadAllColorSchemes"; + int success = 0; + int failed = 0; + + QList nativeColorSchemes = listColorSchemes(); + + QListIterator nativeIter(nativeColorSchemes); + while ( nativeIter.hasNext() ) + { + if ( loadColorScheme( nativeIter.next() ) ) + success++; + else + failed++; + } + + QList kde3ColorSchemes = listKDE3ColorSchemes(); + QListIterator kde3Iter(kde3ColorSchemes); + while ( kde3Iter.hasNext() ) + { + if ( loadKDE3ColorScheme( kde3Iter.next() ) ) + success++; + else + failed++; + } + + if ( failed > 0 ) + qDebug() << "failed to load " << failed << " color schemes."; + + _haveLoadedAll = true; +} +QList ColorSchemeManager::allColorSchemes() +{ + if ( !_haveLoadedAll ) + { + loadAllColorSchemes(); + } + + return _colorSchemes.values(); +} +bool ColorSchemeManager::loadKDE3ColorScheme(const QString& filePath) +{ + QFile file(filePath); + if (!filePath.endsWith(QLatin1String(".schema")) || !file.open(QIODevice::ReadOnly)) + return false; + + KDE3ColorSchemeReader reader(&file); + ColorScheme* scheme = reader.read(); + scheme->setName(QFileInfo(file).baseName()); + file.close(); + + if (scheme->name().isEmpty()) + { + qDebug() << "color scheme name is not valid."; + delete scheme; + return false; + } + + QFileInfo info(filePath); + + if ( !_colorSchemes.contains(info.baseName()) ) + _colorSchemes.insert(scheme->name(),scheme); + else + { + qDebug() << "color scheme with name" << scheme->name() << "has already been" << + "found, ignoring."; + delete scheme; + } + + return true; +} +#if 0 +void ColorSchemeManager::addColorScheme(ColorScheme* scheme) +{ + _colorSchemes.insert(scheme->name(),scheme); + + // save changes to disk + QString path = KGlobal::dirs()->saveLocation("data","konsole/") + scheme->name() + ".colorscheme"; + KConfig config(path , KConfig::NoGlobals); + + scheme->write(config); +} +#endif +bool ColorSchemeManager::loadColorScheme(const QString& filePath) +{ + if ( !filePath.endsWith(QLatin1String(".colorscheme")) || !QFile::exists(filePath) ) + return false; + + QFileInfo info(filePath); + + ColorScheme* scheme = new ColorScheme(); + scheme->setName(info.baseName()); + scheme->read(filePath); + + if (scheme->name().isEmpty()) + { + qDebug() << "Color scheme in" << filePath << "does not have a valid name and was not loaded."; + delete scheme; + return false; + } + + if ( !_colorSchemes.contains(info.baseName()) ) + { + _colorSchemes.insert(scheme->name(),scheme); + } + else + { + qDebug() << "color scheme with name" << scheme->name() << "has already been" << + "found, ignoring."; + + delete scheme; + } + + return true; +} +QList ColorSchemeManager::listKDE3ColorSchemes() +{ + QString dname(get_color_schemes_dir()); + QDir dir(dname); + QStringList filters; + filters << "*.schema"; + dir.setNameFilters(filters); + QStringList list = dir.entryList(filters); + QStringList ret; + foreach(QString i, list) + ret << dname + "/" + i; + return ret; + //return KGlobal::dirs()->findAllResources("data", + // "konsole/*.schema", + // KStandardDirs::NoDuplicates); + // +} +QList ColorSchemeManager::listColorSchemes() +{ + QString dname(get_color_schemes_dir()); + QDir dir(dname); + QStringList filters; + filters << "*.colorscheme"; + dir.setNameFilters(filters); + QStringList list = dir.entryList(filters); + QStringList ret; + foreach(QString i, list) + ret << dname + "/" + i; + return ret; +// return KGlobal::dirs()->findAllResources("data", +// "konsole/*.colorscheme", +// KStandardDirs::NoDuplicates); +} +const ColorScheme ColorSchemeManager::_defaultColorScheme; +const ColorScheme* ColorSchemeManager::defaultColorScheme() const +{ + return &_defaultColorScheme; +} +bool ColorSchemeManager::deleteColorScheme(const QString& name) +{ + Q_ASSERT( _colorSchemes.contains(name) ); + + // lookup the path and delete + QString path = findColorSchemePath(name); + if ( QFile::remove(path) ) + { + _colorSchemes.remove(name); + return true; + } + else + { + qDebug() << "Failed to remove color scheme -" << path; + return false; + } +} +QString ColorSchemeManager::findColorSchemePath(const QString& name) const +{ +// QString path = KStandardDirs::locate("data","konsole/"+name+".colorscheme"); + QString path(get_color_schemes_dir() + "/"+ name + ".colorscheme"); + if ( !path.isEmpty() ) + return path; + + //path = KStandardDirs::locate("data","konsole/"+name+".schema"); + path = get_color_schemes_dir() + "/"+ name + ".schema"; + + return path; +} +const ColorScheme* ColorSchemeManager::findColorScheme(const QString& name) +{ + if ( name.isEmpty() ) + return defaultColorScheme(); + + if ( _colorSchemes.contains(name) ) + return _colorSchemes[name]; + else + { + // look for this color scheme + QString path = findColorSchemePath(name); + if ( !path.isEmpty() && loadColorScheme(path) ) + { + return findColorScheme(name); + } + else + { + if (!path.isEmpty() && loadKDE3ColorScheme(path)) + return findColorScheme(name); + } + + qDebug() << "Could not find color scheme - " << name; + + return 0; + } +} + +ColorSchemeManager* ColorSchemeManager::theColorSchemeManager = 0; +//K_GLOBAL_STATIC( ColorSchemeManager , theColorSchemeManager ) +ColorSchemeManager* ColorSchemeManager::instance() +{ + if (! theColorSchemeManager) + theColorSchemeManager = new ColorSchemeManager(); + return theColorSchemeManager; +} diff --git a/lib/ColorScheme.h b/lib/ColorScheme.h new file mode 100644 index 0000000..fa4a88a --- /dev/null +++ b/lib/ColorScheme.h @@ -0,0 +1,346 @@ +/* + This source file is part of Konsole, a terminal emulator. + + Copyright 2007-2008 by Robert Knight + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. +*/ + +#ifndef COLORSCHEME_H +#define COLORSCHEME_H + +// Qt +#include +#include +#include +#include +#include +#include + +// Konsole +#include "CharacterColor.h" + +class QIODevice; +//class KConfig; + +namespace Konsole +{ + +/** + * Represents a color scheme for a terminal display. + * + * The color scheme includes the palette of colors used to draw the text and character backgrounds + * in the display and the opacity level of the display background. + */ +class ColorScheme +{ +public: + /** + * Constructs a new color scheme which is initialised to the default color set + * for Konsole. + */ + ColorScheme(); + ColorScheme(const ColorScheme& other); + ~ColorScheme(); + + /** Sets the descriptive name of the color scheme. */ + void setDescription(const QString& description); + /** Returns the descriptive name of the color scheme. */ + QString description() const; + + /** Sets the name of the color scheme */ + void setName(const QString& name); + /** Returns the name of the color scheme */ + QString name() const; + +#if 0 +// Implemented upstream - in user apps + /** Reads the color scheme from the specified configuration source */ + void read(KConfig& config); + /** Writes the color scheme to the specified configuration source */ + void write(KConfig& config) const; +#endif + void read(const QString & filename); + + /** Sets a single entry within the color palette. */ + void setColorTableEntry(int index , const ColorEntry& entry); + + /** + * Copies the color entries which form the palette for this color scheme + * into @p table. @p table should be an array with TABLE_COLORS entries. + * + * @param table Array into which the color entries for this color scheme + * are copied. + * @param randomSeed Color schemes may allow certain colors in their + * palette to be randomized. The seed is used to pick the random color. + */ + void getColorTable(ColorEntry* table, uint randomSeed = 0) const; + + /** + * Retrieves a single color entry from the table. + * + * See getColorTable() + */ + ColorEntry colorEntry(int index , uint randomSeed = 0) const; + + /** + * Convenience method. Returns the + * foreground color for this scheme, + * this is the primary color used to draw the + * text in this scheme. + */ + QColor foregroundColor() const; + /** + * Convenience method. Returns the background color for + * this scheme, this is the primary color used to + * draw the terminal background in this scheme. + */ + QColor backgroundColor() const; + + /** + * Returns true if this color scheme has a dark background. + * The background color is said to be dark if it has a value of less than 127 + * in the HSV color space. + */ + bool hasDarkBackground() const; + + /** + * Sets the opacity level of the display background. @p opacity ranges + * between 0 (completely transparent background) and 1 (completely + * opaque background). + * + * Defaults to 1. + * + * TODO: More documentation + */ + void setOpacity(qreal opacity); + /** + * Returns the opacity level for this color scheme, see setOpacity() + * TODO: More documentation + */ + qreal opacity() const; + + /** + * Enables randomization of the background color. This will cause + * the palette returned by getColorTable() and colorEntry() to + * be adjusted depending on the value of the random seed argument + * to them. + */ + void setRandomizedBackgroundColor(bool randomize); + + /** Returns true if the background color is randomized. */ + bool randomizedBackgroundColor() const; + + static QString colorNameForIndex(int index); + static QString translatedColorNameForIndex(int index); + +private: + // specifies how much a particular color can be randomized by + class RandomizationRange + { + public: + RandomizationRange() : hue(0) , saturation(0) , value(0) {} + + bool isNull() const + { + return ( hue == 0 && saturation == 0 && value == 0 ); + } + + quint16 hue; + quint8 saturation; + quint8 value; + }; + + // returns the active color table. if none has been set specifically, + // this is the default color table. + const ColorEntry* colorTable() const; + +#if 0 +// implemented upstream - user apps + // reads a single colour entry from a KConfig source + // and sets the palette entry at 'index' to the entry read. + void readColorEntry(KConfig& config , int index); + // writes a single colour entry to a KConfig source + void writeColorEntry(KConfig& config , const QString& colorName, const ColorEntry& entry,const RandomizationRange& range) const; +#endif + void readColorEntry(QSettings *s, int index); + + // sets the amount of randomization allowed for a particular color + // in the palette. creates the randomization table if + // it does not already exist + void setRandomizationRange( int index , quint16 hue , quint8 saturation , quint8 value ); + + QString _description; + QString _name; + qreal _opacity; + ColorEntry* _table; // pointer to custom color table or 0 if the default + // color scheme is being used + + + static const quint16 MAX_HUE = 340; + + RandomizationRange* _randomTable; // pointer to randomization table or 0 + // if no colors in the color scheme support + // randomization + + static const char* const colorNames[TABLE_COLORS]; + static const char* const translatedColorNames[TABLE_COLORS]; + + static const ColorEntry defaultTable[]; // table of default color entries +}; + +/** + * A color scheme which uses colors from the standard KDE color palette. + * + * This is designed primarily for the benefit of users who are using specially + * designed colors. + * + * TODO Implement and make it the default on systems with specialized KDE + * color schemes. + */ +class AccessibleColorScheme : public ColorScheme +{ +public: + AccessibleColorScheme(); +}; + +/** + * Reads a color scheme stored in the .schema format used in the KDE 3 incarnation + * of Konsole + * + * Only the basic essentials ( title and color palette entries ) are currently + * supported. Additional options such as background image and background + * blend colors are ignored. + */ +class KDE3ColorSchemeReader +{ +public: + /** + * Constructs a new reader which reads from the specified device. + * The device should be open in read-only mode. + */ + KDE3ColorSchemeReader( QIODevice* device ); + + /** + * Reads and parses the contents of the .schema file from the input + * device and returns the ColorScheme defined within it. + * + * Returns a null pointer if an error occurs whilst parsing + * the contents of the file. + */ + ColorScheme* read(); + +private: + // reads a line from the file specifying a colour palette entry + // format is: color [index] [red] [green] [blue] [transparent] [bold] + bool readColorLine(const QString& line , ColorScheme* scheme); + bool readTitleLine(const QString& line , ColorScheme* scheme); + + QIODevice* _device; +}; + +/** + * Manages the color schemes available for use by terminal displays. + * See ColorScheme + */ +class ColorSchemeManager +{ +public: + + /** + * Constructs a new ColorSchemeManager and loads the list + * of available color schemes. + * + * The color schemes themselves are not loaded until they are first + * requested via a call to findColorScheme() + */ + ColorSchemeManager(); + /** + * Destroys the ColorSchemeManager and saves any modified color schemes to disk. + */ + ~ColorSchemeManager(); + + /** + * Returns the default color scheme for Konsole + */ + const ColorScheme* defaultColorScheme() const; + + /** + * Returns the color scheme with the given name or 0 if no + * scheme with that name exists. If @p name is empty, the + * default color scheme is returned. + * + * The first time that a color scheme with a particular name is + * requested, the configuration information is loaded from disk. + */ + const ColorScheme* findColorScheme(const QString& name); + +#if 0 + /** + * Adds a new color scheme to the manager. If @p scheme has the same name as + * an existing color scheme, it replaces the existing scheme. + * + * TODO - Ensure the old color scheme gets deleted + */ + void addColorScheme(ColorScheme* scheme); +#endif + /** + * Deletes a color scheme. Returns true on successful deletion or false otherwise. + */ + bool deleteColorScheme(const QString& name); + + /** + * Returns a list of the all the available color schemes. + * This may be slow when first called because all of the color + * scheme resources on disk must be located, read and parsed. + * + * Subsequent calls will be inexpensive. + */ + QList allColorSchemes(); + + /** Returns the global color scheme manager instance. */ + static ColorSchemeManager* instance(); + +private: + // loads a color scheme from a KDE 4+ .colorscheme file + bool loadColorScheme(const QString& path); + // loads a color scheme from a KDE 3 .schema file + bool loadKDE3ColorScheme(const QString& path); + // returns a list of paths of color schemes in the KDE 4+ .colorscheme file format + QList listColorSchemes(); + // returns a list of paths of color schemes in the .schema file format + // used in KDE 3 + QList listKDE3ColorSchemes(); + // loads all of the color schemes + void loadAllColorSchemes(); + // finds the path of a color scheme + QString findColorSchemePath(const QString& name) const; + + QHash _colorSchemes; + QSet _modifiedSchemes; + + bool _haveLoadedAll; + + static const ColorScheme _defaultColorScheme; + + static ColorSchemeManager * theColorSchemeManager; +}; + +} + +Q_DECLARE_METATYPE(const Konsole::ColorScheme*) + +#endif //COLORSCHEME_H diff --git a/lib/ColorTables.h b/lib/ColorTables.h index 6a9ee94..57b0bd1 100644 --- a/lib/ColorTables.h +++ b/lib/ColorTables.h @@ -3,8 +3,8 @@ #include "CharacterColor.h" -using namespace Konsole; - +//using namespace Konsole; +#if 0 static const ColorEntry whiteonblack_color_table[TABLE_COLORS] = { // normal ColorEntry(QColor(0xFF,0xFF,0xFF), false ), ColorEntry( QColor(0x00,0x00,0x00), true ), // Dfore, Dback @@ -48,7 +48,7 @@ static const ColorEntry blackonlightyellow_color_table[TABLE_COLORS] = { }; - +#endif #endif diff --git a/lib/Emulation.cpp b/lib/Emulation.cpp index 8981468..e68a930 100644 --- a/lib/Emulation.cpp +++ b/lib/Emulation.cpp @@ -1,11 +1,7 @@ /* - This file is part of Konsole, an X terminal. - - Copyright (C) 2007 Robert Knight - Copyright (C) 1997,1998 by Lars Doelle - Copyright (C) 1996 by Matthias Ettrich - - Rewritten for QT4 by e_k , Copyright (C)2008 + Copyright 2007-2008 Robert Knight + Copyright 1997,1998 by Lars Doelle + Copyright 1996 by Matthias Ettrich This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -43,6 +39,9 @@ #include +// KDE +//#include + // Konsole #include "KeyboardTranslator.h" #include "Screen.h" @@ -51,36 +50,24 @@ using namespace Konsole; -/* ------------------------------------------------------------------------- */ -/* */ -/* Emulation */ -/* */ -/* ------------------------------------------------------------------------- */ - -//#define CNTL(c) ((c)-'@') - -/*! -*/ - Emulation::Emulation() : - _currentScreen(0), - _codec(0), - _decoder(0), - _keyTranslator(0), - _usesMouse(false) + _currentScreen(0), + _codec(0), + _decoder(0), + _keyTranslator(0), + _usesMouse(false) { + // create screens with a default size + _screen[0] = new Screen(40,80); + _screen[1] = new Screen(40,80); + _currentScreen = _screen[0]; - // create screens with a default size - _screen[0] = new Screen(40,80); - _screen[1] = new Screen(40,80); - _currentScreen = _screen[0]; - - QObject::connect(&_bulkTimer1, SIGNAL(timeout()), this, SLOT(showBulk()) ); - QObject::connect(&_bulkTimer2, SIGNAL(timeout()), this, SLOT(showBulk()) ); - - // listen for mouse status changes - connect( this , SIGNAL(programUsesMouseChanged(bool)) , - SLOT(usesMouseChanged(bool)) ); + QObject::connect(&_bulkTimer1, SIGNAL(timeout()), this, SLOT(showBulk()) ); + QObject::connect(&_bulkTimer2, SIGNAL(timeout()), this, SLOT(showBulk()) ); + + // listen for mouse status changes + connect( this , SIGNAL(programUsesMouseChanged(bool)) , + SLOT(usesMouseChanged(bool)) ); } bool Emulation::programUsesMouse() const @@ -93,9 +80,9 @@ void Emulation::usesMouseChanged(bool usesMouse) _usesMouse = usesMouse; } -ScreenWindow * Emulation::createWindow() +ScreenWindow* Emulation::createWindow() { - ScreenWindow * window = new ScreenWindow(); + ScreenWindow* window = new ScreenWindow(); window->setScreen(_currentScreen); _windows << window; @@ -107,150 +94,113 @@ ScreenWindow * Emulation::createWindow() return window; } -/*! -*/ - Emulation::~Emulation() { - QListIterator windowIter(_windows); + QListIterator windowIter(_windows); - while (windowIter.hasNext()) { - delete windowIter.next(); - } + while (windowIter.hasNext()) + { + delete windowIter.next(); + } - delete _screen[0]; - delete _screen[1]; - delete _decoder; + delete _screen[0]; + delete _screen[1]; + delete _decoder; } -/*! change between primary and alternate _screen -*/ - void Emulation::setScreen(int n) { - Screen * old = _currentScreen; - _currentScreen = _screen[n&1]; - if (_currentScreen != old) { - old->setBusySelecting(false); - - // tell all windows onto this emulation to switch to the newly active _screen - QListIterator windowIter(_windows); - while ( windowIter.hasNext() ) { - windowIter.next()->setScreen(_currentScreen); - } - } + Screen *old = _currentScreen; + _currentScreen = _screen[n & 1]; + if (_currentScreen != old) + { + // tell all windows onto this emulation to switch to the newly active screen + foreach(ScreenWindow* window,_windows) + window->setScreen(_currentScreen); + } } void Emulation::clearHistory() { _screen[0]->setScroll( _screen[0]->getScroll() , false ); } -void Emulation::setHistory(const HistoryType & t) +void Emulation::setHistory(const HistoryType& t) { - _screen[0]->setScroll(t); + _screen[0]->setScroll(t); - showBulk(); + showBulk(); } -const HistoryType & Emulation::history() +const HistoryType& Emulation::history() const { - return _screen[0]->getScroll(); + return _screen[0]->getScroll(); } void Emulation::setCodec(const QTextCodec * qtc) { - Q_ASSERT( qtc ); + if (qtc) + _codec = qtc; + else + setCodec(LocaleCodec); - _codec = qtc; - delete _decoder; - _decoder = _codec->makeDecoder(); + delete _decoder; + _decoder = _codec->makeDecoder(); - emit useUtf8Request(utf8()); + emit useUtf8Request(utf8()); } void Emulation::setCodec(EmulationCodec codec) { - if ( codec == Utf8Codec ) { + if ( codec == Utf8Codec ) setCodec( QTextCodec::codecForName("utf8") ); - } else if ( codec == LocaleCodec ) { + else if ( codec == LocaleCodec ) setCodec( QTextCodec::codecForLocale() ); - } } -void Emulation::setKeyBindings(const QString & name) +void Emulation::setKeyBindings(const QString& name) { - _keyTranslator = KeyboardTranslatorManager::instance()->findTranslator(name); + _keyTranslator = KeyboardTranslatorManager::instance()->findTranslator(name); + if (!_keyTranslator) + { + _keyTranslator = KeyboardTranslatorManager::instance()->defaultTranslator(); + } } -QString Emulation::keyBindings() +QString Emulation::keyBindings() const { - return _keyTranslator->name(); + return _keyTranslator->name(); } - -// Interpreting Codes --------------------------------------------------------- - -/* - This section deals with decoding the incoming character stream. - Decoding means here, that the stream is first separated into `tokens' - which are then mapped to a `meaning' provided as operations by the - `Screen' class. -*/ - -/*! -*/ - void Emulation::receiveChar(int c) // process application unicode input to terminal // this is a trivial scanner { - c &= 0xff; - switch (c) { - case '\b' : - _currentScreen->BackSpace(); - break; - case '\t' : - _currentScreen->Tabulate(); - break; - case '\n' : - _currentScreen->NewLine(); - break; - case '\r' : - _currentScreen->Return(); - break; - case 0x07 : - emit stateSet(NOTIFYBELL); - break; - default : - _currentScreen->ShowCharacter(c); - break; - }; + c &= 0xff; + switch (c) + { + case '\b' : _currentScreen->backspace(); break; + case '\t' : _currentScreen->tab(); break; + case '\n' : _currentScreen->newLine(); break; + case '\r' : _currentScreen->toStartOfLine(); break; + case 0x07 : emit stateSet(NOTIFYBELL); + break; + default : _currentScreen->displayCharacter(c); break; + }; } -/* ------------------------------------------------------------------------- */ -/* */ -/* Keyboard Handling */ -/* */ -/* ------------------------------------------------------------------------- */ - -/*! -*/ - -void Emulation::sendKeyEvent( QKeyEvent * ev ) +void Emulation::sendKeyEvent( QKeyEvent* ev ) { - emit stateSet(NOTIFYNORMAL); - - if (!ev->text().isEmpty()) { - // A block of text - // Note that the text is proper unicode. - // We should do a conversion here, but since this - // routine will never be used, we simply emit plain ascii. - //emit sendBlock(ev->text().toAscii(),ev->text().length()); - emit sendData(ev->text().toUtf8(),ev->text().length()); - } + emit stateSet(NOTIFYNORMAL); + + if (!ev->text().isEmpty()) + { // A block of text + // Note that the text is proper unicode. + // We should do a conversion here + emit sendData(ev->text().toUtf8(),ev->text().length()); + } } -void Emulation::sendString(const char *,int) +void Emulation::sendString(const char*,int) { // default implementation does nothing } @@ -260,53 +210,51 @@ void Emulation::sendMouseEvent(int /*buttons*/, int /*column*/, int /*row*/, int // default implementation does nothing } -// Unblocking, Byte to Unicode translation --------------------------------- -- - /* We are doing code conversion from locale to unicode first. TODO: Character composition from the old code. See #96536 */ -void Emulation::receiveData(const char * text, int length) +void Emulation::receiveData(const char* text, int length) { emit stateSet(NOTIFYACTIVITY); bufferedUpdate(); - + QString unicodeText = _decoder->toUnicode(text,length); //send characters to terminal emulator - for (int i=0; i 3) && (strncmp(text+i+1, "B00", 3) == 0)) { + for (int i=0;i 3) && (strncmp(text+i+1, "B00", 3) == 0)) emit zmodemDetected(); - } } } } //OLDER VERSION //This version of onRcvBlock was commented out because -// a) It decoded incoming characters one-by-one, which is slow in the current version of Qt (4.2 tech preview) -// b) It messed up decoding of non-ASCII characters, with the result that (for example) chinese characters -// were not printed properly. +// a) It decoded incoming characters one-by-one, which is slow in the current version of Qt (4.2 tech preview) +// b) It messed up decoding of non-ASCII characters, with the result that (for example) chinese characters +// were not printed properly. // //There is something about stopping the _decoder if "we get a control code halfway a multi-byte sequence" (see below) //which hasn't been ported into the newer function (above). Hopefully someone who understands this better -//can find an alternative way of handling the check. +//can find an alternative way of handling the check. /*void Emulation::onRcvBlock(const char *s, int len) { emit notifySessionState(NOTIFYACTIVITY); - + bufferedUpdate(); for (int i = 0; i < len; i++) { @@ -336,86 +284,27 @@ void Emulation::receiveData(const char * text, int length) if (s[i] == '\030') { if ((len-i-1 > 3) && (strncmp(s+i+1, "B00", 3) == 0)) - emit zmodemDetected(); + emit zmodemDetected(); } } }*/ -// Selection --------------------------------------------------------------- -- - -#if 0 -void Emulation::onSelectionBegin(const int x, const int y, const bool columnmode) -{ - if (!connected) { - return; - } - _currentScreen->setSelectionStart( x,y,columnmode); - showBulk(); -} - -void Emulation::onSelectionExtend(const int x, const int y) -{ - if (!connected) { - return; - } - _currentScreen->setSelectionEnd(x,y); - showBulk(); -} - -void Emulation::setSelection(const bool preserve_line_breaks) -{ - if (!connected) { - return; - } - QString t = _currentScreen->selectedText(preserve_line_breaks); - if (!t.isNull()) { - QListIterator< TerminalDisplay * > viewIter(_views); - - while (viewIter.hasNext()) { - viewIter.next()->setSelection(t); - } - } -} - -void Emulation::testIsSelected(const int x, const int y, bool & selected) -{ - if (!connected) { - return; - } - selected=_currentScreen->isSelected(x,y); -} - -void Emulation::clearSelection() -{ - if (!connected) { - return; - } - _currentScreen->clearSelection(); - showBulk(); -} - -#endif - -void Emulation::writeToStream( TerminalCharacterDecoder * _decoder , +void Emulation::writeToStream( TerminalCharacterDecoder* _decoder , int startLine , - int endLine) + int endLine) { - _currentScreen->writeToStream(_decoder,startLine,endLine); + _currentScreen->writeLinesToStream(_decoder,startLine,endLine); } -int Emulation::lineCount() +int Emulation::lineCount() const { // sum number of lines currently on _screen plus number of lines in history return _currentScreen->getLines() + _currentScreen->getHistLines(); } -// Refreshing -------------------------------------------------------------- -- - #define BULK_TIMEOUT1 10 #define BULK_TIMEOUT2 40 -/*! -*/ void Emulation::showBulk() { _bulkTimer1.stop(); @@ -429,106 +318,121 @@ void Emulation::showBulk() void Emulation::bufferedUpdate() { - _bulkTimer1.setSingleShot(true); - _bulkTimer1.start(BULK_TIMEOUT1); - if (!_bulkTimer2.isActive()) { - _bulkTimer2.setSingleShot(true); - _bulkTimer2.start(BULK_TIMEOUT2); - } + _bulkTimer1.setSingleShot(true); + _bulkTimer1.start(BULK_TIMEOUT1); + if (!_bulkTimer2.isActive()) + { + _bulkTimer2.setSingleShot(true); + _bulkTimer2.start(BULK_TIMEOUT2); + } } -char Emulation::getErase() const +char Emulation::eraseChar() const { - return '\b'; + return '\b'; } void Emulation::setImageSize(int lines, int columns) { - //kDebug() << "Resizing image to: " << lines << "by" << columns << QTime::currentTime().msec(); - Q_ASSERT( lines > 0 ); - Q_ASSERT( columns > 0 ); + if ((lines < 1) || (columns < 1)) + return; - _screen[0]->resizeImage(lines,columns); - _screen[1]->resizeImage(lines,columns); + QSize screenSize[2] = { QSize(_screen[0]->getColumns(), + _screen[0]->getLines()), + QSize(_screen[1]->getColumns(), + _screen[1]->getLines()) }; + QSize newSize(columns,lines); - emit imageSizeChanged(lines,columns); + if (newSize == screenSize[0] && newSize == screenSize[1]) + return; - bufferedUpdate(); + _screen[0]->resizeImage(lines,columns); + _screen[1]->resizeImage(lines,columns); + + emit imageSizeChanged(lines,columns); + + bufferedUpdate(); } -QSize Emulation::imageSize() +QSize Emulation::imageSize() const { - return QSize(_currentScreen->getColumns(), _currentScreen->getLines()); + return QSize(_currentScreen->getColumns(), _currentScreen->getLines()); } -ushort ExtendedCharTable::extendedCharHash(ushort * unicodePoints , ushort length) const +ushort ExtendedCharTable::extendedCharHash(ushort* unicodePoints , ushort length) const { ushort hash = 0; - for ( ushort i = 0 ; i < length ; i++ ) { + for ( ushort i = 0 ; i < length ; i++ ) + { hash = 31*hash + unicodePoints[i]; } return hash; } -bool ExtendedCharTable::extendedCharMatch(ushort hash , ushort * unicodePoints , ushort length) const +bool ExtendedCharTable::extendedCharMatch(ushort hash , ushort* unicodePoints , ushort length) const { - ushort * entry = extendedCharTable[hash]; + ushort* entry = extendedCharTable[hash]; - // compare given length with stored sequence length ( given as the first ushort in the - // stored buffer ) - if ( entry == 0 || entry[0] != length ) { - return false; - } + // compare given length with stored sequence length ( given as the first ushort in the + // stored buffer ) + if ( entry == 0 || entry[0] != length ) + return false; // if the lengths match, each character must be checked. the stored buffer starts at // entry[1] - for ( int i = 0 ; i < length ; i++ ) { - if ( entry[i+1] != unicodePoints[i] ) { - return false; - } - } + for ( int i = 0 ; i < length ; i++ ) + { + if ( entry[i+1] != unicodePoints[i] ) + return false; + } return true; } -ushort ExtendedCharTable::createExtendedChar(ushort * unicodePoints , ushort length) +ushort ExtendedCharTable::createExtendedChar(ushort* unicodePoints , ushort length) { // look for this sequence of points in the table ushort hash = extendedCharHash(unicodePoints,length); // check existing entry for match - while ( extendedCharTable.contains(hash) ) { - if ( extendedCharMatch(hash,unicodePoints,length) ) { - // this sequence already has an entry in the table, + while ( extendedCharTable.contains(hash) ) + { + if ( extendedCharMatch(hash,unicodePoints,length) ) + { + // this sequence already has an entry in the table, // return its hash return hash; - } else { + } + else + { // if hash is already used by another, different sequence of unicode character // points then try next hash hash++; } - } + } - - // add the new sequence to the table and - // return that index - ushort * buffer = new ushort[length+1]; + + // add the new sequence to the table and + // return that index + ushort* buffer = new ushort[length+1]; buffer[0] = length; - for ( int i = 0 ; i < length ; i++ ) { - buffer[i+1] = unicodePoints[i]; - } - + for ( int i = 0 ; i < length ; i++ ) + buffer[i+1] = unicodePoints[i]; + extendedCharTable.insert(hash,buffer); return hash; } -ushort * ExtendedCharTable::lookupExtendedChar(ushort hash , ushort & length) const +ushort* ExtendedCharTable::lookupExtendedChar(ushort hash , ushort& length) const { // lookup index in table and if found, set the length // argument and return a pointer to the character sequence - ushort * buffer = extendedCharTable[hash]; - if ( buffer ) { + ushort* buffer = extendedCharTable[hash]; + if ( buffer ) + { length = buffer[0]; return buffer+1; - } else { + } + else + { length = 0; return 0; } @@ -540,8 +444,9 @@ ExtendedCharTable::ExtendedCharTable() ExtendedCharTable::~ExtendedCharTable() { // free all allocated character buffers - QHashIterator iter(extendedCharTable); - while ( iter.hasNext() ) { + QHashIterator iter(extendedCharTable); + while ( iter.hasNext() ) + { iter.next(); delete[] iter.value(); } @@ -551,5 +456,5 @@ ExtendedCharTable::~ExtendedCharTable() ExtendedCharTable ExtendedCharTable::instance; -//#include "moc_Emulation.cpp" +//#include "Emulation.moc" diff --git a/lib/Emulation.h b/lib/Emulation.h index 4a59105..9c59664 100644 --- a/lib/Emulation.h +++ b/lib/Emulation.h @@ -1,10 +1,8 @@ /* This file is part of Konsole, an X terminal. - - Copyright (C) 2007 by Robert Knight - Copyright (C) 1997,1998 by Lars Doelle - - Rewritten for QT4 by e_k , Copyright (C)2008 + + Copyright 2007-2008 by Robert Knight + Copyright 1997,1998 by Lars Doelle This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -28,15 +26,19 @@ // System #include -// Qt +// Qt #include //#include #include #include #include +// Konsole +//#include "konsole_export.h" +#define KONSOLEPRIVATE_EXPORT -namespace Konsole { +namespace Konsole +{ class KeyboardTranslator; class HistoryType; @@ -44,55 +46,56 @@ class Screen; class ScreenWindow; class TerminalCharacterDecoder; -/** - * This enum describes the available states which +/** + * This enum describes the available states which * the terminal emulation may be set to. * - * These are the values used by Emulation::stateChanged() + * These are the values used by Emulation::stateChanged() */ -enum { +enum +{ /** The emulation is currently receiving user input. */ - NOTIFYNORMAL=0, - /** + NOTIFYNORMAL=0, + /** * The terminal program has triggered a bell event * to get the user's attention. */ - NOTIFYBELL=1, - /** - * The emulation is currently receiving data from its + NOTIFYBELL=1, + /** + * The emulation is currently receiving data from its * terminal input. */ NOTIFYACTIVITY=2, - // unused here? - NOTIFYSILENCE=3 + // unused here? + NOTIFYSILENCE=3 }; /** * Base class for terminal emulation back-ends. * - * The back-end is responsible for decoding an incoming character stream and + * The back-end is responsible for decoding an incoming character stream and * producing an output image of characters. * * When input from the terminal is received, the receiveData() slot should be called with - * the data which has arrived. The emulation will process the data and update the + * the data which has arrived. The emulation will process the data and update the * screen image accordingly. The codec used to decode the incoming character stream - * into the unicode characters used internally can be specified using setCodec() + * into the unicode characters used internally can be specified using setCodec() * - * The size of the screen image can be specified by calling setImageSize() with the + * The size of the screen image can be specified by calling setImageSize() with the * desired number of lines and columns. When new lines are added, old content - * is moved into a history store, which can be set by calling setHistory(). + * is moved into a history store, which can be set by calling setHistory(). * - * The screen image can be accessed by creating a ScreenWindow onto this emulation - * by calling createWindow(). Screen windows provide access to a section of the - * output. Each screen window covers the same number of lines and columns as the + * The screen image can be accessed by creating a ScreenWindow onto this emulation + * by calling createWindow(). Screen windows provide access to a section of the + * output. Each screen window covers the same number of lines and columns as the * image size returned by imageSize(). The screen window can be moved up and down - * and provides transparent access to both the current on-screen image and the + * and provides transparent access to both the current on-screen image and the * previous output. The screen windows emit an outputChanged signal * when the section of the image they are looking at changes. * Graphical views can then render the contents of a screen window, listening for notifications - * of output changes from the screen window which they are associated with and updating - * accordingly. + * of output changes from the screen window which they are associated with and updating + * accordingly. * * The emulation also is also responsible for converting input from the connected views such * as keypresses and mouse activity into a character string which can be sent @@ -105,9 +108,9 @@ enum { * character sequences. The name of the key bindings set used can be specified using * setKeyBindings() * - * The emulation maintains certain state information which changes depending on the - * input received. The emulation can be reset back to its starting state by calling - * reset(). + * The emulation maintains certain state information which changes depending on the + * input received. The emulation can be reset back to its starting state by calling + * reset(). * * The emulation also maintains an activity state, which specifies whether * terminal is currently active ( when data is received ), normal @@ -117,348 +120,350 @@ enum { * how long the emulation has been active/idle for and also respond to * a 'bell' event in different ways. */ -class Emulation : public QObject { - Q_OBJECT +class KONSOLEPRIVATE_EXPORT Emulation : public QObject +{ +Q_OBJECT public: + + /** Constructs a new terminal emulation */ + Emulation(); + ~Emulation(); - /** Constructs a new terminal emulation */ - Emulation(); - ~Emulation(); + /** + * Creates a new window onto the output from this emulation. The contents + * of the window are then rendered by views which are set to use this window using the + * TerminalDisplay::setScreenWindow() method. + */ + ScreenWindow* createWindow(); - /** - * Creates a new window onto the output from this emulation. The contents - * of the window are then rendered by views which are set to use this window using the - * TerminalDisplay::setScreenWindow() method. - */ - ScreenWindow * createWindow(); + /** Returns the size of the screen image which the emulation produces */ + QSize imageSize() const; - /** Returns the size of the screen image which the emulation produces */ - QSize imageSize(); + /** + * Returns the total number of lines, including those stored in the history. + */ + int lineCount() const; - /** - * Returns the total number of lines, including those stored in the history. - */ - int lineCount(); + /** + * Sets the history store used by this emulation. When new lines + * are added to the output, older lines at the top of the screen are transferred to a history + * store. + * + * The number of lines which are kept and the storage location depend on the + * type of store. + */ + void setHistory(const HistoryType&); + /** Returns the history store used by this emulation. See setHistory() */ + const HistoryType& history() const; + /** Clears the history scroll. */ + void clearHistory(); + /** + * Copies the output history from @p startLine to @p endLine + * into @p stream, using @p decoder to convert the terminal + * characters into text. + * + * @param decoder A decoder which converts lines of terminal characters with + * appearance attributes into output text. PlainTextDecoder is the most commonly + * used decoder. + * @param startLine Index of first line to copy + * @param endLine Index of last line to copy + */ + virtual void writeToStream(TerminalCharacterDecoder* decoder,int startLine,int endLine); + + /** Returns the codec used to decode incoming characters. See setCodec() */ + const QTextCodec* codec() const { return _codec; } + /** Sets the codec used to decode incoming characters. */ + void setCodec(const QTextCodec*); - /** - * Sets the history store used by this emulation. When new lines - * are added to the output, older lines at the top of the screen are transferred to a history - * store. - * - * The number of lines which are kept and the storage location depend on the - * type of store. - */ - void setHistory(const HistoryType &); - /** Returns the history store used by this emulation. See setHistory() */ - const HistoryType & history(); - /** Clears the history scroll. */ - void clearHistory(); + /** + * Convenience method. + * Returns true if the current codec used to decode incoming + * characters is UTF-8 + */ + bool utf8() const + { Q_ASSERT(_codec); return _codec->mibEnum() == 106; } + - /** - * Copies the output history from @p startLine to @p endLine - * into @p stream, using @p decoder to convert the terminal - * characters into text. - * - * @param decoder A decoder which converts lines of terminal characters with - * appearance attributes into output text. PlainTextDecoder is the most commonly - * used decoder. - * @param startLine The first - */ - virtual void writeToStream(TerminalCharacterDecoder * decoder,int startLine,int endLine); + /** TODO Document me */ + virtual char eraseChar() const; + /** + * Sets the key bindings used to key events + * ( received through sendKeyEvent() ) into character + * streams to send to the terminal. + */ + void setKeyBindings(const QString& name); + /** + * Returns the name of the emulation's current key bindings. + * See setKeyBindings() + */ + QString keyBindings() const; - /** Returns the codec used to decode incoming characters. See setCodec() */ - const QTextCodec * codec() { - return _codec; - } - /** Sets the codec used to decode incoming characters. */ - void setCodec(const QTextCodec *); + /** + * Copies the current image into the history and clears the screen. + */ + virtual void clearEntireScreen() =0; - /** - * Convenience method. - * Returns true if the current codec used to decode incoming - * characters is UTF-8 - */ - bool utf8() { - Q_ASSERT(_codec); - return _codec->mibEnum() == 106; - } + /** Resets the state of the terminal. */ + virtual void reset() =0; + /** + * Returns true if the active terminal program wants + * mouse input events. + * + * The programUsesMouseChanged() signal is emitted when this + * changes. + */ + bool programUsesMouse() const; - /** TODO Document me */ - virtual char getErase() const; +public slots: - /** - * Sets the key bindings used to key events - * ( received through sendKeyEvent() ) into character - * streams to send to the terminal. - */ - void setKeyBindings(const QString & name); - /** - * Returns the name of the emulation's current key bindings. - * See setKeyBindings() - */ - QString keyBindings(); + /** Change the size of the emulation's image */ + virtual void setImageSize(int lines, int columns); + + /** + * Interprets a sequence of characters and sends the result to the terminal. + * This is equivalent to calling sendKeyEvent() for each character in @p text in succession. + */ + virtual void sendText(const QString& text) = 0; - /** - * Copies the current image into the history and clears the screen. - */ - virtual void clearEntireScreen() =0; + /** + * Interprets a key press event and emits the sendData() signal with + * the resulting character stream. + */ + virtual void sendKeyEvent(QKeyEvent*); + + /** + * Converts information about a mouse event into an xterm-compatible escape + * sequence and emits the character sequence via sendData() + */ + virtual void sendMouseEvent(int buttons, int column, int line, int eventType); + + /** + * Sends a string of characters to the foreground terminal process. + * + * @param string The characters to send. + * @param length Length of @p string or if set to a negative value, @p string will + * be treated as a null-terminated string and its length will be determined automatically. + */ + virtual void sendString(const char* string, int length = -1) = 0; - /** Resets the state of the terminal. */ - virtual void reset() =0; - - /** - * Returns true if the active terminal program wants - * mouse input events. - * - * The programUsesMouseChanged() signal is emitted when this - * changes. - */ - bool programUsesMouse() const; - -public slots: - - /** Change the size of the emulation's image */ - virtual void setImageSize(int lines, int columns); - - /** - * Interprets a sequence of characters and sends the result to the terminal. - * This is equivalent to calling sendKeyEvent() for each character in @p text in succession. - */ - virtual void sendText(const QString & text) = 0; - - /** - * Interprets a key press event and emits the sendData() signal with - * the resulting character stream. - */ - virtual void sendKeyEvent(QKeyEvent *); - - /** - * Converts information about a mouse event into an xterm-compatible escape - * sequence and emits the character sequence via sendData() - */ - virtual void sendMouseEvent(int buttons, int column, int line, int eventType); - - /** - * Sends a string of characters to the foreground terminal process. - * - * @param string The characters to send. - * @param length Length of @p string or if set to a negative value, @p string will - * be treated as a null-terminated string and its length will be determined automatically. - */ - virtual void sendString(const char * string, int length = -1) = 0; - - /** - * Processes an incoming stream of characters. receiveData() decodes the incoming - * character buffer using the current codec(), and then calls receiveChar() for - * each unicode character in the resulting buffer. - * - * receiveData() also starts a timer which causes the outputChanged() signal - * to be emitted when it expires. The timer allows multiple updates in quick - * succession to be buffered into a single outputChanged() signal emission. - * - * @param buffer A string of characters received from the terminal program. - * @param len The length of @p buffer - */ - void receiveData(const char * buffer,int len); + /** + * Processes an incoming stream of characters. receiveData() decodes the incoming + * character buffer using the current codec(), and then calls receiveChar() for + * each unicode character in the resulting buffer. + * + * receiveData() also starts a timer which causes the outputChanged() signal + * to be emitted when it expires. The timer allows multiple updates in quick + * succession to be buffered into a single outputChanged() signal emission. + * + * @param buffer A string of characters received from the terminal program. + * @param len The length of @p buffer + */ + void receiveData(const char* buffer,int len); signals: - /** - * Emitted when a buffer of data is ready to send to the - * standard input of the terminal. - * - * @param data The buffer of data ready to be sent - * @paran len The length of @p data in bytes - */ - void sendData(const char * data,int len); + /** + * Emitted when a buffer of data is ready to send to the + * standard input of the terminal. + * + * @param data The buffer of data ready to be sent + * @param len The length of @p data in bytes + */ + void sendData(const char* data,int len); - /** - * Requests that sending of input to the emulation - * from the terminal process be suspended or resumed. - * - * @param suspend If true, requests that sending of - * input from the terminal process' stdout be - * suspended. Otherwise requests that sending of - * input be resumed. - */ - void lockPtyRequest(bool suspend); + /** + * Requests that sending of input to the emulation + * from the terminal process be suspended or resumed. + * + * @param suspend If true, requests that sending of + * input from the terminal process' stdout be + * suspended. Otherwise requests that sending of + * input be resumed. + */ + void lockPtyRequest(bool suspend); - /** - * Requests that the pty used by the terminal process - * be set to UTF 8 mode. - * - * TODO: More documentation - */ - void useUtf8Request(bool); + /** + * Requests that the pty used by the terminal process + * be set to UTF 8 mode. + * + * TODO: More documentation + */ + void useUtf8Request(bool); - /** - * Emitted when the activity state of the emulation is set. - * - * @param state The new activity state, one of NOTIFYNORMAL, NOTIFYACTIVITY - * or NOTIFYBELL - */ - void stateSet(int state); + /** + * Emitted when the activity state of the emulation is set. + * + * @param state The new activity state, one of NOTIFYNORMAL, NOTIFYACTIVITY + * or NOTIFYBELL + */ + void stateSet(int state); - /** TODO Document me */ - void zmodemDetected(); + /** TODO Document me */ + void zmodemDetected(); - /** - * Requests that the color of the text used - * to represent the tabs associated with this - * emulation be changed. This is a Konsole-specific - * extension from pre-KDE 4 times. - * - * TODO: Document how the parameter works. - */ - void changeTabTextColorRequest(int color); + /** + * Requests that the color of the text used + * to represent the tabs associated with this + * emulation be changed. This is a Konsole-specific + * extension from pre-KDE 4 times. + * + * TODO: Document how the parameter works. + */ + void changeTabTextColorRequest(int color); - /** - * This is emitted when the program running in the shell indicates whether or - * not it is interested in mouse events. - * - * @param usesMouse This will be true if the program wants to be informed about - * mouse events or false otherwise. - */ - void programUsesMouseChanged(bool usesMouse); + /** + * This is emitted when the program running in the shell indicates whether or + * not it is interested in mouse events. + * + * @param usesMouse This will be true if the program wants to be informed about + * mouse events or false otherwise. + */ + void programUsesMouseChanged(bool usesMouse); - /** - * Emitted when the contents of the screen image change. - * The emulation buffers the updates from successive image changes, - * and only emits outputChanged() at sensible intervals when - * there is a lot of terminal activity. - * - * Normally there is no need for objects other than the screen windows - * created with createWindow() to listen for this signal. - * - * ScreenWindow objects created using createWindow() will emit their - * own outputChanged() signal in response to this signal. - */ - void outputChanged(); + /** + * Emitted when the contents of the screen image change. + * The emulation buffers the updates from successive image changes, + * and only emits outputChanged() at sensible intervals when + * there is a lot of terminal activity. + * + * Normally there is no need for objects other than the screen windows + * created with createWindow() to listen for this signal. + * + * ScreenWindow objects created using createWindow() will emit their + * own outputChanged() signal in response to this signal. + */ + void outputChanged(); - /** - * Emitted when the program running in the terminal wishes to update the - * session's title. This also allows terminal programs to customize other - * aspects of the terminal emulation display. - * - * This signal is emitted when the escape sequence "\033]ARG;VALUE\007" - * is received in the input string, where ARG is a number specifying what - * should change and VALUE is a string specifying the new value. - * - * TODO: The name of this method is not very accurate since this method - * is used to perform a whole range of tasks besides just setting - * the user-title of the session. - * - * @param title Specifies what to change. - *
    - *
  • 0 - Set window icon text and session title to @p newTitle
  • - *
  • 1 - Set window icon text to @p newTitle
  • - *
  • 2 - Set session title to @p newTitle
  • - *
  • 11 - Set the session's default background color to @p newTitle, - * where @p newTitle can be an HTML-style string (#RRGGBB) or a named - * color (eg 'red', 'blue'). - * See http://doc.trolltech.com/4.2/qcolor.html#setNamedColor for more - * details. - *
  • - *
  • 31 - Supposedly treats @p newTitle as a URL and opens it (NOT IMPLEMENTED)
  • - *
  • 32 - Sets the icon associated with the session. @p newTitle is the name - * of the icon to use, which can be the name of any icon in the current KDE icon - * theme (eg: 'konsole', 'kate', 'folder_home')
  • - *
- * @param newTitle Specifies the new title - */ + /** + * Emitted when the program running in the terminal wishes to update the + * session's title. This also allows terminal programs to customize other + * aspects of the terminal emulation display. + * + * This signal is emitted when the escape sequence "\033]ARG;VALUE\007" + * is received in the input string, where ARG is a number specifying what + * should change and VALUE is a string specifying the new value. + * + * TODO: The name of this method is not very accurate since this method + * is used to perform a whole range of tasks besides just setting + * the user-title of the session. + * + * @param title Specifies what to change. + *
    + *
  • 0 - Set window icon text and session title to @p newTitle
  • + *
  • 1 - Set window icon text to @p newTitle
  • + *
  • 2 - Set session title to @p newTitle
  • + *
  • 11 - Set the session's default background color to @p newTitle, + * where @p newTitle can be an HTML-style string ("#RRGGBB") or a named + * color (eg 'red', 'blue'). + * See http://doc.trolltech.com/4.2/qcolor.html#setNamedColor for more + * details. + *
  • + *
  • 31 - Supposedly treats @p newTitle as a URL and opens it (NOT IMPLEMENTED)
  • + *
  • 32 - Sets the icon associated with the session. @p newTitle is the name + * of the icon to use, which can be the name of any icon in the current KDE icon + * theme (eg: 'konsole', 'kate', 'folder_home')
  • + *
+ * @param newTitle Specifies the new title + */ - void titleChanged(int title,const QString & newTitle); + void titleChanged(int title,const QString& newTitle); - /** - * Emitted when the program running in the terminal changes the - * screen size. - */ - void imageSizeChanged(int lineCount , int columnCount); + /** + * Emitted when the program running in the terminal changes the + * screen size. + */ + void imageSizeChanged(int lineCount , int columnCount); - /** - * Emitted when the terminal program requests to change various properties - * of the terminal display. - * - * A profile change command occurs when a special escape sequence, followed - * by a string containing a series of name and value pairs is received. - * This string can be parsed using a ProfileCommandParser instance. - * - * @param text A string expected to contain a series of key and value pairs in - * the form: name=value;name2=value2 ... - */ - void profileChangeCommandReceived(const QString & text); + /** + * Emitted when the terminal program requests to change various properties + * of the terminal display. + * + * A profile change command occurs when a special escape sequence, followed + * by a string containing a series of name and value pairs is received. + * This string can be parsed using a ProfileCommandParser instance. + * + * @param text A string expected to contain a series of key and value pairs in + * the form: name=value;name2=value2 ... + */ + void profileChangeCommandReceived(const QString& text); + + /** + * Emitted when a flow control key combination ( Ctrl+S or Ctrl+Q ) is pressed. + * @param suspendKeyPressed True if Ctrl+S was pressed to suspend output or Ctrl+Q to + * resume output. + */ + void flowControlKeyPressed(bool suspendKeyPressed); protected: - virtual void setMode (int mode) = 0; - virtual void resetMode(int mode) = 0; + virtual void setMode(int mode) = 0; + virtual void resetMode(int mode) = 0; + + /** + * Processes an incoming character. See receiveData() + * @p ch A unicode character code. + */ + virtual void receiveChar(int ch); - /** - * Processes an incoming character. See receiveData() - * @p ch A unicode character code. - */ - virtual void receiveChar(int ch); + /** + * Sets the active screen. The terminal has two screens, primary and alternate. + * The primary screen is used by default. When certain interactive programs such + * as Vim are run, they trigger a switch to the alternate screen. + * + * @param index 0 to switch to the primary screen, or 1 to switch to the alternate screen + */ + void setScreen(int index); - /** - * Sets the active screen. The terminal has two screens, primary and alternate. - * The primary screen is used by default. When certain interactive programs such - * as Vim are run, they trigger a switch to the alternate screen. - * - * @param index 0 to switch to the primary screen, or 1 to switch to the alternate screen - */ - void setScreen(int index); - - enum EmulationCodec { - LocaleCodec = 0, - Utf8Codec = 1 - }; - void setCodec(EmulationCodec codec); // codec number, 0 = locale, 1=utf8 + enum EmulationCodec + { + LocaleCodec = 0, + Utf8Codec = 1 + }; + void setCodec(EmulationCodec codec); // codec number, 0 = locale, 1=utf8 - QList _windows; + QList _windows; + + Screen* _currentScreen; // pointer to the screen which is currently active, + // this is one of the elements in the screen[] array - Screen * _currentScreen; // pointer to the screen which is currently active, - // this is one of the elements in the screen[] array - - Screen * _screen[2]; // 0 = primary screen ( used by most programs, including the shell - // scrollbars are enabled in this mode ) - // 1 = alternate ( used by vi , emacs etc. - // scrollbars are not enabled in this mode ) - - - //decodes an incoming C-style character stream into a unicode QString using - //the current text codec. (this allows for rendering of non-ASCII characters in text files etc.) - const QTextCodec * _codec; - QTextDecoder * _decoder; - - const KeyboardTranslator * _keyTranslator; // the keyboard layout + Screen* _screen[2]; // 0 = primary screen ( used by most programs, including the shell + // scrollbars are enabled in this mode ) + // 1 = alternate ( used by vi , emacs etc. + // scrollbars are not enabled in this mode ) + + + //decodes an incoming C-style character stream into a unicode QString using + //the current text codec. (this allows for rendering of non-ASCII characters in text files etc.) + const QTextCodec* _codec; + QTextDecoder* _decoder; + const KeyboardTranslator* _keyTranslator; // the keyboard layout protected slots: - /** - * Schedules an update of attached views. - * Repeated calls to bufferedUpdate() in close succession will result in only a single update, - * much like the Qt buffered update of widgets. - */ - void bufferedUpdate(); + /** + * Schedules an update of attached views. + * Repeated calls to bufferedUpdate() in close succession will result in only a single update, + * much like the Qt buffered update of widgets. + */ + void bufferedUpdate(); -private slots: +private slots: - // triggered by timer, causes the emulation to send an updated screen image to each - // view - void showBulk(); + // triggered by timer, causes the emulation to send an updated screen image to each + // view + void showBulk(); - void usesMouseChanged(bool usesMouse); + void usesMouseChanged(bool usesMouse); private: - - bool _usesMouse; - QTimer _bulkTimer1; - QTimer _bulkTimer2; - + bool _usesMouse; + QTimer _bulkTimer1; + QTimer _bulkTimer2; + }; } diff --git a/lib/Filter.cpp b/lib/Filter.cpp index f0d73ba..9aa2900 100644 --- a/lib/Filter.cpp +++ b/lib/Filter.cpp @@ -1,7 +1,5 @@ /* - Copyright (C) 2007 by Robert Knight - - Rewritten for QT4 by e_k , Copyright (C)2008 + Copyright 2007-2008 by Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -30,9 +28,11 @@ #include #include #include - +#include #include -#include +#include +#include +#include // KDE //#include @@ -40,64 +40,65 @@ // Konsole #include "TerminalCharacterDecoder.h" +#include "konsole_wcwidth.h" using namespace Konsole; FilterChain::~FilterChain() { - QMutableListIterator iter(*this); - - while ( iter.hasNext() ) { - Filter * filter = iter.next(); + QMutableListIterator iter(*this); + + while ( iter.hasNext() ) + { + Filter* filter = iter.next(); iter.remove(); delete filter; } } -void FilterChain::addFilter(Filter * filter) +void FilterChain::addFilter(Filter* filter) { append(filter); } -void FilterChain::removeFilter(Filter * filter) +void FilterChain::removeFilter(Filter* filter) { removeAll(filter); } -bool FilterChain::containsFilter(Filter * filter) +bool FilterChain::containsFilter(Filter* filter) { return contains(filter); } void FilterChain::reset() { - QListIterator iter(*this); - while (iter.hasNext()) { + QListIterator iter(*this); + while (iter.hasNext()) iter.next()->reset(); - } } -void FilterChain::setBuffer(const QString * buffer , const QList* linePositions) +void FilterChain::setBuffer(const QString* buffer , const QList* linePositions) { - QListIterator iter(*this); - while (iter.hasNext()) { + QListIterator iter(*this); + while (iter.hasNext()) iter.next()->setBuffer(buffer,linePositions); - } } void FilterChain::process() { - QListIterator iter(*this); - while (iter.hasNext()) { + QListIterator iter(*this); + while (iter.hasNext()) iter.next()->process(); - } } void FilterChain::clear() { - QList::clear(); + QList::clear(); } -Filter::HotSpot * FilterChain::hotSpotAt(int line , int column) const +Filter::HotSpot* FilterChain::hotSpotAt(int line , int column) const { - QListIterator iter(*this); - while (iter.hasNext()) { - Filter * filter = iter.next(); - Filter::HotSpot * spot = filter->hotSpotAt(line,column); - if ( spot != 0 ) { + QListIterator iter(*this); + while (iter.hasNext()) + { + Filter* filter = iter.next(); + Filter::HotSpot* spot = filter->hotSpotAt(line,column); + if ( spot != 0 ) + { return spot; } } @@ -105,12 +106,13 @@ Filter::HotSpot * FilterChain::hotSpotAt(int line , int column) const return 0; } -QList FilterChain::hotSpots() const +QList FilterChain::hotSpots() const { - QList list; - QListIterator iter(*this); - while (iter.hasNext()) { - Filter * filter = iter.next(); + QList list; + QListIterator iter(*this); + while (iter.hasNext()) + { + Filter* filter = iter.next(); list << filter->hotSpots(); } return list; @@ -118,8 +120,8 @@ QList FilterChain::hotSpots() const //QList FilterChain::hotSpotsAtLine(int line) const; TerminalImageFilterChain::TerminalImageFilterChain() - : _buffer(0) - , _linePositions(0) +: _buffer(0) +, _linePositions(0) { } @@ -129,24 +131,19 @@ TerminalImageFilterChain::~TerminalImageFilterChain() delete _linePositions; } -void TerminalImageFilterChain::setImage(const Character * const image , int lines , int columns, const QVector& lineProperties) +void TerminalImageFilterChain::setImage(const Character* const image , int lines , int columns, const QVector& lineProperties) { -//qDebug("%s %d", __FILE__, __LINE__); - if (empty()) { + if (empty()) return; - } -//qDebug("%s %d", __FILE__, __LINE__); // reset all filters and hotspots reset(); -//qDebug("%s %d", __FILE__, __LINE__); PlainTextDecoder decoder; decoder.setTrailingWhitespace(false); - -//qDebug("%s %d", __FILE__, __LINE__); + // setup new shared buffers for the filters to process on - QString * newBuffer = new QString(); + QString* newBuffer = new QString(); QList* newLinePositions = new QList(); setBuffer( newBuffer , newLinePositions ); @@ -160,7 +157,8 @@ void TerminalImageFilterChain::setImage(const Character * const image , int line QTextStream lineStream(_buffer); decoder.begin(&lineStream); - for (int i=0 ; i < lines ; i++) { + for (int i=0 ; i < lines ; i++) + { _linePositions->append(_buffer->length()); decoder.decodeLine(image + i*columns,columns,LINE_DEFAULT); @@ -169,29 +167,28 @@ void TerminalImageFilterChain::setImage(const Character * const image , int 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 - // highlighted. + // highlighted. // // TODO - Use the "line wrapped" attribute associated with lines in a // terminal image to avoid adding this imaginary character for wrapped // lines - if ( !(lineProperties.value(i,LINE_DEFAULT) & LINE_WRAPPED) ) { + if ( !(lineProperties.value(i,LINE_DEFAULT) & LINE_WRAPPED) ) lineStream << QChar('\n'); - } } decoder.end(); -// qDebug("%s %d", __FILE__, __LINE__); } Filter::Filter() : - _linePositions(0), - _buffer(0) +_linePositions(0), +_buffer(0) { } Filter::~Filter() { - QListIterator iter(_hotspotList); - while (iter.hasNext()) { + QListIterator iter(_hotspotList); + while (iter.hasNext()) + { delete iter.next(); } } @@ -201,39 +198,36 @@ void Filter::reset() _hotspotList.clear(); } -void Filter::setBuffer(const QString * buffer , const QList* linePositions) +void Filter::setBuffer(const QString* buffer , const QList* linePositions) { _buffer = buffer; _linePositions = linePositions; } -void Filter::getLineColumn(int position , int & startLine , int & startColumn) +void Filter::getLineColumn(int position , int& startLine , int& startColumn) { Q_ASSERT( _linePositions ); Q_ASSERT( _buffer ); - for (int i = 0 ; i < _linePositions->count() ; i++) { - //kDebug() << "line position at " << i << " = " << _linePositions[i]; + for (int i = 0 ; i < _linePositions->count() ; i++) + { int nextLine = 0; - if ( i == _linePositions->count()-1 ) { + if ( i == _linePositions->count()-1 ) nextLine = _buffer->length() + 1; - } else { + else nextLine = _linePositions->value(i+1); - } - // kDebug() << "pos - " << position << " line pos(" << i<< ") " << _linePositions->value(i) << - // " next = " << nextLine << " buffer len = " << _buffer->length(); - - if ( _linePositions->value(i) <= position && position < nextLine ) { + if ( _linePositions->value(i) <= position && position < nextLine ) + { startLine = i; - startColumn = position - _linePositions->value(i); + startColumn = string_width(buffer()->mid(_linePositions->value(i),position - _linePositions->value(i))); return; } } } - + /*void Filter::addLine(const QString& text) { @@ -241,44 +235,44 @@ void Filter::getLineColumn(int position , int & startLine , int & startColumn) _buffer.append(text); }*/ -const QString * Filter::buffer() +const QString* Filter::buffer() { return _buffer; } Filter::HotSpot::~HotSpot() { } -void Filter::addHotSpot(HotSpot * spot) +void Filter::addHotSpot(HotSpot* spot) { _hotspotList << spot; - for (int line = spot->startLine() ; line <= spot->endLine() ; line++) { + for (int line = spot->startLine() ; line <= spot->endLine() ; line++) + { _hotspots.insert(line,spot); - } + } } -QList Filter::hotSpots() const +QList Filter::hotSpots() const { return _hotspotList; } -QList Filter::hotSpotsAtLine(int line) const +QList Filter::hotSpotsAtLine(int line) const { return _hotspots.values(line); } -Filter::HotSpot * Filter::hotSpotAt(int line , int column) const +Filter::HotSpot* Filter::hotSpotAt(int line , int column) const { - QListIterator spotIter(_hotspots.values(line)); + QListIterator spotIter(_hotspots.values(line)); - while (spotIter.hasNext()) { - HotSpot * spot = spotIter.next(); - - if ( spot->startLine() == line && spot->startColumn() > column ) { + while (spotIter.hasNext()) + { + HotSpot* spot = spotIter.next(); + + if ( spot->startLine() == line && spot->startColumn() > column ) continue; - } - if ( spot->endLine() == line && spot->endColumn() < column ) { + if ( spot->endLine() == line && spot->endColumn() < column ) continue; - } - + return spot; } @@ -286,20 +280,20 @@ Filter::HotSpot * Filter::hotSpotAt(int line , int column) const } Filter::HotSpot::HotSpot(int startLine , int startColumn , int endLine , int endColumn) - : _startLine(startLine) - , _startColumn(startColumn) - , _endLine(endLine) - , _endColumn(endColumn) - , _type(NotSpecified) + : _startLine(startLine) + , _startColumn(startColumn) + , _endLine(endLine) + , _endColumn(endColumn) + , _type(NotSpecified) { } QString Filter::HotSpot::tooltip() const { return QString(); } -QList Filter::HotSpot::actions() +QList Filter::HotSpot::actions() { - return QList(); + return QList(); } int Filter::HotSpot::startLine() const { @@ -331,16 +325,16 @@ RegExpFilter::RegExpFilter() } RegExpFilter::HotSpot::HotSpot(int startLine,int startColumn,int endLine,int endColumn) - : Filter::HotSpot(startLine,startColumn,endLine,endColumn) + : Filter::HotSpot(startLine,startColumn,endLine,endColumn) { setType(Marker); } -void RegExpFilter::HotSpot::activate(QObject *) +void RegExpFilter::HotSpot::activate(QObject*) { } -void RegExpFilter::HotSpot::setCapturedTexts(const QStringList & texts) +void RegExpFilter::HotSpot::setCapturedTexts(const QStringList& texts) { _capturedTexts = texts; } @@ -349,7 +343,7 @@ QStringList RegExpFilter::HotSpot::capturedTexts() const return _capturedTexts; } -void RegExpFilter::setRegExp(const QRegExp & regExp) +void RegExpFilter::setRegExp(const QRegExp& regExp) { _searchText = regExp; } @@ -364,64 +358,59 @@ QRegExp RegExpFilter::regExp() const void RegExpFilter::process() { int pos = 0; - const QString * text = buffer(); + const QString* text = buffer(); Q_ASSERT( text ); // ignore any regular expressions which match an empty string. // otherwise the while loop below will run indefinitely static const QString emptyString(""); - if ( _searchText.exactMatch(emptyString) ) { + if ( _searchText.exactMatch(emptyString) ) return; - } - while (pos >= 0) { + while(pos >= 0) + { pos = _searchText.indexIn(*text,pos); - if ( pos >= 0 ) { - + if ( pos >= 0 ) + { int startLine = 0; int endLine = 0; int startColumn = 0; int endColumn = 0; - - //kDebug() << "pos from " << pos << " to " << pos + _searchText.matchedLength(); - getLineColumn(pos,startLine,startColumn); getLineColumn(pos + _searchText.matchedLength(),endLine,endColumn); - //kDebug() << "start " << startLine << " / " << startColumn; - //kDebug() << "end " << endLine << " / " << endColumn; - - RegExpFilter::HotSpot * spot = newHotSpot(startLine,startColumn, + RegExpFilter::HotSpot* spot = newHotSpot(startLine,startColumn, endLine,endColumn); spot->setCapturedTexts(_searchText.capturedTexts()); - addHotSpot( spot ); + addHotSpot( spot ); pos += _searchText.matchedLength(); // if matchedLength == 0, the program will get stuck in an infinite loop - Q_ASSERT( _searchText.matchedLength() > 0 ); + if ( _searchText.matchedLength() == 0 ) + pos = -1; } - } + } } -RegExpFilter::HotSpot * RegExpFilter::newHotSpot(int startLine,int startColumn, - int endLine,int endColumn) +RegExpFilter::HotSpot* RegExpFilter::newHotSpot(int startLine,int startColumn, + int endLine,int endColumn) { return new RegExpFilter::HotSpot(startLine,startColumn, - endLine,endColumn); + endLine,endColumn); } -RegExpFilter::HotSpot * UrlFilter::newHotSpot(int startLine,int startColumn,int endLine, - int endColumn) +RegExpFilter::HotSpot* UrlFilter::newHotSpot(int startLine,int startColumn,int endLine, + int endColumn) { return new UrlFilter::HotSpot(startLine,startColumn, - endLine,endColumn); + endLine,endColumn); } UrlFilter::HotSpot::HotSpot(int startLine,int startColumn,int endLine,int endColumn) - : RegExpFilter::HotSpot(startLine,startColumn,endLine,endColumn) - , _urlObject(new FilterObject(this)) +: RegExpFilter::HotSpot(startLine,startColumn,endLine,endColumn) +, _urlObject(new FilterObject(this)) { setType(Link); } @@ -431,64 +420,67 @@ QString UrlFilter::HotSpot::tooltip() const const UrlType kind = urlType(); - if ( kind == StandardUrl ) { + if ( kind == StandardUrl ) + return QString(); + else if ( kind == Email ) + return QString(); + else return QString(); - } else if ( kind == Email ) { - return QString(); - } else { - return QString(); - } } UrlFilter::HotSpot::UrlType UrlFilter::HotSpot::urlType() const { QString url = capturedTexts().first(); - - if ( FullUrlRegExp.exactMatch(url) ) { + + if ( FullUrlRegExp.exactMatch(url) ) return StandardUrl; - } else if ( EmailAddressRegExp.exactMatch(url) ) { + else if ( EmailAddressRegExp.exactMatch(url) ) return Email; - } else { + else return Unknown; - } } -void UrlFilter::HotSpot::activate(QObject * object) +void UrlFilter::HotSpot::activate(QObject* object) { QString url = capturedTexts().first(); const UrlType kind = urlType(); - const QString & actionName = object ? object->objectName() : QString(); - - if ( actionName == "copy-action" ) { - //kDebug() << "Copying url to clipboard:" << url; + const QString& actionName = object ? object->objectName() : QString(); + if ( actionName == "copy-action" ) + { QApplication::clipboard()->setText(url); return; } - if ( !object || actionName == "open-action" ) { - if ( kind == StandardUrl ) { + if ( !object || actionName == "open-action" ) + { + if ( kind == StandardUrl ) + { // if the URL path does not include the protocol ( eg. "www.kde.org" ) then // prepend http:// ( eg. "www.kde.org" --> "http://www.kde.org" ) - if (!url.contains("://")) { + if (!url.contains("://")) + { url.prepend("http://"); } - } else if ( kind == Email ) { + } + else if ( kind == Email ) + { url.prepend("mailto:"); } - -// new KRun(url,QApplication::activeWindow()); + + QDesktopServices::openUrl(QUrl(url)); + //new KRun(url,QApplication::activeWindow()); } } -// Note: Altering these regular expressions can have a major effect on the performance of the filters +// Note: Altering these regular expressions can have a major effect on the performance of the filters // used for finding URLs in the text, especially if they are very general and could match very long // pieces of text. // Please be careful when altering them. //regexp matches: -// full url: +// full url: // protocolname:// or www. followed by anything other than whitespaces, <, >, ' or ", and ends before whitespaces, <, >, ', ", ], !, comma and dot const QRegExp UrlFilter::FullUrlRegExp("(www\\.(?!\\.)|[a-z][a-z0-9+.-]*://)[^\\s<>'\"]+[^!,\\.\\s<>'\"\\]]"); // email address: @@ -497,7 +489,7 @@ const QRegExp UrlFilter::EmailAddressRegExp("\\b(\\w|\\.|-)+@(\\w|\\.|-)+\\.\\w+ // matches full url or email address const QRegExp UrlFilter::CompleteUrlRegExp('('+FullUrlRegExp.pattern()+'|'+ - EmailAddressRegExp.pattern()+')'); + EmailAddressRegExp.pattern()+')'); UrlFilter::UrlFilter() { @@ -511,30 +503,33 @@ void FilterObject::activated() { _filter->activate(sender()); } -QList UrlFilter::HotSpot::actions() +QList UrlFilter::HotSpot::actions() { - QList list; + QList list; const UrlType kind = urlType(); - QAction * openAction = new QAction(_urlObject); - QAction * copyAction = new QAction(_urlObject);; + QAction* openAction = new QAction(_urlObject); + QAction* copyAction = new QAction(_urlObject);; Q_ASSERT( kind == StandardUrl || kind == Email ); - if ( kind == StandardUrl ) { - openAction->setText(("Open Link")); - copyAction->setText(("Copy Link Address")); - } else if ( kind == Email ) { - openAction->setText(("Send Email To...")); - copyAction->setText(("Copy Email Address")); + if ( kind == StandardUrl ) + { + openAction->setText(QObject::tr("Open Link")); + copyAction->setText(QObject::tr("Copy Link Address")); + } + else if ( kind == Email ) + { + openAction->setText(QObject::tr("Send Email To...")); + copyAction->setText(QObject::tr("Copy Email Address")); } // object names are set here so that the hotspot performs the // correct action when activated() is called with the triggered // action passed as a parameter. - openAction->setObjectName("open-action"); - copyAction->setObjectName("copy-action"); + openAction->setObjectName( QLatin1String("open-action" )); + copyAction->setObjectName( QLatin1String("copy-action" )); QObject::connect( openAction , SIGNAL(triggered()) , _urlObject , SLOT(activated()) ); QObject::connect( copyAction , SIGNAL(triggered()) , _urlObject , SLOT(activated()) ); @@ -542,7 +537,7 @@ QList UrlFilter::HotSpot::actions() list << openAction; list << copyAction; - return list; + return list; } -//#include "moc_Filter.cpp" +//#include "Filter.moc" diff --git a/lib/Filter.h b/lib/Filter.h index 9947f9f..860208c 100644 --- a/lib/Filter.h +++ b/lib/Filter.h @@ -1,7 +1,5 @@ /* - Copyright (C) 2007 by Robert Knight - - Rewritten for QT4 by e_k , Copyright (C)2008 + Copyright 2007-2008 by Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -33,7 +31,8 @@ // Local #include "Character.h" -namespace Konsole { +namespace Konsole +{ /** * A filter processes blocks of text looking for certain patterns (such as URLs or keywords from a list) @@ -45,7 +44,7 @@ namespace Konsole { * activate() method should be called. Depending on the type of hotspot this will trigger a suitable response. * * For example, if a hotspot represents a URL then a suitable action would be opening that URL in a web browser. - * Hotspots may have more than one action, in which case the list of actions can be obtained using the + * Hotspots may have more than one action, in which case the list of actions can be obtained using the * actions() method. * * Different subclasses of filter will return different types of hotspot. @@ -53,7 +52,8 @@ namespace Konsole { * When processing the text they should create instances of Filter::HotSpot subclasses for sections of interest * and add them to the filter's list of hotspots using addHotSpot() */ -class Filter { +class Filter +{ public: /** * Represents an area of text which matched the pattern a particular filter has been looking for. @@ -64,74 +64,76 @@ public: * activate() method should be called. Depending on the type of hotspot this will trigger a suitable response. * * For example, if a hotspot represents a URL then a suitable action would be opening that URL in a web browser. - * Hotspots may have more than one action, in which case the list of actions can be obtained using the - * actions() method. These actions may then be displayed in a popup menu or toolbar for example. + * Hotspots may have more than one action, in which case the list of actions can be obtained using the + * actions() method. These actions may then be displayed in a popup menu or toolbar for example. */ - class HotSpot { + class HotSpot + { public: - /** - * Constructs a new hotspot which covers the area from (@p startLine,@p startColumn) to (@p endLine,@p endColumn) - * in a block of text. - */ - HotSpot(int startLine , int startColumn , int endLine , int endColumn); - virtual ~HotSpot(); + /** + * Constructs a new hotspot which covers the area from (@p startLine,@p startColumn) to (@p endLine,@p endColumn) + * in a block of text. + */ + HotSpot(int startLine , int startColumn , int endLine , int endColumn); + virtual ~HotSpot(); - enum Type { + enum Type + { // the type of the hotspot is not specified NotSpecified, // this hotspot represents a clickable link Link, // this hotspot represents a marker Marker - }; + }; - /** Returns the line when the hotspot area starts */ - int startLine() const; - /** Returns the line where the hotspot area ends */ - int endLine() const; - /** Returns the column on startLine() where the hotspot area starts */ - int startColumn() const; - /** Returns the column on endLine() where the hotspot area ends */ - int endColumn() const; - /** - * Returns the type of the hotspot. This is usually used as a hint for views on how to represent - * the hotspot graphically. eg. Link hotspots are typically underlined when the user mouses over them - */ - Type type() const; - /** - * Causes the an action associated with a hotspot to be triggered. - * - * @param object The object which caused the hotspot to be triggered. This is - * typically null ( in which case the default action should be performed ) or - * one of the objects from the actions() list. In which case the associated - * action should be performed. - */ - virtual void activate(QObject * object = 0) = 0; - /** - * Returns a list of actions associated with the hotspot which can be used in a - * menu or toolbar - */ - virtual QList actions(); + /** Returns the line when the hotspot area starts */ + int startLine() const; + /** Returns the line where the hotspot area ends */ + int endLine() const; + /** Returns the column on startLine() where the hotspot area starts */ + int startColumn() const; + /** Returns the column on endLine() where the hotspot area ends */ + int endColumn() const; + /** + * Returns the type of the hotspot. This is usually used as a hint for views on how to represent + * the hotspot graphically. eg. Link hotspots are typically underlined when the user mouses over them + */ + Type type() const; + /** + * Causes the an action associated with a hotspot to be triggered. + * + * @param object The object which caused the hotspot to be triggered. This is + * typically null ( in which case the default action should be performed ) or + * one of the objects from the actions() list. In which case the associated + * action should be performed. + */ + virtual void activate(QObject* object = 0) = 0; + /** + * Returns a list of actions associated with the hotspot which can be used in a + * menu or toolbar + */ + virtual QList actions(); - /** - * Returns the text of a tooltip to be shown when the mouse moves over the hotspot, or - * an empty string if there is no tooltip associated with this hotspot. - * - * The default implementation returns an empty string. - */ - virtual QString tooltip() const; + /** + * Returns the text of a tooltip to be shown when the mouse moves over the hotspot, or + * an empty string if there is no tooltip associated with this hotspot. + * + * The default implementation returns an empty string. + */ + virtual QString tooltip() const; protected: - /** Sets the type of a hotspot. This should only be set once */ - void setType(Type type); + /** Sets the type of a hotspot. This should only be set once */ + void setType(Type type); private: - int _startLine; - int _startColumn; - int _endLine; - int _endColumn; - Type _type; - + int _startLine; + int _startColumn; + int _endLine; + int _endColumn; + Type _type; + }; /** Constructs a new filter. */ @@ -141,9 +143,9 @@ public: /** Causes the filter to process the block of text currently in its internal buffer */ virtual void process() = 0; - /** + /** * Empties the filters internal buffer and resets the line count back to 0. - * All hotspots are deleted. + * All hotspots are deleted. */ void reset(); @@ -151,55 +153,57 @@ public: //void addLine(const QString& string); /** Returns the hotspot which covers the given @p line and @p column, or 0 if no hotspot covers that area */ - HotSpot * hotSpotAt(int line , int column) const; + HotSpot* hotSpotAt(int line , int column) const; /** Returns the list of hotspots identified by the filter */ - QList hotSpots() const; + QList hotSpots() const; /** Returns the list of hotspots identified by the filter which occur on a given line */ - QList hotSpotsAtLine(int line) const; + QList hotSpotsAtLine(int line) const; - /** + /** * TODO: Document me */ - void setBuffer(const QString * buffer , const QList* linePositions); + void setBuffer(const QString* buffer , const QList* linePositions); protected: /** Adds a new hotspot to the list */ - void addHotSpot(HotSpot *); + void addHotSpot(HotSpot*); /** Returns the internal buffer */ - const QString * buffer(); + const QString* buffer(); /** Converts a character position within buffer() to a line and column */ - void getLineColumn(int position , int & startLine , int & startColumn); + void getLineColumn(int position , int& startLine , int& startColumn); private: - QMultiHash _hotspots; - QList _hotspotList; - + QMultiHash _hotspots; + QList _hotspotList; + const QList* _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. * * 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: - /** + /** * Type of hotspot created by RegExpFilter. The capturedTexts() method can be used to find the text * matched by the filter's regular expression. */ - class HotSpot : public Filter::HotSpot { + class HotSpot : public Filter::HotSpot + { public: HotSpot(int startLine, int startColumn, int endLine , int endColumn); - virtual void activate(QObject * object = 0); + virtual void activate(QObject* object = 0); /** Sets the captured texts associated with this hotspot */ - void setCapturedTexts(const QStringList & texts); + void setCapturedTexts(const QStringList& texts); /** Returns the texts found by the filter when matching the filter's regular expression */ QStringList capturedTexts() const; private: @@ -209,31 +213,31 @@ public: /** Constructs a new regular expression filter */ RegExpFilter(); - /** - * Sets the regular expression which the filter searches for in blocks of text. + /** + * Sets the regular expression which the filter searches for in blocks of text. * * Regular expressions which match the empty string are treated as not matching - * anything. + * anything. */ - void setRegExp(const QRegExp & text); + void setRegExp(const QRegExp& text); /** Returns the regular expression which the filter searches for in blocks of text */ QRegExp regExp() const; - /** - * Reimplemented to search the filter's text buffer for text matching regExp() + /** + * Reimplemented to search the filter's text buffer for text matching regExp() * * If regexp matches the empty string, then process() will return immediately - * without finding results. + * without finding results. */ virtual void process(); protected: - /** + /** * Called when a match for the regular expression is encountered. Subclasses should reimplement this * to return custom hotspot types */ - virtual RegExpFilter::HotSpot * newHotSpot(int startLine,int startColumn, - int endLine,int endColumn); + virtual RegExpFilter::HotSpot* newHotSpot(int startLine,int startColumn, + int endLine,int endColumn); private: QRegExp _searchText; @@ -242,66 +246,70 @@ private: class FilterObject; /** A filter which matches URLs in blocks of text */ -class UrlFilter : public RegExpFilter { +class UrlFilter : public RegExpFilter +{ public: - /** - * Hotspot type created by UrlFilter instances. The activate() method opens a web browser + /** + * Hotspot type created by UrlFilter instances. The activate() method opens a web browser * at the given URL when called. */ - class HotSpot : public RegExpFilter::HotSpot { + class HotSpot : public RegExpFilter::HotSpot + { public: HotSpot(int startLine,int startColumn,int endLine,int endColumn); virtual ~HotSpot(); - virtual QList actions(); + virtual QList actions(); - /** + /** * Open a web browser at the current URL. The url itself can be determined using * the capturedTexts() method. */ - virtual void activate(QObject * object = 0); + virtual void activate(QObject* object = 0); virtual QString tooltip() const; private: - enum UrlType { + enum UrlType + { StandardUrl, Email, Unknown }; UrlType urlType() const; - FilterObject * _urlObject; + FilterObject* _urlObject; }; UrlFilter(); protected: - virtual RegExpFilter::HotSpot * newHotSpot(int,int,int,int); + virtual RegExpFilter::HotSpot* newHotSpot(int,int,int,int); private: - + static const QRegExp FullUrlRegExp; static const QRegExp EmailAddressRegExp; // combined OR of FullUrlRegExp and EmailAddressRegExp - static const QRegExp CompleteUrlRegExp; + static const QRegExp CompleteUrlRegExp; }; -class FilterObject : public QObject { - Q_OBJECT +class FilterObject : public QObject +{ +Q_OBJECT public: - FilterObject(Filter::HotSpot * filter) : _filter(filter) {} + FilterObject(Filter::HotSpot* filter) : _filter(filter) {} private slots: void activated(); private: - Filter::HotSpot * _filter; + Filter::HotSpot* _filter; }; -/** - * A chain which allows a group of filters to be processed as one. +/** + * A chain which allows a group of filters to be processed as one. * The chain owns the filters added to it and deletes them when the chain itself is destroyed. * - * Use addFilter() to add a new filter to the chain. + * Use addFilter() to add a new filter to the chain. * When new text to be filtered arrives, use addLine() to add each additional * line of text which needs to be processed and then after adding the last line, use * process() to cause each filter in the chain to process the text. @@ -314,40 +322,42 @@ private: * The hotSpots() and hotSpotsAtLine() method return all of the hotspots in the text and on * a given line respectively. */ -class FilterChain : protected QList { +class FilterChain : protected QList +{ public: virtual ~FilterChain(); /** Adds a new filter to the chain. The chain will delete this filter when it is destroyed */ - void addFilter(Filter * filter); + void addFilter(Filter* filter); /** Removes a filter from the chain. The chain will no longer delete the filter when destroyed */ - void removeFilter(Filter * filter); + void removeFilter(Filter* filter); /** Returns true if the chain contains @p filter */ - bool containsFilter(Filter * filter); + bool containsFilter(Filter* filter); /** Removes all filters from the chain */ void clear(); /** Resets each filter in the chain */ void reset(); /** - * Processes each filter in the chain + * Processes each filter in the chain */ void process(); /** Sets the buffer for each filter in the chain to process. */ - void setBuffer(const QString * buffer , const QList* linePositions); + void setBuffer(const QString* buffer , const QList* linePositions); /** Returns the first hotspot which occurs at @p line, @p column or 0 if no hotspot was found */ - Filter::HotSpot * hotSpotAt(int line , int column) const; + Filter::HotSpot* hotSpotAt(int line , int column) const; /** Returns a list of all the hotspots in all the chain's filters */ - QList hotSpots() const; + QList hotSpots() const; /** Returns a list of all hotspots at the given line in all the chain's filters */ QList hotSpotsAtLine(int line) const; }; /** A filter chain which processes character images from terminal displays */ -class TerminalImageFilterChain : public FilterChain { +class TerminalImageFilterChain : public FilterChain +{ public: TerminalImageFilterChain(); virtual ~TerminalImageFilterChain(); @@ -358,12 +368,13 @@ public: * @param image The terminal image * @param lines The number of lines in the terminal image * @param columns The number of columns in the terminal image + * @param lineProperties The line properties to set for image */ - void setImage(const Character * const image , int lines , int columns, - const QVector& lineProperties); + void setImage(const Character* const image , int lines , int columns, + const QVector& lineProperties); private: - QString * _buffer; + QString* _buffer; QList* _linePositions; }; diff --git a/lib/History.cpp b/lib/History.cpp index 0945927..0f9c13f 100644 --- a/lib/History.cpp +++ b/lib/History.cpp @@ -1,8 +1,6 @@ /* This file is part of Konsole, an X terminal. - Copyright (C) 1997,1998 by Lars Doelle - - Rewritten for QT4 by e_k , Copyright (C)2008 + Copyright 1997,1998 by Lars Doelle This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -33,9 +31,15 @@ #include #include +#include + +// KDE +//#include +//#include // Reasonable line size -#define LINE_SIZE 1024 +#define LINE_SIZE 1024 +#define KDE_lseek lseek using namespace Konsole; @@ -84,21 +88,21 @@ FIXME: There is noticeable decrease in speed, also. Perhaps, */ HistoryFile::HistoryFile() - : ion(-1), - length(0), - fileMap(0) + : ion(-1), + length(0), + fileMap(0) { - if (tmpFile.open()) { - tmpFile.setAutoRemove(true); - ion = tmpFile.handle(); - } + if (tmpFile.open()) + { + tmpFile.setAutoRemove(true); + ion = tmpFile.handle(); + } } HistoryFile::~HistoryFile() { - if (fileMap) { + if (fileMap) unmap(); - } } //TODO: Mapping the entire file in will cause problems if the history file becomes exceedingly large, @@ -108,20 +112,21 @@ void HistoryFile::map() { assert( fileMap == 0 ); - fileMap = (char *)mmap( 0 , length , PROT_READ , MAP_PRIVATE , ion , 0 ); + fileMap = (char*)mmap( 0 , length , PROT_READ , MAP_PRIVATE , ion , 0 ); //if mmap'ing fails, fall back to the read-lseek combination - if ( fileMap == MAP_FAILED ) { - readWriteBalance = 0; - fileMap = 0; - qDebug() << ": mmap'ing history failed. errno = " << errno; + if ( fileMap == MAP_FAILED ) + { + readWriteBalance = 0; + fileMap = 0; + qDebug() << __FILE__ << __LINE__ << ": mmap'ing history failed. errno = " << errno; } } void HistoryFile::unmap() { int result = munmap( fileMap , length ); - assert( result == 0 ); + assert( result == 0 ); Q_UNUSED( result ); fileMap = 0; } @@ -131,90 +136,73 @@ bool HistoryFile::isMapped() return (fileMap != 0); } -void HistoryFile::add(const unsigned char * bytes, int len) +void HistoryFile::add(const unsigned char* bytes, int len) { - if ( fileMap ) { - unmap(); - } + if ( fileMap ) + unmap(); + + readWriteBalance++; - readWriteBalance++; + int rc = 0; - int rc = 0; - - rc = lseek(ion,length,SEEK_SET); - if (rc < 0) { - perror("HistoryFile::add.seek"); - return; - } - rc = write(ion,bytes,len); - if (rc < 0) { - perror("HistoryFile::add.write"); - return; - } - length += rc; + rc = KDE_lseek(ion,length,SEEK_SET); if (rc < 0) { perror("HistoryFile::add.seek"); return; } + rc = write(ion,bytes,len); if (rc < 0) { perror("HistoryFile::add.write"); return; } + length += rc; } -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. - //If there are many more get() calls compared with add() - //calls (decided by using MAP_THRESHOLD) then mmap the log - //file to improve performance. - readWriteBalance--; - if ( !fileMap && readWriteBalance < MAP_THRESHOLD ) { - map(); - } + //count number of get() calls vs. number of add() calls. + //If there are many more get() calls compared with add() + //calls (decided by using MAP_THRESHOLD) then mmap the log + //file to improve performance. + readWriteBalance--; + if ( !fileMap && readWriteBalance < MAP_THRESHOLD ) + map(); - if ( fileMap ) { - for (int i=0; i length) { - fprintf(stderr,"getHist(...,%d,%d): invalid args.\n",len,loc); - } - rc = lseek(ion,loc,SEEK_SET); - if (rc < 0) { - perror("HistoryFile::get.seek"); - return; - } - rc = read(ion,bytes,len); - if (rc < 0) { - perror("HistoryFile::get.read"); - return; - } - } + if (loc < 0 || len < 0 || loc + len > length) + fprintf(stderr,"getHist(...,%d,%d): invalid args.\n",len,loc); + rc = KDE_lseek(ion,loc,SEEK_SET); if (rc < 0) { perror("HistoryFile::get.seek"); return; } + rc = read(ion,bytes,len); if (rc < 0) { perror("HistoryFile::get.read"); return; } + } } int HistoryFile::len() { - return length; + return length; } // History Scroll abstract base class ////////////////////////////////////// -HistoryScroll::HistoryScroll(HistoryType * t) - : m_histType(t) +HistoryScroll::HistoryScroll(HistoryType* t) + : m_histType(t) { } HistoryScroll::~HistoryScroll() { - delete m_histType; + delete m_histType; } bool HistoryScroll::hasScroll() { - return true; + return true; } // History Scroll File ////////////////////////////////////// -/* +/* The history scroll makes a Row(Row(Cell)) from two history buffers. The index buffer contains start of line positions which refere to the cells @@ -225,86 +213,83 @@ bool HistoryScroll::hasScroll() at 0 in cells. */ -HistoryScrollFile::HistoryScrollFile(const QString & logFileName) - : HistoryScroll(new HistoryTypeFile(logFileName)), - m_logFileName(logFileName) +HistoryScrollFile::HistoryScrollFile(const QString &logFileName) + : HistoryScroll(new HistoryTypeFile(logFileName)), + m_logFileName(logFileName) { } HistoryScrollFile::~HistoryScrollFile() { } - + int HistoryScrollFile::getLines() { - return index.len() / sizeof(int); + return index.len() / sizeof(int); } int HistoryScrollFile::getLineLen(int lineno) { - return (startOfLine(lineno+1) - startOfLine(lineno)) / sizeof(Character); + return (startOfLine(lineno+1) - startOfLine(lineno)) / sizeof(Character); } bool HistoryScrollFile::isWrappedLine(int lineno) { - if (lineno>=0 && lineno <= getLines()) { - unsigned char flag; - lineflags.get((unsigned char *)&flag,sizeof(unsigned char),(lineno)*sizeof(unsigned char)); - return flag; - } - return false; + if (lineno>=0 && lineno <= getLines()) { + unsigned char flag; + lineflags.get((unsigned char*)&flag,sizeof(unsigned char),(lineno)*sizeof(unsigned char)); + return flag; + } + return false; } int HistoryScrollFile::startOfLine(int lineno) { - if (lineno <= 0) { - return 0; - } - if (lineno <= getLines()) { - - if (!index.isMapped()) { + if (lineno <= 0) return 0; + if (lineno <= getLines()) + { + + if (!index.isMapped()) index.map(); - } - - int res; - index.get((unsigned char *)&res,sizeof(int),(lineno-1)*sizeof(int)); - return res; + + int res; + index.get((unsigned char*)&res,sizeof(int),(lineno-1)*sizeof(int)); + return res; } - return cells.len(); + return cells.len(); } void HistoryScrollFile::getCells(int lineno, int colno, int count, Character res[]) { - cells.get((unsigned char *)res,count*sizeof(Character),startOfLine(lineno)+colno*sizeof(Character)); + cells.get((unsigned char*)res,count*sizeof(Character),startOfLine(lineno)+colno*sizeof(Character)); } void HistoryScrollFile::addCells(const Character text[], int count) { - cells.add((unsigned char *)text,count*sizeof(Character)); + cells.add((unsigned char*)text,count*sizeof(Character)); } void HistoryScrollFile::addLine(bool previousWrapped) { - if (index.isMapped()) { - index.unmap(); - } + if (index.isMapped()) + index.unmap(); - int locn = cells.len(); - index.add((unsigned char *)&locn,sizeof(int)); - unsigned char flags = previousWrapped ? 0x01 : 0x00; - lineflags.add((unsigned char *)&flags,sizeof(unsigned char)); + int locn = cells.len(); + index.add((unsigned char*)&locn,sizeof(int)); + unsigned char flags = previousWrapped ? 0x01 : 0x00; + lineflags.add((unsigned char*)&flags,sizeof(unsigned char)); } // History Scroll Buffer ////////////////////////////////////// HistoryScrollBuffer::HistoryScrollBuffer(unsigned int maxLineCount) - : HistoryScroll(new HistoryTypeBuffer(maxLineCount)) - ,_historyBuffer() - ,_maxLineCount(0) - ,_usedLines(0) - ,_head(0) + : HistoryScroll(new HistoryTypeBuffer(maxLineCount)) + ,_historyBuffer() + ,_maxLineCount(0) + ,_usedLines(0) + ,_head(0) { - setMaxNbLines(maxLineCount); + setMaxNbLines(maxLineCount); } HistoryScrollBuffer::~HistoryScrollBuffer() @@ -315,11 +300,11 @@ HistoryScrollBuffer::~HistoryScrollBuffer() void HistoryScrollBuffer::addCellsVector(const QVector& cells) { _head++; - if ( _usedLines < _maxLineCount ) { + if ( _usedLines < _maxLineCount ) _usedLines++; - } - if ( _head >= _maxLineCount ) { + if ( _head >= _maxLineCount ) + { _head = 0; } @@ -328,10 +313,10 @@ void HistoryScrollBuffer::addCellsVector(const QVector& cells) } void HistoryScrollBuffer::addCells(const Character a[], int count) { - HistoryLine newLine(count); - qCopy(a,a+count,newLine.begin()); + HistoryLine newLine(count); + qCopy(a,a+count,newLine.begin()); - addCellsVector(newLine); + addCellsVector(newLine); } void HistoryScrollBuffer::addLine(bool previousWrapped) @@ -346,60 +331,64 @@ int HistoryScrollBuffer::getLines() int HistoryScrollBuffer::getLineLen(int lineNumber) { - Q_ASSERT( lineNumber >= 0 && lineNumber < _maxLineCount ); + Q_ASSERT( lineNumber >= 0 && lineNumber < _maxLineCount ); - if ( lineNumber < _usedLines ) { - return _historyBuffer[bufferIndex(lineNumber)].size(); - } else { - return 0; - } + if ( lineNumber < _usedLines ) + { + return _historyBuffer[bufferIndex(lineNumber)].size(); + } + else + { + return 0; + } } bool HistoryScrollBuffer::isWrappedLine(int lineNumber) { - Q_ASSERT( lineNumber >= 0 && lineNumber < _maxLineCount ); - - if (lineNumber < _usedLines) { - //kDebug() << "Line" << lineNumber << "wrapped is" << _wrappedLine[bufferIndex(lineNumber)]; - return _wrappedLine[bufferIndex(lineNumber)]; - } else { - return false; - } + Q_ASSERT( lineNumber >= 0 && lineNumber < _maxLineCount ); + + if (lineNumber < _usedLines) + { + //kDebug() << "Line" << lineNumber << "wrapped is" << _wrappedLine[bufferIndex(lineNumber)]; + return _wrappedLine[bufferIndex(lineNumber)]; + } + else + return false; } -void HistoryScrollBuffer::getCells(int lineNumber, int startColumn, int count, Character * buffer) +void HistoryScrollBuffer::getCells(int lineNumber, int startColumn, int count, Character buffer[]) { - if ( count == 0 ) { - return; - } + if ( count == 0 ) return; - Q_ASSERT( lineNumber < _maxLineCount ); + Q_ASSERT( lineNumber < _maxLineCount ); - if (lineNumber >= _usedLines) { - memset(buffer, 0, count * sizeof(Character)); - return; - } + if (lineNumber >= _usedLines) + { + memset(buffer, 0, count * sizeof(Character)); + return; + } + + const HistoryLine& line = _historyBuffer[bufferIndex(lineNumber)]; - const HistoryLine & line = _historyBuffer[bufferIndex(lineNumber)]; + //kDebug() << "startCol " << startColumn; + //kDebug() << "line.size() " << line.size(); + //kDebug() << "count " << count; - //kDebug() << "startCol " << startColumn; - //kDebug() << "line.size() " << line.size(); - //kDebug() << "count " << count; - - Q_ASSERT( startColumn <= line.size() - count ); - - memcpy(buffer, line.constData() + startColumn , count * sizeof(Character)); + Q_ASSERT( startColumn <= line.size() - count ); + + memcpy(buffer, line.constData() + startColumn , count * sizeof(Character)); } void HistoryScrollBuffer::setMaxNbLines(unsigned int lineCount) { - HistoryLine * oldBuffer = _historyBuffer; - HistoryLine * newBuffer = new HistoryLine[lineCount]; - - for ( int i = 0 ; i < qMin(_usedLines,(int)lineCount) ; i++ ) { + HistoryLine* oldBuffer = _historyBuffer; + HistoryLine* newBuffer = new HistoryLine[lineCount]; + + for ( int i = 0 ; i < qMin(_usedLines,(int)lineCount) ; i++ ) + { newBuffer[i] = oldBuffer[bufferIndex(i)]; } - + _usedLines = qMin(_usedLines,(int)lineCount); _maxLineCount = lineCount; _head = ( _usedLines == _maxLineCount ) ? 0 : _usedLines-1; @@ -408,6 +397,7 @@ void HistoryScrollBuffer::setMaxNbLines(unsigned int lineCount) delete[] oldBuffer; _wrappedLine.resize(lineCount); + dynamic_cast(m_histType)->m_nbLines = lineCount; } int HistoryScrollBuffer::bufferIndex(int lineNumber) @@ -416,9 +406,12 @@ int HistoryScrollBuffer::bufferIndex(int lineNumber) Q_ASSERT( lineNumber < _maxLineCount ); Q_ASSERT( (_usedLines == _maxLineCount) || lineNumber <= _head ); - if ( _usedLines == _maxLineCount ) { + if ( _usedLines == _maxLineCount ) + { return (_head+lineNumber+1) % _maxLineCount; - } else { + } + else + { return lineNumber; } } @@ -427,7 +420,7 @@ int HistoryScrollBuffer::bufferIndex(int lineNumber) // History Scroll None ////////////////////////////////////// HistoryScrollNone::HistoryScrollNone() - : HistoryScroll(new HistoryTypeNone()) + : HistoryScroll(new HistoryTypeNone()) { } @@ -437,22 +430,22 @@ HistoryScrollNone::~HistoryScrollNone() bool HistoryScrollNone::hasScroll() { - return false; + return false; } int HistoryScrollNone::getLines() { - return 0; + return 0; } int HistoryScrollNone::getLineLen(int) { - return 0; + return 0; } bool HistoryScrollNone::isWrappedLine(int /*lineno*/) { - return false; + return false; } void HistoryScrollNone::getCells(int, int, int, Character []) @@ -470,9 +463,9 @@ void HistoryScrollNone::addLine(bool) // History Scroll BlockArray ////////////////////////////////////// HistoryScrollBlockArray::HistoryScrollBlockArray(size_t size) - : HistoryScroll(new HistoryTypeBlockArray(size)) + : HistoryScroll(new HistoryTypeBlockArray(size)) { - m_blockArray.setHistorySize(size); // nb. of lines. + m_blockArray.setHistorySize(size); // nb. of lines. } HistoryScrollBlockArray::~HistoryScrollBlockArray() @@ -481,68 +474,315 @@ HistoryScrollBlockArray::~HistoryScrollBlockArray() int HistoryScrollBlockArray::getLines() { - return m_lineLengths.count(); + return m_lineLengths.count(); } int HistoryScrollBlockArray::getLineLen(int lineno) { - if ( m_lineLengths.contains(lineno) ) { + if ( m_lineLengths.contains(lineno) ) return m_lineLengths[lineno]; - } else { + else return 0; - } } bool HistoryScrollBlockArray::isWrappedLine(int /*lineno*/) { - return false; + return false; } void HistoryScrollBlockArray::getCells(int lineno, int colno, int count, Character res[]) { - if (!count) { - return; - } + if (!count) return; - const Block * b = m_blockArray.at(lineno); + const Block *b = m_blockArray.at(lineno); - if (!b) { - memset(res, 0, count * sizeof(Character)); // still better than random data - return; - } + if (!b) { + memset(res, 0, count * sizeof(Character)); // still better than random data + return; + } - assert(((colno + count) * sizeof(Character)) < ENTRIES); - memcpy(res, b->data + (colno * sizeof(Character)), count * sizeof(Character)); + assert(((colno + count) * sizeof(Character)) < ENTRIES); + memcpy(res, b->data + (colno * sizeof(Character)), count * sizeof(Character)); } 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 + assert((count * sizeof(Character)) < ENTRIES); - // put cells in block's data - assert((count * sizeof(Character)) < ENTRIES); + memset(b->data, 0, ENTRIES); - memset(b->data, 0, ENTRIES); + memcpy(b->data, a, count * sizeof(Character)); + b->size = count * sizeof(Character); - memcpy(b->data, a, count * sizeof(Character)); - b->size = count * sizeof(Character); + size_t res = m_blockArray.newBlock(); + assert (res > 0); + Q_UNUSED( res ); - size_t res = m_blockArray.newBlock(); - assert (res > 0); - Q_UNUSED( res ); - - m_lineLengths.insert(m_blockArray.getCurrent(), count); + m_lineLengths.insert(m_blockArray.getCurrent(), count); } void HistoryScrollBlockArray::addLine(bool) { } +//////////////////////////////////////////////////////////////// +// Compact History Scroll ////////////////////////////////////// +//////////////////////////////////////////////////////////////// +void* CompactHistoryBlock::allocate ( size_t length ) +{ + Q_ASSERT ( length > 0 ); + if ( tail-blockStart+length > blockLength ) + return NULL; + + void* block = tail; + tail += length; + //kDebug() << "allocated " << length << " bytes at address " << block; + allocCount++; + return block; +} + +void CompactHistoryBlock::deallocate ( ) +{ + allocCount--; + Q_ASSERT ( allocCount >= 0 ); +} + +void* CompactHistoryBlockList::allocate(size_t size) +{ + CompactHistoryBlock* block; + if ( list.isEmpty() || list.last()->remaining() < size) + { + block = new CompactHistoryBlock(); + list.append ( block ); + //kDebug() << "new block created, remaining " << block->remaining() << "number of blocks=" << list.size(); + } + else + { + block = list.last(); + //kDebug() << "old block used, remaining " << block->remaining(); + } + return block->allocate(size); +} + +void CompactHistoryBlockList::deallocate(void* ptr) +{ + Q_ASSERT( !list.isEmpty()); + + int i=0; + CompactHistoryBlock *block = list.at(i); + while ( icontains(ptr) ) + { + i++; + block=list.at(i); + } + + Q_ASSERT( ideallocate(); + + if (!block->isInUse()) + { + list.removeAt(i); + delete block; + //kDebug() << "block deleted, new size = " << list.size(); + } +} + +CompactHistoryBlockList::~CompactHistoryBlockList() +{ + qDeleteAll ( list.begin(), list.end() ); + list.clear(); +} + +void* CompactHistoryLine::operator new (size_t size, CompactHistoryBlockList& blockList) +{ + return blockList.allocate(size); +} + +CompactHistoryLine::CompactHistoryLine ( const TextLine& line, CompactHistoryBlockList& bList ) + : blockList(bList), + formatLength(0) +{ + length=line.size(); + + if (line.size() > 0) { + formatLength=1; + int k=1; + + // count number of different formats in this text line + Character c = line[0]; + while ( k0) { + blockList.deallocate(text); + blockList.deallocate(formatArray); + } + blockList.deallocate(this); +} + +void CompactHistoryLine::getCharacter ( int index, Character &r ) +{ + Q_ASSERT ( index < length ); + int formatPos=0; + while ( ( formatPos+1 ) < formatLength && index >= formatArray[formatPos+1].startPos ) + formatPos++; + + r.character=text[index]; + r.rendition = formatArray[formatPos].rendition; + r.foregroundColor = formatArray[formatPos].fgColor; + r.backgroundColor = formatArray[formatPos].bgColor; +} + +void CompactHistoryLine::getCharacters ( Character* array, int length, int startColumn ) +{ + Q_ASSERT ( startColumn >= 0 && length >= 0 ); + Q_ASSERT ( startColumn+length <= ( int ) getLength() ); + + for ( int i=startColumn; i ( int ) _maxLineCount ) + { + delete lines.takeAt ( 0 ); + } + lines.append ( line ); +} + +void CompactHistoryScroll::addCells ( const Character a[], int count ) +{ + TextLine newLine ( count ); + qCopy ( a,a+count,newLine.begin() ); + addCellsVector ( newLine ); +} + +void CompactHistoryScroll::addLine ( bool previousWrapped ) +{ + CompactHistoryLine *line = lines.last(); + //kDebug() << "last line at address " << line; + line->setWrapped(previousWrapped); +} + +int CompactHistoryScroll::getLines() +{ + return lines.size(); +} + +int CompactHistoryScroll::getLineLen ( int lineNumber ) +{ + Q_ASSERT ( lineNumber >= 0 && lineNumber < lines.size() ); + CompactHistoryLine* line = lines[lineNumber]; + //kDebug() << "request for line at address " << line; + return line->getLength(); +} + + +void CompactHistoryScroll::getCells ( int lineNumber, int startColumn, int count, Character buffer[] ) +{ + if ( count == 0 ) return; + Q_ASSERT ( lineNumber < lines.size() ); + CompactHistoryLine* line = lines[lineNumber]; + Q_ASSERT ( startColumn >= 0 ); + Q_ASSERT ( (unsigned int)startColumn <= line->getLength() - count ); + line->getCharacters ( buffer, count, startColumn ); +} + +void CompactHistoryScroll::setMaxNbLines ( unsigned int lineCount ) +{ + _maxLineCount = lineCount; + + while (lines.size() > (int) lineCount) { + delete lines.takeAt(0); + } + //kDebug() << "set max lines to: " << _maxLineCount; +} + +bool CompactHistoryScroll::isWrappedLine ( int lineNumber ) +{ + Q_ASSERT ( lineNumber < lines.size() ); + return lines[lineNumber]->isWrapped(); +} + + ////////////////////////////////////////////////////////////////////// // History Types ////////////////////////////////////////////////////////////////////// @@ -563,145 +803,185 @@ HistoryTypeNone::HistoryTypeNone() bool HistoryTypeNone::isEnabled() const { - return false; + return false; } -HistoryScroll * HistoryTypeNone::scroll(HistoryScroll * old) const +HistoryScroll* HistoryTypeNone::scroll(HistoryScroll *old) const { - delete old; - return new HistoryScrollNone(); + delete old; + return new HistoryScrollNone(); } int HistoryTypeNone::maximumLineCount() const { - return 0; + return 0; } ////////////////////////////// HistoryTypeBlockArray::HistoryTypeBlockArray(size_t size) - : m_size(size) + : m_size(size) { } bool HistoryTypeBlockArray::isEnabled() const { - return true; + return true; } int HistoryTypeBlockArray::maximumLineCount() const { - return m_size; + return m_size; } -HistoryScroll * HistoryTypeBlockArray::scroll(HistoryScroll * old) const +HistoryScroll* HistoryTypeBlockArray::scroll(HistoryScroll *old) const { - delete old; - return new HistoryScrollBlockArray(m_size); + delete old; + return new HistoryScrollBlockArray(m_size); } ////////////////////////////// HistoryTypeBuffer::HistoryTypeBuffer(unsigned int nbLines) - : m_nbLines(nbLines) + : m_nbLines(nbLines) { } bool HistoryTypeBuffer::isEnabled() const { - return true; + return true; } int HistoryTypeBuffer::maximumLineCount() const { - return m_nbLines; + return m_nbLines; } -HistoryScroll * HistoryTypeBuffer::scroll(HistoryScroll * old) const +HistoryScroll* HistoryTypeBuffer::scroll(HistoryScroll *old) const { - if (old) { - HistoryScrollBuffer * oldBuffer = dynamic_cast(old); - if (oldBuffer) { - oldBuffer->setMaxNbLines(m_nbLines); - return oldBuffer; - } - - HistoryScroll * newScroll = new HistoryScrollBuffer(m_nbLines); - int lines = old->getLines(); - int startLine = 0; - if (lines > (int) m_nbLines) { - startLine = lines - m_nbLines; - } - - Character line[LINE_SIZE]; - for (int i = startLine; i < lines; i++) { - int size = old->getLineLen(i); - if (size > LINE_SIZE) { - Character * tmp_line = new Character[size]; - old->getCells(i, 0, size, tmp_line); - newScroll->addCells(tmp_line, size); - newScroll->addLine(old->isWrappedLine(i)); - delete [] tmp_line; - } else { - old->getCells(i, 0, size, line); - newScroll->addCells(line, size); - newScroll->addLine(old->isWrappedLine(i)); - } - } - delete old; - return newScroll; + if (old) + { + HistoryScrollBuffer *oldBuffer = dynamic_cast(old); + if (oldBuffer) + { + oldBuffer->setMaxNbLines(m_nbLines); + return oldBuffer; } - return new HistoryScrollBuffer(m_nbLines); + + HistoryScroll *newScroll = new HistoryScrollBuffer(m_nbLines); + int lines = old->getLines(); + int startLine = 0; + if (lines > (int) m_nbLines) + startLine = lines - m_nbLines; + + Character line[LINE_SIZE]; + for(int i = startLine; i < lines; i++) + { + int size = old->getLineLen(i); + if (size > LINE_SIZE) + { + Character *tmp_line = new Character[size]; + old->getCells(i, 0, size, tmp_line); + newScroll->addCells(tmp_line, size); + newScroll->addLine(old->isWrappedLine(i)); + delete [] tmp_line; + } + else + { + old->getCells(i, 0, size, line); + newScroll->addCells(line, size); + newScroll->addLine(old->isWrappedLine(i)); + } + } + delete old; + return newScroll; + } + return new HistoryScrollBuffer(m_nbLines); } ////////////////////////////// -HistoryTypeFile::HistoryTypeFile(const QString & fileName) - : m_fileName(fileName) +HistoryTypeFile::HistoryTypeFile(const QString& fileName) + : m_fileName(fileName) { } bool HistoryTypeFile::isEnabled() const { - return true; + return true; } -const QString & HistoryTypeFile::getFileName() const +const QString& HistoryTypeFile::getFileName() const { - return m_fileName; + return m_fileName; } -HistoryScroll * HistoryTypeFile::scroll(HistoryScroll * old) const +HistoryScroll* HistoryTypeFile::scroll(HistoryScroll *old) const { - if (dynamic_cast(old)) { - return old; // Unchanged. - } + if (dynamic_cast(old)) + return old; // Unchanged. - HistoryScroll * newScroll = new HistoryScrollFile(m_fileName); + HistoryScroll *newScroll = new HistoryScrollFile(m_fileName); - Character line[LINE_SIZE]; - int lines = (old != 0) ? old->getLines() : 0; - for (int i = 0; i < lines; i++) { - int size = old->getLineLen(i); - if (size > LINE_SIZE) { - Character * tmp_line = new Character[size]; - old->getCells(i, 0, size, tmp_line); - newScroll->addCells(tmp_line, size); - newScroll->addLine(old->isWrappedLine(i)); - delete [] tmp_line; - } else { - old->getCells(i, 0, size, line); - newScroll->addCells(line, size); - newScroll->addLine(old->isWrappedLine(i)); - } - } + Character line[LINE_SIZE]; + int lines = (old != 0) ? old->getLines() : 0; + for(int i = 0; i < lines; i++) + { + int size = old->getLineLen(i); + if (size > LINE_SIZE) + { + Character *tmp_line = new Character[size]; + old->getCells(i, 0, size, tmp_line); + newScroll->addCells(tmp_line, size); + newScroll->addLine(old->isWrappedLine(i)); + delete [] tmp_line; + } + else + { + old->getCells(i, 0, size, line); + newScroll->addCells(line, size); + newScroll->addLine(old->isWrappedLine(i)); + } + } - delete old; - return newScroll; + delete old; + return newScroll; } int HistoryTypeFile::maximumLineCount() const { - return 0; + return 0; +} + +////////////////////////////// + +CompactHistoryType::CompactHistoryType ( unsigned int nbLines ) + : m_nbLines ( nbLines ) +{ +} + +bool CompactHistoryType::isEnabled() const +{ + return true; +} + +int CompactHistoryType::maximumLineCount() const +{ + return m_nbLines; +} + +HistoryScroll* CompactHistoryType::scroll ( HistoryScroll *old ) const +{ + if ( old ) + { + CompactHistoryScroll *oldBuffer = dynamic_cast ( old ); + if ( oldBuffer ) + { + oldBuffer->setMaxNbLines ( m_nbLines ); + return oldBuffer; + } + delete old; + } + return new CompactHistoryScroll ( m_nbLines ); } diff --git a/lib/History.h b/lib/History.h index fb8aa34..5bcbfb8 100644 --- a/lib/History.h +++ b/lib/History.h @@ -1,8 +1,6 @@ /* This file is part of Konsole, an X terminal. - Copyright (C) 1997,1998 by Lars Doelle - - Rewritten for QT4 by e_k , Copyright (C)2008 + Copyright 1997,1998 by Lars Doelle This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -26,52 +24,61 @@ // Qt #include #include -#include +#include +#include + +// KDE +//#include // Konsole #include "BlockArray.h" #include "Character.h" -namespace Konsole { +// map +#include + +namespace Konsole +{ #if 1 /* An extendable tmpfile(1) based buffer. */ -class HistoryFile { +class HistoryFile +{ public: - HistoryFile(); - virtual ~HistoryFile(); + HistoryFile(); + virtual ~HistoryFile(); - virtual void add(const unsigned char * bytes, int len); - virtual void get(unsigned char * bytes, int len, int loc); - virtual int len(); + virtual void add(const unsigned char* bytes, int len); + virtual void get(unsigned char* bytes, int len, int loc); + virtual int len(); - //mmaps the file in read-only mode - void map(); - //un-mmaps the file - void unmap(); - //returns true if the file is mmap'ed - bool isMapped(); + //mmaps the file in read-only mode + void map(); + //un-mmaps the file + void unmap(); + //returns true if the file is mmap'ed + bool isMapped(); private: - int ion; - int length; - QTemporaryFile tmpFile; + int ion; + int length; + QTemporaryFile tmpFile; - //pointer to start of mmap'ed file data, or 0 if the file is not mmap'ed - char * fileMap; + //pointer to start of mmap'ed file data, or 0 if the file is not mmap'ed + char* fileMap; + + //incremented whenver 'add' is called and decremented whenever + //'get' is called. + //this is used to detect when a large number of lines are being read and processed from the history + //and automatically mmap the file for better performance (saves the overhead of many lseek-read calls). + int readWriteBalance; - //incremented whenver 'add' is called and decremented whenever - //'get' is called. - //this is used to detect when a large number of lines are being read and processed from the history - //and automatically mmap the file for better performance (saves the overhead of many lseek-read calls). - int readWriteBalance; - - //when readWriteBalance goes below this threshold, the file will be mmap'ed automatically - static const int MAP_THRESHOLD = -1000; + //when readWriteBalance goes below this threshold, the file will be mmap'ed automatically + static const int MAP_THRESHOLD = -1000; }; #endif @@ -82,47 +89,43 @@ private: ////////////////////////////////////////////////////////////////////// class HistoryType; -class HistoryScroll { +class HistoryScroll +{ public: - HistoryScroll(HistoryType *); - virtual ~HistoryScroll(); + HistoryScroll(HistoryType*); + virtual ~HistoryScroll(); - virtual bool hasScroll(); + virtual bool hasScroll(); - // access to history - virtual int getLines() = 0; - virtual int getLineLen(int lineno) = 0; - virtual void getCells(int lineno, int colno, int count, Character res[]) = 0; - virtual bool isWrappedLine(int lineno) = 0; + // access to history + virtual int getLines() = 0; + virtual int getLineLen(int lineno) = 0; + virtual void getCells(int lineno, int colno, int count, Character res[]) = 0; + virtual bool isWrappedLine(int lineno) = 0; - // backward compatibility (obsolete) - Character getCell(int lineno, int colno) { - Character res; - getCells(lineno,colno,1,&res); - return res; - } + // backward compatibility (obsolete) + Character getCell(int lineno, int colno) { Character res; getCells(lineno,colno,1,&res); return res; } - // adding lines. - virtual void addCells(const Character a[], int count) = 0; - // convenience method - this is virtual so that subclasses can take advantage - // of QVector's implicit copying - virtual void addCellsVector(const QVector& cells) { - addCells(cells.data(),cells.size()); - } + // adding lines. + virtual void addCells(const Character a[], int count) = 0; + // convenience method - this is virtual so that subclasses can take advantage + // of QVector's implicit copying + virtual void addCellsVector(const QVector& cells) + { + addCells(cells.data(),cells.size()); + } - virtual void addLine(bool previousWrapped=false) = 0; + virtual void addLine(bool previousWrapped=false) = 0; - // - // FIXME: Passing around constant references to HistoryType instances - // is very unsafe, because those references will no longer - // be valid if the history scroll is deleted. - // - const HistoryType & getType() { - return *m_histType; - } + // + // FIXME: Passing around constant references to HistoryType instances + // is very unsafe, because those references will no longer + // be valid if the history scroll is deleted. + // + const HistoryType& getType() { return *m_histType; } protected: - HistoryType * m_histType; + HistoryType* m_histType; }; @@ -132,69 +135,69 @@ protected: // File-based history (e.g. file log, no limitation in length) ////////////////////////////////////////////////////////////////////// -class HistoryScrollFile : public HistoryScroll { +class HistoryScrollFile : public HistoryScroll +{ public: - HistoryScrollFile(const QString & logFileName); - virtual ~HistoryScrollFile(); + HistoryScrollFile(const QString &logFileName); + virtual ~HistoryScrollFile(); - virtual int getLines(); - virtual int getLineLen(int lineno); - virtual void getCells(int lineno, int colno, int count, Character res[]); - virtual bool isWrappedLine(int lineno); + virtual int getLines(); + virtual int getLineLen(int lineno); + virtual void getCells(int lineno, int colno, int count, Character res[]); + virtual bool isWrappedLine(int lineno); - virtual void addCells(const Character a[], int count); - virtual void addLine(bool previousWrapped=false); + virtual void addCells(const Character a[], int count); + virtual void addLine(bool previousWrapped=false); private: - int startOfLine(int lineno); + int startOfLine(int lineno); - QString m_logFileName; - HistoryFile index; // lines Row(int) - HistoryFile cells; // text Row(Character) - HistoryFile lineflags; // flags Row(unsigned char) + QString m_logFileName; + HistoryFile index; // lines Row(int) + HistoryFile cells; // text Row(Character) + HistoryFile lineflags; // flags Row(unsigned char) }; ////////////////////////////////////////////////////////////////////// // Buffer-based history (limited to a fixed nb of lines) ////////////////////////////////////////////////////////////////////// -class HistoryScrollBuffer : public HistoryScroll { +class HistoryScrollBuffer : public HistoryScroll +{ public: - typedef QVector HistoryLine; + typedef QVector HistoryLine; - HistoryScrollBuffer(unsigned int maxNbLines = 1000); - virtual ~HistoryScrollBuffer(); + HistoryScrollBuffer(unsigned int maxNbLines = 1000); + virtual ~HistoryScrollBuffer(); - virtual int getLines(); - virtual int getLineLen(int lineno); - virtual void getCells(int lineno, int colno, int count, Character res[]); - virtual bool isWrappedLine(int lineno); + virtual int getLines(); + virtual int getLineLen(int lineno); + virtual void getCells(int lineno, int colno, int count, Character res[]); + virtual bool isWrappedLine(int lineno); - virtual void addCells(const Character a[], int count); - virtual void addCellsVector(const QVector& cells); - virtual void addLine(bool previousWrapped=false); - - void setMaxNbLines(unsigned int nbLines); - unsigned int maxNbLines() { - return _maxLineCount; - } + virtual void addCells(const Character a[], int count); + virtual void addCellsVector(const QVector& cells); + virtual void addLine(bool previousWrapped=false); + void setMaxNbLines(unsigned int nbLines); + unsigned int maxNbLines() { return _maxLineCount; } + private: - int bufferIndex(int lineNumber); + int bufferIndex(int lineNumber); - HistoryLine * _historyBuffer; - QBitArray _wrappedLine; - int _maxLineCount; - int _usedLines; - int _head; - - //QVector m_histBuffer; - //QBitArray m_wrappedLine; - //unsigned int m_maxNbLines; - //unsigned int m_nbLines; - //unsigned int m_arrayIndex; - //bool m_buffFilled; + HistoryLine* _historyBuffer; + QBitArray _wrappedLine; + int _maxLineCount; + int _usedLines; + int _head; + + //QVector m_histBuffer; + //QBitArray m_wrappedLine; + //unsigned int m_maxNbLines; + //unsigned int m_nbLines; + //unsigned int m_arrayIndex; + //bool m_buffFilled; }; /*class HistoryScrollBufferV2 : public HistoryScroll @@ -216,124 +219,273 @@ public: ////////////////////////////////////////////////////////////////////// // Nothing-based history (no history :-) ////////////////////////////////////////////////////////////////////// -class HistoryScrollNone : public HistoryScroll { +class HistoryScrollNone : public HistoryScroll +{ public: - HistoryScrollNone(); - virtual ~HistoryScrollNone(); + HistoryScrollNone(); + virtual ~HistoryScrollNone(); - virtual bool hasScroll(); + virtual bool hasScroll(); - virtual int getLines(); - virtual int getLineLen(int lineno); - virtual void getCells(int lineno, int colno, int count, Character res[]); - virtual bool isWrappedLine(int lineno); + virtual int getLines(); + virtual int getLineLen(int lineno); + virtual void getCells(int lineno, int colno, int count, Character res[]); + virtual bool isWrappedLine(int lineno); - virtual void addCells(const Character a[], int count); - virtual void addLine(bool previousWrapped=false); + virtual void addCells(const Character a[], int count); + virtual void addLine(bool previousWrapped=false); }; ////////////////////////////////////////////////////////////////////// // BlockArray-based history ////////////////////////////////////////////////////////////////////// -class HistoryScrollBlockArray : public HistoryScroll { +class HistoryScrollBlockArray : public HistoryScroll +{ public: - HistoryScrollBlockArray(size_t size); - virtual ~HistoryScrollBlockArray(); + HistoryScrollBlockArray(size_t size); + virtual ~HistoryScrollBlockArray(); - virtual int getLines(); - virtual int getLineLen(int lineno); - virtual void getCells(int lineno, int colno, int count, Character res[]); - virtual bool isWrappedLine(int lineno); + virtual int getLines(); + virtual int getLineLen(int lineno); + virtual void getCells(int lineno, int colno, int count, Character res[]); + virtual bool isWrappedLine(int lineno); - virtual void addCells(const Character a[], int count); - virtual void addLine(bool previousWrapped=false); + virtual void addCells(const Character a[], int count); + virtual void addLine(bool previousWrapped=false); protected: - BlockArray m_blockArray; - QHash m_lineLengths; + BlockArray m_blockArray; + QHash m_lineLengths; +}; + +////////////////////////////////////////////////////////////////////// +// History using compact storage +// This implementation uses a list of fixed-sized blocks +// where history lines are allocated in (avoids heap fragmentation) +////////////////////////////////////////////////////////////////////// +typedef QVector TextLine; + +class CharacterFormat +{ +public: + bool equalsFormat(const CharacterFormat &other) const { + return other.rendition==rendition && other.fgColor==fgColor && other.bgColor==bgColor; + } + + bool equalsFormat(const Character &c) const { + return c.rendition==rendition && c.foregroundColor==fgColor && c.backgroundColor==bgColor; + } + + void setFormat(const Character& c) { + rendition=c.rendition; + fgColor=c.foregroundColor; + bgColor=c.backgroundColor; + } + + CharacterColor fgColor, bgColor; + quint16 startPos; + quint8 rendition; +}; + +class CompactHistoryBlock +{ +public: + + CompactHistoryBlock(){ + blockLength = 4096*64; // 256kb + head = (quint8*) mmap(0, blockLength, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0); + //head = (quint8*) malloc(blockLength); + Q_ASSERT(head != MAP_FAILED); + tail = blockStart = head; + allocCount=0; + } + + virtual ~CompactHistoryBlock(){ + //free(blockStart); + munmap(blockStart, blockLength); + } + + virtual unsigned int remaining(){ return blockStart+blockLength-tail;} + virtual unsigned length() { return blockLength; } + virtual void* allocate(size_t length); + virtual bool contains(void *addr) {return addr>=blockStart && addr<(blockStart+blockLength);} + virtual void deallocate(); + virtual bool isInUse(){ return allocCount!=0; } ; + +private: + size_t blockLength; + quint8* head; + quint8* tail; + quint8* blockStart; + int allocCount; +}; + +class CompactHistoryBlockList { +public: + CompactHistoryBlockList() {}; + ~CompactHistoryBlockList(); + + void *allocate( size_t size ); + void deallocate(void *); + int length() {return list.size();} +private: + QList list; +}; + +class CompactHistoryLine +{ +public: + CompactHistoryLine(const TextLine&, CompactHistoryBlockList& blockList); + virtual ~CompactHistoryLine(); + + // custom new operator to allocate memory from custom pool instead of heap + static void *operator new( size_t size, CompactHistoryBlockList& blockList); + static void operator delete( void *) { /* do nothing, deallocation from pool is done in destructor*/ } ; + + virtual void getCharacters(Character* array, int length, int startColumn) ; + virtual void getCharacter(int index, Character &r) ; + virtual bool isWrapped() const {return wrapped;}; + virtual void setWrapped(bool isWrapped) { wrapped=isWrapped;}; + virtual unsigned int getLength() const {return length;}; + +protected: + CompactHistoryBlockList& blockList; + CharacterFormat* formatArray; + quint16 length; + quint16* text; + quint16 formatLength; + bool wrapped; +}; + +class CompactHistoryScroll : public HistoryScroll +{ + typedef QList HistoryArray; + +public: + CompactHistoryScroll(unsigned int maxNbLines = 1000); + virtual ~CompactHistoryScroll(); + + virtual int getLines(); + virtual int getLineLen(int lineno); + virtual void getCells(int lineno, int colno, int count, Character res[]); + virtual bool isWrappedLine(int lineno); + + virtual void addCells(const Character a[], int count); + virtual void addCellsVector(const TextLine& cells); + virtual void addLine(bool previousWrapped=false); + + void setMaxNbLines(unsigned int nbLines); + unsigned int maxNbLines() const { return _maxLineCount; } + +private: + bool hasDifferentColors(const TextLine& line) const; + HistoryArray lines; + CompactHistoryBlockList blockList; + + unsigned int _maxLineCount; }; ////////////////////////////////////////////////////////////////////// // History type ////////////////////////////////////////////////////////////////////// -class HistoryType { +class HistoryType +{ public: - HistoryType(); - virtual ~HistoryType(); + HistoryType(); + virtual ~HistoryType(); - /** - * Returns true if the history is enabled ( can store lines of output ) - * or false otherwise. - */ - virtual bool isEnabled() const = 0; - /** - * Returns true if the history size is unlimited. - */ - bool isUnlimited() const { - return maximumLineCount() == 0; - } - /** - * Returns the maximum number of lines which this history type - * can store or 0 if the history can store an unlimited number of lines. - */ - virtual int maximumLineCount() const = 0; + /** + * Returns true if the history is enabled ( can store lines of output ) + * or false otherwise. + */ + virtual bool isEnabled() const = 0; + /** + * Returns true if the history size is unlimited. + */ + bool isUnlimited() const { return maximumLineCount() == 0; } + /** + * Returns the maximum number of lines which this history type + * can store or 0 if the history can store an unlimited number of lines. + */ + virtual int maximumLineCount() const = 0; - virtual HistoryScroll * scroll(HistoryScroll *) const = 0; + virtual HistoryScroll* scroll(HistoryScroll *) const = 0; }; -class HistoryTypeNone : public HistoryType { +class HistoryTypeNone : public HistoryType +{ public: - HistoryTypeNone(); + HistoryTypeNone(); - virtual bool isEnabled() const; - virtual int maximumLineCount() const; + virtual bool isEnabled() const; + virtual int maximumLineCount() const; - virtual HistoryScroll * scroll(HistoryScroll *) const; + virtual HistoryScroll* scroll(HistoryScroll *) const; }; -class HistoryTypeBlockArray : public HistoryType { +class HistoryTypeBlockArray : public HistoryType +{ public: - HistoryTypeBlockArray(size_t size); + HistoryTypeBlockArray(size_t size); + + virtual bool isEnabled() const; + virtual int maximumLineCount() const; - virtual bool isEnabled() const; - virtual int maximumLineCount() const; - - virtual HistoryScroll * scroll(HistoryScroll *) const; + virtual HistoryScroll* scroll(HistoryScroll *) const; protected: - size_t m_size; + size_t m_size; }; -#if 1 -class HistoryTypeFile : public HistoryType { +#if 1 +class HistoryTypeFile : public HistoryType +{ public: - HistoryTypeFile(const QString & fileName=QString()); + HistoryTypeFile(const QString& fileName=QString()); - virtual bool isEnabled() const; - virtual const QString & getFileName() const; - virtual int maximumLineCount() const; + virtual bool isEnabled() const; + virtual const QString& getFileName() const; + virtual int maximumLineCount() const; - virtual HistoryScroll * scroll(HistoryScroll *) const; + virtual HistoryScroll* scroll(HistoryScroll *) const; protected: - QString m_fileName; + QString m_fileName; }; -class HistoryTypeBuffer : public HistoryType { +class HistoryTypeBuffer : public HistoryType +{ + friend class HistoryScrollBuffer; + public: - HistoryTypeBuffer(unsigned int nbLines); - - virtual bool isEnabled() const; - virtual int maximumLineCount() const; - - virtual HistoryScroll * scroll(HistoryScroll *) const; + HistoryTypeBuffer(unsigned int nbLines); + + virtual bool isEnabled() const; + virtual int maximumLineCount() const; + + virtual HistoryScroll* scroll(HistoryScroll *) const; protected: - unsigned int m_nbLines; + unsigned int m_nbLines; }; +class CompactHistoryType : public HistoryType +{ +public: + CompactHistoryType(unsigned int size); + + virtual bool isEnabled() const; + virtual int maximumLineCount() const; + + virtual HistoryScroll* scroll(HistoryScroll *) const; + +protected: + unsigned int m_nbLines; +}; + + #endif } diff --git a/lib/KeyboardTranslator.cpp b/lib/KeyboardTranslator.cpp index 7853115..fc66a9c 100644 --- a/lib/KeyboardTranslator.cpp +++ b/lib/KeyboardTranslator.cpp @@ -1,9 +1,7 @@ /* - This source file was part of Konsole, a terminal emulator. + This source file is part of Konsole, a terminal emulator. - Copyright (C) 2007 by Robert Knight - - Rewritten for QT4 by e_k , Copyright (C)2008 + Copyright 2007-2008 by Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -30,11 +28,14 @@ // Qt #include -//#include #include #include -#include -#include +#include +#include +#include +#include + +#include "tools.h" // KDE //#include @@ -43,188 +44,154 @@ using namespace Konsole; -//this is for default REALLY fallback translator. -//const char* KeyboardTranslatorManager::defaultTranslatorText = -//#include "DefaultTranslatorText.h" -//; - -//and this is default now translator - default.keytab from original Konsole -const char * KeyboardTranslatorManager::defaultTranslatorText = -#include "ExtendedDefaultTranslator.h" - ; +const QByteArray KeyboardTranslatorManager::defaultTranslatorText( +"keyboard \"Fallback Key Translator\"\n" +"key Tab : \"\\t\"" +); KeyboardTranslatorManager::KeyboardTranslatorManager() - : _haveLoadedAll(false) + : _haveLoadedAll(false) { } KeyboardTranslatorManager::~KeyboardTranslatorManager() { - qDeleteAll(_translators.values()); + qDeleteAll(_translators); } - -/*! Helper function to get possible location of layout files. -By default the KB_LAYOUT_DIR is used (linux/BSD/macports). -But in some cases (apple bundle) there can be more locations). -*/ -QString get_kb_layout_dir() -{ - qDebug() << "get_kb_layout_dir"; - QString k(KB_LAYOUT_DIR); - QDir d(k); - qDebug() << k; - if (d.exists()) - return k; - // subdir in the app location - d.setPath(QCoreApplication::applicationDirPath() + "/kb-layouts/"); - qDebug() << d.path(); - if (d.exists()) - return QCoreApplication::applicationDirPath() + "/kb-layouts/"; - // apple bundle - d.setPath(QCoreApplication::applicationDirPath() + "/../Resources/kb-layouts/"); - qDebug() << d.path(); - if (d.exists()) - return QCoreApplication::applicationDirPath() + "/../Resources/kb-layouts/"; - qDebug() << "Cannot find kb-layouts in any location!"; - return ""; -} - - -QString KeyboardTranslatorManager::findTranslatorPath(const QString & name) +QString KeyboardTranslatorManager::findTranslatorPath(const QString& name) { return QString(get_kb_layout_dir() + name + ".keytab"); + //return KGlobal::dirs()->findResource("data","konsole/"+name+".keytab"); } + void KeyboardTranslatorManager::findTranslators() { QDir dir(get_kb_layout_dir()); - qDebug() << "D" << dir.path(); QStringList filters; filters << "*.keytab"; dir.setNameFilters(filters); - QStringList list = dir.entryList(filters); //(".keytab"); // = KGlobal::dirs()->findAllResources("data", - // "konsole/*.keytab", - // KStandardDirs::NoDuplicates); + QStringList list = dir.entryList(filters); list = dir.entryList(filters); +// QStringList list = KGlobal::dirs()->findAllResources("data", +// "konsole/*.keytab", +// KStandardDirs::NoDuplicates); + // add the name of each translator to the list and associated // the name with a null pointer to indicate that the translator // has not yet been loaded from disk QStringListIterator listIter(list); - while (listIter.hasNext()) { + while (listIter.hasNext()) + { QString translatorPath = listIter.next(); QString name = QFileInfo(translatorPath).baseName(); - - if ( !_translators.contains(name) ) { + + if ( !_translators.contains(name) ) _translators.insert(name,0); - } } + _haveLoadedAll = true; } -const KeyboardTranslator * KeyboardTranslatorManager::findTranslator(const QString & name) +const KeyboardTranslator* KeyboardTranslatorManager::findTranslator(const QString& name) { - if ( name.isEmpty() ) { + if ( name.isEmpty() ) return defaultTranslator(); - } -//here was smth wrong in original Konsole source - findTranslators(); - - if ( _translators.contains(name) && _translators[name] != 0 ) { + if ( _translators.contains(name) && _translators[name] != 0 ) return _translators[name]; - } - KeyboardTranslator * translator = loadTranslator(name); + KeyboardTranslator* translator = loadTranslator(name); - if ( translator != 0 ) { + if ( translator != 0 ) _translators[name] = translator; - } else if ( !name.isEmpty() ) { - qWarning() << "Unable to load translator" << name << "using default"; - _translators[name] = const_cast(defaultTranslator()); - } + else if ( !name.isEmpty() ) + qDebug() << "Unable to load translator" << name; return translator; } -bool KeyboardTranslatorManager::saveTranslator(const KeyboardTranslator * translator) +bool KeyboardTranslatorManager::saveTranslator(const KeyboardTranslator* translator) { - const QString path = ".keytab";// = KGlobal::dirs()->saveLocation("data","konsole/")+translator->name() -// +".keytab"; +qDebug() << "KeyboardTranslatorManager::saveTranslator" << "unimplemented"; +Q_UNUSED(translator); +#if 0 + const QString path = KGlobal::dirs()->saveLocation("data","konsole/")+translator->name() + +".keytab"; - qDebug() << "Saving translator to" << path; + //kDebug() << "Saving translator to" << path; QFile destination(path); - - if (!destination.open(QIODevice::WriteOnly | QIODevice::Text)) { - qWarning() << "Unable to save keyboard translation:" - << destination.errorString(); - + if (!destination.open(QIODevice::WriteOnly | QIODevice::Text)) + { + qDebug() << "Unable to save keyboard translation:" + << destination.errorString(); return false; } { KeyboardTranslatorWriter writer(&destination); writer.writeHeader(translator->description()); - + QListIterator iter(translator->entries()); - while ( iter.hasNext() ) { + while ( iter.hasNext() ) writer.writeEntry(iter.next()); - } } destination.close(); - +#endif return true; } -KeyboardTranslator * KeyboardTranslatorManager::loadTranslator(const QString & name) +KeyboardTranslator* KeyboardTranslatorManager::loadTranslator(const QString& name) { - const QString & path = findTranslatorPath(name); + const QString& path = findTranslatorPath(name); - QFile source(path); - - if (name.isEmpty() || !source.open(QIODevice::ReadOnly | QIODevice::Text)) { + QFile source(path); + if (name.isEmpty() || !source.open(QIODevice::ReadOnly | QIODevice::Text)) return 0; - } return loadTranslator(&source,name); } -const KeyboardTranslator * KeyboardTranslatorManager::defaultTranslator() +const KeyboardTranslator* KeyboardTranslatorManager::defaultTranslator() { - qDebug() << "Loading default translator from text"; - QBuffer textBuffer; - textBuffer.setData(defaultTranslatorText,strlen(defaultTranslatorText)); - - if (!textBuffer.open(QIODevice::ReadOnly)) { - return 0; + // Try to find the default.keytab file if it exists, otherwise + // fall back to the hard-coded one + const KeyboardTranslator* translator = findTranslator("default"); + if (!translator) + { + QBuffer textBuffer; + textBuffer.setData(defaultTranslatorText); + textBuffer.open(QIODevice::ReadOnly); + translator = loadTranslator(&textBuffer,"fallback"); } - - return loadTranslator(&textBuffer,"fallback"); + return translator; } -KeyboardTranslator * KeyboardTranslatorManager::loadTranslator(QIODevice * source,const QString & name) +KeyboardTranslator* KeyboardTranslatorManager::loadTranslator(QIODevice* source,const QString& name) { - KeyboardTranslator * translator = new KeyboardTranslator(name); + KeyboardTranslator* translator = new KeyboardTranslator(name); KeyboardTranslatorReader reader(source); translator->setDescription( reader.description() ); - - while ( reader.hasNextEntry() ) { + while ( reader.hasNextEntry() ) translator->addEntry(reader.nextEntry()); - } source->close(); - if ( !reader.parseError() ) { + if ( !reader.parseError() ) + { return translator; - } else { + } + else + { delete translator; return 0; } } -KeyboardTranslatorWriter::KeyboardTranslatorWriter(QIODevice * destination) - : _destination(destination) +KeyboardTranslatorWriter::KeyboardTranslatorWriter(QIODevice* destination) +: _destination(destination) { Q_ASSERT( destination && destination->isWritable() ); @@ -234,19 +201,17 @@ KeyboardTranslatorWriter::~KeyboardTranslatorWriter() { delete _writer; } -void KeyboardTranslatorWriter::writeHeader( const QString & description ) +void KeyboardTranslatorWriter::writeHeader( const QString& description ) { *_writer << "keyboard \"" << description << '\"' << '\n'; } -void KeyboardTranslatorWriter::writeEntry( const KeyboardTranslator::Entry & entry ) +void KeyboardTranslatorWriter::writeEntry( const KeyboardTranslator::Entry& entry ) { QString result; - - if ( entry.command() != KeyboardTranslator::NoCommand ) { + if ( entry.command() != KeyboardTranslator::NoCommand ) result = entry.resultToString(); - } else { + else result = '\"' + entry.resultToString() + '\"'; - } *_writer << "key " << entry.conditionToString() << " : " << result << '\n'; } @@ -261,7 +226,7 @@ void KeyboardTranslatorWriter::writeEntry( const KeyboardTranslator::Entry & ent // KeySequence begins with the name of the key ( taken from the Qt::Key enum ) // and is followed by the keyboard modifiers and state flags ( with + or - in front // of each modifier or flag to indicate whether it is required ). All keyboard modifiers -// and flags are optional, if a particular modifier or state is not specified it is +// and flags are optional, if a particular modifier or state is not specified it is // assumed not to be a part of the sequence. The key sequence may contain whitespace // // eg: "key Up+Shift : scrollLineUp" @@ -271,27 +236,28 @@ void KeyboardTranslatorWriter::writeEntry( const KeyboardTranslator::Entry & ent // already been removed) // -KeyboardTranslatorReader::KeyboardTranslatorReader( QIODevice * source ) - : _source(source) - , _hasNext(false) +KeyboardTranslatorReader::KeyboardTranslatorReader( QIODevice* source ) + : _source(source) + , _hasNext(false) { - // read input until we find the description - while ( _description.isEmpty() && !source->atEnd() ) { - const QList& tokens = tokenize( QString(source->readLine()) ); - - if ( !tokens.isEmpty() && tokens.first().type == Token::TitleKeyword ) { - _description = (tokens[1].text.toUtf8()); - } - } - - readNext(); + // read input until we find the description + while ( _description.isEmpty() && !source->atEnd() ) + { + QList tokens = tokenize( QString(source->readLine()) ); + if ( !tokens.isEmpty() && tokens.first().type == Token::TitleKeyword ) + _description = tokens[1].text.toUtf8(); + } + // read first entry (if any) + readNext(); } -void KeyboardTranslatorReader::readNext() +void KeyboardTranslatorReader::readNext() { // find next entry - while ( !_source->atEnd() ) { + while ( !_source->atEnd() ) + { const QList& tokens = tokenize( QString(_source->readLine()) ); - if ( !tokens.isEmpty() && tokens.first().type == Token::KeyKeyword ) { + if ( !tokens.isEmpty() && tokens.first().type == Token::KeyKeyword ) + { KeyboardTranslator::States flags = KeyboardTranslator::NoState; KeyboardTranslator::States flagMask = KeyboardTranslator::NoState; Qt::KeyboardModifiers modifiers = Qt::NoModifier; @@ -304,19 +270,21 @@ void KeyboardTranslatorReader::readNext() modifiers, modifierMask, flags, - flagMask); + flagMask); KeyboardTranslator::Command command = KeyboardTranslator::NoCommand; QByteArray text; // get text or command - if ( tokens[2].type == Token::OutputText ) { + if ( tokens[2].type == Token::OutputText ) + { text = tokens[2].text.toLocal8Bit(); - } else if ( tokens[2].type == Token::Command ) { + } + else if ( tokens[2].type == Token::Command ) + { // identify command - if (!parseAsCommand(tokens[2].text,command)) { - qWarning() << "Command" << tokens[2].text << "not understood."; - } + if (!parseAsCommand(tokens[2].text,command)) + qDebug() << "Command" << tokens[2].text << "not understood."; } KeyboardTranslator::Entry newEntry; @@ -334,40 +302,39 @@ void KeyboardTranslatorReader::readNext() return; } - } + } _hasNext = false; } -bool KeyboardTranslatorReader::parseAsCommand(const QString & text,KeyboardTranslator::Command & command) +bool KeyboardTranslatorReader::parseAsCommand(const QString& text,KeyboardTranslator::Command& command) { - if ( text.compare("erase",Qt::CaseInsensitive) == 0 ) { + if ( text.compare("erase",Qt::CaseInsensitive) == 0 ) command = KeyboardTranslator::EraseCommand; - } else if ( text.compare("scrollpageup",Qt::CaseInsensitive) == 0 ) { + else if ( text.compare("scrollpageup",Qt::CaseInsensitive) == 0 ) command = KeyboardTranslator::ScrollPageUpCommand; - } else if ( text.compare("scrollpagedown",Qt::CaseInsensitive) == 0 ) { + else if ( text.compare("scrollpagedown",Qt::CaseInsensitive) == 0 ) command = KeyboardTranslator::ScrollPageDownCommand; - } else if ( text.compare("scrolllineup",Qt::CaseInsensitive) == 0 ) { + else if ( text.compare("scrolllineup",Qt::CaseInsensitive) == 0 ) command = KeyboardTranslator::ScrollLineUpCommand; - } else if ( text.compare("scrolllinedown",Qt::CaseInsensitive) == 0 ) { + else if ( text.compare("scrolllinedown",Qt::CaseInsensitive) == 0 ) command = KeyboardTranslator::ScrollLineDownCommand; - } else if ( text.compare("scrolllock",Qt::CaseInsensitive) == 0 ) { + else if ( text.compare("scrolllock",Qt::CaseInsensitive) == 0 ) command = KeyboardTranslator::ScrollLockCommand; - } else { + else return false; - } return true; } -bool KeyboardTranslatorReader::decodeSequence(const QString & text, - int & keyCode, - Qt::KeyboardModifiers & modifiers, - Qt::KeyboardModifiers & modifierMask, - KeyboardTranslator::States & flags, - KeyboardTranslator::States & flagMask) +bool KeyboardTranslatorReader::decodeSequence(const QString& text, + int& keyCode, + Qt::KeyboardModifiers& modifiers, + Qt::KeyboardModifiers& modifierMask, + KeyboardTranslator::States& flags, + KeyboardTranslator::States& flagMask) { - bool isWanted = true; + bool isWanted = true; bool endOfItem = false; QString buffer; @@ -376,50 +343,56 @@ bool KeyboardTranslatorReader::decodeSequence(const QString & text, KeyboardTranslator::States tempFlags = flags; KeyboardTranslator::States tempFlagMask = flagMask; - for ( int i = 0 ; i < text.count() ; i++ ) { - const QChar & ch = text[i]; + for ( int i = 0 ; i < text.count() ; i++ ) + { + const QChar& ch = text[i]; + bool isFirstLetter = i == 0; bool isLastLetter = ( i == text.count()-1 ); - endOfItem = true; - if ( ch.isLetterOrNumber() ) { + if ( ch.isLetterOrNumber() ) + { endOfItem = false; buffer.append(ch); + } else if ( isFirstLetter ) + { + buffer.append(ch); } - if ( (endOfItem || isLastLetter) && !buffer.isEmpty() ) { + if ( (endOfItem || isLastLetter) && !buffer.isEmpty() ) + { Qt::KeyboardModifier itemModifier = Qt::NoModifier; int itemKeyCode = 0; KeyboardTranslator::State itemFlag = KeyboardTranslator::NoState; - if ( parseAsModifier(buffer,itemModifier) ) { + if ( parseAsModifier(buffer,itemModifier) ) + { tempModifierMask |= itemModifier; - if ( isWanted ) { + if ( isWanted ) tempModifiers |= itemModifier; - } - } else if ( parseAsStateFlag(buffer,itemFlag) ) { + } + else if ( parseAsStateFlag(buffer,itemFlag) ) + { tempFlagMask |= itemFlag; - if ( isWanted ) { + if ( isWanted ) tempFlags |= itemFlag; - } - } else if ( parseAsKeyCode(buffer,itemKeyCode) ) { - keyCode = itemKeyCode; - } else { - qDebug() << "Unable to parse key binding item:" << buffer; } + else if ( parseAsKeyCode(buffer,itemKeyCode) ) + keyCode = itemKeyCode; + else + qDebug() << "Unable to parse key binding item:" << buffer; buffer.clear(); } - // check if this is a wanted / not-wanted flag and update the + // check if this is a wanted / not-wanted flag and update the // state ready for the next item - if ( ch == '+' ) { - isWanted = true; - } else if ( ch == '-' ) { - isWanted = false; - } - } + if ( ch == '+' ) + isWanted = true; + else if ( ch == '-' ) + isWanted = false; + } modifiers = tempModifiers; modifierMask = tempModifierMask; @@ -429,60 +402,61 @@ bool KeyboardTranslatorReader::decodeSequence(const QString & text, return true; } -bool KeyboardTranslatorReader::parseAsModifier(const QString & item , Qt::KeyboardModifier & modifier) +bool KeyboardTranslatorReader::parseAsModifier(const QString& item , Qt::KeyboardModifier& modifier) { - if ( item == "shift" ) { + if ( item == "shift" ) modifier = Qt::ShiftModifier; - } else if ( item == "ctrl" || item == "control" ) { + else if ( item == "ctrl" || item == "control" ) modifier = Qt::ControlModifier; - } else if ( item == "alt" ) { + else if ( item == "alt" ) modifier = Qt::AltModifier; - } else if ( item == "meta" ) { + else if ( item == "meta" ) modifier = Qt::MetaModifier; - } else if ( item == "keypad" ) { + else if ( item == "keypad" ) modifier = Qt::KeypadModifier; - } else { + else return false; - } return true; } -bool KeyboardTranslatorReader::parseAsStateFlag(const QString & item , KeyboardTranslator::State & flag) +bool KeyboardTranslatorReader::parseAsStateFlag(const QString& item , KeyboardTranslator::State& flag) { - if ( item == "appcukeys" ) { + if ( item == "appcukeys" || item == "appcursorkeys" ) flag = KeyboardTranslator::CursorKeysState; - } else if ( item == "ansi" ) { + else if ( item == "ansi" ) flag = KeyboardTranslator::AnsiState; - } else if ( item == "newline" ) { + else if ( item == "newline" ) flag = KeyboardTranslator::NewLineState; - } else if ( item == "appscreen" ) { + else if ( item == "appscreen" ) flag = KeyboardTranslator::AlternateScreenState; - } else if ( item == "anymod" ) { + else if ( item == "anymod" || item == "anymodifier" ) flag = KeyboardTranslator::AnyModifierState; - } else { + else if ( item == "appkeypad" ) + flag = KeyboardTranslator::ApplicationKeypadState; + else return false; - } return true; } -bool KeyboardTranslatorReader::parseAsKeyCode(const QString & item , int & keyCode) +bool KeyboardTranslatorReader::parseAsKeyCode(const QString& item , int& keyCode) { QKeySequence sequence = QKeySequence::fromString(item); - if ( !sequence.isEmpty() ) { + if ( !sequence.isEmpty() ) + { keyCode = sequence[0]; - if ( sequence.count() > 1 ) { + if ( sequence.count() > 1 ) + { qDebug() << "Unhandled key codes in sequence: " << item; } } // additional cases implemented for backwards compatibility with KDE 3 - else if ( item == "prior" ) { + else if ( item == "prior" ) keyCode = Qt::Key_PageUp; - } else if ( item == "next" ) { + else if ( item == "next" ) keyCode = Qt::Key_PageDown; - } else { + else return false; - } return true; } @@ -495,8 +469,8 @@ bool KeyboardTranslatorReader::hasNextEntry() { return _hasNext; } -KeyboardTranslator::Entry KeyboardTranslatorReader::createEntry( const QString & condition , - const QString & result ) +KeyboardTranslator::Entry KeyboardTranslatorReader::createEntry( const QString& condition , + const QString& result ) { QString entryString("keyboard \"temporary\"\nkey "); entryString.append(condition); @@ -506,90 +480,105 @@ KeyboardTranslator::Entry KeyboardTranslatorReader::createEntry( const QString & // otherwise the result will be treated as a string to echo when the key sequence // specified by 'condition' is pressed KeyboardTranslator::Command command; - if (parseAsCommand(result,command)) { + if (parseAsCommand(result,command)) entryString.append(result); - } else { + else entryString.append('\"' + result + '\"'); - } QByteArray array = entryString.toUtf8(); - - KeyboardTranslator::Entry entry; - QBuffer buffer(&array); buffer.open(QIODevice::ReadOnly); KeyboardTranslatorReader reader(&buffer); - if ( reader.hasNextEntry() ) { + KeyboardTranslator::Entry entry; + if ( reader.hasNextEntry() ) entry = reader.nextEntry(); - } return entry; } -KeyboardTranslator::Entry KeyboardTranslatorReader::nextEntry() +KeyboardTranslator::Entry KeyboardTranslatorReader::nextEntry() { Q_ASSERT( _hasNext ); - - KeyboardTranslator::Entry entry = _nextEntry; - readNext(); - return entry; } bool KeyboardTranslatorReader::parseError() { return false; } -QList KeyboardTranslatorReader::tokenize(const QString & line) +QList KeyboardTranslatorReader::tokenize(const QString& line) { - QString text = line.simplified(); + QString text = line; - // comment line: # comment - static QRegExp comment("\\#.*"); + // remove comments + bool inQuotes = false; + int commentPos = -1; + for (int i=text.length()-1;i>=0;i--) + { + QChar ch = text[i]; + if (ch == '\"') + inQuotes = !inQuotes; + else if (ch == '#' && !inQuotes) + commentPos = i; + } + if (commentPos != -1) + text.remove(commentPos,text.length()); + + text = text.simplified(); + // title line: keyboard "title" static QRegExp title("keyboard\\s+\"(.*)\""); // key line: key KeySequence : "output" // key line: key KeySequence : command - static QRegExp key("key\\s+([\\w\\+\\s\\-]+)\\s*:\\s*(\"(.*)\"|\\w+)"); + static QRegExp key("key\\s+([\\w\\+\\s\\-\\*\\.]+)\\s*:\\s*(\"(.*)\"|\\w+)"); QList list; - - if ( text.isEmpty() || comment.exactMatch(text) ) { + if ( text.isEmpty() ) + { return list; } - if ( title.exactMatch(text) ) { + if ( title.exactMatch(text) ) + { Token titleToken = { Token::TitleKeyword , QString() }; Token textToken = { Token::TitleText , title.capturedTexts()[1] }; - + list << titleToken << textToken; - } else if ( key.exactMatch(text) ) { + } + else if ( key.exactMatch(text) ) + { Token keyToken = { Token::KeyKeyword , QString() }; Token sequenceToken = { Token::KeySequence , key.capturedTexts()[1].remove(' ') }; list << keyToken << sequenceToken; - if ( key.capturedTexts()[3].isEmpty() ) { + if ( key.capturedTexts()[3].isEmpty() ) + { // capturedTexts()[2] is a command Token commandToken = { Token::Command , key.capturedTexts()[2] }; - list << commandToken; - } else { + list << commandToken; + } + else + { // capturedTexts()[3] is the output string - Token outputToken = { Token::OutputText , key.capturedTexts()[3] }; - list << outputToken; - } - } else { - qWarning() << "Line in keyboard translator file could not be understood:" << text; + Token outputToken = { Token::OutputText , key.capturedTexts()[3] }; + list << outputToken; + } + } + else + { + qDebug() << "Line in keyboard translator file could not be understood:" << text; } return list; } -QList KeyboardTranslatorManager::allTranslators() +QList KeyboardTranslatorManager::allTranslators() { - if ( !_haveLoadedAll ) { + if ( !_haveLoadedAll ) + { findTranslators(); } @@ -597,16 +586,16 @@ QList KeyboardTranslatorManager::allTranslators() } KeyboardTranslator::Entry::Entry() - : _keyCode(0) - , _modifiers(Qt::NoModifier) - , _modifierMask(Qt::NoModifier) - , _state(NoState) - , _stateMask(NoState) - , _command(NoCommand) +: _keyCode(0) +, _modifiers(Qt::NoModifier) +, _modifierMask(Qt::NoModifier) +, _state(NoState) +, _stateMask(NoState) +, _command(NoCommand) { } -bool KeyboardTranslator::Entry::operator==(const Entry & rhs) const +bool KeyboardTranslator::Entry::operator==(const Entry& rhs) const { return _keyCode == rhs._keyCode && _modifiers == rhs._modifiers && @@ -617,82 +606,64 @@ bool KeyboardTranslator::Entry::operator==(const Entry & rhs) const _text == rhs._text; } -bool KeyboardTranslator::Entry::matches(int keyCode , +bool KeyboardTranslator::Entry::matches(int keyCode , Qt::KeyboardModifiers modifiers, - States state) const + States testState) const { - if ( _keyCode != keyCode ) { + if ( _keyCode != keyCode ) return false; - } - if ( (modifiers & _modifierMask) != (_modifiers & _modifierMask) ) { + if ( (modifiers & _modifierMask) != (_modifiers & _modifierMask) ) return false; - } // if modifiers is non-zero, the 'any modifier' state is implicit - if ( modifiers != 0 ) { - state |= AnyModifierState; - } + if ( modifiers != 0 ) + testState |= AnyModifierState; - if ( (state & _stateMask) != (_state & _stateMask) ) { + if ( (testState & _stateMask) != (_state & _stateMask) ) return false; - } - // special handling for the 'Any Modifier' state, which checks for the presence of + // special handling for the 'Any Modifier' state, which checks for the presence of // any or no modifiers. In this context, the 'keypad' modifier does not count. bool anyModifiersSet = modifiers != 0 && modifiers != Qt::KeypadModifier; - if ( _stateMask & KeyboardTranslator::AnyModifierState ) { - // test fails if any modifier is required but none are set - if ( (_state & KeyboardTranslator::AnyModifierState) && !anyModifiersSet ) { - return false; - } - - // test fails if no modifier is allowed but one or more are set - if ( !(_state & KeyboardTranslator::AnyModifierState) && anyModifiersSet ) { - return false; - } + bool wantAnyModifier = _state & KeyboardTranslator::AnyModifierState; + if ( _stateMask & KeyboardTranslator::AnyModifierState ) + { + if ( wantAnyModifier != anyModifiersSet ) + return false; } - + return true; } QByteArray KeyboardTranslator::Entry::escapedText(bool expandWildCards,Qt::KeyboardModifiers modifiers) const { QByteArray result(text(expandWildCards,modifiers)); - for ( int i = 0 ; i < result.count() ; i++ ) { + for ( int i = 0 ; i < result.count() ; i++ ) + { char ch = result[i]; char replacement = 0; - switch ( ch ) { - case 27 : - replacement = 'E'; - break; - case 8 : - replacement = 'b'; - break; - case 12 : - replacement = 'f'; - break; - case 9 : - replacement = 't'; - break; - case 13 : - replacement = 'r'; - break; - case 10 : - replacement = 'n'; - break; - default: - // any character which is not printable is replaced by an equivalent - // \xhh escape sequence (where 'hh' are the corresponding hex digits) - if ( !QChar(ch).isPrint() ) { - replacement = 'x'; - } + switch ( ch ) + { + case 27 : replacement = 'E'; break; + case 8 : replacement = 'b'; break; + case 12 : replacement = 'f'; break; + case 9 : replacement = 't'; break; + case 13 : replacement = 'r'; break; + case 10 : replacement = 'n'; break; + default: + // any character which is not printable is replaced by an equivalent + // \xhh escape sequence (where 'hh' are the corresponding hex digits) + if ( !QChar(ch).isPrint() ) + replacement = 'x'; } - if ( replacement == 'x' ) { - result.replace(i,1,"\\x"+QByteArray(1,ch).toInt(0, 16)); - } else if ( replacement != 0 ) { + if ( replacement == 'x' ) + { + result.replace(i,1,"\\x"+QByteArray(1,ch).toHex()); + } else if ( replacement != 0 ) + { result.remove(i,1); result.insert(i,'\\'); result.insert(i+1,replacement); @@ -701,136 +672,119 @@ QByteArray KeyboardTranslator::Entry::escapedText(bool expandWildCards,Qt::Keybo return result; } -QByteArray KeyboardTranslator::Entry::unescape(const QByteArray & input) const +QByteArray KeyboardTranslator::Entry::unescape(const QByteArray& input) const { QByteArray result(input); - for ( int i = 0 ; i < result.count()-1 ; i++ ) { + for ( int i = 0 ; i < result.count()-1 ; i++ ) + { QByteRef ch = result[i]; - if ( ch == '\\' ) { - char replacement[2] = {0,0}; - int charsToRemove = 2; - bool escapedChar = true; + if ( ch == '\\' ) + { + char replacement[2] = {0,0}; + int charsToRemove = 2; + bool escapedChar = true; - switch ( result[i+1] ) { - case 'E' : - replacement[0] = 27; - break; - case 'b' : - replacement[0] = 8 ; - break; - case 'f' : - replacement[0] = 12; - break; - case 't' : - replacement[0] = 9 ; - break; - case 'r' : - replacement[0] = 13; - break; - case 'n' : - replacement[0] = 10; - break; - case 'x' : { - // format is \xh or \xhh where 'h' is a hexadecimal - // digit from 0-9 or A-F which should be replaced - // with the corresponding character value - char hexDigits[3] = {0}; + switch ( result[i+1] ) + { + case 'E' : replacement[0] = 27; break; + case 'b' : replacement[0] = 8 ; break; + case 'f' : replacement[0] = 12; break; + case 't' : replacement[0] = 9 ; break; + case 'r' : replacement[0] = 13; break; + case 'n' : replacement[0] = 10; break; + case 'x' : + { + // format is \xh or \xhh where 'h' is a hexadecimal + // digit from 0-9 or A-F which should be replaced + // with the corresponding character value + char hexDigits[3] = {0}; - if ( (i < result.count()-2) && isxdigit(result[i+2]) ) { - hexDigits[0] = result[i+2]; - } - if ( (i < result.count()-3) && isxdigit(result[i+3]) ) { - hexDigits[1] = result[i+3]; - } + if ( (i < result.count()-2) && isxdigit(result[i+2]) ) + hexDigits[0] = result[i+2]; + if ( (i < result.count()-3) && isxdigit(result[i+3]) ) + hexDigits[1] = result[i+3]; - int charValue = 0; - sscanf(hexDigits,"%x",&charValue); + unsigned charValue = 0; + sscanf(hexDigits,"%x",&charValue); - replacement[0] = (char)charValue; + replacement[0] = (char)charValue; + charsToRemove = 2 + strlen(hexDigits); + } + break; + default: + escapedChar = false; + } - charsToRemove = 2 + strlen(hexDigits); - } - break; - default: - escapedChar = false; - } - - if ( escapedChar ) { - result.replace(i,charsToRemove,replacement); - } + if ( escapedChar ) + result.replace(i,charsToRemove,replacement); } } return result; } -void KeyboardTranslator::Entry::insertModifier( QString & item , int modifier ) const +void KeyboardTranslator::Entry::insertModifier( QString& item , int modifier ) const { - if ( !(modifier & _modifierMask) ) { + if ( !(modifier & _modifierMask) ) return; - } - if ( modifier & _modifiers ) { + if ( modifier & _modifiers ) item += '+'; - } else { + else item += '-'; - } - if ( modifier == Qt::ShiftModifier ) { + if ( modifier == Qt::ShiftModifier ) item += "Shift"; - } else if ( modifier == Qt::ControlModifier ) { + else if ( modifier == Qt::ControlModifier ) item += "Ctrl"; - } else if ( modifier == Qt::AltModifier ) { + else if ( modifier == Qt::AltModifier ) item += "Alt"; - } else if ( modifier == Qt::MetaModifier ) { + else if ( modifier == Qt::MetaModifier ) item += "Meta"; - } else if ( modifier == Qt::KeypadModifier ) { + else if ( modifier == Qt::KeypadModifier ) item += "KeyPad"; - } } -void KeyboardTranslator::Entry::insertState( QString & item , int state ) const +void KeyboardTranslator::Entry::insertState( QString& item , int state ) const { - if ( !(state & _stateMask) ) { + if ( !(state & _stateMask) ) return; - } - if ( state & _state ) { + if ( state & _state ) item += '+' ; - } else { + else item += '-' ; - } - if ( state == KeyboardTranslator::AlternateScreenState ) { + if ( state == KeyboardTranslator::AlternateScreenState ) item += "AppScreen"; - } else if ( state == KeyboardTranslator::NewLineState ) { + else if ( state == KeyboardTranslator::NewLineState ) item += "NewLine"; - } else if ( state == KeyboardTranslator::AnsiState ) { + else if ( state == KeyboardTranslator::AnsiState ) item += "Ansi"; - } else if ( state == KeyboardTranslator::CursorKeysState ) { - item += "AppCuKeys"; - } else if ( state == KeyboardTranslator::AnyModifierState ) { - item += "AnyMod"; - } + else if ( state == KeyboardTranslator::CursorKeysState ) + item += "AppCursorKeys"; + else if ( state == KeyboardTranslator::AnyModifierState ) + item += "AnyModifier"; + else if ( state == KeyboardTranslator::ApplicationKeypadState ) + item += "AppKeypad"; } QString KeyboardTranslator::Entry::resultToString(bool expandWildCards,Qt::KeyboardModifiers modifiers) const { - if ( !_text.isEmpty() ) { + if ( !_text.isEmpty() ) return escapedText(expandWildCards,modifiers); - } else if ( _command == EraseCommand ) { + else if ( _command == EraseCommand ) return "Erase"; - } else if ( _command == ScrollPageUpCommand ) { + else if ( _command == ScrollPageUpCommand ) return "ScrollPageUp"; - } else if ( _command == ScrollPageDownCommand ) { + else if ( _command == ScrollPageDownCommand ) return "ScrollPageDown"; - } else if ( _command == ScrollLineUpCommand ) { + else if ( _command == ScrollLineUpCommand ) return "ScrollLineUp"; - } else if ( _command == ScrollLineDownCommand ) { + else if ( _command == ScrollLineDownCommand ) return "ScrollLineDown"; - } else if ( _command == ScrollLockCommand ) { + else if ( _command == ScrollLockCommand ) return "ScrollLock"; - } return QString(); } @@ -838,28 +792,28 @@ QString KeyboardTranslator::Entry::conditionToString() const { QString result = QKeySequence(_keyCode).toString(); - // add modifiers insertModifier( result , Qt::ShiftModifier ); insertModifier( result , Qt::ControlModifier ); insertModifier( result , Qt::AltModifier ); insertModifier( result , Qt::MetaModifier ); + insertModifier( result , Qt::KeypadModifier ); - // add states insertState( result , KeyboardTranslator::AlternateScreenState ); insertState( result , KeyboardTranslator::NewLineState ); insertState( result , KeyboardTranslator::AnsiState ); insertState( result , KeyboardTranslator::CursorKeysState ); insertState( result , KeyboardTranslator::AnyModifierState ); + insertState( result , KeyboardTranslator::ApplicationKeypadState ); return result; } -KeyboardTranslator::KeyboardTranslator(const QString & name) - : _name(name) +KeyboardTranslator::KeyboardTranslator(const QString& name) +: _name(name) { } -void KeyboardTranslator::setDescription(const QString & description) +void KeyboardTranslator::setDescription(const QString& description) { _description = description; } @@ -867,7 +821,7 @@ QString KeyboardTranslator::description() const { return _description; } -void KeyboardTranslator::setName(const QString & name) +void KeyboardTranslator::setName(const QString& name) { _name = name; } @@ -881,66 +835,60 @@ QList KeyboardTranslator::entries() const return _entries.values(); } -void KeyboardTranslator::addEntry(const Entry & entry) +void KeyboardTranslator::addEntry(const Entry& entry) { const int keyCode = entry.keyCode(); - _entries.insertMulti(keyCode,entry); + _entries.insert(keyCode,entry); } -void KeyboardTranslator::replaceEntry(const Entry & existing , const Entry & replacement) +void KeyboardTranslator::replaceEntry(const Entry& existing , const Entry& replacement) { - if ( !existing.isNull() ) { - _entries.remove(existing.keyCode()); - } - _entries.insertMulti(replacement.keyCode(),replacement); + if ( !existing.isNull() ) + _entries.remove(existing.keyCode(),existing); + _entries.insert(replacement.keyCode(),replacement); } -void KeyboardTranslator::removeEntry(const Entry & entry) +void KeyboardTranslator::removeEntry(const Entry& entry) { - _entries.remove(entry.keyCode()); + _entries.remove(entry.keyCode(),entry); } KeyboardTranslator::Entry KeyboardTranslator::findEntry(int keyCode, Qt::KeyboardModifiers modifiers, States state) const { - if ( _entries.contains(keyCode) ) { - QList entriesForKey = _entries.values(keyCode); - - QListIterator iter(entriesForKey); - - while (iter.hasNext()) { - const Entry & next = iter.next(); - if ( next.matches(keyCode,modifiers,state) ) { - return next; - } - } - - return Entry(); // entry not found - } else { - return Entry(); + foreach(const Entry& entry, _entries.values(keyCode)) + { + if ( entry.matches(keyCode,modifiers,state) ) + return entry; } - + return Entry(); // entry not found } -void KeyboardTranslatorManager::addTranslator(KeyboardTranslator * translator) +void KeyboardTranslatorManager::addTranslator(KeyboardTranslator* translator) { _translators.insert(translator->name(),translator); if ( !saveTranslator(translator) ) - qWarning() << "Unable to save translator" << translator->name() - << "to disk."; + qDebug() << "Unable to save translator" << translator->name() + << "to disk."; } -bool KeyboardTranslatorManager::deleteTranslator(const QString & name) +bool KeyboardTranslatorManager::deleteTranslator(const QString& name) { Q_ASSERT( _translators.contains(name) ); // locate and delete QString path = findTranslatorPath(name); - if ( QFile::remove(path) ) { + if ( QFile::remove(path) ) + { _translators.remove(name); - return true; - } else { - qWarning() << "Failed to remove translator - " << path; + return true; + } + else + { + qDebug() << "Failed to remove translator - " << path; return false; } } -K_GLOBAL_STATIC( KeyboardTranslatorManager , theKeyboardTranslatorManager ) -KeyboardTranslatorManager * KeyboardTranslatorManager::instance() +//K_GLOBAL_STATIC( KeyboardTranslatorManager , theKeyboardTranslatorManager ) +KeyboardTranslatorManager* KeyboardTranslatorManager::theKeyboardTranslatorManager = 0; +KeyboardTranslatorManager* KeyboardTranslatorManager::instance() { + if (! theKeyboardTranslatorManager) + theKeyboardTranslatorManager = new KeyboardTranslatorManager(); return theKeyboardTranslatorManager; } diff --git a/lib/KeyboardTranslator.h b/lib/KeyboardTranslator.h index 62db165..8898c2b 100644 --- a/lib/KeyboardTranslator.h +++ b/lib/KeyboardTranslator.h @@ -1,9 +1,7 @@ /* This source file is part of Konsole, a terminal emulator. - Copyright (C) 2007 by Robert Knight - - Rewritten for QT4 by e_k , Copyright (C)2008 + Copyright 2007-2008 by Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -30,90 +28,18 @@ #include #include #include -#include - -typedef void (*CleanUpFunction)(); - -/** - * @internal - * - * Helper class for K_GLOBAL_STATIC to clean up the object on library unload or application - * shutdown. - */ -class CleanUpGlobalStatic { -public: - CleanUpFunction func; - - inline ~CleanUpGlobalStatic() { - func(); - } -}; - - -//these directives are taken from the heart of kdecore - -# define K_GLOBAL_STATIC_STRUCT_NAME(NAME) - -#if QT_VERSION < 0x040400 -# define Q_BASIC_ATOMIC_INITIALIZER Q_ATOMIC_INIT -# define testAndSetOrdered testAndSet -#endif - -#define K_GLOBAL_STATIC(TYPE, NAME) K_GLOBAL_STATIC_WITH_ARGS(TYPE, NAME, ()) - -#define K_GLOBAL_STATIC_WITH_ARGS(TYPE, NAME, ARGS) \ -static QBasicAtomicPointer _k_static_##NAME = Q_BASIC_ATOMIC_INITIALIZER(0); \ -static bool _k_static_##NAME##_destroyed; \ -static struct K_GLOBAL_STATIC_STRUCT_NAME(NAME) \ -{ \ - bool isDestroyed() \ - { \ - return _k_static_##NAME##_destroyed; \ - } \ - inline operator TYPE*() \ - { \ - return operator->(); \ - } \ - inline TYPE *operator->() \ - { \ - if (!_k_static_##NAME) { \ - if (isDestroyed()) { \ - qFatal("Fatal Error: Accessed global static '%s *%s()' after destruction. " \ - "Defined at %s:%d", #TYPE, #NAME, __FILE__, __LINE__); \ - } \ - TYPE *x = new TYPE ARGS; \ - if (!_k_static_##NAME.testAndSetOrdered(0, x) \ - && _k_static_##NAME != x ) { \ - delete x; \ - } else { \ - static CleanUpGlobalStatic cleanUpObject = { destroy }; \ - } \ - } \ - return _k_static_##NAME; \ - } \ - inline TYPE &operator*() \ - { \ - return *operator->(); \ - } \ - static void destroy() \ - { \ - _k_static_##NAME##_destroyed = true; \ - TYPE *x = _k_static_##NAME; \ - _k_static_##NAME = 0; \ - delete x; \ - } \ -} NAME; - - - +// Konsole +//#include "konsole_export.h" +#define KONSOLEPRIVATE_EXPORT class QIODevice; class QTextStream; -namespace Konsole { +namespace Konsole +{ -/** +/** * A convertor which maps between key sequences pressed by the user and the * character strings which should be sent to the terminal and commands * which should be invoked when those character sequences are pressed. @@ -126,9 +52,10 @@ namespace Konsole { * (Shift,Ctrl,Alt,Meta etc.) and state flags which indicate the state * which the terminal must be in for the key sequence to apply. */ -class KeyboardTranslator { +class KeyboardTranslator +{ public: - /** + /** * The meaning of a particular key sequence may depend upon the state which * the terminal emulation is in. Therefore findEntry() may return a different * Entry depending upon the state flags supplied. @@ -136,14 +63,15 @@ public: * This enum describes the states which may be associated with with a particular * entry in the keyboard translation entry. */ - enum State { + enum State + { /** Indicates that no special state is active */ NoState = 0, /** * TODO More documentation */ NewLineState = 1, - /** + /** * Indicates that the terminal is in 'Ansi' mode. * TODO: More documentation */ @@ -154,18 +82,21 @@ public: CursorKeysState = 4, /** * Indicates that the alternate screen ( typically used by interactive programs - * such as screen or vim ) is active + * such as screen or vim ) is active */ AlternateScreenState = 8, - /** Indicates that any of the modifier keys is active. */ - AnyModifierState = 16 + /** Indicates that any of the modifier keys is active. */ + AnyModifierState = 16, + /** Indicates that the numpad is in application mode. */ + ApplicationKeypadState = 32 }; Q_DECLARE_FLAGS(States,State) /** * This enum describes commands which are associated with particular key sequences. */ - enum Command { + enum Command + { /** Indicates that no command is associated with this command sequence */ NoCommand = 0, /** TODO Document me */ @@ -190,16 +121,17 @@ public: * and the character sequence and commands associated with it for a particular * KeyboardTranslator. */ - class Entry { + class Entry + { public: - /** + /** * Constructs a new entry for a keyboard translator. */ Entry(); - /** + /** * Returns true if this entry is null. - * This is true for newly constructed entries which have no properties set. + * This is true for newly constructed entries which have no properties set. */ bool isNull() const; @@ -208,15 +140,15 @@ public: /** Sets the command associated with this entry. */ void setCommand(Command command); - /** - * Returns the character sequence associated with this entry, optionally replacing + /** + * Returns the character sequence associated with this entry, optionally replacing * wildcard '*' characters with numbers to indicate the keyboard modifiers being pressed. * * TODO: The numbers used to replace '*' characters are taken from the Konsole/KDE 3 code. - * Document them. + * Document them. * * @param expandWildCards Specifies whether wild cards (occurrences of the '*' character) in - * the entry should be replaced with a number to indicate the modifier keys being pressed. + * the entry should be replaced with a number to indicate the modifier keys being pressed. * * @param modifiers The keyboard modifiers being pressed. */ @@ -224,9 +156,9 @@ public: Qt::KeyboardModifiers modifiers = Qt::NoModifier) const; /** 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, * with any non-printable characters replaced with escape sequences. * @@ -243,13 +175,13 @@ public: /** Sets the character code associated with this entry */ void setKeyCode(int keyCode); - /** - * Returns a bitwise-OR of the enabled keyboard modifiers associated with this entry. + /** + * Returns a bitwise-OR of the enabled keyboard modifiers associated with this entry. * If a modifier is set in modifierMask() but not in modifiers(), this means that the entry * only matches when that modifier is NOT pressed. * * If a modifier is not set in modifierMask() then the entry matches whether the modifier - * is pressed or not. + * is pressed or not. */ Qt::KeyboardModifiers modifiers() const; @@ -261,13 +193,13 @@ public: /** See modifierMask() and modifiers() */ void setModifierMask( Qt::KeyboardModifiers modifiers ); - /** - * Returns a bitwise-OR of the enabled state flags associated with this entry. - * If flag is set in stateMask() but not in state(), this means that the entry only + /** + * Returns a bitwise-OR of the enabled state flags associated with this entry. + * If flag is set in stateMask() but not in state(), this means that the entry only * matches when the terminal is NOT in that state. * * If a state is not set in stateMask() then the entry matches whether the terminal - * is in that state or not. + * is in that state or not. */ States state() const; @@ -279,13 +211,13 @@ public: /** See stateMask() */ void setStateMask( States mask ); - /** - * Returns the key code and modifiers associated with this entry + /** + * Returns the key code and modifiers associated with this entry * as a QKeySequence */ //QKeySequence keySequence() const; - /** + /** * Returns this entry's conditions ( ie. its key code, modifier and state criteria ) * as a string. */ @@ -301,20 +233,20 @@ public: QString resultToString(bool expandWildCards = false, Qt::KeyboardModifiers modifiers = Qt::NoModifier) const; - /** + /** * Returns true if this entry matches the given key sequence, specified * as a combination of @p keyCode , @p modifiers and @p state. */ - bool matches( int keyCode , - Qt::KeyboardModifiers modifiers , + bool matches( int keyCode , + Qt::KeyboardModifiers modifiers , States flags ) const; - bool operator==(const Entry & rhs) const; - + bool operator==(const Entry& rhs) const; + private: - void insertModifier( QString & item , int modifier ) const; - void insertState( QString & item , int state ) const; - QByteArray unescape(const QByteArray & text) const; + void insertModifier( QString& item , int modifier ) const; + void insertState( QString& item , int state ) const; + QByteArray unescape(const QByteArray& text) const; int _keyCode; Qt::KeyboardModifiers _modifiers; @@ -327,26 +259,26 @@ public: }; /** Constructs a new keyboard translator with the given @p name */ - KeyboardTranslator(const QString & name); - + KeyboardTranslator(const QString& name); + //KeyboardTranslator(const KeyboardTranslator& other); /** Returns the name of this keyboard translator */ QString name() const; /** Sets the name of this keyboard translator */ - void setName(const QString & name); + void setName(const QString& name); /** Returns the descriptive name of this keyboard translator */ QString description() const; /** Sets the descriptive name of this keyboard translator */ - void setDescription(const QString & description); + void setDescription(const QString& description); /** * Looks for an entry in this keyboard translator which matches the given * key code, keyboard modifiers and state flags. - * + * * Returns the matching entry if found or a null Entry otherwise ( ie. * entry.isNull() will return true ) * @@ -354,43 +286,43 @@ public: * @param modifiers A combination of modifiers * @param state Optional flags which specify the current state of the terminal */ - Entry findEntry(int keyCode , - Qt::KeyboardModifiers modifiers , + Entry findEntry(int keyCode , + Qt::KeyboardModifiers modifiers , States state = NoState) const; - /** + /** * Adds an entry to this keyboard translator's table. Entries can be looked up according * to their key sequence using findEntry() */ - void addEntry(const Entry & entry); + void addEntry(const Entry& entry); /** * Replaces an entry in the translator. If the @p existing entry is null, * then this is equivalent to calling addEntry(@p replacement) */ - void replaceEntry(const Entry & existing , const Entry & replacement); + void replaceEntry(const Entry& existing , const Entry& replacement); /** * Removes an entry from the table. */ - void removeEntry(const Entry & entry); + void removeEntry(const Entry& entry); /** Returns a list of all entries in the translator. */ QList entries() const; private: - QHash _entries; // entries in this keyboard translation, - // entries are indexed according to - // their keycode + QMultiHash _entries; // entries in this keyboard translation, + // entries are indexed according to + // their keycode QString _name; QString _description; }; Q_DECLARE_OPERATORS_FOR_FLAGS(KeyboardTranslator::States) Q_DECLARE_OPERATORS_FOR_FLAGS(KeyboardTranslator::Commands) -/** - * Parses the contents of a Keyboard Translator (.keytab) file and +/** + * Parses the contents of a Keyboard Translator (.keytab) file and * returns the entries found in it. * * Usage example: @@ -410,30 +342,31 @@ Q_DECLARE_OPERATORS_FOR_FLAGS(KeyboardTranslator::Commands) * if ( !reader.parseError() ) * { * // parsing succeeded, do something with the translator - * } + * } * else * { * // parsing failed * } * @endcode */ -class KeyboardTranslatorReader { +class KeyboardTranslatorReader +{ public: /** Constructs a new reader which parses the given @p source */ - KeyboardTranslatorReader( QIODevice * source ); + KeyboardTranslatorReader( QIODevice* source ); - /** - * Returns the description text. - * TODO: More documentation + /** + * Returns the description text. + * TODO: More documentation */ QString description() const; /** Returns true if there is another entry in the source stream */ bool hasNextEntry(); /** Returns the next entry found in the source stream */ - KeyboardTranslator::Entry nextEntry(); + KeyboardTranslator::Entry nextEntry(); - /** + /** * Returns true if an error occurred whilst parsing the input or * false if no error occurred. */ @@ -443,13 +376,15 @@ public: * Parses a condition and result string for a translator entry * and produces a keyboard translator entry. * - * The condition and result strings are in the same format as in + * The condition and result strings are in the same format as in */ - static KeyboardTranslator::Entry createEntry( const QString & condition , - const QString & result ); + static KeyboardTranslator::Entry createEntry( const QString& condition , + const QString& result ); private: - struct Token { - enum Type { + struct Token + { + enum Type + { TitleKeyword, TitleText, KeyKeyword, @@ -460,56 +395,58 @@ private: Type type; QString text; }; - QList tokenize(const QString &); + QList tokenize(const QString&); void readNext(); - bool decodeSequence(const QString & , - int & keyCode, - Qt::KeyboardModifiers & modifiers, - Qt::KeyboardModifiers & modifierMask, - KeyboardTranslator::States & state, - KeyboardTranslator::States & stateFlags); + bool decodeSequence(const QString& , + int& keyCode, + Qt::KeyboardModifiers& modifiers, + Qt::KeyboardModifiers& modifierMask, + KeyboardTranslator::States& state, + KeyboardTranslator::States& stateFlags); - static bool parseAsModifier(const QString & item , Qt::KeyboardModifier & modifier); - static bool parseAsStateFlag(const QString & item , KeyboardTranslator::State & state); - static bool parseAsKeyCode(const QString & item , int & keyCode); - static bool parseAsCommand(const QString & text , KeyboardTranslator::Command & command); + static bool parseAsModifier(const QString& item , Qt::KeyboardModifier& modifier); + static bool parseAsStateFlag(const QString& item , KeyboardTranslator::State& state); + static bool parseAsKeyCode(const QString& item , int& keyCode); + static bool parseAsCommand(const QString& text , KeyboardTranslator::Command& command); - QIODevice * _source; + QIODevice* _source; QString _description; KeyboardTranslator::Entry _nextEntry; bool _hasNext; }; /** Writes a keyboard translation to disk. */ -class KeyboardTranslatorWriter { +class KeyboardTranslatorWriter +{ public: - /** + /** * Constructs a new writer which saves data into @p destination. * The caller is responsible for closing the device when writing is complete. */ - KeyboardTranslatorWriter(QIODevice * destination); + KeyboardTranslatorWriter(QIODevice* destination); ~KeyboardTranslatorWriter(); - /** - * Writes the header for the keyboard translator. - * @param description Description of the keyboard translator. + /** + * Writes the header for the keyboard translator. + * @param description Description of the keyboard translator. */ - void writeHeader( const QString & description ); + void writeHeader( const QString& description ); /** Writes a translator entry. */ - void writeEntry( const KeyboardTranslator::Entry & entry ); + void writeEntry( const KeyboardTranslator::Entry& entry ); private: - QIODevice * _destination; - QTextStream * _writer; + QIODevice* _destination; + QTextStream* _writer; }; /** * Manages the keyboard translations available for use by terminal sessions, * see KeyboardTranslator. */ -class KeyboardTranslatorManager { +class KONSOLEPRIVATE_EXPORT KeyboardTranslatorManager +{ public: - /** + /** * Constructs a new KeyboardTranslatorManager and loads the list of * available keyboard translations. * @@ -520,84 +457,74 @@ public: ~KeyboardTranslatorManager(); /** - * Adds a new translator. If a translator with the same name + * Adds a new translator. If a translator with the same name * already exists, it will be replaced by the new translator. * * TODO: More documentation. */ - void addTranslator(KeyboardTranslator * translator); + void addTranslator(KeyboardTranslator* translator); /** * Deletes a translator. Returns true on successful deletion or false otherwise. * * TODO: More documentation */ - bool deleteTranslator(const QString & name); + bool deleteTranslator(const QString& name); /** 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 * with that name exists. * * The first time that a translator with a particular name is requested, - * the on-disk .keyboard file is loaded and parsed. + * the on-disk .keyboard file is loaded and parsed. */ - const KeyboardTranslator * findTranslator(const QString & name); + const KeyboardTranslator* findTranslator(const QString& name); /** * Returns a list of the names of available keyboard translators. * - * The first time this is called, a search for available + * The first time this is called, a search for available * translators is started. */ QList allTranslators(); /** Returns the global KeyboardTranslatorManager instance. */ - static KeyboardTranslatorManager * instance(); + static KeyboardTranslatorManager* instance(); private: - static const char * defaultTranslatorText; - + static const QByteArray defaultTranslatorText; + void findTranslators(); // locate the available translators - KeyboardTranslator * loadTranslator(const QString & name); // loads the translator - // with the given name - KeyboardTranslator * loadTranslator(QIODevice * device,const QString & name); + KeyboardTranslator* loadTranslator(const QString& name); // loads the translator + // with the given name + KeyboardTranslator* loadTranslator(QIODevice* device,const QString& name); - bool saveTranslator(const KeyboardTranslator * translator); - QString findTranslatorPath(const QString & name); - - QHash _translators; // maps translator-name -> KeyboardTranslator - // instance + bool saveTranslator(const KeyboardTranslator* translator); + QString findTranslatorPath(const QString& name); + + QHash _translators; // maps translator-name -> KeyboardTranslator + // instance bool _haveLoadedAll; + + static KeyboardTranslatorManager * theKeyboardTranslatorManager; }; -inline int KeyboardTranslator::Entry::keyCode() const -{ - return _keyCode; -} -inline void KeyboardTranslator::Entry::setKeyCode(int keyCode) -{ - _keyCode = keyCode; -} +inline int KeyboardTranslator::Entry::keyCode() const { return _keyCode; } +inline void KeyboardTranslator::Entry::setKeyCode(int keyCode) { _keyCode = keyCode; } -inline void KeyboardTranslator::Entry::setModifiers( Qt::KeyboardModifiers modifier ) -{ +inline void KeyboardTranslator::Entry::setModifiers( Qt::KeyboardModifiers modifier ) +{ _modifiers = modifier; } -inline Qt::KeyboardModifiers KeyboardTranslator::Entry::modifiers() const -{ - return _modifiers; -} +inline Qt::KeyboardModifiers KeyboardTranslator::Entry::modifiers() const { return _modifiers; } -inline void KeyboardTranslator::Entry::setModifierMask( Qt::KeyboardModifiers mask ) -{ - _modifierMask = mask; -} -inline Qt::KeyboardModifiers KeyboardTranslator::Entry::modifierMask() const -{ - return _modifierMask; +inline void KeyboardTranslator::Entry::setModifierMask( Qt::KeyboardModifiers mask ) +{ + _modifierMask = mask; } +inline Qt::KeyboardModifiers KeyboardTranslator::Entry::modifierMask() const { return _modifierMask; } inline bool KeyboardTranslator::Entry::isNull() const { @@ -605,64 +532,56 @@ inline bool KeyboardTranslator::Entry::isNull() const } inline void KeyboardTranslator::Entry::setCommand( Command command ) -{ - _command = command; -} -inline KeyboardTranslator::Command KeyboardTranslator::Entry::command() const -{ - return _command; +{ + _command = 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); } inline int oneOrZero(int value) { return value ? 1 : 0; } -inline QByteArray KeyboardTranslator::Entry::text(bool expandWildCards,Qt::KeyboardModifiers modifiers) const +inline QByteArray KeyboardTranslator::Entry::text(bool expandWildCards,Qt::KeyboardModifiers modifiers) const { QByteArray expandedText = _text; - - if (expandWildCards) { + + if (expandWildCards) + { int modifierValue = 1; modifierValue += oneOrZero(modifiers & Qt::ShiftModifier); modifierValue += oneOrZero(modifiers & Qt::AltModifier) << 1; modifierValue += oneOrZero(modifiers & Qt::ControlModifier) << 2; - for (int i=0; i<_text.length(); i++) { - if (expandedText[i] == '*') { + for (int i=0;i<_text.length();i++) + { + if (expandedText[i] == '*') expandedText[i] = '0' + modifierValue; - } } } - return expandedText; + return expandedText; } inline void KeyboardTranslator::Entry::setState( States state ) -{ - _state = state; -} -inline KeyboardTranslator::States KeyboardTranslator::Entry::state() const -{ - return _state; +{ + _state = state; } +inline KeyboardTranslator::States KeyboardTranslator::Entry::state() const { return _state; } inline void KeyboardTranslator::Entry::setStateMask( States stateMask ) -{ - _stateMask = stateMask; -} -inline KeyboardTranslator::States KeyboardTranslator::Entry::stateMask() const -{ - return _stateMask; +{ + _stateMask = stateMask; } +inline KeyboardTranslator::States KeyboardTranslator::Entry::stateMask() const { return _stateMask; } } Q_DECLARE_METATYPE(Konsole::KeyboardTranslator::Entry) -Q_DECLARE_METATYPE(const Konsole::KeyboardTranslator *) +Q_DECLARE_METATYPE(const Konsole::KeyboardTranslator*) #endif // KEYBOARDTRANSLATOR_H diff --git a/lib/Pty.cpp b/lib/Pty.cpp index afa2baf..d2328bf 100644 --- a/lib/Pty.cpp +++ b/lib/Pty.cpp @@ -1,8 +1,14 @@ +/* + * This file is a part of QTerminal - http://gitorious.org/qterminal + * + * This file was un-linked from KDE and modified + * by Maxim Bourmistrov + * + */ + /* This file is part of Konsole, an X terminal. - Copyright (C) 1997,1998 by Lars Doelle - - Rewritten for QT4 by e_k , Copyright (C)2008 + Copyright 1997,1998 by Lars Doelle This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -29,96 +35,95 @@ #include #include #include +#include // Qt -#include +#include -// KDE -//#include -//#include -//#include #include "kpty.h" +#include "kptydevice.h" using namespace Konsole; -void Pty::donePty() -{ - emit done(exitStatus()); -} - void Pty::setWindowSize(int lines, int cols) { - _windowColumns = cols; - _windowLines = lines; + _windowColumns = cols; + _windowLines = lines; - if (pty()->masterFd() >= 0) { - pty()->setWinSize(lines, cols); - } + if (pty()->masterFd() >= 0) + pty()->setWinSize(lines, cols); } QSize Pty::windowSize() const { return QSize(_windowColumns,_windowLines); } -void Pty::setXonXoff(bool enable) +void Pty::setFlowControlEnabled(bool enable) { - _xonXoff = enable; + _xonXoff = enable; - if (pty()->masterFd() >= 0) { + if (pty()->masterFd() >= 0) + { + struct ::termios ttmode; + pty()->tcGetAttr(&ttmode); + if (!enable) + ttmode.c_iflag &= ~(IXOFF | IXON); + else + ttmode.c_iflag |= (IXOFF | IXON); + if (!pty()->tcSetAttr(&ttmode)) + qWarning() << "Unable to set terminal attributes."; + } +} +bool Pty::flowControlEnabled() const +{ + if (pty()->masterFd() >= 0) + { struct ::termios ttmode; pty()->tcGetAttr(&ttmode); - if (!enable) { - ttmode.c_iflag &= ~(IXOFF | IXON); - } else { - ttmode.c_iflag |= (IXOFF | IXON); - } - if (!pty()->tcSetAttr(&ttmode)) { - qWarning("Unable to set terminal attributes."); - } - } + return ttmode.c_iflag & IXOFF && + ttmode.c_iflag & IXON; + } + qWarning() << "Unable to get flow control status, terminal not connected."; + return false; } void Pty::setUtf8Mode(bool enable) { #ifdef IUTF8 // XXX not a reasonable place to check it. - _utf8 = enable; + _utf8 = enable; - if (pty()->masterFd() >= 0) { - struct ::termios ttmode; - pty()->tcGetAttr(&ttmode); - if (!enable) { - ttmode.c_iflag &= ~IUTF8; - } else { - ttmode.c_iflag |= IUTF8; - } - if (!pty()->tcSetAttr(&ttmode)) { - qWarning("Unable to set terminal attributes."); - } - } + if (pty()->masterFd() >= 0) + { + struct ::termios ttmode; + pty()->tcGetAttr(&ttmode); + if (!enable) + ttmode.c_iflag &= ~IUTF8; + else + ttmode.c_iflag |= IUTF8; + if (!pty()->tcSetAttr(&ttmode)) + qWarning() << "Unable to set terminal attributes."; + } #endif } void Pty::setErase(char erase) { - _eraseChar = erase; - - if (pty()->masterFd() >= 0) { - struct ::termios ttmode; - - pty()->tcGetAttr(&ttmode); - - ttmode.c_cc[VERASE] = erase; - - if (!pty()->tcSetAttr(&ttmode)) { - qWarning("Unable to set terminal attributes."); - } - } + _eraseChar = erase; + + if (pty()->masterFd() >= 0) + { + struct ::termios ttmode; + pty()->tcGetAttr(&ttmode); + ttmode.c_cc[VERASE] = erase; + if (!pty()->tcSetAttr(&ttmode)) + qWarning() << "Unable to set terminal attributes."; + } } char Pty::erase() const { - if (pty()->masterFd() >= 0) { - qDebug() << "Getting erase char"; + if (pty()->masterFd() >= 0) + { struct ::termios ttyAttributes; pty()->tcGetAttr(&ttyAttributes); return ttyAttributes.c_cc[VERASE]; @@ -127,202 +132,180 @@ char Pty::erase() const return _eraseChar; } -void Pty::addEnvironmentVariables(const QStringList & environment) +void Pty::addEnvironmentVariables(const QStringList& environment) { QListIterator iter(environment); - while (iter.hasNext()) { + while (iter.hasNext()) + { QString pair = iter.next(); // split on the first '=' character int pos = pair.indexOf('='); - - if ( pos >= 0 ) { + + if ( pos >= 0 ) + { QString variable = pair.left(pos); QString value = pair.mid(pos+1); - //kDebug() << "Setting environment pair" << variable << - // " set to " << value; - - setEnvironment(variable,value); + setEnv(variable,value); } } } -int Pty::start(const QString & program, - const QStringList & programArguments, - const QStringList & environment, - ulong winid, +int Pty::start(const QString& program, + const QStringList& programArguments, + const QStringList& environment, + ulong winid, bool addToUtmp -// const QString& dbusService, -// const QString& dbusSession) - ) + //const QString& dbusService, + //const QString& dbusSession + ) { - clearArguments(); + clearProgram(); - setBinaryExecutable(program.toLatin1()); + // For historical reasons, the first argument in programArguments is the + // name of the program to execute, so create a list consisting of all + // but the first argument to pass to setProgram() + Q_ASSERT(programArguments.count() >= 1); + setProgram(program.toLatin1(),programArguments.mid(1)); - addEnvironmentVariables(environment); + addEnvironmentVariables(environment); - QStringListIterator it( programArguments ); - while (it.hasNext()) { - arguments.append( it.next().toUtf8() ); - } + setEnv("WINDOWID", QString::number(winid)); -// if ( !dbusService.isEmpty() ) -// setEnvironment("KONSOLE_DBUS_SERVICE",dbusService); -// if ( !dbusSession.isEmpty() ) -// setEnvironment("KONSOLE_DBUS_SESSION", dbusSession); + // unless the LANGUAGE environment variable has been set explicitly + // set it to a null string + // this fixes the problem where KCatalog sets the LANGUAGE environment + // variable during the application's startup to something which + // differs from LANG,LC_* etc. and causes programs run from + // the terminal to display messages in the wrong language + // + // this can happen if LANG contains a language which KDE + // does not have a translation for + // + // BR:149300 + setEnv("LANGUAGE",QString(),false /* do not overwrite existing value if any */); - setEnvironment("WINDOWID", QString::number(winid)); + setUseUtmp(addToUtmp); - // unless the LANGUAGE environment variable has been set explicitly - // set it to a null string - // this fixes the problem where KCatalog sets the LANGUAGE environment - // variable during the application's startup to something which - // differs from LANG,LC_* etc. and causes programs run from - // the terminal to display mesages in the wrong language - // - // this can happen if LANG contains a language which KDE - // does not have a translation for - // - // BR:149300 - if (!environment.contains("LANGUAGE")) { - setEnvironment("LANGUAGE",QString()); - } - - setUsePty(All, addToUtmp); - - pty()->open(); - - struct ::termios ttmode; - pty()->tcGetAttr(&ttmode); - if (!_xonXoff) { - ttmode.c_iflag &= ~(IXOFF | IXON); - } else { - ttmode.c_iflag |= (IXOFF | IXON); - } + 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; - } + if (!_utf8) + ttmode.c_iflag &= ~IUTF8; + else + ttmode.c_iflag |= IUTF8; #endif - if (_eraseChar != 0) { - ttmode.c_cc[VERASE] = _eraseChar; - } + if (_eraseChar != 0) + ttmode.c_cc[VERASE] = _eraseChar; + + if (!pty()->tcSetAttr(&ttmode)) + qWarning() << "Unable to set terminal attributes."; + + pty()->setWinSize(_windowLines, _windowColumns); - if (!pty()->tcSetAttr(&ttmode)) { - qWarning("Unable to set terminal attributes."); - } + KProcess::start(); - pty()->setWinSize(_windowLines, _windowColumns); - - if ( K3Process::start(NotifyOnExit, (Communication) (Stdin | Stdout)) == false ) { - return -1; - } - - resume(); // Start... - return 0; + if (!waitForStarted()) + return -1; + return 0; } void Pty::setWriteable(bool writeable) { - struct stat sbuf; - stat(pty()->ttyName(), &sbuf); - if (writeable) { - chmod(pty()->ttyName(), sbuf.st_mode | S_IWGRP); - } else { - chmod(pty()->ttyName(), sbuf.st_mode & ~(S_IWGRP|S_IWOTH)); - } + struct stat sbuf; + stat(pty()->ttyName(), &sbuf); + if (writeable) + chmod(pty()->ttyName(), sbuf.st_mode | S_IWGRP); + else + chmod(pty()->ttyName(), sbuf.st_mode & ~(S_IWGRP|S_IWOTH)); } -Pty::Pty() - : _bufferFull(false), - _windowColumns(0), - _windowLines(0), - _eraseChar(0), - _xonXoff(true), - _utf8(true) +Pty::Pty(int masterFd, QObject* parent) + : KPtyProcess(masterFd,parent) { - connect(this, SIGNAL(receivedStdout(K3Process *, char *, int )), - this, SLOT(dataReceived(K3Process *,char *, int))); - connect(this, SIGNAL(processExited(K3Process *)), - this, SLOT(donePty())); - connect(this, SIGNAL(wroteStdin(K3Process *)), - this, SLOT(writeReady())); - _pty = new KPty; + init(); +} +Pty::Pty(QObject* parent) + : KPtyProcess(parent) +{ + init(); +} +void Pty::init() +{ + _windowColumns = 0; + _windowLines = 0; + _eraseChar = 0; + _xonXoff = true; + _utf8 =true; - setUsePty(All, false); // utmp will be overridden later + connect(pty(), SIGNAL(readyRead()) , this , SLOT(dataReceived())); + setPtyChannels(KPtyProcess::AllChannels); } Pty::~Pty() { - delete _pty; } -void Pty::writeReady() +void Pty::sendData(const char* data, int length) { - _pendingSendJobs.erase(_pendingSendJobs.begin()); - _bufferFull = false; - doSendJobs(); + if (!length) + return; + + if (!pty()->write(data,length)) + { + qWarning() << "Pty::doSendJobs - Could not send input data to terminal process."; + return; + } } -void Pty::doSendJobs() +void Pty::dataReceived() { - if (_pendingSendJobs.isEmpty()) { - emit bufferEmpty(); - return; - } - - SendJob & job = _pendingSendJobs.first(); - - - if (!writeStdin( job.data(), job.length() )) { - qWarning("Pty::doSendJobs - Could not send input data to terminal process."); - return; - } - _bufferFull = true; -} - -void Pty::appendSendJob(const char * s, int len) -{ - _pendingSendJobs.append(SendJob(s,len)); -} - -void Pty::sendData(const char * s, int len) -{ - appendSendJob(s,len); - if (!_bufferFull) { - doSendJobs(); - } -} - -void Pty::dataReceived(K3Process *,char * buf, int len) -{ - emit receivedData(buf,len); + QByteArray data = pty()->readAll(); + emit receivedData(data.constData(),data.count()); } void Pty::lockPty(bool lock) { - if (lock) { - suspend(); - } else { - resume(); - } + Q_UNUSED(lock); + +// TODO: Support for locking the Pty + //if (lock) + //suspend(); + //else + //resume(); } int Pty::foregroundProcessGroup() const { int pid = tcgetpgrp(pty()->masterFd()); - if ( pid != -1 ) { + if ( pid != -1 ) + { return pid; - } + } return 0; } -//#include "moc_Pty.cpp" +void Pty::setupChildProcess() +{ + KPtyProcess::setupChildProcess(); + + // reset all signal handlers + // this ensures that terminal applications respond to + // signals generated via key sequences such as Ctrl+C + // (which sends SIGINT) + struct sigaction action; + sigemptyset(&action.sa_mask); + action.sa_handler = SIG_DFL; + action.sa_flags = 0; + for (int signal=1;signal < NSIG; signal++) + sigaction(signal,&action,0L); +} diff --git a/lib/Pty.h b/lib/Pty.h index eb952e9..c16a1d0 100644 --- a/lib/Pty.h +++ b/lib/Pty.h @@ -1,10 +1,16 @@ /* - This file is part of Konsole, KDE's terminal emulator. + * This file is a part of QTerminal - http://gitorious.org/qterminal + * + * This file was un-linked from KDE and modified + * by Maxim Bourmistrov + * + */ - Copyright (C) 2007 by Robert Knight - Copyright (C) 1997,1998 by Lars Doelle - - Rewritten for QT4 by e_k , Copyright (C)2008 +/* + This file is part of Konsole, KDE's terminal emulator. + + Copyright 2007-2008 by Robert Knight + Copyright 1997,1998 by Lars Doelle This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -29,16 +35,16 @@ #include #include #include -#include - -#include "k3process.h" +#include +// KDE +#include "kptyprocess.h" namespace Konsole { /** - * The Pty class is used to start the terminal process, - * send data to it, receive data from it and manipulate + * The Pty class is used to start the terminal process, + * send data to it, receive data from it and manipulate * various properties of the pseudo-teletype interface * used to communicate with the process. * @@ -47,27 +53,35 @@ namespace Konsole { * send data to or receive data from the process. * * To start the terminal process, call the start() method - * with the program name and appropriate arguments. + * with the program name and appropriate arguments. */ -class Pty: public K3Process { - Q_OBJECT +class Pty: public KPtyProcess +{ +Q_OBJECT -public: - - /** + public: + + /** * Constructs a new Pty. - * + * * Connect to the sendData() slot and receivedData() signal to prepare * for sending and receiving data from the terminal process. * - * To start the terminal process, call the run() method with the + * To start the terminal process, call the run() method with the * name of the program to start and appropriate arguments. */ - Pty(); + explicit Pty(QObject* parent = 0); + + /** + * Construct a process using an open pty master. + * See KPtyProcess::KPtyProcess() + */ + explicit Pty(int ptyMasterFd, QObject* parent = 0); + ~Pty(); /** - * Starts the terminal process. + * Starts the terminal process. * * Returns 0 if the process was started successfully or non-zero * otherwise. @@ -80,35 +94,38 @@ public: * @param winid Specifies the value of the WINDOWID environment variable * in the process's environment. * @param addToUtmp Specifies whether a utmp entry should be created for - * the pty used. See K3Process::setUsePty() - * @param dbusService Specifies the value of the KONSOLE_DBUS_SERVICE + * the pty used. See K3Process::setUsePty() + * @param dbusService Specifies the value of the KONSOLE_DBUS_SERVICE * environment variable in the process's environment. * @param dbusSession Specifies the value of the KONSOLE_DBUS_SESSION - * environment variable in the process's environment. + * environment variable in the process's environment. */ - int start( const QString & program, - const QStringList & arguments, - const QStringList & environment, - ulong winid, + int start( const QString& program, + const QStringList& arguments, + const QStringList& environment, + ulong winid, bool addToUtmp -// const QString& dbusService, -// const QString& dbusSession ); /** TODO: Document me */ void setWriteable(bool writeable); - /** - * Enables or disables Xon/Xoff flow control. + /** + * Enables or disables Xon/Xoff flow control. The flow control setting + * may be changed later by a terminal application, so flowControlEnabled() + * may not equal the value of @p on in the previous call to setFlowControlEnabled() */ - void setXonXoff(bool on); + void setFlowControlEnabled(bool on); - /** - * Sets the size of the window (in lines and columns of characters) + /** Queries the terminal state and returns true if Xon/Xoff flow control is enabled. */ + bool flowControlEnabled() const; + + /** + * Sets the size of the window (in lines and columns of characters) * used by this teletype. */ void setWindowSize(int lines, int cols); - + /** Returns the size of the window used by this teletype. See setWindowSize() */ QSize windowSize() const; @@ -127,17 +144,8 @@ public: * 0 will be returned. */ int foregroundProcessGroup() const; - - /** - * Returns whether the buffer used to send data to the - * terminal process is full. - */ - bool bufferFull() const { - return _bufferFull; - } - - -public slots: + + public slots: /** * Put the pty into UTF-8 mode on systems which support it. @@ -145,7 +153,7 @@ public slots: void setUtf8Mode(bool on); /** - * Suspend or resume processing of data from the standard + * Suspend or resume processing of data from the standard * output of the terminal process. * * See K3Process::suspend() and K3Process::resume() @@ -154,24 +162,17 @@ public slots: * otherwise processing is resumed. */ void lockPty(bool lock); - - /** - * Sends data to the process currently controlling the + + /** + * Sends data to the process currently controlling the * teletype ( whose id is returned by foregroundProcessGroup() ) * * @param buffer Pointer to the data to send. * @param length Length of @p buffer. */ - void sendData(const char * buffer, int length); + void sendData(const char* buffer, int length); -signals: - - /** - * Emitted when the terminal process terminates. - * - * @param exitCode The status code which the process exited with. - */ - void done(int exitCode); + signals: /** * Emitted when a new block of data is received from @@ -180,65 +181,27 @@ signals: * @param buffer Pointer to the data received. * @param length Length of @p buffer */ - void receivedData(const char * buffer, int length); + void receivedData(const char* buffer, int length); + + protected: + void setupChildProcess(); - /** - * Emitted when the buffer used to send data to the terminal - * process becomes empty, i.e. all data has been sent. - */ - void bufferEmpty(); + private slots: + // called when data is received from the terminal process + void dataReceived(); + + private: + void init(); - -private slots: - - // called when terminal process exits - void donePty(); - // called when data is received from the terminal process - void dataReceived(K3Process *, char * buffer, int length); - // sends the first enqueued buffer of data to the - // terminal process - void doSendJobs(); - // called when the terminal process is ready to - // receive more data - void writeReady(); - -private: // takes a list of key=value pairs and adds them // to the environment for the process - void addEnvironmentVariables(const QStringList & environment); + void addEnvironmentVariables(const QStringList& environment); - // enqueues a buffer of data to be sent to the - // terminal process - void appendSendJob(const char * buffer, int length); - - // a buffer of data in the queue to be sent to the - // terminal process - class SendJob { - public: - SendJob() {} - SendJob(const char * b, int len) : buffer(len) { - memcpy( buffer.data() , b , len ); - } - - const char * data() const { - return buffer.constData(); - } - int length() const { - return buffer.size(); - } - private: - QVector buffer; - }; - - QList _pendingSendJobs; - bool _bufferFull; - - int _windowColumns; + int _windowColumns; int _windowLines; char _eraseChar; bool _xonXoff; bool _utf8; - KPty * _pty; }; } diff --git a/lib/Screen.cpp b/lib/Screen.cpp index 1e3218c..eb2c187 100644 --- a/lib/Screen.cpp +++ b/lib/Screen.cpp @@ -1,24 +1,24 @@ /* - This file is part of Konsole, an X terminal. - Copyright (C) 1997,1998 by Lars Doelle + This file is part of Konsole, an X terminal. - Rewritten for QT4 by e_k , Copyright (C)2008 + Copyright 2007-2008 by Robert Knight + Copyright 1997,1998 by Lars Doelle - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA - 02110-1301 USA. -*/ + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. + */ // Own #include "Screen.h" @@ -35,6 +35,9 @@ #include #include +// KDE +//#include + // Konsole #include "konsole_wcwidth.h" #include "TerminalCharacterDecoder.h" @@ -47,10 +50,10 @@ using namespace Konsole; //Macro to convert x,y position on screen to position within an image. // -//Originally the image was stored as one large contiguous block of +//Originally the image was stored as one large contiguous block of //memory, so a position within the image could be represented as an //offset from the beginning of the block. For efficiency reasons this -//is no longer the case. +//is no longer the case. //Many internal parts of this class still use this representation for parameters and so on, //notably moveImage() and clearImage(). //This macro converts from an X,Y position into an image offset. @@ -60,35 +63,30 @@ using namespace Konsole; Character Screen::defaultChar = Character(' ', - CharacterColor(COLOR_SPACE_DEFAULT,DEFAULT_FORE_COLOR), - CharacterColor(COLOR_SPACE_DEFAULT,DEFAULT_BACK_COLOR), - DEFAULT_RENDITION); + CharacterColor(COLOR_SPACE_DEFAULT,DEFAULT_FORE_COLOR), + CharacterColor(COLOR_SPACE_DEFAULT,DEFAULT_BACK_COLOR), + DEFAULT_RENDITION); //#define REVERSE_WRAPPED_LINES // for wrapped line debug -Screen::Screen(int l, int c) - : lines(l), - columns(c), - screenLines(new ImageLine[lines+1] ), - _scrolledLines(0), - _droppedLines(0), - hist(new HistoryScrollNone()), - cuX(0), cuY(0), - cu_re(0), - tmargin(0), bmargin(0), - tabstops(0), - sel_begin(0), sel_TL(0), sel_BR(0), - sel_busy(false), - columnmode(false), - ef_fg(CharacterColor()), ef_bg(CharacterColor()), ef_re(0), - sa_cuX(0), sa_cuY(0), - sa_cu_re(0), - lastPos(-1) + Screen::Screen(int l, int c) +: lines(l), + columns(c), + screenLines(new ImageLine[lines+1] ), + _scrolledLines(0), + _droppedLines(0), + history(new HistoryScrollNone()), + cuX(0), cuY(0), + currentRendition(0), + _topMargin(0), _bottomMargin(0), + selBegin(0), selTopLeft(0), selBottomRight(0), + blockSelectionMode(false), + effectiveForeground(CharacterColor()), effectiveBackground(CharacterColor()), effectiveRendition(0), + lastPos(-1) { lineProperties.resize(lines+1); - for (int i=0; i bmargin ? lines-1 : bmargin; + if (n == 0) n = 1; // Default + int stop = cuY > _bottomMargin ? lines-1 : _bottomMargin; cuX = qMin(columns-1,cuX); // nowrap! cuY = qMin(stop,cuY+n); } -/*! - Move the cursor left. - - The cursor will not move beyond the first column. -*/ - void Screen::cursorLeft(int n) -//=CUB + //=CUB { - if (n == 0) { - n = 1; // Default - } + if (n == 0) n = 1; // Default cuX = qMin(columns-1,cuX); // nowrap! cuX = qMax(0,cuX-n); } -/*! - Move the cursor left. - - The cursor will not move beyond the rightmost column. -*/ - void Screen::cursorRight(int n) -//=CUF + //=CUF { - if (n == 0) { - n = 1; // Default - } + if (n == 0) n = 1; // Default cuX = qMin(columns-1,cuX+n); } void Screen::setMargins(int top, int bot) -//=STBM + //=STBM { - if (top == 0) { - top = 1; // Default - } - if (bot == 0) { - bot = lines; // Default - } + if (top == 0) top = 1; // Default + if (bot == 0) bot = lines; // Default top = top - 1; // Adjust to internal lineno bot = bot - 1; // Adjust to internal lineno - if ( !( 0 <= top && top < bot && bot < lines ) ) { - qDebug()<<" setRegion("< 0) { + if (cuY == _topMargin) + scrollDown(_topMargin,1); + else if (cuY > 0) cuY -= 1; - } } -/*! - Move the cursor to the begin of the next line. - - If cursor is on bottom margin, the region between the - actual top and bottom margin is scrolled up. -*/ - -void Screen::NextLine() -//=NEL +void Screen::nextLine() + //=NEL { - Return(); - index(); + toStartOfLine(); index(); } void Screen::eraseChars(int n) { - if (n == 0) { - n = 1; // Default - } + if (n == 0) n = 1; // Default int p = qMax(0,qMin(cuX+n-1,columns-1)); clearImage(loc(cuX,cuY),loc(p,cuY),' '); } @@ -267,182 +198,127 @@ void Screen::deleteChars(int n) Q_ASSERT( n >= 0 ); // always delete at least one char - if (n == 0) { - n = 1; - } + if (n == 0) + n = 1; // if cursor is beyond the end of the line there is nothing to do - if ( cuX >= screenLines[cuY].count() ) { + if ( cuX >= screenLines[cuY].count() ) return; - } - if ( cuX+n >= screenLines[cuY].count() ) { - n = screenLines[cuY].count() - 1 - cuX; - } + if ( cuX+n > screenLines[cuY].count() ) + n = screenLines[cuY].count() - cuX; Q_ASSERT( n >= 0 ); - Q_ASSERT( cuX+n < screenLines[cuY].count() ); + Q_ASSERT( cuX+n <= screenLines[cuY].count() ); screenLines[cuY].remove(cuX,n); } void Screen::insertChars(int n) { - if (n == 0) { - n = 1; // Default - } + if (n == 0) n = 1; // Default - if ( screenLines[cuY].size() < cuX ) { + if ( screenLines[cuY].size() < cuX ) screenLines[cuY].resize(cuX); - } screenLines[cuY].insert(cuX,n,' '); - if ( screenLines[cuY].count() > columns ) { + if ( screenLines[cuY].count() > columns ) screenLines[cuY].resize(columns); - } } void Screen::deleteLines(int n) { - if (n == 0) { - n = 1; // Default - } + if (n == 0) n = 1; // Default scrollUp(cuY,n); } -/*! insert `n' lines at the cursor position. - - The cursor is not moved by the operation. -*/ - void Screen::insertLines(int n) { - if (n == 0) { - n = 1; // Default - } + if (n == 0) n = 1; // Default scrollDown(cuY,n); } -// Mode Operations ----------------------------------------------------------- - -/*! Set a specific mode. */ - void Screen::setMode(int m) { - currParm.mode[m] = true; - switch (m) { - case MODE_Origin : - cuX = 0; - cuY = tmargin; - break; //FIXME: home + currentModes[m] = true; + switch(m) + { + case MODE_Origin : cuX = 0; cuY = _topMargin; break; //FIXME: home } } -/*! Reset a specific mode. */ - void Screen::resetMode(int m) { - currParm.mode[m] = false; - switch (m) { - case MODE_Origin : - cuX = 0; - cuY = 0; - break; //FIXME: home + currentModes[m] = false; + switch(m) + { + case MODE_Origin : cuX = 0; cuY = 0; break; //FIXME: home } } -/*! Save a specific mode. */ - void Screen::saveMode(int m) { - saveParm.mode[m] = currParm.mode[m]; + savedModes[m] = currentModes[m]; } -/*! Restore a specific mode. */ - void Screen::restoreMode(int m) { - currParm.mode[m] = saveParm.mode[m]; + currentModes[m] = savedModes[m]; } bool Screen::getMode(int m) const { - return currParm.mode[m]; + return currentModes[m]; } void Screen::saveCursor() { - sa_cuX = cuX; - sa_cuY = cuY; - sa_cu_re = cu_re; - sa_cu_fg = cu_fg; - sa_cu_bg = cu_bg; + savedState.cursorColumn = cuX; + savedState.cursorLine = cuY; + savedState.rendition = currentRendition; + savedState.foreground = currentForeground; + savedState.background = currentBackground; } void Screen::restoreCursor() { - cuX = qMin(sa_cuX,columns-1); - cuY = qMin(sa_cuY,lines-1); - cu_re = sa_cu_re; - cu_fg = sa_cu_fg; - cu_bg = sa_cu_bg; - effectiveRendition(); + cuX = qMin(savedState.cursorColumn,columns-1); + cuY = qMin(savedState.cursorLine,lines-1); + currentRendition = savedState.rendition; + currentForeground = savedState.foreground; + currentBackground = savedState.background; + updateEffectiveRendition(); } -/* ------------------------------------------------------------------------- */ -/* */ -/* Screen Operations */ -/* */ -/* ------------------------------------------------------------------------- */ - -/*! Resize the screen image - - The topmost left position is maintained, while lower lines - or right hand side columns might be removed or filled with - spaces to fit the new size. - - The region setting is reset to the whole screen and the - tab positions reinitialized. - - If the new image is narrower than the old image then text on lines - which extends past the end of the new image is preserved so that it becomes - visible again if the screen is later resized to make it larger. -*/ - void Screen::resizeImage(int new_lines, int new_columns) { - if ((new_lines==lines) && (new_columns==columns)) { - return; - } + if ((new_lines==lines) && (new_columns==columns)) return; - if (cuY > new_lines-1) { - // attempt to preserve focus and lines - bmargin = lines-1; //FIXME: margin lost - for (int i = 0; i < cuY-(new_lines-1); i++) { - addHistLine(); - scrollUp(0,1); + if (cuY > new_lines-1) + { // attempt to preserve focus and lines + _bottomMargin = lines-1; //FIXME: margin lost + for (int i = 0; i < cuY-(new_lines-1); i++) + { + addHistLine(); scrollUp(0,1); } } // create new screen lines and copy from old to new - ImageLine * newScreenLines = new ImageLine[new_lines+1]; - for (int i=0; i < qMin(lines-1,new_lines+1) ; i++) { + ImageLine* newScreenLines = new ImageLine[new_lines+1]; + for (int i=0; i < qMin(lines-1,new_lines+1) ;i++) newScreenLines[i]=screenLines[i]; - } - for (int i=lines; (i > 0) && (i 0) && (i 0) && (i 0) && (ir &= ~RE_TRANSPARENT; } -void Screen::effectiveRendition() -// calculate rendition +void Screen::updateEffectiveRendition() { - //copy "current rendition" straight into "effective rendition", which is then later copied directly - //into the image[] array which holds the characters and their appearance properties. - //- The old version below filtered out all attributes other than underline and blink at this stage, - //so that they would not be copied into the image[] array and hence would not be visible by TerminalDisplay - //which actually paints the screen using the information from the image[] array. - //I don't know why it did this, but I'm fairly sure it was the wrong thing to do. The net result - //was that bold text wasn't printed in bold by Konsole. - ef_re = cu_re; - - //OLD VERSION: - //ef_re = cu_re & (RE_UNDERLINE | RE_BLINK); - - if (cu_re & RE_REVERSE) { - ef_fg = cu_bg; - ef_bg = cu_fg; - } else { - ef_fg = cu_fg; - ef_bg = cu_bg; + effectiveRendition = currentRendition; + if (currentRendition & RE_REVERSE) + { + effectiveForeground = currentBackground; + effectiveBackground = currentForeground; + } + else + { + effectiveForeground = currentForeground; + effectiveBackground = currentBackground; } - if (cu_re & RE_BOLD) { - ef_fg.toggleIntensive(); - } + if (currentRendition & RE_BOLD) + effectiveForeground.toggleIntensive(); } -/*! - returns the image. - - Get the size of the image by \sa getLines and \sa getColumns. - - NOTE that the image returned by this function must later be - freed. - -*/ - -void Screen::copyFromHistory(Character * dest, int startLine, int count) const +void Screen::copyFromHistory(Character* dest, int startLine, int count) const { - Q_ASSERT( startLine >= 0 && count > 0 && startLine + count <= hist->getLines() ); + Q_ASSERT( startLine >= 0 && count > 0 && startLine + count <= history->getLines() ); - for (int line = startLine; line < startLine + count; line++) { - const int length = qMin(columns,hist->getLineLen(line)); + for (int line = startLine; line < startLine + count; line++) + { + const int length = qMin(columns,history->getLineLen(line)); const int destLineOffset = (line-startLine)*columns; - hist->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; - } // invert selected text - if (sel_begin !=-1) { - for (int column = 0; column < columns; column++) { - if (isSelected(column,line)) { - reverseRendition(dest[destLineOffset + column]); + if (selBegin !=-1) + { + for (int column = 0; column < columns; column++) + { + if (isSelected(column,line)) + { + reverseRendition(dest[destLineOffset + column]); } } } } } -void Screen::copyFromScreen(Character * dest , int startLine , int count) const +void Screen::copyFromScreen(Character* dest , int startLine , int count) const { Q_ASSERT( startLine >= 0 && count > 0 && startLine + count <= lines ); - for (int line = startLine; line < (startLine+count) ; line++) { + for (int line = startLine; line < (startLine+count) ; line++) + { int srcLineStartIndex = line*columns; int destLineStartIndex = (line-startLine)*columns; - for (int column = 0; column < columns; column++) { - int srcIndex = srcLineStartIndex + column; + for (int column = 0; column < columns; column++) + { + int srcIndex = srcLineStartIndex + column; int destIndex = destLineStartIndex + column; dest[destIndex] = screenLines[srcIndex/columns].value(srcIndex%columns,defaultChar); // invert selected text - if (sel_begin != -1 && isSelected(column,line + hist->getLines())) { - reverseRendition(dest[destIndex]); - } + if (selBegin != -1 && isSelected(column,line + history->getLines())) + reverseRendition(dest[destIndex]); } } } -void Screen::getImage( Character * dest, int size, int startLine, int endLine ) const +void Screen::getImage( Character* dest, int size, int startLine, int endLine ) const { Q_ASSERT( startLine >= 0 ); - Q_ASSERT( endLine >= startLine && endLine < hist->getLines() + lines ); + Q_ASSERT( endLine >= startLine && endLine < history->getLines() + lines ); const int mergedLines = endLine - startLine + 1; - Q_ASSERT( size >= mergedLines * columns ); + Q_ASSERT( size >= mergedLines * columns ); + Q_UNUSED( size ); - const int linesInHistoryBuffer = qBound(0,hist->getLines()-startLine,mergedLines); + const int linesInHistoryBuffer = qBound(0,history->getLines()-startLine,mergedLines); const int linesInScreenBuffer = mergedLines - linesInHistoryBuffer; // copy lines from history buffer - if (linesInHistoryBuffer > 0) { - copyFromHistory(dest,startLine,linesInHistoryBuffer); - } + if (linesInHistoryBuffer > 0) + copyFromHistory(dest,startLine,linesInHistoryBuffer); // copy lines from screen buffer - if (linesInScreenBuffer > 0) { + if (linesInScreenBuffer > 0) copyFromScreen(dest + linesInHistoryBuffer*columns, - startLine + linesInHistoryBuffer - hist->getLines(), - linesInScreenBuffer); - } + startLine + linesInHistoryBuffer - history->getLines(), + linesInScreenBuffer); // invert display when in screen mode - if (getMode(MODE_Screen)) { - for (int i = 0; i < mergedLines*columns; i++) { - reverseRendition(dest[i]); // for reverse display - } + if (getMode(MODE_Screen)) + { + for (int i = 0; i < mergedLines*columns; i++) + reverseRendition(dest[i]); // for reverse display } // mark the character at the current cursor position int cursorIndex = loc(cuX, cuY + linesInHistoryBuffer); - if (getMode(MODE_Cursor) && cursorIndex < columns*mergedLines) { + if(getMode(MODE_Cursor) && cursorIndex < columns*mergedLines) dest[cursorIndex].rendition |= RE_CURSOR; - } } QVector Screen::getLineProperties( int startLine , int endLine ) const { - Q_ASSERT( startLine >= 0 ); - Q_ASSERT( endLine >= startLine && endLine < hist->getLines() + lines ); + Q_ASSERT( startLine >= 0 ); + Q_ASSERT( endLine >= startLine && endLine < history->getLines() + lines ); const int mergedLines = endLine-startLine+1; - const int linesInHistory = qBound(0,hist->getLines()-startLine,mergedLines); + const int linesInHistory = qBound(0,history->getLines()-startLine,mergedLines); const int linesInScreen = mergedLines - linesInHistory; QVector result(mergedLines); int index = 0; // copy properties for lines in history - for (int line = startLine; line < startLine + linesInHistory; line++) { + for (int line = startLine; line < startLine + linesInHistory; line++) + { //TODO Support for line properties other than wrapped lines - if (hist->isWrappedLine(line)) { + if (history->isWrappedLine(line)) + { result[index] = (LineProperty)(result[index] | LINE_WRAPPED); } index++; } // copy properties for lines in screen buffer - const int firstScreenLine = startLine + linesInHistory - hist->getLines(); - for (int line = firstScreenLine; line < firstScreenLine+linesInScreen; line++) { + const int firstScreenLine = startLine + linesInHistory - history->getLines(); + for (int line = firstScreenLine; line < firstScreenLine+linesInScreen; line++) + { result[index]=lineProperties[line]; index++; } @@ -662,147 +523,107 @@ QVector Screen::getLineProperties( int startLine , int endLine ) c return result; } -/*! -*/ - void Screen::reset(bool clearScreen) { - setMode(MODE_Wrap ); - saveMode(MODE_Wrap ); // wrap at end of margin - resetMode(MODE_Origin); - saveMode(MODE_Origin); // position refere to [1,1] - resetMode(MODE_Insert); - saveMode(MODE_Insert); // overstroke + setMode(MODE_Wrap ); saveMode(MODE_Wrap ); // wrap at end of margin + resetMode(MODE_Origin); saveMode(MODE_Origin); // position refere to [1,1] + resetMode(MODE_Insert); saveMode(MODE_Insert); // overstroke setMode(MODE_Cursor); // cursor visible resetMode(MODE_Screen); // screen not inverse resetMode(MODE_NewLine); - tmargin=0; - bmargin=lines-1; + _topMargin=0; + _bottomMargin=lines-1; setDefaultRendition(); saveCursor(); - if ( clearScreen ) { + if ( clearScreen ) clear(); - } } -/*! Clear the entire screen and home the cursor. -*/ - void Screen::clear() { clearEntireScreen(); home(); } -void Screen::BackSpace() +void Screen::backspace() { cuX = qMin(columns-1,cuX); // nowrap! cuX = qMax(0,cuX-1); -// if (BS_CLEARS) image[loc(cuX,cuY)].character = ' '; - if (screenLines[cuY].size() < cuX+1) { + if (screenLines[cuY].size() < cuX+1) screenLines[cuY].resize(cuX+1); - } - if (BS_CLEARS) { + if (BS_CLEARS) screenLines[cuY][cuX].character = ' '; - } } -void Screen::Tabulate(int n) +void Screen::tab(int n) { // note that TAB is a format effector (does not write ' '); - if (n == 0) { - n = 1; - } - while ((n > 0) && (cuX < columns-1)) { - cursorRight(1); - while ((cuX < columns-1) && !tabstops[cuX]) { + if (n == 0) n = 1; + while((n > 0) && (cuX < columns-1)) + { + cursorRight(1); + while((cuX < columns-1) && !tabStops[cuX]) cursorRight(1); - } n--; } } -void Screen::backTabulate(int n) +void Screen::backtab(int n) { // note that TAB is a format effector (does not write ' '); - if (n == 0) { - n = 1; - } - while ((n > 0) && (cuX > 0)) { - cursorLeft(1); - while ((cuX > 0) && !tabstops[cuX]) { - cursorLeft(1); - } + if (n == 0) n = 1; + while((n > 0) && (cuX > 0)) + { + cursorLeft(1); while((cuX > 0) && !tabStops[cuX]) cursorLeft(1); n--; } } void Screen::clearTabStops() { - for (int i = 0; i < columns; i++) { - tabstops[i] = false; - } + for (int i = 0; i < columns; i++) tabStops[i] = false; } void Screen::changeTabStop(bool set) { - if (cuX >= columns) { - return; - } - tabstops[cuX] = set; + if (cuX >= columns) return; + tabStops[cuX] = set; } void Screen::initTabStops() { - delete[] tabstops; - tabstops = new bool[columns]; + tabStops.resize(columns); // Arrg! The 1st tabstop has to be one longer than the other. // i.e. the kids start counting from 0 instead of 1. // Other programs might behave correctly. Be aware. - for (int i = 0; i < columns; i++) { - tabstops[i] = (i%8 == 0 && i != 0); - } + for (int i = 0; i < columns; i++) + tabStops[i] = (i%8 == 0 && i != 0); } -/*! - This behaves either as IND (Screen::Index) or as NEL (Screen::NextLine) - depending on the NewLine Mode (LNM). This mode also - affects the key sequence returned for newline ([CR]LF). -*/ - -void Screen::NewLine() +void Screen::newLine() { - if (getMode(MODE_NewLine)) { - Return(); - } + if (getMode(MODE_NewLine)) + toStartOfLine(); index(); } -/*! put `c' literally onto the screen at the current cursor position. - - VT100 uses the convention to produce an automatic newline (am) - with the *first* character that would fall onto the next line (xenl). -*/ - void Screen::checkSelection(int from, int to) { - if (sel_begin == -1) { + if (selBegin == -1) return; - } - int scr_TL = loc(0, hist->getLines()); + int scr_TL = loc(0, history->getLines()); //Clear entire selection if it overlaps region [from, to] - if ( (sel_BR > (from+scr_TL) )&&(sel_TL < (to+scr_TL)) ) { + if ( (selBottomRight >= (from+scr_TL)) && (selTopLeft <= (to+scr_TL)) ) clearSelection(); - } } -void Screen::ShowCharacter(unsigned short c) +void Screen::displayCharacter(unsigned short c) { // Note that VT100 does wrapping BEFORE putting the character. // This has impact on the assumption of valid cursor positions. @@ -810,60 +631,53 @@ void Screen::ShowCharacter(unsigned short c) // putting the cursor one right to the last column of the screen. int w = konsole_wcwidth(c); - - if (w <= 0) { + if (w <= 0) return; - } if (cuX+w > columns) { if (getMode(MODE_Wrap)) { lineProperties[cuY] = (LineProperty)(lineProperties[cuY] | LINE_WRAPPED); - NextLine(); - } else { - cuX = columns-w; + nextLine(); } + else + cuX = columns-w; } // ensure current line vector has enough elements int size = screenLines[cuY].size(); - if (size == 0 && cuY > 0) { - screenLines[cuY].resize( qMax(screenLines[cuY-1].size() , cuX+w) ); - } else { - if (size < cuX+w) { - screenLines[cuY].resize(cuX+w); - } + if (size < cuX+w) + { + screenLines[cuY].resize(cuX+w); } - if (getMode(MODE_Insert)) { - insertChars(w); - } + if (getMode(MODE_Insert)) insertChars(w); lastPos = loc(cuX,cuY); // check if selection is still valid. - checkSelection(cuX,cuY); + checkSelection(lastPos, lastPos); - Character & currentChar = screenLines[cuY][cuX]; + Character& currentChar = screenLines[cuY][cuX]; currentChar.character = c; - currentChar.foregroundColor = ef_fg; - currentChar.backgroundColor = ef_bg; - currentChar.rendition = ef_re; + currentChar.foregroundColor = effectiveForeground; + currentChar.backgroundColor = effectiveBackground; + currentChar.rendition = effectiveRendition; int i = 0; int newCursorX = cuX + w--; - while (w) { + while(w) + { i++; - if ( screenLines[cuY].size() < cuX + i + 1 ) { + if ( screenLines[cuY].size() < cuX + i + 1 ) screenLines[cuY].resize(cuX+i+1); - } - Character & ch = screenLines[cuY][cuX + i]; + Character& ch = screenLines[cuY][cuX + i]; ch.character = 0; - ch.foregroundColor = ef_fg; - ch.backgroundColor = ef_bg; - ch.rendition = ef_re; + ch.foregroundColor = effectiveForeground; + ch.backgroundColor = effectiveBackground; + ch.rendition = effectiveRendition; w--; } @@ -875,12 +689,12 @@ void Screen::compose(const QString& /*compose*/) Q_ASSERT( 0 /*Not implemented yet*/ ); /* if (lastPos == -1) - return; + return; - QChar c(image[lastPos].character); - compose.prepend(c); - //compose.compose(); ### FIXME! - image[lastPos].character = compose[0].unicode();*/ + QChar c(image[lastPos].character); + compose.prepend(c); + //compose.compose(); ### FIXME! + image[lastPos].character = compose[0].unicode();*/ } int Screen::scrolledLines() const @@ -897,29 +711,16 @@ void Screen::resetDroppedLines() } void Screen::resetScrolledLines() { - //kDebug() << "scrolled lines reset"; - _scrolledLines = 0; } -// Region commands ------------------------------------------------------------- - void Screen::scrollUp(int n) { - if (n == 0) { - n = 1; // Default - } - if (tmargin == 0) { - addHistLine(); // hist.history - } - scrollUp(tmargin, n); + if (n == 0) n = 1; // Default + if (_topMargin == 0) addHistLine(); // history.history + scrollUp(_topMargin, n); } -/*! scroll up `n' lines within current region. - The `n' new lines are cleared. - \sa setRegion \sa scrollDown -*/ - QRect Screen::lastScrolledRegion() const { return _lastScrolledRegion; @@ -927,74 +728,54 @@ QRect Screen::lastScrolledRegion() const void Screen::scrollUp(int from, int n) { - if (n <= 0 || from + n > bmargin) { - return; - } + if (n <= 0 || from + n > _bottomMargin) return; _scrolledLines -= n; - _lastScrolledRegion = QRect(0,tmargin,columns-1,(bmargin-tmargin)); + _lastScrolledRegion = QRect(0,_topMargin,columns-1,(_bottomMargin-_topMargin)); - //FIXME: make sure `tmargin', `bmargin', `from', `n' is in bounds. - moveImage(loc(0,from),loc(0,from+n),loc(columns-1,bmargin)); - clearImage(loc(0,bmargin-n+1),loc(columns-1,bmargin),' '); + //FIXME: make sure `topMargin', `bottomMargin', `from', `n' is in bounds. + moveImage(loc(0,from),loc(0,from+n),loc(columns-1,_bottomMargin)); + clearImage(loc(0,_bottomMargin-n+1),loc(columns-1,_bottomMargin),' '); } void Screen::scrollDown(int n) { - if (n == 0) { - n = 1; // Default - } - scrollDown(tmargin, n); + if (n == 0) n = 1; // Default + scrollDown(_topMargin, n); } -/*! scroll down `n' lines within current region. - The `n' new lines are cleared. - \sa setRegion \sa scrollUp -*/ - void Screen::scrollDown(int from, int n) { - - //kDebug() << "Screen::scrollDown( from: " << from << " , n: " << n << ")"; - _scrolledLines += n; -//FIXME: make sure `tmargin', `bmargin', `from', `n' is in bounds. - if (n <= 0) { + //FIXME: make sure `topMargin', `bottomMargin', `from', `n' is in bounds. + if (n <= 0) return; - } - if (from > bmargin) { + if (from > _bottomMargin) return; - } - if (from + n > bmargin) { - n = bmargin - from; - } - moveImage(loc(0,from+n),loc(0,from),loc(columns-1,bmargin-n)); + if (from + n > _bottomMargin) + n = _bottomMargin - from; + moveImage(loc(0,from+n),loc(0,from),loc(columns-1,_bottomMargin-n)); clearImage(loc(0,from),loc(columns-1,from+n-1),' '); } void Screen::setCursorYX(int y, int x) { - setCursorY(y); - setCursorX(x); + setCursorY(y); setCursorX(x); } void Screen::setCursorX(int x) { - if (x == 0) { - x = 1; // Default - } + if (x == 0) x = 1; // Default x -= 1; // Adjust cuX = qMax(0,qMin(columns-1, x)); } void Screen::setCursorY(int y) { - if (y == 0) { - y = 1; // Default - } + if (y == 0) y = 1; // Default y -= 1; // Adjust - cuY = qMax(0,qMin(lines -1, y + (getMode(MODE_Origin) ? tmargin : 0) )); + cuY = qMax(0,qMin(lines -1, y + (getMode(MODE_Origin) ? _topMargin : 0) )); } void Screen::home() @@ -1003,7 +784,7 @@ void Screen::home() cuY = 0; } -void Screen::Return() +void Screen::toStartOfLine() { cuX = 0; } @@ -1018,44 +799,28 @@ int Screen::getCursorY() const return cuY; } -// Erasing --------------------------------------------------------------------- - -/*! \section Erasing - - This group of operations erase parts of the screen contents by filling - it with spaces colored due to the current rendition settings. - - Althought the cursor position is involved in most of these operations, - it is never modified by them. -*/ - -/*! fill screen between (including) `loca' (start) and `loce' (end) with spaces. - - This is an internal helper functions. The parameter types are internal - addresses of within the screen image and make use of the way how the - screen matrix is mapped to the image vector. -*/ - void Screen::clearImage(int loca, int loce, char c) -{ - int scr_TL=loc(0,hist->getLines()); +{ + int scr_TL=loc(0,history->getLines()); //FIXME: check positions //Clear entire selection if it overlaps region to be moved... - if ( (sel_BR > (loca+scr_TL) )&&(sel_TL < (loce+scr_TL)) ) { + if ( (selBottomRight > (loca+scr_TL) )&&(selTopLeft < (loce+scr_TL)) ) + { clearSelection(); } int topLine = loca/columns; int bottomLine = loce/columns; - Character clearCh(c,cu_fg,cu_bg,DEFAULT_RENDITION); + Character clearCh(c,currentForeground,currentBackground,DEFAULT_RENDITION); //if the character being used to clear the area is the same as the //default character, the affected lines can simply be shrunk. bool isDefaultCh = (clearCh == Character()); - for (int y=topLine; y<=bottomLine; y++) { + for (int y=topLine;y<=bottomLine;y++) + { lineProperties[y] = 0; int endCol = ( y == bottomLine) ? loce%columns : columns-1; @@ -1063,103 +828,93 @@ void Screen::clearImage(int loca, int loce, char c) QVector& line = screenLines[y]; - if ( isDefaultCh && endCol == columns-1 ) { + if ( isDefaultCh && endCol == columns-1 ) + { line.resize(startCol); - } else { - if (line.size() < endCol + 1) { + } + else + { + if (line.size() < endCol + 1) line.resize(endCol+1); - } - Character * data = line.data(); - for (int i=startCol; i<=endCol; i++) { + Character* data = line.data(); + for (int i=startCol;i<=endCol;i++) data[i]=clearCh; - } } } } -/*! move image between (including) `sourceBegin' and `sourceEnd' to 'dest'. - - The 'dest', 'sourceBegin' and 'sourceEnd' parameters can be generated using - the loc(column,line) macro. - -NOTE: moveImage() can only move whole lines. - - This is an internal helper functions. The parameter types are internal - addresses of within the screen image and make use of the way how the - screen matrix is mapped to the image vector. -*/ - void Screen::moveImage(int dest, int sourceBegin, int sourceEnd) { - //kDebug() << "moving image from (" << (sourceBegin/columns) - // << "," << (sourceEnd/columns) << ") to " << - // (dest/columns); - Q_ASSERT( sourceBegin <= sourceEnd ); int lines=(sourceEnd-sourceBegin)/columns; //move screen image and line properties: - //the source and destination areas of the image may overlap, - //so it matters that we do the copy in the right order - + //the source and destination areas of the image may overlap, + //so it matters that we do the copy in the right order - //forwards if dest < sourceBegin or backwards otherwise. //(search the web for 'memmove implementation' for details) - if (dest < sourceBegin) { - for (int i=0; i<=lines; i++) { + if (dest < sourceBegin) + { + for (int i=0;i<=lines;i++) + { screenLines[ (dest/columns)+i ] = screenLines[ (sourceBegin/columns)+i ]; lineProperties[(dest/columns)+i]=lineProperties[(sourceBegin/columns)+i]; } - } else { - for (int i=lines; i>=0; i--) { + } + else + { + for (int i=lines;i>=0;i--) + { screenLines[ (dest/columns)+i ] = screenLines[ (sourceBegin/columns)+i ]; lineProperties[(dest/columns)+i]=lineProperties[(sourceBegin/columns)+i]; } } - if (lastPos != -1) { + if (lastPos != -1) + { int diff = dest - sourceBegin; // Scroll by this amount lastPos += diff; - if ((lastPos < 0) || (lastPos >= (lines*columns))) { + if ((lastPos < 0) || (lastPos >= (lines*columns))) lastPos = -1; - } } // Adjust selection to follow scroll. - if (sel_begin != -1) { - bool beginIsTL = (sel_begin == sel_TL); + if (selBegin != -1) + { + bool beginIsTL = (selBegin == selTopLeft); int diff = dest - sourceBegin; // Scroll by this amount - int scr_TL=loc(0,hist->getLines()); + int scr_TL=loc(0,history->getLines()); int srca = sourceBegin+scr_TL; // Translate index from screen to global int srce = sourceEnd+scr_TL; // Translate index from screen to global int desta = srca+diff; int deste = srce+diff; - if ((sel_TL >= srca) && (sel_TL <= srce)) { - sel_TL += diff; - } else if ((sel_TL >= desta) && (sel_TL <= deste)) { - sel_BR = -1; // Clear selection (see below) - } + if ((selTopLeft >= srca) && (selTopLeft <= srce)) + selTopLeft += diff; + else if ((selTopLeft >= desta) && (selTopLeft <= deste)) + selBottomRight = -1; // Clear selection (see below) - if ((sel_BR >= srca) && (sel_BR <= srce)) { - sel_BR += diff; - } else if ((sel_BR >= desta) && (sel_BR <= deste)) { - sel_BR = -1; // Clear selection (see below) - } + if ((selBottomRight >= srca) && (selBottomRight <= srce)) + selBottomRight += diff; + else if ((selBottomRight >= desta) && (selBottomRight <= deste)) + selBottomRight = -1; // Clear selection (see below) - if (sel_BR < 0) { + if (selBottomRight < 0) + { clearSelection(); - } else { - if (sel_TL < 0) { - sel_TL = 0; - } + } + else + { + if (selTopLeft < 0) + selTopLeft = 0; } - if (beginIsTL) { - sel_begin = sel_TL; - } else { - sel_begin = sel_BR; - } + if (beginIsTL) + selBegin = selTopLeft; + else + selBegin = selBottomRight; } } @@ -1176,17 +931,17 @@ void Screen::clearToBeginOfScreen() void Screen::clearEntireScreen() { // Add entire screen to history - for (int i = 0; i < (lines-1); i++) { - addHistLine(); - scrollUp(0,1); + for (int i = 0; i < (lines-1); i++) + { + addHistLine(); scrollUp(0,1); } clearImage(loc(0,0),loc(columns-1,lines-1),' '); } /*! fill screen with 'E' - This is to aid screen alignment -*/ + This is to aid screen alignment + */ void Screen::helpAlign() { @@ -1210,138 +965,137 @@ void Screen::clearEntireLine() void Screen::setRendition(int re) { - cu_re |= re; - effectiveRendition(); + currentRendition |= re; + updateEffectiveRendition(); } void Screen::resetRendition(int re) { - cu_re &= ~re; - effectiveRendition(); + currentRendition &= ~re; + updateEffectiveRendition(); } void Screen::setDefaultRendition() { setForeColor(COLOR_SPACE_DEFAULT,DEFAULT_FORE_COLOR); setBackColor(COLOR_SPACE_DEFAULT,DEFAULT_BACK_COLOR); - cu_re = DEFAULT_RENDITION; - effectiveRendition(); + currentRendition = DEFAULT_RENDITION; + updateEffectiveRendition(); } void Screen::setForeColor(int space, int color) { - cu_fg = CharacterColor(space, color); + currentForeground = CharacterColor(space, color); - if ( cu_fg.isValid() ) { - effectiveRendition(); - } else { + if ( currentForeground.isValid() ) + updateEffectiveRendition(); + else setForeColor(COLOR_SPACE_DEFAULT,DEFAULT_FORE_COLOR); - } } void Screen::setBackColor(int space, int color) { - cu_bg = CharacterColor(space, color); + currentBackground = CharacterColor(space, color); - if ( cu_bg.isValid() ) { - effectiveRendition(); - } else { + if ( currentBackground.isValid() ) + updateEffectiveRendition(); + else setBackColor(COLOR_SPACE_DEFAULT,DEFAULT_BACK_COLOR); +} + +void Screen::clearSelection() +{ + selBottomRight = -1; + selTopLeft = -1; + selBegin = -1; +} + +void Screen::getSelectionStart(int& column , int& line) const +{ + if ( selTopLeft != -1 ) + { + column = selTopLeft % columns; + line = selTopLeft / columns; } -} - -/* ------------------------------------------------------------------------- */ -/* */ -/* Marking & Selection */ -/* */ -/* ------------------------------------------------------------------------- */ - -void Screen::clearSelection() -{ - sel_BR = -1; - sel_TL = -1; - sel_begin = -1; -} - -void Screen::getSelectionStart(int & column , int & line) -{ - if ( sel_TL != -1 ) { - column = sel_TL % columns; - line = sel_TL / columns; - } else { + else + { column = cuX + getHistLines(); line = cuY + getHistLines(); } } -void Screen::getSelectionEnd(int & column , int & line) +void Screen::getSelectionEnd(int& column , int& line) const { - if ( sel_BR != -1 ) { - column = sel_BR % columns; - line = sel_BR / columns; - } else { + if ( selBottomRight != -1 ) + { + column = selBottomRight % columns; + line = selBottomRight / columns; + } + else + { column = cuX + getHistLines(); line = cuY + getHistLines(); - } + } } -void Screen::setSelectionStart(/*const ScreenCursor& viewCursor ,*/ const int x, const int y, const bool mode) +void Screen::setSelectionStart(const int x, const int y, const bool mode) { -// kDebug(1211) << "setSelBeginXY(" << x << "," << y << ")"; - sel_begin = loc(x,y); //+histCursor) ; - + selBegin = loc(x,y); /* FIXME, HACK to correct for x too far to the right... */ - if (x == columns) { - sel_begin--; - } + if (x == columns) selBegin--; - sel_BR = sel_begin; - sel_TL = sel_begin; - columnmode = mode; + selBottomRight = selBegin; + selTopLeft = selBegin; + blockSelectionMode = mode; } void Screen::setSelectionEnd( const int x, const int y) { -// kDebug(1211) << "setSelExtentXY(" << x << "," << y << ")"; - if (sel_begin == -1) { + if (selBegin == -1) return; + + int endPos = loc(x,y); + + if (endPos < selBegin) + { + selTopLeft = endPos; + selBottomRight = selBegin; } - int l = loc(x,y); // + histCursor); - - if (l < sel_begin) { - sel_TL = l; - sel_BR = sel_begin; - } else { + else + { /* FIXME, HACK to correct for x too far to the right... */ - if (x == columns) { - l--; - } + if (x == columns) + endPos--; - sel_TL = sel_begin; - sel_BR = l; + selTopLeft = selBegin; + selBottomRight = endPos; + } + + // Normalize the selection in column mode + if (blockSelectionMode) + { + int topRow = selTopLeft / columns; + int topColumn = selTopLeft % columns; + int bottomRow = selBottomRight / columns; + int bottomColumn = selBottomRight % columns; + + selTopLeft = loc(qMin(topColumn,bottomColumn),topRow); + selBottomRight = loc(qMax(topColumn,bottomColumn),bottomRow); } } bool Screen::isSelected( const int x,const int y) const { - if (columnmode) { - int sel_Left,sel_Right; - if ( sel_TL % columns < sel_BR % columns ) { - sel_Left = sel_TL; - sel_Right = sel_BR; - } else { - sel_Left = sel_BR; - sel_Right = sel_TL; - } - return ( x >= sel_Left % columns ) && ( x <= sel_Right % columns ) && - ( y >= sel_TL / columns ) && ( y <= sel_BR / columns ); - //( y+histCursor >= sel_TL / columns ) && ( y+histCursor <= sel_BR / columns ); - } else { - //int pos = loc(x,y+histCursor); - int pos = loc(x,y); - return ( pos >= sel_TL && pos <= sel_BR ); + bool columnInSelection = true; + if (blockSelectionMode) + { + columnInSelection = x >= (selTopLeft % columns) && + x <= (selBottomRight % columns); } + + int pos = loc(x,y); + return pos >= selTopLeft && pos <= selBottomRight && columnInSelection; } -QString Screen::selectedText(bool preserveLineBreaks) +QString Screen::selectedText(bool preserveLineBreaks) const { QString result; QTextStream stream(&result, QIODevice::ReadWrite); @@ -1356,59 +1110,68 @@ QString Screen::selectedText(bool preserveLineBreaks) bool Screen::isSelectionValid() const { - return ( sel_TL >= 0 && sel_BR >= 0 ); + return selTopLeft >= 0 && selBottomRight >= 0; } -void Screen::writeSelectionToStream(TerminalCharacterDecoder * decoder , - bool preserveLineBreaks) +void Screen::writeSelectionToStream(TerminalCharacterDecoder* decoder , + bool preserveLineBreaks) const { - // do nothing if selection is invalid - if ( !isSelectionValid() ) { + if (!isSelectionValid()) return; - } + writeToStream(decoder,selTopLeft,selBottomRight,preserveLineBreaks); +} - int top = sel_TL / columns; - int left = sel_TL % columns; +void Screen::writeToStream(TerminalCharacterDecoder* decoder, + int startIndex, int endIndex, + bool preserveLineBreaks) const +{ + int top = startIndex / columns; + int left = startIndex % columns; - int bottom = sel_BR / columns; - int right = sel_BR % columns; + int bottom = endIndex / columns; + int right = endIndex % columns; Q_ASSERT( top >= 0 && left >= 0 && bottom >= 0 && right >= 0 ); - //kDebug() << "sel_TL = " << sel_TL; - //kDebug() << "columns = " << columns; - - for (int y=top; y<=bottom; y++) { + for (int y=top;y<=bottom;y++) + { int start = 0; - if ( y == top || columnmode ) { - start = left; - } + if ( y == top || blockSelectionMode ) start = left; int count = -1; - if ( y == bottom || columnmode ) { - count = right - start + 1; - } + if ( y == bottom || blockSelectionMode ) count = right - start + 1; const bool appendNewLine = ( y != bottom ); - copyLineToStream( y, - start, - count, - decoder, - appendNewLine, - preserveLineBreaks ); - } + int copied = copyLineToStream( y, + start, + count, + decoder, + appendNewLine, + preserveLineBreaks ); + + // if the selection goes beyond the end of the last line then + // append a new line character. + // + // this makes it possible to 'select' a trailing new line character after + // the text on a line. + if ( y == bottom && + copied < count ) + { + Character newLineChar('\n'); + decoder->decodeLine(&newLineChar,1,0); + } + } } - -void Screen::copyLineToStream(int line , - int start, - int count, - TerminalCharacterDecoder * decoder, - bool appendNewLine, - bool preserveLineBreaks) +int Screen::copyLineToStream(int line , + int start, + int count, + TerminalCharacterDecoder* decoder, + bool appendNewLine, + bool preserveLineBreaks) const { //buffer to hold characters for decoding - //the buffer is static to avoid initialising every + //the buffer is static to avoid initialising every //element on each call to copyLineToStream //(which is unnecessary since all elements will be overwritten anyway) static const int MAX_CHARS = 1024; @@ -1419,43 +1182,50 @@ void Screen::copyLineToStream(int line , LineProperty currentLineProperties = 0; //determine if the line is in the history buffer or the screen image - if (line < hist->getLines()) { - const int lineLength = hist->getLineLen(line); + if (line < history->getLines()) + { + const int lineLength = history->getLineLen(line); // ensure that start position is before end of line start = qMin(start,qMax(0,lineLength-1)); - //retrieve line from history buffer - if (count == -1) { + // retrieve line from history buffer. It is assumed + // that the history buffer does not store trailing white space + // at the end of the line, so it does not need to be trimmed here + if (count == -1) + { count = lineLength-start; - } else { + } + else + { count = qMin(start+count,lineLength)-start; } // safety checks assert( start >= 0 ); - assert( count >= 0 ); - assert( (start+count) <= hist->getLineLen(line) ); + assert( count >= 0 ); + assert( (start+count) <= history->getLineLen(line) ); - hist->getCells(line,start,count,characterBuffer); + history->getCells(line,start,count,characterBuffer); - if ( hist->isWrappedLine(line) ) { + if ( history->isWrappedLine(line) ) currentLineProperties |= LINE_WRAPPED; - } - } else { - if ( count == -1 ) { + } + else + { + if ( count == -1 ) count = columns - start; - } assert( count >= 0 ); - const int screenLine = line-hist->getLines(); + const int screenLine = line-history->getLines(); - Character * data = screenLines[screenLine].data(); + Character* data = screenLines[screenLine].data(); int length = screenLines[screenLine].count(); //retrieve line from screen image - for (int i=start; i < qMin(start+count,length); i++) { + for (int i=start;i < qMin(start+count,length);i++) + { characterBuffer[i-start] = data[i]; } @@ -1463,61 +1233,29 @@ void Screen::copyLineToStream(int line , count = qBound(0,count,length-start); Q_ASSERT( screenLine < lineProperties.count() ); - currentLineProperties |= lineProperties[screenLine]; + currentLineProperties |= lineProperties[screenLine]; } - //do not decode trailing whitespace characters - for (int i=count-1 ; i >= 0; i--) - if (QChar(characterBuffer[i].character).isSpace()) { - count--; - } else { - break; - } - // add new line character at end const bool omitLineBreak = (currentLineProperties & LINE_WRAPPED) || - !preserveLineBreaks; + !preserveLineBreaks; - if ( !omitLineBreak && appendNewLine && (count+1 < MAX_CHARS) ) { + if ( !omitLineBreak && appendNewLine && (count+1 < MAX_CHARS) ) + { characterBuffer[count] = '\n'; count++; } - //decode line and write to text stream - decoder->decodeLine( (Character *) characterBuffer , - count, currentLineProperties ); + //decode line and write to text stream + decoder->decodeLine( (Character*) characterBuffer , + count, currentLineProperties ); + + return count; } -// Method below has been removed because of its reliance on 'histCursor' -// and I want to restrict the methods which have knowledge of the scroll position -// to just those which deal with selection and supplying final screen images. -// -/*void Screen::writeToStream(QTextStream* stream , TerminalCharacterDecoder* decoder) { - sel_begin = 0; - sel_BR = sel_begin; - sel_TL = sel_begin; - setSelectionEnd(columns-1,lines-1+hist->getLines()-histCursor); - - writeSelectionToStream(stream,decoder); - - clearSelection(); -}*/ - -void Screen::writeToStream(TerminalCharacterDecoder * decoder, int from, int to) +void Screen::writeLinesToStream(TerminalCharacterDecoder* decoder, int fromLine, int toLine) const { - sel_begin = loc(0,from); - sel_TL = sel_begin; - sel_BR = loc(columns-1,to); - writeSelectionToStream(decoder); - clearSelection(); -} - -QString Screen::getHistoryLine(int no) -{ - sel_begin = loc(0,no); - sel_TL = sel_begin; - sel_BR = loc(columns-1,no); - return selectedText(false); + writeToStream(decoder,loc(0,fromLine),loc(columns-1,toLine)); } void Screen::addHistLine() @@ -1525,99 +1263,98 @@ void Screen::addHistLine() // add line to history buffer // we have to take care about scrolling, too... - if (hasScroll()) { - int oldHistLines = hist->getLines(); + if (hasScroll()) + { + int oldHistLines = history->getLines(); - hist->addCellsVector(screenLines[0]); - hist->addLine( lineProperties[0] & LINE_WRAPPED ); + history->addCellsVector(screenLines[0]); + history->addLine( lineProperties[0] & LINE_WRAPPED ); - int newHistLines = hist->getLines(); + int newHistLines = history->getLines(); - bool beginIsTL = (sel_begin == sel_TL); + bool beginIsTL = (selBegin == selTopLeft); // If the history is full, increment the count // of dropped lines - if ( newHistLines == oldHistLines ) { + if ( newHistLines == oldHistLines ) _droppedLines++; - } // Adjust selection for the new point of reference - if (newHistLines > oldHistLines) { - if (sel_begin != -1) { - sel_TL += columns; - sel_BR += columns; + if (newHistLines > oldHistLines) + { + if (selBegin != -1) + { + selTopLeft += columns; + selBottomRight += columns; } } - if (sel_begin != -1) { + if (selBegin != -1) + { // Scroll selection in history up int top_BR = loc(0, 1+newHistLines); - if (sel_TL < top_BR) { - sel_TL -= columns; - } + if (selTopLeft < top_BR) + selTopLeft -= columns; - if (sel_BR < top_BR) { - sel_BR -= columns; - } + if (selBottomRight < top_BR) + selBottomRight -= columns; - if (sel_BR < 0) { + if (selBottomRight < 0) clearSelection(); - } else { - if (sel_TL < 0) { - sel_TL = 0; - } + else + { + if (selTopLeft < 0) + selTopLeft = 0; } - if (beginIsTL) { - sel_begin = sel_TL; - } else { - sel_begin = sel_BR; - } + if (beginIsTL) + selBegin = selTopLeft; + else + selBegin = selBottomRight; } } } -int Screen::getHistLines() +int Screen::getHistLines() const { - return hist->getLines(); + return history->getLines(); } -void Screen::setScroll(const HistoryType & t , bool copyPreviousScroll) +void Screen::setScroll(const HistoryType& t , bool copyPreviousScroll) { clearSelection(); - if ( copyPreviousScroll ) { - hist = t.scroll(hist); - } else { - HistoryScroll * oldScroll = hist; - hist = t.scroll(0); + if ( copyPreviousScroll ) + history = t.scroll(history); + else + { + HistoryScroll* oldScroll = history; + history = t.scroll(0); delete oldScroll; } } -bool Screen::hasScroll() +bool Screen::hasScroll() const { - return hist->hasScroll(); + return history->hasScroll(); } -const HistoryType & Screen::getScroll() +const HistoryType& Screen::getScroll() const { - return hist->getType(); + return history->getType(); } void Screen::setLineProperty(LineProperty property , bool enable) { - if ( enable ) { + if ( enable ) lineProperties[cuY] = (LineProperty)(lineProperties[cuY] | property); - } else { + else lineProperties[cuY] = (LineProperty)(lineProperties[cuY] & ~property); - } } -void Screen::fillWithDefaultChar(Character * dest, int count) +void Screen::fillWithDefaultChar(Character* dest, int count) { - for (int i=0; i - Copyright (C) 1997,1998 by Lars Doelle - - Rewritten for QT4 by e_k , Copyright (C)2008 + Copyright 2007-2008 by Robert Knight + Copyright 1997,1998 by Lars Doelle This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -42,13 +40,8 @@ #define MODE_NewLine 5 #define MODES_SCREEN 6 -namespace Konsole { - -/*! -*/ -struct ScreenParm { - int mode[MODES_SCREEN]; -}; +namespace Konsole +{ class TerminalCharacterDecoder; @@ -59,96 +52,109 @@ class TerminalCharacterDecoder; characters from the program currently running in the terminal. From this stream it creates an image of characters which is ultimately rendered by the display widget ( TerminalDisplay ). Some types of emulation - may have more than one screen image. + may have more than one screen image. getImage() is used to retrieve the currently visible image which is then used by the display widget to draw the output from the - terminal. + terminal. The number of lines of output history which are kept in addition to the current - screen image depends on the history scroll being used to store the output. + screen image depends on the history scroll being used to store the output. The scroll is specified using setScroll() The output history can be retrieved using writeToStream() - The screen image has a selection associated with it, specified using + The screen image has a selection associated with it, specified using setSelectionStart() and setSelectionEnd(). The selected text can be retrieved - using selectedText(). When getImage() is used to retrieve the the visible image, - characters which are part of the selection have their colours inverted. + using selectedText(). When getImage() is used to retrieve the visible image, + characters which are part of the selection have their colours inverted. */ -class Screen { +class Screen +{ public: /** Construct a new screen image of size @p lines by @p columns. */ Screen(int lines, int columns); ~Screen(); - // VT100/2 Operations + // VT100/2 Operations // Cursor Movement - - /** Move the cursor up by @p n lines. */ - void cursorUp (int n); - /** Move the cursor down by @p n lines. */ - void cursorDown (int n); - /** Move the cursor to the left by @p n columns. */ - void cursorLeft (int n); - /** Move the cursor to the right by @p n columns. */ - void cursorRight (int n); + + /** + * Move the cursor up by @p n lines. The cursor will stop at the + * top margin. + */ + void cursorUp(int n); + /** + * Move the cursor down by @p n lines. The cursor will stop at the + * bottom margin. + */ + void cursorDown(int n); + /** + * Move the cursor to the left by @p n columns. + * The cursor will stop at the first column. + */ + void cursorLeft(int n); + /** + * Move the cursor to the right by @p n columns. + * The cursor will stop at the right-most column. + */ + void cursorRight(int n); /** Position the cursor on line @p y. */ - void setCursorY (int y); + void setCursorY(int y); /** Position the cursor at column @p x. */ - void setCursorX (int x); + void setCursorX(int x); /** Position the cursor at line @p y, column @p x. */ - void setCursorYX (int y, int x); + void setCursorYX(int y, int x); /** * Sets the margins for scrolling the screen. * - * @param topLine The top line of the new scrolling margin. - * @param bottomLine The bottom line of the new scrolling margin. + * @param topLine The top line of the new scrolling margin. + * @param bottomLine The bottom line of the new scrolling margin. */ - void setMargins (int topLine , int bottomLine); - /** Returns the top line of the scrolling region. */ + void setMargins(int topLine , int bottomLine); + /** Returns the top line of the scrolling region. */ int topMargin() const; /** Returns the bottom line of the scrolling region. */ int bottomMargin() const; - /** + /** * Resets the scrolling margins back to the top and bottom lines * of the screen. */ void setDefaultMargins(); - - /** - * Moves the cursor down one line, if the MODE_NewLine mode + + /** + * Moves the cursor down one line, if the MODE_NewLine mode * flag is enabled then the cursor is returned to the leftmost * column first. * * Equivalent to NextLine() if the MODE_NewLine flag is set - * or index() otherwise. + * or index() otherwise. */ - void NewLine (); + void newLine(); /** * Moves the cursor down one line and positions it at the beginning - * of the line. + * of the line. Equivalent to calling Return() followed by index() */ - void NextLine (); + void nextLine(); - /** + /** * Move the cursor down one line. If the cursor is on the bottom * line of the scrolling region (as returned by bottomMargin()) the * scrolling region is scrolled up by one line instead. */ - void index (); + void index(); /** * Move the cursor up one line. If the cursor is on the top line * of the scrolling region (as returned by topMargin()) the scrolling * region is scrolled down by one line instead. */ void reverseIndex(); - - /** - * Scroll the scrolling region of the screen up by @p n lines. - * The scrolling region is initially the whole screen, but can be changed + + /** + * Scroll the scrolling region of the screen up by @p n lines. + * The scrolling region is initially the whole screen, but can be changed * using setMargins() - */ + */ void scrollUp(int n); /** * Scroll the scrolling region of the screen down by @p n lines. @@ -156,89 +162,84 @@ public: * using setMargins() */ void scrollDown(int n); - - /** - * Moves the cursor to the beginning of the current line. + /** + * Moves the cursor to the beginning of the current line. * Equivalent to setCursorX(0) */ - void Return (); - /** + void toStartOfLine(); + /** * Moves the cursor one column to the left and erases the character * at the new cursor position. */ - void BackSpace (); - /** - * Moves the cursor @p n tab-stops to the right. - */ - void Tabulate (int n = 1); - /** - * Moves the cursor @p n tab-stops to the left. - */ - void backTabulate(int n); - + void backspace(); + /** Moves the cursor @p n tab-stops to the right. */ + void tab(int n = 1); + /** Moves the cursor @p n tab-stops to the left. */ + void backtab(int n); + // Editing - - /** - * Erase @p n characters beginning from the current cursor position. + + /** + * Erase @p n characters beginning from the current cursor position. * This is equivalent to over-writing @p n characters starting with the current * cursor position with spaces. - * If @p n is 0 then one character is erased. + * If @p n is 0 then one character is erased. */ - void eraseChars (int n); - /** - * Delete @p n characters beginning from the current cursor position. - * If @p n is 0 then one character is deleted. + void eraseChars(int n); + /** + * Delete @p n characters beginning from the current cursor position. + * If @p n is 0 then one character is deleted. */ - void deleteChars (int n); + void deleteChars(int n); /** * Insert @p n blank characters beginning from the current cursor position. - * The position of the cursor is not altered. + * The position of the cursor is not altered. * If @p n is 0 then one character is inserted. */ - void insertChars (int n); - /** + void insertChars(int n); + /** * Removes @p n lines beginning from the current cursor position. * The position of the cursor is not altered. * If @p n is 0 then one line is removed. */ - void deleteLines (int n); + void deleteLines(int n); /** * Inserts @p lines beginning from the current cursor position. * The position of the cursor is not altered. * If @p n is 0 then one line is inserted. */ - void insertLines (int n); + void insertLines(int n); /** Clears all the tab stops. */ void clearTabStops(); - /** Sets or removes a tab stop at the cursor's current column. */ + /** Sets or removes a tab stop at the cursor's current column. */ void changeTabStop(bool set); - + /** Resets (clears) the specified screen @p mode. */ - void resetMode (int mode); + void resetMode(int 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 * using restoreMode() */ - void saveMode (int mode); + void saveMode(int mode); /** Restores the state of a screen @p mode saved by calling saveMode() */ - void restoreMode (int mode); + void restoreMode(int mode); /** Returns whether the specified screen @p mode is enabled or not .*/ - bool getMode (int mode) const; - - /** - * Saves the current position and appearence (text color and style) of the cursor. - * It can be restored by calling restoreCursor() - */ - void saveCursor (); - /** Restores the position and appearence of the cursor. See saveCursor() */ + bool getMode(int mode) const; + + /** + * Saves the current position and appearance (text color and style) of the cursor. + * It can be restored by calling restoreCursor() + */ + void saveCursor(); + /** Restores the position and appearance of the cursor. See saveCursor() */ void restoreCursor(); - - /** Clear the whole screen, moving the current screen contents into the history first. */ + + /** Clear the whole screen, moving the current screen contents into the history first. */ void clearEntireScreen(); - /** - * Clear the area of the screen from the current cursor position to the end of + /** + * Clear the area of the screen from the current cursor position to the end of * the screen. */ void clearToEndOfScreen(); @@ -253,26 +254,26 @@ public: void clearToEndOfLine(); /** Clears from the current cursor position to the beginning of the line. */ void clearToBeginOfLine(); - + /** Fills the entire screen with the letter 'E' */ - void helpAlign (); - - /** - * Enables the given @p rendition flag. Rendition flags control the appearence + void helpAlign(); + + /** + * Enables the given @p rendition flag. Rendition flags control the appearance * of characters on the screen. * * @see Character::rendition - */ - void setRendition (int rendition); + */ + void setRendition(int rendition); /** - * Disables the given @p rendition flag. Rendition flags control the appearence + * Disables the given @p rendition flag. Rendition flags control the appearance * of characters on the screen. * * @see Character::rendition */ void resetRendition(int rendition); - - /** + + /** * Sets the cursor's foreground color. * @param space The color space used by the @p color argument * @param color The new foreground color. The meaning of this depends on @@ -280,7 +281,7 @@ public: * * @see CharacterColor */ - void setForeColor (int space, int color); + void setForeColor(int space, int color); /** * Sets the cursor's background color. * @param space The color space used by the @p color argumnet. @@ -289,23 +290,25 @@ public: * * @see CharacterColor */ - void setBackColor (int space, int color); - /** - * Resets the cursor's color back to the default and sets the + void setBackColor(int space, int color); + /** + * Resets the cursor's color back to the default and sets the * character's rendition flags back to the default settings. */ void setDefaultRendition(); - + /** Returns the column which the cursor is positioned at. */ int getCursorX() const; /** Returns the line which the cursor is positioned on. */ int getCursorY() const; - - /** TODO Document me */ + + /** Clear the entire screen and move the cursor to the home position. + * Equivalent to calling clearEntireScreen() followed by home(). + */ void clear(); - /** + /** * Sets the position of the cursor to the 'home' position at the top-left - * corner of the screen (0,0) + * corner of the screen (0,0) */ void home(); /** @@ -322,40 +325,41 @@ public: *
  • New line mode is disabled. TODO Document me
  • * * - * If @p clearScreen is true then the screen contents are erased entirely, + * If @p clearScreen is true then the screen contents are erased entirely, * otherwise they are unaltered. */ void reset(bool clearScreen = true); - - /** - * Displays a new character at the current cursor position. - * + + /** + * Displays a new character at the current cursor position. + * * If the cursor is currently positioned at the right-edge of the screen and - * line wrapping is enabled then the character is added at the start of a new + * line wrapping is enabled then the character is added at the start of a new * line below the current one. * - * If the MODE_Insert screen mode is currently enabled then the character - * is inserted at the current cursor position, otherwise it will replace the - * character already at the current cursor position. - */ - void ShowCharacter(unsigned short c); - + * If the MODE_Insert screen mode is currently enabled then the character + * is inserted at the current cursor position, otherwise it will replace the + * character already at the current cursor position. + */ + void displayCharacter(unsigned short c); + // Do composition with last shown character FIXME: Not implemented yet for KDE 4 - void compose(const QString & compose); - - /** - * Resizes the image to a new fixed size of @p new_lines by @p new_columns. + void compose(const QString& compose); + + /** + * Resizes the image to a new fixed size of @p new_lines by @p new_columns. * In the case that @p new_columns is smaller than the current number of columns, * existing lines are not truncated. This prevents characters from being lost * if the terminal display is resized smaller and then larger again. * - * (note that in versions of Konsole prior to KDE 4, existing lines were - * truncated when making the screen image smaller) + * The top and bottom margins are reset to the top and bottom of the new + * screen size. Tab stops are also reset and the current selection is + * cleared. */ void resizeImage(int new_lines, int new_columns); - + /** - * Returns the current screen image. + * Returns the current screen image. * The result is an array of Characters of size [getLines()][getColumns()] which * must be freed by the caller after use. * @@ -364,156 +368,155 @@ public: * @param startLine Index of first line to copy * @param endLine Index of last line to copy */ - void getImage( Character * dest , int size , int startLine , int endLine ) const; + void getImage( Character* dest , int size , int startLine , int endLine ) const; - /** + /** * Returns the additional attributes associated with lines in the image. - * The most important attribute is LINE_WRAPPED which specifies that the + * The most important attribute is LINE_WRAPPED which specifies that the * line is wrapped, * other attributes control the size of characters in the line. */ QVector getLineProperties( int startLine , int endLine ) const; - + /** Return the number of lines. */ - int getLines() { - return lines; - } + int getLines() const + { return lines; } /** Return the number of columns. */ - int getColumns() { - return columns; - } + int getColumns() const + { return columns; } /** Return the number of lines in the history buffer. */ - int getHistLines (); - /** - * Sets the type of storage used to keep lines in the history. - * If @p copyPreviousScroll is true then the contents of the previous + int getHistLines() const; + /** + * Sets the type of storage used to keep lines in the history. + * If @p copyPreviousScroll is true then the contents of the previous * history buffer are copied into the new scroll. */ - void setScroll(const HistoryType & , bool copyPreviousScroll = true); + void setScroll(const HistoryType& , bool copyPreviousScroll = true); /** Returns the type of storage used to keep lines in the history. */ - const HistoryType & getScroll(); - /** + const HistoryType& getScroll() const; + /** * Returns true if this screen keeps lines that are scrolled off the screen * in a history buffer. */ - bool hasScroll(); + bool hasScroll() const; - /** + /** * Sets the start of the selection. * * @param column The column index of the first character in the selection. * @param line The line index of the first character in the selection. - * @param columnmode 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 columnmode); - + void setSelectionStart(const int column, const int line, const bool blockSelectionMode); + /** * Sets the end of the current selection. * * @param column The column index of the last character in the selection. - * @param line The line index of the last character in the selection. - */ + * @param line The line index of the last character in the selection. + */ void setSelectionEnd(const int column, const int line); - + /** * Retrieves the start of the selection or the cursor position if there * is no selection. */ - void getSelectionStart(int & column , int & line); - + void getSelectionStart(int& column , int& line) const; + /** * Retrieves the end of the selection or the cursor position if there * is no selection. */ - void getSelectionEnd(int & column , int & line); + void getSelectionEnd(int& column , int& line) const; /** Clears the current selection */ void clearSelection(); - void setBusySelecting(bool busy) { - sel_busy = busy; - } - - /** - * Returns true if the character at (@p column, @p line) is part of the - * current selection. - */ + /** + * Returns true if the character at (@p column, @p line) is part of the + * current selection. + */ bool isSelected(const int column,const int line) const; - /** - * Convenience method. Returns the currently selected text. - * @param preserveLineBreaks Specifies whether new line characters should + /** + * Convenience method. Returns the currently selected text. + * @param preserveLineBreaks Specifies whether new line characters should * be inserted into the returned text at the end of each terminal line. */ - QString selectedText(bool preserveLineBreaks); - + QString selectedText(bool preserveLineBreaks) const; + /** * Copies part of the output to a stream. * - * @param decoder A decoder which coverts terminal characters into text - * @param from The first line in the history to retrieve - * @param to The last line in the history to retrieve + * @param decoder A decoder which converts terminal characters into text + * @param fromLine The first line in the history to retrieve + * @param toLine The last line in the history to retrieve */ - void writeToStream(TerminalCharacterDecoder * decoder, int from, int to); - - /** - * Sets the selection to line @p no in the history and returns - * the text of that line from the history buffer. - */ - QString getHistoryLine(int no); + void writeLinesToStream(TerminalCharacterDecoder* decoder, int fromLine, int toLine) const; /** * Copies the selected characters, set using @see setSelBeginXY and @see setSelExtentXY * into a stream. * - * @param decoder A decoder which converts terminal characters into text. - * PlainTextDecoder is the most commonly used decoder which coverts characters + * @param decoder A decoder which converts terminal characters into text. + * PlainTextDecoder is the most commonly used decoder which converts characters * into plain text with no formatting. - * @param preserveLineBreaks Specifies whether new line characters should - * be inserted into the returned text at the end of each terminal line. + * @param preserveLineBreaks Specifies whether new line characters should + * be inserted into the returned text at the end of each terminal line. */ - void writeSelectionToStream(TerminalCharacterDecoder * decoder , bool - preserveLineBreaks = true); - - /** TODO Document me */ - void checkSelection(int from, int to); + void writeSelectionToStream(TerminalCharacterDecoder* decoder , bool + preserveLineBreaks = true) const; /** - * Sets or clears an attribute of the current line. + * Checks if the text between from and to is inside the current + * selection. If this is the case, the selection is cleared. The + * from and to are coordinates in the current viewable window. + * The loc(x,y) macro can be used to generate these values from a + * column,line pair. * + * @param from The start of the area to check. + * @param to The end of the area to check + */ + void checkSelection(int from, int to); + + /** + * Sets or clears an attribute of the current line. + * * @param property The attribute to set or clear * Possible properties are: - * LINE_WRAPPED: Specifies that the line is wrapped. - * LINE_DOUBLEWIDTH: Specifies that the characters in the current line should be double the normal width. - * LINE_DOUBLEHEIGHT:Specifies that the characters in the current line should be double the normal height. - * Double-height lines are formed of two lines containing the same characters, - * with both having the LINE_DOUBLEHEIGHT attribute. This allows other parts of the - * code to work on the assumption that all lines are the same height. + * LINE_WRAPPED: Specifies that the line is wrapped. + * LINE_DOUBLEWIDTH: Specifies that the characters in the current line + * should be double the normal width. + * LINE_DOUBLEHEIGHT:Specifies that the characters in the current line + * should be double the normal height. + * Double-height lines are formed of two lines containing the same characters, + * with both having the LINE_DOUBLEHEIGHT attribute. + * This allows other parts of the code to work on the + * assumption that all lines are the same height. * * @param enable true to apply the attribute to the current line or false to remove it */ void setLineProperty(LineProperty property , bool enable); - - /** + /** * Returns the number of lines that the image has been scrolled up or down by, * since the last call to resetScrolledLines(). * * a positive return value indicates that the image has been scrolled up, - * a negative return value indicates that the image has been scrolled down. + * a negative return value indicates that the image has been scrolled down. */ int scrolledLines() const; /** * Returns the region of the image which was last scrolled. * - * This is the area of the image from the top margin to the + * This is the area of the image from the top margin to the * bottom margin when the last scroll occurred. */ QRect lastScrolledRegion() const; - /** + /** * Resets the count of the number of lines that the image has been scrolled up or down by, * see scrolledLines() */ @@ -526,7 +529,7 @@ public: * * If the history is not unlimited then it will drop * the oldest lines of output if new lines are added when - * it is full. + * it is full. */ int droppedLines() const; @@ -536,29 +539,32 @@ public: */ void resetDroppedLines(); - /** - * Fills the buffer @p dest with @p count instances of the default (ie. blank) - * Character style. - */ - static void fillWithDefaultChar(Character * dest, int count); + /** + * Fills the buffer @p dest with @p count instances of the default (ie. blank) + * Character style. + */ + static void fillWithDefaultChar(Character* dest, int count); -private: +private: - //copies a line of text from the screen or history into a stream using a - //specified character decoder - //line - the line number to copy, from 0 (the earliest line in the history) up to - // hist->getLines() + lines - 1 + //copies a line of text from the screen or history into a stream using a + //specified character decoder. Returns the number of lines actually copied, + //which may be less than 'count' if (start+count) is more than the number of characters on + //the line + // + //line - the line number to copy, from 0 (the earliest line in the history) up to + // history->getLines() + lines - 1 //start - the first column on the line to copy //count - the number of characters on the line to copy - //decoder - a decoder which coverts 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 - void copyLineToStream(int line, - int start, - int count, - TerminalCharacterDecoder * decoder, + int copyLineToStream(int line, + int start, + int count, + TerminalCharacterDecoder* decoder, bool appendNewLine, - bool preserveLineBreaks); - + bool preserveLineBreaks) const; + //fills a section of the screen image with the character 'c' //the parameters are specified as offsets from the start of the screen image. //the loc(x,y) macro can be used to generate these values from a column,line pair. @@ -567,26 +573,32 @@ private: //move screen image between 'sourceBegin' and 'sourceEnd' to 'dest'. //the parameters are specified as offsets from the start of the screen image. //the loc(x,y) macro can be used to generate these values from a column,line pair. + // + //NOTE: moveImage() can only move whole lines void moveImage(int dest, int sourceBegin, int sourceEnd); - + // scroll up 'i' lines in current region, clearing the bottom 'i' lines void scrollUp(int from, int i); + // scroll down 'i' lines in current region, clearing the top 'i' lines void scrollDown(int from, int i); void addHistLine(); void initTabStops(); - void effectiveRendition(); - void reverseRendition(Character & p) const; + void updateEffectiveRendition(); + void reverseRendition(Character& p) const; bool isSelectionValid() const; - + // copies text from 'startIndex' to 'endIndex' to a stream + // startIndex and endIndex are positions generated using the loc(x,y) macro + void writeToStream(TerminalCharacterDecoder* decoder, int startIndex, + int endIndex, bool preserveLineBreaks = true) const; // copies 'count' lines from the screen buffer into 'dest', // starting from 'startLine', where 0 is the first line in the screen buffer - void copyFromScreen(Character * dest, int startLine, int count) const; + void copyFromScreen(Character* dest, int startLine, int count) const; // copies 'count' lines from the history buffer into 'dest', // starting from 'startLine', where 0 is the first line in the history - void copyFromHistory(Character * dest, int startLine, int count) const; + void copyFromHistory(Character* dest, int startLine, int count) const; // screen image ---------------- @@ -594,69 +606,67 @@ private: int columns; typedef QVector ImageLine; // [0..columns] - ImageLine * screenLines; // [lines] + ImageLine* screenLines; // [lines] int _scrolledLines; QRect _lastScrolledRegion; int _droppedLines; - QVarLengthArray lineProperties; - + QVarLengthArray lineProperties; + // history buffer --------------- - HistoryScroll * hist; - + HistoryScroll* history; + // cursor location int cuX; int cuY; // cursor color and rendition info - CharacterColor cu_fg; // foreground - CharacterColor cu_bg; // background - quint8 cu_re; // rendition + CharacterColor currentForeground; + CharacterColor currentBackground; + quint8 currentRendition; // margins ---------------- - int tmargin; // top margin - int bmargin; // bottom margin + int _topMargin; + int _bottomMargin; // states ---------------- - ScreenParm currParm; + int currentModes[MODES_SCREEN]; + int savedModes[MODES_SCREEN]; // ---------------------------- - bool * tabstops; + QBitArray tabStops; // selection ------------------- - int sel_begin; // The first location selected. - int sel_TL; // TopLeft Location. - int sel_BR; // Bottom Right Location. - bool sel_busy; // Busy making a selection. - bool columnmode; // Column selection mode + int selBegin; // The first location selected. + int selTopLeft; // TopLeft Location. + int selBottomRight; // Bottom Right Location. + bool blockSelectionMode; // Column selection mode // effective colors and rendition ------------ - CharacterColor ef_fg; // These are derived from - CharacterColor ef_bg; // the cu_* variables above - quint8 ef_re; // to speed up operation + CharacterColor effectiveForeground; // These are derived from + CharacterColor effectiveBackground; // the cu_* variables above + quint8 effectiveRendition; // to speed up operation - // - // save cursor, rendition & states ------------ - // - - // cursor location - int sa_cuX; - int sa_cuY; - - // rendition info - quint8 sa_cu_re; - CharacterColor sa_cu_fg; - CharacterColor sa_cu_bg; + class SavedState + { + public: + SavedState() + : cursorColumn(0),cursorLine(0),rendition(0) {} + int cursorColumn; + int cursorLine; + quint8 rendition; + CharacterColor foreground; + CharacterColor background; + }; + SavedState savedState; + // last position where we added a character int lastPos; - // modes - ScreenParm saveParm; - static Character defaultChar; }; diff --git a/lib/ScreenWindow.cpp b/lib/ScreenWindow.cpp index 5c495f3..1d3fadd 100644 --- a/lib/ScreenWindow.cpp +++ b/lib/ScreenWindow.cpp @@ -1,8 +1,6 @@ /* Copyright (C) 2007 by Robert Knight - Rewritten for QT4 by e_k , Copyright (C)2008 - This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or @@ -23,59 +21,59 @@ #include "ScreenWindow.h" // Qt -#include +#include // Konsole #include "Screen.h" using namespace Konsole; -ScreenWindow::ScreenWindow(QObject * parent) - : QObject(parent) - , _windowBuffer(0) - , _windowBufferSize(0) - , _bufferNeedsUpdate(true) - , _windowLines(1) - , _currentLine(0) - , _trackOutput(true) - , _scrollCount(0) +ScreenWindow::ScreenWindow(QObject* parent) + : QObject(parent) + , _windowBuffer(0) + , _windowBufferSize(0) + , _bufferNeedsUpdate(true) + , _windowLines(1) + , _currentLine(0) + , _trackOutput(true) + , _scrollCount(0) { } ScreenWindow::~ScreenWindow() { delete[] _windowBuffer; } -void ScreenWindow::setScreen(Screen * screen) +void ScreenWindow::setScreen(Screen* screen) { Q_ASSERT( screen ); _screen = screen; } -Screen * ScreenWindow::screen() const +Screen* ScreenWindow::screen() const { return _screen; } -Character * ScreenWindow::getImage() +Character* ScreenWindow::getImage() { // reallocate internal buffer if the window size has changed int size = windowLines() * windowColumns(); - if (_windowBuffer == 0 || _windowBufferSize != size) { + if (_windowBuffer == 0 || _windowBufferSize != size) + { delete[] _windowBuffer; _windowBufferSize = size; _windowBuffer = new Character[size]; _bufferNeedsUpdate = true; } - if (!_bufferNeedsUpdate) { + if (!_bufferNeedsUpdate) return _windowBuffer; - } - + _screen->getImage(_windowBuffer,size, currentLine(),endWindowLine()); - // this window may look beyond the end of the screen, in which + // this window may look beyond the end of the screen, in which // case there will be an unused area which needs to be filled // with blank characters fillUnusedArea(); @@ -92,10 +90,10 @@ void ScreenWindow::fillUnusedArea() int unusedLines = windowEndLine - screenEndLine; int charsToFill = unusedLines * windowColumns(); - Screen::fillWithDefaultChar(_windowBuffer + _windowBufferSize - charsToFill,charsToFill); + Screen::fillWithDefaultChar(_windowBuffer + _windowBufferSize - charsToFill,charsToFill); } -// return the index of the line at the end of this window, or if this window +// return the index of the line at the end of this window, or if this window // goes beyond the end of the screen, the index of the line at the end // of the screen. // @@ -110,10 +108,9 @@ int ScreenWindow::endWindowLine() const QVector ScreenWindow::getLineProperties() { QVector result = _screen->getLineProperties(currentLine(),endWindowLine()); - - if (result.count() != windowLines()) { + + if (result.count() != windowLines()) result.resize(windowLines()); - } return result; } @@ -123,12 +120,12 @@ QString ScreenWindow::selectedText( bool preserveLineBreaks ) const return _screen->selectedText( preserveLineBreaks ); } -void ScreenWindow::getSelectionStart( int & column , int & line ) +void ScreenWindow::getSelectionStart( int& column , int& line ) { _screen->getSelectionStart(column,line); line -= currentLine(); } -void ScreenWindow::getSelectionEnd( int & column , int & line ) +void ScreenWindow::getSelectionEnd( int& column , int& line ) { _screen->getSelectionEnd(column,line); line -= currentLine(); @@ -136,7 +133,7 @@ void ScreenWindow::getSelectionEnd( int & column , int & line ) void ScreenWindow::setSelectionStart( int column , int line , bool columnMode ) { _screen->setSelectionStart( column , qMin(line + currentLine(),endWindowLine()) , columnMode); - + _bufferNeedsUpdate = true; emit selectionChanged(); } @@ -168,7 +165,7 @@ void ScreenWindow::setWindowLines(int lines) } int ScreenWindow::windowLines() const { - return _windowLines; + return _windowLines; } int ScreenWindow::windowColumns() const @@ -189,11 +186,11 @@ int ScreenWindow::columnCount() const QPoint ScreenWindow::cursorPosition() const { QPoint position; - + position.setX( _screen->getCursorX() ); position.setY( _screen->getCursorY() ); - return position; + return position; } int ScreenWindow::currentLine() const @@ -203,10 +200,13 @@ int ScreenWindow::currentLine() const void ScreenWindow::scrollBy( RelativeScrollMode mode , int amount ) { - if ( mode == ScrollLines ) { + if ( mode == ScrollLines ) + { scrollTo( currentLine() + amount ); - } else if ( mode == ScrollPages ) { - scrollTo( currentLine() + amount * ( windowLines() / 2 ) ); + } + else if ( mode == ScrollPages ) + { + scrollTo( currentLine() + amount * ( windowLines() / 2 ) ); } } @@ -247,7 +247,7 @@ int ScreenWindow::scrollCount() const return _scrollCount; } -void ScreenWindow::resetScrollCount() +void ScreenWindow::resetScrollCount() { _scrollCount = 0; } @@ -256,28 +256,30 @@ QRect ScreenWindow::scrollRegion() const { bool equalToScreenSize = windowLines() == _screen->getLines(); - if ( atEndOfOutput() && equalToScreenSize ) { + if ( atEndOfOutput() && equalToScreenSize ) return _screen->lastScrolledRegion(); - } else { + else return QRect(0,0,windowColumns(),windowLines()); - } } void ScreenWindow::notifyOutputChanged() { // move window to the bottom of the screen and update scroll count // if this window is currently tracking the bottom of the screen - if ( _trackOutput ) { + if ( _trackOutput ) + { _scrollCount -= _screen->scrolledLines(); _currentLine = qMax(0,_screen->getHistLines() - (windowLines()-_screen->getLines())); - } else { - // if the history is not unlimited then it may + } + else + { + // if the history is not unlimited then it may // have run out of space and dropped the oldest // lines of output - in this case the screen - // window's current line number will need to + // window's current line number will need to // be adjusted - otherwise the output will scroll - _currentLine = qMax(0,_currentLine - - _screen->droppedLines()); + _currentLine = qMax(0,_currentLine - + _screen->droppedLines()); // ensure that the screen window's current position does // not go beyond the bottom of the screen @@ -286,7 +288,7 @@ void ScreenWindow::notifyOutputChanged() _bufferNeedsUpdate = true; - emit outputChanged(); + emit outputChanged(); } -//#include "moc_ScreenWindow.cpp" +//#include "ScreenWindow.moc" diff --git a/lib/ScreenWindow.h b/lib/ScreenWindow.h index 9b16108..51adb42 100644 --- a/lib/ScreenWindow.h +++ b/lib/ScreenWindow.h @@ -1,7 +1,5 @@ /* - Copyright (C) 2007 by Robert Knight - - Rewritten for QT4 by e_k , Copyright (C)2008 + Copyright 2007-2008 by Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -30,18 +28,20 @@ // Konsole #include "Character.h" -namespace Konsole { +namespace Konsole +{ class Screen; /** - * Provides a window onto a section of a terminal screen. - * This window can then be rendered by a terminal display widget ( TerminalDisplay ). + * 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 + * in response to mouse or keyboard input. + * + * A new ScreenWindow for a terminal session can be created by calling Emulation::createWindow() * - * To use the screen window, create a new ScreenWindow() instance and associated it with - * a terminal screen using setScreen(). * Use the scrollTo() method to scroll the window up and down on the screen. - * Call the getImage() method to retrieve the character image which is currently visible in the window. + * Use the getImage() method to retrieve the character image which is currently visible in the window. * * setTrackOutput() controls whether the window moves to the bottom of the associated screen when new * lines are added to it. @@ -50,11 +50,12 @@ class Screen; * be called. This in turn will update the window's position and emit the outputChanged() signal * if necessary. */ -class ScreenWindow : public QObject { - Q_OBJECT +class ScreenWindow : public QObject +{ +Q_OBJECT public: - /** + /** * Constructs a new screen window with the given parent. * A screen must be specified by calling setScreen() before calling getImage() or getLineProperties(). * @@ -63,22 +64,22 @@ public: * to notify the window when the associated screen has changed and synchronize selection updates * between all views on a session. */ - ScreenWindow(QObject * parent = 0); + ScreenWindow(QObject* parent = 0); virtual ~ScreenWindow(); /** Sets the screen which this window looks onto */ - void setScreen(Screen * screen); + void setScreen(Screen* screen); /** 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 * onto the screen. * - * The buffer is managed by the ScreenWindow instance and does not need to be + * The returned buffer is managed by the ScreenWindow instance and does not need to be * deleted by the caller. */ - Character * getImage(); + Character* getImage(); /** * Returns the line attributes associated with the lines of characters which @@ -88,14 +89,14 @@ public: /** * Returns the number of lines which the region of the window - * specified by scrollRegion() has been scrolled by since the last call - * to resetScrollCount(). scrollRegion() is in most cases the + * specified by scrollRegion() has been scrolled by since the last call + * to resetScrollCount(). scrollRegion() is in most cases the * whole window, but will be a smaller area in, for example, applications * which provide split-screen facilities. * - * This is not guaranteed to be accurate, but allows views to optimise + * This is not guaranteed to be accurate, but allows views to optimize * rendering by reducing the amount of costly text rendering that - * needs to be done when the output is scrolled. + * needs to be done when the output is scrolled. */ int scrollCount() const; @@ -105,16 +106,16 @@ public: void resetScrollCount(); /** - * Returns the area of the window which was last scrolled, this is + * Returns the area of the window which was last scrolled, this is * usually the whole window area. * * Like scrollCount(), this is not guaranteed to be accurate, - * but allows views to optimise rendering. + * but allows views to optimize rendering. */ QRect scrollRegion() const; - /** - * Sets the start of the selection to the given @p line and @p column within + /** + * Sets the start of the selection to the given @p line and @p column within * the window. */ void setSelectionStart( int column , int line , bool columnMode ); @@ -122,20 +123,20 @@ public: * Sets the end of the selection to the given @p line and @p column within * the window. */ - void setSelectionEnd( int column , int line ); + void setSelectionEnd( int column , int line ); /** * Retrieves the start of the selection within the window. */ - void getSelectionStart( int & column , int & line ); + void getSelectionStart( int& column , int& line ); /** * Retrieves the end of the selection within the window. */ - void getSelectionEnd( int & column , int & line ); + void getSelectionEnd( int& column , int& line ); /** * Returns true if the character at @p line , @p column is part of the selection. */ bool isSelected( int column , int line ); - /** + /** * Clears the current selection */ void clearSelection(); @@ -146,7 +147,7 @@ public: int windowLines() const; /** Returns the number of columns in the window */ int windowColumns() const; - + /** Returns the total number of lines in the screen */ int lineCount() const; /** Returns the total number of columns in the screen */ @@ -155,13 +156,13 @@ public: /** Returns the index of the line which is currently at the top of this window */ int currentLine() const; - /** - * Returns the position of the cursor + /** + * Returns the position of the cursor * within the window. */ QPoint cursorPosition() const; - /** + /** * Convenience method. Returns true if the window is currently at the bottom * of the screen. */ @@ -170,31 +171,38 @@ public: /** Scrolls the window so that @p line is at the top of the window */ void scrollTo( int line ); - enum RelativeScrollMode { + /** Describes the units which scrollBy() moves the window by. */ + enum RelativeScrollMode + { + /** Scroll the window down by a given number of lines. */ ScrollLines, + /** + * Scroll the window down by a given number of pages, where + * one page is windowLines() lines + */ ScrollPages }; - /** + /** * Scrolls the window relative to its current position on the screen. * * @param mode Specifies whether @p amount refers to the number of lines or the number - * of pages to scroll. + * of pages to scroll. * @param amount The number of lines or pages ( depending on @p mode ) to scroll by. If * this number is positive, the view is scrolled down. If this number is negative, the view * is scrolled up. */ void scrollBy( RelativeScrollMode mode , int amount ); - /** + /** * Specifies whether the window should automatically move to the bottom * of the screen when new output is added. * - * If this is set to true, the window will be moved to the bottom of the associated screen ( see + * If this is set to true, the window will be moved to the bottom of the associated screen ( see * screen() ) when the notifyOutputChanged() method is called. */ void setTrackOutput(bool trackOutput); - /** + /** * Returns whether the window automatically moves to the bottom of the screen as * new output is added. See setTrackOutput() */ @@ -208,7 +216,7 @@ public: QString selectedText( bool preserveLineBreaks ) const; public slots: - /** + /** * Notifies the window that the contents of the associated terminal screen have changed. * This moves the window to the bottom of the screen if trackOutput() is true and causes * the outputChanged() signal to be emitted. @@ -217,36 +225,34 @@ public slots: signals: /** - * Emitted when the contents of the associated terminal screen ( see screen() ) changes. + * Emitted when the contents of the associated terminal screen (see screen()) changes. */ void outputChanged(); /** * Emitted when the screen window is scrolled to a different position. - * + * * @param line The line which is now at the top of the window. */ void scrolled(int line); - /** - * Emitted when the selection is changed. - */ + /** Emitted when the selection is changed. */ void selectionChanged(); private: int endWindowLine() const; void fillUnusedArea(); - Screen * _screen; // see setScreen() , screen() - Character * _windowBuffer; + Screen* _screen; // see setScreen() , screen() + Character* _windowBuffer; int _windowBufferSize; bool _bufferNeedsUpdate; int _windowLines; int _currentLine; // see scrollTo() , currentLine() - bool _trackOutput; // see setTrackOutput() , trackOutput() + bool _trackOutput; // see setTrackOutput() , trackOutput() int _scrollCount; // count of lines which the window has been scrolled by since - // the last call to resetScrollCount() + // the last call to resetScrollCount() }; } diff --git a/lib/Session.cpp b/lib/Session.cpp index 4d599b7..bdd00e9 100644 --- a/lib/Session.cpp +++ b/lib/Session.cpp @@ -40,6 +40,7 @@ #include #include "Pty.h" +//#include "kptyprocess.h" #include "TerminalDisplay.h" #include "ShellCommand.h" #include "Vt102Emulation.h" @@ -105,8 +106,8 @@ Session::Session() : connect( _emulation,SIGNAL(lockPtyRequest(bool)),_shellProcess,SLOT(lockPty(bool)) ); connect( _emulation,SIGNAL(useUtf8Request(bool)),_shellProcess,SLOT(setUtf8Mode(bool)) ); - - connect( _shellProcess,SIGNAL(done(int)), this, SLOT(done(int)) ); + connect( _shellProcess,SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(done(int)) ); + // not in kprocess anymore connect( _shellProcess,SIGNAL(done(int)), this, SLOT(done(int)) ); //setup timer for monitoring session activity _monitorTimer = new QTimer(this); @@ -153,7 +154,7 @@ bool Session::hasDarkBackground() const } bool Session::isRunning() const { - return _shellProcess->isRunning(); + return _shellProcess->state() == QProcess::Running; } void Session::setCodec(QTextCodec * codec) @@ -304,8 +305,8 @@ void Session::run() } // _shellProcess->setWorkingDirectory(QDir::homePath()); - _shellProcess->setXonXoff(_flowControl); - _shellProcess->setErase(_emulation->getErase()); + _shellProcess->setFlowControlEnabled(_flowControl); + _shellProcess->setErase(_emulation->eraseChar()); // this is not strictly accurate use of the COLORFGBG variable. This does not // tell the terminal exactly which colors are being used, but instead approximates @@ -544,7 +545,15 @@ void Session::refresh() bool Session::sendSignal(int signal) { - return _shellProcess->kill(signal); + int result = ::kill(_shellProcess->pid(),signal); + + if ( result == 0 ) + { + _shellProcess->waitForFinished(); + return true; + } + else + return false; } void Session::close() @@ -582,32 +591,29 @@ QString Session::profileKey() const void Session::done(int exitStatus) { if (!_autoClose) { - _userTitle = (""); + _userTitle = ("This session is done. Finished"); emit titleChanged(); return; } - if (!_wantedClose && (exitStatus || _shellProcess->signalled())) { - QString message; - if (_shellProcess->normalExit()) { - message.sprintf ("Session '%s' exited with status %d.", _nameTitle.toAscii().data(), exitStatus); - } else if (_shellProcess->signalled()) { - if (_shellProcess->coreDumped()) { + QString message; + if (!_wantedClose || exitStatus != 0) { - message.sprintf("Session '%s' exited with signal %d and dumped core.", _nameTitle.toAscii().data(), _shellProcess->exitSignal()); - } else { - message.sprintf("Session '%s' exited with signal %d.", _nameTitle.toAscii().data(), _shellProcess->exitSignal()); - } + if (_shellProcess->exitStatus() == QProcess::NormalExit) { + message.sprintf("Session '%s' exited with status %d.", + _nameTitle.toAscii().data(), exitStatus); } else { - message.sprintf ("Session '%s' exited unexpectedly.", _nameTitle.toAscii().data()); + message.sprintf("Session '%s' crashed.", + _nameTitle.toAscii().data()); } - - //FIXME: See comments in Session::monitorTimerDone() -// KNotification::event("Finished", message , QPixmap(), -// QApplication::activeWindow(), -// KNotification::CloseWhenWidgetActivated); } - emit finished(); + + if ( !_wantedClose && _shellProcess->exitStatus() != QProcess::NormalExit ) + message.sprintf("Session '%s' exited unexpectedly.", + _nameTitle.toAscii().data()); + else + emit finished(); + } Emulation * Session::emulation() const @@ -770,7 +776,7 @@ void Session::setFlowControlEnabled(bool enabled) _flowControl = enabled; if (_shellProcess) { - _shellProcess->setXonXoff(_flowControl); + _shellProcess->setFlowControlEnabled(_flowControl); } emit flowControlEnabledChanged(enabled); diff --git a/lib/Session.h b/lib/Session.h index 746de77..b89398d 100644 --- a/lib/Session.h +++ b/lib/Session.h @@ -25,12 +25,10 @@ #ifndef SESSION_H #define SESSION_H -// Qt -#include -#include + +#include #include -// Konsole #include "History.h" class KProcess; @@ -491,7 +489,7 @@ private: int _uniqueIdentifier; - Pty * _shellProcess; + Pty *_shellProcess; Emulation * _emulation; QList _views; diff --git a/lib/TerminalCharacterDecoder.cpp b/lib/TerminalCharacterDecoder.cpp index 15578c2..1603847 100644 --- a/lib/TerminalCharacterDecoder.cpp +++ b/lib/TerminalCharacterDecoder.cpp @@ -1,8 +1,8 @@ /* This file is part of Konsole, an X terminal. - + Copyright 2006-2008 by Robert Knight - + This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or @@ -25,14 +25,17 @@ // Qt #include +// KDE +//#include + // Konsole #include "konsole_wcwidth.h" using namespace Konsole; PlainTextDecoder::PlainTextDecoder() - : _output(0) - , _includeTrailingWhitespace(true) - , _recordLinePositions(false) + : _output(0) + , _includeTrailingWhitespace(true) + , _recordLinePositions(false) { } @@ -46,9 +49,9 @@ bool PlainTextDecoder::trailingWhitespace() const } void PlainTextDecoder::begin(QTextStream* output) { - _output = output; - if (!_linePositions.isEmpty()) - _linePositions.clear(); + _output = output; + if (!_linePositions.isEmpty()) + _linePositions.clear(); } void PlainTextDecoder::end() { @@ -64,11 +67,12 @@ QList PlainTextDecoder::linePositions() const return _linePositions; } void PlainTextDecoder::decodeLine(const Character* const characters, int count, LineProperty /*properties*/ - ) + ) { Q_ASSERT( _output ); - if (_recordLinePositions && _output->string()) { + if (_recordLinePositions && _output->string()) + { int pos = _output->string()->count(); _linePositions << pos; } @@ -80,21 +84,24 @@ void PlainTextDecoder::decodeLine(const Character* const characters, int count, //(since QTextStream always deals with QStrings internally anyway) QString plainText; plainText.reserve(count); - + int outputCount = count; // if inclusion of trailing whitespace is disabled then find the end of the // line - if ( !_includeTrailingWhitespace ) { - for (int i = count-1 ; i >= 0 ; i--) { + if ( !_includeTrailingWhitespace ) + { + for (int i = count-1 ; i >= 0 ; i--) + { if ( characters[i].character != ' ' ) break; else outputCount--; } } - - for (int i=0; i') - text.append(">"); - else - text.append(ch); - } else { + text.append(">"); + else + text.append(ch); + } + else + { text.append(" "); //HTML truncates multiple spaces, so use a space marker instead } - + } //close any remaining open inner spans @@ -218,7 +232,7 @@ void HTMLDecoder::decodeLine(const Character* const characters, int count, LineP //start new line text.append("
    "); - + *_output << text; } void HTMLDecoder::openSpan(QString& text , const QString& style) diff --git a/lib/TerminalCharacterDecoder.h b/lib/TerminalCharacterDecoder.h index 3dd3332..5bdc035 100644 --- a/lib/TerminalCharacterDecoder.h +++ b/lib/TerminalCharacterDecoder.h @@ -1,8 +1,8 @@ /* This file is part of Konsole, an X terminal. - + Copyright 2006-2008 by Robert Knight - + This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or @@ -28,7 +28,8 @@ class QTextStream; -namespace Konsole { +namespace Konsole +{ /** * Base class for terminal character decoders @@ -37,9 +38,10 @@ namespace Konsole { * and background colours and other appearance-related properties into text strings. * * Derived classes may produce either plain text with no other colour or appearance information, or - * they may produce text which incorporates these additional properties. + * they may produce text which incorporates these additional properties. */ -class TerminalCharacterDecoder { +class TerminalCharacterDecoder +{ public: virtual ~TerminalCharacterDecoder() {} @@ -56,21 +58,22 @@ public: * @param count The number of characters * @param properties Additional properties which affect all characters in the line */ - virtual void decodeLine(const Character* const characters, + virtual void decodeLine(const Character* const characters, int count, - LineProperty properties) = 0; + LineProperty properties) = 0; }; /** * A terminal character decoder which produces plain text, ignoring colours and other appearance-related * properties of the original characters. */ -class PlainTextDecoder : public TerminalCharacterDecoder { +class PlainTextDecoder : public TerminalCharacterDecoder +{ public: - PlainTextDecoder(); + PlainTextDecoder(); - /** - * Set whether trailing whitespace at the end of lines should be included + /** + * Set whether trailing whitespace at the end of lines should be included * in the output. * Defaults to true. */ @@ -80,9 +83,9 @@ public: * in the output. */ bool trailingWhitespace() const; - /** + /** * Returns of character positions in the output stream - * at which new lines where added. Returns an empty if setTrackLinePositions() is false or if + * at which new lines where added. Returns an empty if setTrackLinePositions() is false or if * the output device is not a string. */ QList linePositions() const; @@ -94,9 +97,9 @@ public: virtual void decodeLine(const Character* const characters, int count, - LineProperty properties); - + LineProperty properties); + private: QTextStream* _output; bool _includeTrailingWhitespace; @@ -108,9 +111,10 @@ private: /** * A terminal character decoder which produces pretty HTML markup */ -class HTMLDecoder : public TerminalCharacterDecoder { +class HTMLDecoder : public TerminalCharacterDecoder +{ public: - /** + /** * Constructs an HTML decoder using a default black-on-white color scheme. */ HTMLDecoder(); @@ -120,7 +124,7 @@ public: * output */ void setColorTable( const ColorEntry* table ); - + virtual void decodeLine(const Character* const characters, int count, LineProperty properties); @@ -134,7 +138,7 @@ private: QTextStream* _output; const ColorEntry* _colorTable; - bool _innerSpanOpen; + bool _innerSpanOpen; quint8 _lastRendition; CharacterColor _lastForeColor; CharacterColor _lastBackColor; diff --git a/lib/TerminalDisplay.cpp b/lib/TerminalDisplay.cpp index cd1b2ea..9924173 100644 --- a/lib/TerminalDisplay.cpp +++ b/lib/TerminalDisplay.cpp @@ -1,11 +1,9 @@ /* This file is part of Konsole, a terminal emulator for KDE. - + Copyright 2006-2008 by Robert Knight Copyright 1997,1998 by Lars Doelle - - Rewritten for QT4 by e_k , Copyright (C)2008 - + This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or @@ -43,8 +41,22 @@ #include #include #include +#include + +// KDE +//#include +//#include +//#include +//#include +//#include +//#include +//#include +//#include +//#include +//#include // Konsole +//#include #include "Filter.h" #include "konsole_wcwidth.h" #include "ScreenWindow.h" @@ -67,29 +79,29 @@ const ColorEntry Konsole::base_color_table[TABLE_COLORS] = // gamma correction for the dim colors to compensate for bright X screens. // It contains the 8 ansiterm/xterm colors in 2 intensities. { - // Fixme: could add faint colors here, also. - // normal - ColorEntry(QColor(0x00,0x00,0x00), 0), ColorEntry( QColor(0xB2,0xB2,0xB2), 1), // Dfore, Dback - ColorEntry(QColor(0x00,0x00,0x00), 0), ColorEntry( QColor(0xB2,0x18,0x18), 0), // Black, Red - ColorEntry(QColor(0x18,0xB2,0x18), 0), ColorEntry( QColor(0xB2,0x68,0x18), 0), // Green, Yellow - ColorEntry(QColor(0x18,0x18,0xB2), 0), ColorEntry( QColor(0xB2,0x18,0xB2), 0), // Blue, Magenta - ColorEntry(QColor(0x18,0xB2,0xB2), 0), ColorEntry( QColor(0xB2,0xB2,0xB2), 0), // Cyan, White - // intensiv - ColorEntry(QColor(0x00,0x00,0x00), 0), ColorEntry( QColor(0xFF,0xFF,0xFF), 1), - ColorEntry(QColor(0x68,0x68,0x68), 0), ColorEntry( QColor(0xFF,0x54,0x54), 0), - ColorEntry(QColor(0x54,0xFF,0x54), 0), ColorEntry( QColor(0xFF,0xFF,0x54), 0), - ColorEntry(QColor(0x54,0x54,0xFF), 0), ColorEntry( QColor(0xFF,0x54,0xFF), 0), - ColorEntry(QColor(0x54,0xFF,0xFF), 0), ColorEntry( QColor(0xFF,0xFF,0xFF), 0) + // Fixme: could add faint colors here, also. + // normal + ColorEntry(QColor(0x00,0x00,0x00), 0), ColorEntry( QColor(0xB2,0xB2,0xB2), 1), // Dfore, Dback + ColorEntry(QColor(0x00,0x00,0x00), 0), ColorEntry( QColor(0xB2,0x18,0x18), 0), // Black, Red + ColorEntry(QColor(0x18,0xB2,0x18), 0), ColorEntry( QColor(0xB2,0x68,0x18), 0), // Green, Yellow + ColorEntry(QColor(0x18,0x18,0xB2), 0), ColorEntry( QColor(0xB2,0x18,0xB2), 0), // Blue, Magenta + ColorEntry(QColor(0x18,0xB2,0xB2), 0), ColorEntry( QColor(0xB2,0xB2,0xB2), 0), // Cyan, White + // intensiv + ColorEntry(QColor(0x00,0x00,0x00), 0), ColorEntry( QColor(0xFF,0xFF,0xFF), 1), + ColorEntry(QColor(0x68,0x68,0x68), 0), ColorEntry( QColor(0xFF,0x54,0x54), 0), + ColorEntry(QColor(0x54,0xFF,0x54), 0), ColorEntry( QColor(0xFF,0xFF,0x54), 0), + ColorEntry(QColor(0x54,0x54,0xFF), 0), ColorEntry( QColor(0xFF,0x54,0xFF), 0), + ColorEntry(QColor(0x54,0xFF,0xFF), 0), ColorEntry( QColor(0xFF,0xFF,0xFF), 0) }; // scroll increment used when dragging selection at top/bottom of window. // static bool TerminalDisplay::_antialiasText = true; -bool TerminalDisplay::HAVE_TRANSPARENCY = false; +bool TerminalDisplay::HAVE_TRANSPARENCY = true; // we use this to force QPainter to display text in LTR mode -// more information can be found in: http://unicode.org/reports/tr9/ +// more information can be found in: http://unicode.org/reports/tr9/ const QChar LTR_OVERRIDE_CHAR( 0x202D ); /* ------------------------------------------------------------------------- */ @@ -113,36 +125,37 @@ ScreenWindow* TerminalDisplay::screenWindow() const void TerminalDisplay::setScreenWindow(ScreenWindow* window) { // disconnect existing screen window if any - if ( _screenWindow ) { + if ( _screenWindow ) + { disconnect( _screenWindow , 0 , this , 0 ); } _screenWindow = window; - if ( window ) { + if ( window ) + { // TODO: Determine if this is an issue. //#warning "The order here is not specified - does it matter whether updateImage or updateLineProperties comes first?" connect( _screenWindow , SIGNAL(outputChanged()) , this , SLOT(updateLineProperties()) ); connect( _screenWindow , SIGNAL(outputChanged()) , this , SLOT(updateImage()) ); - connect(_screenWindow, SIGNAL(selectionChanged()), this, SLOT(selectionChanged())); window->setWindowLines(_lines); } } const ColorEntry* TerminalDisplay::colorTable() const { - return _colorTable; + return _colorTable; } void TerminalDisplay::setBackgroundColor(const QColor& color) { _colorTable[DEFAULT_BACK_COLOR].color = color; QPalette p = palette(); - p.setColor( backgroundRole(), color ); - setPalette( p ); + p.setColor( backgroundRole(), color ); + setPalette( p ); - // Avoid propagating the palette change to the scroll bar - _scrollBar->setPalette( QApplication::palette() ); + // Avoid propagating the palette change to the scroll bar + _scrollBar->setPalette( QApplication::palette() ); update(); } @@ -154,10 +167,10 @@ void TerminalDisplay::setForegroundColor(const QColor& color) } void TerminalDisplay::setColorTable(const ColorEntry table[]) { - for (int i = 0; i < TABLE_COLORS; i++) - _colorTable[i] = table[i]; + for (int i = 0; i < TABLE_COLORS; i++) + _colorTable[i] = table[i]; - setBackgroundColor(_colorTable[DEFAULT_BACK_COLOR].color); + setBackgroundColor(_colorTable[DEFAULT_BACK_COLOR].color); } /* ------------------------------------------------------------------------- */ @@ -178,60 +191,60 @@ void TerminalDisplay::setColorTable(const ColorEntry table[]) QCodec. */ -static inline bool isLineChar(quint16 c) -{ - return ((c & 0xFF80) == 0x2500); -} +static inline bool isLineChar(quint16 c) { return ((c & 0xFF80) == 0x2500);} static inline bool isLineCharString(const QString& string) { - return (string.length() > 0) && (isLineChar(string.at(0).unicode())); + return (string.length() > 0) && (isLineChar(string.at(0).unicode())); } - + // assert for i in [0..31] : vt100extended(vt100_graphics[i]) == i. -unsigned short Konsole::vt100_graphics[32] = { // 0/8 1/9 2/10 3/11 4/12 5/13 6/14 7/15 - 0x0020, 0x25C6, 0x2592, 0x2409, 0x240c, 0x240d, 0x240a, 0x00b0, - 0x00b1, 0x2424, 0x240b, 0x2518, 0x2510, 0x250c, 0x2514, 0x253c, - 0xF800, 0xF801, 0x2500, 0xF803, 0xF804, 0x251c, 0x2524, 0x2534, - 0x252c, 0x2502, 0x2264, 0x2265, 0x03C0, 0x2260, 0x00A3, 0x00b7 +unsigned short Konsole::vt100_graphics[32] = +{ // 0/8 1/9 2/10 3/11 4/12 5/13 6/14 7/15 + 0x0020, 0x25C6, 0x2592, 0x2409, 0x240c, 0x240d, 0x240a, 0x00b0, + 0x00b1, 0x2424, 0x240b, 0x2518, 0x2510, 0x250c, 0x2514, 0x253c, + 0xF800, 0xF801, 0x2500, 0xF803, 0xF804, 0x251c, 0x2524, 0x2534, + 0x252c, 0x2502, 0x2264, 0x2265, 0x03C0, 0x2260, 0x00A3, 0x00b7 }; void TerminalDisplay::fontChange(const QFont&) { - QFontMetrics fm(font()); - _fontHeight = fm.height() + _lineSpacing; + QFontMetrics fm(font()); + _fontHeight = fm.height() + _lineSpacing; - // waba TerminalDisplay 1.123: - // "Base character width on widest ASCII character. This prevents too wide - // characters in the presence of double wide (e.g. Japanese) characters." - // Get the width from representative normal width characters - _fontWidth = qRound((double)fm.width(REPCHAR)/(double)strlen(REPCHAR)); + // waba TerminalDisplay 1.123: + // "Base character width on widest ASCII character. This prevents too wide + // characters in the presence of double wide (e.g. Japanese) characters." + // Get the width from representative normal width characters + _fontWidth = qRound((double)fm.width(REPCHAR)/(double)strlen(REPCHAR)); - _fixedFont = true; + _fixedFont = true; - int fw = fm.width(REPCHAR[0]); - for (unsigned int i=1; i< strlen(REPCHAR); i++) { - if (fw != fm.width(REPCHAR[i])) { - _fixedFont = false; - break; - } + int fw = fm.width(REPCHAR[0]); + for(unsigned int i=1; i< strlen(REPCHAR); i++) + { + if (fw != fm.width(REPCHAR[i])) + { + _fixedFont = false; + break; } + } - if (_fontWidth < 1) - _fontWidth=1; + if (_fontWidth < 1) + _fontWidth=1; - _fontAscent = fm.ascent(); + _fontAscent = fm.ascent(); - emit changedFontMetricSignal( _fontHeight, _fontWidth ); - propagateSize(); - update(); + emit changedFontMetricSignal( _fontHeight, _fontWidth ); + propagateSize(); + update(); } void TerminalDisplay::setVTFont(const QFont& f) { - QFont font = f; - + QFont font = f; + #ifdef Q_WS_MAC #if QT_VERSION >= 0x040700 // mac uses floats for font width specification. @@ -240,33 +253,35 @@ void TerminalDisplay::setVTFont(const QFont& f) #else #warning "Correct handling of the QFont metrics requited Qt>=4.7" #endif -#endif +#endif - QFontMetrics metrics(font); + QFontMetrics metrics(font); - if ( !QFontInfo(font).fixedPitch() ) { - qDebug() << "Using an unsupported variable-width font in the terminal. This may produce display errors."; - } + if ( !QFontInfo(font).fixedPitch() ) + { + qDebug() << "Using an unsupported variable-width font in the terminal. This may produce display errors."; + } - if ( metrics.height() < height() && metrics.maxWidth() < width() ) { - // hint that text should be drawn without anti-aliasing. - // depending on the user's font configuration, this may not be respected - if (!_antialiasText) - font.setStyleStrategy( QFont::NoAntialias ); + if ( metrics.height() < height() && metrics.maxWidth() < width() ) + { + // hint that text should be drawn without anti-aliasing. + // depending on the user's font configuration, this may not be respected + if (!_antialiasText) + font.setStyleStrategy( QFont::NoAntialias ); + + // experimental optimization. Konsole assumes that the terminal is using a + // mono-spaced font, in which case kerning information should have an effect. + // Disabling kerning saves some computation when rendering text. + font.setKerning(false); - // experimental optimization. Konsole assumes that the terminal is using a - // mono-spaced font, in which case kerning information should have an effect. - // Disabling kerning saves some computation when rendering text. - font.setKerning(false); - - QWidget::setFont(font); - fontChange(font); - } + QWidget::setFont(font); + fontChange(font); + } } void TerminalDisplay::setFont(const QFont &) { - // ignore font change request if not coming from konsole itself + // ignore font change request if not coming from konsole itself } /* ------------------------------------------------------------------------- */ @@ -276,115 +291,118 @@ void TerminalDisplay::setFont(const QFont &) /* ------------------------------------------------------------------------- */ TerminalDisplay::TerminalDisplay(QWidget *parent) - :QWidget(parent) - ,_screenWindow(0) - ,_allowBell(true) - ,_gridLayout(0) - ,_fontHeight(1) - ,_fontWidth(1) - ,_fontAscent(1) - ,_boldIntense(true) - ,_lines(1) - ,_columns(1) - ,_usedLines(1) - ,_usedColumns(1) - ,_contentHeight(1) - ,_contentWidth(1) - ,_image(0) - ,_randomSeed(0) - ,_resizing(false) - ,_terminalSizeHint(false) - ,_terminalSizeStartup(true) - ,_bidiEnabled(false) - ,_actSel(0) - ,_wordSelectionMode(false) - ,_lineSelectionMode(false) - ,_preserveLineBreaks(false) - ,_columnSelectionMode(false) - ,_scrollbarLocation(NoScrollBar) - ,_wordCharacters(":@-./_~") - ,_bellMode(SystemBeepBell) - ,_blinking(false) - ,_hasBlinker(false) - ,_cursorBlinking(false) - ,_hasBlinkingCursor(false) - ,_allowBlinkingText(true) - ,_ctrlDrag(false) - ,_tripleClickMode(SelectWholeLine) - ,_isFixedSize(false) - ,_possibleTripleClick(false) - ,_resizeWidget(0) - ,_resizeTimer(0) - ,_flowControlWarningEnabled(false) - ,_outputSuspendedLabel(0) - ,_lineSpacing(0) - ,_colorsInverted(false) - ,_blendColor(qRgba(0,0,0,0xff)) - ,_filterChain(new TerminalImageFilterChain()) - ,_cursorShape(BlockCursor) +:QWidget(parent) +,_screenWindow(0) +,_allowBell(true) +,_gridLayout(0) +,_fontHeight(1) +,_fontWidth(1) +,_fontAscent(1) +,_boldIntense(true) +,_lines(1) +,_columns(1) +,_usedLines(1) +,_usedColumns(1) +,_contentHeight(1) +,_contentWidth(1) +,_image(0) +,_randomSeed(0) +,_resizing(false) +,_terminalSizeHint(false) +,_terminalSizeStartup(true) +,_bidiEnabled(false) +,_actSel(0) +,_wordSelectionMode(false) +,_lineSelectionMode(false) +,_preserveLineBreaks(false) +,_columnSelectionMode(false) +,_scrollbarLocation(NoScrollBar) +,_wordCharacters(":@-./_~") +,_bellMode(SystemBeepBell) +,_blinking(false) +,_hasBlinker(false) +,_cursorBlinking(false) +,_hasBlinkingCursor(false) +,_allowBlinkingText(true) +,_ctrlDrag(false) +,_tripleClickMode(SelectWholeLine) +,_isFixedSize(false) +,_possibleTripleClick(false) +,_resizeWidget(0) +,_resizeTimer(0) +,_flowControlWarningEnabled(false) +,_outputSuspendedLabel(0) +,_lineSpacing(0) +,_colorsInverted(false) +,_blendColor(qRgba(0,0,0,0xff)) +,_filterChain(new TerminalImageFilterChain()) +,_cursorShape(BlockCursor) { - // terminal applications are not designed with Right-To-Left in mind, - // so the layout is forced to Left-To-Right - setLayoutDirection(Qt::LeftToRight); + // terminal applications are not designed with Right-To-Left in mind, + // so the layout is forced to Left-To-Right + setLayoutDirection(Qt::LeftToRight); - // The offsets are not yet calculated. - // Do not calculate these too often to be more smoothly when resizing - // konsole in opaque mode. - _topMargin = DEFAULT_TOP_MARGIN; - _leftMargin = DEFAULT_LEFT_MARGIN; + // The offsets are not yet calculated. + // Do not calculate these too often to be more smoothly when resizing + // konsole in opaque mode. + _topMargin = DEFAULT_TOP_MARGIN; + _leftMargin = DEFAULT_LEFT_MARGIN; - // create scroll bar for scrolling output up and down - // set the scroll bar's slider to occupy the whole area of the scroll bar initially - _scrollBar = new QScrollBar(this); - setScroll(0,0); - _scrollBar->setCursor( Qt::ArrowCursor ); - connect(_scrollBar, SIGNAL(valueChanged(int)), this, - SLOT(scrollBarPositionChanged(int))); + // create scroll bar for scrolling output up and down + // set the scroll bar's slider to occupy the whole area of the scroll bar initially + _scrollBar = new QScrollBar(this); + setScroll(0,0); + _scrollBar->setCursor( Qt::ArrowCursor ); + connect(_scrollBar, SIGNAL(valueChanged(int)), this, + SLOT(scrollBarPositionChanged(int))); + // qtermwidget: we have to hide it here due the _scrollbarLocation==NoScrollBar + // check in TerminalDisplay::setScrollBarPosition(ScrollBarPosition position) + _scrollBar->hide(); - // setup timers for blinking cursor and text - _blinkTimer = new QTimer(this); - connect(_blinkTimer, SIGNAL(timeout()), this, SLOT(blinkEvent())); - _blinkCursorTimer = new QTimer(this); - connect(_blinkCursorTimer, SIGNAL(timeout()), this, SLOT(blinkCursorEvent())); + // setup timers for blinking cursor and text + _blinkTimer = new QTimer(this); + connect(_blinkTimer, SIGNAL(timeout()), this, SLOT(blinkEvent())); + _blinkCursorTimer = new QTimer(this); + connect(_blinkCursorTimer, SIGNAL(timeout()), this, SLOT(blinkCursorEvent())); - //KCursor::setAutoHideCursor( this, true ); +// KCursor::setAutoHideCursor( this, true ); + + setUsesMouse(true); + setColorTable(base_color_table); + setMouseTracking(true); - setUsesMouse(true); - setColorTable(base_color_table); - setMouseTracking(true); + // Enable drag and drop + setAcceptDrops(true); // attempt + dragInfo.state = diNone; - // Enable drag and drop - setAcceptDrops(true); // attempt - dragInfo.state = diNone; + setFocusPolicy( Qt::WheelFocus ); - setFocusPolicy( Qt::WheelFocus ); + // enable input method support + setAttribute(Qt::WA_InputMethodEnabled, true); - // enable input method support - setAttribute(Qt::WA_InputMethodEnabled, true); + // this is an important optimization, it tells Qt + // that TerminalDisplay will handle repainting its entire area. + setAttribute(Qt::WA_OpaquePaintEvent); - // this is an important optimization, it tells Qt - // that TerminalDisplay will handle repainting its entire area. - setAttribute(Qt::WA_OpaquePaintEvent); + _gridLayout = new QGridLayout(this); + _gridLayout->setContentsMargins(0, 0, 0, 0); - _gridLayout = new QGridLayout(this); - _gridLayout->setContentsMargins(0, 0, 0, 0); + setLayout( _gridLayout ); - setLayout( _gridLayout ); - - new AutoScrollHandler(this); + new AutoScrollHandler(this); } TerminalDisplay::~TerminalDisplay() { - disconnect(_blinkTimer); - disconnect(_blinkCursorTimer); - qApp->removeEventFilter( this ); + disconnect(_blinkTimer); + disconnect(_blinkCursorTimer); + qApp->removeEventFilter( this ); + + delete[] _image; - delete[] _image; - - delete _gridLayout; - delete _outputSuspendedLabel; - delete _filterChain; + delete _gridLayout; + delete _outputSuspendedLabel; + delete _filterChain; } /* ------------------------------------------------------------------------- */ @@ -412,7 +430,8 @@ where _ = none */ -enum LineEncode { +enum LineEncode +{ TopL = (1<<1), TopC = (1<<2), TopR = (1<<3), @@ -508,24 +527,26 @@ static void drawLineChar(QPainter& paint, int x, int y, int w, int h, uchar code } -void TerminalDisplay::drawLineCharString( QPainter& painter, int x, int y, const QString& str, - const Character* attributes) +void TerminalDisplay::drawLineCharString( QPainter& painter, int x, int y, const QString& str, + const Character* attributes) { - const QPen& currentPen = painter.pen(); + const QPen& currentPen = painter.pen(); + + if ( (attributes->rendition & RE_BOLD) && _boldIntense ) + { + QPen boldPen(currentPen); + boldPen.setWidth(3); + painter.setPen( boldPen ); + } + + for (int i=0 ; i < str.length(); i++) + { + uchar code = str[i].cell(); + if (LineChars[code]) + drawLineChar(painter, x + (_fontWidth*i), y, _fontWidth, _fontHeight, code); + } - if ( (attributes->rendition & RE_BOLD) && _boldIntense ) { - QPen boldPen(currentPen); - boldPen.setWidth(3); - painter.setPen( boldPen ); - } - - for (int i=0 ; i < str.length(); i++) { - uchar code = str[i].cell(); - if (LineChars[code]) - drawLineChar(painter, x + (_fontWidth*i), y, _fontWidth, _fontHeight, code); - } - - painter.setPen( currentPen ); + painter.setPen( currentPen ); } void TerminalDisplay::setKeyboardCursorShape(KeyboardCursorShape shape) @@ -540,9 +561,9 @@ void TerminalDisplay::setKeyboardCursorColor(bool useForegroundColor, const QCol { if (useForegroundColor) _cursorColor = QColor(); // an invalid color means that - // the foreground color of the - // current character should - // be used + // the foreground color of the + // current character should + // be used else _cursorColor = color; @@ -559,49 +580,51 @@ void TerminalDisplay::setOpacity(qreal opacity) // enable automatic background filling to prevent the display // flickering if there is no transparency - if ( color.alpha() == 255 ) + /*if ( color.alpha() == 255 ) { setAutoFillBackground(true); } else { setAutoFillBackground(false); - } + }*/ _blendColor = color.rgba(); } void TerminalDisplay::drawBackground(QPainter& painter, const QRect& rect, const QColor& backgroundColor, bool useOpacitySetting ) { - // the area of the widget showing the contents of the terminal display is drawn - // using the background color from the color scheme set with setColorTable() - // - // the area of the widget behind the scroll-bar is drawn using the background - // brush from the scroll-bar's palette, to give the effect of the scroll-bar - // being outside of the terminal display and visual consistency with other KDE - // applications. - // - QRect scrollBarArea = _scrollBar->isVisible() ? - rect.intersected(_scrollBar->geometry()) : - QRect(); - QRegion contentsRegion = QRegion(rect).subtracted(scrollBarArea); - QRect contentsRect = contentsRegion.boundingRect(); + // the area of the widget showing the contents of the terminal display is drawn + // using the background color from the color scheme set with setColorTable() + // + // the area of the widget behind the scroll-bar is drawn using the background + // brush from the scroll-bar's palette, to give the effect of the scroll-bar + // being outside of the terminal display and visual consistency with other KDE + // applications. + // + QRect scrollBarArea = _scrollBar->isVisible() ? + rect.intersected(_scrollBar->geometry()) : + QRect(); + QRegion contentsRegion = QRegion(rect).subtracted(scrollBarArea); + QRect contentsRect = contentsRegion.boundingRect(); - if ( HAVE_TRANSPARENCY && qAlpha(_blendColor) < 0xff && useOpacitySetting ) { - QColor color(backgroundColor); - color.setAlpha(qAlpha(_blendColor)); + if ( HAVE_TRANSPARENCY && qAlpha(_blendColor) < 0xff && useOpacitySetting ) + { + QColor color(backgroundColor); + color.setAlpha(qAlpha(_blendColor)); - painter.save(); - painter.setCompositionMode(QPainter::CompositionMode_Source); - painter.fillRect(contentsRect, color); - painter.restore(); - } else - painter.fillRect(contentsRect, backgroundColor); + painter.save(); + painter.setCompositionMode(QPainter::CompositionMode_Source); + painter.fillRect(contentsRect, color); + painter.restore(); + } + else + painter.fillRect(contentsRect, backgroundColor); - painter.fillRect(scrollBarArea,_scrollBar->palette().background()); + painter.fillRect(scrollBarArea,_scrollBar->palette().background()); } -void TerminalDisplay::drawCursor(QPainter& painter, +void TerminalDisplay::drawCursor(QPainter& painter, const QRect& rect, const QColor& foregroundColor, const QColor& /*backgroundColor*/, @@ -609,14 +632,16 @@ void TerminalDisplay::drawCursor(QPainter& painter, { QRect cursorRect = rect; cursorRect.setHeight(_fontHeight - _lineSpacing - 1); + + if (!_cursorBlinking) + { + if ( _cursorColor.isValid() ) + painter.setPen(_cursorColor); + else + painter.setPen(foregroundColor); - if (!_cursorBlinking) { - if ( _cursorColor.isValid() ) - painter.setPen(_cursorColor); - else - painter.setPen(foregroundColor); - - if ( _cursorShape == BlockCursor ) { + if ( _cursorShape == BlockCursor ) + { // draw the cursor outline, adjusting the area so that // it is draw entirely inside 'rect' int penWidth = qMax(1,painter.pen().width()); @@ -625,26 +650,29 @@ void TerminalDisplay::drawCursor(QPainter& painter, penWidth/2, - penWidth/2 - penWidth%2, - penWidth/2 - penWidth%2)); - if ( hasFocus() ) { + if ( hasFocus() ) + { painter.fillRect(cursorRect, _cursorColor.isValid() ? _cursorColor : foregroundColor); - - if ( !_cursorColor.isValid() ) { + + if ( !_cursorColor.isValid() ) + { // invert the colour used to draw the text to ensure that the character at // the cursor position is readable invertCharacterColor = true; } } - } else if ( _cursorShape == UnderlineCursor ) + } + else if ( _cursorShape == UnderlineCursor ) painter.drawLine(cursorRect.left(), cursorRect.bottom(), cursorRect.right(), cursorRect.bottom()); - else if ( _cursorShape == IBeamCursor ) + else if ( _cursorShape == IBeamCursor ) painter.drawLine(cursorRect.left(), cursorRect.top(), cursorRect.left(), cursorRect.bottom()); - + } } @@ -656,11 +684,11 @@ void TerminalDisplay::drawCharacters(QPainter& painter, { // don't draw text which is currently blinking if ( _blinking && (style->rendition & RE_BLINK) ) - return; - + return; + // setup bold and underline bool useBold; - ColorEntry::FontWeight weight = style->fontWeight(_colorTable); + ColorEntry::FontWeight weight = style->fontWeight(_colorTable); if (weight == ColorEntry::UseCurrentFormat) useBold = ((style->rendition & RE_BOLD) && _boldIntense) || font().bold(); else @@ -668,18 +696,20 @@ void TerminalDisplay::drawCharacters(QPainter& painter, bool useUnderline = style->rendition & RE_UNDERLINE || font().underline(); QFont font = painter.font(); - if ( font.bold() != useBold - || font.underline() != useUnderline ) { - font.setBold(useBold); - font.setUnderline(useUnderline); - painter.setFont(font); + if ( font.bold() != useBold + || font.underline() != useUnderline ) + { + font.setBold(useBold); + font.setUnderline(useUnderline); + painter.setFont(font); } // setup pen const CharacterColor& textColor = ( invertCharacterColor ? style->backgroundColor : style->foregroundColor ); const QColor color = textColor.color(_colorTable); QPen pen = painter.pen(); - if ( pen.color() != color ) { + if ( pen.color() != color ) + { pen.setColor(color); painter.setPen(color); } @@ -687,13 +717,14 @@ void TerminalDisplay::drawCharacters(QPainter& painter, // draw text if ( isLineCharString(text) ) drawLineCharString(painter,rect.x(),rect.y(),text,style); - else { + else + { // the drawText(rect,flags,string) overload is used here with null flags - // instead of drawText(rect,string) because the (rect,string) overload causes - // the application's default layout direction to be used instead of + // instead of drawText(rect,string) because the (rect,string) overload causes + // the application's default layout direction to be used instead of // the widget-specific layout direction, which should always be // Qt::LeftToRight for this widget - // This was discussed in: http://lists.kde.org/?t=120552223600002&r=1&w=2 + // This was discussed in: http://lists.kde.org/?t=120552223600002&r=1&w=2 if (_bidiEnabled) painter.drawText(rect,0,text); else @@ -701,17 +732,17 @@ void TerminalDisplay::drawCharacters(QPainter& painter, } } -void TerminalDisplay::drawTextFragment(QPainter& painter , +void TerminalDisplay::drawTextFragment(QPainter& painter , const QRect& rect, - const QString& text, + const QString& text, const Character* style) { painter.save(); - // setup painter + // setup painter const QColor foregroundColor = style->foregroundColor.color(_colorTable); const QColor backgroundColor = style->backgroundColor.color(_colorTable); - + // draw background if different from the display's background color if ( backgroundColor != palette().background().color() ) drawBackground(painter,rect,backgroundColor, @@ -729,14 +760,8 @@ void TerminalDisplay::drawTextFragment(QPainter& painter , painter.restore(); } -void TerminalDisplay::setRandomSeed(uint randomSeed) -{ - _randomSeed = randomSeed; -} -uint TerminalDisplay::randomSeed() const -{ - return _randomSeed; -} +void TerminalDisplay::setRandomSeed(uint randomSeed) { _randomSeed = randomSeed; } +uint TerminalDisplay::randomSeed() const { return _randomSeed; } #if 0 /*! @@ -760,15 +785,15 @@ void TerminalDisplay::setCursorPos(const int curx, const int cury) // scrolls the image by 'lines', down if lines > 0 or up otherwise. // -// the terminal emulation keeps track of the scrolling of the character -// image as it receives input, and when the view is updated, it calls scrollImage() -// with the final scroll amount. this improves performance because scrolling the -// display is much cheaper than re-rendering all the text for the -// part of the image which has moved up or down. +// the terminal emulation keeps track of the scrolling of the character +// image as it receives input, and when the view is updated, it calls scrollImage() +// with the final scroll amount. this improves performance because scrolling the +// display is much cheaper than re-rendering all the text for the +// part of the image which has moved up or down. // Instead only new lines have to be drawn void TerminalDisplay::scrollImage(int lines , const QRect& screenWindowRegion) { - // if the flow control warning is enabled this will interfere with the + // if the flow control warning is enabled this will interfere with the // scrolling optimizations and cause artifacts. the simple solution here // is to just disable the optimization whilst it is visible if ( _outputSuspendedLabel && _outputSuspendedLabel->isVisible() ) @@ -779,14 +804,14 @@ void TerminalDisplay::scrollImage(int lines , const QRect& screenWindowRegion) // internal image - 2, so that the height of 'region' is strictly less // than the height of the internal image. QRect region = screenWindowRegion; - region.setBottom( qMin(region.bottom(),this->_lines-2) ); + region.setBottom( qMin(region.bottom(),this->_lines-2) ); // return if there is nothing to do - if ( lines == 0 - || _image == 0 - || !region.isValid() - || (region.top() + abs(lines)) >= region.bottom() - || this->_lines <= region.height() ) return; + if ( lines == 0 + || _image == 0 + || !region.isValid() + || (region.top() + abs(lines)) >= region.bottom() + || this->_lines <= region.height() ) return; // hide terminal size label to prevent it being scrolled if (_resizeWidget && _resizeWidget->isVisible()) @@ -795,8 +820,8 @@ void TerminalDisplay::scrollImage(int lines , const QRect& screenWindowRegion) // Note: With Qt 4.4 the left edge of the scrolled area must be at 0 // to get the correct (newly exposed) part of the widget repainted. // - // The right edge must be before the left edge of the scroll bar to - // avoid triggering a repaint of the entire widget, the distance is + // The right edge must be before the left edge of the scroll bar to + // avoid triggering a repaint of the entire widget, the distance is // given by SCROLLBAR_CONTENT_GAP // // Set the QT_FLUSH_PAINT environment variable to '1' before starting the @@ -805,10 +830,13 @@ void TerminalDisplay::scrollImage(int lines , const QRect& screenWindowRegion) int scrollBarWidth = _scrollBar->isHidden() ? 0 : _scrollBar->width(); const int SCROLLBAR_CONTENT_GAP = 1; QRect scrollRect; - if ( _scrollbarLocation == ScrollBarLeft ) { + if ( _scrollbarLocation == ScrollBarLeft ) + { scrollRect.setLeft(scrollBarWidth+SCROLLBAR_CONTENT_GAP); scrollRect.setRight(width()); - } else { + } + else + { scrollRect.setLeft(0); scrollRect.setRight(width() - scrollBarWidth - SCROLLBAR_CONTENT_GAP); } @@ -817,7 +845,7 @@ void TerminalDisplay::scrollImage(int lines , const QRect& screenWindowRegion) int top = _topMargin + (region.top() * _fontHeight); int linesToMove = region.height() - abs(lines); - int bytesToMove = linesToMove * + int bytesToMove = linesToMove * this->_columns * sizeof(Character); @@ -825,28 +853,31 @@ void TerminalDisplay::scrollImage(int lines , const QRect& screenWindowRegion) Q_ASSERT( bytesToMove > 0 ); //scroll internal image - if ( lines > 0 ) { + if ( lines > 0 ) + { // check that the memory areas that we are going to move are valid - Q_ASSERT( (char*)lastCharPos + bytesToMove < + Q_ASSERT( (char*)lastCharPos + bytesToMove < (char*)(_image + (this->_lines * this->_columns)) ); - - Q_ASSERT( (lines*this->_columns) < _imageSize ); + + Q_ASSERT( (lines*this->_columns) < _imageSize ); //scroll internal image down - memmove( firstCharPos , lastCharPos , bytesToMove ); - + memmove( firstCharPos , lastCharPos , bytesToMove ); + //set region of display to scroll scrollRect.setTop(top); - } else { + } + else + { // check that the memory areas that we are going to move are valid - Q_ASSERT( (char*)firstCharPos + bytesToMove < + Q_ASSERT( (char*)firstCharPos + bytesToMove < (char*)(_image + (this->_lines * this->_columns)) ); //scroll internal image up - memmove( lastCharPos , firstCharPos , bytesToMove ); - + memmove( lastCharPos , firstCharPos , bytesToMove ); + //set region of the display to scroll - scrollRect.setTop(top + abs(lines) * _fontHeight); + scrollRect.setTop(top + abs(lines) * _fontHeight); } scrollRect.setHeight(linesToMove * _fontHeight ); @@ -856,10 +887,11 @@ void TerminalDisplay::scrollImage(int lines , const QRect& screenWindowRegion) scroll( 0 , _fontHeight * (-lines) , scrollRect ); } -QRegion TerminalDisplay::hotSpotRegion() const +QRegion TerminalDisplay::hotSpotRegion() const { QRegion region; - foreach( Filter::HotSpot* hotSpot , _filterChain->hotSpots() ) { + foreach( Filter::HotSpot* hotSpot , _filterChain->hotSpots() ) + { QRect r; if (hotSpot->startLine()==hotSpot->endLine()) { r.setLeft(hotSpot->startColumn()); @@ -890,7 +922,7 @@ QRegion TerminalDisplay::hotSpotRegion() const return region; } -void TerminalDisplay::processFilters() +void TerminalDisplay::processFilters() { if (!_screenWindow) return; @@ -900,7 +932,7 @@ void TerminalDisplay::processFilters() // use _screenWindow->getImage() here rather than _image because // other classes may call processFilters() when this display's // ScreenWindow emits a scrolled() signal - which will happen before - // updateImage() is called on the display and therefore _image is + // updateImage() is called on the display and therefore _image is // out of date at this point _filterChain->setImage( _screenWindow->getImage(), _screenWindow->windowLines(), @@ -913,237 +945,249 @@ void TerminalDisplay::processFilters() update( preUpdateHotSpots | postUpdateHotSpots ); } -void TerminalDisplay::updateImage() +void TerminalDisplay::updateImage() { - if ( !_screenWindow ) - return; + if ( !_screenWindow ) + return; - // optimization - scroll the existing image where possible and - // avoid expensive text drawing for parts of the image that - // can simply be moved up or down - scrollImage( _screenWindow->scrollCount() , - _screenWindow->scrollRegion() ); - _screenWindow->resetScrollCount(); + // optimization - scroll the existing image where possible and + // avoid expensive text drawing for parts of the image that + // can simply be moved up or down + scrollImage( _screenWindow->scrollCount() , + _screenWindow->scrollRegion() ); + _screenWindow->resetScrollCount(); - Character* const newimg = _screenWindow->getImage(); - int lines = _screenWindow->windowLines(); - int columns = _screenWindow->windowColumns(); + if (!_image) { + // Create _image. + // The emitted changedContentSizeSignal also leads to getImage being recreated, so do this first. + updateImageSize(); + } - setScroll( _screenWindow->currentLine() , _screenWindow->lineCount() ); + Character* const newimg = _screenWindow->getImage(); + int lines = _screenWindow->windowLines(); + int columns = _screenWindow->windowColumns(); - if (!_image) - updateImageSize(); // Create _image + setScroll( _screenWindow->currentLine() , _screenWindow->lineCount() ); - Q_ASSERT( this->_usedLines <= this->_lines ); - Q_ASSERT( this->_usedColumns <= this->_columns ); + Q_ASSERT( this->_usedLines <= this->_lines ); + Q_ASSERT( this->_usedColumns <= this->_columns ); - int y,x,len; + int y,x,len; - QPoint tL = contentsRect().topLeft(); - int tLx = tL.x(); - int tLy = tL.y(); - _hasBlinker = false; + QPoint tL = contentsRect().topLeft(); + int tLx = tL.x(); + int tLy = tL.y(); + _hasBlinker = false; - CharacterColor cf; // undefined - CharacterColor _clipboard; // undefined - int cr = -1; // undefined + CharacterColor cf; // undefined + CharacterColor _clipboard; // undefined + int cr = -1; // undefined - const int linesToUpdate = qMin(this->_lines, qMax(0,lines )); - const int columnsToUpdate = qMin(this->_columns,qMax(0,columns)); + const int linesToUpdate = qMin(this->_lines, qMax(0,lines )); + const int columnsToUpdate = qMin(this->_columns,qMax(0,columns)); - QChar *disstrU = new QChar[columnsToUpdate]; - char *dirtyMask = new char[columnsToUpdate+2]; - QRegion dirtyRegion; + QChar *disstrU = new QChar[columnsToUpdate]; + char *dirtyMask = new char[columnsToUpdate+2]; + QRegion dirtyRegion; - // debugging variable, this records the number of lines that are found to - // be 'dirty' ( ie. have changed from the old _image to the new _image ) and - // which therefore need to be repainted - int dirtyLineCount = 0; + // debugging variable, this records the number of lines that are found to + // be 'dirty' ( ie. have changed from the old _image to the new _image ) and + // which therefore need to be repainted + int dirtyLineCount = 0; - for (y = 0; y < linesToUpdate; ++y) { - const Character* currentLine = &_image[y*this->_columns]; - const Character* const newLine = &newimg[y*columns]; + for (y = 0; y < linesToUpdate; ++y) + { + const Character* currentLine = &_image[y*this->_columns]; + const Character* const newLine = &newimg[y*columns]; - bool updateLine = false; + bool updateLine = false; + + // The dirty mask indicates which characters need repainting. We also + // mark surrounding neighbours dirty, in case the character exceeds + // its cell boundaries + memset(dirtyMask, 0, columnsToUpdate+2); + + for( x = 0 ; x < columnsToUpdate ; ++x) + { + if ( newLine[x] != currentLine[x] ) + { + dirtyMask[x] = true; + } + } - // The dirty mask indicates which characters need repainting. We also - // mark surrounding neighbours dirty, in case the character exceeds - // its cell boundaries - memset(dirtyMask, 0, columnsToUpdate+2); + if (!_resizing) // not while _resizing, we're expecting a paintEvent + for (x = 0; x < columnsToUpdate; ++x) + { + _hasBlinker |= (newLine[x].rendition & RE_BLINK); + + // Start drawing if this character or the next one differs. + // We also take the next one into account to handle the situation + // where characters exceed their cell width. + if (dirtyMask[x]) + { + quint16 c = newLine[x+0].character; + if ( !c ) + continue; + int p = 0; + disstrU[p++] = c; //fontMap(c); + bool lineDraw = isLineChar(c); + bool doubleWidth = (x+1 == columnsToUpdate) ? false : (newLine[x+1].character == 0); + cr = newLine[x].rendition; + _clipboard = newLine[x].backgroundColor; + if (newLine[x].foregroundColor != cf) cf = newLine[x].foregroundColor; + int lln = columnsToUpdate - x; + for (len = 1; len < lln; ++len) + { + const Character& ch = newLine[x+len]; - for ( x = 0 ; x < columnsToUpdate ; ++x) { - if ( newLine[x] != currentLine[x] ) { - dirtyMask[x] = true; - } + if (!ch.character) + continue; // Skip trailing part of multi-col chars. + + bool nextIsDoubleWidth = (x+len+1 == columnsToUpdate) ? false : (newLine[x+len+1].character == 0); + + if ( ch.foregroundColor != cf || + ch.backgroundColor != _clipboard || + ch.rendition != cr || + !dirtyMask[x+len] || + isLineChar(c) != lineDraw || + nextIsDoubleWidth != doubleWidth ) + break; + + disstrU[p++] = c; //fontMap(c); } - if (!_resizing) // not while _resizing, we're expecting a paintEvent - for (x = 0; x < columnsToUpdate; ++x) { - _hasBlinker |= (newLine[x].rendition & RE_BLINK); + QString unistr(disstrU, p); - // Start drawing if this character or the next one differs. - // We also take the next one into account to handle the situation - // where characters exceed their cell width. - if (dirtyMask[x]) { - quint16 c = newLine[x+0].character; - if ( !c ) - continue; - int p = 0; - disstrU[p++] = c; //fontMap(c); - bool lineDraw = isLineChar(c); - bool doubleWidth = (x+1 == columnsToUpdate) ? false : (newLine[x+1].character == 0); - cr = newLine[x].rendition; - _clipboard = newLine[x].backgroundColor; - if (newLine[x].foregroundColor != cf) cf = newLine[x].foregroundColor; - int lln = columnsToUpdate - x; - for (len = 1; len < lln; ++len) { - const Character& ch = newLine[x+len]; + bool saveFixedFont = _fixedFont; + if (lineDraw) + _fixedFont = false; + if (doubleWidth) + _fixedFont = false; - if (!ch.character) - continue; // Skip trailing part of multi-col chars. + updateLine = true; - bool nextIsDoubleWidth = (x+len+1 == columnsToUpdate) ? false : (newLine[x+len+1].character == 0); - - if ( ch.foregroundColor != cf || - ch.backgroundColor != _clipboard || - ch.rendition != cr || - !dirtyMask[x+len] || - isLineChar(c) != lineDraw || - nextIsDoubleWidth != doubleWidth ) - break; - - disstrU[p++] = c; //fontMap(c); - } - - QString unistr(disstrU, p); - - bool saveFixedFont = _fixedFont; - if (lineDraw) - _fixedFont = false; - if (doubleWidth) - _fixedFont = false; - - updateLine = true; - - _fixedFont = saveFixedFont; - x += len - 1; - } - - } - - //both the top and bottom halves of double height _lines must always be redrawn - //although both top and bottom halves contain the same characters, only - //the top one is actually - //drawn. - if (_lineProperties.count() > y) - updateLine |= (_lineProperties[y] & LINE_DOUBLEHEIGHT); - - // if the characters on the line are different in the old and the new _image - // then this line must be repainted. - if (updateLine) { - dirtyLineCount++; - - // add the area occupied by this line to the region which needs to be - // repainted - QRect dirtyRect = QRect( _leftMargin+tLx , - _topMargin+tLy+_fontHeight*y , - _fontWidth * columnsToUpdate , - _fontHeight ); - - dirtyRegion |= dirtyRect; - } - - // replace the line of characters in the old _image with the - // current line of the new _image - memcpy((void*)currentLine,(const void*)newLine,columnsToUpdate*sizeof(Character)); + _fixedFont = saveFixedFont; + x += len - 1; + } + } - // if the new _image is smaller than the previous _image, then ensure that the area - // outside the new _image is cleared - if ( linesToUpdate < _usedLines ) { - dirtyRegion |= QRect( _leftMargin+tLx , - _topMargin+tLy+_fontHeight*linesToUpdate , - _fontWidth * this->_columns , - _fontHeight * (_usedLines-linesToUpdate) ); + //both the top and bottom halves of double height _lines must always be redrawn + //although both top and bottom halves contain the same characters, only + //the top one is actually + //drawn. + if (_lineProperties.count() > y) + updateLine |= (_lineProperties[y] & LINE_DOUBLEHEIGHT); + + // if the characters on the line are different in the old and the new _image + // then this line must be repainted. + if (updateLine) + { + dirtyLineCount++; + + // add the area occupied by this line to the region which needs to be + // repainted + QRect dirtyRect = QRect( _leftMargin+tLx , + _topMargin+tLy+_fontHeight*y , + _fontWidth * columnsToUpdate , + _fontHeight ); + + dirtyRegion |= dirtyRect; } - _usedLines = linesToUpdate; - if ( columnsToUpdate < _usedColumns ) { - dirtyRegion |= QRect( _leftMargin+tLx+columnsToUpdate*_fontWidth , - _topMargin+tLy , - _fontWidth * (_usedColumns-columnsToUpdate) , - _fontHeight * this->_lines ); - } - _usedColumns = columnsToUpdate; + // replace the line of characters in the old _image with the + // current line of the new _image + memcpy((void*)currentLine,(const void*)newLine,columnsToUpdate*sizeof(Character)); + } - dirtyRegion |= _inputMethodData.previousPreeditRect; + // if the new _image is smaller than the previous _image, then ensure that the area + // outside the new _image is cleared + if ( linesToUpdate < _usedLines ) + { + dirtyRegion |= QRect( _leftMargin+tLx , + _topMargin+tLy+_fontHeight*linesToUpdate , + _fontWidth * this->_columns , + _fontHeight * (_usedLines-linesToUpdate) ); + } + _usedLines = linesToUpdate; + + if ( columnsToUpdate < _usedColumns ) + { + dirtyRegion |= QRect( _leftMargin+tLx+columnsToUpdate*_fontWidth , + _topMargin+tLy , + _fontWidth * (_usedColumns-columnsToUpdate) , + _fontHeight * this->_lines ); + } + _usedColumns = columnsToUpdate; - // update the parts of the display which have changed - update(dirtyRegion); + dirtyRegion |= _inputMethodData.previousPreeditRect; - if ( _hasBlinker && !_blinkTimer->isActive()) _blinkTimer->start( TEXT_BLINK_DELAY ); - if (!_hasBlinker && _blinkTimer->isActive()) { - _blinkTimer->stop(); - _blinking = false; - } - delete[] dirtyMask; - delete[] disstrU; + // update the parts of the display which have changed + update(dirtyRegion); + + if ( _hasBlinker && !_blinkTimer->isActive()) _blinkTimer->start( TEXT_BLINK_DELAY ); + if (!_hasBlinker && _blinkTimer->isActive()) { _blinkTimer->stop(); _blinking = false; } + delete[] dirtyMask; + delete[] disstrU; } void TerminalDisplay::showResizeNotification() { - if (_terminalSizeHint && isVisible()) { - if (_terminalSizeStartup) { - _terminalSizeStartup=false; - return; - } - if (!_resizeWidget) { - _resizeWidget = new QLabel(("Size: XXX x XXX"), this); - _resizeWidget->setMinimumWidth(_resizeWidget->fontMetrics().width(("Size: XXX x XXX"))); - _resizeWidget->setMinimumHeight(_resizeWidget->sizeHint().height()); - _resizeWidget->setAlignment(Qt::AlignCenter); + if (_terminalSizeHint && isVisible()) + { + if (_terminalSizeStartup) { + _terminalSizeStartup=false; + return; + } + if (!_resizeWidget) + { + _resizeWidget = new QLabel("Size: XXX x XXX", this); + _resizeWidget->setMinimumWidth(_resizeWidget->fontMetrics().width("Size: XXX x XXX")); + _resizeWidget->setMinimumHeight(_resizeWidget->sizeHint().height()); + _resizeWidget->setAlignment(Qt::AlignCenter); - _resizeWidget->setStyleSheet("background-color:palette(window);border-style:solid;border-width:1px;border-color:palette(dark)"); + _resizeWidget->setStyleSheet("background-color:palette(window);border-style:solid;border-width:1px;border-color:palette(dark)"); - _resizeTimer = new QTimer(this); - _resizeTimer->setSingleShot(true); - connect(_resizeTimer, SIGNAL(timeout()), _resizeWidget, SLOT(hide())); - } - QString sizeStr; - sizeStr.sprintf("Size: %d x %d", _columns, _lines); - _resizeWidget->setText(sizeStr); - _resizeWidget->move((width()-_resizeWidget->width())/2, - (height()-_resizeWidget->height())/2+20); - _resizeWidget->show(); - _resizeTimer->start(1000); - } + _resizeTimer = new QTimer(this); + _resizeTimer->setSingleShot(true); + connect(_resizeTimer, SIGNAL(timeout()), _resizeWidget, SLOT(hide())); + } + QString sizeStr = QString("Size: %1 x %2").arg(_columns, _lines); + _resizeWidget->setText(sizeStr); + _resizeWidget->move((width()-_resizeWidget->width())/2, + (height()-_resizeWidget->height())/2+20); + _resizeWidget->show(); + _resizeTimer->start(1000); + } } void TerminalDisplay::setBlinkingCursor(bool blink) { - _hasBlinkingCursor=blink; - - if (blink && !_blinkCursorTimer->isActive()) - _blinkCursorTimer->start(QApplication::cursorFlashTime() / 2); - - if (!blink && _blinkCursorTimer->isActive()) { - _blinkCursorTimer->stop(); - if (_cursorBlinking) - blinkCursorEvent(); - else - _cursorBlinking = false; - } + _hasBlinkingCursor=blink; + + if (blink && !_blinkCursorTimer->isActive()) + _blinkCursorTimer->start(QApplication::cursorFlashTime() / 2); + + if (!blink && _blinkCursorTimer->isActive()) + { + _blinkCursorTimer->stop(); + if (_cursorBlinking) + blinkCursorEvent(); + else + _cursorBlinking = false; + } } void TerminalDisplay::setBlinkingTextEnabled(bool blink) { _allowBlinkingText = blink; - if (blink && !_blinkTimer->isActive()) + if (blink && !_blinkTimer->isActive()) _blinkTimer->start(TEXT_BLINK_DELAY); - - if (!blink && _blinkTimer->isActive()) { + + if (!blink && _blinkTimer->isActive()) + { _blinkTimer->stop(); _blinking = false; } @@ -1167,7 +1211,8 @@ void TerminalDisplay::focusOutEvent(QFocusEvent*) void TerminalDisplay::focusInEvent(QFocusEvent*) { emit termGetFocus(); - if (_hasBlinkingCursor) { + if (_hasBlinkingCursor) + { _blinkCursorTimer->start(); } updateCursor(); @@ -1178,15 +1223,16 @@ void TerminalDisplay::focusInEvent(QFocusEvent*) void TerminalDisplay::paintEvent( QPaintEvent* pe ) { - QPainter paint(this); + QPainter paint(this); - foreach (const QRect &rect, (pe->region() & contentsRect()).rects()) { - drawBackground(paint,rect,palette().background().color(), - true /* use opacity setting */); - drawContents(paint, rect); - } - drawInputMethodPreeditString(paint,preeditRect()); - paintFilters(paint); + foreach (const QRect &rect, (pe->region() & contentsRect()).rects()) + { + drawBackground(paint,rect,palette().background().color(), + true /* use opacity setting */); + drawContents(paint, rect); + } + drawInputMethodPreeditString(paint,preeditRect()); + paintFilters(paint); } QPoint TerminalDisplay::cursorPosition() const @@ -1208,14 +1254,14 @@ QRect TerminalDisplay::preeditRect() const _topMargin + _fontHeight*cursorPosition().y(), _fontWidth*preeditLength, _fontHeight); -} +} void TerminalDisplay::drawInputMethodPreeditString(QPainter& painter , const QRect& rect) { if ( _inputMethodData.preeditString.isEmpty() ) return; - const QPoint cursorPos = cursorPosition(); + const QPoint cursorPos = cursorPosition(); bool invertColors = false; const QColor background = _colorTable[DEFAULT_BACK_COLOR].color; @@ -1226,7 +1272,7 @@ void TerminalDisplay::drawInputMethodPreeditString(QPainter& painter , const QRe drawCursor(painter,rect,foreground,background,invertColors); drawCharacters(painter,rect,_inputMethodData.preeditString,style,invertColors); - _inputMethodData.previousPreeditRect = rect; + _inputMethodData.previousPreeditRect = rect; } FilterChain* TerminalDisplay::filterChain() const @@ -1248,54 +1294,56 @@ void TerminalDisplay::paintFilters(QPainter& painter) painter.setPen( QPen(cursorCharacter.foregroundColor.color(colorTable())) ); - // iterate over hotspots identified by the display's currently active filters + // iterate over hotspots identified by the display's currently active filters // and draw appropriate visuals to indicate the presence of the hotspot QList spots = _filterChain->hotSpots(); QListIterator iter(spots); - while (iter.hasNext()) { + while (iter.hasNext()) + { Filter::HotSpot* spot = iter.next(); QRegion region; if ( spot->type() == Filter::HotSpot::Link ) { QRect r; if (spot->startLine()==spot->endLine()) { - r.setCoords( spot->startColumn()*_fontWidth + 1 + scrollBarWidth, + r.setCoords( spot->startColumn()*_fontWidth + 1 + scrollBarWidth, spot->startLine()*_fontHeight + 1, - (spot->endColumn()-1)*_fontWidth - 1 + scrollBarWidth, - (spot->endLine()+1)*_fontHeight - 1 ); + (spot->endColumn()-1)*_fontWidth - 1 + scrollBarWidth, + (spot->endLine()+1)*_fontHeight - 1 ); region |= r; } else { - r.setCoords( spot->startColumn()*_fontWidth + 1 + scrollBarWidth, + r.setCoords( spot->startColumn()*_fontWidth + 1 + scrollBarWidth, spot->startLine()*_fontHeight + 1, - (_columns-1)*_fontWidth - 1 + scrollBarWidth, - (spot->startLine()+1)*_fontHeight - 1 ); + (_columns-1)*_fontWidth - 1 + scrollBarWidth, + (spot->startLine()+1)*_fontHeight - 1 ); region |= r; for ( int line = spot->startLine()+1 ; line < spot->endLine() ; line++ ) { - r.setCoords( 0*_fontWidth + 1 + scrollBarWidth, + r.setCoords( 0*_fontWidth + 1 + scrollBarWidth, line*_fontHeight + 1, (_columns-1)*_fontWidth - 1 + scrollBarWidth, - (line+1)*_fontHeight - 1 ); + (line+1)*_fontHeight - 1 ); region |= r; } r.setCoords( 0*_fontWidth + 1 + scrollBarWidth, spot->endLine()*_fontHeight + 1, (spot->endColumn()-1)*_fontWidth - 1 + scrollBarWidth, - (spot->endLine()+1)*_fontHeight - 1 ); + (spot->endLine()+1)*_fontHeight - 1 ); region |= r; } } - for ( int line = spot->startLine() ; line <= spot->endLine() ; line++ ) { + for ( int line = spot->startLine() ; line <= spot->endLine() ; line++ ) + { int startColumn = 0; - int endColumn = _columns-1; // TODO use number of _columns which are actually - // occupied on this line rather than the width of the - // display in _columns + int endColumn = _columns-1; // TODO use number of _columns which are actually + // occupied on this line rather than the width of the + // display in _columns // ignore whitespace at the end of the lines while ( QChar(_image[loc(endColumn,line)].character).isSpace() && endColumn > 0 ) endColumn--; - + // increment here because the column which we want to set 'endColumn' to // is the first whitespace character at the end of the line endColumn++; @@ -1311,32 +1359,34 @@ void TerminalDisplay::paintFilters(QPainter& painter) // hotspots // // subtracting one pixel from all sides also prevents an edge case where - // moving the mouse outside a link could still leave it underlined + // moving the mouse outside a link could still leave it underlined // because the check below for the position of the cursor // finds it on the border of the target area QRect r; r.setCoords( startColumn*_fontWidth + 1 + scrollBarWidth, line*_fontHeight + 1, endColumn*_fontWidth - 1 + scrollBarWidth, - (line+1)*_fontHeight - 1 ); - // Underline link hotspots - if ( spot->type() == Filter::HotSpot::Link ) { + (line+1)*_fontHeight - 1 ); + // Underline link hotspots + if ( spot->type() == Filter::HotSpot::Link ) + { QFontMetrics metrics(font()); - + // find the baseline (which is the invisible line that the characters in the font sit on, // with some having tails dangling below) int baseline = r.bottom() - metrics.descent(); // find the position of the underline below that int underlinePos = baseline + metrics.underlinePos(); - if ( region.contains( mapFromGlobal(QCursor::pos()) ) ) { - painter.drawLine( r.left() , underlinePos , + if ( region.contains( mapFromGlobal(QCursor::pos()) ) ){ + painter.drawLine( r.left() , underlinePos , r.right() , underlinePos ); } } // Marker hotspots simply have a transparent rectanglular shape // drawn on top of them - else if ( spot->type() == Filter::HotSpot::Marker ) { - //TODO - Do not use a hardcoded colour for this + else if ( spot->type() == Filter::HotSpot::Marker ) + { + //TODO - Do not use a hardcoded colour for this painter.fillRect(r,QBrush(QColor(255,0,0,120))); } } @@ -1344,141 +1394,151 @@ void TerminalDisplay::paintFilters(QPainter& painter) } void TerminalDisplay::drawContents(QPainter &paint, const QRect &rect) { - QPoint tL = contentsRect().topLeft(); - int tLx = tL.x(); - int tLy = tL.y(); + QPoint tL = contentsRect().topLeft(); + int tLx = tL.x(); + int tLy = tL.y(); - int lux = qMin(_usedColumns-1, qMax(0,(rect.left() - tLx - _leftMargin ) / _fontWidth)); - int luy = qMin(_usedLines-1, qMax(0,(rect.top() - tLy - _topMargin ) / _fontHeight)); - int rlx = qMin(_usedColumns-1, qMax(0,(rect.right() - tLx - _leftMargin ) / _fontWidth)); - int rly = qMin(_usedLines-1, qMax(0,(rect.bottom() - tLy - _topMargin ) / _fontHeight)); + int lux = qMin(_usedColumns-1, qMax(0,(rect.left() - tLx - _leftMargin ) / _fontWidth)); + int luy = qMin(_usedLines-1, qMax(0,(rect.top() - tLy - _topMargin ) / _fontHeight)); + int rlx = qMin(_usedColumns-1, qMax(0,(rect.right() - tLx - _leftMargin ) / _fontWidth)); + int rly = qMin(_usedLines-1, qMax(0,(rect.bottom() - tLy - _topMargin ) / _fontHeight)); - const int bufferSize = _usedColumns; - QString unistr; - unistr.reserve(bufferSize); - for (int y = luy; y <= rly; y++) { - quint16 c = _image[loc(lux,y)].character; - int x = lux; - if (!c && x) - x--; // Search for start of multi-column character - for (; x <= rlx; x++) { - int len = 1; - int p = 0; + const int bufferSize = _usedColumns; + QString unistr; + unistr.reserve(bufferSize); + for (int y = luy; y <= rly; y++) + { + quint16 c = _image[loc(lux,y)].character; + int x = lux; + if(!c && x) + x--; // Search for start of multi-column character + for (; x <= rlx; x++) + { + int len = 1; + int p = 0; - // reset our buffer to the maximal size - unistr.resize(bufferSize); - QChar *disstrU = unistr.data(); + // reset our buffer to the maximal size + unistr.resize(bufferSize); + QChar *disstrU = unistr.data(); - // is this a single character or a sequence of characters ? - if ( _image[loc(x,y)].rendition & RE_EXTENDED_CHAR ) { - // sequence of characters - ushort extendedCharLength = 0; - ushort* chars = ExtendedCharTable::instance - .lookupExtendedChar(_image[loc(x,y)].charSequence,extendedCharLength); - for ( int index = 0 ; index < extendedCharLength ; index++ ) { - Q_ASSERT( p < bufferSize ); - disstrU[p++] = chars[index]; - } - } else { - // single character - c = _image[loc(x,y)].character; - if (c) { - Q_ASSERT( p < bufferSize ); - disstrU[p++] = c; //fontMap(c); - } - } + // is this a single character or a sequence of characters ? + if ( _image[loc(x,y)].rendition & RE_EXTENDED_CHAR ) + { + // sequence of characters + ushort extendedCharLength = 0; + ushort* chars = ExtendedCharTable::instance + .lookupExtendedChar(_image[loc(x,y)].charSequence,extendedCharLength); + for ( int index = 0 ; index < extendedCharLength ; index++ ) + { + Q_ASSERT( p < bufferSize ); + disstrU[p++] = chars[index]; + } + } + else + { + // single character + c = _image[loc(x,y)].character; + if (c) + { + Q_ASSERT( p < bufferSize ); + disstrU[p++] = c; //fontMap(c); + } + } - bool lineDraw = isLineChar(c); - bool doubleWidth = (_image[ qMin(loc(x,y)+1,_imageSize) ].character == 0); - CharacterColor currentForeground = _image[loc(x,y)].foregroundColor; - CharacterColor currentBackground = _image[loc(x,y)].backgroundColor; - quint8 currentRendition = _image[loc(x,y)].rendition; - - while (x+len <= rlx && - _image[loc(x+len,y)].foregroundColor == currentForeground && - _image[loc(x+len,y)].backgroundColor == currentBackground && - _image[loc(x+len,y)].rendition == currentRendition && - (_image[ qMin(loc(x+len,y)+1,_imageSize) ].character == 0) == doubleWidth && - isLineChar( c = _image[loc(x+len,y)].character) == lineDraw) { // Assignment! - if (c) - disstrU[p++] = c; //fontMap(c); - if (doubleWidth) // assert((_image[loc(x+len,y)+1].character == 0)), see above if condition - len++; // Skip trailing part of multi-column character - len++; - } - if ((x+len < _usedColumns) && (!_image[loc(x+len,y)].character)) - len++; // Adjust for trailing part of multi-column character + bool lineDraw = isLineChar(c); + bool doubleWidth = (_image[ qMin(loc(x,y)+1,_imageSize) ].character == 0); + CharacterColor currentForeground = _image[loc(x,y)].foregroundColor; + CharacterColor currentBackground = _image[loc(x,y)].backgroundColor; + quint8 currentRendition = _image[loc(x,y)].rendition; + + while (x+len <= rlx && + _image[loc(x+len,y)].foregroundColor == currentForeground && + _image[loc(x+len,y)].backgroundColor == currentBackground && + _image[loc(x+len,y)].rendition == currentRendition && + (_image[ qMin(loc(x+len,y)+1,_imageSize) ].character == 0) == doubleWidth && + isLineChar( c = _image[loc(x+len,y)].character) == lineDraw) // Assignment! + { + if (c) + disstrU[p++] = c; //fontMap(c); + if (doubleWidth) // assert((_image[loc(x+len,y)+1].character == 0)), see above if condition + len++; // Skip trailing part of multi-column character + len++; + } + if ((x+len < _usedColumns) && (!_image[loc(x+len,y)].character)) + len++; // Adjust for trailing part of multi-column character bool save__fixedFont = _fixedFont; - if (lineDraw) - _fixedFont = false; - if (doubleWidth) - _fixedFont = false; - unistr.resize(p); + if (lineDraw) + _fixedFont = false; + if (doubleWidth) + _fixedFont = false; + unistr.resize(p); - // Create a text scaling matrix for double width and double height lines. - QMatrix textScale; + // Create a text scaling matrix for double width and double height lines. + QMatrix textScale; - if (y < _lineProperties.size()) { - if (_lineProperties[y] & LINE_DOUBLEWIDTH) - textScale.scale(2,1); + if (y < _lineProperties.size()) + { + if (_lineProperties[y] & LINE_DOUBLEWIDTH) + textScale.scale(2,1); - if (_lineProperties[y] & LINE_DOUBLEHEIGHT) - textScale.scale(1,2); - } + if (_lineProperties[y] & LINE_DOUBLEHEIGHT) + textScale.scale(1,2); + } - //Apply text scaling matrix. - paint.setWorldMatrix(textScale, true); + //Apply text scaling matrix. + paint.setWorldMatrix(textScale, true); - //calculate the area in which the text will be drawn - QRect textArea = QRect( _leftMargin+tLx+_fontWidth*x , _topMargin+tLy+_fontHeight*y , _fontWidth*len , _fontHeight); + //calculate the area in which the text will be drawn + QRect textArea = QRect( _leftMargin+tLx+_fontWidth*x , _topMargin+tLy+_fontHeight*y , _fontWidth*len , _fontHeight); + + //move the calculated area to take account of scaling applied to the painter. + //the position of the area from the origin (0,0) is scaled + //by the opposite of whatever + //transformation has been applied to the painter. this ensures that + //painting does actually start from textArea.topLeft() + //(instead of textArea.topLeft() * painter-scale) + textArea.moveTopLeft( textScale.inverted().map(textArea.topLeft()) ); + + //paint text fragment + drawTextFragment( paint, + textArea, + unistr, + &_image[loc(x,y)] ); //, + //0, + //!_isPrinting ); + + _fixedFont = save__fixedFont; + + //reset back to single-width, single-height _lines + paint.setWorldMatrix(textScale.inverted(), true); - //move the calculated area to take account of scaling applied to the painter. - //the position of the area from the origin (0,0) is scaled - //by the opposite of whatever - //transformation has been applied to the painter. this ensures that - //painting does actually start from textArea.topLeft() - //(instead of textArea.topLeft() * painter-scale) - textArea.moveTopLeft( textScale.inverted().map(textArea.topLeft()) ); - - //paint text fragment - drawTextFragment( paint, - textArea, - unistr, - &_image[loc(x,y)] ); //, - //0, - //!_isPrinting ); - - _fixedFont = save__fixedFont; - - //reset back to single-width, single-height _lines - paint.setWorldMatrix(textScale.inverted(), true); - - if (y < _lineProperties.size()-1) { - //double-height _lines are represented by two adjacent _lines - //containing the same characters - //both _lines will have the LINE_DOUBLEHEIGHT attribute. - //If the current line has the LINE_DOUBLEHEIGHT attribute, - //we can therefore skip the next line - if (_lineProperties[y] & LINE_DOUBLEHEIGHT) - y++; - } - - x += len - 1; - } + if (y < _lineProperties.size()-1) + { + //double-height _lines are represented by two adjacent _lines + //containing the same characters + //both _lines will have the LINE_DOUBLEHEIGHT attribute. + //If the current line has the LINE_DOUBLEHEIGHT attribute, + //we can therefore skip the next line + if (_lineProperties[y] & LINE_DOUBLEHEIGHT) + y++; + } + + x += len - 1; } + } } void TerminalDisplay::blinkEvent() { - if (!_allowBlinkingText) return; + if (!_allowBlinkingText) return; - _blinking = !_blinking; + _blinking = !_blinking; - //TODO: Optimize to only repaint the areas of the widget - // where there is blinking text - // rather than repainting the whole widget. - update(); + //TODO: Optimize to only repaint the areas of the widget + // where there is blinking text + // rather than repainting the whole widget. + update(); } QRect TerminalDisplay::imageToWidget(const QRect& imageArea) const @@ -1494,14 +1554,14 @@ QRect TerminalDisplay::imageToWidget(const QRect& imageArea) const void TerminalDisplay::updateCursor() { - QRect cursorRect = imageToWidget( QRect(cursorPosition(),QSize(1,1)) ); - update(cursorRect); + QRect cursorRect = imageToWidget( QRect(cursorPosition(),QSize(1,1)) ); + update(cursorRect); } void TerminalDisplay::blinkCursorEvent() { - _cursorBlinking = !_cursorBlinking; - updateCursor(); + _cursorBlinking = !_cursorBlinking; + updateCursor(); } /* ------------------------------------------------------------------------- */ @@ -1512,60 +1572,64 @@ void TerminalDisplay::blinkCursorEvent() void TerminalDisplay::resizeEvent(QResizeEvent*) { - updateImageSize(); + updateImageSize(); } void TerminalDisplay::propagateSize() { - if (_isFixedSize) { - setSize(_columns, _lines); - QWidget::setFixedSize(sizeHint()); - parentWidget()->adjustSize(); - parentWidget()->setFixedSize(parentWidget()->sizeHint()); - return; - } - if (_image) - updateImageSize(); + if (_isFixedSize) + { + setSize(_columns, _lines); + QWidget::setFixedSize(sizeHint()); + parentWidget()->adjustSize(); + parentWidget()->setFixedSize(parentWidget()->sizeHint()); + return; + } + if (_image) + updateImageSize(); } void TerminalDisplay::updateImageSize() { - Character* oldimg = _image; - int oldlin = _lines; - int oldcol = _columns; + Character* oldimg = _image; + int oldlin = _lines; + int oldcol = _columns; - makeImage(); + makeImage(); + + // copy the old image to reduce flicker + int lines = qMin(oldlin,_lines); + int columns = qMin(oldcol,_columns); - // copy the old image to reduce flicker - int lines = qMin(oldlin,_lines); - int columns = qMin(oldcol,_columns); - - if (oldimg) { - for (int line = 0; line < lines; line++) { - memcpy((void*)&_image[_columns*line], - (void*)&oldimg[oldcol*line],columns*sizeof(Character)); - } - delete[] oldimg; + if (oldimg) + { + for (int line = 0; line < lines; line++) + { + memcpy((void*)&_image[_columns*line], + (void*)&oldimg[oldcol*line],columns*sizeof(Character)); } + delete[] oldimg; + } - if (_screenWindow) - _screenWindow->setWindowLines(_lines); + if (_screenWindow) + _screenWindow->setWindowLines(_lines); - _resizing = (oldlin!=_lines) || (oldcol!=_columns); + _resizing = (oldlin!=_lines) || (oldcol!=_columns); - if ( _resizing ) { - showResizeNotification(); - emit changedContentSizeSignal(_contentHeight, _contentWidth); // expose resizeEvent - } - - _resizing = false; + if ( _resizing ) + { + showResizeNotification(); + emit changedContentSizeSignal(_contentHeight, _contentWidth); // expose resizeEvent + } + + _resizing = false; } -//showEvent and hideEvent are reimplemented here so that it appears to other classes that the +//showEvent and hideEvent are reimplemented here so that it appears to other classes that the //display has been resized when the display is hidden or shown. // //TODO: Perhaps it would be better to have separate signals for show and hide instead of using -//the same signal as the one for a content size change +//the same signal as the one for a content size change void TerminalDisplay::showEvent(QShowEvent*) { emit changedContentSizeSignal(_contentHeight,_contentWidth); @@ -1583,444 +1647,466 @@ void TerminalDisplay::hideEvent(QHideEvent*) void TerminalDisplay::scrollBarPositionChanged(int) { - if ( !_screenWindow ) - return; + if ( !_screenWindow ) + return; - _screenWindow->scrollTo( _scrollBar->value() ); + _screenWindow->scrollTo( _scrollBar->value() ); - // if the thumb has been moved to the bottom of the _scrollBar then set - // the display to automatically track new output, - // that is, scroll down automatically - // to how new _lines as they are added - const bool atEndOfOutput = (_scrollBar->value() == _scrollBar->maximum()); - _screenWindow->setTrackOutput( atEndOfOutput ); + // if the thumb has been moved to the bottom of the _scrollBar then set + // the display to automatically track new output, + // that is, scroll down automatically + // to how new _lines as they are added + const bool atEndOfOutput = (_scrollBar->value() == _scrollBar->maximum()); + _screenWindow->setTrackOutput( atEndOfOutput ); - updateImage(); + updateImage(); } void TerminalDisplay::setScroll(int cursor, int slines) { - // update _scrollBar if the range or value has changed, - // otherwise return - // - // setting the range or value of a _scrollBar will always trigger - // a repaint, so it should be avoided if it is not necessary - if ( _scrollBar->minimum() == 0 && - _scrollBar->maximum() == (slines - _lines) && - _scrollBar->value() == cursor ) { + // update _scrollBar if the range or value has changed, + // otherwise return + // + // setting the range or value of a _scrollBar will always trigger + // a repaint, so it should be avoided if it is not necessary + if ( _scrollBar->minimum() == 0 && + _scrollBar->maximum() == (slines - _lines) && + _scrollBar->value() == cursor ) + { return; - } + } - disconnect(_scrollBar, SIGNAL(valueChanged(int)), this, SLOT(scrollBarPositionChanged(int))); - _scrollBar->setRange(0,slines - _lines); - _scrollBar->setSingleStep(1); - _scrollBar->setPageStep(_lines); - _scrollBar->setValue(cursor); - connect(_scrollBar, SIGNAL(valueChanged(int)), this, SLOT(scrollBarPositionChanged(int))); + disconnect(_scrollBar, SIGNAL(valueChanged(int)), this, SLOT(scrollBarPositionChanged(int))); + _scrollBar->setRange(0,slines - _lines); + _scrollBar->setSingleStep(1); + _scrollBar->setPageStep(_lines); + _scrollBar->setValue(cursor); + connect(_scrollBar, SIGNAL(valueChanged(int)), this, SLOT(scrollBarPositionChanged(int))); } void TerminalDisplay::setScrollBarPosition(ScrollBarPosition position) { - if (_scrollbarLocation == position) - return; + if (_scrollbarLocation == position) + return; + + if ( position == NoScrollBar ) + _scrollBar->hide(); + else + _scrollBar->show(); - if ( position == NoScrollBar ) - _scrollBar->hide(); - else - _scrollBar->show(); - - _topMargin = _leftMargin = 1; - _scrollbarLocation = position; - - propagateSize(); - update(); + _topMargin = _leftMargin = 1; + _scrollbarLocation = position; + + propagateSize(); + update(); } void TerminalDisplay::mousePressEvent(QMouseEvent* ev) { - if ( _possibleTripleClick && (ev->button()==Qt::LeftButton) ) { - mouseTripleClickEvent(ev); - return; + if ( _possibleTripleClick && (ev->button()==Qt::LeftButton) ) { + mouseTripleClickEvent(ev); + return; + } + + if ( !contentsRect().contains(ev->pos()) ) return; + + if ( !_screenWindow ) return; + + int charLine; + int charColumn; + getCharacterPosition(ev->pos(),charLine,charColumn); + QPoint pos = QPoint(charColumn,charLine); + + if ( ev->button() == Qt::LeftButton) + { + _lineSelectionMode = false; + _wordSelectionMode = false; + + emit isBusySelecting(true); // Keep it steady... + // Drag only when the Control key is hold + bool selected = false; + + // The receiver of the testIsSelected() signal will adjust + // 'selected' accordingly. + //emit testIsSelected(pos.x(), pos.y(), selected); + + selected = _screenWindow->isSelected(pos.x(),pos.y()); + + if ((!_ctrlDrag || ev->modifiers() & Qt::ControlModifier) && selected ) { + // The user clicked inside selected text + dragInfo.state = diPending; + dragInfo.start = ev->pos(); } + else { + // No reason to ever start a drag event + dragInfo.state = diNone; - if ( !contentsRect().contains(ev->pos()) ) return; + _preserveLineBreaks = !( ( ev->modifiers() & Qt::ControlModifier ) && !(ev->modifiers() & Qt::AltModifier) ); + _columnSelectionMode = (ev->modifiers() & Qt::AltModifier) && (ev->modifiers() & Qt::ControlModifier); - if ( !_screenWindow ) return; + if (_mouseMarks || (ev->modifiers() & Qt::ShiftModifier)) + { + _screenWindow->clearSelection(); - int charLine; - int charColumn; - getCharacterPosition(ev->pos(),charLine,charColumn); - QPoint pos = QPoint(charColumn,charLine); - - if ( ev->button() == Qt::LeftButton) { - _lineSelectionMode = false; - _wordSelectionMode = false; - - emit isBusySelecting(true); // Keep it steady... - // Drag only when the Control key is hold - bool selected = false; - - // The receiver of the testIsSelected() signal will adjust - // 'selected' accordingly. - //emit testIsSelected(pos.x(), pos.y(), selected); - - selected = _screenWindow->isSelected(pos.x(),pos.y()); - - if ((!_ctrlDrag || ev->modifiers() & Qt::ControlModifier) && selected ) { - // The user clicked inside selected text - dragInfo.state = diPending; - dragInfo.start = ev->pos(); - } else { - // No reason to ever start a drag event - dragInfo.state = diNone; - - _preserveLineBreaks = !( ( ev->modifiers() & Qt::ControlModifier ) && !(ev->modifiers() & Qt::AltModifier) ); - _columnSelectionMode = (ev->modifiers() & Qt::AltModifier) && (ev->modifiers() & Qt::ControlModifier); - - if (_mouseMarks || (ev->modifiers() & Qt::ShiftModifier)) { - _screenWindow->clearSelection(); - - //emit clearSelectionSignal(); - pos.ry() += _scrollBar->value(); - _iPntSel = _pntSel = pos; - _actSel = 1; // left mouse button pressed but nothing selected yet. - - } else { - emit mouseSignal( 0, charColumn + 1, charLine + 1 +_scrollBar->value() -_scrollBar->maximum() , 0); - } - } - } else if ( ev->button() == Qt::MidButton ) { - if ( _mouseMarks || (!_mouseMarks && (ev->modifiers() & Qt::ShiftModifier)) ) - emitSelection(true,ev->modifiers() & Qt::ControlModifier); - else - emit mouseSignal( 1, charColumn +1, charLine +1 +_scrollBar->value() -_scrollBar->maximum() , 0); - } else if ( ev->button() == Qt::RightButton ) { - if (_mouseMarks || (ev->modifiers() & Qt::ShiftModifier)) - emit configureRequest(ev->pos()); - else - emit mouseSignal( 2, charColumn +1, charLine +1 +_scrollBar->value() -_scrollBar->maximum() , 0); + //emit clearSelectionSignal(); + pos.ry() += _scrollBar->value(); + _iPntSel = _pntSel = pos; + _actSel = 1; // left mouse button pressed but nothing selected yet. + + } + else + { + emit mouseSignal( 0, charColumn + 1, charLine + 1 +_scrollBar->value() -_scrollBar->maximum() , 0); + } } + } + else if ( ev->button() == Qt::MidButton ) + { + if ( _mouseMarks || (!_mouseMarks && (ev->modifiers() & Qt::ShiftModifier)) ) + emitSelection(true,ev->modifiers() & Qt::ControlModifier); + else + emit mouseSignal( 1, charColumn +1, charLine +1 +_scrollBar->value() -_scrollBar->maximum() , 0); + } + else if ( ev->button() == Qt::RightButton ) + { + if (_mouseMarks || (ev->modifiers() & Qt::ShiftModifier)) + emit configureRequest(ev->pos()); + else + emit mouseSignal( 2, charColumn +1, charLine +1 +_scrollBar->value() -_scrollBar->maximum() , 0); + } } QList TerminalDisplay::filterActions(const QPoint& position) { - int charLine, charColumn; - getCharacterPosition(position,charLine,charColumn); + int charLine, charColumn; + getCharacterPosition(position,charLine,charColumn); - Filter::HotSpot* spot = _filterChain->hotSpotAt(charLine,charColumn); + Filter::HotSpot* spot = _filterChain->hotSpotAt(charLine,charColumn); - return spot ? spot->actions() : QList(); + return spot ? spot->actions() : QList(); } void TerminalDisplay::mouseMoveEvent(QMouseEvent* ev) { - int charLine = 0; - int charColumn = 0; - int scrollBarWidth = (_scrollbarLocation == ScrollBarLeft) ? _scrollBar->width() : 0; + int charLine = 0; + int charColumn = 0; + int scrollBarWidth = (_scrollbarLocation == ScrollBarLeft) ? _scrollBar->width() : 0; - getCharacterPosition(ev->pos(),charLine,charColumn); + getCharacterPosition(ev->pos(),charLine,charColumn); - // handle filters - // change link hot-spot appearance on mouse-over - Filter::HotSpot* spot = _filterChain->hotSpotAt(charLine,charColumn); - if ( spot && spot->type() == Filter::HotSpot::Link) { - QRegion previousHotspotArea = _mouseOverHotspotArea; - _mouseOverHotspotArea = QRegion(); - QRect r; - if (spot->startLine()==spot->endLine()) { - r.setCoords( spot->startColumn()*_fontWidth + scrollBarWidth, - spot->startLine()*_fontHeight, - spot->endColumn()*_fontWidth + scrollBarWidth, - (spot->endLine()+1)*_fontHeight - 1 ); - _mouseOverHotspotArea |= r; - } else { - r.setCoords( spot->startColumn()*_fontWidth + scrollBarWidth, - spot->startLine()*_fontHeight, - _columns*_fontWidth - 1 + scrollBarWidth, - (spot->startLine()+1)*_fontHeight ); - _mouseOverHotspotArea |= r; - for ( int line = spot->startLine()+1 ; line < spot->endLine() ; line++ ) { - r.setCoords( 0*_fontWidth + scrollBarWidth, - line*_fontHeight, - _columns*_fontWidth + scrollBarWidth, - (line+1)*_fontHeight ); - _mouseOverHotspotArea |= r; - } - r.setCoords( 0*_fontWidth + scrollBarWidth, - spot->endLine()*_fontHeight, - spot->endColumn()*_fontWidth + scrollBarWidth, - (spot->endLine()+1)*_fontHeight ); + // handle filters + // change link hot-spot appearance on mouse-over + Filter::HotSpot* spot = _filterChain->hotSpotAt(charLine,charColumn); + if ( spot && spot->type() == Filter::HotSpot::Link) + { + QRegion previousHotspotArea = _mouseOverHotspotArea; + _mouseOverHotspotArea = QRegion(); + QRect r; + if (spot->startLine()==spot->endLine()) { + r.setCoords( spot->startColumn()*_fontWidth + scrollBarWidth, + spot->startLine()*_fontHeight, + spot->endColumn()*_fontWidth + scrollBarWidth, + (spot->endLine()+1)*_fontHeight - 1 ); + _mouseOverHotspotArea |= r; + } else { + r.setCoords( spot->startColumn()*_fontWidth + scrollBarWidth, + spot->startLine()*_fontHeight, + _columns*_fontWidth - 1 + scrollBarWidth, + (spot->startLine()+1)*_fontHeight ); + _mouseOverHotspotArea |= r; + for ( int line = spot->startLine()+1 ; line < spot->endLine() ; line++ ) { + r.setCoords( 0*_fontWidth + scrollBarWidth, + line*_fontHeight, + _columns*_fontWidth + scrollBarWidth, + (line+1)*_fontHeight ); _mouseOverHotspotArea |= r; } - // display tooltips when mousing over links - // TODO: Extend this to work with filter types other than links - const QString& tooltip = spot->tooltip(); - if ( !tooltip.isEmpty() ) { - QToolTip::showText( mapToGlobal(ev->pos()) , tooltip , this , _mouseOverHotspotArea.boundingRect() ); - } + r.setCoords( 0*_fontWidth + scrollBarWidth, + spot->endLine()*_fontHeight, + spot->endColumn()*_fontWidth + scrollBarWidth, + (spot->endLine()+1)*_fontHeight ); + _mouseOverHotspotArea |= r; + } + // display tooltips when mousing over links + // TODO: Extend this to work with filter types other than links + const QString& tooltip = spot->tooltip(); + if ( !tooltip.isEmpty() ) + { + QToolTip::showText( mapToGlobal(ev->pos()) , tooltip , this , _mouseOverHotspotArea.boundingRect() ); + } - update( _mouseOverHotspotArea | previousHotspotArea ); - } else if ( !_mouseOverHotspotArea.isEmpty() ) { + update( _mouseOverHotspotArea | previousHotspotArea ); + } + else if ( !_mouseOverHotspotArea.isEmpty() ) + { update( _mouseOverHotspotArea ); // set hotspot area to an invalid rectangle _mouseOverHotspotArea = QRegion(); + } + + // for auto-hiding the cursor, we need mouseTracking + if (ev->buttons() == Qt::NoButton ) return; + + // if the terminal is interested in mouse movements + // then emit a mouse movement signal, unless the shift + // key is being held down, which overrides this. + if (!_mouseMarks && !(ev->modifiers() & Qt::ShiftModifier)) + { + int button = 3; + if (ev->buttons() & Qt::LeftButton) + button = 0; + if (ev->buttons() & Qt::MidButton) + button = 1; + if (ev->buttons() & Qt::RightButton) + button = 2; + + + emit mouseSignal( button, + charColumn + 1, + charLine + 1 +_scrollBar->value() -_scrollBar->maximum(), + 1 ); + + return; + } + + if (dragInfo.state == diPending) + { + // we had a mouse down, but haven't confirmed a drag yet + // if the mouse has moved sufficiently, we will confirm + +// int distance = KGlobalSettings::dndEventDelay(); + int distance = QApplication::startDragDistance(); + if ( ev->x() > dragInfo.start.x() + distance || ev->x() < dragInfo.start.x() - distance || + ev->y() > dragInfo.start.y() + distance || ev->y() < dragInfo.start.y() - distance) + { + // we've left the drag square, we can start a real drag operation now + emit isBusySelecting(false); // Ok.. we can breath again. + + _screenWindow->clearSelection(); + doDrag(); } + return; + } + else if (dragInfo.state == diDragging) + { + // this isn't technically needed because mouseMoveEvent is suppressed during + // Qt drag operations, replaced by dragMoveEvent + return; + } - // for auto-hiding the cursor, we need mouseTracking - if (ev->buttons() == Qt::NoButton ) return; + if (_actSel == 0) return; - // if the terminal is interested in mouse movements - // then emit a mouse movement signal, unless the shift - // key is being held down, which overrides this. - if (!_mouseMarks && !(ev->modifiers() & Qt::ShiftModifier)) { - int button = 3; - if (ev->buttons() & Qt::LeftButton) - button = 0; - if (ev->buttons() & Qt::MidButton) - button = 1; - if (ev->buttons() & Qt::RightButton) - button = 2; + // don't extend selection while pasting + if (ev->buttons() & Qt::MidButton) return; - - emit mouseSignal( button, - charColumn + 1, - charLine + 1 +_scrollBar->value() -_scrollBar->maximum(), - 1 ); - - return; - } - - if (dragInfo.state == diPending) { - // we had a mouse down, but haven't confirmed a drag yet - // if the mouse has moved sufficiently, we will confirm - //! \todo TODO/FIXME: obtain some sane value - int distance = 10; //KGlobalSettings::dndEventDelay(); - if ( ev->x() > dragInfo.start.x() + distance || ev->x() < dragInfo.start.x() - distance || - ev->y() > dragInfo.start.y() + distance || ev->y() < dragInfo.start.y() - distance) { - // we've left the drag square, we can start a real drag operation now - emit isBusySelecting(false); // Ok.. we can breath again. - - _screenWindow->clearSelection(); - doDrag(); - } - return; - } else if (dragInfo.state == diDragging) { - // this isn't technically needed because mouseMoveEvent is suppressed during - // Qt drag operations, replaced by dragMoveEvent - return; - } - - if (_actSel == 0) return; - -// don't extend selection while pasting - if (ev->buttons() & Qt::MidButton) return; - - extendSelection( ev->pos() ); + extendSelection( ev->pos() ); } void TerminalDisplay::extendSelection( const QPoint& position ) { - QPoint pos = position; + QPoint pos = position; - if ( !_screenWindow ) - return; + if ( !_screenWindow ) + return; - //if ( !contentsRect().contains(ev->pos()) ) return; - QPoint tL = contentsRect().topLeft(); - int tLx = tL.x(); - int tLy = tL.y(); - int scroll = _scrollBar->value(); + //if ( !contentsRect().contains(ev->pos()) ) return; + QPoint tL = contentsRect().topLeft(); + int tLx = tL.x(); + int tLy = tL.y(); + int scroll = _scrollBar->value(); - // we're in the process of moving the mouse with the left button pressed - // the mouse cursor will kept caught within the bounds of the text in - // this widget. + // we're in the process of moving the mouse with the left button pressed + // the mouse cursor will kept caught within the bounds of the text in + // this widget. - int linesBeyondWidget = 0; + int linesBeyondWidget = 0; - QRect textBounds(tLx + _leftMargin, + QRect textBounds(tLx + _leftMargin, tLy + _topMargin, - _usedColumns*_fontWidth-1, - _usedLines*_fontHeight-1); + _usedColumns*_fontWidth-1, + _usedLines*_fontHeight-1); - // Adjust position within text area bounds. - QPoint oldpos = pos; + // Adjust position within text area bounds. + QPoint oldpos = pos; + + pos.setX( qBound(textBounds.left(),pos.x(),textBounds.right()) ); + pos.setY( qBound(textBounds.top(),pos.y(),textBounds.bottom()) ); - pos.setX( qBound(textBounds.left(),pos.x(),textBounds.right()) ); - pos.setY( qBound(textBounds.top(),pos.y(),textBounds.bottom()) ); + if ( oldpos.y() > textBounds.bottom() ) + { + linesBeyondWidget = (oldpos.y()-textBounds.bottom()) / _fontHeight; + _scrollBar->setValue(_scrollBar->value()+linesBeyondWidget+1); // scrollforward + } + if ( oldpos.y() < textBounds.top() ) + { + linesBeyondWidget = (textBounds.top()-oldpos.y()) / _fontHeight; + _scrollBar->setValue(_scrollBar->value()-linesBeyondWidget-1); // history + } - if ( oldpos.y() > textBounds.bottom() ) { - linesBeyondWidget = (oldpos.y()-textBounds.bottom()) / _fontHeight; - _scrollBar->setValue(_scrollBar->value()+linesBeyondWidget+1); // scrollforward - } - if ( oldpos.y() < textBounds.top() ) { - linesBeyondWidget = (textBounds.top()-oldpos.y()) / _fontHeight; - _scrollBar->setValue(_scrollBar->value()-linesBeyondWidget-1); // history + int charColumn = 0; + int charLine = 0; + getCharacterPosition(pos,charLine,charColumn); + + QPoint here = QPoint(charColumn,charLine); //QPoint((pos.x()-tLx-_leftMargin+(_fontWidth/2))/_fontWidth,(pos.y()-tLy-_topMargin)/_fontHeight); + QPoint ohere; + QPoint _iPntSelCorr = _iPntSel; + _iPntSelCorr.ry() -= _scrollBar->value(); + QPoint _pntSelCorr = _pntSel; + _pntSelCorr.ry() -= _scrollBar->value(); + bool swapping = false; + + if ( _wordSelectionMode ) + { + // Extend to word boundaries + int i; + QChar selClass; + + bool left_not_right = ( here.y() < _iPntSelCorr.y() || + ( here.y() == _iPntSelCorr.y() && here.x() < _iPntSelCorr.x() ) ); + bool old_left_not_right = ( _pntSelCorr.y() < _iPntSelCorr.y() || + ( _pntSelCorr.y() == _iPntSelCorr.y() && _pntSelCorr.x() < _iPntSelCorr.x() ) ); + swapping = left_not_right != old_left_not_right; + + // Find left (left_not_right ? from here : from start) + QPoint left = left_not_right ? here : _iPntSelCorr; + i = loc(left.x(),left.y()); + if (i>=0 && i<=_imageSize) { + selClass = charClass(_image[i].character); + while ( ((left.x()>0) || (left.y()>0 && (_lineProperties[left.y()-1] & LINE_WRAPPED) )) + && charClass(_image[i-1].character) == selClass ) + { i--; if (left.x()>0) left.rx()--; else {left.rx()=_usedColumns-1; left.ry()--;} } } - int charColumn = 0; - int charLine = 0; - getCharacterPosition(pos,charLine,charColumn); - - QPoint here = QPoint(charColumn,charLine); //QPoint((pos.x()-tLx-_leftMargin+(_fontWidth/2))/_fontWidth,(pos.y()-tLy-_topMargin)/_fontHeight); - QPoint ohere; - QPoint _iPntSelCorr = _iPntSel; - _iPntSelCorr.ry() -= _scrollBar->value(); - QPoint _pntSelCorr = _pntSel; - _pntSelCorr.ry() -= _scrollBar->value(); - bool swapping = false; - - if ( _wordSelectionMode ) { - // Extend to word boundaries - int i; - QChar selClass; - - bool left_not_right = ( here.y() < _iPntSelCorr.y() || - ( here.y() == _iPntSelCorr.y() && here.x() < _iPntSelCorr.x() ) ); - bool old_left_not_right = ( _pntSelCorr.y() < _iPntSelCorr.y() || - ( _pntSelCorr.y() == _iPntSelCorr.y() && _pntSelCorr.x() < _iPntSelCorr.x() ) ); - swapping = left_not_right != old_left_not_right; - - // Find left (left_not_right ? from here : from start) - QPoint left = left_not_right ? here : _iPntSelCorr; - i = loc(left.x(),left.y()); - if (i>=0 && i<=_imageSize) { - selClass = charClass(_image[i].character); - while ( ((left.x()>0) || (left.y()>0 && (_lineProperties[left.y()-1] & LINE_WRAPPED) )) - && charClass(_image[i-1].character) == selClass ) { - i--; - if (left.x()>0) left.rx()--; - else { - left.rx()=_usedColumns-1; - left.ry()--; - } - } - } - - // Find left (left_not_right ? from start : from here) - QPoint right = left_not_right ? _iPntSelCorr : here; - i = loc(right.x(),right.y()); - if (i>=0 && i<=_imageSize) { - selClass = charClass(_image[i].character); - while ( ((right.x()<_usedColumns-1) || (right.y()<_usedLines-1 && (_lineProperties[right.y()] & LINE_WRAPPED) )) - && charClass(_image[i+1].character) == selClass ) { - i++; - if (right.x()<_usedColumns-1) right.rx()++; - else { - right.rx()=0; - right.ry()++; - } - } - } - - // Pick which is start (ohere) and which is extension (here) - if ( left_not_right ) { - here = left; - ohere = right; - } else { - here = right; - ohere = left; - } - ohere.rx()++; + // Find left (left_not_right ? from start : from here) + QPoint right = left_not_right ? _iPntSelCorr : here; + i = loc(right.x(),right.y()); + if (i>=0 && i<=_imageSize) { + selClass = charClass(_image[i].character); + while( ((right.x()<_usedColumns-1) || (right.y()<_usedLines-1 && (_lineProperties[right.y()] & LINE_WRAPPED) )) + && charClass(_image[i+1].character) == selClass ) + { i++; if (right.x()<_usedColumns-1) right.rx()++; else {right.rx()=0; right.ry()++; } } } - if ( _lineSelectionMode ) { - // Extend to complete line - bool above_not_below = ( here.y() < _iPntSelCorr.y() ); + // Pick which is start (ohere) and which is extension (here) + if ( left_not_right ) + { + here = left; ohere = right; + } + else + { + here = right; ohere = left; + } + ohere.rx()++; + } - QPoint above = above_not_below ? here : _iPntSelCorr; - QPoint below = above_not_below ? _iPntSelCorr : here; + if ( _lineSelectionMode ) + { + // Extend to complete line + bool above_not_below = ( here.y() < _iPntSelCorr.y() ); - while (above.y()>0 && (_lineProperties[above.y()-1] & LINE_WRAPPED) ) - above.ry()--; - while (below.y()<_usedLines-1 && (_lineProperties[below.y()] & LINE_WRAPPED) ) - below.ry()++; + QPoint above = above_not_below ? here : _iPntSelCorr; + QPoint below = above_not_below ? _iPntSelCorr : here; - above.setX(0); - below.setX(_usedColumns-1); + while (above.y()>0 && (_lineProperties[above.y()-1] & LINE_WRAPPED) ) + above.ry()--; + while (below.y()<_usedLines-1 && (_lineProperties[below.y()] & LINE_WRAPPED) ) + below.ry()++; - // Pick which is start (ohere) and which is extension (here) - if ( above_not_below ) { - here = above; - ohere = below; - } else { - here = below; - ohere = above; - } + above.setX(0); + below.setX(_usedColumns-1); - QPoint newSelBegin = QPoint( ohere.x(), ohere.y() ); - swapping = !(_tripleSelBegin==newSelBegin); - _tripleSelBegin = newSelBegin; - - ohere.rx()++; + // Pick which is start (ohere) and which is extension (here) + if ( above_not_below ) + { + here = above; ohere = below; + } + else + { + here = below; ohere = above; } - int offset = 0; - if ( !_wordSelectionMode && !_lineSelectionMode ) { - int i; - QChar selClass; + QPoint newSelBegin = QPoint( ohere.x(), ohere.y() ); + swapping = !(_tripleSelBegin==newSelBegin); + _tripleSelBegin = newSelBegin; - bool left_not_right = ( here.y() < _iPntSelCorr.y() || - ( here.y() == _iPntSelCorr.y() && here.x() < _iPntSelCorr.x() ) ); - bool old_left_not_right = ( _pntSelCorr.y() < _iPntSelCorr.y() || - ( _pntSelCorr.y() == _iPntSelCorr.y() && _pntSelCorr.x() < _iPntSelCorr.x() ) ); - swapping = left_not_right != old_left_not_right; + ohere.rx()++; + } - // Find left (left_not_right ? from here : from start) - QPoint left = left_not_right ? here : _iPntSelCorr; + int offset = 0; + if ( !_wordSelectionMode && !_lineSelectionMode ) + { + int i; + QChar selClass; - // Find left (left_not_right ? from start : from here) - QPoint right = left_not_right ? _iPntSelCorr : here; - if ( right.x() > 0 && !_columnSelectionMode ) { - i = loc(right.x(),right.y()); - if (i>=0 && i<=_imageSize) { - selClass = charClass(_image[i-1].character); - /* if (selClass == ' ') - { - while ( right.x() < _usedColumns-1 && charClass(_image[i+1].character) == selClass && (right.y()<_usedLines-1) && - !(_lineProperties[right.y()] & LINE_WRAPPED)) - { i++; right.rx()++; } - if (right.x() < _usedColumns-1) - right = left_not_right ? _iPntSelCorr : here; - else - right.rx()++; // will be balanced later because of offset=-1; - }*/ - } - } + bool left_not_right = ( here.y() < _iPntSelCorr.y() || + ( here.y() == _iPntSelCorr.y() && here.x() < _iPntSelCorr.x() ) ); + bool old_left_not_right = ( _pntSelCorr.y() < _iPntSelCorr.y() || + ( _pntSelCorr.y() == _iPntSelCorr.y() && _pntSelCorr.x() < _iPntSelCorr.x() ) ); + swapping = left_not_right != old_left_not_right; - // Pick which is start (ohere) and which is extension (here) - if ( left_not_right ) { - here = left; - ohere = right; - offset = 0; - } else { - here = right; - ohere = left; - offset = -1; - } + // Find left (left_not_right ? from here : from start) + QPoint left = left_not_right ? here : _iPntSelCorr; + + // Find left (left_not_right ? from start : from here) + QPoint right = left_not_right ? _iPntSelCorr : here; + if ( right.x() > 0 && !_columnSelectionMode ) + { + i = loc(right.x(),right.y()); + if (i>=0 && i<=_imageSize) { + selClass = charClass(_image[i-1].character); + /* if (selClass == ' ') + { + while ( right.x() < _usedColumns-1 && charClass(_image[i+1].character) == selClass && (right.y()<_usedLines-1) && + !(_lineProperties[right.y()] & LINE_WRAPPED)) + { i++; right.rx()++; } + if (right.x() < _usedColumns-1) + right = left_not_right ? _iPntSelCorr : here; + else + right.rx()++; // will be balanced later because of offset=-1; + }*/ + } } - if ((here == _pntSelCorr) && (scroll == _scrollBar->value())) return; // not moved + // Pick which is start (ohere) and which is extension (here) + if ( left_not_right ) + { + here = left; ohere = right; offset = 0; + } + else + { + here = right; ohere = left; offset = -1; + } + } - if (here == ohere) return; // It's not left, it's not right. + if ((here == _pntSelCorr) && (scroll == _scrollBar->value())) return; // not moved - if ( _actSel < 2 || swapping ) { - if ( _columnSelectionMode && !_lineSelectionMode && !_wordSelectionMode ) { - _screenWindow->setSelectionStart( ohere.x() , ohere.y() , true ); - } else { - _screenWindow->setSelectionStart( ohere.x()-1-offset , ohere.y() , false ); - } + if (here == ohere) return; // It's not left, it's not right. + if ( _actSel < 2 || swapping ) + { + if ( _columnSelectionMode && !_lineSelectionMode && !_wordSelectionMode ) + { + _screenWindow->setSelectionStart( ohere.x() , ohere.y() , true ); + } + else + { + _screenWindow->setSelectionStart( ohere.x()-1-offset , ohere.y() , false ); } - _actSel = 2; // within selection - _pntSel = here; - _pntSel.ry() += _scrollBar->value(); + } - if ( _columnSelectionMode && !_lineSelectionMode && !_wordSelectionMode ) { - _screenWindow->setSelectionEnd( here.x() , here.y() ); - } else { - _screenWindow->setSelectionEnd( here.x()+offset , here.y() ); - } + _actSel = 2; // within selection + _pntSel = here; + _pntSel.ry() += _scrollBar->value(); + + if ( _columnSelectionMode && !_lineSelectionMode && !_wordSelectionMode ) + { + _screenWindow->setSelectionEnd( here.x() , here.y() ); + } + else + { + _screenWindow->setSelectionEnd( here.x()+offset , here.y() ); + } } @@ -2033,40 +2119,46 @@ void TerminalDisplay::mouseReleaseEvent(QMouseEvent* ev) int charColumn; getCharacterPosition(ev->pos(),charLine,charColumn); - if ( ev->button() == Qt::LeftButton) { - emit isBusySelecting(false); - if (dragInfo.state == diPending) { - // We had a drag event pending but never confirmed. Kill selection - _screenWindow->clearSelection(); - //emit clearSelectionSignal(); - } else { - if ( _actSel > 1 ) { - setSelection( _screenWindow->selectedText(_preserveLineBreaks) ); - } - - _actSel = 0; - - //FIXME: emits a release event even if the mouse is - // outside the range. The procedure used in `mouseMoveEvent' - // applies here, too. - - if (!_mouseMarks && !(ev->modifiers() & Qt::ShiftModifier)) - emit mouseSignal( 3, // release - charColumn + 1, - charLine + 1 +_scrollBar->value() -_scrollBar->maximum() , 0); - } - dragInfo.state = diNone; + if ( ev->button() == Qt::LeftButton) + { + emit isBusySelecting(false); + if(dragInfo.state == diPending) + { + // We had a drag event pending but never confirmed. Kill selection + _screenWindow->clearSelection(); + //emit clearSelectionSignal(); } + else + { + if ( _actSel > 1 ) + { + setSelection( _screenWindow->selectedText(_preserveLineBreaks) ); + } + _actSel = 0; - if ( !_mouseMarks && - ((ev->button() == Qt::RightButton && !(ev->modifiers() & Qt::ShiftModifier)) - || ev->button() == Qt::MidButton) ) { - emit mouseSignal( 3, - charColumn + 1, - charLine + 1 +_scrollBar->value() -_scrollBar->maximum() , - 0); + //FIXME: emits a release event even if the mouse is + // outside the range. The procedure used in `mouseMoveEvent' + // applies here, too. + + if (!_mouseMarks && !(ev->modifiers() & Qt::ShiftModifier)) + emit mouseSignal( 3, // release + charColumn + 1, + charLine + 1 +_scrollBar->value() -_scrollBar->maximum() , 0); } + dragInfo.state = diNone; + } + + + if ( !_mouseMarks && + ((ev->button() == Qt::RightButton && !(ev->modifiers() & Qt::ShiftModifier)) + || ev->button() == Qt::MidButton) ) + { + emit mouseSignal( 3, + charColumn + 1, + charLine + 1 +_scrollBar->value() -_scrollBar->maximum() , + 0); + } } void TerminalDisplay::getCharacterPosition(const QPoint& widgetPoint,int& line,int& column) const @@ -2093,210 +2185,222 @@ void TerminalDisplay::getCharacterPosition(const QPoint& widgetPoint,int& line,i void TerminalDisplay::updateLineProperties() { - if ( !_screenWindow ) + if ( !_screenWindow ) return; - _lineProperties = _screenWindow->getLineProperties(); + _lineProperties = _screenWindow->getLineProperties(); } void TerminalDisplay::mouseDoubleClickEvent(QMouseEvent* ev) { - if ( ev->button() != Qt::LeftButton) return; - if ( !_screenWindow ) return; + if ( ev->button() != Qt::LeftButton) return; + if ( !_screenWindow ) return; - int charLine = 0; - int charColumn = 0; + int charLine = 0; + int charColumn = 0; - getCharacterPosition(ev->pos(),charLine,charColumn); + getCharacterPosition(ev->pos(),charLine,charColumn); - QPoint pos(charColumn,charLine); + QPoint pos(charColumn,charLine); - // pass on double click as two clicks. - if (!_mouseMarks && !(ev->modifiers() & Qt::ShiftModifier)) { - // Send just _ONE_ click event, since the first click of the double click - // was already sent by the click handler - emit mouseSignal( 0, - pos.x()+1, - pos.y()+1 +_scrollBar->value() -_scrollBar->maximum(), - 0 ); // left button - return; - } + // pass on double click as two clicks. + if (!_mouseMarks && !(ev->modifiers() & Qt::ShiftModifier)) + { + // Send just _ONE_ click event, since the first click of the double click + // was already sent by the click handler + emit mouseSignal( 0, + pos.x()+1, + pos.y()+1 +_scrollBar->value() -_scrollBar->maximum(), + 0 ); // left button + return; + } - _screenWindow->clearSelection(); - QPoint bgnSel = pos; - QPoint endSel = pos; - int i = loc(bgnSel.x(),bgnSel.y()); - _iPntSel = bgnSel; - _iPntSel.ry() += _scrollBar->value(); + _screenWindow->clearSelection(); + QPoint bgnSel = pos; + QPoint endSel = pos; + int i = loc(bgnSel.x(),bgnSel.y()); + _iPntSel = bgnSel; + _iPntSel.ry() += _scrollBar->value(); - _wordSelectionMode = true; + _wordSelectionMode = true; - // find word boundaries... - QChar selClass = charClass(_image[i].character); - { - // find the start of the word - int x = bgnSel.x(); - while ( ((x>0) || (bgnSel.y()>0 && (_lineProperties[bgnSel.y()-1] & LINE_WRAPPED) )) - && charClass(_image[i-1].character) == selClass ) { - i--; - if (x>0) - x--; - else { - x=_usedColumns-1; - bgnSel.ry()--; - } - } + // find word boundaries... + QChar selClass = charClass(_image[i].character); + { + // find the start of the word + int x = bgnSel.x(); + while ( ((x>0) || (bgnSel.y()>0 && (_lineProperties[bgnSel.y()-1] & LINE_WRAPPED) )) + && charClass(_image[i-1].character) == selClass ) + { + i--; + if (x>0) + x--; + else + { + x=_usedColumns-1; + bgnSel.ry()--; + } + } - bgnSel.setX(x); - _screenWindow->setSelectionStart( bgnSel.x() , bgnSel.y() , false ); + bgnSel.setX(x); + _screenWindow->setSelectionStart( bgnSel.x() , bgnSel.y() , false ); - // find the end of the word - i = loc( endSel.x(), endSel.y() ); - x = endSel.x(); - while ( ((x<_usedColumns-1) || (endSel.y()<_usedLines-1 && (_lineProperties[endSel.y()] & LINE_WRAPPED) )) - && charClass(_image[i+1].character) == selClass ) { - i++; - if (x<_usedColumns-1) - x++; - else { - x=0; - endSel.ry()++; - } - } + // find the end of the word + i = loc( endSel.x(), endSel.y() ); + x = endSel.x(); + while( ((x<_usedColumns-1) || (endSel.y()<_usedLines-1 && (_lineProperties[endSel.y()] & LINE_WRAPPED) )) + && charClass(_image[i+1].character) == selClass ) + { + i++; + if (x<_usedColumns-1) + x++; + else + { + x=0; + endSel.ry()++; + } + } - endSel.setX(x); + endSel.setX(x); - // In word selection mode don't select @ (64) if at end of word. - if ( ( QChar( _image[i].character ) == '@' ) && ( ( endSel.x() - bgnSel.x() ) > 0 ) ) - endSel.setX( x - 1 ); + // In word selection mode don't select @ (64) if at end of word. + if ( ( QChar( _image[i].character ) == '@' ) && ( ( endSel.x() - bgnSel.x() ) > 0 ) ) + endSel.setX( x - 1 ); - _actSel = 2; // within selection + _actSel = 2; // within selection + + _screenWindow->setSelectionEnd( endSel.x() , endSel.y() ); + + setSelection( _screenWindow->selectedText(_preserveLineBreaks) ); + } - _screenWindow->setSelectionEnd( endSel.x() , endSel.y() ); + _possibleTripleClick=true; - setSelection( _screenWindow->selectedText(_preserveLineBreaks) ); - } - - _possibleTripleClick=true; - - QTimer::singleShot(QApplication::doubleClickInterval(),this, - SLOT(tripleClickTimeout())); + QTimer::singleShot(QApplication::doubleClickInterval(),this, + SLOT(tripleClickTimeout())); } void TerminalDisplay::wheelEvent( QWheelEvent* ev ) { - if (ev->orientation() != Qt::Vertical) - return; + if (ev->orientation() != Qt::Vertical) + return; - // if the terminal program is not interested mouse events - // then send the event to the scrollbar if the slider has room to move - // or otherwise send simulated up / down key presses to the terminal program - // for the benefit of programs such as 'less' - if ( _mouseMarks ) { - bool canScroll = _scrollBar->maximum() > 0; - if (canScroll) - _scrollBar->event(ev); - else { - // assume that each Up / Down key event will cause the terminal application - // to scroll by one line. - // - // to get a reasonable scrolling speed, scroll by one line for every 5 degrees - // of mouse wheel rotation. Mouse wheels typically move in steps of 15 degrees, - // giving a scroll of 3 lines - int key = ev->delta() > 0 ? Qt::Key_Up : Qt::Key_Down; + // if the terminal program is not interested mouse events + // then send the event to the scrollbar if the slider has room to move + // or otherwise send simulated up / down key presses to the terminal program + // for the benefit of programs such as 'less' + if ( _mouseMarks ) + { + bool canScroll = _scrollBar->maximum() > 0; + if (canScroll) + _scrollBar->event(ev); + else + { + // assume that each Up / Down key event will cause the terminal application + // to scroll by one line. + // + // to get a reasonable scrolling speed, scroll by one line for every 5 degrees + // of mouse wheel rotation. Mouse wheels typically move in steps of 15 degrees, + // giving a scroll of 3 lines + int key = ev->delta() > 0 ? Qt::Key_Up : Qt::Key_Down; - // QWheelEvent::delta() gives rotation in eighths of a degree - int wheelDegrees = ev->delta() / 8; - int linesToScroll = abs(wheelDegrees) / 5; + // QWheelEvent::delta() gives rotation in eighths of a degree + int wheelDegrees = ev->delta() / 8; + int linesToScroll = abs(wheelDegrees) / 5; - QKeyEvent keyScrollEvent(QEvent::KeyPress,key,Qt::NoModifier); + QKeyEvent keyScrollEvent(QEvent::KeyPress,key,Qt::NoModifier); - for (int i=0; ipos() , charLine , charColumn ); - - emit mouseSignal( ev->delta() > 0 ? 4 : 5, - charColumn + 1, - charLine + 1 +_scrollBar->value() -_scrollBar->maximum() , - 0); + for (int i=0;ipos() , charLine , charColumn ); + + emit mouseSignal( ev->delta() > 0 ? 4 : 5, + charColumn + 1, + charLine + 1 +_scrollBar->value() -_scrollBar->maximum() , + 0); + } } void TerminalDisplay::tripleClickTimeout() { - _possibleTripleClick=false; + _possibleTripleClick=false; } void TerminalDisplay::mouseTripleClickEvent(QMouseEvent* ev) { - if ( !_screenWindow ) return; + if ( !_screenWindow ) return; - int charLine; - int charColumn; - getCharacterPosition(ev->pos(),charLine,charColumn); - _iPntSel = QPoint(charColumn,charLine); + int charLine; + int charColumn; + getCharacterPosition(ev->pos(),charLine,charColumn); + _iPntSel = QPoint(charColumn,charLine); - _screenWindow->clearSelection(); + _screenWindow->clearSelection(); - _lineSelectionMode = true; - _wordSelectionMode = false; + _lineSelectionMode = true; + _wordSelectionMode = false; - _actSel = 2; // within selection - emit isBusySelecting(true); // Keep it steady... + _actSel = 2; // within selection + emit isBusySelecting(true); // Keep it steady... - while (_iPntSel.y()>0 && (_lineProperties[_iPntSel.y()-1] & LINE_WRAPPED) ) - _iPntSel.ry()--; - - if (_tripleClickMode == SelectForwardsFromCursor) { - // find word boundary start - int i = loc(_iPntSel.x(),_iPntSel.y()); - QChar selClass = charClass(_image[i].character); - int x = _iPntSel.x(); - - while ( ((x>0) || - (_iPntSel.y()>0 && (_lineProperties[_iPntSel.y()-1] & LINE_WRAPPED) ) - ) - && charClass(_image[i-1].character) == selClass ) { - i--; - if (x>0) - x--; - else { - x=_columns-1; - _iPntSel.ry()--; - } - } - - _screenWindow->setSelectionStart( x , _iPntSel.y() , false ); - _tripleSelBegin = QPoint( x, _iPntSel.y() ); - } else if (_tripleClickMode == SelectWholeLine) { - _screenWindow->setSelectionStart( 0 , _iPntSel.y() , false ); - _tripleSelBegin = QPoint( 0, _iPntSel.y() ); + while (_iPntSel.y()>0 && (_lineProperties[_iPntSel.y()-1] & LINE_WRAPPED) ) + _iPntSel.ry()--; + + if (_tripleClickMode == SelectForwardsFromCursor) { + // find word boundary start + int i = loc(_iPntSel.x(),_iPntSel.y()); + QChar selClass = charClass(_image[i].character); + int x = _iPntSel.x(); + + while ( ((x>0) || + (_iPntSel.y()>0 && (_lineProperties[_iPntSel.y()-1] & LINE_WRAPPED) ) + ) + && charClass(_image[i-1].character) == selClass ) + { + i--; + if (x>0) + x--; + else + { + x=_columns-1; + _iPntSel.ry()--; + } } - while (_iPntSel.y()<_lines-1 && (_lineProperties[_iPntSel.y()] & LINE_WRAPPED) ) - _iPntSel.ry()++; + _screenWindow->setSelectionStart( x , _iPntSel.y() , false ); + _tripleSelBegin = QPoint( x, _iPntSel.y() ); + } + else if (_tripleClickMode == SelectWholeLine) { + _screenWindow->setSelectionStart( 0 , _iPntSel.y() , false ); + _tripleSelBegin = QPoint( 0, _iPntSel.y() ); + } - _screenWindow->setSelectionEnd( _columns - 1 , _iPntSel.y() ); + while (_iPntSel.y()<_lines-1 && (_lineProperties[_iPntSel.y()] & LINE_WRAPPED) ) + _iPntSel.ry()++; + + _screenWindow->setSelectionEnd( _columns - 1 , _iPntSel.y() ); - setSelection(_screenWindow->selectedText(_preserveLineBreaks)); + setSelection(_screenWindow->selectedText(_preserveLineBreaks)); - _iPntSel.ry() += _scrollBar->value(); + _iPntSel.ry() += _scrollBar->value(); } bool TerminalDisplay::focusNextPrevChild( bool next ) { - if (next) - return false; // This disables changing the active part in konqueror - // when pressing Tab - return QWidget::focusNextPrevChild( next ); + if (next) + return false; // This disables changing the active part in konqueror + // when pressing Tab + return QWidget::focusNextPrevChild( next ); } @@ -2305,7 +2409,7 @@ QChar TerminalDisplay::charClass(QChar qch) const if ( qch.isSpace() ) return ' '; if ( qch.isLetterOrNumber() || _wordCharacters.contains(qch, Qt::CaseInsensitive ) ) - return 'a'; + return 'a'; return qch; } @@ -2317,8 +2421,8 @@ void TerminalDisplay::setWordCharacters(const QString& wc) void TerminalDisplay::setUsesMouse(bool on) { - _mouseMarks = on; - setCursor( _mouseMarks ? Qt::IBeamCursor : Qt::ArrowCursor ); + _mouseMarks = on; + setCursor( _mouseMarks ? Qt::IBeamCursor : Qt::ArrowCursor ); } bool TerminalDisplay::usesMouse() const { @@ -2335,46 +2439,47 @@ bool TerminalDisplay::usesMouse() const void TerminalDisplay::emitSelection(bool useXselection,bool appendReturn) { - if ( !_screenWindow ) - return; + if ( !_screenWindow ) + return; - // Paste Clipboard by simulating keypress events - QString text = QApplication::clipboard()->text(useXselection ? QClipboard::Selection : - QClipboard::Clipboard); - if (appendReturn) - text.append("\r"); - if ( ! text.isEmpty() ) { - text.replace('\n', '\r'); - QKeyEvent e(QEvent::KeyPress, 0, Qt::NoModifier, text); - emit keyPressedSignal(&e); // expose as a big fat keypress event - - _screenWindow->clearSelection(); - } + // Paste Clipboard by simulating keypress events + QString text = QApplication::clipboard()->text(useXselection ? QClipboard::Selection : + QClipboard::Clipboard); + if(appendReturn) + text.append("\r"); + if ( ! text.isEmpty() ) + { + text.replace('\n', '\r'); + QKeyEvent e(QEvent::KeyPress, 0, Qt::NoModifier, text); + emit keyPressedSignal(&e); // expose as a big fat keypress event + + _screenWindow->clearSelection(); + } } void TerminalDisplay::setSelection(const QString& t) { - QApplication::clipboard()->setText(t, QClipboard::Selection); + QApplication::clipboard()->setText(t, QClipboard::Selection); } void TerminalDisplay::copyClipboard() { - if ( !_screenWindow ) - return; + if ( !_screenWindow ) + return; - QString text = _screenWindow->selectedText(_preserveLineBreaks); - if (!text.isEmpty()) - QApplication::clipboard()->setText(text); + QString text = _screenWindow->selectedText(_preserveLineBreaks); + if (!text.isEmpty()) + QApplication::clipboard()->setText(text); } void TerminalDisplay::pasteClipboard() { - emitSelection(false,false); + emitSelection(false,false); } void TerminalDisplay::pasteSelection() { - emitSelection(true,false); + emitSelection(true,false); } /* ------------------------------------------------------------------------- */ @@ -2386,8 +2491,8 @@ void TerminalDisplay::pasteSelection() void TerminalDisplay::setFlowControlWarningEnabled( bool enable ) { _flowControlWarningEnabled = enable; - - // if the dialog is currently visible and the flow control warning has + + // if the dialog is currently visible and the flow control warning has // been disabled then hide the dialog if (!enable) outputSuspended(false); @@ -2398,23 +2503,33 @@ void TerminalDisplay::keyPressEvent( QKeyEvent* event ) bool emitKeyPressSignal = true; // Keyboard-based navigation - if ( event->modifiers() == Qt::ShiftModifier ) { + if ( event->modifiers() == Qt::ShiftModifier ) + { bool update = true; - if ( event->key() == Qt::Key_PageUp ) { + if ( event->key() == Qt::Key_PageUp ) + { _screenWindow->scrollBy( ScreenWindow::ScrollPages , -1 ); - } else if ( event->key() == Qt::Key_PageDown ) { + } + else if ( event->key() == Qt::Key_PageDown ) + { _screenWindow->scrollBy( ScreenWindow::ScrollPages , 1 ); - } else if ( event->key() == Qt::Key_Up ) { + } + else if ( event->key() == Qt::Key_Up ) + { _screenWindow->scrollBy( ScreenWindow::ScrollLines , -1 ); - } else if ( event->key() == Qt::Key_Down ) { + } + else if ( event->key() == Qt::Key_Down ) + { _screenWindow->scrollBy( ScreenWindow::ScrollLines , 1 ); - } else + } + else update = false; - if ( update ) { + if ( update ) + { _screenWindow->setTrackOutput( _screenWindow->atEndOfOutput() ); - + updateLineProperties(); updateImage(); @@ -2424,14 +2539,15 @@ void TerminalDisplay::keyPressEvent( QKeyEvent* event ) } _actSel=0; // Key stroke implies a screen update, so TerminalDisplay won't - // know where the current selection is. + // know where the current selection is. - if (_hasBlinkingCursor) { - _blinkCursorTimer->start(QApplication::cursorFlashTime() / 2); - if (_cursorBlinking) - blinkCursorEvent(); - else - _cursorBlinking = false; + if (_hasBlinkingCursor) + { + _blinkCursorTimer->start(QApplication::cursorFlashTime() / 2); + if (_cursorBlinking) + blinkCursorEvent(); + else + _cursorBlinking = false; } if ( emitKeyPressSignal ) @@ -2447,39 +2563,41 @@ void TerminalDisplay::inputMethodEvent( QInputMethodEvent* event ) _inputMethodData.preeditString = event->preeditString(); update(preeditRect() | _inputMethodData.previousPreeditRect); - + event->accept(); } QVariant TerminalDisplay::inputMethodQuery( Qt::InputMethodQuery query ) const { const QPoint cursorPos = _screenWindow ? _screenWindow->cursorPosition() : QPoint(0,0); - switch ( query ) { - case Qt::ImMicroFocus: - return imageToWidget(QRect(cursorPos.x(),cursorPos.y(),1,1)); - break; - case Qt::ImFont: - return font(); - break; - case Qt::ImCursorPosition: - // return the cursor position within the current line - return cursorPos.x(); - break; - case Qt::ImSurroundingText: { - // return the text from the current line - QString lineText; - QTextStream stream(&lineText); - PlainTextDecoder decoder; - decoder.begin(&stream); - decoder.decodeLine(&_image[loc(0,cursorPos.y())],_usedColumns,_lineProperties[cursorPos.y()]); - decoder.end(); - return lineText; - } - break; - case Qt::ImCurrentSelection: - return QString(); - break; - default: - break; + switch ( query ) + { + case Qt::ImMicroFocus: + return imageToWidget(QRect(cursorPos.x(),cursorPos.y(),1,1)); + break; + case Qt::ImFont: + return font(); + break; + case Qt::ImCursorPosition: + // return the cursor position within the current line + return cursorPos.x(); + break; + case Qt::ImSurroundingText: + { + // return the text from the current line + QString lineText; + QTextStream stream(&lineText); + PlainTextDecoder decoder; + decoder.begin(&stream); + decoder.decodeLine(&_image[loc(0,cursorPos.y())],_usedColumns,_lineProperties[cursorPos.y()]); + decoder.end(); + return lineText; + } + break; + case Qt::ImCurrentSelection: + return QString(); + break; + default: + break; } return QVariant(); @@ -2489,22 +2607,26 @@ bool TerminalDisplay::handleShortcutOverrideEvent(QKeyEvent* keyEvent) { int modifiers = keyEvent->modifiers(); - // When a possible shortcut combination is pressed, + // When a possible shortcut combination is pressed, // emit the overrideShortcutCheck() signal to allow the host // to decide whether the terminal should override it or not. - if (modifiers != Qt::NoModifier) { + if (modifiers != Qt::NoModifier) + { int modifierCount = 0; unsigned int currentModifier = Qt::ShiftModifier; - while (currentModifier <= Qt::KeypadModifier) { + while (currentModifier <= Qt::KeypadModifier) + { if (modifiers & currentModifier) modifierCount++; currentModifier <<= 1; } - if (modifierCount < 2) { + if (modifierCount < 2) + { bool override = false; emit overrideShortcutCheck(keyEvent,override); - if (override) { + if (override) + { keyEvent->accept(); return true; } @@ -2514,15 +2636,16 @@ bool TerminalDisplay::handleShortcutOverrideEvent(QKeyEvent* keyEvent) // Override any of the following shortcuts because // they are needed by the terminal int keyCode = keyEvent->key() | modifiers; - switch ( keyCode ) { - // list is taken from the QLineEdit::event() code - case Qt::Key_Tab: - case Qt::Key_Delete: - case Qt::Key_Home: - case Qt::Key_End: - case Qt::Key_Backspace: - case Qt::Key_Left: - case Qt::Key_Right: + switch ( keyCode ) + { + // list is taken from the QLineEdit::event() code + case Qt::Key_Tab: + case Qt::Key_Delete: + case Qt::Key_Home: + case Qt::Key_End: + case Qt::Key_Backspace: + case Qt::Key_Left: + case Qt::Key_Right: keyEvent->accept(); return true; } @@ -2531,8 +2654,9 @@ bool TerminalDisplay::handleShortcutOverrideEvent(QKeyEvent* keyEvent) bool TerminalDisplay::event(QEvent* event) { - bool eventHandled = false; - switch (event->type()) { + bool eventHandled = false; + switch (event->type()) + { case QEvent::ShortcutOverride: eventHandled = handleShortcutOverrideEvent((QKeyEvent*)event); break; @@ -2542,13 +2666,13 @@ bool TerminalDisplay::event(QEvent* event) break; default: break; - } - return eventHandled ? true : QWidget::event(event); + } + return eventHandled ? true : QWidget::event(event); } void TerminalDisplay::setBellMode(int mode) { - _bellMode=mode; + _bellMode=mode; } void TerminalDisplay::enableBell() @@ -2558,26 +2682,31 @@ void TerminalDisplay::enableBell() void TerminalDisplay::bell(const QString& message) { - if (_bellMode==NoBell) return; + if (_bellMode==NoBell) return; - //limit the rate at which bells can occur - //...mainly for sound effects where rapid bells in sequence - //produce a horrible noise - if ( _allowBell ) { - _allowBell = false; - QTimer::singleShot(500,this,SLOT(enableBell())); - - if (_bellMode==SystemBeepBell) { - //! \todo TODO/FIXME: some notifications for Qt4? - //KNotification::beep(); - } else if (_bellMode==NotifyBell) { - //! \todo TODO/FIXME: some notifications for Qt4? - //KNotification::event("BellVisible", message,QPixmap(),this); - } else if (_bellMode==VisualBell) { - swapColorTable(); - QTimer::singleShot(200,this,SLOT(swapColorTable())); - } + //limit the rate at which bells can occur + //...mainly for sound effects where rapid bells in sequence + //produce a horrible noise + if ( _allowBell ) + { + _allowBell = false; + QTimer::singleShot(500,this,SLOT(enableBell())); + + if (_bellMode==SystemBeepBell) + { + QApplication::beep(); + } + else if (_bellMode==NotifyBell) + { + //KNotification::event("BellVisible", message,QPixmap(),this); + // TODO/FIXME: qt4 notifications? + } + else if (_bellMode==VisualBell) + { + swapColorTable(); + QTimer::singleShot(200,this,SLOT(swapColorTable())); } + } } void TerminalDisplay::selectionChanged() @@ -2587,115 +2716,120 @@ void TerminalDisplay::selectionChanged() void TerminalDisplay::swapColorTable() { - ColorEntry color = _colorTable[1]; - _colorTable[1]=_colorTable[0]; - _colorTable[0]= color; - _colorsInverted = !_colorsInverted; - update(); + ColorEntry color = _colorTable[1]; + _colorTable[1]=_colorTable[0]; + _colorTable[0]= color; + _colorsInverted = !_colorsInverted; + update(); } void TerminalDisplay::clearImage() { - // We initialize _image[_imageSize] too. See makeImage() - for (int i = 0; i <= _imageSize; i++) { - _image[i].character = ' '; - _image[i].foregroundColor = CharacterColor(COLOR_SPACE_DEFAULT, - DEFAULT_FORE_COLOR); - _image[i].backgroundColor = CharacterColor(COLOR_SPACE_DEFAULT, - DEFAULT_BACK_COLOR); - _image[i].rendition = DEFAULT_RENDITION; - } + // We initialize _image[_imageSize] too. See makeImage() + for (int i = 0; i <= _imageSize; i++) + { + _image[i].character = ' '; + _image[i].foregroundColor = CharacterColor(COLOR_SPACE_DEFAULT, + DEFAULT_FORE_COLOR); + _image[i].backgroundColor = CharacterColor(COLOR_SPACE_DEFAULT, + DEFAULT_BACK_COLOR); + _image[i].rendition = DEFAULT_RENDITION; + } } void TerminalDisplay::calcGeometry() { - _scrollBar->resize(_scrollBar->sizeHint().width(), contentsRect().height()); - switch (_scrollbarLocation) { + _scrollBar->resize(_scrollBar->sizeHint().width(), contentsRect().height()); + switch(_scrollbarLocation) + { case NoScrollBar : - _leftMargin = DEFAULT_LEFT_MARGIN; - _contentWidth = contentsRect().width() - 2 * DEFAULT_LEFT_MARGIN; - break; + _leftMargin = DEFAULT_LEFT_MARGIN; + _contentWidth = contentsRect().width() - 2 * DEFAULT_LEFT_MARGIN; + break; case ScrollBarLeft : - _leftMargin = DEFAULT_LEFT_MARGIN + _scrollBar->width(); - _contentWidth = contentsRect().width() - 2 * DEFAULT_LEFT_MARGIN - _scrollBar->width(); - _scrollBar->move(contentsRect().topLeft()); - break; + _leftMargin = DEFAULT_LEFT_MARGIN + _scrollBar->width(); + _contentWidth = contentsRect().width() - 2 * DEFAULT_LEFT_MARGIN - _scrollBar->width(); + _scrollBar->move(contentsRect().topLeft()); + break; case ScrollBarRight: - _leftMargin = DEFAULT_LEFT_MARGIN; - _contentWidth = contentsRect().width() - 2 * DEFAULT_LEFT_MARGIN - _scrollBar->width(); - _scrollBar->move(contentsRect().topRight() - QPoint(_scrollBar->width()-1,0)); - break; - } + _leftMargin = DEFAULT_LEFT_MARGIN; + _contentWidth = contentsRect().width() - 2 * DEFAULT_LEFT_MARGIN - _scrollBar->width(); + _scrollBar->move(contentsRect().topRight() - QPoint(_scrollBar->width()-1,0)); + break; + } - _topMargin = DEFAULT_TOP_MARGIN; - _contentHeight = contentsRect().height() - 2 * DEFAULT_TOP_MARGIN + /* mysterious */ 1; - - if (!_isFixedSize) { - // ensure that display is always at least one column wide - _columns = qMax(1,_contentWidth / _fontWidth); - _usedColumns = qMin(_usedColumns,_columns); - - // ensure that display is always at least one line high - _lines = qMax(1,_contentHeight / _fontHeight); - _usedLines = qMin(_usedLines,_lines); - } + _topMargin = DEFAULT_TOP_MARGIN; + _contentHeight = contentsRect().height() - 2 * DEFAULT_TOP_MARGIN + /* mysterious */ 1; + + if (!_isFixedSize) + { + // ensure that display is always at least one column wide + _columns = qMax(1,_contentWidth / _fontWidth); + _usedColumns = qMin(_usedColumns,_columns); + + // ensure that display is always at least one line high + _lines = qMax(1,_contentHeight / _fontHeight); + _usedLines = qMin(_usedLines,_lines); + } } void TerminalDisplay::makeImage() { - calcGeometry(); + calcGeometry(); - // confirm that array will be of non-zero size, since the painting code - // assumes a non-zero array length - Q_ASSERT( _lines > 0 && _columns > 0 ); - Q_ASSERT( _usedLines <= _lines && _usedColumns <= _columns ); + // confirm that array will be of non-zero size, since the painting code + // assumes a non-zero array length + Q_ASSERT( _lines > 0 && _columns > 0 ); + Q_ASSERT( _usedLines <= _lines && _usedColumns <= _columns ); - _imageSize=_lines*_columns; + _imageSize=_lines*_columns; + + // We over-commit one character so that we can be more relaxed in dealing with + // certain boundary conditions: _image[_imageSize] is a valid but unused position + _image = new Character[_imageSize+1]; - // We over-commit one character so that we can be more relaxed in dealing with - // certain boundary conditions: _image[_imageSize] is a valid but unused position - _image = new Character[_imageSize+1]; - - clearImage(); + clearImage(); } // calculate the needed size, this must be synced with calcGeometry() void TerminalDisplay::setSize(int columns, int lines) { - int scrollBarWidth = _scrollBar->isHidden() ? 0 : _scrollBar->sizeHint().width(); - int horizontalMargin = 2 * DEFAULT_LEFT_MARGIN; - int verticalMargin = 2 * DEFAULT_TOP_MARGIN; + int scrollBarWidth = _scrollBar->isHidden() ? 0 : _scrollBar->sizeHint().width(); + int horizontalMargin = 2 * DEFAULT_LEFT_MARGIN; + int verticalMargin = 2 * DEFAULT_TOP_MARGIN; - QSize newSize = QSize( horizontalMargin + scrollBarWidth + (columns * _fontWidth) , - verticalMargin + (lines * _fontHeight) ); + QSize newSize = QSize( horizontalMargin + scrollBarWidth + (columns * _fontWidth) , + verticalMargin + (lines * _fontHeight) ); - if ( newSize != size() ) { - _size = newSize; - updateGeometry(); - } + if ( newSize != size() ) + { + _size = newSize; + updateGeometry(); + } } void TerminalDisplay::setFixedSize(int cols, int lins) { - _isFixedSize = true; + _isFixedSize = true; + + //ensure that display is at least one line by one column in size + _columns = qMax(1,cols); + _lines = qMax(1,lins); + _usedColumns = qMin(_usedColumns,_columns); + _usedLines = qMin(_usedLines,_lines); - //ensure that display is at least one line by one column in size - _columns = qMax(1,cols); - _lines = qMax(1,lins); - _usedColumns = qMin(_usedColumns,_columns); - _usedLines = qMin(_usedLines,_lines); - - if (_image) { - delete[] _image; - makeImage(); - } - setSize(cols, lins); - QWidget::setFixedSize(_size); + if (_image) + { + delete[] _image; + makeImage(); + } + setSize(cols, lins); + QWidget::setFixedSize(_size); } QSize TerminalDisplay::sizeHint() const { - return _size; + return _size; } @@ -2707,93 +2841,98 @@ QSize TerminalDisplay::sizeHint() const void TerminalDisplay::dragEnterEvent(QDragEnterEvent* event) { - if (event->mimeData()->hasFormat("text/plain")) - event->acceptProposedAction(); + if (event->mimeData()->hasFormat("text/plain")) + event->acceptProposedAction(); } void TerminalDisplay::dropEvent(QDropEvent* event) { - //KUrl::List urls = KUrl::List::fromMimeData(event->mimeData()); + //KUrl::List urls = KUrl::List::fromMimeData(event->mimeData()); + QList urls = event->mimeData()->urls(); - QString dropText; - /* - if (!urls.isEmpty()) - { - for ( int i = 0 ; i < urls.count() ; i++ ) - { - KUrl url = KIO::NetAccess::mostLocalUrl( urls[i] , 0 ); - QString urlText; + QString dropText; + if (!urls.isEmpty()) + { + // TODO/FIXME: escape or quote pasted things if neccessary... + qDebug() << "TerminalDisplay: handling urls. It can be broken. Report any errors, please"; + for ( int i = 0 ; i < urls.count() ; i++ ) + { + //KUrl url = KIO::NetAccess::mostLocalUrl( urls[i] , 0 ); + QUrl url = urls[i]; + QString urlText; - if (url.isLocalFile()) - urlText = url.path(); - else - urlText = url.url(); +// if (url.isLocalFile()) +// urlText = url.path(); +// else +// urlText = url.url(); + urlText = url.toString(); + + // in future it may be useful to be able to insert file names with drag-and-drop + // without quoting them (this only affects paths with spaces in) + //urlText = KShell::quoteArg(urlText); + + dropText += urlText; - // in future it may be useful to be able to insert file names with drag-and-drop - // without quoting them (this only affects paths with spaces in) - urlText = KShell::quoteArg(urlText); - - dropText += urlText; - - if ( i != urls.count()-1 ) - dropText += ' '; - } - } - else - { - */ - dropText = event->mimeData()->text(); - //} - - if (event->mimeData()->hasFormat("text/plain")) { - emit sendStringToEmu(dropText.toLocal8Bit()); + if ( i != urls.count()-1 ) + dropText += ' '; } + } + else + { + dropText = event->mimeData()->text(); + } + + if(event->mimeData()->hasFormat("text/plain")) + { + emit sendStringToEmu(dropText.toLocal8Bit()); + } } void TerminalDisplay::doDrag() { - dragInfo.state = diDragging; - dragInfo.dragObject = new QDrag(this); - QMimeData *mimeData = new QMimeData; - mimeData->setText(QApplication::clipboard()->text(QClipboard::Selection)); - dragInfo.dragObject->setMimeData(mimeData); - dragInfo.dragObject->start(Qt::CopyAction); - // Don't delete the QTextDrag object. Qt will delete it when it's done with it. + dragInfo.state = diDragging; + dragInfo.dragObject = new QDrag(this); + QMimeData *mimeData = new QMimeData; + mimeData->setText(QApplication::clipboard()->text(QClipboard::Selection)); + dragInfo.dragObject->setMimeData(mimeData); + dragInfo.dragObject->start(Qt::CopyAction); + // Don't delete the QTextDrag object. Qt will delete it when it's done with it. } void TerminalDisplay::outputSuspended(bool suspended) { //create the label when this function is first called - if (!_outputSuspendedLabel) { - //This label includes a link to an English language website - //describing the 'flow control' (Xon/Xoff) feature found in almost - //all terminal emulators. - //If there isn't a suitable article available in the target language the link - //can simply be removed. - _outputSuspendedLabel = new QLabel( ("Output has been " - "suspended" - " by pressing Ctrl+S." - " Press Ctrl+Q to resume."), - this ); + if (!_outputSuspendedLabel) + { + //This label includes a link to an English language website + //describing the 'flow control' (Xon/Xoff) feature found in almost + //all terminal emulators. + //If there isn't a suitable article available in the target language the link + //can simply be removed. + _outputSuspendedLabel = new QLabel( tr("Output has been " + "suspended" + " by pressing Ctrl+S." + " Press Ctrl+Q to resume."), + this ); - QPalette palette(_outputSuspendedLabel->palette()); - //KColorScheme::adjustBackground(palette,KColorScheme::NeutralBackground); - _outputSuspendedLabel->setPalette(palette); - _outputSuspendedLabel->setAutoFillBackground(true); - _outputSuspendedLabel->setBackgroundRole(QPalette::Base); - _outputSuspendedLabel->setFont(QApplication::font()); - _outputSuspendedLabel->setContentsMargins(5, 5, 5, 5); + QPalette palette(_outputSuspendedLabel->palette()); + //KColorScheme::adjustBackground(palette,KColorScheme::NeutralBackground); + _outputSuspendedLabel->setPalette(palette); + _outputSuspendedLabel->setAutoFillBackground(true); + _outputSuspendedLabel->setBackgroundRole(QPalette::Base); + _outputSuspendedLabel->setFont(QApplication::font()); + _outputSuspendedLabel->setContentsMargins(5, 5, 5, 5); - //enable activation of "Xon/Xoff" link in label - _outputSuspendedLabel->setTextInteractionFlags(Qt::LinksAccessibleByMouse | - Qt::LinksAccessibleByKeyboard); - _outputSuspendedLabel->setOpenExternalLinks(true); - _outputSuspendedLabel->setVisible(false); + //enable activation of "Xon/Xoff" link in label + _outputSuspendedLabel->setTextInteractionFlags(Qt::LinksAccessibleByMouse | + Qt::LinksAccessibleByKeyboard); + _outputSuspendedLabel->setOpenExternalLinks(true); + _outputSuspendedLabel->setVisible(false); - _gridLayout->addWidget(_outputSuspendedLabel); - _gridLayout->addItem( new QSpacerItem(0,0,QSizePolicy::Expanding, - QSizePolicy::Expanding), - 1,0); + _gridLayout->addWidget(_outputSuspendedLabel); + _gridLayout->addItem( new QSpacerItem(0,0,QSizePolicy::Expanding, + QSizePolicy::Expanding), + 1,0); } @@ -2802,18 +2941,18 @@ void TerminalDisplay::outputSuspended(bool suspended) uint TerminalDisplay::lineSpacing() const { - return _lineSpacing; + return _lineSpacing; } void TerminalDisplay::setLineSpacing(uint i) { - _lineSpacing = i; - setVTFont(font()); // Trigger an update. + _lineSpacing = i; + setVTFont(font()); // Trigger an update. } AutoScrollHandler::AutoScrollHandler(QWidget* parent) - : QObject(parent) - , _timerId(0) +: QObject(parent) +, _timerId(0) { parent->installEventFilter(this); } @@ -2823,12 +2962,12 @@ void AutoScrollHandler::timerEvent(QTimerEvent* event) return; QMouseEvent mouseEvent( QEvent::MouseMove, - widget()->mapFromGlobal(QCursor::pos()), - Qt::NoButton, - Qt::LeftButton, - Qt::NoModifier); + widget()->mapFromGlobal(QCursor::pos()), + Qt::NoButton, + Qt::LeftButton, + Qt::NoModifier); - QApplication::sendEvent(widget(),&mouseEvent); + QApplication::sendEvent(widget(),&mouseEvent); } bool AutoScrollHandler::eventFilter(QObject* watched,QEvent* event) { @@ -2836,29 +2975,37 @@ bool AutoScrollHandler::eventFilter(QObject* watched,QEvent* event) Q_UNUSED( watched ); QMouseEvent* mouseEvent = (QMouseEvent*)event; - switch (event->type()) { - case QEvent::MouseMove: { - bool mouseInWidget = widget()->rect().contains(mouseEvent->pos()); + switch (event->type()) + { + case QEvent::MouseMove: + { + bool mouseInWidget = widget()->rect().contains(mouseEvent->pos()); - if (mouseInWidget) { - if (_timerId) + if (mouseInWidget) + { + if (_timerId) + killTimer(_timerId); + _timerId = 0; + } + else + { + if (!_timerId && (mouseEvent->buttons() & Qt::LeftButton)) + _timerId = startTimer(100); + } + break; + } + case QEvent::MouseButtonRelease: + if (_timerId && (mouseEvent->buttons() & ~Qt::LeftButton)) + { killTimer(_timerId); - _timerId = 0; - } else { - if (!_timerId && (mouseEvent->buttons() & Qt::LeftButton)) - _timerId = startTimer(100); - } + _timerId = 0; + } break; - } - case QEvent::MouseButtonRelease: - if (_timerId && (mouseEvent->buttons() & ~Qt::LeftButton)) { - killTimer(_timerId); - _timerId = 0; - } - break; - default: + default: break; }; return false; } + +//#include "TerminalDisplay.moc" diff --git a/lib/TerminalDisplay.h b/lib/TerminalDisplay.h index 4d6c0a5..6720bc5 100644 --- a/lib/TerminalDisplay.h +++ b/lib/TerminalDisplay.h @@ -2,8 +2,6 @@ Copyright 2007-2008 by Robert Knight Copyright 1997,1998 by Lars Doelle - Rewritten for QT4 by e_k , Copyright (C)2008 - This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or @@ -31,6 +29,8 @@ // Konsole #include "Filter.h" #include "Character.h" +//#include "konsole_export.h" +#define KONSOLEPRIVATE_EXPORT class QDrag; class QDragEnterEvent; @@ -48,7 +48,8 @@ class QWidget; //class KMenu; -namespace Konsole { +namespace Konsole +{ extern unsigned short vt100_graphics[32]; @@ -58,13 +59,14 @@ class ScreenWindow; * A widget which displays output from a terminal emulation and sends input keypresses and mouse activity * to the terminal. * - * When the terminal emulation receives new output from the program running in the terminal, + * When the terminal emulation receives new output from the program running in the terminal, * it will update the display by calling updateImage(). * * TODO More documentation */ -class TerminalDisplay : public QWidget { - Q_OBJECT +class KONSOLEPRIVATE_EXPORT TerminalDisplay : public QWidget +{ + Q_OBJECT public: /** Constructs a new terminal display widget with the specified parent. */ @@ -89,24 +91,25 @@ public: /** Sets the opacity of the terminal display. */ void setOpacity(qreal opacity); - /** + /** * This enum describes the location where the scroll bar is positioned in the display widget. */ - enum ScrollBarPosition { + enum ScrollBarPosition + { /** Do not show the scroll bar. */ - NoScrollBar=0, + NoScrollBar=0, /** Show the scroll bar on the left side of the display. */ - ScrollBarLeft=1, + ScrollBarLeft=1, /** Show the scroll bar on the right side of the display. */ - ScrollBarRight=2 + ScrollBarRight=2 }; - /** + /** * Specifies whether the terminal display has a vertical scroll bar, and if so whether it * is shown on the left or right side of the display. */ void setScrollBarPosition(ScrollBarPosition position); - /** + /** * Sets the current position and range of the display's scroll bar. * * @param cursor The position of the scroll bar's thumb. @@ -114,7 +117,7 @@ public: */ void setScroll(int cursor, int lines); - /** + /** * Returns the display's filter chain. When the image for the display is updated, * the text is passed through each filter in the chain. Each filter can define * hotspots which correspond to certain strings (such as URLs or particular words). @@ -127,11 +130,11 @@ public: */ FilterChain* filterChain() const; - /** + /** * Updates the filters in the display's filter chain. This will cause * the hotspots to be updated to match the current image. * - * WARNING: This function can be expensive depending on the + * WARNING: This function can be expensive depending on the * image size and number of filters in the filterChain() * * TODO - This API does not really allow efficient usage. Revise it so @@ -140,50 +143,41 @@ public: * eg: * - Area of interest may be known ( eg. mouse cursor hovering * over an area ) - */ + */ void processFilters(); - /** + /** * Returns a list of menu actions created by the filters for the content * at the given @p position. */ QList filterActions(const QPoint& position); /** Returns true if the cursor is set to blink or false otherwise. */ - bool blinkingCursor() { - return _hasBlinkingCursor; - } + bool blinkingCursor() { return _hasBlinkingCursor; } /** Specifies whether or not the cursor blinks. */ void setBlinkingCursor(bool blink); /** Specifies whether or not text can blink. */ void setBlinkingTextEnabled(bool blink); - void setCtrlDrag(bool enable) { - _ctrlDrag=enable; - } - bool ctrlDrag() { - return _ctrlDrag; - } + void setCtrlDrag(bool enable) { _ctrlDrag=enable; } + bool ctrlDrag() { return _ctrlDrag; } - /** + /** * This enum describes the methods for selecting text when - * the user triple-clicks within the display. + * the user triple-clicks within the display. */ - enum TripleClickMode { + enum TripleClickMode + { /** Select the whole line underneath the cursor. */ SelectWholeLine, /** Select from the current cursor position to the end of the line. */ SelectForwardsFromCursor }; - /** Sets how the text is selected when the user triple clicks within the display. */ - void setTripleClickMode(TripleClickMode mode) { - _tripleClickMode = mode; - } + /** Sets how the text is selected when the user triple clicks within the display. */ + void setTripleClickMode(TripleClickMode mode) { _tripleClickMode = mode; } /** See setTripleClickSelectionMode() */ - TripleClickMode tripleClickMode() { - return _tripleClickMode; - } + TripleClickMode tripleClickMode() { return _tripleClickMode; } void setLineSpacing(uint); uint lineSpacing() const; @@ -194,25 +188,26 @@ public: * This enum describes the available shapes for the keyboard cursor. * See setKeyboardCursorShape() */ - enum KeyboardCursorShape { + enum KeyboardCursorShape + { /** A rectangular block which covers the entire area of the cursor character. */ BlockCursor, - /** + /** * A single flat line which occupies the space at the bottom of the cursor * character's area. */ UnderlineCursor, - /** - * An cursor shaped like the capital letter 'I', similar to the IBeam + /** + * An cursor shaped like the capital letter 'I', similar to the IBeam * cursor used in Qt/KDE text editors. */ IBeamCursor }; - /** - * Sets the shape of the keyboard cursor. This is the cursor drawn + /** + * Sets the shape of the keyboard cursor. This is the cursor drawn * at the position in the terminal where keyboard input will appear. * - * In addition the terminal display widget also has a cursor for + * In addition the terminal display widget also has a cursor for * the mouse pointer, which can be set using the QWidget::setCursor() * method. * @@ -225,7 +220,7 @@ public: KeyboardCursorShape keyboardCursorShape() const; /** - * Sets the color used to draw the keyboard cursor. + * Sets the color used to draw the keyboard cursor. * * The keyboard cursor defaults to using the foreground color of the character * underneath it. @@ -239,10 +234,10 @@ public: */ void setKeyboardCursorColor(bool useForegroundColor , const QColor& color); - /** + /** * Returns the color of the keyboard cursor, or an invalid color if the keyboard * cursor color is set to change according to the foreground color of the character - * underneath it. + * underneath it. */ QColor keyboardCursorColor() const; @@ -252,9 +247,7 @@ public: * This will depend upon the height of the widget and the current font. * See fontHeight() */ - int lines() { - return _lines; - } + int lines() { return _lines; } /** * Returns the number of characters of text which can be displayed on * each line in the widget. @@ -262,32 +255,26 @@ public: * This will depend upon the width of the widget and the current font. * See fontWidth() */ - int columns() { - return _columns; - } + int columns() { return _columns; } /** * Returns the height of the characters in the font used to draw the text in the display. */ - 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. */ - int fontWidth() { - return _fontWidth; - } + int fontWidth() { return _fontWidth; } void setSize(int cols, int lins); void setFixedSize(int cols, int lins); - + // reimplemented QSize sizeHint() const; /** - * Sets which characters, in addition to letters and numbers, + * Sets which characters, in addition to letters and numbers, * are regarded as being part of a word for the purposes * of selecting words in the display by double clicking on them. * @@ -298,69 +285,64 @@ public: * of a word ( in addition to letters and numbers ). */ void setWordCharacters(const QString& wc); - /** - * Returns the characters which are considered part of a word for the + /** + * Returns the characters which are considered part of a word for the * purpose of selecting words in the display with the mouse. * * @see setWordCharacters() */ - QString wordCharacters() { - return _wordCharacters; - } + QString wordCharacters() { return _wordCharacters; } - /** - * Sets the type of effect used to alert the user when a 'bell' occurs in the + /** + * Sets the type of effect used to alert the user when a 'bell' occurs in the * terminal session. * * The terminal session can trigger the bell effect by calling bell() with * the alert message. */ void setBellMode(int mode); - /** + /** * Returns the type of effect used to alert the user when a 'bell' occurs in * the terminal session. - * + * * See setBellMode() */ - int bellMode() { - return _bellMode; - } + int bellMode() { return _bellMode; } /** * This enum describes the different types of sounds and visual effects which * can be used to alert the user when a 'bell' occurs in the terminal * session. */ - enum BellMode { + enum BellMode + { /** A system beep. */ - SystemBeepBell=0, - /** + SystemBeepBell=0, + /** * KDE notification. This may play a sound, show a passive popup * or perform some other action depending on the user's settings. */ - NotifyBell=1, + NotifyBell=1, /** A silent, visual bell (eg. inverting the display's colors briefly) */ - VisualBell=2, + VisualBell=2, /** No bell effects */ - NoBell=3 + NoBell=3 }; void setSelection(const QString &t); - /** + /** * Reimplemented. Has no effect. Use setVTFont() to change the font * used to draw characters in the display. */ virtual void setFont(const QFont &); /** 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 - * is larger than the size of the display itself. + * is larger than the size of the display itself. */ void setVTFont(const QFont& font); @@ -368,69 +350,51 @@ public: * Specified whether anti-aliasing of text in the terminal display * 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. */ - static bool antialias() { - return _antialiasText; - } + static bool antialias() { return _antialiasText; } /** * Specifies whether characters with intense colors should be rendered * as bold. Defaults to true. */ - void setBoldIntense(bool value) { - _boldIntense = value; - } + void setBoldIntense(bool value) { _boldIntense = value; } /** * 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 * 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 * the terminal in lines and columns is displayed whilst the widget * is being resized. */ - bool terminalSizeHint() { - return _terminalSizeHint; - } - /** + bool terminalSizeHint() { return _terminalSizeHint; } + /** * Sets whether the terminal size display is shown briefly * after the widget is first shown. * * See setTerminalSizeHint() , isTerminalSizeHint() */ - void setTerminalSizeStartup(bool on) { - _terminalSizeStartup=on; - } + void setTerminalSizeStartup(bool on) { _terminalSizeStartup=on; } /** * Sets the status of the BiDi rendering inside the terminal display. * Defaults to disabled. */ - void setBidiEnabled(bool set) { - _bidiEnabled=set; - } + void setBidiEnabled(bool set) { _bidiEnabled=set; } /** * Returns the status of the BiDi rendering in this widget. */ - bool isBidiEnabled() { - return _bidiEnabled; - } + bool isBidiEnabled() { return _bidiEnabled; } /** * Sets the terminal screen section which is displayed in this widget. @@ -448,21 +412,21 @@ public: public slots: - /** + /** * Causes the terminal display to fetch the latest character image from the associated * terminal screen ( see setScreenWindow() ) and redraw the display. */ - void updateImage(); + void updateImage(); /** - * Causes the terminal display to fetch the latest line status flags from the - * associated terminal screen ( see setScreenWindow() ). - */ + * Causes the terminal display to fetch the latest line status flags from the + * associated terminal screen ( see setScreenWindow() ). + */ void updateLineProperties(); /** Copies the selected text to the clipboard. */ void copyClipboard(); - /** - * Pastes the content of the clipboard into the + /** + * Pastes the content of the clipboard into the * display. */ void pasteClipboard(); @@ -472,27 +436,26 @@ public slots: */ void pasteSelection(); - /** + /** * Changes whether the flow control warning box should be shown when the flow control * stop key (Ctrl+S) are pressed. */ void setFlowControlWarningEnabled(bool enabled); - /** - * Returns true if the flow control warning box is enabled. + /** + * Returns true if the flow control warning box is enabled. * See outputSuspended() and setFlowControlWarningEnabled() */ - bool flowControlWarningEnabled() const { - return _flowControlWarningEnabled; - } + bool flowControlWarningEnabled() const + { return _flowControlWarningEnabled; } - /** + /** * Causes the widget to display or hide a message informing the user that terminal * output has been suspended (by using the flow control key combination Ctrl+S) * * @param suspended True if terminal output has been suspended and the warning message should * be shown or false to indicate that terminal output has been resumed and that * the warning message should disappear. - */ + */ void outputSuspended(bool suspended); /** @@ -502,7 +465,7 @@ public slots: * If this is set to true, mouse signals will be emitted by the view when the user clicks, drags * or otherwise moves the mouse inside the view. * The user interaction needed to create selections will also change, and the user will be required - * to hold down the shift key to create a selection or perform other mouse activities inside the + * to hold down the shift key to create a selection or perform other mouse activities inside the * view area - since the program running in the terminal is being allowed to handle normal mouse * events itself. * @@ -510,40 +473,38 @@ public slots: * or false otherwise. */ void setUsesMouse(bool usesMouse); - + /** See setUsesMouse() */ bool usesMouse() const; - /** + /** * Shows a notification that a bell event has occurred in the terminal. * TODO: More documentation here */ void bell(const QString& message); - /** - * Sets the background of the display to the specified color. - * @see setColorTable(), setForegroundColor() + /** + * Sets the background of the display to the specified color. + * @see setColorTable(), setForegroundColor() */ void setBackgroundColor(const QColor& color); - /** - * Sets the text of the display to the specified color. + /** + * Sets the text of the display to the specified color. * @see setColorTable(), setBackgroundColor() */ void setForegroundColor(const QColor& color); - + void selectionChanged(); signals: - void copyAvailable(bool); - /** * Emitted when the user presses a key whilst the terminal widget has focus. */ void keyPressedSignal(QKeyEvent *e); - /** + /** * A mouse event occurred. * @param button The mouse button (0 for left button, 1 for middle button, 2 for right button, 3 for release) * @param column The character column where the event occurred @@ -554,7 +515,7 @@ signals: void changedFontMetricSignal(int height, int width); void changedContentSizeSignal(int height, int width); - /** + /** * Emitted when the user right clicks on the display, or right-clicks with the Shift * key held down if usesMouse() is true. * @@ -563,9 +524,9 @@ signals: void configureRequest(const QPoint& position); /** - * When a shortcut which is also a valid terminal key sequence is pressed while - * the terminal widget has focus, this signal is emitted to allow the host to decide - * whether the shortcut should be overridden. + * When a shortcut which is also a valid terminal key sequence is pressed while + * the terminal widget has focus, this signal is emitted to allow the host to decide + * whether the shortcut should be overridden. * When the shortcut is overridden, the key sequence will be sent to the terminal emulation instead * and the action associated with the shortcut will not be triggered. * @@ -573,12 +534,13 @@ signals: */ void overrideShortcutCheck(QKeyEvent* keyEvent,bool& override); - void isBusySelecting(bool); - void sendStringToEmu(const char*); - - //! Signals to inform that the widget get or lost focus - void termGetFocus(); - void termLostFocus(); + void isBusySelecting(bool); + void sendStringToEmu(const char*); + + // qtermwidget signals + void copyAvailable(bool); + void termGetFocus(); + void termLostFocus(); protected: virtual bool event( QEvent * ); @@ -601,7 +563,7 @@ protected: virtual void wheelEvent( QWheelEvent* ); virtual bool focusNextPrevChild( bool next ); - + // drag and drop virtual void dragEnterEvent(QDragEnterEvent* event); virtual void dropEvent(QDropEvent* event); @@ -609,15 +571,15 @@ protected: enum DragState { diNone, diPending, diDragging }; struct _dragInfo { - DragState state; - QPoint start; - QDrag *dragObject; + DragState state; + QPoint start; + QDrag *dragObject; } dragInfo; // classifies the 'ch' into one of three categories // and returns a character to indicate which category it is in // - // - A space (returns ' ') + // - A space (returns ' ') // - Part of a word (returns 'a') // - Other characters (returns the input character) QChar charClass(QChar ch) const; @@ -635,7 +597,7 @@ protected slots: void scrollBarPositionChanged(int value); void blinkEvent(); void blinkCursorEvent(); - + //Renables bell noises and visuals. Used to disable further bells for a short period of time //after emitting the first in a sequence of bell events. void enableBell(); @@ -651,12 +613,12 @@ private: // divides the part of the display specified by 'rect' into // fragments according to their colors and styles and calls - // drawTextFragment() to draw the fragments + // drawTextFragment() to draw the fragments void drawContents(QPainter &paint, const QRect &rect); // draws a section of text, all the text in this section // has a common color and style - void drawTextFragment(QPainter& painter, const QRect& rect, - const QString& text, const Character* style); + void drawTextFragment(QPainter& painter, const QRect& rect, + const QString& text, const Character* style); // draws the background for a text fragment // if useOpacitySetting is true then the color's alpha value will be set to // the display's transparency (set with setOpacity()), otherwise the background @@ -664,13 +626,13 @@ private: void drawBackground(QPainter& painter, const QRect& rect, const QColor& color, bool useOpacitySetting); // draws the cursor character - void drawCursor(QPainter& painter, const QRect& rect , const QColor& foregroundColor, - const QColor& backgroundColor , bool& invertColors); + void drawCursor(QPainter& painter, const QRect& rect , const QColor& foregroundColor, + const QColor& backgroundColor , bool& invertColors); // draws the characters or line graphics in a text fragment - void drawCharacters(QPainter& painter, const QRect& rect, const QString& text, - const Character* style, bool invertCharacterColor); + void drawCharacters(QPainter& painter, const QRect& rect, const QString& text, + const Character* style, bool invertCharacterColor); // draws a string of line graphics - void drawLineCharString(QPainter& painter, int x, int y, + void drawLineCharString(QPainter& painter, int x, int y, const QString& str, const Character* attributes); // draws the preedit string for input methods @@ -678,10 +640,10 @@ 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; - // 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. void getCharacterPosition(const QPoint& widgetPoint,int& line,int& column) const; @@ -692,8 +654,8 @@ private: // current size in columns and lines void showResizeNotification(); - // scrolls the image by a number of lines. - // 'lines' may be positive ( to scroll the image down ) + // scrolls the image by a number of lines. + // 'lines' may be positive ( to scroll the image down ) // or negative ( to scroll the image up ) // 'region' is the part of the image to scroll - currently only // the top, bottom and height of 'region' are taken into account, @@ -704,7 +666,7 @@ private: void propagateSize(); void updateImageSize(); void makeImage(); - + void paintFilters(QPainter& painter); // returns a region covering all of the areas of the widget which contain @@ -720,7 +682,7 @@ private: bool handleShortcutOverrideEvent(QKeyEvent* event); // the window onto the terminal screen which this display - // is currently showing. + // is currently showing. QPointer _screenWindow; bool _allowBell; @@ -738,19 +700,19 @@ private: int _lines; // the number of lines that can be displayed in the widget int _columns; // the number of columns that can be displayed in the widget - + int _usedLines; // the number of lines that are actually being used, this will be less - // than 'lines' if the character image provided with setImage() is smaller - // than the maximum image size which can be displayed + // than 'lines' if the character image provided with setImage() is smaller + // than the maximum image size which can be displayed int _usedColumns; // the number of columns that are actually being used, this will be less - // than 'columns' if the character image provided with setImage() is smaller - // than the maximum image size which can be displayed - + // than 'columns' if the character image provided with setImage() is smaller + // than the maximum image size which can be displayed + int _contentHeight; int _contentWidth; Character* _image; // [lines][columns] - // only the area [usedLines][usedColumns] in the image contains valid data + // only the area [usedLines][usedColumns] in the image contains valid data int _imageSize; QVector _lineProperties; @@ -790,12 +752,12 @@ private: QTimer* _blinkTimer; // active when hasBlinker QTimer* _blinkCursorTimer; // active when hasBlinkingCursor - //KMenu* _drop; + //QMenu* _drop; QString _dropText; int _dndFileCount; bool _possibleTripleClick; // is set in mouseDoubleClickEvent and deleted - // after QApplication::doubleClickInterval() delay + // after QApplication::doubleClickInterval() delay QLabel* _resizeWidget; @@ -805,14 +767,14 @@ private: //widgets related to the warning message that appears when the user presses Ctrl+S to suspend //terminal output - informing them what has happened and how to resume output - QLabel* _outputSuspendedLabel; - + QLabel* _outputSuspendedLabel; + uint _lineSpacing; bool _colorsInverted; // true during visual bell QSize _size; - + QRgb _blendColor; // list of filters currently applied to the display. used for links and @@ -824,10 +786,11 @@ private: // custom cursor color. if this is invalid then the foreground // color of the character under the cursor is used - QColor _cursorColor; + QColor _cursorColor; - struct InputMethodData { + struct InputMethodData + { QString preeditString; QRect previousPreeditRect; }; @@ -841,13 +804,15 @@ private: static const int DEFAULT_TOP_MARGIN = 1; public: - static void setTransparencyEnabled(bool enable) { + static void setTransparencyEnabled(bool enable) + { HAVE_TRANSPARENCY = enable; } }; -class AutoScrollHandler : public QObject { - Q_OBJECT +class AutoScrollHandler : public QObject +{ +Q_OBJECT public: AutoScrollHandler(QWidget* parent); @@ -855,9 +820,7 @@ protected: virtual void timerEvent(QTimerEvent* event); virtual bool eventFilter(QObject* watched,QEvent* event); private: - QWidget* widget() const { - return static_cast(parent()); - } + QWidget* widget() const { return static_cast(parent()); } int _timerId; }; diff --git a/lib/Vt102Emulation.cpp b/lib/Vt102Emulation.cpp index d467138..bce8b4b 100644 --- a/lib/Vt102Emulation.cpp +++ b/lib/Vt102Emulation.cpp @@ -1,8 +1,8 @@ /* This file is part of Konsole, an X terminal. - Copyright (C) 1997,1998 by Lars Doelle - - Rewritten for QT4 by e_k , Copyright (C)2008 + + Copyright 2007-2008 by Robert Knight + Copyright 1997,1998 by Lars Doelle This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -23,20 +23,21 @@ // Own #include "Vt102Emulation.h" +// XKB //#include - -#if defined(__osf__) || defined(__APPLE__) -#define AVOID_XKB -#endif - // this allows konsole to be compiled without XKB and XTEST extensions // even though it might be available on a particular system. #if defined(AVOID_XKB) -#undef HAVE_XKB + #undef HAVE_XKB #endif -// Standard +#if defined(HAVE_XKB) + void scrolllock_set_off(); + void scrolllock_set_on(); +#endif + +// Standard #include #include #include @@ -54,79 +55,40 @@ #include "KeyboardTranslator.h" #include "Screen.h" -#if defined(HAVE_XKB) -void scrolllock_set_off(); -void scrolllock_set_on(); -#endif using namespace Konsole; -/* VT102 Terminal Emulation - - This class puts together the screens, the pty and the widget to a - complete terminal emulation. Beside combining it's componentes, it - handles the emulations's protocol. - - This module consists of the following sections: - - - Constructor/Destructor - - Incoming Bytes Event pipeline - - Outgoing Bytes - - Mouse Events - - Keyboard Events - - Modes and Charset State - - Diagnostics -*/ - -/* ------------------------------------------------------------------------- */ -/* */ -/* Constructor / Destructor */ -/* */ -/* ------------------------------------------------------------------------- */ - - -Vt102Emulation::Vt102Emulation() - : Emulation(), - _titleUpdateTimer(new QTimer(this)) +Vt102Emulation::Vt102Emulation() + : Emulation(), + _titleUpdateTimer(new QTimer(this)) { - _titleUpdateTimer->setSingleShot(true); + _titleUpdateTimer->setSingleShot(true); + QObject::connect(_titleUpdateTimer , SIGNAL(timeout()) , this , SLOT(updateTitle())); - QObject::connect(_titleUpdateTimer , SIGNAL(timeout()) , this , SLOT(updateTitle())); - - initTokenizer(); - reset(); + initTokenizer(); + reset(); } Vt102Emulation::~Vt102Emulation() -{ -} +{} void Vt102Emulation::clearEntireScreen() { - _currentScreen->clearEntireScreen(); - - bufferedUpdate(); + _currentScreen->clearEntireScreen(); + bufferedUpdate(); } void Vt102Emulation::reset() { - //kDebug(1211)<<"Vt102Emulation::reset() resetToken()"; - resetToken(); - //kDebug(1211)<<"Vt102Emulation::reset() resetModes()"; - resetModes(); - //kDebug(1211)<<"Vt102Emulation::reset() resetCharSet()"; - resetCharset(0); - //kDebug(1211)<<"Vt102Emulation::reset() reset screen0()"; - _screen[0]->reset(); - //kDebug(1211)<<"Vt102Emulation::reset() resetCharSet()"; - resetCharset(1); - //kDebug(1211)<<"Vt102Emulation::reset() reset _screen 1"; - _screen[1]->reset(); - //kDebug(1211)<<"Vt102Emulation::reset() setCodec()"; - setCodec(LocaleCodec); - //kDebug(1211)<<"Vt102Emulation::reset() done"; - - bufferedUpdate(); + resetTokenizer(); + resetModes(); + resetCharset(0); + _screen[0]->reset(); + resetCharset(1); + _screen[1]->reset(); + setCodec(LocaleCodec); + + bufferedUpdate(); } /* ------------------------------------------------------------------------- */ @@ -146,7 +108,7 @@ void Vt102Emulation::reset() - Tokenizing the ESC codes (onReceiveChar) - VT100 code page translation of plain characters (applyCharset) - - Interpretation of ESC codes (tau) + - Interpretation of ESC codes (processToken) The escape codes and their meaning are described in the technical reference of this program. @@ -176,8 +138,9 @@ void Vt102Emulation::reset() - VT52 - VT52 escape codes - - 'Y'{Pc}{Pc} - - XTE_HA - Xterm hacks `]' {Pn} `;' {Text} - note that this is handled differently + - XTE_HA - Xterm window/terminal attribute commands + of the form `]' {Pn} `;' {Text} + (Note that these are handled differently to the other formats) The last two forms allow list of arguments. Since the elements of the lists are treated individually the same way, they are passed @@ -187,97 +150,92 @@ void Vt102Emulation::reset() */ -#define TY_CONSTR(T,A,N) ( ((((int)N) & 0xffff) << 16) | ((((int)A) & 0xff) << 8) | (((int)T) & 0xff) ) +#define TY_CONSTRUCT(T,A,N) ( ((((int)N) & 0xffff) << 16) | ((((int)A) & 0xff) << 8) | (((int)T) & 0xff) ) -#define TY_CHR( ) TY_CONSTR(0,0,0) -#define TY_CTL(A ) TY_CONSTR(1,A,0) -#define TY_ESC(A ) TY_CONSTR(2,A,0) -#define TY_ESC_CS(A,B) TY_CONSTR(3,A,B) -#define TY_ESC_DE(A ) TY_CONSTR(4,A,0) -#define TY_CSI_PS(A,N) TY_CONSTR(5,A,N) -#define TY_CSI_PN(A ) TY_CONSTR(6,A,0) -#define TY_CSI_PR(A,N) TY_CONSTR(7,A,N) +#define TY_CHR( ) TY_CONSTRUCT(0,0,0) +#define TY_CTL(A ) TY_CONSTRUCT(1,A,0) +#define TY_ESC(A ) TY_CONSTRUCT(2,A,0) +#define TY_ESC_CS(A,B) TY_CONSTRUCT(3,A,B) +#define TY_ESC_DE(A ) TY_CONSTRUCT(4,A,0) +#define TY_CSI_PS(A,N) TY_CONSTRUCT(5,A,N) +#define TY_CSI_PN(A ) TY_CONSTRUCT(6,A,0) +#define TY_CSI_PR(A,N) TY_CONSTRUCT(7,A,N) -#define TY_VT52(A ) TY_CONSTR(8,A,0) +#define TY_VT52(A) TY_CONSTRUCT(8,A,0) +#define TY_CSI_PG(A) TY_CONSTRUCT(9,A,0) +#define TY_CSI_PE(A) TY_CONSTRUCT(10,A,0) -#define TY_CSI_PG(A ) TY_CONSTR(9,A,0) - -#define TY_CSI_PE(A ) TY_CONSTR(10,A,0) +#define MAX_ARGUMENT 4096 // Tokenizer --------------------------------------------------------------- -- -/* The tokenizers state +/* The tokenizer's state - The state is represented by the buffer (pbuf, ppos), + The state is represented by the buffer (tokenBuffer, tokenBufferPos), and accompanied by decoded arguments kept in (argv,argc). Note that they are kept internal in the tokenizer. */ -void Vt102Emulation::resetToken() +void Vt102Emulation::resetTokenizer() { - ppos = 0; - argc = 0; - argv[0] = 0; - argv[1] = 0; + tokenBufferPos = 0; + argc = 0; + argv[0] = 0; + argv[1] = 0; } -void Vt102Emulation::addDigit(int dig) +void Vt102Emulation::addDigit(int digit) { - argv[argc] = 10*argv[argc] + dig; + if (argv[argc] < MAX_ARGUMENT) + argv[argc] = 10*argv[argc] + digit; } void Vt102Emulation::addArgument() { - argc = qMin(argc+1,MAXARGS-1); - argv[argc] = 0; + argc = qMin(argc+1,MAXARGS-1); + argv[argc] = 0; } -void Vt102Emulation::pushToToken(int cc) +void Vt102Emulation::addToCurrentToken(int cc) { - pbuf[ppos] = cc; - ppos = qMin(ppos+1,MAXPBUF-1); + tokenBuffer[tokenBufferPos] = cc; + tokenBufferPos = qMin(tokenBufferPos+1,MAX_TOKEN_LENGTH-1); } -// Character Classes used while decoding +// Character Class flags used while decoding -#define CTL 1 -#define CHR 2 -#define CPN 4 -#define DIG 8 -#define SCS 16 -#define GRP 32 -#define CPS 64 +#define CTL 1 // Control character +#define CHR 2 // Printable character +#define CPN 4 // TODO: Document me +#define DIG 8 // Digit +#define SCS 16 // TODO: Document me +#define GRP 32 // TODO: Document me +#define CPS 64 // Character which indicates end of window resize + // escape sequence '\e[8;;t' void Vt102Emulation::initTokenizer() -{ - int i; - quint8 * s; - for (i = 0; i < 256; i++) { - tbl[ i] = 0; - } - for (i = 0; i < 32; i++) { - tbl[ i] |= CTL; - } - for (i = 32; i < 256; i++) { - tbl[ i] |= CHR; - } - for (s = (quint8 *)"@ABCDGHILMPSTXZcdfry"; *s; s++) { - tbl[*s] |= CPN; - } -// resize = \e[8;;t - for (s = (quint8 *)"t"; *s; s++) { - tbl[*s] |= CPS; - } - for (s = (quint8 *)"0123456789" ; *s; s++) { - tbl[*s] |= DIG; - } - for (s = (quint8 *)"()+*%" ; *s; s++) { - tbl[*s] |= SCS; - } - for (s = (quint8 *)"()+*#[]%" ; *s; s++) { - tbl[*s] |= GRP; - } - resetToken(); +{ + int i; + quint8* s; + for(i = 0;i < 256; ++i) + charClass[i] = 0; + for(i = 0;i < 32; ++i) + charClass[i] |= CTL; + for(i = 32;i < 256; ++i) + charClass[i] |= CHR; + for(s = (quint8*)"@ABCDGHILMPSTXZcdfry"; *s; ++s) + charClass[*s] |= CPN; + // resize = \e[8;;t + for(s = (quint8*)"t"; *s; ++s) + charClass[*s] |= CPS; + for(s = (quint8*)"0123456789"; *s; ++s) + charClass[*s] |= DIG; + for(s = (quint8*)"()+*%"; *s; ++s) + charClass[*s] |= SCS; + for(s = (quint8*)"()+*#[]%"; *s; ++s) + charClass[*s] |= GRP; + + resetTokenizer(); } /* Ok, here comes the nasty part of the decoder. @@ -290,197 +248,160 @@ void Vt102Emulation::initTokenizer() - P is the length of the token scanned so far. - L (often P-1) is the position on which contents we base a decision. - - C is a character or a group of characters (taken from 'tbl'). + - C is a character or a group of characters (taken from 'charClass'). + + - 'cc' is the current character + - 's' is a pointer to the start of the token buffer + - 'p' is the current position within the token buffer Note that they need to applied in proper order. */ -#define lec(P,L,C) (p == (P) && s[(L)] == (C)) -#define lun( ) (p == 1 && cc >= 32 ) -#define les(P,L,C) (p == (P) && s[L] < 256 && (tbl[s[(L)]] & (C)) == (C)) -#define eec(C) (p >= 3 && cc == (C)) -#define ees(C) (p >= 3 && cc < 256 && (tbl[ cc ] & (C)) == (C)) -#define eps(C) (p >= 3 && s[2] != '?' && s[2] != '!' && s[2] != '>' && cc < 256 && (tbl[ cc ] & (C)) == (C)) -#define epp( ) (p >= 3 && s[2] == '?' ) -#define epe( ) (p >= 3 && s[2] == '!' ) -#define egt( ) (p >= 3 && s[2] == '>' ) -#define Xpe (ppos>=2 && pbuf[1] == ']' ) -#define Xte (Xpe && cc == 7 ) -#define ces(C) ( cc < 256 && (tbl[ cc ] & (C)) == (C) && !Xte) +#define lec(P,L,C) (p == (P) && s[(L)] == (C)) +#define lun( ) (p == 1 && cc >= 32 ) +#define les(P,L,C) (p == (P) && s[L] < 256 && (charClass[s[(L)]] & (C)) == (C)) +#define eec(C) (p >= 3 && cc == (C)) +#define ees(C) (p >= 3 && cc < 256 && (charClass[cc] & (C)) == (C)) +#define eps(C) (p >= 3 && s[2] != '?' && s[2] != '!' && s[2] != '>' && cc < 256 && (charClass[cc] & (C)) == (C)) +#define epp( ) (p >= 3 && s[2] == '?') +#define epe( ) (p >= 3 && s[2] == '!') +#define egt( ) (p >= 3 && s[2] == '>') +#define Xpe (tokenBufferPos >= 2 && tokenBuffer[1] == ']') +#define Xte (Xpe && cc == 7 ) +#define ces(C) (cc < 256 && (charClass[cc] & (C)) == (C) && !Xte) #define ESC 27 #define CNTL(c) ((c)-'@') // process an incoming unicode character - void Vt102Emulation::receiveChar(int cc) -{ - int i; - if (cc == 127) { - return; //VT100: ignore. +{ + if (cc == 127) + return; //VT100: ignore. + + if (ces(CTL)) + { + // DEC HACK ALERT! Control Characters are allowed *within* esc sequences in VT100 + // This means, they do neither a resetTokenizer() nor a pushToToken(). Some of them, do + // of course. Guess this originates from a weakly layered handling of the X-on + // X-off protocol, which comes really below this level. + if (cc == CNTL('X') || cc == CNTL('Z') || cc == ESC) + resetTokenizer(); //VT100: CAN or SUB + if (cc != ESC) + { + processToken(TY_CTL(cc+'@' ),0,0); + return; + } + } + // advance the state + addToCurrentToken(cc); + + int* s = tokenBuffer; + int p = tokenBufferPos; + + if (getMode(MODE_Ansi)) + { + if (lec(1,0,ESC)) { return; } + if (lec(1,0,ESC+128)) { s[0] = ESC; receiveChar('['); return; } + if (les(2,1,GRP)) { return; } + if (Xte ) { processWindowAttributeChange(); resetTokenizer(); return; } + if (Xpe ) { return; } + if (lec(3,2,'?')) { return; } + if (lec(3,2,'>')) { return; } + if (lec(3,2,'!')) { return; } + if (lun( )) { processToken( TY_CHR(), applyCharset(cc), 0); resetTokenizer(); return; } + if (lec(2,0,ESC)) { processToken( TY_ESC(s[1]), 0, 0); resetTokenizer(); return; } + if (les(3,1,SCS)) { processToken( TY_ESC_CS(s[1],s[2]), 0, 0); resetTokenizer(); return; } + if (lec(3,1,'#')) { processToken( TY_ESC_DE(s[2]), 0, 0); resetTokenizer(); return; } + if (eps( CPN)) { processToken( TY_CSI_PN(cc), argv[0],argv[1]); resetTokenizer(); return; } + + // resize = \e[8;;t + if (eps(CPS)) + { + processToken( TY_CSI_PS(cc, argv[0]), argv[1], argv[2]); + resetTokenizer(); + return; } - if (ces( CTL)) { - // DEC HACK ALERT! Control Characters are allowed *within* esc sequences in VT100 - // This means, they do neither a resetToken nor a pushToToken. Some of them, do - // of course. Guess this originates from a weakly layered handling of the X-on - // X-off protocol, which comes really below this level. - if (cc == CNTL('X') || cc == CNTL('Z') || cc == ESC) { - resetToken(); //VT100: CAN or SUB + if (epe( )) { processToken( TY_CSI_PE(cc), 0, 0); resetTokenizer(); return; } + if (ees(DIG)) { addDigit(cc-'0'); return; } + if (eec(';')) { addArgument(); return; } + for (int i=0;i<=argc;i++) + { + if (epp()) + processToken( TY_CSI_PR(cc,argv[i]), 0, 0); + else if (egt()) + processToken( TY_CSI_PG(cc), 0, 0); // spec. case for ESC]>0c or ESC]>c + else if (cc == 'm' && argc - i >= 4 && (argv[i] == 38 || argv[i] == 48) && argv[i+1] == 2) + { + // ESC[ ... 48;2;;; ... m -or- ESC[ ... 38;2;;; ... m + i += 2; + processToken( TY_CSI_PS(cc, argv[i-2]), COLOR_SPACE_RGB, (argv[i] << 16) | (argv[i+1] << 8) | argv[i+2]); + i += 2; } - if (cc != ESC) { - tau( TY_CTL(cc+'@' ), 0, 0); - return; + else if (cc == 'm' && argc - i >= 2 && (argv[i] == 38 || argv[i] == 48) && argv[i+1] == 5) + { + // ESC[ ... 48;5; ... m -or- ESC[ ... 38;5; ... m + i += 2; + processToken( TY_CSI_PS(cc, argv[i-2]), COLOR_SPACE_256, argv[i]); } + else + processToken( TY_CSI_PS(cc,argv[i]), 0, 0); } - - pushToToken(cc); // advance the state - - int * s = pbuf; - int p = ppos; - - if (getMode(MODE_Ansi)) { // decide on proper action - if (lec(1,0,ESC)) { - return; - } - if (lec(1,0,ESC+128)) { - s[0] = ESC; - receiveChar('['); - return; - } - if (les(2,1,GRP)) { - return; - } - if (Xte ) { - XtermHack(); - resetToken(); - return; - } - if (Xpe ) { - return; - } - if (lec(3,2,'?')) { - return; - } - if (lec(3,2,'>')) { - return; - } - if (lec(3,2,'!')) { - return; - } - if (lun( )) { - tau( TY_CHR(), applyCharset(cc), 0); - resetToken(); - return; - } - if (lec(2,0,ESC)) { - tau( TY_ESC(s[1]), 0, 0); - resetToken(); - return; - } - if (les(3,1,SCS)) { - tau( TY_ESC_CS(s[1],s[2]), 0, 0); - resetToken(); - return; - } - if (lec(3,1,'#')) { - tau( TY_ESC_DE(s[2]), 0, 0); - resetToken(); - return; - } - if (eps( CPN)) { - tau( TY_CSI_PN(cc), argv[0],argv[1]); - resetToken(); - return; - } - -// resize = \e[8;;t - if (eps( CPS)) { - tau( TY_CSI_PS(cc, argv[0]), argv[1], argv[2]); - resetToken(); - return; - } - - if (epe( )) { - tau( TY_CSI_PE(cc), 0, 0); - resetToken(); - return; - } - if (ees( DIG)) { - addDigit(cc-'0'); - return; - } - if (eec( ';')) { - addArgument(); - return; - } - for (i=0; i<=argc; i++) - if ( epp( )) { - tau( TY_CSI_PR(cc,argv[i]), 0, 0); - } else if (egt( )) { - tau( TY_CSI_PG(cc ), 0, 0); // spec. case for ESC]>0c or ESC]>c - } else if (cc == 'm' && argc - i >= 4 && (argv[i] == 38 || argv[i] == 48) && argv[i+1] == 2) { - // ESC[ ... 48;2;;; ... m -or- ESC[ ... 38;2;;; ... m - i += 2; - tau( TY_CSI_PS(cc, argv[i-2]), COLOR_SPACE_RGB, (argv[i] << 16) | (argv[i+1] << 8) | argv[i+2]); - i += 2; - } else if (cc == 'm' && argc - i >= 2 && (argv[i] == 38 || argv[i] == 48) && argv[i+1] == 5) { - // ESC[ ... 48;5; ... m -or- ESC[ ... 38;5; ... m - i += 2; - tau( TY_CSI_PS(cc, argv[i-2]), COLOR_SPACE_256, argv[i]); - } else { - tau( TY_CSI_PS(cc,argv[i]), 0, 0); - } - resetToken(); - } else { // mode VT52 - if (lec(1,0,ESC)) { - return; - } - if (les(1,0,CHR)) { - tau( TY_CHR( ), s[0], 0); - resetToken(); - return; - } - if (lec(2,1,'Y')) { - return; - } - if (lec(3,1,'Y')) { - return; - } - if (p < 4) { - tau( TY_VT52(s[1] ), 0, 0); - resetToken(); - return; - } - tau( TY_VT52(s[1] ), s[2],s[3]); - resetToken(); + resetTokenizer(); + } + else + { + // VT52 Mode + if (lec(1,0,ESC)) return; + if (les(1,0,CHR)) + { + processToken( TY_CHR(), s[0], 0); + resetTokenizer(); + return; } + if (lec(2,1,'Y')) + return; + if (lec(3,1,'Y')) + return; + if (p < 4) + { + processToken( TY_VT52(s[1] ), 0, 0); + resetTokenizer(); + return; + } + processToken( TY_VT52(s[1]), s[2], s[3]); + resetTokenizer(); + return; + } } - -void Vt102Emulation::XtermHack() +void Vt102Emulation::processWindowAttributeChange() { - int i,arg = 0; - for (i = 2; i < ppos && '0'<=pbuf[i] && pbuf[i]<'9' ; i++) { - arg = 10*arg + (pbuf[i]-'0'); - } - if (pbuf[i] != ';') { - ReportErrorToken(); - return; - } - QChar * str = new QChar[ppos-i-2]; - for (int j = 0; j < ppos-i-2; j++) { - str[j] = pbuf[i+1+j]; - } - QString unistr(str,ppos-i-2); + // Describes the window or terminal session attribute to change + // See Session::UserTitleChange for possible values + int attributeToChange = 0; + int i; + for (i = 2; i < tokenBufferPos && + tokenBuffer[i] >= '0' && + tokenBuffer[i] <= '9'; i++) + { + attributeToChange = 10 * attributeToChange + (tokenBuffer[i]-'0'); + } - // arg == 1 doesn't change the title. In XTerm it only changes the icon name - // (btw: arg=0 changes title and icon, arg=1 only icon, arg=2 only title -// emit changeTitle(arg,unistr); - _pendingTitleUpdates[arg] = unistr; - _titleUpdateTimer->start(20); - - delete [] str; + if (tokenBuffer[i] != ';') + { + reportDecodingError(); + return; + } + + QString newValue; + newValue.reserve(tokenBufferPos-i-2); + for (int j = 0; j < tokenBufferPos-i-2; j++) + newValue[j] = tokenBuffer[i+1+j]; + + _pendingTitleUpdates[attributeToChange] = newValue; + _titleUpdateTimer->start(20); } void Vt102Emulation::updateTitle() @@ -488,10 +409,9 @@ void Vt102Emulation::updateTitle() QListIterator iter( _pendingTitleUpdates.keys() ); while (iter.hasNext()) { int arg = iter.next(); - emit titleChanged( arg , _pendingTitleUpdates[arg] ); + emit titleChanged( arg , _pendingTitleUpdates[arg] ); } - - _pendingTitleUpdates.clear(); + _pendingTitleUpdates.clear(); } // Interpreting Codes --------------------------------------------------------- @@ -512,1025 +432,497 @@ void Vt102Emulation::updateTitle() about this mapping. */ -void Vt102Emulation::tau( int token, int p, int q ) +void Vt102Emulation::processToken(int token, int p, int q) { -#if 0 - int N = (token>>0)&0xff; - int A = (token>>8)&0xff; - switch ( N ) { - case 0: - printf("%c", (p < 128) ? p : '?'); - break; - case 1: - if (A == 'J') { - printf("\r"); - } else if (A == 'M') { - printf("\n"); - } else { - printf("CTL-%c ", (token>>8)&0xff); - } - break; - case 2: - printf("ESC-%c ", (token>>8)&0xff); - break; - case 3: - printf("ESC_CS-%c-%c ", (token>>8)&0xff, (token>>16)&0xff); - break; - case 4: - printf("ESC_DE-%c ", (token>>8)&0xff); - break; - case 5: - printf("CSI-PS-%c-%d", (token>>8)&0xff, (token>>16)&0xff ); - break; - case 6: - printf("CSI-PN-%c [%d]", (token>>8)&0xff, p); - break; - case 7: - printf("CSI-PR-%c-%d", (token>>8)&0xff, (token>>16)&0xff ); - break; - case 8: - printf("VT52-%c", (token>>8)&0xff); - break; - case 9: - printf("CSI-PG-%c", (token>>8)&0xff); - break; - case 10: - printf("CSI-PE-%c", (token>>8)&0xff); - break; - } -#endif + switch (token) + { - switch (token) { + case TY_CHR( ) : _currentScreen->displayCharacter (p ); break; //UTF16 - case TY_CHR( ) : - _currentScreen->ShowCharacter (p ); - break; //UTF16 + // 127 DEL : ignored on input - // 127 DEL : ignored on input + case TY_CTL('@' ) : /* NUL: ignored */ break; + case TY_CTL('A' ) : /* SOH: ignored */ break; + case TY_CTL('B' ) : /* STX: ignored */ break; + case TY_CTL('C' ) : /* ETX: ignored */ break; + case TY_CTL('D' ) : /* EOT: ignored */ break; + case TY_CTL('E' ) : reportAnswerBack ( ); break; //VT100 + case TY_CTL('F' ) : /* ACK: ignored */ break; + case TY_CTL('G' ) : emit stateSet(NOTIFYBELL); + break; //VT100 + case TY_CTL('H' ) : _currentScreen->backspace ( ); break; //VT100 + case TY_CTL('I' ) : _currentScreen->tab ( ); break; //VT100 + case TY_CTL('J' ) : _currentScreen->newLine ( ); break; //VT100 + case TY_CTL('K' ) : _currentScreen->newLine ( ); break; //VT100 + case TY_CTL('L' ) : _currentScreen->newLine ( ); break; //VT100 + case TY_CTL('M' ) : _currentScreen->toStartOfLine ( ); break; //VT100 - case TY_CTL('@' ) : /* NUL: ignored */ - break; - case TY_CTL('A' ) : /* SOH: ignored */ - break; - case TY_CTL('B' ) : /* STX: ignored */ - break; - case TY_CTL('C' ) : /* ETX: ignored */ - break; - case TY_CTL('D' ) : /* EOT: ignored */ - break; - case TY_CTL('E' ) : - reportAnswerBack ( ); - break; //VT100 - case TY_CTL('F' ) : /* ACK: ignored */ - break; - case TY_CTL('G' ) : - emit stateSet(NOTIFYBELL); - break; //VT100 - case TY_CTL('H' ) : - _currentScreen->BackSpace ( ); - break; //VT100 - case TY_CTL('I' ) : - _currentScreen->Tabulate ( ); - break; //VT100 - case TY_CTL('J' ) : - _currentScreen->NewLine ( ); - break; //VT100 - case TY_CTL('K' ) : - _currentScreen->NewLine ( ); - break; //VT100 - case TY_CTL('L' ) : - _currentScreen->NewLine ( ); - break; //VT100 - case TY_CTL('M' ) : - _currentScreen->Return ( ); - break; //VT100 + case TY_CTL('N' ) : useCharset ( 1); break; //VT100 + case TY_CTL('O' ) : useCharset ( 0); break; //VT100 - case TY_CTL('N' ) : - useCharset ( 1); - break; //VT100 - case TY_CTL('O' ) : - useCharset ( 0); - break; //VT100 + case TY_CTL('P' ) : /* DLE: ignored */ break; + case TY_CTL('Q' ) : /* DC1: XON continue */ break; //VT100 + case TY_CTL('R' ) : /* DC2: ignored */ break; + case TY_CTL('S' ) : /* DC3: XOFF halt */ break; //VT100 + case TY_CTL('T' ) : /* DC4: ignored */ break; + case TY_CTL('U' ) : /* NAK: ignored */ break; + case TY_CTL('V' ) : /* SYN: ignored */ break; + case TY_CTL('W' ) : /* ETB: ignored */ break; + case TY_CTL('X' ) : _currentScreen->displayCharacter ( 0x2592); break; //VT100 + case TY_CTL('Y' ) : /* EM : ignored */ break; + case TY_CTL('Z' ) : _currentScreen->displayCharacter ( 0x2592); break; //VT100 + case TY_CTL('[' ) : /* ESC: cannot be seen here. */ break; + case TY_CTL('\\' ) : /* FS : ignored */ break; + case TY_CTL(']' ) : /* GS : ignored */ break; + case TY_CTL('^' ) : /* RS : ignored */ break; + case TY_CTL('_' ) : /* US : ignored */ break; - case TY_CTL('P' ) : /* DLE: ignored */ - break; - case TY_CTL('Q' ) : /* DC1: XON continue */ - break; //VT100 - case TY_CTL('R' ) : /* DC2: ignored */ - break; - case TY_CTL('S' ) : /* DC3: XOFF halt */ - break; //VT100 - case TY_CTL('T' ) : /* DC4: ignored */ - break; - case TY_CTL('U' ) : /* NAK: ignored */ - break; - case TY_CTL('V' ) : /* SYN: ignored */ - break; - case TY_CTL('W' ) : /* ETB: ignored */ - break; - case TY_CTL('X' ) : - _currentScreen->ShowCharacter ( 0x2592); - break; //VT100 - case TY_CTL('Y' ) : /* EM : ignored */ - break; - case TY_CTL('Z' ) : - _currentScreen->ShowCharacter ( 0x2592); - break; //VT100 - case TY_CTL('[' ) : /* ESC: cannot be seen here. */ - break; - case TY_CTL('\\' ) : /* FS : ignored */ - break; - case TY_CTL(']' ) : /* GS : ignored */ - break; - case TY_CTL('^' ) : /* RS : ignored */ - break; - case TY_CTL('_' ) : /* US : ignored */ - break; + case TY_ESC('D' ) : _currentScreen->index ( ); break; //VT100 + case TY_ESC('E' ) : _currentScreen->nextLine ( ); break; //VT100 + case TY_ESC('H' ) : _currentScreen->changeTabStop (true ); break; //VT100 + case TY_ESC('M' ) : _currentScreen->reverseIndex ( ); break; //VT100 + case TY_ESC('Z' ) : reportTerminalType ( ); break; + case TY_ESC('c' ) : reset ( ); break; - case TY_ESC('D' ) : - _currentScreen->index ( ); - break; //VT100 - case TY_ESC('E' ) : - _currentScreen->NextLine ( ); - break; //VT100 - case TY_ESC('H' ) : - _currentScreen->changeTabStop (true ); - break; //VT100 - case TY_ESC('M' ) : - _currentScreen->reverseIndex ( ); - break; //VT100 - case TY_ESC('Z' ) : - reportTerminalType ( ); - break; - case TY_ESC('c' ) : - reset ( ); - break; + case TY_ESC('n' ) : useCharset ( 2); break; + case TY_ESC('o' ) : useCharset ( 3); break; + case TY_ESC('7' ) : saveCursor ( ); break; + case TY_ESC('8' ) : restoreCursor ( ); break; - case TY_ESC('n' ) : - useCharset ( 2); - break; - case TY_ESC('o' ) : - useCharset ( 3); - break; - case TY_ESC('7' ) : - saveCursor ( ); - break; - case TY_ESC('8' ) : - restoreCursor ( ); - break; + case TY_ESC('=' ) : setMode (MODE_AppKeyPad); break; + case TY_ESC('>' ) : resetMode (MODE_AppKeyPad); break; + case TY_ESC('<' ) : setMode (MODE_Ansi ); break; //VT100 - case TY_ESC('=' ) : - setMode (MODE_AppKeyPad); - break; - case TY_ESC('>' ) : - resetMode (MODE_AppKeyPad); - break; - case TY_ESC('<' ) : - setMode (MODE_Ansi ); - break; //VT100 + case TY_ESC_CS('(', '0') : setCharset (0, '0'); break; //VT100 + case TY_ESC_CS('(', 'A') : setCharset (0, 'A'); break; //VT100 + case TY_ESC_CS('(', 'B') : setCharset (0, 'B'); break; //VT100 - case TY_ESC_CS('(', '0') : - setCharset (0, '0'); - break; //VT100 - case TY_ESC_CS('(', 'A') : - setCharset (0, 'A'); - break; //VT100 - case TY_ESC_CS('(', 'B') : - setCharset (0, 'B'); - break; //VT100 + case TY_ESC_CS(')', '0') : setCharset (1, '0'); break; //VT100 + case TY_ESC_CS(')', 'A') : setCharset (1, 'A'); break; //VT100 + case TY_ESC_CS(')', 'B') : setCharset (1, 'B'); break; //VT100 - case TY_ESC_CS(')', '0') : - setCharset (1, '0'); - break; //VT100 - case TY_ESC_CS(')', 'A') : - setCharset (1, 'A'); - break; //VT100 - case TY_ESC_CS(')', 'B') : - setCharset (1, 'B'); - break; //VT100 + case TY_ESC_CS('*', '0') : setCharset (2, '0'); break; //VT100 + case TY_ESC_CS('*', 'A') : setCharset (2, 'A'); break; //VT100 + case TY_ESC_CS('*', 'B') : setCharset (2, 'B'); break; //VT100 - case TY_ESC_CS('*', '0') : - setCharset (2, '0'); - break; //VT100 - case TY_ESC_CS('*', 'A') : - setCharset (2, 'A'); - break; //VT100 - case TY_ESC_CS('*', 'B') : - setCharset (2, 'B'); - break; //VT100 + case TY_ESC_CS('+', '0') : setCharset (3, '0'); break; //VT100 + case TY_ESC_CS('+', 'A') : setCharset (3, 'A'); break; //VT100 + case TY_ESC_CS('+', 'B') : setCharset (3, 'B'); break; //VT100 - case TY_ESC_CS('+', '0') : - setCharset (3, '0'); - break; //VT100 - case TY_ESC_CS('+', 'A') : - setCharset (3, 'A'); - break; //VT100 - case TY_ESC_CS('+', 'B') : - setCharset (3, 'B'); - break; //VT100 + case TY_ESC_CS('%', 'G') : setCodec (Utf8Codec ); break; //LINUX + case TY_ESC_CS('%', '@') : setCodec (LocaleCodec ); break; //LINUX - case TY_ESC_CS('%', 'G') : - setCodec (Utf8Codec ); - break; //LINUX - case TY_ESC_CS('%', '@') : - setCodec (LocaleCodec ); - break; //LINUX - - case TY_ESC_DE('3' ) : /* Double height line, top half */ - _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , true ); - _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , true ); - break; - case TY_ESC_DE('4' ) : /* Double height line, bottom half */ - _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , true ); - _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , true ); - break; + case TY_ESC_DE('3' ) : /* Double height line, top half */ + _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , true ); + _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , true ); + break; + case TY_ESC_DE('4' ) : /* Double height line, bottom half */ + _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , true ); + _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , true ); + break; case TY_ESC_DE('5' ) : /* Single width, single height line*/ - _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , false); - _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , false); - break; - case TY_ESC_DE('6' ) : /* Double width, single height line*/ - _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , true); - _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , false); - break; - case TY_ESC_DE('8' ) : - _currentScreen->helpAlign ( ); - break; + _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , false); + _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , false); + break; + case TY_ESC_DE('6' ) : /* Double width, single height line*/ + _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , true); + _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , false); + break; + case TY_ESC_DE('8' ) : _currentScreen->helpAlign ( ); break; // resize = \e[8;;t - case TY_CSI_PS('t', 8) : - setImageSize( q /* colums */, p /* lines */ ); - break; + case TY_CSI_PS('t', 8) : setImageSize( q /* columns */, p /* lines */ ); break; // change tab text color : \e[28;t color: 0-16,777,215 - case TY_CSI_PS('t', 28) : - emit changeTabTextColorRequest ( p ); - break; + case TY_CSI_PS('t', 28) : emit changeTabTextColorRequest ( p ); break; - case TY_CSI_PS('K', 0) : - _currentScreen->clearToEndOfLine ( ); - break; - case TY_CSI_PS('K', 1) : - _currentScreen->clearToBeginOfLine ( ); - break; - case TY_CSI_PS('K', 2) : - _currentScreen->clearEntireLine ( ); - break; - case TY_CSI_PS('J', 0) : - _currentScreen->clearToEndOfScreen ( ); - break; - case TY_CSI_PS('J', 1) : - _currentScreen->clearToBeginOfScreen ( ); - break; - case TY_CSI_PS('J', 2) : - _currentScreen->clearEntireScreen ( ); - break; - case TY_CSI_PS('g', 0) : - _currentScreen->changeTabStop (false ); - break; //VT100 - case TY_CSI_PS('g', 3) : - _currentScreen->clearTabStops ( ); - break; //VT100 - case TY_CSI_PS('h', 4) : - _currentScreen-> setMode (MODE_Insert ); - break; - case TY_CSI_PS('h', 20) : - setMode (MODE_NewLine ); - break; - case TY_CSI_PS('i', 0) : /* IGNORE: attached printer */ - break; //VT100 - case TY_CSI_PS('l', 4) : - _currentScreen-> resetMode (MODE_Insert ); - break; - case TY_CSI_PS('l', 20) : - resetMode (MODE_NewLine ); - break; - case TY_CSI_PS('s', 0) : - saveCursor ( ); - break; - case TY_CSI_PS('u', 0) : - restoreCursor ( ); - break; + case TY_CSI_PS('K', 0) : _currentScreen->clearToEndOfLine ( ); break; + case TY_CSI_PS('K', 1) : _currentScreen->clearToBeginOfLine ( ); break; + case TY_CSI_PS('K', 2) : _currentScreen->clearEntireLine ( ); break; + case TY_CSI_PS('J', 0) : _currentScreen->clearToEndOfScreen ( ); break; + case TY_CSI_PS('J', 1) : _currentScreen->clearToBeginOfScreen ( ); break; + case TY_CSI_PS('J', 2) : _currentScreen->clearEntireScreen ( ); break; + case TY_CSI_PS('J', 3) : clearHistory(); break; + case TY_CSI_PS('g', 0) : _currentScreen->changeTabStop (false ); break; //VT100 + case TY_CSI_PS('g', 3) : _currentScreen->clearTabStops ( ); break; //VT100 + case TY_CSI_PS('h', 4) : _currentScreen-> setMode (MODE_Insert ); break; + case TY_CSI_PS('h', 20) : setMode (MODE_NewLine ); break; + case TY_CSI_PS('i', 0) : /* IGNORE: attached printer */ break; //VT100 + case TY_CSI_PS('l', 4) : _currentScreen-> resetMode (MODE_Insert ); break; + case TY_CSI_PS('l', 20) : resetMode (MODE_NewLine ); break; + case TY_CSI_PS('s', 0) : saveCursor ( ); break; + case TY_CSI_PS('u', 0) : restoreCursor ( ); break; - case TY_CSI_PS('m', 0) : - _currentScreen->setDefaultRendition ( ); - break; - case TY_CSI_PS('m', 1) : - _currentScreen-> setRendition (RE_BOLD ); - break; //VT100 - case TY_CSI_PS('m', 4) : - _currentScreen-> setRendition (RE_UNDERLINE); - break; //VT100 - case TY_CSI_PS('m', 5) : - _currentScreen-> setRendition (RE_BLINK ); - break; //VT100 - case TY_CSI_PS('m', 7) : - _currentScreen-> setRendition (RE_REVERSE ); - break; - case TY_CSI_PS('m', 10) : /* IGNORED: mapping related */ - break; //LINUX - case TY_CSI_PS('m', 11) : /* IGNORED: mapping related */ - break; //LINUX - case TY_CSI_PS('m', 12) : /* IGNORED: mapping related */ - break; //LINUX - case TY_CSI_PS('m', 22) : - _currentScreen->resetRendition (RE_BOLD ); - break; - case TY_CSI_PS('m', 24) : - _currentScreen->resetRendition (RE_UNDERLINE); - break; - case TY_CSI_PS('m', 25) : - _currentScreen->resetRendition (RE_BLINK ); - break; - case TY_CSI_PS('m', 27) : - _currentScreen->resetRendition (RE_REVERSE ); - break; + case TY_CSI_PS('m', 0) : _currentScreen->setDefaultRendition ( ); break; + case TY_CSI_PS('m', 1) : _currentScreen-> setRendition (RE_BOLD ); break; //VT100 + case TY_CSI_PS('m', 4) : _currentScreen-> setRendition (RE_UNDERLINE); break; //VT100 + case TY_CSI_PS('m', 5) : _currentScreen-> setRendition (RE_BLINK ); break; //VT100 + case TY_CSI_PS('m', 7) : _currentScreen-> setRendition (RE_REVERSE ); break; + case TY_CSI_PS('m', 10) : /* IGNORED: mapping related */ break; //LINUX + case TY_CSI_PS('m', 11) : /* IGNORED: mapping related */ break; //LINUX + case TY_CSI_PS('m', 12) : /* IGNORED: mapping related */ break; //LINUX + case TY_CSI_PS('m', 22) : _currentScreen->resetRendition (RE_BOLD ); break; + case TY_CSI_PS('m', 24) : _currentScreen->resetRendition (RE_UNDERLINE); break; + case TY_CSI_PS('m', 25) : _currentScreen->resetRendition (RE_BLINK ); break; + case TY_CSI_PS('m', 27) : _currentScreen->resetRendition (RE_REVERSE ); break; - case TY_CSI_PS('m', 30) : - _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 0); - break; - case TY_CSI_PS('m', 31) : - _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 1); - break; - case TY_CSI_PS('m', 32) : - _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 2); - break; - case TY_CSI_PS('m', 33) : - _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 3); - break; - case TY_CSI_PS('m', 34) : - _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 4); - break; - case TY_CSI_PS('m', 35) : - _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 5); - break; - case TY_CSI_PS('m', 36) : - _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 6); - break; - case TY_CSI_PS('m', 37) : - _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 7); - break; + case TY_CSI_PS('m', 30) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 0); break; + case TY_CSI_PS('m', 31) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 1); break; + case TY_CSI_PS('m', 32) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 2); break; + case TY_CSI_PS('m', 33) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 3); break; + case TY_CSI_PS('m', 34) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 4); break; + case TY_CSI_PS('m', 35) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 5); break; + case TY_CSI_PS('m', 36) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 6); break; + case TY_CSI_PS('m', 37) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 7); break; - case TY_CSI_PS('m', 38) : - _currentScreen->setForeColor (p, q); - break; + case TY_CSI_PS('m', 38) : _currentScreen->setForeColor (p, q); break; - case TY_CSI_PS('m', 39) : - _currentScreen->setForeColor (COLOR_SPACE_DEFAULT, 0); - break; + case TY_CSI_PS('m', 39) : _currentScreen->setForeColor (COLOR_SPACE_DEFAULT, 0); break; - case TY_CSI_PS('m', 40) : - _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 0); - break; - case TY_CSI_PS('m', 41) : - _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 1); - break; - case TY_CSI_PS('m', 42) : - _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 2); - break; - case TY_CSI_PS('m', 43) : - _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 3); - break; - case TY_CSI_PS('m', 44) : - _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 4); - break; - case TY_CSI_PS('m', 45) : - _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 5); - break; - case TY_CSI_PS('m', 46) : - _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 6); - break; - case TY_CSI_PS('m', 47) : - _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 7); - break; + case TY_CSI_PS('m', 40) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 0); break; + case TY_CSI_PS('m', 41) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 1); break; + case TY_CSI_PS('m', 42) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 2); break; + case TY_CSI_PS('m', 43) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 3); break; + case TY_CSI_PS('m', 44) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 4); break; + case TY_CSI_PS('m', 45) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 5); break; + case TY_CSI_PS('m', 46) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 6); break; + case TY_CSI_PS('m', 47) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 7); break; - case TY_CSI_PS('m', 48) : - _currentScreen->setBackColor (p, q); + case TY_CSI_PS('m', 48) : _currentScreen->setBackColor (p, q); break; + + case TY_CSI_PS('m', 49) : _currentScreen->setBackColor (COLOR_SPACE_DEFAULT, 1); break; + + case TY_CSI_PS('m', 90) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 8); break; + case TY_CSI_PS('m', 91) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 9); break; + case TY_CSI_PS('m', 92) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 10); break; + case TY_CSI_PS('m', 93) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 11); break; + case TY_CSI_PS('m', 94) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 12); break; + case TY_CSI_PS('m', 95) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 13); break; + case TY_CSI_PS('m', 96) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 14); break; + case TY_CSI_PS('m', 97) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 15); break; + + case TY_CSI_PS('m', 100) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 8); break; + case TY_CSI_PS('m', 101) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 9); break; + case TY_CSI_PS('m', 102) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 10); break; + case TY_CSI_PS('m', 103) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 11); break; + case TY_CSI_PS('m', 104) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 12); break; + case TY_CSI_PS('m', 105) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 13); break; + case TY_CSI_PS('m', 106) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 14); break; + case TY_CSI_PS('m', 107) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 15); break; + + case TY_CSI_PS('n', 5) : reportStatus ( ); break; + case TY_CSI_PS('n', 6) : reportCursorPosition ( ); break; + case TY_CSI_PS('q', 0) : /* IGNORED: LEDs off */ break; //VT100 + case TY_CSI_PS('q', 1) : /* IGNORED: LED1 on */ break; //VT100 + case TY_CSI_PS('q', 2) : /* IGNORED: LED2 on */ break; //VT100 + case TY_CSI_PS('q', 3) : /* IGNORED: LED3 on */ break; //VT100 + case TY_CSI_PS('q', 4) : /* IGNORED: LED4 on */ break; //VT100 + case TY_CSI_PS('x', 0) : reportTerminalParms ( 2); break; //VT100 + case TY_CSI_PS('x', 1) : reportTerminalParms ( 3); break; //VT100 + + case TY_CSI_PN('@' ) : _currentScreen->insertChars (p ); break; + case TY_CSI_PN('A' ) : _currentScreen->cursorUp (p ); break; //VT100 + case TY_CSI_PN('B' ) : _currentScreen->cursorDown (p ); break; //VT100 + case TY_CSI_PN('C' ) : _currentScreen->cursorRight (p ); break; //VT100 + case TY_CSI_PN('D' ) : _currentScreen->cursorLeft (p ); break; //VT100 + case TY_CSI_PN('G' ) : _currentScreen->setCursorX (p ); break; //LINUX + case TY_CSI_PN('H' ) : _currentScreen->setCursorYX (p, q); break; //VT100 + case TY_CSI_PN('I' ) : _currentScreen->tab (p ); break; + case TY_CSI_PN('L' ) : _currentScreen->insertLines (p ); break; + case TY_CSI_PN('M' ) : _currentScreen->deleteLines (p ); break; + case TY_CSI_PN('P' ) : _currentScreen->deleteChars (p ); break; + case TY_CSI_PN('S' ) : _currentScreen->scrollUp (p ); break; + case TY_CSI_PN('T' ) : _currentScreen->scrollDown (p ); break; + case TY_CSI_PN('X' ) : _currentScreen->eraseChars (p ); break; + case TY_CSI_PN('Z' ) : _currentScreen->backtab (p ); break; + case TY_CSI_PN('c' ) : reportTerminalType ( ); break; //VT100 + case TY_CSI_PN('d' ) : _currentScreen->setCursorY (p ); break; //LINUX + case TY_CSI_PN('f' ) : _currentScreen->setCursorYX (p, q); break; //VT100 + case TY_CSI_PN('r' ) : setMargins (p, q); break; //VT100 + case TY_CSI_PN('y' ) : /* IGNORED: Confidence test */ break; //VT100 + + case TY_CSI_PR('h', 1) : setMode (MODE_AppCuKeys); break; //VT100 + case TY_CSI_PR('l', 1) : resetMode (MODE_AppCuKeys); break; //VT100 + case TY_CSI_PR('s', 1) : saveMode (MODE_AppCuKeys); break; //FIXME + case TY_CSI_PR('r', 1) : restoreMode (MODE_AppCuKeys); break; //FIXME + + case TY_CSI_PR('l', 2) : resetMode (MODE_Ansi ); break; //VT100 + + case TY_CSI_PR('h', 3) : setMode (MODE_132Columns);break; //VT100 + case TY_CSI_PR('l', 3) : resetMode (MODE_132Columns);break; //VT100 + + case TY_CSI_PR('h', 4) : /* IGNORED: soft scrolling */ break; //VT100 + case TY_CSI_PR('l', 4) : /* IGNORED: soft scrolling */ break; //VT100 + + case TY_CSI_PR('h', 5) : _currentScreen-> setMode (MODE_Screen ); break; //VT100 + case TY_CSI_PR('l', 5) : _currentScreen-> resetMode (MODE_Screen ); break; //VT100 + + case TY_CSI_PR('h', 6) : _currentScreen-> setMode (MODE_Origin ); break; //VT100 + case TY_CSI_PR('l', 6) : _currentScreen-> resetMode (MODE_Origin ); break; //VT100 + case TY_CSI_PR('s', 6) : _currentScreen-> saveMode (MODE_Origin ); break; //FIXME + case TY_CSI_PR('r', 6) : _currentScreen->restoreMode (MODE_Origin ); break; //FIXME + + case TY_CSI_PR('h', 7) : _currentScreen-> setMode (MODE_Wrap ); break; //VT100 + case TY_CSI_PR('l', 7) : _currentScreen-> resetMode (MODE_Wrap ); break; //VT100 + case TY_CSI_PR('s', 7) : _currentScreen-> saveMode (MODE_Wrap ); break; //FIXME + case TY_CSI_PR('r', 7) : _currentScreen->restoreMode (MODE_Wrap ); break; //FIXME + + case TY_CSI_PR('h', 8) : /* IGNORED: autorepeat on */ break; //VT100 + case TY_CSI_PR('l', 8) : /* IGNORED: autorepeat off */ break; //VT100 + case TY_CSI_PR('s', 8) : /* IGNORED: autorepeat on */ break; //VT100 + case TY_CSI_PR('r', 8) : /* IGNORED: autorepeat off */ break; //VT100 + + case TY_CSI_PR('h', 9) : /* IGNORED: interlace */ break; //VT100 + case TY_CSI_PR('l', 9) : /* IGNORED: interlace */ break; //VT100 + case TY_CSI_PR('s', 9) : /* IGNORED: interlace */ break; //VT100 + case TY_CSI_PR('r', 9) : /* IGNORED: interlace */ break; //VT100 + + case TY_CSI_PR('h', 12) : /* IGNORED: Cursor blink */ break; //att610 + case TY_CSI_PR('l', 12) : /* IGNORED: Cursor blink */ break; //att610 + case TY_CSI_PR('s', 12) : /* IGNORED: Cursor blink */ break; //att610 + case TY_CSI_PR('r', 12) : /* IGNORED: Cursor blink */ break; //att610 + + case TY_CSI_PR('h', 25) : setMode (MODE_Cursor ); break; //VT100 + case TY_CSI_PR('l', 25) : resetMode (MODE_Cursor ); break; //VT100 + case TY_CSI_PR('s', 25) : saveMode (MODE_Cursor ); break; //VT100 + case TY_CSI_PR('r', 25) : restoreMode (MODE_Cursor ); break; //VT100 + + case TY_CSI_PR('h', 40) : setMode(MODE_Allow132Columns ); break; // XTERM + case TY_CSI_PR('l', 40) : resetMode(MODE_Allow132Columns ); break; // XTERM + + case TY_CSI_PR('h', 41) : /* IGNORED: obsolete more(1) fix */ break; //XTERM + case TY_CSI_PR('l', 41) : /* IGNORED: obsolete more(1) fix */ break; //XTERM + case TY_CSI_PR('s', 41) : /* IGNORED: obsolete more(1) fix */ break; //XTERM + case TY_CSI_PR('r', 41) : /* IGNORED: obsolete more(1) fix */ break; //XTERM + + case TY_CSI_PR('h', 47) : setMode (MODE_AppScreen); break; //VT100 + case TY_CSI_PR('l', 47) : resetMode (MODE_AppScreen); break; //VT100 + case TY_CSI_PR('s', 47) : saveMode (MODE_AppScreen); break; //XTERM + case TY_CSI_PR('r', 47) : restoreMode (MODE_AppScreen); break; //XTERM + + case TY_CSI_PR('h', 67) : /* IGNORED: DECBKM */ break; //XTERM + case TY_CSI_PR('l', 67) : /* IGNORED: DECBKM */ break; //XTERM + case TY_CSI_PR('s', 67) : /* IGNORED: DECBKM */ break; //XTERM + case TY_CSI_PR('r', 67) : /* IGNORED: DECBKM */ break; //XTERM + + // XTerm defines the following modes: + // SET_VT200_MOUSE 1000 + // SET_VT200_HIGHLIGHT_MOUSE 1001 + // SET_BTN_EVENT_MOUSE 1002 + // SET_ANY_EVENT_MOUSE 1003 + // + + //Note about mouse modes: + //There are four mouse modes which xterm-compatible terminals can support - 1000,1001,1002,1003 + //Konsole currently supports mode 1000 (basic mouse press and release) and mode 1002 (dragging the mouse). + //TODO: Implementation of mouse modes 1001 (something called hilight tracking) and + //1003 (a slight variation on dragging the mouse) + // + + case TY_CSI_PR('h', 1000) : setMode (MODE_Mouse1000); break; //XTERM + case TY_CSI_PR('l', 1000) : resetMode (MODE_Mouse1000); break; //XTERM + case TY_CSI_PR('s', 1000) : saveMode (MODE_Mouse1000); break; //XTERM + case TY_CSI_PR('r', 1000) : restoreMode (MODE_Mouse1000); break; //XTERM + + case TY_CSI_PR('h', 1001) : /* IGNORED: hilite mouse tracking */ break; //XTERM + case TY_CSI_PR('l', 1001) : resetMode (MODE_Mouse1001); break; //XTERM + case TY_CSI_PR('s', 1001) : /* IGNORED: hilite mouse tracking */ break; //XTERM + case TY_CSI_PR('r', 1001) : /* IGNORED: hilite mouse tracking */ break; //XTERM + + case TY_CSI_PR('h', 1002) : setMode (MODE_Mouse1002); break; //XTERM + case TY_CSI_PR('l', 1002) : resetMode (MODE_Mouse1002); break; //XTERM + case TY_CSI_PR('s', 1002) : saveMode (MODE_Mouse1002); break; //XTERM + case TY_CSI_PR('r', 1002) : restoreMode (MODE_Mouse1002); break; //XTERM + + case TY_CSI_PR('h', 1003) : setMode (MODE_Mouse1003); break; //XTERM + case TY_CSI_PR('l', 1003) : resetMode (MODE_Mouse1003); break; //XTERM + case TY_CSI_PR('s', 1003) : saveMode (MODE_Mouse1003); break; //XTERM + case TY_CSI_PR('r', 1003) : restoreMode (MODE_Mouse1003); break; //XTERM + + case TY_CSI_PR('h', 1034) : /* IGNORED: 8bitinput activation */ break; //XTERM + + case TY_CSI_PR('h', 1047) : setMode (MODE_AppScreen); break; //XTERM + case TY_CSI_PR('l', 1047) : _screen[1]->clearEntireScreen(); resetMode(MODE_AppScreen); break; //XTERM + case TY_CSI_PR('s', 1047) : saveMode (MODE_AppScreen); break; //XTERM + case TY_CSI_PR('r', 1047) : restoreMode (MODE_AppScreen); break; //XTERM + + //FIXME: Unitoken: save translations + case TY_CSI_PR('h', 1048) : saveCursor ( ); break; //XTERM + case TY_CSI_PR('l', 1048) : restoreCursor ( ); break; //XTERM + case TY_CSI_PR('s', 1048) : saveCursor ( ); break; //XTERM + case TY_CSI_PR('r', 1048) : restoreCursor ( ); break; //XTERM + + //FIXME: every once new sequences like this pop up in xterm. + // Here's a guess of what they could mean. + case TY_CSI_PR('h', 1049) : saveCursor(); _screen[1]->clearEntireScreen(); setMode(MODE_AppScreen); break; //XTERM + case TY_CSI_PR('l', 1049) : resetMode(MODE_AppScreen); restoreCursor(); break; //XTERM + + //FIXME: weird DEC reset sequence + case TY_CSI_PE('p' ) : /* IGNORED: reset ( ) */ break; + + //FIXME: when changing between vt52 and ansi mode evtl do some resetting. + case TY_VT52('A' ) : _currentScreen->cursorUp ( 1); break; //VT52 + case TY_VT52('B' ) : _currentScreen->cursorDown ( 1); break; //VT52 + case TY_VT52('C' ) : _currentScreen->cursorRight ( 1); break; //VT52 + case TY_VT52('D' ) : _currentScreen->cursorLeft ( 1); break; //VT52 + + case TY_VT52('F' ) : setAndUseCharset (0, '0'); break; //VT52 + case TY_VT52('G' ) : setAndUseCharset (0, 'B'); break; //VT52 + + case TY_VT52('H' ) : _currentScreen->setCursorYX (1,1 ); break; //VT52 + case TY_VT52('I' ) : _currentScreen->reverseIndex ( ); break; //VT52 + case TY_VT52('J' ) : _currentScreen->clearToEndOfScreen ( ); break; //VT52 + case TY_VT52('K' ) : _currentScreen->clearToEndOfLine ( ); break; //VT52 + case TY_VT52('Y' ) : _currentScreen->setCursorYX (p-31,q-31 ); break; //VT52 + case TY_VT52('Z' ) : reportTerminalType ( ); break; //VT52 + case TY_VT52('<' ) : setMode (MODE_Ansi ); break; //VT52 + case TY_VT52('=' ) : setMode (MODE_AppKeyPad); break; //VT52 + case TY_VT52('>' ) : resetMode (MODE_AppKeyPad); break; //VT52 + + case TY_CSI_PG('c' ) : reportSecondaryAttributes( ); break; //VT100 + + default: + reportDecodingError(); break; - - case TY_CSI_PS('m', 49) : - _currentScreen->setBackColor (COLOR_SPACE_DEFAULT, 1); - break; - - case TY_CSI_PS('m', 90) : - _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 8); - break; - case TY_CSI_PS('m', 91) : - _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 9); - break; - case TY_CSI_PS('m', 92) : - _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 10); - break; - case TY_CSI_PS('m', 93) : - _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 11); - break; - case TY_CSI_PS('m', 94) : - _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 12); - break; - case TY_CSI_PS('m', 95) : - _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 13); - break; - case TY_CSI_PS('m', 96) : - _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 14); - break; - case TY_CSI_PS('m', 97) : - _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 15); - break; - - case TY_CSI_PS('m', 100) : - _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 8); - break; - case TY_CSI_PS('m', 101) : - _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 9); - break; - case TY_CSI_PS('m', 102) : - _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 10); - break; - case TY_CSI_PS('m', 103) : - _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 11); - break; - case TY_CSI_PS('m', 104) : - _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 12); - break; - case TY_CSI_PS('m', 105) : - _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 13); - break; - case TY_CSI_PS('m', 106) : - _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 14); - break; - case TY_CSI_PS('m', 107) : - _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 15); - break; - - case TY_CSI_PS('n', 5) : - reportStatus ( ); - break; - case TY_CSI_PS('n', 6) : - reportCursorPosition ( ); - break; - case TY_CSI_PS('q', 0) : /* IGNORED: LEDs off */ - break; //VT100 - case TY_CSI_PS('q', 1) : /* IGNORED: LED1 on */ - break; //VT100 - case TY_CSI_PS('q', 2) : /* IGNORED: LED2 on */ - break; //VT100 - case TY_CSI_PS('q', 3) : /* IGNORED: LED3 on */ - break; //VT100 - case TY_CSI_PS('q', 4) : /* IGNORED: LED4 on */ - break; //VT100 - case TY_CSI_PS('x', 0) : - reportTerminalParms ( 2); - break; //VT100 - case TY_CSI_PS('x', 1) : - reportTerminalParms ( 3); - break; //VT100 - - case TY_CSI_PN('@' ) : - _currentScreen->insertChars (p ); - break; - case TY_CSI_PN('A' ) : - _currentScreen->cursorUp (p ); - break; //VT100 - case TY_CSI_PN('B' ) : - _currentScreen->cursorDown (p ); - break; //VT100 - case TY_CSI_PN('C' ) : - _currentScreen->cursorRight (p ); - break; //VT100 - case TY_CSI_PN('D' ) : - _currentScreen->cursorLeft (p ); - break; //VT100 - case TY_CSI_PN('G' ) : - _currentScreen->setCursorX (p ); - break; //LINUX - case TY_CSI_PN('H' ) : - _currentScreen->setCursorYX (p, q); - break; //VT100 - case TY_CSI_PN('I' ) : - _currentScreen->Tabulate (p ); - break; - case TY_CSI_PN('L' ) : - _currentScreen->insertLines (p ); - break; - case TY_CSI_PN('M' ) : - _currentScreen->deleteLines (p ); - break; - case TY_CSI_PN('P' ) : - _currentScreen->deleteChars (p ); - break; - case TY_CSI_PN('S' ) : - _currentScreen->scrollUp (p ); - break; - case TY_CSI_PN('T' ) : - _currentScreen->scrollDown (p ); - break; - case TY_CSI_PN('X' ) : - _currentScreen->eraseChars (p ); - break; - case TY_CSI_PN('Z' ) : - _currentScreen->backTabulate (p ); - break; - case TY_CSI_PN('c' ) : - reportTerminalType ( ); - break; //VT100 - case TY_CSI_PN('d' ) : - _currentScreen->setCursorY (p ); - break; //LINUX - case TY_CSI_PN('f' ) : - _currentScreen->setCursorYX (p, q); - break; //VT100 - case TY_CSI_PN('r' ) : - setMargins (p, q); - break; //VT100 - case TY_CSI_PN('y' ) : /* IGNORED: Confidence test */ - break; //VT100 - - case TY_CSI_PR('h', 1) : - setMode (MODE_AppCuKeys); - break; //VT100 - case TY_CSI_PR('l', 1) : - resetMode (MODE_AppCuKeys); - break; //VT100 - case TY_CSI_PR('s', 1) : - saveMode (MODE_AppCuKeys); - break; //FIXME - case TY_CSI_PR('r', 1) : - restoreMode (MODE_AppCuKeys); - break; //FIXME - - case TY_CSI_PR('l', 2) : - resetMode (MODE_Ansi ); - break; //VT100 - - case TY_CSI_PR('h', 3) : - clearScreenAndSetColumns(132); - break; //VT100 - case TY_CSI_PR('l', 3) : - clearScreenAndSetColumns(80); - break; //VT100 - - case TY_CSI_PR('h', 4) : /* IGNORED: soft scrolling */ - break; //VT100 - case TY_CSI_PR('l', 4) : /* IGNORED: soft scrolling */ - break; //VT100 - - case TY_CSI_PR('h', 5) : - _currentScreen-> setMode (MODE_Screen ); - break; //VT100 - case TY_CSI_PR('l', 5) : - _currentScreen-> resetMode (MODE_Screen ); - break; //VT100 - - case TY_CSI_PR('h', 6) : - _currentScreen-> setMode (MODE_Origin ); - break; //VT100 - case TY_CSI_PR('l', 6) : - _currentScreen-> resetMode (MODE_Origin ); - break; //VT100 - case TY_CSI_PR('s', 6) : - _currentScreen-> saveMode (MODE_Origin ); - break; //FIXME - case TY_CSI_PR('r', 6) : - _currentScreen->restoreMode (MODE_Origin ); - break; //FIXME - - case TY_CSI_PR('h', 7) : - _currentScreen-> setMode (MODE_Wrap ); - break; //VT100 - case TY_CSI_PR('l', 7) : - _currentScreen-> resetMode (MODE_Wrap ); - break; //VT100 - case TY_CSI_PR('s', 7) : - _currentScreen-> saveMode (MODE_Wrap ); - break; //FIXME - case TY_CSI_PR('r', 7) : - _currentScreen->restoreMode (MODE_Wrap ); - break; //FIXME - - case TY_CSI_PR('h', 8) : /* IGNORED: autorepeat on */ - break; //VT100 - case TY_CSI_PR('l', 8) : /* IGNORED: autorepeat off */ - break; //VT100 - case TY_CSI_PR('s', 8) : /* IGNORED: autorepeat on */ - break; //VT100 - case TY_CSI_PR('r', 8) : /* IGNORED: autorepeat off */ - break; //VT100 - - case TY_CSI_PR('h', 9) : /* IGNORED: interlace */ - break; //VT100 - case TY_CSI_PR('l', 9) : /* IGNORED: interlace */ - break; //VT100 - case TY_CSI_PR('s', 9) : /* IGNORED: interlace */ - break; //VT100 - case TY_CSI_PR('r', 9) : /* IGNORED: interlace */ - break; //VT100 - - case TY_CSI_PR('h', 12) : /* IGNORED: Cursor blink */ - break; //att610 - case TY_CSI_PR('l', 12) : /* IGNORED: Cursor blink */ - break; //att610 - case TY_CSI_PR('s', 12) : /* IGNORED: Cursor blink */ - break; //att610 - case TY_CSI_PR('r', 12) : /* IGNORED: Cursor blink */ - break; //att610 - - case TY_CSI_PR('h', 25) : - setMode (MODE_Cursor ); - break; //VT100 - case TY_CSI_PR('l', 25) : - resetMode (MODE_Cursor ); - break; //VT100 - case TY_CSI_PR('s', 25) : - saveMode (MODE_Cursor ); - break; //VT100 - case TY_CSI_PR('r', 25) : - restoreMode (MODE_Cursor ); - break; //VT100 - - case TY_CSI_PR('h', 41) : /* IGNORED: obsolete more(1) fix */ - break; //XTERM - case TY_CSI_PR('l', 41) : /* IGNORED: obsolete more(1) fix */ - break; //XTERM - case TY_CSI_PR('s', 41) : /* IGNORED: obsolete more(1) fix */ - break; //XTERM - case TY_CSI_PR('r', 41) : /* IGNORED: obsolete more(1) fix */ - break; //XTERM - - case TY_CSI_PR('h', 47) : - setMode (MODE_AppScreen); - break; //VT100 - case TY_CSI_PR('l', 47) : - resetMode (MODE_AppScreen); - break; //VT100 - case TY_CSI_PR('s', 47) : - saveMode (MODE_AppScreen); - break; //XTERM - case TY_CSI_PR('r', 47) : - restoreMode (MODE_AppScreen); - break; //XTERM - - case TY_CSI_PR('h', 67) : /* IGNORED: DECBKM */ - break; //XTERM - case TY_CSI_PR('l', 67) : /* IGNORED: DECBKM */ - break; //XTERM - case TY_CSI_PR('s', 67) : /* IGNORED: DECBKM */ - break; //XTERM - case TY_CSI_PR('r', 67) : /* IGNORED: DECBKM */ - break; //XTERM - - // XTerm defines the following modes: - // SET_VT200_MOUSE 1000 - // SET_VT200_HIGHLIGHT_MOUSE 1001 - // SET_BTN_EVENT_MOUSE 1002 - // SET_ANY_EVENT_MOUSE 1003 - // - - //Note about mouse modes: - //There are four mouse modes which xterm-compatible terminals can support - 1000,1001,1002,1003 - //Konsole currently supports mode 1000 (basic mouse press and release) and mode 1002 (dragging the mouse). - //TODO: Implementation of mouse modes 1001 (something called hilight tracking) and - //1003 (a slight variation on dragging the mouse) - // - - case TY_CSI_PR('h', 1000) : - setMode (MODE_Mouse1000); - break; //XTERM - case TY_CSI_PR('l', 1000) : - resetMode (MODE_Mouse1000); - break; //XTERM - case TY_CSI_PR('s', 1000) : - saveMode (MODE_Mouse1000); - break; //XTERM - case TY_CSI_PR('r', 1000) : - restoreMode (MODE_Mouse1000); - break; //XTERM - - case TY_CSI_PR('h', 1001) : /* IGNORED: hilite mouse tracking */ - break; //XTERM - case TY_CSI_PR('l', 1001) : - resetMode (MODE_Mouse1001); - break; //XTERM - case TY_CSI_PR('s', 1001) : /* IGNORED: hilite mouse tracking */ - break; //XTERM - case TY_CSI_PR('r', 1001) : /* IGNORED: hilite mouse tracking */ - break; //XTERM - - case TY_CSI_PR('h', 1002) : - setMode (MODE_Mouse1002); - break; //XTERM - case TY_CSI_PR('l', 1002) : - resetMode (MODE_Mouse1002); - break; //XTERM - case TY_CSI_PR('s', 1002) : - saveMode (MODE_Mouse1002); - break; //XTERM - case TY_CSI_PR('r', 1002) : - restoreMode (MODE_Mouse1002); - break; //XTERM - - case TY_CSI_PR('h', 1003) : - setMode (MODE_Mouse1003); - break; //XTERM - case TY_CSI_PR('l', 1003) : - resetMode (MODE_Mouse1003); - break; //XTERM - case TY_CSI_PR('s', 1003) : - saveMode (MODE_Mouse1003); - break; //XTERM - case TY_CSI_PR('r', 1003) : - restoreMode (MODE_Mouse1003); - break; //XTERM - - case TY_CSI_PR('h', 1047) : - setMode (MODE_AppScreen); - break; //XTERM - case TY_CSI_PR('l', 1047) : - _screen[1]->clearEntireScreen(); - resetMode(MODE_AppScreen); - break; //XTERM - case TY_CSI_PR('s', 1047) : - saveMode (MODE_AppScreen); - break; //XTERM - case TY_CSI_PR('r', 1047) : - restoreMode (MODE_AppScreen); - break; //XTERM - - //FIXME: Unitoken: save translations - case TY_CSI_PR('h', 1048) : - saveCursor ( ); - break; //XTERM - case TY_CSI_PR('l', 1048) : - restoreCursor ( ); - break; //XTERM - case TY_CSI_PR('s', 1048) : - saveCursor ( ); - break; //XTERM - case TY_CSI_PR('r', 1048) : - restoreCursor ( ); - break; //XTERM - - //FIXME: every once new sequences like this pop up in xterm. - // Here's a guess of what they could mean. - case TY_CSI_PR('h', 1049) : - saveCursor(); - _screen[1]->clearEntireScreen(); - setMode(MODE_AppScreen); - break; //XTERM - case TY_CSI_PR('l', 1049) : - resetMode(MODE_AppScreen); - restoreCursor(); - break; //XTERM - - //FIXME: weird DEC reset sequence - case TY_CSI_PE('p' ) : /* IGNORED: reset ( ) */ - break; - - //FIXME: when changing between vt52 and ansi mode evtl do some resetting. - case TY_VT52('A' ) : - _currentScreen->cursorUp ( 1); - break; //VT52 - case TY_VT52('B' ) : - _currentScreen->cursorDown ( 1); - break; //VT52 - case TY_VT52('C' ) : - _currentScreen->cursorRight ( 1); - break; //VT52 - case TY_VT52('D' ) : - _currentScreen->cursorLeft ( 1); - break; //VT52 - - case TY_VT52('F' ) : - setAndUseCharset (0, '0'); - break; //VT52 - case TY_VT52('G' ) : - setAndUseCharset (0, 'B'); - break; //VT52 - - case TY_VT52('H' ) : - _currentScreen->setCursorYX (1,1 ); - break; //VT52 - case TY_VT52('I' ) : - _currentScreen->reverseIndex ( ); - break; //VT52 - case TY_VT52('J' ) : - _currentScreen->clearToEndOfScreen ( ); - break; //VT52 - case TY_VT52('K' ) : - _currentScreen->clearToEndOfLine ( ); - break; //VT52 - case TY_VT52('Y' ) : - _currentScreen->setCursorYX (p-31,q-31 ); - break; //VT52 - case TY_VT52('Z' ) : - reportTerminalType ( ); - break; //VT52 - case TY_VT52('<' ) : - setMode (MODE_Ansi ); - break; //VT52 - case TY_VT52('=' ) : - setMode (MODE_AppKeyPad); - break; //VT52 - case TY_VT52('>' ) : - resetMode (MODE_AppKeyPad); - break; //VT52 - - case TY_CSI_PG('c' ) : - reportSecondaryAttributes( ); - break; //VT100 - - default : - ReportErrorToken(); - break; - }; + }; } void Vt102Emulation::clearScreenAndSetColumns(int columnCount) { - setImageSize(_currentScreen->getLines(),columnCount); + setImageSize(_currentScreen->getLines(),columnCount); clearEntireScreen(); - setDefaultMargins(); + setDefaultMargins(); _currentScreen->setCursorYX(0,0); } -/* ------------------------------------------------------------------------- */ -/* */ -/* Terminal to Host protocol */ -/* */ -/* ------------------------------------------------------------------------- */ - -/* - Outgoing bytes originate from several sources: - - - Replies to Enquieries. - - Mouse Events - - Keyboard Events -*/ - -/*! -*/ - -void Vt102Emulation::sendString(const char * s , int length) +void Vt102Emulation::sendString(const char* s , int length) { - if ( length >= 0 ) { - emit sendData(s,length); - } else { - emit sendData(s,strlen(s)); - } + if ( length >= 0 ) + emit sendData(s,length); + else + emit sendData(s,strlen(s)); } -// Replies ----------------------------------------------------------------- -- - -// This section copes with replies send as response to an enquiery control code. - -/*! -*/ - void Vt102Emulation::reportCursorPosition() -{ - char tmp[20]; - sprintf(tmp,"\033[%d;%dR",_currentScreen->getCursorY()+1,_currentScreen->getCursorX()+1); - sendString(tmp); +{ + char tmp[20]; + sprintf(tmp,"\033[%d;%dR",_currentScreen->getCursorY()+1,_currentScreen->getCursorX()+1); + sendString(tmp); } -/* - What follows here is rather obsolete and faked stuff. - The correspondent enquieries are neverthenless issued. -*/ - -/*! -*/ - void Vt102Emulation::reportTerminalType() { - // Primary device attribute response (Request was: ^[[0c or ^[[c (from TT321 Users Guide)) - // VT220: ^[[?63;1;2;3;6;7;8c (list deps on emul. capabilities) - // VT100: ^[[?1;2c - // VT101: ^[[?1;0c - // VT102: ^[[?6v - if (getMode(MODE_Ansi)) { - sendString("\033[?1;2c"); // I'm a VT100 - } else { - sendString("\033/Z"); // I'm a VT52 - } + // Primary device attribute response (Request was: ^[[0c or ^[[c (from TT321 Users Guide)) + // VT220: ^[[?63;1;2;3;6;7;8c (list deps on emul. capabilities) + // VT100: ^[[?1;2c + // VT101: ^[[?1;0c + // VT102: ^[[?6v + if (getMode(MODE_Ansi)) + sendString("\033[?1;2c"); // I'm a VT100 + else + sendString("\033/Z"); // I'm a VT52 } void Vt102Emulation::reportSecondaryAttributes() { - // Seconday device attribute response (Request was: ^[[>0c or ^[[>c) - if (getMode(MODE_Ansi)) { - sendString("\033[>0;115;0c"); // Why 115? ;) - } else { - sendString("\033/Z"); // FIXME I don't think VT52 knows about it but kept for - } - // konsoles backward compatibility. + // Seconday device attribute response (Request was: ^[[>0c or ^[[>c) + if (getMode(MODE_Ansi)) + sendString("\033[>0;115;0c"); // Why 115? ;) + else + sendString("\033/Z"); // FIXME I don't think VT52 knows about it but kept for + // konsoles backward compatibility. } void Vt102Emulation::reportTerminalParms(int p) // DECREPTPARM -{ - char tmp[100]; - sprintf(tmp,"\033[%d;1;1;112;112;1;0x",p); // not really true. - sendString(tmp); +{ + char tmp[100]; + sprintf(tmp,"\033[%d;1;1;112;112;1;0x",p); // not really true. + sendString(tmp); } -/*! -*/ - void Vt102Emulation::reportStatus() { - sendString("\033[0n"); //VT100. Device status report. 0 = Ready. + sendString("\033[0n"); //VT100. Device status report. 0 = Ready. } -/*! -*/ - -#define ANSWER_BACK "" // This is really obsolete VT100 stuff. - void Vt102Emulation::reportAnswerBack() { - sendString(ANSWER_BACK); + // FIXME - Test this with VTTEST + // This is really obsolete VT100 stuff. + const char* ANSWER_BACK = ""; + sendString(ANSWER_BACK); } -// Mouse Handling ---------------------------------------------------------- -- - /*! - Mouse clicks are possibly reported to the client - application if it has issued interest in them. - They are normally consumed by the widget for copy - and paste, but may be propagated from the widget - when gui->setMouseMarks is set via setMode(MODE_Mouse1000). - - `x',`y' are 1-based. - `ev' (event) indicates the button pressed (0-2) - or a general mouse release (3). + `cx',`cy' are 1-based. + `eventType' indicates the button pressed (0-2) + or a general mouse release (3). eventType represents the kind of mouse action that occurred: - 0 = Mouse button press or release - 1 = Mouse drag + 0 = Mouse button press or release + 1 = Mouse drag */ void Vt102Emulation::sendMouseEvent( int cb, int cx, int cy , int eventType ) -{ - char tmp[20]; - if ( cx<1 || cy<1 ) { - return; - } - // normal buttons are passed as 0x20 + button, - // mouse wheel (buttons 4,5) as 0x5c + button - if (cb >= 4) { - cb += 0x3c; - } +{ + if (cx < 1 || cy < 1) + return; - //Mouse motion handling - if ( (getMode(MODE_Mouse1002) || getMode(MODE_Mouse1003)) && eventType == 1 ) { - cb += 0x20; //add 32 to signify motion event - } + // normal buttons are passed as 0x20 + button, + // mouse wheel (buttons 4,5) as 0x5c + button + if (cb >= 4) + cb += 0x3c; - sprintf(tmp,"\033[M%c%c%c",cb+0x20,cx+0x20,cy+0x20); - sendString(tmp); + //Mouse motion handling + if ((getMode(MODE_Mouse1002) || getMode(MODE_Mouse1003)) && eventType == 1) + cb += 0x20; //add 32 to signify motion event + + char command[20]; + sprintf(command,"\033[M%c%c%c",cb+0x20,cx+0x20,cy+0x20); + sendString(command); } -// Keyboard Handling ------------------------------------------------------- -- - -#define encodeMode(M,B) BITS(B,getMode(M)) -#define encodeStat(M,B) BITS(B,((ev->modifiers() & (M)) == (M))) - -void Vt102Emulation::sendText( const QString & text ) +void Vt102Emulation::sendText( const QString& text ) { - if (!text.isEmpty()) { - QKeyEvent event(QEvent::KeyPress, - 0, - Qt::NoModifier, - text); - sendKeyEvent(&event); // expose as a big fat keypress event - } - + if (!text.isEmpty()) + { + QKeyEvent event(QEvent::KeyPress, + 0, + Qt::NoModifier, + text); + sendKeyEvent(&event); // expose as a big fat keypress event + } } - -void Vt102Emulation::sendKeyEvent( QKeyEvent * event ) +void Vt102Emulation::sendKeyEvent( QKeyEvent* event ) { Qt::KeyboardModifiers modifiers = event->modifiers(); KeyboardTranslator::States states = KeyboardTranslator::NoState; // get current states - if ( getMode(MODE_NewLine) ) { - states |= KeyboardTranslator::NewLineState; - } - if ( getMode(MODE_Ansi) ) { - states |= KeyboardTranslator::AnsiState; - } - if ( getMode(MODE_AppCuKeys)) { - states |= KeyboardTranslator::CursorKeysState; - } - if ( getMode(MODE_AppScreen)) { - states |= KeyboardTranslator::AlternateScreenState; + if (getMode(MODE_NewLine) ) states |= KeyboardTranslator::NewLineState; + if (getMode(MODE_Ansi) ) states |= KeyboardTranslator::AnsiState; + if (getMode(MODE_AppCuKeys)) states |= KeyboardTranslator::CursorKeysState; + if (getMode(MODE_AppScreen)) states |= KeyboardTranslator::AlternateScreenState; + if (getMode(MODE_AppKeyPad) && (modifiers & Qt::KeypadModifier)) + states |= KeyboardTranslator::ApplicationKeypadState; + + // check flow control state + if (modifiers & Qt::ControlModifier) + { + if (event->key() == Qt::Key_S) + emit flowControlKeyPressed(true); + else if (event->key() == Qt::Key_Q) + emit flowControlKeyPressed(false); } // lookup key binding - if ( _keyTranslator ) { - KeyboardTranslator::Entry entry = _keyTranslator->findEntry( - event->key() , - modifiers, - states ); + if ( _keyTranslator ) + { + KeyboardTranslator::Entry entry = _keyTranslator->findEntry( + event->key() , + modifiers, + states ); // send result to terminal QByteArray textToSend; @@ -1540,33 +932,39 @@ void Vt102Emulation::sendKeyEvent( QKeyEvent * event ) // (unless there is an entry defined for this particular combination // in the keyboard modifier) bool wantsAltModifier = entry.modifiers() & entry.modifierMask() & Qt::AltModifier; - bool wantsAnyModifier = entry.state() & entry.stateMask() & KeyboardTranslator::AnyModifierState; + bool wantsAnyModifier = entry.state() & + entry.stateMask() & KeyboardTranslator::AnyModifierState; - if ( modifiers & Qt::AltModifier && !(wantsAltModifier || wantsAnyModifier) - && !event->text().isEmpty() ) { + if ( modifiers & Qt::AltModifier && !(wantsAltModifier || wantsAnyModifier) + && !event->text().isEmpty() ) + { textToSend.prepend("\033"); } - if ( entry.command() != KeyboardTranslator::NoCommand ) { - if (entry.command() & KeyboardTranslator::EraseCommand) { - textToSend += getErase(); - } + if ( entry.command() != KeyboardTranslator::NoCommand ) + { + if (entry.command() & KeyboardTranslator::EraseCommand) + textToSend += eraseChar(); + // TODO command handling - } else if ( !entry.text().isEmpty() ) { - textToSend += _codec->fromUnicode(entry.text(true,modifiers)); - } else { - textToSend += _codec->fromUnicode(event->text()); } + else if ( !entry.text().isEmpty() ) + { + textToSend += _codec->fromUnicode(entry.text(true,modifiers)); + } + else + textToSend += _codec->fromUnicode(event->text()); sendData( textToSend.constData() , textToSend.length() ); - } else { + } + else + { // print an error message to the terminal if no key translator has been // set - QString translatorError = ("No keyboard translator available. " - "The information needed to convert key presses " - "into characters to send to the terminal " - "is missing."); - + QString translatorError = tr("No keyboard translator available. " + "The information needed to convert key presses " + "into characters to send to the terminal " + "is missing."); reset(); receiveData( translatorError.toAscii().constData() , translatorError.count() ); } @@ -1580,7 +978,7 @@ void Vt102Emulation::sendKeyEvent( QKeyEvent * event ) // Character Set Conversion ------------------------------------------------ -- -/* +/* The processing contains a VT100 specific code translation layer. It's still in use and mainly responsible for the line drawing graphics. @@ -1591,7 +989,7 @@ void Vt102Emulation::sendKeyEvent( QKeyEvent * event ) in the pipeline. It only applies to tokens, which represent plain characters. - This conversion it eventually continued in TerminalDisplay.C, since + This conversion it eventually continued in TerminalDisplay.C, since it might involve VT100 enhanced fonts, which have these particular glyphs allocated in (0x00-0x1f) in their code page. */ @@ -1602,18 +1000,14 @@ void Vt102Emulation::sendKeyEvent( QKeyEvent * event ) unsigned short Vt102Emulation::applyCharset(unsigned short c) { - if (CHARSET.graphic && 0x5f <= c && c <= 0x7e) { - return vt100_graphics[c-0x5f]; - } - if (CHARSET.pound && c == '#' ) { - return 0xa3; //This mode is obsolete - } - return c; + if (CHARSET.graphic && 0x5f <= c && c <= 0x7e) return vt100_graphics[c-0x5f]; + if (CHARSET.pound && c == '#' ) return 0xa3; //This mode is obsolete + return c; } /* "Charset" related part of the emulation state. - This configures the VT100 _charset filter. + This configures the VT100 charset filter. While most operation work on the current _screen, the following two are different. @@ -1621,33 +1015,31 @@ unsigned short Vt102Emulation::applyCharset(unsigned short c) void Vt102Emulation::resetCharset(int scrno) { - _charset[scrno].cu_cs = 0; - strncpy(_charset[scrno].charset,"BBBB",4); - _charset[scrno].sa_graphic = false; - _charset[scrno].sa_pound = false; - _charset[scrno].graphic = false; - _charset[scrno].pound = false; + _charset[scrno].cu_cs = 0; + strncpy(_charset[scrno].charset,"BBBB",4); + _charset[scrno].sa_graphic = false; + _charset[scrno].sa_pound = false; + _charset[scrno].graphic = false; + _charset[scrno].pound = false; } -void Vt102Emulation::setCharset(int n, int cs) // on both screens. +void Vt102Emulation::setCharset(int n, int cs) // on both screens. { - _charset[0].charset[n&3] = cs; - useCharset(_charset[0].cu_cs); - _charset[1].charset[n&3] = cs; - useCharset(_charset[1].cu_cs); + _charset[0].charset[n&3] = cs; useCharset(_charset[0].cu_cs); + _charset[1].charset[n&3] = cs; useCharset(_charset[1].cu_cs); } void Vt102Emulation::setAndUseCharset(int n, int cs) { - CHARSET.charset[n&3] = cs; - useCharset(n&3); + CHARSET.charset[n&3] = cs; + useCharset(n&3); } void Vt102Emulation::useCharset(int n) { - CHARSET.cu_cs = n&3; - CHARSET.graphic = (CHARSET.charset[n&3] == '0'); - CHARSET.pound = (CHARSET.charset[n&3] == 'A'); //This mode is obsolete + CHARSET.cu_cs = n&3; + CHARSET.graphic = (CHARSET.charset[n&3] == '0'); + CHARSET.pound = (CHARSET.charset[n&3] == 'A'); //This mode is obsolete } void Vt102Emulation::setDefaultMargins() @@ -1658,29 +1050,25 @@ void Vt102Emulation::setDefaultMargins() void Vt102Emulation::setMargins(int t, int b) { - _screen[0]->setMargins(t, b); - _screen[1]->setMargins(t, b); + _screen[0]->setMargins(t, b); + _screen[1]->setMargins(t, b); } -/*! Save the cursor position and the rendition attribute settings. */ - void Vt102Emulation::saveCursor() { - CHARSET.sa_graphic = CHARSET.graphic; - CHARSET.sa_pound = CHARSET.pound; //This mode is obsolete - // we are not clear about these - //sa_charset = charsets[cScreen->_charset]; - //sa_charset_num = cScreen->_charset; - _currentScreen->saveCursor(); + CHARSET.sa_graphic = CHARSET.graphic; + CHARSET.sa_pound = CHARSET.pound; //This mode is obsolete + // we are not clear about these + //sa_charset = charsets[cScreen->_charset]; + //sa_charset_num = cScreen->_charset; + _currentScreen->saveCursor(); } -/*! Restore the cursor position and the rendition attribute settings. */ - void Vt102Emulation::restoreCursor() { - CHARSET.graphic = CHARSET.sa_graphic; - CHARSET.pound = CHARSET.sa_pound; //This mode is obsolete - _currentScreen->restoreCursor(); + CHARSET.graphic = CHARSET.sa_graphic; + CHARSET.pound = CHARSET.sa_pound; //This mode is obsolete + _currentScreen->restoreCursor(); } /* ------------------------------------------------------------------------- */ @@ -1705,148 +1093,132 @@ void Vt102Emulation::restoreCursor() void Vt102Emulation::resetModes() { - resetMode(MODE_Mouse1000); - saveMode(MODE_Mouse1000); - resetMode(MODE_Mouse1001); - saveMode(MODE_Mouse1001); - resetMode(MODE_Mouse1002); - saveMode(MODE_Mouse1002); - resetMode(MODE_Mouse1003); - saveMode(MODE_Mouse1003); + // MODE_Allow132Columns is not reset here + // to match Xterm's behaviour (see Xterm's VTReset() function) - resetMode(MODE_AppScreen); - saveMode(MODE_AppScreen); - // here come obsolete modes - resetMode(MODE_AppCuKeys); - saveMode(MODE_AppCuKeys); - resetMode(MODE_NewLine ); - setMode(MODE_Ansi ); + resetMode(MODE_132Columns); saveMode(MODE_132Columns); + resetMode(MODE_Mouse1000); saveMode(MODE_Mouse1000); + resetMode(MODE_Mouse1001); saveMode(MODE_Mouse1001); + resetMode(MODE_Mouse1002); saveMode(MODE_Mouse1002); + resetMode(MODE_Mouse1003); saveMode(MODE_Mouse1003); + + resetMode(MODE_AppScreen); saveMode(MODE_AppScreen); + resetMode(MODE_AppCuKeys); saveMode(MODE_AppCuKeys); + resetMode(MODE_AppKeyPad); saveMode(MODE_AppKeyPad); + resetMode(MODE_NewLine); + setMode(MODE_Ansi); } void Vt102Emulation::setMode(int m) { - _currParm.mode[m] = true; - switch (m) { + _currentModes.mode[m] = true; + switch (m) + { + case MODE_132Columns: + if (getMode(MODE_Allow132Columns)) + clearScreenAndSetColumns(132); + else + _currentModes.mode[m] = false; + break; case MODE_Mouse1000: case MODE_Mouse1001: case MODE_Mouse1002: case MODE_Mouse1003: - emit programUsesMouseChanged(false); - break; + emit programUsesMouseChanged(false); + break; - case MODE_AppScreen : - _screen[1]->clearSelection(); - setScreen(1); - break; - } - if (m < MODES_SCREEN || m == MODE_NewLine) { - _screen[0]->setMode(m); - _screen[1]->setMode(m); - } + case MODE_AppScreen : _screen[1]->clearSelection(); + setScreen(1); + break; + } + if (m < MODES_SCREEN || m == MODE_NewLine) + { + _screen[0]->setMode(m); + _screen[1]->setMode(m); + } } void Vt102Emulation::resetMode(int m) { - _currParm.mode[m] = false; - switch (m) { - case MODE_Mouse1000 : + _currentModes.mode[m] = false; + switch (m) + { + case MODE_132Columns: + if (getMode(MODE_Allow132Columns)) + clearScreenAndSetColumns(80); + break; + case MODE_Mouse1000 : case MODE_Mouse1001 : case MODE_Mouse1002 : case MODE_Mouse1003 : - emit programUsesMouseChanged(true); - break; + emit programUsesMouseChanged(true); + break; - case MODE_AppScreen : + case MODE_AppScreen : _screen[0]->clearSelection(); setScreen(0); - break; - } - if (m < MODES_SCREEN || m == MODE_NewLine) { - _screen[0]->resetMode(m); - _screen[1]->resetMode(m); - } + break; + } + if (m < MODES_SCREEN || m == MODE_NewLine) + { + _screen[0]->resetMode(m); + _screen[1]->resetMode(m); + } } void Vt102Emulation::saveMode(int m) { - _saveParm.mode[m] = _currParm.mode[m]; + _savedModes.mode[m] = _currentModes.mode[m]; } void Vt102Emulation::restoreMode(int m) { - if (_saveParm.mode[m]) { - setMode(m); - } else { - resetMode(m); - } + if (_savedModes.mode[m]) + setMode(m); + else + resetMode(m); } bool Vt102Emulation::getMode(int m) { - return _currParm.mode[m]; + return _currentModes.mode[m]; } -char Vt102Emulation::getErase() const +char Vt102Emulation::eraseChar() const { - KeyboardTranslator::Entry entry = _keyTranslator->findEntry( - Qt::Key_Backspace, - 0, - 0); - if ( entry.text().count() > 0 ) { - return entry.text()[0]; - } else { - return '\b'; - } + KeyboardTranslator::Entry entry = _keyTranslator->findEntry( + Qt::Key_Backspace, + 0, + 0); + if ( entry.text().count() > 0 ) + return entry.text()[0]; + else + return '\b'; } -/* ------------------------------------------------------------------------- */ -/* */ -/* Diagnostic */ -/* */ -/* ------------------------------------------------------------------------- */ +// print contents of the scan buffer +static void hexdump(int* s, int len) +{ int i; + for (i = 0; i < len; i++) + { + if (s[i] == '\\') + printf("\\\\"); + else + if ((s[i]) > 32 && s[i] < 127) + printf("%c",s[i]); + else + printf("\\%04x(hex)",s[i]); + } +} -/*! shows the contents of the scan buffer. - - This functions is used for diagnostics. It is called by \e ReportErrorToken - to inform about strings that cannot be decoded or handled by the emulation. - - \sa ReportErrorToken -*/ - -static void hexdump(int * s, int len) +void Vt102Emulation::reportDecodingError() { - int i; - for (i = 0; i < len; i++) { - if (s[i] == '\\') { - printf("\\\\"); - } else if ((s[i]) > 32 && s[i] < 127) { - printf("%c",s[i]); - } else { - printf("\\%04x(hex)",s[i]); - } - } + if (tokenBufferPos == 0 || ( tokenBufferPos == 1 && (tokenBuffer[0] & 0xff) >= 32) ) + return; + printf("Undecodable sequence: "); + hexdump(tokenBuffer,tokenBufferPos); + printf("\n"); } -void Vt102Emulation::scan_buffer_report() -{ - if (ppos == 0 || (ppos == 1 && (pbuf[0] & 0xff) >= 32)) { - return; - } - printf("token: "); - hexdump(pbuf,ppos); - printf("\n"); -} - -/*! -*/ - -void Vt102Emulation::ReportErrorToken() -{ -#ifndef NDEBUG - printf("undecodable "); - scan_buffer_report(); -#endif -} - -//#include "moc_Vt102Emulation.cpp" +//#include "Vt102Emulation.moc" diff --git a/lib/Vt102Emulation.h b/lib/Vt102Emulation.h index b04771e..7f10b16 100644 --- a/lib/Vt102Emulation.h +++ b/lib/Vt102Emulation.h @@ -1,10 +1,8 @@ /* This file is part of Konsole, an X terminal. - - Copyright (C) 2007 by Robert Knight - Copyright (C) 1997,1998 by Lars Doelle - - Rewritten for QT4 by e_k , Copyright (C)2008 + + Copyright 2007-2008 by Robert Knight + Copyright 1997,1998 by Lars Doelle This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -28,7 +26,7 @@ // Standard Library #include -// Qt +// Qt #include #include #include @@ -37,150 +35,155 @@ #include "Emulation.h" #include "Screen.h" -#define MODE_AppScreen (MODES_SCREEN+0) -#define MODE_AppCuKeys (MODES_SCREEN+1) -#define MODE_AppKeyPad (MODES_SCREEN+2) -#define MODE_Mouse1000 (MODES_SCREEN+3) -#define MODE_Mouse1001 (MODES_SCREEN+4) -#define MODE_Mouse1002 (MODES_SCREEN+5) -#define MODE_Mouse1003 (MODES_SCREEN+6) -#define MODE_Ansi (MODES_SCREEN+7) -#define MODE_total (MODES_SCREEN+8) +#define MODE_AppScreen (MODES_SCREEN+0) // Mode #1 +#define MODE_AppCuKeys (MODES_SCREEN+1) // Application cursor keys (DECCKM) +#define MODE_AppKeyPad (MODES_SCREEN+2) // +#define MODE_Mouse1000 (MODES_SCREEN+3) // Send mouse X,Y position on press and release +#define MODE_Mouse1001 (MODES_SCREEN+4) // Use Hilight mouse tracking +#define MODE_Mouse1002 (MODES_SCREEN+5) // Use cell motion mouse tracking +#define MODE_Mouse1003 (MODES_SCREEN+6) // Use all motion mouse tracking +#define MODE_Ansi (MODES_SCREEN+7) // Use US Ascii for character sets G0-G3 (DECANM) +#define MODE_132Columns (MODES_SCREEN+8) // 80 <-> 132 column mode switch (DECCOLM) +#define MODE_Allow132Columns (MODES_SCREEN+9) // Allow DECCOLM mode +#define MODE_total (MODES_SCREEN+10) -namespace Konsole { +namespace Konsole +{ -struct DECpar { - bool mode[MODE_total]; -}; - -struct CharCodes { - // coding info - char charset[4]; // - int cu_cs; // actual charset. - bool graphic; // Some VT100 tricks - bool pound ; // Some VT100 tricks - bool sa_graphic; // saved graphic - bool sa_pound; // saved pound +struct CharCodes +{ + // coding info + char charset[4]; // + int cu_cs; // actual charset. + bool graphic; // Some VT100 tricks + bool pound ; // Some VT100 tricks + bool sa_graphic; // saved graphic + bool sa_pound; // saved pound }; /** * Provides an xterm compatible terminal emulation based on the DEC VT102 terminal. * A full description of this terminal can be found at http://vt100.net/docs/vt102-ug/ - * - * In addition, various additional xterm escape sequences are supported to provide + * + * In addition, various additional xterm escape sequences are supported to provide * features such as mouse input handling. * See http://rtfm.etla.org/xterm/ctlseq.html for a description of xterm's escape - * sequences. + * sequences. * */ -class Vt102Emulation : public Emulation { - Q_OBJECT +class Vt102Emulation : public Emulation +{ +Q_OBJECT public: - - /** Constructs a new emulation */ - Vt102Emulation(); - ~Vt102Emulation(); - - // reimplemented - virtual void clearEntireScreen(); - virtual void reset(); - - // reimplemented - virtual char getErase() const; - -public slots: - - // reimplemented - virtual void sendString(const char *,int length = -1); - virtual void sendText(const QString & text); - virtual void sendKeyEvent(QKeyEvent *); - virtual void sendMouseEvent( int buttons, int column, int line , int eventType ); - + /** Constructs a new emulation */ + Vt102Emulation(); + ~Vt102Emulation(); + + // reimplemented from Emulation + virtual void clearEntireScreen(); + virtual void reset(); + virtual char eraseChar() const; + +public slots: + // reimplemented from Emulation + virtual void sendString(const char*,int length = -1); + virtual void sendText(const QString& text); + virtual void sendKeyEvent(QKeyEvent*); + virtual void sendMouseEvent(int buttons, int column, int line, int eventType); + protected: - // reimplemented - virtual void setMode (int mode); - virtual void resetMode (int mode); - - // reimplemented - virtual void receiveChar(int cc); - - + // reimplemented from Emulation + virtual void setMode(int mode); + virtual void resetMode(int mode); + virtual void receiveChar(int cc); + private slots: - - //causes changeTitle() to be emitted for each (int,QString) pair in pendingTitleUpdates - //used to buffer multiple title updates - void updateTitle(); - + //causes changeTitle() to be emitted for each (int,QString) pair in pendingTitleUpdates + //used to buffer multiple title updates + void updateTitle(); private: - unsigned short applyCharset(unsigned short c); - void setCharset(int n, int cs); - void useCharset(int n); - void setAndUseCharset(int n, int cs); - void saveCursor(); - void restoreCursor(); - void resetCharset(int scrno); + unsigned short applyCharset(unsigned short c); + void setCharset(int n, int cs); + void useCharset(int n); + void setAndUseCharset(int n, int cs); + void saveCursor(); + void restoreCursor(); + void resetCharset(int scrno); - void setMargins(int top, int bottom); - //set margins for all screens back to their defaults - void setDefaultMargins(); + void setMargins(int top, int bottom); + //set margins for all screens back to their defaults + void setDefaultMargins(); - // returns true if 'mode' is set or false otherwise - bool getMode (int mode); - // saves the current boolean value of 'mode' - void saveMode (int mode); - // restores the boolean value of 'mode' - void restoreMode(int mode); - // resets all modes - void resetModes(); + // returns true if 'mode' is set or false otherwise + bool getMode (int mode); + // saves the current boolean value of 'mode' + void saveMode (int mode); + // restores the boolean value of 'mode' + void restoreMode(int mode); + // resets all modes + // (except MODE_Allow132Columns) + void resetModes(); - void resetToken(); -#define MAXPBUF 80 - void pushToToken(int cc); - int pbuf[MAXPBUF]; //FIXME: overflow? - int ppos; + void resetTokenizer(); + #define MAX_TOKEN_LENGTH 80 + void addToCurrentToken(int cc); + int tokenBuffer[MAX_TOKEN_LENGTH]; //FIXME: overflow? + int tokenBufferPos; #define MAXARGS 15 - void addDigit(int dig); - void addArgument(); - int argv[MAXARGS]; - int argc; - void initTokenizer(); - int tbl[256]; + void addDigit(int dig); + void addArgument(); + int argv[MAXARGS]; + int argc; + void initTokenizer(); - void scan_buffer_report(); //FIXME: rename - void ReportErrorToken(); //FIXME: rename + // Set of flags for each of the ASCII characters which indicates + // what category they fall into (printable character, control, digit etc.) + // for the purposes of decoding terminal output + int charClass[256]; - void tau(int code, int p, int q); - void XtermHack(); + void reportDecodingError(); - void reportTerminalType(); - void reportSecondaryAttributes(); - void reportStatus(); - void reportAnswerBack(); - void reportCursorPosition(); - void reportTerminalParms(int p); + void processToken(int code, int p, int q); + void processWindowAttributeChange(); - void onScrollLock(); - void scrollLock(const bool lock); + void reportTerminalType(); + void reportSecondaryAttributes(); + void reportStatus(); + void reportAnswerBack(); + void reportCursorPosition(); + void reportTerminalParms(int p); - // clears the screen and resizes it to the specified - // number of columns - void clearScreenAndSetColumns(int columnCount); + void onScrollLock(); + void scrollLock(const bool lock); - CharCodes _charset[2]; + // clears the screen and resizes it to the specified + // number of columns + void clearScreenAndSetColumns(int columnCount); - DECpar _currParm; - DECpar _saveParm; + CharCodes _charset[2]; - //hash table and timer for buffering calls to the session instance - //to update the name of the session - //or window title. - //these calls occur when certain escape sequences are seen in the - //output from the terminal - QHash _pendingTitleUpdates; - QTimer * _titleUpdateTimer; + class TerminalState + { + public: + // Initializes all modes to false + TerminalState() + { memset(&mode,false,MODE_total * sizeof(bool)); } + bool mode[MODE_total]; + }; + + TerminalState _currentModes; + TerminalState _savedModes; + + //hash table and timer for buffering calls to the session instance + //to update the name of the session + //or window title. + //these calls occur when certain escape sequences are seen in the + //output from the terminal + QHash _pendingTitleUpdates; + QTimer* _titleUpdateTimer; }; } diff --git a/lib/color-schemes/BlackOnLightYellow.schema b/lib/color-schemes/BlackOnLightYellow.schema new file mode 100644 index 0000000..251a696 --- /dev/null +++ b/lib/color-schemes/BlackOnLightYellow.schema @@ -0,0 +1,42 @@ +# example scheme for konsole + +# the title is to appear in the menu. + +title Black on Light Yellow + +# foreground colors + +# note that the default background color is flagged +# to become transparent when an image is present. + +# slot transparent bold +# | | | +# V V--color--V V V + +color 0 0 0 0 0 0 # regular foreground color (Black) +color 1 255 255 221 1 0 # regular background color (Light Yellow) + +color 2 0 0 0 0 0 # regular color 0 Black +color 3 178 24 24 0 0 # regular color 1 Red +color 4 24 178 24 0 0 # regular color 2 Green +color 5 178 104 24 0 0 # regular color 3 Yellow +color 6 24 24 178 0 0 # regular color 4 Blue +color 7 178 24 178 0 0 # regular color 5 Magenta +color 8 24 178 178 0 0 # regular color 6 Cyan +color 9 178 178 178 0 0 # regular color 7 White + +# intensive colors + +# instead of changing the colors, we've flaged the text to become bold + +color 10 0 0 0 0 1 # intensive foreground color +color 11 255 255 221 1 0 # intensive background color + +color 12 104 104 104 0 0 # intensive color 0 +color 13 255 84 84 0 0 # intensive color 1 +color 14 84 255 84 0 0 # intensive color 2 +color 15 255 255 84 0 0 # intensive color 3 +color 16 84 84 255 0 0 # intensive color 4 +color 17 255 84 255 0 0 # intensive color 5 +color 18 84 255 255 0 0 # intensive color 6 +color 19 255 255 255 0 0 # intensive color 7 diff --git a/lib/color-schemes/BlackOnRandomLight.colorscheme b/lib/color-schemes/BlackOnRandomLight.colorscheme new file mode 100644 index 0000000..4d6f831 --- /dev/null +++ b/lib/color-schemes/BlackOnRandomLight.colorscheme @@ -0,0 +1,104 @@ +[Background] +Bold=false +Color=247,247,214 +Transparency=true +MaxRandomHue=340 + +[BackgroundIntense] +Bold=false +Color=255,255,221 +Transparency=true + +[Color0] +Bold=false +Color=0,0,0 +Transparency=false + +[Color0Intense] +Bold=false +Color=104,104,104 +Transparency=false + +[Color1] +Bold=false +Color=178,24,24 +Transparency=false + +[Color1Intense] +Bold=false +Color=255,84,84 +Transparency=false + +[Color2] +Bold=false +Color=24,178,24 +Transparency=false + +[Color2Intense] +Bold=false +Color=84,255,84 +Transparency=false + +[Color3] +Bold=false +Color=178,104,24 +Transparency=false + +[Color3Intense] +Bold=false +Color=255,255,84 +Transparency=false + +[Color4] +Bold=false +Color=24,24,178 +Transparency=false + +[Color4Intense] +Bold=false +Color=84,84,255 +Transparency=false + +[Color5] +Bold=false +Color=178,24,178 +Transparency=false + +[Color5Intense] +Bold=false +Color=255,84,255 +Transparency=false + +[Color6] +Bold=false +Color=24,178,178 +Transparency=false + +[Color6Intense] +Bold=false +Color=84,255,255 +Transparency=false + +[Color7] +Bold=false +Color=178,178,178 +Transparency=false + +[Color7Intense] +Bold=false +Color=255,255,255 +Transparency=false + +[Foreground] +Bold=false +Color=0,0,0 +Transparency=false + +[ForegroundIntense] +Bold=true +Color=0,0,0 +Transparency=false + +[General] +Description=Black on Random Light +Opacity=1 diff --git a/lib/color-schemes/BlackOnWhite.schema b/lib/color-schemes/BlackOnWhite.schema new file mode 100644 index 0000000..11853e6 --- /dev/null +++ b/lib/color-schemes/BlackOnWhite.schema @@ -0,0 +1,42 @@ +# example scheme for konsole + +# the title is to appear in the menu. + +title Black on White + +# foreground colors + +# note that the default background color is flagged +# to become transparent when an image is present. + +# slot transparent bold +# | | | +# V V--color--V V V + +color 0 0 0 0 0 0 # regular foreground color (Black) +color 1 255 255 255 1 0 # regular background color (White) + +color 2 0 0 0 0 0 # regular color 0 Black +color 3 178 24 24 0 0 # regular color 1 Red +color 4 24 178 24 0 0 # regular color 2 Green +color 5 178 104 24 0 0 # regular color 3 Yellow +color 6 24 24 178 0 0 # regular color 4 Blue +color 7 178 24 178 0 0 # regular color 5 Magenta +color 8 24 178 178 0 0 # regular color 6 Cyan +color 9 178 178 178 0 0 # regular color 7 White + +# intensive colors + +# instead of changing the colors, we've flaged the text to become bold + +color 10 0 0 0 0 1 # intensive foreground color +color 11 255 255 255 1 0 # intensive background color + +color 12 104 104 104 0 0 # intensive color 0 +color 13 255 84 84 0 0 # intensive color 1 +color 14 84 255 84 0 0 # intensive color 2 +color 15 255 255 84 0 0 # intensive color 3 +color 16 84 84 255 0 0 # intensive color 4 +color 17 255 84 255 0 0 # intensive color 5 +color 18 84 255 255 0 0 # intensive color 6 +color 19 255 255 255 0 0 # intensive color 7 diff --git a/lib/color-schemes/CMakeLists.txt b/lib/color-schemes/CMakeLists.txt new file mode 100644 index 0000000..6b0f4e7 --- /dev/null +++ b/lib/color-schemes/CMakeLists.txt @@ -0,0 +1,13 @@ +# Note some color schemes are deliberately not installed +# at present + +install( FILES + BlackOnLightYellow.schema + BlackOnRandomLight.colorscheme + BlackOnWhite.schema + GreenOnBlack.colorscheme + WhiteOnBlack.schema + Linux.colorscheme + DarkPastels.colorscheme + DESTINATION + ${DATA_INSTALL_DIR}/konsole ) diff --git a/lib/color-schemes/DarkPastels.colorscheme b/lib/color-schemes/DarkPastels.colorscheme new file mode 100644 index 0000000..fdcb02a --- /dev/null +++ b/lib/color-schemes/DarkPastels.colorscheme @@ -0,0 +1,103 @@ +[Background] +Bold=false +Color=44,44,44 +Transparency=false + +[BackgroundIntense] +Bold=true +Color=44,44,44 +Transparency=false + +[Color0] +Bold=false +Color=63,63,63 +Transparency=false + +[Color0Intense] +Bold=true +Color=112,144,128 +Transparency=false + +[Color1] +Bold=false +Color=112,80,80 +Transparency=false + +[Color1Intense] +Bold=true +Color=220,163,163 +Transparency=false + +[Color2] +Bold=false +Color=96,180,138 +Transparency=false + +[Color2Intense] +Bold=true +Color=114,213,163 +Transparency=false + +[Color3] +Bold=false +Color=223,175,143 +Transparency=false + +[Color3Intense] +Bold=true +Color=240,223,175 +Transparency=false + +[Color4] +Bold=false +Color=154,184,215 +Transparency=false + +[Color4Intense] +Bold=true +Color=148,191,243 +Transparency=false + +[Color5] +Bold=false +Color=220,140,195 +Transparency=false + +[Color5Intense] +Bold=true +Color=236,147,211 +Transparency=false + +[Color6] +Bold=false +Color=140,208,211 +Transparency=false + +[Color6Intense] +Bold=true +Color=147,224,227 +Transparency=false + +[Color7] +Bold=false +Color=220,220,204 +Transparency=false + +[Color7Intense] +Bold=true +Color=255,255,255 +Transparency=false + +[Foreground] +Bold=false +Color=220,220,204 +Transparency=false + +[ForegroundIntense] +Bold=true +Color=220,220,204 +Transparency=false + +[General] +Description=Dark Pastels +Opacity=1 diff --git a/lib/color-schemes/GreenOnBlack.colorscheme b/lib/color-schemes/GreenOnBlack.colorscheme new file mode 100644 index 0000000..4d55b3a --- /dev/null +++ b/lib/color-schemes/GreenOnBlack.colorscheme @@ -0,0 +1,104 @@ + +[Background] +Bold=false +Color=0,0,0 +Transparency=false + +[BackgroundIntense] +Bold=false +Color=0,0,0 +Transparency=false + +[Color0] +Bold=false +Color=0,0,0 +Transparency=false + +[Color0Intense] +Bold=false +Color=104,104,104 +Transparency=false + +[Color1] +Bold=false +Color=250,75,75 +Transparency=false + +[Color1Intense] +Bold=false +Color=255,84,84 +Transparency=false + +[Color2] +Bold=false +Color=24,178,24 +Transparency=false + +[Color2Intense] +Bold=false +Color=84,255,84 +Transparency=false + +[Color3] +Bold=false +Color=178,104,24 +Transparency=false + +[Color3Intense] +Bold=false +Color=255,255,84 +Transparency=false + +[Color4] +Bold=false +Color=92,167,251 +Transparency=false + +[Color4Intense] +Bold=false +Color=84,84,255 +Transparency=false + +[Color5] +Bold=false +Color=225,30,225 +Transparency=false + +[Color5Intense] +Bold=false +Color=255,84,255 +Transparency=false + +[Color6] +Bold=false +Color=24,178,178 +Transparency=false + +[Color6Intense] +Bold=false +Color=84,255,255 +Transparency=false + +[Color7] +Bold=false +Color=178,178,178 +Transparency=false + +[Color7Intense] +Bold=false +Color=255,255,255 +Transparency=false + +[Foreground] +Bold=false +Color=24,240,24 +Transparency=false + +[ForegroundIntense] +Bold=true +Color=24,240,24 +Transparency=false + +[General] +Description=Green on Black +Opacity=1 diff --git a/lib/color-schemes/Linux.colorscheme b/lib/color-schemes/Linux.colorscheme new file mode 100644 index 0000000..c9afb14 --- /dev/null +++ b/lib/color-schemes/Linux.colorscheme @@ -0,0 +1,100 @@ +[Background] +Bold=false +Color=0,0,0 + +[BackgroundIntense] +Bold=false +Color=104,104,104 + +[Color0] +Bold=false +Color=0,0,0 + + +[Color0Intense] +Bold=false +Color=104,104,104 + + +[Color1] +Bold=false +Color=178,24,24 + + +[Color1Intense] +Bold=false +Color=255,84,84 + + +[Color2] +Bold=false +Color=24,178,24 + + +[Color2Intense] +Bold=false +Color=84,255,84 + + +[Color3] +Bold=false +Color=178,104,24 + + +[Color3Intense] +Bold=false +Color=255,255,84 + + +[Color4] +Bold=false +Color=24,24,178 + + +[Color4Intense] +Bold=false +Color=84,84,255 + + +[Color5] +Bold=false +Color=178,24,178 + + +[Color5Intense] +Bold=false +Color=255,84,255 + + +[Color6] +Bold=false +Color=24,178,178 + + +[Color6Intense] +Bold=false +Color=84,255,255 + + +[Color7] +Bold=false +Color=178,178,178 + + +[Color7Intense] +Bold=false +Color=255,255,255 + + +[Foreground] +Bold=false +Color=178,178,178 + + +[ForegroundIntense] +Bold=false +Color=255,255,255 + + +[General] +Description=Linux Colors diff --git a/lib/color-schemes/WhiteOnBlack.schema b/lib/color-schemes/WhiteOnBlack.schema new file mode 100644 index 0000000..05c5bc0 --- /dev/null +++ b/lib/color-schemes/WhiteOnBlack.schema @@ -0,0 +1,42 @@ +# example scheme for konsole + +# the title is to appear in the menu. + +title White on Black + +# foreground colors + +# note that the default background color is flagged +# to become transparent when an image is present. + +# slot transparent bold +# | | | +# V V--color--V V V + +color 0 255 255 255 0 0 # regular foreground color (White) +color 1 0 0 0 1 0 # regular background color (Black) + +color 2 0 0 0 0 0 # regular color 0 Black +color 3 178 24 24 0 0 # regular color 1 Red +color 4 24 178 24 0 0 # regular color 2 Green +color 5 178 104 24 0 0 # regular color 3 Yellow +color 6 24 24 178 0 0 # regular color 4 Blue +color 7 178 24 178 0 0 # regular color 5 Magenta +color 8 24 178 178 0 0 # regular color 6 Cyan +color 9 178 178 178 0 0 # regular color 7 White + +# intensive colors + +# instead of changing the colors, we've flaged the text to become bold + +color 10 255 255 255 0 1 # intensive foreground color +color 11 0 0 0 1 0 # intensive background color + +color 12 104 104 104 0 0 # intensive color 0 +color 13 255 84 84 0 0 # intensive color 1 +color 14 84 255 84 0 0 # intensive color 2 +color 15 255 255 84 0 0 # intensive color 3 +color 16 84 84 255 0 0 # intensive color 4 +color 17 255 84 255 0 0 # intensive color 5 +color 18 84 255 255 0 0 # intensive color 6 +color 19 255 255 255 0 0 # intensive color 7 diff --git a/lib/color-schemes/historic/BlackOnLightColor.schema b/lib/color-schemes/historic/BlackOnLightColor.schema new file mode 100644 index 0000000..92e598a --- /dev/null +++ b/lib/color-schemes/historic/BlackOnLightColor.schema @@ -0,0 +1,42 @@ +# example scheme for konsole + +# the title is to appear in the menu. + +title Black on Light Color + +# foreground colors + +# note that the default background color is flagged +# to become transparent when an image is present. + +# slot transparent bold +# | | | +# V V--color--V V V + +color 0 0 0 0 0 0 # regular foreground color (Black) +rcolor 1 30 255 1 0 # regular background color (Light Color) + +color 2 0 0 0 0 0 # regular color 0 Black +color 3 178 24 24 0 0 # regular color 1 Red +color 4 24 178 24 0 0 # regular color 2 Green +color 5 178 104 24 0 0 # regular color 3 Yellow +color 6 24 24 178 0 0 # regular color 4 Blue +color 7 178 24 178 0 0 # regular color 5 Magenta +color 8 24 178 178 0 0 # regular color 6 Cyan +color 9 178 178 178 0 0 # regular color 7 White + +# intensive colors + +# instead of changing the colors, we've flaged the text to become bold + +color 10 0 0 0 0 1 # intensive foreground color +color 11 255 255 221 1 0 # intensive background color + +color 12 104 104 104 0 0 # intensive color 0 +color 13 255 84 84 0 0 # intensive color 1 +color 14 84 255 84 0 0 # intensive color 2 +color 15 255 255 84 0 0 # intensive color 3 +color 16 84 84 255 0 0 # intensive color 4 +color 17 255 84 255 0 0 # intensive color 5 +color 18 84 255 255 0 0 # intensive color 6 +color 19 255 255 255 0 0 # intensive color 7 diff --git a/lib/color-schemes/historic/DarkPicture.schema b/lib/color-schemes/historic/DarkPicture.schema new file mode 100644 index 0000000..78ab3df --- /dev/null +++ b/lib/color-schemes/historic/DarkPicture.schema @@ -0,0 +1,44 @@ +# example scheme for konsole + +# the title is to appear in the menu. + +title Marble + +image tile Blkmarble.jpg + +# foreground colors + +# note that the default background color is flagged +# to become transparent when an image is present. + +# slot transparent bold +# | | | +# V V--color--V V V + +color 0 255 255 255 0 0 # regular foreground color (White) +color 1 0 0 0 1 0 # regular background color (Black) + +color 2 0 0 0 0 0 # regular color 0 Black +color 3 178 24 24 0 0 # regular color 1 Red +color 4 24 178 24 0 0 # regular color 2 Green +color 5 178 104 24 0 0 # regular color 3 Yellow +color 6 24 24 178 0 0 # regular color 4 Blue +color 7 178 24 178 0 0 # regular color 5 Magenta +color 8 24 178 178 0 0 # regular color 6 Cyan +color 9 178 178 178 0 0 # regular color 7 White + +# intensive colors + +# instead of changing the colors, we've flaged the text to become bold + +color 10 255 255 255 0 1 # intensive foreground color +color 11 0 0 0 1 0 # intensive background color + +color 12 104 104 104 0 0 # intensive color 0 +color 13 255 84 84 0 0 # intensive color 1 +color 14 84 255 84 0 0 # intensive color 2 +color 15 255 255 84 0 0 # intensive color 3 +color 16 84 84 255 0 0 # intensive color 4 +color 17 255 84 255 0 0 # intensive color 5 +color 18 84 255 255 0 0 # intensive color 6 +color 19 255 255 255 0 0 # intensive color 7 diff --git a/lib/color-schemes/historic/Example.Schema b/lib/color-schemes/historic/Example.Schema new file mode 100644 index 0000000..8611d44 --- /dev/null +++ b/lib/color-schemes/historic/Example.Schema @@ -0,0 +1,47 @@ +# example scheme for konsole + +# the title is to appear in the menu. + +title Ugly 1 + +# add a wallpaper, if you like. Second word one of { tile,center,full } + +image tile /opt/kde/share/wallpapers/dancy_pants.jpg + + +# foreground colors + +# note that the default background color is flagged +# to become transparent when an image is present. + +# slot transparent bold +# | | | +# V V--color--V V V + +color 0 0 0 0 0 0 # regular foreground color (Black) +color 1 255 255 255 1 0 # regular background color (White) + +color 2 0 0 0 0 0 # regular color 0 Black +color 3 255 0 0 0 0 # regular color 1 Red +color 4 0 255 0 0 0 # regular color 2 Green +color 5 255 255 0 0 0 # regular color 3 Yellow +color 6 0 0 255 0 0 # regular color 4 Blue +color 7 255 0 255 0 0 # regular color 5 Magenta +color 8 0 255 255 0 0 # regular color 6 Cyan +color 9 255 255 255 0 0 # regular color 7 White + +# intensive colors + +# instead of changing the colors, we've flaged the text to become bold + +color 10 0 0 0 0 1 # intensive foreground color +color 11 255 255 255 1 1 # intensive background color + +color 12 0 0 0 0 1 # intensive color 0 +color 13 255 0 0 0 1 # intensive color 1 +color 14 0 255 0 0 1 # intensive color 2 +color 15 255 255 0 0 1 # intensive color 3 +color 16 0 0 255 0 1 # intensive color 4 +color 17 255 0 255 0 1 # intensive color 5 +color 18 0 255 255 0 1 # intensive color 6 +color 19 255 255 255 0 1 # intensive color 7 diff --git a/lib/color-schemes/historic/GreenOnBlack.schema b/lib/color-schemes/historic/GreenOnBlack.schema new file mode 100644 index 0000000..8f19c5b --- /dev/null +++ b/lib/color-schemes/historic/GreenOnBlack.schema @@ -0,0 +1,42 @@ +# example scheme for konsole + +# the title is to appear in the menu. + +title Green on Black + +# foreground colors + +# note that the default background color is flagged +# to become transparent when an image is present. + +# slot transparent bold +# | | | +# V V--color--V V V + +color 0 24 240 24 0 0 # regular foreground color (Green) +color 1 0 0 0 1 0 # regular background color (Black) + +color 2 0 0 0 0 0 # regular color 0 Black +color 3 178 24 24 0 0 # regular color 1 Red +color 4 24 178 24 0 0 # regular color 2 Green +color 5 178 104 24 0 0 # regular color 3 Yellow +color 6 24 24 178 0 0 # regular color 4 Blue +color 7 178 24 178 0 0 # regular color 5 Magenta +color 8 24 178 178 0 0 # regular color 6 Cyan +color 9 178 178 178 0 0 # regular color 7 White + +# intensive colors + +# instead of changing the colors, we've flaged the text to become bold + +color 10 24 240 24 0 1 # intensive foreground color +color 11 0 0 0 1 0 # intensive background color + +color 12 104 104 104 0 0 # intensive color 0 +color 13 255 84 84 0 0 # intensive color 1 +color 14 84 255 84 0 0 # intensive color 2 +color 15 255 255 84 0 0 # intensive color 3 +color 16 84 84 255 0 0 # intensive color 4 +color 17 255 84 255 0 0 # intensive color 5 +color 18 84 255 255 0 0 # intensive color 6 +color 19 255 255 255 0 0 # intensive color 7 diff --git a/lib/color-schemes/historic/GreenTint.schema b/lib/color-schemes/historic/GreenTint.schema new file mode 100644 index 0000000..2786678 --- /dev/null +++ b/lib/color-schemes/historic/GreenTint.schema @@ -0,0 +1,49 @@ +# linux color schema for konsole + +title Green Tint + +transparency 0.3 0 150 0 + +# FIXME +# +# The flaw in this schema is that "blick" comes out on the +# Linux console as intensive background, really. +# Since this is not used in clients you'll hardly notice +# it in practice. + +# foreground colors + +# note that the default background color is flagged +# to become transparent when an image is present. + +# slot transparent bold +# | red grn blu | | +# V V--color--V V V + +color 0 178 178 178 0 0 # regular foreground color (White) +color 1 0 0 0 1 0 # regular background color (Black) + +color 2 0 0 0 0 0 # regular color 0 Black +color 3 178 24 24 0 0 # regular color 1 Red +color 4 24 178 24 0 0 # regular color 2 Green +color 5 178 104 24 0 0 # regular color 3 Yellow +color 6 24 24 178 0 0 # regular color 4 Blue +color 7 178 24 178 0 0 # regular color 5 Magenta +color 8 24 178 178 0 0 # regular color 6 Cyan +color 9 178 178 178 0 0 # regular color 7 White + +# intensive colors + +# instead of changing the colors, we've flaged the text to become bold + +color 10 255 255 255 0 0 # intensive foreground color +color 11 104 104 104 1 0 # intensive background color + +color 12 104 104 104 0 0 # intensive color 0 +color 13 255 84 84 0 0 # intensive color 1 +color 14 84 255 84 0 0 # intensive color 2 +color 15 255 255 84 0 0 # intensive color 3 +color 16 84 84 255 0 0 # intensive color 4 +color 17 255 84 255 0 0 # intensive color 5 +color 18 84 255 255 0 0 # intensive color 6 +color 19 255 255 255 0 0 # intensive color 7 diff --git a/lib/color-schemes/historic/GreenTint_MC.schema b/lib/color-schemes/historic/GreenTint_MC.schema new file mode 100644 index 0000000..954755e --- /dev/null +++ b/lib/color-schemes/historic/GreenTint_MC.schema @@ -0,0 +1,49 @@ +# linux color schema for konsole + +title Green Tint with Transparent MC + +transparency 0.3 0 150 0 + +# FIXME +# +# The flaw in this schema is that "blick" comes out on the +# Linux console as intensive background, really. +# Since this is not used in clients you'll hardly notice +# it in practice. + +# foreground colors + +# note that the default background color is flagged +# to become transparent when an image is present. + +# slot transparent bold +# | red grn blu | | +# V V--color--V V V + +color 0 178 178 178 0 0 # regular foreground color (White) +color 1 0 0 0 1 0 # regular background color (Black) + +color 2 0 0 0 0 0 # regular color 0 Black +color 3 178 24 24 0 0 # regular color 1 Red +color 4 24 178 24 0 0 # regular color 2 Green +color 5 178 104 24 0 0 # regular color 3 Yellow +color 6 0 0 0 1 0 # regular color 4 Blue +color 7 178 24 178 0 0 # regular color 5 Magenta +color 8 24 178 178 0 0 # regular color 6 Cyan +color 9 178 178 178 0 0 # regular color 7 White + +# intensive colors + +# instead of changing the colors, we've flaged the text to become bold + +color 10 255 255 255 0 0 # intensive foreground color +color 11 104 104 104 1 0 # intensive background color + +color 12 104 104 104 0 0 # intensive color 0 +color 13 255 84 84 0 0 # intensive color 1 +color 14 84 255 84 0 0 # intensive color 2 +color 15 255 255 84 0 0 # intensive color 3 +color 16 84 84 255 0 0 # intensive color 4 +color 17 255 84 255 0 0 # intensive color 5 +color 18 84 255 255 0 0 # intensive color 6 +color 19 255 255 255 0 0 # intensive color 7 diff --git a/lib/color-schemes/historic/LightPicture.schema b/lib/color-schemes/historic/LightPicture.schema new file mode 100644 index 0000000..6acd7a8 --- /dev/null +++ b/lib/color-schemes/historic/LightPicture.schema @@ -0,0 +1,44 @@ +# example scheme for konsole + +# the title is to appear in the menu. + +title Paper + +image tile Paper01.jpg + +# foreground colors + +# note that the default background color is flagged +# to become transparent when an image is present. + +# slot transparent bold +# | | | +# V V--color--V V V + +color 0 0 0 0 0 0 # regular foreground color (Black) +color 1 255 255 255 1 0 # regular background color (White) + +color 2 0 0 0 0 0 # regular color 0 Black +color 3 178 24 24 0 0 # regular color 1 Red +color 4 24 178 24 0 0 # regular color 2 Green +color 5 178 104 24 0 0 # regular color 3 Yellow +color 6 24 24 178 0 0 # regular color 4 Blue +color 7 178 24 178 0 0 # regular color 5 Magenta +color 8 24 178 178 0 0 # regular color 6 Cyan +color 9 178 178 178 0 0 # regular color 7 White + +# intensive colors + +# instead of changing the colors, we've flaged the text to become bold + +color 10 0 0 0 0 1 # intensive foreground color +color 11 255 255 255 1 0 # intensive background color + +color 12 104 104 104 0 0 # intensive color 0 +color 13 255 84 84 0 0 # intensive color 1 +color 14 84 255 84 0 0 # intensive color 2 +color 15 255 255 84 0 0 # intensive color 3 +color 16 84 84 255 0 0 # intensive color 4 +color 17 255 84 255 0 0 # intensive color 5 +color 18 84 255 255 0 0 # intensive color 6 +color 19 255 255 255 0 0 # intensive color 7 diff --git a/lib/color-schemes/historic/Linux.schema b/lib/color-schemes/historic/Linux.schema new file mode 100644 index 0000000..a2515d9 --- /dev/null +++ b/lib/color-schemes/historic/Linux.schema @@ -0,0 +1,47 @@ +# linux color schema for konsole + +title Linux Colors + +# FIXME +# +# The flaw in this schema is that "blick" comes out on the +# Linux console as intensive background, really. +# Since this is not used in clients you'll hardly notice +# it in practice. + +# foreground colors + +# note that the default background color is flagged +# to become transparent when an image is present. + +# slot transparent bold +# | red grn blu | | +# V V--color--V V V + +color 0 178 178 178 0 0 # regular foreground color (White) +color 1 0 0 0 1 0 # regular background color (Black) + +color 2 0 0 0 0 0 # regular color 0 Black +color 3 178 24 24 0 0 # regular color 1 Red +color 4 24 178 24 0 0 # regular color 2 Green +color 5 178 104 24 0 0 # regular color 3 Yellow +color 6 24 24 178 0 0 # regular color 4 Blue +color 7 178 24 178 0 0 # regular color 5 Magenta +color 8 24 178 178 0 0 # regular color 6 Cyan +color 9 178 178 178 0 0 # regular color 7 White + +# intensive colors + +# instead of changing the colors, we've flaged the text to become bold + +color 10 255 255 255 0 0 # intensive foreground color +color 11 104 104 104 1 0 # intensive background color + +color 12 104 104 104 0 0 # intensive color 0 +color 13 255 84 84 0 0 # intensive color 1 +color 14 84 255 84 0 0 # intensive color 2 +color 15 255 255 84 0 0 # intensive color 3 +color 16 84 84 255 0 0 # intensive color 4 +color 17 255 84 255 0 0 # intensive color 5 +color 18 84 255 255 0 0 # intensive color 6 +color 19 255 255 255 0 0 # intensive color 7 diff --git a/lib/color-schemes/historic/README.Schema b/lib/color-schemes/historic/README.Schema new file mode 100644 index 0000000..f737c14 --- /dev/null +++ b/lib/color-schemes/historic/README.Schema @@ -0,0 +1,132 @@ +[README.Schema] + +The schemata offered in the Options/Schema menu are +taken from from configurations files with a *.schema +pattern either located in $KDEDIR/share/apps/konsole +or ~/.kde/share/apps/konsole. + +Schemata allow to configure the color set that konsole +uses, together with some more information on rendition +processing. + +Syntax + + File + :: { [Line] ['#' Comment] '\n' } + + Line + :: "title" Title + :: "image" Usage PathToPictureFile + :: "transparency" Fade Red Green Blue + :: "color" Slot Red Green Blue Transparent Bold + :: "rcolor" Slot Saturation Value Transparent Bold + :: "sysfg" Slot Transparent Bold + :: "sysbg" Slot Transparent Bold + +Meaning + + - Title is the text to appear in the Option/Schema menu. + It should be unique among all other schemata therefore. + + - The "image" clause allows to place an image on the + konsole's background. + + - Usage can be either + - "tile" - the image is tilewise replicated. + - "center" - the image is centered. + - "full" - the image is stretched to fit the window size. + + - The Path of the picture can both be relative + (to kde wallpapers) or absolute. + + When a schema uses a background image (or transparency) + one has to make at least one color slot transparent to + achive any visible effect. Please read below about the + "Transparent" field in color,sysbg,sysfg. + + - The "transparency" clause picks and uses the background + of the desktop as if it where an image together with + a fade effect. This effect will fade the background + to the specified color. + + The "Fade" is a real value between 0 and 1, indicating + the strength of the fade. A value of 0 will not change + the image, a value of 1 will make it the fade color + everywhere, and in between. This will make the "glas" + of the window be of the color given in the clause and + being more(1) or less(0) intransparent. + + - The remaining clauses (color,sysbg,sysfg) are used + to setup konsoles rendition system. + + To this end, konsole offers 20 color slots. + + Slot Meaning + ----- -------------------------- + 0 regular foreground color + 1 regular background color + 2-9 regular bgr color 0-7 + 10 intensive foreground color + 11 intensive background color + 12-19 intensive bgr color 0-7 + + The traditional meaning of the "bgr" color codes + has a bitwise interpretation of an additive three + primary color scheme inherited from early EGA + color terminals. + + Color Bits Colors + ----- ---- ------- + 0 000 Black + 1 001 Red + 2 010 Green + 3 011 Yellow + 4 100 Blue + 5 101 Magenta + 6 110 Cyan + 7 111 White + + One may or may not stick to this tradition. + Konsole allows to assign colors freely to slots. + + The slots fall apart into two groups, regular + and intensive colors. The later are used when + BOLD rendition is used by the client. + + Each of the groups have a default fore- and + background color and the said bgr colors. + Normal terminal processing will simply use + the default colors. + + The color desired for a slot is indicated + in the Red Green Blue fields of the color + clause. Use the sysfg or the sysbg clause + to indicate the default fore and background + colors of the desktop. + + To specify randomized color for a slot use + the clause rcolor. The two parameters to it + being Saturation - the amount of colour, + and Value, the darkness of the colour. + + To use transparency/images and to simulate + the behavior of the xterm, one can supply + two additional tags to each slot: + - Transparent (0/1) meaning to show the + background picture, if any. + - Bold (0/1) to render characters bold. + + +If you know about the escape codes, you might have +noticed that intensive and bold rendition are sort +of confused. This is inherited by the xterm which +konsole is simulating. + +One can use the colortest.sh script supplied +with the konsole source distribution to test +a schema. + +The schema installed with konsole are more or +less demonstrations and not really beauty, +beside the Linux.schema, perhaps, which is +made after the VGA colors. diff --git a/lib/color-schemes/historic/README.default.Schema b/lib/color-schemes/historic/README.default.Schema new file mode 100644 index 0000000..e024e5a --- /dev/null +++ b/lib/color-schemes/historic/README.default.Schema @@ -0,0 +1,44 @@ +# default scheme for konsole (only here for documentation purposes) + +# the title is to appear in the menu. + +title Konsole Defaults + +# image tile /opt/kde/share/wallpapers/gray2.jpg + +# foreground colors + +# note that the default background color is flagged +# to become transparent when an image is present. + +# slot transparent bold +# | | | +# V V--color--V V V + +color 0 0 0 0 0 0 # regular foreground color (Black) +color 1 255 255 255 1 0 # regular background color (White) + +color 2 0 0 0 0 0 # regular color 0 Black +color 3 178 24 24 0 0 # regular color 1 Red +color 4 24 178 24 0 0 # regular color 2 Green +color 5 178 104 24 0 0 # regular color 3 Yellow +color 6 24 24 178 0 0 # regular color 4 Blue +color 7 178 24 178 0 0 # regular color 5 Magenta +color 8 24 178 178 0 0 # regular color 6 Cyan +color 9 178 178 178 0 0 # regular color 7 White + +# intensive colors + +# instead of changing the colors, we've flaged the text to become bold + +color 10 0 0 0 0 1 # intensive foreground color +color 11 255 255 255 1 0 # intensive background color + +color 12 104 104 104 0 0 # intensive color 0 +color 13 255 84 84 0 0 # intensive color 1 +color 14 84 255 84 0 0 # intensive color 2 +color 15 255 255 84 0 0 # intensive color 3 +color 16 84 84 255 0 0 # intensive color 4 +color 17 255 84 255 0 0 # intensive color 5 +color 18 84 255 255 0 0 # intensive color 6 +color 19 255 255 255 0 0 # intensive color 7 diff --git a/lib/color-schemes/historic/Transparent.schema b/lib/color-schemes/historic/Transparent.schema new file mode 100644 index 0000000..41f8dc0 --- /dev/null +++ b/lib/color-schemes/historic/Transparent.schema @@ -0,0 +1,49 @@ +# linux color schema for konsole + +title Transparent Konsole + +transparency 0.35 0 0 0 + +# FIXME +# +# The flaw in this schema is that "blick" comes out on the +# Linux console as intensive background, really. +# Since this is not used in clients you'll hardly notice +# it in practice. + +# foreground colors + +# note that the default background color is flagged +# to become transparent when an image is present. + +# slot transparent bold +# | red grn blu | | +# V V--color--V V V + +color 0 178 178 178 0 0 # regular foreground color (White) +color 1 0 0 0 1 0 # regular background color (Black) + +color 2 0 0 0 0 0 # regular color 0 Black +color 3 178 24 24 0 0 # regular color 1 Red +color 4 24 178 24 0 0 # regular color 2 Green +color 5 178 104 24 0 0 # regular color 3 Yellow +color 6 24 24 178 0 0 # regular color 4 Blue +color 7 178 24 178 0 0 # regular color 5 Magenta +color 8 24 178 178 0 0 # regular color 6 Cyan +color 9 178 178 178 0 0 # regular color 7 White + +# intensive colors + +# instead of changing the colors, we've flaged the text to become bold + +color 10 255 255 255 0 0 # intensive foreground color +color 11 104 104 104 1 0 # intensive background color + +color 12 104 104 104 0 0 # intensive color 0 +color 13 255 84 84 0 0 # intensive color 1 +color 14 84 255 84 0 0 # intensive color 2 +color 15 255 255 84 0 0 # intensive color 3 +color 16 84 84 255 0 0 # intensive color 4 +color 17 255 84 255 0 0 # intensive color 5 +color 18 84 255 255 0 0 # intensive color 6 +color 19 255 255 255 0 0 # intensive color 7 diff --git a/lib/color-schemes/historic/Transparent_MC.schema b/lib/color-schemes/historic/Transparent_MC.schema new file mode 100644 index 0000000..8991b9a --- /dev/null +++ b/lib/color-schemes/historic/Transparent_MC.schema @@ -0,0 +1,51 @@ +# linux color schema for konsole + +title Transparent for MC + +transparency 0.35 0 0 0 + +# FIXME +# +# The flaw in this schema is that "blick" comes out on the +# Linux console as intensive background, really. +# Since this is not used in clients you'll hardly notice +# it in practice. + +# foreground colors + +# note that the default background color is flagged +# to become transparent when an image is present. + +# slot transparent bold +# | red grn blu | | +# V V--color--V V V + +color 0 178 178 178 0 0 # regular foreground color (White) +color 1 0 0 0 1 0 # regular background color (Black) + +color 2 0 0 0 0 0 # regular color 0 Black +color 3 178 24 24 0 0 # regular color 1 Red +color 4 24 178 24 0 0 # regular color 2 Green +color 5 178 104 24 0 0 # regular color 3 Yellow +#color 6 24 24 178 0 0 # regular color 4 Blue +color 6 0 0 0 1 0 # regular color 4 Blue + +color 7 178 24 178 0 0 # regular color 5 Magenta +color 8 24 178 178 0 0 # regular color 6 Cyan +color 9 178 178 178 0 0 # regular color 7 White + +# intensive colors + +# instead of changing the colors, we've flaged the text to become bold + +color 10 255 255 255 0 0 # intensive foreground color +color 11 104 104 104 1 0 # intensive background color + +color 12 104 104 104 0 0 # intensive color 0 +color 13 255 84 84 0 0 # intensive color 1 +color 14 84 255 84 0 0 # intensive color 2 +color 15 255 255 84 0 0 # intensive color 3 +color 16 84 84 255 0 0 # intensive color 4 +color 17 255 84 255 0 0 # intensive color 5 +color 18 84 255 255 0 0 # intensive color 6 +color 19 255 255 255 0 0 # intensive color 7 diff --git a/lib/color-schemes/historic/Transparent_darkbg.schema b/lib/color-schemes/historic/Transparent_darkbg.schema new file mode 100644 index 0000000..61792fa --- /dev/null +++ b/lib/color-schemes/historic/Transparent_darkbg.schema @@ -0,0 +1,42 @@ +# linux color schema for konsole + +title Transparent, Dark Background + +transparency 0.75 0 0 0 + +# foreground colors + +# note that the default background color is flagged +# to become transparent when an image is present. + +# slot transparent bold +# | red grn blu | | +# V V--color--V V V + +color 0 255 255 255 0 0 # regular foreground color (White) +color 1 0 0 0 1 0 # regular background color (Black) + +color 2 0 0 0 0 0 # regular color 0 Black +color 3 178 24 24 0 0 # regular color 1 Red +color 4 24 178 24 0 0 # regular color 2 Green +color 5 178 104 24 0 0 # regular color 3 Yellow +color 6 24 24 178 0 0 # regular color 4 Blue +color 7 178 24 178 0 0 # regular color 5 Magenta +color 8 24 178 178 0 0 # regular color 6 Cyan +color 9 178 178 178 0 0 # regular color 7 White + +# intensive colors + +# instead of changing the colors, we've flaged the text to become bold + +color 10 255 255 255 0 0 # intensive foreground color +color 11 104 104 104 1 0 # intensive background color + +color 12 104 104 104 0 0 # intensive color 0 +color 13 255 84 84 0 0 # intensive color 1 +color 14 84 255 84 0 0 # intensive color 2 +color 15 255 255 84 0 0 # intensive color 3 +color 16 84 84 255 0 0 # intensive color 4 +color 17 255 84 255 0 0 # intensive color 5 +color 18 84 255 255 0 0 # intensive color 6 +color 19 255 255 255 0 0 # intensive color 7 diff --git a/lib/color-schemes/historic/Transparent_lightbg.schema b/lib/color-schemes/historic/Transparent_lightbg.schema new file mode 100644 index 0000000..ce201f2 --- /dev/null +++ b/lib/color-schemes/historic/Transparent_lightbg.schema @@ -0,0 +1,51 @@ +# linux color schema for konsole + +title Transparent, Light Background + +transparency 0.1 0 0 0 + +# This is a schema for very light backgrounds. It makes some +# hacks about the colors to make Midnight Commander transparent +# and with suitable colors. + +# foreground colors + +# note that the default background color is flagged +# to become transparent when an image is present. + +# slot transparent bold +# | red grn blu | | +# V V--color--V V V + +color 0 50 50 50 0 0 # regular foreground color (DarkGray) +color 1 200 200 200 1 0 # regular background color (White) + +# color 2 0 0 0 0 0 # regular color 0 Black +color 2 200 200 200 1 0 # regular background color (White) +color 3 178 24 24 0 0 # regular color 1 Red +color 4 24 178 24 0 0 # regular color 2 Green +color 5 178 104 24 0 0 # regular color 3 Yellow +#color 6 24 24 178 0 0 # regular color 4 Blue +color 6 0 0 0 1 0 # regular color 4 Blue +# Blue is transparent, to make MC transparent + +color 7 178 24 178 0 0 # regular color 5 Magenta +color 8 24 178 178 0 0 # regular color 6 Cyan +# color 9 178 178 178 0 0 # regular color 7 White +color 9 50 50 50 0 0 # regular foreground color (DarkGray) + +# intensive colors + +# instead of changing the colors, we've flaged the text to become bold + +color 10 0 0 0 0 0 # intensive foreground color +color 11 255 255 255 1 0 # intensive background color + +color 12 104 104 104 0 0 # intensive color 0 +color 13 255 84 84 0 0 # intensive color 1 +color 14 84 255 84 0 0 # intensive color 2 +color 15 255 255 84 0 0 # intensive color 3 +color 16 84 84 255 0 0 # intensive color 4 +color 17 255 84 255 0 0 # intensive color 5 +color 18 84 255 255 0 0 # intensive color 6 +color 19 255 255 255 0 0 # intensive color 7 diff --git a/lib/color-schemes/historic/XTerm.schema b/lib/color-schemes/historic/XTerm.schema new file mode 100644 index 0000000..3ff787d --- /dev/null +++ b/lib/color-schemes/historic/XTerm.schema @@ -0,0 +1,46 @@ +# xterm color schema for konsole + +# xterm colors can be configured (almost) like +# konsole colors can. This is the uncustomized +# xterm schema. +# Please refere to your local xterm setup files +# if this schema differs. + +title XTerm Colors + +# foreground colors ------------------------------- + +# note that the default background color is flagged +# to become transparent when an image is present. + +# slot transparent bold +# | red grn blu | | +# V V--color--V V V + +color 0 0 0 0 0 0 # regular foreground color (Black) +color 1 255 255 255 1 0 # regular background color (White) + +color 2 0 0 0 0 0 # regular color 0 Black +color 3 205 0 0 0 0 # regular color 1 Red +color 4 0 205 0 0 0 # regular color 2 Green +color 5 205 205 0 0 0 # regular color 3 Yellow +color 6 0 0 205 0 0 # regular color 4 Blue +color 7 205 0 205 0 0 # regular color 5 Magenta +color 8 0 205 205 0 0 # regular color 6 Cyan +color 9 229 229 229 0 0 # regular color 7 White + +# intensive colors ------------------------------------------- + +# for some strange reason, intensive colors are bold, also. + +color 10 77 77 77 0 1 # intensive foreground color +color 11 255 255 255 1 1 # intensive background color + +color 12 77 77 77 0 1 # intensive color 0 +color 13 255 0 0 0 1 # intensive color 1 +color 14 0 255 0 0 1 # intensive color 2 +color 15 255 255 0 0 1 # intensive color 3 +color 16 0 0 255 0 1 # intensive color 4 +color 17 255 0 255 0 1 # intensive color 5 +color 18 0 255 255 0 1 # intensive color 6 +color 19 255 255 255 0 1 # intensive color 7 diff --git a/lib/color-schemes/historic/syscolor.schema b/lib/color-schemes/historic/syscolor.schema new file mode 100644 index 0000000..a9a65ea --- /dev/null +++ b/lib/color-schemes/historic/syscolor.schema @@ -0,0 +1,44 @@ +# schema that uses system colors + +# the title is to appear in the menu. + +title System Colors + +# image none + +# foreground colors + +# note that the default background color is flagged +# to become transparent when an image is present. + +# slot transparent bold +# | | | +# V V--color--V V V + +sysfg 0 0 0 # regular foreground color (system) +sysbg 1 1 0 # regular background color (system) + +color 2 0 0 0 0 0 # regular color 0 Black +color 3 178 24 24 0 0 # regular color 1 Red +color 4 24 178 24 0 0 # regular color 2 Green +color 5 178 104 24 0 0 # regular color 3 Yellow +color 6 24 24 178 0 0 # regular color 4 Blue +color 7 178 24 178 0 0 # regular color 5 Magenta +color 8 24 178 178 0 0 # regular color 6 Cyan +color 9 178 178 178 0 0 # regular color 7 White + +# intensive colors + +# instead of changing the colors, we've flaged the text to become bold + +color 10 0 0 0 0 1 # intensive foreground color +color 11 255 255 255 1 0 # intensive background color + +color 12 104 104 104 0 0 # intensive color 0 +color 13 255 84 84 0 0 # intensive color 1 +color 14 84 255 84 0 0 # intensive color 2 +color 15 255 255 84 0 0 # intensive color 3 +color 16 84 84 255 0 0 # intensive color 4 +color 17 255 84 255 0 0 # intensive color 5 +color 18 84 255 255 0 0 # intensive color 6 +color 19 255 255 255 0 0 # intensive color 7 diff --git a/lib/color-schemes/historic/vim.schema b/lib/color-schemes/historic/vim.schema new file mode 100644 index 0000000..f29e3f7 --- /dev/null +++ b/lib/color-schemes/historic/vim.schema @@ -0,0 +1,40 @@ +# VIM-recommended color schema for konsole + +# VIM (VI improved) in "help xiterm" recommends these colors for xterm. + +title VIM Colors + +# foreground colors ------------------------------- + +# note that the default background color is flagged +# to become transparent when an image is present. + +# slot transparent bold +# | red grn blu | | +# V V--color--V V V + +color 0 0 0 0 0 0 # regular foreground color (Black) +color 1 255 255 255 1 0 # regular background color (White) + +color 2 0 0 0 0 0 # regular color 0 Black +color 3 192 0 0 0 0 # regular color 1 Red +color 4 0 128 0 0 0 # regular color 2 Green +color 5 128 128 0 0 0 # regular color 3 Yellow +color 6 0 0 192 0 0 # regular color 4 Blue +color 7 192 0 192 0 0 # regular color 5 Magenta +color 8 0 128 128 0 0 # regular color 6 Cyan +color 9 192 192 192 0 0 # regular color 7 White + +# intensive colors ------------------------------------------- + +color 10 77 77 77 0 1 # intensive foreground color +color 11 255 255 255 1 1 # intensive background color + +color 12 128 128 128 0 0 # intensive color 0 +color 13 255 96 96 0 0 # intensive color 1 +color 14 0 255 0 0 0 # intensive color 2 +color 15 255 255 0 0 0 # intensive color 3 +color 16 128 128 255 0 0 # intensive color 4 +color 17 255 64 255 0 0 # intensive color 5 +color 18 0 255 255 0 0 # intensive color 6 +color 19 255 255 255 0 0 # intensive color 7 diff --git a/lib/k3process.cpp b/lib/k3process.cpp deleted file mode 100644 index de210d5..0000000 --- a/lib/k3process.cpp +++ /dev/null @@ -1,1095 +0,0 @@ -/* - This file is part of the KDE libraries - Copyright (C) 1997 Christian Czezatke (e9025461@student.tuwien.ac.at) - - Rewritten for QT4 by e_k , Copyright (C)2008 - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - - -#include "k3process.h" -//#include - -#include "k3processcontroller.h" -#include "kpty.h" - -#ifdef __osf__ -#define _OSF_SOURCE -#include -#endif - -#ifdef _AIX -#define _ALL_SOURCE -#endif - -#include -#include - -#include -#include -#include -#include -#include - -#ifdef HAVE_SYS_SELECT_H -#include -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -//#include -//#include -//#include - - -////////////////// -// private data // -////////////////// - -class K3ProcessPrivate { -public: - K3ProcessPrivate() : - usePty(K3Process::NoCommunication), - addUtmp(false), useShell(false), - pty(0), - priority(0) { - } - - K3Process::Communication usePty; - bool addUtmp : 1; - bool useShell : 1; - - KPty * pty; - - int priority; - - QMap env; - QString wd; - QByteArray shell; - QByteArray executable; -}; - -///////////////////////////// -// public member functions // -///////////////////////////// - -K3Process::K3Process( QObject * parent ) - : QObject( parent ), - run_mode(NotifyOnExit), - runs(false), - pid_(0), - status(0), - keepPrivs(false), - innot(0), - outnot(0), - errnot(0), - communication(NoCommunication), - input_data(0), - input_sent(0), - input_total(0), - d(new K3ProcessPrivate) -{ - K3ProcessController::ref(); - K3ProcessController::instance()->addKProcess(this); - - - out[0] = out[1] = -1; - in[0] = in[1] = -1; - err[0] = err[1] = -1; -} - -void -K3Process::setEnvironment(const QString & name, const QString & value) -{ - d->env.insert(name, value); -} - -void -K3Process::setWorkingDirectory(const QString & dir) -{ - d->wd = dir; -} - -void -K3Process::setupEnvironment() -{ - QMap::Iterator it; - for (it = d->env.begin(); it != d->env.end(); ++it) { - setenv(QFile::encodeName(it.key()).data(), - QFile::encodeName(it.value()).data(), 1); - } - if (!d->wd.isEmpty()) { - if (-1 == chdir(QFile::encodeName(d->wd).constData())) { - qDebug() << "Can't change directory: " << strerror(errno) << endl; - } - } -} - -void -K3Process::setRunPrivileged(bool keepPrivileges) -{ - keepPrivs = keepPrivileges; -} - -bool -K3Process::runPrivileged() const -{ - return keepPrivs; -} - -bool -K3Process::setPriority(int prio) -{ - if (runs) { - if (setpriority(PRIO_PROCESS, pid_, prio)) { - return false; - } - } else { - if (prio > 19 || prio < (geteuid() ? getpriority(PRIO_PROCESS, 0) : -20)) { - return false; - } - } - d->priority = prio; - return true; -} - -K3Process::~K3Process() -{ - if (run_mode != DontCare) { - kill(SIGKILL); - } - detach(); - - delete d->pty; - delete d; - - K3ProcessController::instance()->removeKProcess(this); - K3ProcessController::deref(); -} - -void K3Process::detach() -{ - if (runs) { - K3ProcessController::instance()->addProcess(pid_); - runs = false; - pid_ = 0; // close without draining - commClose(); // Clean up open fd's and socket notifiers. - } -} - -void K3Process::setBinaryExecutable(const char * filename) -{ - d->executable = filename; -} - -K3Process & K3Process::operator<<(const QStringList & args) -{ - QStringList::ConstIterator it = args.begin(); - for ( ; it != args.end() ; ++it ) { - arguments.append(QFile::encodeName(*it)); - } - return *this; -} - -K3Process & K3Process::operator<<(const QByteArray & arg) -{ - return operator<< (arg.data()); -} - -K3Process & K3Process::operator<<(const char * arg) -{ - arguments.append(arg); - return *this; -} - -K3Process & K3Process::operator<<(const QString & arg) -{ - arguments.append(QFile::encodeName(arg)); - return *this; -} - -void K3Process::clearArguments() -{ - arguments.clear(); -} - -bool K3Process::start(RunMode runmode, Communication comm) -{ - if (runs) { - qDebug() << "Attempted to start an already running process" << endl; - return false; - } - - uint n = arguments.count(); - if (n == 0) { - qDebug() << "Attempted to start a process without arguments" << endl; - return false; - } - char ** arglist; - QByteArray shellCmd; - if (d->useShell) { - if (d->shell.isEmpty()) { - qDebug() << "Invalid shell specified" << endl; - return false; - } - - for (uint i = 0; i < n; i++) { - shellCmd += arguments[i]; - shellCmd += ' '; // CC: to separate the arguments - } - - arglist = static_cast(malloc( 4 * sizeof(char *))); - arglist[0] = d->shell.data(); - arglist[1] = (char *) "-c"; - arglist[2] = shellCmd.data(); - arglist[3] = 0; - } else { - arglist = static_cast(malloc( (n + 1) * sizeof(char *))); - for (uint i = 0; i < n; i++) { - arglist[i] = arguments[i].data(); - } - arglist[n] = 0; - } - - run_mode = runmode; - - if (!setupCommunication(comm)) { - qDebug() << "Could not setup Communication!" << endl; - free(arglist); - return false; - } - - // We do this in the parent because if we do it in the child process - // gdb gets confused when the application runs from gdb. -#ifdef HAVE_INITGROUPS - struct passwd * pw = geteuid() ? 0 : getpwuid(getuid()); -#endif - - int fd[2]; - if (pipe(fd)) { - fd[0] = fd[1] = -1; // Pipe failed.. continue - } - - // we don't use vfork() because - // - it has unclear semantics and is not standardized - // - we do way too much magic in the child - pid_ = fork(); - if (pid_ == 0) { - // The child process - - close(fd[0]); - // Closing of fd[1] indicates that the execvp() succeeded! - fcntl(fd[1], F_SETFD, FD_CLOEXEC); - - if (!commSetupDoneC()) { - qDebug() << "Could not finish comm setup in child!" << endl; - } - - // reset all signal handlers - struct sigaction act; - sigemptyset(&act.sa_mask); - act.sa_handler = SIG_DFL; - act.sa_flags = 0; - for (int sig = 1; sig < NSIG; sig++) { - sigaction(sig, &act, 0L); - } - - if (d->priority) { - setpriority(PRIO_PROCESS, 0, d->priority); - } - - if (!runPrivileged()) { - setgid(getgid()); -#ifdef HAVE_INITGROUPS - if (pw) { - initgroups(pw->pw_name, pw->pw_gid); - } -#endif - if (geteuid() != getuid()) { - setuid(getuid()); - } - if (geteuid() != getuid()) { - _exit(1); - } - } - - setupEnvironment(); - - if (runmode == DontCare || runmode == OwnGroup) { - setsid(); - } - - const char * executable = arglist[0]; - if (!d->executable.isEmpty()) { - executable = d->executable.data(); - } - execvp(executable, arglist); - - char resultByte = 1; - write(fd[1], &resultByte, 1); - _exit(-1); - } else if (pid_ == -1) { - // forking failed - - // commAbort(); - pid_ = 0; - free(arglist); - return false; - } - // the parent continues here - free(arglist); - - if (!commSetupDoneP()) { - qDebug() << "Could not finish comm setup in parent!" << endl; - } - - // Check whether client could be started. - close(fd[1]); - for (;;) { - char resultByte; - int n = ::read(fd[0], &resultByte, 1); - if (n == 1) { - // exec() failed - close(fd[0]); - waitpid(pid_, 0, 0); - pid_ = 0; - commClose(); - return false; - } - if (n == -1) { - if (errno == EINTR) { - continue; // Ignore - } - } - break; // success - } - close(fd[0]); - - runs = true; - switch (runmode) { - case Block: - for (;;) { - commClose(); // drain only, unless obsolete reimplementation - if (!runs) { - // commClose detected data on the process exit notifification pipe - K3ProcessController::instance()->unscheduleCheck(); - if (waitpid(pid_, &status, WNOHANG) != 0) { // error finishes, too - commClose(); // this time for real (runs is false) - K3ProcessController::instance()->rescheduleCheck(); - break; - } - runs = true; // for next commClose() iteration - } else { - // commClose is an obsolete reimplementation and waited until - // all output channels were closed (or it was interrupted). - // there is a chance that it never gets here ... - waitpid(pid_, &status, 0); - runs = false; - break; - } - } - // why do we do this? i think this signal should be emitted _only_ - // after the process has successfully run _asynchronously_ --ossi - emit processExited(this); - break; - default: // NotifyOnExit & OwnGroup - input_data = 0; // Discard any data for stdin that might still be there - break; - } - return true; -} - - - -bool K3Process::kill(int signo) -{ - if (runs && pid_ > 0 && !::kill(run_mode == OwnGroup ? -pid_ : pid_, signo)) { - return true; - } - return false; -} - - - -bool K3Process::isRunning() const -{ - return runs; -} - - - -pid_t K3Process::pid() const -{ - return pid_; -} - -#ifndef timersub -# define timersub(a, b, result) \ - do { \ - (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \ - (result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \ - if ((result)->tv_usec < 0) { \ - --(result)->tv_sec; \ - (result)->tv_usec += 1000000; \ - } \ - } while (0) -#endif - -bool K3Process::wait(int timeout) -{ - if (!runs) { - return true; - } - -#ifndef __linux__ - struct timeval etv; -#endif - struct timeval tv, *tvp; - if (timeout < 0) { - tvp = 0; - } else { -#ifndef __linux__ - gettimeofday(&etv, 0); - etv.tv_sec += timeout; -#else - tv.tv_sec = timeout; - tv.tv_usec = 0; -#endif - tvp = &tv; - } - - int fd = K3ProcessController::instance()->notifierFd(); - for (;;) { - fd_set fds; - FD_ZERO( &fds ); - FD_SET( fd, &fds ); - -#ifndef __linux__ - if (tvp) { - gettimeofday(&tv, 0); - timersub(&etv, &tv, &tv); - if (tv.tv_sec < 0) { - tv.tv_sec = tv.tv_usec = 0; - } - } -#endif - - switch ( select( fd+1, &fds, 0, 0, tvp ) ) { - case -1: - if ( errno == EINTR ) { - break; - } - // fall through; should happen if tvp->tv_sec < 0 - case 0: - K3ProcessController::instance()->rescheduleCheck(); - return false; - default: - K3ProcessController::instance()->unscheduleCheck(); - if (waitpid(pid_, &status, WNOHANG) != 0) { // error finishes, too - processHasExited(status); - K3ProcessController::instance()->rescheduleCheck(); - return true; - } - } - } - return false; -} - - - -bool K3Process::normalExit() const -{ - return (pid_ != 0) && !runs && WIFEXITED(status); -} - - -bool K3Process::signalled() const -{ - return (pid_ != 0) && !runs && WIFSIGNALED(status); -} - - -bool K3Process::coreDumped() const -{ -#ifdef WCOREDUMP - return signalled() && WCOREDUMP(status); -#else - return false; -#endif -} - - -int K3Process::exitStatus() const -{ - return WEXITSTATUS(status); -} - - -int K3Process::exitSignal() const -{ - return WTERMSIG(status); -} - - -bool K3Process::writeStdin(const char * buffer, int buflen) -{ - // if there is still data pending, writing new data - // to stdout is not allowed (since it could also confuse - // kprocess ...) - if (input_data != 0) { - return false; - } - - if (communication & Stdin) { - input_data = buffer; - input_sent = 0; - input_total = buflen; - innot->setEnabled(true); - if (input_total) { - slotSendData(0); - } - return true; - } else { - return false; - } -} - -void K3Process::suspend() -{ - if (outnot) { - outnot->setEnabled(false); - } -} - -void K3Process::resume() -{ - if (outnot) { - outnot->setEnabled(true); - } -} - -bool K3Process::closeStdin() -{ - if (communication & Stdin) { - communication = communication & ~Stdin; - delete innot; - innot = 0; - if (!(d->usePty & Stdin)) { - close(in[1]); - } - in[1] = -1; - return true; - } else { - return false; - } -} - -bool K3Process::closeStdout() -{ - if (communication & Stdout) { - communication = communication & ~Stdout; - delete outnot; - outnot = 0; - if (!(d->usePty & Stdout)) { - close(out[0]); - } - out[0] = -1; - return true; - } else { - return false; - } -} - -bool K3Process::closeStderr() -{ - if (communication & Stderr) { - communication = communication & ~Stderr; - delete errnot; - errnot = 0; - if (!(d->usePty & Stderr)) { - close(err[0]); - } - err[0] = -1; - return true; - } else { - return false; - } -} - -bool K3Process::closePty() -{ - if (d->pty && d->pty->masterFd() >= 0) { - if (d->addUtmp) { - d->pty->logout(); - } - d->pty->close(); - return true; - } else { - return false; - } -} - -void K3Process::closeAll() -{ - closeStdin(); - closeStdout(); - closeStderr(); - closePty(); -} - -///////////////////////////// -// protected slots // -///////////////////////////// - - - -void K3Process::slotChildOutput(int fdno) -{ - if (!childOutput(fdno)) { - closeStdout(); - } -} - - -void K3Process::slotChildError(int fdno) -{ - if (!childError(fdno)) { - closeStderr(); - } -} - - -void K3Process::slotSendData(int) -{ - if (input_sent == input_total) { - innot->setEnabled(false); - input_data = 0; - emit wroteStdin(this); - } else { - int result = ::write(in[1], input_data+input_sent, input_total-input_sent); - if (result >= 0) { - input_sent += result; - } else if ((errno != EAGAIN) && (errno != EINTR)) { - qDebug() << "Error writing to stdin of child process" << endl; - closeStdin(); - } - } -} - -void K3Process::setUseShell(bool useShell, const char * shell) -{ - d->useShell = useShell; - if (shell && *shell) { - d->shell = shell; - } else -// #ifdef NON_FREE // ... as they ship non-POSIX /bin/sh -#if !defined(__linux__) && !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && !defined(__GNU__) && !defined(__DragonFly__) - // Solaris POSIX ... - if (!access( "/usr/xpg4/bin/sh", X_OK )) { - d->shell = "/usr/xpg4/bin/sh"; - } else - // ... which links here anyway - if (!access( "/bin/ksh", X_OK )) { - d->shell = "/bin/ksh"; - } else - // dunno, maybe superfluous? - if (!access( "/usr/ucb/sh", X_OK )) { - d->shell = "/usr/ucb/sh"; - } else -#endif - d->shell = "/bin/sh"; -} - -void K3Process::setUsePty(Communication usePty, bool addUtmp) -{ - d->usePty = usePty; - d->addUtmp = addUtmp; - if (usePty) { - if (!d->pty) { - d->pty = new KPty; - } - } else { - delete d->pty; - d->pty = 0; - } -} - -KPty * K3Process::pty() const -{ - return d->pty; -} - -QString K3Process::quote(const QString & arg) -{ - QChar q('\''); - return QString(arg).replace(q, "'\\''").prepend(q).append(q); -} - - -////////////////////////////// -// private member functions // -////////////////////////////// - - -void K3Process::processHasExited(int state) -{ - // only successfully run NotifyOnExit processes ever get here - - status = state; - runs = false; // do this before commClose, so it knows we're dead - - commClose(); // cleanup communication sockets - - if (run_mode != DontCare) { - emit processExited(this); - } -} - - - -int K3Process::childOutput(int fdno) -{ - if (communication & NoRead) { - int len = -1; - emit receivedStdout(fdno, len); - errno = 0; // Make sure errno doesn't read "EAGAIN" - return len; - } else { - char buffer[1025]; - int len; - - len = ::read(fdno, buffer, 1024); - - if (len > 0) { - buffer[len] = 0; // Just in case. - emit receivedStdout(this, buffer, len); - } - return len; - } -} - -int K3Process::childError(int fdno) -{ - char buffer[1025]; - int len; - - len = ::read(fdno, buffer, 1024); - - if (len > 0) { - buffer[len] = 0; // Just in case. - emit receivedStderr(this, buffer, len); - } - return len; -} - - -int K3Process::setupCommunication(Communication comm) -{ - // PTY stuff // - if (d->usePty) { - // cannot communicate on both stderr and stdout if they are both on the pty - if (!(~(comm & d->usePty) & (Stdout | Stderr))) { - qWarning() << "Invalid usePty/communication combination (" << d->usePty << "/" << comm << ")" << endl; - return 0; - } - if (!d->pty->open()) { - return 0; - } - - int rcomm = comm & d->usePty; - int mfd = d->pty->masterFd(); - if (rcomm & Stdin) { - in[1] = mfd; - } - if (rcomm & Stdout) { - out[0] = mfd; - } - if (rcomm & Stderr) { - err[0] = mfd; - } - } - - communication = comm; - - comm = comm & ~d->usePty; - if (comm & Stdin) { - if (socketpair(AF_UNIX, SOCK_STREAM, 0, in)) { - goto fail0; - } - fcntl(in[0], F_SETFD, FD_CLOEXEC); - fcntl(in[1], F_SETFD, FD_CLOEXEC); - } - if (comm & Stdout) { - if (socketpair(AF_UNIX, SOCK_STREAM, 0, out)) { - goto fail1; - } - fcntl(out[0], F_SETFD, FD_CLOEXEC); - fcntl(out[1], F_SETFD, FD_CLOEXEC); - } - if (comm & Stderr) { - if (socketpair(AF_UNIX, SOCK_STREAM, 0, err)) { - goto fail2; - } - fcntl(err[0], F_SETFD, FD_CLOEXEC); - fcntl(err[1], F_SETFD, FD_CLOEXEC); - } - return 1; // Ok -fail2: - if (comm & Stdout) { - close(out[0]); - close(out[1]); - out[0] = out[1] = -1; - } -fail1: - if (comm & Stdin) { - close(in[0]); - close(in[1]); - in[0] = in[1] = -1; - } -fail0: - communication = NoCommunication; - return 0; // Error -} - - - -int K3Process::commSetupDoneP() -{ - int rcomm = communication & ~d->usePty; - if (rcomm & Stdin) { - close(in[0]); - } - if (rcomm & Stdout) { - close(out[1]); - } - if (rcomm & Stderr) { - close(err[1]); - } - in[0] = out[1] = err[1] = -1; - - // Don't create socket notifiers if no interactive comm is to be expected - if (run_mode != NotifyOnExit && run_mode != OwnGroup) { - return 1; - } - - if (communication & Stdin) { - fcntl(in[1], F_SETFL, O_NONBLOCK | fcntl(in[1], F_GETFL)); - innot = new QSocketNotifier(in[1], QSocketNotifier::Write, this); - Q_CHECK_PTR(innot); - innot->setEnabled(false); // will be enabled when data has to be sent - QObject::connect(innot, SIGNAL(activated(int)), - this, SLOT(slotSendData(int))); - } - - if (communication & Stdout) { - outnot = new QSocketNotifier(out[0], QSocketNotifier::Read, this); - Q_CHECK_PTR(outnot); - QObject::connect(outnot, SIGNAL(activated(int)), - this, SLOT(slotChildOutput(int))); - if (communication & NoRead) { - suspend(); - } - } - - if (communication & Stderr) { - errnot = new QSocketNotifier(err[0], QSocketNotifier::Read, this ); - Q_CHECK_PTR(errnot); - QObject::connect(errnot, SIGNAL(activated(int)), - this, SLOT(slotChildError(int))); - } - - return 1; -} - - - -int K3Process::commSetupDoneC() -{ - int ok = 1; - if (d->usePty & Stdin) { - if (dup2(d->pty->slaveFd(), STDIN_FILENO) < 0) { - ok = 0; - } - } else if (communication & Stdin) { - if (dup2(in[0], STDIN_FILENO) < 0) { - ok = 0; - } - } else { - int null_fd = open( "/dev/null", O_RDONLY ); - if (dup2( null_fd, STDIN_FILENO ) < 0) { - ok = 0; - } - close( null_fd ); - } - struct linger so; - memset(&so, 0, sizeof(so)); - if (d->usePty & Stdout) { - if (dup2(d->pty->slaveFd(), STDOUT_FILENO) < 0) { - ok = 0; - } - } else if (communication & Stdout) { - if (dup2(out[1], STDOUT_FILENO) < 0 || - setsockopt(out[1], SOL_SOCKET, SO_LINGER, (char *)&so, sizeof(so))) { - ok = 0; - } - if (communication & MergedStderr) { - if (dup2(out[1], STDERR_FILENO) < 0) { - ok = 0; - } - } - } - if (d->usePty & Stderr) { - if (dup2(d->pty->slaveFd(), STDERR_FILENO) < 0) { - ok = 0; - } - } else if (communication & Stderr) { - if (dup2(err[1], STDERR_FILENO) < 0 || - setsockopt(err[1], SOL_SOCKET, SO_LINGER, (char *)&so, sizeof(so))) { - ok = 0; - } - } - - // don't even think about closing all open fds here or anywhere else - - // PTY stuff // - if (d->usePty) { - d->pty->setCTty(); - if (d->addUtmp) { - d->pty->login(getenv("USER"), getenv("DISPLAY")); - } - } - - return ok; -} - - - -void K3Process::commClose() -{ - closeStdin(); - - if (pid_) { // detached, failed, and killed processes have no output. basta. :) - // If both channels are being read we need to make sure that one socket - // buffer doesn't fill up whilst we are waiting for data on the other - // (causing a deadlock). Hence we need to use select. - - int notfd = K3ProcessController::instance()->notifierFd(); - - while ((communication & (Stdout | Stderr)) || runs) { - fd_set rfds; - FD_ZERO(&rfds); - struct timeval timeout, *p_timeout; - - int max_fd = 0; - if (communication & Stdout) { - FD_SET(out[0], &rfds); - max_fd = out[0]; - } - if (communication & Stderr) { - FD_SET(err[0], &rfds); - if (err[0] > max_fd) { - max_fd = err[0]; - } - } - if (runs) { - FD_SET(notfd, &rfds); - if (notfd > max_fd) { - max_fd = notfd; - } - // If the process is still running we block until we - // receive data or the process exits. - p_timeout = 0; // no timeout - } else { - // If the process has already exited, we only check - // the available data, we don't wait for more. - timeout.tv_sec = timeout.tv_usec = 0; // timeout immediately - p_timeout = &timeout; - } - - int fds_ready = select(max_fd+1, &rfds, 0, 0, p_timeout); - if (fds_ready < 0) { - if (errno == EINTR) { - continue; - } - break; - } else if (!fds_ready) { - break; - } - - if ((communication & Stdout) && FD_ISSET(out[0], &rfds)) { - slotChildOutput(out[0]); - } - - if ((communication & Stderr) && FD_ISSET(err[0], &rfds)) { - slotChildError(err[0]); - } - - if (runs && FD_ISSET(notfd, &rfds)) { - runs = false; // hack: signal potential exit - return; // don't close anything, we will be called again - } - } - } - - closeStdout(); - closeStderr(); - - closePty(); -} - - - -/////////////////////////// -// CC: Class K3ShellProcess -/////////////////////////// - -K3ShellProcess::K3ShellProcess(const char * shellname): - K3Process(), d(0) -{ - setUseShell( true, shellname ? shellname : getenv("SHELL") ); -} - -K3ShellProcess::~K3ShellProcess() -{ -} - -QString K3ShellProcess::quote(const QString & arg) -{ - return K3Process::quote(arg); -} - -bool K3ShellProcess::start(RunMode runmode, Communication comm) -{ - return K3Process::start(runmode, comm); -} - - -//#include "moc_k3process.cpp" diff --git a/lib/k3process.h b/lib/k3process.h deleted file mode 100644 index 80ae181..0000000 --- a/lib/k3process.h +++ /dev/null @@ -1,891 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 1997 Christian Czezakte (e9025461@student.tuwien.ac.at) - - Rewritten for QT4 by e_k , Copyright (C)2008 - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef K3PROCESS_H -#define K3PROCESS_H - -#include - -#include // for pid_t -#include -#include -#include - -class QSocketNotifier; -class K3ProcessPrivate; -class KPty; - -/** - * @obsolete Use KProcess and KPtyProcess instead. - * - * Child process invocation, monitoring and control. - * This class works only in the application's main thread. - * - * General usage and features:\n - * - * This class allows a KDE application to start child processes without having - * to worry about UN*X signal handling issues and zombie process reaping. - * - * @see K3ProcIO - * - * Basically, this class distinguishes three different ways of running - * child processes: - * - * @li DontCare -- The child process is invoked and both the child - * process and the parent process continue concurrently. - * - * The process is started in an own session (see setsid(2)). - * - * @li NotifyOnExit -- The child process is invoked and both the - * child and the parent process run concurrently. - * - * When the child process exits, the K3Process instance - * corresponding to it emits the Qt signal processExited(). - * Since this signal is @em not emitted from within a UN*X - * signal handler, arbitrary function calls can be made. - * - * Be aware: When the K3Process object gets destructed, the child - * process will be killed if it is still running! - * This means in particular, that it usually makes no sense to use - * a K3Process on the stack with NotifyOnExit. - * - * @li OwnGroup -- like NotifyOnExit, but the child process is started - * in an own process group (and an own session, FWIW). The behavior of - * kill() changes to killing the whole process group - this makes - * this mode useful for implementing primitive job management. It can be - * used to work around broken wrapper scripts that don't propagate signals - * to the "real" program. However, use this with care, as you disturb the - * shell's job management if your program is started from the command line. - * - * @li Block -- The child process starts and the parent process - * is suspended until the child process exits. (@em Really not recommended - * for programs with a GUI.) - * In this mode the parent can read the child's output, but can't send it any - * input. - * - * K3Process also provides several functions for determining the exit status - * and the pid of the child process it represents. - * - * Furthermore it is possible to supply command-line arguments to the process - * in a clean fashion (no null-terminated stringlists and such...) - * - * A small usage example: - * \code - * K3Process *proc = new K3Process; - * - * *proc << "my_executable"; - * *proc << "These" << "are" << "the" << "command" << "line" << "args"; - * QApplication::connect(proc, SIGNAL(processExited(K3Process *)), - * pointer_to_my_object, SLOT(my_objects_slot(K3Process *))); - * proc->start(); - * \endcode - * - * This will start "my_executable" with the commandline arguments "These"... - * - * When the child process exits, the slot will be invoked. - * - * Communication with the child process:\n - * - * K3Process supports communication with the child process through - * stdin/stdout/stderr. - * - * The following functions are provided for getting data from the child - * process or sending data to the child's stdin (For more information, - * have a look at the documentation of each function): - * - * @li writeStdin() - * -- Transmit data to the child process' stdin. When all data was sent, the - * signal wroteStdin() is emitted. - * - * @li When data arrives at stdout or stderr, the signal receivedStdout() - * resp. receivedStderr() is emitted. - * - * @li You can shut down individual communication channels with - * closeStdin(), closeStdout(), and closeStderr(), resp. - * - * @author Christian Czezatke e9025461@student.tuwien.ac.at - * - **/ -class K3Process : public QObject { - Q_OBJECT - -public: - - /** - * Modes in which the communication channels can be opened. - * - * If communication for more than one channel is required, - * the values should be or'ed together, for example to get - * communication with stdout as well as with stdin, you would - * specify @p Stdin | @p Stdout - * - */ - enum CommunicationFlag { - NoCommunication = 0, /**< No communication with the process. */ - Stdin = 1, /**< Connect to write to the process with writeStdin(). */ - Stdout = 2, /**< Connect to read from the process' output. */ - Stderr = 4, /**< Connect to read from the process' stderr. */ - AllOutput = 6, /**< Connects to all output channels. */ - All = 7, /**< Connects to all channels. */ - NoRead = 8, /**< If specified with Stdout, no data is actually read from stdout, - * only the signal receivedStdout(int fd, int &len) is emitted. */ - CTtyOnly = NoRead, /**< Tells setUsePty() to create a PTY for the process - * and make it the process' controlling TTY, but does not - * redirect any I/O channel to the PTY. */ - MergedStderr = 16 /**< If specified with Stdout, the process' stderr will be - * redirected onto the same file handle as its stdout, i.e., - * all error output will be signalled with receivedStdout(). - * Don't specify Stderr if you specify MergedStderr. */ - }; - - Q_DECLARE_FLAGS(Communication, CommunicationFlag) - - /** - * Run-modes for a child process. - */ - enum RunMode { - /** - * The application does not receive notifications from the subprocess when - * it is finished or aborted. - */ - DontCare, - /** - * The application is notified when the subprocess dies. - */ - NotifyOnExit, - /** - * The application is suspended until the started process is finished. - */ - Block, - /** - * Same as NotifyOnExit, but the process is run in an own session, - * just like with DontCare. - */ - OwnGroup - }; - - /** - * Constructor - */ - explicit K3Process( QObject * parent=0L ); - - /** - *Destructor: - * - * If the process is running when the destructor for this class - * is called, the child process is killed with a SIGKILL, but - * only if the run mode is not of type @p DontCare. - * Processes started as @p DontCare keep running anyway. - */ - virtual ~K3Process(); - - /** - * Sets the executable and the command line argument list for this process. - * - * For example, doing an "ls -l /usr/local/bin" can be achieved by: - * \code - * K3Process p; - * ... - * p << "ls" << "-l" << "/usr/local/bin" - * \endcode - * - * @param arg the argument to add - * @return a reference to this K3Process - **/ - K3Process & operator<<(const QString & arg); - /** - * Similar to previous method, takes a char *, supposed to be in locale 8 bit already. - */ - K3Process & operator<<(const char * arg); - /** - * Similar to previous method, takes a QByteArray, supposed to be in locale 8 bit already. - * @param arg the argument to add - * @return a reference to this K3Process - */ - K3Process & operator<<(const QByteArray & arg); - - /** - * Sets the executable and the command line argument list for this process, - * in a single method call, or add a list of arguments. - * @param args the arguments to add - * @return a reference to this K3Process - **/ - K3Process & operator<<(const QStringList & args); - - /** - * Clear a command line argument list that has been set by using - * operator<<. - */ - void clearArguments(); - - /** - * Starts the process. - * For a detailed description of the - * various run modes and communication semantics, have a look at the - * general description of the K3Process class. Note that if you use - * setUsePty( Stdout | Stderr, \ ), you cannot use Stdout | Stderr - * here - instead, use Stdout only to receive the mixed output. - * - * The following problems could cause this function to - * return false: - * - * @li The process is already running. - * @li The command line argument list is empty. - * @li The the @p comm parameter is incompatible with the selected pty usage. - * @li The starting of the process failed (could not fork). - * @li The executable was not found. - * - * @param runmode The Run-mode for the process. - * @param comm Specifies which communication channels should be - * established to the child process (stdin/stdout/stderr). By default, - * no communication takes place and the respective communication - * signals will never get emitted. - * - * @return true on success, false on error - * (see above for error conditions) - **/ - virtual bool start(RunMode runmode = NotifyOnExit, - Communication comm = NoCommunication); - - /** - * Stop the process (by sending it a signal). - * - * @param signo The signal to send. The default is SIGTERM. - * @return true if the signal was delivered successfully. - */ - virtual bool kill(int signo = SIGTERM); - - /** - * Checks whether the process is running. - * @return true if the process is (still) considered to be running - */ - bool isRunning() const; - - /** Returns the process id of the process. - * - * If it is called after - * the process has exited, it returns the process id of the last - * child process that was created by this instance of K3Process. - * - * Calling it before any child process has been started by this - * K3Process instance causes pid() to return 0. - * @return the pid of the process or 0 if no process has been started yet. - **/ - pid_t pid() const; - - /** - * Suspend processing of data from stdout of the child process. - */ - void suspend(); - - /** - * Resume processing of data from stdout of the child process. - */ - void resume(); - - /** - * Suspend execution of the current thread until the child process dies - * or the timeout hits. This function is not recommended for programs - * with a GUI. - * @param timeout timeout in seconds. -1 means wait indefinitely. - * @return true if the process exited, false if the timeout hit. - */ - bool wait(int timeout = -1); - - /** - * Checks whether the process exited cleanly. - * - * @return true if the process has already finished and has exited - * "voluntarily", ie: it has not been killed by a signal. - */ - bool normalExit() const; - - /** - * Checks whether the process was killed by a signal. - * - * @return true if the process has already finished and has not exited - * "voluntarily", ie: it has been killed by a signal. - */ - bool signalled() const; - - /** - * Checks whether a killed process dumped core. - * - * @return true if signalled() returns true and the process - * dumped core. Note that on systems that don't define the - * WCOREDUMP macro, the return value is always false. - */ - bool coreDumped() const; - - /** - * Returns the exit status of the process. - * - * @return the exit status of the process. Note that this value - * is not valid if normalExit() returns false. - */ - int exitStatus() const; - - /** - * Returns the signal the process was killed by. - * - * @return the signal number that caused the process to exit. - * Note that this value is not valid if signalled() returns false. - */ - int exitSignal() const; - - /** - * Transmit data to the child process' stdin. - * - * This function may return false in the following cases: - * - * @li The process is not currently running. - * This implies that you cannot use this function in Block mode. - * - * @li Communication to stdin has not been requested in the start() call. - * - * @li Transmission of data to the child process by a previous call to - * writeStdin() is still in progress. - * - * Please note that the data is sent to the client asynchronously, - * so when this function returns, the data might not have been - * processed by the child process. - * That means that you must not free @p buffer or call writeStdin() - * again until either a wroteStdin() signal indicates that the - * data has been sent or a processExited() signal shows that - * the child process is no longer alive. - * - * If all the data has been sent to the client, the signal - * wroteStdin() will be emitted. - * - * This function does not work when the process is start()ed in Block mode. - * - * @param buffer the buffer to write - * @param buflen the length of the buffer - * @return false if an error has occurred - **/ - bool writeStdin(const char * buffer, int buflen); - - /** - * Shuts down the Stdin communication link. If no pty is used, this - * causes "EOF" to be indicated on the child's stdin file descriptor. - * - * @return false if no Stdin communication link exists (any more). - */ - bool closeStdin(); - - /** - * Shuts down the Stdout communication link. If no pty is used, any further - * attempts by the child to write to its stdout file descriptor will cause - * it to receive a SIGPIPE. - * - * @return false if no Stdout communication link exists (any more). - */ - bool closeStdout(); - - /** - * Shuts down the Stderr communication link. If no pty is used, any further - * attempts by the child to write to its stderr file descriptor will cause - * it to receive a SIGPIPE. - * - * @return false if no Stderr communication link exists (any more). - */ - bool closeStderr(); - - /** - * Deletes the optional utmp entry and closes the pty. - * - * Make sure to shut down any communication links that are using the pty - * before calling this function. - * - * @return false if the pty is not open (any more). - */ - bool closePty(); - - /** - * @brief Close stdin, stdout, stderr and the pty - * - * This is the same that calling all close* functions in a row: - * @see closeStdin, @see closeStdout, @see closeStderr and @see closePty - */ - void closeAll(); - - /** - * Lets you see what your arguments are for debugging. - * @return the list of arguments - */ - const QList &args() { /* const */ - return arguments; - } - - /** - * Controls whether the started process should drop any - * setuid/setgid privileges or whether it should keep them. - * Note that this function is mostly a dummy, as the KDE libraries - * currently refuse to run with setuid/setgid privileges. - * - * The default is false: drop privileges - * @param keepPrivileges true to keep the privileges - */ - void setRunPrivileged(bool keepPrivileges); - - /** - * Returns whether the started process will drop any - * setuid/setgid privileges or whether it will keep them. - * @return true if the process runs privileged - */ - bool runPrivileged() const; - - /** - * Adds the variable @p name to the process' environment. - * This function must be called before starting the process. - * @param name the name of the environment variable - * @param value the new value for the environment variable - */ - void setEnvironment(const QString & name, const QString & value); - - /** - * Changes the current working directory (CWD) of the process - * to be started. - * This function must be called before starting the process. - * @param dir the new directory - */ - void setWorkingDirectory(const QString & dir); - - /** - * Specify whether to start the command via a shell or directly. - * The default is to start the command directly. - * If @p useShell is true @p shell will be used as shell, or - * if shell is empty, /bin/sh will be used. - * - * When using a shell, the caller should make sure that all filenames etc. - * are properly quoted when passed as argument. - * @see quote() - * @param useShell true if the command should be started via a shell - * @param shell the path to the shell that will execute the process, or - * 0 to use /bin/sh. Use getenv("SHELL") to use the user's - * default shell, but note that doing so is usually a bad idea - * for shell compatibility reasons. - */ - void setUseShell(bool useShell, const char * shell = 0); - - /** - * This function can be used to quote an argument string such that - * the shell processes it properly. This is e. g. necessary for - * user-provided file names which may contain spaces or quotes. - * It also prevents expansion of wild cards and environment variables. - * @param arg the argument to quote - * @return the quoted argument - */ - static QString quote(const QString & arg); - - /** - * Detaches K3Process from child process. All communication is closed. - * No exit notification is emitted any more for the child process. - * Deleting the K3Process will no longer kill the child process. - * Note that the current process remains the parent process of the - * child process. - */ - void detach(); - - /** - * Specify whether to create a pty (pseudo-terminal) for running the - * command. - * This function should be called before starting the process. - * - * @param comm for which stdio handles to use a pty. Note that it is not - * allowed to specify Stdout and Stderr at the same time both here and to - * start (there is only one pty, so they cannot be distinguished). - * @param addUtmp true if a utmp entry should be created for the pty - */ - void setUsePty(Communication comm, bool addUtmp); - - /** - * Obtains the pty object used by this process. The return value is - * valid only after setUsePty() was used with a non-zero argument. - * The pty is open only while the process is running. - * @return a pointer to the pty object - */ - KPty * pty() const; - - /** - * More or less intuitive constants for use with setPriority(). - */ - enum { PrioLowest = 20, PrioLow = 10, PrioLower = 5, PrioNormal = 0, - PrioHigher = -5, PrioHigh = -10, PrioHighest = -19 - }; - - /** - * Sets the scheduling priority of the process. - * @param prio the new priority in the range -20 (high) to 19 (low). - * @return false on error; see setpriority(2) for possible reasons. - */ - bool setPriority(int prio); - -Q_SIGNALS: - /** - * Emitted after the process has terminated when - * the process was run in the @p NotifyOnExit (==default option to - * start() ) or the Block mode. - * @param proc a pointer to the process that has exited - **/ - void processExited(K3Process * proc); - - - /** - * Emitted, when output from the child process has - * been received on stdout. - * - * To actually get this signal, the Stdout communication link - * has to be turned on in start(). - * - * @param proc a pointer to the process that has received the output - * @param buffer The data received. - * @param buflen The number of bytes that are available. - * - * You should copy the information contained in @p buffer to your private - * data structures before returning from the slot. - * Example: - * \code - * QString myBuf = QLatin1String(buffer, buflen); - * \endcode - **/ - void receivedStdout(K3Process * proc, char * buffer, int buflen); - - /** - * Emitted when output from the child process has - * been received on stdout. - * - * To actually get this signal, the Stdout communication link - * has to be turned on in start() and the - * NoRead flag must have been passed. - * - * You will need to explicitly call resume() after your call to start() - * to begin processing data from the child process' stdout. This is - * to ensure that this signal is not emitted when no one is connected - * to it, otherwise this signal will not be emitted. - * - * The data still has to be read from file descriptor @p fd. - * @param fd the file descriptor that provides the data - * @param len the number of bytes that have been read from @p fd must - * be written here - **/ - void receivedStdout(int fd, int & len); // KDE4: change, broken API - - - /** - * Emitted, when output from the child process has - * been received on stderr. - * - * To actually get this signal, the Stderr communication link - * has to be turned on in start(). - * - * You should copy the information contained in @p buffer to your private - * data structures before returning from the slot. - * - * @param proc a pointer to the process that has received the data - * @param buffer The data received. - * @param buflen The number of bytes that are available. - **/ - void receivedStderr(K3Process * proc, char * buffer, int buflen); - - /** - * Emitted after all the data that has been - * specified by a prior call to writeStdin() has actually been - * written to the child process. - * @param proc a pointer to the process - **/ - void wroteStdin(K3Process * proc); - - -protected Q_SLOTS: - - /** - * This slot gets activated when data from the child's stdout arrives. - * It usually calls childOutput(). - * @param fdno the file descriptor for the output - */ - void slotChildOutput(int fdno); - - /** - * This slot gets activated when data from the child's stderr arrives. - * It usually calls childError(). - * @param fdno the file descriptor for the output - */ - void slotChildError(int fdno); - - /** - * Called when another bulk of data can be sent to the child's - * stdin. If there is no more data to be sent to stdin currently - * available, this function must disable the QSocketNotifier innot. - * @param dummy ignore this argument - */ - void slotSendData(int dummy); // KDE 4: remove dummy - -protected: - - /** - * Sets up the environment according to the data passed via - * setEnvironment() - */ - void setupEnvironment(); - - /** - * The list of the process' command line arguments. The first entry - * in this list is the executable itself. - */ - QList arguments; - /** - * How to run the process (Block, NotifyOnExit, DontCare). You should - * not modify this data member directly from derived classes. - */ - RunMode run_mode; - /** - * true if the process is currently running. You should not - * modify this data member directly from derived classes. Please use - * isRunning() for reading the value of this data member since it - * will probably be made private in later versions of K3Process. - */ - bool runs; - - /** - * The PID of the currently running process. - * You should not modify this data member in derived classes. - * Please use pid() instead of directly accessing this - * member since it will probably be made private in - * later versions of K3Process. - */ - pid_t pid_; - - /** - * The process' exit status as returned by waitpid(). You should not - * modify the value of this data member from derived classes. You should - * rather use exitStatus() than accessing this data member directly - * since it will probably be made private in further versions of - * K3Process. - */ - int status; - - - /** - * If false, the child process' effective uid & gid will be reset to the - * real values. - * @see setRunPrivileged() - */ - bool keepPrivs; - - /** - * This function is called from start() right before a fork() takes - * place. According to the @p comm parameter this function has to initialize - * the in, out and err data members of K3Process. - * - * This function should return 1 if setting the needed communication channels - * was successful. - * - * The default implementation is to create UNIX STREAM sockets for the - * communication, but you could reimplement this function to establish a - * TCP/IP communication for network communication, for example. - */ - virtual int setupCommunication(Communication comm); - - /** - * Called right after a (successful) fork() on the parent side. This function - * will usually do some communications cleanup, like closing in[0], - * out[1] and out[1]. - * - * Furthermore, it must also create the QSocketNotifiers innot, - * outnot and errnot and connect their Qt signals to the respective - * K3Process slots. - * - * For a more detailed explanation, it is best to have a look at the default - * implementation in kprocess.cpp. - */ - virtual int commSetupDoneP(); - - /** - * Called right after a (successful) fork(), but before an exec() on the child - * process' side. It usually duplicates the in[0], out[1] and - * err[1] file handles to the respective standard I/O handles. - */ - virtual int commSetupDoneC(); - - - /** - * Immediately called after a successfully started process in NotifyOnExit - * mode has exited. This function normally calls commClose() - * and emits the processExited() signal. - * @param state the exit code of the process as returned by waitpid() - */ - virtual void processHasExited(int state); - - /** - * Cleans up the communication links to the child after it has exited. - * This function should act upon the values of pid() and runs. - * See the kprocess.cpp source for details. - * @li If pid() returns zero, the communication links should be closed - * only. - * @li if pid() returns non-zero and runs is false, all data - * immediately available from the communication links should be processed - * before closing them. - * @li if pid() returns non-zero and runs is true, the communication - * links should be monitored for data until the file handle returned by - * K3ProcessController::theKProcessController->notifierFd() becomes ready - * for reading - when it triggers, runs should be reset to false, and - * the function should be immediately left without closing anything. - * - * The previous semantics of this function are forward-compatible, but should - * be avoided, as they are prone to race conditions and can cause K3Process - * (and thus the whole program) to lock up under certain circumstances. At the - * end the function closes the communication links in any case. Additionally - * @li if runs is true, the communication links are monitored for data - * until all of them have returned EOF. Note that if any system function is - * interrupted (errno == EINTR) the polling loop should be aborted. - * @li if runs is false, all data immediately available from the - * communication links is processed. - */ - virtual void commClose(); - - /* KDE 4 - commClose will be changed to perform cleanup only in all cases * - * If @p notfd is -1, all data immediately available from the - * communication links should be processed. - * If @p notfd is not -1, the communication links should be monitored - * for data until the file handle @p notfd becomes ready for reading. - */ -// virtual void commDrain(int notfd); - - /** - * Specify the actual executable that should be started (first argument to execve) - * Normally the the first argument is the executable but you can - * override that with this function. - */ - void setBinaryExecutable(const char * filename); - - /** - * The socket descriptors for stdout. - */ - int out[2]; - /** - * The socket descriptors for stdin. - */ - int in[2]; - /** - * The socket descriptors for stderr. - */ - int err[2]; - - /** - * The socket notifier for in[1]. - */ - QSocketNotifier * innot; - /** - * The socket notifier for out[0]. - */ - QSocketNotifier * outnot; - /** - * The socket notifier for err[0]. - */ - QSocketNotifier * errnot; - - /** - * Lists the communication links that are activated for the child - * process. Should not be modified from derived classes. - */ - Communication communication; - - /** - * Called by slotChildOutput() this function copies data arriving from - * the child process' stdout to the respective buffer and emits the signal - * receivedStdout(). - */ - int childOutput(int fdno); - - /** - * Called by slotChildError() this function copies data arriving from - * the child process' stderr to the respective buffer and emits the signal - * receivedStderr(). - */ - int childError(int fdno); - - /** - * The buffer holding the data that has to be sent to the child - */ - const char * input_data; - /** - * The number of bytes already transmitted - */ - int input_sent; - /** - * The total length of input_data - */ - int input_total; - - /** - * K3ProcessController is a friend of K3Process because it has to have - * access to various data members. - */ - friend class K3ProcessController; - -private: - K3ProcessPrivate * const d; -}; - -Q_DECLARE_OPERATORS_FOR_FLAGS(K3Process::Communication) - -class K3ShellProcessPrivate; - -/** -* @obsolete -* -* Use K3Process and K3Process::setUseShell(true) instead. -* -* @short A class derived from K3Process to start child -* processes through a shell. -* @author Christian Czezatke -*/ -class K3ShellProcess : public K3Process { - Q_OBJECT - -public: - - /** - * Constructor - * - * If no shellname is specified, the user's default shell is used. - */ - explicit K3ShellProcess(const char * shellname=0); - - /** - * Destructor. - */ - ~K3ShellProcess(); - - virtual bool start(RunMode runmode = NotifyOnExit, - Communication comm = NoCommunication); - - static QString quote(const QString & arg); - -private: - K3ShellProcessPrivate * const d; -}; - - - -#endif - diff --git a/lib/k3processcontroller.cpp b/lib/k3processcontroller.cpp deleted file mode 100644 index df61a52..0000000 --- a/lib/k3processcontroller.cpp +++ /dev/null @@ -1,338 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 1997 Christian Czezakte (e9025461@student.tuwien.ac.at) - - Rewritten for QT4 by e_k , Copyright (C)2008 - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "k3processcontroller.h" -#include "k3process.h" - -//#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -class K3ProcessController::Private { -public: - Private() - : needcheck( false ), - notifier( 0 ) { - } - - ~Private() { - delete notifier; - } - - int fd[2]; - bool needcheck; - QSocketNotifier * notifier; - QList kProcessList; - QList unixProcessList; - static struct sigaction oldChildHandlerData; - static bool handlerSet; - static int refCount; - static K3ProcessController * instance; -}; - -K3ProcessController * K3ProcessController::Private::instance = 0; -int K3ProcessController::Private::refCount = 0; - -void K3ProcessController::ref() -{ - if ( !Private::refCount ) { - Private::instance = new K3ProcessController; - setupHandlers(); - } - Private::refCount++; -} - -void K3ProcessController::deref() -{ - Private::refCount--; - if ( !Private::refCount ) { - resetHandlers(); - delete Private::instance; - Private::instance = 0; - } -} - -K3ProcessController * K3ProcessController::instance() -{ - /* - * there were no safety guards in previous revisions, is that ok? - if ( !Private::instance ) { - ref(); - } - */ - - return Private::instance; -} - -K3ProcessController::K3ProcessController() - : d( new Private ) -{ - if ( pipe( d->fd ) ) { - perror( "pipe" ); - abort(); - } - - fcntl( d->fd[0], F_SETFL, O_NONBLOCK ); // in case slotDoHousekeeping is called without polling first - fcntl( d->fd[1], F_SETFL, O_NONBLOCK ); // in case it fills up - fcntl( d->fd[0], F_SETFD, FD_CLOEXEC ); - fcntl( d->fd[1], F_SETFD, FD_CLOEXEC ); - - d->notifier = new QSocketNotifier( d->fd[0], QSocketNotifier::Read ); - d->notifier->setEnabled( true ); - QObject::connect( d->notifier, SIGNAL(activated(int)), - SLOT(slotDoHousekeeping())); -} - -K3ProcessController::~K3ProcessController() -{ -#ifndef Q_OS_MAC - /* not sure why, but this is causing lockups */ - close( d->fd[0] ); - close( d->fd[1] ); -#else -#warning FIXME: why does close() freeze up destruction? -#endif - - delete d; -} - - -extern "C" { - static void theReaper( int num ) { - K3ProcessController::theSigCHLDHandler( num ); - } -} - -#ifdef Q_OS_UNIX -struct sigaction K3ProcessController::Private::oldChildHandlerData; -#endif -bool K3ProcessController::Private::handlerSet = false; - -void K3ProcessController::setupHandlers() -{ - if ( Private::handlerSet ) { - return; - } - Private::handlerSet = true; - -#ifdef Q_OS_UNIX - struct sigaction act; - sigemptyset( &act.sa_mask ); - - act.sa_handler = SIG_IGN; - act.sa_flags = 0; - sigaction( SIGPIPE, &act, 0L ); - - act.sa_handler = theReaper; - act.sa_flags = SA_NOCLDSTOP; - // CC: take care of SunOS which automatically restarts interrupted system - // calls (and thus does not have SA_RESTART) -#ifdef SA_RESTART - act.sa_flags |= SA_RESTART; -#endif - sigaction( SIGCHLD, &act, &Private::oldChildHandlerData ); - - sigaddset( &act.sa_mask, SIGCHLD ); - // Make sure we don't block this signal. gdb tends to do that :-( - sigprocmask( SIG_UNBLOCK, &act.sa_mask, 0 ); -#else - //TODO: win32 -#endif -} - -void K3ProcessController::resetHandlers() -{ - if ( !Private::handlerSet ) { - return; - } - Private::handlerSet = false; - -#ifdef Q_OS_UNIX - sigset_t mask, omask; - sigemptyset( &mask ); - sigaddset( &mask, SIGCHLD ); - sigprocmask( SIG_BLOCK, &mask, &omask ); - - struct sigaction act; - sigaction( SIGCHLD, &Private::oldChildHandlerData, &act ); - if (act.sa_handler != theReaper) { - sigaction( SIGCHLD, &act, 0 ); - Private::handlerSet = true; - } - - sigprocmask( SIG_SETMASK, &omask, 0 ); -#else - //TODO: win32 -#endif - // there should be no problem with SIGPIPE staying SIG_IGN -} - -// the pipe is needed to sync the child reaping with our event processing, -// as otherwise there are race conditions, locking requirements, and things -// generally get harder -void K3ProcessController::theSigCHLDHandler( int arg ) -{ - int saved_errno = errno; - - char dummy = 0; - ssize_t result = ::write( instance()->d->fd[1], &dummy, 1 ); - if (result < 0) { - qDebug() << "Write failed with the error code " << result << endl; - } - -#ifdef Q_OS_UNIX - if ( Private::oldChildHandlerData.sa_handler != SIG_IGN && - Private::oldChildHandlerData.sa_handler != SIG_DFL ) { - Private::oldChildHandlerData.sa_handler( arg ); // call the old handler - } -#else - //TODO: win32 -#endif - - errno = saved_errno; -} - -int K3ProcessController::notifierFd() const -{ - return d->fd[0]; -} - -void K3ProcessController::unscheduleCheck() -{ - char dummy[16]; // somewhat bigger - just in case several have queued up - if ( ::read( d->fd[0], dummy, sizeof(dummy) ) > 0 ) { - d->needcheck = true; - } -} - -void -K3ProcessController::rescheduleCheck() -{ - if ( d->needcheck ) { - d->needcheck = false; - char dummy = 0; - ssize_t result = ::write( d->fd[1], &dummy, 1 ); - if (result < 0) { - qDebug() << "Write failed with the error code " << result << endl; - } - - } -} - -void K3ProcessController::slotDoHousekeeping() -{ - char dummy[16]; // somewhat bigger - just in case several have queued up - ssize_t result = ::read( d->fd[0], dummy, sizeof(dummy) ); - if (result < 0) { - qDebug() << "Write failed with the error code " << result << endl; - } - - int status; -again: - QList::iterator it( d->kProcessList.begin() ); - QList::iterator eit( d->kProcessList.end() ); - while ( it != eit ) { - K3Process * prc = *it; - if ( prc->runs && waitpid( prc->pid_, &status, WNOHANG ) > 0 ) { - prc->processHasExited( status ); - // the callback can nuke the whole process list and even 'this' - if (!instance()) { - return; - } - goto again; - } - ++it; - } - QList::iterator uit( d->unixProcessList.begin() ); - QList::iterator ueit( d->unixProcessList.end() ); - while ( uit != ueit ) { - if ( waitpid( *uit, 0, WNOHANG ) > 0 ) { - uit = d->unixProcessList.erase( uit ); - deref(); // counterpart to addProcess, can invalidate 'this' - } else { - ++uit; - } - } -} - -bool K3ProcessController::waitForProcessExit( int timeout ) -{ -#ifdef Q_OS_UNIX - for (;;) { - struct timeval tv, *tvp; - if (timeout < 0) { - tvp = 0; - } else { - tv.tv_sec = timeout; - tv.tv_usec = 0; - tvp = &tv; - } - - fd_set fds; - FD_ZERO( &fds ); - FD_SET( d->fd[0], &fds ); - - switch ( select( d->fd[0]+1, &fds, 0, 0, tvp ) ) { - case -1: - if ( errno == EINTR ) { - continue; - } - // fall through; should never happen - case 0: - return false; - default: - slotDoHousekeeping(); - return true; - } - } -#else - //TODO: win32 - return false; -#endif -} - -void K3ProcessController::addKProcess( K3Process * p ) -{ - d->kProcessList.append( p ); -} - -void K3ProcessController::removeKProcess( K3Process * p ) -{ - d->kProcessList.removeAll( p ); -} - -void K3ProcessController::addProcess( int pid ) -{ - d->unixProcessList.append( pid ); - ref(); // make sure we stay around when the K3Process goes away -} - -//#include "moc_k3processcontroller.cpp" diff --git a/lib/k3processcontroller.h b/lib/k3processcontroller.h deleted file mode 100644 index f25000b..0000000 --- a/lib/k3processcontroller.h +++ /dev/null @@ -1,136 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 1997 Christian Czezakte (e9025461@student.tuwien.ac.at) - - Rewritten for QT4 by e_k , Copyright (C)2008 - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef K3PROCCTRL_H -#define K3PROCCTRL_H - -#include -#include - - -/** - * @short Used internally by K3Process - * @internal - * @author Christian Czezatke - * - * A class for internal use by K3Process only. -- Exactly one instance - * of this class is created by KApplication. - * - * This class takes care of the actual (UN*X) signal handling. - */ -class K3ProcessController : public QObject { - Q_OBJECT - -public: - /** - * Create an instance if none exists yet. - * Called by KApplication::KApplication() - */ - static void ref(); - - /** - * Destroy the instance if one exists and it is not referenced any more. - * Called by KApplication::~KApplication() - */ - static void deref(); - - /** - * Only a single instance of this class is allowed at a time. - * This method provides access to that instance. - */ - static K3ProcessController * instance(); - - /** - * Automatically called upon SIGCHLD. Never call it directly. - * If your application (or some library it uses) redirects SIGCHLD, - * the new signal handler (and only it) should call the old handler - * returned by sigaction(). - * @internal - */ - static void theSigCHLDHandler(int signal); // KDE4: private - - /** - * Wait for any process to exit and handle their exit without - * starting an event loop. - * This function may cause K3Process to emit any of its signals. - * - * @param timeout the timeout in seconds. -1 means no timeout. - * @return true if a process exited, false - * if no process exited within @p timeout seconds. - */ - bool waitForProcessExit(int timeout); - - /** - * Call this function to defer processing of the data that became available - * on notifierFd(). - */ - void unscheduleCheck(); - - /** - * This function @em must be called at some point after calling - * unscheduleCheck(). - */ - void rescheduleCheck(); - - /* - * Obtain the file descriptor K3ProcessController uses to get notified - * about process exits. select() or poll() on it if you create a custom - * event loop that needs to act upon SIGCHLD. - * @return the file descriptor of the reading end of the notification pipe - */ - int notifierFd() const; - - /** - * @internal - */ - void addKProcess( K3Process * ); - /** - * @internal - */ - void removeKProcess( K3Process * ); - /** - * @internal - */ - void addProcess( int pid ); - -private Q_SLOTS: - void slotDoHousekeeping(); - -private: - friend class I_just_love_gcc; - - static void setupHandlers(); - static void resetHandlers(); - - // Disallow instantiation - K3ProcessController(); - ~K3ProcessController(); - - // Disallow assignment and copy-construction - K3ProcessController( const K3ProcessController & ); - K3ProcessController & operator= ( const K3ProcessController & ); - - class Private; - Private * const d; -}; - -#endif - diff --git a/lib/kb-layouts/macbook.keytab b/lib/kb-layouts/macbook.keytab new file mode 100644 index 0000000..adbc784 --- /dev/null +++ b/lib/kb-layouts/macbook.keytab @@ -0,0 +1,175 @@ +# [README.default.Keytab] Buildin Keyboard Table +# +# To customize your keyboard, copy this file to something +# ending with .keytab and change it to meet you needs. +# Please read the README.KeyTab and the README.keyboard +# in this case. +# +# -------------------------------------------------------------- + +keyboard "Default (XFree 4)" + +# -------------------------------------------------------------- +# +# Note that this particular table is a "risc" version made to +# ease customization without bothering with obsolete details. +# See VT100.keytab for the more hairy stuff. +# +# -------------------------------------------------------------- + +# common keys + +key Escape : "\x1b" + +#key Control : "^" + +key Tab -Shift : "\t" +key Tab +Shift+Ansi : "\E[Z" +key Tab +Shift-Ansi : "\t" +key Backtab +Ansi : "\E[Z" +key Backtab -Ansi : "\t" + +key Return-Shift-NewLine : "\r" +key Return-Shift+NewLine : "\r\n" + +key Return+Shift : "\EOM" + +# Backspace and Delete codes are preserving CTRL-H. + +key Backspace : "\x7f" + +# Arrow keys in VT52 mode +# shift up/down are reserved for scrolling. +# shift left/right are reserved for switching between tabs (this is hardcoded). + + +# Command + C +# on mac - Control=Command, Meta=Ctrl +# do not use Control+C for interrupt signal - it's used for "Copy to clipboard" +#key Control +C : "\x03" +key Meta +C: "\x03" + + +# Arrow keys in ANSI mode with Application - and Normal Cursor Mode) + +key Up -Shift+Ansi-AppCuKeys : "\E[A" +key Down -Shift+Ansi-AppCuKeys : "\E[B" +key Right-Shift+Ansi-AppCuKeys : "\E[C" +key Left -Shift+Ansi-AppCuKeys : "\E[D" + +key Up -Ansi : "\E[1;*A" +key Down -Ansi : "\E[1;*B" +key Right -Ansi : "\E[1;*C" +key Left -Ansi : "\E[1;*D" + +#key Up -Shift-Ansi : "\EA" +#key Down -Shift-Ansi : "\EB" +#key Right-Shift-Ansi : "\EC" +#key Left -Shift-Ansi : "\ED" + +#key Up -Shift-AnyMod+Ansi-AppCuKeys : "\E[A" +#key Down -Shift-AnyMod+Ansi-AppCuKeys : "\E[B" +#key Right -Shift-AnyMod+Ansi-AppCuKeys : "\E[C" +#key Left -Shift-AnyMod+Ansi-AppCuKeys : "\E[D" + +#key Up -Shift-AnyMod+Ansi-AppCuKeys : "\EOA" +#key Down -Shift-AnyMod+Ansi-AppCuKeys : "\EOB" +#key Right -Shift-AnyMod+Ansi-AppCuKeys : "\EOC" +#key Left -Shift-AnyMod+Ansi-AppCuKeys : "\EOD" + +#key Up -Shift-AnyMod+Ansi : "\E[1;*A" +#key Down -Shift-AnyMod+Ansi : "\E[1;*B" +#key Right -Shift-AnyMod+Ansi : "\E[1;*C" +#key Left -Shift-AnyMod+Ansi : "\E[1;*D" + +# other grey PC keys + +key Enter+NewLine : "\r\n" +key Enter-NewLine : "\r" + +key Home -AnyMod -AppCuKeys : "\E[H" +key End -AnyMod -AppCuKeys : "\E[F" +key Home -AnyMod +AppCuKeys : "\EOH" +key End -AnyMod +AppCuKeys : "\EOF" +key Home +AnyMod : "\E[1;*H" +key End +AnyMod : "\E[1;*F" + +key Insert -AnyMod : "\E[2~" +key Delete -AnyMod : "\E[3~" +key Insert +AnyMod : "\E[2;*~" +key Delete +AnyMod : "\E[3;*~" + +key Prior -Shift-AnyMod : "\E[5~" +key Next -Shift-AnyMod : "\E[6~" +key Prior -Shift+AnyMod : "\E[5;*~" +key Next -Shift+AnyMod : "\E[6;*~" + +# Function keys +#key F1 -AnyMod : "\EOP" +#key F2 -AnyMod : "\EOQ" +#key F3 -AnyMod : "\EOR" +#key F4 -AnyMod : "\EOS" +#define ALT_KP_0 "\033Op" +#define ALT_KP_1 "\033Oq" +#define ALT_KP_2 "\033Or" +#define ALT_KP_3 "\033Os" +#define ALT_KP_4 "\033Ot" +#define ALT_KP_5 "\033Ou" +#define ALT_KP_6 "\033Ov" +#define ALT_KP_7 "\033Ow" +#define ALT_KP_8 "\033Ox" +#define ALT_KP_9 "\033Oy" + +key F1 -AnyMod : "\EOP" +key F2 -AnyMod : "\EOQ" +key F3 -AnyMod : "\EOR" +key F4 -AnyMod : "\EOS" +key F5 -AnyMod : "\EOT" +key F6 -AnyMod : "\EOU" +key F7 -AnyMod : "\EOV" +key F8 -AnyMod : "\EOW" +key F9 -AnyMod : "\EOX" +key F10 -AnyMod : "\EOY" + +#key F5 -AnyMod : "\E[15~" +#key F6 -AnyMod : "\E[17~" +#key F7 -AnyMod : "\E[18~" +#key F8 -AnyMod : "\E[19~" +#key F9 -AnyMod : "\E[20~" +#key F10 -AnyMod : "\E[21~" +#key F11 -AnyMod : "\E[23~" +#key F12 -AnyMod : "\E[24~" + +#key F1 +AnyMod : "\EO*P" +#key F2 +AnyMod : "\EO*Q" +#key F3 +AnyMod : "\EO*R" +#key F4 +AnyMod : "\EO*S" +#key F5 +AnyMod : "\E[15;*~" +#key F6 +AnyMod : "\E[17;*~" +#key F7 +AnyMod : "\E[18;*~" +#key F8 +AnyMod : "\E[19;*~" +#key F9 +AnyMod : "\E[20;*~" +#key F10 +AnyMod : "\E[21;*~" +#key F11 +AnyMod : "\E[23;*~" +#key F12 +AnyMod : "\E[24;*~" + +# Work around dead keys + +key Space +Control : "\x00" + +# Some keys are used by konsole to cause operations. +# The scroll* operations refer to the history buffer. + +key Up +Shift-AppScreen : scrollLineUp +key Prior +Shift-AppScreen : scrollPageUp +key Down +Shift-AppScreen : scrollLineDown +key Next +Shift-AppScreen : scrollPageDown + +#key Up +Shift : scrollLineUp +#key Prior +Shift : scrollPageUp +#key Down +Shift : scrollLineDown +#key Next +Shift : scrollPageDown + +key ScrollLock : scrollLock + +# keypad characters are not offered differently by Qt. diff --git a/lib/kprocess.cpp b/lib/kprocess.cpp new file mode 100644 index 0000000..73264a6 --- /dev/null +++ b/lib/kprocess.cpp @@ -0,0 +1,412 @@ +/* + * This file is a part of QTerminal - http://gitorious.org/qterminal + * + * This file was un-linked from KDE and modified + * by Maxim Bourmistrov + * + */ + +/* + This file is part of the KDE libraries + + Copyright (C) 2007 Oswald Buddenhagen + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include "kprocess.h" + +#include + +#ifdef Q_OS_WIN +# include +#else +# include +# include +#endif + +#ifndef Q_OS_WIN +# define STD_OUTPUT_HANDLE 1 +# define STD_ERROR_HANDLE 2 +#endif + +#ifdef _WIN32_WCE +#include +#endif + +void KProcessPrivate::writeAll(const QByteArray &buf, int fd) +{ +#ifdef Q_OS_WIN +#ifndef _WIN32_WCE + HANDLE h = GetStdHandle(fd); + if (h) { + DWORD wr; + WriteFile(h, buf.data(), buf.size(), &wr, 0); + } +#else + fwrite(buf.data(), 1, buf.size(), (FILE*)fd); +#endif +#else + int off = 0; + do { + int ret = ::write(fd, buf.data() + off, buf.size() - off); + if (ret < 0) { + if (errno != EINTR) + return; + } else { + off += ret; + } + } while (off < buf.size()); +#endif +} + +void KProcessPrivate::forwardStd(KProcess::ProcessChannel good, int fd) +{ + Q_Q(KProcess); + + QProcess::ProcessChannel oc = q->readChannel(); + q->setReadChannel(good); + writeAll(q->readAll(), fd); + q->setReadChannel(oc); +} + +void KProcessPrivate::_k_forwardStdout() +{ +#ifndef _WIN32_WCE + forwardStd(KProcess::StandardOutput, STD_OUTPUT_HANDLE); +#else + forwardStd(KProcess::StandardOutput, (int)stdout); +#endif +} + +void KProcessPrivate::_k_forwardStderr() +{ +#ifndef _WIN32_WCE + forwardStd(KProcess::StandardError, STD_ERROR_HANDLE); +#else + forwardStd(KProcess::StandardError, (int)stderr); +#endif +} + +///////////////////////////// +// public member functions // +///////////////////////////// + +KProcess::KProcess(QObject *parent) : + QProcess(parent), + d_ptr(new KProcessPrivate) +{ + d_ptr->q_ptr = this; + setOutputChannelMode(ForwardedChannels); +} + +KProcess::KProcess(KProcessPrivate *d, QObject *parent) : + QProcess(parent), + d_ptr(d) +{ + d_ptr->q_ptr = this; + setOutputChannelMode(ForwardedChannels); +} + +KProcess::~KProcess() +{ + delete d_ptr; +} + +void KProcess::setOutputChannelMode(OutputChannelMode mode) +{ + Q_D(KProcess); + + d->outputChannelMode = mode; + disconnect(this, SIGNAL(readyReadStandardOutput())); + disconnect(this, SIGNAL(readyReadStandardError())); + switch (mode) { + case OnlyStdoutChannel: + connect(this, SIGNAL(readyReadStandardError()), SLOT(_k_forwardStderr())); + break; + case OnlyStderrChannel: + connect(this, SIGNAL(readyReadStandardOutput()), SLOT(_k_forwardStdout())); + break; + default: + QProcess::setProcessChannelMode((ProcessChannelMode)mode); + return; + } + QProcess::setProcessChannelMode(QProcess::SeparateChannels); +} + +KProcess::OutputChannelMode KProcess::outputChannelMode() const +{ + Q_D(const KProcess); + + return d->outputChannelMode; +} + +void KProcess::setNextOpenMode(QIODevice::OpenMode mode) +{ + Q_D(KProcess); + + d->openMode = mode; +} + +#define DUMMYENV "_KPROCESS_DUMMY_=" + +void KProcess::clearEnvironment() +{ + setEnvironment(QStringList() << QString::fromLatin1(DUMMYENV)); +} + +void KProcess::setEnv(const QString &name, const QString &value, bool overwrite) +{ + QStringList env = environment(); + if (env.isEmpty()) { + env = systemEnvironment(); + env.removeAll(QString::fromLatin1(DUMMYENV)); + } + QString fname(name); + fname.append(QLatin1Char('=')); + for (QStringList::Iterator it = env.begin(); it != env.end(); ++it) + if ((*it).startsWith(fname)) { + if (overwrite) { + *it = fname.append(value); + setEnvironment(env); + } + return; + } + env.append(fname.append(value)); + setEnvironment(env); +} + +void KProcess::unsetEnv(const QString &name) +{ + QStringList env = environment(); + if (env.isEmpty()) { + env = systemEnvironment(); + env.removeAll(QString::fromLatin1(DUMMYENV)); + } + QString fname(name); + fname.append(QLatin1Char('=')); + for (QStringList::Iterator it = env.begin(); it != env.end(); ++it) + if ((*it).startsWith(fname)) { + env.erase(it); + if (env.isEmpty()) + env.append(QString::fromLatin1(DUMMYENV)); + setEnvironment(env); + return; + } +} + +void KProcess::setProgram(const QString &exe, const QStringList &args) +{ + Q_D(KProcess); + + d->prog = exe; + d->args = args; +#ifdef Q_OS_WIN + setNativeArguments(QString()); +#endif +} + +void KProcess::setProgram(const QStringList &argv) +{ + Q_D(KProcess); + + Q_ASSERT( !argv.isEmpty() ); + d->args = argv; + d->prog = d->args.takeFirst(); +#ifdef Q_OS_WIN + setNativeArguments(QString()); +#endif +} + +KProcess &KProcess::operator<<(const QString &arg) +{ + Q_D(KProcess); + + if (d->prog.isEmpty()) + d->prog = arg; + else + d->args << arg; + return *this; +} + +KProcess &KProcess::operator<<(const QStringList &args) +{ + Q_D(KProcess); + + if (d->prog.isEmpty()) + setProgram(args); + else + d->args << args; + return *this; +} + +void KProcess::clearProgram() +{ + Q_D(KProcess); + + d->prog.clear(); + d->args.clear(); +#ifdef Q_OS_WIN + setNativeArguments(QString()); +#endif +} + +#if 0 +void KProcess::setShellCommand(const QString &cmd) +{ + Q_D(KProcess); + + KShell::Errors err; + d->args = KShell::splitArgs( + cmd, KShell::AbortOnMeta | KShell::TildeExpand, &err); + if (err == KShell::NoError && !d->args.isEmpty()) { + d->prog = KStandardDirs::findExe(d->args[0]); + if (!d->prog.isEmpty()) { + d->args.removeFirst(); +#ifdef Q_OS_WIN + setNativeArguments(QString()); +#endif + return; + } + } + + d->args.clear(); + +#ifdef Q_OS_UNIX +// #ifdef NON_FREE // ... as they ship non-POSIX /bin/sh +# if !defined(__linux__) && !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && !defined(__DragonFly__) && !defined(__GNU__) + // If /bin/sh is a symlink, we can be pretty sure that it points to a + // POSIX shell - the original bourne shell is about the only non-POSIX + // shell still in use and it is always installed natively as /bin/sh. + d->prog = QFile::symLinkTarget(QString::fromLatin1("/bin/sh")); + if (d->prog.isEmpty()) { + // Try some known POSIX shells. + d->prog = KStandardDirs::findExe(QString::fromLatin1("ksh")); + if (d->prog.isEmpty()) { + d->prog = KStandardDirs::findExe(QString::fromLatin1("ash")); + if (d->prog.isEmpty()) { + d->prog = KStandardDirs::findExe(QString::fromLatin1("bash")); + if (d->prog.isEmpty()) { + d->prog = KStandardDirs::findExe(QString::fromLatin1("zsh")); + if (d->prog.isEmpty()) + // We're pretty much screwed, to be honest ... + d->prog = QString::fromLatin1("/bin/sh"); + } + } + } + } +# else + d->prog = QString::fromLatin1("/bin/sh"); +# endif + + d->args << QString::fromLatin1("-c") << cmd; +#else // Q_OS_UNIX + // KMacroExpander::expandMacrosShellQuote(), KShell::quoteArg() and + // KShell::joinArgs() may generate these for security reasons. + setEnv(PERCENT_VARIABLE, QLatin1String("%")); + +#ifndef _WIN32_WCE + WCHAR sysdir[MAX_PATH + 1]; + UINT size = GetSystemDirectoryW(sysdir, MAX_PATH + 1); + d->prog = QString::fromUtf16((const ushort *) sysdir, size); + d->prog += QLatin1String("\\cmd.exe"); + setNativeArguments(QLatin1String("/V:OFF /S /C \"") + cmd + QLatin1Char('"')); +#else + d->prog = QLatin1String("\\windows\\cmd.exe"); + setNativeArguments(QLatin1String("/S /C \"") + cmd + QLatin1Char('"')); +#endif +#endif +} +#endif +QStringList KProcess::program() const +{ + Q_D(const KProcess); + + QStringList argv = d->args; + argv.prepend(d->prog); + return argv; +} + +void KProcess::start() +{ + Q_D(KProcess); + + QProcess::start(d->prog, d->args, d->openMode); +} + +int KProcess::execute(int msecs) +{ + start(); + if (!waitForFinished(msecs)) { + kill(); + waitForFinished(-1); + return -2; + } + return (exitStatus() == QProcess::NormalExit) ? exitCode() : -1; +} + +// static +int KProcess::execute(const QString &exe, const QStringList &args, int msecs) +{ + KProcess p; + p.setProgram(exe, args); + return p.execute(msecs); +} + +// static +int KProcess::execute(const QStringList &argv, int msecs) +{ + KProcess p; + p.setProgram(argv); + return p.execute(msecs); +} + +int KProcess::startDetached() +{ + Q_D(KProcess); + + qint64 pid; + if (!QProcess::startDetached(d->prog, d->args, workingDirectory(), &pid)) + return 0; + return (int) pid; +} + +// static +int KProcess::startDetached(const QString &exe, const QStringList &args) +{ + qint64 pid; + if (!QProcess::startDetached(exe, args, QString(), &pid)) + return 0; + return (int) pid; +} + +// static +int KProcess::startDetached(const QStringList &argv) +{ + QStringList args = argv; + QString prog = args.takeFirst(); + return startDetached(prog, args); +} + +int KProcess::pid() const +{ +#ifdef Q_OS_UNIX + return (int) QProcess::pid(); +#else + return QProcess::pid() ? QProcess::pid()->dwProcessId : 0; +#endif +} + diff --git a/lib/kprocess.h b/lib/kprocess.h new file mode 100644 index 0000000..74e3978 --- /dev/null +++ b/lib/kprocess.h @@ -0,0 +1,372 @@ +/* + * This file is a part of QTerminal - http://gitorious.org/qterminal + * + * This file was un-linked from KDE and modified + * by Maxim Bourmistrov + * + */ + +/* + This file is part of the KDE libraries + + Copyright (C) 2007 Oswald Buddenhagen + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#ifndef KPROCESS_H +#define KPROCESS_H + +//#include + +#include + +class KProcessPrivate; + +/** + * \class KProcess kprocess.h + * + * Child process invocation, monitoring and control. + * + * This class extends QProcess by some useful functionality, overrides + * some defaults with saner values and wraps parts of the API into a more + * accessible one. + * This is the preferred way of spawning child processes in KDE; don't + * use QProcess directly. + * + * @author Oswald Buddenhagen + **/ +class KProcess : public QProcess +{ + Q_OBJECT + Q_DECLARE_PRIVATE(KProcess) + +public: + + /** + * Modes in which the output channels can be opened. + */ + enum OutputChannelMode { + SeparateChannels = QProcess::SeparateChannels, + /**< Standard output and standard error are handled by KProcess + as separate channels */ + MergedChannels = QProcess::MergedChannels, + /**< Standard output and standard error are handled by KProcess + as one channel */ + ForwardedChannels = QProcess::ForwardedChannels, + /**< Both standard output and standard error are forwarded + to the parent process' respective channel */ + OnlyStdoutChannel, + /**< Only standard output is handled; standard error is forwarded */ + OnlyStderrChannel /**< Only standard error is handled; standard output is forwarded */ + }; + + /** + * Constructor + */ + explicit KProcess(QObject *parent = 0); + + /** + * Destructor + */ + virtual ~KProcess(); + + /** + * Set how to handle the output channels of the child process. + * + * The default is ForwardedChannels, which is unlike in QProcess. + * Do not request more than you actually handle, as this output is + * simply lost otherwise. + * + * This function must be called before starting the process. + * + * @param mode the output channel handling mode + */ + void setOutputChannelMode(OutputChannelMode mode); + + /** + * Query how the output channels of the child process are handled. + * + * @return the output channel handling mode + */ + OutputChannelMode outputChannelMode() const; + + /** + * Set the QIODevice open mode the process will be opened in. + * + * This function must be called before starting the process, obviously. + * + * @param mode the open mode. Note that this mode is automatically + * "reduced" according to the channel modes and redirections. + * The default is QIODevice::ReadWrite. + */ + void setNextOpenMode(QIODevice::OpenMode mode); + + /** + * Adds the variable @p name to the process' environment. + * + * This function must be called before starting the process. + * + * @param name the name of the environment variable + * @param value the new value for the environment variable + * @param overwrite if @c false and the environment variable is already + * set, the old value will be preserved + */ + void setEnv(const QString &name, const QString &value, bool overwrite = true); + + /** + * Removes the variable @p name from the process' environment. + * + * This function must be called before starting the process. + * + * @param name the name of the environment variable + */ + void unsetEnv(const QString &name); + + /** + * Empties the process' environment. + * + * Note that LD_LIBRARY_PATH/DYLD_LIBRARY_PATH is automatically added + * on *NIX. + * + * This function must be called before starting the process. + */ + void clearEnvironment(); + + /** + * Set the program and the command line arguments. + * + * This function must be called before starting the process, obviously. + * + * @param exe the program to execute + * @param args the command line arguments for the program, + * one per list element + */ + void setProgram(const QString &exe, const QStringList &args = QStringList()); + + /** + * @overload + * + * @param argv the program to execute and the command line arguments + * for the program, one per list element + */ + void setProgram(const QStringList &argv); + + /** + * Append an element to the command line argument list for this process. + * + * If no executable is set yet, it will be set instead. + * + * For example, doing an "ls -l /usr/local/bin" can be achieved by: + * \code + * KProcess p; + * p << "ls" << "-l" << "/usr/local/bin"; + * ... + * \endcode + * + * This function must be called before starting the process, obviously. + * + * @param arg the argument to add + * @return a reference to this KProcess + */ + KProcess &operator<<(const QString& arg); + + /** + * @overload + * + * @param args the arguments to add + * @return a reference to this KProcess + */ + KProcess &operator<<(const QStringList& args); + + /** + * Clear the program and command line argument list. + */ + void clearProgram(); + + /** + * Set a command to execute through a shell (a POSIX sh on *NIX + * and cmd.exe on Windows). + * + * Using this for anything but user-supplied commands is usually a bad + * idea, as the command's syntax depends on the platform. + * Redirections including pipes, etc. are better handled by the + * respective functions provided by QProcess. + * + * If KProcess determines that the command does not really need a + * shell, it will trasparently execute it without one for performance + * reasons. + * + * This function must be called before starting the process, obviously. + * + * @param cmd the command to execute through a shell. + * The caller must make sure that all filenames etc. are properly + * quoted when passed as argument. Failure to do so often results in + * serious security holes. See KShell::quoteArg(). + */ + void setShellCommand(const QString &cmd); + + /** + * Obtain the currently set program and arguments. + * + * @return a list, the first element being the program, the remaining ones + * being command line arguments to the program. + */ + QStringList program() const; + + /** + * Start the process. + * + * @see QProcess::start(const QString &, const QStringList &, OpenMode) + */ + void start(); + + /** + * Start the process, wait for it to finish, and return the exit code. + * + * This method is roughly equivalent to the sequence: + * + * start(); + * waitForFinished(msecs); + * return exitCode(); + * + * + * Unlike the other execute() variants this method is not static, + * so the process can be parametrized properly and talked to. + * + * @param msecs time to wait for process to exit before killing it + * @return -2 if the process could not be started, -1 if it crashed, + * otherwise its exit code + */ + int execute(int msecs = -1); + + /** + * @overload + * + * @param exe the program to execute + * @param args the command line arguments for the program, + * one per list element + * @param msecs time to wait for process to exit before killing it + * @return -2 if the process could not be started, -1 if it crashed, + * otherwise its exit code + */ + static int execute(const QString &exe, const QStringList &args = QStringList(), int msecs = -1); + + /** + * @overload + * + * @param argv the program to execute and the command line arguments + * for the program, one per list element + * @param msecs time to wait for process to exit before killing it + * @return -2 if the process could not be started, -1 if it crashed, + * otherwise its exit code + */ + static int execute(const QStringList &argv, int msecs = -1); + + /** + * Start the process and detach from it. See QProcess::startDetached() + * for details. + * + * Unlike the other startDetached() variants this method is not static, + * so the process can be parametrized properly. + * @note Currently, only the setProgram()/setShellCommand() and + * setWorkingDirectory() parametrizations are supported. + * + * The KProcess object may be re-used immediately after calling this + * function. + * + * @return the PID of the started process or 0 on error + */ + int startDetached(); + + /** + * @overload + * + * @param exe the program to start + * @param args the command line arguments for the program, + * one per list element + * @return the PID of the started process or 0 on error + */ + static int startDetached(const QString &exe, const QStringList &args = QStringList()); + + /** + * @overload + * + * @param argv the program to start and the command line arguments + * for the program, one per list element + * @return the PID of the started process or 0 on error + */ + static int startDetached(const QStringList &argv); + + /** + * Obtain the process' ID as known to the system. + * + * Unlike with QProcess::pid(), this is a real PID also on Windows. + * + * This function can be called only while the process is running. + * It cannot be applied to detached processes. + * + * @return the process ID + */ + int pid() const; + +protected: + /** + * @internal + */ + KProcess(KProcessPrivate *d, QObject *parent); + + /** + * @internal + */ + KProcessPrivate * const d_ptr; + +private: + // hide those + using QProcess::setReadChannelMode; + using QProcess::readChannelMode; + using QProcess::setProcessChannelMode; + using QProcess::processChannelMode; + + Q_PRIVATE_SLOT(d_func(), void _k_forwardStdout()) + Q_PRIVATE_SLOT(d_func(), void _k_forwardStderr()) +}; + +/* ----------- kprocess_p.h ---------------- */ +class KProcessPrivate { + + Q_DECLARE_PUBLIC(KProcess) + +protected: + KProcessPrivate() : + openMode(QIODevice::ReadWrite) + { + } + void writeAll(const QByteArray &buf, int fd); + void forwardStd(KProcess::ProcessChannel good, int fd); + void _k_forwardStdout(); + void _k_forwardStderr(); + + QString prog; + QStringList args; + KProcess::OutputChannelMode outputChannelMode; + QIODevice::OpenMode openMode; + + KProcess *q_ptr; +}; +/* ------------------------------------------- */ +#endif + diff --git a/lib/kpty.cpp b/lib/kpty.cpp index d1f51ac..797a5f6 100644 --- a/lib/kpty.cpp +++ b/lib/kpty.cpp @@ -361,6 +361,48 @@ grantedpt: return true; } +bool KPty::open(int fd) +{ +#if !defined(HAVE_PTSNAME) && !defined(TIOCGPTN) + qWarning() << "Unsupported attempt to open pty with fd" << fd; + return false; +#else + Q_D(KPty); + + if (d->masterFd >= 0) { + qWarning() << "Attempting to open an already open pty"; + return false; + } + + d->ownMaster = false; + +# ifdef HAVE_PTSNAME + char *ptsn = ptsname(fd); + if (ptsn) { + d->ttyName = ptsn; +# else + int ptyno; + if (!ioctl(fd, TIOCGPTN, &ptyno)) { + char buf[32]; + sprintf(buf, "/dev/pts/%d", ptyno); + d->ttyName = buf; +# endif + } else { + qWarning() << "Failed to determine pty slave device for fd" << fd; + return false; + } + + d->masterFd = fd; + if (!openSlave()) { + + d->masterFd = -1; + return false; + } + + return true; +#endif +} + void KPty::closeSlave() { Q_D(KPty); @@ -372,6 +414,26 @@ void KPty::closeSlave() d->slaveFd = -1; } +bool KPty::openSlave() +{ + Q_D(KPty); + + if (d->slaveFd >= 0) + return true; + if (d->masterFd < 0) { + qDebug() << "Attempting to open pty slave while master is closed"; + return false; + } + //d->slaveFd = KDE_open(d->ttyName.data(), O_RDWR | O_NOCTTY); + d->slaveFd = ::open(d->ttyName.data(), O_RDWR | O_NOCTTY); + if (d->slaveFd < 0) { + qDebug() << "Can't open slave pseudo teletype"; + return false; + } + fcntl(d->slaveFd, F_SETFD, FD_CLOEXEC); + return true; +} + void KPty::close() { Q_D(KPty); diff --git a/lib/kpty.h b/lib/kpty.h index 094b758..b0a30c3 100644 --- a/lib/kpty.h +++ b/lib/kpty.h @@ -57,6 +57,8 @@ public: */ bool open(); + bool open(int fd); + /** * Close the pty master/slave pair. */ @@ -75,6 +77,7 @@ public: * used. */ void closeSlave(); + bool openSlave(); /** * Creates a new session and process group and makes this pty the diff --git a/lib/kpty_p.h b/lib/kpty_p.h index dabfcc8..276419d 100644 --- a/lib/kpty_p.h +++ b/lib/kpty_p.h @@ -28,10 +28,12 @@ #include struct KPtyPrivate { + Q_DECLARE_PUBLIC(KPty) KPtyPrivate(KPty* parent); virtual ~KPtyPrivate(); + #ifndef HAVE_OPENPTY bool chownpty(bool grant); #endif diff --git a/lib/kptydevice.cpp b/lib/kptydevice.cpp new file mode 100644 index 0000000..37ecce8 --- /dev/null +++ b/lib/kptydevice.cpp @@ -0,0 +1,422 @@ +/* + * This file is a part of QTerminal - http://gitorious.org/qterminal + * + * This file was un-linked from KDE and modified + * by Maxim Bourmistrov + * + */ + +/* + + This file is part of the KDE libraries + Copyright (C) 2007 Oswald Buddenhagen + Copyright (C) 2010 KDE e.V. + Author Adriaan de Groot + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include "kptydevice.h" +#include "kpty_p.h" + +#include + +#include +#include +#include +#include +#include +#include +#ifdef HAVE_SYS_FILIO_H +# include +#endif +#ifdef HAVE_SYS_TIME_H +# include +#endif + +#if defined(Q_OS_FREEBSD) || defined(Q_OS_MAC) + // "the other end's output queue size" - kinda braindead, huh? +# define PTY_BYTES_AVAILABLE TIOCOUTQ +#elif defined(TIOCINQ) + // "our end's input queue size" +# define PTY_BYTES_AVAILABLE TIOCINQ +#else + // likewise. more generic ioctl (theoretically) +# define PTY_BYTES_AVAILABLE FIONREAD +#endif + + + + +////////////////// +// private data // +////////////////// + +// Lifted from Qt. I don't think they would mind. ;) +// Re-lift again from Qt whenever a proper replacement for pthread_once appears +static void qt_ignore_sigpipe() +{ + static QBasicAtomicInt atom = Q_BASIC_ATOMIC_INITIALIZER(0); + if (atom.testAndSetRelaxed(0, 1)) { + struct sigaction noaction; + memset(&noaction, 0, sizeof(noaction)); + noaction.sa_handler = SIG_IGN; + sigaction(SIGPIPE, &noaction, 0); + } +} + +#define NO_INTR(ret,func) do { ret = func; } while (ret < 0 && errno == EINTR) + +bool KPtyDevicePrivate::_k_canRead() +{ + Q_Q(KPtyDevice); + qint64 readBytes = 0; + +#ifdef Q_OS_IRIX // this should use a config define, but how to check it? + size_t available; +#else + int available; +#endif + if (!::ioctl(q->masterFd(), PTY_BYTES_AVAILABLE, (char *) &available)) { +#ifdef Q_OS_SOLARIS + // A Pty is a STREAMS module, and those can be activated + // with 0 bytes available. This happens either when ^C is + // pressed, or when an application does an explicit write(a,b,0) + // which happens in experiments fairly often. When 0 bytes are + // available, you must read those 0 bytes to clear the STREAMS + // module, but we don't want to hit the !readBytes case further down. + if (!available) { + char c; + // Read the 0-byte STREAMS message + NO_INTR(readBytes, read(q->masterFd(), &c, 0)); + // Should return 0 bytes read; -1 is error + if (readBytes < 0) { + readNotifier->setEnabled(false); + emit q->readEof(); + return false; + } + return true; + } +#endif + + char *ptr = readBuffer.reserve(available); +#ifdef Q_OS_SOLARIS + // Even if available > 0, it is possible for read() + // to return 0 on Solaris, due to 0-byte writes in the stream. + // Ignore them and keep reading until we hit *some* data. + // In Solaris it is possible to have 15 bytes available + // and to (say) get 0, 0, 6, 0 and 9 bytes in subsequent reads. + // Because the stream is set to O_NONBLOCK in finishOpen(), + // an EOF read will return -1. + readBytes = 0; + while (!readBytes) +#endif + // Useless block braces except in Solaris + { + NO_INTR(readBytes, read(q->masterFd(), ptr, available)); + } + if (readBytes < 0) { + readBuffer.unreserve(available); + q->setErrorString("Error reading from PTY"); + return false; + } + readBuffer.unreserve(available - readBytes); // *should* be a no-op + } + + if (!readBytes) { + readNotifier->setEnabled(false); + emit q->readEof(); + return false; + } else { + if (!emittedReadyRead) { + emittedReadyRead = true; + emit q->readyRead(); + emittedReadyRead = false; + } + return true; + } +} + +bool KPtyDevicePrivate::_k_canWrite() +{ + Q_Q(KPtyDevice); + + writeNotifier->setEnabled(false); + if (writeBuffer.isEmpty()) + return false; + + qt_ignore_sigpipe(); + int wroteBytes; + NO_INTR(wroteBytes, + write(q->masterFd(), + writeBuffer.readPointer(), writeBuffer.readSize())); + if (wroteBytes < 0) { + q->setErrorString("Error writing to PTY"); + return false; + } + writeBuffer.free(wroteBytes); + + if (!emittedBytesWritten) { + emittedBytesWritten = true; + emit q->bytesWritten(wroteBytes); + emittedBytesWritten = false; + } + + if (!writeBuffer.isEmpty()) + writeNotifier->setEnabled(true); + return true; +} + +#ifndef timeradd +// Lifted from GLIBC +# define timeradd(a, b, result) \ + do { \ + (result)->tv_sec = (a)->tv_sec + (b)->tv_sec; \ + (result)->tv_usec = (a)->tv_usec + (b)->tv_usec; \ + if ((result)->tv_usec >= 1000000) { \ + ++(result)->tv_sec; \ + (result)->tv_usec -= 1000000; \ + } \ + } while (0) +# define timersub(a, b, result) \ + do { \ + (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \ + (result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \ + if ((result)->tv_usec < 0) { \ + --(result)->tv_sec; \ + (result)->tv_usec += 1000000; \ + } \ + } while (0) +#endif + +bool KPtyDevicePrivate::doWait(int msecs, bool reading) +{ + Q_Q(KPtyDevice); +#ifndef __linux__ + struct timeval etv; +#endif + struct timeval tv, *tvp; + + if (msecs < 0) + tvp = 0; + else { + tv.tv_sec = msecs / 1000; + tv.tv_usec = (msecs % 1000) * 1000; +#ifndef __linux__ + gettimeofday(&etv, 0); + timeradd(&tv, &etv, &etv); +#endif + tvp = &tv; + } + + while (reading ? readNotifier->isEnabled() : !writeBuffer.isEmpty()) { + fd_set rfds; + fd_set wfds; + + FD_ZERO(&rfds); + FD_ZERO(&wfds); + + if (readNotifier->isEnabled()) + FD_SET(q->masterFd(), &rfds); + if (!writeBuffer.isEmpty()) + FD_SET(q->masterFd(), &wfds); + +#ifndef __linux__ + if (tvp) { + gettimeofday(&tv, 0); + timersub(&etv, &tv, &tv); + if (tv.tv_sec < 0) + tv.tv_sec = tv.tv_usec = 0; + } +#endif + + switch (select(q->masterFd() + 1, &rfds, &wfds, 0, tvp)) { + case -1: + if (errno == EINTR) + break; + return false; + case 0: + q->setErrorString("PTY operation timed out"); + return false; + default: + if (FD_ISSET(q->masterFd(), &rfds)) { + bool canRead = _k_canRead(); + if (reading && canRead) + return true; + } + if (FD_ISSET(q->masterFd(), &wfds)) { + bool canWrite = _k_canWrite(); + if (!reading) + return canWrite; + } + break; + } + } + return false; +} + +void KPtyDevicePrivate::finishOpen(QIODevice::OpenMode mode) +{ + Q_Q(KPtyDevice); + + q->QIODevice::open(mode); + fcntl(q->masterFd(), F_SETFL, O_NONBLOCK); + readBuffer.clear(); + readNotifier = new QSocketNotifier(q->masterFd(), QSocketNotifier::Read, q); + writeNotifier = new QSocketNotifier(q->masterFd(), QSocketNotifier::Write, q); + QObject::connect(readNotifier, SIGNAL(activated(int)), q, SLOT(_k_canRead())); + QObject::connect(writeNotifier, SIGNAL(activated(int)), q, SLOT(_k_canWrite())); + readNotifier->setEnabled(true); +} + +///////////////////////////// +// public member functions // +///////////////////////////// + +KPtyDevice::KPtyDevice(QObject *parent) : + QIODevice(parent), + KPty(new KPtyDevicePrivate(this)) +{ +} + +KPtyDevice::~KPtyDevice() +{ + close(); +} + +bool KPtyDevice::open(OpenMode mode) +{ + Q_D(KPtyDevice); + + if (masterFd() >= 0) + return true; + + if (!KPty::open()) { + setErrorString("Error opening PTY"); + return false; + } + + d->finishOpen(mode); + + return true; +} + +bool KPtyDevice::open(int fd, OpenMode mode) +{ + Q_D(KPtyDevice); + + if (!KPty::open(fd)) { + setErrorString("Error opening PTY"); + return false; + } + + d->finishOpen(mode); + + return true; +} + +void KPtyDevice::close() +{ + Q_D(KPtyDevice); + + if (masterFd() < 0) + return; + + delete d->readNotifier; + delete d->writeNotifier; + + QIODevice::close(); + + KPty::close(); +} + +bool KPtyDevice::isSequential() const +{ + return true; +} + +bool KPtyDevice::canReadLine() const +{ + Q_D(const KPtyDevice); + return QIODevice::canReadLine() || d->readBuffer.canReadLine(); +} + +bool KPtyDevice::atEnd() const +{ + Q_D(const KPtyDevice); + return QIODevice::atEnd() && d->readBuffer.isEmpty(); +} + +qint64 KPtyDevice::bytesAvailable() const +{ + Q_D(const KPtyDevice); + return QIODevice::bytesAvailable() + d->readBuffer.size(); +} + +qint64 KPtyDevice::bytesToWrite() const +{ + Q_D(const KPtyDevice); + return d->writeBuffer.size(); +} + +bool KPtyDevice::waitForReadyRead(int msecs) +{ + Q_D(KPtyDevice); + return d->doWait(msecs, true); +} + +bool KPtyDevice::waitForBytesWritten(int msecs) +{ + Q_D(KPtyDevice); + return d->doWait(msecs, false); +} + +void KPtyDevice::setSuspended(bool suspended) +{ + Q_D(KPtyDevice); + d->readNotifier->setEnabled(!suspended); +} + +bool KPtyDevice::isSuspended() const +{ + Q_D(const KPtyDevice); + return !d->readNotifier->isEnabled(); +} + +// protected +qint64 KPtyDevice::readData(char *data, qint64 maxlen) +{ + Q_D(KPtyDevice); + return d->readBuffer.read(data, (int)qMin(maxlen, KMAXINT)); +} + +// protected +qint64 KPtyDevice::readLineData(char *data, qint64 maxlen) +{ + Q_D(KPtyDevice); + return d->readBuffer.readLine(data, (int)qMin(maxlen, KMAXINT)); +} + +// protected +qint64 KPtyDevice::writeData(const char *data, qint64 len) +{ + Q_D(KPtyDevice); + Q_ASSERT(len <= KMAXINT); + + d->writeBuffer.write(data, len); + d->writeNotifier->setEnabled(true); + return len; +} diff --git a/lib/kptydevice.h b/lib/kptydevice.h new file mode 100644 index 0000000..05a7787 --- /dev/null +++ b/lib/kptydevice.h @@ -0,0 +1,360 @@ +/* + * This file is a part of QTerminal - http://gitorious.org/qterminal + * + * This file was un-linked from KDE and modified + * by Maxim Bourmistrov + * + */ + +/* This file is part of the KDE libraries + + Copyright (C) 2007 Oswald Buddenhagen + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#ifndef kptydev_h +#define kptydev_h + +#include "kpty_p.h" + +#include + +#define KMAXINT ((int)(~0U >> 1)) + +struct KPtyDevicePrivate; + +#define Q_DECLARE_PRIVATE_MI(Class, SuperClass) \ + inline Class##Private* d_func() { return reinterpret_cast(SuperClass::d_ptr); } \ + inline const Class##Private* d_func() const { return reinterpret_cast(SuperClass::d_ptr); } \ + friend class Class##Private; + +/** + * Encapsulates KPty into a QIODevice, so it can be used with Q*Stream, etc. + */ +class KPtyDevice : public QIODevice, public KPty { + Q_OBJECT + Q_DECLARE_PRIVATE_MI(KPtyDevice, KPty) + +public: + + /** + * Constructor + */ + KPtyDevice(QObject *parent = 0); + + /** + * Destructor: + * + * If the pty is still open, it will be closed. Note, however, that + * an utmp registration is @em not undone. + */ + virtual ~KPtyDevice(); + + /** + * Create a pty master/slave pair. + * + * @return true if a pty pair was successfully opened + */ + virtual bool open(OpenMode mode = ReadWrite | Unbuffered); + + /** + * Open using an existing pty master. The ownership of the fd + * remains with the caller, i.e., close() will not close the fd. + * + * This is useful if you wish to attach a secondary "controller" to an + * existing pty device such as a terminal widget. + * Note that you will need to use setSuspended() on both devices to + * control which one gets the incoming data from the pty. + * + * @param fd an open pty master file descriptor. + * @param mode the device mode to open the pty with. + * @return true if a pty pair was successfully opened + */ + bool open(int fd, OpenMode mode = ReadWrite | Unbuffered); + + /** + * Close the pty master/slave pair. + */ + virtual void close(); + + /** + * Sets whether the KPtyDevice monitors the pty for incoming data. + * + * When the KPtyDevice is suspended, it will no longer attempt to buffer + * data that becomes available from the pty and it will not emit any + * signals. + * + * Do not use on closed ptys. + * After a call to open(), the pty is not suspended. If you need to + * ensure that no data is read, call this function before the main loop + * is entered again (i.e., immediately after opening the pty). + */ + void setSuspended(bool suspended); + + /** + * Returns true if the KPtyDevice is not monitoring the pty for incoming + * data. + * + * Do not use on closed ptys. + * + * See setSuspended() + */ + bool isSuspended() const; + + /** + * @return always true + */ + virtual bool isSequential() const; + + /** + * @reimp + */ + bool canReadLine() const; + + /** + * @reimp + */ + bool atEnd() const; + + /** + * @reimp + */ + qint64 bytesAvailable() const; + + /** + * @reimp + */ + qint64 bytesToWrite() const; + + bool waitForBytesWritten(int msecs = -1); + bool waitForReadyRead(int msecs = -1); + + +Q_SIGNALS: + /** + * Emitted when EOF is read from the PTY. + * + * Data may still remain in the buffers. + */ + void readEof(); + +protected: + virtual qint64 readData(char *data, qint64 maxSize); + virtual qint64 readLineData(char *data, qint64 maxSize); + virtual qint64 writeData(const char *data, qint64 maxSize); + +private: + Q_PRIVATE_SLOT(d_func(), bool _k_canRead()) + Q_PRIVATE_SLOT(d_func(), bool _k_canWrite()) +}; + +///////////////////////////////////////////////////// +// Helper. Remove when QRingBuffer becomes public. // +///////////////////////////////////////////////////// + +#include +#include + +#define CHUNKSIZE 4096 + +class KRingBuffer +{ +public: + KRingBuffer() + { + clear(); + } + + void clear() + { + buffers.clear(); + QByteArray tmp; + tmp.resize(CHUNKSIZE); + buffers << tmp; + head = tail = 0; + totalSize = 0; + } + + inline bool isEmpty() const + { + return buffers.count() == 1 && !tail; + } + + inline int size() const + { + return totalSize; + } + + inline int readSize() const + { + return (buffers.count() == 1 ? tail : buffers.first().size()) - head; + } + + inline const char *readPointer() const + { + Q_ASSERT(totalSize > 0); + return buffers.first().constData() + head; + } + + void free(int bytes) + { + totalSize -= bytes; + Q_ASSERT(totalSize >= 0); + + forever { + int nbs = readSize(); + + if (bytes < nbs) { + head += bytes; + if (head == tail && buffers.count() == 1) { + buffers.first().resize(CHUNKSIZE); + head = tail = 0; + } + break; + } + + bytes -= nbs; + if (buffers.count() == 1) { + buffers.first().resize(CHUNKSIZE); + head = tail = 0; + break; + } + + buffers.removeFirst(); + head = 0; + } + } + + char *reserve(int bytes) + { + totalSize += bytes; + + char *ptr; + if (tail + bytes <= buffers.last().size()) { + ptr = buffers.last().data() + tail; + tail += bytes; + } else { + buffers.last().resize(tail); + QByteArray tmp; + tmp.resize(qMax(CHUNKSIZE, bytes)); + ptr = tmp.data(); + buffers << tmp; + tail = bytes; + } + return ptr; + } + + // release a trailing part of the last reservation + inline void unreserve(int bytes) + { + totalSize -= bytes; + tail -= bytes; + } + + inline void write(const char *data, int len) + { + memcpy(reserve(len), data, len); + } + + // Find the first occurrence of c and return the index after it. + // If c is not found until maxLength, maxLength is returned, provided + // it is smaller than the buffer size. Otherwise -1 is returned. + int indexAfter(char c, int maxLength = KMAXINT) const + { + int index = 0; + int start = head; + QLinkedList::ConstIterator it = buffers.begin(); + forever { + if (!maxLength) + return index; + if (index == size()) + return -1; + const QByteArray &buf = *it; + ++it; + int len = qMin((it == buffers.end() ? tail : buf.size()) - start, + maxLength); + const char *ptr = buf.data() + start; + if (const char *rptr = (const char *)memchr(ptr, c, len)) + return index + (rptr - ptr) + 1; + index += len; + maxLength -= len; + start = 0; + } + } + + inline int lineSize(int maxLength = KMAXINT) const + { + return indexAfter('\n', maxLength); + } + + inline bool canReadLine() const + { + return lineSize() != -1; + } + + int read(char *data, int maxLength) + { + int bytesToRead = qMin(size(), maxLength); + int readSoFar = 0; + while (readSoFar < bytesToRead) { + const char *ptr = readPointer(); + int bs = qMin(bytesToRead - readSoFar, readSize()); + memcpy(data + readSoFar, ptr, bs); + readSoFar += bs; + free(bs); + } + return readSoFar; + } + + int readLine(char *data, int maxLength) + { + return read(data, lineSize(qMin(maxLength, size()))); + } + +private: + QLinkedList buffers; + int head, tail; + int totalSize; +}; + +struct KPtyDevicePrivate : public KPtyPrivate { + + Q_DECLARE_PUBLIC(KPtyDevice) + + KPtyDevicePrivate(KPty* parent) : + KPtyPrivate(parent), + emittedReadyRead(false), emittedBytesWritten(false), + readNotifier(0), writeNotifier(0) + { + } + + bool _k_canRead(); + bool _k_canWrite(); + + bool doWait(int msecs, bool reading); + void finishOpen(QIODevice::OpenMode mode); + + bool emittedReadyRead; + bool emittedBytesWritten; + QSocketNotifier *readNotifier; + QSocketNotifier *writeNotifier; + KRingBuffer readBuffer; + KRingBuffer writeBuffer; +}; + +#endif + diff --git a/lib/kptyprocess.cpp b/lib/kptyprocess.cpp new file mode 100644 index 0000000..078770b --- /dev/null +++ b/lib/kptyprocess.cpp @@ -0,0 +1,129 @@ +/* + * This file is a part of QTerminal - http://gitorious.org/qterminal + * + * This file was un-linked from KDE and modified + * by Maxim Bourmistrov + * + */ + +/* + This file is part of the KDE libraries + + Copyright (C) 2007 Oswald Buddenhagen + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + + +#include "kptyprocess.h" +#include "kprocess.h" +#include "kptydevice.h" + +#include +#include + +KPtyProcess::KPtyProcess(QObject *parent) : + KProcess(new KPtyProcessPrivate, parent) +{ + Q_D(KPtyProcess); + + d->pty = new KPtyDevice(this); + d->pty->open(); + connect(this, SIGNAL(stateChanged(QProcess::ProcessState)), + SLOT(_k_onStateChanged(QProcess::ProcessState))); +} + +KPtyProcess::KPtyProcess(int ptyMasterFd, QObject *parent) : + KProcess(new KPtyProcessPrivate, parent) +{ + Q_D(KPtyProcess); + + d->pty = new KPtyDevice(this); + d->pty->open(ptyMasterFd); + connect(this, SIGNAL(stateChanged(QProcess::ProcessState)), + SLOT(_k_onStateChanged(QProcess::ProcessState))); +} + +KPtyProcess::~KPtyProcess() +{ + Q_D(KPtyProcess); + + if (state() != QProcess::NotRunning && d->addUtmp) { + d->pty->logout(); + disconnect(SIGNAL(stateChanged(QProcess::ProcessState)), + this, SLOT(_k_onStateChanged(QProcess::ProcessState))); + } + delete d->pty; +} + +void KPtyProcess::setPtyChannels(PtyChannels channels) +{ + Q_D(KPtyProcess); + + d->ptyChannels = channels; +} + +KPtyProcess::PtyChannels KPtyProcess::ptyChannels() const +{ + Q_D(const KPtyProcess); + + return d->ptyChannels; +} + +void KPtyProcess::setUseUtmp(bool value) +{ + Q_D(KPtyProcess); + + d->addUtmp = value; +} + +bool KPtyProcess::isUseUtmp() const +{ + Q_D(const KPtyProcess); + + return d->addUtmp; +} + +KPtyDevice *KPtyProcess::pty() const +{ + Q_D(const KPtyProcess); + + return d->pty; +} + +void KPtyProcess::setupChildProcess() +{ + Q_D(KPtyProcess); + + d->pty->setCTty(); + +#if 0 + if (d->addUtmp) + d->pty->login(KUser(KUser::UseRealUserID).loginName().toLocal8Bit().data(), qgetenv("DISPLAY")); +#endif + if (d->ptyChannels & StdinChannel) + dup2(d->pty->slaveFd(), 0); + + if (d->ptyChannels & StdoutChannel) + dup2(d->pty->slaveFd(), 1); + + if (d->ptyChannels & StderrChannel) + dup2(d->pty->slaveFd(), 2); + + KProcess::setupChildProcess(); +} + +//#include "kptyprocess.moc" diff --git a/lib/kptyprocess.h b/lib/kptyprocess.h new file mode 100644 index 0000000..15e4de4 --- /dev/null +++ b/lib/kptyprocess.h @@ -0,0 +1,178 @@ +/* + * This file is a part of QTerminal - http://gitorious.org/qterminal + * + * This file was un-linked from KDE and modified + * by Maxim Bourmistrov + * + */ + +/* + This file is part of the KDE libraries + + Copyright (C) 2007 Oswald Buddenhagen + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#ifndef KPTYPROCESS_H +#define KPTYPROCESS_H + +#include "kprocess.h" +#include "kptydevice.h" + +#include + +class KPtyDevice; + +struct KPtyProcessPrivate; + +/** + * This class extends KProcess by support for PTYs (pseudo TTYs). + * + * The PTY is opened as soon as the class is instantiated. Verify that + * it was opened successfully by checking that pty()->masterFd() is not -1. + * + * The PTY is always made the process' controlling TTY. + * Utmp registration and connecting the stdio handles to the PTY are optional. + * + * No attempt to integrate with QProcess' waitFor*() functions was made, + * for it is impossible. Note that execute() does not work with the PTY, too. + * Use the PTY device's waitFor*() functions or use it asynchronously. + * + * @author Oswald Buddenhagen + */ +class KPtyProcess : public KProcess +{ + Q_OBJECT + Q_DECLARE_PRIVATE(KPtyProcess) + +public: + enum PtyChannelFlag { + NoChannels = 0, /**< The PTY is not connected to any channel. */ + StdinChannel = 1, /**< Connect PTY to stdin. */ + StdoutChannel = 2, /**< Connect PTY to stdout. */ + StderrChannel = 4, /**< Connect PTY to stderr. */ + AllOutputChannels = 6, /**< Connect PTY to all output channels. */ + AllChannels = 7 /**< Connect PTY to all channels. */ + }; + + Q_DECLARE_FLAGS(PtyChannels, PtyChannelFlag) + + /** + * Constructor + */ + explicit KPtyProcess(QObject *parent = 0); + + /** + * Construct a process using an open pty master. + * + * @param ptyMasterFd an open pty master file descriptor. + * The process does not take ownership of the descriptor; + * it will not be automatically closed at any point. + */ + KPtyProcess(int ptyMasterFd, QObject *parent = 0); + + /** + * Destructor + */ + virtual ~KPtyProcess(); + + /** + * Set to which channels the PTY should be assigned. + * + * This function must be called before starting the process. + * + * @param channels the output channel handling mode + */ + void setPtyChannels(PtyChannels channels); + + bool isRunning() const + { + bool rval; + (pid() > 0) ? rval= true : rval= false; + return rval; + + } + /** + * Query to which channels the PTY is assigned. + * + * @return the output channel handling mode + */ + PtyChannels ptyChannels() const; + + /** + * Set whether to register the process as a TTY login in utmp. + * + * Utmp is disabled by default. + * It should enabled for interactively fed processes, like terminal + * emulations. + * + * This function must be called before starting the process. + * + * @param value whether to register in utmp. + */ + void setUseUtmp(bool value); + + /** + * Get whether to register the process as a TTY login in utmp. + * + * @return whether to register in utmp + */ + bool isUseUtmp() const; + + /** + * Get the PTY device of this process. + * + * @return the PTY device + */ + KPtyDevice *pty() const; + +protected: + /** + * @reimp + */ + virtual void setupChildProcess(); + +private: + Q_PRIVATE_SLOT(d_func(), void _k_onStateChanged(QProcess::ProcessState)) +}; + + +////////////////// +// private data // +////////////////// + +struct KPtyProcessPrivate : KProcessPrivate { + KPtyProcessPrivate() : + ptyChannels(KPtyProcess::NoChannels), + addUtmp(false) + { + } + + void _k_onStateChanged(QProcess::ProcessState newState) + { + if (newState == QProcess::NotRunning && addUtmp) + pty->logout(); + } + + KPtyDevice *pty; + KPtyProcess::PtyChannels ptyChannels; + bool addUtmp : 1; +}; + +Q_DECLARE_OPERATORS_FOR_FLAGS(KPtyProcess::PtyChannels) + +#endif diff --git a/lib/qtermwidget.cpp b/lib/qtermwidget.cpp index dc329a7..923f1ca 100644 --- a/lib/qtermwidget.cpp +++ b/lib/qtermwidget.cpp @@ -23,6 +23,7 @@ #include "Session.h" #include "TerminalDisplay.h" #include "KeyboardTranslator.h" +#include "ColorScheme.h" using namespace Konsole; @@ -200,6 +201,7 @@ void QTermWidget::setTerminalOpacity(qreal level) { if (!m_impl->m_terminalDisplay) return; + m_impl->m_terminalDisplay->setOpacity(level); } @@ -231,21 +233,33 @@ void QTermWidget::setTextCodec(QTextCodec *codec) m_impl->m_session->setCodec(codec); } -void QTermWidget::setColorScheme(int scheme) +void QTermWidget::setColorScheme(const QString & name) { - switch (scheme) { - case COLOR_SCHEME_WHITE_ON_BLACK: - m_impl->m_terminalDisplay->setColorTable(whiteonblack_color_table); - break; - case COLOR_SCHEME_GREEN_ON_BLACK: - m_impl->m_terminalDisplay->setColorTable(greenonblack_color_table); - break; - case COLOR_SCHEME_BLACK_ON_LIGHT_YELLOW: - m_impl->m_terminalDisplay->setColorTable(blackonlightyellow_color_table); - break; - default: //do nothing - break; - }; + const ColorScheme *cs; + // avoid legacy (int) solution + if (!availableColorSchemes().contains(name)) + cs = ColorSchemeManager::instance()->defaultColorScheme(); + else + cs = ColorSchemeManager::instance()->findColorScheme(name); + + if (! cs) + { + QMessageBox::information(this, + tr("Color Scheme Error"), + tr("Cannot load color scheme: %1").arg(name)); + return; + } + ColorEntry table[TABLE_COLORS]; + cs->getColorTable(table); + m_impl->m_terminalDisplay->setColorTable(table); +} + +QStringList QTermWidget::availableColorSchemes() +{ + QStringList ret; + foreach (const ColorScheme* cs, ColorSchemeManager::instance()->allColorSchemes()) + ret.append(cs->name()); + return ret; } void QTermWidget::setSize(int h, int v) diff --git a/lib/qtermwidget.h b/lib/qtermwidget.h index eb586b0..592fbd6 100644 --- a/lib/qtermwidget.h +++ b/lib/qtermwidget.h @@ -24,10 +24,6 @@ struct TermWidgetImpl; -enum COLOR_SCHEME { COLOR_SCHEME_WHITE_ON_BLACK = 1, - COLOR_SCHEME_GREEN_ON_BLACK, - COLOR_SCHEME_BLACK_ON_LIGHT_YELLOW - }; class QTermWidget : public QWidget { Q_OBJECT @@ -84,7 +80,8 @@ public: void setTextCodec(QTextCodec * codec); //Color scheme, default is white on black - void setColorScheme(int scheme); + void setColorScheme(const QString & name); + static QStringList availableColorSchemes(); //set size void setSize(int h, int v); diff --git a/lib/tools.cpp b/lib/tools.cpp new file mode 100644 index 0000000..a269200 --- /dev/null +++ b/lib/tools.cpp @@ -0,0 +1,80 @@ +#include "tools.h" + +#include +#include +#include + + +/*! Helper function to get possible location of layout files. +By default the KB_LAYOUT_DIR is used (linux/BSD/macports). +But in some cases (apple bundle) there can be more locations). +*/ +QString get_kb_layout_dir() +{ + qDebug() << __FILE__ << __FUNCTION__; + + QString rval = ""; + QString k(KB_LAYOUT_DIR); + QDir d(k); + + qDebug() << "default KB_LAYOUT_DIR: " << k; + + if (d.exists()) + rval = k.append("/"); + + // subdir in the app location + d.setPath(QCoreApplication::applicationDirPath() + "/kb-layouts/"); + //qDebug() << d.path(); + if (d.exists()) + rval = QCoreApplication::applicationDirPath() + "/kb-layouts/"; +#ifdef Q_WS_MAC + d.setPath(QCoreApplication::applicationDirPath() + "/../Resources/kb-layouts/"); + if (d.exists()) + rval = QCoreApplication::applicationDirPath() + "/../Resources/kb-layouts/"; +#endif +#ifdef QT_DEBUG + if(!rval.isEmpty()) { + qDebug() << "Using kb-layouts: " << rval; + } else { + qDebug() << "Cannot find kb-layouts in any location!"; + } +#endif + return rval; +} + +/*! Helper function to get possible location of layout files. +By default the COLORSCHEMES_DIR is used (linux/BSD/macports). +But in some cases (apple bundle) there can be more locations). +*/ +QString get_color_schemes_dir() +{ + qDebug() << __FILE__ << __FUNCTION__; + + QString rval = ""; + QString k(COLORSCHEMES_DIR); + QDir d(k); + + qDebug() << "default COLORSCHEMES_DIR: " << k; + + if (d.exists()) + rval = k.append("/"); + + // subdir in the app location + d.setPath(QCoreApplication::applicationDirPath() + "/color-schemes/"); + //qDebug() << d.path(); + if (d.exists()) + rval = QCoreApplication::applicationDirPath() + "/color-schemes/"; +#ifdef Q_WS_MAC + d.setPath(QCoreApplication::applicationDirPath() + "/../Resources/color-schemes/"); + if (d.exists()) + rval = QCoreApplication::applicationDirPath() + "/../Resources/color-schemes/"; +#endif +#ifdef QT_DEBUG + if(!rval.isEmpty()) { + qDebug() << "Using color-schemes: " << rval; + } else { + qDebug() << "Cannot find color-schemes in any location!"; + } +#endif + return rval; +} \ No newline at end of file diff --git a/lib/tools.h b/lib/tools.h new file mode 100644 index 0000000..b24d88f --- /dev/null +++ b/lib/tools.h @@ -0,0 +1,10 @@ +#ifndef TOOLS_H +#define TOOLS_H + +#include + +QString get_kb_layout_dir(); +QString get_color_schemes_dir(); + + +#endif