diff options
author | adelcastillo <adelcastillo@us.es> | 2009-10-23 17:45:58 +0000 |
---|---|---|
committer | adelcastillo <adelcastillo@us.es> | 2009-10-23 17:45:58 +0000 |
commit | dd11f859bf6684574adef1b34f21234059cd080d (patch) | |
tree | b3f07581c0f1b982de6cfa34d502f6b074f70146 /client/browser | |
parent | 4395836393cc3a4d448cf1449d239e72df5af62f (diff) |
Ahora el browser tiene consola en vez del output.
Pasado todo el sistema de compilacion a cmake.
git-svn-id: https://opengnsys.es/svn/trunk@408 a21b9725-9963-47de-94b9-378ad31fedc9
Diffstat (limited to 'client/browser')
62 files changed, 13954 insertions, 4 deletions
diff --git a/client/browser/CMakeLists.txt b/client/browser/CMakeLists.txt new file mode 100644 index 00000000..815123ca --- /dev/null +++ b/client/browser/CMakeLists.txt @@ -0,0 +1,17 @@ +project(browser) + +cmake_minimum_required(VERSION 2.6) + +find_package(Qt4 REQUIRED) + +include_directories(qtermwidget/src/ ${QT_INCLUDES} ${QT_QTWEBKIT_INCLUDE_DIR} ${CMAKE_CURRENT_BINARY_DIR}) + +add_subdirectory(qtermwidget) + +set(browser_SRCS main.cpp mainwindow.cpp) + +qt4_automoc(${browser_SRCS}) + +add_executable(browser ${browser_SRCS}) + +target_link_libraries(browser qtermwidget ${QT_LIBRARIES} ${QT_QTWEBKIT_LIBRARIES} ) diff --git a/client/browser/main.cpp b/client/browser/main.cpp new file mode 100644 index 00000000..d1873ce3 --- /dev/null +++ b/client/browser/main.cpp @@ -0,0 +1,17 @@ +#include <QtGui/QApplication> +#include <stdio.h> +#include "mainwindow.h" + +int main(int argc, char *argv[]) +{ + if(argc<=1) + { + printf("Usage: %s http://siteweb.com/\n",argv[0]); + return -1; + } + + QApplication a(argc, argv); + MainWindow w; + w.show(); + return a.exec(); +} diff --git a/client/browser/mainwindow.cpp b/client/browser/mainwindow.cpp new file mode 100644 index 00000000..d22bff34 --- /dev/null +++ b/client/browser/mainwindow.cpp @@ -0,0 +1,272 @@ +#include "mainwindow.h" +#include "mainwindow.moc" +#include <QtWebKit> +#include <QStringList> +#include <QWebView> +#include <QDockWidget> +#include <QtDebug> +#include <QWebPage> +#include <QProcess> +#include <QTextEdit> +#include <QMessageBox> +#include <QPushButton> +#include <QDateTime> + +#include "qtermwidget.h" + +#define BUFFERSIZE 2048 + +#define CURRENT_TIME() QDateTime::currentDateTime().toString("dd/MM/yy hh:mm:ss") + +MainWindow::MainWindow(QWidget *parent) + : QMainWindow(parent),web(new QWebView()),text(new QTextEdit()), + process(new QProcess(this)), + logfile(NULL),logstream(NULL) +{ + // Graphic + setCentralWidget(web); + + dock=new QDockWidget(this); + dock->setAllowedAreas(Qt::BottomDockWidgetArea); + dock->setFeatures(QDockWidget::NoDockWidgetFeatures); + + console = new QTermWidget(); + + QFont font = QApplication::font(); + font.setFamily("Terminus"); + font.setPointSize(12); + + console->setTerminalFont(font); + + //console->setColorScheme(COLOR_SCHEME_BLACK_ON_LIGHT_YELLOW); + console->setScrollBarPosition(QTermWidget::ScrollBarRight); + + //showFullScreen(); + + dock->setWidget(console); + addDockWidget(Qt::BottomDockWidgetArea,dock); + + text->setReadOnly(true); + + web->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks); + + // Web signals + connect(web->page(),SIGNAL(linkClicked(const QUrl&)),this, + SLOT(slotLinkHandle(const QUrl&))); + connect(web,SIGNAL(loadStarted()),this,SLOT(slotWebLoadStarted())); + connect(web,SIGNAL(loadFinished(bool)),this,SLOT(slotWebLoadFinished(bool))); + connect(web,SIGNAL(loadProgress(int)),this,SLOT(slotWebLoadProgress(int))); + + QStringList arguments=QCoreApplication::arguments(); + web->load(QUrl(arguments[1])); + + + // Process signals + connect(process,SIGNAL(started()),this,SLOT(slotProcessStarted())); + connect(process,SIGNAL(finished(int,QProcess::ExitStatus)), + this,SLOT(slotProcessFinished(int,QProcess::ExitStatus))); + + connect(process,SIGNAL(error(QProcess::ProcessError)), + this,SLOT(slotProcessError(QProcess::ProcessError))); + + connect(process,SIGNAL(readyReadStandardOutput()),this,SLOT(slotProcessOutput())); + connect(process,SIGNAL(readyReadStandardError()), + this,SLOT(slotProcessErrorOutput())); + + // Set tittle + setWindowTitle(tr("OpenGNSys Browser")); + + if(!readEnvironmentValues()) + text->insertPlainText(tr("Any environment variable/s didn't be setted\n")); + + if(env.contains("OGLOGFILE") && env["OGLOGFILE"]!="") + { + logfile=new QFile(env["OGLOGFILE"]); + if(!logfile->open(QIODevice::WriteOnly | QIODevice::Text | + QIODevice::Append)) + { + text->insertPlainText(tr("The log file couldn't be opened: ")+logfile->fileName()); + delete logfile; + logfile=NULL; + } + else + logstream=new QTextStream(logfile); + } +} + +MainWindow::~MainWindow() +{ + if(logfile) + { + logfile->close(); + delete logfile; + } + if(logstream) + delete logstream; +} + +void MainWindow::slotLinkHandle(const QUrl &url) +{ + QString string = url.toString(); + qDebug() << string; + // Si es un link del tipo PROTOCOL lo ejecutamos + if(string.startsWith(PROTOCOL)) + { + string=string.remove(0,QString(PROTOCOL).length()); + QStringList list=string.split(" ",QString::SkipEmptyParts); + QString command=list.takeFirst(); + process->setReadChannel(QProcess::StandardOutput); + // Le ponemos el mismo entorno que tiene el browser ahora mismo + process->setEnvironment(QProcess::systemEnvironment()); + process->start(command,list); + } + else + { + qDebug() << "Load URL: " << url <<endl; + web->load(url); + } +} + +void MainWindow::slotWebLoadStarted() +{ + qDebug()<<"Empieza la carga de la web"; +} + +void MainWindow::slotWebLoadProgress(int progress) +{ + qDebug()<<"Progress "<<progress; +} + +void MainWindow::slotWebLoadFinished(bool ok) +{ + // If any error ocurred, show a pop up + // Sometimes when the url hasn't got a dot, i.e /var/www/pageweb, + // the return value is always true so we check the bytes received too + if(ok == false || web->page()->totalBytes() == 0) + { + qDebug()<<"Error accediendo a la web"; + QMessageBox msgBox; + msgBox.setText(tr("The web page couldn't load. What do you want to do?")); + + QPushButton *reloadButton = msgBox.addButton(tr("Reload"), QMessageBox::ActionRole); + msgBox.addButton(QMessageBox::Abort); + + msgBox.exec(); + + if (msgBox.clickedButton() == reloadButton) + { + web->reload(); + } + else + { + close(); + } + } + else + qDebug()<<"Descarga finalizada satisfactoriamente"; +} + +void MainWindow::slotProcessStarted() +{ + qDebug()<<"Proceso inicializado"<<endl; +} + +void MainWindow::slotProcessOutput() +{ + qDebug()<<"Output"<<endl; + process->setReadChannel(QProcess::StandardOutput); + char buf[BUFFERSIZE]; + while((process->readLine(buf,BUFFERSIZE) > 0)) + { + text->insertPlainText(buf); + /* + QString str="<b>"; + str+=buf; + str+="</b>"; + text->insertHtml(str); + */ + output<<buf; + if(logstream) + *logstream<<CURRENT_TIME()<<": "<<buf; + } +} + +void MainWindow::slotProcessErrorOutput() +{ + qDebug()<<"ErrorOutput"<<endl; + process->setReadChannel(QProcess::StandardError); + char buf[BUFFERSIZE]; + while((process->readLine(buf,BUFFERSIZE) > 0)) + { + text->insertPlainText(buf); + errors<<buf; + } +} + +void MainWindow::slotProcessFinished(int code,QProcess::ExitStatus status) +{ + if(status==QProcess::NormalExit) + { + qDebug()<<"Finished: "<<code<<" "<<status<<endl; + qDebug()<<"OUTPUT:"<<endl<<output<<endl<<"ERROR:"<<endl<<errors<<endl; + } + else + { + qDebug()<<"Ha petado"<<endl; + qDebug()<<"Finished: "<<code<<" "<<status<<endl; + qDebug()<<"OUTPUT:"<<endl<<output<<endl<<"ERROR:"<<endl<<errors<<endl; + } +} + +void MainWindow::slotProcessError(QProcess::ProcessError error) +{ + switch(error) + { + case QProcess::FailedToStart: + qDebug()<<"Imposible arrancar el programa"<<endl; + break; + // No capturo crashed porque la pillo por finished + case QProcess::Crashed: + case QProcess::Timedout: + case QProcess::WriteError: + case QProcess::ReadError: + case QProcess::UnknownError: + default: + qDebug()<<"Otro error"<<endl; + break; + } +} + +int MainWindow::readEnvironmentValues() +{ + // The return value + int ret=true; + + // Get all environment variables + QStringList environmentlist=QProcess::systemEnvironment(); + // This is the list of the important variables + QStringList variablelist=QString(ENVIRONMENT).split(","); + + // This is an auxiliar variable + QStringList stringlist; + + foreach (QString str,variablelist) + { + // Look for the variable in the environment + stringlist=environmentlist.filter(str+"="); + + if(stringlist.isEmpty()) + { + env[str]=""; + ret=false; + } + else + { + // Get the first element and get the value part + env[str]=(stringlist.first().split("="))[1]; + } + } + + return ret; +} + diff --git a/client/browser/mainwindow.h b/client/browser/mainwindow.h new file mode 100644 index 00000000..b51de988 --- /dev/null +++ b/client/browser/mainwindow.h @@ -0,0 +1,67 @@ +#ifndef MAINWINDOW_H +#define MAINWINDOW_H + +#define PROTOCOL "command:" +#define ENVIRONMENT "OGLOGFILE" +//#define ENVIRONMENT "OGIP,OGSERVER,OGLOG" + +#include <QWidget> +#include <QProcess> +#include <QMap> +#include <QMainWindow> + +class QWebView; +class QTextEdit; +class QVBoxLayout; +class QProcess; +class QStringList; +class QString; +class QUrl; +class QFile; +class QTextStream; +class QDockWidget; +class QTermWidget; + +class MainWindow : public QMainWindow +{ + Q_OBJECT + + public: + MainWindow(QWidget *parent = 0); + ~MainWindow(); + + public slots: + // Funcion que maneja los links + void slotLinkHandle(const QUrl& url); + void slotWebLoadStarted(); + void slotWebLoadFinished(bool ok); + void slotWebLoadProgress(int progress); + + // Funciones que manejan cada vez que el proceso hace algo + void slotProcessStarted(); + void slotProcessFinished(int code,QProcess::ExitStatus status); + void slotProcessError(QProcess::ProcessError error); + void slotProcessOutput(); + void slotProcessErrorOutput(); + + //Functions + protected: + int readEnvironmentValues(); + + + protected: + QWebView *web; + QTextEdit *text; + QDockWidget *dock; + QTermWidget *console; + + QProcess *process; + QStringList output; + QStringList errors; + + QMap<QString,QString> env; + QFile *logfile; + QTextStream *logstream; +}; + +#endif // MAINWINDOW_H diff --git a/client/browser/qtermwidget/CMakeLists.txt b/client/browser/qtermwidget/CMakeLists.txt new file mode 100644 index 00000000..8cb94542 --- /dev/null +++ b/client/browser/qtermwidget/CMakeLists.txt @@ -0,0 +1,9 @@ +add_definitions(-DHAVE_POSIX_OPENPT) + +aux_source_directory(src qtermwidget_SRCS) + +include_directories(${CMAKE_CURRENT_BINARY_DIR}) + +qt4_automoc(${qtermwidget_SRCS}) + +add_library(qtermwidget STATIC ${qtermwidget_SRCS}) diff --git a/client/browser/qtermwidget/Changelog b/client/browser/qtermwidget/Changelog new file mode 100644 index 00000000..291a3ff9 --- /dev/null +++ b/client/browser/qtermwidget/Changelog @@ -0,0 +1,19 @@ +31.07.2008 +Interface class from c-style conversions rewritten with pimpl support. + + +16.07.2008 +Added optional scrollbar + + +06.06.2008 +Some artefacts were removed, some added... +Also added support for color schemes, and 3 color schemes provided (classical - white on black, green on black, black on light yellow). Is it enough or not? + + +26.05.2008 +Added file release as an archive with source code. But preferrable way is still getting code from CVS, cause file release can be outdated. + + +11.05.2008 +Initial CVS import - first version comes with number 0.0.1
\ No newline at end of file diff --git a/client/browser/qtermwidget/README b/client/browser/qtermwidget/README index 5d7c1472..0d3228f2 100644 --- a/client/browser/qtermwidget/README +++ b/client/browser/qtermwidget/README @@ -1,10 +1,8 @@ -This is a external source gotten it from: +This is a external source gotten from: http://www.qt-apps.org/content/show.php/QTermWidget?content=82832 -Only library and headers needed. Compile with QtEmbedded-4.5.1. - -********************************************************************************** +************************************************************************************* QTermWidget version 0.1.0 diff --git a/client/browser/qtermwidget/TODO b/client/browser/qtermwidget/TODO new file mode 100644 index 00000000..c3cb62ca --- /dev/null +++ b/client/browser/qtermwidget/TODO @@ -0,0 +1,10 @@ +Global + - provide more compatibility for vttest + +Package + - migrate to autotools if needed + +Source + - provide more options for customization + - clean unused code + - add some QT3 support features if needed diff --git a/client/browser/qtermwidget/lib/libqtermwidget.a b/client/browser/qtermwidget/lib/libqtermwidget.a Binary files differdeleted file mode 100644 index 48052b57..00000000 --- a/client/browser/qtermwidget/lib/libqtermwidget.a +++ /dev/null diff --git a/client/browser/qtermwidget/lib/libqtermwidget_d.a b/client/browser/qtermwidget/lib/libqtermwidget_d.a Binary files differdeleted file mode 100644 index ab31e1b0..00000000 --- a/client/browser/qtermwidget/lib/libqtermwidget_d.a +++ /dev/null diff --git a/client/browser/qtermwidget/src/BlockArray.cpp b/client/browser/qtermwidget/src/BlockArray.cpp new file mode 100644 index 00000000..39ef499a --- /dev/null +++ b/client/browser/qtermwidget/src/BlockArray.cpp @@ -0,0 +1,337 @@ +/* + 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 + + 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 "BlockArray.h" + +#include <QtCore> + +// System +#include <assert.h> +#include <sys/mman.h> +#include <sys/param.h> +#include <unistd.h> +#include <stdio.h> + + +using namespace Konsole; + +static int blocksize = 0; + +BlockArray::BlockArray() + : size(0), + current(size_t(-1)), + index(size_t(-1)), + lastmap(0), + lastmap_index(size_t(-1)), + lastblock(0), ion(-1), + length(0) +{ + // lastmap_index = index = current = size_t(-1); + if (blocksize == 0) + blocksize = ((sizeof(Block) / getpagesize()) + 1) * getpagesize(); + +} + +BlockArray::~BlockArray() +{ + setHistorySize(0); + assert(!lastblock); +} + +size_t BlockArray::append(Block *block) +{ + if (!size) + return size_t(-1); + + ++current; + 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 = write(ion, block, blocksize); if (rc < 0) { perror("HistoryBuffer::add.write"); setHistorySize(0); return size_t(-1); } + + length++; + if (length > size) length = size; + + ++index; + + delete block; + return current; +} + +size_t BlockArray::newBlock() +{ + if (!size) + return size_t(-1); + append(lastblock); + + lastblock = new Block(); + return index + 1; +} + +Block *BlockArray::lastBlock() const +{ + return lastblock; +} + +bool BlockArray::has(size_t i) const +{ + if (i == index + 1) + return true; + + if (i > index) + return false; + if (index - i >= length) + return false; + return true; +} + +const Block* BlockArray::at(size_t i) +{ + if (i == index + 1) + return lastblock; + + if (i == lastmap_index) + return lastmap; + + if (i > index) { + qDebug() << "BlockArray::at() i > index\n"; + return 0; + } + +// if (index - i >= length) { +// kDebug(1211) << "BlockArray::at() index - i >= length\n"; +// return 0; +// } + + size_t j = i; // (current - (index - i) + (index/size+1)*size) % size ; + + assert(j < size); + unmap(); + + Block *block = (Block*)mmap(0, blocksize, PROT_READ, MAP_PRIVATE, ion, j * blocksize); + + if (block == (Block*)-1) { perror("mmap"); return 0; } + + lastmap = block; + lastmap_index = i; + + return block; +} + +void BlockArray::unmap() +{ + if (lastmap) { + int res = munmap((char*)lastmap, blocksize); + if (res < 0) perror("munmap"); + } + lastmap = 0; + lastmap_index = size_t(-1); +} + +bool BlockArray::setSize(size_t newsize) +{ + return setHistorySize(newsize * 1024 / blocksize); +} + +bool BlockArray::setHistorySize(size_t newsize) +{ +// kDebug(1211) << "setHistorySize " << size << " " << newsize; + + if (size == newsize) + return false; + + unmap(); + + if (!newsize) { + delete lastblock; + lastblock = 0; + if (ion >= 0) close(ion); + ion = -1; + current = size_t(-1); + return true; + } + + if (!size) { + FILE* tmp = tmpfile(); + if (!tmp) { + perror("konsole: cannot open temp file.\n"); + } else { + ion = dup(fileno(tmp)); + if (ion<0) { + perror("konsole: cannot dup temp file.\n"); + fclose(tmp); + } + } + if (ion < 0) + return false; + + assert(!lastblock); + + lastblock = new Block(); + size = newsize; + return false; + } + + if (newsize > size) { + increaseBuffer(); + size = newsize; + return false; + } else { + decreaseBuffer(newsize); + ftruncate(ion, length*blocksize); + size = newsize; + + return true; + } +} + +void moveBlock(FILE *fion, int cursor, int newpos, char *buffer2) +{ + int res = 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); + if (res) + perror("fseek"); + res = fwrite(buffer2, blocksize, 1, fion); + if (res != 1) + perror("fwrite"); + // printf("moving block %d to %d\n", cursor, newpos); +} + +void BlockArray::decreaseBuffer(size_t newsize) +{ + if (index < newsize) // still fits in whole + return; + + int offset = (current - (newsize - 1) + size) % size; + + if (!offset) + return; + + // The Block constructor could do somthing in future... + char *buffer1 = new char[blocksize]; + + FILE *fion = fdopen(dup(ion), "w+b"); + if (!fion) { + delete [] buffer1; + perror("fdopen/dup"); + return; + } + + int firstblock; + if (current <= newsize) { + firstblock = current + 1; + } else { + firstblock = 0; + } + + size_t oldpos; + for (size_t i = 0, cursor=firstblock; i < newsize; i++) { + oldpos = (size + cursor + offset) % size; + moveBlock(fion, oldpos, cursor, buffer1); + if (oldpos < newsize) { + cursor = oldpos; + } else + cursor++; + } + + current = newsize - 1; + length = newsize; + + delete [] buffer1; + + fclose(fion); + +} + +void BlockArray::increaseBuffer() +{ + if (index < size) // not even wrapped once + return; + + int offset = (current + size + 1) % size; + if (!offset) // no moving needed + return; + + // The Block constructor could do somthing in future... + char *buffer1 = new char[blocksize]; + char *buffer2 = new char[blocksize]; + + int runs = 1; + int bpr = size; // blocks per run + + if (size % offset == 0) { + bpr = size / offset; + runs = offset; + } + + FILE *fion = fdopen(dup(ion), "w+b"); + if (!fion) { + perror("fdopen/dup"); + delete [] buffer1; + delete [] buffer2; + return; + } + + int res; + for (int i = 0; i < runs; i++) + { + // free one block in chain + int firstblock = (offset + i) % size; + res = fseek(fion, firstblock * blocksize, SEEK_SET); + if (res) + perror("fseek"); + res = fread(buffer1, blocksize, 1, fion); + if (res != 1) + perror("fread"); + int newpos = 0; + for (int j = 1, cursor=firstblock; j < bpr; j++) + { + cursor = (cursor + offset) % size; + newpos = (cursor - offset + size) % size; + moveBlock(fion, cursor, newpos, buffer2); + } + res = fseek(fion, i * blocksize, SEEK_SET); + if (res) + perror("fseek"); + res = fwrite(buffer1, blocksize, 1, fion); + if (res != 1) + perror("fwrite"); + } + current = size - 1; + length = size; + + delete [] buffer1; + delete [] buffer2; + + fclose(fion); + +} + diff --git a/client/browser/qtermwidget/includes/BlockArray.h b/client/browser/qtermwidget/src/BlockArray.h index ca473889..ca473889 100644 --- a/client/browser/qtermwidget/includes/BlockArray.h +++ b/client/browser/qtermwidget/src/BlockArray.h diff --git a/client/browser/qtermwidget/includes/Character.h b/client/browser/qtermwidget/src/Character.h index 0978ce5d..0978ce5d 100644 --- a/client/browser/qtermwidget/includes/Character.h +++ b/client/browser/qtermwidget/src/Character.h diff --git a/client/browser/qtermwidget/includes/CharacterColor.h b/client/browser/qtermwidget/src/CharacterColor.h index 1b866740..1b866740 100644 --- a/client/browser/qtermwidget/includes/CharacterColor.h +++ b/client/browser/qtermwidget/src/CharacterColor.h diff --git a/client/browser/qtermwidget/includes/ColorTables.h b/client/browser/qtermwidget/src/ColorTables.h index 321d6db4..321d6db4 100644 --- a/client/browser/qtermwidget/includes/ColorTables.h +++ b/client/browser/qtermwidget/src/ColorTables.h diff --git a/client/browser/qtermwidget/includes/DefaultTranslatorText.h b/client/browser/qtermwidget/src/DefaultTranslatorText.h index e47417c5..e47417c5 100644 --- a/client/browser/qtermwidget/includes/DefaultTranslatorText.h +++ b/client/browser/qtermwidget/src/DefaultTranslatorText.h diff --git a/client/browser/qtermwidget/src/Emulation.cpp b/client/browser/qtermwidget/src/Emulation.cpp new file mode 100644 index 00000000..6db1b29d --- /dev/null +++ b/client/browser/qtermwidget/src/Emulation.cpp @@ -0,0 +1,544 @@ +/* + 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 + + 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 "Emulation.h" +#include "Emulation.moc" + +// System +#include <assert.h> +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> + +// Qt +#include <QtGui/QApplication> +#include <QtGui/QClipboard> +#include <QtCore/QHash> +#include <QtGui/QKeyEvent> +#include <QtCore/QRegExp> +#include <QtCore/QTextStream> +#include <QtCore/QThread> + +#include <QtCore/QTime> + +// Konsole +#include "KeyboardTranslator.h" +#include "Screen.h" +#include "TerminalCharacterDecoder.h" +#include "ScreenWindow.h" + +using namespace Konsole; + +/* ------------------------------------------------------------------------- */ +/* */ +/* Emulation */ +/* */ +/* ------------------------------------------------------------------------- */ + +//#define CNTL(c) ((c)-'@') + +/*! +*/ + +Emulation::Emulation() : + _currentScreen(0), + _codec(0), + _decoder(0), + _keyTranslator(0), + _usesMouse(false) +{ + + // create screens with a default size + _screen[0] = new Screen(40,80); + _screen[1] = new Screen(40,80); + _currentScreen = _screen[0]; + + QObject::connect(&_bulkTimer1, SIGNAL(timeout()), this, SLOT(showBulk()) ); + QObject::connect(&_bulkTimer2, SIGNAL(timeout()), this, SLOT(showBulk()) ); + + // listen for mouse status changes + connect( this , SIGNAL(programUsesMouseChanged(bool)) , + SLOT(usesMouseChanged(bool)) ); +} + +bool Emulation::programUsesMouse() const +{ + return _usesMouse; +} + +void Emulation::usesMouseChanged(bool usesMouse) +{ + _usesMouse = usesMouse; +} + +ScreenWindow* Emulation::createWindow() +{ + ScreenWindow* window = new ScreenWindow(); + window->setScreen(_currentScreen); + _windows << window; + + connect(window , SIGNAL(selectionChanged()), + this , SLOT(bufferedUpdate())); + + connect(this , SIGNAL(outputChanged()), + window , SLOT(notifyOutputChanged()) ); + return window; +} + +/*! +*/ + +Emulation::~Emulation() +{ + QListIterator<ScreenWindow*> windowIter(_windows); + + while (windowIter.hasNext()) + { + delete windowIter.next(); + } + + delete _screen[0]; + delete _screen[1]; + delete _decoder; +} + +/*! change between primary and alternate _screen +*/ + +void Emulation::setScreen(int n) +{ + Screen *old = _currentScreen; + _currentScreen = _screen[n&1]; + if (_currentScreen != old) + { + old->setBusySelecting(false); + + // tell all windows onto this emulation to switch to the newly active _screen + QListIterator<ScreenWindow*> windowIter(_windows); + while ( windowIter.hasNext() ) + { + windowIter.next()->setScreen(_currentScreen); + } + } +} + +void Emulation::clearHistory() +{ + _screen[0]->setScroll( _screen[0]->getScroll() , false ); +} +void Emulation::setHistory(const HistoryType& t) +{ + _screen[0]->setScroll(t); + + showBulk(); +} + +const HistoryType& Emulation::history() +{ + return _screen[0]->getScroll(); +} + +void Emulation::setCodec(const QTextCodec * qtc) +{ + Q_ASSERT( qtc ); + + _codec = qtc; + delete _decoder; + _decoder = _codec->makeDecoder(); + + emit useUtf8Request(utf8()); +} + +void Emulation::setCodec(EmulationCodec codec) +{ + if ( codec == Utf8Codec ) + setCodec( QTextCodec::codecForName("utf8") ); + else if ( codec == LocaleCodec ) + setCodec( QTextCodec::codecForLocale() ); +} + +void Emulation::setKeyBindings(const QString& name) +{ + _keyTranslator = KeyboardTranslatorManager::instance()->findTranslator(name); +} + +QString Emulation::keyBindings() +{ + return _keyTranslator->name(); +} + + +// Interpreting Codes --------------------------------------------------------- + +/* + This section deals with decoding the incoming character stream. + Decoding means here, that the stream is first separated into `tokens' + which are then mapped to a `meaning' provided as operations by the + `Screen' class. +*/ + +/*! +*/ + +void Emulation::receiveChar(int c) +// process application unicode input to terminal +// this is a trivial scanner +{ + c &= 0xff; + switch (c) + { + case '\b' : _currentScreen->BackSpace(); break; + case '\t' : _currentScreen->Tabulate(); break; + case '\n' : _currentScreen->NewLine(); break; + case '\r' : _currentScreen->Return(); break; + case 0x07 : emit stateSet(NOTIFYBELL); + break; + default : _currentScreen->ShowCharacter(c); break; + }; +} + +/* ------------------------------------------------------------------------- */ +/* */ +/* Keyboard Handling */ +/* */ +/* ------------------------------------------------------------------------- */ + +/*! +*/ + +void Emulation::sendKeyEvent( QKeyEvent* ev ) +{ + emit stateSet(NOTIFYNORMAL); + + if (!ev->text().isEmpty()) + { // A block of text + // Note that the text is proper unicode. + // We should do a conversion here, but since this + // routine will never be used, we simply emit plain ascii. + //emit sendBlock(ev->text().toAscii(),ev->text().length()); + emit sendData(ev->text().toUtf8(),ev->text().length()); + } +} + +void Emulation::sendString(const char*,int) +{ + // default implementation does nothing +} + +void Emulation::sendMouseEvent(int /*buttons*/, int /*column*/, int /*row*/, int /*eventType*/) +{ + // default implementation does nothing +} + +// Unblocking, Byte to Unicode translation --------------------------------- -- + +/* + We are doing code conversion from locale to unicode first. +TODO: Character composition from the old code. See #96536 +*/ + +void Emulation::receiveData(const char* text, int length) +{ + emit stateSet(NOTIFYACTIVITY); + + bufferedUpdate(); + + QString unicodeText = _decoder->toUnicode(text,length); + + //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(); + } + } +} + +//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. +// +//There is something about stopping the _decoder if "we get a control code halfway a multi-byte sequence" (see below) +//which hasn't been ported into the newer function (above). Hopefully someone who understands this better +//can find an alternative way of handling the check. + + +/*void Emulation::onRcvBlock(const char *s, int len) +{ + emit notifySessionState(NOTIFYACTIVITY); + + bufferedUpdate(); + for (int i = 0; i < len; i++) + { + + QString result = _decoder->toUnicode(&s[i],1); + int reslen = result.length(); + + // If we get a control code halfway a multi-byte sequence + // we flush the _decoder and continue with the control code. + if ((s[i] < 32) && (s[i] > 0)) + { + // Flush _decoder + while(!result.length()) + result = _decoder->toUnicode(&s[i],1); + reslen = 1; + result.resize(reslen); + result[0] = QChar(s[i]); + } + + for (int j = 0; j < reslen; j++) + { + if (result[j].characterategory() == QChar::Mark_NonSpacing) + _currentScreen->compose(result.mid(j,1)); + else + onRcvChar(result[j].unicode()); + } + if (s[i] == '\030') + { + if ((len-i-1 > 3) && (strncmp(s+i+1, "B00", 3) == 0)) + 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); +} + +int Emulation::lineCount() +{ + // 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(); + _bulkTimer2.stop(); + + emit outputChanged(); + + _currentScreen->resetScrolledLines(); + _currentScreen->resetDroppedLines(); +} + +void Emulation::bufferedUpdate() +{ + _bulkTimer1.setSingleShot(true); + _bulkTimer1.start(BULK_TIMEOUT1); + if (!_bulkTimer2.isActive()) + { + _bulkTimer2.setSingleShot(true); + _bulkTimer2.start(BULK_TIMEOUT2); + } +} + +char Emulation::getErase() 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 ); + + _screen[0]->resizeImage(lines,columns); + _screen[1]->resizeImage(lines,columns); + + emit imageSizeChanged(lines,columns); + + bufferedUpdate(); +} + +QSize Emulation::imageSize() +{ + return QSize(_currentScreen->getColumns(), _currentScreen->getLines()); +} + +ushort ExtendedCharTable::extendedCharHash(ushort* unicodePoints , ushort length) const +{ + ushort hash = 0; + for ( ushort i = 0 ; i < length ; i++ ) + { + hash = 31*hash + unicodePoints[i]; + } + return hash; +} +bool ExtendedCharTable::extendedCharMatch(ushort hash , ushort* unicodePoints , ushort length) const +{ + ushort* entry = extendedCharTable[hash]; + + // compare given length with stored sequence length ( given as the first ushort in the + // stored buffer ) + if ( entry == 0 || entry[0] != length ) + return false; + // if the lengths match, each character must be checked. the stored buffer starts at + // entry[1] + for ( int i = 0 ; i < length ; i++ ) + { + if ( entry[i+1] != unicodePoints[i] ) + return false; + } + return true; +} +ushort ExtendedCharTable::createExtendedChar(ushort* unicodePoints , ushort length) +{ + // look for this sequence of points in the table + ushort hash = extendedCharHash(unicodePoints,length); + + // check existing entry for match + while ( extendedCharTable.contains(hash) ) + { + if ( extendedCharMatch(hash,unicodePoints,length) ) + { + // this sequence already has an entry in the table, + // return its hash + return hash; + } + else + { + // if hash is already used by another, different sequence of unicode character + // points then try next hash + hash++; + } + } + + + // add the new sequence to the table and + // return that index + ushort* buffer = new ushort[length+1]; + buffer[0] = length; + for ( int i = 0 ; i < length ; i++ ) + buffer[i+1] = unicodePoints[i]; + + extendedCharTable.insert(hash,buffer); + + return hash; +} + +ushort* ExtendedCharTable::lookupExtendedChar(ushort hash , ushort& length) const +{ + // lookup index in table and if found, set the length + // argument and return a pointer to the character sequence + + ushort* buffer = extendedCharTable[hash]; + if ( buffer ) + { + length = buffer[0]; + return buffer+1; + } + else + { + length = 0; + return 0; + } +} + +ExtendedCharTable::ExtendedCharTable() +{ +} +ExtendedCharTable::~ExtendedCharTable() +{ + // free all allocated character buffers + QHashIterator<ushort,ushort*> iter(extendedCharTable); + while ( iter.hasNext() ) + { + iter.next(); + delete[] iter.value(); + } +} + +// global instance +ExtendedCharTable ExtendedCharTable::instance; + + +//#include "moc_Emulation.cpp" + diff --git a/client/browser/qtermwidget/includes/Emulation.h b/client/browser/qtermwidget/src/Emulation.h index 2782df7b..2782df7b 100644 --- a/client/browser/qtermwidget/includes/Emulation.h +++ b/client/browser/qtermwidget/src/Emulation.h diff --git a/client/browser/qtermwidget/includes/ExtendedDefaultTranslator.h b/client/browser/qtermwidget/src/ExtendedDefaultTranslator.h index 6403c729..6403c729 100644 --- a/client/browser/qtermwidget/includes/ExtendedDefaultTranslator.h +++ b/client/browser/qtermwidget/src/ExtendedDefaultTranslator.h diff --git a/client/browser/qtermwidget/src/Filter.cpp b/client/browser/qtermwidget/src/Filter.cpp new file mode 100644 index 00000000..d8d56138 --- /dev/null +++ b/client/browser/qtermwidget/src/Filter.cpp @@ -0,0 +1,564 @@ +/* + Copyright (C) 2007 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 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 "Filter.h" +#include "Filter.moc" + + +// System +#include <iostream> + +// Qt +#include <QtGui/QAction> +#include <QtGui/QApplication> +#include <QtGui/QClipboard> +#include <QtCore/QString> + +#include <QtCore/QSharedData> +#include <QtCore> + +// KDE +//#include <KLocale> +//#include <KRun> + +// Konsole +#include "TerminalCharacterDecoder.h" + +using namespace Konsole; + +FilterChain::~FilterChain() +{ + QMutableListIterator<Filter*> iter(*this); + + while ( iter.hasNext() ) + { + Filter* filter = iter.next(); + iter.remove(); + delete filter; + } +} + +void FilterChain::addFilter(Filter* filter) +{ + append(filter); +} +void FilterChain::removeFilter(Filter* filter) +{ + removeAll(filter); +} +bool FilterChain::containsFilter(Filter* filter) +{ + return contains(filter); +} +void FilterChain::reset() +{ + QListIterator<Filter*> iter(*this); + while (iter.hasNext()) + iter.next()->reset(); +} +void FilterChain::setBuffer(const QString* buffer , const QList<int>* linePositions) +{ + QListIterator<Filter*> iter(*this); + while (iter.hasNext()) + iter.next()->setBuffer(buffer,linePositions); +} +void FilterChain::process() +{ + QListIterator<Filter*> iter(*this); + while (iter.hasNext()) + iter.next()->process(); +} +void FilterChain::clear() +{ + QList<Filter*>::clear(); +} +Filter::HotSpot* FilterChain::hotSpotAt(int line , int column) const +{ + QListIterator<Filter*> iter(*this); + while (iter.hasNext()) + { + Filter* filter = iter.next(); + Filter::HotSpot* spot = filter->hotSpotAt(line,column); + if ( spot != 0 ) + { + return spot; + } + } + + return 0; +} + +QList<Filter::HotSpot*> FilterChain::hotSpots() const +{ + QList<Filter::HotSpot*> list; + QListIterator<Filter*> iter(*this); + while (iter.hasNext()) + { + Filter* filter = iter.next(); + list << filter->hotSpots(); + } + return list; +} +//QList<Filter::HotSpot*> FilterChain::hotSpotsAtLine(int line) const; + +TerminalImageFilterChain::TerminalImageFilterChain() +: _buffer(0) +, _linePositions(0) +{ +} + +TerminalImageFilterChain::~TerminalImageFilterChain() +{ + delete _buffer; + delete _linePositions; +} + +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>(); + setBuffer( newBuffer , newLinePositions ); + + // free the old buffers + delete _buffer; + delete _linePositions; + + _buffer = newBuffer; + _linePositions = newLinePositions; + + QTextStream lineStream(_buffer); + decoder.begin(&lineStream); + + for (int i=0 ; i < lines ; i++) + { + _linePositions->append(_buffer->length()); + decoder.decodeLine(image + i*columns,columns,LINE_DEFAULT); + + // pretend that each line ends with a newline character. + // this prevents a link that occurs at the end of one line + // being treated as part of a link that occurs at the start of the next line + // + // the downside is that links which are spread over more than one line are not + // highlighted. + // + // TODO - Use the "line wrapped" attribute associated with lines in a + // terminal image to avoid adding this imaginary character for wrapped + // lines + if ( !(lineProperties.value(i,LINE_DEFAULT) & LINE_WRAPPED) ) + lineStream << QChar('\n'); + } + decoder.end(); +// qDebug("%s %d", __FILE__, __LINE__); +} + +Filter::Filter() : +_linePositions(0), +_buffer(0) +{ +} + +Filter::~Filter() +{ + QListIterator<HotSpot*> iter(_hotspotList); + while (iter.hasNext()) + { + delete iter.next(); + } +} +void Filter::reset() +{ + _hotspots.clear(); + _hotspotList.clear(); +} + +void Filter::setBuffer(const QString* buffer , const QList<int>* linePositions) +{ + _buffer = buffer; + _linePositions = linePositions; +} + +void Filter::getLineColumn(int position , int& startLine , int& startColumn) +{ + Q_ASSERT( _linePositions ); + Q_ASSERT( _buffer ); + + + for (int i = 0 ; i < _linePositions->count() ; i++) + { + //kDebug() << "line position at " << i << " = " << _linePositions[i]; + 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); + return; + } + } +} + + +/*void Filter::addLine(const QString& text) +{ + _linePositions << _buffer.length(); + _buffer.append(text); +}*/ + +const QString* Filter::buffer() +{ + return _buffer; +} +Filter::HotSpot::~HotSpot() +{ +} +void Filter::addHotSpot(HotSpot* spot) +{ + _hotspotList << spot; + + for (int line = spot->startLine() ; line <= spot->endLine() ; line++) + { + _hotspots.insert(line,spot); + } +} +QList<Filter::HotSpot*> Filter::hotSpots() const +{ + return _hotspotList; +} +QList<Filter::HotSpot*> Filter::hotSpotsAtLine(int line) const +{ + return _hotspots.values(line); +} + +Filter::HotSpot* Filter::hotSpotAt(int line , int column) const +{ + QListIterator<HotSpot*> spotIter(_hotspots.values(line)); + + while (spotIter.hasNext()) + { + HotSpot* spot = spotIter.next(); + + if ( spot->startLine() == line && spot->startColumn() > column ) + continue; + if ( spot->endLine() == line && spot->endColumn() < column ) + continue; + + return spot; + } + + return 0; +} + +Filter::HotSpot::HotSpot(int startLine , int startColumn , int endLine , int endColumn) + : _startLine(startLine) + , _startColumn(startColumn) + , _endLine(endLine) + , _endColumn(endColumn) + , _type(NotSpecified) +{ +} +QString Filter::HotSpot::tooltip() const +{ + return QString(); +} +QList<QAction*> Filter::HotSpot::actions() +{ + return QList<QAction*>(); +} +int Filter::HotSpot::startLine() const +{ + return _startLine; +} +int Filter::HotSpot::endLine() const +{ + return _endLine; +} +int Filter::HotSpot::startColumn() const +{ + return _startColumn; +} +int Filter::HotSpot::endColumn() const +{ + return _endColumn; +} +Filter::HotSpot::Type Filter::HotSpot::type() const +{ + return _type; +} +void Filter::HotSpot::setType(Type type) +{ + _type = type; +} + +RegExpFilter::RegExpFilter() +{ +} + +RegExpFilter::HotSpot::HotSpot(int startLine,int startColumn,int endLine,int endColumn) + : Filter::HotSpot(startLine,startColumn,endLine,endColumn) +{ + setType(Marker); +} + +void RegExpFilter::HotSpot::activate(QObject*) +{ +} + +void RegExpFilter::HotSpot::setCapturedTexts(const QStringList& texts) +{ + _capturedTexts = texts; +} +QStringList RegExpFilter::HotSpot::capturedTexts() const +{ + return _capturedTexts; +} + +void RegExpFilter::setRegExp(const QRegExp& regExp) +{ + _searchText = regExp; +} +QRegExp RegExpFilter::regExp() const +{ + return _searchText; +} +/*void RegExpFilter::reset(int) +{ + _buffer = QString(); +}*/ +void RegExpFilter::process() +{ + int pos = 0; + const QString* text = buffer(); + + Q_ASSERT( text ); + + // ignore any regular expressions which match an empty string. + // otherwise the while loop below will run indefinitely + static const QString emptyString(""); + if ( _searchText.exactMatch(emptyString) ) + return; + + while(pos >= 0) + { + pos = _searchText.indexIn(*text,pos); + + 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()); + + addHotSpot( spot ); + pos += _searchText.matchedLength(); + + // if matchedLength == 0, the program will get stuck in an infinite loop + Q_ASSERT( _searchText.matchedLength() > 0 ); + } + } +} + +RegExpFilter::HotSpot* RegExpFilter::newHotSpot(int startLine,int startColumn, + int endLine,int endColumn) +{ + return new RegExpFilter::HotSpot(startLine,startColumn, + endLine,endColumn); +} +RegExpFilter::HotSpot* UrlFilter::newHotSpot(int startLine,int startColumn,int endLine, + int endColumn) +{ + return new UrlFilter::HotSpot(startLine,startColumn, + endLine,endColumn); +} +UrlFilter::HotSpot::HotSpot(int startLine,int startColumn,int endLine,int endColumn) +: RegExpFilter::HotSpot(startLine,startColumn,endLine,endColumn) +, _urlObject(new FilterObject(this)) +{ + setType(Link); +} +QString UrlFilter::HotSpot::tooltip() const +{ + QString url = capturedTexts().first(); + + const UrlType kind = urlType(); + + if ( kind == StandardUrl ) + return QString(); + else if ( kind == Email ) + return QString(); + else + return QString(); +} +UrlFilter::HotSpot::UrlType UrlFilter::HotSpot::urlType() const +{ + QString url = capturedTexts().first(); + + if ( FullUrlRegExp.exactMatch(url) ) + return StandardUrl; + else if ( EmailAddressRegExp.exactMatch(url) ) + return Email; + else + return Unknown; +} + +void UrlFilter::HotSpot::activate(QObject* object) +{ + QString url = capturedTexts().first(); + + const UrlType kind = urlType(); + + const QString& actionName = object ? object->objectName() : QString(); + + if ( actionName == "copy-action" ) + { + //kDebug() << "Copying url to clipboard:" << url; + + QApplication::clipboard()->setText(url); + return; + } + + if ( !object || actionName == "open-action" ) + { + if ( kind == StandardUrl ) + { + // if the URL path does not include the protocol ( eg. "www.kde.org" ) then + // prepend http:// ( eg. "www.kde.org" --> "http://www.kde.org" ) + if (!url.contains("://")) + { + url.prepend("http://"); + } + } + else if ( kind == Email ) + { + url.prepend("mailto:"); + } + +// new KRun(url,QApplication::activeWindow()); + } +} + +// Note: Altering these regular expressions can have a major effect on the performance of the filters +// used for finding URLs in the text, especially if they are very general and could match very long +// pieces of text. +// Please be careful when altering them. + +//regexp matches: +// full url: +// protocolname:// or www. followed by anything other than whitespaces, <, >, ' or ", and ends before whitespaces, <, >, ', ", ], !, comma and dot +const QRegExp UrlFilter::FullUrlRegExp("(www\\.(?!\\.)|[a-z][a-z0-9+.-]*://)[^\\s<>'\"]+[^!,\\.\\s<>'\"\\]]"); +// email address: +// [word chars, dots or dashes]@[word chars, dots or dashes].[word chars] +const QRegExp UrlFilter::EmailAddressRegExp("\\b(\\w|\\.|-)+@(\\w|\\.|-)+\\.\\w+\\b"); + +// matches full url or email address +const QRegExp UrlFilter::CompleteUrlRegExp('('+FullUrlRegExp.pattern()+'|'+ + EmailAddressRegExp.pattern()+')'); + +UrlFilter::UrlFilter() +{ + setRegExp( CompleteUrlRegExp ); +} +UrlFilter::HotSpot::~HotSpot() +{ + delete _urlObject; +} +void FilterObject::activated() +{ + _filter->activate(sender()); +} +QList<QAction*> UrlFilter::HotSpot::actions() +{ + QList<QAction*> list; + + const UrlType kind = urlType(); + + QAction* openAction = new QAction(_urlObject); + QAction* copyAction = new QAction(_urlObject);; + + Q_ASSERT( kind == StandardUrl || kind == Email ); + + if ( kind == StandardUrl ) + { + openAction->setText(("Open Link")); + copyAction->setText(("Copy Link Address")); + } + else if ( kind == Email ) + { + openAction->setText(("Send Email To...")); + copyAction->setText(("Copy Email Address")); + } + + // 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"); + + QObject::connect( openAction , SIGNAL(triggered()) , _urlObject , SLOT(activated()) ); + QObject::connect( copyAction , SIGNAL(triggered()) , _urlObject , SLOT(activated()) ); + + list << openAction; + list << copyAction; + + return list; +} + +//#include "moc_Filter.cpp" diff --git a/client/browser/qtermwidget/includes/Filter.h b/client/browser/qtermwidget/src/Filter.h index 06ea5e35..06ea5e35 100644 --- a/client/browser/qtermwidget/includes/Filter.h +++ b/client/browser/qtermwidget/src/Filter.h diff --git a/client/browser/qtermwidget/src/History.cpp b/client/browser/qtermwidget/src/History.cpp new file mode 100644 index 00000000..1e3d7217 --- /dev/null +++ b/client/browser/qtermwidget/src/History.cpp @@ -0,0 +1,698 @@ +/* + 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 + + 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 "History.h" + +// System +#include <iostream> +#include <stdlib.h> +#include <assert.h> +#include <stdio.h> +#include <sys/types.h> +#include <sys/mman.h> +#include <unistd.h> +#include <errno.h> + + +// Reasonable line size +#define LINE_SIZE 1024 + +using namespace Konsole; + +/* + An arbitrary long scroll. + + One can modify the scroll only by adding either cells + or newlines, but access it randomly. + + The model is that of an arbitrary wide typewriter scroll + in that the scroll is a serie of lines and each line is + a serie of cells with no overwriting permitted. + + The implementation provides arbitrary length and numbers + of cells and line/column indexed read access to the scroll + at constant costs. + +KDE4: Can we use QTemporaryFile here, instead of KTempFile? + +FIXME: some complain about the history buffer comsuming the + memory of their machines. This problem is critical + since the history does not behave gracefully in cases + where the memory is used up completely. + + I put in a workaround that should handle it problem + now gracefully. I'm not satisfied with the solution. + +FIXME: Terminating the history is not properly indicated + in the menu. We should throw a signal. + +FIXME: There is noticeable decrease in speed, also. Perhaps, + there whole feature needs to be revisited therefore. + Disadvantage of a more elaborated, say block-oriented + scheme with wrap around would be it's complexity. +*/ + +//FIXME: tempory replacement for tmpfile +// this is here one for debugging purpose. + +//#define tmpfile xTmpFile + +// History File /////////////////////////////////////////// + +/* + A Row(X) data type which allows adding elements to the end. +*/ + +HistoryFile::HistoryFile() + : ion(-1), + length(0), + fileMap(0) +{ + if (tmpFile.open()) + { + tmpFile.setAutoRemove(true); + ion = tmpFile.handle(); + } +} + +HistoryFile::~HistoryFile() +{ + if (fileMap) + unmap(); +} + +//TODO: Mapping the entire file in will cause problems if the history file becomes exceedingly large, +//(ie. larger than available memory). HistoryFile::map() should only map in sections of the file at a time, +//to avoid this. +void HistoryFile::map() +{ + assert( fileMap == 0 ); + + fileMap = (char*)mmap( 0 , length , PROT_READ , MAP_PRIVATE , ion , 0 ); + + //if mmap'ing fails, fall back to the read-lseek combination + if ( fileMap == MAP_FAILED ) + { + readWriteBalance = 0; + fileMap = 0; + qDebug() << ": mmap'ing history failed. errno = " << errno; + } +} + +void HistoryFile::unmap() +{ + int result = munmap( fileMap , length ); + assert( result == 0 ); + + fileMap = 0; +} + +bool HistoryFile::isMapped() +{ + return (fileMap != 0); +} + +void HistoryFile::add(const unsigned char* bytes, int len) +{ + if ( fileMap ) + unmap(); + + readWriteBalance++; + + int rc = 0; + + rc = lseek(ion,length,SEEK_SET); if (rc < 0) { perror("HistoryFile::add.seek"); return; } + rc = write(ion,bytes,len); if (rc < 0) { perror("HistoryFile::add.write"); return; } + length += rc; +} + +void HistoryFile::get(unsigned char* bytes, int len, int loc) +{ + //count number of get() calls vs. number of add() calls. + //If there are many more get() calls compared with add() + //calls (decided by using MAP_THRESHOLD) then mmap the log + //file to improve performance. + readWriteBalance--; + if ( !fileMap && readWriteBalance < MAP_THRESHOLD ) + map(); + + if ( fileMap ) + { + for (int i=0;i<len;i++) + bytes[i]=fileMap[loc+i]; + } + else + { + int rc = 0; + + if (loc < 0 || len < 0 || loc + len > length) + fprintf(stderr,"getHist(...,%d,%d): invalid args.\n",len,loc); + rc = lseek(ion,loc,SEEK_SET); if (rc < 0) { perror("HistoryFile::get.seek"); return; } + rc = read(ion,bytes,len); if (rc < 0) { perror("HistoryFile::get.read"); return; } + } +} + +int HistoryFile::len() +{ + return length; +} + + +// History Scroll abstract base class ////////////////////////////////////// + + +HistoryScroll::HistoryScroll(HistoryType* t) + : m_histType(t) +{ +} + +HistoryScroll::~HistoryScroll() +{ + delete m_histType; +} + +bool HistoryScroll::hasScroll() +{ + return true; +} + +// History Scroll File ////////////////////////////////////// + +/* + The history scroll makes a Row(Row(Cell)) from + two history buffers. The index buffer contains + start of line positions which refere to the cells + buffer. + + Note that index[0] addresses the second line + (line #1), while the first line (line #0) starts + at 0 in cells. +*/ + +HistoryScrollFile::HistoryScrollFile(const QString &logFileName) + : HistoryScroll(new HistoryTypeFile(logFileName)), + m_logFileName(logFileName) +{ +} + +HistoryScrollFile::~HistoryScrollFile() +{ +} + +int HistoryScrollFile::getLines() +{ + return index.len() / sizeof(int); +} + +int HistoryScrollFile::getLineLen(int lineno) +{ + return (startOfLine(lineno+1) - startOfLine(lineno)) / sizeof(Character); +} + +bool HistoryScrollFile::isWrappedLine(int lineno) +{ + if (lineno>=0 && lineno <= getLines()) { + unsigned char flag; + lineflags.get((unsigned char*)&flag,sizeof(unsigned char),(lineno)*sizeof(unsigned char)); + return flag; + } + return false; +} + +int HistoryScrollFile::startOfLine(int lineno) +{ + if (lineno <= 0) return 0; + if (lineno <= getLines()) + { + + if (!index.isMapped()) + index.map(); + + int res; + index.get((unsigned char*)&res,sizeof(int),(lineno-1)*sizeof(int)); + return res; + } + return cells.len(); +} + +void HistoryScrollFile::getCells(int lineno, int colno, int count, Character res[]) +{ + cells.get((unsigned char*)res,count*sizeof(Character),startOfLine(lineno)+colno*sizeof(Character)); +} + +void HistoryScrollFile::addCells(const Character text[], int count) +{ + cells.add((unsigned char*)text,count*sizeof(Character)); +} + +void HistoryScrollFile::addLine(bool previousWrapped) +{ + if (index.isMapped()) + index.unmap(); + + int locn = cells.len(); + index.add((unsigned char*)&locn,sizeof(int)); + unsigned char flags = previousWrapped ? 0x01 : 0x00; + lineflags.add((unsigned char*)&flags,sizeof(unsigned char)); +} + + +// History Scroll Buffer ////////////////////////////////////// +HistoryScrollBuffer::HistoryScrollBuffer(unsigned int maxLineCount) + : HistoryScroll(new HistoryTypeBuffer(maxLineCount)) + ,_historyBuffer() + ,_maxLineCount(0) + ,_usedLines(0) + ,_head(0) +{ + setMaxNbLines(maxLineCount); +} + +HistoryScrollBuffer::~HistoryScrollBuffer() +{ + delete[] _historyBuffer; +} + +void HistoryScrollBuffer::addCellsVector(const QVector<Character>& cells) +{ + _head++; + if ( _usedLines < _maxLineCount ) + _usedLines++; + + if ( _head >= _maxLineCount ) + { + _head = 0; + } + + _historyBuffer[bufferIndex(_usedLines-1)] = cells; + _wrappedLine[bufferIndex(_usedLines-1)] = false; +} +void HistoryScrollBuffer::addCells(const Character a[], int count) +{ + HistoryLine newLine(count); + qCopy(a,a+count,newLine.begin()); + + addCellsVector(newLine); +} + +void HistoryScrollBuffer::addLine(bool previousWrapped) +{ + _wrappedLine[bufferIndex(_usedLines-1)] = previousWrapped; +} + +int HistoryScrollBuffer::getLines() +{ + return _usedLines; +} + +int HistoryScrollBuffer::getLineLen(int lineNumber) +{ + Q_ASSERT( lineNumber >= 0 && lineNumber < _maxLineCount ); + + if ( lineNumber < _usedLines ) + { + return _historyBuffer[bufferIndex(lineNumber)].size(); + } + else + { + return 0; + } +} + +bool HistoryScrollBuffer::isWrappedLine(int lineNumber) +{ + Q_ASSERT( lineNumber >= 0 && lineNumber < _maxLineCount ); + + if (lineNumber < _usedLines) + { + //kDebug() << "Line" << lineNumber << "wrapped is" << _wrappedLine[bufferIndex(lineNumber)]; + return _wrappedLine[bufferIndex(lineNumber)]; + } + else + return false; +} + +void HistoryScrollBuffer::getCells(int lineNumber, int startColumn, int count, Character* buffer) +{ + if ( count == 0 ) return; + + Q_ASSERT( lineNumber < _maxLineCount ); + + if (lineNumber >= _usedLines) + { + memset(buffer, 0, count * sizeof(Character)); + return; + } + + const HistoryLine& line = _historyBuffer[bufferIndex(lineNumber)]; + + //kDebug() << "startCol " << startColumn; + //kDebug() << "line.size() " << line.size(); + //kDebug() << "count " << count; + + Q_ASSERT( startColumn <= line.size() - count ); + + memcpy(buffer, line.constData() + startColumn , count * sizeof(Character)); +} + +void HistoryScrollBuffer::setMaxNbLines(unsigned int lineCount) +{ + HistoryLine* oldBuffer = _historyBuffer; + HistoryLine* newBuffer = new HistoryLine[lineCount]; + + for ( int i = 0 ; i < qMin(_usedLines,(int)lineCount) ; i++ ) + { + newBuffer[i] = oldBuffer[bufferIndex(i)]; + } + + _usedLines = qMin(_usedLines,(int)lineCount); + _maxLineCount = lineCount; + _head = ( _usedLines == _maxLineCount ) ? 0 : _usedLines-1; + + _historyBuffer = newBuffer; + delete[] oldBuffer; + + _wrappedLine.resize(lineCount); +} + +int HistoryScrollBuffer::bufferIndex(int lineNumber) +{ + Q_ASSERT( lineNumber >= 0 ); + Q_ASSERT( lineNumber < _maxLineCount ); + Q_ASSERT( (_usedLines == _maxLineCount) || lineNumber <= _head ); + + if ( _usedLines == _maxLineCount ) + { + return (_head+lineNumber+1) % _maxLineCount; + } + else + { + return lineNumber; + } +} + + +// History Scroll None ////////////////////////////////////// + +HistoryScrollNone::HistoryScrollNone() + : HistoryScroll(new HistoryTypeNone()) +{ +} + +HistoryScrollNone::~HistoryScrollNone() +{ +} + +bool HistoryScrollNone::hasScroll() +{ + return false; +} + +int HistoryScrollNone::getLines() +{ + return 0; +} + +int HistoryScrollNone::getLineLen(int) +{ + return 0; +} + +bool HistoryScrollNone::isWrappedLine(int /*lineno*/) +{ + return false; +} + +void HistoryScrollNone::getCells(int, int, int, Character []) +{ +} + +void HistoryScrollNone::addCells(const Character [], int) +{ +} + +void HistoryScrollNone::addLine(bool) +{ +} + +// History Scroll BlockArray ////////////////////////////////////// + +HistoryScrollBlockArray::HistoryScrollBlockArray(size_t size) + : HistoryScroll(new HistoryTypeBlockArray(size)) +{ + m_blockArray.setHistorySize(size); // nb. of lines. +} + +HistoryScrollBlockArray::~HistoryScrollBlockArray() +{ +} + +int HistoryScrollBlockArray::getLines() +{ + return m_lineLengths.count(); +} + +int HistoryScrollBlockArray::getLineLen(int lineno) +{ + if ( m_lineLengths.contains(lineno) ) + return m_lineLengths[lineno]; + else + return 0; +} + +bool HistoryScrollBlockArray::isWrappedLine(int /*lineno*/) +{ + return false; +} + +void HistoryScrollBlockArray::getCells(int lineno, int colno, + int count, Character res[]) +{ + if (!count) return; + + const Block *b = m_blockArray.at(lineno); + + if (!b) { + memset(res, 0, count * sizeof(Character)); // still better than random data + return; + } + + assert(((colno + count) * sizeof(Character)) < ENTRIES); + memcpy(res, b->data + (colno * sizeof(Character)), count * sizeof(Character)); +} + +void HistoryScrollBlockArray::addCells(const Character a[], int count) +{ + Block *b = m_blockArray.lastBlock(); + + if (!b) return; + + // put cells in block's data + assert((count * sizeof(Character)) < ENTRIES); + + memset(b->data, 0, ENTRIES); + + memcpy(b->data, a, count * sizeof(Character)); + b->size = count * sizeof(Character); + + size_t res = m_blockArray.newBlock(); + assert (res > 0); + Q_UNUSED( res ); + + m_lineLengths.insert(m_blockArray.getCurrent(), count); +} + +void HistoryScrollBlockArray::addLine(bool) +{ +} + +////////////////////////////////////////////////////////////////////// +// History Types +////////////////////////////////////////////////////////////////////// + +HistoryType::HistoryType() +{ +} + +HistoryType::~HistoryType() +{ +} + +////////////////////////////// + +HistoryTypeNone::HistoryTypeNone() +{ +} + +bool HistoryTypeNone::isEnabled() const +{ + return false; +} + +HistoryScroll* HistoryTypeNone::scroll(HistoryScroll *old) const +{ + delete old; + return new HistoryScrollNone(); +} + +int HistoryTypeNone::maximumLineCount() const +{ + return 0; +} + +////////////////////////////// + +HistoryTypeBlockArray::HistoryTypeBlockArray(size_t size) + : m_size(size) +{ +} + +bool HistoryTypeBlockArray::isEnabled() const +{ + return true; +} + +int HistoryTypeBlockArray::maximumLineCount() const +{ + return m_size; +} + +HistoryScroll* HistoryTypeBlockArray::scroll(HistoryScroll *old) const +{ + delete old; + return new HistoryScrollBlockArray(m_size); +} + + +////////////////////////////// + +HistoryTypeBuffer::HistoryTypeBuffer(unsigned int nbLines) + : m_nbLines(nbLines) +{ +} + +bool HistoryTypeBuffer::isEnabled() const +{ + return true; +} + +int HistoryTypeBuffer::maximumLineCount() const +{ + return m_nbLines; +} + +HistoryScroll* HistoryTypeBuffer::scroll(HistoryScroll *old) const +{ + if (old) + { + HistoryScrollBuffer *oldBuffer = dynamic_cast<HistoryScrollBuffer*>(old); + if (oldBuffer) + { + oldBuffer->setMaxNbLines(m_nbLines); + return oldBuffer; + } + + HistoryScroll *newScroll = new HistoryScrollBuffer(m_nbLines); + int lines = old->getLines(); + int startLine = 0; + if (lines > (int) m_nbLines) + startLine = lines - m_nbLines; + + Character line[LINE_SIZE]; + for(int i = startLine; i < lines; i++) + { + int size = old->getLineLen(i); + if (size > LINE_SIZE) + { + Character *tmp_line = new Character[size]; + old->getCells(i, 0, size, tmp_line); + newScroll->addCells(tmp_line, size); + newScroll->addLine(old->isWrappedLine(i)); + delete [] tmp_line; + } + else + { + old->getCells(i, 0, size, line); + newScroll->addCells(line, size); + newScroll->addLine(old->isWrappedLine(i)); + } + } + delete old; + return newScroll; + } + return new HistoryScrollBuffer(m_nbLines); +} + +////////////////////////////// + +HistoryTypeFile::HistoryTypeFile(const QString& fileName) + : m_fileName(fileName) +{ +} + +bool HistoryTypeFile::isEnabled() const +{ + return true; +} + +const QString& HistoryTypeFile::getFileName() const +{ + return m_fileName; +} + +HistoryScroll* HistoryTypeFile::scroll(HistoryScroll *old) const +{ + if (dynamic_cast<HistoryFile *>(old)) + return old; // Unchanged. + + HistoryScroll *newScroll = new HistoryScrollFile(m_fileName); + + Character line[LINE_SIZE]; + int lines = (old != 0) ? old->getLines() : 0; + for(int i = 0; i < lines; i++) + { + int size = old->getLineLen(i); + if (size > LINE_SIZE) + { + Character *tmp_line = new Character[size]; + old->getCells(i, 0, size, tmp_line); + newScroll->addCells(tmp_line, size); + newScroll->addLine(old->isWrappedLine(i)); + delete [] tmp_line; + } + else + { + old->getCells(i, 0, size, line); + newScroll->addCells(line, size); + newScroll->addLine(old->isWrappedLine(i)); + } + } + + delete old; + return newScroll; +} + +int HistoryTypeFile::maximumLineCount() const +{ + return 0; +} diff --git a/client/browser/qtermwidget/includes/History.h b/client/browser/qtermwidget/src/History.h index a26a367d..a26a367d 100644 --- a/client/browser/qtermwidget/includes/History.h +++ b/client/browser/qtermwidget/src/History.h diff --git a/client/browser/qtermwidget/src/KeyboardTranslator.cpp b/client/browser/qtermwidget/src/KeyboardTranslator.cpp new file mode 100644 index 00000000..1f7f112a --- /dev/null +++ b/client/browser/qtermwidget/src/KeyboardTranslator.cpp @@ -0,0 +1,903 @@ +/* + This source file was 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 + + 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 "KeyboardTranslator.h" + +// System +#include <ctype.h> +#include <stdio.h> + +// Qt +#include <QtCore/QBuffer> +//#include <KDebug> +#include <QtCore/QFile> +#include <QtCore/QFileInfo> +#include <QtCore> +#include <QtGui> + +// KDE +//#include <KDebug> +//#include <KLocale> +//#include <KStandardDirs> + +using namespace Konsole; + +//this is for default REALLY fallback translator. + +//const char* KeyboardTranslatorManager::defaultTranslatorText = +//#include "DefaultTranslatorText.h" +//; + +//and this is default now translator - default.keytab from original Konsole +const char* KeyboardTranslatorManager::defaultTranslatorText = +#include "ExtendedDefaultTranslator.h" +; + +KeyboardTranslatorManager::KeyboardTranslatorManager() + : _haveLoadedAll(false) +{ +} +KeyboardTranslatorManager::~KeyboardTranslatorManager() +{ + qDeleteAll(_translators.values()); +} +QString KeyboardTranslatorManager::findTranslatorPath(const QString& name) +{ + return QString("kb-layouts/" + name + ".keytab"); +} +void KeyboardTranslatorManager::findTranslators() +{ + 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); + // add the name of each translator to the list and associated + // the name with a null pointer to indicate that the translator + // has not yet been loaded from disk + QStringListIterator listIter(list); + while (listIter.hasNext()) + { + QString translatorPath = listIter.next(); + + QString name = QFileInfo(translatorPath).baseName(); + + if ( !_translators.contains(name) ) { + _translators.insert(name,0); + } + } + _haveLoadedAll = true; +} + +const KeyboardTranslator* KeyboardTranslatorManager::findTranslator(const QString& name) +{ + if ( name.isEmpty() ) + return defaultTranslator(); + +//here was smth wrong in original Konsole source + findTranslators(); + + 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; + + return translator; +} + +bool KeyboardTranslatorManager::saveTranslator(const KeyboardTranslator* translator) +{ + const QString path = ".keytab";// = KGlobal::dirs()->saveLocation("data","konsole/")+translator->name() +// +".keytab"; + + qDebug() << "Saving translator to" << path; + + QFile destination(path); + + if (!destination.open(QIODevice::WriteOnly | QIODevice::Text)) + { + qWarning() << "Unable to save keyboard translation:" + << destination.errorString(); + + return false; + } + + { + KeyboardTranslatorWriter writer(&destination); + writer.writeHeader(translator->description()); + + QListIterator<KeyboardTranslator::Entry> iter(translator->entries()); + while ( iter.hasNext() ) + writer.writeEntry(iter.next()); + } + + destination.close(); + + return true; +} + +KeyboardTranslator* KeyboardTranslatorManager::loadTranslator(const QString& name) +{ + const QString& path = findTranslatorPath(name); + + QFile source(path); + + if (name.isEmpty() || !source.open(QIODevice::ReadOnly | QIODevice::Text)) + return 0; + + return loadTranslator(&source,name); +} + +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"); +} + +KeyboardTranslator* KeyboardTranslatorManager::loadTranslator(QIODevice* source,const QString& name) +{ + KeyboardTranslator* translator = new KeyboardTranslator(name); + KeyboardTranslatorReader reader(source); + translator->setDescription( reader.description() ); + + while ( reader.hasNextEntry() ) { + translator->addEntry(reader.nextEntry()); + } + + source->close(); + + if ( !reader.parseError() ) + { + return translator; + } + else + { + delete translator; + return 0; + } +} + +KeyboardTranslatorWriter::KeyboardTranslatorWriter(QIODevice* destination) +: _destination(destination) +{ + Q_ASSERT( destination && destination->isWritable() ); + + _writer = new QTextStream(_destination); +} +KeyboardTranslatorWriter::~KeyboardTranslatorWriter() +{ + delete _writer; +} +void KeyboardTranslatorWriter::writeHeader( const QString& description ) +{ + *_writer << "keyboard \"" << description << '\"' << '\n'; +} +void KeyboardTranslatorWriter::writeEntry( const KeyboardTranslator::Entry& entry ) +{ + QString result; + + if ( entry.command() != KeyboardTranslator::NoCommand ) + result = entry.resultToString(); + else + result = '\"' + entry.resultToString() + '\"'; + + *_writer << "key " << entry.conditionToString() << " : " << result << '\n'; +} + + +// each line of the keyboard translation file is one of: +// +// - keyboard "name" +// - key KeySequence : "characters" +// - key KeySequence : CommandName +// +// KeySequence begins with the name of the key ( taken from the Qt::Key enum ) +// and is followed by the keyboard modifiers and state flags ( with + or - in front +// of each modifier or flag to indicate whether it is required ). All keyboard modifiers +// and flags are optional, if a particular modifier or state is not specified it is +// assumed not to be a part of the sequence. The key sequence may contain whitespace +// +// eg: "key Up+Shift : scrollLineUp" +// "key Next-Shift : "\E[6~" +// +// (lines containing only whitespace are ignored, parseLine assumes that comments have +// already been removed) +// + +KeyboardTranslatorReader::KeyboardTranslatorReader( QIODevice* source ) + : _source(source) + , _hasNext(false) +{ + // read input until we find the description + while ( _description.isEmpty() && !source->atEnd() ) + { + const QList<Token>& tokens = tokenize( QString(source->readLine()) ); + + if ( !tokens.isEmpty() && tokens.first().type == Token::TitleKeyword ) + { + _description = (tokens[1].text.toUtf8()); + } + } + + readNext(); +} +void KeyboardTranslatorReader::readNext() +{ + // find next entry + while ( !_source->atEnd() ) + { + const QList<Token>& tokens = tokenize( QString(_source->readLine()) ); + if ( !tokens.isEmpty() && tokens.first().type == Token::KeyKeyword ) + { + KeyboardTranslator::States flags = KeyboardTranslator::NoState; + KeyboardTranslator::States flagMask = KeyboardTranslator::NoState; + Qt::KeyboardModifiers modifiers = Qt::NoModifier; + Qt::KeyboardModifiers modifierMask = Qt::NoModifier; + + int keyCode = Qt::Key_unknown; + + decodeSequence(tokens[1].text.toLower(), + keyCode, + modifiers, + modifierMask, + flags, + flagMask); + + KeyboardTranslator::Command command = KeyboardTranslator::NoCommand; + QByteArray text; + + // get text or command + if ( tokens[2].type == Token::OutputText ) + { + text = tokens[2].text.toLocal8Bit(); + } + else if ( tokens[2].type == Token::Command ) + { + // identify command + if (!parseAsCommand(tokens[2].text,command)) + qWarning() << "Command" << tokens[2].text << "not understood."; + } + + KeyboardTranslator::Entry newEntry; + newEntry.setKeyCode( keyCode ); + newEntry.setState( flags ); + newEntry.setStateMask( flagMask ); + newEntry.setModifiers( modifiers ); + newEntry.setModifierMask( modifierMask ); + newEntry.setText( text ); + newEntry.setCommand( command ); + + _nextEntry = newEntry; + + _hasNext = true; + + return; + } + } + + _hasNext = false; +} + +bool KeyboardTranslatorReader::parseAsCommand(const QString& text,KeyboardTranslator::Command& command) +{ + 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 ) + command = KeyboardTranslator::ScrollPageDownCommand; + else if ( text.compare("scrolllineup",Qt::CaseInsensitive) == 0 ) + command = KeyboardTranslator::ScrollLineUpCommand; + else if ( text.compare("scrolllinedown",Qt::CaseInsensitive) == 0 ) + command = KeyboardTranslator::ScrollLineDownCommand; + else if ( text.compare("scrolllock",Qt::CaseInsensitive) == 0 ) + command = KeyboardTranslator::ScrollLockCommand; + else + return false; + + return true; +} + +bool KeyboardTranslatorReader::decodeSequence(const QString& text, + int& keyCode, + Qt::KeyboardModifiers& modifiers, + Qt::KeyboardModifiers& modifierMask, + KeyboardTranslator::States& flags, + KeyboardTranslator::States& flagMask) +{ + bool isWanted = true; + bool endOfItem = false; + QString buffer; + + Qt::KeyboardModifiers tempModifiers = modifiers; + Qt::KeyboardModifiers tempModifierMask = modifierMask; + KeyboardTranslator::States tempFlags = flags; + KeyboardTranslator::States tempFlagMask = flagMask; + + for ( int i = 0 ; i < text.count() ; i++ ) + { + const QChar& ch = text[i]; + bool isLastLetter = ( i == text.count()-1 ); + + endOfItem = true; + if ( ch.isLetterOrNumber() ) + { + endOfItem = false; + buffer.append(ch); + } + + if ( (endOfItem || isLastLetter) && !buffer.isEmpty() ) + { + Qt::KeyboardModifier itemModifier = Qt::NoModifier; + int itemKeyCode = 0; + KeyboardTranslator::State itemFlag = KeyboardTranslator::NoState; + + if ( parseAsModifier(buffer,itemModifier) ) + { + tempModifierMask |= itemModifier; + + if ( isWanted ) + tempModifiers |= itemModifier; + } + else if ( parseAsStateFlag(buffer,itemFlag) ) + { + tempFlagMask |= itemFlag; + + if ( isWanted ) + tempFlags |= itemFlag; + } + else if ( parseAsKeyCode(buffer,itemKeyCode) ) + keyCode = itemKeyCode; + else + qDebug() << "Unable to parse key binding item:" << buffer; + + buffer.clear(); + } + + // check if this is a wanted / not-wanted flag and update the + // state ready for the next item + if ( ch == '+' ) + isWanted = true; + else if ( ch == '-' ) + isWanted = false; + } + + modifiers = tempModifiers; + modifierMask = tempModifierMask; + flags = tempFlags; + flagMask = tempFlagMask; + + return true; +} + +bool KeyboardTranslatorReader::parseAsModifier(const QString& item , Qt::KeyboardModifier& modifier) +{ + if ( item == "shift" ) + modifier = Qt::ShiftModifier; + else if ( item == "ctrl" || item == "control" ) + modifier = Qt::ControlModifier; + else if ( item == "alt" ) + modifier = Qt::AltModifier; + else if ( item == "meta" ) + modifier = Qt::MetaModifier; + else if ( item == "keypad" ) + modifier = Qt::KeypadModifier; + else + return false; + + return true; +} +bool KeyboardTranslatorReader::parseAsStateFlag(const QString& item , KeyboardTranslator::State& flag) +{ + if ( item == "appcukeys" ) + flag = KeyboardTranslator::CursorKeysState; + else if ( item == "ansi" ) + flag = KeyboardTranslator::AnsiState; + else if ( item == "newline" ) + flag = KeyboardTranslator::NewLineState; + else if ( item == "appscreen" ) + flag = KeyboardTranslator::AlternateScreenState; + else if ( item == "anymod" ) + flag = KeyboardTranslator::AnyModifierState; + else + return false; + + return true; +} +bool KeyboardTranslatorReader::parseAsKeyCode(const QString& item , int& keyCode) +{ + QKeySequence sequence = QKeySequence::fromString(item); + if ( !sequence.isEmpty() ) + { + keyCode = sequence[0]; + + if ( sequence.count() > 1 ) + { + qDebug() << "Unhandled key codes in sequence: " << item; + } + } + // additional cases implemented for backwards compatibility with KDE 3 + else if ( item == "prior" ) + keyCode = Qt::Key_PageUp; + else if ( item == "next" ) + keyCode = Qt::Key_PageDown; + else + return false; + + return true; +} + +QString KeyboardTranslatorReader::description() const +{ + return _description; +} +bool KeyboardTranslatorReader::hasNextEntry() +{ + return _hasNext; +} +KeyboardTranslator::Entry KeyboardTranslatorReader::createEntry( const QString& condition , + const QString& result ) +{ + QString entryString("keyboard \"temporary\"\nkey "); + 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 + '\"'); + + QByteArray array = entryString.toUtf8(); + + KeyboardTranslator::Entry entry; + + QBuffer buffer(&array); + buffer.open(QIODevice::ReadOnly); + KeyboardTranslatorReader reader(&buffer); + + if ( reader.hasNextEntry() ) + entry = reader.nextEntry(); + + return entry; +} + +KeyboardTranslator::Entry KeyboardTranslatorReader::nextEntry() +{ + Q_ASSERT( _hasNext ); + + + KeyboardTranslator::Entry entry = _nextEntry; + + readNext(); + + return entry; +} +bool KeyboardTranslatorReader::parseError() +{ + return false; +} +QList<KeyboardTranslatorReader::Token> KeyboardTranslatorReader::tokenize(const QString& line) +{ + QString text = line.simplified(); + + // comment line: # comment + static QRegExp comment("\\#.*"); + // 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+)"); + + QList<Token> list; + + if ( text.isEmpty() || comment.exactMatch(text) ) + { + return list; + } + + if ( title.exactMatch(text) ) + { + Token titleToken = { Token::TitleKeyword , QString() }; + Token textToken = { Token::TitleText , title.capturedTexts()[1] }; + + list << titleToken << textToken; + } + else if ( key.exactMatch(text) ) + { + Token keyToken = { Token::KeyKeyword , QString() }; + Token sequenceToken = { Token::KeySequence , key.capturedTexts()[1].remove(' ') }; + + list << keyToken << sequenceToken; + + if ( key.capturedTexts()[3].isEmpty() ) + { + // capturedTexts()[2] is a command + Token commandToken = { Token::Command , key.capturedTexts()[2] }; + list << commandToken; + } + else + { + // capturedTexts()[3] is the output string + Token outputToken = { Token::OutputText , key.capturedTexts()[3] }; + list << outputToken; + } + } + else + { + qWarning() << "Line in keyboard translator file could not be understood:" << text; + } + + return list; +} + +QList<QString> KeyboardTranslatorManager::allTranslators() +{ + if ( !_haveLoadedAll ) + { + findTranslators(); + } + + return _translators.keys(); +} + +KeyboardTranslator::Entry::Entry() +: _keyCode(0) +, _modifiers(Qt::NoModifier) +, _modifierMask(Qt::NoModifier) +, _state(NoState) +, _stateMask(NoState) +, _command(NoCommand) +{ +} + +bool KeyboardTranslator::Entry::operator==(const Entry& rhs) const +{ + return _keyCode == rhs._keyCode && + _modifiers == rhs._modifiers && + _modifierMask == rhs._modifierMask && + _state == rhs._state && + _stateMask == rhs._stateMask && + _command == rhs._command && + _text == rhs._text; +} + +bool KeyboardTranslator::Entry::matches(int keyCode , + Qt::KeyboardModifiers modifiers, + States state) const +{ + if ( _keyCode != keyCode ) + return false; + + if ( (modifiers & _modifierMask) != (_modifiers & _modifierMask) ) + return false; + + // if modifiers is non-zero, the 'any modifier' state is implicit + if ( modifiers != 0 ) + state |= AnyModifierState; + + if ( (state & _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; + if ( _stateMask & KeyboardTranslator::AnyModifierState ) + { + // test fails if any modifier is required but none are set + if ( (_state & KeyboardTranslator::AnyModifierState) && !anyModifiersSet ) + return false; + + // test fails if no modifier is allowed but one or more are set + if ( !(_state & KeyboardTranslator::AnyModifierState) && anyModifiersSet ) + return false; + } + + return true; +} +QByteArray KeyboardTranslator::Entry::escapedText(bool expandWildCards,Qt::KeyboardModifiers modifiers) const +{ + QByteArray result(text(expandWildCards,modifiers)); + + for ( int i = 0 ; i < result.count() ; i++ ) + { + char ch = result[i]; + char replacement = 0; + + switch ( ch ) + { + case 27 : replacement = 'E'; break; + case 8 : replacement = 'b'; break; + case 12 : replacement = 'f'; break; + case 9 : replacement = 't'; break; + case 13 : replacement = 'r'; break; + case 10 : replacement = 'n'; break; + default: + // any character which is not printable is replaced by an equivalent + // \xhh escape sequence (where 'hh' are the corresponding hex digits) + if ( !QChar(ch).isPrint() ) + replacement = 'x'; + } + + if ( replacement == 'x' ) + { + result.replace(i,1,"\\x"+QByteArray(1,ch).toInt(0, 16)); + } else if ( replacement != 0 ) + { + result.remove(i,1); + result.insert(i,'\\'); + result.insert(i+1,replacement); + } + } + + return result; +} +QByteArray KeyboardTranslator::Entry::unescape(const QByteArray& input) const +{ + QByteArray result(input); + + for ( int i = 0 ; i < result.count()-1 ; i++ ) + { + + QByteRef ch = result[i]; + if ( ch == '\\' ) + { + char replacement[2] = {0,0}; + int charsToRemove = 2; + bool escapedChar = true; + + switch ( result[i+1] ) + { + case 'E' : replacement[0] = 27; break; + case 'b' : replacement[0] = 8 ; break; + case 'f' : replacement[0] = 12; break; + case 't' : replacement[0] = 9 ; break; + case 'r' : replacement[0] = 13; break; + case 'n' : replacement[0] = 10; break; + case 'x' : + { + // format is \xh or \xhh where 'h' is a hexadecimal + // digit from 0-9 or A-F which should be replaced + // with the corresponding character value + char hexDigits[3] = {0}; + + if ( (i < result.count()-2) && isxdigit(result[i+2]) ) + hexDigits[0] = result[i+2]; + if ( (i < result.count()-3) && isxdigit(result[i+3]) ) + hexDigits[1] = result[i+3]; + + int charValue = 0; + sscanf(hexDigits,"%x",&charValue); + + replacement[0] = (char)charValue; + + charsToRemove = 2 + strlen(hexDigits); + } + break; + default: + escapedChar = false; + } + + if ( escapedChar ) + result.replace(i,charsToRemove,replacement); + } + } + + return result; +} + +void KeyboardTranslator::Entry::insertModifier( QString& item , int modifier ) const +{ + if ( !(modifier & _modifierMask) ) + return; + + if ( modifier & _modifiers ) + item += '+'; + else + item += '-'; + + if ( modifier == Qt::ShiftModifier ) + item += "Shift"; + else if ( modifier == Qt::ControlModifier ) + item += "Ctrl"; + else if ( modifier == Qt::AltModifier ) + item += "Alt"; + else if ( modifier == Qt::MetaModifier ) + item += "Meta"; + else if ( modifier == Qt::KeypadModifier ) + item += "KeyPad"; +} +void KeyboardTranslator::Entry::insertState( QString& item , int state ) const +{ + if ( !(state & _stateMask) ) + return; + + if ( state & _state ) + item += '+' ; + else + item += '-' ; + + if ( state == KeyboardTranslator::AlternateScreenState ) + item += "AppScreen"; + else if ( state == KeyboardTranslator::NewLineState ) + item += "NewLine"; + else if ( state == KeyboardTranslator::AnsiState ) + item += "Ansi"; + else if ( state == KeyboardTranslator::CursorKeysState ) + item += "AppCuKeys"; + else if ( state == KeyboardTranslator::AnyModifierState ) + item += "AnyMod"; +} +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 == ScrollPageUpCommand ) + return "ScrollPageUp"; + else if ( _command == ScrollPageDownCommand ) + return "ScrollPageDown"; + else if ( _command == ScrollLineUpCommand ) + return "ScrollLineUp"; + else if ( _command == ScrollLineDownCommand ) + return "ScrollLineDown"; + else if ( _command == ScrollLockCommand ) + return "ScrollLock"; + + return QString(); +} +QString KeyboardTranslator::Entry::conditionToString() const +{ + QString result = QKeySequence(_keyCode).toString(); + + // add modifiers + insertModifier( result , Qt::ShiftModifier ); + insertModifier( result , Qt::ControlModifier ); + insertModifier( result , Qt::AltModifier ); + insertModifier( result , Qt::MetaModifier ); + + // add states + insertState( result , KeyboardTranslator::AlternateScreenState ); + insertState( result , KeyboardTranslator::NewLineState ); + insertState( result , KeyboardTranslator::AnsiState ); + insertState( result , KeyboardTranslator::CursorKeysState ); + insertState( result , KeyboardTranslator::AnyModifierState ); + + return result; +} + +KeyboardTranslator::KeyboardTranslator(const QString& name) +: _name(name) +{ +} + +void KeyboardTranslator::setDescription(const QString& description) +{ + _description = description; +} +QString KeyboardTranslator::description() const +{ + return _description; +} +void KeyboardTranslator::setName(const QString& name) +{ + _name = name; +} +QString KeyboardTranslator::name() const +{ + return _name; +} + +QList<KeyboardTranslator::Entry> KeyboardTranslator::entries() const +{ + return _entries.values(); +} + +void KeyboardTranslator::addEntry(const Entry& entry) +{ + const int keyCode = entry.keyCode(); + _entries.insertMulti(keyCode,entry); +} +void KeyboardTranslator::replaceEntry(const Entry& existing , const Entry& replacement) +{ + if ( !existing.isNull() ) + _entries.remove(existing.keyCode()); + _entries.insertMulti(replacement.keyCode(),replacement); +} +void KeyboardTranslator::removeEntry(const Entry& entry) +{ + _entries.remove(entry.keyCode()); +} +KeyboardTranslator::Entry KeyboardTranslator::findEntry(int keyCode, Qt::KeyboardModifiers modifiers, States state) const +{ + if ( _entries.contains(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 + } + else + { + return Entry(); + } + +} +void KeyboardTranslatorManager::addTranslator(KeyboardTranslator* translator) +{ + _translators.insert(translator->name(),translator); + + if ( !saveTranslator(translator) ) + qWarning() << "Unable to save translator" << translator->name() + << "to disk."; +} +bool KeyboardTranslatorManager::deleteTranslator(const QString& name) +{ + Q_ASSERT( _translators.contains(name) ); + + // locate and delete + QString path = findTranslatorPath(name); + if ( QFile::remove(path) ) + { + _translators.remove(name); + return true; + } + else + { + qWarning() << "Failed to remove translator - " << path; + return false; + } +} +K_GLOBAL_STATIC( KeyboardTranslatorManager , theKeyboardTranslatorManager ) +KeyboardTranslatorManager* KeyboardTranslatorManager::instance() +{ + return theKeyboardTranslatorManager; +} diff --git a/client/browser/qtermwidget/includes/KeyboardTranslator.h b/client/browser/qtermwidget/src/KeyboardTranslator.h index e0082ae1..e0082ae1 100644 --- a/client/browser/qtermwidget/includes/KeyboardTranslator.h +++ b/client/browser/qtermwidget/src/KeyboardTranslator.h diff --git a/client/browser/qtermwidget/includes/LineFont.h b/client/browser/qtermwidget/src/LineFont.h index 9b641439..9b641439 100644 --- a/client/browser/qtermwidget/includes/LineFont.h +++ b/client/browser/qtermwidget/src/LineFont.h diff --git a/client/browser/qtermwidget/includes/LineFont.src b/client/browser/qtermwidget/src/LineFont.src index 6835253f..6835253f 100644 --- a/client/browser/qtermwidget/includes/LineFont.src +++ b/client/browser/qtermwidget/src/LineFont.src diff --git a/client/browser/qtermwidget/src/Pty.cpp b/client/browser/qtermwidget/src/Pty.cpp new file mode 100644 index 00000000..211ad46f --- /dev/null +++ b/client/browser/qtermwidget/src/Pty.cpp @@ -0,0 +1,321 @@ +/* + 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 + + 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 "Pty.h" +#include "Pty.moc" + +// System +#include <sys/types.h> +#include <sys/stat.h> +#include <unistd.h> +#include <errno.h> +#include <termios.h> + +// Qt +#include <QtCore> + +// KDE +//#include <KStandardDirs> +//#include <KLocale> +//#include <KDebug> +#include "kpty.h" + +using namespace Konsole; + +void Pty::donePty() +{ + emit done(exitStatus()); +} + +void Pty::setWindowSize(int lines, int cols) +{ + _windowColumns = cols; + _windowLines = lines; + + if (pty()->masterFd() >= 0) + pty()->setWinSize(lines, cols); +} +QSize Pty::windowSize() const +{ + return QSize(_windowColumns,_windowLines); +} + +void Pty::setXonXoff(bool enable) +{ + _xonXoff = enable; + + if (pty()->masterFd() >= 0) + { + struct ::termios ttmode; + pty()->tcGetAttr(&ttmode); + if (!enable) + ttmode.c_iflag &= ~(IXOFF | IXON); + else + ttmode.c_iflag |= (IXOFF | IXON); + if (!pty()->tcSetAttr(&ttmode)) + qWarning("Unable to set terminal attributes."); + } +} + +void Pty::setUtf8Mode(bool enable) +{ +#ifdef IUTF8 // XXX not a reasonable place to check it. + _utf8 = enable; + + if (pty()->masterFd() >= 0) + { + struct ::termios ttmode; + pty()->tcGetAttr(&ttmode); + if (!enable) + ttmode.c_iflag &= ~IUTF8; + else + ttmode.c_iflag |= IUTF8; + if (!pty()->tcSetAttr(&ttmode)) + qWarning("Unable to set terminal attributes."); + } +#endif +} + +void Pty::setErase(char erase) +{ + _eraseChar = erase; + + if (pty()->masterFd() >= 0) + { + struct ::termios ttmode; + + pty()->tcGetAttr(&ttmode); + + ttmode.c_cc[VERASE] = erase; + + if (!pty()->tcSetAttr(&ttmode)) + qWarning("Unable to set terminal attributes."); + } +} + +char Pty::erase() const +{ + if (pty()->masterFd() >= 0) + { + qDebug() << "Getting erase char"; + struct ::termios ttyAttributes; + pty()->tcGetAttr(&ttyAttributes); + return ttyAttributes.c_cc[VERASE]; + } + + return _eraseChar; +} + +void Pty::addEnvironmentVariables(const QStringList& environment) +{ + QListIterator<QString> iter(environment); + while (iter.hasNext()) + { + QString pair = iter.next(); + + // split on the first '=' character + int pos = pair.indexOf('='); + + if ( pos >= 0 ) + { + QString variable = pair.left(pos); + QString value = pair.mid(pos+1); + + //kDebug() << "Setting environment pair" << variable << + // " set to " << value; + + setEnvironment(variable,value); + } + } +} + +int Pty::start(const QString& program, + const QStringList& programArguments, + const QStringList& environment, + ulong winid, + bool addToUtmp +// const QString& dbusService, +// const QString& dbusSession) + ) +{ + clearArguments(); + + setBinaryExecutable(program.toLatin1()); + + addEnvironmentVariables(environment); + + QStringListIterator it( programArguments ); + while (it.hasNext()) + arguments.append( it.next().toUtf8() ); + +// if ( !dbusService.isEmpty() ) +// setEnvironment("KONSOLE_DBUS_SERVICE",dbusService); +// if ( !dbusSession.isEmpty() ) +// setEnvironment("KONSOLE_DBUS_SESSION", dbusSession); + + setEnvironment("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 + // + // this can happen if LANG contains a language which KDE + // does not have a translation for + // + // BR:149300 + if (!environment.contains("LANGUAGE")) + setEnvironment("LANGUAGE",QString()); + + setUsePty(All, addToUtmp); + + pty()->open(); + + struct ::termios ttmode; + pty()->tcGetAttr(&ttmode); + if (!_xonXoff) + ttmode.c_iflag &= ~(IXOFF | IXON); + else + ttmode.c_iflag |= (IXOFF | IXON); +#ifdef IUTF8 // XXX not a reasonable place to check it. + if (!_utf8) + ttmode.c_iflag &= ~IUTF8; + else + ttmode.c_iflag |= IUTF8; +#endif + + if (_eraseChar != 0) + ttmode.c_cc[VERASE] = _eraseChar; + + if (!pty()->tcSetAttr(&ttmode)) + qWarning("Unable to set terminal attributes."); + + pty()->setWinSize(_windowLines, _windowColumns); + + if ( K3Process::start(NotifyOnExit, (Communication) (Stdin | Stdout)) == false ) + return -1; + + resume(); // Start... + return 0; + +} + +void Pty::setWriteable(bool writeable) +{ + struct stat sbuf; + stat(pty()->ttyName(), &sbuf); + if (writeable) + chmod(pty()->ttyName(), sbuf.st_mode | S_IWGRP); + else + chmod(pty()->ttyName(), sbuf.st_mode & ~(S_IWGRP|S_IWOTH)); +} + +Pty::Pty() + : _bufferFull(false), + _windowColumns(0), + _windowLines(0), + _eraseChar(0), + _xonXoff(true), + _utf8(true) +{ + 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; + + setUsePty(All, false); // utmp will be overridden later +} + +Pty::~Pty() +{ + delete _pty; +} + +void Pty::writeReady() +{ + _pendingSendJobs.erase(_pendingSendJobs.begin()); + _bufferFull = false; + doSendJobs(); +} + +void Pty::doSendJobs() { + if(_pendingSendJobs.isEmpty()) + { + emit bufferEmpty(); + return; + } + + SendJob& job = _pendingSendJobs.first(); + + + if (!writeStdin( job.data(), job.length() )) + { + qWarning("Pty::doSendJobs - Could not send input data to terminal process."); + return; + } + _bufferFull = true; +} + +void Pty::appendSendJob(const char* s, int len) +{ + _pendingSendJobs.append(SendJob(s,len)); +} + +void Pty::sendData(const char* s, int len) +{ + appendSendJob(s,len); + if (!_bufferFull) + doSendJobs(); +} + +void Pty::dataReceived(K3Process *,char *buf, int len) +{ + emit receivedData(buf,len); +} + +void Pty::lockPty(bool lock) +{ + if (lock) + suspend(); + else + resume(); +} + +int Pty::foregroundProcessGroup() const +{ + int pid = tcgetpgrp(pty()->masterFd()); + + if ( pid != -1 ) + { + return pid; + } + + return 0; +} + +//#include "moc_Pty.cpp" diff --git a/client/browser/qtermwidget/includes/Pty.h b/client/browser/qtermwidget/src/Pty.h index f3e94322..f3e94322 100644 --- a/client/browser/qtermwidget/includes/Pty.h +++ b/client/browser/qtermwidget/src/Pty.h diff --git a/client/browser/qtermwidget/src/README b/client/browser/qtermwidget/src/README new file mode 100644 index 00000000..18013612 --- /dev/null +++ b/client/browser/qtermwidget/src/README @@ -0,0 +1,7 @@ +lib.pro is a *.pro-file for qmake + +It produces static lib (libqtermwidget.a) only. +For creating shared lib (*.so) uncomment "dll" in "CONFIG" line in *.pro-file + +Library was tested both with HAVE_POSIX_OPENPT and HAVE_GETPT precompiler directives, +defined in "DEFINES" line. You should select variant which would be correct for your system.
\ No newline at end of file diff --git a/client/browser/qtermwidget/src/Screen.cpp b/client/browser/qtermwidget/src/Screen.cpp new file mode 100644 index 00000000..ead0066a --- /dev/null +++ b/client/browser/qtermwidget/src/Screen.cpp @@ -0,0 +1,1567 @@ +/* + 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 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. +*/ + +// Own +#include "Screen.h" + +// Standard +#include <stdio.h> +#include <stdlib.h> +#include <unistd.h> +#include <assert.h> +#include <string.h> +#include <ctype.h> + +// Qt +#include <QtCore/QTextStream> +#include <QtCore/QDate> + +// Konsole +#include "konsole_wcwidth.h" +#include "TerminalCharacterDecoder.h" + +using namespace Konsole; + +//FIXME: this is emulation specific. Use false for xterm, true for ANSI. +//FIXME: see if we can get this from terminfo. +#define BS_CLEARS false + +//Macro to convert x,y position on screen to position within an image. +// +//Originally the image was stored as one large contiguous block of +//memory, so a position within the image could be represented as an +//offset from the beginning of the block. For efficiency reasons this +//is no longer the case. +//Many internal parts of this class still use this representation for parameters and so on, +//notably moveImage() and clearImage(). +//This macro converts from an X,Y position into an image offset. +#ifndef loc +#define loc(X,Y) ((Y)*columns+(X)) +#endif + + +Character Screen::defaultChar = Character(' ', + CharacterColor(COLOR_SPACE_DEFAULT,DEFAULT_FORE_COLOR), + CharacterColor(COLOR_SPACE_DEFAULT,DEFAULT_BACK_COLOR), + DEFAULT_RENDITION); + +//#define REVERSE_WRAPPED_LINES // for wrapped line debug + +Screen::Screen(int l, int c) + : lines(l), + columns(c), + screenLines(new ImageLine[lines+1] ), + _scrolledLines(0), + _droppedLines(0), + hist(new HistoryScrollNone()), + cuX(0), cuY(0), + cu_re(0), + tmargin(0), bmargin(0), + tabstops(0), + sel_begin(0), sel_TL(0), sel_BR(0), + sel_busy(false), + columnmode(false), + ef_fg(CharacterColor()), ef_bg(CharacterColor()), ef_re(0), + sa_cuX(0), sa_cuY(0), + sa_cu_re(0), + lastPos(-1) +{ + lineProperties.resize(lines+1); + for (int i=0;i<lines+1;i++) + lineProperties[i]=LINE_DEFAULT; + + initTabStops(); + clearSelection(); + reset(); +} + +/*! Destructor +*/ + +Screen::~Screen() +{ + delete[] screenLines; + delete[] tabstops; + delete hist; +} + +/* ------------------------------------------------------------------------- */ +/* */ +/* 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 +{ + if (n == 0) n = 1; // Default + int stop = cuY < tmargin ? 0 : tmargin; + 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 +{ + if (n == 0) n = 1; // Default + int stop = cuY > bmargin ? lines-1 : bmargin; + 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 +{ + 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 +{ + if (n == 0) n = 1; // Default + cuX = qMin(columns-1,cuX+n); +} + +void Screen::setMargins(int top, int bot) +//=STBM +{ + if (top == 0) top = 1; // Default + if (bot == 0) bot = lines; // Default + top = top - 1; // Adjust to internal lineno + bot = bot - 1; // Adjust to internal lineno + if ( !( 0 <= top && top < bot && bot < lines ) ) + { qDebug()<<" setRegion("<<top<<","<<bot<<") : bad range."; + return; // Default error action: ignore + } + tmargin = top; + bmargin = bot; + cuX = 0; + cuY = getMode(MODE_Origin) ? top : 0; + +} + +int Screen::topMargin() const +{ + return tmargin; +} +int Screen::bottomMargin() const +{ + return bmargin; +} + +void Screen::index() +//=IND +{ + if (cuY == bmargin) + { + scrollUp(1); + } + else if (cuY < lines-1) + cuY += 1; +} + +void Screen::reverseIndex() +//=RI +{ + if (cuY == tmargin) + scrollDown(tmargin,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 +{ + Return(); 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),' '); +} + +void Screen::deleteChars(int n) +{ + Q_ASSERT( n >= 0 ); + + // always delete at least one char + if (n == 0) + n = 1; + + // if cursor is beyond the end of the line there is nothing to do + if ( cuX >= screenLines[cuY].count() ) + return; + + if ( cuX+n >= screenLines[cuY].count() ) + n = screenLines[cuY].count() - 1 - cuX; + + Q_ASSERT( n >= 0 ); + Q_ASSERT( cuX+n < screenLines[cuY].count() ); + + screenLines[cuY].remove(cuX,n); +} + +void Screen::insertChars(int n) +{ + if (n == 0) n = 1; // Default + + if ( screenLines[cuY].size() < cuX ) + screenLines[cuY].resize(cuX); + + screenLines[cuY].insert(cuX,n,' '); + + if ( screenLines[cuY].count() > columns ) + screenLines[cuY].resize(columns); +} + +void Screen::deleteLines(int 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); +} + +// 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 + } +} + +/*! 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 + } +} + +/*! Save a specific mode. */ + +void Screen::saveMode(int m) +{ + saveParm.mode[m] = currParm.mode[m]; +} + +/*! Restore a specific mode. */ + +void Screen::restoreMode(int m) +{ + currParm.mode[m] = saveParm.mode[m]; +} + +bool Screen::getMode(int m) const +{ + return currParm.mode[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; +} + +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(); +} + +/* ------------------------------------------------------------------------- */ +/* */ +/* 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 (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); + } + } + + // 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; + + clearSelection(); + + delete[] screenLines; + screenLines = newScreenLines; + + 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(); +} + +void Screen::setDefaultMargins() +{ + tmargin = 0; + bmargin = lines-1; +} + + +/* + 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 + + cu_fg, cu_bg contain values 0..8; + - 0 = default color + - 1..8 = ansi specified color + + re_fg, re_bg contain values 0..17 + due to the TerminalDisplay's color table + + 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 + + Note that RE_BOLD is used in both widget + and screen rendition. Since xterm/vt102 + is to poor to distinguish between bold + (which is a font attribute) and intensive + (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; +} + +void Screen::effectiveRendition() +// calculate rendition +{ + //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(); +} + +/*! + 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() ); + + for (int line = startLine; line < startLine + count; line++) + { + const int length = qMin(columns,hist->getLineLen(line)); + const int destLineOffset = (line-startLine)*columns; + + hist->getCells(line,0,length,dest + destLineOffset); + + 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]); + } + } + } + } +} + +void Screen::copyFromScreen(Character* dest , int startLine , int count) const +{ + Q_ASSERT( startLine >= 0 && count > 0 && startLine + count <= lines ); + + for (int line = startLine; line < (startLine+count) ; line++) + { + int srcLineStartIndex = line*columns; + int destLineStartIndex = (line-startLine)*columns; + + for (int column = 0; column < columns; column++) + { + int srcIndex = srcLineStartIndex + column; + int destIndex = destLineStartIndex + column; + + dest[destIndex] = screenLines[srcIndex/columns].value(srcIndex%columns,defaultChar); + + // invert selected text + if (sel_begin != -1 && isSelected(column,line + hist->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 ); + + const int mergedLines = endLine - startLine + 1; + + Q_ASSERT( size >= mergedLines * columns ); + + 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 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; +} + +QVector<LineProperty> Screen::getLineProperties( int startLine , int endLine ) const +{ + Q_ASSERT( startLine >= 0 ); + Q_ASSERT( endLine >= startLine && endLine < hist->getLines() + lines ); + + const int mergedLines = endLine-startLine+1; + const int linesInHistory = qBound(0,hist->getLines()-startLine,mergedLines); + const int linesInScreen = mergedLines - linesInHistory; + + 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++; + } + + return result; +} + +/*! +*/ + +void Screen::reset(bool clearScreen) +{ + setMode(MODE_Wrap ); saveMode(MODE_Wrap ); // wrap at end of margin + resetMode(MODE_Origin); saveMode(MODE_Origin); // position refere to [1,1] + resetMode(MODE_Insert); saveMode(MODE_Insert); // overstroke + setMode(MODE_Cursor); // cursor visible + resetMode(MODE_Screen); // screen not inverse + resetMode(MODE_NewLine); + + tmargin=0; + bmargin=lines-1; + + setDefaultRendition(); + saveCursor(); + + if ( clearScreen ) + clear(); +} + +/*! Clear the entire screen and home the cursor. +*/ + +void Screen::clear() +{ + clearEntireScreen(); + home(); +} + +void Screen::BackSpace() +{ + cuX = qMin(columns-1,cuX); // nowrap! + cuX = qMax(0,cuX-1); + // if (BS_CLEARS) image[loc(cuX,cuY)].character = ' '; + + if (screenLines[cuY].size() < cuX+1) + screenLines[cuY].resize(cuX+1); + + if (BS_CLEARS) screenLines[cuY][cuX].character = ' '; +} + +void Screen::Tabulate(int n) +{ + // note that TAB is a format effector (does not write ' '); + if (n == 0) n = 1; + while((n > 0) && (cuX < columns-1)) + { + cursorRight(1); while((cuX < columns-1) && !tabstops[cuX]) cursorRight(1); + n--; + } +} + +void Screen::backTabulate(int n) +{ + // note that TAB is a format effector (does not write ' '); + if (n == 0) n = 1; + while((n > 0) && (cuX > 0)) + { + cursorLeft(1); while((cuX > 0) && !tabstops[cuX]) cursorLeft(1); + n--; + } +} + +void Screen::clearTabStops() +{ + for (int i = 0; i < columns; i++) tabstops[i] = false; +} + +void Screen::changeTabStop(bool set) +{ + if (cuX >= columns) return; + tabstops[cuX] = set; +} + +void Screen::initTabStops() +{ + delete[] tabstops; + tabstops = new bool[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); +} + +/*! + 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() +{ + if (getMode(MODE_NewLine)) Return(); + 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(); + } +} + +void Screen::ShowCharacter(unsigned short c) +{ + // Note that VT100 does wrapping BEFORE putting the character. + // This has impact on the assumption of valid cursor positions. + // We indicate the fact that a newline has to be triggered by + // putting the cursor one right to the last column of the screen. + + int w = konsole_wcwidth(c); + + if (w <= 0) + return; + + if (cuX+w > columns) { + if (getMode(MODE_Wrap)) { + lineProperties[cuY] = (LineProperty)(lineProperties[cuY] | LINE_WRAPPED); + NextLine(); + } + else + cuX = columns-w; + } + + // ensure current line vector has enough elements + int size = screenLines[cuY].size(); + if (size == 0 && cuY > 0) + { + screenLines[cuY].resize( qMax(screenLines[cuY-1].size() , cuX+w) ); + } + else + { + if (size < cuX+w) + { + screenLines[cuY].resize(cuX+w); + } + } + + if (getMode(MODE_Insert)) insertChars(w); + + lastPos = loc(cuX,cuY); + + // check if selection is still valid. + checkSelection(cuX,cuY); + + Character& currentChar = screenLines[cuY][cuX]; + + currentChar.character = c; + currentChar.foregroundColor = ef_fg; + currentChar.backgroundColor = ef_bg; + currentChar.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); + + Character& ch = screenLines[cuY][cuX + i]; + ch.character = 0; + ch.foregroundColor = ef_fg; + ch.backgroundColor = ef_bg; + ch.rendition = ef_re; + + w--; + } + cuX = newCursorX; +} + +void Screen::compose(const QString& /*compose*/) +{ + Q_ASSERT( 0 /*Not implemented yet*/ ); + +/* if (lastPos == -1) + return; + + QChar c(image[lastPos].character); + compose.prepend(c); + //compose.compose(); ### FIXME! + image[lastPos].character = compose[0].unicode();*/ +} + +int Screen::scrolledLines() const +{ + return _scrolledLines; +} +int Screen::droppedLines() const +{ + return _droppedLines; +} +void Screen::resetDroppedLines() +{ + _droppedLines = 0; +} +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); +} + +/*! scroll up `n' lines within current region. + The `n' new lines are cleared. + \sa setRegion \sa scrollDown +*/ + +QRect Screen::lastScrolledRegion() const +{ + return _lastScrolledRegion; +} + +void Screen::scrollUp(int from, int n) +{ + if (n <= 0 || from + n > bmargin) return; + + _scrolledLines -= n; + _lastScrolledRegion = QRect(0,tmargin,columns-1,(bmargin-tmargin)); + + //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),' '); +} + +void Screen::scrollDown(int n) +{ + if (n == 0) n = 1; // Default + scrollDown(tmargin, n); +} + +/*! scroll down `n' lines within current region. + The `n' new lines are cleared. + \sa setRegion \sa scrollUp +*/ + +void Screen::scrollDown(int from, int n) +{ + + //kDebug() << "Screen::scrollDown( from: " << from << " , n: " << n << ")"; + + _scrolledLines += n; + +//FIXME: make sure `tmargin', `bmargin', `from', `n' is in bounds. + if (n <= 0) 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),' '); +} + +void Screen::setCursorYX(int y, int x) +{ + setCursorY(y); setCursorX(x); +} + +void Screen::setCursorX(int x) +{ + if (x == 0) x = 1; // Default + x -= 1; // Adjust + cuX = qMax(0,qMin(columns-1, x)); +} + +void Screen::setCursorY(int y) +{ + if (y == 0) y = 1; // Default + y -= 1; // Adjust + cuY = qMax(0,qMin(lines -1, y + (getMode(MODE_Origin) ? tmargin : 0) )); +} + +void Screen::home() +{ + cuX = 0; + cuY = 0; +} + +void Screen::Return() +{ + cuX = 0; +} + +int Screen::getCursorX() const +{ + return cuX; +} + +int Screen::getCursorY() const +{ + return cuY; +} + +// Erasing --------------------------------------------------------------------- + +/*! \section Erasing + + This group of operations erase parts of the screen contents by filling + it with spaces colored due to the current rendition settings. + + Althought the cursor position is involved in most of these operations, + it is never modified by them. +*/ + +/*! fill screen between (including) `loca' (start) and `loce' (end) with spaces. + + This is an internal helper functions. The parameter types are internal + addresses of within the screen image and make use of the way how the + screen matrix is mapped to the image vector. +*/ + +void Screen::clearImage(int loca, int loce, char c) +{ + int scr_TL=loc(0,hist->getLines()); + //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(); + } + + int topLine = loca/columns; + int bottomLine = loce/columns; + + 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()); + + for (int y=topLine;y<=bottomLine;y++) + { + lineProperties[y] = 0; + + int endCol = ( y == bottomLine) ? loce%columns : columns-1; + int startCol = ( y == topLine ) ? loca%columns : 0; + + QVector<Character>& line = screenLines[y]; + + if ( isDefaultCh && endCol == columns-1 ) + { + line.resize(startCol); + } + else + { + if (line.size() < endCol + 1) + line.resize(endCol+1); + + Character* data = line.data(); + for (int i=startCol;i<=endCol;i++) + data[i]=clearCh; + } + } +} + +/*! move image between (including) `sourceBegin' and `sourceEnd' to 'dest'. + + The 'dest', 'sourceBegin' and 'sourceEnd' parameters can be generated using + the loc(column,line) macro. + +NOTE: moveImage() can only move whole lines. + + This is an internal helper functions. The parameter types are internal + addresses of within the screen image and make use of the way how the + screen matrix is mapped to the image vector. +*/ + +void Screen::moveImage(int dest, int sourceBegin, int sourceEnd) +{ + //kDebug() << "moving image from (" << (sourceBegin/columns) + // << "," << (sourceEnd/columns) << ") to " << + // (dest/columns); + + Q_ASSERT( sourceBegin <= sourceEnd ); + + int lines=(sourceEnd-sourceBegin)/columns; + + //move screen image and line properties: + //the source and destination areas of the image may overlap, + //so it matters that we do the copy in the right order - + //forwards if dest < sourceBegin or backwards otherwise. + //(search the web for 'memmove implementation' for details) + if (dest < sourceBegin) + { + for (int i=0;i<=lines;i++) + { + screenLines[ (dest/columns)+i ] = screenLines[ (sourceBegin/columns)+i ]; + lineProperties[(dest/columns)+i]=lineProperties[(sourceBegin/columns)+i]; + } + } + else + { + for (int i=lines;i>=0;i--) + { + screenLines[ (dest/columns)+i ] = screenLines[ (sourceBegin/columns)+i ]; + lineProperties[(dest/columns)+i]=lineProperties[(sourceBegin/columns)+i]; + } + } + + if (lastPos != -1) + { + 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; + + 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 (sel_BR < 0) + { + clearSelection(); + } + else + { + if (sel_TL < 0) + sel_TL = 0; + } + + if (beginIsTL) + sel_begin = sel_TL; + else + sel_begin = sel_BR; + } +} + +void Screen::clearToEndOfScreen() +{ + clearImage(loc(cuX,cuY),loc(columns-1,lines-1),' '); +} + +void Screen::clearToBeginOfScreen() +{ + clearImage(loc(0,0),loc(cuX,cuY),' '); +} + +void Screen::clearEntireScreen() +{ + // Add entire screen to history + for (int i = 0; i < (lines-1); i++) + { + addHistLine(); scrollUp(0,1); + } + + clearImage(loc(0,0),loc(columns-1,lines-1),' '); +} + +/*! fill screen with 'E' + This is to aid screen alignment +*/ + +void Screen::helpAlign() +{ + clearImage(loc(0,0),loc(columns-1,lines-1),'E'); +} + +void Screen::clearToEndOfLine() +{ + clearImage(loc(cuX,cuY),loc(columns-1,cuY),' '); +} + +void Screen::clearToBeginOfLine() +{ + clearImage(loc(0,cuY),loc(cuX,cuY),' '); +} + +void Screen::clearEntireLine() +{ + clearImage(loc(0,cuY),loc(columns-1,cuY),' '); +} + +void Screen::setRendition(int re) +{ + cu_re |= re; + effectiveRendition(); +} + +void Screen::resetRendition(int re) +{ + cu_re &= ~re; + effectiveRendition(); +} + +void Screen::setDefaultRendition() +{ + setForeColor(COLOR_SPACE_DEFAULT,DEFAULT_FORE_COLOR); + setBackColor(COLOR_SPACE_DEFAULT,DEFAULT_BACK_COLOR); + cu_re = DEFAULT_RENDITION; + effectiveRendition(); +} + +void Screen::setForeColor(int space, int color) +{ + cu_fg = CharacterColor(space, color); + + if ( cu_fg.isValid() ) + effectiveRendition(); + else + setForeColor(COLOR_SPACE_DEFAULT,DEFAULT_FORE_COLOR); +} + +void Screen::setBackColor(int space, int color) +{ + cu_bg = CharacterColor(space, color); + + if ( cu_bg.isValid() ) + effectiveRendition(); + else + setBackColor(COLOR_SPACE_DEFAULT,DEFAULT_BACK_COLOR); +} + +/* ------------------------------------------------------------------------- */ +/* */ +/* Marking & Selection */ +/* */ +/* ------------------------------------------------------------------------- */ + +void Screen::clearSelection() +{ + sel_BR = -1; + sel_TL = -1; + sel_begin = -1; +} + +void Screen::getSelectionStart(int& column , int& line) +{ + if ( sel_TL != -1 ) + { + column = sel_TL % columns; + line = sel_TL / columns; + } + else + { + column = cuX + getHistLines(); + line = cuY + getHistLines(); + } +} +void Screen::getSelectionEnd(int& column , int& line) +{ + if ( sel_BR != -1 ) + { + column = sel_BR % columns; + line = sel_BR / columns; + } + else + { + column = cuX + getHistLines(); + line = cuY + getHistLines(); + } +} +void Screen::setSelectionStart(/*const ScreenCursor& viewCursor ,*/ const int x, const int y, const bool mode) +{ +// kDebug(1211) << "setSelBeginXY(" << x << "," << y << ")"; + sel_begin = loc(x,y); //+histCursor) ; + + /* 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; +} + +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 (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--; + + sel_TL = sel_begin; + sel_BR = l; + } +} + +bool Screen::isSelected( const int x,const int y) const +{ + if (columnmode) { + int sel_Left,sel_Right; + if ( sel_TL % columns < sel_BR % columns ) { + sel_Left = sel_TL; sel_Right = sel_BR; + } else { + sel_Left = sel_BR; sel_Right = sel_TL; + } + return ( x >= sel_Left % columns ) && ( x <= sel_Right % columns ) && + ( y >= sel_TL / columns ) && ( y <= sel_BR / columns ); + //( y+histCursor >= sel_TL / columns ) && ( y+histCursor <= sel_BR / columns ); + } + else { + //int pos = loc(x,y+histCursor); + int pos = loc(x,y); + return ( pos >= sel_TL && pos <= sel_BR ); + } +} + +QString Screen::selectedText(bool preserveLineBreaks) +{ + 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 ); +} + +void Screen::writeSelectionToStream(TerminalCharacterDecoder* decoder , + bool preserveLineBreaks) +{ + // do nothing if selection is invalid + if ( !isSelectionValid() ) + return; + + int top = sel_TL / columns; + int left = sel_TL % columns; + + int bottom = sel_BR / columns; + int right = sel_BR % 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 || columnmode ) start = left; + + int count = -1; + if ( y == bottom || columnmode ) count = right - start + 1; + + const bool appendNewLine = ( y != bottom ); + copyLineToStream( y, + start, + count, + decoder, + appendNewLine, + preserveLineBreaks ); + } +} + + +void Screen::copyLineToStream(int line , + int start, + int count, + TerminalCharacterDecoder* decoder, + bool appendNewLine, + bool preserveLineBreaks) +{ + //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; + + //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)); + + //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); + + if ( hist->isWrappedLine(line) ) + currentLineProperties |= LINE_WRAPPED; + } + else + { + if ( count == -1 ) + count = columns - start; + + assert( count >= 0 ); + + 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]; + } + + // 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) ) + { + characterBuffer[count] = '\n'; + count++; + } + + //decode line and write to text stream + decoder->decodeLine( (Character*) characterBuffer , + count, currentLineProperties ); +} + +// 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) +{ + 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); +} + +void Screen::addHistLine() +{ + // add line to history buffer + // we have to take care about scrolling, too... + + if (hasScroll()) + { + int oldHistLines = hist->getLines(); + + hist->addCellsVector(screenLines[0]); + hist->addLine( lineProperties[0] & LINE_WRAPPED ); + + int newHistLines = hist->getLines(); + + bool beginIsTL = (sel_begin == sel_TL); + + // 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 (sel_begin != -1) + { + sel_TL += columns; + sel_BR += columns; + } + } + + 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() +{ + return hist->getLines(); +} + +void Screen::setScroll(const HistoryType& t , bool copyPreviousScroll) +{ + clearSelection(); + + if ( copyPreviousScroll ) + hist = t.scroll(hist); + else + { + HistoryScroll* oldScroll = hist; + hist = t.scroll(0); + delete oldScroll; + } +} + +bool Screen::hasScroll() +{ + return hist->hasScroll(); +} + +const HistoryType& Screen::getScroll() +{ + return hist->getType(); +} + +void Screen::setLineProperty(LineProperty property , bool enable) +{ + 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; +} diff --git a/client/browser/qtermwidget/includes/Screen.h b/client/browser/qtermwidget/src/Screen.h index a4ad199b..a4ad199b 100644 --- a/client/browser/qtermwidget/includes/Screen.h +++ b/client/browser/qtermwidget/src/Screen.h diff --git a/client/browser/qtermwidget/src/ScreenWindow.cpp b/client/browser/qtermwidget/src/ScreenWindow.cpp new file mode 100644 index 00000000..27749344 --- /dev/null +++ b/client/browser/qtermwidget/src/ScreenWindow.cpp @@ -0,0 +1,298 @@ +/* + Copyright (C) 2007 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 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 "ScreenWindow.h" +#include "ScreenWindow.moc" + +// Qt +#include <QtCore> + +// Konsole +#include "Screen.h" + + +using namespace Konsole; + +ScreenWindow::ScreenWindow(QObject* parent) + : QObject(parent) + , _windowBuffer(0) + , _windowBufferSize(0) + , _bufferNeedsUpdate(true) + , _windowLines(1) + , _currentLine(0) + , _trackOutput(true) + , _scrollCount(0) +{ +} +ScreenWindow::~ScreenWindow() +{ + delete[] _windowBuffer; +} +void ScreenWindow::setScreen(Screen* screen) +{ + Q_ASSERT( screen ); + + _screen = screen; +} + +Screen* ScreenWindow::screen() const +{ + return _screen; +} + +Character* ScreenWindow::getImage() +{ + // reallocate internal buffer if the window size has changed + int size = windowLines() * windowColumns(); + if (_windowBuffer == 0 || _windowBufferSize != size) + { + delete[] _windowBuffer; + _windowBufferSize = size; + _windowBuffer = new Character[size]; + _bufferNeedsUpdate = true; + } + + if (!_bufferNeedsUpdate) + return _windowBuffer; + + _screen->getImage(_windowBuffer,size, + currentLine(),endWindowLine()); + + // this window may look beyond the end of the screen, in which + // case there will be an unused area which needs to be filled + // with blank characters + fillUnusedArea(); + + _bufferNeedsUpdate = false; + return _windowBuffer; +} + +void ScreenWindow::fillUnusedArea() +{ + int screenEndLine = _screen->getHistLines() + _screen->getLines() - 1; + int windowEndLine = currentLine() + windowLines() - 1; + + int unusedLines = windowEndLine - screenEndLine; + int charsToFill = unusedLines * windowColumns(); + + Screen::fillWithDefaultChar(_windowBuffer + _windowBufferSize - charsToFill,charsToFill); +} + +// return the index of the line at the end of this window, or if this window +// goes beyond the end of the screen, the index of the line at the end +// of the screen. +// +// when passing a line number to a Screen method, the line number should +// never be more than endWindowLine() +// +int ScreenWindow::endWindowLine() const +{ + return qMin(currentLine() + windowLines() - 1, + lineCount() - 1); +} +QVector<LineProperty> ScreenWindow::getLineProperties() +{ + QVector<LineProperty> result = _screen->getLineProperties(currentLine(),endWindowLine()); + + if (result.count() != windowLines()) + result.resize(windowLines()); + + return result; +} + +QString ScreenWindow::selectedText( bool preserveLineBreaks ) const +{ + return _screen->selectedText( preserveLineBreaks ); +} + +void ScreenWindow::getSelectionStart( int& column , int& line ) +{ + _screen->getSelectionStart(column,line); + line -= currentLine(); +} +void ScreenWindow::getSelectionEnd( int& column , int& line ) +{ + _screen->getSelectionEnd(column,line); + line -= currentLine(); +} +void ScreenWindow::setSelectionStart( int column , int line , bool columnMode ) +{ + _screen->setSelectionStart( column , qMin(line + currentLine(),endWindowLine()) , columnMode); + + _bufferNeedsUpdate = true; + emit selectionChanged(); +} + +void ScreenWindow::setSelectionEnd( int column , int line ) +{ + _screen->setSelectionEnd( column , qMin(line + currentLine(),endWindowLine()) ); + + _bufferNeedsUpdate = true; + emit selectionChanged(); +} + +bool ScreenWindow::isSelected( int column , int line ) +{ + return _screen->isSelected( column , qMin(line + currentLine(),endWindowLine()) ); +} + +void ScreenWindow::clearSelection() +{ + _screen->clearSelection(); + + emit selectionChanged(); +} + +void ScreenWindow::setWindowLines(int lines) +{ + Q_ASSERT(lines > 0); + _windowLines = lines; +} +int ScreenWindow::windowLines() const +{ + return _windowLines; +} + +int ScreenWindow::windowColumns() const +{ + return _screen->getColumns(); +} + +int ScreenWindow::lineCount() const +{ + return _screen->getHistLines() + _screen->getLines(); +} + +int ScreenWindow::columnCount() const +{ + return _screen->getColumns(); +} + +QPoint ScreenWindow::cursorPosition() const +{ + QPoint position; + + position.setX( _screen->getCursorX() ); + position.setY( _screen->getCursorY() ); + + return position; +} + +int ScreenWindow::currentLine() const +{ + return qBound(0,_currentLine,lineCount()-windowLines()); +} + +void ScreenWindow::scrollBy( RelativeScrollMode mode , int amount ) +{ + if ( mode == ScrollLines ) + { + scrollTo( currentLine() + amount ); + } + else if ( mode == ScrollPages ) + { + scrollTo( currentLine() + amount * ( windowLines() / 2 ) ); + } +} + +bool ScreenWindow::atEndOfOutput() const +{ + return currentLine() == (lineCount()-windowLines()); +} + +void ScreenWindow::scrollTo( int line ) +{ + int maxCurrentLineNumber = lineCount() - windowLines(); + line = qBound(0,line,maxCurrentLineNumber); + + const int delta = line - _currentLine; + _currentLine = line; + + // keep track of number of lines scrolled by, + // this can be reset by calling resetScrollCount() + _scrollCount += delta; + + _bufferNeedsUpdate = true; + + emit scrolled(_currentLine); +} + +void ScreenWindow::setTrackOutput(bool trackOutput) +{ + _trackOutput = trackOutput; +} + +bool ScreenWindow::trackOutput() const +{ + return _trackOutput; +} + +int ScreenWindow::scrollCount() const +{ + return _scrollCount; +} + +void ScreenWindow::resetScrollCount() +{ + _scrollCount = 0; +} + +QRect ScreenWindow::scrollRegion() const +{ + bool equalToScreenSize = windowLines() == _screen->getLines(); + + if ( atEndOfOutput() && equalToScreenSize ) + return _screen->lastScrolledRegion(); + else + return QRect(0,0,windowColumns(),windowLines()); +} + +void ScreenWindow::notifyOutputChanged() +{ + // move window to the bottom of the screen and update scroll count + // if this window is currently tracking the bottom of the screen + if ( _trackOutput ) + { + _scrollCount -= _screen->scrolledLines(); + _currentLine = qMax(0,_screen->getHistLines() - (windowLines()-_screen->getLines())); + } + else + { + // if the history is not unlimited then it may + // have run out of space and dropped the oldest + // lines of output - in this case the screen + // window's current line number will need to + // be adjusted - otherwise the output will scroll + _currentLine = qMax(0,_currentLine - + _screen->droppedLines()); + + // ensure that the screen window's current position does + // not go beyond the bottom of the screen + _currentLine = qMin( _currentLine , _screen->getHistLines() ); + } + + _bufferNeedsUpdate = true; + + emit outputChanged(); +} + +//#include "moc_ScreenWindow.cpp" diff --git a/client/browser/qtermwidget/includes/ScreenWindow.h b/client/browser/qtermwidget/src/ScreenWindow.h index d2955abf..d2955abf 100644 --- a/client/browser/qtermwidget/includes/ScreenWindow.h +++ b/client/browser/qtermwidget/src/ScreenWindow.h diff --git a/client/browser/qtermwidget/src/Session.cpp b/client/browser/qtermwidget/src/Session.cpp new file mode 100644 index 00000000..64dbdca3 --- /dev/null +++ b/client/browser/qtermwidget/src/Session.cpp @@ -0,0 +1,1023 @@ +/* + 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 + + 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 "Session.h" +#include "Session.moc" + +// Standard +#include <assert.h> +#include <stdlib.h> + +// Qt +#include <QtGui/QApplication> +#include <QtCore/QByteRef> +#include <QtCore/QDir> +#include <QtCore/QFile> +#include <QtCore/QRegExp> +#include <QtCore/QStringList> +#include <QtCore> + +#include "Pty.h" +#include "TerminalDisplay.h" +#include "ShellCommand.h" +#include "Vt102Emulation.h" + + +using namespace Konsole; + +int Session::lastSessionId = 0; + +Session::Session() : + _shellProcess(0) + , _emulation(0) + , _monitorActivity(false) + , _monitorSilence(false) + , _notifiedActivity(false) + , _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 + , _flowControl(true) + , _fullScripting(false) + , _sessionId(0) +// , _zmodemBusy(false) +// , _zmodemProc(0) +// , _zmodemProgress(0) + , _hasDarkBackground(false) +{ + //prepare DBus communication +// new SessionAdaptor(this); + _sessionId = ++lastSessionId; +// QDBusConnection::sessionBus().registerObject(QLatin1String("/Sessions/")+QString::number(_sessionId), this); + + //create teletype for I/O with shell process + _shellProcess = new Pty(); + + //create emulation backend + _emulation = new Vt102Emulation(); + + connect( _emulation, SIGNAL( titleChanged( int, const QString & ) ), + 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&)) ); + // TODO + // connect( _emulation,SIGNAL(imageSizeChanged(int,int)) , this , + // SLOT(onEmulationSizeChange(int,int)) ); + + //connect teletype to emulation backend + _shellProcess->setUtf8Mode(_emulation->utf8()); + + 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())); +} + +WId Session::windowId() const +{ + // Returns a window ID for this session which is used + // to set the WINDOWID environment variable in the shell + // process. + // + // Sessions can have multiple views or no views, which means + // that a single ID is not always going to be accurate. + // + // If there are no views, the window ID is just 0. If + // there are multiple views, then the window ID for the + // top-level window which contains the first view is + // returned + + if ( _views.count() == 0 ) + return 0; + else + { + QWidget* window = _views.first(); + + Q_ASSERT( window ); + + while ( window->parentWidget() != 0 ) + window = window->parentWidget(); + + return window->winId(); + } +} + +void Session::setDarkBackground(bool darkBackground) +{ + _hasDarkBackground = darkBackground; +} +bool Session::hasDarkBackground() const +{ + return _hasDarkBackground; +} +bool Session::isRunning() const +{ + return _shellProcess->isRunning(); +} + +void Session::setCodec(QTextCodec* codec) +{ + emulation()->setCodec(codec); +} + +void Session::setProgram(const QString& program) +{ + _program = ShellCommand::expand(program); +} +void Session::setInitialWorkingDirectory(const QString& dir) +{ + _initialWorkingDir = ShellCommand::expand(dir); +} +void Session::setArguments(const QStringList& arguments) +{ + _arguments = ShellCommand::expand(arguments); +} + +QList<TerminalDisplay*> Session::views() const +{ + return _views; +} + +void Session::addView(TerminalDisplay* widget) +{ + Q_ASSERT( !_views.contains(widget) ); + + _views.append(widget); + + if ( _emulation != 0 ) + { + // connect emulation - view signals and slots + connect( widget , SIGNAL(keyPressedSignal(QKeyEvent*)) , _emulation , + SLOT(sendKeyEvent(QKeyEvent*)) ); + connect( widget , SIGNAL(mouseSignal(int,int,int,int)) , _emulation , + SLOT(sendMouseEvent(int,int,int,int)) ); + connect( widget , SIGNAL(sendStringToEmu(const char*)) , _emulation , + SLOT(sendString(const char*)) ); + + // allow emulation to notify view when the foreground process + // indicates whether or not it is interested in mouse signals + connect( _emulation , SIGNAL(programUsesMouseChanged(bool)) , widget , + SLOT(setUsesMouse(bool)) ); + + widget->setUsesMouse( _emulation->programUsesMouse() ); + + widget->setScreenWindow(_emulation->createWindow()); + } + + //connect view signals and slots + QObject::connect( widget ,SIGNAL(changedContentSizeSignal(int,int)),this, + SLOT(onViewSizeChange(int,int))); + + QObject::connect( widget ,SIGNAL(destroyed(QObject*)) , this , + SLOT(viewDestroyed(QObject*)) ); +//slot for close + QObject::connect(this, SIGNAL(finished()), widget, SLOT(close())); + +} + +void Session::viewDestroyed(QObject* view) +{ + TerminalDisplay* display = (TerminalDisplay*)view; + + Q_ASSERT( _views.contains(display) ); + + removeView(display); +} + +void Session::removeView(TerminalDisplay* widget) +{ + _views.removeAll(widget); + + disconnect(widget,0,this,0); + + if ( _emulation != 0 ) + { + // disconnect + // - key presses signals from widget + // - mouse activity signals from widget + // - string sending signals from widget + // + // ... and any other signals connected in addView() + disconnect( widget, 0, _emulation, 0); + + // disconnect state change signals emitted by emulation + disconnect( _emulation , 0 , widget , 0); + } + + // close the session automatically when the last view is removed + if ( _views.count() == 0 ) + { + close(); + } +} + +void Session::run() +{ + //check that everything is in place to run the session + if (_program.isEmpty()) + qDebug() << "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; + } + + QString cwd_save = QDir::currentPath(); + if (!_initialWorkingDir.isEmpty()) + _shellProcess->setWorkingDirectory(_initialWorkingDir); + else + _shellProcess->setWorkingDirectory(QDir::homePath()); + + _shellProcess->setXonXoff(_flowControl); + _shellProcess->setErase(_emulation->getErase()); + + // 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"; + + int result = _shellProcess->start(QFile::encodeName(_program), + arguments, + _environment << backgroundColorHint, + windowId(), + _addToUtmp); + + if (result < 0) + { + return; + } + + _shellProcess->setWriteable(false); // We are reachable via kwrited. + + emit started(); +} + +void Session::setUserTitle( int what, const QString &caption ) +{ + //set to true if anything is actually changed (eg. old _nameTitle != new _nameTitle ) + bool modified = false; + + // (btw: what=0 changes _userTitle and icon, what=1 only icon, what=2 only _nameTitle + if ((what == 0) || (what == 2)) + { + if ( _userTitle != caption ) { + _userTitle = caption; + modified = true; + } + } + + if ((what == 0) || (what == 1)) + { + if ( _iconText != caption ) { + _iconText = caption; + modified = true; + } + } + + if (what == 11) + { + 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); + } + } + } + + if (what == 30) + { + 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; + + modified = true; + } + } + + if (what == 50) + { + emit profileChangeCommandReceived(caption); + return; + } + + if ( modified ) + emit titleChanged(); +} + +QString Session::userTitle() const +{ + return _userTitle; +} +void Session::setTabTitleFormat(TabTitleContext context , const QString& format) +{ + if ( context == LocalTabTitle ) + _localTabTitleFormat = format; + else if ( context == RemoteTabTitle ) + _remoteTabTitleFormat = format; +} +QString Session::tabTitleFormat(TabTitleContext context) const +{ + if ( context == LocalTabTitle ) + return _localTabTitleFormat; + else if ( context == RemoteTabTitle ) + return _remoteTabTitleFormat; + + return QString(); +} + +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) { +// KNotification::event("Silence", ("Silence in session '%1'", _nameTitle), QPixmap(), +// QApplication::activeWindow(), +// KNotification::CloseWhenWidgetActivated); + emit stateChanged(NOTIFYSILENCE); + } + else + { + emit stateChanged(NOTIFYNORMAL); + } + + _notifiedActivity=false; +} + +void Session::activityStateSet(int state) +{ + if (state==NOTIFYBELL) + { + QString s; s.sprintf("Bell in session '%s'",_nameTitle.toAscii().data()); + + emit bellRequest( s ); + } + else if (state==NOTIFYACTIVITY) + { + if (_monitorSilence) { + _monitorTimer->start(_silenceSeconds*1000); + } + + if ( _monitorActivity ) { + //FIXME: See comments in Session::monitorTimerDone() + if (!_notifiedActivity) { +// KNotification::event("Activity", ("Activity in session '%1'", _nameTitle), QPixmap(), +// QApplication::activeWindow(), +// KNotification::CloseWhenWidgetActivated); + _notifiedActivity=true; + } + } + } + + if ( state==NOTIFYACTIVITY && !_monitorActivity ) + state = NOTIFYNORMAL; + if ( state==NOTIFYSILENCE && !_monitorSilence ) + state = NOTIFYNORMAL; + + emit stateChanged(state); +} + +void Session::onViewSizeChange(int /*height*/, int /*width*/) +{ + updateTerminalSize(); +} +void Session::onEmulationSizeChange(int lines , int columns) +{ + setSize( QSize(lines,columns) ); +} + +void Session::updateTerminalSize() +{ + QListIterator<TerminalDisplay*> viewIter(_views); + + int minLines = -1; + int minColumns = -1; + + // minimum number of lines and columns that views require for + // their size to be taken into consideration ( to avoid problems + // with new view widgets which haven't yet been set to their correct size ) + const int VIEW_LINES_THRESHOLD = 2; + const int VIEW_COLUMNS_THRESHOLD = 2; + + //select largest number of lines and columns that will fit in all visible views + while ( viewIter.hasNext() ) + { + TerminalDisplay* view = viewIter.next(); + if ( view->isHidden() == false && + view->lines() >= VIEW_LINES_THRESHOLD && + view->columns() >= VIEW_COLUMNS_THRESHOLD ) + { + minLines = (minLines == -1) ? view->lines() : qMin( minLines , view->lines() ); + minColumns = (minColumns == -1) ? view->columns() : qMin( minColumns , view->columns() ); + } + } + + // backend emulation must have a _terminal of at least 1 column x 1 line in size + if ( minLines > 0 && minColumns > 0 ) + { + _emulation->setImageSize( minLines , minColumns ); + _shellProcess->setWindowSize( minLines , minColumns ); + } +} + +void Session::refresh() +{ + // attempt to get the shell process to redraw the display + // + // this requires the program running in the shell + // to cooperate by sending an update in response to + // a window size change + // + // the window size is changed twice, first made slightly larger and then + // resized back to its normal size so that there is actually a change + // in the window size (some shells do nothing if the + // new and old sizes are the same) + // + // if there is a more 'correct' way to do this, please + // send an email with method or patches to konsole-devel@kde.org + + const QSize existingSize = _shellProcess->windowSize(); + _shellProcess->setWindowSize(existingSize.height(),existingSize.width()+1); + _shellProcess->setWindowSize(existingSize.height(),existingSize.width()); +} + +bool Session::sendSignal(int signal) +{ + return _shellProcess->kill(signal); +} + +void Session::close() +{ + _autoClose = true; + _wantedClose = true; + if (!_shellProcess->isRunning() || !sendSignal(SIGHUP)) + { + // Forced close. + QTimer::singleShot(1, this, SIGNAL(finished())); + } +} + +void Session::sendText(const QString &text) const +{ + _emulation->sendText(text); +} + +Session::~Session() +{ + delete _emulation; + delete _shellProcess; +// delete _zmodemProc; +} + +void Session::setProfileKey(const QString& key) +{ + _profileKey = key; + emit profileChanged(key); +} +QString Session::profileKey() const { return _profileKey; } + +void Session::done(int exitStatus) +{ + if (!_autoClose) + { + _userTitle = ("<Finished>"); + emit titleChanged(); + return; + } + if (!_wantedClose && (exitStatus || _shellProcess->signalled())) + { + QString message; + + if (_shellProcess->normalExit()) + message.sprintf ("Session '%s' exited with status %d.", _nameTitle.toAscii().data(), exitStatus); + else if (_shellProcess->signalled()) + { + if (_shellProcess->coreDumped()) + { + + 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()); + + //FIXME: See comments in Session::monitorTimerDone() +// KNotification::event("Finished", message , QPixmap(), +// QApplication::activeWindow(), +// KNotification::CloseWhenWidgetActivated); + } + emit finished(); +} + +Emulation* Session::emulation() const +{ + return _emulation; +} + +QString Session::keyBindings() const +{ + return _emulation->keyBindings(); +} + +QStringList Session::environment() const +{ + return _environment; +} + +void Session::setEnvironment(const QStringList& environment) +{ + _environment = environment; +} + +int Session::sessionId() const +{ + return _sessionId; +} + +void Session::setKeyBindings(const QString &id) +{ + _emulation->setKeyBindings(id); +} + +void Session::setTitle(TitleRole role , const QString& newTitle) +{ + if ( title(role) != newTitle ) + { + if ( role == NameRole ) + _nameTitle = newTitle; + else if ( role == DisplayedTitleRole ) + _displayTitle = newTitle; + + emit titleChanged(); + } +} + +QString Session::title(TitleRole role) const +{ + if ( role == NameRole ) + return _nameTitle; + else if ( role == DisplayedTitleRole ) + return _displayTitle; + else + return QString(); +} + +void Session::setIconName(const QString& iconName) +{ + if ( iconName != _iconName ) + { + _iconName = iconName; + emit titleChanged(); + } +} + +void Session::setIconText(const QString& iconText) +{ + _iconText = iconText; + //kDebug(1211)<<"Session setIconText " << _iconText; +} + +QString Session::iconName() const +{ + return _iconName; +} + +QString Session::iconText() const +{ + return _iconText; +} + +void Session::setHistoryType(const HistoryType &hType) +{ + _emulation->setHistory(hType); +} + +const HistoryType& Session::historyType() const +{ + return _emulation->history(); +} + +void Session::clearHistory() +{ + _emulation->clearHistory(); +} + +QStringList Session::arguments() const +{ + return _arguments; +} + +QString Session::program() const +{ + return _program; +} + +// unused currently +bool Session::isMonitorActivity() const { return _monitorActivity; } +// unused currently +bool Session::isMonitorSilence() const { return _monitorSilence; } + +void Session::setMonitorActivity(bool _monitor) +{ + _monitorActivity=_monitor; + _notifiedActivity=false; + + activityStateSet(NOTIFYNORMAL); +} + +void Session::setMonitorSilence(bool _monitor) +{ + if (_monitorSilence==_monitor) + return; + + _monitorSilence=_monitor; + if (_monitorSilence) + { + _monitorTimer->start(_silenceSeconds*1000); + } + else + _monitorTimer->stop(); + + activityStateSet(NOTIFYNORMAL); +} + +void Session::setMonitorSilenceSeconds(int seconds) +{ + _silenceSeconds=seconds; + if (_monitorSilence) { + _monitorTimer->start(_silenceSeconds*1000); + } +} + +void Session::setAddToUtmp(bool set) +{ + _addToUtmp = set; +} + +void Session::setFlowControlEnabled(bool enabled) +{ + if (_flowControl == enabled) + return; + + _flowControl = enabled; + + if (_shellProcess) + _shellProcess->setXonXoff(_flowControl); + + emit flowControlEnabledChanged(enabled); +} +bool Session::flowControlEnabled() const +{ + 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); +// +// _zmodemProc->start(); +// +// connect(_zmodemProc,SIGNAL (readyReadStandardOutput()), +// this, SLOT(zmodemReadAndSendBlock())); +// connect(_zmodemProc,SIGNAL (readyReadStandardError()), +// this, SLOT(zmodemReadStatus())); +// connect(_zmodemProc,SIGNAL (finished(int,QProcess::ExitStatus)), +// this, SLOT(zmodemFinished())); +// +// disconnect( _shellProcess,SIGNAL(block_in(const char*,int)), this, SLOT(onReceiveBlock(const char*,int)) ); +// connect( _shellProcess,SIGNAL(block_in(const char*,int)), this, SLOT(zmodemRcvBlock(const char*,int)) ); +// +// _zmodemProgress = new ZModemDialog(QApplication::activeWindow(), false, +// i18n("ZModem Progress")); +// +// connect(_zmodemProgress, SIGNAL(user1Clicked()), +// this, SLOT(zmodemDone())); +// +// _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() +{ + if (_zmodemProc) + { + delete _zmodemProc; + _zmodemProc = 0; + _zmodemBusy = false; + + disconnect( _shellProcess,SIGNAL(block_in(const char*,int)), this ,SLOT(zmodemRcvBlock(const char*,int)) ); + connect( _shellProcess,SIGNAL(block_in(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 ); + emit receivedData( QString::fromLatin1( buf, len ) ); +} + +QSize Session::size() +{ + return _emulation->imageSize(); +} + +void Session::setSize(const QSize& size) +{ + if ((size.width() <= 1) || (size.height() <= 1)) + return; + + emit resizeRequest(size); +} +int Session::foregroundProcessId() const +{ + return _shellProcess->foregroundProcessGroup(); +} +int Session::processId() const +{ + return _shellProcess->pid(); +} + +SessionGroup::SessionGroup() + : _masterMode(0) +{ +} +SessionGroup::~SessionGroup() +{ + // disconnect all + connectAll(false); +} +int SessionGroup::masterMode() const { return _masterMode; } +QList<Session*> SessionGroup::sessions() const { return _sessions.keys(); } +bool SessionGroup::masterStatus(Session* session) const { return _sessions[session]; } + +void SessionGroup::addSession(Session* session) +{ + _sessions.insert(session,false); + + QListIterator<Session*> masterIter(masters()); + + while ( masterIter.hasNext() ) + connectPair(masterIter.next(),session); +} +void SessionGroup::removeSession(Session* session) +{ + setMasterStatus(session,false); + + QListIterator<Session*> masterIter(masters()); + + while ( masterIter.hasNext() ) + disconnectPair(masterIter.next(),session); + + _sessions.remove(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]; + _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); + } + } +} +void SessionGroup::connectPair(Session* master , Session* other) +{ +// 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)) ); + } +} +void SessionGroup::disconnectPair(Session* master , Session* other) +{ +// qDebug() << k_funcinfo; + + 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)) ); + } +} + +//#include "moc_Session.cpp" diff --git a/client/browser/qtermwidget/includes/Session.h b/client/browser/qtermwidget/src/Session.h index 7b2ae25c..7b2ae25c 100644 --- a/client/browser/qtermwidget/includes/Session.h +++ b/client/browser/qtermwidget/src/Session.h diff --git a/client/browser/qtermwidget/src/ShellCommand.cpp b/client/browser/qtermwidget/src/ShellCommand.cpp new file mode 100644 index 00000000..764dd66c --- /dev/null +++ b/client/browser/qtermwidget/src/ShellCommand.cpp @@ -0,0 +1,168 @@ +/* + Copyright (C) 2007 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 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 "ShellCommand.h" + +//some versions of gcc(4.3) require explicit include +#include <cstdlib> + + +using namespace Konsole; + +// expands environment variables in 'text' +// function copied from kdelibs/kio/kio/kurlcompletion.cpp +static bool expandEnv(QString& text); + +ShellCommand::ShellCommand(const QString& fullCommand) +{ + bool inQuotes = false; + + QString builder; + + for ( int i = 0 ; i < fullCommand.count() ; i++ ) + { + QChar ch = fullCommand[i]; + + const bool isLastChar = ( i == fullCommand.count() - 1 ); + const bool isQuote = ( ch == '\'' || ch == '\"' ); + + if ( !isLastChar && isQuote ) + inQuotes = !inQuotes; + else + { + if ( (!ch.isSpace() || inQuotes) && !isQuote ) + builder.append(ch); + + if ( (ch.isSpace() && !inQuotes) || ( i == fullCommand.count()-1 ) ) + { + _arguments << builder; + builder.clear(); + } + } + } +} +ShellCommand::ShellCommand(const QString& command , const QStringList& arguments) +{ + _arguments = arguments; + + if ( !_arguments.isEmpty() ) + _arguments[0] == command; +} +QString ShellCommand::fullCommand() const +{ + return _arguments.join(QChar(' ')); +} +QString ShellCommand::command() const +{ + if ( !_arguments.isEmpty() ) + return _arguments[0]; + else + return QString(); +} +QStringList ShellCommand::arguments() const +{ + return _arguments; +} +bool ShellCommand::isRootCommand() const +{ + Q_ASSERT(0); // not implemented yet + return false; +} +bool ShellCommand::isAvailable() const +{ + Q_ASSERT(0); // not implemented yet + return false; +} +QStringList ShellCommand::expand(const QStringList& items) +{ + QStringList result; + + foreach( QString item , items ) + result << expand(item); + + return result; +} +QString ShellCommand::expand(const QString& text) +{ + QString result = text; + expandEnv(result); + return result; +} + +/* + * expandEnv + * + * Expand environment variables in text. Escaped '$' characters are ignored. + * Return true if any variables were expanded + */ +static bool expandEnv( QString &text ) +{ + // Find all environment variables beginning with '$' + // + int pos = 0; + + bool expanded = false; + + while ( (pos = text.indexOf(QLatin1Char('$'), pos)) != -1 ) { + + // Skip escaped '$' + // + if ( pos > 0 && text.at(pos-1) == QLatin1Char('\\') ) { + pos++; + } + // Variable found => expand + // + else { + // Find the end of the variable = next '/' or ' ' + // + int pos2 = text.indexOf( QLatin1Char(' '), pos+1 ); + int pos_tmp = text.indexOf( QLatin1Char('/'), pos+1 ); + + if ( pos2 == -1 || (pos_tmp != -1 && pos_tmp < pos2) ) + pos2 = pos_tmp; + + if ( pos2 == -1 ) + pos2 = text.length(); + + // Replace if the variable is terminated by '/' or ' ' + // and defined + // + if ( pos2 >= 0 ) { + int len = pos2 - pos; + QString key = text.mid( pos+1, len-1); + QString value = + QString::fromLocal8Bit( ::getenv(key.toLocal8Bit()) ); + + if ( !value.isEmpty() ) { + expanded = true; + text.replace( pos, len, value ); + pos = pos + value.length(); + } + else { + pos = pos2; + } + } + } + } + + return expanded; +} diff --git a/client/browser/qtermwidget/includes/ShellCommand.h b/client/browser/qtermwidget/src/ShellCommand.h index 44e0db8b..44e0db8b 100644 --- a/client/browser/qtermwidget/includes/ShellCommand.h +++ b/client/browser/qtermwidget/src/ShellCommand.h diff --git a/client/browser/qtermwidget/src/TerminalCharacterDecoder.cpp b/client/browser/qtermwidget/src/TerminalCharacterDecoder.cpp new file mode 100644 index 00000000..18571d9d --- /dev/null +++ b/client/browser/qtermwidget/src/TerminalCharacterDecoder.cpp @@ -0,0 +1,227 @@ +/* + This file is part of Konsole, an X terminal. + + Copyright (C) 2006 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 + (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 Lesser 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 "TerminalCharacterDecoder.h" + +// Qt +#include <QtCore/QTextStream> + + +using namespace Konsole; + +PlainTextDecoder::PlainTextDecoder() + : _output(0) + , _includeTrailingWhitespace(true) +{ + +} +void PlainTextDecoder::setTrailingWhitespace(bool enable) +{ + _includeTrailingWhitespace = enable; +} +bool PlainTextDecoder::trailingWhitespace() const +{ + return _includeTrailingWhitespace; +} +void PlainTextDecoder::begin(QTextStream* output) +{ + _output = output; +} +void PlainTextDecoder::end() +{ + _output = 0; +} +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? + + //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; + + // if inclusion of trailing whitespace is disabled then find the end of the + // line + if ( !_includeTrailingWhitespace ) + { + for (int i = count-1 ; i >= 0 ; i--) + { + if ( characters[i].character != ' ' ) + break; + else + outputCount--; + } + } + + for (int i=0;i<outputCount;i++) + { + plainText.append( QChar(characters[i].character) ); + } + + *_output << plainText; +} + +HTMLDecoder::HTMLDecoder() : + _output(0) + ,_colorTable(base_color_table) + ,_innerSpanOpen(false) + ,_lastRendition(DEFAULT_RENDITION) +{ + +} + +void HTMLDecoder::begin(QTextStream* output) +{ + _output = output; + + QString text; + + //open monospace span + openSpan(text,"font-family:monospace"); + + *output << text; +} + +void HTMLDecoder::end() +{ + Q_ASSERT( _output ); + + QString text; + + closeSpan(text); + + *_output << text; + + _output = 0; + +} + +//TODO: Support for LineProperty (mainly double width , double height) +void HTMLDecoder::decodeLine(const Character* const characters, int count, LineProperty /*properties*/ + ) +{ + Q_ASSERT( _output ); + + QString text; + + 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); + + _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;"); + + + 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; + } + + //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("<"); + else if (ch == '>') + text.append(">"); + else + text.append(ch); + } + else + { + text.append(" "); //HTML truncates multiple spaces, so use a space marker instead + } + + } + + //close any remaining open inner spans + if ( _innerSpanOpen ) + closeSpan(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) ); +} + +void HTMLDecoder::closeSpan(QString& text) +{ + text.append("</span>"); +} + +void HTMLDecoder::setColorTable(const ColorEntry* table) +{ + _colorTable = table; +} diff --git a/client/browser/qtermwidget/includes/TerminalCharacterDecoder.h b/client/browser/qtermwidget/src/TerminalCharacterDecoder.h index 5d97fc37..5d97fc37 100644 --- a/client/browser/qtermwidget/includes/TerminalCharacterDecoder.h +++ b/client/browser/qtermwidget/src/TerminalCharacterDecoder.h diff --git a/client/browser/qtermwidget/src/TerminalDisplay.cpp b/client/browser/qtermwidget/src/TerminalDisplay.cpp new file mode 100644 index 00000000..35463a92 --- /dev/null +++ b/client/browser/qtermwidget/src/TerminalDisplay.cpp @@ -0,0 +1,2726 @@ +/* + 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> + + 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 + (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 "TerminalDisplay.h" +#include "TerminalDisplay.moc" + +// Qt +#include <QtGui/QApplication> +#include <QtGui/QBoxLayout> +#include <QtGui/QClipboard> +#include <QtGui/QKeyEvent> +#include <QtCore/QEvent> +#include <QtCore/QTime> +#include <QtCore/QFile> +#include <QtGui/QGridLayout> +#include <QtGui/QLabel> +#include <QtGui/QLayout> +#include <QtGui/QPainter> +#include <QtGui/QPixmap> +#include <QtGui/QScrollBar> +#include <QtGui/QStyle> +#include <QtCore> +#include <QtGui> + +#include "Filter.h" +#include "konsole_wcwidth.h" +#include "ScreenWindow.h" +#include "TerminalCharacterDecoder.h" +#include "ColorTables.h" + + +using namespace Konsole; + +#ifndef loc +#define loc(X,Y) ((Y)*_columns+(X)) +#endif + +#define yMouseScroll 1 + +#define REPCHAR "ABCDEFGHIJKLMNOPQRSTUVWXYZ" \ + "abcdefgjijklmnopqrstuvwxyz" \ + "0123456789./+@" + +// scroll increment used when dragging selection at top/bottom of window. + +// static +bool TerminalDisplay::_antialiasText = true; +bool TerminalDisplay::HAVE_TRANSPARENCY = false; + +/* ------------------------------------------------------------------------- */ +/* */ +/* Colors */ +/* */ +/* ------------------------------------------------------------------------- */ + +/* Note that we use ANSI color order (bgr), while IBMPC color order is (rgb) + + Code 0 1 2 3 4 5 6 7 + ----------- ------- ------- ------- ------- ------- ------- ------- ------- + ANSI (bgr) Black Red Green Yellow Blue Magenta Cyan White + IBMPC (rgb) Black Blue Green Cyan Red Magenta Yellow White +*/ + +ScreenWindow* TerminalDisplay::screenWindow() const +{ + return _screenWindow; +} +void TerminalDisplay::setScreenWindow(ScreenWindow* window) +{ + // disconnect existing screen window if any + if ( _screenWindow ) + { + disconnect( _screenWindow , 0 , this , 0 ); + } + + _screenWindow = window; + + if ( window ) + { +//#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); + } +} + +const ColorEntry* TerminalDisplay::colorTable() const +{ + return _colorTable; +} + +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(); +} + +/* ------------------------------------------------------------------------- */ +/* */ +/* Font */ +/* */ +/* ------------------------------------------------------------------------- */ + +/* + The VT100 has 32 special graphical characters. The usual vt100 extended + xterm fonts have these at 0x00..0x1f. + + QT's iso mapping leaves 0x00..0x7f without any changes. But the graphicals + come in here as proper unicode characters. + + We treat non-iso10646 fonts as VT100 extended and do the requiered mapping + from unicode to 0x00..0x1f. The remaining translation is then left to the + QCodec. +*/ + +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())); +} + + +// assert for i in [0..31] : vt100extended(vt100_graphics[i]) == i. + +unsigned short Konsole::vt100_graphics[32] = +{ // 0/8 1/9 2/10 3/11 4/12 5/13 6/14 7/15 + 0x0020, 0x25C6, 0x2592, 0x2409, 0x240c, 0x240d, 0x240a, 0x00b0, + 0x00b1, 0x2424, 0x240b, 0x2518, 0x2510, 0x250c, 0x2514, 0x253c, + 0xF800, 0xF801, 0x2500, 0xF803, 0xF804, 0x251c, 0x2524, 0x2534, + 0x252c, 0x2502, 0x2264, 0x2265, 0x03C0, 0x2260, 0x00A3, 0x00b7 +}; + +void TerminalDisplay::fontChange(const QFont&) +{ + QFontMetrics fm(font()); + _fontHeight = fm.height() + _lineSpacing; + + + // waba TerminalDisplay 1.123: + // "Base character width on widest ASCII character. This prevents too wide + // characters in the presence of double wide (e.g. Japanese) characters." + // Get the width from representative normal width characters + _fontWidth = qRound((double)fm.width(REPCHAR)/(double)strlen(REPCHAR)); + + _fixedFont = true; + + int fw = fm.width(REPCHAR[0]); + for(unsigned int i=1; i< strlen(REPCHAR); i++) + { + if (fw != fm.width(REPCHAR[i])) + { + _fixedFont = false; + break; + } + } + + if (_fontWidth < 1) + _fontWidth=1; + + _fontAscent = fm.ascent(); + + emit changedFontMetricSignal( _fontHeight, _fontWidth ); + propagateSize(); + update(); +} + +void TerminalDisplay::setVTFont(const QFont& f) +{ + QFont font = f; + + QFontMetrics metrics(font); + + if ( metrics.height() < height() && metrics.maxWidth() < width() ) + { + // hint that text should be drawn without anti-aliasing. + // depending on the user's font configuration, this may not be respected + if (!_antialiasText) + font.setStyleStrategy( QFont::NoAntialias ); + + // experimental optimization. Konsole assumes that the terminal is using a + // mono-spaced font, in which case kerning information should have an effect. + // Disabling kerning saves some computation when rendering text. + font.setKerning(false); + + QWidget::setFont(font); + fontChange(font); + } +} + +void TerminalDisplay::setFont(const QFont &) +{ + // ignore font change request if not coming from konsole itself +} + +/* ------------------------------------------------------------------------- */ +/* */ +/* Constructor / Destructor */ +/* */ +/* ------------------------------------------------------------------------- */ + +TerminalDisplay::TerminalDisplay(QWidget *parent) +:QWidget(parent) +,_screenWindow(0) +,_allowBell(true) +,_gridLayout(0) +,_fontHeight(1) +,_fontWidth(1) +,_fontAscent(1) +,_lines(1) +,_columns(1) +,_usedLines(1) +,_usedColumns(1) +,_contentHeight(1) +,_contentWidth(1) +,_image(0) +,_randomSeed(0) +,_resizing(false) +,_terminalSizeHint(false) +,_terminalSizeStartup(true) +,_bidiEnabled(false) +,_actSel(0) +,_wordSelectionMode(false) +,_lineSelectionMode(false) +,_preserveLineBreaks(false) +,_columnSelectionMode(false) +,_scrollbarLocation(NoScrollBar) +,_wordCharacters(":@-./_~") +,_bellMode(SystemBeepBell) +,_blinking(false) +,_cursorBlinking(false) +,_hasBlinkingCursor(false) +,_ctrlDrag(false) +,_tripleClickMode(SelectWholeLine) +,_isFixedSize(false) +,_possibleTripleClick(false) +,_resizeWidget(0) +,_resizeTimer(0) +,_flowControlWarningEnabled(false) +,_outputSuspendedLabel(0) +,_lineSpacing(0) +,_colorsInverted(false) +,_blendColor(qRgba(0,0,0,0xff)) +,_filterChain(new TerminalImageFilterChain()) +,_cursorShape(BlockCursor) +{ + // terminal applications are not designed with Right-To-Left in mind, + // so the layout is forced to Left-To-Right + setLayoutDirection(Qt::LeftToRight); + + // The offsets are not yet calculated. + // Do not calculate these too often to be more smoothly when resizing + // konsole in opaque mode. + _topMargin = DEFAULT_TOP_MARGIN; + _leftMargin = DEFAULT_LEFT_MARGIN; + + // create scroll bar for scrolling output up and down + // set the scroll bar's slider to occupy the whole area of the scroll bar initially + _scrollBar = new QScrollBar(this); + setScroll(0,0); + _scrollBar->setCursor( Qt::ArrowCursor ); + connect(_scrollBar, SIGNAL(valueChanged(int)), this, + SLOT(scrollBarPositionChanged(int))); + + // setup timers for blinking cursor and text + _blinkTimer = new QTimer(this); + connect(_blinkTimer, SIGNAL(timeout()), this, SLOT(blinkEvent())); + _blinkCursorTimer = new QTimer(this); + connect(_blinkCursorTimer, SIGNAL(timeout()), this, SLOT(blinkCursorEvent())); + +// QCursor::setAutoHideCursor( this, true ); + + setUsesMouse(true); + setColorTable(whiteonblack_color_table); +// setColorTable(blackonlightyellow_color_table); + setMouseTracking(true); + + // Enable drag and drop + setAcceptDrops(true); // attempt + dragInfo.state = diNone; + + setFocusPolicy( Qt::WheelFocus ); + + // enable input method support + setAttribute(Qt::WA_InputMethodEnabled, true); + + // this is an important optimization, it tells Qt + // that TerminalDisplay will handle repainting its entire area. + setAttribute(Qt::WA_OpaquePaintEvent); + + _gridLayout = new QGridLayout(this); + _gridLayout->setMargin(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)) ); +} + +TerminalDisplay::~TerminalDisplay() +{ + qApp->removeEventFilter( this ); + + delete[] _image; + + delete _gridLayout; + delete _outputSuspendedLabel; + delete _filterChain; +} + +/* ------------------------------------------------------------------------- */ +/* */ +/* Display Operations */ +/* */ +/* ------------------------------------------------------------------------- */ + +/** + A table for emulating the simple (single width) unicode drawing chars. + It represents the 250x - 257x glyphs. If it's zero, we can't use it. + if it's not, it's encoded as follows: imagine a 5x5 grid where the points are numbered + 0 to 24 left to top, top to bottom. Each point is represented by the corresponding bit. + + Then, the pixels basically have the following interpretation: + _|||_ + -...- + -...- + -...- + _|||_ + +where _ = none + | = vertical line. + - = horizontal line. + */ + + +enum LineEncode +{ + TopL = (1<<1), + TopC = (1<<2), + TopR = (1<<3), + + LeftT = (1<<5), + Int11 = (1<<6), + Int12 = (1<<7), + Int13 = (1<<8), + RightT = (1<<9), + + LeftC = (1<<10), + Int21 = (1<<11), + Int22 = (1<<12), + Int23 = (1<<13), + RightC = (1<<14), + + LeftB = (1<<15), + Int31 = (1<<16), + Int32 = (1<<17), + Int33 = (1<<18), + RightB = (1<<19), + + BotL = (1<<21), + BotC = (1<<22), + BotR = (1<<23) +}; + +#include "LineFont.h" + +static void drawLineChar(QPainter& paint, int x, int y, int w, int h, uchar code) +{ + //Calculate cell midpoints, end points. + int cx = x + w/2; + int cy = y + h/2; + int ex = x + w - 1; + int ey = y + h - 1; + + quint32 toDraw = LineChars[code]; + + //Top _lines: + if (toDraw & TopL) + paint.drawLine(cx-1, y, cx-1, cy-2); + if (toDraw & TopC) + paint.drawLine(cx, y, cx, cy-2); + if (toDraw & TopR) + paint.drawLine(cx+1, y, cx+1, cy-2); + + //Bot _lines: + if (toDraw & BotL) + paint.drawLine(cx-1, cy+2, cx-1, ey); + if (toDraw & BotC) + paint.drawLine(cx, cy+2, cx, ey); + if (toDraw & BotR) + paint.drawLine(cx+1, cy+2, cx+1, ey); + + //Left _lines: + if (toDraw & LeftT) + paint.drawLine(x, cy-1, cx-2, cy-1); + if (toDraw & LeftC) + paint.drawLine(x, cy, cx-2, cy); + if (toDraw & LeftB) + paint.drawLine(x, cy+1, cx-2, cy+1); + + //Right _lines: + if (toDraw & RightT) + paint.drawLine(cx+2, cy-1, ex, cy-1); + if (toDraw & RightC) + paint.drawLine(cx+2, cy, ex, cy); + if (toDraw & RightB) + paint.drawLine(cx+2, cy+1, ex, cy+1); + + //Intersection points. + if (toDraw & Int11) + paint.drawPoint(cx-1, cy-1); + if (toDraw & Int12) + paint.drawPoint(cx, cy-1); + if (toDraw & Int13) + paint.drawPoint(cx+1, cy-1); + + if (toDraw & Int21) + paint.drawPoint(cx-1, cy); + if (toDraw & Int22) + paint.drawPoint(cx, cy); + if (toDraw & Int23) + paint.drawPoint(cx+1, cy); + + if (toDraw & Int31) + paint.drawPoint(cx-1, cy+1); + if (toDraw & Int32) + paint.drawPoint(cx, cy+1); + if (toDraw & Int33) + paint.drawPoint(cx+1, cy+1); + +} + +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 ); +} + +void TerminalDisplay::setKeyboardCursorShape(KeyboardCursorShape shape) +{ + _cursorShape = shape; +} +TerminalDisplay::KeyboardCursorShape TerminalDisplay::keyboardCursorShape() const +{ + return _cursorShape; +} +void TerminalDisplay::setKeyboardCursorColor(bool useForegroundColor, const QColor& color) +{ + if (useForegroundColor) + _cursorColor = QColor(); // an invalid color means that + // the foreground color of the + // current character should + // be used + + else + _cursorColor = color; +} +QColor TerminalDisplay::keyboardCursorColor() const +{ + return _cursorColor; +} + +void TerminalDisplay::setOpacity(qreal opacity) +{ + QColor color(_blendColor); + color.setAlphaF(opacity); + + // enable automatic background filling to prevent the display + // flickering if there is no transparency + if ( color.alpha() == 255 ) + { + setAutoFillBackground(true); + } + else + { + setAutoFillBackground(false); + } + + _blendColor = color.rgba(); +} + +void TerminalDisplay::drawBackground(QPainter& painter, const QRect& rect, const QColor& backgroundColor, bool useOpacitySetting ) +{ + // the area of the widget showing the contents of the terminal display is drawn + // using the background color from the color scheme set with setColorTable() + // + // the area of the widget behind the scroll-bar is drawn using the background + // brush from the scroll-bar's palette, to give the effect of the scroll-bar + // being outside of the terminal display and visual consistency with other KDE + // applications. + // + QRect scrollBarArea = _scrollBar->isVisible() ? + rect.intersected(_scrollBar->geometry()) : + QRect(); + QRegion contentsRegion = QRegion(rect).subtracted(scrollBarArea); + QRect contentsRect = contentsRegion.boundingRect(); + + if ( HAVE_TRANSPARENCY && qAlpha(_blendColor) < 0xff && useOpacitySetting ) + { + QColor color(backgroundColor); + color.setAlpha(qAlpha(_blendColor)); + + painter.save(); + painter.setCompositionMode(QPainter::CompositionMode_Source); + painter.fillRect(contentsRect, color); + painter.restore(); + } + else { + painter.fillRect(contentsRect, backgroundColor); + } + + painter.fillRect(scrollBarArea,_scrollBar->palette().background()); +} + +void TerminalDisplay::drawCursor(QPainter& painter, + const QRect& rect, + const QColor& foregroundColor, + const QColor& /*backgroundColor*/, + bool& invertCharacterColor) +{ + QRect cursorRect = rect; + cursorRect.setHeight(_fontHeight - _lineSpacing - 1); + + if (!_cursorBlinking) + { + if ( _cursorColor.isValid() ) + painter.setPen(_cursorColor); + else { + painter.setPen(foregroundColor); + } + + if ( _cursorShape == BlockCursor ) + { + // draw the cursor outline, adjusting the area so that + // it is draw entirely inside 'rect' + int penWidth = qMax(1,painter.pen().width()); + + painter.drawRect(cursorRect.adjusted(penWidth/2, + penWidth/2, + - penWidth/2 - penWidth%2, + - penWidth/2 - penWidth%2)); + 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 + // the cursor position is readable + invertCharacterColor = true; + } + } + } + else if ( _cursorShape == UnderlineCursor ) + painter.drawLine(cursorRect.left(), + cursorRect.bottom(), + cursorRect.right(), + cursorRect.bottom()); + else if ( _cursorShape == IBeamCursor ) + painter.drawLine(cursorRect.left(), + cursorRect.top(), + cursorRect.left(), + cursorRect.bottom()); + + } +} + +void TerminalDisplay::drawCharacters(QPainter& painter, + const QRect& rect, + const QString& text, + const Character* style, + bool invertCharacterColor) +{ + // don't draw text which is currently blinking + if ( _blinking && (style->rendition & RE_BLINK) ) + return; + + // setup bold and underline + bool useBold = style->rendition & RE_BOLD || style->isBold(_colorTable) || font().bold(); + bool useUnderline = style->rendition & RE_UNDERLINE || font().underline(); + + QFont font = painter.font(); + if ( font.bold() != useBold + || font.underline() != useUnderline ) + { + font.setBold(useBold); + font.setUnderline(useUnderline); + painter.setFont(font); + } + + 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); + } + 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); + } +} + +void TerminalDisplay::drawTextFragment(QPainter& painter , + const QRect& rect, + const QString& text, + const Character* style) +{ + painter.save(); + + // setup painter + const QColor foregroundColor = style->foregroundColor.color(_colorTable); + const QColor backgroundColor = style->backgroundColor.color(_colorTable); + + // draw background if different from the display's background color + if ( backgroundColor != palette().background().color() ) + drawBackground(painter,rect,backgroundColor, 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); + + painter.restore(); +} + +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 +// image as it receives input, and when the view is updated, it calls scrollImage() +// with the final scroll amount. this improves performance because scrolling the +// display is much cheaper than re-rendering all the text for the +// part of the image which has moved up or down. +// Instead only new lines have to be drawn +// +// 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; + } + + // constrain the region to the display + // the bottom of the region is capped to the number of lines in the display's + // internal image - 2, so that the height of 'region' is strictly less + // than the height of the internal image. + QRect region = screenWindowRegion; + region.setBottom( qMin(region.bottom(),this->_lines-2) ); + + if ( lines == 0 + || _image == 0 + || !region.isValid() + || (region.top() + abs(lines)) >= region.bottom() + || this->_lines <= region.height() ) return; + + QRect scrollRect; + + void* firstCharPos = &_image[ region.top() * this->_columns ]; + void* lastCharPos = &_image[ (region.top() + abs(lines)) * this->_columns ]; + + int top = _topMargin + (region.top() * _fontHeight); + int linesToMove = region.height() - abs(lines); + int bytesToMove = linesToMove * + this->_columns * + sizeof(Character); + + Q_ASSERT( linesToMove > 0 ); + Q_ASSERT( bytesToMove > 0 ); + + //scroll internal image + if ( lines > 0 ) + { + // check that the memory areas that we are going to move are valid + Q_ASSERT( (char*)lastCharPos + bytesToMove < + (char*)(_image + (this->_lines * this->_columns)) ); + + Q_ASSERT( (lines*this->_columns) < _imageSize ); + + //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 ); + } + else + { + // check that the memory areas that we are going to move are valid + Q_ASSERT( (char*)firstCharPos + bytesToMove < + (char*)(_image + (this->_lines * this->_columns)) ); + + //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 )); + } + + //scroll the display vertically to match internal _image + scroll( 0 , _fontHeight * (-lines) , scrollRect ); +} + +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; +} + +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() ); + _filterChain->process(); + + QRegion postUpdateHotSpots = hotSpotRegion(); + + update( preUpdateHotSpots | postUpdateHotSpots ); +} + +void TerminalDisplay::updateImage() +{ + if ( !_screenWindow ) + return; + + // optimization - scroll the existing image where possible and + // avoid expensive text drawing for parts of the image that + // can simply be moved up or down + scrollImage( _screenWindow->scrollCount() , + _screenWindow->scrollRegion() ); + _screenWindow->resetScrollCount(); + + 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; + + CharacterColor cf; // undefined + CharacterColor _clipboard; // undefined + int cr = -1; // undefined + + const int linesToUpdate = qMin(this->_lines, qMax(0,lines )); + const int columnsToUpdate = qMin(this->_columns,qMax(0,columns)); + + QChar *disstrU = new QChar[columnsToUpdate]; + char *dirtyMask = new char[columnsToUpdate+2]; + QRegion dirtyRegion; + + // debugging variable, this records the number of lines that are found to + // be 'dirty' ( ie. have changed from the old _image to the new _image ) and + // which therefore need to be repainted + int dirtyLineCount = 0; + + for (y = 0; y < linesToUpdate; y++) + { + const Character* currentLine = &_image[y*this->_columns]; + const Character* const newLine = &newimg[y*columns]; + + bool updateLine = false; + + // The dirty mask indicates which characters need repainting. We also + // mark surrounding neighbours dirty, in case the character exceeds + // its cell boundaries + memset(dirtyMask, 0, columnsToUpdate+2); + + for( x = 0 ; x < columnsToUpdate ; x++) + { + if ( newLine[x] != currentLine[x] ) + { + dirtyMask[x] = true; + } + } + + if (!_resizing) // not while _resizing, we're expecting a paintEvent + for (x = 0; x < columnsToUpdate; x++) + { + _hasBlinker |= (newLine[x].rendition & RE_BLINK); + + // Start drawing if this character or the next one differs. + // We also take the next one into account to handle the situation + // where characters exceed their cell width. + if (dirtyMask[x]) + { + quint16 c = newLine[x+0].character; + if ( !c ) + continue; + int p = 0; + disstrU[p++] = c; //fontMap(c); + bool lineDraw = isLineChar(c); + bool doubleWidth = (x+1 == columnsToUpdate) ? false : (newLine[x+1].character == 0); + cr = newLine[x].rendition; + _clipboard = newLine[x].backgroundColor; + if (newLine[x].foregroundColor != cf) cf = newLine[x].foregroundColor; + int lln = columnsToUpdate - x; + for (len = 1; len < lln; len++) + { + const Character& ch = newLine[x+len]; + + if (!ch.character) + continue; // Skip trailing part of multi-col chars. + + bool nextIsDoubleWidth = (x+len+1 == columnsToUpdate) ? false : (newLine[x+len+1].character == 0); + + if ( ch.foregroundColor != cf || + ch.backgroundColor != _clipboard || + ch.rendition != cr || + !dirtyMask[x+len] || + isLineChar(c) != lineDraw || + nextIsDoubleWidth != doubleWidth ) + break; + + disstrU[p++] = c; //fontMap(c); + } + + QString unistr(disstrU, p); + + bool saveFixedFont = _fixedFont; + if (lineDraw) + _fixedFont = false; + if (doubleWidth) + _fixedFont = false; + + updateLine = true; + + _fixedFont = saveFixedFont; + x += len - 1; + } + + } + + //both the top and bottom halves of double height _lines must always be redrawn + //although both top and bottom halves contain the same characters, only + //the top one is actually + //drawn. + if (_lineProperties.count() > y) + updateLine |= (_lineProperties[y] & LINE_DOUBLEHEIGHT); + + // if the characters on the line are different in the old and the new _image + // then this line must be repainted. + if (updateLine) + { + dirtyLineCount++; + + // add the area occupied by this line to the region which needs to be + // repainted + QRect dirtyRect = QRect( _leftMargin+tLx , + _topMargin+tLy+_fontHeight*y , + _fontWidth * columnsToUpdate , + _fontHeight ); + + dirtyRegion |= dirtyRect; + } + + // replace the line of characters in the old _image with the + // current line of the new _image + memcpy((void*)currentLine,(const void*)newLine,columnsToUpdate*sizeof(Character)); + } + + // if the new _image is smaller than the previous _image, then ensure that the area + // outside the new _image is cleared + if ( linesToUpdate < _usedLines ) + { + dirtyRegion |= QRect( _leftMargin+tLx , + _topMargin+tLy+_fontHeight*linesToUpdate , + _fontWidth * this->_columns , + _fontHeight * (_usedLines-linesToUpdate) ); + } + _usedLines = linesToUpdate; + + if ( columnsToUpdate < _usedColumns ) + { + dirtyRegion |= QRect( _leftMargin+tLx+columnsToUpdate*_fontWidth , + _topMargin+tLy , + _fontWidth * (_usedColumns-columnsToUpdate) , + _fontHeight * this->_lines ); + } + _usedColumns = columnsToUpdate; + + dirtyRegion |= _inputMethodData.previousPreeditRect; + + // update the parts of the display which have changed + update(dirtyRegion); + + if ( _hasBlinker && !_blinkTimer->isActive()) _blinkTimer->start( BLINK_DELAY ); + if (!_hasBlinker && _blinkTimer->isActive()) { _blinkTimer->stop(); _blinking = false; } + delete[] dirtyMask; + delete[] disstrU; + +} + +void TerminalDisplay::showResizeNotification() +{ + if (_terminalSizeHint && isVisible()) + { + if (_terminalSizeStartup) { + _terminalSizeStartup=false; + return; + } + if (!_resizeWidget) + { + _resizeWidget = new QLabel(("Size: XXX x XXX"), this); + _resizeWidget->setMinimumWidth(_resizeWidget->fontMetrics().width(("Size: XXX x XXX"))); + _resizeWidget->setMinimumHeight(_resizeWidget->sizeHint().height()); + _resizeWidget->setAlignment(Qt::AlignCenter); + + _resizeWidget->setStyleSheet("background-color:palette(window);border-style:solid;border-width:1px;border-color:palette(dark)"); + + _resizeTimer = new QTimer(this); + _resizeTimer->setSingleShot(true); + connect(_resizeTimer, SIGNAL(timeout()), _resizeWidget, SLOT(hide())); + + } + QString sizeStr; + sizeStr.sprintf("Size: %d x %d", _columns, _lines); + _resizeWidget->setText(sizeStr); + _resizeWidget->move((width()-_resizeWidget->width())/2, + (height()-_resizeWidget->height())/2+20); + _resizeWidget->show(); + _resizeTimer->start(1000); + } +} + +void TerminalDisplay::setBlinkingCursor(bool blink) +{ + _hasBlinkingCursor=blink; + + if (blink && !_blinkCursorTimer->isActive()) + _blinkCursorTimer->start(BLINK_DELAY); + + if (!blink && _blinkCursorTimer->isActive()) + { + _blinkCursorTimer->stop(); + if (_cursorBlinking) + blinkCursorEvent(); + else + _cursorBlinking = false; + } +} + +void TerminalDisplay::paintEvent( QPaintEvent* pe ) +{ +//qDebug("%s %d paintEvent", __FILE__, __LINE__); + QPainter paint(this); + + foreach (QRect rect, (pe->region() & contentsRect()).rects()) + { + 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); +} + +QRect TerminalDisplay::preeditRect() const +{ + const int preeditLength = string_width(_inputMethodData.preeditString); + + if ( preeditLength == 0 ) + return QRect(); + + return QRect(_leftMargin + _fontWidth*cursorPosition().x(), + _topMargin + _fontHeight*cursorPosition().y(), + _fontWidth*preeditLength, + _fontHeight); +} + +void TerminalDisplay::drawInputMethodPreeditString(QPainter& painter , const QRect& rect) +{ + if ( _inputMethodData.preeditString.isEmpty() ) { + return; + } + const QPoint cursorPos = cursorPosition(); + + bool invertColors = false; + const QColor background = _colorTable[DEFAULT_BACK_COLOR].color; + const QColor foreground = _colorTable[DEFAULT_FORE_COLOR].color; + const Character* style = &_image[loc(cursorPos.x(),cursorPos.y())]; + + drawBackground(painter,rect,background,true); + drawCursor(painter,rect,foreground,background,invertColors); + drawCharacters(painter,rect,_inputMethodData.preeditString,style,invertColors); + + _inputMethodData.previousPreeditRect = rect; +} + +FilterChain* TerminalDisplay::filterChain() const +{ + return _filterChain; +} + +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; + getCharacterPosition( cursorPos , cursorLine , cursorColumn ); + Character cursorCharacter = _image[loc(cursorColumn,cursorLine)]; + + painter.setPen( QPen(cursorCharacter.foregroundColor.color(colorTable())) ); + + // iterate over hotspots identified by the display's currently active filters + // and draw appropriate visuals to indicate the presence of the hotspot + + QList<Filter::HotSpot*> spots = _filterChain->hotSpots(); + QListIterator<Filter::HotSpot*> iter(spots); + while (iter.hasNext()) + { + Filter::HotSpot* spot = iter.next(); + + for ( int line = spot->startLine() ; line <= spot->endLine() ; line++ ) + { + int startColumn = 0; + int endColumn = _columns-1; // TODO use number of _columns which are actually + // occupied on this line rather than the width of the + // display in _columns + + // ignore whitespace at the end of the lines + while ( QChar(_image[loc(endColumn,line)].character).isSpace() && endColumn > 0 ) + endColumn--; + + // increment here because the column which we want to set 'endColumn' to + // is the first whitespace character at the end of the line + endColumn++; + + if ( line == spot->startLine() ) + startColumn = spot->startColumn(); + if ( line == spot->endLine() ) + endColumn = spot->endColumn(); + + // subtract one pixel from + // the right and bottom so that + // we do not overdraw adjacent + // hotspots + // + // subtracting one pixel from all sides also prevents an edge case where + // moving the mouse outside a link could still leave it underlined + // because the check below for the position of the cursor + // finds it on the border of the target area + QRect r; + r.setCoords( startColumn*_fontWidth + 1, line*_fontHeight + 1, + endColumn*_fontWidth - 1, (line+1)*_fontHeight - 1 ); + + // Underline link hotspots + if ( spot->type() == Filter::HotSpot::Link ) + { + QFontMetrics metrics(font()); + + // find the baseline (which is the invisible line that the characters in the font sit on, + // with some having tails dangling below) + int baseline = r.bottom() - metrics.descent(); + // find the position of the underline below that + int underlinePos = baseline + metrics.underlinePos(); + + if ( r.contains( mapFromGlobal(QCursor::pos()) ) ) + painter.drawLine( r.left() , underlinePos , + r.right() , underlinePos ); + } + // Marker hotspots simply have a transparent rectanglular shape + // drawn on top of them + else if ( spot->type() == Filter::HotSpot::Marker ) + { + //TODO - Do not use a hardcoded colour for this + painter.fillRect(r,QBrush(QColor(255,0,0,120))); + } + } + } +} +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 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)); + + const int bufferSize = _usedColumns; + QChar *disstrU = new QChar[bufferSize]; + for (int y = luy; y <= rly; y++) + { + quint16 c = _image[loc(lux,y)].character; + int x = lux; + if(!c && x) + x--; // Search for start of multi-column character + for (; x <= rlx; x++) + { + int len = 1; + int p = 0; + + // is this a single character or a sequence of characters ? + if ( _image[loc(x,y)].rendition & RE_EXTENDED_CHAR ) + { + // sequence of characters + ushort extendedCharLength = 0; + ushort* chars = ExtendedCharTable::instance + .lookupExtendedChar(_image[loc(x,y)].charSequence,extendedCharLength); + for ( int index = 0 ; index < extendedCharLength ; index++ ) + { + Q_ASSERT( p < bufferSize ); + disstrU[p++] = chars[index]; + } + } + else + { + // single character + c = _image[loc(x,y)].character; + if (c) + { + Q_ASSERT( p < bufferSize ); + disstrU[p++] = c; //fontMap(c); + } + } + + bool lineDraw = isLineChar(c); + bool doubleWidth = (_image[ qMin(loc(x,y)+1,_imageSize) ].character == 0); + CharacterColor currentForeground = _image[loc(x,y)].foregroundColor; + CharacterColor currentBackground = _image[loc(x,y)].backgroundColor; + quint8 currentRendition = _image[loc(x,y)].rendition; + + while (x+len <= rlx && + _image[loc(x+len,y)].foregroundColor == currentForeground && + _image[loc(x+len,y)].backgroundColor == currentBackground && + _image[loc(x+len,y)].rendition == currentRendition && + (_image[ qMin(loc(x+len,y)+1,_imageSize) ].character == 0) == doubleWidth && + isLineChar( c = _image[loc(x+len,y)].character) == lineDraw) // Assignment! + { + if (c) + disstrU[p++] = c; //fontMap(c); + if (doubleWidth) // assert((_image[loc(x+len,y)+1].character == 0)), see above if condition + len++; // Skip trailing part of multi-column character + len++; + } + if ((x+len < _usedColumns) && (!_image[loc(x+len,y)].character)) + len++; // Adjust for trailing part of multi-column character + + bool 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 + //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 ); + + _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 + //containing the same characters + //both _lines will have the LINE_DOUBLEHEIGHT attribute. + //If the current line has the LINE_DOUBLEHEIGHT attribute, + //we can therefore skip the next line + if (_lineProperties[y] & LINE_DOUBLEHEIGHT) + y++; + } + + x += len - 1; + } + } + delete [] disstrU; +} + +void TerminalDisplay::blinkEvent() +{ + _blinking = !_blinking; + + //TODO: Optimise to only repaint the areas of the widget + // where there is blinking text + // rather than repainting the whole widget. + update(); +} + +QRect TerminalDisplay::imageToWidget(const QRect& imageArea) const +{ +//qDebug("%s %d imageToWidget", __FILE__, __LINE__); + QRect result; + result.setLeft( _leftMargin + _fontWidth * imageArea.left() ); + result.setTop( _topMargin + _fontHeight * imageArea.top() ); + result.setWidth( _fontWidth * imageArea.width() ); + result.setHeight( _fontHeight * imageArea.height() ); + + return result; +} + +void TerminalDisplay::blinkCursorEvent() +{ + _cursorBlinking = !_cursorBlinking; + + QRect cursorRect = imageToWidget( QRect(cursorPosition(),QSize(1,1)) ); + + update(cursorRect); +} + +/* ------------------------------------------------------------------------- */ +/* */ +/* Resizing */ +/* */ +/* ------------------------------------------------------------------------- */ + +void TerminalDisplay::resizeEvent(QResizeEvent*) +{ + updateImageSize(); +} + +void TerminalDisplay::propagateSize() +{ + if (_isFixedSize) + { + setSize(_columns, _lines); + QWidget::setFixedSize(sizeHint()); + parentWidget()->adjustSize(); + parentWidget()->setFixedSize(parentWidget()->sizeHint()); + return; + } + if (_image) + updateImageSize(); +} + +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); + int columns = qMin(oldcol,_columns); + + if (oldimg) + { + for (int line = 0; line < lines; line++) + { + memcpy((void*)&_image[_columns*line], + (void*)&oldimg[oldcol*line],columns*sizeof(Character)); + } + delete[] oldimg; + } + + if (_screenWindow) + _screenWindow->setWindowLines(_lines); + + _resizing = (oldlin!=_lines) || (oldcol!=_columns); + + if ( _resizing ) + { + showResizeNotification(); + emit changedContentSizeSignal(_contentHeight, _contentWidth); // expose resizeEvent + } + + _resizing = false; +} + +//showEvent and hideEvent are reimplemented here so that it appears to other classes that the +//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*) +{ + emit changedContentSizeSignal(_contentHeight,_contentWidth); +} +void TerminalDisplay::hideEvent(QHideEvent*) +{ + emit changedContentSizeSignal(_contentHeight,_contentWidth); +} + +/* ------------------------------------------------------------------------- */ +/* */ +/* Scrollbar */ +/* */ +/* ------------------------------------------------------------------------- */ + +void TerminalDisplay::scrollBarPositionChanged(int) +{ + if ( !_screenWindow ) + return; + + _screenWindow->scrollTo( _scrollBar->value() ); + + // if the thumb has been moved to the bottom of the _scrollBar then set + // the display to automatically track new output, + // that is, scroll down automatically + // to how new _lines as they are added + const bool atEndOfOutput = (_scrollBar->value() == _scrollBar->maximum()); + _screenWindow->setTrackOutput( atEndOfOutput ); + + updateImage(); +} + +void TerminalDisplay::setScroll(int cursor, int slines) +{ +//qDebug("%s %d setScroll", __FILE__, __LINE__); + // update _scrollBar if the range or value has changed, + // otherwise return + // + // setting the range or value of a _scrollBar will always trigger + // a repaint, so it should be avoided if it is not necessary + if ( _scrollBar->minimum() == 0 && + _scrollBar->maximum() == (slines - _lines) && + _scrollBar->value() == cursor ) + { + return; + } + + disconnect(_scrollBar, SIGNAL(valueChanged(int)), this, SLOT(scrollBarPositionChanged(int))); + _scrollBar->setRange(0,slines - _lines); + _scrollBar->setSingleStep(1); + _scrollBar->setPageStep(_lines); + _scrollBar->setValue(cursor); + connect(_scrollBar, SIGNAL(valueChanged(int)), this, SLOT(scrollBarPositionChanged(int))); +} + +void TerminalDisplay::setScrollBarPosition(ScrollBarPosition position) +{ + if (_scrollbarLocation == position) { +// return; + } + + if ( position == NoScrollBar ) + _scrollBar->hide(); + else + _scrollBar->show(); + + _topMargin = _leftMargin = 1; + _scrollbarLocation = position; + + propagateSize(); + update(); +} + +void TerminalDisplay::mousePressEvent(QMouseEvent* ev) +{ + if ( _possibleTripleClick && (ev->button()==Qt::LeftButton) ) { + mouseTripleClickEvent(ev); + return; + } + + if ( !contentsRect().contains(ev->pos()) ) return; + + if ( !_screenWindow ) return; + + int charLine; + int charColumn; + getCharacterPosition(ev->pos(),charLine,charColumn); + QPoint pos = QPoint(charColumn,charLine); + + if ( ev->button() == Qt::LeftButton) + { + _lineSelectionMode = false; + _wordSelectionMode = false; + + emit isBusySelecting(true); // Keep it steady... + // Drag only when the Control key is hold + bool selected = false; + + // The receiver of the testIsSelected() signal will adjust + // 'selected' accordingly. + //emit testIsSelected(pos.x(), pos.y(), selected); + + selected = _screenWindow->isSelected(pos.x(),pos.y()); + + if ((!_ctrlDrag || ev->modifiers() & Qt::ControlModifier) && selected ) { + // The user clicked inside selected text + dragInfo.state = diPending; + dragInfo.start = ev->pos(); + } + else { + // No reason to ever start a drag event + dragInfo.state = diNone; + + _preserveLineBreaks = !( ( ev->modifiers() & Qt::ControlModifier ) && !(ev->modifiers() & Qt::AltModifier) ); + _columnSelectionMode = (ev->modifiers() & Qt::AltModifier) && (ev->modifiers() & Qt::ControlModifier); + + if (_mouseMarks || (ev->modifiers() & Qt::ShiftModifier)) + { + _screenWindow->clearSelection(); + + //emit clearSelectionSignal(); + pos.ry() += _scrollBar->value(); + _iPntSel = _pntSel = pos; + _actSel = 1; // left mouse button pressed but nothing selected yet. + + } + else + { + emit mouseSignal( 0, charColumn + 1, charLine + 1 +_scrollBar->value() -_scrollBar->maximum() , 0); + } + } + } + else if ( ev->button() == Qt::MidButton ) + { + if ( _mouseMarks || (!_mouseMarks && (ev->modifiers() & Qt::ShiftModifier)) ) + emitSelection(true,ev->modifiers() & Qt::ControlModifier); + else + emit mouseSignal( 1, charColumn +1, charLine +1 +_scrollBar->value() -_scrollBar->maximum() , 0); + } + else if ( ev->button() == Qt::RightButton ) + { + if (_mouseMarks || (ev->modifiers() & Qt::ShiftModifier)) + { + emit configureRequest( this, + ev->modifiers() & (Qt::ShiftModifier|Qt::ControlModifier), + ev->pos() + ); + } + else + emit mouseSignal( 2, charColumn +1, charLine +1 +_scrollBar->value() -_scrollBar->maximum() , 0); + } +} + +QList<QAction*> TerminalDisplay::filterActions(const QPoint& position) +{ + int charLine, charColumn; + getCharacterPosition(position,charLine,charColumn); + + Filter::HotSpot* spot = _filterChain->hotSpotAt(charLine,charColumn); + + return spot ? spot->actions() : QList<QAction*>(); +} + +void TerminalDisplay::mouseMoveEvent(QMouseEvent* ev) +{ + int charLine = 0; + int charColumn = 0; + + getCharacterPosition(ev->pos(),charLine,charColumn); + + // handle filters + // change link hot-spot appearance on mouse-over + Filter::HotSpot* spot = _filterChain->hotSpotAt(charLine,charColumn); + if ( spot && spot->type() == Filter::HotSpot::Link) + { + QRect previousHotspotArea = _mouseOverHotspotArea; + _mouseOverHotspotArea.setCoords( qMin(spot->startColumn() , spot->endColumn()) * _fontWidth, + spot->startLine() * _fontHeight, + qMax(spot->startColumn() , spot->endColumn()) * _fontHeight, + (spot->endLine()+1) * _fontHeight ); + + // 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 ); + } + + update( _mouseOverHotspotArea | previousHotspotArea ); + } + else if ( _mouseOverHotspotArea.isValid() ) + { + update( _mouseOverHotspotArea ); + // set hotspot area to an invalid rectangle + _mouseOverHotspotArea = QRect(); + } + + // for auto-hiding the cursor, we need mouseTracking + if (ev->buttons() == Qt::NoButton ) return; + + // if the terminal is interested in mouse movements + // then emit a mouse movement signal, unless the shift + // key is being held down, which overrides this. + if (!_mouseMarks && !(ev->modifiers() & Qt::ShiftModifier)) + { + int button = 3; + if (ev->buttons() & Qt::LeftButton) + button = 0; + if (ev->buttons() & Qt::MidButton) + button = 1; + if (ev->buttons() & Qt::RightButton) + button = 2; + + + emit mouseSignal( button, + charColumn + 1, + charLine + 1 +_scrollBar->value() -_scrollBar->maximum(), + 1 ); + + return; + } + + if (dragInfo.state == diPending) + { + // we had a mouse down, but haven't confirmed a drag yet + // if the mouse has moved sufficiently, we will confirm + + int distance = 10; //KGlobalSettings::dndEventDelay(); + if ( ev->x() > dragInfo.start.x() + distance || ev->x() < dragInfo.start.x() - distance || + ev->y() > dragInfo.start.y() + distance || ev->y() < dragInfo.start.y() - distance) + { + // we've left the drag square, we can start a real drag operation now + emit isBusySelecting(false); // Ok.. we can breath again. + + _screenWindow->clearSelection(); + doDrag(); + } + return; + } + else if (dragInfo.state == diDragging) + { + // this isn't technically needed because mouseMoveEvent is suppressed during + // Qt drag operations, replaced by dragMoveEvent + return; + } + + if (_actSel == 0) return; + + // don't extend selection while pasting + if (ev->buttons() & Qt::MidButton) return; + + extendSelection( ev->pos() ); +} + +#if 0 +void TerminalDisplay::setSelectionEnd() +{ + extendSelection( _configureRequestPoint ); +} +#endif + +void TerminalDisplay::extendSelection( const QPoint& position ) +{ + QPoint pos = position; + + if ( !_screenWindow ) + return; + + //if ( !contentsRect().contains(ev->pos()) ) return; + QPoint tL = contentsRect().topLeft(); + int tLx = tL.x(); + int tLy = tL.y(); + int scroll = _scrollBar->value(); + + // we're in the process of moving the mouse with the left button pressed + // the mouse cursor will kept caught within the bounds of the text in + // this widget. + + // Adjust position within text area bounds. See FIXME above. + 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 ) + { + _scrollBar->setValue(_scrollBar->value()+yMouseScroll); // scrollforward + } + if ( pos.y() == tLy+_topMargin ) + { + _scrollBar->setValue(_scrollBar->value()-yMouseScroll); // scrollback + } + + int charColumn = 0; + int charLine = 0; + getCharacterPosition(pos,charLine,charColumn); + + QPoint here = QPoint(charColumn,charLine); //QPoint((pos.x()-tLx-_leftMargin+(_fontWidth/2))/_fontWidth,(pos.y()-tLy-_topMargin)/_fontHeight); + QPoint ohere; + QPoint _iPntSelCorr = _iPntSel; + _iPntSelCorr.ry() -= _scrollBar->value(); + QPoint _pntSelCorr = _pntSel; + _pntSelCorr.ry() -= _scrollBar->value(); + bool swapping = false; + + if ( _wordSelectionMode ) + { + // Extend to word boundaries + int i; + int selClass; + + bool left_not_right = ( here.y() < _iPntSelCorr.y() || + here.y() == _iPntSelCorr.y() && here.x() < _iPntSelCorr.x() ); + bool old_left_not_right = ( _pntSelCorr.y() < _iPntSelCorr.y() || + _pntSelCorr.y() == _iPntSelCorr.y() && _pntSelCorr.x() < _iPntSelCorr.x() ); + swapping = left_not_right != old_left_not_right; + + // Find left (left_not_right ? from here : from start) + QPoint left = left_not_right ? here : _iPntSelCorr; + i = loc(left.x(),left.y()); + if (i>=0 && i<=_imageSize) { + selClass = charClass(_image[i].character); + while ( ((left.x()>0) || (left.y()>0 && (_lineProperties[left.y()-1] & LINE_WRAPPED) )) + && charClass(_image[i-1].character) == selClass ) + { i--; if (left.x()>0) left.rx()--; else {left.rx()=_usedColumns-1; left.ry()--;} } + } + + // Find left (left_not_right ? from start : from here) + QPoint right = left_not_right ? _iPntSelCorr : here; + i = loc(right.x(),right.y()); + if (i>=0 && i<=_imageSize) { + selClass = charClass(_image[i].character); + while( ((right.x()<_usedColumns-1) || (right.y()<_usedLines-1 && (_lineProperties[right.y()] & LINE_WRAPPED) )) + && charClass(_image[i+1].character) == selClass ) + { i++; if (right.x()<_usedColumns-1) right.rx()++; else {right.rx()=0; right.ry()++; } } + } + + // Pick which is start (ohere) and which is extension (here) + if ( left_not_right ) + { + here = left; ohere = right; + } + else + { + here = right; ohere = left; + } + ohere.rx()++; + } + + if ( _lineSelectionMode ) + { + // Extend to complete line + bool above_not_below = ( here.y() < _iPntSelCorr.y() ); + + QPoint above = above_not_below ? here : _iPntSelCorr; + QPoint below = above_not_below ? _iPntSelCorr : here; + + while (above.y()>0 && (_lineProperties[above.y()-1] & LINE_WRAPPED) ) + above.ry()--; + while (below.y()<_usedLines-1 && (_lineProperties[below.y()] & LINE_WRAPPED) ) + below.ry()++; + + above.setX(0); + below.setX(_usedColumns-1); + + // Pick which is start (ohere) and which is extension (here) + if ( above_not_below ) + { + here = above; ohere = below; + } + else + { + here = below; ohere = above; + } + + QPoint newSelBegin = QPoint( ohere.x(), ohere.y() ); + swapping = !(_tripleSelBegin==newSelBegin); + _tripleSelBegin = newSelBegin; + + ohere.rx()++; + } + + int offset = 0; + if ( !_wordSelectionMode && !_lineSelectionMode ) + { + int i; + int selClass; + + bool left_not_right = ( here.y() < _iPntSelCorr.y() || + here.y() == _iPntSelCorr.y() && here.x() < _iPntSelCorr.x() ); + bool old_left_not_right = ( _pntSelCorr.y() < _iPntSelCorr.y() || + _pntSelCorr.y() == _iPntSelCorr.y() && _pntSelCorr.x() < _iPntSelCorr.x() ); + swapping = left_not_right != old_left_not_right; + + // Find left (left_not_right ? from here : from start) + QPoint left = left_not_right ? here : _iPntSelCorr; + + // Find left (left_not_right ? from start : from here) + QPoint right = left_not_right ? _iPntSelCorr : here; + if ( right.x() > 0 && !_columnSelectionMode ) + { + i = loc(right.x(),right.y()); + if (i>=0 && i<=_imageSize) { + selClass = charClass(_image[i-1].character); + if (selClass == ' ') + { + while ( right.x() < _usedColumns-1 && charClass(_image[i+1].character) == selClass && (right.y()<_usedLines-1) && + !(_lineProperties[right.y()] & LINE_WRAPPED)) + { i++; right.rx()++; } + if (right.x() < _usedColumns-1) + right = left_not_right ? _iPntSelCorr : here; + else + right.rx()++; // will be balanced later because of offset=-1; + } + } + } + + // Pick which is start (ohere) and which is extension (here) + if ( left_not_right ) + { + here = left; ohere = right; offset = 0; + } + else + { + here = right; ohere = left; offset = -1; + } + } + + if ((here == _pntSelCorr) && (scroll == _scrollBar->value())) return; // not moved + + if (here == ohere) return; // It's not left, it's not right. + + if ( _actSel < 2 || swapping ) + { + if ( _columnSelectionMode && !_lineSelectionMode && !_wordSelectionMode ) + { + _screenWindow->setSelectionStart( ohere.x() , ohere.y() , true ); + } + else + { + _screenWindow->setSelectionStart( ohere.x()-1-offset , ohere.y() , false ); + } + + } + + _actSel = 2; // within selection + _pntSel = here; + _pntSel.ry() += _scrollBar->value(); + + if ( _columnSelectionMode && !_lineSelectionMode && !_wordSelectionMode ) + { + _screenWindow->setSelectionEnd( here.x() , here.y() ); + } + else + { + _screenWindow->setSelectionEnd( here.x()+offset , here.y() ); + } + +} + +void TerminalDisplay::mouseReleaseEvent(QMouseEvent* ev) +{ + if ( !_screenWindow ) + return; + + int charLine; + int charColumn; + getCharacterPosition(ev->pos(),charLine,charColumn); + + if ( ev->button() == Qt::LeftButton) + { + emit isBusySelecting(false); + if(dragInfo.state == diPending) + { + // We had a drag event pending but never confirmed. Kill selection + _screenWindow->clearSelection(); + //emit clearSelectionSignal(); + } + else + { + if ( _actSel > 1 ) + { + setSelection( _screenWindow->selectedText(_preserveLineBreaks) ); + } + + _actSel = 0; + + //FIXME: emits a release event even if the mouse is + // outside the range. The procedure used in `mouseMoveEvent' + // applies here, too. + + if (!_mouseMarks && !(ev->modifiers() & Qt::ShiftModifier)) + emit mouseSignal( 3, // release + charColumn + 1, + charLine + 1 +_scrollBar->value() -_scrollBar->maximum() , 0); + } + dragInfo.state = diNone; + } + + + if ( !_mouseMarks && + ((ev->button() == Qt::RightButton && !(ev->modifiers() & Qt::ShiftModifier)) + || ev->button() == Qt::MidButton) ) + { + emit mouseSignal( 3, + charColumn + 1, + charLine + 1 +_scrollBar->value() -_scrollBar->maximum() , + 0); + } +} + +void TerminalDisplay::getCharacterPosition(const QPoint& widgetPoint,int& line,int& column) const +{ + + column = (widgetPoint.x() + _fontWidth/2 -contentsRect().left()-_leftMargin) / _fontWidth; + line = (widgetPoint.y()-contentsRect().top()-_topMargin) / _fontHeight; + + if ( line < 0 ) + line = 0; + if ( column < 0 ) + column = 0; + + if ( line >= _usedLines ) + line = _usedLines-1; + + // the column value returned can be equal to _usedColumns, which + // is the position just after the last character displayed in a line. + // + // this is required so that the user can select characters in the right-most + // column (or left-most for right-to-left input) + if ( column > _usedColumns ) + column = _usedColumns; +} + +void TerminalDisplay::updateLineProperties() +{ + if ( !_screenWindow ) + return; + + _lineProperties = _screenWindow->getLineProperties(); +} + +void TerminalDisplay::mouseDoubleClickEvent(QMouseEvent* ev) +{ + if ( ev->button() != Qt::LeftButton) return; + if ( !_screenWindow ) return; + + int charLine = 0; + int charColumn = 0; + + getCharacterPosition(ev->pos(),charLine,charColumn); + + QPoint pos(charColumn,charLine); + + // pass on double click as two clicks. + if (!_mouseMarks && !(ev->modifiers() & Qt::ShiftModifier)) + { + // Send just _ONE_ click event, since the first click of the double click + // was already sent by the click handler + emit mouseSignal( 0, + pos.x()+1, + pos.y()+1 +_scrollBar->value() -_scrollBar->maximum(), + 0 ); // left button + return; + } + + _screenWindow->clearSelection(); + QPoint bgnSel = pos; + QPoint endSel = pos; + int i = loc(bgnSel.x(),bgnSel.y()); + _iPntSel = bgnSel; + _iPntSel.ry() += _scrollBar->value(); + + _wordSelectionMode = true; + + // find word boundaries... + int selClass = charClass(_image[i].character); + { + // find the start of the word + int x = bgnSel.x(); + while ( ((x>0) || (bgnSel.y()>0 && (_lineProperties[bgnSel.y()-1] & LINE_WRAPPED) )) + && charClass(_image[i-1].character) == selClass ) + { + i--; + if (x>0) + x--; + else + { + x=_usedColumns-1; + bgnSel.ry()--; + } + } + + bgnSel.setX(x); + _screenWindow->setSelectionStart( bgnSel.x() , bgnSel.y() , false ); + + // find the end of the word + i = loc( endSel.x(), endSel.y() ); + x = endSel.x(); + while( ((x<_usedColumns-1) || (endSel.y()<_usedLines-1 && (_lineProperties[endSel.y()] & LINE_WRAPPED) )) + && charClass(_image[i+1].character) == selClass ) + { + i++; + if (x<_usedColumns-1) + x++; + else + { + x=0; + endSel.ry()++; + } + } + + endSel.setX(x); + + // In word selection mode don't select @ (64) if at end of word. + if ( ( QChar( _image[i].character ) == '@' ) && ( ( endSel.x() - bgnSel.x() ) > 0 ) ) + endSel.setX( x - 1 ); + + + _actSel = 2; // within selection + + _screenWindow->setSelectionEnd( endSel.x() , endSel.y() ); + + setSelection( _screenWindow->selectedText(_preserveLineBreaks) ); + } + + _possibleTripleClick=true; + + QTimer::singleShot(QApplication::doubleClickInterval(),this, + SLOT(tripleClickTimeout())); +} + +void TerminalDisplay::wheelEvent( QWheelEvent* ev ) +{ + if (ev->orientation() != Qt::Vertical) + return; + + if ( _mouseMarks ) + _scrollBar->event(ev); + else + { + int charLine; + int charColumn; + getCharacterPosition( ev->pos() , charLine , charColumn ); + + emit mouseSignal( ev->delta() > 0 ? 4 : 5, + charColumn + 1, + charLine + 1 +_scrollBar->value() -_scrollBar->maximum() , + 0); + } +} + +void TerminalDisplay::tripleClickTimeout() +{ + _possibleTripleClick=false; +} + +void TerminalDisplay::mouseTripleClickEvent(QMouseEvent* ev) +{ + if ( !_screenWindow ) return; + + int charLine; + int charColumn; + getCharacterPosition(ev->pos(),charLine,charColumn); + _iPntSel = QPoint(charColumn,charLine); + + _screenWindow->clearSelection(); + + _lineSelectionMode = true; + _wordSelectionMode = false; + + _actSel = 2; // within selection + emit isBusySelecting(true); // Keep it steady... + + while (_iPntSel.y()>0 && (_lineProperties[_iPntSel.y()-1] & LINE_WRAPPED) ) + _iPntSel.ry()--; + + if (_tripleClickMode == SelectForwardsFromCursor) { + // find word boundary start + int i = loc(_iPntSel.x(),_iPntSel.y()); + int selClass = charClass(_image[i].character); + int x = _iPntSel.x(); + + while ( ((x>0) || + (_iPntSel.y()>0 && (_lineProperties[_iPntSel.y()-1] & LINE_WRAPPED) ) + ) + && charClass(_image[i-1].character) == selClass ) + { + i--; + if (x>0) + x--; + else + { + x=_columns-1; + _iPntSel.ry()--; + } + } + + _screenWindow->setSelectionStart( x , _iPntSel.y() , false ); + _tripleSelBegin = QPoint( x, _iPntSel.y() ); + } + else if (_tripleClickMode == SelectWholeLine) { + _screenWindow->setSelectionStart( 0 , _iPntSel.y() , false ); + _tripleSelBegin = QPoint( 0, _iPntSel.y() ); + } + + while (_iPntSel.y()<_lines-1 && (_lineProperties[_iPntSel.y()] & LINE_WRAPPED) ) + _iPntSel.ry()++; + + _screenWindow->setSelectionEnd( _columns - 1 , _iPntSel.y() ); + + setSelection(_screenWindow->selectedText(_preserveLineBreaks)); + + _iPntSel.ry() += _scrollBar->value(); +} + + +bool TerminalDisplay::focusNextPrevChild( bool next ) +{ + if (next) + return false; // This disables changing the active part in konqueror + // when pressing Tab + return QWidget::focusNextPrevChild( next ); +} + + +int TerminalDisplay::charClass(quint16 ch) 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; +} + +void TerminalDisplay::setWordCharacters(const QString& wc) +{ + _wordCharacters = wc; +} + +void TerminalDisplay::setUsesMouse(bool on) +{ + _mouseMarks = on; + setCursor( _mouseMarks ? Qt::IBeamCursor : Qt::ArrowCursor ); +} +bool TerminalDisplay::usesMouse() const +{ + return _mouseMarks; +} + +/* ------------------------------------------------------------------------- */ +/* */ +/* Clipboard */ +/* */ +/* ------------------------------------------------------------------------- */ + +#undef KeyPress + +void TerminalDisplay::emitSelection(bool useXselection,bool appendReturn) +{ + if ( !_screenWindow ) + return; + + // Paste Clipboard by simulating keypress events + QString text = QApplication::clipboard()->text(useXselection ? QClipboard::Selection : + QClipboard::Clipboard); + if(appendReturn) + text.append("\r"); + if ( ! text.isEmpty() ) + { + text.replace("\n", "\r"); + QKeyEvent e(QEvent::KeyPress, 0, Qt::NoModifier, text); + emit keyPressedSignal(&e); // expose as a big fat keypress event + + _screenWindow->clearSelection(); + } +} + +void TerminalDisplay::setSelection(const QString& t) +{ + QApplication::clipboard()->setText(t, QClipboard::Selection); +} + +void TerminalDisplay::copyClipboard() +{ + if ( !_screenWindow ) + return; + + QString text = _screenWindow->selectedText(_preserveLineBreaks); + QApplication::clipboard()->setText(text); +} + +void TerminalDisplay::pasteClipboard() +{ + emitSelection(false,false); +} + +void TerminalDisplay::pasteSelection() +{ + emitSelection(true,false); +} + +/* ------------------------------------------------------------------------- */ +/* */ +/* Keyboard */ +/* */ +/* ------------------------------------------------------------------------- */ + +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); +} + +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 ) + { + bool update = true; + + 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 { + update = false; + } + + if ( update ) + { + //qDebug("%s %d updating", __FILE__, __LINE__); + _screenWindow->setTrackOutput( _screenWindow->atEndOfOutput() ); + + updateLineProperties(); + updateImage(); + + // do not send key press to terminal + 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); + if (_cursorBlinking) + blinkCursorEvent(); + else + _cursorBlinking = false; + } + + if ( emitKeyPressSignal ) + emit keyPressedSignal(event); + + event->accept(); +} + +void TerminalDisplay::inputMethodEvent( QInputMethodEvent* event ) +{ + QKeyEvent keyEvent(QEvent::KeyPress,0,Qt::NoModifier,event->commitString()); + emit keyPressedSignal(&keyEvent); + + _inputMethodData.preeditString = event->preeditString(); + update(preeditRect() | _inputMethodData.previousPreeditRect); + + event->accept(); +} +QVariant TerminalDisplay::inputMethodQuery( Qt::InputMethodQuery query ) const +{ + const QPoint cursorPos = _screenWindow ? _screenWindow->cursorPosition() : QPoint(0,0); + switch ( query ) + { + case Qt::ImMicroFocus: + return imageToWidget(QRect(cursorPos.x(),cursorPos.y(),1,1)); + break; + case Qt::ImFont: + return font(); + break; + case Qt::ImCursorPosition: + // return the cursor position within the current line + return cursorPos.x(); + break; + case Qt::ImSurroundingText: + { + // return the text from the current line + QString lineText; + QTextStream stream(&lineText); + PlainTextDecoder decoder; + decoder.begin(&stream); + decoder.decodeLine(&_image[loc(0,cursorPos.y())],_usedColumns,_lineProperties[cursorPos.y()]); + decoder.end(); + return lineText; + } + break; + case Qt::ImCurrentSelection: + return QString(); + break; + } + + return QVariant(); +} + +bool TerminalDisplay::event( QEvent *e ) +{ + 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() ) + { + keyEvent->accept(); + return true; + } + + // Override any of the following shortcuts because + // they are needed by the terminal + int keyCode = keyEvent->key() | keyEvent->modifiers(); + switch ( keyCode ) + { + // list is taken from the QLineEdit::event() code + case Qt::Key_Tab: + case Qt::Key_Delete: + case Qt::Key_Home: + case Qt::Key_End: + case Qt::Key_Backspace: + case Qt::Key_Left: + case Qt::Key_Right: + keyEvent->accept(); + return true; + } + } + return QWidget::event( e ); +} + +void TerminalDisplay::setBellMode(int mode) +{ + _bellMode=mode; +} + +void TerminalDisplay::enableBell() +{ + _allowBell = true; +} + +void TerminalDisplay::bell(const QString&) +{ + if (_bellMode==NoBell) return; + + //limit the rate at which bells can occur + //...mainly for sound effects where rapid bells in sequence + //produce a horrible noise + if ( _allowBell ) + { + _allowBell = false; + QTimer::singleShot(500,this,SLOT(enableBell())); + + if (_bellMode==SystemBeepBell) + { +// KNotification::beep(); + } + else if (_bellMode==NotifyBell) + { +// KNotification::event("BellVisible", message,QPixmap(),this); + } + else if (_bellMode==VisualBell) + { + swapColorTable(); + QTimer::singleShot(200,this,SLOT(swapColorTable())); + } + } +} + +void TerminalDisplay::swapColorTable() +{ + ColorEntry color = _colorTable[1]; + _colorTable[1]=_colorTable[0]; + _colorTable[0]= color; + _colorsInverted = !_colorsInverted; + update(); +} + +void TerminalDisplay::clearImage() +{ + // We initialize _image[_imageSize] too. See makeImage() + for (int i = 0; i <= _imageSize; i++) + { + _image[i].character = ' '; + _image[i].foregroundColor = CharacterColor(COLOR_SPACE_DEFAULT, + DEFAULT_FORE_COLOR); + _image[i].backgroundColor = CharacterColor(COLOR_SPACE_DEFAULT, + DEFAULT_BACK_COLOR); + _image[i].rendition = DEFAULT_RENDITION; + } +} + +void TerminalDisplay::calcGeometry() +{ + _scrollBar->resize(QApplication::style()->pixelMetric(QStyle::PM_ScrollBarExtent), + contentsRect().height()); + switch(_scrollbarLocation) + { + case NoScrollBar : + _leftMargin = DEFAULT_LEFT_MARGIN; + _contentWidth = contentsRect().width() - 2 * DEFAULT_LEFT_MARGIN; + break; + case ScrollBarLeft : + _leftMargin = DEFAULT_LEFT_MARGIN + _scrollBar->width(); + _contentWidth = contentsRect().width() - 2 * DEFAULT_LEFT_MARGIN - _scrollBar->width(); + _scrollBar->move(contentsRect().topLeft()); + break; + case ScrollBarRight: + _leftMargin = DEFAULT_LEFT_MARGIN; + _contentWidth = contentsRect().width() - 2 * DEFAULT_LEFT_MARGIN - _scrollBar->width(); + _scrollBar->move(contentsRect().topRight() - QPoint(_scrollBar->width()-1,0)); + break; + } + + _topMargin = DEFAULT_TOP_MARGIN; + _contentHeight = contentsRect().height() - 2 * DEFAULT_TOP_MARGIN + /* mysterious */ 1; + + if (!_isFixedSize) + { + // ensure that display is always at least one column wide + _columns = qMax(1,_contentWidth / _fontWidth); + _usedColumns = qMin(_usedColumns,_columns); + + // ensure that display is always at least one line high + _lines = qMax(1,_contentHeight / _fontHeight); + _usedLines = qMin(_usedLines,_lines); + } +} + +void TerminalDisplay::makeImage() +{ +//qDebug("%s %d makeImage", __FILE__, __LINE__); + calcGeometry(); + + // confirm that array will be of non-zero size, since the painting code + // assumes a non-zero array length + Q_ASSERT( _lines > 0 && _columns > 0 ); + Q_ASSERT( _usedLines <= _lines && _usedColumns <= _columns ); + + _imageSize=_lines*_columns; + + // We over-commit one character so that we can be more relaxed in dealing with + // certain boundary conditions: _image[_imageSize] is a valid but unused position + _image = new Character[_imageSize+1]; + + clearImage(); +} + +// calculate the needed size +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 ); + + if ( newSize != size() ) + { + _size = newSize; + updateGeometry(); + } +} + +void TerminalDisplay::setFixedSize(int cols, int lins) +{ + _isFixedSize = true; + + //ensure that display is at least one line by one column in size + _columns = qMax(1,cols); + _lines = qMax(1,lins); + _usedColumns = qMin(_usedColumns,_columns); + _usedLines = qMin(_usedLines,_lines); + + if (_image) + { + delete[] _image; + makeImage(); + } + setSize(cols, lins); + QWidget::setFixedSize(_size); +} + +QSize TerminalDisplay::sizeHint() const +{ + return _size; +} + + +/* --------------------------------------------------------------------- */ +/* */ +/* Drag & Drop */ +/* */ +/* --------------------------------------------------------------------- */ + +void TerminalDisplay::dragEnterEvent(QDragEnterEvent* event) +{ + if (event->mimeData()->hasFormat("text/plain")) + event->acceptProposedAction(); +} + +void TerminalDisplay::dropEvent(QDropEvent* event) +{ +// KUrl::List urls = KUrl::List::fromMimeData(event->mimeData()); + + QString dropText; +/* if (!urls.isEmpty()) + { + for ( int i = 0 ; i < urls.count() ; i++ ) + { + KUrl url = KIO::NetAccess::mostLocalUrl( urls[i] , 0 ); + QString urlText; + + if (url.isLocalFile()) + urlText = url.path(); + else + urlText = url.url(); + + // in future it may be useful to be able to insert file names with drag-and-drop + // without quoting them (this only affects paths with spaces in) + urlText = KShell::quoteArg(urlText); + + dropText += urlText; + + if ( i != urls.count()-1 ) + dropText += ' '; + } + } + else + { + dropText = event->mimeData()->text(); + } +*/ + if(event->mimeData()->hasFormat("text/plain")) + { + emit sendStringToEmu(dropText.toLocal8Bit()); + } +} + +void TerminalDisplay::doDrag() +{ + dragInfo.state = diDragging; + dragInfo.dragObject = new QDrag(this); + QMimeData *mimeData = new QMimeData; + mimeData->setText(QApplication::clipboard()->text(QClipboard::Selection)); + dragInfo.dragObject->setMimeData(mimeData); + dragInfo.dragObject->start(Qt::CopyAction); + // Don't delete the QTextDrag object. Qt will delete it when it's done with it. +} + +void TerminalDisplay::outputSuspended(bool suspended) +{ + //create the label when this function is first called + if (!_outputSuspendedLabel) + { + //This label includes a link to an English language website + //describing the 'flow control' (Xon/Xoff) feature found in almost + //all terminal emulators. + //If there isn't a suitable article available in the target language the link + //can simply be removed. + _outputSuspendedLabel = new QLabel( ("<qt>Output has been " + "<a href=\"http://en.wikipedia.org/wiki/XON\">suspended</a>" + " by pressing Ctrl+S." + " 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); + + //enable activation of "Xon/Xoff" link in label + _outputSuspendedLabel->setTextInteractionFlags(Qt::LinksAccessibleByMouse | + Qt::LinksAccessibleByKeyboard); + _outputSuspendedLabel->setOpenExternalLinks(true); + _outputSuspendedLabel->setVisible(false); + + _gridLayout->addWidget(_outputSuspendedLabel); + _gridLayout->addItem( new QSpacerItem(0,0,QSizePolicy::Expanding, + QSizePolicy::Expanding), + 1,0); + + } + + _outputSuspendedLabel->setVisible(suspended); +} + +uint TerminalDisplay::lineSpacing() const +{ + return _lineSpacing; +} + +void TerminalDisplay::setLineSpacing(uint i) +{ + _lineSpacing = i; + setVTFont(font()); // Trigger an update. +} + +//#include "moc_TerminalDisplay.cpp" diff --git a/client/browser/qtermwidget/includes/TerminalDisplay.h b/client/browser/qtermwidget/src/TerminalDisplay.h index 6b3c6d82..6b3c6d82 100644 --- a/client/browser/qtermwidget/includes/TerminalDisplay.h +++ b/client/browser/qtermwidget/src/TerminalDisplay.h diff --git a/client/browser/qtermwidget/src/Vt102Emulation.cpp b/client/browser/qtermwidget/src/Vt102Emulation.cpp new file mode 100644 index 00000000..d4a56b82 --- /dev/null +++ b/client/browser/qtermwidget/src/Vt102Emulation.cpp @@ -0,0 +1,1268 @@ +/* + 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 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. +*/ + +// Own +#include "Vt102Emulation.h" +#include "Vt102Emulation.moc" + +//#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 +#endif + +// Standard +#include <stdio.h> +#include <unistd.h> +#include <assert.h> + +// Qt +#include <QtCore/QEvent> +#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 + + +using namespace Konsole; + +/* VT102 Terminal Emulation + + This class puts together the screens, the pty and the widget to a + complete terminal emulation. Beside combining it's componentes, it + handles the emulations's protocol. + + This module consists of the following sections: + + - Constructor/Destructor + - Incoming Bytes Event pipeline + - Outgoing Bytes + - Mouse Events + - Keyboard Events + - Modes and Charset State + - Diagnostics +*/ + +/* ------------------------------------------------------------------------- */ +/* */ +/* Constructor / Destructor */ +/* */ +/* ------------------------------------------------------------------------- */ + + +Vt102Emulation::Vt102Emulation() + : Emulation(), + _titleUpdateTimer(new QTimer(this)) +{ + _titleUpdateTimer->setSingleShot(true); + + QObject::connect(_titleUpdateTimer , SIGNAL(timeout()) , this , SLOT(updateTitle())); + + initTokenizer(); + reset(); +} + +Vt102Emulation::~Vt102Emulation() +{ +} + +void Vt102Emulation::clearEntireScreen() +{ + _currentScreen->clearEntireScreen(); + + bufferedUpdate(); +} + +void Vt102Emulation::reset() +{ + //kDebug(1211)<<"Vt102Emulation::reset() resetToken()"; + resetToken(); + //kDebug(1211)<<"Vt102Emulation::reset() resetModes()"; + resetModes(); + //kDebug(1211)<<"Vt102Emulation::reset() resetCharSet()"; + resetCharset(0); + //kDebug(1211)<<"Vt102Emulation::reset() reset screen0()"; + _screen[0]->reset(); + //kDebug(1211)<<"Vt102Emulation::reset() resetCharSet()"; + resetCharset(1); + //kDebug(1211)<<"Vt102Emulation::reset() reset _screen 1"; + _screen[1]->reset(); + //kDebug(1211)<<"Vt102Emulation::reset() setCodec()"; + setCodec(LocaleCodec); + //kDebug(1211)<<"Vt102Emulation::reset() done"; + + bufferedUpdate(); +} + +/* ------------------------------------------------------------------------- */ +/* */ +/* Processing the incoming byte stream */ +/* */ +/* ------------------------------------------------------------------------- */ + +/* Incoming Bytes Event pipeline + + This section deals with decoding the incoming character stream. + Decoding means here, that the stream is first separated into `tokens' + which are then mapped to a `meaning' provided as operations by the + `Screen' class or by the emulation class itself. + + The pipeline proceeds as follows: + + - Tokenizing the ESC codes (onReceiveChar) + - VT100 code page translation of plain characters (applyCharset) + - Interpretation of ESC codes (tau) + + The escape codes and their meaning are described in the + technical reference of this program. +*/ + +// Tokens ------------------------------------------------------------------ -- + +/* + Since the tokens are the central notion if this section, we've put them + in front. They provide the syntactical elements used to represent the + terminals operations as byte sequences. + + They are encodes here into a single machine word, so that we can later + switch over them easily. Depending on the token itself, additional + argument variables are filled with parameter values. + + The tokens are defined below: + + - CHR - Printable characters (32..255 but DEL (=127)) + - CTL - Control characters (0..31 but ESC (= 27), DEL) + - ESC - Escape codes of the form <ESC><CHR but `[]()+*#'> + - ESC_DE - Escape codes of the form <ESC><any of `()+*#%'> C + - CSI_PN - Escape codes of the form <ESC>'[' {Pn} ';' {Pn} C + - CSI_PS - Escape codes of the form <ESC>'[' {Pn} ';' ... C + - CSI_PR - Escape codes of the form <ESC>'[' '?' {Pn} ';' ... C + - CSI_PE - Escape codes of the form <ESC>'[' '!' {Pn} ';' ... C + - VT52 - VT52 escape codes + - <ESC><Chr> + - <ESC>'Y'{Pc}{Pc} + - XTE_HA - Xterm hacks <ESC>`]' {Pn} `;' {Text} <BEL> + note that this is handled differently + + The last two forms allow list of arguments. Since the elements of + the lists are treated individually the same way, they are passed + as individual tokens to the interpretation. Further, because the + meaning of the parameters are names (althought represented as numbers), + they are includes within the token ('N'). + +*/ + +#define TY_CONSTR(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_VT52(A ) TY_CONSTR(8,A,0) + +#define TY_CSI_PG(A ) TY_CONSTR(9,A,0) + +#define TY_CSI_PE(A ) TY_CONSTR(10,A,0) + +// Tokenizer --------------------------------------------------------------- -- + +/* The tokenizers state + + The state is represented by the buffer (pbuf, ppos), + and accompanied by decoded arguments kept in (argv,argc). + Note that they are kept internal in the tokenizer. +*/ + +void Vt102Emulation::resetToken() +{ + ppos = 0; argc = 0; argv[0] = 0; argv[1] = 0; +} + +void Vt102Emulation::addDigit(int dig) +{ + argv[argc] = 10*argv[argc] + dig; +} + +void Vt102Emulation::addArgument() +{ + argc = qMin(argc+1,MAXARGS-1); + argv[argc] = 0; +} + +void Vt102Emulation::pushToToken(int cc) +{ + pbuf[ppos] = cc; + ppos = qMin(ppos+1,MAXPBUF-1); +} + +// Character Classes used while decoding + +#define CTL 1 +#define CHR 2 +#define CPN 4 +#define DIG 8 +#define SCS 16 +#define GRP 32 +#define CPS 64 + +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(); +} + +/* Ok, here comes the nasty part of the decoder. + + Instead of keeping an explicit state, we deduce it from the + token scanned so far. It is then immediately combined with + the current character to form a scanning decision. + + This is done by the following defines. + + - P is the length of the token scanned so far. + - L (often P-1) is the position on which contents we base a decision. + - C is a character or a group of characters (taken from 'tbl'). + + 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 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 (ces( CTL)) + { // DEC HACK ALERT! Control Characters are allowed *within* esc sequences in VT100 + // This means, they do neither a resetToken nor a pushToToken. Some of them, do + // of course. Guess this originates from a weakly layered handling of the X-on + // X-off protocol, which comes really below this level. + if (cc == CNTL('X') || cc == CNTL('Z') || cc == ESC) resetToken(); //VT100: CAN or SUB + if (cc != ESC) { tau( TY_CTL(cc+'@' ), 0, 0); return; } + } + + 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(); + } + 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; + _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(); +} + +// Interpreting Codes --------------------------------------------------------- + +/* + Now that the incoming character stream is properly tokenized, + meaning is assigned to them. These are either operations of + the current _screen, or of the emulation class itself. + + The token to be interpreteted comes in as a machine word + possibly accompanied by two parameters. + + Likewise, the operations assigned to, come with up to two + arguments. One could consider to make up a proper table + from the function below. + + The technical reference manual provides more information + about this mapping. +*/ + +void Vt102Emulation::tau( int token, int p, int q ) +{ +#if 0 +int N = (token>>0)&0xff; +int A = (token>>8)&0xff; +switch( N ) +{ + case 0: printf("%c", (p < 128) ? p : '?'); + break; + case 1: if (A == 'J') printf("\r"); + else if (A == 'M') printf("\n"); + else printf("CTL-%c ", (token>>8)&0xff); + break; + case 2: printf("ESC-%c ", (token>>8)&0xff); + break; + case 3: printf("ESC_CS-%c-%c ", (token>>8)&0xff, (token>>16)&0xff); + break; + case 4: printf("ESC_DE-%c ", (token>>8)&0xff); + break; + case 5: printf("CSI-PS-%c-%d", (token>>8)&0xff, (token>>16)&0xff ); + break; + case 6: printf("CSI-PN-%c [%d]", (token>>8)&0xff, p); + break; + case 7: printf("CSI-PR-%c-%d", (token>>8)&0xff, (token>>16)&0xff ); + break; + case 8: printf("VT52-%c", (token>>8)&0xff); + break; + case 9: printf("CSI-PG-%c", (token>>8)&0xff); + break; + case 10: printf("CSI-PE-%c", (token>>8)&0xff); + break; +} +#endif + + switch (token) + { + + case TY_CHR( ) : _currentScreen->ShowCharacter (p ); break; //UTF16 + + // 127 DEL : ignored on input + + case TY_CTL('@' ) : /* NUL: ignored */ break; + case TY_CTL('A' ) : /* SOH: ignored */ break; + case TY_CTL('B' ) : /* STX: ignored */ break; + case TY_CTL('C' ) : /* ETX: ignored */ break; + case TY_CTL('D' ) : /* EOT: ignored */ break; + case TY_CTL('E' ) : reportAnswerBack ( ); break; //VT100 + case TY_CTL('F' ) : /* ACK: ignored */ break; + case TY_CTL('G' ) : emit stateSet(NOTIFYBELL); + break; //VT100 + case TY_CTL('H' ) : _currentScreen->BackSpace ( ); break; //VT100 + case TY_CTL('I' ) : _currentScreen->Tabulate ( ); break; //VT100 + case TY_CTL('J' ) : _currentScreen->NewLine ( ); break; //VT100 + case TY_CTL('K' ) : _currentScreen->NewLine ( ); break; //VT100 + case TY_CTL('L' ) : _currentScreen->NewLine ( ); break; //VT100 + case TY_CTL('M' ) : _currentScreen->Return ( ); break; //VT100 + + case TY_CTL('N' ) : useCharset ( 1); break; //VT100 + case TY_CTL('O' ) : useCharset ( 0); break; //VT100 + + case TY_CTL('P' ) : /* DLE: ignored */ break; + case TY_CTL('Q' ) : /* DC1: XON continue */ break; //VT100 + case TY_CTL('R' ) : /* DC2: ignored */ break; + case TY_CTL('S' ) : /* DC3: XOFF halt */ break; //VT100 + case TY_CTL('T' ) : /* DC4: ignored */ break; + case TY_CTL('U' ) : /* NAK: ignored */ break; + case TY_CTL('V' ) : /* SYN: ignored */ break; + case TY_CTL('W' ) : /* ETB: ignored */ break; + case TY_CTL('X' ) : _currentScreen->ShowCharacter ( 0x2592); break; //VT100 + case TY_CTL('Y' ) : /* EM : ignored */ break; + case TY_CTL('Z' ) : _currentScreen->ShowCharacter ( 0x2592); break; //VT100 + case TY_CTL('[' ) : /* ESC: cannot be seen here. */ break; + case TY_CTL('\\' ) : /* FS : ignored */ break; + case TY_CTL(']' ) : /* GS : ignored */ break; + case TY_CTL('^' ) : /* RS : ignored */ break; + case TY_CTL('_' ) : /* US : ignored */ break; + + case TY_ESC('D' ) : _currentScreen->index ( ); break; //VT100 + case TY_ESC('E' ) : _currentScreen->NextLine ( ); break; //VT100 + case TY_ESC('H' ) : _currentScreen->changeTabStop (true ); break; //VT100 + case TY_ESC('M' ) : _currentScreen->reverseIndex ( ); break; //VT100 + case TY_ESC('Z' ) : reportTerminalType ( ); break; + case TY_ESC('c' ) : reset ( ); break; + + case TY_ESC('n' ) : useCharset ( 2); break; + case TY_ESC('o' ) : useCharset ( 3); break; + case TY_ESC('7' ) : saveCursor ( ); break; + case TY_ESC('8' ) : restoreCursor ( ); break; + + case TY_ESC('=' ) : setMode (MODE_AppKeyPad); break; + case TY_ESC('>' ) : resetMode (MODE_AppKeyPad); break; + case TY_ESC('<' ) : setMode (MODE_Ansi ); break; //VT100 + + case TY_ESC_CS('(', '0') : setCharset (0, '0'); break; //VT100 + case TY_ESC_CS('(', 'A') : setCharset (0, 'A'); break; //VT100 + case TY_ESC_CS('(', 'B') : setCharset (0, 'B'); break; //VT100 + + case TY_ESC_CS(')', '0') : setCharset (1, '0'); break; //VT100 + case TY_ESC_CS(')', 'A') : setCharset (1, 'A'); break; //VT100 + case TY_ESC_CS(')', 'B') : setCharset (1, 'B'); break; //VT100 + + case TY_ESC_CS('*', '0') : setCharset (2, '0'); break; //VT100 + case TY_ESC_CS('*', 'A') : setCharset (2, 'A'); break; //VT100 + case TY_ESC_CS('*', 'B') : setCharset (2, 'B'); break; //VT100 + + case TY_ESC_CS('+', '0') : setCharset (3, '0'); break; //VT100 + case TY_ESC_CS('+', 'A') : setCharset (3, 'A'); break; //VT100 + case TY_ESC_CS('+', 'B') : setCharset (3, 'B'); break; //VT100 + + case TY_ESC_CS('%', 'G') : setCodec (Utf8Codec ); break; //LINUX + case TY_ESC_CS('%', '@') : setCodec (LocaleCodec ); break; //LINUX + + case TY_ESC_DE('3' ) : /* Double height line, top half */ + _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , true ); + _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , true ); + break; + case TY_ESC_DE('4' ) : /* Double height line, bottom half */ + _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , true ); + _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , true ); + break; + case TY_ESC_DE('5' ) : /* Single width, single height line*/ + _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , false); + _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , false); + break; + case TY_ESC_DE('6' ) : /* Double width, single height line*/ + _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , true); + _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , false); + break; + case TY_ESC_DE('8' ) : _currentScreen->helpAlign ( ); break; + +// resize = \e[8;<row>;<col>t + case TY_CSI_PS('t', 8) : setImageSize( q /* colums */, 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; + + case TY_CSI_PS('K', 0) : _currentScreen->clearToEndOfLine ( ); break; + case TY_CSI_PS('K', 1) : _currentScreen->clearToBeginOfLine ( ); break; + case TY_CSI_PS('K', 2) : _currentScreen->clearEntireLine ( ); break; + case TY_CSI_PS('J', 0) : _currentScreen->clearToEndOfScreen ( ); break; + case TY_CSI_PS('J', 1) : _currentScreen->clearToBeginOfScreen ( ); break; + case TY_CSI_PS('J', 2) : _currentScreen->clearEntireScreen ( ); break; + case TY_CSI_PS('g', 0) : _currentScreen->changeTabStop (false ); break; //VT100 + case TY_CSI_PS('g', 3) : _currentScreen->clearTabStops ( ); break; //VT100 + case TY_CSI_PS('h', 4) : _currentScreen-> setMode (MODE_Insert ); break; + case TY_CSI_PS('h', 20) : setMode (MODE_NewLine ); break; + case TY_CSI_PS('i', 0) : /* IGNORE: attached printer */ break; //VT100 + case TY_CSI_PS('l', 4) : _currentScreen-> resetMode (MODE_Insert ); break; + case TY_CSI_PS('l', 20) : resetMode (MODE_NewLine ); break; + case TY_CSI_PS('s', 0) : saveCursor ( ); break; + case TY_CSI_PS('u', 0) : restoreCursor ( ); break; + + case TY_CSI_PS('m', 0) : _currentScreen->setDefaultRendition ( ); break; + case TY_CSI_PS('m', 1) : _currentScreen-> setRendition (RE_BOLD ); break; //VT100 + case TY_CSI_PS('m', 4) : _currentScreen-> setRendition (RE_UNDERLINE); break; //VT100 + case TY_CSI_PS('m', 5) : _currentScreen-> setRendition (RE_BLINK ); break; //VT100 + case TY_CSI_PS('m', 7) : _currentScreen-> setRendition (RE_REVERSE ); break; + case TY_CSI_PS('m', 10) : /* IGNORED: mapping related */ break; //LINUX + case TY_CSI_PS('m', 11) : /* IGNORED: mapping related */ break; //LINUX + case TY_CSI_PS('m', 12) : /* IGNORED: mapping related */ break; //LINUX + case TY_CSI_PS('m', 22) : _currentScreen->resetRendition (RE_BOLD ); break; + case TY_CSI_PS('m', 24) : _currentScreen->resetRendition (RE_UNDERLINE); break; + case TY_CSI_PS('m', 25) : _currentScreen->resetRendition (RE_BLINK ); break; + case TY_CSI_PS('m', 27) : _currentScreen->resetRendition (RE_REVERSE ); break; + + case TY_CSI_PS('m', 30) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 0); break; + case TY_CSI_PS('m', 31) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 1); break; + case TY_CSI_PS('m', 32) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 2); break; + case TY_CSI_PS('m', 33) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 3); break; + case TY_CSI_PS('m', 34) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 4); break; + case TY_CSI_PS('m', 35) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 5); break; + case TY_CSI_PS('m', 36) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 6); break; + case TY_CSI_PS('m', 37) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 7); break; + + case TY_CSI_PS('m', 38) : _currentScreen->setForeColor (p, q); break; + + case TY_CSI_PS('m', 39) : _currentScreen->setForeColor (COLOR_SPACE_DEFAULT, 0); break; + + case TY_CSI_PS('m', 40) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 0); break; + case TY_CSI_PS('m', 41) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 1); break; + case TY_CSI_PS('m', 42) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 2); break; + case TY_CSI_PS('m', 43) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 3); break; + case TY_CSI_PS('m', 44) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 4); break; + case TY_CSI_PS('m', 45) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 5); break; + case TY_CSI_PS('m', 46) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 6); break; + case TY_CSI_PS('m', 47) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 7); break; + + case TY_CSI_PS('m', 48) : _currentScreen->setBackColor (p, q); break; + + case TY_CSI_PS('m', 49) : _currentScreen->setBackColor (COLOR_SPACE_DEFAULT, 1); break; + + case TY_CSI_PS('m', 90) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 8); break; + case TY_CSI_PS('m', 91) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 9); break; + case TY_CSI_PS('m', 92) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 10); break; + case TY_CSI_PS('m', 93) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 11); break; + case TY_CSI_PS('m', 94) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 12); break; + case TY_CSI_PS('m', 95) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 13); break; + case TY_CSI_PS('m', 96) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 14); break; + case TY_CSI_PS('m', 97) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 15); break; + + case TY_CSI_PS('m', 100) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 8); break; + case TY_CSI_PS('m', 101) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 9); break; + case TY_CSI_PS('m', 102) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 10); break; + case TY_CSI_PS('m', 103) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 11); break; + case TY_CSI_PS('m', 104) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 12); break; + case TY_CSI_PS('m', 105) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 13); break; + case TY_CSI_PS('m', 106) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 14); break; + case TY_CSI_PS('m', 107) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 15); break; + + case TY_CSI_PS('n', 5) : reportStatus ( ); break; + case TY_CSI_PS('n', 6) : reportCursorPosition ( ); break; + case TY_CSI_PS('q', 0) : /* IGNORED: LEDs off */ break; //VT100 + case TY_CSI_PS('q', 1) : /* IGNORED: LED1 on */ break; //VT100 + case TY_CSI_PS('q', 2) : /* IGNORED: LED2 on */ break; //VT100 + case TY_CSI_PS('q', 3) : /* IGNORED: LED3 on */ break; //VT100 + case TY_CSI_PS('q', 4) : /* IGNORED: LED4 on */ break; //VT100 + case TY_CSI_PS('x', 0) : reportTerminalParms ( 2); break; //VT100 + case TY_CSI_PS('x', 1) : reportTerminalParms ( 3); break; //VT100 + + case TY_CSI_PN('@' ) : _currentScreen->insertChars (p ); break; + case TY_CSI_PN('A' ) : _currentScreen->cursorUp (p ); break; //VT100 + case TY_CSI_PN('B' ) : _currentScreen->cursorDown (p ); break; //VT100 + case TY_CSI_PN('C' ) : _currentScreen->cursorRight (p ); break; //VT100 + case TY_CSI_PN('D' ) : _currentScreen->cursorLeft (p ); break; //VT100 + case TY_CSI_PN('G' ) : _currentScreen->setCursorX (p ); break; //LINUX + case TY_CSI_PN('H' ) : _currentScreen->setCursorYX (p, q); break; //VT100 + case TY_CSI_PN('I' ) : _currentScreen->Tabulate (p ); break; + case TY_CSI_PN('L' ) : _currentScreen->insertLines (p ); break; + case TY_CSI_PN('M' ) : _currentScreen->deleteLines (p ); break; + case TY_CSI_PN('P' ) : _currentScreen->deleteChars (p ); break; + case TY_CSI_PN('S' ) : _currentScreen->scrollUp (p ); break; + case TY_CSI_PN('T' ) : _currentScreen->scrollDown (p ); break; + case TY_CSI_PN('X' ) : _currentScreen->eraseChars (p ); break; + case TY_CSI_PN('Z' ) : _currentScreen->backTabulate (p ); break; + case TY_CSI_PN('c' ) : reportTerminalType ( ); break; //VT100 + case TY_CSI_PN('d' ) : _currentScreen->setCursorY (p ); break; //LINUX + case TY_CSI_PN('f' ) : _currentScreen->setCursorYX (p, q); break; //VT100 + case TY_CSI_PN('r' ) : setMargins (p, q); break; //VT100 + case TY_CSI_PN('y' ) : /* IGNORED: Confidence test */ break; //VT100 + + case TY_CSI_PR('h', 1) : setMode (MODE_AppCuKeys); break; //VT100 + case TY_CSI_PR('l', 1) : resetMode (MODE_AppCuKeys); break; //VT100 + case TY_CSI_PR('s', 1) : saveMode (MODE_AppCuKeys); break; //FIXME + case TY_CSI_PR('r', 1) : restoreMode (MODE_AppCuKeys); break; //FIXME + + case TY_CSI_PR('l', 2) : resetMode (MODE_Ansi ); break; //VT100 + + case TY_CSI_PR('h', 3) : clearScreenAndSetColumns(132); break; //VT100 + case TY_CSI_PR('l', 3) : clearScreenAndSetColumns(80); break; //VT100 + + case TY_CSI_PR('h', 4) : /* IGNORED: soft scrolling */ break; //VT100 + case TY_CSI_PR('l', 4) : /* IGNORED: soft scrolling */ break; //VT100 + + case TY_CSI_PR('h', 5) : _currentScreen-> setMode (MODE_Screen ); break; //VT100 + case TY_CSI_PR('l', 5) : _currentScreen-> resetMode (MODE_Screen ); break; //VT100 + + case TY_CSI_PR('h', 6) : _currentScreen-> setMode (MODE_Origin ); break; //VT100 + case TY_CSI_PR('l', 6) : _currentScreen-> resetMode (MODE_Origin ); break; //VT100 + case TY_CSI_PR('s', 6) : _currentScreen-> saveMode (MODE_Origin ); break; //FIXME + case TY_CSI_PR('r', 6) : _currentScreen->restoreMode (MODE_Origin ); break; //FIXME + + case TY_CSI_PR('h', 7) : _currentScreen-> setMode (MODE_Wrap ); break; //VT100 + case TY_CSI_PR('l', 7) : _currentScreen-> resetMode (MODE_Wrap ); break; //VT100 + case TY_CSI_PR('s', 7) : _currentScreen-> saveMode (MODE_Wrap ); break; //FIXME + case TY_CSI_PR('r', 7) : _currentScreen->restoreMode (MODE_Wrap ); break; //FIXME + + case TY_CSI_PR('h', 8) : /* IGNORED: autorepeat on */ break; //VT100 + case TY_CSI_PR('l', 8) : /* IGNORED: autorepeat off */ break; //VT100 + case TY_CSI_PR('s', 8) : /* IGNORED: autorepeat on */ break; //VT100 + case TY_CSI_PR('r', 8) : /* IGNORED: autorepeat off */ break; //VT100 + + case TY_CSI_PR('h', 9) : /* IGNORED: interlace */ break; //VT100 + case TY_CSI_PR('l', 9) : /* IGNORED: interlace */ break; //VT100 + case TY_CSI_PR('s', 9) : /* IGNORED: interlace */ break; //VT100 + case TY_CSI_PR('r', 9) : /* IGNORED: interlace */ break; //VT100 + + case TY_CSI_PR('h', 12) : /* IGNORED: Cursor blink */ break; //att610 + case TY_CSI_PR('l', 12) : /* IGNORED: Cursor blink */ break; //att610 + case TY_CSI_PR('s', 12) : /* IGNORED: Cursor blink */ break; //att610 + case TY_CSI_PR('r', 12) : /* IGNORED: Cursor blink */ break; //att610 + + case TY_CSI_PR('h', 25) : setMode (MODE_Cursor ); break; //VT100 + case TY_CSI_PR('l', 25) : resetMode (MODE_Cursor ); break; //VT100 + case TY_CSI_PR('s', 25) : saveMode (MODE_Cursor ); break; //VT100 + case TY_CSI_PR('r', 25) : restoreMode (MODE_Cursor ); break; //VT100 + + case TY_CSI_PR('h', 41) : /* IGNORED: obsolete more(1) fix */ break; //XTERM + case TY_CSI_PR('l', 41) : /* IGNORED: obsolete more(1) fix */ break; //XTERM + case TY_CSI_PR('s', 41) : /* IGNORED: obsolete more(1) fix */ break; //XTERM + case TY_CSI_PR('r', 41) : /* IGNORED: obsolete more(1) fix */ break; //XTERM + + case TY_CSI_PR('h', 47) : setMode (MODE_AppScreen); break; //VT100 + case TY_CSI_PR('l', 47) : resetMode (MODE_AppScreen); break; //VT100 + case TY_CSI_PR('s', 47) : saveMode (MODE_AppScreen); break; //XTERM + case TY_CSI_PR('r', 47) : restoreMode (MODE_AppScreen); break; //XTERM + + case TY_CSI_PR('h', 67) : /* IGNORED: DECBKM */ break; //XTERM + case TY_CSI_PR('l', 67) : /* IGNORED: DECBKM */ break; //XTERM + case TY_CSI_PR('s', 67) : /* IGNORED: DECBKM */ break; //XTERM + case TY_CSI_PR('r', 67) : /* IGNORED: DECBKM */ break; //XTERM + + // XTerm defines the following modes: + // SET_VT200_MOUSE 1000 + // SET_VT200_HIGHLIGHT_MOUSE 1001 + // SET_BTN_EVENT_MOUSE 1002 + // SET_ANY_EVENT_MOUSE 1003 + // + + //Note about mouse modes: + //There are four mouse modes which xterm-compatible terminals can support - 1000,1001,1002,1003 + //Konsole currently supports mode 1000 (basic mouse press and release) and mode 1002 (dragging the mouse). + //TODO: Implementation of mouse modes 1001 (something called hilight tracking) and + //1003 (a slight variation on dragging the mouse) + // + + case TY_CSI_PR('h', 1000) : setMode (MODE_Mouse1000); break; //XTERM + case TY_CSI_PR('l', 1000) : resetMode (MODE_Mouse1000); break; //XTERM + case TY_CSI_PR('s', 1000) : saveMode (MODE_Mouse1000); break; //XTERM + case TY_CSI_PR('r', 1000) : restoreMode (MODE_Mouse1000); break; //XTERM + + case TY_CSI_PR('h', 1001) : /* IGNORED: hilite mouse tracking */ break; //XTERM + case TY_CSI_PR('l', 1001) : resetMode (MODE_Mouse1001); break; //XTERM + case TY_CSI_PR('s', 1001) : /* IGNORED: hilite mouse tracking */ break; //XTERM + case TY_CSI_PR('r', 1001) : /* IGNORED: hilite mouse tracking */ break; //XTERM + + case TY_CSI_PR('h', 1002) : setMode (MODE_Mouse1002); break; //XTERM + case TY_CSI_PR('l', 1002) : resetMode (MODE_Mouse1002); break; //XTERM + case TY_CSI_PR('s', 1002) : saveMode (MODE_Mouse1002); break; //XTERM + case TY_CSI_PR('r', 1002) : restoreMode (MODE_Mouse1002); break; //XTERM + + case TY_CSI_PR('h', 1003) : setMode (MODE_Mouse1003); break; //XTERM + case TY_CSI_PR('l', 1003) : resetMode (MODE_Mouse1003); break; //XTERM + case TY_CSI_PR('s', 1003) : saveMode (MODE_Mouse1003); break; //XTERM + case TY_CSI_PR('r', 1003) : restoreMode (MODE_Mouse1003); break; //XTERM + + case TY_CSI_PR('h', 1047) : setMode (MODE_AppScreen); break; //XTERM + case TY_CSI_PR('l', 1047) : _screen[1]->clearEntireScreen(); resetMode(MODE_AppScreen); break; //XTERM + case TY_CSI_PR('s', 1047) : saveMode (MODE_AppScreen); break; //XTERM + case TY_CSI_PR('r', 1047) : restoreMode (MODE_AppScreen); break; //XTERM + + //FIXME: Unitoken: save translations + case TY_CSI_PR('h', 1048) : saveCursor ( ); break; //XTERM + case TY_CSI_PR('l', 1048) : restoreCursor ( ); break; //XTERM + case TY_CSI_PR('s', 1048) : saveCursor ( ); break; //XTERM + case TY_CSI_PR('r', 1048) : restoreCursor ( ); break; //XTERM + + //FIXME: every once new sequences like this pop up in xterm. + // Here's a guess of what they could mean. + case TY_CSI_PR('h', 1049) : saveCursor(); _screen[1]->clearEntireScreen(); setMode(MODE_AppScreen); break; //XTERM + case TY_CSI_PR('l', 1049) : resetMode(MODE_AppScreen); restoreCursor(); break; //XTERM + + //FIXME: weird DEC reset sequence + case TY_CSI_PE('p' ) : /* IGNORED: reset ( ) */ break; + + //FIXME: when changing between vt52 and ansi mode evtl do some resetting. + case TY_VT52('A' ) : _currentScreen->cursorUp ( 1); break; //VT52 + case TY_VT52('B' ) : _currentScreen->cursorDown ( 1); break; //VT52 + case TY_VT52('C' ) : _currentScreen->cursorRight ( 1); break; //VT52 + case TY_VT52('D' ) : _currentScreen->cursorLeft ( 1); break; //VT52 + + case TY_VT52('F' ) : setAndUseCharset (0, '0'); break; //VT52 + case TY_VT52('G' ) : setAndUseCharset (0, 'B'); break; //VT52 + + case TY_VT52('H' ) : _currentScreen->setCursorYX (1,1 ); break; //VT52 + case TY_VT52('I' ) : _currentScreen->reverseIndex ( ); break; //VT52 + case TY_VT52('J' ) : _currentScreen->clearToEndOfScreen ( ); break; //VT52 + case TY_VT52('K' ) : _currentScreen->clearToEndOfLine ( ); break; //VT52 + case TY_VT52('Y' ) : _currentScreen->setCursorYX (p-31,q-31 ); break; //VT52 + case TY_VT52('Z' ) : reportTerminalType ( ); break; //VT52 + case TY_VT52('<' ) : setMode (MODE_Ansi ); break; //VT52 + case TY_VT52('=' ) : setMode (MODE_AppKeyPad); break; //VT52 + case TY_VT52('>' ) : resetMode (MODE_AppKeyPad); break; //VT52 + + case TY_CSI_PG('c' ) : reportSecondaryAttributes( ); break; //VT100 + + default : ReportErrorToken(); break; + }; +} + +void Vt102Emulation::clearScreenAndSetColumns(int columnCount) +{ + setImageSize(_currentScreen->getLines(),columnCount); + clearEntireScreen(); + setDefaultMargins(); + _currentScreen->setCursorYX(0,0); +} + +/* ------------------------------------------------------------------------- */ +/* */ +/* Terminal to Host protocol */ +/* */ +/* ------------------------------------------------------------------------- */ + +/* + Outgoing bytes originate from several sources: + + - Replies to Enquieries. + - Mouse Events + - Keyboard Events +*/ + +/*! +*/ + +void Vt102Emulation::sendString(const char* s , int length) +{ + if ( length >= 0 ) + emit sendData(s,length); + else + emit sendData(s,strlen(s)); +} + +// Replies ----------------------------------------------------------------- -- + +// This section copes with replies send as response to an enquiery control code. + +/*! +*/ + +void Vt102Emulation::reportCursorPosition() +{ char tmp[20]; + sprintf(tmp,"\033[%d;%dR",_currentScreen->getCursorY()+1,_currentScreen->getCursorX()+1); + sendString(tmp); +} + +/* + What follows here is rather obsolete and faked stuff. + The correspondent enquieries are neverthenless issued. +*/ + +/*! +*/ + +void Vt102Emulation::reportTerminalType() +{ + // Primary device attribute response (Request was: ^[[0c or ^[[c (from TT321 Users Guide)) + // VT220: ^[[?63;1;2;3;6;7;8c (list deps on emul. capabilities) + // VT100: ^[[?1;2c + // VT101: ^[[?1;0c + // VT102: ^[[?6v + if (getMode(MODE_Ansi)) + sendString("\033[?1;2c"); // I'm a VT100 + else + sendString("\033/Z"); // I'm a VT52 +} + +void Vt102Emulation::reportSecondaryAttributes() +{ + // Seconday device attribute response (Request was: ^[[>0c or ^[[>c) + if (getMode(MODE_Ansi)) + sendString("\033[>0;115;0c"); // Why 115? ;) + else + sendString("\033/Z"); // FIXME I don't think VT52 knows about it but kept for + // konsoles backward compatibility. +} + +void Vt102Emulation::reportTerminalParms(int p) +// DECREPTPARM +{ char tmp[100]; + sprintf(tmp,"\033[%d;1;1;112;112;1;0x",p); // not really true. + sendString(tmp); +} + +/*! +*/ + +void Vt102Emulation::reportStatus() +{ + sendString("\033[0n"); //VT100. Device status report. 0 = Ready. +} + +/*! +*/ + +#define ANSWER_BACK "" // This is really obsolete VT100 stuff. + +void Vt102Emulation::reportAnswerBack() +{ + 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). + + eventType represents the kind of mouse action that occurred: + 0 = Mouse button press or release + 1 = Mouse drag +*/ + +void Vt102Emulation::sendMouseEvent( int cb, int cx, int cy , int eventType ) +{ char tmp[20]; + if ( cx<1 || cy<1 ) return; + // normal buttons are passed as 0x20 + button, + // mouse wheel (buttons 4,5) as 0x5c + button + if (cb >= 4) cb += 0x3c; + + //Mouse motion handling + 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); +} + +// 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()) { + 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; + + // lookup key binding + if ( _keyTranslator ) + { + KeyboardTranslator::Entry entry = _keyTranslator->findEntry( + event->key() , + modifiers, + states ); + + // send result to terminal + QByteArray textToSend; + + // special handling for the Alt (aka. Meta) modifier. pressing + // Alt+[Character] results in Esc+[Character] being sent + // (unless there is an entry defined for this particular combination + // in the keyboard modifier) + bool wantsAltModifier = entry.modifiers() & entry.modifierMask() & Qt::AltModifier; + bool wantsAnyModifier = entry.state() & entry.stateMask() & KeyboardTranslator::AnyModifierState; + + if ( modifiers & Qt::AltModifier && !(wantsAltModifier || wantsAnyModifier) + && !event->text().isEmpty() ) + { + textToSend.prepend("\033"); + } + + if ( entry.command() != KeyboardTranslator::NoCommand ) + { + if (entry.command() & KeyboardTranslator::EraseCommand) + textToSend += getErase(); + // TODO command handling + } + else if ( !entry.text().isEmpty() ) + { + textToSend += _codec->fromUnicode(entry.text(true,modifiers)); + } + else + textToSend += _codec->fromUnicode(event->text()); + + sendData( textToSend.constData() , textToSend.length() ); + } + else + { + // print an error message to the terminal if no key translator has been + // set + QString translatorError = ("No keyboard translator available. " + "The information needed to convert key presses " + "into characters to send to the terminal " + "is missing."); + + reset(); + receiveData( translatorError.toAscii().constData() , translatorError.count() ); + } +} + +/* ------------------------------------------------------------------------- */ +/* */ +/* VT100 Charsets */ +/* */ +/* ------------------------------------------------------------------------- */ + +// Character Set Conversion ------------------------------------------------ -- + +/* + The processing contains a VT100 specific code translation layer. + It's still in use and mainly responsible for the line drawing graphics. + + These and some other glyphs are assigned to codes (0x5f-0xfe) + normally occupied by the latin letters. Since this codes also + appear within control sequences, the extra code conversion + does not permute with the tokenizer and is placed behind it + in the pipeline. It only applies to tokens, which represent + plain characters. + + This conversion it eventually continued in TerminalDisplay.C, since + it might involve VT100 enhanced fonts, which have these + particular glyphs allocated in (0x00-0x1f) in their code page. +*/ + +#define CHARSET _charset[_currentScreen==_screen[1]] + +// Apply current character map. + +unsigned short Vt102Emulation::applyCharset(unsigned short c) +{ + if (CHARSET.graphic && 0x5f <= c && c <= 0x7e) return vt100_graphics[c-0x5f]; + if (CHARSET.pound && c == '#' ) return 0xa3; //This mode is obsolete + return c; +} + +/* + "Charset" related part of the emulation state. + This configures the VT100 _charset filter. + + While most operation work on the current _screen, + the following two are different. +*/ + +void Vt102Emulation::resetCharset(int scrno) +{ + _charset[scrno].cu_cs = 0; + strncpy(_charset[scrno].charset,"BBBB",4); + _charset[scrno].sa_graphic = false; + _charset[scrno].sa_pound = false; + _charset[scrno].graphic = false; + _charset[scrno].pound = false; +} + +void Vt102Emulation::setCharset(int n, int cs) // on both screens. +{ + _charset[0].charset[n&3] = cs; useCharset(_charset[0].cu_cs); + _charset[1].charset[n&3] = cs; useCharset(_charset[1].cu_cs); +} + +void Vt102Emulation::setAndUseCharset(int n, int cs) +{ + CHARSET.charset[n&3] = cs; + useCharset(n&3); +} + +void Vt102Emulation::useCharset(int n) +{ + CHARSET.cu_cs = n&3; + CHARSET.graphic = (CHARSET.charset[n&3] == '0'); + CHARSET.pound = (CHARSET.charset[n&3] == 'A'); //This mode is obsolete +} + +void Vt102Emulation::setDefaultMargins() +{ + _screen[0]->setDefaultMargins(); + _screen[1]->setDefaultMargins(); +} + +void Vt102Emulation::setMargins(int t, int b) +{ + _screen[0]->setMargins(t, b); + _screen[1]->setMargins(t, b); +} + +/*! Save the cursor position and the rendition attribute settings. */ + +void Vt102Emulation::saveCursor() +{ + CHARSET.sa_graphic = CHARSET.graphic; + CHARSET.sa_pound = CHARSET.pound; //This mode is obsolete + // we are not clear about these + //sa_charset = charsets[cScreen->_charset]; + //sa_charset_num = cScreen->_charset; + _currentScreen->saveCursor(); +} + +/*! Restore the cursor position and the rendition attribute settings. */ + +void Vt102Emulation::restoreCursor() +{ + CHARSET.graphic = CHARSET.sa_graphic; + CHARSET.pound = CHARSET.sa_pound; //This mode is obsolete + _currentScreen->restoreCursor(); +} + +/* ------------------------------------------------------------------------- */ +/* */ +/* Mode Operations */ +/* */ +/* ------------------------------------------------------------------------- */ + +/* + Some of the emulations state is either added to the state of the screens. + + This causes some scoping problems, since different emulations choose to + located the mode either to the current _screen or to both. + + For strange reasons, the extend of the rendition attributes ranges over + all screens and not over the actual _screen. + + We decided on the precise precise extend, somehow. +*/ + +// "Mode" related part of the state. These are all booleans. + +void Vt102Emulation::resetModes() +{ + 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); + // here come obsolete modes + resetMode(MODE_AppCuKeys); saveMode(MODE_AppCuKeys); + resetMode(MODE_NewLine ); + setMode(MODE_Ansi ); +} + +void Vt102Emulation::setMode(int m) +{ + _currParm.mode[m] = true; + switch (m) + { + case MODE_Mouse1000: + case MODE_Mouse1001: + case MODE_Mouse1002: + case MODE_Mouse1003: + emit programUsesMouseChanged(false); + break; + + case MODE_AppScreen : _screen[1]->clearSelection(); + setScreen(1); + break; + } + if (m < MODES_SCREEN || m == MODE_NewLine) + { + _screen[0]->setMode(m); + _screen[1]->setMode(m); + } +} + +void Vt102Emulation::resetMode(int m) +{ + _currParm.mode[m] = false; + switch (m) + { + case MODE_Mouse1000 : + case MODE_Mouse1001 : + case MODE_Mouse1002 : + case MODE_Mouse1003 : + emit programUsesMouseChanged(true); + break; + + case MODE_AppScreen : _screen[0]->clearSelection(); + setScreen(0); + break; + } + if (m < MODES_SCREEN || m == MODE_NewLine) + { + _screen[0]->resetMode(m); + _screen[1]->resetMode(m); + } +} + +void Vt102Emulation::saveMode(int m) +{ + _saveParm.mode[m] = _currParm.mode[m]; +} + +void Vt102Emulation::restoreMode(int m) +{ + if (_saveParm.mode[m]) + setMode(m); + else + resetMode(m); +} + +bool Vt102Emulation::getMode(int m) +{ + return _currParm.mode[m]; +} + +char Vt102Emulation::getErase() const +{ + KeyboardTranslator::Entry entry = _keyTranslator->findEntry( + Qt::Key_Backspace, + 0, + 0); + if ( entry.text().count() > 0 ) + return entry.text()[0]; + else + 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 +*/ + +static void hexdump(int* s, int len) +{ int i; + for (i = 0; i < len; i++) + { + if (s[i] == '\\') + printf("\\\\"); + else + if ((s[i]) > 32 && s[i] < 127) + printf("%c",s[i]); + else + printf("\\%04x(hex)",s[i]); + } +} + +void Vt102Emulation::scan_buffer_report() +{ + if (ppos == 0 || ppos == 1 && (pbuf[0] & 0xff) >= 32) return; + printf("token: "); hexdump(pbuf,ppos); printf("\n"); +} + +/*! +*/ + +void Vt102Emulation::ReportErrorToken() +{ +#ifndef NDEBUG + printf("undecodable "); scan_buffer_report(); +#endif +} + +//#include "moc_Vt102Emulation.cpp" + diff --git a/client/browser/qtermwidget/includes/Vt102Emulation.h b/client/browser/qtermwidget/src/Vt102Emulation.h index 4554c1bf..4554c1bf 100644 --- a/client/browser/qtermwidget/includes/Vt102Emulation.h +++ b/client/browser/qtermwidget/src/Vt102Emulation.h diff --git a/client/browser/qtermwidget/includes/default.keytab b/client/browser/qtermwidget/src/default.keytab index f84293d9..f84293d9 100644 --- a/client/browser/qtermwidget/includes/default.keytab +++ b/client/browser/qtermwidget/src/default.keytab diff --git a/client/browser/qtermwidget/src/k3process.cpp b/client/browser/qtermwidget/src/k3process.cpp new file mode 100644 index 00000000..ca4b8fd9 --- /dev/null +++ b/client/browser/qtermwidget/src/k3process.cpp @@ -0,0 +1,1055 @@ +/* + This file is part of the KDE libraries + Copyright (C) 1997 Christian Czezatke (e9025461@student.tuwien.ac.at) + + 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + + +#include "k3process.h" +#include "k3process.moc" +//#include <config.h> + +#include "k3processcontroller.h" +#include "kpty.h" + +#ifdef __osf__ +#define _OSF_SOURCE +#include <float.h> +#endif + +#ifdef _AIX +#define _ALL_SOURCE +#endif + +#include <sys/socket.h> +#include <sys/ioctl.h> + +#include <sys/types.h> +#include <sys/time.h> +#include <sys/resource.h> +#include <sys/stat.h> +#include <sys/wait.h> + +#ifdef HAVE_SYS_SELECT_H +#include <sys/select.h> +#endif + +#include <errno.h> +#include <assert.h> +#include <fcntl.h> +#include <time.h> +#include <stdlib.h> +#include <signal.h> +#include <stdio.h> +#include <string.h> +#include <unistd.h> +#include <pwd.h> +#include <grp.h> + +#include <QtCore/QMap> +#include <QtCore/QFile> +#include <QtCore/QSocketNotifier> + +//#include <kdebug.h> +//#include <kstandarddirs.h> +//#include <kuser.h> + + + +////////////////// +// private data // +////////////////// + +class K3ProcessPrivate { +public: + K3ProcessPrivate() : + usePty(K3Process::NoCommunication), + addUtmp(false), useShell(false), + pty(0), + priority(0) + { + } + + K3Process::Communication usePty; + bool addUtmp : 1; + bool useShell : 1; + + KPty *pty; + + int priority; + + QMap<QString,QString> env; + QString wd; + QByteArray shell; + QByteArray executable; +}; + +///////////////////////////// +// public member functions // +///////////////////////////// + +K3Process::K3Process( QObject* parent ) + : QObject( parent ), + run_mode(NotifyOnExit), + runs(false), + pid_(0), + status(0), + keepPrivs(false), + innot(0), + outnot(0), + errnot(0), + communication(NoCommunication), + input_data(0), + input_sent(0), + input_total(0), + d(new K3ProcessPrivate) +{ + K3ProcessController::ref(); + K3ProcessController::instance()->addKProcess(this); + + + out[0] = out[1] = -1; + in[0] = in[1] = -1; + err[0] = err[1] = -1; +} + +void +K3Process::setEnvironment(const QString &name, const QString &value) +{ + d->env.insert(name, value); +} + +void +K3Process::setWorkingDirectory(const QString &dir) +{ + d->wd = dir; +} + +void +K3Process::setupEnvironment() +{ + QMap<QString,QString>::Iterator it; + for(it = d->env.begin(); it != d->env.end(); ++it) + { + setenv(QFile::encodeName(it.key()).data(), + QFile::encodeName(it.value()).data(), 1); + } + if (!d->wd.isEmpty()) + { + chdir(QFile::encodeName(d->wd).data()); + } +} + +void +K3Process::setRunPrivileged(bool keepPrivileges) +{ + keepPrivs = keepPrivileges; +} + +bool +K3Process::runPrivileged() const +{ + return keepPrivs; +} + +bool +K3Process::setPriority(int prio) +{ + if (runs) { + if (setpriority(PRIO_PROCESS, pid_, prio)) + return false; + } else { + if (prio > 19 || prio < (geteuid() ? getpriority(PRIO_PROCESS, 0) : -20)) + return false; + } + d->priority = prio; + return true; +} + +K3Process::~K3Process() +{ + if (run_mode != DontCare) + kill(SIGKILL); + detach(); + + delete d->pty; + delete d; + + K3ProcessController::instance()->removeKProcess(this); + K3ProcessController::deref(); +} + +void K3Process::detach() +{ + if (runs) { + K3ProcessController::instance()->addProcess(pid_); + runs = false; + pid_ = 0; // close without draining + commClose(); // Clean up open fd's and socket notifiers. + } +} + +void K3Process::setBinaryExecutable(const char *filename) +{ + d->executable = filename; +} + +K3Process &K3Process::operator<<(const QStringList& args) +{ + QStringList::ConstIterator it = args.begin(); + for ( ; it != args.end() ; ++it ) + arguments.append(QFile::encodeName(*it)); + return *this; +} + +K3Process &K3Process::operator<<(const QByteArray& arg) +{ + return operator<< (arg.data()); +} + +K3Process &K3Process::operator<<(const char* arg) +{ + arguments.append(arg); + return *this; +} + +K3Process &K3Process::operator<<(const QString& arg) +{ + arguments.append(QFile::encodeName(arg)); + return *this; +} + +void K3Process::clearArguments() +{ + arguments.clear(); +} + +bool K3Process::start(RunMode runmode, Communication comm) +{ + if (runs) { + qDebug() << "Attempted to start an already running process" << endl; + return false; + } + + uint n = arguments.count(); + if (n == 0) { + qDebug() << "Attempted to start a process without arguments" << endl; + return false; + } + char **arglist; + QByteArray shellCmd; + if (d->useShell) + { + if (d->shell.isEmpty()) { + qDebug() << "Invalid shell specified" << endl; + return false; + } + + for (uint i = 0; i < n; i++) { + shellCmd += arguments[i]; + shellCmd += ' '; // CC: to separate the arguments + } + + arglist = static_cast<char **>(malloc( 4 * sizeof(char *))); + arglist[0] = d->shell.data(); + arglist[1] = (char *) "-c"; + arglist[2] = shellCmd.data(); + arglist[3] = 0; + } + else + { + arglist = static_cast<char **>(malloc( (n + 1) * sizeof(char *))); + for (uint i = 0; i < n; i++) + arglist[i] = arguments[i].data(); + arglist[n] = 0; + } + + run_mode = runmode; + + if (!setupCommunication(comm)) + { + qDebug() << "Could not setup Communication!" << endl; + free(arglist); + return false; + } + + // We do this in the parent because if we do it in the child process + // gdb gets confused when the application runs from gdb. +#ifdef HAVE_INITGROUPS + struct passwd *pw = geteuid() ? 0 : getpwuid(getuid()); +#endif + + int fd[2]; + if (pipe(fd)) + fd[0] = fd[1] = -1; // Pipe failed.. continue + + // we don't use vfork() because + // - it has unclear semantics and is not standardized + // - we do way too much magic in the child + pid_ = fork(); + if (pid_ == 0) { + // The child process + + close(fd[0]); + // Closing of fd[1] indicates that the execvp() succeeded! + fcntl(fd[1], F_SETFD, FD_CLOEXEC); + + if (!commSetupDoneC()) + qDebug() << "Could not finish comm setup in child!" << endl; + + // reset all signal handlers + struct sigaction act; + sigemptyset(&act.sa_mask); + act.sa_handler = SIG_DFL; + act.sa_flags = 0; + for (int sig = 1; sig < NSIG; sig++) + sigaction(sig, &act, 0L); + + if (d->priority) + setpriority(PRIO_PROCESS, 0, d->priority); + + if (!runPrivileged()) + { + setgid(getgid()); +#ifdef HAVE_INITGROUPS + if (pw) + initgroups(pw->pw_name, pw->pw_gid); +#endif + if (geteuid() != getuid()) + setuid(getuid()); + if (geteuid() != getuid()) + _exit(1); + } + + setupEnvironment(); + + if (runmode == DontCare || runmode == OwnGroup) + setsid(); + + const char *executable = arglist[0]; + if (!d->executable.isEmpty()) + executable = d->executable.data(); + execvp(executable, arglist); + + char resultByte = 1; + write(fd[1], &resultByte, 1); + _exit(-1); + } else if (pid_ == -1) { + // forking failed + + // commAbort(); + pid_ = 0; + free(arglist); + return false; + } + // the parent continues here + free(arglist); + + if (!commSetupDoneP()) + qDebug() << "Could not finish comm setup in parent!" << endl; + + // Check whether client could be started. + close(fd[1]); + for(;;) + { + char resultByte; + int n = ::read(fd[0], &resultByte, 1); + if (n == 1) + { + // exec() failed + close(fd[0]); + waitpid(pid_, 0, 0); + pid_ = 0; + commClose(); + return false; + } + if (n == -1) + { + if (errno == EINTR) + continue; // Ignore + } + break; // success + } + close(fd[0]); + + runs = true; + switch (runmode) + { + case Block: + for (;;) + { + commClose(); // drain only, unless obsolete reimplementation + if (!runs) + { + // commClose detected data on the process exit notifification pipe + K3ProcessController::instance()->unscheduleCheck(); + if (waitpid(pid_, &status, WNOHANG) != 0) // error finishes, too + { + commClose(); // this time for real (runs is false) + K3ProcessController::instance()->rescheduleCheck(); + break; + } + runs = true; // for next commClose() iteration + } + else + { + // commClose is an obsolete reimplementation and waited until + // all output channels were closed (or it was interrupted). + // there is a chance that it never gets here ... + waitpid(pid_, &status, 0); + runs = false; + break; + } + } + // why do we do this? i think this signal should be emitted _only_ + // after the process has successfully run _asynchronously_ --ossi + emit processExited(this); + break; + default: // NotifyOnExit & OwnGroup + input_data = 0; // Discard any data for stdin that might still be there + break; + } + return true; +} + + + +bool K3Process::kill(int signo) +{ + if (runs && pid_ > 0 && !::kill(run_mode == OwnGroup ? -pid_ : pid_, signo)) + return true; + return false; +} + + + +bool K3Process::isRunning() const +{ + return runs; +} + + + +pid_t K3Process::pid() const +{ + return pid_; +} + +#ifndef timersub +# define timersub(a, b, result) \ + do { \ + (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \ + (result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \ + if ((result)->tv_usec < 0) { \ + --(result)->tv_sec; \ + (result)->tv_usec += 1000000; \ + } \ + } while (0) +#endif + +bool K3Process::wait(int timeout) +{ + if (!runs) + return true; + +#ifndef __linux__ + struct timeval etv; +#endif + struct timeval tv, *tvp; + if (timeout < 0) + tvp = 0; + else + { +#ifndef __linux__ + gettimeofday(&etv, 0); + etv.tv_sec += timeout; +#else + tv.tv_sec = timeout; + tv.tv_usec = 0; +#endif + tvp = &tv; + } + + int fd = K3ProcessController::instance()->notifierFd(); + for(;;) + { + fd_set fds; + FD_ZERO( &fds ); + FD_SET( fd, &fds ); + +#ifndef __linux__ + if (tvp) + { + gettimeofday(&tv, 0); + timersub(&etv, &tv, &tv); + if (tv.tv_sec < 0) + tv.tv_sec = tv.tv_usec = 0; + } +#endif + + switch( select( fd+1, &fds, 0, 0, tvp ) ) + { + case -1: + if( errno == EINTR ) + break; + // fall through; should happen if tvp->tv_sec < 0 + case 0: + K3ProcessController::instance()->rescheduleCheck(); + return false; + default: + K3ProcessController::instance()->unscheduleCheck(); + if (waitpid(pid_, &status, WNOHANG) != 0) // error finishes, too + { + processHasExited(status); + K3ProcessController::instance()->rescheduleCheck(); + return true; + } + } + } + return false; +} + + + +bool K3Process::normalExit() const +{ + return (pid_ != 0) && !runs && WIFEXITED(status); +} + + +bool K3Process::signalled() const +{ + return (pid_ != 0) && !runs && WIFSIGNALED(status); +} + + +bool K3Process::coreDumped() const +{ +#ifdef WCOREDUMP + return signalled() && WCOREDUMP(status); +#else + return false; +#endif +} + + +int K3Process::exitStatus() const +{ + return WEXITSTATUS(status); +} + + +int K3Process::exitSignal() const +{ + return WTERMSIG(status); +} + + +bool K3Process::writeStdin(const char *buffer, int buflen) +{ + // if there is still data pending, writing new data + // to stdout is not allowed (since it could also confuse + // kprocess ...) + if (input_data != 0) + return false; + + if (communication & Stdin) { + input_data = buffer; + input_sent = 0; + input_total = buflen; + innot->setEnabled(true); + if (input_total) + slotSendData(0); + return true; + } else + return false; +} + +void K3Process::suspend() +{ + if (outnot) + outnot->setEnabled(false); +} + +void K3Process::resume() +{ + if (outnot) + outnot->setEnabled(true); +} + +bool K3Process::closeStdin() +{ + if (communication & Stdin) { + communication = communication & ~Stdin; + delete innot; + innot = 0; + if (!(d->usePty & Stdin)) + close(in[1]); + in[1] = -1; + return true; + } else + return false; +} + +bool K3Process::closeStdout() +{ + if (communication & Stdout) { + communication = communication & ~Stdout; + delete outnot; + outnot = 0; + if (!(d->usePty & Stdout)) + close(out[0]); + out[0] = -1; + return true; + } else + return false; +} + +bool K3Process::closeStderr() +{ + if (communication & Stderr) { + communication = communication & ~Stderr; + delete errnot; + errnot = 0; + if (!(d->usePty & Stderr)) + close(err[0]); + err[0] = -1; + return true; + } else + return false; +} + +bool K3Process::closePty() +{ + if (d->pty && d->pty->masterFd() >= 0) { + if (d->addUtmp) + d->pty->logout(); + d->pty->close(); + return true; + } else + return false; +} + +void K3Process::closeAll() +{ + closeStdin(); + closeStdout(); + closeStderr(); + closePty(); +} + +///////////////////////////// +// protected slots // +///////////////////////////// + + + +void K3Process::slotChildOutput(int fdno) +{ + if (!childOutput(fdno)) + closeStdout(); +} + + +void K3Process::slotChildError(int fdno) +{ + if (!childError(fdno)) + closeStderr(); +} + + +void K3Process::slotSendData(int) +{ + if (input_sent == input_total) { + innot->setEnabled(false); + input_data = 0; + emit wroteStdin(this); + } else { + int result = ::write(in[1], input_data+input_sent, input_total-input_sent); + if (result >= 0) + { + input_sent += result; + } + else if ((errno != EAGAIN) && (errno != EINTR)) + { + qDebug() << "Error writing to stdin of child process" << endl; + closeStdin(); + } + } +} + +void K3Process::setUseShell(bool useShell, const char *shell) +{ + d->useShell = useShell; + if (shell && *shell) + d->shell = shell; + else +// #ifdef NON_FREE // ... as they ship non-POSIX /bin/sh +#if !defined(__linux__) && !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && !defined(__GNU__) && !defined(__DragonFly__) + // Solaris POSIX ... + if (!access( "/usr/xpg4/bin/sh", X_OK )) + d->shell = "/usr/xpg4/bin/sh"; + else + // ... which links here anyway + if (!access( "/bin/ksh", X_OK )) + d->shell = "/bin/ksh"; + else + // dunno, maybe superfluous? + if (!access( "/usr/ucb/sh", X_OK )) + d->shell = "/usr/ucb/sh"; + else +#endif + d->shell = "/bin/sh"; +} + +void K3Process::setUsePty(Communication usePty, bool addUtmp) +{ + d->usePty = usePty; + d->addUtmp = addUtmp; + if (usePty) { + if (!d->pty) + d->pty = new KPty; + } else { + delete d->pty; + d->pty = 0; + } +} + +KPty *K3Process::pty() const +{ + return d->pty; +} + +QString K3Process::quote(const QString &arg) +{ + QChar q('\''); + return QString(arg).replace(q, "'\\''").prepend(q).append(q); +} + + +////////////////////////////// +// private member functions // +////////////////////////////// + + +void K3Process::processHasExited(int state) +{ + // only successfully run NotifyOnExit processes ever get here + + status = state; + runs = false; // do this before commClose, so it knows we're dead + + commClose(); // cleanup communication sockets + + if (run_mode != DontCare) + emit processExited(this); +} + + + +int K3Process::childOutput(int fdno) +{ + if (communication & NoRead) { + int len = -1; + emit receivedStdout(fdno, len); + errno = 0; // Make sure errno doesn't read "EAGAIN" + return len; + } + else + { + char buffer[1025]; + int len; + + len = ::read(fdno, buffer, 1024); + + if (len > 0) { + buffer[len] = 0; // Just in case. + emit receivedStdout(this, buffer, len); + } + return len; + } +} + +int K3Process::childError(int fdno) +{ + char buffer[1025]; + int len; + + len = ::read(fdno, buffer, 1024); + + if (len > 0) { + buffer[len] = 0; // Just in case. + emit receivedStderr(this, buffer, len); + } + return len; +} + + +int K3Process::setupCommunication(Communication comm) +{ + // PTY stuff // + if (d->usePty) + { + // cannot communicate on both stderr and stdout if they are both on the pty + if (!(~(comm & d->usePty) & (Stdout | Stderr))) { + qWarning() << "Invalid usePty/communication combination (" << d->usePty << "/" << comm << ")" << endl; + return 0; + } + if (!d->pty->open()) + return 0; + + int rcomm = comm & d->usePty; + int mfd = d->pty->masterFd(); + if (rcomm & Stdin) + in[1] = mfd; + if (rcomm & Stdout) + out[0] = mfd; + if (rcomm & Stderr) + err[0] = mfd; + } + + communication = comm; + + comm = comm & ~d->usePty; + if (comm & Stdin) { + if (socketpair(AF_UNIX, SOCK_STREAM, 0, in)) + goto fail0; + fcntl(in[0], F_SETFD, FD_CLOEXEC); + fcntl(in[1], F_SETFD, FD_CLOEXEC); + } + if (comm & Stdout) { + if (socketpair(AF_UNIX, SOCK_STREAM, 0, out)) + goto fail1; + fcntl(out[0], F_SETFD, FD_CLOEXEC); + fcntl(out[1], F_SETFD, FD_CLOEXEC); + } + if (comm & Stderr) { + if (socketpair(AF_UNIX, SOCK_STREAM, 0, err)) + goto fail2; + fcntl(err[0], F_SETFD, FD_CLOEXEC); + fcntl(err[1], F_SETFD, FD_CLOEXEC); + } + return 1; // Ok + fail2: + if (comm & Stdout) + { + close(out[0]); + close(out[1]); + out[0] = out[1] = -1; + } + fail1: + if (comm & Stdin) + { + close(in[0]); + close(in[1]); + in[0] = in[1] = -1; + } + fail0: + communication = NoCommunication; + return 0; // Error +} + + + +int K3Process::commSetupDoneP() +{ + int rcomm = communication & ~d->usePty; + if (rcomm & Stdin) + close(in[0]); + if (rcomm & Stdout) + close(out[1]); + if (rcomm & Stderr) + close(err[1]); + in[0] = out[1] = err[1] = -1; + + // Don't create socket notifiers if no interactive comm is to be expected + if (run_mode != NotifyOnExit && run_mode != OwnGroup) + return 1; + + if (communication & Stdin) { + fcntl(in[1], F_SETFL, O_NONBLOCK | fcntl(in[1], F_GETFL)); + innot = new QSocketNotifier(in[1], QSocketNotifier::Write, this); + Q_CHECK_PTR(innot); + innot->setEnabled(false); // will be enabled when data has to be sent + QObject::connect(innot, SIGNAL(activated(int)), + this, SLOT(slotSendData(int))); + } + + if (communication & Stdout) { + outnot = new QSocketNotifier(out[0], QSocketNotifier::Read, this); + Q_CHECK_PTR(outnot); + QObject::connect(outnot, SIGNAL(activated(int)), + this, SLOT(slotChildOutput(int))); + if (communication & NoRead) + suspend(); + } + + if (communication & Stderr) { + errnot = new QSocketNotifier(err[0], QSocketNotifier::Read, this ); + Q_CHECK_PTR(errnot); + QObject::connect(errnot, SIGNAL(activated(int)), + this, SLOT(slotChildError(int))); + } + + return 1; +} + + + +int K3Process::commSetupDoneC() +{ + int ok = 1; + if (d->usePty & Stdin) { + if (dup2(d->pty->slaveFd(), STDIN_FILENO) < 0) ok = 0; + } else if (communication & Stdin) { + if (dup2(in[0], STDIN_FILENO) < 0) ok = 0; + } else { + int null_fd = open( "/dev/null", O_RDONLY ); + if (dup2( null_fd, STDIN_FILENO ) < 0) ok = 0; + close( null_fd ); + } + struct linger so; + memset(&so, 0, sizeof(so)); + if (d->usePty & Stdout) { + if (dup2(d->pty->slaveFd(), STDOUT_FILENO) < 0) ok = 0; + } else if (communication & Stdout) { + if (dup2(out[1], STDOUT_FILENO) < 0 || + setsockopt(out[1], SOL_SOCKET, SO_LINGER, (char *)&so, sizeof(so))) + ok = 0; + if (communication & MergedStderr) { + if (dup2(out[1], STDERR_FILENO) < 0) + ok = 0; + } + } + if (d->usePty & Stderr) { + if (dup2(d->pty->slaveFd(), STDERR_FILENO) < 0) ok = 0; + } else if (communication & Stderr) { + if (dup2(err[1], STDERR_FILENO) < 0 || + setsockopt(err[1], SOL_SOCKET, SO_LINGER, (char *)&so, sizeof(so))) + ok = 0; + } + + // don't even think about closing all open fds here or anywhere else + + // PTY stuff // + if (d->usePty) { + d->pty->setCTty(); + if (d->addUtmp) + d->pty->login(getenv("USER"), getenv("DISPLAY")); + } + + return ok; +} + + + +void K3Process::commClose() +{ + closeStdin(); + + if (pid_) { // detached, failed, and killed processes have no output. basta. :) + // If both channels are being read we need to make sure that one socket + // buffer doesn't fill up whilst we are waiting for data on the other + // (causing a deadlock). Hence we need to use select. + + int notfd = K3ProcessController::instance()->notifierFd(); + + while ((communication & (Stdout | Stderr)) || runs) { + fd_set rfds; + FD_ZERO(&rfds); + struct timeval timeout, *p_timeout; + + int max_fd = 0; + if (communication & Stdout) { + FD_SET(out[0], &rfds); + max_fd = out[0]; + } + if (communication & Stderr) { + FD_SET(err[0], &rfds); + if (err[0] > max_fd) + max_fd = err[0]; + } + if (runs) { + FD_SET(notfd, &rfds); + if (notfd > max_fd) + max_fd = notfd; + // If the process is still running we block until we + // receive data or the process exits. + p_timeout = 0; // no timeout + } else { + // If the process has already exited, we only check + // the available data, we don't wait for more. + timeout.tv_sec = timeout.tv_usec = 0; // timeout immediately + p_timeout = &timeout; + } + + int fds_ready = select(max_fd+1, &rfds, 0, 0, p_timeout); + if (fds_ready < 0) { + if (errno == EINTR) + continue; + break; + } else if (!fds_ready) + break; + + if ((communication & Stdout) && FD_ISSET(out[0], &rfds)) + slotChildOutput(out[0]); + + if ((communication & Stderr) && FD_ISSET(err[0], &rfds)) + slotChildError(err[0]); + + if (runs && FD_ISSET(notfd, &rfds)) { + runs = false; // hack: signal potential exit + return; // don't close anything, we will be called again + } + } + } + + closeStdout(); + closeStderr(); + + closePty(); +} + + + +/////////////////////////// +// CC: Class K3ShellProcess +/////////////////////////// + +K3ShellProcess::K3ShellProcess(const char *shellname): + K3Process(), d(0) +{ + setUseShell( true, shellname ? shellname : getenv("SHELL") ); +} + +K3ShellProcess::~K3ShellProcess() { +} + +QString K3ShellProcess::quote(const QString &arg) +{ + return K3Process::quote(arg); +} + +bool K3ShellProcess::start(RunMode runmode, Communication comm) +{ + return K3Process::start(runmode, comm); +} + + +//#include "moc_k3process.cpp" diff --git a/client/browser/qtermwidget/includes/k3process.h b/client/browser/qtermwidget/src/k3process.h index f8388eac..f8388eac 100644 --- a/client/browser/qtermwidget/includes/k3process.h +++ b/client/browser/qtermwidget/src/k3process.h diff --git a/client/browser/qtermwidget/src/k3processcontroller.cpp b/client/browser/qtermwidget/src/k3processcontroller.cpp new file mode 100644 index 00000000..9e41091d --- /dev/null +++ b/client/browser/qtermwidget/src/k3processcontroller.cpp @@ -0,0 +1,336 @@ +/* This file is part of the KDE libraries + Copyright (C) 1997 Christian Czezakte (e9025461@student.tuwien.ac.at) + + 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 + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include "k3processcontroller.h" +#include "k3processcontroller.moc" +#include "k3process.h" + +//#include <config.h> + +#include <sys/time.h> +#include <sys/types.h> +#include <sys/wait.h> +#include <unistd.h> +#include <errno.h> +#include <fcntl.h> +#include <stdio.h> +#include <stdlib.h> + +#include <QtCore/QSocketNotifier> + + +class K3ProcessController::Private +{ +public: + Private() + : needcheck( false ), + notifier( 0 ) + { + } + + ~Private() + { + delete notifier; + } + + int fd[2]; + bool needcheck; + QSocketNotifier *notifier; + QList<K3Process*> kProcessList; + QList<int> unixProcessList; + static struct sigaction oldChildHandlerData; + static bool handlerSet; + static int refCount; + static K3ProcessController* instance; +}; + +K3ProcessController *K3ProcessController::Private::instance = 0; +int K3ProcessController::Private::refCount = 0; + +void K3ProcessController::ref() +{ + if ( !Private::refCount ) { + Private::instance = new K3ProcessController; + setupHandlers(); + } + Private::refCount++; +} + +void K3ProcessController::deref() +{ + Private::refCount--; + if( !Private::refCount ) { + resetHandlers(); + delete Private::instance; + Private::instance = 0; + } +} + +K3ProcessController* K3ProcessController::instance() +{ + /* + * there were no safety guards in previous revisions, is that ok? + if ( !Private::instance ) { + ref(); + } + */ + + return Private::instance; +} + +K3ProcessController::K3ProcessController() + : d( new Private ) +{ + if( pipe( d->fd ) ) + { + perror( "pipe" ); + abort(); + } + + fcntl( d->fd[0], F_SETFL, O_NONBLOCK ); // in case slotDoHousekeeping is called without polling first + fcntl( d->fd[1], F_SETFL, O_NONBLOCK ); // in case it fills up + fcntl( d->fd[0], F_SETFD, FD_CLOEXEC ); + fcntl( d->fd[1], F_SETFD, FD_CLOEXEC ); + + d->notifier = new QSocketNotifier( d->fd[0], QSocketNotifier::Read ); + d->notifier->setEnabled( true ); + QObject::connect( d->notifier, SIGNAL(activated(int)), + SLOT(slotDoHousekeeping())); +} + +K3ProcessController::~K3ProcessController() +{ +#ifndef Q_OS_MAC +/* not sure why, but this is causing lockups */ + close( d->fd[0] ); + close( d->fd[1] ); +#else +#warning FIXME: why does close() freeze up destruction? +#endif + + delete d; +} + + +extern "C" { +static void theReaper( int num ) +{ + K3ProcessController::theSigCHLDHandler( num ); +} +} + +#ifdef Q_OS_UNIX +struct sigaction K3ProcessController::Private::oldChildHandlerData; +#endif +bool K3ProcessController::Private::handlerSet = false; + +void K3ProcessController::setupHandlers() +{ + if( Private::handlerSet ) + return; + Private::handlerSet = true; + +#ifdef Q_OS_UNIX + struct sigaction act; + sigemptyset( &act.sa_mask ); + + act.sa_handler = SIG_IGN; + act.sa_flags = 0; + sigaction( SIGPIPE, &act, 0L ); + + act.sa_handler = theReaper; + act.sa_flags = SA_NOCLDSTOP; + // CC: take care of SunOS which automatically restarts interrupted system + // calls (and thus does not have SA_RESTART) +#ifdef SA_RESTART + act.sa_flags |= SA_RESTART; +#endif + sigaction( SIGCHLD, &act, &Private::oldChildHandlerData ); + + sigaddset( &act.sa_mask, SIGCHLD ); + // Make sure we don't block this signal. gdb tends to do that :-( + sigprocmask( SIG_UNBLOCK, &act.sa_mask, 0 ); +#else + //TODO: win32 +#endif +} + +void K3ProcessController::resetHandlers() +{ + if( !Private::handlerSet ) + return; + Private::handlerSet = false; + +#ifdef Q_OS_UNIX + sigset_t mask, omask; + sigemptyset( &mask ); + sigaddset( &mask, SIGCHLD ); + sigprocmask( SIG_BLOCK, &mask, &omask ); + + struct sigaction act; + sigaction( SIGCHLD, &Private::oldChildHandlerData, &act ); + if (act.sa_handler != theReaper) { + sigaction( SIGCHLD, &act, 0 ); + Private::handlerSet = true; + } + + sigprocmask( SIG_SETMASK, &omask, 0 ); +#else + //TODO: win32 +#endif + // there should be no problem with SIGPIPE staying SIG_IGN +} + +// the pipe is needed to sync the child reaping with our event processing, +// as otherwise there are race conditions, locking requirements, and things +// generally get harder +void K3ProcessController::theSigCHLDHandler( int arg ) +{ + int saved_errno = errno; + + char dummy = 0; + ::write( instance()->d->fd[1], &dummy, 1 ); + +#ifdef Q_OS_UNIX + if ( Private::oldChildHandlerData.sa_handler != SIG_IGN && + Private::oldChildHandlerData.sa_handler != SIG_DFL ) { + Private::oldChildHandlerData.sa_handler( arg ); // call the old handler + } +#else + //TODO: win32 +#endif + + errno = saved_errno; +} + +int K3ProcessController::notifierFd() const +{ + return d->fd[0]; +} + +void K3ProcessController::unscheduleCheck() +{ + char dummy[16]; // somewhat bigger - just in case several have queued up + if( ::read( d->fd[0], dummy, sizeof(dummy) ) > 0 ) + d->needcheck = true; +} + +void +K3ProcessController::rescheduleCheck() +{ + if( d->needcheck ) + { + d->needcheck = false; + char dummy = 0; + ::write( d->fd[1], &dummy, 1 ); + } +} + +void K3ProcessController::slotDoHousekeeping() +{ + char dummy[16]; // somewhat bigger - just in case several have queued up + ::read( d->fd[0], dummy, sizeof(dummy) ); + + int status; + again: + QList<K3Process*>::iterator it( d->kProcessList.begin() ); + QList<K3Process*>::iterator eit( d->kProcessList.end() ); + while( it != eit ) + { + K3Process *prc = *it; + if( prc->runs && waitpid( prc->pid_, &status, WNOHANG ) > 0 ) + { + prc->processHasExited( status ); + // the callback can nuke the whole process list and even 'this' + if (!instance()) + return; + goto again; + } + ++it; + } + QList<int>::iterator uit( d->unixProcessList.begin() ); + QList<int>::iterator ueit( d->unixProcessList.end() ); + while( uit != ueit ) + { + if( waitpid( *uit, 0, WNOHANG ) > 0 ) + { + uit = d->unixProcessList.erase( uit ); + deref(); // counterpart to addProcess, can invalidate 'this' + } else + ++uit; + } +} + +bool K3ProcessController::waitForProcessExit( int timeout ) +{ +#ifdef Q_OS_UNIX + for(;;) + { + struct timeval tv, *tvp; + if (timeout < 0) + tvp = 0; + else + { + tv.tv_sec = timeout; + tv.tv_usec = 0; + tvp = &tv; + } + + fd_set fds; + FD_ZERO( &fds ); + FD_SET( d->fd[0], &fds ); + + switch( select( d->fd[0]+1, &fds, 0, 0, tvp ) ) + { + case -1: + if( errno == EINTR ) + continue; + // fall through; should never happen + case 0: + return false; + default: + slotDoHousekeeping(); + return true; + } + } +#else + //TODO: win32 + return false; +#endif +} + +void K3ProcessController::addKProcess( K3Process* p ) +{ + d->kProcessList.append( p ); +} + +void K3ProcessController::removeKProcess( K3Process* p ) +{ + d->kProcessList.removeAll( p ); +} + +void K3ProcessController::addProcess( int pid ) +{ + d->unixProcessList.append( pid ); + ref(); // make sure we stay around when the K3Process goes away +} + +//#include "moc_k3processcontroller.cpp" diff --git a/client/browser/qtermwidget/includes/k3processcontroller.h b/client/browser/qtermwidget/src/k3processcontroller.h index c077af21..c077af21 100644 --- a/client/browser/qtermwidget/includes/k3processcontroller.h +++ b/client/browser/qtermwidget/src/k3processcontroller.h diff --git a/client/browser/qtermwidget/src/kb-layouts/CVS/Entries b/client/browser/qtermwidget/src/kb-layouts/CVS/Entries new file mode 100644 index 00000000..1595129e --- /dev/null +++ b/client/browser/qtermwidget/src/kb-layouts/CVS/Entries @@ -0,0 +1,4 @@ +/default.keytab/1.1.1.1/Sat May 10 21:27:57 2008// +/linux.keytab/1.1.1.1/Sat May 10 21:27:57 2008// +/vt420pc.keytab/1.1.1.1/Sat May 10 21:27:57 2008// +D diff --git a/client/browser/qtermwidget/src/kb-layouts/CVS/Repository b/client/browser/qtermwidget/src/kb-layouts/CVS/Repository new file mode 100644 index 00000000..f49cd956 --- /dev/null +++ b/client/browser/qtermwidget/src/kb-layouts/CVS/Repository @@ -0,0 +1 @@ +qtermwidget/lib/kb-layouts diff --git a/client/browser/qtermwidget/src/kb-layouts/CVS/Root b/client/browser/qtermwidget/src/kb-layouts/CVS/Root new file mode 100644 index 00000000..41f2928f --- /dev/null +++ b/client/browser/qtermwidget/src/kb-layouts/CVS/Root @@ -0,0 +1 @@ +:ext:e_k@qtermwidget.cvs.sourceforge.net:/cvsroot/qtermwidget diff --git a/client/browser/qtermwidget/src/kb-layouts/default.keytab b/client/browser/qtermwidget/src/kb-layouts/default.keytab new file mode 100644 index 00000000..76362cd6 --- /dev/null +++ b/client/browser/qtermwidget/src/kb-layouts/default.keytab @@ -0,0 +1,133 @@ +# [README.default.Keytab] Buildin Keyboard Table +# +# To customize your keyboard, copy this file to something +# ending with .keytab and change it to meet you needs. +# Please read the README.KeyTab and the README.keyboard +# in this case. +# +# -------------------------------------------------------------- + +keyboard "Default (XFree 4)" + +# -------------------------------------------------------------- +# +# Note that this particular table is a "risc" version made to +# ease customization without bothering with obsolete details. +# See VT100.keytab for the more hairy stuff. +# +# -------------------------------------------------------------- + +# common keys + +key Escape : "\E" + +key Tab -Shift : "\t" +key Tab +Shift+Ansi : "\E[Z" +key Tab +Shift-Ansi : "\t" +key Backtab +Ansi : "\E[Z" +key Backtab -Ansi : "\t" + +key Return-Shift-NewLine : "\r" +key Return-Shift+NewLine : "\r\n" + +key Return+Shift : "\EOM" + +# Backspace and Delete codes are preserving CTRL-H. + +key Backspace : "\x7f" + +# Arrow keys in VT52 mode +# shift up/down are reserved for scrolling. +# shift left/right are reserved for switching between tabs (this is hardcoded). + +key Up -Shift-Ansi : "\EA" +key Down -Shift-Ansi : "\EB" +key Right-Shift-Ansi : "\EC" +key Left -Shift-Ansi : "\ED" + +# Arrow keys in ANSI mode with Application - and Normal Cursor Mode) + +key Up -Shift-AnyMod+Ansi+AppCuKeys : "\EOA" +key Down -Shift-AnyMod+Ansi+AppCuKeys : "\EOB" +key Right -Shift-AnyMod+Ansi+AppCuKeys : "\EOC" +key Left -Shift-AnyMod+Ansi+AppCuKeys : "\EOD" + +key Up -Shift-AnyMod+Ansi-AppCuKeys : "\E[A" +key Down -Shift-AnyMod+Ansi-AppCuKeys : "\E[B" +key Right -Shift-AnyMod+Ansi-AppCuKeys : "\E[C" +key Left -Shift-AnyMod+Ansi-AppCuKeys : "\E[D" + +key Up -Shift+AnyMod+Ansi : "\E[1;*A" +key Down -Shift+AnyMod+Ansi : "\E[1;*B" +key Right -Shift+AnyMod+Ansi : "\E[1;*C" +key Left -Shift+AnyMod+Ansi : "\E[1;*D" + +# other grey PC keys + +key Enter+NewLine : "\r\n" +key Enter-NewLine : "\r" + +key Home -AnyMod -AppCuKeys : "\E[H" +key End -AnyMod -AppCuKeys : "\E[F" +key Home -AnyMod +AppCuKeys : "\EOH" +key End -AnyMod +AppCuKeys : "\EOF" +key Home +AnyMod : "\E[1;*H" +key End +AnyMod : "\E[1;*F" + +key Insert -AnyMod : "\E[2~" +key Delete -AnyMod : "\E[3~" +key Insert +AnyMod : "\E[2;*~" +key Delete +AnyMod : "\E[3;*~" + +key Prior -Shift-AnyMod : "\E[5~" +key Next -Shift-AnyMod : "\E[6~" +key Prior -Shift+AnyMod : "\E[5;*~" +key Next -Shift+AnyMod : "\E[6;*~" + +# Function keys +key F1 -AnyMod : "\EOP" +key F2 -AnyMod : "\EOQ" +key F3 -AnyMod : "\EOR" +key F4 -AnyMod : "\EOS" +key F5 -AnyMod : "\E[15~" +key F6 -AnyMod : "\E[17~" +key F7 -AnyMod : "\E[18~" +key F8 -AnyMod : "\E[19~" +key F9 -AnyMod : "\E[20~" +key F10 -AnyMod : "\E[21~" +key F11 -AnyMod : "\E[23~" +key F12 -AnyMod : "\E[24~" + +key F1 +AnyMod : "\EO*P" +key F2 +AnyMod : "\EO*Q" +key F3 +AnyMod : "\EO*R" +key F4 +AnyMod : "\EO*S" +key F5 +AnyMod : "\E[15;*~" +key F6 +AnyMod : "\E[17;*~" +key F7 +AnyMod : "\E[18;*~" +key F8 +AnyMod : "\E[19;*~" +key F9 +AnyMod : "\E[20;*~" +key F10 +AnyMod : "\E[21;*~" +key F11 +AnyMod : "\E[23;*~" +key F12 +AnyMod : "\E[24;*~" + +# Work around dead keys + +key Space +Control : "\x00" + +# Some keys are used by konsole to cause operations. +# The scroll* operations refer to the history buffer. + +key Up +Shift-AppScreen : scrollLineUp +key Prior +Shift-AppScreen : scrollPageUp +key Down +Shift-AppScreen : scrollLineDown +key Next +Shift-AppScreen : scrollPageDown + +#key Up +Shift : scrollLineUp +#key Prior +Shift : scrollPageUp +#key Down +Shift : scrollLineDown +#key Next +Shift : scrollPageDown + +key ScrollLock : scrollLock + +# keypad characters are not offered differently by Qt. diff --git a/client/browser/qtermwidget/src/kb-layouts/linux.keytab b/client/browser/qtermwidget/src/kb-layouts/linux.keytab new file mode 100644 index 00000000..c0fe4446 --- /dev/null +++ b/client/browser/qtermwidget/src/kb-layouts/linux.keytab @@ -0,0 +1,133 @@ +# [linux.keytab] Konsole Keyboard Table (Linux console keys) +# +# -------------------------------------------------------------- + +# NOT TESTED, MAY NEED SOME CLEANUPS +keyboard "Linux console" + +# -------------------------------------------------------------- +# +# This configuration table allows to customize the +# meaning of the keys. +# +# The syntax is that each entry has the form : +# +# "key" Keyname { ("+"|"-") Modename } ":" (String|Operation) +# +# Keynames are those defined in <qnamespace.h> with the +# "Qt::Key_" removed. (We'd better insert the list here) +# +# Mode names are : +# +# - Shift +# - Alt +# - Control +# +# The VT100 emulation has two modes that can affect the +# sequences emitted by certain keys. These modes are +# under control of the client program. +# +# - Newline : effects Return and Enter key. +# - Application : effects Up and Down key. +# +# - Ansi : effects Up and Down key (This is for VT52, really). +# +# Operations are +# +# - scrollUpLine +# - scrollUpPage +# - scrollDownLine +# - scrollDownPage +# +# - emitSelection +# +# If the key is not found here, the text of the +# key event as provided by QT is emitted, possibly +# preceeded by ESC if the Alt key is pressed. +# +# -------------------------------------------------------------- + +key Escape : "\E" +key Tab : "\t" + +# VT100 can add an extra \n after return. +# The NewLine mode is set by an escape sequence. + +key Return-NewLine : "\r" +key Return+NewLine : "\r\n" + +# Some desperately try to save the ^H. + +key Backspace : "\x7f" +key Delete : "\E[3~" + +# These codes are for the VT52 mode of VT100 +# The Ansi mode (i.e. VT100 mode) is set by +# an escape sequence + +key Up -Shift-Ansi : "\EA" +key Down -Shift-Ansi : "\EB" +key Right-Shift-Ansi : "\EC" +key Left -Shift-Ansi : "\ED" + +# VT100 emits a mode bit together +# with the arrow keys.The AppCuKeys +# mode is set by an escape sequence. + +key Up -Shift+Ansi+AppCuKeys : "\EOA" +key Down -Shift+Ansi+AppCuKeys : "\EOB" +key Right-Shift+Ansi+AppCuKeys : "\EOC" +key Left -Shift+Ansi+AppCuKeys : "\EOD" + +key Up -Shift+Ansi-AppCuKeys : "\E[A" +key Down -Shift+Ansi-AppCuKeys : "\E[B" +key Right-Shift+Ansi-AppCuKeys : "\E[C" +key Left -Shift+Ansi-AppCuKeys : "\E[D" + +# linux functions keys F1-F5 differ from xterm + +key F1 : "\E[[A" +key F2 : "\E[[B" +key F3 : "\E[[C" +key F4 : "\E[[D" +key F5 : "\E[[E" + +key F6 : "\E[17~" +key F7 : "\E[18~" +key F8 : "\E[19~" +key F9 : "\E[20~" +key F10 : "\E[21~" +key F11 : "\E[23~" +key F12 : "\E[24~" + +key Home : "\E[1~" +key End : "\E[4~" + +key Prior -Shift : "\E[5~" +key Next -Shift : "\E[6~" +key Insert-Shift : "\E[2~" + +# Keypad-Enter. See comment on Return above. + +key Enter+NewLine : "\r\n" +key Enter-NewLine : "\r" + +key Space +Control : "\x00" + +# some of keys are used by konsole. + +key Up +Shift : scrollLineUp +key Prior +Shift : scrollPageUp +key Down +Shift : scrollLineDown +key Next +Shift : scrollPageDown + +key ScrollLock : scrollLock + +#---------------------------------------------------------- + +# keypad characters as offered by Qt +# cannot be recognized as such. + +#---------------------------------------------------------- + +# Following other strings as emitted by konsole. diff --git a/client/browser/qtermwidget/src/kb-layouts/vt420pc.keytab b/client/browser/qtermwidget/src/kb-layouts/vt420pc.keytab new file mode 100644 index 00000000..2b7102f2 --- /dev/null +++ b/client/browser/qtermwidget/src/kb-layouts/vt420pc.keytab @@ -0,0 +1,163 @@ +# [vt420pc.keytab] Konsole Keyboard Table (VT420pc keys) +# adapted by ferdinand gassauer f.gassauer@aon.at +# Nov 2000 +# +################################################################ +# +# The escape sequences emmited by the +# keys Shift+F1 to Shift+F12 might not fit your needs +# +################# IMPORTANT NOTICE ############################# +# the key bindings (Kcontrol -> look and feel -> keybindgs) +# overrule the settings in this file. The key bindings might be +# changed by the user WITHOUT notification of the maintainer of +# the keytab file. Konsole will not work as expected by +# the maintainer of the keytab file. +################################################################ +# +# -------------------------------------------------------------- + +keyboard "DEC VT420 Terminal" + +# -------------------------------------------------------------- +# +# This configuration table allows to customize the +# meaning of the keys. +# +# The syntax is that each entry has the form : +# +# "key" Keyname { ("+"|"-") Modename } ":" (String|Operation) +# +# Keynames are those defined in <qnamespace.h> with the +# "Qt::Key_" removed. (We'd better insert the list here) +# +# Mode names are : +# +# - Shift +# - Alt +# - Control +# +# The VT100 emulation has two modes that can affect the +# sequences emitted by certain keys. These modes are +# under control of the client program. +# +# - Newline : effects Return and Enter key. +# - Application : effects Up and Down key. +# +# - Ansi : effects Up and Down key (This is for VT52, really). +# +# Operations are +# +# - scrollUpLine +# - scrollUpPage +# - scrollDownLine +# - scrollDownPage +# +# - emitSelection +# +# If the key is not found here, the text of the +# key event as provided by QT is emitted, possibly +# preceeded by ESC if the Alt key is pressed. +# +# -------------------------------------------------------------- + +key Escape : "\E" +key Tab : "\t" +key Backtab: "\E[Z" + +# VT100 can add an extra \n after return. +# The NewLine mode is set by an escape sequence. + +key Return-NewLine : "\r" +key Return+NewLine : "\r\n" + +# Some desperately try to save the ^H. +# may be not everyone wants this + +key Backspace : "\x08" # Control H +key Delete : "\x7f" + +# These codes are for the VT420pc +# The Ansi mode (i.e. VT100 mode) is set by +# an escape sequence + +key Up -Shift-Ansi : "\EA" +key Down -Shift-Ansi : "\EB" +key Right-Shift-Ansi : "\EC" +key Left -Shift-Ansi : "\ED" + +# VT100 emits a mode bit together +# with the arrow keys.The AppCuKeys +# mode is set by an escape sequence. + +key Up -Shift+Ansi+AppCuKeys : "\EOA" +key Down -Shift+Ansi+AppCuKeys : "\EOB" +key Right-Shift+Ansi+AppCuKeys : "\EOC" +key Left -Shift+Ansi+AppCuKeys : "\EOD" + +key Up -Shift+Ansi-AppCuKeys : "\E[A" +key Down -Shift+Ansi-AppCuKeys : "\E[B" +key Right-Shift+Ansi-AppCuKeys : "\E[C" +key Left -Shift+Ansi-AppCuKeys : "\E[D" + +# function keys + +key F1 -Shift : "\E[11~" +key F2 -Shift : "\E[12~" +key F3 -Shift : "\E[13~" +key F4 -Shift : "\E[14~" +key F5 -Shift : "\E[15~" +key F6 -Shift : "\E[17~" +key F7 -Shift : "\E[18~" +key F8 -Shift : "\E[19~" +key F9 -Shift : "\E[20~" +key F10-Shift : "\E[21~" +key F11-Shift : "\E[23~" +key F12-Shift : "\E[24~" +# +# Shift F1-F12 +# +key F1 +Shift : "\E[11;2~" +key F2 +Shift : "\E[12;2~" +key F3 +Shift : "\E[13;2~" +key F4 +Shift : "\E[14;2~" +key F5 +Shift : "\E[15;2~" +key F6 +Shift : "\E[17;2~" +key F7 +Shift : "\E[18;2~" +key F8 +Shift : "\E[19;2~" +key F9 +Shift : "\E[20;2~" +key F10+Shift : "\E[21;2~" +key F11+Shift : "\E[23;2~" +key F12+Shift : "\E[24;2~" + +key Home : "\E[H" +key End : "\E[F" + +key Prior -Shift : "\E[5~" +key Next -Shift : "\E[6~" +key Insert-Shift : "\E[2~" + +# Keypad-Enter. See comment on Return above. + +key Enter+NewLine : "\r\n" +key Enter-NewLine : "\r" + +key Space +Control : "\x00" + +# some of keys are used by konsole. + +key Up +Shift : scrollLineUp +key Prior +Shift : scrollPageUp +key Down +Shift : scrollLineDown +key Next +Shift : scrollPageDown + +key ScrollLock : scrollLock + +#---------------------------------------------------------- + +# keypad characters as offered by Qt +# cannot be recognized as such. + +#---------------------------------------------------------- + +# Following other strings as emitted by konsole. diff --git a/client/browser/qtermwidget/src/konsole_wcwidth.cpp b/client/browser/qtermwidget/src/konsole_wcwidth.cpp new file mode 100644 index 00000000..e4ef1178 --- /dev/null +++ b/client/browser/qtermwidget/src/konsole_wcwidth.cpp @@ -0,0 +1,216 @@ +/* $XFree86: xc/programs/xterm/wcwidth.character,v 1.3 2001/07/29 22:08:16 tsi Exp $ */ +/* + * This is an implementation of wcwidth() and wcswidth() as defined in + * "The Single UNIX Specification, Version 2, The Open Group, 1997" + * <http://www.UNIX-systems.org/online.html> + * + * Markus Kuhn -- 2001-01-12 -- public domain + */ + +#include "konsole_wcwidth.h" + +struct interval { + unsigned short first; + unsigned short last; +}; + +/* auxiliary function for binary search in interval table */ +static int bisearch(quint16 ucs, const struct interval *table, int max) { + int min = 0; + int mid; + + if (ucs < table[0].first || ucs > table[max].last) + return 0; + while (max >= min) { + mid = (min + max) / 2; + if (ucs > table[mid].last) + min = mid + 1; + else if (ucs < table[mid].first) + max = mid - 1; + else + return 1; + } + + return 0; +} + + +/* The following functions define the column width of an ISO 10646 + * character as follows: + * + * - The null character (U+0000) has a column width of 0. + * + * - Other C0/C1 control characters and DEL will lead to a return + * value of -1. + * + * - Non-spacing and enclosing combining characters (general + * category code Mn or Me in the Unicode database) have a + * column width of 0. + * + * - Other format characters (general category code Cf in the Unicode + * database) and ZERO WIDTH SPACE (U+200B) have a column width of 0. + * + * - Hangul Jamo medial vowels and final consonants (U+1160-U+11FF) + * have a column width of 0. + * + * - Spacing characters in the East Asian Wide (W) or East Asian + * FullWidth (F) category as defined in Unicode Technical + * Report #11 have a column width of 2. + * + * - All remaining characters (including all printable + * ISO 8859-1 and WGL4 characters, Unicode control characters, + * etc.) have a column width of 1. + * + * This implementation assumes that quint16 characters are encoded + * in ISO 10646. + */ + +int konsole_wcwidth(quint16 ucs) +{ + /* sorted list of non-overlapping intervals of non-spacing characters */ + static const struct interval combining[] = { + { 0x0300, 0x034E }, { 0x0360, 0x0362 }, { 0x0483, 0x0486 }, + { 0x0488, 0x0489 }, { 0x0591, 0x05A1 }, { 0x05A3, 0x05B9 }, + { 0x05BB, 0x05BD }, { 0x05BF, 0x05BF }, { 0x05C1, 0x05C2 }, + { 0x05C4, 0x05C4 }, { 0x064B, 0x0655 }, { 0x0670, 0x0670 }, + { 0x06D6, 0x06E4 }, { 0x06E7, 0x06E8 }, { 0x06EA, 0x06ED }, + { 0x070F, 0x070F }, { 0x0711, 0x0711 }, { 0x0730, 0x074A }, + { 0x07A6, 0x07B0 }, { 0x0901, 0x0902 }, { 0x093C, 0x093C }, + { 0x0941, 0x0948 }, { 0x094D, 0x094D }, { 0x0951, 0x0954 }, + { 0x0962, 0x0963 }, { 0x0981, 0x0981 }, { 0x09BC, 0x09BC }, + { 0x09C1, 0x09C4 }, { 0x09CD, 0x09CD }, { 0x09E2, 0x09E3 }, + { 0x0A02, 0x0A02 }, { 0x0A3C, 0x0A3C }, { 0x0A41, 0x0A42 }, + { 0x0A47, 0x0A48 }, { 0x0A4B, 0x0A4D }, { 0x0A70, 0x0A71 }, + { 0x0A81, 0x0A82 }, { 0x0ABC, 0x0ABC }, { 0x0AC1, 0x0AC5 }, + { 0x0AC7, 0x0AC8 }, { 0x0ACD, 0x0ACD }, { 0x0B01, 0x0B01 }, + { 0x0B3C, 0x0B3C }, { 0x0B3F, 0x0B3F }, { 0x0B41, 0x0B43 }, + { 0x0B4D, 0x0B4D }, { 0x0B56, 0x0B56 }, { 0x0B82, 0x0B82 }, + { 0x0BC0, 0x0BC0 }, { 0x0BCD, 0x0BCD }, { 0x0C3E, 0x0C40 }, + { 0x0C46, 0x0C48 }, { 0x0C4A, 0x0C4D }, { 0x0C55, 0x0C56 }, + { 0x0CBF, 0x0CBF }, { 0x0CC6, 0x0CC6 }, { 0x0CCC, 0x0CCD }, + { 0x0D41, 0x0D43 }, { 0x0D4D, 0x0D4D }, { 0x0DCA, 0x0DCA }, + { 0x0DD2, 0x0DD4 }, { 0x0DD6, 0x0DD6 }, { 0x0E31, 0x0E31 }, + { 0x0E34, 0x0E3A }, { 0x0E47, 0x0E4E }, { 0x0EB1, 0x0EB1 }, + { 0x0EB4, 0x0EB9 }, { 0x0EBB, 0x0EBC }, { 0x0EC8, 0x0ECD }, + { 0x0F18, 0x0F19 }, { 0x0F35, 0x0F35 }, { 0x0F37, 0x0F37 }, + { 0x0F39, 0x0F39 }, { 0x0F71, 0x0F7E }, { 0x0F80, 0x0F84 }, + { 0x0F86, 0x0F87 }, { 0x0F90, 0x0F97 }, { 0x0F99, 0x0FBC }, + { 0x0FC6, 0x0FC6 }, { 0x102D, 0x1030 }, { 0x1032, 0x1032 }, + { 0x1036, 0x1037 }, { 0x1039, 0x1039 }, { 0x1058, 0x1059 }, + { 0x1160, 0x11FF }, { 0x17B7, 0x17BD }, { 0x17C6, 0x17C6 }, + { 0x17C9, 0x17D3 }, { 0x180B, 0x180E }, { 0x18A9, 0x18A9 }, + { 0x200B, 0x200F }, { 0x202A, 0x202E }, { 0x206A, 0x206F }, + { 0x20D0, 0x20E3 }, { 0x302A, 0x302F }, { 0x3099, 0x309A }, + { 0xFB1E, 0xFB1E }, { 0xFE20, 0xFE23 }, { 0xFEFF, 0xFEFF }, + { 0xFFF9, 0xFFFB } + }; + + /* test for 8-bit control characters */ + if (ucs == 0) + return 0; + if (ucs < 32 || (ucs >= 0x7f && ucs < 0xa0)) + return -1; + + /* binary search in table of non-spacing characters */ + if (bisearch(ucs, combining, + sizeof(combining) / sizeof(struct interval) - 1)) + return 0; + + /* if we arrive here, ucs is not a combining or C0/C1 control character */ + + return 1 + + (ucs >= 0x1100 && + (ucs <= 0x115f || /* Hangul Jamo init. consonants */ + (ucs >= 0x2e80 && ucs <= 0xa4cf && (ucs & ~0x0011) != 0x300a && + ucs != 0x303f) || /* CJK ... Yi */ + (ucs >= 0xac00 && ucs <= 0xd7a3) || /* Hangul Syllables */ + (ucs >= 0xf900 && ucs <= 0xfaff) || /* CJK Compatibility Ideographs */ + (ucs >= 0xfe30 && ucs <= 0xfe6f) || /* CJK Compatibility Forms */ + (ucs >= 0xff00 && ucs <= 0xff5f) || /* Fullwidth Forms */ + (ucs >= 0xffe0 && ucs <= 0xffe6) /* do not compare UINT16 with 0x20000 || + (ucs >= 0x20000 && ucs <= 0x2ffff) */)); +} + +#if 0 +/* + * The following function is the same as konsole_wcwidth(), except that + * spacing characters in the East Asian Ambiguous (A) category as + * defined in Unicode Technical Report #11 have a column width of 2. + * This experimental variant might be useful for users of CJK legacy + * encodings who want to migrate to UCS. It is not otherwise + * recommended for general use. + */ +int konsole_wcwidth_cjk(quint16 ucs) +{ + /* sorted list of non-overlapping intervals of East Asian Ambiguous + * characters */ + static const struct interval ambiguous[] = { + { 0x00A1, 0x00A1 }, { 0x00A4, 0x00A4 }, { 0x00A7, 0x00A8 }, + { 0x00AA, 0x00AA }, { 0x00AD, 0x00AD }, { 0x00B0, 0x00B4 }, + { 0x00B6, 0x00BA }, { 0x00BC, 0x00BF }, { 0x00C6, 0x00C6 }, + { 0x00D0, 0x00D0 }, { 0x00D7, 0x00D8 }, { 0x00DE, 0x00E1 }, + { 0x00E6, 0x00E6 }, { 0x00E8, 0x00EA }, { 0x00EC, 0x00ED }, + { 0x00F0, 0x00F0 }, { 0x00F2, 0x00F3 }, { 0x00F7, 0x00FA }, + { 0x00FC, 0x00FC }, { 0x00FE, 0x00FE }, { 0x0101, 0x0101 }, + { 0x0111, 0x0111 }, { 0x0113, 0x0113 }, { 0x011B, 0x011B }, + { 0x0126, 0x0127 }, { 0x012B, 0x012B }, { 0x0131, 0x0133 }, + { 0x0138, 0x0138 }, { 0x013F, 0x0142 }, { 0x0144, 0x0144 }, + { 0x0148, 0x014A }, { 0x014D, 0x014D }, { 0x0152, 0x0153 }, + { 0x0166, 0x0167 }, { 0x016B, 0x016B }, { 0x01CE, 0x01CE }, + { 0x01D0, 0x01D0 }, { 0x01D2, 0x01D2 }, { 0x01D4, 0x01D4 }, + { 0x01D6, 0x01D6 }, { 0x01D8, 0x01D8 }, { 0x01DA, 0x01DA }, + { 0x01DC, 0x01DC }, { 0x0251, 0x0251 }, { 0x0261, 0x0261 }, + { 0x02C7, 0x02C7 }, { 0x02C9, 0x02CB }, { 0x02CD, 0x02CD }, + { 0x02D0, 0x02D0 }, { 0x02D8, 0x02DB }, { 0x02DD, 0x02DD }, + { 0x0391, 0x03A1 }, { 0x03A3, 0x03A9 }, { 0x03B1, 0x03C1 }, + { 0x03C3, 0x03C9 }, { 0x0401, 0x0401 }, { 0x0410, 0x044F }, + { 0x0451, 0x0451 }, { 0x2010, 0x2010 }, { 0x2013, 0x2016 }, + { 0x2018, 0x2019 }, { 0x201C, 0x201D }, { 0x2020, 0x2021 }, + { 0x2025, 0x2027 }, { 0x2030, 0x2030 }, { 0x2032, 0x2033 }, + { 0x2035, 0x2035 }, { 0x203B, 0x203B }, { 0x2074, 0x2074 }, + { 0x207F, 0x207F }, { 0x2081, 0x2084 }, { 0x20AC, 0x20AC }, + { 0x2103, 0x2103 }, { 0x2105, 0x2105 }, { 0x2109, 0x2109 }, + { 0x2113, 0x2113 }, { 0x2121, 0x2122 }, { 0x2126, 0x2126 }, + { 0x212B, 0x212B }, { 0x2154, 0x2155 }, { 0x215B, 0x215B }, + { 0x215E, 0x215E }, { 0x2160, 0x216B }, { 0x2170, 0x2179 }, + { 0x2190, 0x2199 }, { 0x21D2, 0x21D2 }, { 0x21D4, 0x21D4 }, + { 0x2200, 0x2200 }, { 0x2202, 0x2203 }, { 0x2207, 0x2208 }, + { 0x220B, 0x220B }, { 0x220F, 0x220F }, { 0x2211, 0x2211 }, + { 0x2215, 0x2215 }, { 0x221A, 0x221A }, { 0x221D, 0x2220 }, + { 0x2223, 0x2223 }, { 0x2225, 0x2225 }, { 0x2227, 0x222C }, + { 0x222E, 0x222E }, { 0x2234, 0x2237 }, { 0x223C, 0x223D }, + { 0x2248, 0x2248 }, { 0x224C, 0x224C }, { 0x2252, 0x2252 }, + { 0x2260, 0x2261 }, { 0x2264, 0x2267 }, { 0x226A, 0x226B }, + { 0x226E, 0x226F }, { 0x2282, 0x2283 }, { 0x2286, 0x2287 }, + { 0x2295, 0x2295 }, { 0x2299, 0x2299 }, { 0x22A5, 0x22A5 }, + { 0x22BF, 0x22BF }, { 0x2312, 0x2312 }, { 0x2460, 0x24BF }, + { 0x24D0, 0x24E9 }, { 0x2500, 0x254B }, { 0x2550, 0x2574 }, + { 0x2580, 0x258F }, { 0x2592, 0x2595 }, { 0x25A0, 0x25A1 }, + { 0x25A3, 0x25A9 }, { 0x25B2, 0x25B3 }, { 0x25B6, 0x25B7 }, + { 0x25BC, 0x25BD }, { 0x25C0, 0x25C1 }, { 0x25C6, 0x25C8 }, + { 0x25CB, 0x25CB }, { 0x25CE, 0x25D1 }, { 0x25E2, 0x25E5 }, + { 0x25EF, 0x25EF }, { 0x2605, 0x2606 }, { 0x2609, 0x2609 }, + { 0x260E, 0x260F }, { 0x261C, 0x261C }, { 0x261E, 0x261E }, + { 0x2640, 0x2640 }, { 0x2642, 0x2642 }, { 0x2660, 0x2661 }, + { 0x2663, 0x2665 }, { 0x2667, 0x266A }, { 0x266C, 0x266D }, + { 0x266F, 0x266F }, { 0x300A, 0x300B }, { 0x301A, 0x301B }, + { 0xE000, 0xF8FF }, { 0xFFFD, 0xFFFD } + }; + + /* binary search in table of non-spacing characters */ + if (bisearch(ucs, ambiguous, + sizeof(ambiguous) / sizeof(struct interval) - 1)) + return 2; + + return konsole_wcwidth(ucs); +} +#endif + +// single byte char: +1, multi byte char: +2 +int string_width( const QString &txt ) +{ + int w = 0; + for ( int i = 0; i < txt.length(); ++i ) + w += konsole_wcwidth( txt[ i ].unicode() ); + return w; +} diff --git a/client/browser/qtermwidget/includes/konsole_wcwidth.h b/client/browser/qtermwidget/src/konsole_wcwidth.h index 6f4e46aa..6f4e46aa 100644 --- a/client/browser/qtermwidget/includes/konsole_wcwidth.h +++ b/client/browser/qtermwidget/src/konsole_wcwidth.h diff --git a/client/browser/qtermwidget/src/kpty.cpp b/client/browser/qtermwidget/src/kpty.cpp new file mode 100644 index 00000000..953b9565 --- /dev/null +++ b/client/browser/qtermwidget/src/kpty.cpp @@ -0,0 +1,624 @@ +/* + + 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 + + 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 "kpty_p.h" + +#ifdef __sgi +#define __svr4__ +#endif + +#ifdef __osf__ +#define _OSF_SOURCE +#include <float.h> +#endif + +#ifdef _AIX +#define _ALL_SOURCE +#endif + +// __USE_XOPEN isn't defined by default in ICC +// (needed for ptsname(), grantpt() and unlockpt()) +#ifdef __INTEL_COMPILER +# ifndef __USE_XOPEN +# define __USE_XOPEN +# endif +#endif + +#include <sys/types.h> +#include <sys/ioctl.h> +#include <sys/time.h> +#include <sys/resource.h> +#include <sys/stat.h> +#include <sys/param.h> + +#include <errno.h> +#include <fcntl.h> +#include <time.h> +#include <stdlib.h> +#include <stdio.h> +#include <string.h> +#include <unistd.h> +#include <grp.h> + +#if defined(HAVE_PTY_H) +# include <pty.h> +#endif + +#ifdef HAVE_LIBUTIL_H +# include <libutil.h> +#elif defined(HAVE_UTIL_H) +# include <util.h> +#endif + +#ifdef HAVE_UTEMPTER +extern "C" { +# include <utempter.h> +} +#else +# include <utmp.h> +# ifdef HAVE_UTMPX +# include <utmpx.h> +# endif +# if !defined(_PATH_UTMPX) && defined(_UTMPX_FILE) +# define _PATH_UTMPX _UTMPX_FILE +# endif +# if !defined(_PATH_WTMPX) && defined(_WTMPX_FILE) +# define _PATH_WTMPX _WTMPX_FILE +# endif +#endif + +/* for HP-UX (some versions) the extern C is needed, and for other + platforms it doesn't hurt */ +extern "C" { +#include <termios.h> +#if defined(HAVE_TERMIO_H) +# include <termio.h> // struct winsize on some systems +#endif +} + +#if defined (_HPUX_SOURCE) +# define _TERMIOS_INCLUDED +# include <bsdtty.h> +#endif + +#ifdef HAVE_SYS_STROPTS_H +# include <sys/stropts.h> // Defines I_PUSH +# define _NEW_TTY_CTRL +#endif + +#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__) +# define _tcgetattr(fd, ttmode) tcgetattr(fd, ttmode) +# else +# define _tcgetattr(fd, ttmode) ioctl(fd, TCGETS, (char *)ttmode) +# endif +#endif + +#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__) +# define _tcsetattr(fd, ttmode) tcsetattr(fd, TCSANOW, ttmode) +# else +# define _tcsetattr(fd, ttmode) ioctl(fd, TCSETS, (char *)ttmode) +# endif +#endif + +//#include <kdebug.h> +//#include <kstandarddirs.h> // findExe + +#include <QtCore> + +// not defined on HP-UX for example +#ifndef CTRL +# define CTRL(x) ((x) & 037) +#endif + +#define TTY_GROUP "tty" + +/////////////////////// +// private functions // +/////////////////////// + +////////////////// +// private data // +////////////////// + +KPtyPrivate::KPtyPrivate() : + masterFd(-1), slaveFd(-1) +{ +} + +bool KPtyPrivate::chownpty(bool) +{ +// return !QProcess::execute(KStandardDirs::findExe("kgrantpty"), +// QStringList() << (grant?"--grant":"--revoke") << QString::number(masterFd)); + return true; +} + +///////////////////////////// +// public member functions // +///////////////////////////// + +KPty::KPty() : + d_ptr(new KPtyPrivate) +{ + d_ptr->q_ptr = this; +} + +KPty::KPty(KPtyPrivate *d) : + d_ptr(d) +{ + d_ptr->q_ptr = this; +} + +KPty::~KPty() +{ + close(); + delete d_ptr; +} + +bool KPty::open() +{ + Q_D(KPty); + + if (d->masterFd >= 0) + return true; + + QByteArray ptyName; + + // Find a master pty that we can open //////////////////////////////// + + // Because not all the pty animals are created equal, they want to + // be opened by several different methods. + + // We try, as we know them, one by one. + +#ifdef HAVE_OPENPTY + + char ptsn[PATH_MAX]; + if (::openpty( &d->masterFd, &d->slaveFd, ptsn, 0, 0)) + { + d->masterFd = -1; + d->slaveFd = -1; + kWarning(175) << "Can't open a pseudo teletype"; + return false; + } + d->ttyName = ptsn; + +#else + +#ifdef HAVE__GETPTY // irix + + char *ptsn = _getpty(&d->masterFd, O_RDWR|O_NOCTTY, S_IRUSR|S_IWUSR, 0); + if (ptsn) { + d->ttyName = ptsn; + goto grantedpt; + } + +#elif defined(HAVE_PTSNAME) || defined(TIOCGPTN) + +#ifdef HAVE_POSIX_OPENPT + d->masterFd = ::posix_openpt(O_RDWR|O_NOCTTY); +#elif defined(HAVE_GETPT) + d->masterFd = ::getpt(); +#elif defined(PTM_DEVICE) + 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) { + d->ttyName = ptsn; +#else + int ptyno; + if (!ioctl(d->masterFd, TIOCGPTN, &ptyno)) { + d->ttyName = QByteArray("/dev/pts/") + QByteArray::number(ptyno); +#endif +#ifdef HAVE_GRANTPT + if (!grantpt(d->masterFd)) + goto grantedpt; +#else + + goto gotpty; +#endif + } + ::close(d->masterFd); + d->masterFd = -1; + } +#endif // HAVE_PTSNAME || TIOCGPTN + + // Linux device names, FIXME: Trouble on other systems? + for (const char* s3 = "pqrstuvwxyzabcde"; *s3; s3++) + { + for (const char* s4 = "0123456789abcdef"; *s4; s4++) + { + ptyName = QString().sprintf("/dev/pty%c%c", *s3, *s4).toAscii(); + d->ttyName = QString().sprintf("/dev/tty%c%c", *s3, *s4).toAscii(); + + d->masterFd = ::open(ptyName.data(), O_RDWR); + if (d->masterFd >= 0) + { +#ifdef Q_OS_SOLARIS + /* Need to check the process group of the pty. + * If it exists, then the slave pty is in use, + * and we need to get another one. + */ + int pgrp_rtn; + if (ioctl(d->masterFd, TIOCGPGRP, &pgrp_rtn) == 0 || errno != EIO) { + ::close(d->masterFd); + d->masterFd = -1; + continue; + } +#endif /* Q_OS_SOLARIS */ + if (!access(d->ttyName.data(),R_OK|W_OK)) // checks availability based on permission bits + { + if (!geteuid()) + { + struct group* p = getgrnam(TTY_GROUP); + if (!p) + p = getgrnam("wheel"); + gid_t gid = p ? p->gr_gid : getgid (); + + chown(d->ttyName.data(), getuid(), gid); + chmod(d->ttyName.data(), S_IRUSR|S_IWUSR|S_IWGRP); + } + goto gotpty; + } + ::close(d->masterFd); + d->masterFd = -1; + } + } + } + + qWarning() << "Can't open a pseudo teletype"; + return false; + + gotpty: + struct stat st; + if (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() + << "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()); +#endif + +#ifdef HAVE_UNLOCKPT + unlockpt(d->masterFd); +#elif defined(TIOCSPTLCK) + int flag = 0; + ioctl(d->masterFd, TIOCSPTLCK, &flag); +#endif + + d->slaveFd = ::open(d->ttyName.data(), O_RDWR | O_NOCTTY); + if (d->slaveFd < 0) + { + qWarning() << "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"); +#endif + +#endif /* HAVE_OPENPTY */ + + fcntl(d->masterFd, F_SETFD, FD_CLOEXEC); + fcntl(d->slaveFd, F_SETFD, FD_CLOEXEC); + + return true; +} + +void KPty::closeSlave() +{ + Q_D(KPty); + + if (d->slaveFd < 0) + return; + ::close(d->slaveFd); + d->slaveFd = -1; +} + +void KPty::close() +{ + 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; +} + +void KPty::setCTty() +{ + Q_D(KPty); + + // Setup job control ////////////////////////////////// + + // Become session leader, process group leader, + // and get rid of the old controlling terminal. + setsid(); + + // make our slave pty the new controlling terminal. +#ifdef TIOCSCTTY + ioctl(d->slaveFd, TIOCSCTTY, 0); +#else + // __svr4__ hack: the first tty opened after setsid() becomes controlling tty + ::close(::open(d->ttyName, O_WRONLY, 0)); +#endif + + // make our new process group the foreground group on the pty + int pgrp = getpid(); +#if defined(_POSIX_VERSION) || defined(__svr4__) + tcsetpgrp(d->slaveFd, pgrp); +#elif defined(TIOCSPGRP) + ioctl(d->slaveFd, TIOCSPGRP, (char *)&pgrp); +#endif +} + +void KPty::login(const char *user, const char *remotehost) +{ +#ifdef HAVE_UTEMPTER + Q_D(KPty); + + addToUtmp(d->ttyName, remotehost, d->masterFd); + Q_UNUSED(user); +#else +# ifdef HAVE_UTMPX + struct utmpx l_struct; +# else + struct utmp l_struct; +# endif + memset(&l_struct, 0, sizeof(l_struct)); + // note: strncpy without terminators _is_ correct here. man 4 utmp + + if (user) + strncpy(l_struct.ut_name, user, sizeof(l_struct.ut_name)); + + if (remotehost) { + strncpy(l_struct.ut_host, remotehost, sizeof(l_struct.ut_host)); +# ifdef HAVE_STRUCT_UTMP_UT_SYSLEN + l_struct.ut_syslen = qMin(strlen(remotehost), sizeof(l_struct.ut_host)); +# endif + } + +# ifndef __GLIBC__ + Q_D(KPty); + const char *str_ptr = d->ttyName.data(); + if (!memcmp(str_ptr, "/dev/", 5)) + str_ptr += 5; + strncpy(l_struct.ut_line, str_ptr, sizeof(l_struct.ut_line)); +# ifdef HAVE_STRUCT_UTMP_UT_ID + strncpy(l_struct.ut_id, + str_ptr + strlen(str_ptr) - sizeof(l_struct.ut_id), + sizeof(l_struct.ut_id)); +# endif +# endif + +# ifdef HAVE_UTMPX + gettimeofday(&l_struct.ut_tv, 0); +# else + l_struct.ut_time = time(0); +# endif + +# ifdef HAVE_LOGIN +# ifdef HAVE_LOGINX + ::loginx(&l_struct); +# else + ::login(&l_struct); +# endif +# else +# ifdef HAVE_STRUCT_UTMP_UT_TYPE + l_struct.ut_type = USER_PROCESS; +# endif +# ifdef HAVE_STRUCT_UTMP_UT_PID + l_struct.ut_pid = getpid(); +# ifdef HAVE_STRUCT_UTMP_UT_SESSION + l_struct.ut_session = getsid(0); +# endif +# endif +# ifdef HAVE_UTMPX + utmpxname(_PATH_UTMPX); + setutxent(); + pututxline(&l_struct); + endutxent(); + updwtmpx(_PATH_WTMPX, &l_struct); +# else + utmpname(_PATH_UTMP); + setutent(); + pututline(&l_struct); + endutent(); + updwtmp(_PATH_WTMP, &l_struct); +# endif +# endif +#endif +} + +void KPty::logout() +{ +#ifdef HAVE_UTEMPTER + Q_D(KPty); + + removeLineFromUtmp(d->ttyName, d->masterFd); +#else + Q_D(KPty); + + const char *str_ptr = d->ttyName.data(); + if (!memcmp(str_ptr, "/dev/", 5)) + str_ptr += 5; +# ifdef __GLIBC__ + else { + const char *sl_ptr = strrchr(str_ptr, '/'); + if (sl_ptr) + str_ptr = sl_ptr + 1; + } +# endif +# ifdef HAVE_LOGIN +# ifdef HAVE_LOGINX + ::logoutx(str_ptr, 0, DEAD_PROCESS); +# else + ::logout(str_ptr); +# endif +# else +# ifdef HAVE_UTMPX + struct utmpx l_struct, *ut; +# else + struct utmp l_struct, *ut; +# endif + memset(&l_struct, 0, sizeof(l_struct)); + + strncpy(l_struct.ut_line, str_ptr, sizeof(l_struct.ut_line)); + +# ifdef HAVE_UTMPX + utmpxname(_PATH_UTMPX); + setutxent(); + if ((ut = getutxline(&l_struct))) { +# else + utmpname(_PATH_UTMP); + setutent(); + if ((ut = getutline(&l_struct))) { +# endif + memset(ut->ut_name, 0, sizeof(*ut->ut_name)); + memset(ut->ut_host, 0, sizeof(*ut->ut_host)); +# ifdef HAVE_STRUCT_UTMP_UT_SYSLEN + ut->ut_syslen = 0; +# endif +# ifdef HAVE_STRUCT_UTMP_UT_TYPE + ut->ut_type = DEAD_PROCESS; +# endif +# ifdef HAVE_UTMPX + gettimeofday(ut->ut_tv, 0); + pututxline(ut); + } + endutxent(); +# else + ut->ut_time = time(0); + pututline(ut); + } + endutent(); +# endif +# endif +#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); + + return _tcgetattr(d->masterFd, ttmode) == 0; +} + +bool KPty::tcSetAttr(struct ::termios *ttmode) +{ + Q_D(KPty); + + return _tcsetattr(d->masterFd, ttmode) == 0; +} + +bool KPty::setWinSize(int lines, int columns) +{ + Q_D(KPty); + + struct winsize winSize; + memset(&winSize, 0, sizeof(winSize)); + winSize.ws_row = (unsigned short)lines; + winSize.ws_col = (unsigned short)columns; + return ioctl(d->masterFd, TIOCSWINSZ, (char *)&winSize) == 0; +} + +bool KPty::setEcho(bool echo) +{ + struct ::termios ttmode; + if (!tcGetAttr(&ttmode)) + return false; + if (!echo) + ttmode.c_lflag &= ~ECHO; + else + ttmode.c_lflag |= ECHO; + return tcSetAttr(&ttmode); +} + +const char *KPty::ttyName() const +{ + Q_D(const KPty); + + return d->ttyName.data(); +} + +int KPty::masterFd() const +{ + Q_D(const KPty); + + return d->masterFd; +} + +int KPty::slaveFd() const +{ + Q_D(const KPty); + + return d->slaveFd; +} diff --git a/client/browser/qtermwidget/includes/kpty.h b/client/browser/qtermwidget/src/kpty.h index 82868341..82868341 100644 --- a/client/browser/qtermwidget/includes/kpty.h +++ b/client/browser/qtermwidget/src/kpty.h diff --git a/client/browser/qtermwidget/includes/kpty_p.h b/client/browser/qtermwidget/src/kpty_p.h index 1702b44e..1702b44e 100644 --- a/client/browser/qtermwidget/includes/kpty_p.h +++ b/client/browser/qtermwidget/src/kpty_p.h diff --git a/client/browser/qtermwidget/src/qtermwidget.cpp b/client/browser/qtermwidget/src/qtermwidget.cpp new file mode 100644 index 00000000..f98e5bca --- /dev/null +++ b/client/browser/qtermwidget/src/qtermwidget.cpp @@ -0,0 +1,224 @@ +/* Copyright (C) 2008 e_k (e_k@users.sourceforge.net) + + 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 "qtermwidget.h" +#include "qtermwidget.moc" + +#include "Session.h" +#include "TerminalDisplay.h" + + +using namespace Konsole; + +void *createTermWidget(int startnow, void *parent) +{ + return (void*) new QTermWidget(startnow, (QWidget*)parent); +} + +struct TermWidgetImpl +{ + TermWidgetImpl(QWidget* parent = 0); + + TerminalDisplay *m_terminalDisplay; + Session *m_session; + + Session* createSession(); + TerminalDisplay* createTerminalDisplay(Session *session, QWidget* parent); +}; + +TermWidgetImpl::TermWidgetImpl(QWidget* parent) +{ + this->m_session = createSession(); + this->m_terminalDisplay = createTerminalDisplay(this->m_session, parent); +} + + +Session *TermWidgetImpl::createSession() +{ + Session *session = new Session(); + + session->setTitle(Session::NameRole, "QTermWidget"); + session->setProgram("/bin/bash"); + QStringList args(""); + session->setArguments(args); + session->setAutoClose(true); + + session->setCodec(QTextCodec::codecForName("UTF-8")); + + session->setFlowControlEnabled(true); + session->setHistoryType(HistoryTypeBuffer(1000)); + + session->setDarkBackground(true); + + session->setKeyBindings(""); + return session; +} + +TerminalDisplay *TermWidgetImpl::createTerminalDisplay(Session *session, QWidget* parent) +{ +// TerminalDisplay* display = new TerminalDisplay(this); + TerminalDisplay* display = new TerminalDisplay(parent); + + display->setBellMode(TerminalDisplay::NotifyBell); + display->setTerminalSizeHint(true); + display->setTripleClickMode(TerminalDisplay::SelectWholeLine); + display->setTerminalSizeStartup(true); + + display->setRandomSeed(session->sessionId() * 31); + + return display; +} + + +QTermWidget::QTermWidget(int startnow, QWidget *parent) +:QWidget(parent) +{ + m_impl = new TermWidgetImpl(this); + + init(); + + if (startnow && m_impl->m_session) { + m_impl->m_session->run(); + } + + this->setFocus( Qt::OtherFocusReason ); + m_impl->m_terminalDisplay->resize(this->size()); + + this->setFocusProxy(m_impl->m_terminalDisplay); +} + +void QTermWidget::startShellProgram() +{ + if ( m_impl->m_session->isRunning() ) + return; + + m_impl->m_session->run(); +} + +void QTermWidget::init() +{ + m_impl->m_terminalDisplay->setSize(80, 40); + + QFont font = QApplication::font(); + font.setFamily("Monospace"); + font.setPointSize(10); + font.setStyleHint(QFont::TypeWriter); + setTerminalFont(font); + setScrollBarPosition(NoScrollBar); + + m_impl->m_session->addView(m_impl->m_terminalDisplay); + + connect(m_impl->m_session, SIGNAL(finished()), this, SLOT(sessionFinished())); +} + + +QTermWidget::~QTermWidget() +{ + emit destroyed(); +} + + +void QTermWidget::setTerminalFont(QFont &font) +{ + if (!m_impl->m_terminalDisplay) + return; + m_impl->m_terminalDisplay->setVTFont(font); +} + +void QTermWidget::setShellProgram(QString &progname) +{ + if (!m_impl->m_session) + return; + m_impl->m_session->setProgram(progname); +} + +void QTermWidget::setArgs(QStringList &args) +{ + if (!m_impl->m_session) + return; + m_impl->m_session->setArguments(args); +} + +void QTermWidget::setTextCodec(QTextCodec *codec) +{ + if (!m_impl->m_session) + return; + m_impl->m_session->setCodec(codec); +} + +void QTermWidget::setColorScheme(int scheme) +{ + switch(scheme) { + case COLOR_SCHEME_WHITE_ON_BLACK: + m_impl->m_terminalDisplay->setColorTable(whiteonblack_color_table); + break; + case COLOR_SCHEME_GREEN_ON_BLACK: + m_impl->m_terminalDisplay->setColorTable(greenonblack_color_table); + break; + case COLOR_SCHEME_BLACK_ON_LIGHT_YELLOW: + m_impl->m_terminalDisplay->setColorTable(blackonlightyellow_color_table); + break; + default: //do nothing + break; + }; +} + +void QTermWidget::setSize(int h, int v) +{ + if (!m_impl->m_terminalDisplay) + return; + m_impl->m_terminalDisplay->setSize(h, v); +} + +void QTermWidget::setHistorySize(int lines) +{ + if (lines < 0) + m_impl->m_session->setHistoryType(HistoryTypeFile()); + else + m_impl->m_session->setHistoryType(HistoryTypeBuffer(lines)); +} + +void QTermWidget::setScrollBarPosition(ScrollBarPosition pos) +{ + if (!m_impl->m_terminalDisplay) + return; + m_impl->m_terminalDisplay->setScrollBarPosition((TerminalDisplay::ScrollBarPosition)pos); +} + +void QTermWidget::sendText(QString &text) +{ + m_impl->m_session->sendText(text); +} + +void QTermWidget::resizeEvent(QResizeEvent*) +{ +//qDebug("global window resizing...with %d %d", this->size().width(), this->size().height()); + m_impl->m_terminalDisplay->resize(this->size()); +} + + + +void QTermWidget::sessionFinished() +{ + emit finished(); +} + + +//#include "moc_consoleq.cpp" + diff --git a/client/browser/qtermwidget/includes/qtermwidget.h b/client/browser/qtermwidget/src/qtermwidget.h index 1a11c4df..1a11c4df 100644 --- a/client/browser/qtermwidget/includes/qtermwidget.h +++ b/client/browser/qtermwidget/src/qtermwidget.h |