changeset 13381:7519e2efaf31

Incorporated files from OctaveDE project.
author Jacob Dawid <jacob.dawid@googlemail.com>
date Sat, 09 Apr 2011 00:23:46 +0200
parents 6fd5e06285da
children 9d5e5da5a297
files gui//Quint.pro gui//src/BlockArray.cpp gui//src/BlockArray.h gui//src/Character.h gui//src/CharacterColor.h gui//src/Emulation.cpp gui//src/Emulation.h gui//src/Filter.cpp gui//src/Filter.h gui//src/KeyboardTranslator.cpp gui//src/KeyboardTranslator.h gui//src/MainWindow.cpp gui//src/MainWindow.h gui//src/OctaveLink.cpp gui//src/ProcessInfo.cpp gui//src/ProcessInfo.h gui//src/Pty.cpp gui//src/Pty.h gui//src/QTerminalWidget.cpp gui//src/QTerminalWidget.h gui//src/Quint.cpp gui//src/Screen.cpp gui//src/Screen.h gui//src/Session.cpp gui//src/Session.h gui//src/TerminalCharacterDecoder.cpp gui//src/TerminalCharacterDecoder.h gui//src/TerminalDisplay.cpp gui//src/TerminalDisplay.h gui//src/TerminalMdiSubWindow.cpp gui//src/TerminalMdiSubWindow.h gui//src/Vt102Emulation.cpp gui//src/Vt102Emulation.h gui//src/k3process.cpp gui//src/kdecore_export.h gui//src/konsole_export.h gui//src/kprocess.cpp gui//src/kprocess.h gui//src/kprocess_p.h gui//src/kpty.cpp gui//src/kpty.h gui//src/kpty_export.h gui//src/kpty_p.h gui//src/kptydevice.cpp gui//src/kptydevice.h gui//src/kptyprocess.cpp gui//src/kptyprocess.h
diffstat 47 files changed, 8094 insertions(+), 3373 deletions(-) [+]
line wrap: on
line diff
--- a/gui//Quint.pro	Fri Apr 08 15:23:21 2011 +0200
+++ b/gui//Quint.pro	Sat Apr 09 00:23:46 2011 +0200
@@ -12,7 +12,7 @@
 TEMPLATE = app
 DEFINES += HAVE_POSIX_OPENPT
 INCLUDEPATH += src
-DESTDIR = bin
+DESTDIR = ../Quint/bin
 SOURCES +=\
         src/TerminalCharacterDecoder.cpp \
         src/KeyboardTranslator.cpp \
@@ -27,6 +27,9 @@
         src/Filter.cpp \
         src/Pty.cpp \
         src/kpty.cpp \
+        src/kptyprocess.cpp \
+        src/kprocess.cpp \
+        src/kptydevice.cpp \
         src/k3process.cpp \
         src/k3processcontroller.cpp \
         src/Session.cpp \
@@ -35,7 +38,8 @@
         src/TerminalMdiSubWindow.cpp \
         src/MainWindow.cpp \
         src/Quint.cpp \
-	src/OctaveLink.cpp
+        src/OctaveLink.cpp \
+        src/ProcessInfo.cpp
 
 HEADERS += \
         src/TerminalCharacterDecoder.h \
@@ -56,6 +60,10 @@
         src/Pty.h \
         src/kpty.h \
         src/kpty_p.h \
+        src/kptyprocess.h \
+        src/kprocess.h \
+        src/kprocess_p.h \
+        src/kptydevice.h \
         src/k3process.h \
         src/k3processcontroller.h \
         src/Session.h \
@@ -63,7 +71,11 @@
         src/QTerminalWidget.h \
         src/TerminalMdiSubWindow.h \
     	src/MainWindow.h \
-	src/OctaveLink.h
+        src/OctaveLink.h \
+        src/konsole_export.h \
+        src/ProcessInfo.h \
+        src/kpty_export.h \
+        src/kdecore_export.h
 
 INCFLAGS = -g3 $$system(mkoctfile -p INCFLAGS)
 LFLAGS = $$system(mkoctfile -p LFLAGS) \
--- a/gui//src/BlockArray.cpp	Fri Apr 08 15:23:21 2011 +0200
+++ b/gui//src/BlockArray.cpp	Sat Apr 09 00:23:46 2011 +0200
@@ -1,8 +1,6 @@
 /*
     This file is part of Konsole, an X terminal.
-    Copyright (C) 2000 by Stephan Kulow <coolo@kde.org>
-
-    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+    Copyright 2000 by Stephan Kulow <coolo@kde.org>
 
     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
@@ -18,14 +16,11 @@
     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 "BlockArray.h"
 
-#include <QtCore>
-
 // System
 #include <assert.h>
 #include <sys/mman.h>
@@ -33,6 +28,13 @@
 #include <unistd.h>
 #include <stdio.h>
 
+// KDE
+//#include <kde_file.h>
+//#include <kdebug.h>
+
+#define KDE_fseek ::fseek
+#define KDE_lseek ::lseek
+
 static int blocksize = 0;
 
 BlockArray::BlockArray()
@@ -65,7 +67,7 @@
     if (current >= size) current = 0;
 
     int rc;
-    rc = lseek(ion, current * blocksize, SEEK_SET); if (rc < 0) { perror("HistoryBuffer::add.seek"); setHistorySize(0); return size_t(-1); }
+    rc = KDE_lseek(ion, current * blocksize, SEEK_SET); if (rc < 0) { perror("HistoryBuffer::add.seek"); setHistorySize(0); return size_t(-1); }
     rc = write(ion, block, blocksize); if (rc < 0) { perror("HistoryBuffer::add.write"); setHistorySize(0); return size_t(-1); }
 
     length++;
@@ -113,7 +115,7 @@
         return lastmap;
 
     if (i > index) {
-        qDebug() << "BlockArray::at() i > index\n";
+        //kDebug(1211) << "BlockArray::at() i > index\n";
         return 0;
     }
     
@@ -197,7 +199,8 @@
         return false;
     } else {
         decreaseBuffer(newsize);
-        ftruncate(ion, length*blocksize);
+        if (ftruncate(ion, length*blocksize) == -1)
+            perror("ftruncate");
         size = newsize;
 
         return true;
@@ -206,14 +209,14 @@
 
 void moveBlock(FILE *fion, int cursor, int newpos, char *buffer2)
 {
-    int res = fseek(fion, cursor * blocksize, SEEK_SET);
+    int res = KDE_fseek(fion, cursor * blocksize, SEEK_SET);
     if (res)
         perror("fseek");
     res = fread(buffer2, blocksize, 1, fion);
     if (res != 1)
         perror("fread");
 
-    res = fseek(fion, newpos * blocksize, SEEK_SET);
+    res = KDE_fseek(fion, newpos * blocksize, SEEK_SET);
     if (res)
         perror("fseek");
     res = fwrite(buffer2, blocksize, 1, fion);
@@ -292,8 +295,8 @@
     FILE *fion = fdopen(dup(ion), "w+b");
     if (!fion) {
         perror("fdopen/dup");
-	delete [] buffer1;
-	delete [] buffer2;
+    delete [] buffer1;
+    delete [] buffer2;
         return;
     }
 
@@ -302,7 +305,7 @@
     {
         // free one block in chain
         int firstblock = (offset + i) % size;
-        res = fseek(fion, firstblock * blocksize, SEEK_SET);
+        res = KDE_fseek(fion, firstblock * blocksize, SEEK_SET);
         if (res)
             perror("fseek");
         res = fread(buffer1, blocksize, 1, fion);
@@ -315,7 +318,7 @@
             newpos = (cursor - offset + size) % size;
             moveBlock(fion, cursor, newpos, buffer2);
         }
-        res = fseek(fion, i * blocksize, SEEK_SET);
+        res = KDE_fseek(fion, i * blocksize, SEEK_SET);
         if (res)
             perror("fseek");
         res = fwrite(buffer1, blocksize, 1, fion);
--- a/gui//src/BlockArray.h	Fri Apr 08 15:23:21 2011 +0200
+++ b/gui//src/BlockArray.h	Sat Apr 09 00:23:46 2011 +0200
@@ -1,8 +1,6 @@
 /*
     This file is part of Konsole, an X terminal.
-    Copyright (C) 2000 by Stephan Kulow <coolo@kde.org>
-   
-    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+    Copyright 2000 by Stephan Kulow <coolo@kde.org>
 
     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
@@ -35,6 +33,7 @@
     unsigned char data[ENTRIES];
     size_t size;
 };
+
 // ///////////////////////////////////////////////////////
 
 class BlockArray {
@@ -54,7 +53,7 @@
     * adds the Block at the end of history.
     * This may drop other blocks.
     *
-    * The ownership on the block is transfered.
+    * The ownership on the block is transferred.
     * An unique index number is returned for accessing
     * it later (if not yet dropped then)
     *
@@ -113,5 +112,6 @@
 
     int ion;
     size_t length;
+
 };
 #endif
--- a/gui//src/Character.h	Fri Apr 08 15:23:21 2011 +0200
+++ b/gui//src/Character.h	Sat Apr 09 00:23:46 2011 +0200
@@ -1,10 +1,8 @@
 /*
     This file is part of Konsole, KDE's terminal.
     
-    Copyright (C) 2007 by Robert Knight <robertknight@gmail.com>
-    Copyright (C) 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
-
-    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+    Copyright 2007-2008 by Robert Knight <robertknight@gmail.com>
+    Copyright 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
 
     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,10 +31,10 @@
 
 typedef unsigned char LineProperty;
 
-static const int LINE_DEFAULT		= 0;
-static const int LINE_WRAPPED 	 	= (1 << 0);
-static const int LINE_DOUBLEWIDTH  	= (1 << 1);
-static const int LINE_DOUBLEHEIGHT	= (1 << 2);
+static const int LINE_DEFAULT        = 0;
+static const int LINE_WRAPPED          = (1 << 0);
+static const int LINE_DOUBLEWIDTH      = (1 << 1);
+static const int LINE_DOUBLEHEIGHT    = (1 << 2);
 
 #define DEFAULT_RENDITION  0
 #define RE_BOLD            (1 << 0)
@@ -101,9 +99,14 @@
    * it is drawn with the specified @p palette, independent of whether
    * or not the character has the RE_BOLD rendition flag. 
    */
-  bool   isBold(const ColorEntry* base) const;
+  ColorEntry::FontWeight fontWeight(const ColorEntry* base) const;
   
   /** 
+   * returns true if the format (color, rendition flag) of the compared characters is equal
+   */
+  bool equalsFormat(const Character &other) const;
+
+  /** 
    * Compares two characters and returns true if they have the same unicode character value,
    * rendition and colors.
    */
@@ -139,12 +142,22 @@
           base[backgroundColor._u+2+(backgroundColor._v?BASE_COLORS:0)].transparent);
 }
 
-inline bool Character::isBold(const ColorEntry* base) const
+inline bool Character::equalsFormat(const Character& other) const
 {
-  return ((backgroundColor._colorSpace == COLOR_SPACE_DEFAULT) &&
-            base[backgroundColor._u+0+(backgroundColor._v?BASE_COLORS:0)].bold)
-      || ((backgroundColor._colorSpace == COLOR_SPACE_SYSTEM) &&
-            base[backgroundColor._u+2+(backgroundColor._v?BASE_COLORS:0)].bold);
+  return 
+    backgroundColor==other.backgroundColor &&
+    foregroundColor==other.foregroundColor &&
+    rendition==other.rendition;
+}	
+
+inline ColorEntry::FontWeight Character::fontWeight(const ColorEntry* base) const
+{
+    if (backgroundColor._colorSpace == COLOR_SPACE_DEFAULT)
+        return base[backgroundColor._u+0+(backgroundColor._v?BASE_COLORS:0)].fontWeight;
+    else if (backgroundColor._colorSpace == COLOR_SPACE_SYSTEM)
+        return base[backgroundColor._u+2+(backgroundColor._v?BASE_COLORS:0)].fontWeight;
+    else
+        return ColorEntry::UseCurrentFormat;
 }
 
 extern unsigned short vt100_graphics[32];
@@ -201,5 +214,7 @@
     QHash<ushort,ushort*> extendedCharTable;
 };
 
+Q_DECLARE_TYPEINFO(Character, Q_MOVABLE_TYPE);
+
 #endif // CHARACTER_H
 
--- a/gui//src/CharacterColor.h	Fri Apr 08 15:23:21 2011 +0200
+++ b/gui//src/CharacterColor.h	Sat Apr 09 00:23:46 2011 +0200
@@ -1,10 +1,8 @@
 /*
     This file is part of Konsole, KDE's terminal.
     
-    Copyright (C) 2007 by Robert Knight <robertknight@gmail.com>
-    Copyright (C) 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
-
-    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+    Copyright 2007-2008 by Robert Knight <robertknight@gmail.com>
+    Copyright 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
 
     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,6 +26,9 @@
 // Qt
 #include <QtGui/QColor>
 
+//#include <kdemacros.h>
+#define KDE_NO_EXPORT
+
 /** 
  * An entry in a terminal display's color palette. 
  *
@@ -44,20 +45,35 @@
 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 b Specifies that text drawn with this color should be bold.
+   * @param weight Specifies the font weight to use when drawing text with this color. 
    */
-  ColorEntry(QColor c, bool tr, bool b) : color(c), transparent(tr), bold(b) {}
+  ColorEntry(QColor c, bool tr, FontWeight weight = UseCurrentFormat) 
+          : color(c), transparent(tr), fontWeight(weight) {}
 
   /**
    * Constructs a new color palette entry with an undefined color, and
    * with the transparent and bold flags set to false.
    */ 
-  ColorEntry() : transparent(false), bold(false) {} 
+  ColorEntry() : transparent(false), fontWeight(UseCurrentFormat) {} 
  
   /**
    * Sets the color, transparency and boldness of this color to those of @p rhs.
@@ -66,7 +82,7 @@
   { 
        color = rhs.color; 
        transparent = rhs.transparent; 
-       bold = rhs.bold; 
+       fontWeight = rhs.fontWeight; 
   }
 
   /** The color value of this entry for display. */
@@ -78,10 +94,10 @@
    */
   bool   transparent;
   /**
-   * If true characters drawn using this color should be bold.
+   * 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.
    */
-  bool   bold;        
+  FontWeight fontWeight;        
 };
 
 
@@ -99,25 +115,7 @@
 //a standard set of colors using black text on a white background.
 //defined in TerminalDisplay.cpp
 
-static const ColorEntry base_color_table[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.
-{
-  // Fixme: could add faint colors here, also.
-  // normal
-  ColorEntry(QColor(0x00,0x00,0x00), 0, 0 ), ColorEntry( QColor(0xB2,0xB2,0xB2), 1, 0 ), // Dfore, Dback
-  ColorEntry(QColor(0x00,0x00,0x00), 0, 0 ), ColorEntry( QColor(0xB2,0x18,0x18), 0, 0 ), // Black, Red
-  ColorEntry(QColor(0x18,0xB2,0x18), 0, 0 ), ColorEntry( QColor(0xB2,0x68,0x18), 0, 0 ), // Green, Yellow
-  ColorEntry(QColor(0x18,0x18,0xB2), 0, 0 ), ColorEntry( QColor(0xB2,0x18,0xB2), 0, 0 ), // Blue, Magenta
-  ColorEntry(QColor(0x18,0xB2,0xB2), 0, 0 ), ColorEntry( QColor(0xB2,0xB2,0xB2), 0, 0 ), // Cyan, White
-  // intensiv
-  ColorEntry(QColor(0x00,0x00,0x00), 0, 1 ), ColorEntry( QColor(0xFF,0xFF,0xFF), 1, 0 ),
-  ColorEntry(QColor(0x68,0x68,0x68), 0, 0 ), ColorEntry( QColor(0xFF,0x54,0x54), 0, 0 ),
-  ColorEntry(QColor(0x54,0xFF,0x54), 0, 0 ), ColorEntry( QColor(0xFF,0xFF,0x54), 0, 0 ),
-  ColorEntry(QColor(0x54,0x54,0xFF), 0, 0 ), ColorEntry( QColor(0xFF,0x54,0xFF), 0, 0 ),
-  ColorEntry(QColor(0x54,0xFF,0xFF), 0, 0 ), ColorEntry( QColor(0xFF,0xFF,0xFF), 0, 0 )
-};
+extern const ColorEntry base_color_table[TABLE_COLORS] KDE_NO_EXPORT;
 
 /* CharacterColor is a union of the various color spaces.
 
@@ -213,7 +211,7 @@
   void toggleIntensive();
 
   /** 
-   * Returns the color within the specified color @palette
+   * Returns the color within the specified color @p palette
    *
    * The @p palette is only used if this color is one of the 16 system colors, otherwise
    * it is ignored.
@@ -242,14 +240,14 @@
 
 inline bool operator == (const CharacterColor& a, const CharacterColor& b)
 { 
-  return *reinterpret_cast<const quint32*>(&a._colorSpace) == 
-         *reinterpret_cast<const quint32*>(&b._colorSpace);
+    return     a._colorSpace == b._colorSpace &&
+            a._u == b._u &&
+            a._v == b._v &&
+            a._w == b._w;
 }
-
 inline bool operator != (const CharacterColor& a, const CharacterColor& b)
 {
-  return *reinterpret_cast<const quint32*>(&a._colorSpace) != 
-         *reinterpret_cast<const quint32*>(&b._colorSpace);
+    return !operator==(a,b);
 }
 
 inline const QColor color256(quint8 u, const ColorEntry* base)
@@ -259,9 +257,9 @@
   if (u <   8) return base[u+2+BASE_COLORS].color; u -= 8;
 
   //  16..231: 6x6x6 rgb color cube
-  if (u < 216) return QColor(255*((u/36)%6)/5,
-                             255*((u/ 6)%6)/5,
-                             255*((u/ 1)%6)/5); u -= 216;
+  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);
--- a/gui//src/Emulation.cpp	Fri Apr 08 15:23:21 2011 +0200
+++ b/gui//src/Emulation.cpp	Sat Apr 09 00:23:46 2011 +0200
@@ -1,11 +1,7 @@
 /*
-    This file is part of Konsole, an X terminal.
-
-    Copyright (C) 2007 Robert Knight <robertknight@gmail.com> 
-    Copyright (C) 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
-    Copyright (C) 1996 by Matthias Ettrich <ettrich@kde.org>
-
-    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+    Copyright 2007-2008 Robert Knight <robertknight@gmail.com> 
+    Copyright 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
+    Copyright 1996 by Matthias Ettrich <ettrich@kde.org>
 
     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,23 +39,15 @@
 
 #include <QtCore/QTime>
 
+// KDE
+//#include <kdebug.h>
+
 // Konsole
 #include "KeyboardTranslator.h"
 #include "Screen.h"
 #include "TerminalCharacterDecoder.h"
 #include "ScreenWindow.h"
 
-/* ------------------------------------------------------------------------- */
-/*                                                                           */
-/*                               Emulation                                  */
-/*                                                                           */
-/* ------------------------------------------------------------------------- */
-
-//#define CNTL(c) ((c)-'@')
-
-/*!
-*/
-
 Emulation::Emulation() :
   _currentScreen(0),
   _codec(0),
@@ -67,7 +55,6 @@
   _keyTranslator(0),
   _usesMouse(false)
 {
-
   // create screens with a default size
   _screen[0] = new Screen(40,80);
   _screen[1] = new Screen(40,80);
@@ -105,9 +92,6 @@
     return window;
 }
 
-/*!
-*/
-
 Emulation::~Emulation()
 {
   QListIterator<ScreenWindow*> windowIter(_windows);
@@ -122,23 +106,15 @@
   delete _decoder;
 }
 
-/*! change between primary and alternate _screen
-*/
-
 void Emulation::setScreen(int n)
 {
   Screen *old = _currentScreen;
-  _currentScreen = _screen[n&1];
+  _currentScreen = _screen[n & 1];
   if (_currentScreen != old) 
   {
-     old->setBusySelecting(false);
-
-     // tell all windows onto this emulation to switch to the newly active _screen
-     QListIterator<ScreenWindow*> windowIter(_windows);
-     while ( windowIter.hasNext() )
-     {
-         windowIter.next()->setScreen(_currentScreen);
-     }
+     // tell all windows onto this emulation to switch to the newly active screen
+     foreach(ScreenWindow* window,_windows)
+         window->setScreen(_currentScreen);
   }
 }
 
@@ -153,16 +129,18 @@
   showBulk();
 }
 
-const HistoryType& Emulation::history()
+const HistoryType& Emulation::history() const
 {
   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();
 
@@ -180,26 +158,17 @@
 void Emulation::setKeyBindings(const QString& name)
 {
   _keyTranslator = KeyboardTranslatorManager::instance()->findTranslator(name);
+  if (!_keyTranslator)
+  {
+      _keyTranslator = KeyboardTranslatorManager::instance()->defaultTranslator();
+  }
 }
 
-QString Emulation::keyBindings()
+QString Emulation::keyBindings() const
 {
   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
@@ -207,25 +176,16 @@
   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 '\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->ShowCharacter(c);            break;
+    default        : _currentScreen->displayCharacter(c);         break;
   };
 }
 
-/* ------------------------------------------------------------------------- */
-/*                                                                           */
-/*                             Keyboard Handling                             */
-/*                                                                           */
-/* ------------------------------------------------------------------------- */
-
-/*!
-*/
-
 void Emulation::sendKeyEvent( QKeyEvent* ev )
 {
   emit stateSet(NOTIFYNORMAL);
@@ -233,9 +193,7 @@
   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());
+    // We should do a conversion here
     emit sendData(ev->text().toUtf8(),ev->text().length());
   }
 }
@@ -250,8 +208,6 @@
     // 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
@@ -259,36 +215,34 @@
 
 void Emulation::receiveData(const char* text, int length)
 {
-	emit stateSet(NOTIFYACTIVITY);
+    emit stateSet(NOTIFYACTIVITY);
 
-	bufferedUpdate();
-    	
+    bufferedUpdate();
+        
     QString unicodeText = _decoder->toUnicode(text,length);
 
-	//send characters to terminal emulator
-	for (int i=0;i<unicodeText.length();i++)
-	{
-		receiveChar(unicodeText[i].unicode());
-	}
+    //send characters to terminal emulator
+    for (int i=0;i<unicodeText.length();i++)
+        receiveChar(unicodeText[i].unicode());
 
-	//look for z-modem indicator
-	//-- someone who understands more about z-modems that I do may be able to move
-	//this check into the above for loop?
-	for (int i=0;i<length;i++)
-	{
-		if (text[i] == '\030')
-    		{
-      			if ((length-i-1 > 3) && (strncmp(text+i+1, "B00", 3) == 0))
-      				emit zmodemDetected();
-    		}
-	}
+    //look for z-modem indicator
+    //-- someone who understands more about z-modems that I do may be able to move
+    //this check into the above for loop?
+    for (int i=0;i<length;i++)
+    {
+        if (text[i] == '\030')
+        {
+            if ((length-i-1 > 3) && (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
@@ -328,72 +282,27 @@
     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 , 
                                int startLine ,
                                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();
@@ -416,16 +325,24 @@
    }
 }
 
-char Emulation::getErase() const
+char Emulation::eraseChar() const
 {
   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;
+
+  QSize screenSize[2] = { QSize(_screen[0]->getColumns(),
+                                _screen[0]->getLines()),
+                          QSize(_screen[1]->getColumns(),
+                                _screen[1]->getLines()) };
+  QSize newSize(columns,lines);
+
+  if (newSize == screenSize[0] && newSize == screenSize[1])
+    return;    
 
   _screen[0]->resizeImage(lines,columns);
   _screen[1]->resizeImage(lines,columns);
@@ -435,7 +352,7 @@
   bufferedUpdate();
 }
 
-QSize Emulation::imageSize()
+QSize Emulation::imageSize() const
 {
   return QSize(_currentScreen->getColumns(), _currentScreen->getLines());
 }
@@ -537,5 +454,3 @@
 ExtendedCharTable ExtendedCharTable::instance;
 
 
-//#include "moc_Emulation.cpp"
-
--- a/gui//src/Emulation.h	Fri Apr 08 15:23:21 2011 +0200
+++ b/gui//src/Emulation.h	Sat Apr 09 00:23:46 2011 +0200
@@ -1,10 +1,8 @@
 /*
     This file is part of Konsole, an X terminal.
     
-    Copyright (C) 2007 by Robert Knight <robertknight@gmail.com>
-    Copyright (C) 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
-
-    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+    Copyright 2007-2008 by Robert Knight <robertknight@gmail.com>
+    Copyright 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
 
     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,10 +28,14 @@
 
 // Qt 
 #include <QtGui/QKeyEvent>
+//#include <QPointer>
 #include <QtCore/QTextCodec>
 #include <QtCore/QTextStream>
 #include <QtCore/QTimer>
 
+// Konsole
+#include "konsole_export.h"
+
 class KeyboardTranslator;
 class HistoryType;
 class Screen;
@@ -114,7 +116,7 @@
  * how long the emulation has been active/idle for and also respond to
  * a 'bell' event in different ways.
  */
-class Emulation : public QObject
+class KONSOLEPRIVATE_EXPORT Emulation : public QObject
 { 
 Q_OBJECT
 
@@ -132,14 +134,13 @@
   ScreenWindow* createWindow();
 
   /** Returns the size of the screen image which the emulation produces */
-  QSize imageSize();
+  QSize imageSize() const;
 
   /**
    * Returns the total number of lines, including those stored in the history.
    */ 
-  int lineCount();
+  int lineCount() const;
 
-  
   /** 
    * Sets the history store used by this emulation.  When new lines
    * are added to the output, older lines at the top of the screen are transferred to a history
@@ -150,7 +151,7 @@
    */
   void setHistory(const HistoryType&);
   /** Returns the history store used by this emulation.  See setHistory() */
-  const HistoryType& history();
+  const HistoryType& history() const;
   /** Clears the history scroll. */
   void clearHistory();
 
@@ -162,13 +163,13 @@
    * @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
+   * @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() { return _codec; }
+  const QTextCodec* codec() const { return _codec; }
   /** Sets the codec used to decode incoming characters.  */
   void setCodec(const QTextCodec*);
 
@@ -177,11 +178,12 @@
    * Returns true if the current codec used to decode incoming
    * characters is UTF-8
    */
-  bool utf8() { Q_ASSERT(_codec); return _codec->mibEnum() == 106; }
+  bool utf8() const
+  { Q_ASSERT(_codec); return _codec->mibEnum() == 106; }
   
 
   /** TODO Document me */
-  virtual char getErase() const;
+  virtual char eraseChar() const;
 
   /** 
    * Sets the key bindings used to key events
@@ -193,7 +195,7 @@
    * Returns the name of the emulation's current key bindings.
    * See setKeyBindings()
    */
-  QString keyBindings();
+  QString keyBindings() const;
 
   /** 
    * Copies the current image into the history and clears the screen.
@@ -265,7 +267,7 @@
    * standard input of the terminal.
    *
    * @param data The buffer of data ready to be sent
-   * @paran len The length of @p data in bytes
+   * @param len The length of @p data in bytes
    */
   void sendData(const char* data,int len);
 
@@ -352,7 +354,7 @@
    * <li>1 - Set window icon text to @p newTitle</li>
    * <li>2 - Set session title to @p newTitle</li>
    * <li>11 - Set the session's default background color to @p newTitle,
-   *         where @p newTitle can be an HTML-style string (#RRGGBB) or a named
+   *         where @p newTitle can be an HTML-style string ("#RRGGBB") or a named
    *         color (eg 'red', 'blue').  
    *         See http://doc.trolltech.com/4.2/qcolor.html#setNamedColor for more
    *         details.
@@ -386,11 +388,18 @@
    */
   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 setMode(int mode) = 0;
   virtual void resetMode(int mode) = 0;
    
- /** 
+  /** 
    * Processes an incoming character.  See receiveData()
    * @p ch A unicode character code. 
    */
@@ -428,7 +437,6 @@
   //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:
@@ -448,7 +456,6 @@
   void usesMouseChanged(bool usesMouse);
 
 private:
-
   bool _usesMouse;
   QTimer _bulkTimer1;
   QTimer _bulkTimer2;
--- a/gui//src/Filter.cpp	Fri Apr 08 15:23:21 2011 +0200
+++ b/gui//src/Filter.cpp	Sat Apr 09 00:23:46 2011 +0200
@@ -1,7 +1,5 @@
 /*
-    Copyright (C) 2007 by Robert Knight <robertknight@gmail.com>
-
-    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+    Copyright 2007-2008 by Robert Knight <robertknight@gmail.com>
 
     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,12 +28,18 @@
 #include <QtGui/QApplication>
 #include <QtGui/QClipboard>
 #include <QtCore/QString>
-
+#include <QtCore/QTextStream>
 #include <QtCore/QSharedData>
-#include <QtCore>
+#include <QtCore/QFile>
+
+// KDE
+//#include <KLocale>
+//#include <KRun>
 
 // Konsole
 #include "TerminalCharacterDecoder.h"
+#include "konsole_wcwidth.h"
+#include "konsole_export.h"
 
 FilterChain::~FilterChain()
 {
@@ -126,19 +130,15 @@
 
 void TerminalImageFilterChain::setImage(const Character* const image , int lines , int columns, const QVector<LineProperty>& lineProperties)
 {
-//qDebug("%s %d", __FILE__, __LINE__);
     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();
     QList<int>* newLinePositions = new QList<int>();
@@ -170,10 +170,9 @@
         // terminal image to avoid adding this imaginary character for wrapped
         // lines
         if ( !(lineProperties.value(i,LINE_DEFAULT) & LINE_WRAPPED) )
-        	lineStream << QChar('\n');
+            lineStream << QChar('\n');
     }
     decoder.end();
-//    qDebug("%s %d", __FILE__, __LINE__);
 }
 
 Filter::Filter() :
@@ -210,29 +209,28 @@
 
     for (int i = 0 ; i < _linePositions->count() ; i++)
     {
-        //kDebug() << "line position at " << i << " = " << _linePositions[i];
         int nextLine = 0;
 
         if ( i == _linePositions->count()-1 )
-        {
             nextLine = _buffer->length() + 1;
-        }
         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 ) 
         {
             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)
+{
+    _linePositions << _buffer.length();
+    _buffer.append(text);
+}*/
 
 const QString* Filter::buffer()
 {
@@ -350,7 +348,10 @@
 {
     return _searchText;
 }
-
+/*void RegExpFilter::reset(int)
+{
+    _buffer = QString();
+}*/
 void RegExpFilter::process()
 {
     int pos = 0;
@@ -370,21 +371,14 @@
 
         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,
                                            endLine,endColumn);
             spot->setCapturedTexts(_searchText.capturedTexts());
@@ -393,7 +387,8 @@
             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;
         }
     }    
 }
@@ -451,8 +446,6 @@
 
     if ( actionName == "copy-action" )
     {
-        //kDebug() << "Copying url to clipboard:" << url;
-
         QApplication::clipboard()->setText(url);
         return;
     }
@@ -473,7 +466,7 @@
             url.prepend("mailto:");
         }
     
-//        new KRun(url,QApplication::activeWindow());
+        //new KRun(url,QApplication::activeWindow());
     }
 }
 
@@ -519,20 +512,20 @@
 
     if ( kind == StandardUrl )
     {
-        openAction->setText(("Open Link"));
-        copyAction->setText(("Copy Link Address"));
+        openAction->setText(i18n("Open Link"));
+        copyAction->setText(i18n("Copy Link Address"));
     }
     else if ( kind == Email )
     {
-        openAction->setText(("Send Email To..."));
-        copyAction->setText(("Copy Email Address"));
+        openAction->setText(i18n("Send Email To..."));
+        copyAction->setText(i18n("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()) );
--- a/gui//src/Filter.h	Fri Apr 08 15:23:21 2011 +0200
+++ b/gui//src/Filter.h	Sat Apr 09 00:23:46 2011 +0200
@@ -1,7 +1,5 @@
 /*
-    Copyright (C) 2007 by Robert Knight <robertknight@gmail.com>
-
-    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+    Copyright 2007-2008 by Robert Knight <robertknight@gmail.com>
 
     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,6 +31,7 @@
 // Local
 #include "Character.h"
 
+
 /**
  * A filter processes blocks of text looking for certain patterns (such as URLs or keywords from a list)
  * and marks the areas which match the filter's patterns as 'hotspots'.
@@ -367,12 +366,14 @@
      * @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<LineProperty>& lineProperties);  
+                  const QVector<LineProperty>& lineProperties);  
 
 private:
     QString* _buffer;
     QList<int>* _linePositions;
 };
+
 #endif //FILTER_H
--- a/gui//src/KeyboardTranslator.cpp	Fri Apr 08 15:23:21 2011 +0200
+++ b/gui//src/KeyboardTranslator.cpp	Sat Apr 09 00:23:46 2011 +0200
@@ -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 <robertknight@gmail.com>
-
-    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+    Copyright 2007-2008 by Robert Knight <robertknight@gmail.com>
 
     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
@@ -32,20 +30,24 @@
 #include <QtCore/QBuffer>
 #include <QtCore/QFile>
 #include <QtCore/QFileInfo>
-#include <QtCore>
-#include <QtGui>
-
-
-//this is for default REALLY fallback translator.
+#include <QtCore/QTextStream>
+#include <QtGui/QKeySequence>
+#include <QtCore/QDir>
+#include <QtCore/QStringList>
+#include <QtCore/QDebug>
+#include <QtCore/QDataStream>
 
-//const char* KeyboardTranslatorManager::defaultTranslatorText =
-//#include "DefaultTranslatorText.h"
-//;
+// KDE
+#include "konsole_export.h"
+//#include <KDebug>
+//#include <KLocale>
+//#include <KStandardDirs>
+//#include "kdebug.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)
@@ -53,22 +55,25 @@
 }
 KeyboardTranslatorManager::~KeyboardTranslatorManager()
 {
-    qDeleteAll(_translators.values());
+    qDeleteAll(_translators);
 }
 QString KeyboardTranslatorManager::findTranslatorPath(const QString& name)
 {
-    return QString("kb-layouts/" + name + ".keytab");
+  return QString("kb-layouts/" + name + ".keytab");
+  // return KGlobal::dirs()->findResource("data","konsole/"+name+".keytab");
 }
 void KeyboardTranslatorManager::findTranslators()
 {
+  //QStringList list = KGlobal::dirs()->findAllResources("data",
+  //                                                     "konsole/*.keytab",
+  //                                                     KStandardDirs::NoDuplicates);
+
     QDir dir("kb-layouts/");
     QStringList filters;
     filters << "*.keytab";
     dir.setNameFilters(filters);
-    QStringList list = dir.entryList(filters); //(".keytab"); // = KGlobal::dirs()->findAllResources("data",
-                        //                                 "konsole/*.keytab",
-                        //                                 KStandardDirs::NoDuplicates);
-    list = dir.entryList(filters);
+    QStringList list = dir.entryList(filters);
+
     // 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
@@ -79,10 +84,10 @@
 
         QString name = QFileInfo(translatorPath).baseName();
        
-        if ( !_translators.contains(name) ) {
+        if ( !_translators.contains(name) ) 
             _translators.insert(name,0);
-	}
     }
+
     _haveLoadedAll = true;
 }
 
@@ -91,37 +96,32 @@
     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);
 
     if ( translator != 0 )
         _translators[name] = translator;
-    else if ( !name.isEmpty() )
-        qWarning() << "Unable to load translator" << name;
+    //else if ( !name.isEmpty() )
+    //  kWarning() << "Unable to load translator" << name;
 
     return translator;
 }
 
 bool KeyboardTranslatorManager::saveTranslator(const KeyboardTranslator* translator)
 {
-    const QString path = ".keytab";// = KGlobal::dirs()->saveLocation("data","konsole/")+translator->name()
-//           +".keytab";
+  //const QString path = KGlobal::dirs()->saveLocation("data","konsole/")+translator->name()
+  //         +".keytab";
+  const QString path = ".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();
-
+        //kWarning() << "Unable to save keyboard translation:"
+         //          << destination.errorString();
         return false;
     }
 
@@ -144,7 +144,6 @@
     const QString& path = findTranslatorPath(name);
 
     QFile source(path); 
-    
     if (name.isEmpty() || !source.open(QIODevice::ReadOnly | QIODevice::Text))
         return 0;
 
@@ -153,14 +152,17 @@
 
 const KeyboardTranslator* KeyboardTranslatorManager::defaultTranslator()
 {
-    qDebug() << "Loading default translator from text";
-    QBuffer textBuffer;
-    textBuffer.setData(defaultTranslatorText,strlen(defaultTranslatorText));
-
-    if (!textBuffer.open(QIODevice::ReadOnly))
-        return 0;
-
-    return loadTranslator(&textBuffer,"fallback");
+    // 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 translator;
 }
 
 KeyboardTranslator* KeyboardTranslatorManager::loadTranslator(QIODevice* source,const QString& name)
@@ -168,10 +170,8 @@
     KeyboardTranslator* translator = new KeyboardTranslator(name);
     KeyboardTranslatorReader reader(source);
     translator->setDescription( reader.description() );
-    
-    while ( reader.hasNextEntry() ) {
+    while ( reader.hasNextEntry() )
         translator->addEntry(reader.nextEntry());
-    }	
 
     source->close();
 
@@ -204,7 +204,6 @@
 void KeyboardTranslatorWriter::writeEntry( const KeyboardTranslator::Entry& entry )
 {
     QString result;
-
     if ( entry.command() != KeyboardTranslator::NoCommand )
         result = entry.resultToString();
     else
@@ -240,14 +239,11 @@
    // read input until we find the description
    while ( _description.isEmpty() && !source->atEnd() )
    {
-        const QList<Token>& tokens = tokenize( QString(source->readLine()) );
-   
+        QList<Token> tokens = tokenize( QString(source->readLine()) );
         if ( !tokens.isEmpty() && tokens.first().type == Token::TitleKeyword )
-        {
-            _description = (tokens[1].text.toUtf8());
-        }
+            _description = i18n(tokens[1].text.toLatin1().data());
    }
-
+   // read first entry (if any)
    readNext();
 }
 void KeyboardTranslatorReader::readNext() 
@@ -283,8 +279,8 @@
             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))
+                //  kWarning() << "Command" << tokens[2].text << "not understood.";
             }
 
             KeyboardTranslator::Entry newEntry;
@@ -309,8 +305,8 @@
 
 bool KeyboardTranslatorReader::parseAsCommand(const QString& text,KeyboardTranslator::Command& command) 
 {
-	if ( text.compare("erase",Qt::CaseInsensitive) == 0 )
-		command = KeyboardTranslator::EraseCommand;
+    if ( text.compare("erase",Qt::CaseInsensitive) == 0 )
+        command = KeyboardTranslator::EraseCommand;
     else if ( text.compare("scrollpageup",Qt::CaseInsensitive) == 0 )
         command = KeyboardTranslator::ScrollPageUpCommand;
     else if ( text.compare("scrollpagedown",Qt::CaseInsensitive) == 0 )
@@ -322,9 +318,9 @@
     else if ( text.compare("scrolllock",Qt::CaseInsensitive) == 0 )
         command = KeyboardTranslator::ScrollLockCommand;
     else
-    	return false;
+        return false;
 
-	return true;
+    return true;
 }
 
 bool KeyboardTranslatorReader::decodeSequence(const QString& text,
@@ -346,13 +342,16 @@
     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() )
         {
             endOfItem = false;
             buffer.append(ch);
+        } else if ( isFirstLetter )
+        {
+            buffer.append(ch);
         }
 
         if ( (endOfItem || isLastLetter) && !buffer.isEmpty() )
@@ -377,8 +376,8 @@
             }
             else if ( parseAsKeyCode(buffer,itemKeyCode) )
                 keyCode = itemKeyCode;
-            else
-                qDebug() << "Unable to parse key binding item:" << buffer;
+            //else
+          //      kWarning() << "Unable to parse key binding item:" << buffer;
 
             buffer.clear();
         }
@@ -409,8 +408,8 @@
         modifier = Qt::AltModifier;
     else if ( item == "meta" )
         modifier = Qt::MetaModifier;
-	else if ( item == "keypad" )
-		modifier = Qt::KeypadModifier;
+    else if ( item == "keypad" )
+        modifier = Qt::KeypadModifier;
     else
         return false;
 
@@ -418,7 +417,7 @@
 }
 bool KeyboardTranslatorReader::parseAsStateFlag(const QString& item , KeyboardTranslator::State& flag)
 {
-    if ( item == "appcukeys" )
+    if ( item == "appcukeys" || item == "appcursorkeys" )
         flag = KeyboardTranslator::CursorKeysState;
     else if ( item == "ansi" )
         flag = KeyboardTranslator::AnsiState;
@@ -426,8 +425,10 @@
         flag = KeyboardTranslator::NewLineState;
     else if ( item == "appscreen" )
         flag = KeyboardTranslator::AlternateScreenState;
-    else if ( item == "anymod" )
+    else if ( item == "anymod" || item == "anymodifier" )
         flag = KeyboardTranslator::AnyModifierState;
+    else if ( item == "appkeypad" )
+        flag = KeyboardTranslator::ApplicationKeypadState;
     else
         return false;
 
@@ -442,7 +443,7 @@
 
         if ( sequence.count() > 1 )
         {
-            qDebug() << "Unhandled key codes in sequence: " << item;
+            //kWarning() << "Unhandled key codes in sequence: " << item;
         }
     }
     // additional cases implemented for backwards compatibility with KDE 3
@@ -471,23 +472,21 @@
     entryString.append(condition);
     entryString.append(" : ");
 
-	// if 'result' is the name of a command then the entry result will be that command,
-	// 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))
-    	entryString.append(result);
-	else
-		entryString.append('\"' + result + '\"');
+    // if 'result' is the name of a command then the entry result will be that command,
+    // 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))
+        entryString.append(result);
+    else
+        entryString.append('\"' + result + '\"');
 
     QByteArray array = entryString.toUtf8();
-
-    KeyboardTranslator::Entry entry;
-
     QBuffer buffer(&array);
     buffer.open(QIODevice::ReadOnly);
     KeyboardTranslatorReader reader(&buffer);
 
+    KeyboardTranslator::Entry entry;
     if ( reader.hasNextEntry() )
         entry = reader.nextEntry();
 
@@ -497,12 +496,8 @@
 KeyboardTranslator::Entry KeyboardTranslatorReader::nextEntry() 
 {
     Q_ASSERT( _hasNext );
-
-
     KeyboardTranslator::Entry entry = _nextEntry;
-
     readNext();
-
     return entry;
 }
 bool KeyboardTranslatorReader::parseError()
@@ -511,19 +506,32 @@
 }
 QList<KeyboardTranslatorReader::Token> 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<Token> list;
-
-    if ( text.isEmpty() || comment.exactMatch(text) )
+    if ( text.isEmpty() ) 
     {
         return list;
     }
@@ -553,11 +561,11 @@
             // 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;
+        //kWarning() << "Line in keyboard translator file could not be understood:" << text;
     }
 
     return list;
@@ -596,7 +604,7 @@
 
 bool KeyboardTranslator::Entry::matches(int keyCode , 
                                         Qt::KeyboardModifiers modifiers,
-                                        States state) const
+                                        States testState) const
 {
     if ( _keyCode != keyCode )
         return false;
@@ -606,25 +614,21 @@
 
     // if modifiers is non-zero, the 'any modifier' state is implicit
     if ( modifiers != 0 )
-        state |= AnyModifierState;
+        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 
     // any or no modifiers.  In this context, the 'keypad' modifier does not count.
     bool anyModifiersSet = modifiers != 0 && modifiers != Qt::KeypadModifier;
+    bool wantAnyModifier = _state & KeyboardTranslator::AnyModifierState;
     if ( _stateMask & KeyboardTranslator::AnyModifierState )
     {
-        // test fails if any modifier is required but none are set
-        if ( (_state & KeyboardTranslator::AnyModifierState) && !anyModifiersSet )
+        if ( wantAnyModifier != anyModifiersSet )
            return false;
-
-        // test fails if no modifier is allowed but one or more are set
-        if ( !(_state & KeyboardTranslator::AnyModifierState) && anyModifiersSet )
-            return false;
     }
-
+    
     return true;
 }
 QByteArray KeyboardTranslator::Entry::escapedText(bool expandWildCards,Qt::KeyboardModifiers modifiers) const
@@ -653,7 +657,7 @@
 
         if ( replacement == 'x' )
         {
-            result.replace(i,1,"\\x"+QByteArray(1,ch).toInt(0, 16)); 
+            result.replace(i,1,"\\x"+QByteArray(1,ch).toHex()); 
         } else if ( replacement != 0 )
         {
             result.remove(i,1);
@@ -676,7 +680,7 @@
         {
            char replacement[2] = {0,0};
            int charsToRemove = 2;
-		   bool escapedChar = true;
+           bool escapedChar = true;
 
            switch ( result[i+1] )
            {
@@ -687,7 +691,7 @@
               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
@@ -698,23 +702,22 @@
                     if ( (i < result.count()-3) && isxdigit(result[i+3]) )
                             hexDigits[1] = result[i+3];
 
-                    int charValue = 0;
+                    unsigned charValue = 0;
                     sscanf(hexDigits,"%x",&charValue);
-                    
-                    replacement[0] = (char)charValue; 
 
+                    replacement[0] = (char)charValue; 
                     charsToRemove = 2 + strlen(hexDigits);
-			  }
+                  }
               break;
-			  default:
-			  		escapedChar = false;
+              default:
+                  escapedChar = false;
            }
 
            if ( escapedChar )
                result.replace(i,charsToRemove,replacement);
         }
     }
-    
+
     return result;
 }
 
@@ -736,8 +739,8 @@
         item += "Alt";
     else if ( modifier == Qt::MetaModifier )
         item += "Meta";
-	else if ( modifier == Qt::KeypadModifier )
-		item += "KeyPad";
+    else if ( modifier == Qt::KeypadModifier )
+        item += "KeyPad";
 }
 void KeyboardTranslator::Entry::insertState( QString& item , int state ) const
 {
@@ -756,16 +759,18 @@
     else if ( state == KeyboardTranslator::AnsiState )
         item += "Ansi";
     else if ( state == KeyboardTranslator::CursorKeysState )
-        item += "AppCuKeys";
+        item += "AppCursorKeys";
     else if ( state == KeyboardTranslator::AnyModifierState )
-        item += "AnyMod";
+        item += "AnyModifier";
+    else if ( state == KeyboardTranslator::ApplicationKeypadState )
+        item += "AppKeypad";
 }
 QString KeyboardTranslator::Entry::resultToString(bool expandWildCards,Qt::KeyboardModifiers modifiers) const
 {
     if ( !_text.isEmpty() )
         return escapedText(expandWildCards,modifiers);
-	else if ( _command == EraseCommand )
-		return "Erase";
+    else if ( _command == EraseCommand )
+        return "Erase";
     else if ( _command == ScrollPageUpCommand )
         return "ScrollPageUp";
     else if ( _command == ScrollPageDownCommand )
@@ -783,18 +788,18 @@
 {
     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::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;
 }
@@ -829,48 +834,34 @@
 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)
 {
     if ( !existing.isNull() )
-        _entries.remove(existing.keyCode());
-    _entries.insertMulti(replacement.keyCode(),replacement);
+        _entries.remove(existing.keyCode(),existing);
+    _entries.insert(replacement.keyCode(),replacement);
 }
 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) )
+    foreach(const Entry& entry, _entries.values(keyCode))
     {
-        QList<Entry> entriesForKey = _entries.values(keyCode);
-        
-        QListIterator<Entry> iter(entriesForKey);
-
-        while (iter.hasNext())
-        {
-            const Entry& next = iter.next();
-            if ( next.matches(keyCode,modifiers,state) )
-                return next;
-        }
-
-        return Entry(); // entry not found
+        if ( entry.matches(keyCode,modifiers,state) )
+            return entry;
     }
-    else
-    {
-        return Entry();
-    }
-    
+    return Entry(); // entry not found
 }
 void KeyboardTranslatorManager::addTranslator(KeyboardTranslator* translator)
 {
     _translators.insert(translator->name(),translator);
 
-    if ( !saveTranslator(translator) )
-        qWarning() << "Unable to save translator" << translator->name()
-                   << "to disk.";
+  //  if ( !saveTranslator(translator) )
+  //      kWarning() << "Unable to save translator" << translator->name()
+    //               << "to disk.";
 }
 bool KeyboardTranslatorManager::deleteTranslator(const QString& name)
 {
@@ -885,10 +876,100 @@
     }
     else
     {
-        qWarning() << "Failed to remove translator - " << path;
+        //kWarning() << "Failed to remove translator - " << path;
         return false;
     }
 }
+
+/**
+ * @internal
+ */
+typedef void (*KdeCleanUpFunction)();
+
+/**
+ * @internal
+ *
+ * Helper class for K_GLOBAL_STATIC to clean up the object on library unload or application
+ * shutdown.
+ */
+class KCleanUpGlobalStatic
+{
+    public:
+        KdeCleanUpFunction func;
+
+        inline ~KCleanUpGlobalStatic() { func(); }
+};
+
+
+
+#ifdef Q_CC_MSVC
+/**
+ * @internal
+ *
+ * MSVC seems to give anonymous structs the same name which fails at link time. So instead we name
+ * the struct and hope that by adding the line number to the name it's unique enough to never clash.
+ */
+# define K_GLOBAL_STATIC_STRUCT_NAME(NAME) _k_##NAME##__LINE__
+#else
+/**
+ * @internal
+ *
+ * Make the struct of the K_GLOBAL_STATIC anonymous.
+ */
+# define K_GLOBAL_STATIC_STRUCT_NAME(NAME)
+#endif
+
+
+
+#define K_GLOBAL_STATIC_WITH_ARGS(TYPE, NAME, ARGS)                            \
+static QBasicAtomicPointer<TYPE > _k_static_##NAME = Q_BASIC_ATOMIC_INITIALIZER(0); \
+static bool _k_static_##NAME##_destroyed;                                      \
+static struct K_GLOBAL_STATIC_STRUCT_NAME(NAME)                                \
+{                                                                              \
+    inline bool isDestroyed() const                                            \
+    {                                                                          \
+        return _k_static_##NAME##_destroyed;                                   \
+    }                                                                          \
+    inline bool exists() const                                                 \
+    {                                                                          \
+        return _k_static_##NAME != 0;                                          \
+    }                                                                          \
+    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 KCleanUpGlobalStatic 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;
+
+#define K_GLOBAL_STATIC(TYPE, NAME) K_GLOBAL_STATIC_WITH_ARGS(TYPE, NAME, ())
+
 K_GLOBAL_STATIC( KeyboardTranslatorManager , theKeyboardTranslatorManager )
 KeyboardTranslatorManager* KeyboardTranslatorManager::instance()
 {
--- a/gui//src/KeyboardTranslator.h	Fri Apr 08 15:23:21 2011 +0200
+++ b/gui//src/KeyboardTranslator.h	Sat Apr 09 00:23:46 2011 +0200
@@ -1,9 +1,7 @@
 /*
     This source file is part of Konsole, a terminal emulator.
 
-    Copyright (C) 2007 by Robert Knight <robertknight@gmail.com>
-
-    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+    Copyright 2007-2008 by Robert Knight <robertknight@gmail.com>
 
     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,82 +28,9 @@
 #include <QtGui/QKeySequence>
 #include <QtCore/QMetaType>
 #include <QtCore/QVarLengthArray>
-#include <QtCore>
 
-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<TYPE > _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"
 
 class QIODevice;
 class QTextStream;
@@ -157,7 +82,9 @@
          */
         AlternateScreenState = 8,
         /** Indicates that any of the modifier keys is active. */ 
-        AnyModifierState = 16
+        AnyModifierState = 16,
+        /** Indicates that the numpad is in application mode. */
+        ApplicationKeypadState = 32
     };
     Q_DECLARE_FLAGS(States,State)
 
@@ -180,8 +107,8 @@
         ScrollLineDownCommand = 16,
         /** Toggles scroll lock mode */
         ScrollLockCommand = 32,
-		/** Echos the operating system specific erase character. */
-		EraseCommand = 64
+        /** Echos the operating system specific erase character. */
+        EraseCommand = 64
     };
     Q_DECLARE_FLAGS(Commands,Command)
 
@@ -381,7 +308,7 @@
 
 private:
 
-    QHash<int,Entry> _entries; // entries in this keyboard translation,
+    QMultiHash<int,Entry> _entries; // entries in this keyboard translation,
                                                  // entries are indexed according to
                                                  // their keycode
     QString _name;
@@ -476,7 +403,7 @@
     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 parseAsCommand(const QString& text , KeyboardTranslator::Command& command);
 
     QIODevice* _source;
     QString _description;
@@ -512,7 +439,7 @@
  * Manages the keyboard translations available for use by terminal sessions,
  * see KeyboardTranslator.
  */
-class KeyboardTranslatorManager
+class KONSOLEPRIVATE_EXPORT KeyboardTranslatorManager
 {
 public:
     /** 
@@ -563,7 +490,7 @@
    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 
--- a/gui//src/MainWindow.cpp	Fri Apr 08 15:23:21 2011 +0200
+++ b/gui//src/MainWindow.cpp	Sat Apr 09 00:23:46 2011 +0200
@@ -24,6 +24,7 @@
 #include "MainWindow.h"
 #include "TerminalMdiSubWindow.h"
 
+
 MainWindow::MainWindow(QWidget *parent)
     : QMainWindow(parent) {
     constructWindow();
--- a/gui//src/MainWindow.h	Fri Apr 08 15:23:21 2011 +0200
+++ b/gui//src/MainWindow.h	Sat Apr 09 00:23:46 2011 +0200
@@ -22,6 +22,7 @@
 #include <QtGui/QMainWindow>
 #include <QMdiArea>
 
+
 /**
   * \class MainWindow
   *
--- a/gui//src/OctaveLink.cpp	Fri Apr 08 15:23:21 2011 +0200
+++ b/gui//src/OctaveLink.cpp	Sat Apr 09 00:23:46 2011 +0200
@@ -128,22 +128,14 @@
 }
 
 //*************************************************************************
-OctaveLink::OctaveLink()
-{
-  // Create the mutexes 
+OctaveLink::OctaveLink() {
   pthread_mutex_init(&m_serverMutex,NULL);
   pthread_mutex_init(&m_octaveLockMutex,NULL);
-
   m_previousHistoryLength = 0;
-
   m_isProcessingServerData = false;
 }
 
-
-//*************************************************************************
-OctaveLink::~OctaveLink()
-{
-
+OctaveLink::~OctaveLink() {
 }
 
 /*******************************************************************************
@@ -153,21 +145,19 @@
  *******************************************************************************/
 
 //*************************************************************************
-std::vector<OctaveLink::VariableMetaData> OctaveLink::variableInfoList(void)
-{
-  // Acquire the mutex
-  if( pthread_mutex_trylock( &m_serverMutex ) != 0 )
-    return std::vector<VariableMetaData>();
+std::vector<OctaveLink::VariableMetaData> OctaveLink::variableInfoList(void) {
+    // Acquire the mutex
+    if( pthread_mutex_trylock( &m_serverMutex ) != 0 )
+        return std::vector<VariableMetaData>();
 
-  // Copy the list of variable information
-  std::vector<VariableMetaData> retval( m_variableSymbolTableList.size() );
-  std::copy( m_variableSymbolTableList.begin(), m_variableSymbolTableList.end(), retval.begin() );
-  m_variableSymbolTableList = std::vector<VariableMetaData>();
+    // Copy the list of variable information
+    std::vector<VariableMetaData> retval( m_variableSymbolTableList.size() );
+    std::copy( m_variableSymbolTableList.begin(), m_variableSymbolTableList.end(), retval.begin() );
+    m_variableSymbolTableList = std::vector<VariableMetaData>();
 
-  // Release the mutex
-  pthread_mutex_unlock( &m_serverMutex );
-
-  return retval;
+    // Release the mutex
+    pthread_mutex_unlock( &m_serverMutex );
+    return retval;
 }
 
 
@@ -374,8 +364,6 @@
   double elapsed = stop.tv_sec - start.tv_sec + 1E-6 * (stop.tv_usec - start.tv_usec);
   //octave_stdout << "SERVER ELAPSED: " << elapsed << std::endl;
 #endif
-
-
   return 0;
 }
 
@@ -570,9 +558,6 @@
       else
         octave_stdout << " <unknown line>" << std::endl;
     }
-
-  
-
   return 0;
 }
 
@@ -665,11 +650,5 @@
     //octave_stdout << "Removing breakpoint: " << funcName << " : " << lines[0] << std::endl; 
   }
   m_removedBreakpoints = std::vector<BreakPoint>();
-
-  // Process modified breakpoints
-  // TODO:
-
-
-
   return 0;
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gui//src/ProcessInfo.cpp	Sat Apr 09 00:23:46 2011 +0200
@@ -0,0 +1,1121 @@
+/*
+    Copyright 2007-2008 by Robert Knight <robertknight@gmail.countm>
+
+    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 "ProcessInfo.h"
+//#include <config-konsole.h>
+
+// Unix
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <unistd.h>
+#include <pwd.h>
+
+// Qt
+//#include <KDebug>
+#include <QtCore/QDir>
+#include <QtCore/QFileInfo>
+#include <QtCore/QRegExp>
+#include <QtCore/QTextStream>
+#include <QtCore/QStringList>
+#include <QtCore/QSet>
+//#include "kdebug.h"
+
+// KDE
+#include "konsole_export.h"
+//#include <KConfigGroup>
+//#include <KGlobal>
+//#include <KSharedConfig>
+//#include <KUser>
+
+#if defined(Q_OS_MAC)
+#include <sys/sysctl.h>
+#include <libproc.h>
+#ifdef HAVE_SYS_PROC_INFO_H
+#include <sys/proc_info.h>
+#endif
+#ifdef HAVE_SYS_PROC_H
+#include <sys/proc.h>
+#endif
+//#include <kde_file.h>
+#define KDE_struct_stat struct stat
+#define KDE_stat ::stat
+#endif
+
+#if defined(Q_OS_FREEBSD)
+#include <sys/sysctl.h> //krazy:exclude=includes
+#include <sys/types.h>
+#include <sys/user.h>
+#include <sys/syslimits.h>
+#include <libutil.h>
+#endif
+
+ProcessInfo::ProcessInfo(int pid , bool enableEnvironmentRead)
+    : _fields( ARGUMENTS | ENVIRONMENT ) // arguments and environments
+                                         // are currently always valid,
+                                         // they just return an empty
+                                         // vector / map respectively
+                                         // if no arguments
+                                         // or environment bindings
+                                         // have been explicitly set
+    , _enableEnvironmentRead(enableEnvironmentRead)
+    , _pid(pid)
+    , _parentPid(0)
+    , _foregroundPid(0)
+    , _userId(0)
+    , _lastError(NoError)
+    , _userName(QString())
+    , _userHomeDir(QString())
+{
+}
+
+ProcessInfo::Error ProcessInfo::error() const { return _lastError; }
+void ProcessInfo::setError(Error error) { _lastError = error; }
+
+void ProcessInfo::update() 
+{
+    readProcessInfo(_pid,_enableEnvironmentRead);
+}
+
+QString ProcessInfo::validCurrentDir() const
+{
+   bool ok = false;
+
+   // read current dir, if an error occurs try the parent as the next
+   // best option
+   int currentPid = parentPid(&ok);
+   QString dir = currentDir(&ok);
+   while ( !ok && currentPid != 0 )
+   {
+       ProcessInfo* current = ProcessInfo::newInstance(currentPid);
+       current->update();
+       currentPid = current->parentPid(&ok); 
+       dir = current->currentDir(&ok);
+       delete current;
+   }
+
+   return dir;
+}
+
+QString ProcessInfo::format(const QString& input) const
+{
+   bool ok = false;
+
+   QString output(input);
+
+   // search for and replace known marker
+   output.replace("%u",userName());
+   output.replace("%n",name(&ok));
+   output.replace("%c",formatCommand(name(&ok),arguments(&ok),ShortCommandFormat));
+   output.replace("%C",formatCommand(name(&ok),arguments(&ok),LongCommandFormat));
+   
+   QString dir = validCurrentDir();
+   if (output.contains("%D"))
+   {
+      QString homeDir = userHomeDir();
+      QString tempDir = dir;
+      // Change User's Home Dir w/ ~ only at the beginning
+      if (tempDir.startsWith(homeDir))
+      {
+         tempDir.remove(0, homeDir.length());
+         tempDir.prepend('~');
+      }
+      output.replace("%D", tempDir);
+   }
+   output.replace("%d",formatShortDir(dir));
+   
+   // remove any remaining %[LETTER] sequences
+   // output.replace(QRegExp("%\\w"), QString());
+
+   return output;
+}
+
+QString ProcessInfo::formatCommand(const QString& name, 
+                                   const QVector<QString>& arguments,
+                                   CommandFormat format) const
+{
+    Q_UNUSED(name);
+    Q_UNUSED(format);
+
+    // TODO Implement me
+    return QStringList(QList<QString>::fromVector(arguments)).join(" ");
+}
+
+QSet<QString> ProcessInfo::_commonDirNames;
+
+QSet<QString> ProcessInfo::commonDirNames() 
+{
+  // JPS: Don't know of a good replacement for this in QT
+  /*
+    if ( _commonDirNames.isEmpty() )
+    {
+        KSharedConfigPtr config = KGlobal::config();
+        KConfigGroup configGroup = config->group("ProcessInfo");
+
+        QStringList defaults = QStringList() 
+                             << "src" << "build" << "debug" << "release" 
+                             << "bin" << "lib"   << "libs"  << "tmp" 
+                             << "doc" << "docs"  << "data"  << "share"
+                             << "examples" << "icons" << "pics" << "plugins" 
+                             << "tests" << "media" << "l10n" << "include" 
+                             << "includes" << "locale" << "ui";
+
+        _commonDirNames = QSet<QString>::fromList(configGroup.readEntry("CommonDirNames",defaults));
+
+    }
+  */
+    return _commonDirNames;
+}
+
+QString ProcessInfo::formatShortDir(const QString& input) const
+{
+    QString result;
+
+    QStringList parts = input.split( QDir::separator() );
+
+    // temporarily hard-coded
+    QSet<QString> dirNamesToShorten = commonDirNames();
+
+    QListIterator<QString> iter(parts);
+    iter.toBack();
+
+    // go backwards through the list of the path's parts
+    // adding abbreviations of common directory names
+    // and stopping when we reach a dir name which is not
+    // in the commonDirNames set
+    while ( iter.hasPrevious() )
+    {
+        QString part = iter.previous();
+
+        if ( dirNamesToShorten.contains(part) )
+        {
+            result.prepend(QDir::separator() + part[0]);
+        }
+        else
+        {
+            result.prepend(part);
+            break;
+        }
+    }
+
+    return result;
+}
+
+QVector<QString> ProcessInfo::arguments(bool* ok) const
+{
+    *ok = _fields & ARGUMENTS;
+
+    return _arguments;
+}
+
+QMap<QString,QString> ProcessInfo::environment(bool* ok) const
+{
+    *ok = _fields & ENVIRONMENT;
+
+    return _environment;
+}
+
+bool ProcessInfo::isValid() const
+{
+    return _fields & PROCESS_ID;
+}
+
+int ProcessInfo::pid(bool* ok) const
+{
+    *ok = _fields & PROCESS_ID;
+
+    return _pid;
+}
+
+int ProcessInfo::parentPid(bool* ok) const
+{
+    *ok = _fields & PARENT_PID;
+
+    return _parentPid;
+}
+
+int ProcessInfo::foregroundPid(bool* ok) const
+{
+    *ok = _fields & FOREGROUND_PID;
+
+    return _foregroundPid;
+}
+
+QString ProcessInfo::name(bool* ok) const
+{
+    *ok = _fields & NAME;
+
+    return _name;
+}
+
+int ProcessInfo::userId(bool* ok) const
+{
+    *ok = _fields & UID;
+
+    return _userId;
+}
+
+QString ProcessInfo::userName() const
+{
+    return _userName;
+}
+
+QString ProcessInfo::userHomeDir() const
+{
+    return _userHomeDir;
+}
+
+void ProcessInfo::setPid(int pid)
+{
+    _pid = pid;
+    _fields |= PROCESS_ID;
+}
+
+void ProcessInfo::setUserId(int uid)
+{
+    _userId = uid;
+    _fields |= UID;
+}
+
+void ProcessInfo::setUserName(const QString& name)
+{
+    _userName = name;
+    setUserHomeDir();
+}
+
+void ProcessInfo::setUserHomeDir()
+{
+    QString usersName = userName();
+    // JPS: I don't know a good QT replacement
+    //if (!usersName.isEmpty())
+    //    _userHomeDir = KUser(usersName).homeDir();
+    //else
+        _userHomeDir = QDir::homePath();
+}
+
+void ProcessInfo::setParentPid(int pid)
+{
+    _parentPid = pid;
+    _fields |= PARENT_PID;
+}
+void ProcessInfo::setForegroundPid(int pid)
+{
+    _foregroundPid = pid;
+    _fields |= FOREGROUND_PID;
+}
+
+QString ProcessInfo::currentDir(bool* ok) const
+{
+    if (ok)
+        *ok = _fields & CURRENT_DIR;
+
+    return _currentDir;
+}
+void ProcessInfo::setCurrentDir(const QString& dir)
+{
+    _fields |= CURRENT_DIR;
+    _currentDir = dir;
+}
+
+void ProcessInfo::setName(const QString& name)
+{
+    _name = name;
+    _fields |= NAME;
+}
+void ProcessInfo::addArgument(const QString& argument)
+{
+    _arguments << argument;    
+}
+
+void ProcessInfo::addEnvironmentBinding(const QString& name , const QString& value)
+{
+    _environment.insert(name,value);
+}
+
+void ProcessInfo::setFileError( QFile::FileError error )
+{
+    switch ( error )
+    {
+        case PermissionsError:
+            setError( PermissionsError );
+            break;
+        case NoError:
+            setError( NoError );
+            break;
+        default:
+            setError( UnknownError );
+    }
+}
+
+//
+// ProcessInfo::newInstance() is way at the bottom so it can see all of the
+// implementations of the UnixProcessInfo abstract class.
+//
+
+NullProcessInfo::NullProcessInfo(int pid,bool enableEnvironmentRead)
+    : ProcessInfo(pid,enableEnvironmentRead)
+{
+}
+
+bool NullProcessInfo::readProcessInfo(int /*pid*/ , bool /*enableEnvironmentRead*/)
+{
+    return false;
+}
+
+void NullProcessInfo::readUserName()
+{
+}
+
+UnixProcessInfo::UnixProcessInfo(int pid,bool enableEnvironmentRead)
+    : ProcessInfo(pid,enableEnvironmentRead)
+{
+}
+
+bool UnixProcessInfo::readProcessInfo(int pid , bool enableEnvironmentRead)
+{
+    bool ok = readProcInfo(pid);
+    if (ok)
+    {
+        ok |= readArguments(pid);
+        ok |= readCurrentDir(pid);
+        if ( enableEnvironmentRead )
+        {
+            ok |= readEnvironment(pid);
+        }
+    }
+    return ok;
+}
+
+void UnixProcessInfo::readUserName()
+{
+    bool ok = false;
+    int uid = userId(&ok);
+    if (!ok) return;
+
+    struct passwd passwdStruct;
+    struct passwd *getpwResult;
+    char *getpwBuffer;
+    long getpwBufferSize;
+    int getpwStatus;
+
+    getpwBufferSize = sysconf(_SC_GETPW_R_SIZE_MAX);
+    if (getpwBufferSize == -1)
+        getpwBufferSize = 16384;
+
+    getpwBuffer = new char[getpwBufferSize];
+    if (getpwBuffer == NULL)
+        return;
+    getpwStatus = getpwuid_r(uid, &passwdStruct, getpwBuffer, getpwBufferSize, &getpwResult);
+    if (getpwResult != NULL)
+        setUserName(QString(passwdStruct.pw_name));
+    else
+        setUserName(QString());
+    delete [] getpwBuffer;
+}
+
+
+class LinuxProcessInfo : public UnixProcessInfo
+{
+public:
+    LinuxProcessInfo(int pid, bool env) :
+        UnixProcessInfo(pid,env)
+    {
+    }
+
+private:
+    virtual bool readProcInfo(int pid)
+    {
+        // indicies of various fields within the process status file which
+        // contain various information about the process
+        const int PARENT_PID_FIELD = 3;
+        const int PROCESS_NAME_FIELD = 1;
+        const int GROUP_PROCESS_FIELD = 7;
+
+        QString parentPidString;
+        QString processNameString;
+        QString foregroundPidString;
+        QString uidLine;
+        QString uidString;
+        QStringList uidStrings;
+
+        // For user id read process status file ( /proc/<pid>/status )
+        //  Can not use getuid() due to it does not work for 'su'
+        QFile statusInfo( QString("/proc/%1/status").arg(pid) );
+        if ( statusInfo.open(QIODevice::ReadOnly) )
+        {
+            QTextStream stream(&statusInfo);
+            QString statusLine;
+            do {
+                statusLine = stream.readLine(0);
+                if (statusLine.startsWith(QLatin1String("Uid:")))
+                    uidLine = statusLine;
+            } while (!statusLine.isNull() && uidLine.isNull());
+
+            uidStrings << uidLine.split('\t', QString::SkipEmptyParts);
+            // Must be 5 entries: 'Uid: %d %d %d %d' and
+            // uid string must be less than 5 chars (uint)
+            if (uidStrings.size() == 5)
+                uidString = uidStrings[1];
+            if (uidString.size() > 5)
+                uidString.clear();
+
+            bool ok = false;
+            int uid = uidString.toInt(&ok);
+            if (ok)
+                setUserId(uid);
+            readUserName();
+        }
+        else
+        {
+            setFileError( statusInfo.error() );
+            return false;
+        }
+
+
+        // read process status file ( /proc/<pid/stat )
+        //
+        // the expected file format is a list of fields separated by spaces, using
+        // parenthesies to escape fields such as the process name which may itself contain
+        // spaces:
+        //
+        // FIELD FIELD (FIELD WITH SPACES) FIELD FIELD
+        //
+        QFile processInfo( QString("/proc/%1/stat").arg(pid) );
+        if ( processInfo.open(QIODevice::ReadOnly) )
+        {
+            QTextStream stream(&processInfo);
+            QString data = stream.readAll();
+
+            int stack = 0;
+            int field = 0;
+            int pos = 0;
+
+            while (pos < data.count())
+            {
+                QChar c = data[pos];
+
+                if ( c == '(' )
+                    stack++;
+                else if ( c == ')' )
+                    stack--;
+                else if ( stack == 0 && c == ' ' )
+                    field++;
+                else
+                {
+                    switch ( field )
+                    {
+                        case PARENT_PID_FIELD:
+                            parentPidString.append(c);
+                            break;
+                        case PROCESS_NAME_FIELD:
+                            processNameString.append(c);
+                            break;
+                        case GROUP_PROCESS_FIELD:
+                            foregroundPidString.append(c);
+                            break;
+                    }
+                }
+
+                pos++;
+            }
+        }
+        else
+        {
+            setFileError( processInfo.error() );
+            return false;
+        }
+
+        // check that data was read successfully
+        bool ok = false;
+        int foregroundPid = foregroundPidString.toInt(&ok);
+        if (ok)
+            setForegroundPid(foregroundPid);
+
+        int parentPid = parentPidString.toInt(&ok);
+        if (ok)
+            setParentPid(parentPid);
+
+        if (!processNameString.isEmpty())
+            setName(processNameString);
+
+        // update object state
+        setPid(pid);
+
+        return ok;
+    }
+
+    virtual bool readArguments(int pid)
+    {
+        // read command-line arguments file found at /proc/<pid>/cmdline
+        // the expected format is a list of strings delimited by null characters,
+        // and ending in a double null character pair.
+
+        QFile argumentsFile( QString("/proc/%1/cmdline").arg(pid) );
+        if ( argumentsFile.open(QIODevice::ReadOnly) )
+        {
+            QTextStream stream(&argumentsFile);
+            QString data = stream.readAll();
+
+            QStringList argList = data.split( QChar('\0') );
+
+            foreach ( const QString &entry , argList )
+            {
+                if (!entry.isEmpty())
+                    addArgument(entry);
+            }
+        }
+        else
+        {
+            setFileError( argumentsFile.error() );
+        }
+
+        return true;
+    }
+
+    virtual bool readCurrentDir(int pid)
+    {
+        QFileInfo info( QString("/proc/%1/cwd").arg(pid) );
+
+        const bool readable = info.isReadable();
+
+        if ( readable && info.isSymLink() )
+        {
+            setCurrentDir( info.symLinkTarget() );
+            return true;
+        }
+        else
+        {
+            if ( !readable )
+                setError( PermissionsError );
+            else
+                setError( UnknownError );
+
+            return false;
+        }
+    }
+
+    virtual bool readEnvironment(int pid)
+    {
+        // read environment bindings file found at /proc/<pid>/environ
+        // the expected format is a list of KEY=VALUE strings delimited by null
+        // characters and ending in a double null character pair.
+
+        QFile environmentFile( QString("/proc/%1/environ").arg(pid) );
+        if ( environmentFile.open(QIODevice::ReadOnly) )
+        {
+            QTextStream stream(&environmentFile);
+            QString data = stream.readAll();
+
+            QStringList bindingList = data.split( QChar('\0') );
+
+            foreach( const QString &entry , bindingList )
+            {
+                QString name;
+                QString value;
+
+                int splitPos = entry.indexOf('=');
+
+                if ( splitPos != -1 )
+                {
+                    name = entry.mid(0,splitPos);
+                    value = entry.mid(splitPos+1,-1);
+
+                    addEnvironmentBinding(name,value);
+                }
+            }
+        }
+        else
+        {
+            setFileError( environmentFile.error() );
+        }
+
+        return true;
+    }
+} ;
+
+#if defined(Q_OS_FREEBSD)
+class FreeBSDProcessInfo : public UnixProcessInfo
+{
+public:
+    FreeBSDProcessInfo(int pid, bool readEnvironment) :
+        UnixProcessInfo(pid, readEnvironment)
+    {
+    }
+
+private:
+    virtual bool readProcInfo(int pid)
+    {
+        int managementInfoBase[4];
+        size_t mibLength;
+        struct kinfo_proc* kInfoProc;
+
+        managementInfoBase[0] = CTL_KERN;
+        managementInfoBase[1] = KERN_PROC;
+        managementInfoBase[2] = KERN_PROC_PID;
+        managementInfoBase[3] = pid;
+
+        if (sysctl(managementInfoBase, 4, NULL, &mibLength, NULL, 0) == -1)
+            return false;
+
+        kInfoProc = new struct kinfo_proc [mibLength];
+
+        if (sysctl(managementInfoBase, 4, kInfoProc, &mibLength, NULL, 0) == -1)
+        {
+            delete [] kInfoProc;
+            return false;
+        }
+
+#if defined(__DragonFly__)
+        setName(kInfoProc->kp_comm);
+        setPid(kInfoProc->kp_pid);
+        setParentPid(kInfoProc->kp_ppid);
+        setForegroundPid(kInfoProc->kp_pgid);
+        setUserId(kInfoProc->kp_uid);
+#else
+        setName(kInfoProc->ki_comm);
+        setPid(kInfoProc->ki_pid);
+        setParentPid(kInfoProc->ki_ppid);
+        setForegroundPid(kInfoProc->ki_pgid);
+        setUserId(kInfoProc->ki_uid);
+#endif
+
+        readUserName();
+
+        delete [] kInfoProc;
+        return true;
+    }
+
+    virtual bool readArguments(int pid)
+    {
+        char args[ARG_MAX];
+        int managementInfoBase[4];
+        size_t len;
+
+        managementInfoBase[0] = CTL_KERN;
+        managementInfoBase[1] = KERN_PROC;
+        managementInfoBase[2] = KERN_PROC_PID;
+        managementInfoBase[3] = pid;
+
+        len = sizeof(args);
+        if (sysctl(managementInfoBase, 4, args, &len, NULL, 0) == -1)
+            return false;
+
+        const QStringList argumentList = QString(args).split(QChar('\0'));
+
+        for (QStringList::const_iterator it = argumentList.begin(); it != argumentList.end(); ++it)
+        {
+            addArgument(*it);
+        }
+
+        return true;
+    }
+
+    virtual bool readEnvironment(int pid)
+    {
+        // Not supported in FreeBSD?
+        return false;
+    }
+
+    virtual bool readCurrentDir(int pid)
+    {
+#if defined(__DragonFly__)
+        char buf[PATH_MAX];
+        int managementInfoBase[4];
+        size_t len;
+
+        managementInfoBase[0] = CTL_KERN;
+        managementInfoBase[1] = KERN_PROC;
+        managementInfoBase[2] = KERN_PROC_CWD;
+        managementInfoBase[3] = pid;
+
+        len = sizeof(buf);
+        if (sysctl(managementInfoBase, 4, buf, &len, NULL, 0) == -1)
+            return false;
+
+        setCurrentDir(buf);
+
+        return true;
+#else
+        int numrecords;
+        struct kinfo_file* info = 0;
+
+        info = kinfo_getfile(pid, &numrecords);
+
+        if (!info)
+            return false;
+
+        for (int i = 0; i < numrecords; ++i)
+        {
+            if (info[i].kf_fd == KF_FD_TYPE_CWD)
+            {
+                setCurrentDir(info[i].kf_path);
+
+                free(info);
+                return true;
+            }
+        }
+
+        free(info);
+        return false;
+#endif
+    }
+} ;
+#endif
+
+#if defined(Q_OS_MAC)
+class MacProcessInfo : public UnixProcessInfo
+{
+public:
+    MacProcessInfo(int pid, bool env) :
+        UnixProcessInfo(pid, env)
+    {
+    }
+
+private:
+    virtual bool readProcInfo(int pid)
+    {
+        int managementInfoBase[4];
+        size_t mibLength;
+        struct kinfo_proc* kInfoProc;
+        KDE_struct_stat statInfo;
+
+        // Find the tty device of 'pid' (Example: /dev/ttys001)
+        managementInfoBase[0] = CTL_KERN;
+        managementInfoBase[1] = KERN_PROC;
+        managementInfoBase[2] = KERN_PROC_PID;
+        managementInfoBase[3] = pid;
+
+        if (sysctl(managementInfoBase, 4, NULL, &mibLength, NULL, 0) == -1)
+        {
+            return false;
+        } 
+        else
+        {
+            kInfoProc = new struct kinfo_proc [mibLength];
+            if (sysctl(managementInfoBase, 4, kInfoProc, &mibLength, NULL, 0) == -1)
+            {
+                delete [] kInfoProc;
+                return false;
+            }
+            else
+            { 
+                QString deviceNumber = QString(devname(((&kInfoProc->kp_eproc)->e_tdev), S_IFCHR));
+                QString fullDeviceName =  QString("/dev/") + deviceNumber.rightJustified(3, '0');
+                delete [] kInfoProc;
+
+                QByteArray deviceName = fullDeviceName.toLatin1();
+                const char* ttyName = deviceName.data();
+
+                if (KDE_stat(ttyName, &statInfo) != 0)
+                    return false;
+
+                // Find all processes attached to ttyName
+                managementInfoBase[0] = CTL_KERN;
+                managementInfoBase[1] = KERN_PROC;
+                managementInfoBase[2] = KERN_PROC_TTY;
+                managementInfoBase[3] = statInfo.st_rdev;
+
+                mibLength = 0;
+                if (sysctl(managementInfoBase, sizeof(managementInfoBase)/sizeof(int), NULL, &mibLength, NULL, 0) == -1)
+                    return false;
+
+                kInfoProc = new struct kinfo_proc [mibLength];
+                if (sysctl(managementInfoBase, sizeof(managementInfoBase)/sizeof(int), kInfoProc, &mibLength, NULL, 0) == -1)
+                    return false;
+
+                // The foreground program is the first one
+                setName(QString(kInfoProc->kp_proc.p_comm));
+
+                delete [] kInfoProc;
+            }
+        }
+        return true;
+    }
+
+    virtual bool readArguments(int pid)
+    {
+        Q_UNUSED(pid);
+        return false;
+    }
+    virtual bool readCurrentDir(int pid)
+    {
+        struct proc_vnodepathinfo vpi;
+        int nb = proc_pidinfo(pid, PROC_PIDVNODEPATHINFO, 0, &vpi, sizeof(vpi));
+        if (nb == sizeof(vpi))
+        {
+            setCurrentDir(QString(vpi.pvi_cdir.vip_path));
+            return true;
+        }
+        return false;
+    }
+    virtual bool readEnvironment(int pid)
+    {
+        Q_UNUSED(pid);
+        return false;
+    }
+} ;
+#endif
+
+#ifdef Q_OS_SOLARIS
+    // The procfs structure definition requires off_t to be
+    // 32 bits, which only applies if FILE_OFFSET_BITS=32.
+    // Futz around here to get it to compile regardless,
+    // although some of the structure sizes might be wrong.
+    // Fortunately, the structures we actually use don't use
+    // off_t, and we're safe.
+    #if defined(_FILE_OFFSET_BITS) && (_FILE_OFFSET_BITS==64)
+        #undef _FILE_OFFSET_BITS
+    #endif
+    #include <procfs.h>
+#else
+    // On non-Solaris platforms, define a fake psinfo structure
+    // so that the SolarisProcessInfo class can be compiled
+    //
+    // That avoids the trap where you change the API and
+    // don't notice it in #ifdeffed platform-specific parts
+    // of the code.
+    struct psinfo {
+        int pr_ppid;
+        int pr_pgid;
+        char* pr_fname;
+        char* pr_psargs;
+    } ;
+    static const int PRARGSZ=1;
+#endif
+
+class SolarisProcessInfo : public UnixProcessInfo
+{
+public:
+    SolarisProcessInfo(int pid, bool readEnvironment) 
+    : UnixProcessInfo(pid,readEnvironment)
+    {
+    }
+private:
+    virtual bool readProcInfo(int pid)
+    {
+        QFile psinfo( QString("/proc/%1/psinfo").arg(pid) );
+        if ( psinfo.open( QIODevice::ReadOnly ) )
+        {
+            struct psinfo info;
+            if (psinfo.read((char *)&info,sizeof(info)) != sizeof(info))
+            {
+                return false;
+            }
+
+            setParentPid(info.pr_ppid);
+            setForegroundPid(info.pr_pgid);
+            setName(info.pr_fname);
+            setPid(pid);
+
+            // Bogus, because we're treating the arguments as one single string
+            info.pr_psargs[PRARGSZ-1]=0;
+            addArgument(info.pr_psargs);
+        }
+        return true;
+    }
+
+    virtual bool readArguments(int /*pid*/)
+    {
+        // Handled in readProcInfo()
+        return false;
+    }
+
+    virtual bool readEnvironment(int /*pid*/)
+    {
+        // Not supported in Solaris
+        return false;
+    }
+
+    virtual bool readCurrentDir(int pid)
+    {
+        QFileInfo info( QString("/proc/%1/path/cwd").arg(pid) );
+        const bool readable = info.isReadable();
+
+        if ( readable && info.isSymLink() )
+        {
+            setCurrentDir( info.symLinkTarget() );
+            return true;
+        }
+        else
+        {
+            if ( !readable )
+                setError( PermissionsError );
+            else
+                setError( UnknownError );
+
+            return false;
+        }
+    }
+} ;
+
+SSHProcessInfo::SSHProcessInfo(const ProcessInfo& process)
+ : _process(process)
+{
+    bool ok = false;
+
+    // check that this is a SSH process
+    const QString& name = _process.name(&ok);
+
+    if ( !ok || name != "ssh" )
+    {
+        //if ( !ok )
+        //    kWarning() << "Could not read process info";
+        //else
+        //    kWarning() << "Process is not a SSH process";
+
+        return;
+    }
+
+    // read arguments
+    const QVector<QString>& args = _process.arguments(&ok); 
+
+    // SSH options
+    // these are taken from the SSH manual ( accessed via 'man ssh' )
+    
+    // options which take no arguments
+    static const QString noOptionsArguments("1246AaCfgkMNnqsTtVvXxY"); 
+    // options which take one argument
+    static const QString singleOptionArguments("bcDeFiLlmOopRSw");
+
+    if ( ok )
+    {
+         // find the username, host and command arguments
+         //
+         // the username/host is assumed to be the first argument 
+         // which is not an option
+         // ( ie. does not start with a dash '-' character )
+         // or an argument to a previous option.
+         //
+         // the command, if specified, is assumed to be the argument following
+         // the username and host
+         //
+         // note that we skip the argument at index 0 because that is the
+         // program name ( expected to be 'ssh' in this case )
+         for ( int i = 1 ; i < args.count() ; i++ )
+         {
+            // if this argument is an option then skip it, plus any 
+            // following arguments which refer to this option
+            if ( args[i].startsWith('-') )
+            {
+                QChar argChar = ( args[i].length() > 1 ) ? args[i][1] : '\0';
+
+                if ( noOptionsArguments.contains(argChar) )
+                    continue;
+                else if ( singleOptionArguments.contains(argChar) )
+                {
+                    i++;
+                    continue;
+                }
+            }
+
+            // check whether the host has been found yet
+            // if not, this must be the username/host argument 
+            if ( _host.isEmpty() )
+            {
+                // check to see if only a hostname is specified, or whether
+                // both a username and host are specified ( in which case they
+                // are separated by an '@' character:  username@host )
+            
+                int separatorPosition = args[i].indexOf('@');
+                if ( separatorPosition != -1 )
+                {
+                    // username and host specified
+                    _user = args[i].left(separatorPosition);
+                    _host = args[i].mid(separatorPosition+1);
+                }
+                else
+                {
+                    // just the host specified
+                    _host = args[i];
+                }
+            }
+            else
+            {
+                // host has already been found, this must be the command argument
+                _command = args[i];
+            }
+
+         }
+    }
+    else
+    {
+        //kWarning() << "Could not read arguments";
+        
+        return;
+    }
+}
+
+QString SSHProcessInfo::userName() const
+{
+    return _user;
+}
+QString SSHProcessInfo::host() const
+{
+    return _host;
+}
+QString SSHProcessInfo::command() const
+{
+    return _command;
+}
+QString SSHProcessInfo::format(const QString& input) const
+{
+    QString output(input);
+   
+    // test whether host is an ip address
+    // in which case 'short host' and 'full host'
+    // markers in the input string are replaced with
+    // the full address
+    bool isIpAddress = false;
+   
+    struct in_addr address;
+    if ( inet_aton(_host.toLocal8Bit().constData(),&address) != 0 )
+        isIpAddress = true;
+    else
+        isIpAddress = false;
+
+    // search for and replace known markers
+    output.replace("%u",_user);
+
+    if ( isIpAddress )
+        output.replace("%h",_host);
+    else
+        output.replace("%h",_host.left(_host.indexOf('.')));
+    
+    output.replace("%H",_host);
+    output.replace("%c",_command);
+
+    return output;
+}
+
+ProcessInfo* ProcessInfo::newInstance(int pid,bool enableEnvironmentRead)
+{
+#ifdef Q_OS_LINUX
+    return new LinuxProcessInfo(pid,enableEnvironmentRead);
+#elif defined(Q_OS_SOLARIS)
+    return new SolarisProcessInfo(pid,enableEnvironmentRead);
+#elif defined(Q_OS_MAC)
+    return new MacProcessInfo(pid,enableEnvironmentRead);
+#elif defined(Q_OS_FREEBSD)
+    return new FreeBSDProcessInfo(pid,enableEnvironmentRead);
+#else
+    return new NullProcessInfo(pid,enableEnvironmentRead);
+#endif
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gui//src/ProcessInfo.h	Sat Apr 09 00:23:46 2011 +0200
@@ -0,0 +1,462 @@
+/*
+    Copyright 2007-2008 by Robert Knight <robertknight@gmail.com>
+
+    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 PROCESSINFO_H
+#define PROCESSINFO_H
+
+// Qt
+#include <QtCore/QFile>
+#include <QtCore/QMap>
+#include <QtCore/QString>
+#include <QtCore/QVector>
+
+/**
+ * Takes a snapshot of the state of a process and provides access to 
+ * information such as the process name, parent process,
+ * the foreground process in the controlling terminal,
+ * the arguments with which the process was started and the 
+ * environment.
+ *
+ * To create a new snapshot, construct a new ProcessInfo instance,
+ * using ProcessInfo::newInstance(),
+ * passing the process identifier of the process you are interested in.
+ *
+ * After creating a new instance, call the update() method to take a 
+ * snapshot of the current state of the process.
+ *
+ * Before calling any additional methods, check that the process state
+ * was read successfully using the isValid() method.
+ *
+ * Each accessor method which provides information about the process state ( such as pid(), 
+ * currentDir(), name() ) takes a pointer to a boolean as an argument.  If the information
+ * requested was read successfully then the boolean is set to true, otherwise it is set
+ * to false, in which case the return value from the function should be ignored.
+ * If this boolean is set to false, it may indicate an error reading the process information,
+ * or it may indicate that the information is not available on the current platform. 
+ *
+ * eg.
+ *
+ * @code
+ *   ProcessInfo* info = ProcessInfo::newInstance(pid);
+ *   info->update();
+ *
+ *   if ( info->isValid() )
+ *   {
+ *      bool ok;
+ *      QString value = info->name(&ok);
+ *
+ *      if ( ok ) kDebug() << "process name - " << name;
+ *      int parentPid = info->parentPid(&ok);
+ *      if ( ok ) kDebug() << "parent process - " << parentPid;
+ *      int foregroundPid = info->foregroundColororegroundPid(&ok);
+ *      if ( ok ) kDebug() << "foreground process - " << foregroundPid;
+ *   }
+ * @endcode
+ */
+class ProcessInfo
+{
+public:
+    /**
+     * Constructs a new instance of a suitable ProcessInfo sub-class for 
+     * the current platform which provides information about a given process.
+     *
+     * @param pid The pid of the process to examine
+     * @param readEnvironment Specifies whether environment bindings should
+     * be read.  If this is false, then environment() calls will
+     * always fail.  This is an optimization to avoid the overhead
+     * of reading the (potentially large) environment data when it
+     * is not required. 
+     */
+    static ProcessInfo* newInstance(int pid,bool readEnvironment = false);
+
+    virtual ~ProcessInfo() {}
+
+    /** 
+     * Updates the information about the process.  This must
+     * be called before attempting to use any of the accessor methods.
+     */
+    void update();
+
+    /** Returns true if the process state was read successfully. */ 
+    bool isValid() const;
+    /** 
+     * Returns the process id.  
+     *
+     * @param ok Set to true if the process id was read successfully or false otherwise 
+     */
+    int pid(bool* ok) const;
+    /** 
+     * Returns the id of the parent process id was read successfully or false otherwise
+     * 
+     * @param ok Set to true if the parent process id
+     */
+    int parentPid(bool* ok) const;
+    
+    /** 
+     * Returns the id of the current foreground process 
+     *
+     * NOTE:  Using the foregroundProcessGroup() method of the Pty
+     * instance associated with the terminal of interest is preferred
+     * over using this method.
+     *
+     * @param ok Set to true if the foreground process id was read successfully or false otherwise
+     */
+    int foregroundPid(bool* ok) const;
+    
+    /* Returns the user id of the process */
+    int userId(bool* ok) const;
+
+    /** Returns the user's name of the process */
+    QString userName() const;
+   
+    /** Returns the user's home directory of the process */
+    QString userHomeDir() const;
+
+    /** Returns the name of the current process */
+    QString name(bool* ok) const;
+   
+    /** 
+     * Returns the command-line arguments which the process
+     * was started with.
+     *
+     * The first argument is the name used to launch the process.
+     *
+     * @param ok Set to true if the arguments were read successfully or false otherwise.
+     */
+    QVector<QString> arguments(bool* ok) const;
+    /**
+     * Returns the environment bindings which the process
+     * was started with.
+     * In the returned map, the key is the name of the environment variable,
+     * and the value is the corresponding value.
+     *
+     * @param ok Set to true if the environment bindings were read successfully or false otherwise
+     */
+    QMap<QString,QString> environment(bool* ok) const;
+
+    /**
+     * Returns the current working directory of the process
+     *
+     * @param ok Set to true if the current working directory was read successfully or false otherwise
+     */
+    QString currentDir(bool* ok) const;
+
+    /**
+     * Returns the current working directory of the process (or its parent)
+     */
+    QString validCurrentDir() const;
+
+    /** Forces the user home directory to be calculated */
+    void setUserHomeDir();
+
+    /**
+     * Parses an input string, looking for markers beginning with a '%' 
+     * character and returns a string with the markers replaced
+     * with information from this process description.
+     * <br>
+     * The markers recognised are:
+     * <ul>
+     * <li> %u - Name of the user which owns the process. </li>
+     * <li> %n - Replaced with the name of the process.   </li>
+     * <li> %d - Replaced with the last part of the path name of the 
+     *      process' current working directory.
+     *      
+     *      (eg. if the current directory is '/home/bob' then
+     *      'bob' would be returned)
+     * </li>
+     * <li> %D - Replaced with the current working directory of the process. </li>
+     * </ul>
+     */
+    QString format(const QString& text) const;
+
+    /** 
+     * This enum describes the errors which can occur when trying to read 
+     * a process's information.
+     */
+    enum Error
+    {
+        /** No error occurred. */
+        NoError,
+        /** The nature of the error is unknown. */
+        UnknownError,
+        /** Konsole does not have permission to obtain the process information. */
+        PermissionsError
+    };
+
+    /**
+     * Returns the last error which occurred.
+     */
+    Error error() const;
+
+protected:
+    /**
+     * Constructs a new process instance.  You should not call the constructor
+     * of ProcessInfo or its subclasses directly.  Instead use the 
+     * static ProcessInfo::newInstance() method which will return
+     * a suitable ProcessInfo instance for the current platform.
+     */ 
+    explicit ProcessInfo(int pid , bool readEnvironment = false);
+
+    /** 
+     * This is called on construction to read the process state 
+     * Subclasses should reimplement this function to provide
+     * platform-specific process state reading functionality.
+     *
+     * When called, readProcessInfo() should attempt to read all
+     * of the necessary state information.  If the attempt is successful,
+     * it should set the process id using setPid(), and update
+     * the other relevant information using setParentPid(), setName(),
+     * setArguments() etc.
+     *
+     * Calls to isValid() will return true only if the process id
+     * has been set using setPid()
+     *
+     * @param pid The process id of the process to read
+     * @param readEnvironment Specifies whether the environment bindings
+     *                        for the process should be read
+     */
+    virtual bool readProcessInfo(int pid , bool readEnvironment) = 0;
+
+    /* Read the user name */
+    virtual void readUserName(void) = 0;
+
+    /** Sets the process id associated with this ProcessInfo instance */
+    void setPid(int pid);
+    /** Sets the parent process id as returned by parentPid() */
+    void setParentPid(int pid);
+    /** Sets the foreground process id as returend by foregroundPid() */
+    void setForegroundPid(int pid);
+    /** Sets the user id associated with this ProcessInfo instance */
+    void setUserId(int uid);
+    /** Sets the user name of the process as set by readUserName() */
+    void setUserName(const QString& name);
+    /** Sets the name of the process as returned by name() */
+    void setName(const QString& name);
+    /** Sets the current working directory for the process */
+    void setCurrentDir(const QString& dir);
+
+    /** Sets the error */
+    void setError( Error error );
+
+    /** Convenience method.  Sets the error based on a QFile error code. */ 
+    void setFileError( QFile::FileError error ); 
+
+    /** 
+     * Adds a commandline argument for the process, as returned
+     * by arguments()
+     */
+    void addArgument(const QString& argument);
+    /**
+     * Adds an environment binding for the process, as returned by
+     * environment()
+     *
+     * @param name The name of the environment variable, eg. "PATH"
+     * @param value The value of the environment variable, eg. "/bin"
+     */
+    void addEnvironmentBinding(const QString& name , const QString& value);
+
+private:
+    // takes a full directory path and returns a
+    // shortened version suitable for display in 
+    // space-constrained UI elements (eg. tabs)
+    QString formatShortDir(const QString& dirPath) const;
+
+    enum CommandFormat
+    {
+        ShortCommandFormat,
+        LongCommandFormat
+    };
+    // takes a process name and its arguments and produces formatted output
+    QString formatCommand(const QString& name , const QVector<QString>& arguments , 
+                          CommandFormat format) const;
+
+    // valid bits for _fields variable, ensure that
+    // _fields is changed to an int if more than 8 fields are added
+    enum FIELD_BITS
+    {
+        PROCESS_ID          = 1,
+        PARENT_PID          = 2,
+        FOREGROUND_PID      = 4,
+        ARGUMENTS           = 8,
+        ENVIRONMENT         = 16,
+        NAME                = 32,
+        CURRENT_DIR         = 64,
+        UID                 =128 
+    };
+
+    char _fields; // a bitmap indicating which fields are valid
+                  // used to set the "ok" parameters for the public
+                  // accessor functions
+
+    bool _enableEnvironmentRead; // specifies whether to read the environment
+                                 // bindings when update() is called
+    int _pid;  
+    int _parentPid;
+    int _foregroundPid;
+    int _userId;  
+
+    Error _lastError;
+
+    QString _name;
+    QString _userName;
+    QString _userHomeDir;
+    QString _currentDir;
+
+    QVector<QString> _arguments;
+    QMap<QString,QString> _environment;
+
+    static QSet<QString> commonDirNames();
+    static QSet<QString> _commonDirNames;
+};
+
+/** 
+ * Implementation of ProcessInfo which does nothing.
+ * Used on platforms where a suitable ProcessInfo subclass is not 
+ * available.
+ *
+ * isValid() will always return false for instances of NullProcessInfo
+ */
+class NullProcessInfo : public ProcessInfo
+{
+public:
+    /** 
+     * Constructs a new NullProcessInfo instance.
+     * See ProcessInfo::newInstance()
+     */
+    explicit NullProcessInfo(int pid,bool readEnvironment = false);
+protected:
+    virtual bool readProcessInfo(int pid,bool readEnvironment);
+    virtual void readUserName(void);
+};
+
+/**
+ * Implementation of ProcessInfo for Unix platforms which uses
+ * the /proc filesystem
+ */
+class UnixProcessInfo : public ProcessInfo
+{
+public:
+    /** 
+     * Constructs a new instance of UnixProcessInfo.
+     * See ProcessInfo::newInstance()
+     */
+    explicit UnixProcessInfo(int pid,bool readEnvironment = false);
+
+protected:
+    /** 
+     * Implementation of ProcessInfo::readProcessInfo(); calls the
+     * four private methods below in turn.
+     */
+    virtual bool readProcessInfo(int pid , bool readEnvironment);
+
+    virtual void readUserName(void);
+
+private:
+    /**
+     * Read the standard process information -- PID, parent PID, foreground PID.
+     * @param pid process ID to use
+     * @return true on success
+     */
+    virtual bool readProcInfo(int pid)=0;
+
+    /**
+     * Read the environment of the process. Sets _environment.
+     * @param pid process ID to use
+     * @return true on success
+     */
+    virtual bool readEnvironment(int pid)=0;
+
+    /**
+     * Determine what arguments were passed to the process. Sets _arguments.
+     * @param pid process ID to use
+     * @return true on success
+     */
+    virtual bool readArguments(int pid)=0;
+
+    /**
+     * Determine the current directory of the process.
+     * @param pid process ID to use
+     * @return true on success
+     */
+    virtual bool readCurrentDir(int pid)=0;
+};
+
+/** 
+ * Lightweight class which provides additional information about SSH processes.
+ */
+class SSHProcessInfo
+{
+public:
+    /** 
+     * Constructs a new SSHProcessInfo instance which provides additional
+     * information about the specified SSH process.
+     *
+     * @param process A ProcessInfo instance for a SSH process.
+     */
+    SSHProcessInfo(const ProcessInfo& process);
+
+    /** 
+     * Returns the user name which the user initially logged into on
+     * the remote computer.
+     */
+    QString userName() const;
+
+    /**
+     * Returns the host which the user has connected to.
+     */
+    QString host() const;
+
+    /** 
+     * Returns the command which the user specified to execute on the 
+     * remote computer when starting the SSH process.
+     */
+    QString command() const;
+
+    /**
+     * Operates in the same way as ProcessInfo::format(), except
+     * that the set of markers understood is different:
+     *
+     * %u - Replaced with user name which the user initially logged
+     *      into on the remote computer.
+     * %h - Replaced with the first part of the host name which
+     *      is connected to.
+     * %H - Replaced with the full host name of the computer which
+     *      is connected to.
+     * %c - Replaced with the command which the user specified
+     *      to execute when starting the SSH process.
+     */
+    QString format(const QString& input) const;
+
+private:
+    const ProcessInfo& _process;
+    QString _user;
+    QString _host;
+    QString _command;
+};
+
+#endif //PROCESSINFO_H
+
+/*
+  Local Variables:
+  mode: c++
+  c-file-style: "stroustrup"
+  indent-tabs-mode: nil
+  tab-width: 4
+  End:
+*/
--- a/gui//src/Pty.cpp	Fri Apr 08 15:23:21 2011 +0200
+++ b/gui//src/Pty.cpp	Sat Apr 09 00:23:46 2011 +0200
@@ -1,8 +1,6 @@
 /*
     This file is part of Konsole, an X terminal.
-    Copyright (C) 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
-
-    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+    Copyright 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
 
     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
@@ -21,6 +19,8 @@
 */
 
 // Own
+#include "kprocess.h"
+#include "kptyprocess.h"
 #include "Pty.h"
 
 // System
@@ -29,15 +29,24 @@
 #include <unistd.h>
 #include <errno.h>
 #include <termios.h>
+#include <signal.h>
 
 // Qt
-#include <QtCore>
-#include "kpty.h"
+#include <QtCore/QStringList>
 
-void Pty::donePty()
-{
-  emit done(exitStatus());
-}
+// KDE
+//#include <KStandardDirs>
+//#include <KLocale>
+//#include <KDebug>
+//#include <KPty>
+//#include <KPtyDevice>
+//#include <kde_file.h>
+
+//#include "kdebug.h"
+
+#include "kpty.h"
+#include "kptydevice.h"
+
 
 void Pty::setWindowSize(int lines, int cols)
 {
@@ -52,7 +61,7 @@
     return QSize(_windowColumns,_windowLines);
 }
 
-void Pty::setXonXoff(bool enable)
+void Pty::setFlowControlEnabled(bool enable)
 {
   _xonXoff = enable;
 
@@ -64,10 +73,22 @@
       ttmode.c_iflag &= ~(IXOFF | IXON);
     else
       ttmode.c_iflag |= (IXOFF | IXON);
-    if (!pty()->tcSetAttr(&ttmode))
-      qWarning("Unable to set terminal attributes.");
+    //if (!pty()->tcSetAttr(&ttmode))
+    //  kWarning() << "Unable to set terminal attributes.";
   }
 }
+bool Pty::flowControlEnabled() const
+{
+    if (pty()->masterFd() >= 0)
+    {
+        struct ::termios ttmode;
+        pty()->tcGetAttr(&ttmode);
+        return ttmode.c_iflag & IXOFF &&
+               ttmode.c_iflag & IXON;
+    }  
+    //kWarning() << "Unable to get flow control status, terminal not connected.";
+    return false;
+}
 
 void Pty::setUtf8Mode(bool enable)
 {
@@ -82,8 +103,8 @@
       ttmode.c_iflag &= ~IUTF8;
     else
       ttmode.c_iflag |= IUTF8;
-    if (!pty()->tcSetAttr(&ttmode))
-      qWarning("Unable to set terminal attributes.");
+   // if (!pty()->tcSetAttr(&ttmode))
+    //  kWarning() << "Unable to set terminal attributes.";
   }
 #endif
 }
@@ -95,27 +116,23 @@
   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.");
-  }  
+    //if (!pty()->tcSetAttr(&ttmode))
+    //  kWarning() << "Unable to set terminal attributes.";
+  }
 }
 
 char Pty::erase() const
 {
-	if (pty()->masterFd() >= 0)
-	{
-		qDebug() << "Getting erase char";
-		struct ::termios ttyAttributes;
-		pty()->tcGetAttr(&ttyAttributes);
-		return ttyAttributes.c_cc[VERASE];
-	}
+    if (pty()->masterFd() >= 0)
+    {
+        struct ::termios ttyAttributes;
+        pty()->tcGetAttr(&ttyAttributes);
+        return ttyAttributes.c_cc[VERASE];
+    }
 
-	return _eraseChar;
+    return _eraseChar;
 }
 
 void Pty::addEnvironmentVariables(const QStringList& environment)
@@ -133,10 +150,7 @@
             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);
         }
     }
 }
@@ -145,46 +159,42 @@
                const QStringList& programArguments, 
                const QStringList& environment, 
                ulong winid, 
-               bool addToUtmp
-//               const QString& dbusService, 
-//               const QString& dbusSession)
-		)
+               bool addToUtmp,
+               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);
 
-  QStringListIterator it( programArguments );
-  while (it.hasNext())
-    arguments.append( it.next().toUtf8() );
+  if ( !dbusService.isEmpty() )
+     setEnv("KONSOLE_DBUS_SERVICE",dbusService);
+  if ( !dbusSession.isEmpty() )
+     setEnv("KONSOLE_DBUS_SESSION", dbusSession);
 
-//  if ( !dbusService.isEmpty() )
-//     setEnvironment("KONSOLE_DBUS_SERVICE",dbusService);
-//  if ( !dbusSession.isEmpty() )
-//     setEnvironment("KONSOLE_DBUS_SESSION", dbusSession);
-
-  setEnvironment("WINDOWID", QString::number(winid));
+  setEnv("WINDOWID", QString::number(winid));
 
   // 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
+  // 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
-  if (!environment.contains("LANGUAGE"))
-      setEnvironment("LANGUAGE",QString());
+  setEnv("LANGUAGE",QString(),false /* do not overwrite existing value if any */);
 
-  setUsePty(All, addToUtmp);
+  setUseUtmp(addToUtmp);
 
-  pty()->open();
-  
   struct ::termios ttmode;
   pty()->tcGetAttr(&ttmode);
   if (!_xonXoff)
@@ -199,103 +209,86 @@
 #endif
 
   if (_eraseChar != 0)
-  	ttmode.c_cc[VERASE] = _eraseChar;
+      ttmode.c_cc[VERASE] = _eraseChar;
   
-  if (!pty()->tcSetAttr(&ttmode))
-    qWarning("Unable to set terminal attributes.");
+  //if (!pty()->tcSetAttr(&ttmode))
+  //  kWarning() << "Unable to set terminal attributes.";
   
   pty()->setWinSize(_windowLines, _windowColumns);
 
-  if ( K3Process::start(NotifyOnExit, (Communication) (Stdin | Stdout)) == false )
-     return -1;
+  KProcess::start();
 
-  resume(); // Start...
+  if (!waitForStarted())
+      return -1;
+
   return 0;
-
 }
 
 void Pty::setWriteable(bool writeable)
 {
+  //KDE_struct_stat sbuf;
   struct stat sbuf;
-  stat(pty()->ttyName(), &sbuf);
+  //KDE_stat(pty()->ttyName(), &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)
+{
+    init();
+}
+Pty::Pty(QObject* parent)
+    : KPtyProcess(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();
+}
+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()
-{
-  _pendingSendJobs.erase(_pendingSendJobs.begin());
-  _bufferFull = false;
-  doSendJobs();
 }
 
-void Pty::doSendJobs() {
-  if(_pendingSendJobs.isEmpty())
-  {
-     emit bufferEmpty(); 
-     return;
-  }
+void Pty::sendData(const char* data, int length)
+{
+  if (!length)
+      return;
   
-  SendJob& job = _pendingSendJobs.first();
-
-  
-  if (!writeStdin( job.data(), job.length() ))
+  if (!pty()->write(data,length)) 
   {
-    qWarning("Pty::doSendJobs - Could not send input data to terminal process.");
+    //kWarning() << "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)
+void Pty::dataReceived() 
 {
-  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
@@ -310,4 +303,18 @@
     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);
+}
--- a/gui//src/Pty.h	Fri Apr 08 15:23:21 2011 +0200
+++ b/gui//src/Pty.h	Sat Apr 09 00:23:46 2011 +0200
@@ -1,10 +1,8 @@
 /*
     This file is part of Konsole, KDE's terminal emulator. 
     
-    Copyright (C) 2007 by Robert Knight <robertknight@gmail.com>
-    Copyright (C) 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
-
-    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+    Copyright 2007-2008 by Robert Knight <robertknight@gmail.com>
+    Copyright 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
 
     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,9 +27,15 @@
 #include <QtCore/QStringList>
 #include <QtCore/QVector>
 #include <QtCore/QList>
-#include <QtCore>
+#include <QtCore/QSize>
 
-#include "k3process.h"
+// KDE
+//#include <KPtyProcess>
+#include "kprocess.h"
+#include "kptyprocess.h"
+
+// Konsole
+#include "konsole_export.h"
 
 /**
  * The Pty class is used to start the terminal process, 
@@ -46,7 +50,8 @@
  * To start the terminal process, call the start() method
  * with the program name and appropriate arguments. 
  */
-class Pty: public K3Process
+//class KONSOLEPRIVATE_EXPORT Pty: public KPtyProcess
+class KONSOLEPRIVATE_EXPORT Pty: public KPtyProcess
 {
 Q_OBJECT
 
@@ -61,7 +66,14 @@
      * 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();
 
     /**
@@ -88,18 +100,23 @@
                const QStringList& arguments, 
                const QStringList& environment, 
                ulong winid, 
-               bool addToUtmp
-//               const QString& dbusService,
-//               const QString& dbusSession
+               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);
+
+    /** 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) 
@@ -113,8 +130,8 @@
     /** TODO Document me */
     void setErase(char erase);
 
-	/** */
-	char erase() const;
+    /** */
+    char erase() const;
 
     /**
      * Returns the process id of the teletype's current foreground
@@ -126,13 +143,6 @@
      */
     int foregroundProcessGroup() const;
    
-    /**
-     * Returns whether the buffer used to send data to the
-     * terminal process is full.
-     */
-    bool bufferFull() const { return _bufferFull; }
-
-
   public slots:
 
     /**
@@ -163,13 +173,6 @@
   signals:
 
     /**
-     * Emitted when the terminal process terminates.
-     *
-     * @param exitCode The status code which the process exited with.
-     */
-    void done(int exitCode);
-
-    /**
      * Emitted when a new block of data is received from
      * the teletype.
      *
@@ -177,60 +180,26 @@
      * @param length Length of @p buffer
      */
     void receivedData(const char* buffer, int length);
-    
-    /**
-     * Emitted when the buffer used to send data to the terminal
-     * process becomes empty, i.e. all data has been sent.
-     */
-    void bufferEmpty();
-    
+   
+  protected:
+      void setupChildProcess();
 
   private slots:
+    // called when data is received from the terminal process 
+    void dataReceived(); 
     
-    // 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:
+      void init();
 
-  private:
     // takes a list of key=value pairs and adds them
     // to the environment for the process
     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<char> buffer;
-    };
-
-    QList<SendJob> _pendingSendJobs;
-    bool _bufferFull;
-
     int  _windowColumns; 
     int  _windowLines;
     char _eraseChar;
     bool _xonXoff;
     bool _utf8;
-    KPty *_pty;
 };
+
 #endif // PTY_H
--- a/gui//src/QTerminalWidget.cpp	Fri Apr 08 15:23:21 2011 +0200
+++ b/gui//src/QTerminalWidget.cpp	Sat Apr 09 00:23:46 2011 +0200
@@ -123,6 +123,14 @@
     m_impl->m_session->setProgram(progname);	
 }
 
+void QTerminalWidget::openTeletype(int fd)
+{
+  if ( m_impl->m_session->isRunning() )
+    return;
+
+  m_impl->m_session->openTeletype(fd);
+}
+
 void QTerminalWidget::setArgs(QStringList &args)
 {
     if (!m_impl->m_session)
@@ -139,6 +147,7 @@
 
 void QTerminalWidget::setColorScheme(ColorScheme scheme)
 {
+    /*
     switch(scheme) {
         case WhiteOnBlack:
 		m_impl->m_terminalDisplay->setColorTable(whiteonblack_color_table);
@@ -149,7 +158,7 @@
         case BlackOnLightYellow:
 		m_impl->m_terminalDisplay->setColorTable(blackonlightyellow_color_table);
 		break;
-    };
+    };*/
 }
 
 void QTerminalWidget::setSize(int h, int v)
--- a/gui//src/QTerminalWidget.h	Fri Apr 08 15:23:21 2011 +0200
+++ b/gui//src/QTerminalWidget.h	Sat Apr 09 00:23:46 2011 +0200
@@ -55,6 +55,7 @@
     ~QTerminalWidget();
 
     void startShellProgram();
+    void openTeletype(int fd);
 
     /** Default is application font with family Monospace, size 10. */
     void setTerminalFont(QFont &font); 
--- a/gui//src/Quint.cpp	Fri Apr 08 15:23:21 2011 +0200
+++ b/gui//src/Quint.cpp	Sat Apr 09 00:23:46 2011 +0200
@@ -19,6 +19,18 @@
 #include <QtGui/QApplication>
 #include "MainWindow.h"
 
+// System
+#include <termios.h>
+#include <sys/types.h>
+#include <signal.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+
+#include <iostream>
+#include "pty.h"
+#include <assert.h>
+#include "QTerminalWidget.h"
+
 int main(int argc, char *argv[])
 {
     QApplication a(argc, argv);
--- a/gui//src/Screen.cpp	Fri Apr 08 15:23:21 2011 +0200
+++ b/gui//src/Screen.cpp	Sat Apr 09 00:23:46 2011 +0200
@@ -1,24 +1,24 @@
 /*
-    This file is part of Konsole, an X terminal.
-    Copyright (C) 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
+   This file is part of Konsole, an X terminal.
 
-    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+   Copyright 2007-2008 by Robert Knight <robert.knight@gmail.com>
+   Copyright 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
 
-    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 <QtCore/QTextStream>
 #include <QtCore/QDate>
 
+// KDE
+//#include <kdebug.h>
+
 // Konsole
 #include "konsole_wcwidth.h"
 #include "TerminalCharacterDecoder.h"
@@ -58,38 +61,34 @@
 
 
 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),
+    Screen::Screen(int l, int c)
+: lines(l),
     columns(c),
     screenLines(new ImageLine[lines+1] ),
     _scrolledLines(0),
     _droppedLines(0),
-    hist(new HistoryScrollNone()),
+    history(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),
+    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<lines+1;i++)
-          lineProperties[i]=LINE_DEFAULT;
+    lineProperties.resize(lines+1);
+    for (int i=0;i<lines+1;i++)
+        lineProperties[i]=LINE_DEFAULT;
 
-  initTabStops();
-  clearSelection();
-  reset();
+    initTabStops();
+    clearSelection();
+    reset();
 }
 
 /*! Destructor
@@ -97,332 +96,245 @@
 
 Screen::~Screen()
 {
-  delete[] screenLines;
-  delete[] tabstops;
-  delete hist;
+    delete[] screenLines;
+    delete history;
 }
 
-/* ------------------------------------------------------------------------- */
-/*                                                                           */
-/* Normalized                    Screen Operations                           */
-/*                                                                           */
-/* ------------------------------------------------------------------------- */
-
-// Cursor Setting --------------------------------------------------------------
-
-/*! \section Cursor
-
-    The `cursor' is a location within the screen that is implicitely used in
-    many operations. The operations within this section allow to manipulate
-    the cursor explicitly and to obtain it's value.
-
-    The position of the cursor is guarantied to be between (including) 0 and
-    `columns-1' and `lines-1'.
-*/
-
-/*!
-    Move the cursor up.
-
-    The cursor will not be moved beyond the top margin.
-*/
-
 void Screen::cursorUp(int n)
-//=CUU
+    //=CUU
 {
-  if (n == 0) n = 1; // Default
-  int stop = cuY < tmargin ? 0 : tmargin;
-  cuX = qMin(columns-1,cuX); // nowrap!
-  cuY = qMax(stop,cuY-n);
+    if (n == 0) n = 1; // Default
+    int stop = cuY < _topMargin ? 0 : _topMargin;
+    cuX = qMin(columns-1,cuX); // nowrap!
+    cuY = qMax(stop,cuY-n);
 }
 
-/*!
-    Move the cursor down.
-
-    The cursor will not be moved beyond the bottom margin.
-*/
-
 void Screen::cursorDown(int n)
-//=CUD
+    //=CUD
 {
-  if (n == 0) n = 1; // Default
-  int stop = cuY > bmargin ? lines-1 : bmargin;
-  cuX = qMin(columns-1,cuX); // nowrap!
-  cuY = qMin(stop,cuY+n);
+    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
-  cuX = qMin(columns-1,cuX); // nowrap!
-  cuX = qMax(0,cuX-n);
+    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
-  cuX = qMin(columns-1,cuX+n);
+    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
-  top = top - 1;              // Adjust to internal lineno
-  bot = bot - 1;              // Adjust to internal lineno
-  if ( !( 0 <= top && top < bot && bot < lines ) )
-  { qDebug()<<" setRegion("<<top<<","<<bot<<") : bad range.";
-    return;                   // Default error action: ignore
-  }
-  tmargin = top;
-  bmargin = bot;
-  cuX = 0;
-  cuY = getMode(MODE_Origin) ? top : 0;
+    if (top == 0) top = 1;      // Default
+    if (bot == 0) bot = lines;  // Default
+    top = top - 1;              // Adjust to internal lineno
+    bot = bot - 1;              // Adjust to internal lineno
+    if ( !( 0 <= top && top < bot && bot < lines ) )
+    { //Debug()<<" setRegion("<<top<<","<<bot<<") : bad range.";
+        return;                   // Default error action: ignore
+    }
+    _topMargin = top;
+    _bottomMargin = bot;
+    cuX = 0;
+    cuY = getMode(MODE_Origin) ? top : 0;
 
 }
 
 int Screen::topMargin() const
 {
-    return tmargin;
+    return _topMargin;
 }
 int Screen::bottomMargin() const
 {
-    return bmargin;
+    return _bottomMargin;
 }
 
 void Screen::index()
-//=IND
+    //=IND
 {
-  if (cuY == bmargin)
-  {
-    scrollUp(1);
-  }
-  else if (cuY < lines-1)
-    cuY += 1;
+    if (cuY == _bottomMargin)
+        scrollUp(1);
+    else if (cuY < lines-1)
+        cuY += 1;
 }
 
 void Screen::reverseIndex()
-//=RI
+    //=RI
 {
-  if (cuY == tmargin)
-     scrollDown(tmargin,1);
-  else if (cuY > 0)
-    cuY -= 1;
+    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
-  int p = qMax(0,qMin(cuX+n-1,columns-1));
-  clearImage(loc(cuX,cuY),loc(p,cuY),' ');
+    if (n == 0) n = 1; // Default
+    int p = qMax(0,qMin(cuX+n-1,columns-1));
+    clearImage(loc(cuX,cuY),loc(p,cuY),' ');
 }
 
 void Screen::deleteChars(int n)
 {
-  Q_ASSERT( n >= 0 );
+    Q_ASSERT( n >= 0 );
 
-  // always delete at least one char
-  if (n == 0) 
-      n = 1; 
+    // always delete at least one char
+    if (n == 0) 
+        n = 1; 
 
-  // if cursor is beyond the end of the line there is nothing to do
-  if ( cuX >= screenLines[cuY].count() )
-      return;
+    // if cursor is beyond the end of the line there is nothing to do
+    if ( cuX >= screenLines[cuY].count() )
+        return;
 
-  if ( cuX+n >= screenLines[cuY].count() ) 
-       n = screenLines[cuY].count() - 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( n >= 0 );
+    Q_ASSERT( cuX+n <= screenLines[cuY].count() );
 
-  screenLines[cuY].remove(cuX,n);
+    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 )
-    screenLines[cuY].resize(cuX);
+    if ( screenLines[cuY].size() < cuX )
+        screenLines[cuY].resize(cuX);
 
-  screenLines[cuY].insert(cuX,n,' ');
+    screenLines[cuY].insert(cuX,n,' ');
 
-  if ( screenLines[cuY].count() > columns )
-      screenLines[cuY].resize(columns);
+    if ( screenLines[cuY].count() > columns )
+        screenLines[cuY].resize(columns);
 }
 
 void Screen::deleteLines(int n)
 {
-  if (n == 0) n = 1; // Default
-  scrollUp(cuY,n);
+    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
-  scrollDown(cuY,n);
+    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++)
+        newScreenLines[i]=screenLines[i];
+    for (int i=lines;(i > 0) && (i<new_lines+1);i++)
+        newScreenLines[i].resize( new_columns );
 
-  // create new screen lines and copy from old to new
-  
-   ImageLine* newScreenLines = new ImageLine[new_lines+1];
-   for (int i=0; i < qMin(lines-1,new_lines+1) ;i++)
-           newScreenLines[i]=screenLines[i];
-   for (int i=lines;(i > 0) && (i<new_lines+1);i++)
-           newScreenLines[i].resize( new_columns );
-   
-  lineProperties.resize(new_lines+1);
-  for (int i=lines;(i > 0) && (i<new_lines+1);i++)
-          lineProperties[i] = LINE_DEFAULT;
+    lineProperties.resize(new_lines+1);
+    for (int i=lines;(i > 0) && (i<new_lines+1);i++)
+        lineProperties[i] = LINE_DEFAULT;
+
+    clearSelection();
+
+    delete[] screenLines; 
+    screenLines = newScreenLines;
 
-  clearSelection();
- 
-  delete[] screenLines; 
-  screenLines = newScreenLines;
+    lines = new_lines;
+    columns = new_columns;
+    cuX = qMin(cuX,columns-1);
+    cuY = qMin(cuY,lines-1);
 
-  lines = new_lines;
-  columns = new_columns;
-  cuX = qMin(cuX,columns-1);
-  cuY = qMin(cuY,lines-1);
-
-  // FIXME: try to keep values, evtl.
-  tmargin=0;
-  bmargin=lines-1;
-  initTabStops();
-  clearSelection();
+    // FIXME: try to keep values, evtl.
+    _topMargin=0;
+    _bottomMargin=lines-1;
+    initTabStops();
+    clearSelection();
 }
 
 void Screen::setDefaultMargins()
 {
-	tmargin = 0;
-	bmargin = lines-1;
+    _topMargin = 0;
+    _bottomMargin = lines-1;
 }
 
 
@@ -430,10 +342,10 @@
    Clarifying rendition here and in the display.
 
    currently, the display's color table is
-     0       1       2 .. 9    10 .. 17
-     dft_fg, dft_bg, dim 0..7, intensive 0..7
+   0       1       2 .. 9    10 .. 17
+   dft_fg, dft_bg, dim 0..7, intensive 0..7
 
-   cu_fg, cu_bg contain values 0..8;
+   currentForeground, currentBackground contain values 0..8;
    - 0    = default color
    - 1..8 = ansi specified color
 
@@ -442,14 +354,14 @@
 
    rendition attributes are
 
-      attr           widget screen
-      -------------- ------ ------
-      RE_UNDERLINE     XX     XX    affects foreground only
-      RE_BLINK         XX     XX    affects foreground only
-      RE_BOLD          XX     XX    affects foreground only
-      RE_REVERSE       --     XX
-      RE_TRANSPARENT   XX     --    affects background only
-      RE_INTENSIVE     XX     --    affects foreground only
+   attr           widget screen
+   -------------- ------ ------
+   RE_UNDERLINE     XX     XX    affects foreground only
+   RE_BLINK         XX     XX    affects foreground only
+   RE_BOLD          XX     XX    affects foreground only
+   RE_REVERSE       --     XX
+   RE_TRANSPARENT   XX     --    affects background only
+   RE_INTENSIVE     XX     --    affects foreground only
 
    Note that RE_BOLD is used in both widget
    and screen rendition. Since xterm/vt102
@@ -458,381 +370,334 @@
    (which is a color attribute), we translate
    this and RE_BOLD in falls eventually appart
    into RE_BOLD and RE_INTENSIVE.
-*/
+   */
 
 void Screen::reverseRendition(Character& p) const
 { 
-	CharacterColor f = p.foregroundColor; 
-	CharacterColor b = p.backgroundColor;
-  	
-	p.foregroundColor = b; 
-	p.backgroundColor = f; //p->r &= ~RE_TRANSPARENT;
+    CharacterColor f = p.foregroundColor; 
+    CharacterColor b = p.backgroundColor;
+
+    p.foregroundColor = b; 
+    p.backgroundColor = f; //p->r &= ~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;
-  }
- 
-  if (cu_re & RE_BOLD)
-    ef_fg.toggleIntensive();
+    effectiveRendition = currentRendition;
+    if (currentRendition & RE_REVERSE)
+    {
+        effectiveForeground = currentBackground;
+        effectiveBackground = currentForeground;
+    }
+    else
+    {
+        effectiveForeground = currentForeground;
+        effectiveBackground = currentBackground;
+    }
+
+    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
 {
-  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));
-    const int destLineOffset  = (line-startLine)*columns;
+    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++) 
+            dest[destLineOffset+column] = defaultChar;
 
-    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]); 
-    		}
-  		}
-	}
-  }
+        // invert selected text
+        if (selBegin !=-1)
+        {
+            for (int column = 0; column < columns; column++)
+            {
+                if (isSelected(column,line)) 
+                {
+                    reverseRendition(dest[destLineOffset + column]); 
+                }
+            }
+        }
+    }
 }
 
 void Screen::copyFromScreen(Character* dest , int startLine , int count) const
 {
-	Q_ASSERT( startLine >= 0 && count > 0 && startLine + count <= lines );
+    Q_ASSERT( startLine >= 0 && count > 0 && startLine + count <= lines );
 
     for (int line = startLine; line < (startLine+count) ; line++)
     {
-       int srcLineStartIndex  = line*columns;
-	   int destLineStartIndex = (line-startLine)*columns;
+        int srcLineStartIndex  = line*columns;
+        int destLineStartIndex = (line-startLine)*columns;
 
-       for (int column = 0; column < columns; column++)
-       { 
-		 int srcIndex = srcLineStartIndex + column; 
-		 int destIndex = destLineStartIndex + 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);
+            dest[destIndex] = screenLines[srcIndex/columns].value(srcIndex%columns,defaultChar);
 
-	     // invert selected text
-         if (sel_begin != -1 && isSelected(column,line + hist->getLines()))
-           reverseRendition(dest[destIndex]); 
-       }
+            // invert selected text
+            if (selBegin != -1 && isSelected(column,line + history->getLines()))
+                reverseRendition(dest[destIndex]); 
+        }
 
     }
 }
 
 void Screen::getImage( Character* dest, int size, int startLine, int endLine ) const
 {
-  Q_ASSERT( startLine >= 0 ); 
-  Q_ASSERT( endLine >= startLine && endLine < hist->getLines() + lines );
+    Q_ASSERT( startLine >= 0 );
+    Q_ASSERT( endLine >= startLine && endLine < history->getLines() + lines );
+
+    const int mergedLines = endLine - startLine + 1;
 
-  const int mergedLines = endLine - startLine + 1;
+    Q_ASSERT( size >= mergedLines * columns ); 
+    Q_UNUSED( size );
 
-  Q_ASSERT( size >= mergedLines * columns ); 
+    const int linesInHistoryBuffer = qBound(0,history->getLines()-startLine,mergedLines);
+    const int linesInScreenBuffer = mergedLines - linesInHistoryBuffer;
 
-  const int linesInHistoryBuffer = qBound(0,hist->getLines()-startLine,mergedLines);
-  const int linesInScreenBuffer = mergedLines - linesInHistoryBuffer;
+    // copy lines from history buffer
+    if (linesInHistoryBuffer > 0)
+        copyFromHistory(dest,startLine,linesInHistoryBuffer); 
 
-  // copy lines from history buffer
-  if (linesInHistoryBuffer > 0) {
-  	copyFromHistory(dest,startLine,linesInHistoryBuffer); 
+    // copy lines from screen buffer
+    if (linesInScreenBuffer > 0)
+        copyFromScreen(dest + linesInHistoryBuffer*columns,
+                startLine + linesInHistoryBuffer - history->getLines(),
+                linesInScreenBuffer);
+
+    // invert display when in screen mode
+    if (getMode(MODE_Screen))
+    {
+        for (int i = 0; i < mergedLines*columns; i++)
+            reverseRendition(dest[i]); // for reverse display
     }
 
-  // copy lines from screen buffer
-  if (linesInScreenBuffer > 0) {
-  	copyFromScreen(dest + linesInHistoryBuffer*columns,
-				   startLine + linesInHistoryBuffer - hist->getLines(),
-				   linesInScreenBuffer);
-    }				
- 
-  // invert display when in screen mode
-  if (getMode(MODE_Screen))
-  {  
-    for (int i = 0; i < mergedLines*columns; i++)
-      reverseRendition(dest[i]); // for reverse display
-  }
-
-  // mark the character at the current cursor position
-  int cursorIndex = loc(cuX, cuY + linesInHistoryBuffer);
-  if(getMode(MODE_Cursor) && cursorIndex < columns*mergedLines)
-    dest[cursorIndex].rendition |= RE_CURSOR;
+    // mark the character at the current cursor position
+    int cursorIndex = loc(cuX, cuY + linesInHistoryBuffer);
+    if(getMode(MODE_Cursor) && cursorIndex < columns*mergedLines)
+        dest[cursorIndex].rendition |= RE_CURSOR;
 }
 
 QVector<LineProperty> 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 linesInScreen = mergedLines - linesInHistory;
+    const int mergedLines = endLine-startLine+1;
+    const int linesInHistory = qBound(0,history->getLines()-startLine,mergedLines);
+    const int linesInScreen = mergedLines - linesInHistory;
 
-  QVector<LineProperty> result(mergedLines);
-  int index = 0;
+    QVector<LineProperty> result(mergedLines);
+    int index = 0;
 
-  // copy properties for lines in history
-  for (int line = startLine; line < startLine + linesInHistory; line++) 
-  {
-		//TODO Support for line properties other than wrapped lines
-	  if (hist->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++)
-	{
-    result[index]=lineProperties[line];
-  	index++;
-	}
+    // copy properties for lines in history
+    for (int line = startLine; line < startLine + linesInHistory; line++) 
+    {
+        //TODO Support for line properties other than wrapped lines
+        if (history->isWrappedLine(line))
+        {
+            result[index] = (LineProperty)(result[index] | LINE_WRAPPED);
+        }
+        index++;
+    }
 
-  return result;
-}
+    // copy properties for lines in screen buffer
+    const int firstScreenLine = startLine + linesInHistory - history->getLines();
+    for (int line = firstScreenLine; line < firstScreenLine+linesInScreen; line++)
+    {
+        result[index]=lineProperties[line];
+        index++;
+    }
 
-/*!
-*/
+    return result;
+}
 
 void Screen::reset(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
+    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;
+    resetMode(MODE_Screen);                         // screen not inverse
+    resetMode(MODE_NewLine);
 
-  setDefaultRendition();
-  saveCursor();
+    _topMargin=0;
+    _bottomMargin=lines-1;
 
-  if ( clearScreen )
-    clear();
+    setDefaultRendition();
+    saveCursor();
+
+    if ( clearScreen )
+        clear();
 }
 
-/*! Clear the entire screen and home the cursor.
-*/
-
 void Screen::clear()
 {
-  clearEntireScreen();
-  home();
+    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 = ' ';
+    cuX = qMin(columns-1,cuX); // nowrap!
+    cuX = qMax(0,cuX-1);
 
-  if (screenLines[cuY].size() < cuX+1)
-          screenLines[cuY].resize(cuX+1);
+    if (screenLines[cuY].size() < cuX+1)
+        screenLines[cuY].resize(cuX+1);
 
-  if (BS_CLEARS) screenLines[cuY][cuX].character = ' ';
+    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]) cursorRight(1);
-    n--;
-  }
+    // note that TAB is a format effector (does not write ' ');
+    if (n == 0) n = 1;
+    while((n > 0) && (cuX < columns-1))
+    {
+        cursorRight(1); 
+        while((cuX < columns-1) && !tabStops[cuX]) 
+            cursorRight(1);
+        n--;
+    }
 }
 
-void Screen::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);
-     n--;
-  }
+    // note that TAB is a format effector (does not write ' ');
+    if (n == 0) n = 1;
+    while((n > 0) && (cuX > 0))
+    {
+        cursorLeft(1); while((cuX > 0) && !tabStops[cuX]) cursorLeft(1);
+        n--;
+    }
 }
 
 void Screen::clearTabStops()
 {
-  for (int i = 0; i < columns; i++) tabstops[i] = false;
+    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);
+    // 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);
 }
 
-/*!
-   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();
-  index();
+    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) return;
-  int scr_TL = loc(0, hist->getLines());
-  //Clear entire selection if it overlaps region [from, to]
-  if ( (sel_BR > (from+scr_TL) )&&(sel_TL < (to+scr_TL)) )
-  {
-    clearSelection();
-  }
+    if (selBegin == -1) 
+        return;
+    int scr_TL = loc(0, history->getLines());
+    //Clear entire selection if it overlaps region [from, to]
+    if ( (selBottomRight >= (from+scr_TL)) && (selTopLeft <= (to+scr_TL)) )
+        clearSelection();
 }
 
-void Screen::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.
-  // We indicate the fact that a newline has to be triggered by
-  // putting the cursor one right to the last column of the screen.
+    // Note that VT100 does wrapping BEFORE putting the character.
+    // This has impact on the assumption of valid cursor positions.
+    // We indicate the fact that a newline has to be triggered by
+    // putting the cursor one right to the last column of the screen.
 
-  int w = konsole_wcwidth(c);
-
-  if (w <= 0)
-     return;
+    int w = konsole_wcwidth(c);
+    if (w <= 0)
+        return;
 
-  if (cuX+w > columns) {
-    if (getMode(MODE_Wrap)) {
-      lineProperties[cuY] = (LineProperty)(lineProperties[cuY] | LINE_WRAPPED);
-      NextLine();
+    if (cuX+w > columns) {
+        if (getMode(MODE_Wrap)) {
+            lineProperties[cuY] = (LineProperty)(lineProperties[cuY] | LINE_WRAPPED);
+            nextLine();
+        }
+        else
+            cuX = columns-w;
     }
-    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
-  {
+    // ensure current line vector has enough elements
+    int size = screenLines[cuY].size();
     if (size < cuX+w)
     {
-          screenLines[cuY].resize(cuX+w);
+        screenLines[cuY].resize(cuX+w);
     }
-  }
 
-  if (getMode(MODE_Insert)) insertChars(w);
+    if (getMode(MODE_Insert)) insertChars(w);
 
-  lastPos = loc(cuX,cuY);
+    lastPos = loc(cuX,cuY);
 
-  // check if selection is still valid.
-  checkSelection(cuX,cuY);
+    // check if selection is still valid.
+    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.character = c;
+    currentChar.foregroundColor = effectiveForeground;
+    currentChar.backgroundColor = effectiveBackground;
+    currentChar.rendition = effectiveRendition;
 
-  int i = 0;
-  int newCursorX = cuX + w--;
-  while(w)
-  {
-     i++;
-   
-     if ( screenLines[cuY].size() < cuX + i + 1 )
-         screenLines[cuY].resize(cuX+i+1);
-     
-     Character& ch = screenLines[cuY][cuX + i];
-     ch.character = 0;
-     ch.foregroundColor = ef_fg;
-     ch.backgroundColor = ef_bg;
-     ch.rendition = ef_re;
+    int i = 0;
+    int newCursorX = cuX + w--;
+    while(w)
+    {
+        i++;
+
+        if ( screenLines[cuY].size() < cuX + i + 1 )
+            screenLines[cuY].resize(cuX+i+1);
 
-     w--;
-  }
-  cuX = newCursorX;
+        Character& ch = screenLines[cuY][cuX + i];
+        ch.character = 0;
+        ch.foregroundColor = effectiveForeground;
+        ch.backgroundColor = effectiveBackground;
+        ch.rendition = effectiveRendition;
+
+        w--;
+    }
+    cuX = newCursorX;
 }
 
 void Screen::compose(const QString& /*compose*/)
 {
-   Q_ASSERT( 0 /*Not implemented yet*/ );
+    Q_ASSERT( 0 /*Not implemented yet*/ );
+
+    /*  if (lastPos == -1)
+        return;
 
-/*  if (lastPos == -1)
-     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
 {
-        return _scrolledLines;
+    return _scrolledLines;
 }
 int Screen::droppedLines() const
 {
@@ -844,25 +709,16 @@
 }
 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;
@@ -870,122 +726,99 @@
 
 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));
+    _scrolledLines -= n;
+    _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;
+    _scrolledLines += n;
 
-//FIXME: make sure `tmargin', `bmargin', `from', `n' is in bounds.
-  if (n <= 0) return;
-  if (from > bmargin) return;
-  if (from + n > bmargin) n = bmargin - from;
-  moveImage(loc(0,from+n),loc(0,from),loc(columns-1,bmargin-n));
-  clearImage(loc(0,from),loc(columns-1,from+n-1),' ');
+    //FIXME: make sure `topMargin', `bottomMargin', `from', `n' is in bounds.
+    if (n <= 0) 
+        return;
+    if (from > _bottomMargin) 
+        return;
+    if (from + n > _bottomMargin) 
+        n = _bottomMargin - from;
+    moveImage(loc(0,from+n),loc(0,from),loc(columns-1,_bottomMargin-n));
+    clearImage(loc(0,from),loc(columns-1,from+n-1),' ');
 }
 
 void Screen::setCursorYX(int y, int x)
 {
-  setCursorY(y); setCursorX(x);
+    setCursorY(y); setCursorX(x);
 }
 
 void Screen::setCursorX(int x)
 {
-  if (x == 0) x = 1; // Default
-  x -= 1; // Adjust
-  cuX = qMax(0,qMin(columns-1, x));
+    if (x == 0) x = 1; // Default
+    x -= 1; // Adjust
+    cuX = qMax(0,qMin(columns-1, x));
 }
 
 void Screen::setCursorY(int y)
 {
-  if (y == 0) y = 1; // Default
-  y -= 1; // Adjust
-  cuY = qMax(0,qMin(lines  -1, y + (getMode(MODE_Origin) ? tmargin : 0) ));
+    if (y == 0) y = 1; // Default
+    y -= 1; // Adjust
+    cuY = qMax(0,qMin(lines  -1, y + (getMode(MODE_Origin) ? _topMargin : 0) ));
 }
 
 void Screen::home()
 {
-  cuX = 0;
-  cuY = 0;
+    cuX = 0;
+    cuY = 0;
 }
 
-void Screen::Return()
+void Screen::toStartOfLine()
 {
-  cuX = 0;
+    cuX = 0;
 }
 
 int Screen::getCursorX() const
 {
-  return cuX;
+    return cuX;
 }
 
 int Screen::getCursorY() const
 {
-  return cuY;
+    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());
-  //FIXME: check positions
+    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)) )
-  {
-    clearSelection();
-  }
+    //Clear entire selection if it overlaps region to be moved...
+    if ( (selBottomRight > (loca+scr_TL) )&&(selTopLeft < (loce+scr_TL)) )
+    {
+        clearSelection();
+    }
 
-  int topLine = loca/columns;
-  int bottomLine = loce/columns;
+    int topLine = loca/columns;
+    int bottomLine = loce/columns;
+
+    Character clearCh(c,currentForeground,currentBackground,DEFAULT_RENDITION);
 
-  Character clearCh(c,cu_fg,cu_bg,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());
+    //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;
@@ -1006,203 +839,181 @@
             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 );
 
-  Q_ASSERT( sourceBegin <= sourceEnd );
- 
-  int lines=(sourceEnd-sourceBegin)/columns;
+    int lines=(sourceEnd-sourceBegin)/columns;
 
-  //move screen image and line properties:
-  //the source and destination areas of the image may overlap, 
-  //so it matters that we do the copy in the right order - 
-  //forwards if dest < sourceBegin or backwards otherwise.
-  //(search the web for 'memmove implementation' for details)
-  if (dest < sourceBegin)
-  {
-    for (int i=0;i<=lines;i++)
+    //move screen image and line properties:
+    //the source and destination areas of the image may overlap, 
+    //so it matters that we do the copy in the right order - 
+    //forwards if dest < sourceBegin or backwards otherwise.
+    //(search the web for 'memmove implementation' for details)
+    if (dest < sourceBegin)
+    {
+        for (int i=0;i<=lines;i++)
+        {
+            screenLines[ (dest/columns)+i ] = screenLines[ (sourceBegin/columns)+i ];
+            lineProperties[(dest/columns)+i]=lineProperties[(sourceBegin/columns)+i];
+        }
+    }
+    else
     {
-        screenLines[ (dest/columns)+i ] = screenLines[ (sourceBegin/columns)+i ];
-        lineProperties[(dest/columns)+i]=lineProperties[(sourceBegin/columns)+i];
+        for (int i=lines;i>=0;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--)
+
+    if (lastPos != -1)
     {
-        screenLines[ (dest/columns)+i ] = screenLines[ (sourceBegin/columns)+i ];
-        lineProperties[(dest/columns)+i]=lineProperties[(sourceBegin/columns)+i];
+        int diff = dest - sourceBegin; // Scroll by this amount
+        lastPos += diff;
+        if ((lastPos < 0) || (lastPos >= (lines*columns)))
+            lastPos = -1;
     }
-  }
 
-  if (lastPos != -1)
-  {
-     int diff = dest - sourceBegin; // Scroll by this amount
-     lastPos += diff;
-     if ((lastPos < 0) || (lastPos >= (lines*columns)))
-        lastPos = -1;
-  }
-     
-  // Adjust selection to follow scroll.
-  if (sel_begin != -1)
-  {
-     bool beginIsTL = (sel_begin == sel_TL);
-     int diff = dest - sourceBegin; // Scroll by this amount
-     int scr_TL=loc(0,hist->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;
+    // Adjust selection to follow scroll.
+    if (selBegin != -1)
+    {
+        bool beginIsTL = (selBegin == selTopLeft);
+        int diff = dest - sourceBegin; // Scroll by this amount
+        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 ((selTopLeft >= srca) && (selTopLeft <= srce))
+            selTopLeft += diff;
+        else if ((selTopLeft >= desta) && (selTopLeft <= deste))
+            selBottomRight = -1; // Clear selection (see below)
 
-     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 ((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)
-     {
-        clearSelection();
-     }
-     else
-     {
-        if (sel_TL < 0)
-           sel_TL = 0;
-     }
+        if (selBottomRight < 0)
+        {
+            clearSelection();
+        }
+        else
+        {
+            if (selTopLeft < 0)
+                selTopLeft = 0;
+        }
 
-     if (beginIsTL)
-        sel_begin = sel_TL;
-     else
-        sel_begin = sel_BR;
-  }
+        if (beginIsTL)
+            selBegin = selTopLeft;
+        else
+            selBegin = selBottomRight;
+    }
 }
 
 void Screen::clearToEndOfScreen()
 {
-  clearImage(loc(cuX,cuY),loc(columns-1,lines-1),' ');
+    clearImage(loc(cuX,cuY),loc(columns-1,lines-1),' ');
 }
 
 void Screen::clearToBeginOfScreen()
 {
-  clearImage(loc(0,0),loc(cuX,cuY),' ');
+    clearImage(loc(0,0),loc(cuX,cuY),' ');
 }
 
 void Screen::clearEntireScreen()
 {
-  // Add entire screen to history
-  for (int i = 0; i < (lines-1); i++)
-  {
-    addHistLine(); scrollUp(0,1);
-  }
+    // Add entire screen to history
+    for (int i = 0; i < (lines-1); i++)
+    {
+        addHistLine(); scrollUp(0,1);
+    }
 
-  clearImage(loc(0,0),loc(columns-1,lines-1),' ');
+    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()
 {
-  clearImage(loc(0,0),loc(columns-1,lines-1),'E');
+    clearImage(loc(0,0),loc(columns-1,lines-1),'E');
 }
 
 void Screen::clearToEndOfLine()
 {
-  clearImage(loc(cuX,cuY),loc(columns-1,cuY),' ');
+    clearImage(loc(cuX,cuY),loc(columns-1,cuY),' ');
 }
 
 void Screen::clearToBeginOfLine()
 {
-  clearImage(loc(0,cuY),loc(cuX,cuY),' ');
+    clearImage(loc(0,cuY),loc(cuX,cuY),' ');
 }
 
 void Screen::clearEntireLine()
 {
-  clearImage(loc(0,cuY),loc(columns-1,cuY),' ');
+    clearImage(loc(0,cuY),loc(columns-1,cuY),' ');
 }
 
 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();
+    setForeColor(COLOR_SPACE_DEFAULT,DEFAULT_FORE_COLOR);
+    setBackColor(COLOR_SPACE_DEFAULT,DEFAULT_BACK_COLOR);
+    currentRendition   = DEFAULT_RENDITION;
+    updateEffectiveRendition();
 }
 
 void Screen::setForeColor(int space, int color)
 {
-  cu_fg = CharacterColor(space, color);
+    currentForeground = CharacterColor(space, color);
 
-  if ( cu_fg.isValid() ) 
-    effectiveRendition();
-  else 
-    setForeColor(COLOR_SPACE_DEFAULT,DEFAULT_FORE_COLOR);
+    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
-    setBackColor(COLOR_SPACE_DEFAULT,DEFAULT_BACK_COLOR);
+    if ( currentBackground.isValid() ) 
+        updateEffectiveRendition();
+    else
+        setBackColor(COLOR_SPACE_DEFAULT,DEFAULT_BACK_COLOR);
 }
 
-/* ------------------------------------------------------------------------- */
-/*                                                                           */
-/*                            Marking & Selection                            */
-/*                                                                           */
-/* ------------------------------------------------------------------------- */
-
-void Screen::clearSelection()
+void Screen::clearSelection() 
 {
-  sel_BR = -1;
-  sel_TL = -1;
-  sel_begin = -1;
+    selBottomRight = -1;
+    selTopLeft = -1;
+    selBegin = -1;
 }
 
-void Screen::getSelectionStart(int& column , int& line)
+void Screen::getSelectionStart(int& column , int& line) const
 {
-    if ( sel_TL != -1 )
+    if ( selTopLeft != -1 )
     {
-        column = sel_TL % columns;
-        line = sel_TL / columns; 
+        column = selTopLeft % columns;
+        line = selTopLeft / columns; 
     }
     else
     {
@@ -1210,12 +1021,12 @@
         line = cuY + getHistLines();
     }
 }
-void Screen::getSelectionEnd(int& column , int& line)
+void Screen::getSelectionEnd(int& column , int& line) const
 {
-    if ( sel_BR != -1 )
+    if ( selBottomRight != -1 )
     {
-        column = sel_BR % columns;
-        line = sel_BR / columns;
+        column = selBottomRight % columns;
+        line = selBottomRight / columns;
     }
     else
     {
@@ -1223,343 +1034,325 @@
         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) selBegin--;
 
-  /* FIXME, HACK to correct for x too far to the right... */
-  if (x == columns) sel_begin--;
-
-  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) return;
-  int l =  loc(x,y); // + histCursor);
+    if (selBegin == -1) 
+        return;
+
+    int endPos =  loc(x,y); 
+
+    if (endPos < selBegin)
+    {
+        selTopLeft = endPos;
+        selBottomRight = selBegin;
+    }
+    else
+    {
+        /* FIXME, HACK to correct for x too far to the right... */
+        if (x == columns) 
+            endPos--;
 
-  if (l < sel_begin)
-  {
-    sel_TL = l;
-    sel_BR = sel_begin;
-  }
-  else
-  {
-    /* FIXME, HACK to correct for x too far to the right... */
-    if (x == columns) l--;
+        selTopLeft = selBegin;
+        selBottomRight = endPos;
+    }
 
-    sel_TL = sel_begin;
-    sel_BR = l;
-  }
+    // 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;
+    bool columnInSelection = true;
+    if (blockSelectionMode)
+    {
+        columnInSelection = x >= (selTopLeft % columns) &&
+            x <= (selBottomRight % columns);
     }
-    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 );
-  }
+
+    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);
-  
-  PlainTextDecoder decoder;
-  decoder.begin(&stream);
-  writeSelectionToStream(&decoder , preserveLineBreaks);
-  decoder.end();
-  
-  return result;
+    QString result;
+    QTextStream stream(&result, QIODevice::ReadWrite);
+
+    PlainTextDecoder decoder;
+    decoder.begin(&stream);
+    writeSelectionToStream(&decoder , preserveLineBreaks);
+    decoder.end();
+
+    return result;
 }
 
 bool Screen::isSelectionValid() const
 {
-    return ( sel_TL >= 0 && sel_BR >= 0 );
+    return selTopLeft >= 0 && selBottomRight >= 0;
 }
 
 void Screen::writeSelectionToStream(TerminalCharacterDecoder* decoder , 
-                                    bool preserveLineBreaks)
+        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++)
+    {
+        int start = 0;
+        if ( y == top || blockSelectionMode ) start = left;
+
+        int count = -1;
+        if ( y == bottom || blockSelectionMode ) count = right - start + 1;
 
-	for (int y=top;y<=bottom;y++)
-	{
-			int start = 0;
-			if ( y == top || columnmode ) start = left;
-		
-			int count = -1;
-			if ( y == bottom || columnmode ) count = right - start + 1;
+        const bool appendNewLine = ( y != bottom );
+        int copied = copyLineToStream( y,
+                start,
+                count,
+                decoder, 
+                appendNewLine,
+                preserveLineBreaks );
 
-            const bool appendNewLine = ( y != bottom );
-			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 
-        //element on each call to copyLineToStream
-		//(which is unnecessary since all elements will be overwritten anyway)
-		static const int MAX_CHARS = 1024;
-		static Character characterBuffer[MAX_CHARS];
-		
-		assert( count < MAX_CHARS );
-
-        LineProperty currentLineProperties = 0;
+    //buffer to hold characters for decoding
+    //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;
+    static Character characterBuffer[MAX_CHARS];
 
-		//determine if the line is in the history buffer or the screen image
-		if (line < hist->getLines())
-		{
-            const int lineLength = hist->getLineLen(line);
-
-            // ensure that start position is before end of line
-            start = qMin(start,qMax(0,lineLength-1));
+    assert( count < MAX_CHARS );
 
-			//retrieve line from history buffer
-			if (count == -1)
-            {
-					count = lineLength-start;
-            }
-			else
-            {
-					count = qMin(start+count,lineLength)-start;
-            }
-
-            // safety checks
-            assert( start >= 0 );
-            assert( count >= 0 );    
-            assert( (start+count) <= hist->getLineLen(line) );
-
-			hist->getCells(line,start,count,characterBuffer);
+    LineProperty currentLineProperties = 0;
 
-            if ( hist->isWrappedLine(line) )
-                currentLineProperties |= LINE_WRAPPED;
-		}
-		else
-		{
-			if ( count == -1 )
-					count = columns - start;
-
-            assert( count >= 0 );
+    //determine if the line is in the history buffer or the screen image
+    if (line < history->getLines())
+    {
+        const int lineLength = history->getLineLen(line);
 
-            const int screenLine = line-hist->getLines();
-
-            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++)
-			{
-			    characterBuffer[i-start] = data[i];
-            }
+        // ensure that start position is before end of line
+        start = qMin(start,qMax(0,lineLength-1));
 
-            // count cannot be any greater than length
-			count = qBound(0,count,length-start);
-
-            Q_ASSERT( screenLine < lineProperties.count() );
-            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;
-
-        if ( !omitLineBreak && appendNewLine && (count+1 < MAX_CHARS) )
+        // 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)
         {
-            characterBuffer[count] = '\n';
-            count++;
+            count = lineLength-start;
+        }
+        else
+        {
+            count = qMin(start+count,lineLength)-start;
         }
 
-		//decode line and write to text stream	
-		decoder->decodeLine( (Character*) characterBuffer , 
-                             count, currentLineProperties );
+        // safety checks
+        assert( start >= 0 );
+        assert( count >= 0 );    
+        assert( (start+count) <= history->getLineLen(line) );
+
+        history->getCells(line,start,count,characterBuffer);
+
+        if ( history->isWrappedLine(line) )
+            currentLineProperties |= LINE_WRAPPED;
+    }
+    else
+    {
+        if ( count == -1 )
+            count = columns - start;
+
+        assert( count >= 0 );
+
+        const int screenLine = line-history->getLines();
+
+        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++)
+        {
+            characterBuffer[i-start] = data[i];
+        }
+
+        // count cannot be any greater than length
+        count = qBound(0,count,length-start);
+
+        Q_ASSERT( screenLine < lineProperties.count() );
+        currentLineProperties |= lineProperties[screenLine]; 
+    }
+
+    // add new line character at end
+    const bool omitLineBreak = (currentLineProperties & LINE_WRAPPED) ||
+        !preserveLineBreaks;
+
+    if ( !omitLineBreak && appendNewLine && (count+1 < MAX_CHARS) )
+    {
+        characterBuffer[count] = '\n';
+        count++;
+    }
+
+    //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()
 {
-  // add line to history buffer
-  // we have to take care about scrolling, too...
+    // 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 = history->getLines();
 
-    int newHistLines = hist->getLines();
+        bool beginIsTL = (selBegin == selTopLeft);
 
-    bool beginIsTL = (sel_begin == sel_TL);
+        // If the history is full, increment the count
+        // of dropped lines
+        if ( newHistLines == oldHistLines )
+            _droppedLines++;
 
-    // If the history is full, increment the count
-    // of dropped lines
-    if ( newHistLines == oldHistLines )
-        _droppedLines++;
+        // Adjust selection for the new point of reference
+        if (newHistLines > oldHistLines)
+        {
+            if (selBegin != -1)
+            {
+                selTopLeft += columns;
+                selBottomRight += columns;
+            }
+        }
+
+        if (selBegin != -1)
+        {
+            // Scroll selection in history up
+            int top_BR = loc(0, 1+newHistLines);
 
-    // Adjust selection for the new point of reference
-    if (newHistLines > oldHistLines)
-    {
-       if (sel_begin != -1)
-       {
-          sel_TL += columns;
-          sel_BR += columns;
-       }
+            if (selTopLeft < top_BR)
+                selTopLeft -= columns;
+
+            if (selBottomRight < top_BR)
+                selBottomRight -= columns;
+
+            if (selBottomRight < 0)
+                clearSelection();
+            else
+            {
+                if (selTopLeft < 0)
+                    selTopLeft = 0;
+            }
+
+            if (beginIsTL)
+                selBegin = selTopLeft;
+            else
+                selBegin = selBottomRight;
+        }
     }
 
-    if (sel_begin != -1)
-    {
-       // Scroll selection in history up
-       int top_BR = loc(0, 1+newHistLines);
-
-       if (sel_TL < top_BR)
-          sel_TL -= columns;
-
-       if (sel_BR < top_BR)
-          sel_BR -= columns;
-
-       if (sel_BR < 0)
-       {
-          clearSelection();
-       }
-       else
-       {
-          if (sel_TL < 0)
-             sel_TL = 0;
-       }
-
-       if (beginIsTL)
-          sel_begin = sel_TL;
-       else
-          sel_begin = sel_BR;
-    }
-  }
-
 }
 
-int Screen::getHistLines()
+int Screen::getHistLines() const
 {
-  return hist->getLines();
+    return history->getLines();
 }
 
 void Screen::setScroll(const HistoryType& t , bool copyPreviousScroll)
 {
-  clearSelection();
+    clearSelection();
 
-  if ( copyPreviousScroll )
-    hist = t.scroll(hist);
-  else
-  {
-      HistoryScroll* oldScroll = hist;
-      hist = t.scroll(0);
-      delete oldScroll;
-  }
+    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 )
-	{
-		lineProperties[cuY] = (LineProperty)(lineProperties[cuY] | property);
-	}
-	else
-	{
-		lineProperties[cuY] = (LineProperty)(lineProperties[cuY] & ~property);
-	}
+    if ( enable )
+        lineProperties[cuY] = (LineProperty)(lineProperties[cuY] | property);
+    else
+        lineProperties[cuY] = (LineProperty)(lineProperties[cuY] & ~property);
 }
 void Screen::fillWithDefaultChar(Character* dest, int count)
 {
-	for (int i=0;i<count;i++)
-		dest[i] = defaultChar;
+    for (int i=0;i<count;i++)
+        dest[i] = defaultChar;
 }
--- a/gui//src/Screen.h	Fri Apr 08 15:23:21 2011 +0200
+++ b/gui//src/Screen.h	Sat Apr 09 00:23:46 2011 +0200
@@ -1,10 +1,8 @@
 /*
     This file is part of Konsole, KDE's terminal.
 
-    Copyright (C) 2007 by Robert Knight <robertknight@gmail.com>
-    Copyright (C) 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
-
-    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+    Copyright 2007-2008 by Robert Knight <robertknight@gmail.com>
+    Copyright 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
 
     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,11 +40,6 @@
 #define MODE_NewLine   5
 #define MODES_SCREEN   6
 
-struct ScreenParm
-{
-  int mode[MODES_SCREEN];
-};
-
 class TerminalCharacterDecoder;
 
 /**
@@ -69,7 +62,7 @@
 
     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,
+    using selectedText().  When getImage() is used to retrieve the visible image,
     characters which are part of the selection have their colours inverted.   
 */
 class Screen
@@ -82,27 +75,39 @@
     // 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. 
      */
-    void setMargins  (int topLine , int bottomLine);
+    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. */
@@ -122,19 +127,19 @@
      * Equivalent to NextLine() if the MODE_NewLine flag is set
      * 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
@@ -154,25 +159,20 @@
      * using setMargins()
      */
     void scrollDown(int n);
-    
     /** 
      * 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
     
@@ -182,55 +182,55 @@
      * cursor position with spaces.
      * If @p n is 0 then one character is erased. 
      */
-    void eraseChars  (int n);
+    void eraseChars(int n);
     /** 
      * Delete @p n characters beginning from the current cursor position. 
      * 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.  
      * 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. */ 
     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;
+    bool getMode(int mode) const;
    
     /** 
-     * Saves the current position and appearence (text color and style) of the cursor. 
+     * Saves the current position and appearance (text color and style) of the cursor. 
      * It can be restored by calling restoreCursor() 
      */ 
-    void saveCursor  ();
-    /** Restores the position and appearence of the cursor.  See saveCursor() */
+    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. */ 
@@ -253,17 +253,17 @@
     void clearToBeginOfLine();
     
     /** Fills the entire screen with the letter 'E' */
-    void helpAlign   ();
+    void helpAlign();
        
     /** 
-     * Enables the given @p rendition flag.  Rendition flags control the appearence 
+     * 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
@@ -278,7 +278,7 @@
      *
      * @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.
@@ -287,7 +287,7 @@
      *
      * @see CharacterColor
      */
-    void setBackColor  (int space, int color);
+    void setBackColor(int space, int color);
     /** 
      * Resets the cursor's color back to the default and sets the 
      * character's rendition flags back to the default settings.
@@ -299,8 +299,10 @@
     /** Returns the line which the cursor is positioned on. */
     int  getCursorY() const;
    
-	/** TODO Document me */ 
-	void clear();
+    /** 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) 
@@ -336,7 +338,7 @@
      * is inserted at the current cursor position, otherwise it will replace the 
      * character already at the current cursor position.  
      */ 
-    void ShowCharacter(unsigned short c);
+    void displayCharacter(unsigned short c);
     
     // Do composition with last shown character FIXME: Not implemented yet for KDE 4
     void compose(const QString& compose);
@@ -347,8 +349,9 @@
      * 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);
     
@@ -371,14 +374,16 @@
      * other attributes control the size of characters in the line.
      */
     QVector<LineProperty> 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 ();
+    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 
@@ -386,21 +391,21 @@
      */
     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.
@@ -414,23 +419,21 @@
      * 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;
 
     /** 
@@ -438,55 +441,60 @@
      * @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);
-	    
-	/**
-	 * 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
-	 */
-	void writeToStream(TerminalCharacterDecoder* decoder, int from, int to);
+    QString selectedText(bool preserveLineBreaks) const;
+        
+    /**
+     * Copies part of the output to a stream.
+     *
+     * @param decoder A decoder which converts terminal characters into text
+     * @param fromLine The first line in the history to retrieve
+     * @param toLine The last line in the history to retrieve
+     */
+    void writeLinesToStream(TerminalCharacterDecoder* decoder, int fromLine, int toLine) const;
+
+    /**
+     * Copies the selected characters, set using @see setSelBeginXY and @see setSelExtentXY
+     * into a stream.
+     *
+     * @param decoder A decoder which converts terminal characters into text.  
+     * PlainTextDecoder is the most commonly used decoder which converts characters 
+     * into plain text with no formatting.
+     * @param preserveLineBreaks Specifies whether new line characters should 
+     * be inserted into the returned text at the end of each terminal line. 
+     */
+    void writeSelectionToStream(TerminalCharacterDecoder* decoder , bool
+                                preserveLineBreaks = true) const;
+
+    /**
+     * 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 the selection to line @p no in the history and returns
-     * the text of that line from the history buffer.
+     * Sets or clears an attribute of the current line.
+     * 
+     * @param property The attribute to set or clear
+     * Possible properties are:
+     * LINE_WRAPPED:     Specifies that the line is wrapped.
+     * LINE_DOUBLEWIDTH: Specifies that the characters in the current line
+     *                   should be double the normal width.
+     * LINE_DOUBLEHEIGHT:Specifies that the characters in the current line 
+     *                   should be double the normal height.
+     *                   Double-height lines are formed of two lines containing the same characters,
+     *                   with both having the LINE_DOUBLEHEIGHT attribute.
+     *                   This allows other parts of the code to work on the
+     *                   assumption that all lines are the same height.
+     *
+     * @param enable true to apply the attribute to the current line or false to remove it
      */
-    QString getHistoryLine(int no);
-
-	/**
-	 * 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 
-	 * 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. 
-	 */
-	void writeSelectionToStream(TerminalCharacterDecoder* decoder , bool
-                                preserveLineBreaks = true);
-
-    /** TODO Document me */
-    void checkSelection(int from, int to);
-
-	/** 
-	 * Sets or clears an attribute of the current line.
-	 * 
-	 * @param property The attribute to set or clear
-	 * Possible properties are:
-	 * LINE_WRAPPED:	 Specifies that the line is wrapped.
-	 * LINE_DOUBLEWIDTH: Specifies that the characters in the current line should be double the normal width.
-	 * LINE_DOUBLEHEIGHT:Specifies that the characters in the current line should be double the normal height.
-     *                   Double-height lines are formed of two lines containing the same characters,
-     *                   with both having the LINE_DOUBLEHEIGHT attribute.  This allows other parts of the 
-     *                   code to work on the assumption that all lines are the same height.
-	 *
-	 * @param enable true to apply the attribute to the current line or false to remove it
-	 */
-	void setLineProperty(LineProperty property , bool enable);
-
+    void setLineProperty(LineProperty property , bool enable);
 
     /** 
      * Returns the number of lines that the image has been scrolled up or down by,
@@ -528,29 +536,32 @@
      */
     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: 
 
-	//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
-	//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
+    //copies a line of text from the screen or history into a stream using a 
+    //specified character decoder.  Returns the number of lines actually copied,
+    //which may be less than 'count' if (start+count) is more than the number of characters on
+    //the line 
+    //
+    //line - the line number to copy, from 0 (the earliest line in the history) up to 
+    //         history->getLines() + lines - 1
+    //start - the first column on the line to copy
+    //count - the number of characters on the line to copy
+    //decoder - a decoder which converts terminal characters (an Character array) into text
     //appendNewLine - if true a new line character (\n) is appended to the end of the line
-	void copyLineToStream(int line, 
+    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.
@@ -559,26 +570,32 @@
     //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 updateEffectiveRendition();
     void reverseRendition(Character& p) const;
 
     bool isSelectionValid() const;
-
-	// copies 'count' lines from the screen buffer into 'dest',
-	// starting from 'startLine', where 0 is the first line in the screen buffer
-	void copyFromScreen(Character* dest, int startLine, int count) const;
-	// copies 'count' lines from the history buffer into 'dest',
-	// starting from 'startLine', where 0 is the first line in the history
-	void copyFromHistory(Character* dest, int startLine, int count) const;
+    // 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;
+    // copies 'count' lines from the history buffer into 'dest',
+    // starting from 'startLine', where 0 is the first line in the history
+    void copyFromHistory(Character* dest, int startLine, int count) const;
 
 
     // screen image ----------------
@@ -594,61 +611,59 @@
     int _droppedLines;
 
     QVarLengthArray<LineProperty,64> 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
-
-    //
-    // save cursor, rendition & states ------------
-    // 
+    CharacterColor effectiveForeground; // These are derived from
+    CharacterColor effectiveBackground; // the cu_* variables above
+    quint8 effectiveRendition;          // to speed up operation
 
-    // cursor location
-    int sa_cuX;
-    int sa_cuY;
+    class SavedState  
+    {
+    public:
+        SavedState()
+        : cursorColumn(0),cursorLine(0),rendition(0) {}
 
-    // rendition info
-    quint8 sa_cu_re;
-    CharacterColor sa_cu_fg;
-    CharacterColor sa_cu_bg;
-    
+        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;
 };
 
--- a/gui//src/Session.cpp	Fri Apr 08 15:23:21 2011 +0200
+++ b/gui//src/Session.cpp	Sat Apr 09 00:23:46 2011 +0200
@@ -1,10 +1,9 @@
 /*
     This file is part of Konsole
 
-    Copyright (C) 2006-2007 by Robert Knight <robertknight@gmail.com>
-    Copyright (C) 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
-
-    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+    Copyright 2006-2008 by Robert Knight <robertknight@gmail.com>
+    Copyright 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
+    Copyright 2009 by Thomas Dreibholz <dreibh@iem.uni-due.de>
 
     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
@@ -22,9 +21,13 @@
     02110-1301  USA.
 */
 
+// Own
+#include "Session.h"
+
 // Standard
 #include <assert.h>
 #include <stdlib.h>
+#include <signal.h>
 
 // Qt
 #include <QtGui/QApplication>
@@ -33,19 +36,73 @@
 #include <QtCore/QFile>
 #include <QtCore/QRegExp>
 #include <QtCore/QStringList>
-#include <QtCore>
+//#include <QtDBus/QtDBus>
+#include <QtCore/QDate>
+
 
-// Own
-#include "Session.h"
+// KDE
+//#include <KDebug>
+//#include <KLocale>
+//#include <KMessageBox>
+//#include <KNotification>
+//#include <KProcess>
+//#include <KRun>
+//#include <kshell.h>
+//#include <KStandardDirs>
+//#include <KPtyDevice>
+//#include <KUrl>
+#include "kprocess.h"
+#include "kptydevice.h"
+//#include "kdebug.h"
+
+// Konsole
+//#include <config-konsole.h>
+//#include <sessionadaptor.h>
+
+#include "ProcessInfo.h"
 #include "Pty.h"
 #include "TerminalDisplay.h"
 #include "ShellCommand.h"
 #include "Vt102Emulation.h"
+//#include "ZModemDialog.h"
 
 int Session::lastSessionId = 0;
 
-Session::Session() :
-    _shellProcess(0)
+// HACK This is copied out of QUuid::createUuid with reseeding forced.
+// Required because color schemes repeatedly seed the RNG...
+// ...with a constant.
+QUuid createUuid()
+{
+    static const int intbits = sizeof(int)*8;
+    static int randbits = 0;
+    if (!randbits)
+    {
+        int max = RAND_MAX;
+        do { ++randbits; } while ((max=max>>1));
+    }
+
+    qsrand(uint(QDateTime::currentDateTime().toTime_t()));
+    qrand(); // Skip first
+
+    QUuid result;
+    uint *data = &(result.data1);
+    int chunks = 16 / sizeof(uint);
+    while (chunks--) {
+        uint randNumber = 0;
+        for (int filled = 0; filled < intbits; filled += randbits)
+            randNumber |= qrand()<<filled;
+         *(data+chunks) = randNumber;
+    }
+
+    result.data4[0] = (result.data4[0] & 0x3F) | 0x80;        // UV_DCE
+    result.data3 = (result.data3 & 0x0FFF) | 0x4000;        // UV_Random
+
+    return result;
+}
+
+Session::Session(QObject* parent) :
+   QObject(parent)
+   , _shellProcess(0)
    , _emulation(0)
    , _monitorActivity(false)
    , _monitorSilence(false)
@@ -53,19 +110,26 @@
    , _autoClose(true)
    , _wantedClose(false)
    , _silenceSeconds(10)
-   , _addToUtmp(false)  // disabled by default because of a bug encountered on certain systems
-                        // which caused Konsole to hang when closing a tab and then opening a new
-                        // one.  A 'QProcess destroyed while still running' warning was being
-                        // printed to the terminal.  Likely a problem in KPty::logout() 
-                        // or KPty::login() which uses a QProcess to start /usr/bin/utempter 
+   , _addToUtmp(true)  
    , _flowControl(true)
    , _fullScripting(false)
    , _sessionId(0)
+   , _sessionProcessInfo(0)
+   , _foregroundProcessInfo(0)
+   , _foregroundPid(0)
+   //, _zmodemBusy(false)
+   //, _zmodemProc(0)
+   //, _zmodemProgress(0)
    , _hasDarkBackground(false)
 {
+    _uniqueIdentifier = createUuid();
+
+    //prepare DBus communication
+    //new SessionAdaptor(this);
     _sessionId = ++lastSessionId;
-    //create teletype for I/O with shell process
-    _shellProcess = new Pty();
+    
+    // JPS: commented out for lack of DBUS support by default on OSX
+    //QDBusConnection::sessionBus().registerObject(QLatin1String("/Sessions/")+QString::number(_sessionId), this);
 
     //create emulation backend
     _emulation = new Vt102Emulation();
@@ -74,25 +138,50 @@
            this, SLOT( setUserTitle( int, const QString & ) ) );
     connect( _emulation, SIGNAL( stateSet(int) ),
            this, SLOT( activityStateSet(int) ) );
+    //connect( _emulation, SIGNAL( zmodemDetected() ), this ,
+    //        SLOT( fireZModemDetected() ) );
     connect( _emulation, SIGNAL( changeTabTextColorRequest( int ) ),
            this, SIGNAL( changeTabTextColorRequest( int ) ) );
     connect( _emulation, SIGNAL(profileChangeCommandReceived(const QString&)),
            this, SIGNAL( profileChangeCommandReceived(const QString&)) );
-    //connect teletype to emulation backend
+    connect( _emulation, SIGNAL(flowControlKeyPressed(bool)) , this, 
+             SLOT(updateFlowControlState(bool)) );
+
+    //create new teletype for I/O with shell process
+    openTeletype(-1);
+
+    //setup timer for monitoring session activity
+    _monitorTimer = new QTimer(this);
+    _monitorTimer->setSingleShot(true);
+    connect(_monitorTimer, SIGNAL(timeout()), this, SLOT(monitorTimerDone()));
+}
+
+void Session::openTeletype(int fd)
+{
+    if (_shellProcess && isRunning())
+    {
+        //kWarning() << "Attempted to open teletype in a running session.";
+        return;
+    }
+
+    delete _shellProcess;
+
+    if (fd < 0)
+        _shellProcess = new Pty();
+    else
+        _shellProcess = new Pty(fd);
+
     _shellProcess->setUtf8Mode(_emulation->utf8());
 
+    //connect teletype to emulation backend
     connect( _shellProcess,SIGNAL(receivedData(const char*,int)),this,
             SLOT(onReceiveBlock(const char*,int)) );
     connect( _emulation,SIGNAL(sendData(const char*,int)),_shellProcess,
             SLOT(sendData(const char*,int)) );
     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)) );
-
-    //setup timer for monitoring session activity
-    _monitorTimer = new QTimer(this);
-    _monitorTimer->setSingleShot(true);
-    connect(_monitorTimer, SIGNAL(timeout()), this, SLOT(monitorTimerDone()));
+    connect( _shellProcess,SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(done(int)) );
+    connect( _emulation,SIGNAL(imageSizeChanged(int,int)),this,SLOT(updateWindowSize(int,int)) );
 }
 
 WId Session::windowId() const
@@ -134,7 +223,7 @@
 }
 bool Session::isRunning() const
 {
-    return _shellProcess->isRunning();
+    return _shellProcess->state() == QProcess::Running;
 }
 
 void Session::setCodec(QTextCodec* codec)
@@ -142,19 +231,48 @@
     emulation()->setCodec(codec);
 }
 
+bool Session::setCodec(QByteArray name)
+{
+    QTextCodec *codec = QTextCodec::codecForName(name);
+    if (codec) {
+        setCodec(codec);
+        return true;
+    }
+    return false;
+}
+
+QByteArray Session::codec()
+{
+    return _emulation->codec()->name();
+}
+
 void Session::setProgram(const QString& program)
 {
     _program = ShellCommand::expand(program);
 }
 void Session::setInitialWorkingDirectory(const QString& dir)
 {
-    _initialWorkingDir = ShellCommand::expand(dir);
+  //_initialWorkingDir = KShell::tildeExpand(ShellCommand::expand(dir));
+  _initialWorkingDir = ShellCommand::expand(dir);
 }
 void Session::setArguments(const QStringList& arguments)
 {
     _arguments = ShellCommand::expand(arguments);
 }
 
+QString Session::currentWorkingDirectory()
+{
+    // only returned cached value
+    if (_currentWorkingDir.isEmpty()) updateWorkingDirectory();
+    return _currentWorkingDir;
+}
+ProcessInfo* Session::updateWorkingDirectory()
+{
+    ProcessInfo *process = getProcessInfo();
+    _currentWorkingDir = process->validCurrentDir();
+    return process;
+}
+
 QList<TerminalDisplay*> Session::views() const
 {
     return _views;
@@ -192,9 +310,6 @@
 
     QObject::connect( widget ,SIGNAL(destroyed(QObject*)) , this ,
                     SLOT(viewDestroyed(QObject*)) );
-
-    QObject::connect(this, SIGNAL(finished()), widget, SLOT(close()));		    
-    
 }
 
 void Session::viewDestroyed(QObject* view)
@@ -210,7 +325,7 @@
 {
     _views.removeAll(widget);
 
-	disconnect(widget,0,this,0);
+    disconnect(widget,0,this,0);
 
     if ( _emulation != 0 )
     {
@@ -226,66 +341,153 @@
         disconnect( _emulation , 0 , widget , 0);
     }
 
-	// close the session automatically when the last view is removed
-	if ( _views.count() == 0 )
-	{
-		close();
-	}
+    // close the session automatically when the last view is removed
+    if ( _views.count() == 0 )
+    {
+        close();
+    }
+}
+
+QString Session::checkProgram(const QString& program) const
+{
+  // Upon a KPty error, there is no description on what that error was...
+  // Check to see if the given program is executable.
+  QString exec = QFile::encodeName(program);
+
+  if (exec.isEmpty())
+      return QString();
+
+  // if 'exec' is not specified, fall back to default shell.  if that 
+  // is not set then fall back to /bin/sh
+  if ( exec.isEmpty() )
+      exec = qgetenv("SHELL");
+  if ( exec.isEmpty() )
+        exec = "/bin/sh";
+
+  // JPS: commented out to get rid of KShell and KRun
+  /*
+  exec = KRun::binaryName(exec, false);
+  exec = KShell::tildeExpand(exec);
+  QString pexec = KGlobal::dirs()->findExe(exec);
+  if ( pexec.isEmpty() ) 
+  {
+      kError() << i18n("Could not find binary: ") << exec;
+    return QString();
+  }
+
+  return exec;
+  */
+  return program;
+}
+
+void Session::terminalWarning(const QString& message)
+{
+  //static const QByteArray warningText = i18nc("@info:shell Alert the user with red color text", "Warning: ").toLocal8Bit(); 
+  static const QByteArray warningText = i18nc("@info:shell Alert the user with red color text", "Warning: "); 
+    QByteArray messageText = message.toLocal8Bit();
+
+    static const char redPenOn[] = "\033[1m\033[31m";
+    static const char redPenOff[] = "\033[0m";
+
+    _emulation->receiveData(redPenOn,strlen(redPenOn));
+    _emulation->receiveData("\n\r\n\r",4);
+    _emulation->receiveData(warningText.constData(),strlen(warningText.constData()));
+    _emulation->receiveData(messageText.constData(),strlen(messageText.constData()));
+    _emulation->receiveData("\n\r\n\r",4);
+    _emulation->receiveData(redPenOff,strlen(redPenOff));
+}
+
+QString Session::shellSessionId() const
+{
+    QString friendlyUuid(_uniqueIdentifier.toString());
+    friendlyUuid.remove('-').remove('{').remove('}');
+
+    return friendlyUuid;
 }
 
 void Session::run()
 {
   //check that everything is in place to run the session
   if (_program.isEmpty())
-      qDebug() << "Session::run() - program to run not set.";
+  {
+      //kWarning() << "Session::run() - program to run not set.";
+  }
   if (_arguments.isEmpty())
-      qDebug() << "Session::run() - no command line arguments specified.";
-
-  // Upon a KPty error, there is no description on what that error was...
-  // Check to see if the given program is executable.
-  QString exec = QFile::encodeName(_program);
-
-  // if 'exec' is not specified, fall back to default shell.  if that 
-  // is not set then fall back to /bin/sh
-  if ( exec.isEmpty() )
-      exec = getenv("SHELL");
-  if ( exec.isEmpty() )
-  	  exec = "/bin/sh";
-
-  // if no arguments are specified, fall back to shell
-  QStringList arguments =  _arguments.join(QChar(' ')).isEmpty() ?
-                                    QStringList() << exec : _arguments;
-  QString pexec = exec;
-
-  if ( pexec.isEmpty() ) {
-    qDebug()<<"can not execute "<<exec<<endl;
-    QTimer::singleShot(1, this, SIGNAL(finished()));
-    return;
+  {
+      //kWarning() << "Session::run() - no command line arguments specified.";
+  }
+  if (_uniqueIdentifier.isNull())
+  {
+      _uniqueIdentifier = createUuid();
   }
 
-  QString cwd_save = QDir::currentPath();
+  const int CHOICE_COUNT = 3;
+  QString programs[CHOICE_COUNT] = {_program,qgetenv("SHELL"),"/bin/sh"};
+  QString exec;
+  int choice = 0;
+  while (choice < CHOICE_COUNT)
+  {
+    exec = checkProgram(programs[choice]);
+    if (exec.isEmpty())
+        choice++;
+    else
+        break;
+  }
+
+  // if a program was specified via setProgram(), but it couldn't be found, print a warning
+  if (choice != 0 && choice < CHOICE_COUNT && !_program.isEmpty())
+  {
+    QString msg;
+    QTextStream msgStream(&msg);
+    msgStream << "Could not find '" << _program << "', starting '" << exec << "' instead. Please check your profile settings.";
+    terminalWarning(msg);
+    //terminalWarning(i18n("Could not find '%1', starting '%2' instead.  Please check your profile settings.",_program.toLatin1().data(),exec.toLatin1().data())); 
+  }
+  // if none of the choices are available, print a warning
+  else if (choice == CHOICE_COUNT)
+  {
+      terminalWarning(i18n("Could not find an interactive shell to start."));
+      return;
+  }
+  
+  // if no arguments are specified, fall back to program name
+  QStringList arguments = _arguments.join(QChar(' ')).isEmpty() ?
+                                                   QStringList() << exec : _arguments;
+
+  // JPS: commented out for lack of DBUS support by default on OSX
+  QString dbusService = ""; //QDBusConnection::sessionBus().baseService();
   if (!_initialWorkingDir.isEmpty())
     _shellProcess->setWorkingDirectory(_initialWorkingDir);
   else
     _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
   // the color scheme as "black on white" or "white on black" depending on whether
   // the background color is deemed dark or not
   QString backgroundColorHint = _hasDarkBackground ? "COLORFGBG=15;0" : "COLORFGBG=0;15";
+  _environment << backgroundColorHint;
+  _environment << QString("SHELL_SESSION_ID=%1").arg(shellSessionId());
 
-  int result = _shellProcess->start(QFile::encodeName(_program),
+  int result = _shellProcess->start(exec,
                                   arguments,
-                                  _environment << backgroundColorHint,
+                                  _environment,
                                   windowId(),
-                                  _addToUtmp);
+                                  _addToUtmp,
+                                  dbusService,
+                                  (QLatin1String("/Sessions/") +
+                                   QString::number(_sessionId)));
 
   if (result < 0)
   {
+    QString msg;
+    QTextStream msgStream(&msg);
+    msgStream << QString("Could not start program '") << exec << QString("' with arguments '") << arguments.join(" ") << QString("'.");
+    terminalWarning (msg);
+    //      terminalWarning(i18n("Could not start program '%1' with arguments '%2'.", exec.toLatin1().data(), arguments.join(" ").toLatin1().data()));
     return;
   }
 
@@ -297,78 +499,70 @@
 void Session::setUserTitle( int what, const QString &caption )
 {
     //set to true if anything is actually changed (eg. old _nameTitle != new _nameTitle )
-	bool modified = false;
+    bool modified = false;
 
-    // (btw: what=0 changes _userTitle and icon, what=1 only icon, what=2 only _nameTitle
-    if ((what == 0) || (what == 2)) 
+    if ((what == IconNameAndWindowTitle) || (what == WindowTitle)) 
     {
-       	if ( _userTitle != caption ) {
-			_userTitle = caption;
-			modified = true;
-		}
+           if ( _userTitle != caption ) {
+            _userTitle = caption;
+            modified = true;
+        }
     }
 
-    if ((what == 0) || (what == 1))
-	{
-		if ( _iconText != caption ) {
-       		_iconText = caption;
-			modified = true;
-		}
-	}
+    if ((what == IconNameAndWindowTitle) || (what == IconName))
+    {
+        if ( _iconText != caption ) {
+               _iconText = caption;
+            modified = true;
+        }
+    }
 
-    if (what == 11) 
+    if (what == TextColor || what == BackgroundColor) 
     {
       QString colorString = caption.section(';',0,0);
-      qDebug() << __FILE__ << __LINE__ << ": setting background colour to " << colorString;
-      QColor backColor = QColor(colorString);
-      if (backColor.isValid()){// change color via \033]11;Color\007
-          if (backColor != _modifiedBackground)
-          {
-              _modifiedBackground = backColor;
-
-              // bail out here until the code to connect the terminal display
-              // to the changeBackgroundColor() signal has been written
-              // and tested - just so we don't forget to do this.
-              Q_ASSERT( 0 );
-
-              emit changeBackgroundColorRequest(backColor);
-          }
+      QColor color = QColor(colorString);
+      if (color.isValid())
+      {
+          if (what == TextColor)
+                  emit changeForegroundColorRequest(color);
+          else
+                  emit changeBackgroundColorRequest(color);
       }
     }
 
-	if (what == 30) 
+    if (what == SessionName) 
     {
-		if ( _nameTitle != caption ) {
-       		setTitle(Session::NameRole,caption);
-			return;
-		}
-	}
+        if ( _nameTitle != caption ) {
+               setTitle(Session::NameRole,caption);
+            return;
+        }
+    }
 
     if (what == 31) 
     {
        QString cwd=caption;
        cwd=cwd.replace( QRegExp("^~"), QDir::homePath() );
        emit openUrlRequest(cwd);
-	}
+    }
 
     // change icon via \033]32;Icon\007
     if (what == 32) 
     { 
-    	if ( _iconName != caption ) {
-	   		_iconName = caption;
+        if ( _iconName != caption ) {
+               _iconName = caption;
 
-			modified = true;
-		}
+            modified = true;
+        }
     }
 
-    if (what == 50) 
+    if (what == ProfileChange) 
     {
         emit profileChangeCommandReceived(caption);
         return;
     }
 
-	if ( modified )
-    	emit titleChanged();
+    if ( modified )
+        emit titleChanged();
 }
 
 QString Session::userTitle() const
@@ -394,8 +588,19 @@
 
 void Session::monitorTimerDone()
 {
+  //FIXME: The idea here is that the notification popup will appear to tell the user than output from
+  //the terminal has stopped and the popup will disappear when the user activates the session.
+  //
+  //This breaks with the addition of multiple views of a session.  The popup should disappear
+  //when any of the views of the session becomes active
+  
+
+  //FIXME: Make message text for this notification and the activity notification more descriptive.    
   if (_monitorSilence) {
-  emit stateChanged(NOTIFYSILENCE);
+    //KNotification::event("Silence", i18n("Silence in session '%1'", _nameTitle), QPixmap(),
+    //                QApplication::activeWindow(),
+    //                KNotification::CloseWhenWidgetActivated);
+    emit stateChanged(NOTIFYSILENCE);
   }
   else
   {
@@ -404,14 +609,30 @@
 
   _notifiedActivity=false;
 }
-
+void Session::updateFlowControlState(bool suspended)
+{
+    if (suspended)
+    {
+        if (flowControlEnabled())
+        {
+            foreach(TerminalDisplay* display,_views)
+            {
+                if (display->flowControlWarningEnabled())
+                    display->outputSuspended(true);
+            }
+        }
+    } 
+    else
+    {
+        foreach(TerminalDisplay* display,_views)
+            display->outputSuspended(false);
+    }   
+}
 void Session::activityStateSet(int state)
 {
   if (state==NOTIFYBELL)
   {
-      QString s; s.sprintf("Bell in session '%s'",_nameTitle.toAscii().data());
-      
-      emit bellRequest( s );
+      emit bellRequest( i18n("Bell in session '%1'",_nameTitle.toLatin1().data()) );
   }
   else if (state==NOTIFYACTIVITY)
   {
@@ -422,9 +643,9 @@
     if ( _monitorActivity ) {
       //FIXME:  See comments in Session::monitorTimerDone()
       if (!_notifiedActivity) {
-//        KNotification::event("Activity", ("Activity in session '%1'", _nameTitle), QPixmap(),
-//                        QApplication::activeWindow(),
-//        KNotification::CloseWhenWidgetActivated);
+        //KNotification::event("Activity", i18n("Activity in session '%1'", _nameTitle), QPixmap(),
+        //                QApplication::activeWindow(),
+        //KNotification::CloseWhenWidgetActivated);
         _notifiedActivity=true;
       }
     }
@@ -442,10 +663,6 @@
 {
   updateTerminalSize();
 }
-void Session::onEmulationSizeChange(int lines , int columns)
-{
-  setSize( QSize(lines,columns) );
-}
 
 void Session::updateTerminalSize()
 {
@@ -470,6 +687,7 @@
         {
             minLines = (minLines == -1) ? view->lines() : qMin( minLines , view->lines() );
             minColumns = (minColumns == -1) ? view->columns() : qMin( minColumns , view->columns() );
+            view->processFilters();
         }
     }
 
@@ -477,10 +695,13 @@
     if ( minLines > 0 && minColumns > 0 )
     {
         _emulation->setImageSize( minLines , minColumns );
-        _shellProcess->setWindowSize( minLines , minColumns );
     }
 }
-
+void Session::updateWindowSize(int lines, int columns)
+{
+    Q_ASSERT(lines > 0 && columns > 0);
+    _shellProcess->setWindowSize(lines,columns);
+}
 void Session::refresh()
 {
     // attempt to get the shell process to redraw the display
@@ -502,17 +723,40 @@
     _shellProcess->setWindowSize(existingSize.height(),existingSize.width());
 }
 
-bool Session::sendSignal(int signal)
+bool Session::kill(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()
 {
   _autoClose = true;
   _wantedClose = true;
-  if (!_shellProcess->isRunning() || !sendSignal(SIGHUP))
+
+  if (!isRunning() || !kill(SIGHUP))
   {
+     if (isRunning())
+     {
+        //kWarning() << "Process" << _shellProcess->pid() << "did not respond to SIGHUP";
+
+        // close the pty and wait to see if the process finishes.  If it does,
+        // the done() slot will have been called so we can return.  Otherwise,
+        // emit the finished() signal regardless
+        _shellProcess->pty()->close();
+        if (_shellProcess->waitForFinished(3000))
+            return;
+
+        //kWarning() << "Unable to kill process" << _shellProcess->pid();
+     }
+
      // Forced close.
      QTimer::singleShot(1, this, SIGNAL(finished()));
   }
@@ -523,49 +767,58 @@
   _emulation->sendText(text);
 }
 
-Session::~Session()
+void Session::sendMouseEvent(int buttons, int column, int line, int eventType)
 {
-  delete _emulation;
-  delete _shellProcess;
+    _emulation->sendMouseEvent(buttons, column, line, eventType);
 }
 
-void Session::setProfileKey(const QString& key)
+Session::~Session()
 {
-    _profileKey = key;
-    emit profileChanged(key);
+  if (_foregroundProcessInfo)
+      delete _foregroundProcessInfo;
+  if (_sessionProcessInfo)
+      delete _sessionProcessInfo;
+  delete _emulation;
+  delete _shellProcess;
+  //delete _zmodemProc;
 }
-QString Session::profileKey() const { return _profileKey; }
 
 void Session::done(int exitStatus)
 {
   if (!_autoClose)
   {
-    _userTitle = ("<Finished>");
+    _userTitle = i18n("@info:shell This session is done", "Finished");
     emit titleChanged();
     return;
   }
-  if (!_wantedClose && (exitStatus || _shellProcess->signalled()))
+
+  QString message;
+  QTextStream msgStream(&message);
+  if (!_wantedClose || exitStatus != 0)
   {
-    QString message;
-
-    if (_shellProcess->normalExit())
-      message.sprintf ("Session '%s' exited with status %d.", _nameTitle.toAscii().data(), exitStatus);
-    else if (_shellProcess->signalled())
+    if (_shellProcess->exitStatus() == QProcess::NormalExit)
     {
-      if (_shellProcess->coreDumped())
-      {    
+      msgStream << "Program '" << _program << "' exited with statis " << exitStatus << ".";
+      //message = i18n("Program '%1' exited with status %2.", _program.toLatin1().data(), exitStatus);
 
-        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());
-      }
     }
     else
-        message.sprintf ("Session '%s' exited unexpectedly.", _nameTitle.toAscii().data());
+    {
+      msgStream << "Program '" << _program << "' crashed.";
+      //message = i18n("Program '%1' crashed.", _program.toLatin1().data());
+	
+    }
 
+    //FIXME: See comments in Session::monitorTimerDone()
+    //KNotification::event("Finished", message , QPixmap(),
+    //                     QApplication::activeWindow(),
+    //                     KNotification::CloseWhenWidgetActivated);
   }
-  emit finished();
+
+  if ( !_wantedClose && _shellProcess->exitStatus() != QProcess::NormalExit )
+      terminalWarning(message);
+  else
+        emit finished();
 }
 
 Emulation* Session::emulation() const
@@ -621,6 +874,123 @@
         return QString();
 }
 
+ProcessInfo* Session::getProcessInfo()
+{
+    ProcessInfo* process;
+
+    if (isForegroundProcessActive())
+        process = _foregroundProcessInfo;
+    else
+    {
+        updateSessionProcessInfo();
+        process = _sessionProcessInfo;
+    }
+
+    return process;
+}
+
+void Session::updateSessionProcessInfo()
+{
+    Q_ASSERT(_shellProcess);
+    if (!_sessionProcessInfo)
+    {
+        _sessionProcessInfo = ProcessInfo::newInstance(processId());
+        _sessionProcessInfo->setUserHomeDir();
+    }
+    _sessionProcessInfo->update();
+}
+
+bool Session::updateForegroundProcessInfo()
+{
+    bool valid = (_foregroundProcessInfo != 0);
+
+    // has foreground process changed?
+    Q_ASSERT(_shellProcess);
+    int pid = _shellProcess->foregroundProcessGroup();
+    if (pid != _foregroundPid)
+    {
+        if (valid)
+            delete _foregroundProcessInfo;
+        _foregroundProcessInfo = ProcessInfo::newInstance(pid);
+        _foregroundPid = pid;
+        valid = true;
+    }
+
+    if (valid)
+    {
+        _foregroundProcessInfo->update();
+        valid = _foregroundProcessInfo->isValid();
+    }
+
+    return valid;
+}
+
+bool Session::isRemote()
+{
+    ProcessInfo* process = getProcessInfo();
+
+    bool ok = false;
+    return ( process->name(&ok) == "ssh" && ok );
+}
+
+QString Session::getDynamicTitle()
+{
+    // update current directory from process
+    ProcessInfo* process = updateWorkingDirectory();
+
+    // format tab titles using process info
+    bool ok = false;
+    QString title;
+    if ( process->name(&ok) == "ssh" && ok )
+    {
+        SSHProcessInfo sshInfo(*process);
+        title = sshInfo.format(tabTitleFormat(Session::RemoteTabTitle));
+    }
+    else
+        title = process->format(tabTitleFormat(Session::LocalTabTitle));
+
+    return title;
+}
+
+/*
+KUrl Session::getUrl()
+{
+    QString path;
+    
+    updateSessionProcessInfo();
+    if (_sessionProcessInfo->isValid())
+    {
+        bool ok = false;
+
+        // check if foreground process is bookmark-able
+        if (isForegroundProcessActive())
+        {
+            // for remote connections, save the user and host
+            // bright ideas to get the directory at the other end are welcome :)
+            if (_foregroundProcessInfo->name(&ok) == "ssh" && ok)
+            {
+                SSHProcessInfo sshInfo(*_foregroundProcessInfo);
+                path = "ssh://" + sshInfo.userName() + '@' + sshInfo.host();
+            }
+            else
+            {
+                path = _foregroundProcessInfo->currentDir(&ok);
+                if (!ok)
+                    path.clear();
+            }
+        }
+        else // otherwise use the current working directory of the shell process
+        {
+            path = _sessionProcessInfo->currentDir(&ok);
+            if (!ok)
+                path.clear();
+        }
+    }
+
+    return KUrl(path);
+}
+*/
+
 void Session::setIconName(const QString& iconName)
 {
     if ( iconName != _iconName )
@@ -714,21 +1084,136 @@
 
 void Session::setFlowControlEnabled(bool enabled)
 {
-  if (_flowControl == enabled)
-  	return;
-
   _flowControl = enabled;
 
   if (_shellProcess)  
-	_shellProcess->setXonXoff(_flowControl);
-  
+    _shellProcess->setFlowControlEnabled(_flowControl);
   emit flowControlEnabledChanged(enabled);
 }
 bool Session::flowControlEnabled() const
 {
-	return _flowControl;
+    if (_shellProcess)
+            return _shellProcess->flowControlEnabled();
+    else
+            return _flowControl;
+}
+
+/*
+void Session::fireZModemDetected()
+{
+  if (!_zmodemBusy)
+  {
+    QTimer::singleShot(10, this, SIGNAL(zmodemDetected()));
+    _zmodemBusy = true;
+  }
+}
+
+void Session::cancelZModem()
+{
+  _shellProcess->sendData("\030\030\030\030", 4); // Abort
+  _zmodemBusy = false;
+}
+
+void Session::startZModem(const QString &zmodem, const QString &dir, const QStringList &list)
+{
+  _zmodemBusy = true;
+  _zmodemProc = new KProcess();
+  _zmodemProc->setOutputChannelMode( KProcess::SeparateChannels );
+
+  *_zmodemProc << zmodem << "-v" << list;
+
+  if (!dir.isEmpty())
+     _zmodemProc->setWorkingDirectory(dir);
+
+  connect(_zmodemProc,SIGNAL (readyReadStandardOutput()),
+          this, SLOT(zmodemReadAndSendBlock()));
+  connect(_zmodemProc,SIGNAL (readyReadStandardError()),
+          this, SLOT(zmodemReadStatus()));
+  connect(_zmodemProc,SIGNAL (finished(int,QProcess::ExitStatus)),
+          this, SLOT(zmodemFinished()));
+
+  _zmodemProc->start();
+  
+  disconnect( _shellProcess,SIGNAL(receivedData(const char*,int)), this, SLOT(onReceiveBlock(const char*,int)) );
+  connect( _shellProcess,SIGNAL(receivedData(const char*,int)), this, SLOT(zmodemRcvBlock(const char*,int)) );
+
+  _zmodemProgress = new ZModemDialog(QApplication::activeWindow(), false,
+                                    i18n("ZModem Progress"));
+
+  connect(_zmodemProgress, SIGNAL(user1Clicked()),
+          this, SLOT(zmodemFinished()));
+
+  _zmodemProgress->show();
 }
 
+void Session::zmodemReadAndSendBlock()
+{
+  _zmodemProc->setReadChannel( QProcess::StandardOutput );
+  QByteArray data = _zmodemProc->readAll();
+
+  if ( data.count() == 0 )
+      return;
+
+  _shellProcess->sendData(data.constData(),data.count());
+}
+
+void Session::zmodemReadStatus()
+{
+  _zmodemProc->setReadChannel( QProcess::StandardError );
+  QByteArray msg = _zmodemProc->readAll();
+  while(!msg.isEmpty())
+  {
+     int i = msg.indexOf('\015');
+     int j = msg.indexOf('\012');
+     QByteArray txt;
+     if ((i != -1) && ((j == -1) || (i < j)))
+     {
+       msg = msg.mid(i+1);
+     }
+     else if (j != -1)
+     {
+       txt = msg.left(j);
+       msg = msg.mid(j+1);
+     }
+     else
+     {
+       txt = msg;
+       msg.truncate(0);
+     }
+     if (!txt.isEmpty())
+       _zmodemProgress->addProgressText(QString::fromLocal8Bit(txt));
+  }
+}
+
+void Session::zmodemRcvBlock(const char *data, int len)
+{
+  QByteArray ba( data, len );
+
+  _zmodemProc->write( ba );
+}
+
+void Session::zmodemFinished()
+{
+  // zmodemFinished() is called by QProcess's finished() and
+  //    ZModemDialog's user1Clicked(). Therefore, an invocation by
+  //    user1Clicked() will recursively invoke this function again
+  //    when the KProcess is deleted!
+  if (_zmodemProc) {
+    KProcess* process = _zmodemProc;
+    _zmodemProc = 0;   // Set _zmodemProc to 0 avoid recursive invocations!
+    _zmodemBusy = false;
+    delete process;    // Now, the KProcess may be disposed safely.
+
+    disconnect( _shellProcess,SIGNAL(receivedData(const char*,int)), this ,SLOT(zmodemRcvBlock(const char*,int)) );
+    connect( _shellProcess,SIGNAL(receivedData(const char*,int)), this, SLOT(onReceiveBlock(const char*,int)) );
+
+    _shellProcess->sendData("\030\030\030\030", 4); // Abort
+    _shellProcess->sendData("\001\013\n", 3); // Try to get prompt back
+    _zmodemProgress->transferDone();
+  }
+}
+*/
+
 void Session::onReceiveBlock( const char* buf, int len )
 {
     _emulation->receiveData( buf, len );
@@ -747,23 +1232,125 @@
 
   emit resizeRequest(size);
 }
-int Session::foregroundProcessId() const
-{
-    return _shellProcess->foregroundProcessGroup();
-}
 int Session::processId() const
 {
     return _shellProcess->pid();
 }
 
-SessionGroup::SessionGroup()
-    : _masterMode(0)
+void Session::setTitle(int role , const QString& title)
+{
+    switch (role) {
+    case (0):
+        this->setTitle(Session::NameRole, title);
+        break;
+    case (1):
+        this->setTitle(Session::DisplayedTitleRole, title);
+        break;
+    }
+}
+
+QString Session::title(int role) const
+{
+    switch (role) {
+    case (0):
+        return this->title(Session::NameRole);
+    case (1):
+        return this->title(Session::DisplayedTitleRole);
+    default:
+        return QString();
+    }
+}
+
+void Session::setTabTitleFormat(int context , const QString& format)
+{
+    switch (context) {
+    case (0):
+        this->setTabTitleFormat(Session::LocalTabTitle, format);
+        break;
+    case (1):
+        this->setTabTitleFormat(Session::RemoteTabTitle, format);
+        break;
+    }
+}
+
+QString Session::tabTitleFormat(int context) const
+{
+    switch (context) {
+    case (0):
+        return this->tabTitleFormat(Session::LocalTabTitle);
+    case (1):
+        return this->tabTitleFormat(Session::RemoteTabTitle);
+    default:
+        return QString();
+    }
+}
+
+int Session::foregroundProcessId()
+{
+    int pid;
+
+    bool ok = false;
+    pid = getProcessInfo()->pid(&ok);
+    if (!ok)
+        pid = -1;
+
+    return pid;
+}
+
+bool Session::isForegroundProcessActive()
+{
+    // foreground process info is always updated after this
+    return updateForegroundProcessInfo() && (processId() != _foregroundPid);
+}
+
+QString Session::foregroundProcessName()
+{
+    QString name;
+
+    if (updateForegroundProcessInfo()) 
+    {
+        bool ok = false;
+        name = _foregroundProcessInfo->name(&ok);
+        if (!ok)
+            name.clear();
+    }
+
+    return name;
+}
+
+/*
+void Session::saveSession(KConfigGroup& group)
+{
+    group.writePathEntry("WorkingDir", currentWorkingDirectory());
+    group.writeEntry("LocalTab",       tabTitleFormat(LocalTabTitle));
+    group.writeEntry("RemoteTab",      tabTitleFormat(RemoteTabTitle));
+    group.writeEntry("SessionGuid",    _uniqueIdentifier.toString());
+    group.writeEntry("Encoding",       QString(codec()));
+}
+
+void Session::restoreSession(KConfigGroup& group)
+{
+    QString value;
+
+    value = group.readPathEntry("WorkingDir", QString());
+    if (!value.isEmpty()) setInitialWorkingDirectory(value);
+    value = group.readEntry("LocalTab");
+    if (!value.isEmpty()) setTabTitleFormat(LocalTabTitle, value);
+    value = group.readEntry("RemoteTab");
+    if (!value.isEmpty()) setTabTitleFormat(RemoteTabTitle, value);
+    value = group.readEntry("SessionGuid");
+    if (!value.isEmpty()) _uniqueIdentifier = QUuid(value);
+    value = group.readEntry("Encoding");
+    if (!value.isEmpty()) setCodec(value.toUtf8());
+}
+*/
+
+SessionGroup::SessionGroup(QObject* parent)
+    : QObject(parent), _masterMode(0)
 {
 }
 SessionGroup::~SessionGroup()
 {
-    // disconnect all
-    connectAll(false);
 }
 int SessionGroup::masterMode() const { return _masterMode; }
 QList<Session*> SessionGroup::sessions() const { return _sessions.keys(); }
@@ -771,100 +1358,68 @@
 
 void SessionGroup::addSession(Session* session)
 {
+    connect(session,SIGNAL(finished()),this,SLOT(sessionFinished()));
     _sessions.insert(session,false);
-
-    QListIterator<Session*> masterIter(masters());
-
-    while ( masterIter.hasNext() )
-        connectPair(masterIter.next(),session);
 }
 void SessionGroup::removeSession(Session* session)
 {
+    disconnect(session,SIGNAL(finished()),this,SLOT(sessionFinished()));
     setMasterStatus(session,false);
-
-    QListIterator<Session*> masterIter(masters());
-
-    while ( masterIter.hasNext() )
-        disconnectPair(masterIter.next(),session);
-
     _sessions.remove(session);
 }
+void SessionGroup::sessionFinished()
+{
+    Session* session = qobject_cast<Session*>(sender());
+    Q_ASSERT(session);
+    removeSession(session);
+}
 void SessionGroup::setMasterMode(int mode)
 {
    _masterMode = mode;
-
-   connectAll(false);
-   connectAll(true);
 }
 QList<Session*> SessionGroup::masters() const
 {
     return _sessions.keys(true);
 }
-void SessionGroup::connectAll(bool connect)
-{
-    QListIterator<Session*> masterIter(masters());
-
-    while ( masterIter.hasNext() )
-    {
-        Session* master = masterIter.next();
-
-        QListIterator<Session*> otherIter(_sessions.keys());
-        while ( otherIter.hasNext() )
-        {
-            Session* other = otherIter.next();
-
-            if ( other != master )
-            {
-                if ( connect )
-                    connectPair(master,other);
-                else
-                    disconnectPair(master,other);
-            }
-        }
-    }
-}
 void SessionGroup::setMasterStatus(Session* session , bool master)
 {
-    bool wasMaster = _sessions[session];
+    const bool wasMaster = _sessions[session];
+
+    if (wasMaster == master) {
+        // No status change -> nothing to do.
+        return;
+    }
     _sessions[session] = master;
 
-    if (    !wasMaster && !master
-         || wasMaster && master )
-      return;
-
-    QListIterator<Session*> iter(_sessions.keys());
-    while ( iter.hasNext() )
-    {
-        Session* other = iter.next();
-
-        if ( other != session )
-        {
-            if ( master )
-                connectPair(session,other);
-            else
-                disconnectPair(session,other);
-        }
+    if(master) {
+        connect( session->emulation() , SIGNAL(sendData(const char*,int)) , this,
+                 SLOT(forwardData(const char*,int)) );
+    }
+    else {
+        disconnect( session->emulation() , SIGNAL(sendData(const char*,int)) , this,
+                    SLOT(forwardData(const char*,int)) );
     }
 }
-void SessionGroup::connectPair(Session* master , Session* other)
+void SessionGroup::forwardData(const char* data, int size)
 {
-//    qDebug() << k_funcinfo;
-
-    if ( _masterMode & CopyInputToAll )
-    {
-        qDebug() << "Connection session " << master->nameTitle() << "to" << other->nameTitle();
-
-        connect( master->emulation() , SIGNAL(sendData(const char*,int)) , other->emulation() ,
-                 SLOT(sendString(const char*,int)) );
+    static bool _inForwardData = false;
+    if(_inForwardData) {   // Avoid recursive calls among session groups!
+       // A recursive call happens when a master in group A calls forwardData()
+       // in group B. If one of the destination sessions in group B is also a
+       // master of a group including the master session of group A, this would
+       // again call forwardData() in group A, and so on.
+       return;
     }
+    
+    _inForwardData = true;
+    QListIterator<Session*> iter(_sessions.keys());
+    while(iter.hasNext()) {
+        Session* other = iter.next();
+        if(!_sessions[other]) {
+           other->emulation()->sendString(data, size);
+        }
+    }
+    _inForwardData = false;
 }
-void SessionGroup::disconnectPair(Session* master , Session* other)
-{
-    if ( _masterMode & CopyInputToAll )
-    {
-        qDebug() << "Disconnecting session " << master->nameTitle() << "from" << other->nameTitle();
 
-        disconnect( master->emulation() , SIGNAL(sendData(const char*,int)) , other->emulation() ,
-                SLOT(sendString(const char*,int)) );
-    }
-}
+
--- a/gui//src/Session.h	Fri Apr 08 15:23:21 2011 +0200
+++ b/gui//src/Session.h	Sat Apr 09 00:23:46 2011 +0200
@@ -1,10 +1,9 @@
 /*
     This file is part of Konsole, an X terminal.
 
-    Copyright (C) 2007 by Robert Knight <robertknight@gmail.com>
-    Copyright (C) 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
-
-    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+    Copyright 2007-2008 by Robert Knight <robertknight@gmail.com>
+    Copyright 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
+    Copyright 2009 by Thomas Dreibholz <dreibh@iem.uni-due.de>
 
     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
@@ -27,17 +26,26 @@
 
 // Qt
 #include <QtCore/QStringList>
-#include <QtCore>
+#include <QtCore/QByteRef>
+#include <QtCore/QSize>
+#include <QUuid>
 #include <QWidget>
 
+// KDE
+//#include <KApplication>
+//#include <KMainWindow>
+#include "konsole_export.h"
+
 // Konsole
 #include "History.h"
 
 class KProcess;
+class KUrl;
 class Emulation;
 class Pty;
+class ProcessInfo;
 class TerminalDisplay;
-
+  //class ZModemDialog;
 /**
  * Represents a terminal session consisting of a pseudo-teletype and a terminal emulation.
  * The pseudo-teletype (or PTY) handles I/O between the terminal process and Konsole.
@@ -52,6 +60,7 @@
 class Session : public QObject
 {
 Q_OBJECT
+Q_CLASSINFO("D-Bus Interface", "org.kde.konsole.Session")
 
 public:
   Q_PROPERTY(QString name READ nameTitle)
@@ -70,9 +79,21 @@
    * falls back to using the program specified in the SHELL environment
    * variable.
    */
-  Session();
+  explicit Session(QObject* parent = 0);
   ~Session();
 
+  /** 
+   * Connect to an existing terminal.  When a new Session() is constructed it 
+   * automatically searches for and opens a new teletype.  If you want to 
+   * use an existing teletype (given its file descriptor) call this after
+   * constructing the session.
+   *
+   * Calling openTeletype() while a session is running has no effect.
+   *
+   * @param masterFd The file descriptor of the pseudo-teletype master (See KPtyProcess::KPtyProcess())
+   */
+  void openTeletype(int masterFd);
+
   /**
    * Returns true if the session is currently running.  This will be true
    * after run() has been called successfully.
@@ -80,20 +101,6 @@
   bool isRunning() const;
 
   /**
-   * Sets the profile associated with this session.
-   *
-   * @param profileKey A key which can be used to obtain the current
-   * profile settings from the SessionManager
-   */
-  void setProfileKey(const QString& profileKey);
-  /**
-   * Returns the profile key associated with this session.
-   * This can be passed to the SessionManager to obtain the current
-   * profile settings.
-   */
-  QString profileKey() const;
-
-  /**
    * Adds a new view for this session.
    *
    * The viewing widget will display the output from the terminal and
@@ -124,28 +131,10 @@
    */
   Emulation*  emulation() const;
 
-  /**
-   * Returns the environment of this session as a list of strings like
-   * VARIABLE=VALUE
-   */
-  QStringList environment() const;
-  /**
-   * Sets the environment for this session.
-   * @p environment should be a list of strings like
-   * VARIABLE=VALUE
-   */
-  void setEnvironment(const QStringList& environment);
-
   /** Returns the unique ID for this session. */
   int sessionId() const;
 
   /**
-   * Return the session title set by the user (ie. the program running
-   * in the terminal), or an empty string if the user has not set a custom title
-   */
-  QString userTitle() const;
-
-  /**
    * This enum describes the contexts for which separate
    * tab title formats may be specified.
    */
@@ -159,6 +148,13 @@
      */
     RemoteTabTitle
   };
+
+  /**
+   * Returns true if the session currently contains a connection to a 
+   * remote computer.  It currently supports ssh.
+   */
+  bool isRemote();
+
   /**
    * Sets the format used by this session for tab titles.
    *
@@ -196,6 +192,11 @@
   void setInitialWorkingDirectory( const QString& dir );
 
   /**
+   * Returns the current directory of the foreground process in the session
+   */
+  QString currentWorkingDirectory();
+
+  /**
    * Sets the type of history store used by this session.
    * Lines of output produced by the terminal are added
    * to the history store.  The type of history store
@@ -214,32 +215,6 @@
   void clearHistory();
 
   /**
-   * Enables monitoring for activity in the session.
-   * This will cause notifySessionState() to be emitted
-   * with the NOTIFYACTIVITY state flag when output is
-   * received from the terminal.
-   */
-  void setMonitorActivity(bool);
-  /** Returns true if monitoring for activity is enabled. */
-  bool isMonitorActivity() const;
-
-  /**
-   * Enables monitoring for silence in the session.
-   * This will cause notifySessionState() to be emitted
-   * with the NOTIFYSILENCE state flag when output is not
-   * received from the terminal for a certain period of
-   * time, specified with setMonitorSilenceSeconds()
-   */
-  void setMonitorSilence(bool);
-  /**
-   * Returns true if monitoring for inactivity (silence)
-   * in the session is enabled.
-   */
-  bool isMonitorSilence()  const;
-  /** See setMonitorSilence() */
-  void setMonitorSilenceSeconds(int seconds);
-
-  /**
    * Sets the key bindings used by this session.  The bindings
    * specify how input key sequences are translated into
    * the character stream which is sent to the terminal.
@@ -263,28 +238,41 @@
       DisplayedTitleRole
   };
 
-  /** Sets the session's title for the specified @p role to @p title. */
-  void setTitle(TitleRole role , const QString& title);
-  /** Returns the session's title for the specified @p role. */
-  QString title(TitleRole role) const;
+  /**
+   * Return the session title set by the user (ie. the program running
+   * in the terminal), or an empty string if the user has not set a custom title
+   */
+  QString userTitle() const;
+
   /** Convenience method used to read the name property.  Returns title(Session::NameRole). */
   QString nameTitle() const { return title(Session::NameRole); }
+  /** Returns a title generated from tab format and process information. */
+  QString getDynamicTitle();
 
   /** Sets the name of the icon associated with this session. */
   void setIconName(const QString& iconName);
   /** Returns the name of the icon associated with this session. */
   QString iconName() const;
 
+  /** Return URL for the session. */
+  //KUrl getUrl();
+
   /** Sets the text of the icon associated with this session. */
   void setIconText(const QString& iconText);
   /** Returns the text of the icon associated with this session. */
   QString iconText() const;
 
-  /** Specifies whether a utmp entry should be created for the pty used by this session. */
-  void setAddToUtmp(bool);
+  /** Sets the session's title for the specified @p role to @p title. */
+  void setTitle(TitleRole role , const QString& title);
+
+  /** Returns the session's title for the specified @p role. */
+  QString title(TitleRole role) const;
 
-  /** Sends the specified @p signal to the terminal process. */
-  bool sendSignal(int signal);
+  /** 
+   * Specifies whether a utmp entry should be created for the pty used by this session.
+   * If true, KPty::login() is called when the session is started.
+   */
+  void setAddToUtmp(bool);
 
   /**
    * Specifies whether to close the session automatically when the terminal
@@ -292,32 +280,11 @@
    */
   void setAutoClose(bool b) { _autoClose = b; }
 
-  /**
-   * Sets whether flow control is enabled for this terminal
-   * session.
-   */
-  void setFlowControlEnabled(bool enabled);
-
-  /** Returns whether flow control is enabled for this terminal session. */
-  bool flowControlEnabled() const;
+  /** Returns true if the user has started a program in the session. */
+  bool isForegroundProcessActive();
 
-  /**
-   * Sends @p text to the current foreground terminal program.
-   */
-  void sendText(const QString& text) const;
-
-  /**
-   * Returns the process id of the terminal process.
-   * This is the id used by the system API to refer to the process.
-   */
-  int processId() const;
-
-  /**
-   * Returns the process id of the terminal's foreground process.
-   * This is initially the same as processId() but can change
-   * as the user starts other programs inside the terminal.
-   */
-  int foregroundProcessId() const;
+  /** Returns the name of the current foreground process. */
+  QString foregroundProcessName();
 
   /** Returns the terminal session's window size in lines and columns. */
   QSize size();
@@ -329,9 +296,6 @@
    */
   void setSize(const QSize& size);
 
-  /** Sets the text codec used by this session's terminal emulation. */
-  void setCodec(QTextCodec* codec);
-
   /**
    * Sets whether the session has a dark background or not.  The session
    * uses this information to set the COLORFGBG variable in the process's
@@ -353,6 +317,33 @@
    * shell to redraw the prompt line.
    */
   void refresh();
+
+  //  void startZModem(const QString &rz, const QString &dir, const QStringList &list);
+  //  void cancelZModem();
+  //  bool isZModemBusy() { return _zmodemBusy; }
+
+ /** 
+   * Possible values of the @p what parameter for setUserTitle()
+   * See "Operating System Controls" section on http://rtfm.etla.org/xterm/ctlseq.html 
+   */
+  enum UserTitleChange
+  {
+      IconNameAndWindowTitle     = 0,
+    IconName                 = 1,
+    WindowTitle                = 2,
+    TextColor                = 10,
+    BackgroundColor            = 11,
+    SessionName                = 30,
+    ProfileChange            = 50     // this clashes with Xterm's font change command
+  };
+
+  // Sets the text codec used by this sessions terminal emulation.
+  void setCodec(QTextCodec* codec);
+
+  // session management
+  //void saveSession(KConfigGroup& group);
+  //void restoreSession(KConfigGroup& group);
+
 public slots:
 
   /**
@@ -363,18 +354,145 @@
   void run();
 
   /**
+   * Returns the environment of this session as a list of strings like
+   * VARIABLE=VALUE
+   */
+  Q_SCRIPTABLE QStringList environment() const;
+
+  /**
+   * Sets the environment for this session.
+   * @p environment should be a list of strings like
+   * VARIABLE=VALUE
+   */
+  Q_SCRIPTABLE void setEnvironment(const QStringList& environment);
+
+  /**
    * Closes the terminal session.  This sends a hangup signal
-   * (SIGHUP) to the terminal process and causes the done(Session*)
-   * signal to be emitted.
+   * (SIGHUP) to the terminal process and causes the finished()  
+   * signal to be emitted.  If the process does not respond to the SIGHUP signal
+   * then the terminal connection (the pty) is closed and Konsole waits for the 
+   * process to exit.
    */
-  void close();
+  Q_SCRIPTABLE void close();
 
   /**
    * Changes the session title or other customizable aspects of the terminal
    * emulation display. For a list of what may be changed see the
    * Emulation::titleChanged() signal.
+   *
+   * @param what The feature being changed.  Value is one of UserTitleChange
+   * @param caption The text part of the terminal command
    */
-  void setUserTitle( int, const QString &caption );
+  void setUserTitle( int what , const QString &caption );
+
+  /**
+   * Enables monitoring for activity in the session.
+   * This will cause notifySessionState() to be emitted
+   * with the NOTIFYACTIVITY state flag when output is
+   * received from the terminal.
+   */
+  Q_SCRIPTABLE void setMonitorActivity(bool);
+
+  /** Returns true if monitoring for activity is enabled. */
+  Q_SCRIPTABLE bool isMonitorActivity() const;
+
+  /**
+   * Enables monitoring for silence in the session.
+   * This will cause notifySessionState() to be emitted
+   * with the NOTIFYSILENCE state flag when output is not
+   * received from the terminal for a certain period of
+   * time, specified with setMonitorSilenceSeconds()
+   */
+  Q_SCRIPTABLE void setMonitorSilence(bool);
+
+  /**
+   * Returns true if monitoring for inactivity (silence)
+   * in the session is enabled.
+   */
+  Q_SCRIPTABLE bool isMonitorSilence() const;
+
+  /** See setMonitorSilence() */
+  Q_SCRIPTABLE void setMonitorSilenceSeconds(int seconds);
+
+  /**
+   * Sets whether flow control is enabled for this terminal
+   * session.
+   */
+  Q_SCRIPTABLE void setFlowControlEnabled(bool enabled);
+
+  /** Returns whether flow control is enabled for this terminal session. */
+  Q_SCRIPTABLE bool flowControlEnabled() const;
+
+  /**
+   * Sends @p text to the current foreground terminal program.
+   */
+  Q_SCRIPTABLE void sendText(const QString& text) const;
+
+   /**
+    * Sends a mouse event of type @p eventType emitted by button
+    * @p buttons on @p column/@p line to the current foreground
+    * terminal program
+    */
+   Q_SCRIPTABLE void sendMouseEvent(int buttons, int column, int line, int eventType);
+
+   /**
+   * Returns the process id of the terminal process.
+   * This is the id used by the system API to refer to the process.
+   */
+  Q_SCRIPTABLE int processId() const;
+
+  /**
+   * Returns the process id of the terminal's foreground process.
+   * This is initially the same as processId() but can change
+   * as the user starts other programs inside the terminal.
+   */
+  Q_SCRIPTABLE int foregroundProcessId();
+
+  /** Sets the text codec used by this sessions terminal emulation.
+    * Overloaded to accept a QByteArray for convenience since DBus
+    * does not accept QTextCodec directky.
+    */
+  Q_SCRIPTABLE bool setCodec(QByteArray codec);
+
+  /** Returns the codec used to decode incoming characters in this
+   * terminal emulation
+   */
+  Q_SCRIPTABLE QByteArray codec();
+
+  /** Sets the session's title for the specified @p role to @p title.
+   *  This is an overloaded member function for setTitle(TitleRole, QString)
+   *  provided for convenience since enum data types may not be
+   *  exported directly through DBus
+   */
+  Q_SCRIPTABLE void setTitle(int role, const QString& title);
+
+  /** Returns the session's title for the specified @p role.
+   * This is an overloaded member function for  setTitle(TitleRole)
+   * provided for convenience since enum data types may not be
+   * exported directly through DBus
+   */
+  Q_SCRIPTABLE QString title(int role) const;
+
+  /** Returns the "friendly" version of the QUuid of this session.
+  * This is a QUuid with the braces and dashes removed, so it cannot be
+  * used to construct a new QUuid. The same text appears in the
+  * SHELL_SESSION_ID environment variable.
+  */
+  Q_SCRIPTABLE QString shellSessionId() const;
+
+  /** Sets the session's tab title format for the specified @p context to @p format.
+   *  This is an overloaded member function for setTabTitleFormat(TabTitleContext, QString)
+   *  provided for convenience since enum data types may not be
+   *  exported directly through DBus
+   */
+  Q_SCRIPTABLE void setTabTitleFormat(int context, const QString& format);
+
+  /** Returns the session's tab title format for the specified @p context.
+   * This is an overloaded member function for tabTitleFormat(TitleRole)
+   * provided for convenience since enum data types may not be
+   * exported directly through DBus
+   */
+  Q_SCRIPTABLE QString tabTitleFormat(int context) const;
 
 signals:
 
@@ -394,9 +512,6 @@
   /** Emitted when the session's title has changed. */
   void titleChanged();
 
-  /** Emitted when the session's profile has changed. */
-  void profileChanged(const QString& profile);
-
   /**
    * Emitted when the activity state of this session changes.
    *
@@ -421,10 +536,18 @@
    * should be changed.
    */
   void changeBackgroundColorRequest(const QColor&);
+  /** 
+   * Requests that the text color of views on this session should
+   * be changed to @p color.
+   */
+  void changeForegroundColorRequest(const QColor&);
 
   /** TODO: Document me. */
   void openUrlRequest(const QString& url);
 
+  /** TODO: Document me. */
+  //void zmodemDetected();
+
   /**
    * Emitted when the terminal process requests a change
    * in the size of the terminal window.
@@ -451,23 +574,43 @@
 private slots:
   void done(int);
 
+  //  void fireZModemDetected();
+
   void onReceiveBlock( const char* buffer, int len );
   void monitorTimerDone();
 
   void onViewSizeChange(int height, int width);
-  void onEmulationSizeChange(int lines , int columns);
 
   void activityStateSet(int);
 
   //automatically detach views from sessions when view is destroyed
   void viewDestroyed(QObject* view);
 
+  //void zmodemReadStatus();
+  //void zmodemReadAndSendBlock();
+  //void zmodemRcvBlock(const char *data, int len);
+  //void zmodemFinished();
+
+  void updateFlowControlState(bool suspended);
+  void updateWindowSize(int lines, int columns);
 private:
 
   void updateTerminalSize();
   WId windowId() const;
+  bool kill(int signal);
+  // print a warning message in the terminal.  This is used
+  // if the program fails to start, or if the shell exits in 
+  // an unsuccessful manner
+  void terminalWarning(const QString& message);
+  // checks that the binary 'program' is available and can be executed
+  // returns the binary name if available or an empty string otherwise
+  QString checkProgram(const QString& program) const;
+  ProcessInfo* getProcessInfo();
+  void updateSessionProcessInfo();
+  bool updateForegroundProcessInfo();
+  ProcessInfo* updateWorkingDirectory();
 
-  int            _uniqueIdentifier;
+  QUuid            _uniqueIdentifier; // SHELL_SESSION_ID
 
   Pty*          _shellProcess;
   Emulation*    _emulation;
@@ -504,6 +647,18 @@
   int            _sessionId;
 
   QString        _initialWorkingDir;
+  QString        _currentWorkingDir;
+
+  ProcessInfo*   _sessionProcessInfo;
+  ProcessInfo*   _foregroundProcessInfo;
+  int            _foregroundPid;
+
+  // ZModem
+  //  bool           _zmodemBusy;
+  //  KProcess*      _zmodemProc;
+  //  ZModemDialog*  _zmodemProgress;
+
+  // Color/Font Changes by ESC Sequences
 
   QColor         _modifiedBackground; // as set by: echo -en '\033]11;Color\007
 
@@ -527,7 +682,7 @@
 
 public:
     /** Constructs an empty session group. */
-    SessionGroup();
+    SessionGroup(QObject* parent);
     /** Destroys the session group and removes all connections between master and slave sessions. */
     ~SessionGroup();
 
@@ -577,10 +732,11 @@
      */
     int masterMode() const;
 
+private slots:
+    void sessionFinished();
+    void forwardData(const char* data, int size);
+
 private:
-    void connectPair(Session* master , Session* other);
-    void disconnectPair(Session* master , Session* other);
-    void connectAll(bool connect);
     QList<Session*> masters() const;
 
     // maps sessions to their master status
@@ -588,4 +744,14 @@
 
     int _masterMode;
 };
+
 #endif
+
+/*
+  Local Variables:
+  mode: c++
+  c-file-style: "stroustrup"
+  indent-tabs-mode: nil
+  tab-width: 4
+  End:
+*/
--- a/gui//src/TerminalCharacterDecoder.cpp	Fri Apr 08 15:23:21 2011 +0200
+++ b/gui//src/TerminalCharacterDecoder.cpp	Sat Apr 09 00:23:46 2011 +0200
@@ -1,10 +1,8 @@
 /*
     This file is part of Konsole, an X terminal.
     
-    Copyright (C) 2006 by Robert Knight <robertknight@gmail.com>
+    Copyright 2006-2008 by Robert Knight <robertknight@gmail.com>
     
-    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
-
     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
@@ -27,9 +25,16 @@
 // Qt
 #include <QtCore/QTextStream>
 
+// KDE
+//#include <kdebug.h>
+
+// Konsole
+#include "konsole_wcwidth.h"
+
 PlainTextDecoder::PlainTextDecoder()
  : _output(0)
  , _includeTrailingWhitespace(true)
+ , _recordLinePositions(false)
 {
 
 }
@@ -43,24 +48,41 @@
 }
 void PlainTextDecoder::begin(QTextStream* output)
 {
-   _output = output; 
+   _output = output;
+   if (!_linePositions.isEmpty())
+       _linePositions.clear();
 }
 void PlainTextDecoder::end()
 {
     _output = 0;
 }
+
+void PlainTextDecoder::setRecordLinePositions(bool record)
+{
+    _recordLinePositions = record;
+}
+QList<int> PlainTextDecoder::linePositions() const
+{
+    return _linePositions;
+}
 void PlainTextDecoder::decodeLine(const Character* const characters, int count, LineProperty /*properties*/
-							 )
+                             )
 {
     Q_ASSERT( _output );
 
-	//TODO should we ignore or respect the LINE_WRAPPED line property?
+    if (_recordLinePositions && _output->string())
+    {
+        int pos = _output->string()->count();
+        _linePositions << pos;
+    }
 
-	//note:  we build up a QString and send it to the text stream rather writing into the text
-	//stream a character at a time because it is more efficient.
-	//(since QTextStream always deals with QStrings internally anyway)
-	QString plainText;
-	plainText.reserve(count);
+    //TODO should we ignore or respect the LINE_WRAPPED line property?
+
+    //note:  we build up a QString and send it to the text stream rather writing into the text
+    //stream a character at a time because it is more efficient.
+    //(since QTextStream always deals with QStrings internally anyway)
+    QString plainText;
+    plainText.reserve(count);
    
     int outputCount = count;
 
@@ -76,22 +98,22 @@
                 outputCount--;
         }
     }
-
-	for (int i=0;i<outputCount;i++)
-	{
-		plainText.append( QChar(characters[i].character) );
-	}
-
-	*_output << plainText;
+    
+    for (int i=0;i<outputCount;)
+    {
+        plainText.append( QChar(characters[i].character) );
+        i += qMax(1,konsole_wcwidth(characters[i].character));
+    }
+    *_output << plainText;
 }
 
 HTMLDecoder::HTMLDecoder() :
         _output(0)
-	   ,_colorTable(base_color_table)
+    ,_colorTable(base_color_table)
        ,_innerSpanOpen(false)
        ,_lastRendition(DEFAULT_RENDITION)
 {
-	
+    
 }
 
 void HTMLDecoder::begin(QTextStream* output)
@@ -100,7 +122,7 @@
 
     QString text;
 
-	//open monospace span
+    //open monospace span
     openSpan(text,"font-family:monospace");
 
     *output << text;
@@ -121,103 +143,108 @@
 }
 
 //TODO: Support for LineProperty (mainly double width , double height)
-void HTMLDecoder::decodeLine(const Character* const characters, int count, LineProperty)
+void HTMLDecoder::decodeLine(const Character* const characters, int count, LineProperty /*properties*/
+                            )
 {
     Q_ASSERT( _output );
 
-	QString text;
+    QString text;
 
-	int spaceCount = 0;
-		
-	for (int i=0;i<count;i++)
-	{
-		QChar ch(characters[i].character);
+    int spaceCount = 0;
+        
+    for (int i=0;i<count;i++)
+    {
+        QChar ch(characters[i].character);
 
-		//check if appearance of character is different from previous char
-		if ( characters[i].rendition != _lastRendition  ||
-		     characters[i].foregroundColor != _lastForeColor  ||
-			 characters[i].backgroundColor != _lastBackColor )
-		{
-			if ( _innerSpanOpen )
-					closeSpan(text);
+        //check if appearance of character is different from previous char
+        if ( characters[i].rendition != _lastRendition  ||
+             characters[i].foregroundColor != _lastForeColor  ||
+             characters[i].backgroundColor != _lastBackColor )
+        {
+            if ( _innerSpanOpen )
+                    closeSpan(text);
 
-			_lastRendition = characters[i].rendition;
-			_lastForeColor = characters[i].foregroundColor;
-			_lastBackColor = characters[i].backgroundColor;
-			
-			//build up style string
-			QString style;
+            _lastRendition = characters[i].rendition;
+            _lastForeColor = characters[i].foregroundColor;
+            _lastBackColor = characters[i].backgroundColor;
+            
+            //build up style string
+            QString style;
 
-			if ( _lastRendition & RE_BOLD ||
-                             (_colorTable && characters[i].isBold(_colorTable)) )
-					style.append("font-weight:bold;");
-
+            bool useBold;
+            ColorEntry::FontWeight weight = characters[i].fontWeight(_colorTable);
+            if (weight == ColorEntry::UseCurrentFormat)
+                useBold = _lastRendition & RE_BOLD;
+            else
+                useBold = weight == ColorEntry::Bold;
+            
+            if (useBold)
+                style.append("font-weight:bold;");
 
-			if ( _lastRendition & RE_UNDERLINE )
-					style.append("font-decoration:underline;");
-		
-			//colours - a colour table must have been defined first
-			if ( _colorTable )	
-			{
-				style.append( QString("color:%1;").arg(_lastForeColor.color(_colorTable).name() ) );
+            if ( _lastRendition & RE_UNDERLINE )
+                    style.append("font-decoration:underline;");
+        
+            //colours - a colour table must have been defined first
+            if ( _colorTable )    
+            {
+                style.append( QString("color:%1;").arg(_lastForeColor.color(_colorTable).name() ) );
 
-				if (!characters[i].isTransparent(_colorTable))
-				{
-					style.append( QString("background-color:%1;").arg(_lastBackColor.color(_colorTable).name() ) );
-				}
-			}
-		
-			//open the span with the current style	
-			openSpan(text,style);
-			_innerSpanOpen = true;
-		}
+                if (!characters[i].isTransparent(_colorTable))
+                {
+                    style.append( QString("background-color:%1;").arg(_lastBackColor.color(_colorTable).name() ) );
+                }
+            }
+        
+            //open the span with the current style    
+            openSpan(text,style);
+            _innerSpanOpen = true;
+        }
 
-		//handle whitespace
-		if (ch.isSpace())
-			spaceCount++;
-		else
-			spaceCount = 0;
-		
+        //handle whitespace
+        if (ch.isSpace())
+            spaceCount++;
+        else
+            spaceCount = 0;
+        
 
-		//output current character
-		if (spaceCount < 2)
-		{
-			//escape HTML tag characters and just display others as they are
-			if ( ch == '<' )
-				text.append("&lt;");
-			else if (ch == '>')
-					text.append("&gt;");
-			else	
-					text.append(ch);
-		}
-		else
-		{
-			text.append("&nbsp;"); //HTML truncates multiple spaces, so use a space marker instead
-		}
-		
-	}
+        //output current character
+        if (spaceCount < 2)
+        {
+            //escape HTML tag characters and just display others as they are
+            if ( ch == '<' )
+                text.append("&lt;");
+            else if (ch == '>')
+                    text.append("&gt;");
+            else    
+                    text.append(ch);
+        }
+        else
+        {
+            text.append("&nbsp;"); //HTML truncates multiple spaces, so use a space marker instead
+        }
+        
+    }
 
-	//close any remaining open inner spans
-	if ( _innerSpanOpen )
-		closeSpan(text);
+    //close any remaining open inner spans
+    if ( _innerSpanOpen )
+        closeSpan(text);
 
-	//start new line
-	text.append("<br>");
-	
-	*_output << text;
+    //start new line
+    text.append("<br>");
+    
+    *_output << text;
 }
-
 void HTMLDecoder::openSpan(QString& text , const QString& style)
 {
-	text.append( QString("<span style=\"%1\">").arg(style) );
+    text.append( QString("<span style=\"%1\">").arg(style) );
 }
 
 void HTMLDecoder::closeSpan(QString& text)
 {
-	text.append("</span>");
+    text.append("</span>");
 }
 
 void HTMLDecoder::setColorTable(const ColorEntry* table)
 {
-	_colorTable = table;
+    _colorTable = table;
 }
--- a/gui//src/TerminalCharacterDecoder.h	Fri Apr 08 15:23:21 2011 +0200
+++ b/gui//src/TerminalCharacterDecoder.h	Sat Apr 09 00:23:46 2011 +0200
@@ -1,10 +1,8 @@
 /*
     This file is part of Konsole, an X terminal.
     
-    Copyright (C) 2006-7 by Robert Knight <robertknight@gmail.com>
+    Copyright 2006-2008 by Robert Knight <robertknight@gmail.com>
     
-    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
-
     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
@@ -26,6 +24,8 @@
 
 #include "Character.h"
 
+#include <QList>
+
 class QTextStream;
 
 /**
@@ -40,24 +40,24 @@
 class TerminalCharacterDecoder
 {
 public:
-	virtual ~TerminalCharacterDecoder() {}
+    virtual ~TerminalCharacterDecoder() {}
 
     /** Begin decoding characters.  The resulting text is appended to @p output. */
     virtual void begin(QTextStream* output) = 0;
     /** End decoding. */
     virtual void end() = 0;
 
-	/**
-	 * Converts a line of terminal characters with associated properties into a text string
-	 * and writes the string into an output QTextStream.
-	 *
-	 * @param characters An array of characters of length @p count.
-	 * @param properties Additional properties which affect all characters in the line
-	 * @param output The output stream which receives the decoded text
-	 */
-	virtual void decodeLine(const Character* const characters, 
-							int count,
-							LineProperty properties) = 0; 
+    /**
+     * Converts a line of terminal characters with associated properties into a text string
+     * and writes the string into an output QTextStream.
+     *
+     * @param characters An array of characters of length @p count.
+     * @param count The number of characters
+     * @param properties Additional properties which affect all characters in the line
+     */
+    virtual void decodeLine(const Character* const characters, 
+                            int count,
+                            LineProperty properties) = 0; 
 };
 
 /**
@@ -67,7 +67,7 @@
 class PlainTextDecoder : public TerminalCharacterDecoder
 {
 public:
-	PlainTextDecoder(); 
+    PlainTextDecoder(); 
 
     /** 
      * Set whether trailing whitespace at the end of lines should be included 
@@ -80,18 +80,29 @@
      * 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 
+     * the output device is not a string.
+     */
+    QList<int> linePositions() const;
+    /** Enables recording of character positions at which new lines are added.  See linePositions() */
+    void setRecordLinePositions(bool record);
 
     virtual void begin(QTextStream* output);
     virtual void end();
 
-	virtual void decodeLine(const Character* const characters,
-							int count,
-							LineProperty properties);	
+    virtual void decodeLine(const Character* const characters,
+                            int count,
+                            LineProperty properties);    
 
     
 private:
     QTextStream* _output;
     bool _includeTrailingWhitespace;
+
+    bool _recordLinePositions;
+    QList<int> _linePositions;
 };
 
 /**
@@ -100,34 +111,35 @@
 class HTMLDecoder : public TerminalCharacterDecoder
 {
 public:
-	/** 
-	 * Constructs an HTML decoder using a default black-on-white color scheme.
-	 */
-	HTMLDecoder();
+    /** 
+     * Constructs an HTML decoder using a default black-on-white color scheme.
+     */
+    HTMLDecoder();
 
-	/**
-	 * Sets the colour table which the decoder uses to produce the HTML colour codes in its
-	 * output
-	 */
-	void setColorTable( const ColorEntry* table );
-		
-	virtual void decodeLine(const Character* const characters,
-							int count,
-							LineProperty properties);
+    /**
+     * Sets the colour table which the decoder uses to produce the HTML colour codes in its
+     * output
+     */
+    void setColorTable( const ColorEntry* table );
+        
+    virtual void decodeLine(const Character* const characters,
+                            int count,
+                            LineProperty properties);
 
     virtual void begin(QTextStream* output);
     virtual void end();
 
 private:
-	void openSpan(QString& text , const QString& style);
-	void closeSpan(QString& text);
+    void openSpan(QString& text , const QString& style);
+    void closeSpan(QString& text);
 
     QTextStream* _output;
-	const ColorEntry* _colorTable;
+    const ColorEntry* _colorTable;
     bool _innerSpanOpen; 
-	quint8 _lastRendition;
-	CharacterColor _lastForeColor;
-	CharacterColor _lastBackColor;
+    quint8 _lastRendition;
+    CharacterColor _lastForeColor;
+    CharacterColor _lastBackColor;
 
 };
+
 #endif
--- a/gui//src/TerminalDisplay.cpp	Fri Apr 08 15:23:21 2011 +0200
+++ b/gui//src/TerminalDisplay.cpp	Sat Apr 09 00:23:46 2011 +0200
@@ -1,11 +1,9 @@
 /*
     This file is part of Konsole, a terminal emulator for KDE.
     
-    Copyright (C) 2006-7 by Robert Knight <robertknight@gmail.com>
-    Copyright (C) 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
+    Copyright 2006-2008 by Robert Knight <robertknight@gmail.com>
+    Copyright 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
     
-    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, 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
@@ -40,14 +38,29 @@
 #include <QtGui/QPixmap>
 #include <QtGui/QScrollBar>
 #include <QtGui/QStyle>
-#include <QtCore>
-#include <QtGui>
-
+#include <QtCore/QTimer>
+#include <QtGui/QToolTip>
+#include <QtCore/QTextStream>
+
+// KDE
+//#include <kshell.h>
+//#include <KColorScheme>
+//#include <KCursor>
+//#include <kdebug.h>
+//#include <KLocale>
+//#include <KMenu>
+//#include <KNotification>
+//#include <KGlobalSettings>
+//#include <KShortcut>
+//#include <KIO/NetAccess>
+//#include "kdebug.h"
+
+// Konsole
+//#include <config-apps.h>
 #include "Filter.h"
 #include "konsole_wcwidth.h"
 #include "ScreenWindow.h"
 #include "TerminalCharacterDecoder.h"
-#include "ColorTables.h"
 
 #ifndef loc
 #define loc(X,Y) ((Y)*_columns+(X))
@@ -59,12 +72,36 @@
                   "abcdefgjijklmnopqrstuvwxyz" \
                   "0123456789./+@"
 
+const ColorEntry base_color_table[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.
+{
+  // 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;
 
+// we use this to force QPainter to display text in LTR mode
+// more information can be found in: http://unicode.org/reports/tr9/ 
+const QChar LTR_OVERRIDE_CHAR( 0x202D );
+
 /* ------------------------------------------------------------------------- */
 /*                                                                           */
 /*                                Colors                                     */
@@ -95,10 +132,12 @@
 
     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()) );
-	window->setWindowLines(_lines);
+        window->setWindowLines(_lines);
     }
 }
 
@@ -106,20 +145,30 @@
 {
   return _colorTable;
 }
-
+void TerminalDisplay::setBackgroundColor(const QColor& color)
+{
+    _colorTable[DEFAULT_BACK_COLOR].color = color;
+    QPalette p = palette();
+      p.setColor( backgroundRole(), color ); 
+      setPalette( p );
+
+      // Avoid propagating the palette change to the scroll bar 
+      _scrollBar->setPalette( QApplication::palette() );  
+
+    update();
+}
+void TerminalDisplay::setForegroundColor(const QColor& color)
+{
+    _colorTable[DEFAULT_FORE_COLOR].color = color;
+
+    update();
+}
 void TerminalDisplay::setColorTable(const ColorEntry table[])
 {
   for (int i = 0; i < TABLE_COLORS; i++)
       _colorTable[i] = table[i];
 
-  QPalette p = palette();
-  p.setColor( backgroundRole(), _colorTable[DEFAULT_BACK_COLOR].color );
-  setPalette( p );
-
-  // Avoid propagating the palette change to the scroll bar 
-  _scrollBar->setPalette( QApplication::palette() );  
-
-  update();
+  setBackgroundColor(_colorTable[DEFAULT_BACK_COLOR].color);
 }
 
 /* ------------------------------------------------------------------------- */
@@ -143,9 +192,9 @@
 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.
 
@@ -162,7 +211,6 @@
   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."
@@ -197,6 +245,11 @@
 
   QFontMetrics metrics(font);
 
+  if ( !QFontInfo(font).fixedPitch() )
+  {
+      //kWarning() << "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.  
@@ -233,6 +286,7 @@
 ,_fontHeight(1)
 ,_fontWidth(1)
 ,_fontAscent(1)
+,_boldIntense(true)
 ,_lines(1)
 ,_columns(1)
 ,_usedLines(1)
@@ -254,9 +308,11 @@
 ,_wordCharacters(":@-./_~")
 ,_bellMode(SystemBeepBell)
 ,_blinking(false)
+,_hasBlinker(false)
 ,_cursorBlinking(false)
 ,_hasBlinkingCursor(false)
-,_ctrlDrag(false)
+,_allowBlinkingText(true)
+,_ctrlDrag(true)
 ,_tripleClickMode(SelectWholeLine)
 ,_isFixedSize(false)
 ,_possibleTripleClick(false)
@@ -286,7 +342,7 @@
   setScroll(0,0); 
   _scrollBar->setCursor( Qt::ArrowCursor );
   connect(_scrollBar, SIGNAL(valueChanged(int)), this, 
-  					  SLOT(scrollBarPositionChanged(int)));
+                        SLOT(scrollBarPositionChanged(int)));
 
   // setup timers for blinking cursor and text
   _blinkTimer   = new QTimer(this);
@@ -294,11 +350,10 @@
   _blinkCursorTimer   = new QTimer(this);
   connect(_blinkCursorTimer, SIGNAL(timeout()), this, SLOT(blinkCursorEvent()));
 
-//  QCursor::setAutoHideCursor( this, true );
+  //KCursor::setAutoHideCursor( this, true );
   
   setUsesMouse(true);
-  setColorTable(whiteonblack_color_table); 
-//  setColorTable(blackonlightyellow_color_table); 
+  setColorTable(base_color_table);
   setMouseTracking(true);
 
   // Enable drag and drop 
@@ -315,16 +370,17 @@
   setAttribute(Qt::WA_OpaquePaintEvent);
 
   _gridLayout = new QGridLayout(this);
-  _gridLayout->setMargin(0);
+  _gridLayout->setContentsMargins(0, 0, 0, 0);
 
   setLayout( _gridLayout ); 
 
-  //set up a warning message when the user presses Ctrl+S to avoid confusion
-  connect( this,SIGNAL(flowControlKeyPressed(bool)),this,SLOT(outputSuspended(bool)) );
+  new AutoScrollHandler(this);
 }
 
 TerminalDisplay::~TerminalDisplay()
 {
+  disconnect(_blinkTimer);
+  disconnect(_blinkCursorTimer);
   qApp->removeEventFilter( this );
   
   delete[] _image;
@@ -456,26 +512,26 @@
 
 }
 
-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();
-		
-		if ( attributes->rendition & RE_BOLD )
-		{
-			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 );
+        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);
+        }
+
+        painter.setPen( currentPen );
 }
 
 void TerminalDisplay::setKeyboardCursorShape(KeyboardCursorShape shape)
@@ -509,14 +565,14 @@
 
     // 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();
 }
@@ -547,9 +603,8 @@
             painter.fillRect(contentsRect, color);
             painter.restore();
         } 
-        else {
-	    painter.fillRect(contentsRect, backgroundColor);
-	}
+        else
+            painter.fillRect(contentsRect, backgroundColor);
 
         painter.fillRect(scrollBarArea,_scrollBar->palette().background());
 }
@@ -567,9 +622,8 @@
     {
        if ( _cursorColor.isValid() )
            painter.setPen(_cursorColor);
-       else {
-    	    painter.setPen(foregroundColor);
-	}
+       else
+           painter.setPen(foregroundColor);
 
        if ( _cursorShape == BlockCursor )
        {
@@ -584,7 +638,7 @@
             if ( hasFocus() )
             {
                 painter.fillRect(cursorRect, _cursorColor.isValid() ? _cursorColor : foregroundColor);
-	    
+            
                 if ( !_cursorColor.isValid() )
                 {
                     // invert the colour used to draw the text to ensure that the character at
@@ -618,7 +672,12 @@
             return;
    
     // setup bold and underline
-    bool useBold = style->rendition & RE_BOLD || style->isBold(_colorTable) || font().bold();
+    bool useBold;
+    ColorEntry::FontWeight weight = style->fontWeight(_colorTable);    
+    if (weight == ColorEntry::UseCurrentFormat)
+        useBold = ((style->rendition & RE_BOLD) && _boldIntense) || font().bold();
+    else
+        useBold = (weight == ColorEntry::Bold) ? true : false;
     bool useUnderline = style->rendition & RE_UNDERLINE || font().underline();
 
     QFont font = painter.font();
@@ -630,28 +689,32 @@
        painter.setFont(font);
     }
 
+    // setup pen
     const CharacterColor& textColor = ( invertCharacterColor ? style->backgroundColor : style->foregroundColor );
     const QColor color = textColor.color(_colorTable);
-
     QPen pen = painter.pen();
     if ( pen.color() != color )
     {
         pen.setColor(color);
         painter.setPen(color);
     }
+
     // draw text
-    if ( isLineCharString(text) ) {
-	  	drawLineCharString(painter,rect.x(),rect.y(),text,style);
-    }
+    if ( isLineCharString(text) )
+        drawLineCharString(painter,rect.x(),rect.y(),text,style);
     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 
-		// the widget-specific layout direction, which should always be
-		// Qt::LeftToRight for this widget
-        painter.drawText(rect,0,text);
-	}
+    {
+        // 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 
+        // 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
+        if (_bidiEnabled)
+            painter.drawText(rect,0,text);
+        else
+            painter.drawText(rect,0,LTR_OVERRIDE_CHAR+text);
+    }
 }
 
 void TerminalDisplay::drawTextFragment(QPainter& painter , 
@@ -667,14 +730,15 @@
     
     // draw background if different from the display's background color
     if ( backgroundColor != palette().background().color() )
-        drawBackground(painter,rect,backgroundColor, false /* do not use transparency */);
+        drawBackground(painter,rect,backgroundColor,
+                       false /* do not use transparency */);
 
     // draw cursor shape if the current character is the cursor
     // this may alter the foreground and background colors
     bool invertCharacterColor = false;
-
     if ( style->rendition & RE_CURSOR )
         drawCursor(painter,rect,foregroundColor,backgroundColor,invertCharacterColor);
+
     // draw text
     drawCharacters(painter,rect,text,style,invertCharacterColor);
 
@@ -684,6 +748,26 @@
 void TerminalDisplay::setRandomSeed(uint randomSeed) { _randomSeed = randomSeed; }
 uint TerminalDisplay::randomSeed() const { return _randomSeed; }
 
+#if 0
+/*!
+    Set XIM Position
+*/
+void TerminalDisplay::setCursorPos(const int curx, const int cury)
+{
+    QPoint tL  = contentsRect().topLeft();
+    int    tLx = tL.x();
+    int    tLy = tL.y();
+
+    int xpos, ypos;
+    ypos = _topMargin + tLy + _fontHeight*(cury-1) + _fontAscent;
+    xpos = _leftMargin + tLx + _fontWidth*curx;
+    //setMicroFocusHint(xpos, ypos, 0, _fontHeight); //### ???
+    // fprintf(stderr, "x/y = %d/%d\txpos/ypos = %d/%d\n", curx, cury, xpos, ypos);
+    _cursorLine = cury;
+    _cursorCol = curx;
+}
+#endif
+
 // scrolls the image by 'lines', down if lines > 0 or up otherwise.
 //
 // the terminal emulation keeps track of the scrolling of the character 
@@ -692,19 +776,13 @@
 // 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
-//
-// note:  it is important that the area of the display which is 
-// scrolled aligns properly with the character grid - 
-// which has a top left point at (_leftMargin,_topMargin) , 
-// a cell width of _fontWidth and a cell height of _fontHeight).    
 void TerminalDisplay::scrollImage(int lines , const QRect& screenWindowRegion)
 {
-	// if the flow control warning is enabled this will interfere with the 
-	// scrolling optimisations and cause artifacts.  the simple solution here
-	// is to just disable the optimisation whilst it is visible
-	if ( _outputSuspendedLabel && _outputSuspendedLabel->isVisible() ) {
-		return;
-	}
+    // if the flow control warning is enabled this will interfere with the 
+    // scrolling optimizations and cause artifacts.  the simple solution here
+    // is to just disable the optimization whilst it is visible
+    if ( _outputSuspendedLabel && _outputSuspendedLabel->isVisible() )
+        return;
 
     // constrain the region to the display
     // the bottom of the region is capped to the number of lines in the display's
@@ -713,14 +791,40 @@
     QRect region = screenWindowRegion;
     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;
 
+    // hide terminal size label to prevent it being scrolled
+    if (_resizeWidget && _resizeWidget->isVisible())
+        _resizeWidget->hide();
+
+    // Note:  With Qt 4.4 the left edge of the scrolled area must be at 0
+    // to get the correct (newly exposed) part of the widget repainted.
+    //
+    // The right edge must be before the left edge of the scroll bar to 
+    // avoid triggering a repaint of the entire widget, the distance is 
+    // given by SCROLLBAR_CONTENT_GAP
+    //
+    // Set the QT_FLUSH_PAINT environment variable to '1' before starting the
+    // application to monitor repainting.
+    //
+    int scrollBarWidth = _scrollBar->isHidden() ? 0 : _scrollBar->width();
+    const int SCROLLBAR_CONTENT_GAP = 1;
     QRect scrollRect;
-
+    if ( _scrollbarLocation == ScrollBarLeft )
+    {
+        scrollRect.setLeft(scrollBarWidth+SCROLLBAR_CONTENT_GAP);
+        scrollRect.setRight(width());
+    }
+    else
+    {
+        scrollRect.setLeft(0);
+        scrollRect.setRight(width() - scrollBarWidth - SCROLLBAR_CONTENT_GAP);
+    }
     void* firstCharPos = &_image[ region.top() * this->_columns ];
     void* lastCharPos = &_image[ (region.top() + abs(lines)) * this->_columns ];
 
@@ -745,11 +849,8 @@
         //scroll internal image down
         memmove( firstCharPos , lastCharPos , bytesToMove ); 
       
-        //set region of display to scroll, making sure that
-        //the region aligns correctly to the character grid 
-        scrollRect = QRect( _leftMargin , top, 
-                            this->_usedColumns * _fontWidth , 
-                            linesToMove * _fontHeight );
+        //set region of display to scroll
+        scrollRect.setTop(top);
     }
     else
     {
@@ -760,14 +861,12 @@
         //scroll internal image up
         memmove( lastCharPos , firstCharPos , bytesToMove ); 
      
-        //set region of the display to scroll, making sure that
-        //the region aligns correctly to the character grid
-        QPoint topPoint( _leftMargin , top + abs(lines)*_fontHeight );
-
-        scrollRect = QRect( topPoint ,
-                     QSize( this->_usedColumns*_fontWidth , 
-                            linesToMove * _fontHeight ));
+        //set region of the display to scroll
+        scrollRect.setTop(top + abs(lines) * _fontHeight); 
     }
+    scrollRect.setHeight(linesToMove * _fontHeight );
+
+    Q_ASSERT(scrollRect.isValid() && !scrollRect.isEmpty());
 
     //scroll the display vertically to match internal _image
     scroll( 0 , _fontHeight * (-lines) , scrollRect );
@@ -775,41 +874,60 @@
 
 QRegion TerminalDisplay::hotSpotRegion() const 
 {
-	QRegion region;
-	foreach( Filter::HotSpot* hotSpot , _filterChain->hotSpots() )
-	{
-		QRect rect;
-		rect.setLeft(hotSpot->startColumn());
-		rect.setTop(hotSpot->startLine());
-		rect.setRight(hotSpot->endColumn());
-		rect.setBottom(hotSpot->endLine());
-
-		region |= imageToWidget(rect); 
-	}
-	return region;
+    QRegion region;
+    foreach( Filter::HotSpot* hotSpot , _filterChain->hotSpots() )
+    {
+        QRect r;
+        if (hotSpot->startLine()==hotSpot->endLine()) {
+            r.setLeft(hotSpot->startColumn());
+            r.setTop(hotSpot->startLine());
+            r.setRight(hotSpot->endColumn());
+            r.setBottom(hotSpot->endLine());
+            region |= imageToWidget(r);;
+        } else {
+            r.setLeft(hotSpot->startColumn());
+            r.setTop(hotSpot->startLine());
+            r.setRight(_columns);
+            r.setBottom(hotSpot->startLine());
+            region |= imageToWidget(r);;
+            for ( int line = hotSpot->startLine()+1 ; line < hotSpot->endLine() ; line++ ) {
+                r.setLeft(0);
+                r.setTop(line);
+                r.setRight(_columns);
+                r.setBottom(line);
+                region |= imageToWidget(r);;
+            }
+            r.setLeft(0);
+            r.setTop(hotSpot->endLine());
+            r.setRight(hotSpot->endColumn());
+            r.setBottom(hotSpot->endLine());
+            region |= imageToWidget(r);;
+        }
+    }
+    return region;
 }
 
 void TerminalDisplay::processFilters() 
 {
-	if (!_screenWindow)
-		return;
-
-	QRegion preUpdateHotSpots = hotSpotRegion();
-
-	// use _screenWindow->getImage() here rather than _image because
-	// other classes may call processFilters() when this display's
-	// ScreenWindow emits a scrolled() signal - which will happen before
-	// updateImage() is called on the display and therefore _image is 
-	// out of date at this point
-	_filterChain->setImage( _screenWindow->getImage(),
-							_screenWindow->windowLines(),
-							_screenWindow->windowColumns(),
-							_screenWindow->getLineProperties() );
+    if (!_screenWindow)
+        return;
+
+    QRegion preUpdateHotSpots = hotSpotRegion();
+
+    // use _screenWindow->getImage() here rather than _image because
+    // other classes may call processFilters() when this display's
+    // ScreenWindow emits a scrolled() signal - which will happen before
+    // updateImage() is called on the display and therefore _image is 
+    // out of date at this point
+    _filterChain->setImage( _screenWindow->getImage(),
+                            _screenWindow->windowLines(),
+                            _screenWindow->windowColumns(),
+                            _screenWindow->getLineProperties() );
     _filterChain->process();
 
-	QRegion postUpdateHotSpots = hotSpotRegion();
-
-	update( preUpdateHotSpots | postUpdateHotSpots );
+    QRegion postUpdateHotSpots = hotSpotRegion();
+
+    update( preUpdateHotSpots | postUpdateHotSpots );
 }
 
 void TerminalDisplay::updateImage() 
@@ -824,22 +942,24 @@
                _screenWindow->scrollRegion() );
   _screenWindow->resetScrollCount();
 
+  if (!_image) {
+     // Create _image.
+     // The emitted changedContentSizeSignal also leads to getImage being recreated, so do this first.
+     updateImageSize();
+  }
+
   Character* const newimg = _screenWindow->getImage();
   int lines = _screenWindow->windowLines();
   int columns = _screenWindow->windowColumns();
 
   setScroll( _screenWindow->currentLine() , _screenWindow->lineCount() );
 
-  if (!_image)
-     updateImageSize(); // Create _image
-
   Q_ASSERT( this->_usedLines <= this->_lines );
   Q_ASSERT( this->_usedColumns <= this->_columns );
 
   int y,x,len;
 
   QPoint tL  = contentsRect().topLeft();
-
   int    tLx = tL.x();
   int    tLy = tL.y();
   _hasBlinker = false;
@@ -860,7 +980,7 @@
   // which therefore need to be repainted
   int dirtyLineCount = 0;
 
-  for (y = 0; y < linesToUpdate; y++)
+  for (y = 0; y < linesToUpdate; ++y)
   {
     const Character*       currentLine = &_image[y*this->_columns];
     const Character* const newLine = &newimg[y*columns];
@@ -872,7 +992,7 @@
     // its cell boundaries
     memset(dirtyMask, 0, columnsToUpdate+2);
    
-    for( x = 0 ; x < columnsToUpdate ; x++)
+    for( x = 0 ; x < columnsToUpdate ; ++x)
     {
         if ( newLine[x] != currentLine[x] ) 
         {
@@ -881,7 +1001,7 @@
     }
 
     if (!_resizing) // not while _resizing, we're expecting a paintEvent
-    for (x = 0; x < columnsToUpdate; x++)
+    for (x = 0; x < columnsToUpdate; ++x)
     {
       _hasBlinker |= (newLine[x].rendition & RE_BLINK);
     
@@ -901,14 +1021,14 @@
         _clipboard = newLine[x].backgroundColor;
         if (newLine[x].foregroundColor != cf) cf = newLine[x].foregroundColor;
         int lln = columnsToUpdate - x;
-        for (len = 1; len < lln; len++)
+        for (len = 1; len < lln; ++len)
         {
             const Character& ch = newLine[x+len];
 
             if (!ch.character)
                 continue; // Skip trailing part of multi-col chars.
 
-			bool nextIsDoubleWidth = (x+len+1 == columnsToUpdate) ? false : (newLine[x+len+1].character == 0);
+            bool nextIsDoubleWidth = (x+len+1 == columnsToUpdate) ? false : (newLine[x+len+1].character == 0);
 
             if (  ch.foregroundColor != cf || 
                   ch.backgroundColor != _clipboard || 
@@ -929,18 +1049,18 @@
         if (doubleWidth)
            _fixedFont = false;
 
-		updateLine = true;
-
-		_fixedFont = saveFixedFont;
+        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 
+    //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.
+    //drawn.
     if (_lineProperties.count() > y)
         updateLine |= (_lineProperties[y] & LINE_DOUBLEHEIGHT);
 
@@ -955,7 +1075,7 @@
         QRect dirtyRect = QRect( _leftMargin+tLx , 
                                  _topMargin+tLy+_fontHeight*y , 
                                  _fontWidth * columnsToUpdate , 
-                                 _fontHeight ); 	
+                                 _fontHeight );     
 
         dirtyRegion |= dirtyRect;
     }
@@ -990,7 +1110,7 @@
   // update the parts of the display which have changed
   update(dirtyRegion);
 
-  if ( _hasBlinker && !_blinkTimer->isActive()) _blinkTimer->start( BLINK_DELAY ); 
+  if ( _hasBlinker && !_blinkTimer->isActive()) _blinkTimer->start( TEXT_BLINK_DELAY ); 
   if (!_hasBlinker && _blinkTimer->isActive()) { _blinkTimer->stop(); _blinking = false; }
   delete[] dirtyMask;
   delete[] disstrU;
@@ -1002,25 +1122,23 @@
   if (_terminalSizeHint && isVisible())
   {
      if (_terminalSizeStartup) {
-       		_terminalSizeStartup=false;
+               _terminalSizeStartup=false;
        return;
      }
      if (!_resizeWidget)
      {
-        _resizeWidget = new QLabel(("Size: XXX x XXX"), this);
-        _resizeWidget->setMinimumWidth(_resizeWidget->fontMetrics().width(("Size: XXX x XXX")));
+        _resizeWidget = new QLabel(i18n("Size: XXX x XXX"), this);
+        _resizeWidget->setMinimumWidth(_resizeWidget->fontMetrics().width(i18n("Size: XXX x XXX")));
         _resizeWidget->setMinimumHeight(_resizeWidget->sizeHint().height());
-		_resizeWidget->setAlignment(Qt::AlignCenter);
+        _resizeWidget->setAlignment(Qt::AlignCenter);
 
         _resizeWidget->setStyleSheet("background-color:palette(window);border-style:solid;border-width:1px;border-color:palette(dark)");
 
-		_resizeTimer = new QTimer(this);
-		_resizeTimer->setSingleShot(true);
+        _resizeTimer = new QTimer(this);
+        _resizeTimer->setSingleShot(true);
         connect(_resizeTimer, SIGNAL(timeout()), _resizeWidget, SLOT(hide()));
-
      }
-     QString sizeStr;
-     sizeStr.sprintf("Size: %d x %d", _columns, _lines);
+     QString sizeStr = i18n("Size: %1 x %2", _columns, _lines);
      _resizeWidget->setText(sizeStr);
      _resizeWidget->move((width()-_resizeWidget->width())/2,
                          (height()-_resizeWidget->height())/2+20);
@@ -1034,7 +1152,7 @@
   _hasBlinkingCursor=blink;
   
   if (blink && !_blinkCursorTimer->isActive()) 
-      _blinkCursorTimer->start(BLINK_DELAY);
+      _blinkCursorTimer->start(QApplication::cursorFlashTime() / 2);
   
   if (!blink && _blinkCursorTimer->isActive()) 
   {
@@ -1046,30 +1164,66 @@
   }
 }
 
+void TerminalDisplay::setBlinkingTextEnabled(bool blink)
+{
+    _allowBlinkingText = blink;
+
+    if (blink && !_blinkTimer->isActive()) 
+        _blinkTimer->start(TEXT_BLINK_DELAY);
+  
+    if (!blink && _blinkTimer->isActive()) 
+    {
+        _blinkTimer->stop();
+        _blinking = false;
+    }
+}
+
+void TerminalDisplay::focusOutEvent(QFocusEvent*)
+{
+    // trigger a repaint of the cursor so that it is both visible (in case
+    // it was hidden during blinking)
+    // and drawn in a focused out state
+    _cursorBlinking = false;
+    updateCursor();
+
+    _blinkCursorTimer->stop();
+    if (_blinking)
+        blinkEvent();
+
+    _blinkTimer->stop();
+}
+void TerminalDisplay::focusInEvent(QFocusEvent*)
+{
+    if (_hasBlinkingCursor)
+    {
+        _blinkCursorTimer->start();
+    }
+    updateCursor();
+
+    if (_hasBlinker)
+        _blinkTimer->start();
+}
+
 void TerminalDisplay::paintEvent( QPaintEvent* pe )
 {
-//qDebug("%s %d paintEvent", __FILE__, __LINE__);
   QPainter paint(this);
 
-  foreach (QRect rect, (pe->region() & contentsRect()).rects())
+  foreach (const QRect &rect, (pe->region() & contentsRect()).rects())
   {
-    drawBackground(paint,rect,palette().background().color(),	true /* use opacity setting */);
-    drawContents(paint, rect);    
+    drawBackground(paint,rect,palette().background().color(),
+                    true /* use opacity setting */);
+    drawContents(paint, rect);
   }
-//    drawBackground(paint,contentsRect(),palette().background().color(),	true /* use opacity setting */);
-//    drawContents(paint, contentsRect());    
   drawInputMethodPreeditString(paint,preeditRect());
   paintFilters(paint);
-
-  paint.end();
 }
 
 QPoint TerminalDisplay::cursorPosition() const
 {
-	if (_screenWindow)
-		return _screenWindow->cursorPosition();
-	else
-		return QPoint(0,0);
+    if (_screenWindow)
+        return _screenWindow->cursorPosition();
+    else
+        return QPoint(0,0);
 }
 
 QRect TerminalDisplay::preeditRect() const
@@ -1087,9 +1241,9 @@
 
 void TerminalDisplay::drawInputMethodPreeditString(QPainter& painter , const QRect& rect)
 {
-    if ( _inputMethodData.preeditString.isEmpty() ) {
+    if ( _inputMethodData.preeditString.isEmpty() )
         return;
-    }
+
     const QPoint cursorPos = cursorPosition(); 
 
     bool invertColors = false;
@@ -1111,13 +1265,13 @@
 
 void TerminalDisplay::paintFilters(QPainter& painter)
 {
-//qDebug("%s %d paintFilters", __FILE__, __LINE__);
-
     // get color of character under mouse and use it to draw
     // lines for filters
     QPoint cursorPos = mapFromGlobal(QCursor::pos());
     int cursorLine;
     int cursorColumn;
+    int scrollBarWidth = (_scrollbarLocation == ScrollBarLeft) ? _scrollBar->width() : 0;
+
     getCharacterPosition( cursorPos , cursorLine , cursorColumn );
     Character cursorCharacter = _image[loc(cursorColumn,cursorLine)];
 
@@ -1132,6 +1286,36 @@
     {
         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, 
+                             spot->startLine()*_fontHeight + 1,
+                             (spot->endColumn()-1)*_fontWidth - 1 + scrollBarWidth, 
+                             (spot->endLine()+1)*_fontHeight - 1 ); 
+                region |= r;
+            } else {
+                r.setCoords( spot->startColumn()*_fontWidth + 1 + scrollBarWidth, 
+                             spot->startLine()*_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, 
+                                 line*_fontHeight + 1,
+                                 (_columns-1)*_fontWidth - 1 + scrollBarWidth,
+                                 (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 ); 
+                region |= r;
+            }
+        }
+
         for ( int line = spot->startLine() ; line <= spot->endLine() ; line++ )
         {
             int startColumn = 0;
@@ -1162,9 +1346,10 @@
             // 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, line*_fontHeight + 1,
-                             endColumn*_fontWidth - 1, (line+1)*_fontHeight - 1 ); 
-                                                                           
+            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 )
             {
@@ -1175,10 +1360,10 @@
                 int baseline = r.bottom() - metrics.descent();
                 // find the position of the underline below that
                 int underlinePos = baseline + metrics.underlinePos();
-
-                if ( r.contains( mapFromGlobal(QCursor::pos()) ) )
+                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
@@ -1192,23 +1377,18 @@
 }
 void TerminalDisplay::drawContents(QPainter &paint, const QRect &rect)
 {
-//qDebug("%s %d drawContents and rect x=%d y=%d w=%d h=%d", __FILE__, __LINE__, rect.x(), rect.y(),rect.width(),rect.height());
-
   QPoint tL  = contentsRect().topLeft();
-//  int    tLx = tL.x();
+  int    tLx = tL.x();
   int    tLy = tL.y();
 
-  int tLx = (_contentWidth - _usedColumns * _fontWidth)/2;
-//  int tLy = (_contentHeight - _usedLines * _fontHeight)/2; 
-//qDebug("%d %d %d %d", tLx, tLy, _contentWidth, _usedColumns * _fontWidth);  
-
   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 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;
-  QChar *disstrU = new QChar[bufferSize];
+  QString unistr;
+  unistr.reserve(bufferSize);
   for (int y = luy; y <= rly; y++)
   {
     quint16 c = _image[loc(lux,y)].character;
@@ -1220,6 +1400,10 @@
       int len = 1;
       int p = 0;
 
+      // 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 )
       {
@@ -1249,7 +1433,7 @@
       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 &&
@@ -1266,76 +1450,75 @@
       if ((x+len < _usedColumns) && (!_image[loc(x+len,y)].character))
         len++; // Adjust for trailing part of multi-column character
 
-   	     bool save__fixedFont = _fixedFont;
+            bool save__fixedFont = _fixedFont;
          if (lineDraw)
             _fixedFont = false;
          if (doubleWidth)
             _fixedFont = false;
-         QString unistr(disstrU,p);
-		 
-		 if (y < _lineProperties.size())
-		 {
-			if (_lineProperties[y] & LINE_DOUBLEWIDTH) {
-				paint.scale(2,1);
-			}
-			
-			if (_lineProperties[y] & LINE_DOUBLEHEIGHT) {
-  		 		paint.scale(1,2);
-			}
-		 }
-
-		 //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 
+         unistr.resize(p);
+
+         // Create a text scaling matrix for double width and double height lines.
+         QMatrix textScale;
+
+         if (y < _lineProperties.size())
+         {
+            if (_lineProperties[y] & LINE_DOUBLEWIDTH)
+                textScale.scale(2,1);
+
+            if (_lineProperties[y] & LINE_DOUBLEHEIGHT)
+                textScale.scale(1,2);
+         }
+
+         //Apply text scaling matrix.
+         paint.setWorldMatrix(textScale, true);
+
+         //calculate the area in which the text will be drawn
+         QRect textArea = QRect( _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)	
-		 QMatrix inverted = paint.matrix().inverted();
-//		 textArea.moveTopLeft( inverted.map(textArea.topLeft()) );
-		 textArea.moveCenter( inverted.map(textArea.center()) );
-
-		 
-		 //paint text fragment
-         drawTextFragment(	paint,
-                		    textArea,
-                		    unistr, 
-					    	&_image[loc(x,y)] ); //, 
-						    //0, 
-						    //!_isPrinting );
+         //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()) );
          
-		 _fixedFont = save__fixedFont;
+         //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.resetMatrix();
-
-		 if (y < _lineProperties.size()-1)
-		 {
-			//double-height _lines are represented by two adjacent _lines 
+         //reset back to single-width, single-height _lines 
+         paint.setWorldMatrix(textScale.inverted(), true);
+
+         if (y < _lineProperties.size()-1)
+         {
+            //double-height _lines are represented by two adjacent _lines 
             //containing the same characters
-			//both _lines will have the LINE_DOUBLEHEIGHT attribute.  
+            //both _lines will have the LINE_DOUBLEHEIGHT attribute.  
             //If the current line has the LINE_DOUBLEHEIGHT attribute, 
             //we can therefore skip the next line
-			if (_lineProperties[y] & LINE_DOUBLEHEIGHT)
-				y++;
-		 }
-		 
-	    x += len - 1;
+            if (_lineProperties[y] & LINE_DOUBLEHEIGHT)
+                y++;
+         }
+         
+        x += len - 1;
     }
   }
-  delete [] disstrU;
 }
 
 void TerminalDisplay::blinkEvent()
 {
+  if (!_allowBlinkingText) return;
+
   _blinking = !_blinking;
 
-  //TODO:  Optimise to only repaint the areas of the widget 
+  //TODO:  Optimize to only repaint the areas of the widget 
   // where there is blinking text
   // rather than repainting the whole widget.
   update();
@@ -1343,7 +1526,6 @@
 
 QRect TerminalDisplay::imageToWidget(const QRect& imageArea) const
 {
-//qDebug("%s %d imageToWidget", __FILE__, __LINE__);
     QRect result;
     result.setLeft( _leftMargin + _fontWidth * imageArea.left() );
     result.setTop( _topMargin + _fontHeight * imageArea.top() );
@@ -1353,13 +1535,16 @@
     return result;
 }
 
+void TerminalDisplay::updateCursor()
+{
+  QRect cursorRect = imageToWidget( QRect(cursorPosition(),QSize(1,1)) ); 
+  update(cursorRect);
+}
+
 void TerminalDisplay::blinkCursorEvent()
 {
   _cursorBlinking = !_cursorBlinking;
-
-  QRect cursorRect = imageToWidget( QRect(cursorPosition(),QSize(1,1)) ); 
-
-  update(cursorRect);
+  updateCursor();
 }
 
 /* ------------------------------------------------------------------------- */
@@ -1371,7 +1556,6 @@
 void TerminalDisplay::resizeEvent(QResizeEvent*)
 {
   updateImageSize();
-  updateImage();
 }
 
 void TerminalDisplay::propagateSize()
@@ -1390,13 +1574,11 @@
 
 void TerminalDisplay::updateImageSize()
 {
-//qDebug("%s %d updateImageSize", __FILE__, __LINE__);
   Character* oldimg = _image;
   int oldlin = _lines;
   int oldcol = _columns;
 
   makeImage();
-
   
   // copy the old image to reduce flicker
   int lines = qMin(oldlin,_lines);
@@ -1413,13 +1595,13 @@
   }
 
   if (_screenWindow)
-  	_screenWindow->setWindowLines(_lines);
+      _screenWindow->setWindowLines(_lines);
 
   _resizing = (oldlin!=_lines) || (oldcol!=_columns);
 
   if ( _resizing )
   {
-  	showResizeNotification();
+      showResizeNotification();
     emit changedContentSizeSignal(_contentHeight, _contentWidth); // expose resizeEvent
   }
   
@@ -1429,7 +1611,6 @@
 //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.
 //
-//this allows  
 //TODO: Perhaps it would be better to have separate signals for show and hide instead of using
 //the same signal as the one for a content size change 
 void TerminalDisplay::showEvent(QShowEvent*)
@@ -1466,7 +1647,6 @@
 
 void TerminalDisplay::setScroll(int cursor, int slines)
 {
-//qDebug("%s %d setScroll", __FILE__, __LINE__);
   // update _scrollBar if the range or value has changed,
   // otherwise return
   //
@@ -1489,9 +1669,8 @@
 
 void TerminalDisplay::setScrollBarPosition(ScrollBarPosition position)
 {
-  if (_scrollbarLocation == position) {
-//      return; 
-  }
+  if (_scrollbarLocation == position) 
+      return; 
  
   if ( position == NoScrollBar )
      _scrollBar->hide();
@@ -1574,14 +1753,9 @@
   else if ( ev->button() == Qt::RightButton )
   {
     if (_mouseMarks || (ev->modifiers() & Qt::ShiftModifier)) 
-    {
-        emit configureRequest( this, 
-                               ev->modifiers() & (Qt::ShiftModifier|Qt::ControlModifier), 
-                               ev->pos()
-                             );
-    }
+        emit configureRequest(ev->pos());
     else
-      emit mouseSignal( 2, charColumn +1, charLine +1 +_scrollBar->value() -_scrollBar->maximum() , 0);
+        emit mouseSignal( 2, charColumn +1, charLine +1 +_scrollBar->value() -_scrollBar->maximum() , 0);
   }
 }
 
@@ -1599,6 +1773,7 @@
 {
   int charLine = 0;
   int charColumn = 0;
+  int scrollBarWidth = (_scrollbarLocation == ScrollBarLeft) ? _scrollBar->width() : 0;
 
   getCharacterPosition(ev->pos(),charLine,charColumn); 
 
@@ -1607,27 +1782,49 @@
   Filter::HotSpot* spot = _filterChain->hotSpotAt(charLine,charColumn);
   if ( spot && spot->type() == Filter::HotSpot::Link)
   {
-    QRect previousHotspotArea = _mouseOverHotspotArea;
-    _mouseOverHotspotArea.setCoords( qMin(spot->startColumn() , spot->endColumn()) * _fontWidth,
-                                     spot->startLine() * _fontHeight,
-                                     qMax(spot->startColumn() , spot->endColumn()) * _fontHeight,
-                                     (spot->endLine()+1) * _fontHeight );
-
+    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 ); 
+        _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 );
+        QToolTip::showText( mapToGlobal(ev->pos()) , tooltip , this , _mouseOverHotspotArea.boundingRect() );
     }
 
     update( _mouseOverHotspotArea | previousHotspotArea );
   }
-  else if ( _mouseOverHotspotArea.isValid() )
+  else if ( !_mouseOverHotspotArea.isEmpty() )
   {
         update( _mouseOverHotspotArea );
         // set hotspot area to an invalid rectangle
-        _mouseOverHotspotArea = QRect();
+        _mouseOverHotspotArea = QRegion();
   }
   
   // for auto-hiding the cursor, we need mouseTracking
@@ -1638,21 +1835,21 @@
   // 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;
+    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 );
+             1 );
       
-	return;
+    return;
   }
       
   if (dragInfo.state == diPending) 
@@ -1687,13 +1884,6 @@
   extendSelection( ev->pos() );
 }
 
-#if 0
-void TerminalDisplay::setSelectionEnd()
-{
-  extendSelection( _configureRequestPoint );
-}
-#endif
-
 void TerminalDisplay::extendSelection( const QPoint& position )
 {
   QPoint pos = position;
@@ -1711,24 +1901,28 @@
   // the mouse cursor will kept caught within the bounds of the text in
   // this widget.
 
-  // Adjust position within text area bounds. See FIXME above.
+  int linesBeyondWidget = 0;
+
+  QRect textBounds(tLx + _leftMargin,
+                     tLy + _topMargin,
+                   _usedColumns*_fontWidth-1,
+                   _usedLines*_fontHeight-1);
+
+  // Adjust position within text area bounds.
   QPoint oldpos = pos;
-  if ( pos.x() < tLx+_leftMargin )                  
-      pos.setX( tLx+_leftMargin );
-  if ( pos.x() > tLx+_leftMargin+_usedColumns*_fontWidth-1 ) 
-      pos.setX( tLx+_leftMargin+_usedColumns*_fontWidth );
-  if ( pos.y() < tLy+_topMargin )                   
-      pos.setY( tLy+_topMargin );
-  if ( pos.y() > tLy+_topMargin+_usedLines*_fontHeight-1 )    
-      pos.setY( tLy+_topMargin+_usedLines*_fontHeight-1 );
-
-  if ( pos.y() == tLy+_topMargin+_usedLines*_fontHeight-1 )
+ 
+  pos.setX( qBound(textBounds.left(),pos.x(),textBounds.right()) );
+  pos.setY( qBound(textBounds.top(),pos.y(),textBounds.bottom()) );
+
+  if ( oldpos.y() > textBounds.bottom() ) 
   {
-    _scrollBar->setValue(_scrollBar->value()+yMouseScroll); // scrollforward
+      linesBeyondWidget = (oldpos.y()-textBounds.bottom()) / _fontHeight;
+    _scrollBar->setValue(_scrollBar->value()+linesBeyondWidget+1); // scrollforward
   }
-  if ( pos.y() == tLy+_topMargin )
+  if ( oldpos.y() < textBounds.top() )
   {
-    _scrollBar->setValue(_scrollBar->value()-yMouseScroll); // scrollback
+      linesBeyondWidget = (textBounds.top()-oldpos.y()) / _fontHeight;
+    _scrollBar->setValue(_scrollBar->value()-linesBeyondWidget-1); // history
   }
 
   int charColumn = 0;
@@ -1747,12 +1941,12 @@
   {
     // Extend to word boundaries
     int i;
-    int selClass;
+    QChar selClass;
 
     bool left_not_right = ( here.y() < _iPntSelCorr.y() ||
-	   here.y() == _iPntSelCorr.y() && here.x() < _iPntSelCorr.x() );
+       ( 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() );
+       ( _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)
@@ -1761,7 +1955,7 @@
     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 )
+                      && charClass(_image[i-1].character) == selClass )
       { i--; if (left.x()>0) left.rx()--; else {left.rx()=_usedColumns-1; left.ry()--;} }
     }
 
@@ -1771,7 +1965,7 @@
     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 )
+                      && charClass(_image[i+1].character) == selClass )
       { i++; if (right.x()<_usedColumns-1) right.rx()++; else {right.rx()=0; right.ry()++; } }
     }
 
@@ -1824,12 +2018,12 @@
   if ( !_wordSelectionMode && !_lineSelectionMode )
   {
     int i;
-    int selClass;
+    QChar selClass;
 
     bool left_not_right = ( here.y() < _iPntSelCorr.y() ||
-	   here.y() == _iPntSelCorr.y() && here.x() < _iPntSelCorr.x() );
+       ( 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() );
+       ( _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)
@@ -1842,16 +2036,16 @@
       i = loc(right.x(),right.y());
       if (i>=0 && i<=_imageSize) {
         selClass = charClass(_image[i-1].character);
-        if (selClass == ' ')
+       /* if (selClass == ' ')
         {
           while ( right.x() < _usedColumns-1 && charClass(_image[i+1].character) == selClass && (right.y()<_usedLines-1) && 
-						  !(_lineProperties[right.y()] & LINE_WRAPPED))
+                          !(_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;
-        }
+        }*/
       }
     }
 
@@ -1951,7 +2145,6 @@
 
 void TerminalDisplay::getCharacterPosition(const QPoint& widgetPoint,int& line,int& column) const
 {
-
     column = (widgetPoint.x() + _fontWidth/2 -contentsRect().left()-_leftMargin) / _fontWidth;
     line = (widgetPoint.y()-contentsRect().top()-_topMargin) / _fontHeight;
 
@@ -2014,12 +2207,12 @@
   _wordSelectionMode = true;
 
   // find word boundaries...
-  int selClass = charClass(_image[i].character);
+  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 )
+                     && charClass(_image[i-1].character) == selClass )
      {  
        i--; 
        if (x>0) 
@@ -2038,7 +2231,7 @@
      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 )
+                     && charClass(_image[i+1].character) == selClass )
      { 
          i++; 
          if (x<_usedColumns-1) 
@@ -2075,10 +2268,39 @@
   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 )
-    _scrollBar->event(ev);
+  {
+    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;
+
+        QKeyEvent keyScrollEvent(QEvent::KeyPress,key,Qt::NoModifier);
+
+        for (int i=0;i<linesToScroll;i++)
+            emit keyPressedSignal(&keyScrollEvent);
+    }
+  }
   else
   {
+    // terminal program wants notification of mouse activity
+    
     int charLine;
     int charColumn;
     getCharacterPosition( ev->pos() , charLine , charColumn );
@@ -2118,7 +2340,7 @@
   if (_tripleClickMode == SelectForwardsFromCursor) {
     // find word boundary start
     int i = loc(_iPntSel.x(),_iPntSel.y());
-    int selClass = charClass(_image[i].character);
+    QChar selClass = charClass(_image[i].character);
     int x = _iPntSel.x();
     
     while ( ((x>0) || 
@@ -2164,21 +2386,19 @@
 }
 
 
-int TerminalDisplay::charClass(quint16 ch) const
+QChar TerminalDisplay::charClass(QChar qch) const
 {
-    QChar qch=QChar(ch);
     if ( qch.isSpace() ) return ' ';
 
     if ( qch.isLetterOrNumber() || _wordCharacters.contains(qch, Qt::CaseInsensitive ) )
     return 'a';
 
-    // Everything else is weird
-    return 1;
+    return qch;
 }
 
 void TerminalDisplay::setWordCharacters(const QString& wc)
 {
-	_wordCharacters = wc;
+    _wordCharacters = wc;
 }
 
 void TerminalDisplay::setUsesMouse(bool on)
@@ -2211,7 +2431,7 @@
     text.append("\r");
   if ( ! text.isEmpty() )
   {
-    text.replace("\n", "\r");
+    text.replace('\n', '\r');
     QKeyEvent e(QEvent::KeyPress, 0, Qt::NoModifier, text);
     emit keyPressedSignal(&e); // expose as a big fat keypress event
     
@@ -2230,7 +2450,8 @@
       return;
 
   QString text = _screenWindow->selectedText(_preserveLineBreaks);
-  QApplication::clipboard()->setText(text);
+  if (!text.isEmpty())
+    QApplication::clipboard()->setText(text);
 }
 
 void TerminalDisplay::pasteClipboard()
@@ -2251,33 +2472,18 @@
 
 void TerminalDisplay::setFlowControlWarningEnabled( bool enable )
 {
-	_flowControlWarningEnabled = enable;
-	
-	// if the dialog is currently visible and the flow control warning has 
-	// been disabled then hide the dialog
-	if (!enable)
-		outputSuspended(false);
+    _flowControlWarningEnabled = enable;
+    
+    // if the dialog is currently visible and the flow control warning has 
+    // been disabled then hide the dialog
+    if (!enable)
+        outputSuspended(false);
 }
 
 void TerminalDisplay::keyPressEvent( QKeyEvent* event )
 {
-//qDebug("%s %d keyPressEvent and key is %d", __FILE__, __LINE__, event->key());
-
     bool emitKeyPressSignal = true;
 
-    // XonXoff flow control
-    if (event->modifiers() & Qt::ControlModifier && _flowControlWarningEnabled)
-	{
-		if ( event->key() == Qt::Key_S ) {
-		//qDebug("%s %d keyPressEvent, output suspended", __FILE__, __LINE__);
-				emit flowControlKeyPressed(true /*output suspended*/);
-		}
-		else if ( event->key() == Qt::Key_Q ) {
-		//qDebug("%s %d keyPressEvent, output enabled", __FILE__, __LINE__);
-				emit flowControlKeyPressed(false /*output enabled*/);
-		}
-	}
-
     // Keyboard-based navigation
     if ( event->modifiers() == Qt::ShiftModifier )
     {
@@ -2285,31 +2491,25 @@
 
         if ( event->key() == Qt::Key_PageUp )
         {
-	    //qDebug("%s %d pageup", __FILE__, __LINE__);
             _screenWindow->scrollBy( ScreenWindow::ScrollPages , -1 );
         }
         else if ( event->key() == Qt::Key_PageDown )
         {
-	    //qDebug("%s %d pagedown", __FILE__, __LINE__);
             _screenWindow->scrollBy( ScreenWindow::ScrollPages , 1 );
         }
         else if ( event->key() == Qt::Key_Up )
         {
-	    //qDebug("%s %d keyup", __FILE__, __LINE__);	
             _screenWindow->scrollBy( ScreenWindow::ScrollLines , -1 );
         }
         else if ( event->key() == Qt::Key_Down )
         {
-	    //qDebug("%s %d keydown", __FILE__, __LINE__);	
             _screenWindow->scrollBy( ScreenWindow::ScrollLines , 1 );
         }
-        else {
+        else
             update = false;
-	}
 
         if ( update )
         {
-	    //qDebug("%s %d updating", __FILE__, __LINE__);	
             _screenWindow->setTrackOutput( _screenWindow->atEndOfOutput() );
             
             updateLineProperties();
@@ -2319,15 +2519,13 @@
             emitKeyPressSignal = false;
         }
     }
-    
-    _screenWindow->setTrackOutput( true );
-    
+
     _actSel=0; // Key stroke implies a screen update, so TerminalDisplay won't
               // know where the current selection is.
 
     if (_hasBlinkingCursor) 
     {
-      _blinkCursorTimer->start(BLINK_DELAY);
+      _blinkCursorTimer->start(QApplication::cursorFlashTime() / 2);
       if (_cursorBlinking)
         blinkCursorEvent();
       else
@@ -2380,33 +2578,46 @@
         case Qt::ImCurrentSelection:
                 return QString();
             break;
+        default:
+            break;
     }
 
     return QVariant();
 }
 
-bool TerminalDisplay::event( QEvent *e )
+bool TerminalDisplay::handleShortcutOverrideEvent(QKeyEvent* keyEvent)
 {
-  if ( e->type() == QEvent::ShortcutOverride )
-  {
-    QKeyEvent* keyEvent = static_cast<QKeyEvent *>( e );
-
-    // a check to see if keyEvent->text() is empty is used
-    // to avoid intercepting the press of the modifier key on its own.
-    //
-    // this is important as it allows a press and release of the Alt key
-    // on its own to focus the menu bar, making it possible to
-    // work with the menu without using the mouse
-    if ( (keyEvent->modifiers() == Qt::AltModifier) && 
-         !keyEvent->text().isEmpty() )
+    int modifiers = keyEvent->modifiers();
+
+    //  When a possible shortcut combination is pressed, 
+    //  emit the overrideShortcutCheck() signal to allow the host
+    //  to decide whether the terminal should override it or not.
+    if (modifiers != Qt::NoModifier) 
     {
-    	keyEvent->accept();
-      	return true;
+        int modifierCount = 0;
+        unsigned int currentModifier = Qt::ShiftModifier;
+
+        while (currentModifier <= Qt::KeypadModifier)
+        {
+            if (modifiers & currentModifier)
+                modifierCount++;
+            currentModifier <<= 1;
+        }
+        if (modifierCount < 2) 
+        {
+            bool override = false;
+            emit overrideShortcutCheck(keyEvent,override);
+            if (override)
+            {
+                keyEvent->accept();
+                return true;
+            }
+        }
     }
 
     // Override any of the following shortcuts because
     // they are needed by the terminal
-    int keyCode = keyEvent->key() | keyEvent->modifiers();
+    int keyCode = keyEvent->key() | modifiers;
     switch ( keyCode )
     {
       // list is taken from the QLineEdit::event() code
@@ -2420,8 +2631,25 @@
         keyEvent->accept();
         return true;
     }
+    return false;
+}
+
+bool TerminalDisplay::event(QEvent* event)
+{
+  bool eventHandled = false;
+  switch (event->type())
+  {
+    case QEvent::ShortcutOverride:
+        eventHandled = handleShortcutOverrideEvent((QKeyEvent*)event);
+        break;
+    case QEvent::PaletteChange:
+    case QEvent::ApplicationPaletteChange:
+        _scrollBar->setPalette( QApplication::palette() );
+        break;
+    default:
+        break;
   }
-  return QWidget::event( e );
+  return eventHandled ? true : QWidget::event(event); 
 }
 
 void TerminalDisplay::setBellMode(int mode)
@@ -2434,7 +2662,7 @@
     _allowBell = true;
 }
 
-void TerminalDisplay::bell(const QString&)
+void TerminalDisplay::bell(const QString& message)
 {
   if (_bellMode==NoBell) return;
 
@@ -2448,11 +2676,13 @@
  
     if (_bellMode==SystemBeepBell) 
     {
-//        KNotification::beep();
+      // TODO: This will need added back in at some point
+      //KNotification::beep();
     } 
     else if (_bellMode==NotifyBell) 
     {
-//        KNotification::event("BellVisible", message,QPixmap(),this);
+      // TODO: This will need added back in at some point
+      //KNotification::event("BellVisible", message,QPixmap(),this);
     } 
     else if (_bellMode==VisualBell) 
     {
@@ -2487,8 +2717,7 @@
 
 void TerminalDisplay::calcGeometry()
 {
-  _scrollBar->resize(QApplication::style()->pixelMetric(QStyle::PM_ScrollBarExtent),
-                    contentsRect().height());
+  _scrollBar->resize(_scrollBar->sizeHint().width(), contentsRect().height());
   switch(_scrollbarLocation)
   {
     case NoScrollBar :
@@ -2509,7 +2738,7 @@
 
   _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
@@ -2524,7 +2753,6 @@
 
 void TerminalDisplay::makeImage()
 {
-//qDebug("%s %d makeImage", __FILE__, __LINE__);
   calcGeometry();
 
   // confirm that array will be of non-zero size, since the painting code 
@@ -2541,16 +2769,15 @@
   clearImage();
 }
 
-// calculate the needed size
+// calculate the needed size, this must be synced with calcGeometry()
 void TerminalDisplay::setSize(int columns, int lines)
 {
-  //FIXME - Not quite correct, a small amount of additional space
-  // will be used for margins, the scrollbar etc.
-  // we need to allow for this so that '_size' does allow
-  // enough room for the specified number of columns and lines to fit
-
-  QSize newSize = QSize( columns * _fontWidth  ,
-				 lines * _fontHeight   );
+  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)   );
 
   if ( newSize != size() )
   {
@@ -2598,10 +2825,11 @@
 
 void TerminalDisplay::dropEvent(QDropEvent* event)
 {
-//  KUrl::List urls = KUrl::List::fromMimeData(event->mimeData());
+  //KUrl::List urls = KUrl::List::fromMimeData(event->mimeData());
 
   QString dropText;
-/*  if (!urls.isEmpty()) 
+  /*
+  if (!urls.isEmpty()) 
   {
     for ( int i = 0 ; i < urls.count() ; i++ ) 
     {
@@ -2627,7 +2855,8 @@
   {
     dropText = event->mimeData()->text();
   }
-*/
+  */
+
   if(event->mimeData()->hasFormat("text/plain")) 
   {
     emit sendStringToEmu(dropText.toLocal8Bit());
@@ -2647,31 +2876,27 @@
 
 void TerminalDisplay::outputSuspended(bool suspended)
 {
-	//create the label when this function is first called
-	if (!_outputSuspendedLabel)
-	{
+    //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( ("<qt>Output has been "
-                                                "<a href=\"http://en.wikipedia.org/wiki/XON\">suspended</a>"
+            _outputSuspendedLabel = new QLabel( i18n("<qt>Output has been "
+                                                "<a href=\"http://en.wikipedia.org/wiki/Flow_control\">suspended</a>"
                                                 " by pressing Ctrl+S."
-											   "  Press <b>Ctrl+Q</b> to resume.</qt>"),
-											   this );
+                                               "  Press <b>Ctrl+Q</b> to resume.</qt>"),
+                                               this );
 
             QPalette palette(_outputSuspendedLabel->palette());
-	    
-	    palette.setColor(QPalette::Normal, QPalette::WindowText, QColor(Qt::white));
-	    palette.setColor(QPalette::Normal, QPalette::Window, QColor(Qt::black));
-//            KColorScheme::adjustForeground(palette,KColorScheme::NeutralText);
-//		KColorScheme::adjustBackground(palette,KColorScheme::NeutralBackground);
-    	    _outputSuspendedLabel->setPalette(palette);
-	    _outputSuspendedLabel->setAutoFillBackground(true);
-	    _outputSuspendedLabel->setBackgroundRole(QPalette::Base);
-	    _outputSuspendedLabel->setFont(QApplication::font());
-            _outputSuspendedLabel->setMargin(5);
+            //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 | 
@@ -2686,7 +2911,7 @@
 
     }
 
-	_outputSuspendedLabel->setVisible(suspended);
+    _outputSuspendedLabel->setVisible(suspended);
 }
 
 uint TerminalDisplay::lineSpacing() const
@@ -2700,4 +2925,60 @@
   setVTFont(font()); // Trigger an update.
 }
 
-//#include "moc_TerminalDisplay.cpp"
+AutoScrollHandler::AutoScrollHandler(QWidget* parent)
+: QObject(parent)
+, _timerId(0)
+{
+    parent->installEventFilter(this);
+}
+void AutoScrollHandler::timerEvent(QTimerEvent* event)
+{
+    if (event->timerId() != _timerId)
+        return;
+
+    QMouseEvent mouseEvent(    QEvent::MouseMove,
+                              widget()->mapFromGlobal(QCursor::pos()),
+                              Qt::NoButton,
+                              Qt::LeftButton,
+                              Qt::NoModifier);
+
+    QApplication::sendEvent(widget(),&mouseEvent);    
+}
+bool AutoScrollHandler::eventFilter(QObject* watched,QEvent* event)
+{
+    Q_ASSERT( watched == parent() );
+    Q_UNUSED( watched );
+
+    QMouseEvent* mouseEvent = (QMouseEvent*)event;
+    switch (event->type())
+    {
+        case QEvent::MouseMove:
+        {
+            bool mouseInWidget = widget()->rect().contains(mouseEvent->pos());
+
+            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;
+            }
+        break;
+        default:
+        break;
+    };
+
+    return false;
+}
--- a/gui//src/TerminalDisplay.h	Fri Apr 08 15:23:21 2011 +0200
+++ b/gui//src/TerminalDisplay.h	Sat Apr 09 00:23:46 2011 +0200
@@ -1,8 +1,6 @@
 /*
-    Copyright (C) 2007 by Robert Knight <robertknight@gmail.com>
-    Copyright (C) 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
-
-    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+    Copyright 2007-2008 by Robert Knight <robertknight@gmail.com>
+    Copyright 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
 
     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
@@ -31,7 +29,7 @@
 // Konsole
 #include "Filter.h"
 #include "Character.h"
-#include "ColorTables.h"
+#include "konsole_export.h"
 
 class QDrag;
 class QDragEnterEvent;
@@ -39,14 +37,16 @@
 class QLabel;
 class QTimer;
 class QEvent;
-class QFrame;
 class QGridLayout;
 class QKeyEvent;
 class QScrollBar;
 class QShowEvent;
 class QHideEvent;
+class QTimerEvent;
 class QWidget;
 
+class KMenu;
+
 extern unsigned short vt100_graphics[32];
 
 class ScreenWindow;
@@ -60,7 +60,7 @@
  *
  * TODO More documentation
  */
-class TerminalDisplay : public QWidget
+class KONSOLEPRIVATE_EXPORT TerminalDisplay : public QWidget
 {
    Q_OBJECT
 
@@ -153,23 +153,26 @@
     /** 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; }
 
-	/** 
+    /** 
      *  This enum describes the methods for selecting text when
- 	 *  the user triple-clicks within the display. 
- 	 */
-	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. */	
+      *  the user triple-clicks within the display. 
+      */
+    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; }
-	/** See setTripleClickSelectionMode() */
+    /** See setTripleClickSelectionMode() */
     TripleClickMode tripleClickMode() { return _tripleClickMode; }
 
     void setLineSpacing(uint);
@@ -348,6 +351,16 @@
      * Returns true if anti-aliasing of text in the terminal is enabled.
      */
     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; }
+    /**
+     * Returns true if characters with intense colors are rendered in bold.
+     */
+    bool getBoldIntense() { return _boldIntense; }
     
     /**
      * Sets whether or not the current height and width of the 
@@ -369,7 +382,14 @@
      */
     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; }
+    /**
+     * Returns the status of the BiDi rendering in this widget.
+     */
     bool isBidiEnabled() { return _bidiEnabled; }
 
     /**
@@ -412,21 +432,27 @@
      */
     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);
-	
+    /** 
+       * Changes whether the flow control warning box should be shown when the flow control
+       * stop key (Ctrl+S) are pressed.
+       */
+    void setFlowControlWarningEnabled(bool enabled);
     /** 
-	 * 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);
+     * Returns true if the flow control warning box is enabled. 
+     * See outputSuspended() and setFlowControlWarningEnabled()
+     */
+    bool flowControlWarningEnabled() const
+    { return _flowControlWarningEnabled; }
+
+    /** 
+     * Causes the widget to display or hide a message informing the user that terminal
+     * output has been suspended (by using the flow control key combination Ctrl+S)
+     *
+     * @param suspended True if terminal output has been suspended and the warning message should
+     *                     be shown or false to indicate that terminal output has been resumed and that
+     *                     the warning message should disappear.
+     */ 
+    void outputSuspended(bool suspended);
 
     /**
      * Sets whether the program whoose output is being displayed in the view
@@ -453,6 +479,18 @@
      */
     void bell(const QString& message);
 
+    /** 
+     * 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. 
+     * @see setColorTable(), setBackgroundColor()
+     */
+    void setForegroundColor(const QColor& color);
+
 signals:
 
     /**
@@ -460,14 +498,6 @@
      */
     void keyPressedSignal(QKeyEvent *e);
 
-    /**
-     * Emitted when the user presses the suspend or resume flow control key combinations 
-     * 
-     * @param suspend true if the user pressed Ctrl+S (the suspend output key combination) or
-     * false if the user pressed Ctrl+Q (the resume output key combination)
-     */
-    void flowControlKeyPressed(bool suspend);
-    
     /** 
      * A mouse event occurred.
      * @param button The mouse button (0 for left button, 1 for middle button, 2 for right button, 3 for release)
@@ -485,7 +515,18 @@
      *
      * This can be used to display a context menu.
      */
-    void configureRequest( TerminalDisplay*, int state, const QPoint& position );
+    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 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.
+     *
+     * @p override is set to false by default and the shortcut will be triggered as normal.
+     */
+    void overrideShortcutCheck(QKeyEvent* keyEvent,bool& override);
 
    void isBusySelecting(bool);
    void sendStringToEmu(const char*);
@@ -500,7 +541,8 @@
     virtual void resizeEvent(QResizeEvent*);
 
     virtual void fontChange(const QFont &font);
-
+    virtual void focusInEvent(QFocusEvent* event);
+    virtual void focusOutEvent(QFocusEvent* event);
     virtual void keyPressEvent(QKeyEvent* event);
     virtual void mouseDoubleClickEvent(QMouseEvent* ev);
     virtual void mousePressEvent( QMouseEvent* );
@@ -523,7 +565,13 @@
       QDrag           *dragObject;
     } dragInfo;
 
-    virtual int charClass(quint16) const;
+    // classifies the 'ch' into one of three categories
+    // and returns a character to indicate which category it is in
+    //
+    //     - A space (returns ' ') 
+    //     - Part of a word (returns 'a')
+    //     - Other characters (returns the input character)
+    QChar charClass(QChar ch) const;
 
     void clearImage();
 
@@ -565,7 +613,7 @@
     // the display's transparency (set with setOpacity()), otherwise the background
     // will be drawn fully opaque
     void drawBackground(QPainter& painter, const QRect& rect, const QColor& color,
-						bool useOpacitySetting);
+                        bool useOpacitySetting);
     // draws the cursor character
     void drawCursor(QPainter& painter, const QRect& rect , const QColor& foregroundColor, 
                                        const QColor& backgroundColor , bool& invertColors);
@@ -573,7 +621,7 @@
     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
@@ -610,12 +658,17 @@
     
     void paintFilters(QPainter& painter);
 
-	// returns a region covering all of the areas of the widget which contain
-	// a hotspot
-	QRegion hotSpotRegion() const;
+    // returns a region covering all of the areas of the widget which contain
+    // a hotspot
+    QRegion hotSpotRegion() const;
 
-	// returns the position of the cursor in columns and lines
-	QPoint cursorPosition() const;
+    // returns the position of the cursor in columns and lines
+    QPoint cursorPosition() const;
+
+    // redraws the cursor
+    void updateCursor();
+
+    bool handleShortcutOverrideEvent(QKeyEvent* event);
 
     // the window onto the terminal screen which this display
     // is currently showing.  
@@ -629,6 +682,7 @@
     int  _fontHeight;     // height
     int  _fontWidth;     // width
     int  _fontAscent;     // ascend
+    bool _boldIntense;   // Whether intense colors should be rendered with bold font
 
     int _leftMargin;    // offset
     int _topMargin;    // offset
@@ -680,13 +734,14 @@
     bool _hasBlinker; // has characters to blink
     bool _cursorBlinking;     // hide cursor in paintEvent
     bool _hasBlinkingCursor;  // has blinking cursor enabled
+    bool _allowBlinkingText;  // allow text to blink
     bool _ctrlDrag;           // require Ctrl key for drag
     TripleClickMode _tripleClickMode;
     bool _isFixedSize; //Columns / lines are locked.
     QTimer* _blinkTimer;  // active when hasBlinker
     QTimer* _blinkCursorTimer;  // active when hasBlinkingCursor
 
-//    KMenu* _drop;
+    KMenu* _drop;
     QString _dropText;
     int _dndFileCount;
 
@@ -697,24 +752,24 @@
     QLabel* _resizeWidget;
     QTimer* _resizeTimer;
 
-	bool _flowControlWarningEnabled;
+    bool _flowControlWarningEnabled;
 
     //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; 
-    	
+        
     uint _lineSpacing;
 
     bool _colorsInverted; // true during visual bell
 
     QSize _size;
-	
+    
     QRgb _blendColor;
 
     // list of filters currently applied to the display.  used for links and
     // search highlight
     TerminalImageFilterChain* _filterChain;
-    QRect _mouseOverHotspotArea;
+    QRegion _mouseOverHotspotArea;
 
     KeyboardCursorShape _cursorShape;
 
@@ -733,9 +788,9 @@
     static bool _antialiasText;   // do we antialias or not
 
     //the delay in milliseconds between redrawing blinking text
-    static const int BLINK_DELAY = 500;
-	static const int DEFAULT_LEFT_MARGIN = 1;
-	static const int DEFAULT_TOP_MARGIN = 1;
+    static const int TEXT_BLINK_DELAY = 500;
+    static const int DEFAULT_LEFT_MARGIN = 1;
+    static const int DEFAULT_TOP_MARGIN = 1;
 
 public:
     static void setTransparencyEnabled(bool enable)
@@ -743,4 +798,20 @@
         HAVE_TRANSPARENCY = enable;
     }
 };
+
+class AutoScrollHandler : public QObject
+{
+Q_OBJECT
+
+public:
+    AutoScrollHandler(QWidget* parent);
+protected:
+    virtual void timerEvent(QTimerEvent* event);
+    virtual bool eventFilter(QObject* watched,QEvent* event);
+private:
+    QWidget* widget() const { return static_cast<QWidget*>(parent()); }
+    int _timerId;
+};
+
+
 #endif // TERMINALDISPLAY_H
--- a/gui//src/TerminalMdiSubWindow.cpp	Fri Apr 08 15:23:21 2011 +0200
+++ b/gui//src/TerminalMdiSubWindow.cpp	Sat Apr 09 00:23:46 2011 +0200
@@ -2,13 +2,64 @@
 #include <QHBoxLayout>
 #include <QVBoxLayout>
 
+bool is_inside_main_loop = false;
+bool is_cleanup_complete = false;
+
+extern bool quit_allowed;
+bool threadRunning = true;
+void * octave_main_wrapper(void *ptr)
+{
+  //MainWindow *mainWindow = (MainWindow*)ptr;
+
+  int argc = 3;
+  const char* argv[] = {"octave", "-i", "--line-editing"};
+  octave_main(argc,(char**)argv,1);
+  switch_to_buffer (create_buffer (get_input_from_stdin ()));
+  quit_allowed = true;
+
+  is_inside_main_loop = true;
+  main_loop();
+  is_inside_main_loop = false;
+
+  if (!is_cleanup_complete)
+    clean_up_and_exit(0);
+  return 0;
+}
+
 TerminalMdiSubWindow::TerminalMdiSubWindow(QWidget *parent)
     : QMdiSubWindow(parent),
-      m_terminalWidget(0) {
+      m_terminalWidget(0),
+      isRunning(true) {
+    establishOctaveLink();
     constructWindow();
 }
 
+TerminalMdiSubWindow::~TerminalMdiSubWindow() {
+    delete m_octaveLink;
+    isRunning = false;
+}
+
+void TerminalMdiSubWindow::establishOctaveLink() {
+    m_octaveLink = new OctaveLink();
+    pthread_create(&octave_thread, NULL, octave_main_wrapper, (void*)this);
+    pthread_create(&octave_monitor_thread, 0, TerminalMdiSubWindow::octave_monitor, this);
+    command_editor::add_event_hook(server_rl_event_hook_function);
+}
+
 void TerminalMdiSubWindow::constructWindow() {
+/*
+    int fdm;
+    int fds;
+
+    if ( openpty (&fdm, &fds, 0, 0, 0) < 0 )
+      {
+        fprintf (stderr, "oops!\n");
+      }
+
+    dup2 (fds, 0);
+    dup2 (fds, 1);
+    dup2 (fds, 2);
+*/
     setWindowTitle("Octave Session");
     resize(900, 600);
     setWidget(new QWidget(this));
@@ -51,3 +102,75 @@
 
     m_statusBar->showMessage("Ready.");
 }
+
+bool ui_can_interrupt = true;
+void* TerminalMdiSubWindow::octave_monitor(void *octaveUI)
+{
+  TerminalMdiSubWindow* oui = (TerminalMdiSubWindow*)octaveUI;
+
+  while ( oui->isRunning )
+  {
+    // collect all the variable info
+    std::vector<OctaveLink::VariableMetaData> variables = oct_octave_server.variableInfoList();
+    if ( variables.size() > 0 )
+    {
+      qDebug("Update variables.");
+      //oui->mVariablesTreeView.clearRows();
+      //oui->mVariablesTreeView.addVariables(variables);
+    }
+
+    // Check whether any requested variables have been returned
+    std::vector<OctaveLink::RequestedVariable> reqVars = oct_octave_server.requestedVariables();
+    for(std::vector<OctaveLink::RequestedVariable>::iterator it = reqVars.begin() ;
+                                 it != reqVars.end() ;
+                                 it++ )
+    {
+      std::cout << "Requested variable returned: " << (*it).name << std::endl;
+    }
+
+    // collect history info
+    string_vector historyList = oct_octave_server.getHistoryList();
+    if( historyList.length() > 0 )
+    {
+      qDebug("Update history.");
+      //oui->mHistoryTreeView.addRows(historyList);
+      //oui->historyListWidget->addRows(historyList);
+    }
+
+    // Put a marker in each buffer at the proper location
+    int status = 0;
+    std::vector<OctaveLink::BreakPoint> bps = oct_octave_server.breakPointList(status);
+    if (status==0)
+    {
+      //MEditor::GetInstance()->process_breakpoint_list (bps);
+    }
+
+    // Find out if a breakpoint is hit
+    static bool line_number = -1;
+    bool is_bp_hit = oct_octave_server.isBreakpointReached(status);
+    if (status==0 && is_bp_hit)
+    {
+      std::vector<OctaveLink::BreakPoint> hit_breakpoint = oct_octave_server.reachedBreakpoint();
+      if (hit_breakpoint.size() > 0 && (hit_breakpoint[0].lineNumber != line_number))
+        {
+          //MEditor::GetInstance()->remove_hit_breakpoint_marker ();
+          //MEditor::GetInstance()->add_breakpoint_marker(hit_breakpoint[0], BP_MARKER_TYPE_HIT);
+          line_number = hit_breakpoint[0].lineNumber;
+      }
+    }
+    else if (status==0 && line_number>0)
+    {
+      //MEditor::GetInstance()->remove_hit_breakpoint_marker ();
+      line_number = -1;
+    }
+
+    if( global_command == 0 )
+      ui_can_interrupt = true;
+
+    usleep(100000);
+  }
+
+  //oui->threadEnded = 1;
+  std::cout << "Thread ended" << std::endl;
+  return 0;
+}
--- a/gui//src/TerminalMdiSubWindow.h	Fri Apr 08 15:23:21 2011 +0200
+++ b/gui//src/TerminalMdiSubWindow.h	Sat Apr 09 00:23:46 2011 +0200
@@ -6,20 +6,84 @@
 #include <QListView>
 #include <QStatusBar>
 #include "QTerminalWidget.h"
+#include "OctaveLink.h"
+
+
+// Octave includes
+#undef PACKAGE_BUGREPORT
+#undef PACKAGE_NAME
+#undef PACKAGE_STRING
+#undef PACKAGE_TARNAME
+#undef PACKAGE_VERSION
+#undef PACKAGE_URL
+#include "octave/config.h"
+
+#include "octave/debug.h"
+#include "octave/octave.h"
+#include "octave/symtab.h"
+#include "octave/parse.h"
+#include "octave/unwind-prot.h"
+#include "octave/toplev.h"
+#include "octave/load-path.h"
+#include "octave/error.h"
+#include "octave/quit.h"
+#include "octave/variables.h"
+#include "octave/sighandlers.h"
+#include "octave/sysdep.h"
+#include "octave/str-vec.h"
+#include "octave/cmd-hist.h"
+#include "octave/cmd-edit.h"
+#include "octave/oct-env.h"
+#include "octave/symtab.h"
+#include "cmd-edit.h"
+
+typedef struct yy_buffer_state *YY_BUFFER_STATE;
+extern OCTINTERP_API YY_BUFFER_STATE create_buffer (FILE *f);
+extern OCTINTERP_API void switch_to_buffer (YY_BUFFER_STATE buf);
+extern OCTINTERP_API FILE *get_input_from_stdin (void);
+
+// System
+#include <termios.h>
+#include <sys/types.h>
+#include <signal.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+
+#include <iostream>
+#include <vector>
+#include "pty.h"
 
 class TerminalMdiSubWindow : public QMdiSubWindow {
     Q_OBJECT
 public:
+    /**
+     * Stops the monitor thread.
+     */
+    void stopMonitorRunning(void) { this->isRunning = false; }
+
+    /**
+     * Checks if the monitor thread is currently running.
+     */
+    bool isMonitorRunning() { return this->isRunning; }
+
+    static void* octave_monitor(void *octaveUI);
     TerminalMdiSubWindow(QWidget *parent = 0);
+    ~TerminalMdiSubWindow();
 
 private slots:
 
 private:
+    void establishOctaveLink();
     void constructWindow();
     QTerminalWidget *m_terminalWidget;
     QTreeView *m_variableView;
     QListView *m_commandHistoryView;
     QStatusBar *m_statusBar;
-};
+    OctaveLink *m_octaveLink;
 
+    // Threads for running octave and managing the data interaction
+    pthread_t octave_thread;
+    pthread_t octave_monitor_thread;
+    bool isRunning;
+};
 #endif // TERMINALMDISUBWINDOW_H
--- a/gui//src/Vt102Emulation.cpp	Fri Apr 08 15:23:21 2011 +0200
+++ b/gui//src/Vt102Emulation.cpp	Sat Apr 09 00:23:46 2011 +0200
@@ -1,8 +1,8 @@
 /*
     This file is part of Konsole, an X terminal.
-    Copyright (C) 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
-
-    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+    
+    Copyright 2007-2008 by Robert Knight <robert.knight@gmail.com>
+    Copyright 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
 
     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,17 +23,18 @@
 // Own
 #include "Vt102Emulation.h"
 
+// XKB
 //#include <config-konsole.h>
 
-
-#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
+
+#if defined(HAVE_XKB)
+    void scrolllock_set_off();
+    void scrolllock_set_on();
 #endif
 
 // Standard 
@@ -46,45 +47,19 @@
 #include <QtGui/QKeyEvent>
 #include <QtCore/QByteRef>
 
+// KDE
+//#include <kdebug.h>
+//#include <klocale.h>
+
 // Konsole
 #include "KeyboardTranslator.h"
 #include "Screen.h"
 
-#if defined(HAVE_XKB)
-void scrolllock_set_off();
-void scrolllock_set_on();
-#endif
-
-/* 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))
 {
   _titleUpdateTimer->setSingleShot(true);
-
   QObject::connect(_titleUpdateTimer , SIGNAL(timeout()) , this , SLOT(updateTitle()));
 
   initTokenizer();
@@ -92,33 +67,23 @@
 }
 
 Vt102Emulation::~Vt102Emulation()
-{
-}
+{}
 
 void Vt102Emulation::clearEntireScreen()
 {
   _currentScreen->clearEntireScreen();
-
   bufferedUpdate(); 
 }
 
 void Vt102Emulation::reset()
 {
-  //kDebug(1211)<<"Vt102Emulation::reset() resetToken()";
-  resetToken();
-  //kDebug(1211)<<"Vt102Emulation::reset() resetModes()";
+  resetTokenizer();
   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();
 }
@@ -140,7 +105,7 @@
 
    - 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.
@@ -170,8 +135,9 @@
    - VT52       - VT52 escape codes
                   - <ESC><Chr>
                   - <ESC>'Y'{Pc}{Pc}
-   - XTE_HA     - Xterm hacks              <ESC>`]' {Pn} `;' {Text} <BEL>
-                  note that this is handled differently
+   - XTE_HA     - Xterm window/terminal attribute commands 
+                  of the form <ESC>`]' {Pn} `;' {Text} <BEL>
+                  (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
@@ -181,40 +147,44 @@
 
 */
 
-#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()
@@ -223,34 +193,46 @@
   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;<row>;<col>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;<row>;<col>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;<row>;<col>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.
@@ -263,125 +245,170 @@
 
    - 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 resetToken nor a pushToToken. Some of them, do
+  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) resetToken(); //VT100: CAN or SUB
-    if (cc != ESC)    { tau( TY_CTL(cc+'@' ),   0,  0); return; }
+    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;<row>;<col>t
+    if (eps(CPS)) 
+    { 
+        processToken( TY_CSI_PS(cc, argv[0]), argv[1], argv[2]);   
+        resetTokenizer(); 
+        return; 
+    }
+
+    if (epe(   )) { processToken( TY_CSI_PE(cc), 0, 0); resetTokenizer(); return; }
+    if (ees(DIG)) { addDigit(cc-'0'); return; }
+    if (eec(';')) { addArgument();    return; }
+    for (int i=0;i<=argc;i++)
+    {
+        if (epp())  
+            processToken( TY_CSI_PR(cc,argv[i]), 0, 0);
+        else if (egt())   
+            processToken( TY_CSI_PG(cc), 0, 0); // spec. case for ESC]>0c or ESC]>c
+        else if (cc == 'm' && argc - i >= 4 && (argv[i] == 38 || argv[i] == 48) && argv[i+1] == 2)
+        { 
+            // ESC[ ... 48;2;<red>;<green>;<blue> ... m -or- ESC[ ... 38;2;<red>;<green>;<blue> ... m
+            i += 2;
+            processToken( TY_CSI_PS(cc, argv[i-2]), COLOR_SPACE_RGB, (argv[i] << 16) | (argv[i+1] << 8) | argv[i+2]);
+            i += 2;
+        }
+        else if (cc == 'm' && argc - i >= 2 && (argv[i] == 38 || argv[i] == 48) && argv[i+1] == 5)
+        { 
+            // ESC[ ... 48;5;<index> ... m -or- ESC[ ... 38;5;<index> ... m
+            i += 2;
+            processToken( TY_CSI_PS(cc, argv[i-2]), COLOR_SPACE_256, argv[i]);
+        }
+        else
+            processToken( TY_CSI_PS(cc,argv[i]), 0, 0);
+    }
+    resetTokenizer();
+  }
+  else 
+  {
+    // VT52 Mode
+    if (lec(1,0,ESC))                                                      
+        return;
+    if (les(1,0,CHR)) 
+    { 
+        processToken( TY_CHR(), s[0], 0); 
+        resetTokenizer(); 
+        return; 
+    }
+    if (lec(2,1,'Y'))                                                      
+        return;
+    if (lec(3,1,'Y'))                                                      
+        return;
+    if (p < 4) 
+    { 
+        processToken( TY_VT52(s[1] ), 0, 0); 
+        resetTokenizer(); 
+        return; 
+    }
+    processToken( TY_VT52(s[1]), s[2], s[3]); 
+    resetTokenizer(); 
+    return;
+  }
+}
+void Vt102Emulation::processWindowAttributeChange()
+{
+  // 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');
   }
 
-  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;<row>;<col>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;<red>;<green>;<blue> ... m -or- ESC[ ... 38;2;<red>;<green>;<blue> ... 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;<index> ... m -or- ESC[ ... 38;5;<index> ... 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();
+  if (tokenBuffer[i] != ';') 
+  { 
+    reportDecodingError(); 
+    return; 
   }
-  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(); return;
-  }
-}
-
-void Vt102Emulation::XtermHack()
-{ 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);
   
-  // 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;
+  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);
-
-  delete [] str;
 }
 
 void Vt102Emulation::updateTitle()
 {
-	QListIterator<int> iter( _pendingTitleUpdates.keys() );
-	while (iter.hasNext()) {
-		int arg = iter.next();
-		emit titleChanged( arg , _pendingTitleUpdates[arg] );	
-	}
-
-    _pendingTitleUpdates.clear();	
+    QListIterator<int> iter( _pendingTitleUpdates.keys() );
+    while (iter.hasNext()) {
+        int arg = iter.next();
+        emit titleChanged( arg , _pendingTitleUpdates[arg] );    
+    }
+    _pendingTitleUpdates.clear();    
 }
 
 // Interpreting Codes ---------------------------------------------------------
@@ -402,44 +429,12 @@
    about this mapping.
 */
 
-void Vt102Emulation::tau( int token, int p, int q )
-{
-#if 0
-int N = (token>>0)&0xff;
-int A = (token>>8)&0xff;
-switch( N )
+void Vt102Emulation::processToken(int token, int p, int q)
 {
-   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)
   {
 
-    case TY_CHR(         ) : _currentScreen->ShowCharacter        (p         ); break; //UTF16
+    case TY_CHR(         ) : _currentScreen->displayCharacter     (p         ); break; //UTF16
 
     //             127 DEL    : ignored on input
 
@@ -452,12 +447,12 @@
     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('H'      ) : _currentScreen->backspace            (          ); break; //VT100
+    case TY_CTL('I'      ) : _currentScreen->tab                  (          ); break; //VT100
+    case TY_CTL('J'      ) : _currentScreen->newLine              (          ); break; //VT100
+    case TY_CTL('K'      ) : _currentScreen->newLine              (          ); break; //VT100
+    case TY_CTL('L'      ) : _currentScreen->newLine              (          ); break; //VT100
+    case TY_CTL('M'      ) : _currentScreen->toStartOfLine        (          ); break; //VT100
 
     case TY_CTL('N'      ) :      useCharset           (         1); break; //VT100
     case TY_CTL('O'      ) :      useCharset           (         0); break; //VT100
@@ -470,9 +465,9 @@
     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('X'      ) : _currentScreen->displayCharacter     (    0x2592); break; //VT100
     case TY_CTL('Y'      ) : /* EM : ignored                      */ break;
-    case TY_CTL('Z'      ) : _currentScreen->ShowCharacter        (    0x2592); break; //VT100
+    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;
@@ -480,7 +475,7 @@
     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('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;
@@ -515,25 +510,25 @@
     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;
+                                _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;
+                                _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;
+                                _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;
+                                _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , true);    
+                                _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , false);
+                                break;
     case TY_ESC_DE('8'      ) : _currentScreen->helpAlign            (          ); break;
 
 // resize = \e[8;<row>;<col>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;<color>t  color: 0-16,777,215
     case TY_CSI_PS('t',   28) : emit changeTabTextColorRequest      ( p        );          break;
@@ -544,6 +539,7 @@
     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;
@@ -628,14 +624,14 @@
     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('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->backTabulate         (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
@@ -649,8 +645,8 @@
 
     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',   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
@@ -688,6 +684,9 @@
     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
@@ -737,6 +736,8 @@
     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
@@ -777,7 +778,9 @@
 
     case TY_CSI_PG('c'      ) :  reportSecondaryAttributes(          ); break; //VT100
 
-    default : ReportErrorToken();    break;
+    default: 
+        reportDecodingError();    
+        break;
   };
 }
 
@@ -789,23 +792,6 @@
     _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)
 {
   if ( length >= 0 )
@@ -814,38 +800,24 @@
     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];
+{ 
+  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
+  // 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
+    sendString("\033[?1;2c"); // I'm a VT100
   else
-    sendString("\033/Z");         // I'm a VT52
+    sendString("\033/Z"); // I'm a VT52
 }
 
 void Vt102Emulation::reportSecondaryAttributes()
@@ -860,89 +832,86 @@
 
 void Vt102Emulation::reportTerminalParms(int p)
 // DECREPTPARM
-{ char tmp[100];
+{ 
+  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.
 }
 
-/*!
-*/
-
-#define ANSWER_BACK "" // This is really obsolete VT100 stuff.
-
 void Vt102Emulation::reportAnswerBack()
 {
+  // 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;
+{ 
+  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 (cb >= 4) 
+    cb += 0x3c;
 
   //Mouse motion handling
-  if ( (getMode(MODE_Mouse1002) || getMode(MODE_Mouse1003)) && eventType == 1 )
-	  cb += 0x20; //add 32 to signify motion event
+  if ((getMode(MODE_Mouse1002) || getMode(MODE_Mouse1003)) && eventType == 1)
+      cb += 0x20; //add 32 to signify motion event
 
-  sprintf(tmp,"\033[M%c%c%c",cb+0x20,cx+0x20,cy+0x20);
-  sendString(tmp);
+  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 )
 {
-  if (!text.isEmpty()) {
+  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 )
 {
     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 )
@@ -960,7 +929,8 @@
         // (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() )
@@ -970,8 +940,9 @@
 
         if ( entry.command() != KeyboardTranslator::NoCommand )
         {
-			if (entry.command() & KeyboardTranslator::EraseCommand)
-				textToSend += getErase();
+            if (entry.command() & KeyboardTranslator::EraseCommand)
+                textToSend += eraseChar();
+
             // TODO command handling
         }
         else if ( !entry.text().isEmpty() ) 
@@ -987,11 +958,10 @@
     {
         // print an error message to the terminal if no key translator has been
         // set
-        QString translatorError =  ("No keyboard translator available.  "
+        QString translatorError =  i18n("No keyboard translator available.  "
                                          "The information needed to convert key presses "
                                          "into characters to send to the terminal " 
                                          "is missing.");
-
         reset();
         receiveData( translatorError.toAscii().constData() , translatorError.count() );
     }
@@ -1028,13 +998,13 @@
 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
+  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.
@@ -1042,12 +1012,12 @@
 
 void Vt102Emulation::resetCharset(int scrno)
 {
-  _charset[scrno].cu_cs   = 0;
+  _charset[scrno].cu_cs = 0;
   strncpy(_charset[scrno].charset,"BBBB",4);
   _charset[scrno].sa_graphic = false;
-  _charset[scrno].sa_pound   = false;
+  _charset[scrno].sa_pound = false;
   _charset[scrno].graphic = false;
-  _charset[scrno].pound   = false;
+  _charset[scrno].pound = false;
 }
 
 void Vt102Emulation::setCharset(int n, int cs) // on both screens.
@@ -1071,8 +1041,8 @@
 
 void Vt102Emulation::setDefaultMargins()
 {
-	_screen[0]->setDefaultMargins();
-	_screen[1]->setDefaultMargins();
+    _screen[0]->setDefaultMargins();
+    _screen[1]->setDefaultMargins();
 }
 
 void Vt102Emulation::setMargins(int t, int b)
@@ -1081,8 +1051,6 @@
   _screen[1]->setMargins(t, b);
 }
 
-/*! Save the cursor position and the rendition attribute settings. */
-
 void Vt102Emulation::saveCursor()
 {
   CHARSET.sa_graphic = CHARSET.graphic;
@@ -1093,8 +1061,6 @@
   _currentScreen->saveCursor();
 }
 
-/*! Restore the cursor position and the rendition attribute settings. */
-
 void Vt102Emulation::restoreCursor()
 {
   CHARSET.graphic = CHARSET.sa_graphic;
@@ -1124,28 +1090,38 @@
 
 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;
+  _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); 
+         emit programUsesMouseChanged(false); 
     break;
 
     case MODE_AppScreen : _screen[1]->clearSelection();
@@ -1161,18 +1137,23 @@
 
 void Vt102Emulation::resetMode(int m)
 {
-  _currParm.mode[m] = false;
+  _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); 
+        emit programUsesMouseChanged(true); 
     break;
 
-    case MODE_AppScreen : _screen[0]->clearSelection();
-                          setScreen(0);
+    case MODE_AppScreen : 
+        _screen[0]->clearSelection();
+        setScreen(0);
     break;
   }
   if (m < MODES_SCREEN || m == MODE_NewLine)
@@ -1184,12 +1165,12 @@
 
 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]) 
+  if (_savedModes.mode[m]) 
       setMode(m); 
   else 
       resetMode(m);
@@ -1197,10 +1178,10 @@
 
 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,
@@ -1212,20 +1193,7 @@
       return '\b';
 }
 
-/* ------------------------------------------------------------------------- */
-/*                                                                           */
-/*                               Diagnostic                                  */
-/*                                                                           */
-/* ------------------------------------------------------------------------- */
-
-/*! 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
-*/
-
+// print contents of the scan buffer
 static void hexdump(int* s, int len)
 { int i;
   for (i = 0; i < len; i++)
@@ -1240,15 +1208,12 @@
   }
 }
 
-void Vt102Emulation::scan_buffer_report()
+void Vt102Emulation::reportDecodingError()
 {
-  if (ppos == 0 || ppos == 1 && (pbuf[0] & 0xff) >= 32) return;
-  printf("token: "); hexdump(pbuf,ppos); printf("\n");
+  if (tokenBufferPos == 0 || ( tokenBufferPos == 1 && (tokenBuffer[0] & 0xff) >= 32) ) 
+    return;
+  printf("Undecodable sequence: "); 
+  hexdump(tokenBuffer,tokenBufferPos); 
+  printf("\n");
 }
 
-void Vt102Emulation::ReportErrorToken()
-{
-#ifndef NDEBUG
-  printf("undecodable "); scan_buffer_report();
-#endif
-}
--- a/gui//src/Vt102Emulation.h	Fri Apr 08 15:23:21 2011 +0200
+++ b/gui//src/Vt102Emulation.h	Sat Apr 09 00:23:46 2011 +0200
@@ -1,10 +1,8 @@
 /*
     This file is part of Konsole, an X terminal.
     
-    Copyright (C) 2007 by Robert Knight <robertknight@gmail.com>
-    Copyright (C) 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
-
-    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+    Copyright 2007-2008 by Robert Knight <robertknight@gmail.com>
+    Copyright 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
 
     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
@@ -37,20 +35,17 @@
 #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)
-
-struct DECpar
-{
-  bool mode[MODE_total];
-};
+#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)
 
 struct CharCodes
 {
@@ -78,42 +73,33 @@
 Q_OBJECT
 
 public:
-
   /** Constructs a new emulation */
   Vt102Emulation();
   ~Vt102Emulation();
   
-  // reimplemented
+  // reimplemented from Emulation
   virtual void clearEntireScreen();
   virtual void reset();
-  
-  // reimplemented
-  virtual char getErase() const;
+  virtual char eraseChar() const;
   
 public slots: 
-
-  // reimplemented 
+  // 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 );
+  virtual void sendMouseEvent(int buttons, int column, int line, int eventType);
   
 protected:
-  // reimplemented
-  virtual void setMode    (int mode);
-  virtual void resetMode  (int mode);
-
-  // reimplemented 
+  // 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();
 
-
 private:
   unsigned short applyCharset(unsigned short c);
   void setCharset(int n, int cs);
@@ -134,26 +120,30 @@
   // 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 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 processToken(int code, int p, int q);
+  void processWindowAttributeChange();
 
   void reportTerminalType();
   void reportSecondaryAttributes();
@@ -171,8 +161,18 @@
 
   CharCodes _charset[2];
 
-  DECpar _currParm;
-  DECpar _saveParm;
+  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
@@ -181,6 +181,6 @@
   //output from the terminal
   QHash<int,QString> _pendingTitleUpdates;
   QTimer* _titleUpdateTimer;
-  
 };
+
 #endif // VT102EMULATION_H
--- a/gui//src/k3process.cpp	Fri Apr 08 15:23:21 2011 +0200
+++ b/gui//src/k3process.cpp	Sat Apr 09 00:23:46 2011 +0200
@@ -64,7 +64,8 @@
 #include <QtCore/QMap>
 #include <QtCore/QFile>
 #include <QtCore/QSocketNotifier>
-
+#include <QStringList>
+#include <QDebug>
 //#include <kdebug.h>
 //#include <kstandarddirs.h>
 //#include <kuser.h>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gui//src/kdecore_export.h	Sat Apr 09 00:23:46 2011 +0200
@@ -0,0 +1,46 @@
+/*  This file is part of the KDE project
+    Copyright (C) 2007 David Faure <faure@kde.org>
+
+    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 KDECORE_EXPORT_H
+#define KDECORE_EXPORT_H
+
+/* needed for KDE_EXPORT and KDE_IMPORT macros */
+//#include <kdemacros.h>
+#define KDE_EXPORT
+#define KDE_IMPORT
+#define KDE_DEPRECATED
+
+#ifndef KDECORE_EXPORT
+# if defined(KDELIBS_STATIC_LIBS)
+   /* No export/import for static libraries */
+#  define KDECORE_EXPORT
+# elif defined(MAKE_KDECORE_LIB)
+   /* We are building this library */ 
+#  define KDECORE_EXPORT KDE_EXPORT
+# else
+   /* We are using this library */ 
+#  define KDECORE_EXPORT KDE_IMPORT
+# endif
+#endif
+
+# ifndef KDECORE_EXPORT_DEPRECATED
+#  define KDECORE_EXPORT_DEPRECATED KDE_DEPRECATED KDECORE_EXPORT
+# endif
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gui//src/konsole_export.h	Sat Apr 09 00:23:46 2011 +0200
@@ -0,0 +1,67 @@
+/*
+    This file is part of the KDE project
+    Copyright (C) 2009 Patrick Spendrin <ps_ml@gmx.de>
+
+    This library 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 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 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 KONSOLE_EXPORT_H
+#define KONSOLE_EXPORT_H
+
+/* needed for KDE_EXPORT macros */
+//#include <kdemacros.h>
+#include <QtCore/qglobal.h>
+#define KDE_EXPORT
+#define KDE_IMPORT
+
+#ifndef KONSOLEPRIVATE_EXPORT
+# if defined(MAKE_KONSOLEPRIVATE_LIB)
+   /* We are building this library */
+#  define KONSOLEPRIVATE_EXPORT KDE_EXPORT
+# else
+   /* We are using this library */
+#  define KONSOLEPRIVATE_EXPORT KDE_IMPORT
+# endif
+#endif
+
+#include <iostream>
+//#define kWarning(x) std::cout
+
+#include <stdio.h>
+
+//#define i18n 
+inline QString i18n(char *buff,...)
+{
+  char msg[2048];
+    va_list arglist;
+
+    va_start(arglist,buff);
+
+    snprintf(msg,2048,buff, arglist);
+
+    va_end(arglist);
+
+    return QString(msg);
+}
+
+#define i18nc 
+
+
+//#define KDE_fseek ::fseek
+//#define KDE_lseek ::lseek
+
+
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gui//src/kprocess.cpp	Sat Apr 09 00:23:46 2011 +0200
@@ -0,0 +1,416 @@
+/*
+    This file is part of the KDE libraries
+
+    Copyright (C) 2007 Oswald Buddenhagen <ossi@kde.org>
+
+    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_p.h"
+
+//#include <kstandarddirs.h>
+//#include <kshell.h>
+//#ifdef Q_OS_WIN
+//# include <kshell_p.h>
+//#endif
+
+#include <qfile.h>
+
+#ifdef Q_OS_WIN
+# include <windows.h>
+#else
+# include <unistd.h>
+# include <errno.h>
+#endif
+
+#ifndef Q_OS_WIN
+# define STD_OUTPUT_HANDLE 1
+# define STD_ERROR_HANDLE 2
+#endif
+
+#ifdef _WIN32_WCE
+#include <stdio.h>
+#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
+}
+
+void KProcess::setShellCommand(const QString &cmd)
+{
+    Q_D(KProcess);
+
+    // JPS: commented out because I didn't want to pull in KShell also.  It
+    // seems this is mostly for handling program arguments, which I won't be
+    // using.
+    /*
+    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
+}
+
+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
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gui//src/kprocess.h	Sat Apr 09 00:23:46 2011 +0200
@@ -0,0 +1,341 @@
+/*
+    This file is part of the KDE libraries
+
+    Copyright (C) 2007 Oswald Buddenhagen <ossi@kde.org>
+
+    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 "kdecore_export.h"
+
+#include <QtCore/QProcess>
+
+class KProcessPrivate;
+
+/**
+ * \class KProcess kprocess.h <KProcess>
+ * 
+ * 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 <ossi@kde.org>
+ **/
+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:
+     * <code>
+     *   start();
+     *   waitForFinished(msecs);
+     *   return exitCode();
+     * </code>
+     *
+     * 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())
+};
+
+#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gui//src/kprocess_p.h	Sat Apr 09 00:23:46 2011 +0200
@@ -0,0 +1,48 @@
+/*
+    This file is part of the KDE libraries
+
+    Copyright (C) 2007 Oswald Buddenhagen <ossi@kde.org>
+
+    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_P_H
+#define KPROCESS_P_H
+
+#include "kprocess.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
--- a/gui//src/kpty.cpp	Fri Apr 08 15:23:21 2011 +0200
+++ b/gui//src/kpty.cpp	Sat Apr 09 00:23:46 2011 +0200
@@ -2,9 +2,9 @@
 
    This file is part of the KDE libraries
    Copyright (C) 2002 Waldo Bastian <bastian@kde.org>
-   Copyright (C) 2002-2003,2007 Oswald Buddenhagen <ossi@kde.org>
-
-    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, Copyright (C)2008
+   Copyright (C) 2002-2003,2007-2008 Oswald Buddenhagen <ossi@kde.org>
+   Copyright (C) 2010 KDE e.V. <kde-ev-board@kde.org>
+     Author Adriaan de Groot <groot@kde.org>
 
    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
@@ -24,6 +24,8 @@
 
 #include "kpty_p.h"
 
+//#include <config.h>
+
 #ifdef __sgi
 #define __svr4__
 #endif
@@ -71,6 +73,9 @@
 # include <util.h>
 #endif
 
+#define HAVE_UTMPX
+#define _UTMPX_COMPAT
+
 #ifdef HAVE_UTEMPTER
 extern "C" {
 # include <utempter.h>
@@ -110,7 +115,7 @@
 #if defined (__FreeBSD__) || defined (__NetBSD__) || defined (__OpenBSD__) || defined (__bsdi__) || defined(__APPLE__) || defined (__DragonFly__)
 # define _tcgetattr(fd, ttmode) ioctl(fd, TIOCGETA, (char *)ttmode)
 #else
-# if defined(_HPUX_SOURCE) || defined(__Lynx__) || defined (__CYGWIN__)
+# if defined(_HPUX_SOURCE) || defined(__Lynx__) || defined (__CYGWIN__) || defined(__sun)
 #  define _tcgetattr(fd, ttmode) tcgetattr(fd, ttmode)
 # else
 #  define _tcgetattr(fd, ttmode) ioctl(fd, TCGETS, (char *)ttmode)
@@ -120,7 +125,7 @@
 #if defined (__FreeBSD__) || defined (__NetBSD__) || defined (__OpenBSD__) || defined (__bsdi__) || defined(__APPLE__) || defined (__DragonFly__)
 # define _tcsetattr(fd, ttmode) ioctl(fd, TIOCSETA, (char *)ttmode)
 #else
-# if defined(_HPUX_SOURCE) || defined(__CYGWIN__)
+# if defined(_HPUX_SOURCE) || defined(__CYGWIN__) || defined(__sun)
 #  define _tcsetattr(fd, ttmode) tcsetattr(fd, TCSANOW, ttmode)
 # else
 #  define _tcsetattr(fd, ttmode) ioctl(fd, TCSETS, (char *)ttmode)
@@ -129,16 +134,20 @@
 
 //#include <kdebug.h>
 //#include <kstandarddirs.h>	// findExe
-
-#include <QtCore>
+//#include <kde_file.h>
 
-// not defined on HP-UX for example
-#ifndef CTRL
-# define CTRL(x) ((x) & 037)
-#endif
+#include <QtCore/Q_PID>
 
 #define TTY_GROUP "tty"
 
+#ifndef PATH_MAX
+# ifdef MAXPATHLEN
+#  define PATH_MAX MAXPATHLEN
+# else
+#  define PATH_MAX 1024
+# endif
+#endif
+
 ///////////////////////
 // private functions //
 ///////////////////////
@@ -147,26 +156,30 @@
 // private data //
 //////////////////
 
-KPtyPrivate::KPtyPrivate() :
-    masterFd(-1), slaveFd(-1)
+KPtyPrivate::KPtyPrivate(KPty* parent) :
+    masterFd(-1), slaveFd(-1), ownMaster(true), q_ptr(parent)
 {
 }
 
-bool KPtyPrivate::chownpty(bool)
+KPtyPrivate::~KPtyPrivate()
 {
-//    return !QProcess::execute(KStandardDirs::findExe("kgrantpty"),
-//        QStringList() << (grant?"--grant":"--revoke") << QString::number(masterFd));
-    return true;
 }
 
+#ifndef HAVE_OPENPTY
+bool KPtyPrivate::chownpty(bool grant)
+{
+    return !QProcess::execute(KStandardDirs::findExe("kgrantpty"),
+        QStringList() << (grant?"--grant":"--revoke") << QString::number(masterFd));
+}
+#endif
+
 /////////////////////////////
 // public member functions //
 /////////////////////////////
 
 KPty::KPty() :
-    d_ptr(new KPtyPrivate)
+    d_ptr(new KPtyPrivate(this))
 {
-    d_ptr->q_ptr = this;
 }
 
 KPty::KPty(KPtyPrivate *d) :
@@ -188,6 +201,8 @@
   if (d->masterFd >= 0)
     return true;
 
+  d->ownMaster = true;
+
   QByteArray ptyName;
 
   // Find a master pty that we can open ////////////////////////////////
@@ -204,7 +219,7 @@
   {
     d->masterFd = -1;
     d->slaveFd = -1;
-    kWarning(175) << "Can't open a pseudo teletype";
+    //kWarning(175) << "Can't open a pseudo teletype";
     return false;
   }
   d->ttyName = ptsn;
@@ -226,14 +241,13 @@
 #elif defined(HAVE_GETPT)
   d->masterFd = ::getpt();
 #elif defined(PTM_DEVICE)
-  d->masterFd = ::open(PTM_DEVICE, O_RDWR|O_NOCTTY);
+  //d->masterFd = KDE_open(PTM_DEVICE, O_RDWR|O_NOCTTY);
+d->masterFd = ::open(PTM_DEVICE, O_RDWR|O_NOCTTY);
 #else
 # error No method to open a PTY master detected.
 #endif
-
   if (d->masterFd >= 0)
   {
- 
 #ifdef HAVE_PTSNAME
     char *ptsn = ptsname(d->masterFd);
     if (ptsn) {
@@ -241,13 +255,14 @@
 #else
     int ptyno;
     if (!ioctl(d->masterFd, TIOCGPTN, &ptyno)) {
-        d->ttyName = QByteArray("/dev/pts/") + QByteArray::number(ptyno);
+        char buf[32];
+        sprintf(buf, "/dev/pts/%d", ptyno);
+        d->ttyName = buf;
 #endif
 #ifdef HAVE_GRANTPT
         if (!grantpt(d->masterFd))
            goto grantedpt;
 #else
-
         goto gotpty;
 #endif
     }
@@ -299,28 +314,27 @@
     }
   }
 
-  qWarning() << "Can't open a pseudo teletype";
+  //kWarning(175) << "Can't open a pseudo teletype";
   return false;
 
  gotpty:
-  struct stat st;
-  if (stat(d->ttyName.data(), &st)) {
+  KDE_struct_stat st;
+  if (KDE_stat(d->ttyName.data(), &st))
     return false; // this just cannot happen ... *cough*  Yeah right, I just
                   // had it happen when pty #349 was allocated.  I guess
                   // there was some sort of leak?  I only had a few open.
-    }
   if (((st.st_uid != getuid()) ||
        (st.st_mode & (S_IRGRP|S_IXGRP|S_IROTH|S_IWOTH|S_IXOTH))) &&
       !d->chownpty(true))
   {
-    qWarning()
+
+    /*kWarning(175)
       << "chownpty failed for device " << ptyName << "::" << d->ttyName
       << "\nThis means the communication can be eavesdropped." << endl;
-  }
+*/  
+}
 
-#if defined (HAVE__GETPTY) || defined (HAVE_GRANTPT)
  grantedpt:
-#endif 
 
 #ifdef HAVE_REVOKE
   revoke(d->ttyName.data());
@@ -336,16 +350,25 @@
   d->slaveFd = ::open(d->ttyName.data(), O_RDWR | O_NOCTTY);
   if (d->slaveFd < 0)
   {
-    qWarning() << "Can't open slave pseudo teletype";
+    //kWarning(175) << "Can't open slave pseudo teletype";
     ::close(d->masterFd);
     d->masterFd = -1;
     return false;
   }
 
-#if (defined(__svr4__) || defined(__sgi__))
-  // Solaris
-  ioctl(d->slaveFd, I_PUSH, "ptem");
-  ioctl(d->slaveFd, I_PUSH, "ldterm");
+#if (defined(__svr4__) || defined(__sgi__) || defined(Q_OS_SOLARIS))
+  // Solaris uses STREAMS for terminal handling. It is possible
+  // for the pty handling modules to be left off the stream; in that
+  // case push them on. ioctl(fd, I_FIND, ...) is documented to return
+  // 1 if the module is on the stream already.
+  {
+    static const char *pt = "ptem";
+    static const char *ld = "ldterm";
+    if (ioctl(d->slaveFd, I_FIND, pt) == 0)
+      ioctl(d->slaveFd, I_PUSH, pt);
+    if (ioctl(d->slaveFd, I_FIND, ld) == 0)
+      ioctl(d->slaveFd, I_PUSH, ld);
+  }
 #endif
 
 #endif /* HAVE_OPENPTY */
@@ -356,6 +379,47 @@
   return true;
 }
 
+bool KPty::open(int fd)
+{
+#if !defined(HAVE_PTSNAME) && !defined(TIOCGPTN)
+    //kWarning(175) << "Unsupported attempt to open pty with fd" << fd;
+    return false;
+#else
+    Q_D(KPty);
+
+    if (d->masterFd >= 0) {
+        //kWarning(175) << "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 {
+        //kWarning(175) << "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);
@@ -366,28 +430,51 @@
     d->slaveFd = -1;
 }
 
+bool KPty::openSlave()
+{
+    Q_D(KPty);
+
+    if (d->slaveFd >= 0)
+        return true;
+    if (d->masterFd < 0) {
+        //kWarning(175) << "Attempting to open pty slave while master is closed";
+        return false;
+    }
+    d->slaveFd = ::open(d->ttyName.data(), O_RDWR | O_NOCTTY);
+    if (d->slaveFd < 0) {
+        //kWarning(175) << "Can't open slave pseudo teletype";
+        return false;
+    }
+    fcntl(d->slaveFd, F_SETFD, FD_CLOEXEC);
+    return true;
+}
+
 void KPty::close()
 {
-   Q_D(KPty);
+    Q_D(KPty);
 
-   if (d->masterFd < 0)
-      return;
-   closeSlave();
-   // don't bother resetting unix98 pty, it will go away after closing master anyway.
-   if (memcmp(d->ttyName.data(), "/dev/pts/", 9)) {
-      if (!geteuid()) {
-         struct stat st;
-         if (!stat(d->ttyName.data(), &st)) {
-            chown(d->ttyName.data(), 0, st.st_gid == getgid() ? 0 : -1);
-            chmod(d->ttyName.data(), S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);
-         }
-      } else {
-         fcntl(d->masterFd, F_SETFD, 0);
-         d->chownpty(false);
-      }
-   }
-   ::close(d->masterFd);
-   d->masterFd = -1;
+    if (d->masterFd < 0)
+        return;
+    closeSlave();
+    if (d->ownMaster) {
+#ifndef HAVE_OPENPTY
+        // don't bother resetting unix98 pty, it will go away after closing master anyway.
+        if (memcmp(d->ttyName.data(), "/dev/pts/", 9)) {
+            if (!geteuid()) {
+                struct stat st;
+                if (!stat(d->ttyName.data(), &st)) {
+                    chown(d->ttyName.data(), 0, st.st_gid == getgid() ? 0 : -1);
+                    chmod(d->ttyName.data(), S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);
+                }
+            } else {
+                fcntl(d->masterFd, F_SETFD, 0);
+                d->chownpty(false);
+            }
+        }
+#endif
+        ::close(d->masterFd);
+    }
+    d->masterFd = -1;
 }
 
 void KPty::setCTty()
@@ -405,7 +492,7 @@
     ioctl(d->slaveFd, TIOCSCTTY, 0);
 #else
     // __svr4__ hack: the first tty opened after setsid() becomes controlling tty
-    ::close(::open(d->ttyName, O_WRONLY, 0));
+    ::close(open(d->ttyName, O_WRONLY, 0));
 #endif
 
     // make our new process group the foreground group on the pty
@@ -457,7 +544,8 @@
 # endif
 
 # ifdef HAVE_UTMPX
-    gettimeofday(&l_struct.ut_tv, 0);
+    //gettimeofday(&l_struct.ut_tv, 0);
+    gettimeofday((struct timeval *)&l_struct.ut_tv, 0);
 # else
     l_struct.ut_time = time(0);
 # endif
@@ -483,7 +571,7 @@
     setutxent();
     pututxline(&l_struct);
     endutxent();
-    updwtmpx(_PATH_WTMPX, &l_struct);
+    //updwtmpx(_PATH_WTMPX, &l_struct);
 #  else
     utmpname(_PATH_UTMP);
     setutent();
@@ -548,7 +636,8 @@
         ut->ut_type = DEAD_PROCESS;
 #  endif
 #  ifdef HAVE_UTMPX
-        gettimeofday(ut->ut_tv, 0);
+        //gettimeofday(&(ut->ut_tv), 0);
+	gettimeofday((struct timeval *)&(ut->ut_tv), 0);
         pututxline(ut);
     }
     endutxent();
@@ -562,13 +651,13 @@
 #endif
 }
 
-// XXX Supposedly, tc[gs]etattr do not work with the master on Solaris.
-// Please verify.
-
 bool KPty::tcGetAttr(struct ::termios *ttmode) const
 {
     Q_D(const KPty);
 
+#ifdef Q_OS_SOLARIS
+    if (_tcgetattr(d->slaveFd, ttmode) == 0) return true;
+#endif
     return _tcgetattr(d->masterFd, ttmode) == 0;
 }
 
@@ -576,6 +665,9 @@
 {
     Q_D(KPty);
 
+#ifdef Q_OS_SOLARIS
+    if (_tcsetattr(d->slaveFd, ttmode) == 0) return true;
+#endif
     return _tcsetattr(d->masterFd, ttmode) == 0;
 }
 
--- a/gui//src/kpty.h	Fri Apr 08 15:23:21 2011 +0200
+++ b/gui//src/kpty.h	Sat Apr 09 00:23:46 2011 +0200
@@ -2,8 +2,6 @@
 
     Copyright (C) 2003,2007 Oswald Buddenhagen <ossi@kde.org>
 
-    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, 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
@@ -22,8 +20,8 @@
 
 #ifndef kpty_h
 #define kpty_h
-
-#include <QtCore>
+#include <QtCore/qglobal.h>
+//#include "kpty_export.h"
 
 struct KPtyPrivate;
 struct termios;
@@ -58,6 +56,16 @@
   bool open();
 
   /**
+   * Open using an existing pty master.
+   *
+   * @param fd an open pty master file descriptor.
+   *   The ownership of the fd remains with the caller;
+   *   it will not be automatically closed at any point.
+   * @return true if a pty pair was successfully opened
+   */
+  bool open(int fd);
+
+  /**
    * Close the pty master/slave pair.
    */
   void close();
@@ -77,6 +85,15 @@
   void closeSlave();
 
   /**
+   * Open the pty slave descriptor.
+   *
+   * This undoes the effect of closeSlave().
+   *
+   * @return true if the pty slave was successfully opened
+   */
+  bool openSlave();
+
+  /**
    * Creates a new session and process group and makes this pty the
    * controlling tty.
    */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gui//src/kpty_export.h	Sat Apr 09 00:23:46 2011 +0200
@@ -0,0 +1,46 @@
+/*  This file is part of the KDE project
+    Copyright (C) 2007 David Faure <faure@kde.org>
+
+    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 KPTY_EXPORT_H
+#define KPTY_EXPORT_H
+
+/* needed for KDE_EXPORT and KDE_IMPORT macros */
+//#include <kdemacros.h>
+#include <QtCore/qglobal.h>
+#define KDE_EXPORT
+#define KDE_IMPORT
+
+#ifndef KPTY_EXPORT
+# if defined(KDELIBS_STATIC_LIBS)
+   /* No export/import for static libraries */
+#  define KPTY_EXPORT
+# elif defined(MAKE_KDECORE_LIB)
+   /* We are building this library */ 
+#  define KPTY_EXPORT KDE_EXPORT
+# else
+   /* We are using this library */ 
+#  define KPTY_EXPORT KDE_IMPORT
+# endif
+#endif
+
+# ifndef KPTY_EXPORT_DEPRECATED
+#  define KPTY_EXPORT_DEPRECATED KDE_DEPRECATED KPTY_EXPORT
+# endif
+
+#endif
--- a/gui//src/kpty_p.h	Fri Apr 08 15:23:21 2011 +0200
+++ b/gui//src/kpty_p.h	Sat Apr 09 00:23:46 2011 +0200
@@ -2,8 +2,6 @@
 
     Copyright (C) 2003,2007 Oswald Buddenhagen <ossi@kde.org>
 
-    Rewritten for QT4 by e_k <e_k at users.sourceforge.net>, 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
@@ -25,16 +23,33 @@
 
 #include "kpty.h"
 
+//#include <config-pty.h>
+#if defined(Q_OS_MAC)
+#define HAVE_UTIL_H
+#define HAVE_UTMPX
+#define _UTMPX_COMPAT
+#define HAVE_PTSNAME
+#define HAVE_SYS_TIME_H
+#else
+#define HAVE_PTY_H
+#endif
+
+#define HAVE_OPENPTY
+
 #include <QtCore/QByteArray>
 
 struct KPtyPrivate {
     Q_DECLARE_PUBLIC(KPty)
 
-    KPtyPrivate();
+    KPtyPrivate(KPty* parent);
+    virtual ~KPtyPrivate();
+#ifndef HAVE_OPENPTY
     bool chownpty(bool grant);
+#endif
 
     int masterFd;
     int slaveFd;
+    bool ownMaster:1;
 
     QByteArray ttyName;
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gui//src/kptydevice.cpp	Sat Apr 09 00:23:46 2011 +0200
@@ -0,0 +1,614 @@
+/*
+
+   This file is part of the KDE libraries
+   Copyright (C) 2007 Oswald Buddenhagen <ossi@kde.org>
+   Copyright (C) 2010 KDE e.V. <kde-ev-board@kde.org>
+     Author Adriaan de Groot <groot@kde.org>
+
+   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 <config.h>
+//#include <config-pty.h>
+
+#define i18n
+
+#include <QtCore/QSocketNotifier>
+
+//#include <klocale.h>
+
+#include <unistd.h>
+#include <errno.h>
+#include <signal.h>
+#include <termios.h>
+#include <fcntl.h>
+#include <sys/ioctl.h>
+#ifdef HAVE_SYS_FILIO_H
+# include <sys/filio.h>
+#endif
+#ifdef HAVE_SYS_TIME_H
+# include <sys/time.h>
+#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
+
+#define KMAXINT ((int)(~0U >> 1))
+
+/////////////////////////////////////////////////////
+// Helper. Remove when QRingBuffer becomes public. //
+/////////////////////////////////////////////////////
+
+#include <QtCore/qbytearray.h>
+#include <QtCore/qlinkedlist.h>
+
+#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<QByteArray>::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<QByteArray> buffers;
+    int head, tail;
+    int totalSize;
+};
+
+//////////////////
+// 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)
+
+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;
+};
+
+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(i18n("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(i18n("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(i18n("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(i18n("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(i18n("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<qint64>(maxlen, KMAXINT));
+}
+
+// protected
+qint64 KPtyDevice::readLineData(char *data, qint64 maxlen)
+{
+    Q_D(KPtyDevice);
+    return d->readBuffer.readLine(data, (int)qMin<qint64>(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;
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gui//src/kptydevice.h	Sat Apr 09 00:23:46 2011 +0200
@@ -0,0 +1,156 @@
+/* This file is part of the KDE libraries
+
+    Copyright (C) 2007 Oswald Buddenhagen <ossi@kde.org>
+
+    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.h"
+
+#include <QtCore/QIODevice>
+
+struct KPtyDevicePrivate;
+
+#define Q_DECLARE_PRIVATE_MI(Class, SuperClass) \
+    inline Class##Private* d_func() { return reinterpret_cast<Class##Private *>(SuperClass::d_ptr); } \
+    inline const Class##Private* d_func() const { return reinterpret_cast<const Class##Private *>(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 { //krazy:exclude=dpointer (via macro)
+    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())
+};
+
+#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gui//src/kptyprocess.cpp	Sat Apr 09 00:23:46 2011 +0200
@@ -0,0 +1,138 @@
+/*
+
+    This file is part of the KDE libraries
+
+    Copyright (C) 2007 Oswald Buddenhagen <ossi@kde.org>
+
+    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_p.h"
+
+//#include <kuser.h>
+#include "kptydevice.h"
+
+#include <stdlib.h>
+#include <unistd.h>
+
+//////////////////
+// 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;
+};
+
+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 (d->addUtmp)
+      d->pty->login(getenv("USER"), getenv("DISPLAY"));
+      //d->pty->login(KUser(KUser::UseRealUserID).loginName().toLocal8Bit().data(), qgetenv("DISPLAY"));
+    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();
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gui//src/kptyprocess.h	Sat Apr 09 00:23:46 2011 +0200
@@ -0,0 +1,138 @@
+/*
+    This file is part of the KDE libraries
+
+    Copyright (C) 2007 Oswald Buddenhagen <ossi@kde.org>
+
+    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 "kpty_export.h"
+
+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 <ossi@kde.org>
+ */
+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);
+
+    /**
+     * 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))
+};
+
+Q_DECLARE_OPERATORS_FOR_FLAGS(KPtyProcess::PtyChannels)
+
+#endif