diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8351056 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +CMakeLists.txt.user* +out +build +build2 +.vscode diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..2c43366 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,10 @@ +cmake_minimum_required(VERSION 3.16) +project(Browser) + + +set_property(GLOBAL PROPERTY CMAKE_CXX_STANDARD 17) +set_property(GLOBAL PROPERTY CMAKE_CXX_STANDARD_REQUIRED ON) + +add_subdirectory(qtermwidget) +add_subdirectory(digitalclock) +add_subdirectory(src) diff --git a/CMakePresets.json b/CMakePresets.json new file mode 100644 index 0000000..f5371d5 --- /dev/null +++ b/CMakePresets.json @@ -0,0 +1,17 @@ +{ + "version": 2, + "configurePresets": [ + { + "name": "Default", + "displayName": "Configure preset using toolchain file", + "description": "Sets Ninja generator, build and install directory", + "generator": "Ninja", + "binaryDir": "${sourceDir}/out/build/${presetName}", + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Debug", + "CMAKE_TOOLCHAIN_FILE": "", + "CMAKE_INSTALL_PREFIX": "${sourceDir}/out/install/${presetName}" + } + } + ] +} \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..4f67d5b --- /dev/null +++ b/README.md @@ -0,0 +1,55 @@ +# OG Browser + +El OpenGnsys Browser es un navegador limitado de tipo quiosco, basado en Qt6/Chrome. + +## Compilacion + +El sistema esta basado en CMake. Para compilar: + + + git clone https://ognproject.evlt.uma.es/gitea/unizar/ogbrowser.git + cd ogbrowser + mkdir build + cd build + cmake .. + make -j8 # 8 cores -- cambiar según hardware + + +## Uso + + src/OGBrowser URL + +Por ejemplo: + + src/OGBrowser http://example.com + + +## URLs especiales: + +El navegador reconoce URLs especiales dentro de los documentos, que pueden usarse +para ejecutar comandos locales. + +* command - Ejecuta un comando +* command+output - Ejecuta un comando y muestra la salida +* command+confirm - Pregunta antes de ejecutar un comando +* command+confirm+output - Pregunta antes de ejecutar un comando y muestra la salida +* command+output+confirm - Idéntico al anterior + + +Ejemplo: + + Ejecutar + +Esto crea un enlace que al hacerse click, ejecuta el comando ping y muestra el resultado en una ventana. + + +## Proxy + +Usa el proxy del sistema, incluyendo las variables de entorno: HTTP_PROXY, HTTPS_PROXY, ALL_PROXY, NO_PROXY + +## Modo administrativo + +El administrador dispone de una consola y mas información sobre la ejecución de comandos. + +Se activa estableciendo la variable de entorno `ogactiveadmin=true` + diff --git a/browser.pro b/browser.pro deleted file mode 100644 index 01978c7..0000000 --- a/browser.pro +++ /dev/null @@ -1,5 +0,0 @@ -TEMPLATE = subdirs -SUBDIRS = qtermwidget digitalclock src - -OPTIONS += ordered -CONFIG += qt warn_on release diff --git a/digitalclock/CMakeLists.txt b/digitalclock/CMakeLists.txt new file mode 100644 index 0000000..58bd30c --- /dev/null +++ b/digitalclock/CMakeLists.txt @@ -0,0 +1,34 @@ +cmake_minimum_required(VERSION 3.16) + +project(DigitalClock LANGUAGES CXX) + +set(CMAKE_INCLUDE_CURRENT_DIR ON) + +set(CMAKE_AUTOUIC ON) +set(CMAKE_AUTOMOC ON) +set(CMAKE_AUTORCC ON) + + +find_package(QT NAMES Qt6 dirCOMPONENTS Widgets LinguistTools Network REQUIRED) +find_package(Qt${QT_VERSION_MAJOR} COMPONENTS Widgets LinguistTools Network REQUIRED) + +message(STATUS "Building DigitalClock with Qt ${QT_VERSION}") + + +set(SOURCES + digitalclock.cpp + ) + + +add_library(DigitalClock ${SOURCES} ) + +set_property(TARGET DigitalClock PROPERTY CXX_STANDARD 17) +set_property(TARGET DigitalClock PROPERTY CXX_STANDARD_REQUIRED ON) + +target_link_libraries(DigitalClock PRIVATE Qt${QT_VERSION_MAJOR}::Widgets ) + + + +# We export this information so that other projects can use it +set(${PROJECT_NAME}_INCLUDE_DIRS ${PROJECT_SOURCE_DIR} CACHE INTERNAL "${PROJECT_NAME}: Include directories" FORCE) +set(${PROJECT_NAME}_LIB_DIRS ${PROJECT_BINARY_DIR} CACHE INTERNAL "${PROJECT_NAME}: Library directories" FORCE) diff --git a/digitalclock/digitalclock.cpp b/digitalclock/digitalclock.cpp index 4b65b6b..2b130ec 100644 --- a/digitalclock/digitalclock.cpp +++ b/digitalclock/digitalclock.cpp @@ -1,12 +1,22 @@ /**************************************************************************** ** -** Copyright (C) 2015 The Qt Company Ltd. -** Contact: http://www.qt.io/licensing/ +** Copyright (C) 2016 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ -** You may use this file under the terms of the BSD license as follows: +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are @@ -38,10 +48,11 @@ ** ****************************************************************************/ -#include - #include "digitalclock.h" +#include +#include + //! [0] DigitalClock::DigitalClock(QWidget *parent) : QLCDNumber(parent) @@ -49,7 +60,7 @@ DigitalClock::DigitalClock(QWidget *parent) setSegmentStyle(Filled); QTimer *timer = new QTimer(this); - connect(timer, SIGNAL(timeout()), this, SLOT(showTime())); + connect(timer, &QTimer::timeout, this, &DigitalClock::showTime); timer->start(1000); showTime(); diff --git a/digitalclock/digitalclock.h b/digitalclock/digitalclock.h index f891335..31c12f3 100644 --- a/digitalclock/digitalclock.h +++ b/digitalclock/digitalclock.h @@ -1,12 +1,22 @@ /**************************************************************************** ** -** Copyright (C) 2015 The Qt Company Ltd. -** Contact: http://www.qt.io/licensing/ +** Copyright (C) 2016 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ -** You may use this file under the terms of the BSD license as follows: +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are @@ -49,7 +59,7 @@ class DigitalClock : public QLCDNumber Q_OBJECT public: - DigitalClock(QWidget *parent = 0); + DigitalClock(QWidget *parent = nullptr); private slots: void showTime(); diff --git a/digitalclock/digitalclock.pro b/digitalclock/digitalclock.pro index 6d2d283..4e4bc0f 100644 --- a/digitalclock/digitalclock.pro +++ b/digitalclock/digitalclock.pro @@ -1,23 +1,9 @@ -TEMPLATE = lib -DESTDIR = .. - -TARGET = digitalclock - -CONFIG += qt release warn_on build_all staticlib - -QT += core gui - -MOC_DIR = ../.moc - -OBJECTS_DIR = ../.objs -TARGET = digitalclock - -DEFINES += HAVE_POSIX_OPENPT -#or DEFINES += HAVE_GETPT - -HEADERS = digitalclock.h - -SOURCES = digitalclock.cpp - +QT += widgets +HEADERS = digitalclock.h +SOURCES = digitalclock.cpp \ + main.cpp +# install +target.path = $$[QT_INSTALL_EXAMPLES]/widgets/widgets/digitalclock +INSTALLS += target diff --git a/digitalclock/main.cpp b/digitalclock/main.cpp new file mode 100644 index 0000000..9440a81 --- /dev/null +++ b/digitalclock/main.cpp @@ -0,0 +1,61 @@ +/**************************************************************************** +** +** Copyright (C) 2016 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include "digitalclock.h" + +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + DigitalClock clock; + clock.show(); + return app.exec(); +} diff --git a/qndtest b/qndtest new file mode 100644 index 0000000..9daeafb --- /dev/null +++ b/qndtest @@ -0,0 +1 @@ +test diff --git a/qtermwidget/.translation-update b/qtermwidget/.translation-update new file mode 100644 index 0000000..8b818c9 --- /dev/null +++ b/qtermwidget/.translation-update @@ -0,0 +1 @@ +translations='./lib' diff --git a/qtermwidget/AUTHORS b/qtermwidget/AUTHORS index bfa5fa3..0540a6a 100644 --- a/qtermwidget/AUTHORS +++ b/qtermwidget/AUTHORS @@ -1 +1,15 @@ -e_k@users.sourceforge.net \ No newline at end of file +Originally forked from Konsole by + +Revived by Petr Vanek + +Contributors: + +Adam Treat +Chris Mueller +Christian Surlykke +Daniel O'Neill +Francisco Ballina +Georg Rudoy <0xd34df00d@gmail.com> +Jerome Leclanche +Petr Vanek +@kulti diff --git a/qtermwidget/CHANGELOG b/qtermwidget/CHANGELOG new file mode 100644 index 0000000..bacffc0 --- /dev/null +++ b/qtermwidget/CHANGELOG @@ -0,0 +1,427 @@ +qtermwidget-1.4.0 / unreleased +=============================== + * TERM env variable set to xterm-256color when not set with QTermWidget::setEnvironment(). + +qtermwidget-1.3.0 / 2023-04-15 +=============================== + * Fixed a problem in switching the color scheme between dark and light. + * Prevented a crash on splitting the terminal under `kwin_wayland` + +qtermwidget-1.2.0 / 2022-11-05 +=============================== + * Enabled Bidi rendering by default. + * Made text DND follow the settings for newline trimming and multiline prompt. + * Allow `QTermWidget` to be used as a Qt Plugin. + +qtermwidget-1.1.0 / 2022-04-15 +=============================== + * Handled the zero history size. + * Removed an unused variable. + * Corrected some code indentations. + * Added API documentation and followed naming convention. + * Return focus to terminal on closing search bar. + * Moved to SIP 5.x wth PyQt. + * Added contexts to some lambda connections. + +qtermwidget-1.0.0 / 2021-11-04 +=============================== + * Bumped minimum required Qt version to 5.15. + * Fixed crash under (Plasma) Wayland on opening tab and splitting. + * Use "empty()" to check for container emptiness. + * Made some member functions const. + * Quote drag-and-drop file names. + * Backported CNL and CPL support from Konsole. + * Use QRandomGenerator instead of qrand(). + * Silenced some compilation warnings. + * Basic EditorConfig definition. + +qtermwidget-0.17.0 / 2021-04-15 +=============================== + * Drop support for KDE3 color scheme formats. + * Some code cleanup and modernization. + * Added a method to disable bracketed paste mode. + * Added an example for PyQt5. + * Improve "Undecodable sequence" warnings. + * Properly implement the "Action after paste" feature. + * Fix execution after paste when Ctrl is hold. + * Workaround an issue with glibc 2.33 on old Docker engines. + * Added modes for background image. How background images are drawn is changed and manual reconfiguration is needed. See docs/configuration.md for more details. + +qtermwidget-0.16.1 / 2020-11-14 +=============================== + * Bumped version to 0.16.1, for a point release of qterminal. + +qtermwidget-0.16.0 / 2020-11-01 +=============================== + + * Use qAsConst. + * Don't search application dir for keyboard and scheme data. + * Use Q_EMIT to call signals, instead of the emit keyword. + * Dropped the deprecated class QLinkedList. + * Don't use 0/nullptr to initialize QFlags. + * Fixed ColorEntry copy operator. + * Disabled the use of copy constructors and assignment operators. + * Check for successful ioctl() calls by testing that the call did not return -1. + * Fix find_package() developer warning in cmake. + * Use const references wherever possible. + * Handle keyboard commands properly. + +qtermwidget-0.15.0 / 2020-04-24 +=============================== + + * Bumped version to 0.15.0. + * Replaced Q_WS_MAC with Q_OS_MACOS for Qt5 compatibility. + * KPty: Don't conditionalize chownpty existence on HAVE_OPENPTY. + * cmake: set CMAKE_BUILD_WITH_INSTALL_NAME_DIR ON for macOS. + * Fixed the default font on macOS. + * pyqt: Fixes deprecation warning (CMP0002). + * Fixed the PyQt5 binding with Qt ≥ 5.11. + * Swap Qt's ControlModifier and MetaModifier on macOS. + * C++11 code updates. + * Use braced initializer list in returns. + * Fixed the memory access violation in TerminalDisplay's method `getCharacterPosition`. + * Completed the support for transient scrollbars. + * Added `saveHistory` to QTermWidget. + * Use vanilla Qt instead of patched one. + * Don't set the selection clipboard if it's unsupported. + * Announce truecolor support via COLORTERM. + * Fixed numpad handling and added entries for numpad 5. + * Allow to disable drawing line chars. + * Use QRectF for cursor drawing and fix artifacts in hidpi. + * Fixed compilation on NetBSD. + * Added sendKeyEvent() API. + * Fixed flickering on font change. + * Select all text when opening search bar. + * Removed some debug outputs. + * Removed (duplicated) string casts definitions. + * Removed obsolete qCopy. + * Fix SearchBar light text over white background with dark themes. + * pyqt: also check for sip 5.x path. + * Prevented a c++11 range-loop might detach Qt container. + * Dropped the deprecated QString method `sprintf()`. + * Avoid buffer overflows exploits. + * Fixed build with LLVM/clang. + * Explicitly mark exported classes. + * Fixed QCharRef's deprecated behavior. + * Correctly initialize sigsets. + +qtermwidget-0.14.1 / 2019-02-25 +=============================== + + * Bumped version to 0.14.1 + * Only translations was changed. + +qtermwidget-0.14.0 / 2019-01-25 +=============================== + + * Bumped version to 0.14.0 + The big bump was needed to prevent conflicts with translations + that were former built out of lxqt-l10n and have version 0.13.0 + * Clarify the licenses used in qtermwidget and added the missed root licenses + * Implementation fixes: + - kpty: use openpty() on mac + - kpty: make it work on OpenBSD + - kptyprocess: ensure .bash_history is correctly written out + - kb-layouts: Make Backspace behaves the same as xterm + - tools: Drop the ability to bundle kb-layouts and colorschemes + - SearchBar: Fix visual glitches in search-bar + - TerminalDisplay: Fixed link mouseover after recent changes + - TerminalDisplay: Redraw cursor after cursor type changed + - Vt102Emulation: Fix handling of ST (String Terminator) for OSC (Operating System Commands) + - qterminal: Correct deleting of HotSpot list items + - qterminal: Removed unnecessary checks + - ColorScheme: Fixed local variable will be copied despite being returned by name + - ColorScheme: Fixed error return-std-move + - Removed unnecessary checks + - Suppressed compilation warnings + - Don't use automatic string conversions + - Marked some functions const + - Implemented terminal margins + * Improved cmake scripting + - Set cmake_minimum_required to 3.1.0 + - Removed locale compile definitions + - Removed QUIET from find_package + * Moved translations from lxqt-l10n back to qtermwidget + - Removed obsolete translation functionality + - Added translation promo in README.md + * Translation updates + +qtermwidget-0.9.0 / 2018-05-21 +============================== + + * Bumped minor version to 9 + * Take transient scrollbars into account + * CMake: Prevent in-source builds + * Refactor and fixes Python binding + * kptyprocess: Try to terminate the shell process + * New color scheme: Ubuntu inspired + * Fixed some github paths in uris + * Add a comment for potential future breakage + * Use wstring in TerminalCharacterDecoder for UCS-4 compatibility + * Support UTF-32 characters correctly + * Fix "bold and intensive" colors + * New color scheme: Tango (#167) + * Finish SGR mouse protocol (1006) + * Fix build of example with latest lxqt-build-tools + * Expose bracket text function + * Drop Qt foreach. + * Revert deletions in .sip file + * fix python bindings + * Expose terminal size hint API + * Remove class name + * Return something + * Expose bidi option + * Add an example for remote terminal + * Makes the use of libutempter optional + * Fix behavior of scroll up (SU) + * Install cmake files in LIBDIR as they are architecture dependent + * Check if utempter.h header exists (mainly for FreeBSD) + * Need lxqt-build-tools 0.4.0 + +qtermwidget-0.8.0 / 2017-10-21 +================== + + * Release 0.8.0: Update changelog + * FIX: #46 fix vertical font truncation + * bump versions + * Really fallback to /bin/sh when $SHELL is missing or invalid + * README: don't recommend building from source + * Improve README + * Don't export github templates + * Support REP escape sequence defined in ECMA-48, section 8.3.103 + * Fix build issue related to utmpx in Mac OSX Sierra + * Remove the deprecation notice + * Handle DECSCUSR signals + * Copied issue template + * Update building instructions + * Require Qt 5.6+ + * This commit allows the consumer of qtermwidget to capture the (#111) + * Allow the terminal display to be smaller than the size hint (#123) + * Backport Vt102 emulation fixes (#113) + * Backport the default.keytab from Konsole + * Fixes (#122) + * Updated README, Added support for PyQT 5.7 + * Fix memory leak in hotspot (URLs & emails) detection + * Adds superbuild support + * Use target_compile_definitions() instead of add_definitions() + * Update find_package() documentation + * Use the lxqt_create_pkgconfig_file + * Improve lxqt_translate_ts() use + * Adds COMPONENT to the install files + * Renames test app to example. Make it work + * Drop include_directories() for in tree dirs + * Use the CMake Targets way + * Pack Utf8Proc stuff + * Adds export header + * Use LXQtCompilerSettings + * Packs compile definitions + * Adds package version file + * Removes Qt4 stuff + * Add translation mechanism + * Use const iterators when possible. + * Enable strict iterators for debug builds + * TerminalDisplay: Make resizing "Size" translatable + * Exposes receivedData signal to users of QTermWidget + * Exposes sessions autoClose property to QTermWidget + +qtermwidget-0.7.1 / 2016-12-21 +================== + + * Release 0.7.1: Update changelog + * Bump patch version (#105) + * Added a modified Breeze color scheme (#104) + * Accept hex color strings as well (#101) + * Remove the stale lib/README (#102) + * Implement background images (#95) + * Implement other BOX DRAWING characters (#98) + * Preparations for context menu actions on URLs (#97) + * Drop the ancient wcwidth impl. and use utf8proc if possible (#99) + * Remove widget size checks in setVTFont() (#86) + * Delete unused tooltip code (#81) + * Fix size of the array passed to memset() (#79) + * Remove cpack (#93) + +qtermwidget-0.7.0 / 2016-09-24 +================== + + * Release 0.7.0: Add changelog + * Bump version to 0.7.0 (#92) + * Add Solarized Color Schemes + * Update README.md + * qtermwidget: Unify title & icon propagation + * lib: Fix FTBFS (struct vs. class mismatch) + * Add 'const' decorators + * Expose titleChanged() signal + * Fix building instructions + * cmake support changes + * Make addCustomColorSchemeDir() static and check for duplicates + * Address review comments + * Allow app to add custom color scheme locations + * Avoid enums duplication + * Add support for setting keyboard cursor shape + * Remove assignment to self + * Backport konsole changes to fix memory leaks + * Remove __FILE__ macros + * Replace assert() with Q_ASSERT() + * Fix ASan error about delete size mismatch + * Add support for GNU/Hurd to kpty.cpp. + * fixes kfreebsd builds on debian and derivatives + * Fix indenations (misleading-indentation warning) + * Remove Q_DECL_OVERRIDE macros + * typo Higlight + * Remove noisy qDebugs + * Bracketed paste mode implementation + * Use function setWorldTranfer for Qpainter instead of setWorldMatrix + * Modify treatment drawing double width character + * pyqt5 bindings + * pyqt5 bindings + * Avoid checking uninitialized member + simplify condition + * Use markdown for README and improve it a bit + * Remove support for Qt <= 5.4 + * Remove Designer plugin + * Fix LICENSE text and name + * Remove Changelog + * Remove empty TODO file + * Remove PyQt4 bindings + * Sort out terminal resizing + * Rebase Vt102Emulation to Konsole + * Enable terminal resizing from the emulator + * Clean up trailing whitespaces + * implemented start TTY for external recipient; + * Fix: typo in TerminalDisplay + * add method for get pty slave fd; + * add method for get pty slave fd; + * Use GNUInstallDirs in CMakeLists.txt to stop hardcoding paths + * Set the '_notifiedActivity' flag early + * Also expose signals and slots to pyqt + * Get/set selection end in python bindings + * Avoid calling winId() on Qt5. + * Fix TerminalDisplay::getCharacterPosition for proportional fonts + * Handle proportional fonts a bit better + * Expose more functionality through the python bindings (#23) + * Allow stopping test.py with ctrl-C + * Fix 'getSelectionEnd' + * Make whitespace consistent (tabs->spaces) + * Fix python binding compile errors #23 + * Add event to notify the application that the shell application uses mouse. + * Change mouseMarks only when needed. This might be useful if an application wants to be notified of the event. + * Prevents deleting the last line when resizing. + +qtermwidget-0.6.0 / 2014-10-21 +================== + + * Release 0.6.0 + * Update AUTHORS + * Update INSTALL instructions + * CMakeLists.txt cleanup + * osx: link fixes + * fixed #57 Linux emulation does not seem to support Ctrl+Arrows (warning: I have no clue what I did...) + * Fix Qt4 compilation + * qterminal #64 No drag & drop support + * fixed qterminal #71 qt5 version ignoring page up / down + * Fixed a typo in CMakeLists.txt. + +qtermwidget-0.5.1 / 2014-07-14 +================== + + * fixed 'make dist'; version bump + * Url activation & filters #21 + * Proxy activity/silence methods to Session in QTermWidget. + * Emit activity() and silence() signals instead of KNotification. + * Support bells. + * Support bells. + * Added QTermWidget::urlActivated(QUrl) signal. + * Emit UrlFilter::activated() instead of QDesktopServices::openUrl(). + * Derive Filter from QObject. + * Add UrlFilter. + * Activate link filters on ctrl+click. + * Update filters on resize and screen events. + * Const-correctness for QTermWidget API. + * Load arbitrary schemes by path via setColorScheme(). + * ColorSchemeManager::loadCustomColorScheme(const QString& path). + * Unified schemeName() usage. + * fixed #17 lib/ShellCommand.cpp:66: possible =/== mixup + * Delete CMakeLists.txt.user + * new API selectedText() + * new API methods (thanks to William Brumley) + * fixed #11 compile against Qt 5 (Qt4 and Qt5 supported and waguely tested) + * build simplified: qtermwidget is versioned (libqtermwidget4 for Qt4, 5 for Qt5...). Better cmake support. + * fixed broken API for sendText() - const missing + * mail address change + * Current Working Directory for linux. Part of #8. More implementations welcomed... + * Add a method for get working directory in class QTermWidget + * Fix missing cleanup for temporary history files + * a potential improvement for #9 font fractional pixels causes spacing errors + * fix #2 update various documentations for debian packaging + * fix #10 Update FSF address + +qtermwidget-0.4.0 / 2013-04-16 +================== + + * readme updated + * Added pasteSelection-slot and corrected two nonsense comments + * qt/embedded doesn't ship with a Monospace font (and it won't use system fonts even if they exist). Using 'fixed' instead works fine + * Without this, the terminal display area will permanently lose focus when consoleq's Find dialog is called up. + * This is only needed when using Qt/E built for DirectFB display. DirectFB blocks SIGINT and some other signals, so any terminal app (be it Qt or otherwise) must call sigprocmask() to unblock them. Without this, ^C doesn't work. + * The control and tab keys don't work in Qt/E. This fixes it, but maybe not in the most elegant way. The trouble seems to be that _codec->fromUnicode(event->text()) doesn't handle control characters in qt-embedded. + * Fix resize label + * Search code cleanup + * Change searchbar background color to red(ish) when no match found + * Fix search, find-next when selection is one character long + * Hotkeys for search: Return->find-next, Shift-Return->find-previous, Escape->hide searchbar + * Added search functionality + * Add zoom. Add choice action after paste clipboard + * Add zoom. Add choice action after paste clipboard + * Add zoom. Add choice action after paste clipboard + * Add zoom. Add choice action after paste clipboard + * Add zoom. Add choice action after paste clipboard + * Add zoom. Add choice action after paste clipboard + * Add zoom. Add choice action after paste clipboard + * Add zoom. Add choice action after paste clipboard + * Add zoom. Add choice action after paste clipboard + * Fix logical error + * Add zoom. Add choice action after paste clipboard + * Add zoom. Add choice action after paste clipboard + * Add Shift+KeyEnd and Shift+KeyHome to go line 0 and line end. No move screenwindow when copy and paste with keyboard + * fix for text drawing in qt>=4.8,x + * constructor for Qt Designer + * test commit + * clear() slot implemented + * fix the scroll at the end again + * The escape key is always needed for terminal programs like vim. + * Add resource files and the appropriate paths to enable bundling of color schemes and keyboard layouts into the actual executable. + * Add a define which will be used to bundle the color schemes and keyboard layouts as resource files with the executable itself instead of putting them on disk. + * scrollToEnd() method provided to trigger 'snapping' the terminal to cursor tracked position (typically the extreme value of the scrollbar, or the 'end') Some signal-fu particular to keyPressEvent(QKeyEvent *) done to make the above usable, no existing dependent implementations should be disturbed by this. + * revert workaround for key on end + * scroll to bottom on input + * scrollToEnd() method provided to trigger 'snapping' the terminal to cursor tracked position (typically the extreme value of the scrollbar, or the 'end') Some signal-fu particular to keyPressEvent(QKeyEvent *) done to make the above usable, no existing dependent implementations should be disturbed by this. + * improved sample app for testing + * macosx compile fix + * arguments work correctly for custom shells too + * lib has to be built first in any case + * merge changes from the experimental "bundle" repository + * fix for kb-layout location on mac (mainly) + * rpm builds + * mac universal build helper + * build cleanup; make dist; various readmes updated + * make availableKeyBindings static + * transparency support + * font display fix on mac (widths in int) + * qt designer plugin + * correct lib ID for mac + * remove the KDE legacy code + * code reformatted after resync + * display stuff synced from konsole again to improve color scheme handling + * focus in/out signals + * correct shell detection (BSD, Christopher VdoP) + * library location on BSD + * patches to build on BSD by Christopher VdoP + * K&R formatting + * K&R formatting + * merge with qscite + * fixed KB finding + sort + * key layouts can be read and provided to widget + * install keyboard bindings; handle KB in src code; allow to get and set KB + * fix for includes and 64bit builds + * port to macosx + * initial import diff --git a/qtermwidget/CMakeLists.txt b/qtermwidget/CMakeLists.txt new file mode 100644 index 0000000..880911a --- /dev/null +++ b/qtermwidget/CMakeLists.txt @@ -0,0 +1,375 @@ +cmake_minimum_required(VERSION 3.5 FATAL_ERROR) +# CMP0000: Call the cmake_minimum_required() command at the beginning of the top-level +# CMakeLists.txt file even before calling the project() command. +# The cmake_minimum_required(VERSION) command implicitly invokes the cmake_policy(VERSION) +# command to specify that the current project code is written for the given range of CMake +# versions. +project(qtermwidget) + +include(GNUInstallDirs) +include(GenerateExportHeader) +include(CMakePackageConfigHelpers) +include(CheckFunctionExists) +include(CheckIncludeFile) + +option(UPDATE_TRANSLATIONS "Update source translation translations/*.ts files" OFF) +option(BUILD_EXAMPLE "Build example application. Default OFF." OFF) +option(QTERMWIDGET_USE_UTEMPTER "Uses libutempter on Linux or libulog on FreeBSD for login records." OFF) +option(QTERMWIDGET_BUILD_PYTHON_BINDING "Build python binding" OFF) +option(USE_UTF8PROC "Use libutf8proc for better Unicode support. Default OFF" OFF) +option(USE_QT5 "Use Qt 5 instead of Qt6 (if available). Default OFF" OFF) + +# just change version for releases +# keep this in sync with the version in pyqt/pyproject.toml +set(QTERMWIDGET_VERSION_MAJOR "1") +set(QTERMWIDGET_VERSION_MINOR "3") +set(QTERMWIDGET_VERSION_PATCH "0") + +set(QTERMWIDGET_VERSION "${QTERMWIDGET_VERSION_MAJOR}.${QTERMWIDGET_VERSION_MINOR}.${QTERMWIDGET_VERSION_PATCH}") + +# additional cmake files +set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${PROJECT_SOURCE_DIR}/cmake") +set(CMAKE_INCLUDE_CURRENT_DIR ON) + +# Minimum Versions +set(QT_MINIMUM_VERSION "5.15.0") +set(QT6_MINIMUM_VERSION "6.1.0") +set(LXQTBT_MINIMUM_VERSION "0.10.0") + +if (NOT USE_QT5) + find_package(Qt6 COMPONENTS Widgets) + if (NOT Qt6_FOUND) + find_package(Qt5Widgets "${QT_MINIMUM_VERSION}" REQUIRED) + find_package(Qt5LinguistTools "${QT_MINIMUM_VERSION}" REQUIRED) + endif() + + if (Qt6_FOUND) + find_package(Qt6Widgets "${QT6_MINIMUM_VERSION}" REQUIRED) + find_package(Qt6LinguistTools "${QT6_MINIMUM_VERSION}" REQUIRED) + find_package(Qt6Core5Compat "${QT6_MINIMUM_VERSION}" REQUIRED) + endif() +else() + find_package(Qt5Widgets "${QT_MINIMUM_VERSION}" REQUIRED) + find_package(Qt5LinguistTools "${QT_MINIMUM_VERSION}" REQUIRED) +endif() + +find_package(lxqt-build-tools ${LXQTBT_MINIMUM_VERSION} REQUIRED) + +if(USE_UTF8PROC) + find_package(Utf8Proc REQUIRED) +endif() + +include(LXQtPreventInSourceBuilds) +include(LXQtTranslateTs) +include(LXQtCompilerSettings NO_POLICY_SCOPE) +include(LXQtCreatePkgConfigFile) + +if(APPLE) + if(CMAKE_VERSION VERSION_GREATER 3.9) + cmake_policy(SET CMP0068 NEW) + set(CMAKE_BUILD_WITH_INSTALL_NAME_DIR ON) + endif() +endif() + +if (NOT Qt6_FOUND) + set(QTERMWIDGET_LIBRARY_NAME qtermwidget5) +else() + set(QTERMWIDGET_LIBRARY_NAME qtermwidget6) +endif() + +# main library + +set(SRCS + lib/BlockArray.cpp + lib/ColorScheme.cpp + lib/Emulation.cpp + lib/Filter.cpp + lib/History.cpp + lib/HistorySearch.cpp + lib/KeyboardTranslator.cpp + lib/konsole_wcwidth.cpp + lib/kprocess.cpp + lib/kpty.cpp + lib/kptydevice.cpp + lib/kptyprocess.cpp + lib/Pty.cpp + lib/qtermwidget.cpp + lib/Screen.cpp + lib/ScreenWindow.cpp + lib/SearchBar.cpp + lib/Session.cpp + lib/ShellCommand.cpp + lib/TerminalCharacterDecoder.cpp + lib/TerminalDisplay.cpp + lib/tools.cpp + lib/Vt102Emulation.cpp +) + +# Only the Headers that need to be moc'd go here +set(HDRS + lib/Emulation.h + lib/Filter.h + lib/HistorySearch.h + lib/kprocess.h + lib/kptydevice.h + lib/kptyprocess.h + lib/Pty.h + lib/qtermwidget.h + lib/ScreenWindow.h + lib/SearchBar.h + lib/Session.h + lib/TerminalDisplay.h + lib/Vt102Emulation.h +) + +set(UI + lib/SearchBar.ui +) + +# for distribution +set(HDRS_DISTRIB + lib/qtermwidget.h + lib/Emulation.h + lib/KeyboardTranslator.h + lib/Filter.h + lib/qtermwidget_interface.h +) + +# dirs +set(KB_LAYOUT_DIR "${CMAKE_INSTALL_FULL_DATADIR}/${QTERMWIDGET_LIBRARY_NAME}/kb-layouts") +message(STATUS "Keyboard layouts will be installed in: ${KB_LAYOUT_DIR}") + +set(COLORSCHEMES_DIR "${CMAKE_INSTALL_FULL_DATADIR}/${QTERMWIDGET_LIBRARY_NAME}/color-schemes") +message(STATUS "Color schemes will be installed in: ${COLORSCHEMES_DIR}" ) + +set(TRANSLATIONS_DIR "${CMAKE_INSTALL_FULL_DATADIR}/${QTERMWIDGET_LIBRARY_NAME}/translations") +message(STATUS "Translations will be installed in: ${TRANSLATIONS_DIR}") + +set(QTERMWIDGET_INCLUDE_DIR "${CMAKE_INSTALL_FULL_INCLUDEDIR}/${QTERMWIDGET_LIBRARY_NAME}") + +CHECK_FUNCTION_EXISTS(updwtmpx HAVE_UPDWTMPX) + +if (NOT USE_QT5) + if (NOT Qt6_FOUND) + qt5_wrap_cpp(MOCS ${HDRS}) + qt5_wrap_ui(UI_SRCS ${UI}) + set(PKG_CONFIG_REQ "Qt5Widgets") + else() + qt6_wrap_cpp(MOCS ${HDRS}) + qt6_wrap_ui(UI_SRCS ${UI}) + set(PKG_CONFIG_REQ "Qt6Widgets") + endif() +else() + qt5_wrap_cpp(MOCS ${HDRS}) + qt5_wrap_ui(UI_SRCS ${UI}) + set(PKG_CONFIG_REQ "Qt5Widgets") +endif() + +lxqt_translate_ts(QTERMWIDGET_QM + TRANSLATION_DIR "lib/translations" + UPDATE_TRANSLATIONS + ${UPDATE_TRANSLATIONS} + SOURCES + ${SRCS} ${HDRS} ${UI} + INSTALL_DIR + ${TRANSLATIONS_DIR} + COMPONENT + Runtime +) + +add_library(${QTERMWIDGET_LIBRARY_NAME} SHARED ${SRCS} ${MOCS} ${UI_SRCS} ${QTERMWIDGET_QM}) +if (NOT USE_QT5) + if (NOT Qt6_FOUND) + target_link_libraries(${QTERMWIDGET_LIBRARY_NAME} Qt5::Widgets) + else() + target_link_libraries(${QTERMWIDGET_LIBRARY_NAME} Qt6::Widgets) + target_link_libraries(${QTERMWIDGET_LIBRARY_NAME} Qt6::Core5Compat) + endif() +else() + target_link_libraries(${QTERMWIDGET_LIBRARY_NAME} Qt5::Widgets) +endif() + +set_target_properties( ${QTERMWIDGET_LIBRARY_NAME} PROPERTIES + SOVERSION ${QTERMWIDGET_VERSION_MAJOR} + VERSION ${QTERMWIDGET_VERSION} + ) + + +if(APPLE) + target_compile_definitions(${QTERMWIDGET_LIBRARY_NAME} + PRIVATE + "HAVE_UTMPX" + "UTMPX_COMPAT" + ) +endif() + +if(HAVE_UPDWTMPX) + target_compile_definitions(${QTERMWIDGET_LIBRARY_NAME} + PRIVATE + "HAVE_UPDWTMPX" + ) +endif() + +if (QTERMWIDGET_USE_UTEMPTER) + CHECK_INCLUDE_FILE(utempter.h HAVE_UTEMPTER) + if (HAVE_UTEMPTER) + target_compile_definitions(${QTERMWIDGET_LIBRARY_NAME} PRIVATE + "HAVE_UTEMPTER" + ) + find_library(UTEMPTER_LIB NAMES utempter ulog REQUIRED) + target_link_libraries(${QTERMWIDGET_LIBRARY_NAME} ${UTEMPTER_LIB}) + endif() +endif() + +if (UTF8PROC_FOUND) + target_compile_definitions(${QTERMWIDGET_LIBRARY_NAME} + PRIVATE + "HAVE_UTF8PROC" + ) + target_include_directories(${QTERMWIDGET_LIBRARY_NAME} + INTERFACE + ${UTF8PROC_INCLUDE_DIRS} + ) + target_link_libraries(${QTERMWIDGET_LIBRARY_NAME} + ${UTF8PROC_LIBRARIES} + ) + string(APPEND PKG_CONFIG_REQ ", libutf8proc") +endif() + +if(APPLE) + set (CMAKE_SKIP_RPATH 1) + # this is a must to load the lib correctly + set_target_properties(${QTERMWIDGET_LIBRARY_NAME} PROPERTIES INSTALL_NAME_DIR ${CMAKE_INSTALL_FULL_LIBDIR}) +endif() + +target_compile_definitions(${QTERMWIDGET_LIBRARY_NAME} + PRIVATE + "KB_LAYOUT_DIR=\"${KB_LAYOUT_DIR}\"" + "COLORSCHEMES_DIR=\"${COLORSCHEMES_DIR}\"" + "TRANSLATIONS_DIR=\"${TRANSLATIONS_DIR}\"" + "HAVE_POSIX_OPENPT" + "HAVE_SYS_TIME_H" +) + + +generate_export_header(${QTERMWIDGET_LIBRARY_NAME} + EXPORT_FILE_NAME "${CMAKE_CURRENT_BINARY_DIR}/lib/qtermwidget_export.h" + BASE_NAME QTERMWIDGET +) + +target_include_directories(${QTERMWIDGET_LIBRARY_NAME} + PUBLIC + "$" + "$" + "$" + INTERFACE + "$" + "$" +) + +write_basic_package_version_file( + "${CMAKE_BINARY_DIR}/${QTERMWIDGET_LIBRARY_NAME}-config-version.cmake" + VERSION ${QTERMWIDGET_VERSION} + COMPATIBILITY AnyNewerVersion +) + +install(FILES + "${CMAKE_BINARY_DIR}/${QTERMWIDGET_LIBRARY_NAME}-config-version.cmake" + DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${QTERMWIDGET_LIBRARY_NAME}" + COMPONENT Devel +) + +install(EXPORT + "${QTERMWIDGET_LIBRARY_NAME}-targets" + DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${QTERMWIDGET_LIBRARY_NAME}" + COMPONENT Devel +) + +install(FILES + ${HDRS_DISTRIB} "${CMAKE_CURRENT_BINARY_DIR}/lib/qtermwidget_export.h" "${CMAKE_CURRENT_BINARY_DIR}/lib/qtermwidget_version.h" + DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/${QTERMWIDGET_LIBRARY_NAME}" + COMPONENT Devel +) +# keyboard layouts +install(DIRECTORY + lib/kb-layouts/ + DESTINATION "${KB_LAYOUT_DIR}" + COMPONENT Runtime + FILES_MATCHING PATTERN "*.keytab" +) +# color schemes +install(DIRECTORY + lib/color-schemes/ + DESTINATION "${COLORSCHEMES_DIR}" + COMPONENT Runtime + FILES_MATCHING PATTERN "*.*schem*" +) + +lxqt_create_pkgconfig_file( + PACKAGE_NAME ${QTERMWIDGET_LIBRARY_NAME} + DESCRIPTIVE_NAME ${QTERMWIDGET_LIBRARY_NAME} + DESCRIPTION "QTermWidget library for Qt ${QTERMWIDGET_VERSION_MAJOR}.x" + INCLUDEDIRS ${QTERMWIDGET_LIBRARY_NAME} + LIBS ${QTERMWIDGET_LIBRARY_NAME} + REQUIRES ${PKG_CONFIG_REQ} + VERSION ${QTERMWIDGET_VERSION} + INSTALL + COMPONENT Devel +) + +configure_file( + "${PROJECT_SOURCE_DIR}/cmake/${QTERMWIDGET_LIBRARY_NAME}-config.cmake.in" + "${CMAKE_BINARY_DIR}/${QTERMWIDGET_LIBRARY_NAME}-config.cmake" + @ONLY +) + +configure_file( + "${PROJECT_SOURCE_DIR}/lib/qtermwidget_version.h.in" + "${CMAKE_BINARY_DIR}/lib/qtermwidget_version.h" + @ONLY +) + +install(FILES + "${CMAKE_BINARY_DIR}/${QTERMWIDGET_LIBRARY_NAME}-config.cmake" + DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${QTERMWIDGET_LIBRARY_NAME}" + COMPONENT Devel +) + +install(TARGETS ${QTERMWIDGET_LIBRARY_NAME} + DESTINATION "${CMAKE_INSTALL_LIBDIR}" + EXPORT "${QTERMWIDGET_LIBRARY_NAME}-targets" + LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}" + PUBLIC_HEADER + COMPONENT Runtime +) + +export(TARGETS ${QTERMWIDGET_LIBRARY_NAME} + FILE "${CMAKE_BINARY_DIR}/${QTERMWIDGET_LIBRARY_NAME}-targets.cmake" + EXPORT_LINK_INTERFACE_LIBRARIES +) +# end of main library + + +# example application +if(BUILD_EXAMPLE) + set(EXAMPLE_SRC examples/cpp/main.cpp) + add_executable(example ${EXAMPLE_SRC}) + target_link_libraries(example ${QTERMWIDGET_LIBRARY_NAME}) +endif() +# end of example application + +# python binding +if (QTERMWIDGET_BUILD_PYTHON_BINDING) + message(SEND_ERROR "QTERMWIDGET_BUILD_PYTHON_BINDING is no longer supported. Check README.md for how to build PyQt bindings.") +endif() +# end of python binding + + +CONFIGURE_FILE( + "${CMAKE_CURRENT_SOURCE_DIR}/cmake/cmake_uninstall.cmake.in" + "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake" + IMMEDIATE @ONLY +) +ADD_CUSTOM_TARGET(uninstall + "${CMAKE_COMMAND}" -P "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake" +) diff --git a/qtermwidget/CMakePresets.json b/qtermwidget/CMakePresets.json new file mode 100644 index 0000000..f5371d5 --- /dev/null +++ b/qtermwidget/CMakePresets.json @@ -0,0 +1,17 @@ +{ + "version": 2, + "configurePresets": [ + { + "name": "Default", + "displayName": "Configure preset using toolchain file", + "description": "Sets Ninja generator, build and install directory", + "generator": "Ninja", + "binaryDir": "${sourceDir}/out/build/${presetName}", + "cacheVariables": { + "CMAKE_BUILD_TYPE": "Debug", + "CMAKE_TOOLCHAIN_FILE": "", + "CMAKE_INSTALL_PREFIX": "${sourceDir}/out/install/${presetName}" + } + } + ] +} \ No newline at end of file diff --git a/qtermwidget/COPYING-CMAKE-SCRIPTS b/qtermwidget/COPYING-CMAKE-SCRIPTS new file mode 120000 index 0000000..37e4ca8 --- /dev/null +++ b/qtermwidget/COPYING-CMAKE-SCRIPTS @@ -0,0 +1 @@ +LICENSE.BSD-3-clause \ No newline at end of file diff --git a/qtermwidget/Changelog b/qtermwidget/Changelog deleted file mode 100644 index 291a3ff..0000000 --- a/qtermwidget/Changelog +++ /dev/null @@ -1,19 +0,0 @@ -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/qtermwidget/COPYING b/qtermwidget/LICENSE similarity index 82% rename from qtermwidget/COPYING rename to qtermwidget/LICENSE index 5b6e7c6..d8cf7d4 100644 --- a/qtermwidget/COPYING +++ b/qtermwidget/LICENSE @@ -1,12 +1,12 @@ - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 - Copyright (C) 1989, 1991 Free Software Foundation, Inc. - 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. - Preamble + Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public @@ -15,7 +15,7 @@ software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by -the GNU Library General Public License instead.) You can apply it to +the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not @@ -55,8 +55,8 @@ patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. - - GNU GENERAL PUBLIC LICENSE + + GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains @@ -110,7 +110,7 @@ above, provided that you also meet all of these conditions: License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) - + These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in @@ -168,7 +168,7 @@ access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. - + 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is @@ -225,7 +225,7 @@ impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. - + 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License @@ -255,7 +255,7 @@ make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. - NO WARRANTY + NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN @@ -277,64 +277,4 @@ YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: - - Gnomovision version 69, Copyright (C) year name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - , 1 April 1989 - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Library General -Public License instead of this License. + END OF TERMS AND CONDITIONS diff --git a/qtermwidget/LICENSE.BSD-3-clause b/qtermwidget/LICENSE.BSD-3-clause new file mode 100644 index 0000000..c7a0aa4 --- /dev/null +++ b/qtermwidget/LICENSE.BSD-3-clause @@ -0,0 +1,26 @@ +Copyright (c) The Regents of the University of California. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. diff --git a/qtermwidget/LICENSE.LGPL2+ b/qtermwidget/LICENSE.LGPL2+ new file mode 100644 index 0000000..5bc8fb2 --- /dev/null +++ b/qtermwidget/LICENSE.LGPL2+ @@ -0,0 +1,481 @@ + GNU LIBRARY GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1991 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the library GPL. It is + numbered 2 because it goes with version 2 of the ordinary GPL.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Library General Public License, applies to some +specially designated Free Software Foundation software, and to any +other libraries whose authors decide to use it. You can use it for +your libraries, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if +you distribute copies of the library, or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link a program with the library, you must provide +complete object files to the recipients so that they can relink them +with the library, after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + Our method of protecting your rights has two steps: (1) copyright +the library, and (2) offer you this license which gives you legal +permission to copy, distribute and/or modify the library. + + Also, for each distributor's protection, we want to make certain +that everyone understands that there is no warranty for this free +library. If the library is modified by someone else and passed on, we +want its recipients to know that what they have is not the original +version, so that any problems introduced by others will not reflect on +the original authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that companies distributing free +software will individually obtain patent licenses, thus in effect +transforming the program into proprietary software. To prevent this, +we have made it clear that any patent must be licensed for everyone's +free use or not licensed at all. + + Most GNU software, including some libraries, is covered by the ordinary +GNU General Public License, which was designed for utility programs. This +license, the GNU Library General Public License, applies to certain +designated libraries. This license is quite different from the ordinary +one; be sure to read it in full, and don't assume that anything in it is +the same as in the ordinary license. + + The reason we have a separate public license for some libraries is that +they blur the distinction we usually make between modifying or adding to a +program and simply using it. Linking a program with a library, without +changing the library, is in some sense simply using the library, and is +analogous to running a utility program or application program. However, in +a textual and legal sense, the linked executable is a combined work, a +derivative of the original library, and the ordinary General Public License +treats it as such. + + Because of this blurred distinction, using the ordinary General +Public License for libraries did not effectively promote software +sharing, because most developers did not use the libraries. We +concluded that weaker conditions might promote sharing better. + + However, unrestricted linking of non-free programs would deprive the +users of those programs of all benefit from the free status of the +libraries themselves. This Library General Public License is intended to +permit developers of non-free programs to use free libraries, while +preserving your freedom as a user of such programs to change the free +libraries that are incorporated in them. (We have not seen how to achieve +this as regards changes in header files, but we have achieved it as regards +changes in the actual functions of the Library.) The hope is that this +will lead to faster development of free libraries. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, while the latter only +works together with the library. + + Note that it is possible for a library to be covered by the ordinary +General Public License rather than by this special one. + + GNU LIBRARY GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library which +contains a notice placed by the copyright holder or other authorized +party saying it may be distributed under the terms of this Library +General Public License (also called "this License"). Each licensee is +addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also compile or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + c) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + d) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the source code distributed need not include anything that is normally +distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Library General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + 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; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! diff --git a/qtermwidget/README b/qtermwidget/README deleted file mode 100644 index 0d3228f..0000000 --- a/qtermwidget/README +++ /dev/null @@ -1,26 +0,0 @@ -This is a external source gotten from: - -http://www.qt-apps.org/content/show.php/QTermWidget?content=82832 - -************************************************************************************* -QTermWidget -version 0.1.0 - -QTermWidget is an opensource project based on KDE4 Konsole application. -The main goal of this project is to provide unicode-enabled, embeddable -QT widget for using as a built-in console (or terminal emulation widget). - -Of course I`m aware about embedding abilities of original Konsole, -but once I had Qt without KDE, and it was a serious obstacle. -I decided not to rely on a chance. I cannot find any interesting related project, -so I had to write it. - -The original Konsole`s code was rewritten entirely with QT4 only; also I have to -include in the project some parts of code from kde core library. All code dealing -with user interface parts and session managers was removed (maybe later I bring it -back somehow), and the result is quite useful, I suppose. - -This library was compiled and tested on three linux systems, -based on 2.4.32, 2.6.20, 2.6.23 kernels, x86 and amd64. -Please inform about its behaviour on other systems. - diff --git a/qtermwidget/README.md b/qtermwidget/README.md new file mode 100644 index 0000000..6cbeb17 --- /dev/null +++ b/qtermwidget/README.md @@ -0,0 +1,346 @@ +# QTermWidget + +## Overview + +A terminal emulator widget for Qt 5. + +QTermWidget is an open-source project originally based on the KDE4 Konsole application, but it took its own direction later on. +The main goal of this project is to provide a Unicode-enabled, embeddable Qt widget for using as a built-in console (or terminal emulation widget). + +It is compatible with BSD, Linux and OS X. + +This project is licensed under the terms of the [GPLv2](https://www.gnu.org/licenses/gpl-2.0.en.html) or any later version. See the LICENSE file for the full text of the license. Some files are published under compatible licenses: +``` +Files: example/main.cpp + lib/TerminalCharacterDecoder.cpp + lib/TerminalCharacterDecoder.h + lib/kprocess.cpp + lib/kprocess.h + lib/kpty.cpp + lib/kpty.h + lib/kpty_p.h + lib/kptydevice.cpp + lib/kptydevice.h + lib/kptyprocess.cpp + lib/kptyprocess.h + lib/qtermwidget.cpp + lib/qtermwidget.h + lib/qtermwidget_interface.h +Copyright: Author Adriaan de Groot + 2010, KDE e.V + 2002-2007, Oswald Buddenhagen + 2006-2008, Robert Knight + 2002, Waldo Bastian + 2008, e_k + 2022, Francesc Martinez +License: LGPL-2+ + +Files: cmake/FindUtf8Proc.cmake +Copyright: 2009-2011, Kitware, Inc + 2009-2011, Philip Lowman +License: BSD-3-clause +``` + +## Installation + +### Compiling sources + +The only runtime dependency is qtbase ≥ 5.12.0. +Build dependencies are as follows: +- CMake ≥ 3.1.0 serves as the build system and therefore needs to be present to compile. +- The latest [lxqt-build-tools](https://github.com/lxqt/lxqt-build-tools/) is also needed for compilation. +- Git is needed to optionally pull latest VCS checkouts. + +Code configuration is handled by CMake. CMake variable `CMAKE_INSTALL_PREFIX` will normally have to be set to `/usr`, depending on the way library paths are dealt with on 64bit systems. Variables like `CMAKE_INSTALL_LIBDIR` may have to be set as well. + +To build, run `make`. To install, run `make install` which accepts variable `DESTDIR` as usual. + +To build PyQt bindings, build this library first, and then invoke `sip-wheel` in pyqt/ directory. Environment variables `CXXFLAGS` and `LDFLAGS` can be used to specify non-installed or non-standard directories for headers and shared libraries, and the built Python wheel can be installed by standard tools like `pip`. See [the CI script](.ci/build.sh) for a complete example. + +### Binary packages + +The library is provided by all major Linux distributions. This includes Arch Linux, Debian, Fedora, openSUSE and all of their children, given they use the same package repositories. +Just use the distributions' package managers to search for string `qtermwidget`. + + +### Translation + +Translations can be done in [LXQt-Weblate](https://translate.lxqt-project.org/projects/lxqt-desktop/qtermwidget/) + + +Translation status + + +## API +### Public Types +Type | Variable +| ---: | :--- +enum | ScrollBarPosition { NoScrollBar, ScrollBarLeft, ScrollBarRight } +enum | KeyboardCursorShape { BlockCursor, UnderlineCursor, IBeamCursor } + +### Properties +* flowControlEnabled : bool +* getPtySlaveFd : const int +* getShellPID : int +* getForegroundProcessId : int +* getTerminalFont : QFont +* historyLinesCount : int +* icon : const QString +* keyBindings : QString +* screenColumnsCount : int +* selectedText(bool _preserveLineBreaks_ = true) : QString +* sizeHint : const QSize +* terminalSizeHint : bool +* title : const QString +* workingDirectory : QString + +### Public Functions +Type | Function +| ---: | :--- +| | QTermWidget(int _startnow_ = 1, QWidget *_parent_ = 0) +virtual | ~QTermWidget() +void | changeDir(const QString _&dir_) +void | getSelectionEnd(int &_row_, int &_column_) +void | getSelectionStart(int &_row_, int &_column_) +void | scrollToEnd() +void | sendText(QString &_text_) +void | setArgs(QStringList &_args_) +void | setAutoClose(bool _enabled_) +void | setColorScheme(const QString &_name_) +void | setEnvironment(const QStringList &_environment_) +void | setFlowControlEnabled(bool _enabled_) +void | setFlowControlWarningEnabled(bool _enabled_) +void | setHistorySize(int _lines_) +void | setKeyboardCursorShape(QTermWidget::KeyboardCursorShape _shape_) +void | setMonitorActivity(bool _enabled_) +void | setMonitorSilence(bool _enabled_) +void | setMotionAfterPasting(int _action_) +void | setScrollBarPosition(QTermWidget::ScrollBarPosition _pos_) +void | setSelectionEnd(int _row_, int _column_) +void | setSelectionStart(int _row_, int _column_) +void | setShellProgram(const QString &_program_) +void | setSilenceTimeout(int _seconds_) +void | setTerminalFont(QFont &_font_) +void | setTerminalOpacity(qreal _level_) +void | setTerminalSizeHint(bool _enabled_) +void | setTextCodec(QTextCodec *_codec_) +void | setWorkingDirectory(const QString &_dir_) +void | startShellProgram() +void | startTerminalTeletype() +QStringList | availableColorSchemes() + +### Public Slots +Type | Function +| ---: | :--- +void | copyClipboard() +void | pasteClipboard() +void | pasteSelection() +void | zoomIn() +void | zoomOut() +void | setSize(_const QSize &_) +void | setKeyBindings(const QString &_kb_) +void | clear() +void | toggleShowSearchBar() + +### Signals +Type | Function +| ---: | :--- +void | activity() +void | bell(const QString &_message_) +void | copyAvailable(bool) +void | finished() +void | profileChanged(const QString &_profile_) +void | receivedData(const QString &_text_) +void | sendData(const char*, int) +void | silence() +void | termGetFocus() +void | termKeyPressed(QKeyEvent*) +void | termLostFocus() +void | titleChanged() +void | urlActivated(const QUrl &, bool _fromContextMenu_) + +### Static Public Members +Type | Function +| ---: | :--- +static QStringList | availableColorSchemes() +static QStringList | availableKeyBindings() +static void | addCustomColorSchemeDir(const QString &*custom_dir*) + +### Protected Functions +Type | Function +| ---: | :--- +virtual void | resizeEvent(_QResizeEvent_*) + +### Protected Slots +Type | Function +| ---: | :--- +void | sessionFinished() +void | selectionChanged(bool _textSelected_) + +### Member Type Documentation +**enum QTermWidget::ScrollBarPosition**\ +This enum describes the location where the scroll bar is positioned in the display widget when calling QTermWidget::setScrollBarPosition(). + +Constant | Value | Description +| --- | :---: | --- | +QTermWidget::NoScrollBar | 0x0 | Do not show the scroll bar. +QTermWidget::ScrollBarLeft | 0x1 | Show the scroll bar on the left side of the display. +QTermWidget::ScrollBarRight | 0x2 | Show the scroll bar on the right side of the display. + +\ +**enum QTermWidget::KeyboardCursorShape**\ +This enum describes the available shapes for the keyboard cursor when calling QTermWidget::setKeyboardCursorShape(). + +Constant | Value | Description +| --- | :---: | --- | +QTermWidget::BlockCursor | 0x0 | A rectangular block which covers the entire area of the cursor character. +QTermWidget::UnderlineCursor | 0x1 | A single flat line which occupies the space at the bottom of the cursor character's area. +QTermWidget::IBeamCursor | 0x2 | A cursor shaped like the capital letter 'I', similar to the IBeam cursor used in Qt/KDE text editors. + +### Property Documentation +**flowControlEnabled : bool**\ +Returns whether flow control is enabled. + +**getPtySlaveFd : const int**\ +Returns a pty slave file descriptor. This can be used for display and control a remote terminal. + + +**getForegroundProcessId : int**\ +Returns the PID of the foreground process. This is initially the same as processId() but can change +as the user starts other programs inside the terminal. If there is a problem reading the foreground +process id, 0 will be returned. + + + +**historyLinesCount : int**\ +Returns the number of lines in the history buffer. + + + +**keyBindings : QString**\ +Returns current key bindings. + + + +**selectedText(bool _preserveLineBreaks_ = true) : QString**\ +Returns the currently selected text. + + + + + + +### Member Function Documentation + + + +__void changeDir(const QString _&dir_)__\ +Attempt to change shell directory (Linux only). + +__void clear()__\ +Clear the terminal content and move to home position. + + + +__void copyClipboard()__\ +Copy selection to clipboard. + + + + + +__void pasteClipboard()__\ +Paste clipboard to terminal. + +__void pasteSelection()__\ +Paste selection to terminal. + + + +__void receivedData(const QString &_text_)__\ +Signals that we received new data from the process running in the terminal emulator. + +__void scrollToEnd()__\ +Wrapped, scroll to end of text. + +__void sendData(const char*, int)__\ +Emitted when emulator send data to the terminal process (redirected for external recipient). It can be used for control and display the remote terminal. + +__void sendText(QString &_text_)__\ +Send text to terminal. + +__void setArgs(QStringList &_args_)__\ +Sets the shell program arguments, default is none. + +__void setAutoClose(bool _enabled_)__\ +Automatically close the terminal session after the shell process exits or keep it running. + +__void setColorScheme(const QString &_name_)__\ +Sets the color scheme, default is white on black. + +__void setEnvironment(const QStringList &_environment_)__\ +Sets environment variables. + +__void setFlowControlEnabled(bool _enabled_)__\ +Sets whether flow control is enabled. + +__void setFlowControlWarningEnabled(bool _enabled_)__\ +Sets whether the flow control warning box should be shown when the flow control stop key (Ctrl+S) is pressed. + +__void setHistorySize(int _lines_)__\ +History size for scrolling. + +__void setKeyBindings(const QString &_kb_)__\ +Set named key binding for given widget. + +__void setKeyboardCursorShape(QTermWidget::KeyboardCursorShape _shape_)__\ +Sets the shape of the keyboard cursor. This is the cursor drawn at the position in the terminal where keyboard input will appear. + + + + + +__void setScrollBarPosition(QTermWidget::ScrollBarPosition _pos_)__\ +Sets presence and position of scrollbar. + + + + +__void setShellProgram(const QString &_program_)__\ +Sets the shell program, default is /bin/bash. + + + + +__void setTerminalFont(QFont &_font_)__\ +Sets terminal font. Default is application font with family Monospace, size 10. Beware of a performance penalty and display/alignment issues when using a proportional font. + + + +__void setTerminalSizeHint(bool _enabled_)__\ +Exposes TerminalDisplay::TerminalSizeHint. + +__void setTextCodec(QTextCodec *_codec_)__\ +Sets text codec, default is UTF-8. + + + + +__void startShellProgram()__\ +Starts shell program if it was not started in constructor. + +__void startTerminalTeletype()__\ +Starts terminal teletype as is and redirect data for external recipient. It can be used for display and control a remote terminal. + + + + + + + + +__void zoomIn()__\ +Zooms in on the text. + +__void zoomOut()__\ +Zooms out in on the text. diff --git a/qtermwidget/TODO b/qtermwidget/TODO deleted file mode 100644 index c3cb62c..0000000 --- a/qtermwidget/TODO +++ /dev/null @@ -1,10 +0,0 @@ -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/qtermwidget/cmake/FindUtf8Proc.cmake b/qtermwidget/cmake/FindUtf8Proc.cmake new file mode 100644 index 0000000..8e0d1af --- /dev/null +++ b/qtermwidget/cmake/FindUtf8Proc.cmake @@ -0,0 +1,60 @@ +#.rst: +# FindUtf8Proc +# -------- +# +# Find utf8proc +# +# Find the UTF-8 processing library +# +# :: +# +# This module defines the following variables: +# UTF8PROC_FOUND - True if UTF8PROC_INCLUDE_DIR & UTF8PROC_LIBRARY are found +# UTF8PROC_LIBRARIES - Set when UTF8PROC_LIBRARY is found +# UTF8PROC_INCLUDE_DIRS - Set when UTF8PROC_INCLUDE_DIR is found +# +# +# +# :: +# +# UTF8PROC_INCLUDE_DIR - where to find utf8proc.h +# UTF8PROC_LIBRARY - the utf8proc library + +#============================================================================= +# This module is adapted from FindALSA.cmake. Below are the original license +# header. +#============================================================================= +# Copyright 2009-2011 Kitware, Inc. +# Copyright 2009-2011 Philip Lowman +# +# Distributed under the OSI-approved BSD License (the "License"); +# see accompanying file Copyright.txt for details. +# +# This software is distributed WITHOUT ANY WARRANTY; without even the +# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +# See the License for more information. +#============================================================================= + +find_path( + UTF8PROC_INCLUDE_DIR NAMES utf8proc.h DOC "The utf8proc include directory" +) + +find_library( + UTF8PROC_LIBRARY NAMES utf8proc DOC "The utf8proc library" +) + +# handle the QUIETLY and REQUIRED arguments and set UTF8PROC_FOUND to TRUE if +# all listed variables are TRUE +include(FindPackageHandleStandardArgs) +FIND_PACKAGE_HANDLE_STANDARD_ARGS( + Utf8Proc + FOUND_VAR Utf8Proc_FOUND + REQUIRED_VARS UTF8PROC_LIBRARY UTF8PROC_INCLUDE_DIR +) + +if(Utf8Proc_FOUND) + set( UTF8PROC_LIBRARIES ${UTF8PROC_LIBRARY} ) + set( UTF8PROC_INCLUDE_DIRS ${UTF8PROC_INCLUDE_DIR} ) +endif() + +mark_as_advanced(UTF8PROC_INCLUDE_DIR UTF8PROC_LIBRARY) diff --git a/qtermwidget/cmake/cmake_uninstall.cmake.in b/qtermwidget/cmake/cmake_uninstall.cmake.in new file mode 100644 index 0000000..02cb12d --- /dev/null +++ b/qtermwidget/cmake/cmake_uninstall.cmake.in @@ -0,0 +1,23 @@ +IF(NOT EXISTS "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt") + MESSAGE(FATAL_ERROR "Cannot find install manifest: \"@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt\"") +ENDIF(NOT EXISTS "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt") + +# this works on Linux, but not on mac. +#FILE(READ "@CMAKE_CURRENT_BINARY_DIR@/install_manifest.txt" files) +#STRING(REGEX REPLACE "\n" ";" files "${files}") +#FOREACH(file ${files}) +# MESSAGE(STATUS "Uninstalling \"${file}\"") +# IF(NOT EXISTS "${file}") +# MESSAGE(FATAL_ERROR "File \"${file}\" does not exists.") +# ENDIF(NOT EXISTS "${file}") +# EXEC_PROGRAM("@CMAKE_COMMAND@" ARGS "-E remove \"${file}\"" +# OUTPUT_VARIABLE rm_out +# RETURN_VARIABLE rm_retval) +# IF("${rm_retval}" GREATER 0) +# MESSAGE(FATAL_ERROR "Problem when removing \"${file}\"") +# ENDIF("${rm_retval}" GREATER 0) +#ENDFOREACH(file) + +EXEC_PROGRAM("xargs rm < @CMAKE_BINARY_DIR@/install_manifest.txt" + OUTPUT_VARIABLE rm_out + RETURN_VARIABLE rm_ret) diff --git a/qtermwidget/cmake/qtermwidget5-config.cmake.in b/qtermwidget/cmake/qtermwidget5-config.cmake.in new file mode 100644 index 0000000..db62356 --- /dev/null +++ b/qtermwidget/cmake/qtermwidget5-config.cmake.in @@ -0,0 +1,20 @@ +# - Find the QTermWidget include and library +# +# Typical usage: +# find_package(QTermWidget5 REQUIRED) +# +# add_executable(foo main.cpp) +# target_link_libraries(foo qtermwidget5) + +@PACKAGE_INIT@ + +if (CMAKE_VERSION VERSION_LESS 3.0.2) + message(FATAL_ERROR \"qtermwidget requires at least CMake version 3.0.2\") +endif() + +if (NOT TARGET @QTERMWIDGET_LIBRARY_NAME@) + if (POLICY CMP0024) + cmake_policy(SET CMP0024 NEW) + endif() + include("${CMAKE_CURRENT_LIST_DIR}/@QTERMWIDGET_LIBRARY_NAME@-targets.cmake") +endif() diff --git a/qtermwidget/cmake/qtermwidget6-config.cmake.in b/qtermwidget/cmake/qtermwidget6-config.cmake.in new file mode 100644 index 0000000..db62356 --- /dev/null +++ b/qtermwidget/cmake/qtermwidget6-config.cmake.in @@ -0,0 +1,20 @@ +# - Find the QTermWidget include and library +# +# Typical usage: +# find_package(QTermWidget5 REQUIRED) +# +# add_executable(foo main.cpp) +# target_link_libraries(foo qtermwidget5) + +@PACKAGE_INIT@ + +if (CMAKE_VERSION VERSION_LESS 3.0.2) + message(FATAL_ERROR \"qtermwidget requires at least CMake version 3.0.2\") +endif() + +if (NOT TARGET @QTERMWIDGET_LIBRARY_NAME@) + if (POLICY CMP0024) + cmake_policy(SET CMP0024 NEW) + endif() + include("${CMAKE_CURRENT_LIST_DIR}/@QTERMWIDGET_LIBRARY_NAME@-targets.cmake") +endif() diff --git a/qtermwidget/docs/configuration.md b/qtermwidget/docs/configuration.md new file mode 100644 index 0000000..4950009 --- /dev/null +++ b/qtermwidget/docs/configuration.md @@ -0,0 +1,20 @@ +# Migration for background images + +How the background image is drawn has been changed since version 0.17. +Intuitively, the background image is now drawn above the background color instead of below it. +Technically, the background image is no longer blended with the background color. + +Any background image can be used but, of course, it should be chosen so that the terminal text can be easily read on it. +Since an image may not be totally dark or light, you might want to use a translucent image as the background. +As a result, the background image is mixed with the background color to improve readability. +Opaque images can also be converted to translucent ones with a few steps. + +A common usage is an effect similar to previous qtermwidget versions or other terminal emulators. +To achieve that, you can convert the background image to a translucent one with the transparency level matching the original terminal transparency. +For example, if the original terminal transparency of qtermwidget was 25% (or 75% in some other terminal emulators), a converted image with transparency 25% will work as usual. +The conversion can be done via ImageMagick, GraphicsMagick, GIMP or Krita. +Here is an example command using ImageMagick: + + $ convert original_image.jpg -matte -channel A +level 0,25% +channel translucent_image.png + +You may also want to change the terminal transparency to 0% if you do not want to see another window or the desktop below the terminal. diff --git a/qtermwidget/examples/README b/qtermwidget/examples/README new file mode 100644 index 0000000..a985b57 --- /dev/null +++ b/qtermwidget/examples/README @@ -0,0 +1 @@ +Here are two sample programs which use QTermWidget for displaying a terminal diff --git a/qtermwidget/examples/cpp/RemoteTerm/README.md b/qtermwidget/examples/cpp/RemoteTerm/README.md new file mode 100644 index 0000000..065ee8c --- /dev/null +++ b/qtermwidget/examples/cpp/RemoteTerm/README.md @@ -0,0 +1,8 @@ +A simple example showing how to use QTermWidget to control and display a remote terminal. + +To run this example, you should: +1. Build client-side program. In my PC, I use 'apt-get' to install the QTermWidget library. +2. Start the shell-srv.py with specific parameters.This will expose a shell via socket. +3. Start the client-side program from commandline with specific parameters. + +Now you will get your own remote terminal work with QTermWidget. \ No newline at end of file diff --git a/qtermwidget/examples/cpp/RemoteTerm/RemoteTerm.pro b/qtermwidget/examples/cpp/RemoteTerm/RemoteTerm.pro new file mode 100644 index 0000000..21c36f7 --- /dev/null +++ b/qtermwidget/examples/cpp/RemoteTerm/RemoteTerm.pro @@ -0,0 +1,34 @@ +#------------------------------------------------- +# +# Project created by QtCreator 2017-10-31T00:37:59 +# +#------------------------------------------------- + +QT += core gui network + +greaterThan(QT_MAJOR_VERSION, 4): QT += widgets + +TARGET = RemoteTerm +TEMPLATE = app + +# The following define makes your compiler emit warnings if you use +# any feature of Qt which as been marked as deprecated (the exact warnings +# depend on your compiler). Please consult the documentation of the +# deprecated API in order to know how to port your code away from it. +DEFINES += QT_DEPRECATED_WARNINGS + +# You can also make your code fail to compile if you use deprecated APIs. +# In order to do so, uncomment the following line. +# You can also select to disable deprecated APIs only up to a certain version of Qt. +#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 + +CONFIG += c++11 + +SOURCES += \ + main.cpp \ + remoteterm.cpp + +HEADERS += \ + remoteterm.h + +unix:!macx: LIBS += -lqtermwidget5 diff --git a/qtermwidget/examples/cpp/RemoteTerm/main.cpp b/qtermwidget/examples/cpp/RemoteTerm/main.cpp new file mode 100644 index 0000000..f51df3a --- /dev/null +++ b/qtermwidget/examples/cpp/RemoteTerm/main.cpp @@ -0,0 +1,19 @@ +#include "remoteterm.h" +#include +#include + +int main(int argc, char *argv[]) +{ + QApplication a(argc, argv); + if(a.arguments().size() != 3){ + qDebug() << "Example(client-side) for remote terminal of QTermWidget."; + qDebug() << QString("Usage: %1 ipaddr port").arg(a.arguments()[0]); + return 1; + } + QString ipaddr = a.arguments().at(1); + quint16 port = a.arguments().at(2).toUShort(); + RemoteTerm w(ipaddr,port); + w.show(); + + return a.exec(); +} diff --git a/qtermwidget/examples/cpp/RemoteTerm/remoteterm.cpp b/qtermwidget/examples/cpp/RemoteTerm/remoteterm.cpp new file mode 100644 index 0000000..551ac25 --- /dev/null +++ b/qtermwidget/examples/cpp/RemoteTerm/remoteterm.cpp @@ -0,0 +1,32 @@ +#include "remoteterm.h" +#include +#include +#include + +RemoteTerm::RemoteTerm(const QString &ipaddr, quint16 port, QWidget *parent) + : QTermWidget(0,parent) +{ + socket = new QTcpSocket(this); + + // Write what we input to remote terminal via socket + connect(this, &RemoteTerm::sendData,[this](const char *data, int size){ + this->socket->write(data, size); + }); + + // Read anything from remote terminal via socket and show it on widget. + connect(socket,&QTcpSocket::readyRead,[this](){ + QByteArray data = socket->readAll(); + write(this->getPtySlaveFd(), data.data(), data.size()); + }); + connect(socket, SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(atError())); + + // Here we start an empty pty. + this->startTerminalTeletype(); + + socket->connectToHost(ipaddr, port); +} + +void RemoteTerm::atError() +{ + qDebug() << socket->errorString(); +} diff --git a/qtermwidget/examples/cpp/RemoteTerm/remoteterm.h b/qtermwidget/examples/cpp/RemoteTerm/remoteterm.h new file mode 100644 index 0000000..c591ec4 --- /dev/null +++ b/qtermwidget/examples/cpp/RemoteTerm/remoteterm.h @@ -0,0 +1,19 @@ +#ifndef WIDGET_H +#define WIDGET_H + +#include + +class QTcpSocket; + +class RemoteTerm : public QTermWidget +{ + Q_OBJECT +public: + RemoteTerm(const QString &ipaddr, quint16 port, QWidget *parent = 0); +public slots: + void atError(); +private: + QTcpSocket *socket; +}; + +#endif // WIDGET_H diff --git a/qtermwidget/examples/cpp/RemoteTerm/shell-srv.py b/qtermwidget/examples/cpp/RemoteTerm/shell-srv.py new file mode 100644 index 0000000..dc0cb62 --- /dev/null +++ b/qtermwidget/examples/cpp/RemoteTerm/shell-srv.py @@ -0,0 +1,37 @@ +#!/usr/bin/env python + +import sys +import os +import socket +import pty + +def usage(program): + print "Example(server-side) for remote terminal of QTermWidget." + print "Usage: %s ipaddr port" %program + + +def main(): + if len(sys.argv) != 3: + usage(sys.argv[0]) + sys.exit(1) + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + try: + s.bind((sys.argv[1], int(sys.argv[2]))) + s.listen(0) + print "[+]Start Server." + except Exception as e: + print "[-]Error Happened: %s" %e.message + sys.exit(2) + + while True: + c = s.accept() + os.dup2(c[0].fileno(), 0) + os.dup2(c[0].fileno(), 1) + os.dup2(c[0].fileno(), 2) + + # It's important to use pty to spawn the shell. + pty.spawn("/bin/sh") + c[0].close() + +if __name__ == "__main__": + main() diff --git a/qtermwidget/examples/cpp/main.cpp b/qtermwidget/examples/cpp/main.cpp new file mode 100644 index 0000000..dc1b8d2 --- /dev/null +++ b/qtermwidget/examples/cpp/main.cpp @@ -0,0 +1,87 @@ +/* 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 +#include +#include +#include +#include + +#include "qtermwidget.h" + +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + QIcon::setThemeName(QStringLiteral("oxygen")); + QMainWindow *mainWindow = new QMainWindow(); + + QTermWidget *console = new QTermWidget(); + + QMenuBar *menuBar = new QMenuBar(mainWindow); + QMenu *actionsMenu = new QMenu(QStringLiteral("Actions"), menuBar); + menuBar->addMenu(actionsMenu); + actionsMenu->addAction(QStringLiteral("Find..."), console, &QTermWidget::toggleShowSearchBar, + QKeySequence(QLatin1String("Ctrl+Shift+F"))); + actionsMenu->addAction(QStringLiteral("Copy"), console, &QTermWidget::copyClipboard, + QKeySequence(QLatin1String("Ctrl+Shift+C"))); + actionsMenu->addAction(QStringLiteral("Paste"), console, &QTermWidget::pasteClipboard, + QKeySequence(QLatin1String("Ctrl+Shift+V"))); + actionsMenu->addAction(QStringLiteral("About Qt"), &app, &QApplication::aboutQt); + mainWindow->setMenuBar(menuBar); + + QFont font = QApplication::font(); +#ifdef Q_OS_MACOS + font.setFamily(QStringLiteral("Monaco")); +#elif defined(Q_WS_QWS) + font.setFamily(QStringLiteral("fixed")); +#else + font.setFamily(QStringLiteral("Monospace")); +#endif + font.setPointSize(12); + + console->setTerminalFont(font); + + // console->setColorScheme(COLOR_SCHEME_BLACK_ON_LIGHT_YELLOW); + console->setScrollBarPosition(QTermWidget::ScrollBarRight); + + const auto arguments = QApplication::arguments(); + for (const QString& arg : arguments) + { + if (console->availableColorSchemes().contains(arg)) + console->setColorScheme(arg); + if (console->availableKeyBindings().contains(arg)) + console->setKeyBindings(arg); + } + + mainWindow->setCentralWidget(console); + mainWindow->resize(600, 400); + + // info output + qDebug() << "* INFO *************************"; + qDebug() << " availableKeyBindings:" << console->availableKeyBindings(); + qDebug() << " keyBindings:" << console->keyBindings(); + qDebug() << " availableColorSchemes:" << console->availableColorSchemes(); + qDebug() << "* INFO END *********************"; + + // real startup + QObject::connect(console, &QTermWidget::finished, mainWindow, &QMainWindow::close); + + mainWindow->show(); + return app.exec(); +} diff --git a/qtermwidget/examples/pyqt/main.py b/qtermwidget/examples/pyqt/main.py new file mode 100755 index 0000000..5d5a8ef --- /dev/null +++ b/qtermwidget/examples/pyqt/main.py @@ -0,0 +1,22 @@ +#!/usr/bin/python3 +from PyQt5 import QtWidgets +from QTermWidget import QTermWidget + + +class Terminal(QTermWidget): + def __init__(self, process: str, args: list): + super().__init__(0) + self.finished.connect(self.close) + self.setTerminalSizeHint(False) + self.setColorScheme("DarkPastels") + self.setShellProgram(process) + self.setArgs(args) + self.startShellProgram() + self.show() + + +if __name__ == "__main__": + app = QtWidgets.QApplication([]) + args = ["--clean", "--noplugin"] + term = Terminal("vim", args) + app.exec() diff --git a/qtermwidget/src/BlockArray.cpp b/qtermwidget/lib/BlockArray.cpp similarity index 67% rename from qtermwidget/src/BlockArray.cpp rename to qtermwidget/lib/BlockArray.cpp index 39ef499..db9e645 100644 --- a/qtermwidget/src/BlockArray.cpp +++ b/qtermwidget/lib/BlockArray.cpp @@ -21,17 +21,16 @@ */ +#include + // Own #include "BlockArray.h" -#include - // System -#include #include #include #include -#include +#include using namespace Konsole; @@ -39,40 +38,56 @@ 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) + : size(0), + current(size_t(-1)), + index(size_t(-1)), + lastmap(nullptr), + lastmap_index(size_t(-1)), + lastblock(nullptr), ion(-1), + length(0) { // lastmap_index = index = current = size_t(-1); - if (blocksize == 0) + if (blocksize == 0) { blocksize = ((sizeof(Block) / getpagesize()) + 1) * getpagesize(); + } } BlockArray::~BlockArray() { setHistorySize(0); - assert(!lastblock); + Q_ASSERT(!lastblock); } -size_t BlockArray::append(Block *block) +size_t BlockArray::append(Block * block) { - if (!size) + if (!size) { return size_t(-1); + } ++current; - if (current >= size) current = 0; + 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); } + 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; + if (length > size) { + length = size; + } ++index; @@ -82,44 +97,50 @@ size_t BlockArray::append(Block *block) size_t BlockArray::newBlock() { - if (!size) + if (!size) { return size_t(-1); + } append(lastblock); lastblock = new Block(); return index + 1; } -Block *BlockArray::lastBlock() const +Block * BlockArray::lastBlock() const { return lastblock; } bool BlockArray::has(size_t i) const { - if (i == index + 1) + if (i == index + 1) { return true; + } - if (i > index) + if (i > index) { return false; - if (index - i >= length) + } + if (index - i >= length) { return false; + } return true; } -const Block* BlockArray::at(size_t i) +const Block * BlockArray::at(size_t i) { - if (i == index + 1) + if (i == index + 1) { return lastblock; + } - if (i == lastmap_index) + if (i == lastmap_index) { return lastmap; + } if (i > index) { qDebug() << "BlockArray::at() i > index\n"; - return 0; + return nullptr; } - + // if (index - i >= length) { // kDebug(1211) << "BlockArray::at() index - i >= length\n"; // return 0; @@ -127,12 +148,15 @@ const Block* BlockArray::at(size_t i) size_t j = i; // (current - (index - i) + (index/size+1)*size) % size ; - assert(j < size); + Q_ASSERT(j < size); unmap(); - Block *block = (Block*)mmap(0, blocksize, PROT_READ, MAP_PRIVATE, ion, j * blocksize); + Block * block = (Block *)mmap(nullptr, blocksize, PROT_READ, MAP_PRIVATE, ion, j * blocksize); - if (block == (Block*)-1) { perror("mmap"); return 0; } + if (block == (Block *)-1) { + perror("mmap"); + return nullptr; + } lastmap = block; lastmap_index = i; @@ -143,10 +167,12 @@ const Block* BlockArray::at(size_t i) void BlockArray::unmap() { if (lastmap) { - int res = munmap((char*)lastmap, blocksize); - if (res < 0) perror("munmap"); + int res = munmap((char *)lastmap, blocksize); + if (res < 0) { + perror("munmap"); + } } - lastmap = 0; + lastmap = nullptr; lastmap_index = size_t(-1); } @@ -159,22 +185,25 @@ bool BlockArray::setHistorySize(size_t newsize) { // kDebug(1211) << "setHistorySize " << size << " " << newsize; - if (size == newsize) + if (size == newsize) { return false; + } unmap(); if (!newsize) { delete lastblock; - lastblock = 0; - if (ion >= 0) close(ion); + lastblock = nullptr; + if (ion >= 0) { + close(ion); + } ion = -1; current = size_t(-1); return true; } if (!size) { - FILE* tmp = tmpfile(); + FILE * tmp = tmpfile(); if (!tmp) { perror("konsole: cannot open temp file.\n"); } else { @@ -184,10 +213,11 @@ bool BlockArray::setHistorySize(size_t newsize) fclose(tmp); } } - if (ion < 0) + if (ion < 0) { return false; + } - assert(!lastblock); + Q_ASSERT(!lastblock); lastblock = new Block(); size = newsize; @@ -207,38 +237,44 @@ bool BlockArray::setHistorySize(size_t newsize) } } -void moveBlock(FILE *fion, int cursor, int newpos, char *buffer2) +void moveBlock(FILE * fion, int cursor, int newpos, char * buffer2) { int res = fseek(fion, cursor * blocksize, SEEK_SET); - if (res) + if (res) { perror("fseek"); + } res = fread(buffer2, blocksize, 1, fion); - if (res != 1) + if (res != 1) { perror("fread"); + } res = fseek(fion, newpos * blocksize, SEEK_SET); - if (res) + if (res) { perror("fseek"); + } res = fwrite(buffer2, blocksize, 1, fion); - if (res != 1) + 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 + if (index < newsize) { // still fits in whole return; + } int offset = (current - (newsize - 1) + size) % size; - if (!offset) + if (!offset) { return; + } - // The Block constructor could do somthing in future... - char *buffer1 = new char[blocksize]; + // The Block constructor could do something in future... + char * buffer1 = new char[blocksize]; - FILE *fion = fdopen(dup(ion), "w+b"); + FILE * fion = fdopen(dup(ion), "w+b"); if (!fion) { delete [] buffer1; perror("fdopen/dup"); @@ -258,8 +294,9 @@ void BlockArray::decreaseBuffer(size_t newsize) moveBlock(fion, oldpos, cursor, buffer1); if (oldpos < newsize) { cursor = oldpos; - } else + } else { cursor++; + } } current = newsize - 1; @@ -273,16 +310,18 @@ void BlockArray::decreaseBuffer(size_t newsize) void BlockArray::increaseBuffer() { - if (index < size) // not even wrapped once + if (index < size) { // not even wrapped once return; + } int offset = (current + size + 1) % size; - if (!offset) // no moving needed + if (!offset) { // no moving needed return; + } - // The Block constructor could do somthing in future... - char *buffer1 = new char[blocksize]; - char *buffer2 = new char[blocksize]; + // The Block constructor could do something in future... + char * buffer1 = new char[blocksize]; + char * buffer2 = new char[blocksize]; int runs = 1; int bpr = size; // blocks per run @@ -292,38 +331,40 @@ void BlockArray::increaseBuffer() runs = offset; } - FILE *fion = fdopen(dup(ion), "w+b"); + FILE * fion = fdopen(dup(ion), "w+b"); if (!fion) { perror("fdopen/dup"); - delete [] buffer1; - delete [] buffer2; + delete [] buffer1; + delete [] buffer2; return; } int res; - for (int i = 0; i < runs; i++) - { + 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) + if (res) { perror("fseek"); + } res = fread(buffer1, blocksize, 1, fion); - if (res != 1) + if (res != 1) { perror("fread"); + } int newpos = 0; - for (int j = 1, cursor=firstblock; j < bpr; j++) - { + 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) + if (res) { perror("fseek"); + } res = fwrite(buffer1, blocksize, 1, fion); - if (res != 1) + if (res != 1) { perror("fwrite"); + } } current = size - 1; length = size; diff --git a/qtermwidget/src/BlockArray.h b/qtermwidget/lib/BlockArray.h similarity index 82% rename from qtermwidget/src/BlockArray.h rename to qtermwidget/lib/BlockArray.h index ca47388..09158bd 100644 --- a/qtermwidget/src/BlockArray.h +++ b/qtermwidget/lib/BlockArray.h @@ -1,7 +1,7 @@ /* This file is part of Konsole, an X terminal. Copyright (C) 2000 by Stephan Kulow - + Rewritten for QT4 by e_k , Copyright (C)2008 This program is free software; you can redistribute it and/or modify @@ -27,14 +27,15 @@ //#error Do not use in KDE 2.1 -#define BlockSize (1 << 12) -#define ENTRIES ((BlockSize - sizeof(size_t) ) / sizeof(unsigned char)) +#define QTERMWIDGET_BLOCKSIZE (1 << 12) +#define ENTRIES ((QTERMWIDGET_BLOCKSIZE - sizeof(size_t) ) / sizeof(unsigned char)) -namespace Konsole -{ +namespace Konsole { struct Block { - Block() { size = 0; } + Block() { + size = 0; + } unsigned char data[ENTRIES]; size_t size; }; @@ -58,24 +59,24 @@ public: * adds the Block at the end of history. * This may drop other blocks. * - * The ownership on the block is transfered. + * The ownership on the block is transferred. * An unique index number is returned for accessing * it later (if not yet dropped then) * * Note, that the block may be dropped completely * if history is turned off. */ - size_t append(Block *block); + size_t append(Block * block); /** * gets the block at the index. Function may return * 0 if the block isn't available any more. * * The returned block is strictly readonly as only - * maped in memory - and will be invalid on the next + * mapped in memory - and will be invalid on the next * operation on this class. */ - const Block *at(size_t index); + const Block * at(size_t index); /** * reorders blocks as needed. If newsize is null, @@ -87,7 +88,7 @@ public: size_t newBlock(); - Block *lastBlock() const; + Block * lastBlock() const; /** * Convenient function to set the size in KBytes @@ -95,11 +96,15 @@ public: */ bool setSize(size_t newsize); - size_t len() const { return length; } + size_t len() const { + return length; + } bool has(size_t index) const; - size_t getCurrent() const { return current; } + size_t getCurrent() const { + return current; + } private: void unmap(); @@ -111,9 +116,9 @@ private: size_t current; size_t index; - Block *lastmap; + Block * lastmap; size_t lastmap_index; - Block *lastblock; + Block * lastblock; int ion; size_t length; diff --git a/qtermwidget/src/Character.h b/qtermwidget/lib/Character.h similarity index 74% rename from qtermwidget/src/Character.h rename to qtermwidget/lib/Character.h index 0978ce5..c6e8362 100644 --- a/qtermwidget/src/Character.h +++ b/qtermwidget/lib/Character.h @@ -1,10 +1,8 @@ /* This file is part of Konsole, KDE's terminal. - - Copyright (C) 2007 by Robert Knight - Copyright (C) 1997,1998 by Lars Doelle - Rewritten for QT4 by e_k , Copyright (C)2008 + Copyright 2007-2008 by Robert Knight + Copyright 1997,1998 by Lars Doelle This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -26,7 +24,7 @@ #define CHARACTER_H // Qt -#include +#include // Local #include "CharacterColor.h" @@ -36,10 +34,10 @@ namespace Konsole typedef unsigned char LineProperty; -static const int LINE_DEFAULT = 0; -static const int LINE_WRAPPED = (1 << 0); -static const int LINE_DOUBLEWIDTH = (1 << 1); -static const int LINE_DOUBLEHEIGHT = (1 << 2); +static const int LINE_DEFAULT = 0; +static const int LINE_WRAPPED = (1 << 0); +static const int LINE_DOUBLEWIDTH = (1 << 1); +static const int LINE_DOUBLEHEIGHT = (1 << 2); #define DEFAULT_RENDITION 0 #define RE_BOLD (1 << 0) @@ -47,8 +45,13 @@ static const int LINE_DOUBLEHEIGHT = (1 << 2); #define RE_UNDERLINE (1 << 2) #define RE_REVERSE (1 << 3) // Screen only #define RE_INTENSIVE (1 << 3) // Widget only -#define RE_CURSOR (1 << 4) -#define RE_EXTENDED_CHAR (1 << 5) +#define RE_ITALIC (1 << 4) +#define RE_CURSOR (1 << 5) +#define RE_EXTENDED_CHAR (1 << 6) +#define RE_FAINT (1 << 7) +#define RE_STRIKEOUT (1 << 8) +#define RE_CONCEAL (1 << 9) +#define RE_OVERLINE (1 << 10) /** * A single character in the terminal which consists of a unicode character @@ -58,7 +61,7 @@ static const int LINE_DOUBLEHEIGHT = (1 << 2); class Character { public: - /** + /** * Constructs a new character. * * @param _c The unicode character value of this character. @@ -75,26 +78,30 @@ public: union { /** The unicode character value for this character. */ - quint16 character; - /** +#if QT_VERSION >= 0x060000 + char16_t character; +#else + wchar_t character; +#endif + /** * Experimental addition which allows a single Character instance to contain more than * one unicode character. * * charSequence is a hash code which can be used to look up the unicode * character sequence in the ExtendedCharTable used to create the sequence. */ - quint16 charSequence; + quint16 charSequence; }; /** A combination of RENDITION flags which specify options for drawing the character. */ quint8 rendition; /** The foreground color used to draw this character. */ - CharacterColor foregroundColor; + CharacterColor foregroundColor; /** The color used to draw this character's background. */ CharacterColor backgroundColor; - /** + /** * Returns true if this character has a transparent background when * it is drawn with the specified @p palette. */ @@ -102,11 +109,16 @@ public: /** * Returns true if this character should always be drawn in bold when * it is drawn with the specified @p palette, independent of whether - * or not the character has the RE_BOLD rendition flag. + * or not the character has the RE_BOLD rendition flag. */ - bool isBold(const ColorEntry* base) const; - - /** + ColorEntry::FontWeight fontWeight(const ColorEntry* base) const; + + /** + * returns true if the format (color, rendition flag) of the compared characters is equal + */ + bool equalsFormat(const Character &other) const; + + /** * Compares two characters and returns true if they have the same unicode character value, * rendition and colors. */ @@ -119,35 +131,45 @@ public: }; inline bool operator == (const Character& a, const Character& b) -{ - return a.character == b.character && - a.rendition == b.rendition && - a.foregroundColor == b.foregroundColor && +{ + return a.character == b.character && + a.rendition == b.rendition && + a.foregroundColor == b.foregroundColor && a.backgroundColor == b.backgroundColor; } inline bool operator != (const Character& a, const Character& b) { - return a.character != b.character || - a.rendition != b.rendition || - a.foregroundColor != b.foregroundColor || + return a.character != b.character || + a.rendition != b.rendition || + a.foregroundColor != b.foregroundColor || a.backgroundColor != b.backgroundColor; } inline bool Character::isTransparent(const ColorEntry* base) const { - return ((backgroundColor._colorSpace == COLOR_SPACE_DEFAULT) && + return ((backgroundColor._colorSpace == COLOR_SPACE_DEFAULT) && base[backgroundColor._u+0+(backgroundColor._v?BASE_COLORS:0)].transparent) - || ((backgroundColor._colorSpace == COLOR_SPACE_SYSTEM) && + || ((backgroundColor._colorSpace == COLOR_SPACE_SYSTEM) && base[backgroundColor._u+2+(backgroundColor._v?BASE_COLORS:0)].transparent); } -inline bool Character::isBold(const ColorEntry* base) const +inline bool Character::equalsFormat(const Character& other) const { - return ((backgroundColor._colorSpace == COLOR_SPACE_DEFAULT) && - base[backgroundColor._u+0+(backgroundColor._v?BASE_COLORS:0)].bold) - || ((backgroundColor._colorSpace == COLOR_SPACE_SYSTEM) && - base[backgroundColor._u+2+(backgroundColor._v?BASE_COLORS:0)].bold); + return + backgroundColor==other.backgroundColor && + foregroundColor==other.foregroundColor && + rendition==other.rendition; +} + +inline ColorEntry::FontWeight Character::fontWeight(const ColorEntry* base) const +{ + if (backgroundColor._colorSpace == COLOR_SPACE_DEFAULT) + return base[backgroundColor._u+0+(backgroundColor._v?BASE_COLORS:0)].fontWeight; + else if (backgroundColor._colorSpace == COLOR_SPACE_SYSTEM) + return base[backgroundColor._u+2+(backgroundColor._v?BASE_COLORS:0)].fontWeight; + else + return ColorEntry::UseCurrentFormat; } extern unsigned short vt100_graphics[32]; @@ -183,7 +205,7 @@ public: * which was added to the table using createExtendedChar(). * * @param hash The hash key returned by createExtendedChar() - * @param length This variable is set to the length of the + * @param length This variable is set to the length of the * character sequence. * * @return A unicode character sequence of size @p length. @@ -195,7 +217,7 @@ public: private: // calculates the hash key of a sequence of unicode points of size 'length' ushort extendedCharHash(ushort* unicodePoints , ushort length) const; - // tests whether the entry in the table specified by 'hash' matches the + // tests whether the entry in the table specified by 'hash' matches the // character sequence 'unicodePoints' of size 'length' bool extendedCharMatch(ushort hash , ushort* unicodePoints , ushort length) const; // internal, maps hash keys to character sequence buffers. The first ushort @@ -205,6 +227,7 @@ private: }; } +Q_DECLARE_TYPEINFO(Konsole::Character, Q_MOVABLE_TYPE); #endif // CHARACTER_H diff --git a/qtermwidget/src/CharacterColor.h b/qtermwidget/lib/CharacterColor.h similarity index 61% rename from qtermwidget/src/CharacterColor.h rename to qtermwidget/lib/CharacterColor.h index 1b86674..25bbb0e 100644 --- a/qtermwidget/src/CharacterColor.h +++ b/qtermwidget/lib/CharacterColor.h @@ -1,10 +1,8 @@ /* This file is part of Konsole, KDE's terminal. - - Copyright (C) 2007 by Robert Knight - Copyright (C) 1997,1998 by Lars Doelle - Rewritten for QT4 by e_k , Copyright (C)2008 + Copyright 2007-2008 by Robert Knight + Copyright 1997,1998 by Lars Doelle This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -26,19 +24,22 @@ #define CHARACTERCOLOR_H // Qt -#include +#include + +//#include +#define KDE_NO_EXPORT namespace Konsole { -/** - * An entry in a terminal display's color palette. +/** + * An entry in a terminal display's color palette. * * A color palette is an array of 16 ColorEntry instances which map * system color indexes (from 0 to 15) into actual colors. * * Each entry can be set as bold, in which case any text - * drawn using the color should be drawn in bold. + * drawn using the color should be drawn in bold. * * Each entry can also be transparent, in which case the terminal * display should avoid drawing the background for any characters @@ -47,44 +48,49 @@ namespace Konsole class ColorEntry { public: - /** + /** Specifies the weight to use when drawing text with this color. */ + enum FontWeight + { + /** Always draw text in this color with a bold weight. */ + Bold, + /** Always draw text in this color with a normal weight. */ + Normal, + /** + * Use the current font weight set by the terminal application. + * This is the default behavior. + */ + UseCurrentFormat + }; + + /** * Constructs a new color palette entry. * * @param c The color value for this entry. * @param tr Specifies that the color should be transparent when used as a background color. - * @param b Specifies that text drawn with this color should be bold. + * @param weight Specifies the font weight to use when drawing text with this color. */ - ColorEntry(QColor c, bool tr, bool b) : color(c), transparent(tr), bold(b) {} + ColorEntry(QColor c, bool tr, FontWeight weight = UseCurrentFormat) + : color(c), transparent(tr), fontWeight(weight) {} /** * Constructs a new color palette entry with an undefined color, and * with the transparent and bold flags set to false. - */ - ColorEntry() : transparent(false), bold(false) {} - - /** - * Sets the color, transparency and boldness of this color to those of @p rhs. - */ - void operator=(const ColorEntry& rhs) - { - color = rhs.color; - transparent = rhs.transparent; - bold = rhs.bold; - } + */ + ColorEntry() : transparent(false), fontWeight(UseCurrentFormat) {} /** The color value of this entry for display. */ QColor color; - /** - * If true character backgrounds using this color should be transparent. + /** + * If true character backgrounds using this color should be transparent. * This is not applicable when the color is used to render text. */ bool transparent; /** - * If true characters drawn using this color should be bold. + * Specifies the font weight to use when drawing text with this color. * This is not applicable when the color is used to draw a character's background. */ - bool bold; + FontWeight fontWeight; }; @@ -102,25 +108,7 @@ public: //a standard set of colors using black text on a white background. //defined in TerminalDisplay.cpp -static const ColorEntry base_color_table[TABLE_COLORS] = -// The following are almost IBM standard color codes, with some slight -// gamma correction for the dim colors to compensate for bright X screens. -// It contains the 8 ansiterm/xterm colors in 2 intensities. -{ - // Fixme: could add faint colors here, also. - // normal - ColorEntry(QColor(0x00,0x00,0x00), 0, 0 ), ColorEntry( QColor(0xB2,0xB2,0xB2), 1, 0 ), // Dfore, Dback - ColorEntry(QColor(0x00,0x00,0x00), 0, 0 ), ColorEntry( QColor(0xB2,0x18,0x18), 0, 0 ), // Black, Red - ColorEntry(QColor(0x18,0xB2,0x18), 0, 0 ), ColorEntry( QColor(0xB2,0x68,0x18), 0, 0 ), // Green, Yellow - ColorEntry(QColor(0x18,0x18,0xB2), 0, 0 ), ColorEntry( QColor(0xB2,0x18,0xB2), 0, 0 ), // Blue, Magenta - ColorEntry(QColor(0x18,0xB2,0xB2), 0, 0 ), ColorEntry( QColor(0xB2,0xB2,0xB2), 0, 0 ), // Cyan, White - // intensiv - ColorEntry(QColor(0x00,0x00,0x00), 0, 1 ), ColorEntry( QColor(0xFF,0xFF,0xFF), 1, 0 ), - ColorEntry(QColor(0x68,0x68,0x68), 0, 0 ), ColorEntry( QColor(0xFF,0x54,0x54), 0, 0 ), - ColorEntry(QColor(0x54,0xFF,0x54), 0, 0 ), ColorEntry( QColor(0xFF,0xFF,0x54), 0, 0 ), - ColorEntry(QColor(0x54,0x54,0xFF), 0, 0 ), ColorEntry( QColor(0xFF,0x54,0xFF), 0, 0 ), - ColorEntry(QColor(0x54,0xFF,0xFF), 0, 0 ), ColorEntry( QColor(0xFF,0xFF,0xFF), 0, 0 ) -}; +extern const ColorEntry base_color_table[TABLE_COLORS] KDE_NO_EXPORT; /* CharacterColor is a union of the various color spaces. @@ -152,16 +140,16 @@ class CharacterColor friend class Character; public: - /** Constructs a new CharacterColor whoose color and color space are undefined. */ - CharacterColor() - : _colorSpace(COLOR_SPACE_UNDEFINED), - _u(0), - _v(0), - _w(0) + /** Constructs a new CharacterColor whose color and color space are undefined. */ + CharacterColor() + : _colorSpace(COLOR_SPACE_UNDEFINED), + _u(0), + _v(0), + _w(0) {} - /** - * Constructs a new CharacterColor using the specified @p colorSpace and with + /** + * Constructs a new CharacterColor using the specified @p colorSpace and with * color value @p co * * The meaning of @p co depends on the @p colorSpace used. @@ -170,10 +158,10 @@ public: * * TODO : Add documentation about available color spaces. */ - CharacterColor(quint8 colorSpace, int co) - : _colorSpace(colorSpace), - _u(0), - _v(0), + CharacterColor(quint8 colorSpace, int co) + : _colorSpace(colorSpace), + _u(0), + _v(0), _w(0) { switch (colorSpace) @@ -185,7 +173,7 @@ public: _u = co & 7; _v = (co >> 3) & 1; break; - case COLOR_SPACE_256: + case COLOR_SPACE_256: _u = co & 255; break; case COLOR_SPACE_RGB: @@ -198,32 +186,32 @@ public: } } - /** + /** * Returns true if this character color entry is valid. */ - bool isValid() + bool isValid() const { return _colorSpace != COLOR_SPACE_UNDEFINED; } - - /** - * Toggles the value of this color between a normal system color and the corresponding intensive - * system color. - * + + /** + * Set the value of this color from a normal system color to the corresponding intensive + * system color if it's not already an intensive system color. + * * This is only applicable if the color is using the COLOR_SPACE_DEFAULT or COLOR_SPACE_SYSTEM * color spaces. */ - void toggleIntensive(); + void setIntensive(); - /** - * Returns the color within the specified color @palette + /** + * Returns the color within the specified color @p palette * * The @p palette is only used if this color is one of the 16 system colors, otherwise * it is ignored. */ QColor color(const ColorEntry* palette) const; - - /** + + /** * Compares two colors and returns true if they represent the same color value and * use the same color space. */ @@ -237,35 +225,38 @@ public: private: quint8 _colorSpace; - // bytes storing the character color - quint8 _u; - quint8 _v; - quint8 _w; + // bytes storing the character color + quint8 _u; + quint8 _v; + quint8 _w; }; inline bool operator == (const CharacterColor& a, const CharacterColor& b) -{ - return *reinterpret_cast(&a._colorSpace) == - *reinterpret_cast(&b._colorSpace); +{ + return a._colorSpace == b._colorSpace && + a._u == b._u && + a._v == b._v && + a._w == b._w; } - inline bool operator != (const CharacterColor& a, const CharacterColor& b) { - return *reinterpret_cast(&a._colorSpace) != - *reinterpret_cast(&b._colorSpace); + return !operator==(a,b); } inline const QColor color256(quint8 u, const ColorEntry* base) { // 0.. 16: system colors - if (u < 8) return base[u+2 ].color; u -= 8; - if (u < 8) return base[u+2+BASE_COLORS].color; u -= 8; + if (u < 8) return base[u+2 ].color; + u -= 8; + if (u < 8) return base[u+2+BASE_COLORS].color; + u -= 8; // 16..231: 6x6x6 rgb color cube - if (u < 216) return QColor(255*((u/36)%6)/5, - 255*((u/ 6)%6)/5, - 255*((u/ 1)%6)/5); u -= 216; - + if (u < 216) return QColor(((u/36)%6) ? (40*((u/36)%6)+55) : 0, + ((u/ 6)%6) ? (40*((u/ 6)%6)+55) : 0, + ((u/ 1)%6) ? (40*((u/ 1)%6)+55) : 0); + u -= 216; + // 232..255: gray, leaving out black and white int gray = u*10+8; return QColor(gray,gray,gray); } @@ -277,7 +268,7 @@ inline QColor CharacterColor::color(const ColorEntry* base) const case COLOR_SPACE_DEFAULT: return base[_u+0+(_v?BASE_COLORS:0)].color; case COLOR_SPACE_SYSTEM: return base[_u+2+(_v?BASE_COLORS:0)].color; case COLOR_SPACE_256: return color256(_u,base); - case COLOR_SPACE_RGB: return QColor(_u,_v,_w); + case COLOR_SPACE_RGB: return {_u,_v,_w}; case COLOR_SPACE_UNDEFINED: return QColor(); } @@ -286,11 +277,11 @@ inline QColor CharacterColor::color(const ColorEntry* base) const return QColor(); } -inline void CharacterColor::toggleIntensive() +inline void CharacterColor::setIntensive() { if (_colorSpace == COLOR_SPACE_SYSTEM || _colorSpace == COLOR_SPACE_DEFAULT) { - _v = !_v; + _v = 1; } } diff --git a/qtermwidget/lib/ColorScheme.cpp b/qtermwidget/lib/ColorScheme.cpp new file mode 100644 index 0000000..032e931 --- /dev/null +++ b/qtermwidget/lib/ColorScheme.cpp @@ -0,0 +1,686 @@ +/* + This source file is part of Konsole, a terminal emulator. + + Copyright 2007-2008 by Robert Knight + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. +*/ + +// Own +#include "ColorScheme.h" +#include "tools.h" + +// Qt +#include +#include +#include +#include +#include +#include +#include +#include +#if QT_VERSION >= 0x060000 +#include +#endif + +// KDE +//#include +//#include +//#include +//#include +//#include +//#include + +using namespace Konsole; + +const ColorEntry ColorScheme::defaultTable[TABLE_COLORS] = + // The following are almost IBM standard color codes, with some slight + // gamma correction for the dim colors to compensate for bright X screens. + // It contains the 8 ansiterm/xterm colors in 2 intensities. +{ + ColorEntry( QColor(0x00,0x00,0x00), false), ColorEntry( +QColor(0xFF,0xFF,0xFF), true), // Dfore, Dback + ColorEntry( QColor(0x00,0x00,0x00), false), ColorEntry( +QColor(0xB2,0x18,0x18), false), // Black, Red + ColorEntry( QColor(0x18,0xB2,0x18), false), ColorEntry( +QColor(0xB2,0x68,0x18), false), // Green, Yellow + ColorEntry( QColor(0x18,0x18,0xB2), false), ColorEntry( +QColor(0xB2,0x18,0xB2), false), // Blue, Magenta + ColorEntry( QColor(0x18,0xB2,0xB2), false), ColorEntry( +QColor(0xB2,0xB2,0xB2), false), // Cyan, White + // intensive + ColorEntry( QColor(0x00,0x00,0x00), false), ColorEntry( +QColor(0xFF,0xFF,0xFF), true), + ColorEntry( QColor(0x68,0x68,0x68), false), ColorEntry( +QColor(0xFF,0x54,0x54), false), + ColorEntry( QColor(0x54,0xFF,0x54), false), ColorEntry( +QColor(0xFF,0xFF,0x54), false), + ColorEntry( QColor(0x54,0x54,0xFF), false), ColorEntry( +QColor(0xFF,0x54,0xFF), false), + ColorEntry( QColor(0x54,0xFF,0xFF), false), ColorEntry( +QColor(0xFF,0xFF,0xFF), false) +}; + +const char* const ColorScheme::colorNames[TABLE_COLORS] = +{ + "Foreground", + "Background", + "Color0", + "Color1", + "Color2", + "Color3", + "Color4", + "Color5", + "Color6", + "Color7", + "ForegroundIntense", + "BackgroundIntense", + "Color0Intense", + "Color1Intense", + "Color2Intense", + "Color3Intense", + "Color4Intense", + "Color5Intense", + "Color6Intense", + "Color7Intense" +}; +// dummy silently comment out the tr_NOOP +#define tr_NOOP +const char* const ColorScheme::translatedColorNames[TABLE_COLORS] = +{ + tr_NOOP("Foreground"), + tr_NOOP("Background"), + tr_NOOP("Color 1"), + tr_NOOP("Color 2"), + tr_NOOP("Color 3"), + tr_NOOP("Color 4"), + tr_NOOP("Color 5"), + tr_NOOP("Color 6"), + tr_NOOP("Color 7"), + tr_NOOP("Color 8"), + tr_NOOP("Foreground (Intense)"), + tr_NOOP("Background (Intense)"), + tr_NOOP("Color 1 (Intense)"), + tr_NOOP("Color 2 (Intense)"), + tr_NOOP("Color 3 (Intense)"), + tr_NOOP("Color 4 (Intense)"), + tr_NOOP("Color 5 (Intense)"), + tr_NOOP("Color 6 (Intense)"), + tr_NOOP("Color 7 (Intense)"), + tr_NOOP("Color 8 (Intense)") +}; + +ColorScheme::ColorScheme() +{ + _table = nullptr; + _randomTable = nullptr; + _opacity = 1.0; +} +ColorScheme::ColorScheme(const ColorScheme& other) + : _opacity(other._opacity) + ,_table(nullptr) + ,_randomTable(nullptr) +{ + setName(other.name()); + setDescription(other.description()); + + if ( other._table != nullptr ) + { + for ( int i = 0 ; i < TABLE_COLORS ; i++ ) + setColorTableEntry(i,other._table[i]); + } + + if ( other._randomTable != nullptr ) + { + for ( int i = 0 ; i < TABLE_COLORS ; i++ ) + { + const RandomizationRange& range = other._randomTable[i]; + setRandomizationRange(i,range.hue,range.saturation,range.value); + } + } +} +ColorScheme::~ColorScheme() +{ + delete[] _table; + delete[] _randomTable; +} + +void ColorScheme::setDescription(const QString& description) { _description = description; } +QString ColorScheme::description() const { return _description; } + +void ColorScheme::setName(const QString& name) { _name = name; } +QString ColorScheme::name() const { return _name; } + +void ColorScheme::setColorTableEntry(int index , const ColorEntry& entry) +{ + Q_ASSERT( index >= 0 && index < TABLE_COLORS ); + + if ( !_table ) + { + _table = new ColorEntry[TABLE_COLORS]; + + for (int i=0;i= 0 && index < TABLE_COLORS ); + + ColorEntry entry = colorTable()[index]; + + if ( _randomTable != nullptr && + !_randomTable[index].isNull() ) + { + const RandomizationRange& range = _randomTable[index]; + + + int hueDifference = range.hue ? QRandomGenerator::global()->bounded(range.hue) - range.hue/2 : 0; + int saturationDifference = range.saturation ? QRandomGenerator::global()->bounded(range.saturation) - range.saturation/2 : 0; + int valueDifference = range.value ? QRandomGenerator::global()->bounded(range.value) - range.value/2 : 0; + + QColor& color = entry.color; + + int newHue = qAbs( (color.hue() + hueDifference) % MAX_HUE ); + int newValue = qMin( qAbs(color.value() + valueDifference) , 255 ); + int newSaturation = qMin( qAbs(color.saturation() + saturationDifference) , 255 ); + + color.setHsv(newHue,newSaturation,newValue); + } + + return entry; +} +void ColorScheme::getColorTable(ColorEntry* table) const +{ + for ( int i = 0 ; i < TABLE_COLORS ; i++ ) + table[i] = colorEntry(i); +} +bool ColorScheme::randomizedBackgroundColor() const +{ + return _randomTable == nullptr ? false : !_randomTable[1].isNull(); +} +void ColorScheme::setRandomizedBackgroundColor(bool randomize) +{ + // the hue of the background colour is allowed to be randomly + // adjusted as much as possible. + // + // the value and saturation are left alone to maintain read-ability + if ( randomize ) + { + setRandomizationRange( 1 /* background color index */ , MAX_HUE , 255 , 0 ); + } + else + { + if ( _randomTable ) + setRandomizationRange( 1 /* background color index */ , 0 , 0 , 0 ); + } +} + +void ColorScheme::setRandomizationRange( int index , quint16 hue , quint8 saturation , + quint8 value ) +{ + Q_ASSERT( hue <= MAX_HUE ); + Q_ASSERT( index >= 0 && index < TABLE_COLORS ); + + if ( _randomTable == nullptr ) + _randomTable = new RandomizationRange[TABLE_COLORS]; + + _randomTable[index].hue = hue; + _randomTable[index].value = value; + _randomTable[index].saturation = saturation; +} + +const ColorEntry* ColorScheme::colorTable() const +{ + if ( _table ) + return _table; + else + return defaultTable; +} +QColor ColorScheme::foregroundColor() const +{ + return colorTable()[0].color; +} +QColor ColorScheme::backgroundColor() const +{ + return colorTable()[1].color; +} +bool ColorScheme::hasDarkBackground() const +{ + // value can range from 0 - 255, with larger values indicating higher brightness. + // so 127 is in the middle, anything less is deemed 'dark' + return backgroundColor().value() < 127; +} +void ColorScheme::setOpacity(qreal opacity) { _opacity = opacity; } +qreal ColorScheme::opacity() const { return _opacity; } + +void ColorScheme::read(const QString & fileName) +{ + QSettings s(fileName, QSettings::IniFormat); + s.beginGroup(QLatin1String("General")); + + _description = s.value(QLatin1String("Description"), QObject::tr("Un-named Color Scheme")).toString(); + _opacity = s.value(QLatin1String("Opacity"),qreal(1.0)).toDouble(); + s.endGroup(); + + for (int i=0 ; i < TABLE_COLORS ; i++) + { + readColorEntry(&s, i); + } +} +#if 0 +// implemented upstream - user apps +void ColorScheme::read(KConfig& config) +{ + KConfigGroup configGroup = config.group("General"); + + QString description = configGroup.readEntry("Description", QObject::tr("Un-named Color Scheme")); + + _description = tr(description.toUtf8()); + _opacity = configGroup.readEntry("Opacity",qreal(1.0)); + + for (int i=0 ; i < TABLE_COLORS ; i++) + { + readColorEntry(config,i); + } +} +void ColorScheme::write(KConfig& config) const +{ + KConfigGroup configGroup = config.group("General"); + + configGroup.writeEntry("Description",_description); + configGroup.writeEntry("Opacity",_opacity); + + for (int i=0 ; i < TABLE_COLORS ; i++) + { + RandomizationRange random = _randomTable != 0 ? _randomTable[i] : RandomizationRange(); + writeColorEntry(config,colorNameForIndex(i),colorTable()[i],random); + } +} +#endif + +QString ColorScheme::colorNameForIndex(int index) +{ + Q_ASSERT( index >= 0 && index < TABLE_COLORS ); + + return QString::fromLatin1(colorNames[index]); +} +QString ColorScheme::translatedColorNameForIndex(int index) +{ + Q_ASSERT( index >= 0 && index < TABLE_COLORS ); + + return QString::fromLatin1(translatedColorNames[index]); +} + +void ColorScheme::readColorEntry(QSettings * s , int index) +{ + QString colorName = colorNameForIndex(index); + + s->beginGroup(colorName); + + ColorEntry entry; + + QVariant colorValue = s->value(QLatin1String("Color")); + QString colorStr; + int r, g, b; + bool ok = false; + // XXX: Undocumented(?) QSettings behavior: values with commas are parsed + // as QStringList and others QString +#if QT_VERSION >= 0x060000 + if (colorValue.typeId() == QMetaType::QStringList) +#else + if (colorValue.type() == QVariant::StringList) +#endif + { + QStringList rgbList = colorValue.toStringList(); + colorStr = rgbList.join(QLatin1Char(',')); + if (rgbList.count() == 3) + { + bool parse_ok; + + ok = true; + r = rgbList[0].toInt(&parse_ok); + ok = ok && parse_ok && (r >= 0 && r <= 0xff); + g = rgbList[1].toInt(&parse_ok); + ok = ok && parse_ok && (g >= 0 && g <= 0xff); + b = rgbList[2].toInt(&parse_ok); + ok = ok && parse_ok && (b >= 0 && b <= 0xff); + } + } + else + { + colorStr = colorValue.toString(); + QRegularExpression hexColorPattern(QLatin1String("^#[0-9a-f]{6}$"), + QRegularExpression::CaseInsensitiveOption); + if (hexColorPattern.match(colorStr).hasMatch()) + { + // Parsing is always ok as already matched by the regexp +#if QT_VERSION >= 0x060000 + r = QStringView{colorStr}.mid(1, 2).toInt(nullptr, 16); + g = QStringView{colorStr}.mid(3, 2).toInt(nullptr, 16); + b = QStringView{colorStr}.mid(5, 2).toInt(nullptr, 16); +#else + r = colorStr.midRef(1, 2).toInt(nullptr, 16); + g = colorStr.midRef(3, 2).toInt(nullptr, 16); + b = colorStr.midRef(5, 2).toInt(nullptr, 16); +#endif + ok = true; + } + } + if (!ok) + { + qWarning().nospace() << "Invalid color value " << colorStr + << " for " << colorName << ". Fallback to black."; + r = g = b = 0; + } + entry.color = QColor(r, g, b); + + entry.transparent = s->value(QLatin1String("Transparent"),false).toBool(); + + // Deprecated key from KDE 4.0 which set 'Bold' to true to force + // a color to be bold or false to use the current format + // + // TODO - Add a new tri-state key which allows for bold, normal or + // current format + if (s->contains(QLatin1String("Bold"))) + entry.fontWeight = s->value(QLatin1String("Bold"),false).toBool() ? ColorEntry::Bold : + ColorEntry::UseCurrentFormat; + + quint16 hue = s->value(QLatin1String("MaxRandomHue"),0).toInt(); + quint8 value = s->value(QLatin1String("MaxRandomValue"),0).toInt(); + quint8 saturation = s->value(QLatin1String("MaxRandomSaturation"),0).toInt(); + + setColorTableEntry( index , entry ); + + if ( hue != 0 || value != 0 || saturation != 0 ) + setRandomizationRange( index , hue , saturation , value ); + + s->endGroup(); +} +#if 0 +// implemented upstream - user apps +void ColorScheme::writeColorEntry(KConfig& config , const QString& colorName, const ColorEntry& entry , const RandomizationRange& random) const +{ + KConfigGroup configGroup(&config,colorName); + + configGroup.writeEntry("Color",entry.color); + configGroup.writeEntry("Transparency",(bool)entry.transparent); + if (entry.fontWeight != ColorEntry::UseCurrentFormat) + { + configGroup.writeEntry("Bold",entry.fontWeight == ColorEntry::Bold); + } + + // record randomization if this color has randomization or + // if one of the keys already exists + if ( !random.isNull() || configGroup.hasKey("MaxRandomHue") ) + { + configGroup.writeEntry("MaxRandomHue",(int)random.hue); + configGroup.writeEntry("MaxRandomValue",(int)random.value); + configGroup.writeEntry("MaxRandomSaturation",(int)random.saturation); + } +} +#endif + +// +// Work In Progress - A color scheme for use on KDE setups for users +// with visual disabilities which means that they may have trouble +// reading text with the supplied color schemes. +// +// This color scheme uses only the 'safe' colors defined by the +// KColorScheme class. +// +// A complication this introduces is that each color provided by +// KColorScheme is defined as a 'background' or 'foreground' color. +// Only foreground colors are allowed to be used to render text and +// only background colors are allowed to be used for backgrounds. +// +// The ColorEntry and TerminalDisplay classes do not currently +// support this restriction. +// +// Requirements: +// - A color scheme which uses only colors from the KColorScheme class +// - Ability to restrict which colors the TerminalDisplay widget +// uses as foreground and background color +// - Make use of KGlobalSettings::allowDefaultBackgroundImages() as +// a hint to determine whether this accessible color scheme should +// be used by default. +// +// +// -- Robert Knight 21/07/2007 +// +AccessibleColorScheme::AccessibleColorScheme() + : ColorScheme() +{ +#if 0 +// It's not finished in konsole and it breaks Qt4 compilation as well + // basic attributes + setName("accessible"); + setDescription(QObject::tr("Accessible Color Scheme")); + + // setup colors + const int ColorRoleCount = 8; + + const KColorScheme colorScheme(QPalette::Active); + + QBrush colors[ColorRoleCount] = + { + colorScheme.foreground( colorScheme.NormalText ), + colorScheme.background( colorScheme.NormalBackground ), + + colorScheme.foreground( colorScheme.InactiveText ), + colorScheme.foreground( colorScheme.ActiveText ), + colorScheme.foreground( colorScheme.LinkText ), + colorScheme.foreground( colorScheme.VisitedText ), + colorScheme.foreground( colorScheme.NegativeText ), + colorScheme.foreground( colorScheme.NeutralText ) + }; + + for ( int i = 0 ; i < TABLE_COLORS ; i++ ) + { + ColorEntry entry; + entry.color = colors[ i % ColorRoleCount ].color(); + + setColorTableEntry( i , entry ); + } +#endif +} + +ColorSchemeManager::ColorSchemeManager() + : _haveLoadedAll(false) +{ +} +ColorSchemeManager::~ColorSchemeManager() +{ + QHashIterator iter(_colorSchemes); + while (iter.hasNext()) + { + iter.next(); + delete iter.value(); + } +} +void ColorSchemeManager::loadAllColorSchemes() +{ + //qDebug() << "loadAllColorSchemes"; + int failed = 0; + + QList nativeColorSchemes = listColorSchemes(); + QListIterator nativeIter(nativeColorSchemes); + while ( nativeIter.hasNext() ) + { + if ( !loadColorScheme( nativeIter.next() ) ) + failed++; + } + + /*if ( failed > 0 ) + qDebug() << "failed to load " << failed << " color schemes.";*/ + + _haveLoadedAll = true; +} +QList ColorSchemeManager::allColorSchemes() +{ + if ( !_haveLoadedAll ) + { + loadAllColorSchemes(); + } + + return _colorSchemes.values(); +} +#if 0 +void ColorSchemeManager::addColorScheme(ColorScheme* scheme) +{ + _colorSchemes.insert(scheme->name(),scheme); + + // save changes to disk + QString path = KGlobal::dirs()->saveLocation("data","konsole/") + scheme->name() + ".colorscheme"; + KConfig config(path , KConfig::NoGlobals); + + scheme->write(config); +} +#endif + +bool ColorSchemeManager::loadCustomColorScheme(const QString& path) +{ + if (path.endsWith(QLatin1String(".colorscheme"))) + return loadColorScheme(path); + + return false; +} + +void ColorSchemeManager::addCustomColorSchemeDir(const QString& custom_dir) +{ + add_custom_color_scheme_dir(custom_dir); +} + +bool ColorSchemeManager::loadColorScheme(const QString& filePath) +{ + if ( !filePath.endsWith(QLatin1String(".colorscheme")) || !QFile::exists(filePath) ) + return false; + + QFileInfo info(filePath); + + const QString& schemeName = info.baseName(); + + ColorScheme* scheme = new ColorScheme(); + scheme->setName(schemeName); + scheme->read(filePath); + + if (scheme->name().isEmpty()) + { + //qDebug() << "Color scheme in" << filePath << "does not have a valid name and was not loaded."; + delete scheme; + return false; + } + + if ( !_colorSchemes.contains(schemeName) ) + { + _colorSchemes.insert(schemeName,scheme); + } + else + { + /*qDebug() << "color scheme with name" << schemeName << "has already been" << + "found, ignoring.";*/ + + delete scheme; + } + + return true; +} +QList ColorSchemeManager::listColorSchemes() +{ + QList ret; + for (const QString &scheme_dir : get_color_schemes_dirs()) + { + const QString dname(scheme_dir); + QDir dir(dname); + QStringList filters; + filters << QLatin1String("*.colorscheme"); + dir.setNameFilters(filters); + const QStringList list = dir.entryList(filters); + for (const QString &i : list) + ret << dname + QLatin1Char('/') + i; + } + return ret; +// return KGlobal::dirs()->findAllResources("data", +// "konsole/*.colorscheme", +// KStandardDirs::NoDuplicates); +} +const ColorScheme ColorSchemeManager::_defaultColorScheme; +const ColorScheme* ColorSchemeManager::defaultColorScheme() const +{ + return &_defaultColorScheme; +} +bool ColorSchemeManager::deleteColorScheme(const QString& name) +{ + Q_ASSERT( _colorSchemes.contains(name) ); + + // lookup the path and delete + QString path = findColorSchemePath(name); + if ( QFile::remove(path) ) + { + _colorSchemes.remove(name); + return true; + } + else + { + //qDebug() << "Failed to remove color scheme -" << path; + return false; + } +} +QString ColorSchemeManager::findColorSchemePath(const QString& name) const +{ +// QString path = KStandardDirs::locate("data","konsole/"+name+".colorscheme"); + const QStringList dirs = get_color_schemes_dirs(); + if ( dirs.isEmpty() ) + return QString(); + + const QString dir = dirs.first(); + QString path(dir + QLatin1Char('/')+ name + QLatin1String(".colorscheme")); + if ( !path.isEmpty() ) + return path; + + //path = KStandardDirs::locate("data","konsole/"+name+".schema"); + path = dir + QLatin1Char('/')+ name + QLatin1String(".schema"); + + return path; +} +const ColorScheme* ColorSchemeManager::findColorScheme(const QString& name) +{ + if ( name.isEmpty() ) + return defaultColorScheme(); + + if ( _colorSchemes.contains(name) ) + return _colorSchemes[name]; + else + { + // look for this color scheme + QString path = findColorSchemePath(name); + if ( !path.isEmpty() && loadColorScheme(path) ) + { + return findColorScheme(name); + } + + //qDebug() << "Could not find color scheme - " << name; + + return nullptr; + } +} +Q_GLOBAL_STATIC(ColorSchemeManager, theColorSchemeManager) +ColorSchemeManager* ColorSchemeManager::instance() +{ + return theColorSchemeManager; +} diff --git a/qtermwidget/lib/ColorScheme.h b/qtermwidget/lib/ColorScheme.h new file mode 100644 index 0000000..15ceb4d --- /dev/null +++ b/qtermwidget/lib/ColorScheme.h @@ -0,0 +1,325 @@ +/* + This source file is part of Konsole, a terminal emulator. + + Copyright 2007-2008 by Robert Knight + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. +*/ + +#ifndef COLORSCHEME_H +#define COLORSCHEME_H + +// Qt +#include +#include +#include +#include +#include +#include + +// Konsole +#include "CharacterColor.h" + +class QIODevice; +//class KConfig; + +namespace Konsole +{ + +/** + * Represents a color scheme for a terminal display. + * + * The color scheme includes the palette of colors used to draw the text and character backgrounds + * in the display and the opacity level of the display background. + */ +class ColorScheme +{ +public: + /** + * Constructs a new color scheme which is initialised to the default color set + * for Konsole. + */ + ColorScheme(); + ColorScheme(const ColorScheme& other); + ~ColorScheme(); + + /** Sets the descriptive name of the color scheme. */ + void setDescription(const QString& description); + /** Returns the descriptive name of the color scheme. */ + QString description() const; + + /** Sets the name of the color scheme */ + void setName(const QString& name); + /** Returns the name of the color scheme */ + QString name() const; + +#if 0 +// Implemented upstream - in user apps + /** Reads the color scheme from the specified configuration source */ + void read(KConfig& config); + /** Writes the color scheme to the specified configuration source */ + void write(KConfig& config) const; +#endif + void read(const QString & filename); + + /** Sets a single entry within the color palette. */ + void setColorTableEntry(int index , const ColorEntry& entry); + + /** + * Copies the color entries which form the palette for this color scheme + * into @p table. @p table should be an array with TABLE_COLORS entries. + * + * @param table Array into which the color entries for this color scheme + * are copied. + * @param randomSeed Color schemes may allow certain colors in their + * palette to be randomized. The seed is used to pick the random color. + */ + void getColorTable(ColorEntry* table) const; + + /** + * Retrieves a single color entry from the table. + * + * See getColorTable() + */ + ColorEntry colorEntry(int index) const; + + /** + * Convenience method. Returns the + * foreground color for this scheme, + * this is the primary color used to draw the + * text in this scheme. + */ + QColor foregroundColor() const; + /** + * Convenience method. Returns the background color for + * this scheme, this is the primary color used to + * draw the terminal background in this scheme. + */ + QColor backgroundColor() const; + + /** + * Returns true if this color scheme has a dark background. + * The background color is said to be dark if it has a value of less than 127 + * in the HSV color space. + */ + bool hasDarkBackground() const; + + /** + * Sets the opacity level of the display background. @p opacity ranges + * between 0 (completely transparent background) and 1 (completely + * opaque background). + * + * Defaults to 1. + * + * TODO: More documentation + */ + void setOpacity(qreal opacity); + /** + * Returns the opacity level for this color scheme, see setOpacity() + * TODO: More documentation + */ + qreal opacity() const; + + /** + * Enables randomization of the background color. This will cause + * the palette returned by getColorTable() and colorEntry() to + * be adjusted depending on the value of the random seed argument + * to them. + */ + void setRandomizedBackgroundColor(bool randomize); + + /** Returns true if the background color is randomized. */ + bool randomizedBackgroundColor() const; + + static QString colorNameForIndex(int index); + static QString translatedColorNameForIndex(int index); + +private: + // specifies how much a particular color can be randomized by + class RandomizationRange + { + public: + RandomizationRange() : hue(0) , saturation(0) , value(0) {} + + bool isNull() const + { + return ( hue == 0 && saturation == 0 && value == 0 ); + } + + quint16 hue; + quint8 saturation; + quint8 value; + }; + + // returns the active color table. if none has been set specifically, + // this is the default color table. + const ColorEntry* colorTable() const; + +#if 0 +// implemented upstream - user apps + // reads a single colour entry from a KConfig source + // and sets the palette entry at 'index' to the entry read. + void readColorEntry(KConfig& config , int index); + // writes a single colour entry to a KConfig source + void writeColorEntry(KConfig& config , const QString& colorName, const ColorEntry& entry,const RandomizationRange& range) const; +#endif + void readColorEntry(QSettings *s, int index); + + // sets the amount of randomization allowed for a particular color + // in the palette. creates the randomization table if + // it does not already exist + void setRandomizationRange( int index , quint16 hue , quint8 saturation , quint8 value ); + + QString _description; + QString _name; + qreal _opacity; + ColorEntry* _table; // pointer to custom color table or 0 if the default + // color scheme is being used + + + static const quint16 MAX_HUE = 340; + + RandomizationRange* _randomTable; // pointer to randomization table or 0 + // if no colors in the color scheme support + // randomization + + static const char* const colorNames[TABLE_COLORS]; + static const char* const translatedColorNames[TABLE_COLORS]; + + static const ColorEntry defaultTable[]; // table of default color entries +}; + +/** + * A color scheme which uses colors from the standard KDE color palette. + * + * This is designed primarily for the benefit of users who are using specially + * designed colors. + * + * TODO Implement and make it the default on systems with specialized KDE + * color schemes. + */ +class AccessibleColorScheme : public ColorScheme +{ +public: + AccessibleColorScheme(); +}; + +/** + * Manages the color schemes available for use by terminal displays. + * See ColorScheme + */ +class ColorSchemeManager +{ +public: + + /** + * Constructs a new ColorSchemeManager and loads the list + * of available color schemes. + * + * The color schemes themselves are not loaded until they are first + * requested via a call to findColorScheme() + */ + ColorSchemeManager(); + /** + * Destroys the ColorSchemeManager and saves any modified color schemes to disk. + */ + ~ColorSchemeManager(); + + /** + * Returns the default color scheme for Konsole + */ + const ColorScheme* defaultColorScheme() const; + + /** + * Returns the color scheme with the given name or 0 if no + * scheme with that name exists. If @p name is empty, the + * default color scheme is returned. + * + * The first time that a color scheme with a particular name is + * requested, the configuration information is loaded from disk. + */ + const ColorScheme* findColorScheme(const QString& name); + +#if 0 + /** + * Adds a new color scheme to the manager. If @p scheme has the same name as + * an existing color scheme, it replaces the existing scheme. + * + * TODO - Ensure the old color scheme gets deleted + */ + void addColorScheme(ColorScheme* scheme); +#endif + /** + * Deletes a color scheme. Returns true on successful deletion or false otherwise. + */ + bool deleteColorScheme(const QString& name); + + /** + * Returns a list of the all the available color schemes. + * This may be slow when first called because all of the color + * scheme resources on disk must be located, read and parsed. + * + * Subsequent calls will be inexpensive. + */ + QList allColorSchemes(); + + /** Returns the global color scheme manager instance. */ + static ColorSchemeManager* instance(); + + /** @brief Loads a custom color scheme under given \em path. + * + * The \em path may refer to either KDE 4 .colorscheme or KDE 3 + * .schema file + * + * The loaded color scheme is available under the name equal to + * the base name of the \em path via the allColorSchemes() and + * findColorScheme() methods after this call if loaded successfully. + * + * @param[in] path The path to KDE 4 .colorscheme or KDE 3 .schema. + * @return Whether the color scheme is loaded successfully. + */ + bool loadCustomColorScheme(const QString& path); + + /** + * @brief Allows to add a custom location of color schemes. + * + * @param[in] custom_dir Custom location of color schemes (must end with /). + */ + void addCustomColorSchemeDir(const QString& custom_dir); + +private: + // loads a color scheme from a KDE 4+ .colorscheme file + bool loadColorScheme(const QString& path); + // returns a list of paths of color schemes in the KDE 4+ .colorscheme file format + QList listColorSchemes(); + // loads all of the color schemes + void loadAllColorSchemes(); + // finds the path of a color scheme + QString findColorSchemePath(const QString& name) const; + + QHash _colorSchemes; + QSet _modifiedSchemes; + + bool _haveLoadedAll; + + static const ColorScheme _defaultColorScheme; +}; + +} + +Q_DECLARE_METATYPE(const Konsole::ColorScheme*) + +#endif //COLORSCHEME_H diff --git a/qtermwidget/lib/ColorTables.h b/qtermwidget/lib/ColorTables.h new file mode 100644 index 0000000..57b0bd1 --- /dev/null +++ b/qtermwidget/lib/ColorTables.h @@ -0,0 +1,55 @@ +#ifndef _COLOR_TABLE_H +#define _COLOR_TABLE_H + +#include "CharacterColor.h" + +//using namespace Konsole; +#if 0 +static const ColorEntry whiteonblack_color_table[TABLE_COLORS] = { + // normal + ColorEntry(QColor(0xFF,0xFF,0xFF), false ), ColorEntry( QColor(0x00,0x00,0x00), true ), // Dfore, Dback + ColorEntry(QColor(0x00,0x00,0x00), false ), ColorEntry( QColor(0xB2,0x18,0x18), false ), // Black, Red + ColorEntry(QColor(0x18,0xB2,0x18), false ), ColorEntry( QColor(0xB2,0x68,0x18), false ), // Green, Yellow + ColorEntry(QColor(0x18,0x18,0xB2), false ), ColorEntry( QColor(0xB2,0x18,0xB2), false ), // Blue, Magenta + ColorEntry(QColor(0x18,0xB2,0xB2), false ), ColorEntry( QColor(0xB2,0xB2,0xB2), false ), // Cyan, White + // intensiv + ColorEntry(QColor(0x00,0x00,0x00), false ), ColorEntry( QColor(0xFF,0xFF,0xFF), true ), + ColorEntry(QColor(0x68,0x68,0x68), false ), ColorEntry( QColor(0xFF,0x54,0x54), false ), + ColorEntry(QColor(0x54,0xFF,0x54), false ), ColorEntry( QColor(0xFF,0xFF,0x54), false ), + ColorEntry(QColor(0x54,0x54,0xFF), false ), ColorEntry( QColor(0xFF,0x54,0xFF), false ), + ColorEntry(QColor(0x54,0xFF,0xFF), false ), ColorEntry( QColor(0xFF,0xFF,0xFF), false ) +}; + +static const ColorEntry greenonblack_color_table[TABLE_COLORS] = { + ColorEntry(QColor( 24, 240, 24), false), ColorEntry(QColor( 0, 0, 0), true), + ColorEntry(QColor( 0, 0, 0), false), ColorEntry(QColor( 178, 24, 24), false), + ColorEntry(QColor( 24, 178, 24), false), ColorEntry(QColor( 178, 104, 24), false), + ColorEntry(QColor( 24, 24, 178), false), ColorEntry(QColor( 178, 24, 178), false), + ColorEntry(QColor( 24, 178, 178), false), ColorEntry(QColor( 178, 178, 178), false), + // intensive colors + ColorEntry(QColor( 24, 240, 24), false ), ColorEntry(QColor( 0, 0, 0), true ), + ColorEntry(QColor( 104, 104, 104), false ), ColorEntry(QColor( 255, 84, 84), false ), + ColorEntry(QColor( 84, 255, 84), false ), ColorEntry(QColor( 255, 255, 84), false ), + ColorEntry(QColor( 84, 84, 255), false ), ColorEntry(QColor( 255, 84, 255), false ), + ColorEntry(QColor( 84, 255, 255), false ), ColorEntry(QColor( 255, 255, 255), false ) +}; + +static const ColorEntry blackonlightyellow_color_table[TABLE_COLORS] = { + ColorEntry(QColor( 0, 0, 0), false), ColorEntry(QColor( 255, 255, 221), true), + ColorEntry(QColor( 0, 0, 0), false), ColorEntry(QColor( 178, 24, 24), false), + ColorEntry(QColor( 24, 178, 24), false), ColorEntry(QColor( 178, 104, 24), false), + ColorEntry(QColor( 24, 24, 178), false), ColorEntry(QColor( 178, 24, 178), false), + ColorEntry(QColor( 24, 178, 178), false), ColorEntry(QColor( 178, 178, 178), false), + ColorEntry(QColor( 0, 0, 0), false), ColorEntry(QColor( 255, 255, 221), true), + ColorEntry(QColor(104, 104, 104), false), ColorEntry(QColor( 255, 84, 84), false), + ColorEntry(QColor( 84, 255, 84), false), ColorEntry(QColor( 255, 255, 84), false), + ColorEntry(QColor( 84, 84, 255), false), ColorEntry(QColor( 255, 84, 255), false), + ColorEntry(QColor( 84, 255, 255), false), ColorEntry(QColor( 255, 255, 255), false) +}; + + +#endif + + +#endif + diff --git a/qtermwidget/src/DefaultTranslatorText.h b/qtermwidget/lib/DefaultTranslatorText.h similarity index 100% rename from qtermwidget/src/DefaultTranslatorText.h rename to qtermwidget/lib/DefaultTranslatorText.h diff --git a/qtermwidget/src/Emulation.cpp b/qtermwidget/lib/Emulation.cpp similarity index 58% rename from qtermwidget/src/Emulation.cpp rename to qtermwidget/lib/Emulation.cpp index e767a42..0b3082f 100644 --- a/qtermwidget/src/Emulation.cpp +++ b/qtermwidget/lib/Emulation.cpp @@ -1,11 +1,7 @@ /* - This file is part of Konsole, an X terminal. - - Copyright (C) 2007 Robert Knight - Copyright (C) 1997,1998 by Lars Doelle - Copyright (C) 1996 by Matthias Ettrich - - Rewritten for QT4 by e_k , Copyright (C)2008 + Copyright 2007-2008 Robert Knight + Copyright 1997,1998 by Lars Doelle + Copyright 1996 by Matthias Ettrich This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -27,21 +23,31 @@ #include "Emulation.h" // System -#include -#include -#include +#include +#include #include +#include // Qt -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#if QT_VERSION >= 0x060000 +#include +#include +#else +#include +#endif +#include +#include -#include +#include +//TODO REMOVE THIS +#include + +// KDE +//#include // Konsole #include "KeyboardTranslator.h" @@ -51,25 +57,14 @@ using namespace Konsole; -/* ------------------------------------------------------------------------- */ -/* */ -/* Emulation */ -/* */ -/* ------------------------------------------------------------------------- */ - -//#define CNTL(c) ((c)-'@') - -/*! -*/ - Emulation::Emulation() : - _currentScreen(0), - _codec(0), - _decoder(0), - _keyTranslator(0), - _usesMouse(false) + _currentScreen(nullptr), + _codec(nullptr), + _decoder(nullptr), + _keyTranslator(nullptr), + _usesMouse(false), + _bracketedPasteMode(false) { - // create screens with a default size _screen[0] = new Screen(40,80); _screen[1] = new Screen(40,80); @@ -77,10 +72,17 @@ Emulation::Emulation() : QObject::connect(&_bulkTimer1, SIGNAL(timeout()), this, SLOT(showBulk()) ); QObject::connect(&_bulkTimer2, SIGNAL(timeout()), this, SLOT(showBulk()) ); - + // listen for mouse status changes - connect( this , SIGNAL(programUsesMouseChanged(bool)) , - SLOT(usesMouseChanged(bool)) ); + connect(this , SIGNAL(programUsesMouseChanged(bool)) , + SLOT(usesMouseChanged(bool))); + connect(this , SIGNAL(programBracketedPasteModeChanged(bool)) , + SLOT(bracketedPasteModeChanged(bool))); + + connect(this, &Emulation::cursorChanged, this, [this] (KeyboardCursorShape cursorShape, bool blinkingCursorEnabled) { + emit titleChanged( 50, QString(QLatin1String("CursorShape=%1;BlinkingCursorEnabled=%2")) + .arg(static_cast(cursorShape)).arg(blinkingCursorEnabled) ); + }); } bool Emulation::programUsesMouse() const @@ -93,6 +95,16 @@ void Emulation::usesMouseChanged(bool usesMouse) _usesMouse = usesMouse; } +bool Emulation::programBracketedPasteMode() const +{ + return _bracketedPasteMode; +} + +void Emulation::bracketedPasteModeChanged(bool bracketedPasteMode) +{ + _bracketedPasteMode = bracketedPasteMode; +} + ScreenWindow* Emulation::createWindow() { ScreenWindow* window = new ScreenWindow(); @@ -104,12 +116,15 @@ ScreenWindow* Emulation::createWindow() connect(this , SIGNAL(outputChanged()), window , SLOT(notifyOutputChanged()) ); + + connect(this, &Emulation::handleCommandFromKeyboard, + window, &ScreenWindow::handleCommandFromKeyboard); + connect(this, &Emulation::outputFromKeypressEvent, + window, &ScreenWindow::scrollToEnd); + return window; } -/*! -*/ - Emulation::~Emulation() { QListIterator windowIter(_windows); @@ -124,23 +139,15 @@ Emulation::~Emulation() delete _decoder; } -/*! change between primary and alternate _screen -*/ - void Emulation::setScreen(int n) { Screen *old = _currentScreen; - _currentScreen = _screen[n&1]; - if (_currentScreen != old) + _currentScreen = _screen[n & 1]; + if (_currentScreen != old) { - old->setBusySelecting(false); - - // tell all windows onto this emulation to switch to the newly active _screen - QListIterator windowIter(_windows); - while ( windowIter.hasNext() ) - { - windowIter.next()->setScreen(_currentScreen); - } + // tell all windows onto this emulation to switch to the newly active screen + for(ScreenWindow* window : qAsConst(_windows)) + window->setScreen(_currentScreen); } } @@ -155,16 +162,18 @@ void Emulation::setHistory(const HistoryType& t) showBulk(); } -const HistoryType& Emulation::history() +const HistoryType& Emulation::history() const { return _screen[0]->getScroll(); } void Emulation::setCodec(const QTextCodec * qtc) { - Q_ASSERT( qtc ); + if (qtc) + _codec = qtc; + else + setCodec(LocaleCodec); - _codec = qtc; delete _decoder; _decoder = _codec->makeDecoder(); @@ -182,63 +191,45 @@ void Emulation::setCodec(EmulationCodec codec) void Emulation::setKeyBindings(const QString& name) { _keyTranslator = KeyboardTranslatorManager::instance()->findTranslator(name); + if (!_keyTranslator) + { + _keyTranslator = KeyboardTranslatorManager::instance()->defaultTranslator(); + } } -QString Emulation::keyBindings() +QString Emulation::keyBindings() const { return _keyTranslator->name(); } - -// Interpreting Codes --------------------------------------------------------- - -/* - This section deals with decoding the incoming character stream. - Decoding means here, that the stream is first separated into `tokens' - which are then mapped to a `meaning' provided as operations by the - `Screen' class. -*/ - -/*! -*/ - -void Emulation::receiveChar(int c) +void Emulation::receiveChar(wchar_t c) // process application unicode input to terminal // this is a trivial scanner { + qDebug() << "Emulation::receiveChar: character " << c; c &= 0xff; + qDebug() << "Emulation::receiveChar (after &=): character " << c; switch (c) { - case '\b' : _currentScreen->BackSpace(); break; - case '\t' : _currentScreen->Tabulate(); break; - case '\n' : _currentScreen->NewLine(); break; - case '\r' : _currentScreen->Return(); break; + case '\b' : _currentScreen->backspace(); break; + case '\t' : _currentScreen->tab(); break; + case '\n' : _currentScreen->newLine(); break; + case '\r' : _currentScreen->toStartOfLine(); break; case 0x07 : emit stateSet(NOTIFYBELL); break; - default : _currentScreen->ShowCharacter(c); break; + default : _currentScreen->displayCharacter(c); break; }; } -/* ------------------------------------------------------------------------- */ -/* */ -/* Keyboard Handling */ -/* */ -/* ------------------------------------------------------------------------- */ - -/*! -*/ - -void Emulation::sendKeyEvent( QKeyEvent* ev ) +void Emulation::sendKeyEvent(QKeyEvent* ev, bool) { 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()); + // We should do a conversion here + emit sendData(ev->text().toUtf8().constData(),ev->text().length()); } } @@ -252,8 +243,6 @@ void Emulation::sendMouseEvent(int /*buttons*/, int /*column*/, int /*row*/, int // default implementation does nothing } -// Unblocking, Byte to Unicode translation --------------------------------- -- - /* We are doing code conversion from locale to unicode first. TODO: Character composition from the old code. See #96536 @@ -261,46 +250,50 @@ TODO: Character composition from the old code. See #96536 void Emulation::receiveData(const char* text, int length) { - emit stateSet(NOTIFYACTIVITY); + emit stateSet(NOTIFYACTIVITY); - bufferedUpdate(); - - QString unicodeText = _decoder->toUnicode(text,length); + bufferedUpdate(); - //send characters to terminal emulator - for (int i=0;itoUnicode(text,length); + std::wstring unicodeText = utf16Text.toStdWString(); - //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 3) && (strncmp(text+i+1, "B00", 3) == 0)) - emit zmodemDetected(); - } - } + //send characters to terminal emulator + for (size_t i=0;i 3) && (strncmp(text+i+1, "B00", 3) == 0)) + emit zmodemDetected(); + } + } } //OLDER VERSION //This version of onRcvBlock was commented out because -// a) It decoded incoming characters one-by-one, which is slow in the current version of Qt (4.2 tech preview) -// b) It messed up decoding of non-ASCII characters, with the result that (for example) chinese characters -// were not printed properly. +// a) It decoded incoming characters one-by-one, which is slow in the current version of Qt (4.2 tech preview) +// b) It messed up decoding of non-ASCII characters, with the result that (for example) chinese characters +// were not printed properly. // //There is something about stopping the _decoder if "we get a control code halfway a multi-byte sequence" (see below) //which hasn't been ported into the newer function (above). Hopefully someone who understands this better -//can find an alternative way of handling the check. +//can find an alternative way of handling the check. /*void Emulation::onRcvBlock(const char *s, int len) { emit notifySessionState(NOTIFYACTIVITY); - + bufferedUpdate(); for (int i = 0; i < len; i++) { @@ -330,72 +323,27 @@ void Emulation::receiveData(const char* text, int length) if (s[i] == '\030') { if ((len-i-1 > 3) && (strncmp(s+i+1, "B00", 3) == 0)) - emit zmodemDetected(); + emit zmodemDetected(); } } }*/ -// Selection --------------------------------------------------------------- -- - -#if 0 -void Emulation::onSelectionBegin(const int x, const int y, const bool columnmode) { - if (!connected) return; - _currentScreen->setSelectionStart( x,y,columnmode); - showBulk(); -} - -void Emulation::onSelectionExtend(const int x, const int y) { - if (!connected) return; - _currentScreen->setSelectionEnd(x,y); - showBulk(); -} - -void Emulation::setSelection(const bool preserve_line_breaks) { - if (!connected) return; - QString t = _currentScreen->selectedText(preserve_line_breaks); - if (!t.isNull()) - { - QListIterator< TerminalDisplay* > viewIter(_views); - - while (viewIter.hasNext()) - viewIter.next()->setSelection(t); - } -} - -void Emulation::testIsSelected(const int x, const int y, bool &selected) -{ - if (!connected) return; - selected=_currentScreen->isSelected(x,y); -} - -void Emulation::clearSelection() { - if (!connected) return; - _currentScreen->clearSelection(); - showBulk(); -} - -#endif - -void Emulation::writeToStream( TerminalCharacterDecoder* _decoder , +void Emulation::writeToStream( TerminalCharacterDecoder* _decoder , int startLine , - int endLine) + int endLine) { - _currentScreen->writeToStream(_decoder,startLine,endLine); + _currentScreen->writeLinesToStream(_decoder,startLine,endLine); } -int Emulation::lineCount() +int Emulation::lineCount() const { // sum number of lines currently on _screen plus number of lines in history return _currentScreen->getLines() + _currentScreen->getHistLines(); } -// Refreshing -------------------------------------------------------------- -- - #define BULK_TIMEOUT1 10 #define BULK_TIMEOUT2 40 -/*! -*/ void Emulation::showBulk() { _bulkTimer1.stop(); @@ -418,16 +366,24 @@ void Emulation::bufferedUpdate() } } -char Emulation::getErase() const +char Emulation::eraseChar() const { return '\b'; } void Emulation::setImageSize(int lines, int columns) { - //kDebug() << "Resizing image to: " << lines << "by" << columns << QTime::currentTime().msec(); - Q_ASSERT( lines > 0 ); - Q_ASSERT( columns > 0 ); + if ((lines < 1) || (columns < 1)) + return; + + QSize screenSize[2] = { QSize(_screen[0]->getColumns(), + _screen[0]->getLines()), + QSize(_screen[1]->getColumns(), + _screen[1]->getLines()) }; + QSize newSize(columns,lines); + + if (newSize == screenSize[0] && newSize == screenSize[1]) + return; _screen[0]->resizeImage(lines,columns); _screen[1]->resizeImage(lines,columns); @@ -437,9 +393,9 @@ void Emulation::setImageSize(int lines, int columns) bufferedUpdate(); } -QSize Emulation::imageSize() +QSize Emulation::imageSize() const { - return QSize(_currentScreen->getColumns(), _currentScreen->getLines()); + return {_currentScreen->getColumns(), _currentScreen->getLines()}; } ushort ExtendedCharTable::extendedCharHash(ushort* unicodePoints , ushort length) const @@ -455,17 +411,17 @@ bool ExtendedCharTable::extendedCharMatch(ushort hash , ushort* unicodePoints , { ushort* entry = extendedCharTable[hash]; - // compare given length with stored sequence length ( given as the first ushort in the - // stored buffer ) - if ( entry == 0 || entry[0] != length ) + // compare given length with stored sequence length ( given as the first ushort in the + // stored buffer ) + if ( entry == nullptr || entry[0] != length ) return false; // if the lengths match, each character must be checked. the stored buffer starts at // entry[1] for ( int i = 0 ; i < length ; i++ ) { if ( entry[i+1] != unicodePoints[i] ) - return false; - } + return false; + } return true; } ushort ExtendedCharTable::createExtendedChar(ushort* unicodePoints , ushort length) @@ -478,7 +434,7 @@ ushort ExtendedCharTable::createExtendedChar(ushort* unicodePoints , ushort leng { if ( extendedCharMatch(hash,unicodePoints,length) ) { - // this sequence already has an entry in the table, + // this sequence already has an entry in the table, // return its hash return hash; } @@ -488,16 +444,16 @@ ushort ExtendedCharTable::createExtendedChar(ushort* unicodePoints , ushort leng // points then try next hash hash++; } - } + } + - // add the new sequence to the table and // return that index ushort* buffer = new ushort[length+1]; buffer[0] = length; for ( int i = 0 ; i < length ; i++ ) - buffer[i+1] = unicodePoints[i]; - + buffer[i+1] = unicodePoints[i]; + extendedCharTable.insert(hash,buffer); return hash; @@ -517,7 +473,7 @@ ushort* ExtendedCharTable::lookupExtendedChar(ushort hash , ushort& length) cons else { length = 0; - return 0; + return nullptr; } } @@ -539,5 +495,5 @@ ExtendedCharTable::~ExtendedCharTable() ExtendedCharTable ExtendedCharTable::instance; -//#include "moc_Emulation.cpp" +//#include "Emulation.moc" diff --git a/qtermwidget/src/Emulation.h b/qtermwidget/lib/Emulation.h similarity index 74% rename from qtermwidget/src/Emulation.h rename to qtermwidget/lib/Emulation.h index 2782df7..7109e69 100644 --- a/qtermwidget/src/Emulation.h +++ b/qtermwidget/lib/Emulation.h @@ -1,10 +1,8 @@ /* This file is part of Konsole, an X terminal. - - Copyright (C) 2007 by Robert Knight - Copyright (C) 1997,1998 by Lars Doelle - Rewritten for QT4 by e_k , Copyright (C)2008 + Copyright 2007-2008 by Robert Knight + Copyright 1997,1998 by Lars Doelle This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -26,75 +24,80 @@ #define EMULATION_H // System -#include +#include -// Qt -#include +// Qt +#include //#include -#include -#include -#include +#if QT_VERSION >= 0x060000 +#include +#else +#include +#endif +#include +#include +#include "qtermwidget_export.h" +#include "KeyboardTranslator.h" namespace Konsole { -class KeyboardTranslator; class HistoryType; class Screen; class ScreenWindow; class TerminalCharacterDecoder; -/** - * This enum describes the available states which +/** + * This enum describes the available states which * the terminal emulation may be set to. * - * These are the values used by Emulation::stateChanged() + * These are the values used by Emulation::stateChanged() */ -enum -{ +enum +{ /** The emulation is currently receiving user input. */ - NOTIFYNORMAL=0, - /** + NOTIFYNORMAL=0, + /** * The terminal program has triggered a bell event * to get the user's attention. */ - NOTIFYBELL=1, - /** - * The emulation is currently receiving data from its + NOTIFYBELL=1, + /** + * The emulation is currently receiving data from its * terminal input. */ NOTIFYACTIVITY=2, - // unused here? - NOTIFYSILENCE=3 + // unused here? + NOTIFYSILENCE=3 }; /** * Base class for terminal emulation back-ends. * - * The back-end is responsible for decoding an incoming character stream and + * The back-end is responsible for decoding an incoming character stream and * producing an output image of characters. * * When input from the terminal is received, the receiveData() slot should be called with - * the data which has arrived. The emulation will process the data and update the + * the data which has arrived. The emulation will process the data and update the * screen image accordingly. The codec used to decode the incoming character stream - * into the unicode characters used internally can be specified using setCodec() + * into the unicode characters used internally can be specified using setCodec() * - * The size of the screen image can be specified by calling setImageSize() with the + * The size of the screen image can be specified by calling setImageSize() with the * desired number of lines and columns. When new lines are added, old content - * is moved into a history store, which can be set by calling setHistory(). + * is moved into a history store, which can be set by calling setHistory(). * - * The screen image can be accessed by creating a ScreenWindow onto this emulation - * by calling createWindow(). Screen windows provide access to a section of the - * output. Each screen window covers the same number of lines and columns as the + * The screen image can be accessed by creating a ScreenWindow onto this emulation + * by calling createWindow(). Screen windows provide access to a section of the + * output. Each screen window covers the same number of lines and columns as the * image size returned by imageSize(). The screen window can be moved up and down - * and provides transparent access to both the current on-screen image and the + * and provides transparent access to both the current on-screen image and the * previous output. The screen windows emit an outputChanged signal * when the section of the image they are looking at changes. * Graphical views can then render the contents of a screen window, listening for notifications - * of output changes from the screen window which they are associated with and updating - * accordingly. + * of output changes from the screen window which they are associated with and updating + * accordingly. * * The emulation also is also responsible for converting input from the connected views such * as keypresses and mouse activity into a character string which can be sent @@ -107,9 +110,9 @@ enum * character sequences. The name of the key bindings set used can be specified using * setKeyBindings() * - * The emulation maintains certain state information which changes depending on the - * input received. The emulation can be reset back to its starting state by calling - * reset(). + * The emulation maintains certain state information which changes depending on the + * input received. The emulation can be reset back to its starting state by calling + * reset(). * * The emulation also maintains an activity state, which specifies whether * terminal is currently active ( when data is received ), normal @@ -119,15 +122,35 @@ enum * how long the emulation has been active/idle for and also respond to * a 'bell' event in different ways. */ -class Emulation : public QObject -{ +class QTERMWIDGET_EXPORT Emulation : public QObject +{ Q_OBJECT public: - - /** Constructs a new terminal emulation */ + + /** + * This enum describes the available shapes for the keyboard cursor. + * See setKeyboardCursorShape() + */ + enum class KeyboardCursorShape { + /** A rectangular block which covers the entire area of the cursor character. */ + BlockCursor = 0, + /** + * A single flat line which occupies the space at the bottom of the cursor + * character's area. + */ + UnderlineCursor = 1, + /** + * An cursor shaped like the capital letter 'I', similar to the IBeam + * cursor used in Qt/KDE text editors. + */ + IBeamCursor = 2 + }; + + + /** Constructs a new terminal emulation */ Emulation(); - ~Emulation(); + ~Emulation() override; /** * Creates a new window onto the output from this emulation. The contents @@ -137,70 +160,70 @@ public: ScreenWindow* createWindow(); /** Returns the size of the screen image which the emulation produces */ - QSize imageSize(); + QSize imageSize() const; /** * Returns the total number of lines, including those stored in the history. - */ - int lineCount(); + */ + int lineCount() const; - - /** + /** * Sets the history store used by this emulation. When new lines * are added to the output, older lines at the top of the screen are transferred to a history - * store. + * store. * - * The number of lines which are kept and the storage location depend on the + * The number of lines which are kept and the storage location depend on the * type of store. */ void setHistory(const HistoryType&); /** Returns the history store used by this emulation. See setHistory() */ - const HistoryType& history(); + const HistoryType& history() const; /** Clears the history scroll. */ void clearHistory(); - /** - * Copies the output history from @p startLine to @p endLine + /** + * Copies the output history from @p startLine to @p endLine * into @p stream, using @p decoder to convert the terminal - * characters into text. + * characters into text. * - * @param decoder A decoder which converts lines of terminal characters with + * @param decoder A decoder which converts lines of terminal characters with * appearance attributes into output text. PlainTextDecoder is the most commonly * used decoder. - * @param startLine The first + * @param startLine Index of first line to copy + * @param endLine Index of last line to copy */ virtual void writeToStream(TerminalCharacterDecoder* decoder,int startLine,int endLine); - - + /** Returns the codec used to decode incoming characters. See setCodec() */ - const QTextCodec* codec() { return _codec; } + const QTextCodec* codec() const { return _codec; } /** Sets the codec used to decode incoming characters. */ void setCodec(const QTextCodec*); - /** - * Convenience method. + /** + * Convenience method. * Returns true if the current codec used to decode incoming * characters is UTF-8 */ - bool utf8() { Q_ASSERT(_codec); return _codec->mibEnum() == 106; } - + bool utf8() const + { Q_ASSERT(_codec); return _codec->mibEnum() == 106; } + /** TODO Document me */ - virtual char getErase() const; + virtual char eraseChar() const; - /** + /** * Sets the key bindings used to key events * ( received through sendKeyEvent() ) into character * streams to send to the terminal. */ void setKeyBindings(const QString& name); - /** + /** * Returns the name of the emulation's current key bindings. * See setKeyBindings() */ - QString keyBindings(); + QString keyBindings() const; - /** + /** * Copies the current image into the history and clears the screen. */ virtual void clearEntireScreen() =0; @@ -208,7 +231,7 @@ public: /** Resets the state of the terminal. */ virtual void reset() =0; - /** + /** * Returns true if the active terminal program wants * mouse input events. * @@ -217,42 +240,44 @@ public: */ bool programUsesMouse() const; -public slots: + bool programBracketedPasteMode() const; + +public slots: /** Change the size of the emulation's image */ virtual void setImageSize(int lines, int columns); - - /** + + /** * Interprets a sequence of characters and sends the result to the terminal. * This is equivalent to calling sendKeyEvent() for each character in @p text in succession. */ virtual void sendText(const QString& text) = 0; - /** + /** * Interprets a key press event and emits the sendData() signal with - * the resulting character stream. + * the resulting character stream. */ - virtual void sendKeyEvent(QKeyEvent*); - - /** + virtual void sendKeyEvent(QKeyEvent*, bool fromPaste); + + /** * Converts information about a mouse event into an xterm-compatible escape * sequence and emits the character sequence via sendData() */ virtual void sendMouseEvent(int buttons, int column, int line, int eventType); - + /** - * Sends a string of characters to the foreground terminal process. + * Sends a string of characters to the foreground terminal process. * - * @param string The characters to send. + * @param string The characters to send. * @param length Length of @p string or if set to a negative value, @p string will * be treated as a null-terminated string and its length will be determined automatically. */ virtual void sendString(const char* string, int length = -1) = 0; - /** + /** * Processes an incoming stream of characters. receiveData() decodes the incoming * character buffer using the current codec(), and then calls receiveChar() for - * each unicode character in the resulting buffer. + * each unicode character in the resulting buffer. * * receiveData() also starts a timer which causes the outputChanged() signal * to be emitted when it expires. The timer allows multiple updates in quick @@ -265,29 +290,29 @@ public slots: signals: - /** - * Emitted when a buffer of data is ready to send to the + /** + * Emitted when a buffer of data is ready to send to the * standard input of the terminal. * * @param data The buffer of data ready to be sent - * @paran len The length of @p data in bytes + * @param len The length of @p data in bytes */ void sendData(const char* data,int len); - /** + /** * Requests that sending of input to the emulation * from the terminal process be suspended or resumed. * - * @param suspend If true, requests that sending of - * input from the terminal process' stdout be + * @param suspend If true, requests that sending of + * input from the terminal process' stdout be * suspended. Otherwise requests that sending of - * input be resumed. + * input be resumed. */ void lockPtyRequest(bool suspend); /** * Requests that the pty used by the terminal process - * be set to UTF 8 mode. + * be set to UTF 8 mode. * * TODO: More documentation */ @@ -315,7 +340,7 @@ signals: */ void changeTabTextColorRequest(int color); - /** + /** * This is emitted when the program running in the shell indicates whether or * not it is interested in mouse events. * @@ -324,7 +349,9 @@ signals: */ void programUsesMouseChanged(bool usesMouse); - /** + void programBracketedPasteModeChanged(bool bracketedPasteMode); + + /** * Emitted when the contents of the screen image change. * The emulation buffers the updates from successive image changes, * and only emits outputChanged() at sensible intervals when @@ -334,14 +361,14 @@ signals: * created with createWindow() to listen for this signal. * * ScreenWindow objects created using createWindow() will emit their - * own outputChanged() signal in response to this signal. + * own outputChanged() signal in response to this signal. */ void outputChanged(); /** - * Emitted when the program running in the terminal wishes to update the + * Emitted when the program running in the terminal wishes to update the * session's title. This also allows terminal programs to customize other - * aspects of the terminal emulation display. + * aspects of the terminal emulation display. * * This signal is emitted when the escape sequence "\033]ARG;VALUE\007" * is received in the input string, where ARG is a number specifying what @@ -349,7 +376,7 @@ signals: * * TODO: The name of this method is not very accurate since this method * is used to perform a whole range of tasks besides just setting - * the user-title of the session. + * the user-title of the session. * * @param title Specifies what to change. *
    @@ -357,17 +384,17 @@ signals: *
  • 1 - Set window icon text to @p newTitle
  • *
  • 2 - Set session title to @p newTitle
  • *
  • 11 - Set the session's default background color to @p newTitle, - * where @p newTitle can be an HTML-style string (#RRGGBB) or a named - * color (eg 'red', 'blue'). + * where @p newTitle can be an HTML-style string ("#RRGGBB") or a named + * color (eg 'red', 'blue'). * See http://doc.trolltech.com/4.2/qcolor.html#setNamedColor for more * details. *
  • *
  • 31 - Supposedly treats @p newTitle as a URL and opens it (NOT IMPLEMENTED)
  • - *
  • 32 - Sets the icon associated with the session. @p newTitle is the name + *
  • 32 - Sets the icon associated with the session. @p newTitle is the name * of the icon to use, which can be the name of any icon in the current KDE icon * theme (eg: 'konsole', 'kate', 'folder_home')
  • *
- * @param newTitle Specifies the new title + * @param newTitle Specifies the new title */ void titleChanged(int title,const QString& newTitle); @@ -378,9 +405,21 @@ signals: */ void imageSizeChanged(int lineCount , int columnCount); - /** + /** + * Emitted when the setImageSize() is called on this emulation for + * the first time. + */ + void imageSizeInitialized(); + + /** + * Emitted after receiving the escape sequence which asks to change + * the terminal emulator's size + */ + void imageResizeRequest(const QSize& sizz); + + /** * Emitted when the terminal program requests to change various properties - * of the terminal display. + * of the terminal display. * * A profile change command occurs when a special escape sequence, followed * by a string containing a series of name and value pairs is received. @@ -391,24 +430,43 @@ signals: */ void profileChangeCommandReceived(const QString& text); -protected: - virtual void setMode (int mode) = 0; - virtual void resetMode(int mode) = 0; - - /** - * Processes an incoming character. See receiveData() - * @p ch A unicode character code. + /** + * Emitted when a flow control key combination ( Ctrl+S or Ctrl+Q ) is pressed. + * @param suspendKeyPressed True if Ctrl+S was pressed to suspend output or Ctrl+Q to + * resume output. */ - virtual void receiveChar(int ch); + void flowControlKeyPressed(bool suspendKeyPressed); - /** + /** + * Emitted when the cursor shape or its blinking state is changed via + * DECSCUSR sequences. + * + * @param cursorShape One of 3 possible values in KeyboardCursorShape enum + * @param blinkingCursorEnabled Whether to enable blinking or not + */ + void cursorChanged(KeyboardCursorShape cursorShape, bool blinkingCursorEnabled); + + void handleCommandFromKeyboard(KeyboardTranslator::Command command); + void outputFromKeypressEvent(void); + +protected: + virtual void setMode(int mode) = 0; + virtual void resetMode(int mode) = 0; + + /** + * Processes an incoming character. See receiveData() + * @p ch A unicode character code. + */ + virtual void receiveChar(wchar_t ch); + + /** * Sets the active screen. The terminal has two screens, primary and alternate. * The primary screen is used by default. When certain interactive programs such * as Vim are run, they trigger a switch to the alternate screen. * * @param index 0 to switch to the primary screen, or 1 to switch to the alternate screen */ - void setScreen(int index); + void setScreen(int index); enum EmulationCodec { @@ -419,45 +477,46 @@ protected: QList _windows; - - Screen* _currentScreen; // pointer to the screen which is currently active, + + Screen* _currentScreen; // pointer to the screen which is currently active, // this is one of the elements in the screen[] array Screen* _screen[2]; // 0 = primary screen ( used by most programs, including the shell // scrollbars are enabled in this mode ) // 1 = alternate ( used by vi , emacs etc. // scrollbars are not enabled in this mode ) - - - //decodes an incoming C-style character stream into a unicode QString using + + + //decodes an incoming C-style character stream into a unicode QString using //the current text codec. (this allows for rendering of non-ASCII characters in text files etc.) const QTextCodec* _codec; QTextDecoder* _decoder; - const KeyboardTranslator* _keyTranslator; // the keyboard layout protected slots: - /** + /** * Schedules an update of attached views. * Repeated calls to bufferedUpdate() in close succession will result in only a single update, - * much like the Qt buffered update of widgets. + * much like the Qt buffered update of widgets. */ void bufferedUpdate(); -private slots: +private slots: // triggered by timer, causes the emulation to send an updated screen image to each // view - void showBulk(); + void showBulk(); void usesMouseChanged(bool usesMouse); -private: + void bracketedPasteModeChanged(bool bracketedPasteMode); +private: bool _usesMouse; + bool _bracketedPasteMode; QTimer _bulkTimer1; QTimer _bulkTimer2; - + }; } diff --git a/qtermwidget/src/ExtendedDefaultTranslator.h b/qtermwidget/lib/ExtendedDefaultTranslator.h similarity index 100% rename from qtermwidget/src/ExtendedDefaultTranslator.h rename to qtermwidget/lib/ExtendedDefaultTranslator.h diff --git a/qtermwidget/src/Filter.cpp b/qtermwidget/lib/Filter.cpp similarity index 75% rename from qtermwidget/src/Filter.cpp rename to qtermwidget/lib/Filter.cpp index b20f500..f219292 100644 --- a/qtermwidget/src/Filter.cpp +++ b/qtermwidget/lib/Filter.cpp @@ -1,7 +1,5 @@ /* - Copyright (C) 2007 by Robert Knight - - Rewritten for QT4 by e_k , Copyright (C)2008 + Copyright 2007-2008 by Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -22,18 +20,20 @@ // Own #include "Filter.h" - // System #include // Qt -#include -#include -#include -#include - -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include // KDE //#include @@ -41,13 +41,14 @@ // Konsole #include "TerminalCharacterDecoder.h" +#include "konsole_wcwidth.h" using namespace Konsole; FilterChain::~FilterChain() { QMutableListIterator iter(*this); - + while ( iter.hasNext() ) { Filter* filter = iter.next(); @@ -97,13 +98,13 @@ Filter::HotSpot* FilterChain::hotSpotAt(int line , int column) const { Filter* filter = iter.next(); Filter::HotSpot* spot = filter->hotSpotAt(line,column); - if ( spot != 0 ) + if ( spot != nullptr ) { return spot; } } - return 0; + return nullptr; } QList FilterChain::hotSpots() const @@ -120,8 +121,8 @@ QList FilterChain::hotSpots() const //QList FilterChain::hotSpotsAtLine(int line) const; TerminalImageFilterChain::TerminalImageFilterChain() -: _buffer(0) -, _linePositions(0) +: _buffer(nullptr) +, _linePositions(nullptr) { } @@ -133,19 +134,15 @@ TerminalImageFilterChain::~TerminalImageFilterChain() void TerminalImageFilterChain::setImage(const Character* const image , int lines , int columns, const QVector& 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* newLinePositions = new QList(); @@ -171,34 +168,31 @@ void TerminalImageFilterChain::setImage(const Character* const image , int lines // being treated as part of a link that occurs at the start of the next line // // the downside is that links which are spread over more than one line are not - // highlighted. + // highlighted. // // TODO - Use the "line wrapped" attribute associated with lines in a // terminal image to avoid adding this imaginary character for wrapped // lines if ( !(lineProperties.value(i,LINE_DEFAULT) & LINE_WRAPPED) ) - lineStream << QChar('\n'); + lineStream << QLatin1Char('\n'); } decoder.end(); -// qDebug("%s %d", __FILE__, __LINE__); } Filter::Filter() : -_linePositions(0), -_buffer(0) +_linePositions(nullptr), +_buffer(nullptr) { } Filter::~Filter() { - QListIterator iter(_hotspotList); - while (iter.hasNext()) - { - delete iter.next(); - } + qDeleteAll(_hotspotList); + _hotspotList.clear(); } void Filter::reset() { + qDeleteAll(_hotspotList); _hotspots.clear(); _hotspotList.clear(); } @@ -217,30 +211,22 @@ void Filter::getLineColumn(int position , int& startLine , int& startColumn) 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 ) + if ( _linePositions->value(i) <= position && position < nextLine ) { startLine = i; - startColumn = position - _linePositions->value(i); + startColumn = string_width(buffer()->mid(_linePositions->value(i),position - _linePositions->value(i)).toStdWString()); return; } } } - + /*void Filter::addLine(const QString& text) { @@ -262,7 +248,7 @@ void Filter::addHotSpot(HotSpot* spot) for (int line = spot->startLine() ; line <= spot->endLine() ; line++) { _hotspots.insert(line,spot); - } + } } QList Filter::hotSpots() const { @@ -280,16 +266,16 @@ Filter::HotSpot* Filter::hotSpotAt(int line , int column) const while (spotIter.hasNext()) { HotSpot* spot = spotIter.next(); - + if ( spot->startLine() == line && spot->startColumn() > column ) continue; if ( spot->endLine() == line && spot->endColumn() < column ) continue; - + return spot; } - return 0; + return nullptr; } Filter::HotSpot::HotSpot(int startLine , int startColumn , int endLine , int endColumn) @@ -300,10 +286,6 @@ Filter::HotSpot::HotSpot(int startLine , int startColumn , int endLine , int end , _type(NotSpecified) { } -QString Filter::HotSpot::tooltip() const -{ - return QString(); -} QList Filter::HotSpot::actions() { return QList(); @@ -343,7 +325,7 @@ RegExpFilter::HotSpot::HotSpot(int startLine,int startColumn,int endLine,int end setType(Marker); } -void RegExpFilter::HotSpot::activate(QObject*) +void RegExpFilter::HotSpot::activate(const QString&) { } @@ -356,7 +338,7 @@ QStringList RegExpFilter::HotSpot::capturedTexts() const return _capturedTexts; } -void RegExpFilter::setRegExp(const QRegExp& regExp) +void RegExpFilter::setRegExp(const QRegExp& regExp) { _searchText = regExp; } @@ -377,7 +359,7 @@ void RegExpFilter::process() // ignore any regular expressions which match an empty string. // otherwise the while loop below will run indefinitely - static const QString emptyString(""); + static const QString emptyString; if ( _searchText.exactMatch(emptyString) ) return; @@ -387,32 +369,26 @@ void RegExpFilter::process() 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 ); + addHotSpot( spot ); pos += _searchText.matchedLength(); // if matchedLength == 0, the program will get stuck in an infinite loop - Q_ASSERT( _searchText.matchedLength() > 0 ); + if ( _searchText.matchedLength() == 0 ) + pos = -1; } - } + } } RegExpFilter::HotSpot* RegExpFilter::newHotSpot(int startLine,int startColumn, @@ -424,32 +400,23 @@ RegExpFilter::HotSpot* RegExpFilter::newHotSpot(int startLine,int startColumn, RegExpFilter::HotSpot* UrlFilter::newHotSpot(int startLine,int startColumn,int endLine, int endColumn) { - return new UrlFilter::HotSpot(startLine,startColumn, + HotSpot *spot = new UrlFilter::HotSpot(startLine,startColumn, endLine,endColumn); + connect(spot->getUrlObject(), &FilterObject::activated, this, &UrlFilter::activated); + return spot; } + 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(); - + QString url = capturedTexts().constFirst(); + if ( FullUrlRegExp.exactMatch(url) ) return StandardUrl; else if ( EmailAddressRegExp.exactMatch(url) ) @@ -458,71 +425,80 @@ UrlFilter::HotSpot::UrlType UrlFilter::HotSpot::urlType() const return Unknown; } -void UrlFilter::HotSpot::activate(QObject* object) +void UrlFilter::HotSpot::activate(const QString& actionName) { - QString url = capturedTexts().first(); + QString url = capturedTexts().constFirst(); const UrlType kind = urlType(); - const QString& actionName = object ? object->objectName() : QString(); - - if ( actionName == "copy-action" ) + if ( actionName == QLatin1String("copy-action") ) { - //kDebug() << "Copying url to clipboard:" << url; - QApplication::clipboard()->setText(url); return; } - if ( !object || actionName == "open-action" ) + if ( actionName.isEmpty() || actionName == QLatin1String("open-action") || actionName == QLatin1String("click-action") ) { if ( kind == StandardUrl ) { // if the URL path does not include the protocol ( eg. "www.kde.org" ) then // prepend http:// ( eg. "www.kde.org" --> "http://www.kde.org" ) - if (!url.contains("://")) + if (!url.contains(QLatin1String("://"))) { - url.prepend("http://"); + url.prepend(QLatin1String("http://")); } - } + } else if ( kind == Email ) { - url.prepend("mailto:"); + url.prepend(QLatin1String("mailto:")); } - -// new KRun(url,QApplication::activeWindow()); + + _urlObject->emitActivated(QUrl(url, QUrl::StrictMode), actionName != QLatin1String("click-action")); } } -// Note: Altering these regular expressions can have a major effect on the performance of the filters +// Note: Altering these regular expressions can have a major effect on the performance of the filters // used for finding URLs in the text, especially if they are very general and could match very long // pieces of text. // Please be careful when altering them. //regexp matches: -// full url: +// full url: // protocolname:// or www. followed by anything other than whitespaces, <, >, ' or ", and ends before whitespaces, <, >, ', ", ], !, comma and dot -const QRegExp UrlFilter::FullUrlRegExp("(www\\.(?!\\.)|[a-z][a-z0-9+.-]*://)[^\\s<>'\"]+[^!,\\.\\s<>'\"\\]]"); +const QRegExp UrlFilter::FullUrlRegExp(QLatin1String("(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"); +const QRegExp UrlFilter::EmailAddressRegExp(QLatin1String("\\b(\\w|\\.|-)+@(\\w|\\.|-)+\\.\\w+\\b")); // matches full url or email address -const QRegExp UrlFilter::CompleteUrlRegExp('('+FullUrlRegExp.pattern()+'|'+ - EmailAddressRegExp.pattern()+')'); +const QRegExp UrlFilter::CompleteUrlRegExp(QLatin1Char('(')+FullUrlRegExp.pattern()+QLatin1Char('|')+ + EmailAddressRegExp.pattern()+QLatin1Char(')')); UrlFilter::UrlFilter() { setRegExp( CompleteUrlRegExp ); } + UrlFilter::HotSpot::~HotSpot() { delete _urlObject; } -void FilterObject::activated() + +void FilterObject::emitActivated(const QUrl& url, bool fromContextMenu) { - _filter->activate(sender()); + emit activated(url, fromContextMenu); } + +void FilterObject::activate() +{ + _filter->activate(sender()->objectName()); +} + +FilterObject* UrlFilter::HotSpot::getUrlObject() const +{ + return _urlObject; +} + QList UrlFilter::HotSpot::actions() { QList list; @@ -536,28 +512,28 @@ QList UrlFilter::HotSpot::actions() if ( kind == StandardUrl ) { - openAction->setText(("Open Link")); - copyAction->setText(("Copy Link Address")); + openAction->setText(QObject::tr("Open Link")); + copyAction->setText(QObject::tr("Copy Link Address")); } else if ( kind == Email ) { - openAction->setText(("Send Email To...")); - copyAction->setText(("Copy Email Address")); + openAction->setText(QObject::tr("Send Email To...")); + copyAction->setText(QObject::tr("Copy Email Address")); } // object names are set here so that the hotspot performs the // correct action when activated() is called with the triggered // action passed as a parameter. - openAction->setObjectName("open-action"); - copyAction->setObjectName("copy-action"); + openAction->setObjectName( QLatin1String("open-action" )); + copyAction->setObjectName( QLatin1String("copy-action" )); - QObject::connect( openAction , SIGNAL(triggered()) , _urlObject , SLOT(activated()) ); - QObject::connect( copyAction , SIGNAL(triggered()) , _urlObject , SLOT(activated()) ); + QObject::connect( openAction , &QAction::triggered , _urlObject , &FilterObject::activate ); + QObject::connect( copyAction , &QAction::triggered , _urlObject , &FilterObject::activate ); list << openAction; list << copyAction; - return list; + return list; } -//#include "moc_Filter.cpp" +//#include "Filter.moc" diff --git a/qtermwidget/src/Filter.h b/qtermwidget/lib/Filter.h similarity index 80% rename from qtermwidget/src/Filter.h rename to qtermwidget/lib/Filter.h index 06ea5e3..64cb36f 100644 --- a/qtermwidget/src/Filter.h +++ b/qtermwidget/lib/Filter.h @@ -1,7 +1,5 @@ /* - Copyright (C) 2007 by Robert Knight - - Rewritten for QT4 by e_k , Copyright (C)2008 + Copyright 2007-2008 by Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -23,19 +21,26 @@ #define FILTER_H // Qt -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#if QT_VERSION >= 0x060000 +#include +#else +#include +#endif // Local -#include "Character.h" +#include "qtermwidget_export.h" namespace Konsole { +typedef unsigned char LineProperty; +class Character; + /** * A filter processes blocks of text looking for certain patterns (such as URLs or keywords from a list) * and marks the areas which match the filter's patterns as 'hotspots'. @@ -46,7 +51,7 @@ namespace Konsole * activate() method should be called. Depending on the type of hotspot this will trigger a suitable response. * * For example, if a hotspot represents a URL then a suitable action would be opening that URL in a web browser. - * Hotspots may have more than one action, in which case the list of actions can be obtained using the + * Hotspots may have more than one action, in which case the list of actions can be obtained using the * actions() method. * * Different subclasses of filter will return different types of hotspot. @@ -54,7 +59,7 @@ namespace Konsole * When processing the text they should create instances of Filter::HotSpot subclasses for sections of interest * and add them to the filter's list of hotspots using addHotSpot() */ -class Filter +class QTERMWIDGET_EXPORT Filter : public QObject { public: /** @@ -66,13 +71,13 @@ public: * activate() method should be called. Depending on the type of hotspot this will trigger a suitable response. * * For example, if a hotspot represents a URL then a suitable action would be opening that URL in a web browser. - * Hotspots may have more than one action, in which case the list of actions can be obtained using the - * actions() method. These actions may then be displayed in a popup menu or toolbar for example. + * Hotspots may have more than one action, in which case the list of actions can be obtained using the + * actions() method. These actions may then be displayed in a popup menu or toolbar for example. */ class HotSpot { public: - /** + /** * Constructs a new hotspot which covers the area from (@p startLine,@p startColumn) to (@p endLine,@p endColumn) * in a block of text. */ @@ -87,7 +92,7 @@ public: Link, // this hotspot represents a marker Marker - }; + }; /** Returns the line when the hotspot area starts */ int startLine() const; @@ -97,34 +102,26 @@ public: int startColumn() const; /** Returns the column on endLine() where the hotspot area ends */ int endColumn() const; - /** + /** * Returns the type of the hotspot. This is usually used as a hint for views on how to represent * the hotspot graphically. eg. Link hotspots are typically underlined when the user mouses over them */ Type type() const; - /** - * Causes the an action associated with a hotspot to be triggered. + /** + * Causes the an action associated with a hotspot to be triggered. * - * @param object The object which caused the hotspot to be triggered. This is - * typically null ( in which case the default action should be performed ) or - * one of the objects from the actions() list. In which case the associated - * action should be performed. + * @param action The action to trigger. This is + * typically empty ( in which case the default action should be performed ) or + * one of the object names from the actions() list. In which case the associated + * action should be performed. */ - virtual void activate(QObject* object = 0) = 0; - /** - * Returns a list of actions associated with the hotspot which can be used in a - * menu or toolbar + virtual void activate(const QString& action = QString()) = 0; + /** + * Returns a list of actions associated with the hotspot which can be used in a + * menu or toolbar */ virtual QList actions(); - /** - * Returns the text of a tooltip to be shown when the mouse moves over the hotspot, or - * an empty string if there is no tooltip associated with this hotspot. - * - * The default implementation returns an empty string. - */ - virtual QString tooltip() const; - protected: /** Sets the type of a hotspot. This should only be set once */ void setType(Type type); @@ -135,19 +132,19 @@ public: int _endLine; int _endColumn; Type _type; - + }; /** Constructs a new filter. */ Filter(); - virtual ~Filter(); + ~Filter() override; /** Causes the filter to process the block of text currently in its internal buffer */ virtual void process() = 0; - /** + /** * Empties the filters internal buffer and resets the line count back to 0. - * All hotspots are deleted. + * All hotspots are deleted. */ void reset(); @@ -163,7 +160,7 @@ public: /** Returns the list of hotspots identified by the filter which occur on a given line */ QList hotSpotsAtLine(int line) const; - /** + /** * TODO: Document me */ void setBuffer(const QString* buffer , const QList* linePositions); @@ -179,22 +176,22 @@ protected: private: QMultiHash _hotspots; QList _hotspotList; - + const QList* _linePositions; const QString* _buffer; }; -/** - * A filter which searches for sections of text matching a regular expression and creates a new RegExpFilter::HotSpot +/** + * A filter which searches for sections of text matching a regular expression and creates a new RegExpFilter::HotSpot * instance for them. * * Subclasses can reimplement newHotSpot() to return custom hotspot types when matches for the regular expression - * are found. + * are found. */ -class RegExpFilter : public Filter +class QTERMWIDGET_EXPORT RegExpFilter : public Filter { public: - /** + /** * Type of hotspot created by RegExpFilter. The capturedTexts() method can be used to find the text * matched by the filter's regular expression. */ @@ -202,7 +199,7 @@ public: { public: HotSpot(int startLine, int startColumn, int endLine , int endColumn); - virtual void activate(QObject* object = 0); + void activate(const QString& action = QString()) override; /** Sets the captured texts associated with this hotspot */ void setCapturedTexts(const QStringList& texts); @@ -215,26 +212,26 @@ public: /** Constructs a new regular expression filter */ RegExpFilter(); - /** - * Sets the regular expression which the filter searches for in blocks of text. + /** + * Sets the regular expression which the filter searches for in blocks of text. * * Regular expressions which match the empty string are treated as not matching - * anything. + * anything. */ void setRegExp(const QRegExp& text); /** Returns the regular expression which the filter searches for in blocks of text */ QRegExp regExp() const; - /** - * Reimplemented to search the filter's text buffer for text matching regExp() + /** + * Reimplemented to search the filter's text buffer for text matching regExp() * * If regexp matches the empty string, then process() will return immediately - * without finding results. + * without finding results. */ - virtual void process(); + void process() override; protected: - /** + /** * Called when a match for the regular expression is encountered. Subclasses should reimplement this * to return custom hotspot types */ @@ -248,28 +245,30 @@ private: class FilterObject; /** A filter which matches URLs in blocks of text */ -class UrlFilter : public RegExpFilter +class QTERMWIDGET_EXPORT UrlFilter : public RegExpFilter { + Q_OBJECT public: - /** - * Hotspot type created by UrlFilter instances. The activate() method opens a web browser + /** + * Hotspot type created by UrlFilter instances. The activate() method opens a web browser * at the given URL when called. */ - class HotSpot : public RegExpFilter::HotSpot + class HotSpot : public RegExpFilter::HotSpot { public: HotSpot(int startLine,int startColumn,int endLine,int endColumn); - virtual ~HotSpot(); + ~HotSpot() override; - virtual QList actions(); + FilterObject* getUrlObject() const; - /** + QList actions() override; + + /** * Open a web browser at the current URL. The url itself can be determined using * the capturedTexts() method. */ - virtual void activate(QObject* object = 0); + void activate(const QString& action = QString()) override; - virtual QString tooltip() const; private: enum UrlType { @@ -285,33 +284,39 @@ public: UrlFilter(); protected: - virtual RegExpFilter::HotSpot* newHotSpot(int,int,int,int); + RegExpFilter::HotSpot* newHotSpot(int,int,int,int) override; private: - + static const QRegExp FullUrlRegExp; static const QRegExp EmailAddressRegExp; // combined OR of FullUrlRegExp and EmailAddressRegExp - static const QRegExp CompleteUrlRegExp; + static const QRegExp CompleteUrlRegExp; +signals: + void activated(const QUrl& url, bool fromContextMenu); }; -class FilterObject : public QObject +class QTERMWIDGET_NO_EXPORT FilterObject : public QObject { -Q_OBJECT + Q_OBJECT public: FilterObject(Filter::HotSpot* filter) : _filter(filter) {} -private slots: - void activated(); + + void emitActivated(const QUrl& url, bool fromContextMenu); +public slots: + void activate(); private: Filter::HotSpot* _filter; +signals: + void activated(const QUrl& url, bool fromContextMenu); }; -/** - * A chain which allows a group of filters to be processed as one. +/** + * A chain which allows a group of filters to be processed as one. * The chain owns the filters added to it and deletes them when the chain itself is destroyed. * - * Use addFilter() to add a new filter to the chain. + * Use addFilter() to add a new filter to the chain. * When new text to be filtered arrives, use addLine() to add each additional * line of text which needs to be processed and then after adding the last line, use * process() to cause each filter in the chain to process the text. @@ -324,7 +329,7 @@ private: * The hotSpots() and hotSpotsAtLine() method return all of the hotspots in the text and on * a given line respectively. */ -class FilterChain : protected QList +class QTERMWIDGET_EXPORT FilterChain : protected QList { public: virtual ~FilterChain(); @@ -341,12 +346,12 @@ public: /** Resets each filter in the chain */ void reset(); /** - * Processes each filter in the chain + * Processes each filter in the chain */ void process(); /** Sets the buffer for each filter in the chain to process. */ - void setBuffer(const QString* buffer , const QList* linePositions); + void setBuffer(const QString* buffer , const QList* linePositions); /** Returns the first hotspot which occurs at @p line, @p column or 0 if no hotspot was found */ Filter::HotSpot* hotSpotAt(int line , int column) const; @@ -358,11 +363,11 @@ public: }; /** A filter chain which processes character images from terminal displays */ -class TerminalImageFilterChain : public FilterChain +class QTERMWIDGET_NO_EXPORT TerminalImageFilterChain : public FilterChain { public: TerminalImageFilterChain(); - virtual ~TerminalImageFilterChain(); + ~TerminalImageFilterChain() override; /** * Set the current terminal image to @p image. @@ -370,9 +375,10 @@ public: * @param image The terminal image * @param lines The number of lines in the terminal image * @param columns The number of columns in the terminal image + * @param lineProperties The line properties to set for image */ void setImage(const Character* const image , int lines , int columns, - const QVector& lineProperties); + const QVector& lineProperties); private: QString* _buffer; @@ -380,4 +386,7 @@ private: }; } + +typedef Konsole::Filter Filter; + #endif //FILTER_H diff --git a/qtermwidget/src/History.cpp b/qtermwidget/lib/History.cpp similarity index 58% rename from qtermwidget/src/History.cpp rename to qtermwidget/lib/History.cpp index 1e3d721..d8220da 100644 --- a/qtermwidget/src/History.cpp +++ b/qtermwidget/lib/History.cpp @@ -1,8 +1,6 @@ /* This file is part of Konsole, an X terminal. - Copyright (C) 1997,1998 by Lars Doelle - - Rewritten for QT4 by e_k , Copyright (C)2008 + Copyright 1997,1998 by Lars Doelle This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -24,18 +22,24 @@ #include "History.h" // System +#include #include -#include -#include -#include +#include +#include #include #include #include -#include +#include +#include + +// KDE +//#include +//#include // Reasonable line size -#define LINE_SIZE 1024 +#define LINE_SIZE 1024 +#define KDE_lseek lseek using namespace Konsole; @@ -55,7 +59,7 @@ using namespace Konsole; KDE4: Can we use QTemporaryFile here, instead of KTempFile? -FIXME: some complain about the history buffer comsuming the +FIXME: some complain about the history buffer consuming 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. @@ -72,7 +76,7 @@ FIXME: There is noticeable decrease in speed, also. Perhaps, scheme with wrap around would be it's complexity. */ -//FIXME: tempory replacement for tmpfile +//FIXME: temporary replacement for tmpfile // this is here one for debugging purpose. //#define tmpfile xTmpFile @@ -86,10 +90,11 @@ FIXME: There is noticeable decrease in speed, also. Perhaps, HistoryFile::HistoryFile() : ion(-1), length(0), - fileMap(0) + fileMap(nullptr), + readWriteBalance(0) { if (tmpFile.open()) - { + { tmpFile.setAutoRemove(true); ion = tmpFile.handle(); } @@ -97,8 +102,8 @@ HistoryFile::HistoryFile() HistoryFile::~HistoryFile() { - if (fileMap) - unmap(); + if (fileMap) + unmap(); } //TODO: Mapping the entire file in will cause problems if the history file becomes exceedingly large, @@ -106,69 +111,69 @@ HistoryFile::~HistoryFile() //to avoid this. void HistoryFile::map() { - assert( fileMap == 0 ); + Q_ASSERT( fileMap == nullptr ); - fileMap = (char*)mmap( 0 , length , PROT_READ , MAP_PRIVATE , ion , 0 ); + fileMap = (char*)mmap( nullptr , 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; + readWriteBalance = 0; + fileMap = nullptr; + //qDebug() << __FILE__ << __LINE__ << ": mmap'ing history failed. errno = " << errno; } } void HistoryFile::unmap() { - int result = munmap( fileMap , length ); - assert( result == 0 ); + int result = munmap( fileMap , length ); + Q_ASSERT( result == 0 ); Q_UNUSED( result ); - fileMap = 0; + fileMap = nullptr; } -bool HistoryFile::isMapped() +bool HistoryFile::isMapped() const { - return (fileMap != 0); + return (fileMap != nullptr); } void HistoryFile::add(const unsigned char* bytes, int len) { if ( fileMap ) - unmap(); - + unmap(); + readWriteBalance++; int rc = 0; - rc = lseek(ion,length,SEEK_SET); if (rc < 0) { perror("HistoryFile::add.seek"); return; } + rc = KDE_lseek(ion,length,SEEK_SET); if (rc < 0) { perror("HistoryFile::add.seek"); return; } rc = write(ion,bytes,len); if (rc < 0) { perror("HistoryFile::add.write"); return; } length += rc; } void HistoryFile::get(unsigned char* bytes, int len, int loc) { - //count number of get() calls vs. number of add() calls. - //If there are many more get() calls compared with add() + //count number of get() calls vs. number of add() calls. + //If there are many more get() calls compared with add() //calls (decided by using MAP_THRESHOLD) then mmap the log //file to improve performance. readWriteBalance--; if ( !fileMap && readWriteBalance < MAP_THRESHOLD ) - map(); + map(); if ( fileMap ) { - for (int i=0;i length) - fprintf(stderr,"getHist(...,%d,%d): invalid args.\n",len,loc); - rc = lseek(ion,loc,SEEK_SET); if (rc < 0) { perror("HistoryFile::get.seek"); return; } - rc = read(ion,bytes,len); if (rc < 0) { perror("HistoryFile::get.read"); return; } + if (loc < 0 || len < 0 || loc + len > length) + fprintf(stderr,"getHist(...,%d,%d): invalid args.\n",len,loc); + rc = KDE_lseek(ion,loc,SEEK_SET); if (rc < 0) { perror("HistoryFile::get.seek"); return; } + rc = read(ion,bytes,len); if (rc < 0) { perror("HistoryFile::get.read"); return; } } } @@ -198,10 +203,10 @@ bool HistoryScroll::hasScroll() // History Scroll File ////////////////////////////////////// -/* +/* The history scroll makes a Row(Row(Cell)) from two history buffers. The index buffer contains - start of line positions which refere to the cells + start of line positions which refers to the cells buffer. Note that index[0] addresses the second line @@ -218,7 +223,7 @@ HistoryScrollFile::HistoryScrollFile(const QString &logFileName) HistoryScrollFile::~HistoryScrollFile() { } - + int HistoryScrollFile::getLines() { return index.len() / sizeof(int); @@ -243,12 +248,12 @@ int HistoryScrollFile::startOfLine(int lineno) { if (lineno <= 0) return 0; if (lineno <= getLines()) - { - - if (!index.isMapped()) - index.map(); - - int res; + { + + if (!index.isMapped()) + index.map(); + + int res = 0; index.get((unsigned char*)&res,sizeof(int),(lineno-1)*sizeof(int)); return res; } @@ -268,7 +273,7 @@ void HistoryScrollFile::addCells(const Character text[], int count) void HistoryScrollFile::addLine(bool previousWrapped) { if (index.isMapped()) - index.unmap(); + index.unmap(); int locn = cells.len(); index.add((unsigned char*)&locn,sizeof(int)); @@ -310,7 +315,7 @@ void HistoryScrollBuffer::addCellsVector(const QVector& cells) void HistoryScrollBuffer::addCells(const Character a[], int count) { HistoryLine newLine(count); - qCopy(a,a+count,newLine.begin()); + std::copy(a,a+count,newLine.begin()); addCellsVector(newLine); } @@ -342,7 +347,7 @@ int HistoryScrollBuffer::getLineLen(int lineNumber) bool HistoryScrollBuffer::isWrappedLine(int lineNumber) { Q_ASSERT( lineNumber >= 0 && lineNumber < _maxLineCount ); - + if (lineNumber < _usedLines) { //kDebug() << "Line" << lineNumber << "wrapped is" << _wrappedLine[bufferIndex(lineNumber)]; @@ -352,18 +357,18 @@ bool HistoryScrollBuffer::isWrappedLine(int lineNumber) return false; } -void HistoryScrollBuffer::getCells(int lineNumber, int startColumn, int count, Character* buffer) +void HistoryScrollBuffer::getCells(int lineNumber, int startColumn, int count, Character buffer[]) { if ( count == 0 ) return; Q_ASSERT( lineNumber < _maxLineCount ); - if (lineNumber >= _usedLines) + if (lineNumber >= _usedLines) { - memset(buffer, 0, count * sizeof(Character)); + memset(static_cast(buffer), 0, count * sizeof(Character)); return; } - + const HistoryLine& line = _historyBuffer[bufferIndex(lineNumber)]; //kDebug() << "startCol " << startColumn; @@ -371,7 +376,7 @@ void HistoryScrollBuffer::getCells(int lineNumber, int startColumn, int count, C //kDebug() << "count " << count; Q_ASSERT( startColumn <= line.size() - count ); - + memcpy(buffer, line.constData() + startColumn , count * sizeof(Character)); } @@ -379,12 +384,12 @@ void HistoryScrollBuffer::setMaxNbLines(unsigned int lineCount) { HistoryLine* oldBuffer = _historyBuffer; HistoryLine* newBuffer = new HistoryLine[lineCount]; - + for ( int i = 0 ; i < qMin(_usedLines,(int)lineCount) ; i++ ) { newBuffer[i] = oldBuffer[bufferIndex(i)]; } - + _usedLines = qMin(_usedLines,(int)lineCount); _maxLineCount = lineCount; _head = ( _usedLines == _maxLineCount ) ? 0 : _usedLines-1; @@ -393,9 +398,10 @@ void HistoryScrollBuffer::setMaxNbLines(unsigned int lineCount) delete[] oldBuffer; _wrappedLine.resize(lineCount); + dynamic_cast(m_histType)->m_nbLines = lineCount; } -int HistoryScrollBuffer::bufferIndex(int lineNumber) +int HistoryScrollBuffer::bufferIndex(int lineNumber) const { Q_ASSERT( lineNumber >= 0 ); Q_ASSERT( lineNumber < _maxLineCount ); @@ -406,7 +412,7 @@ int HistoryScrollBuffer::bufferIndex(int lineNumber) return (_head+lineNumber+1) % _maxLineCount; } else - { + { return lineNumber; } } @@ -493,30 +499,30 @@ void HistoryScrollBlockArray::getCells(int lineno, int colno, const Block *b = m_blockArray.at(lineno); if (!b) { - memset(res, 0, count * sizeof(Character)); // still better than random data + memset(static_cast(res), 0, count * sizeof(Character)); // still better than random data return; } - assert(((colno + count) * sizeof(Character)) < ENTRIES); + Q_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); + Q_ASSERT((count * sizeof(Character)) < ENTRIES); - memset(b->data, 0, ENTRIES); + memset(b->data, 0, sizeof(b->data)); memcpy(b->data, a, count * sizeof(Character)); b->size = count * sizeof(Character); size_t res = m_blockArray.newBlock(); - assert (res > 0); + Q_ASSERT(res > 0); Q_UNUSED( res ); m_lineLengths.insert(m_blockArray.getCurrent(), count); @@ -526,6 +532,257 @@ void HistoryScrollBlockArray::addLine(bool) { } +//////////////////////////////////////////////////////////////// +// Compact History Scroll ////////////////////////////////////// +//////////////////////////////////////////////////////////////// +void* CompactHistoryBlock::allocate ( size_t length ) +{ + Q_ASSERT ( length > 0 ); + if ( tail-blockStart+length > blockLength ) + return nullptr; + + void* block = tail; + tail += length; + //kDebug() << "allocated " << length << " bytes at address " << block; + allocCount++; + return block; +} + +void CompactHistoryBlock::deallocate ( ) +{ + allocCount--; + Q_ASSERT ( allocCount >= 0 ); +} + +void* CompactHistoryBlockList::allocate(size_t size) +{ + CompactHistoryBlock* block; + if ( list.isEmpty() || list.last()->remaining() < size) + { + block = new CompactHistoryBlock(); + list.append ( block ); + //kDebug() << "new block created, remaining " << block->remaining() << "number of blocks=" << list.size(); + } + else + { + block = list.last(); + //kDebug() << "old block used, remaining " << block->remaining(); + } + return block->allocate(size); +} + +void CompactHistoryBlockList::deallocate(void* ptr) +{ + Q_ASSERT( !list.isEmpty()); + + int i=0; + CompactHistoryBlock *block = list.at(i); + while ( icontains(ptr) ) + { + i++; + block=list.at(i); + } + + Q_ASSERT( ideallocate(); + + if (!block->isInUse()) + { + list.removeAt(i); + delete block; + //kDebug() << "block deleted, new size = " << list.size(); + } +} + +CompactHistoryBlockList::~CompactHistoryBlockList() +{ + qDeleteAll ( list.begin(), list.end() ); + list.clear(); +} + +void* CompactHistoryLine::operator new (size_t size, CompactHistoryBlockList& blockList) +{ + return blockList.allocate(size); +} + +CompactHistoryLine::CompactHistoryLine ( const TextLine& line, CompactHistoryBlockList& bList ) + : blockList(bList), + formatLength(0) +{ + length=line.size(); + + if (!line.empty()) { + formatLength=1; + int k=1; + + // count number of different formats in this text line + Character c = line[0]; + while ( k0) { + blockList.deallocate(text); + blockList.deallocate(formatArray); + } + blockList.deallocate(this); +} + +void CompactHistoryLine::getCharacter ( int index, Character &r ) +{ + Q_ASSERT ( index < length ); + int formatPos=0; + while ( ( formatPos+1 ) < formatLength && index >= formatArray[formatPos+1].startPos ) + formatPos++; + + r.character=text[index]; + r.rendition = formatArray[formatPos].rendition; + r.foregroundColor = formatArray[formatPos].fgColor; + r.backgroundColor = formatArray[formatPos].bgColor; +} + +void CompactHistoryLine::getCharacters ( Character* array, int length, int startColumn ) +{ + Q_ASSERT ( startColumn >= 0 && length >= 0 ); + Q_ASSERT ( startColumn+length <= ( int ) getLength() ); + + for ( int i=startColumn; i ( int ) _maxLineCount ) + { + delete lines.takeAt ( 0 ); + } + lines.append ( line ); +} + +void CompactHistoryScroll::addCells ( const Character a[], int count ) +{ + TextLine newLine ( count ); + std::copy ( a,a+count,newLine.begin() ); + addCellsVector ( newLine ); +} + +void CompactHistoryScroll::addLine ( bool previousWrapped ) +{ + CompactHistoryLine *line = lines.last(); + //kDebug() << "last line at address " << line; + line->setWrapped(previousWrapped); +} + +int CompactHistoryScroll::getLines() +{ + return lines.size(); +} + +int CompactHistoryScroll::getLineLen ( int lineNumber ) +{ + Q_ASSERT ( lineNumber >= 0 && lineNumber < lines.size() ); + CompactHistoryLine* line = lines[lineNumber]; + //kDebug() << "request for line at address " << line; + return line->getLength(); +} + + +void CompactHistoryScroll::getCells ( int lineNumber, int startColumn, int count, Character buffer[] ) +{ + if ( count == 0 ) return; + Q_ASSERT ( lineNumber < lines.size() ); + CompactHistoryLine* line = lines[lineNumber]; + Q_ASSERT ( startColumn >= 0 ); + Q_ASSERT ( (unsigned int)startColumn <= line->getLength() - count ); + line->getCharacters ( buffer, count, startColumn ); +} + +void CompactHistoryScroll::setMaxNbLines ( unsigned int lineCount ) +{ + _maxLineCount = lineCount; + + while (lines.size() > (int) lineCount) { + delete lines.takeAt(0); + } + //kDebug() << "set max lines to: " << _maxLineCount; +} + +bool CompactHistoryScroll::isWrappedLine ( int lineNumber ) +{ + Q_ASSERT ( lineNumber < lines.size() ); + return lines[lineNumber]->isWrapped(); +} + + ////////////////////////////////////////////////////////////////////// // History Types ////////////////////////////////////////////////////////////////////// @@ -662,13 +919,13 @@ const QString& HistoryTypeFile::getFileName() const HistoryScroll* HistoryTypeFile::scroll(HistoryScroll *old) const { - if (dynamic_cast(old)) + if (dynamic_cast(old)) return old; // Unchanged. HistoryScroll *newScroll = new HistoryScrollFile(m_fileName); Character line[LINE_SIZE]; - int lines = (old != 0) ? old->getLines() : 0; + int lines = (old != nullptr) ? old->getLines() : 0; for(int i = 0; i < lines; i++) { int size = old->getLineLen(i); @@ -689,10 +946,42 @@ HistoryScroll* HistoryTypeFile::scroll(HistoryScroll *old) const } delete old; - return newScroll; + return newScroll; } int HistoryTypeFile::maximumLineCount() const { return 0; } + +////////////////////////////// + +CompactHistoryType::CompactHistoryType ( unsigned int nbLines ) + : m_nbLines ( nbLines ) +{ +} + +bool CompactHistoryType::isEnabled() const +{ + return true; +} + +int CompactHistoryType::maximumLineCount() const +{ + return m_nbLines; +} + +HistoryScroll* CompactHistoryType::scroll ( HistoryScroll *old ) const +{ + if ( old ) + { + CompactHistoryScroll *oldBuffer = dynamic_cast ( old ); + if ( oldBuffer ) + { + oldBuffer->setMaxNbLines ( m_nbLines ); + return oldBuffer; + } + delete old; + } + return new CompactHistoryScroll ( m_nbLines ); +} diff --git a/qtermwidget/src/History.h b/qtermwidget/lib/History.h similarity index 51% rename from qtermwidget/src/History.h rename to qtermwidget/lib/History.h index a26a367..5487999 100644 --- a/qtermwidget/src/History.h +++ b/qtermwidget/lib/History.h @@ -1,8 +1,6 @@ /* This file is part of Konsole, an X terminal. - Copyright (C) 1997,1998 by Lars Doelle - - Rewritten for QT4 by e_k , Copyright (C)2008 + Copyright 1997,1998 by Lars Doelle This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -24,14 +22,21 @@ #define TEHISTORY_H // Qt -#include -#include -#include +#include +#include +#include +#include + +// KDE +//#include // Konsole #include "BlockArray.h" #include "Character.h" +// map +#include + namespace Konsole { @@ -55,7 +60,7 @@ public: //un-mmaps the file void unmap(); //returns true if the file is mmap'ed - bool isMapped(); + bool isMapped() const; private: @@ -65,8 +70,8 @@ private: //pointer to start of mmap'ed file data, or 0 if the file is not mmap'ed char* fileMap; - - //incremented whenver 'add' is called and decremented whenever + + //incremented whenever 'add' is called and decremented whenever //'get' is called. //this is used to detect when a large number of lines are being read and processed from the history //and automatically mmap the file for better performance (saves the overhead of many lseek-read calls). @@ -134,15 +139,15 @@ class HistoryScrollFile : public HistoryScroll { public: HistoryScrollFile(const QString &logFileName); - virtual ~HistoryScrollFile(); + ~HistoryScrollFile() override; - virtual int getLines(); - virtual int getLineLen(int lineno); - virtual void getCells(int lineno, int colno, int count, Character res[]); - virtual bool isWrappedLine(int lineno); + int getLines() override; + int getLineLen(int lineno) override; + void getCells(int lineno, int colno, int count, Character res[]) override; + bool isWrappedLine(int lineno) override; - virtual void addCells(const Character a[], int count); - virtual void addLine(bool previousWrapped=false); + void addCells(const Character a[], int count) override; + void addLine(bool previousWrapped=false) override; private: int startOfLine(int lineno); @@ -163,30 +168,30 @@ public: typedef QVector HistoryLine; HistoryScrollBuffer(unsigned int maxNbLines = 1000); - virtual ~HistoryScrollBuffer(); + ~HistoryScrollBuffer() override; - virtual int getLines(); - virtual int getLineLen(int lineno); - virtual void getCells(int lineno, int colno, int count, Character res[]); - virtual bool isWrappedLine(int lineno); + int getLines() override; + int getLineLen(int lineno) override; + void getCells(int lineno, int colno, int count, Character res[]) override; + bool isWrappedLine(int lineno) override; - virtual void addCells(const Character a[], int count); - virtual void addCellsVector(const QVector& cells); - virtual void addLine(bool previousWrapped=false); + void addCells(const Character a[], int count) override; + void addCellsVector(const QVector& cells) override; + void addLine(bool previousWrapped=false) override; void setMaxNbLines(unsigned int nbLines); - unsigned int maxNbLines() { return _maxLineCount; } - + unsigned int maxNbLines() const { return _maxLineCount; } + private: - int bufferIndex(int lineNumber); + int bufferIndex(int lineNumber) const; HistoryLine* _historyBuffer; QBitArray _wrappedLine; int _maxLineCount; - int _usedLines; + int _usedLines; int _head; - + //QVector m_histBuffer; //QBitArray m_wrappedLine; //unsigned int m_maxNbLines; @@ -218,17 +223,17 @@ class HistoryScrollNone : public HistoryScroll { public: HistoryScrollNone(); - virtual ~HistoryScrollNone(); + ~HistoryScrollNone() override; - virtual bool hasScroll(); + bool hasScroll() override; - virtual int getLines(); - virtual int getLineLen(int lineno); - virtual void getCells(int lineno, int colno, int count, Character res[]); - virtual bool isWrappedLine(int lineno); + int getLines() override; + int getLineLen(int lineno) override; + void getCells(int lineno, int colno, int count, Character res[]) override; + bool isWrappedLine(int lineno) override; - virtual void addCells(const Character a[], int count); - virtual void addLine(bool previousWrapped=false); + void addCells(const Character a[], int count) override; + void addLine(bool previousWrapped=false) override; }; ////////////////////////////////////////////////////////////////////// @@ -238,21 +243,148 @@ class HistoryScrollBlockArray : public HistoryScroll { public: HistoryScrollBlockArray(size_t size); - virtual ~HistoryScrollBlockArray(); + ~HistoryScrollBlockArray() override; - virtual int getLines(); - virtual int getLineLen(int lineno); - virtual void getCells(int lineno, int colno, int count, Character res[]); - virtual bool isWrappedLine(int lineno); + int getLines() override; + int getLineLen(int lineno) override; + void getCells(int lineno, int colno, int count, Character res[]) override; + bool isWrappedLine(int lineno) override; - virtual void addCells(const Character a[], int count); - virtual void addLine(bool previousWrapped=false); + void addCells(const Character a[], int count) override; + void addLine(bool previousWrapped=false) override; protected: BlockArray m_blockArray; QHash m_lineLengths; }; +////////////////////////////////////////////////////////////////////// +// History using compact storage +// This implementation uses a list of fixed-sized blocks +// where history lines are allocated in (avoids heap fragmentation) +////////////////////////////////////////////////////////////////////// +typedef QVector TextLine; + +class CharacterFormat +{ +public: + bool equalsFormat(const CharacterFormat &other) const { + return other.rendition==rendition && other.fgColor==fgColor && other.bgColor==bgColor; + } + + bool equalsFormat(const Character &c) const { + return c.rendition==rendition && c.foregroundColor==fgColor && c.backgroundColor==bgColor; + } + + void setFormat(const Character& c) { + rendition=c.rendition; + fgColor=c.foregroundColor; + bgColor=c.backgroundColor; + } + + CharacterColor fgColor, bgColor; + quint16 startPos; + quint8 rendition; +}; + +class CompactHistoryBlock +{ +public: + + CompactHistoryBlock(){ + blockLength = 4096*64; // 256kb + head = (quint8*) mmap(nullptr, blockLength, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0); + //head = (quint8*) malloc(blockLength); + Q_ASSERT(head != MAP_FAILED); + tail = blockStart = head; + allocCount=0; + } + + virtual ~CompactHistoryBlock(){ + //free(blockStart); + munmap(blockStart, blockLength); + } + + virtual unsigned int remaining(){ return blockStart+blockLength-tail;} + virtual unsigned length() { return blockLength; } + virtual void* allocate(size_t length); + virtual bool contains(void *addr) {return addr>=blockStart && addr<(blockStart+blockLength);} + virtual void deallocate(); + virtual bool isInUse(){ return allocCount!=0; } ; + +private: + size_t blockLength; + quint8* head; + quint8* tail; + quint8* blockStart; + int allocCount; +}; + +class CompactHistoryBlockList { +public: + CompactHistoryBlockList() {}; + ~CompactHistoryBlockList(); + + void *allocate( size_t size ); + void deallocate(void *); + int length() {return list.size();} +private: + QList list; +}; + +class CompactHistoryLine +{ +public: + CompactHistoryLine(const TextLine&, CompactHistoryBlockList& blockList); + virtual ~CompactHistoryLine(); + + // custom new operator to allocate memory from custom pool instead of heap + static void *operator new( size_t size, CompactHistoryBlockList& blockList); + static void operator delete( void *) { /* do nothing, deallocation from pool is done in destructor*/ } ; + + virtual void getCharacters(Character* array, int length, int startColumn) ; + virtual void getCharacter(int index, Character &r) ; + virtual bool isWrapped() const {return wrapped;}; + virtual void setWrapped(bool isWrapped) { wrapped=isWrapped;}; + virtual unsigned int getLength() const {return length;}; + +protected: + CompactHistoryBlockList& blockList; + CharacterFormat* formatArray; + quint16 length; + quint16* text; + quint16 formatLength; + bool wrapped; +}; + +class CompactHistoryScroll : public HistoryScroll +{ + typedef QList HistoryArray; + +public: + CompactHistoryScroll(unsigned int maxNbLines = 1000); + ~CompactHistoryScroll() override; + + int getLines() override; + int getLineLen(int lineno) override; + void getCells(int lineno, int colno, int count, Character res[]) override; + bool isWrappedLine(int lineno) override; + + void addCells(const Character a[], int count) override; + void addCellsVector(const TextLine& cells) override; + void addLine(bool previousWrapped=false) override; + + void setMaxNbLines(unsigned int nbLines); + unsigned int maxNbLines() const { return _maxLineCount; } + +private: + bool hasDifferentColors(const TextLine& line) const; + HistoryArray lines; + CompactHistoryBlockList blockList; + + unsigned int _maxLineCount; +}; + ////////////////////////////////////////////////////////////////////// // History type ////////////////////////////////////////////////////////////////////// @@ -265,7 +397,7 @@ public: /** * Returns true if the history is enabled ( can store lines of output ) - * or false otherwise. + * or false otherwise. */ virtual bool isEnabled() const = 0; /** @@ -286,37 +418,37 @@ class HistoryTypeNone : public HistoryType public: HistoryTypeNone(); - virtual bool isEnabled() const; - virtual int maximumLineCount() const; + bool isEnabled() const override; + int maximumLineCount() const override; - virtual HistoryScroll* scroll(HistoryScroll *) const; + HistoryScroll* scroll(HistoryScroll *) const override; }; class HistoryTypeBlockArray : public HistoryType { public: HistoryTypeBlockArray(size_t size); - - virtual bool isEnabled() const; - virtual int maximumLineCount() const; - virtual HistoryScroll* scroll(HistoryScroll *) const; + bool isEnabled() const override; + int maximumLineCount() const override; + + HistoryScroll* scroll(HistoryScroll *) const override; protected: size_t m_size; }; -#if 1 +#if 1 class HistoryTypeFile : public HistoryType { public: HistoryTypeFile(const QString& fileName=QString()); - virtual bool isEnabled() const; + bool isEnabled() const override; virtual const QString& getFileName() const; - virtual int maximumLineCount() const; + int maximumLineCount() const override; - virtual HistoryScroll* scroll(HistoryScroll *) const; + HistoryScroll* scroll(HistoryScroll *) const override; protected: QString m_fileName; @@ -325,18 +457,35 @@ protected: class HistoryTypeBuffer : public HistoryType { + friend class HistoryScrollBuffer; + public: HistoryTypeBuffer(unsigned int nbLines); - - virtual bool isEnabled() const; - virtual int maximumLineCount() const; - virtual HistoryScroll* scroll(HistoryScroll *) const; + bool isEnabled() const override; + int maximumLineCount() const override; + + HistoryScroll* scroll(HistoryScroll *) const override; protected: unsigned int m_nbLines; }; +class CompactHistoryType : public HistoryType +{ +public: + CompactHistoryType(unsigned int size); + + bool isEnabled() const override; + int maximumLineCount() const override; + + HistoryScroll* scroll(HistoryScroll *) const override; + +protected: + unsigned int m_nbLines; +}; + + #endif } diff --git a/qtermwidget/lib/HistorySearch.cpp b/qtermwidget/lib/HistorySearch.cpp new file mode 100644 index 0000000..25c98db --- /dev/null +++ b/qtermwidget/lib/HistorySearch.cpp @@ -0,0 +1,166 @@ +/* + Copyright 2013 Christian Surlykke + + 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. +*/ +#include +#include +#include + +#include "TerminalCharacterDecoder.h" +#include "Emulation.h" +#include "HistorySearch.h" + +HistorySearch::HistorySearch(EmulationPtr emulation, const RegExp& regExp, + bool forwards, int startColumn, int startLine, + QObject* parent) : +QObject(parent), +m_emulation(emulation), +m_regExp(regExp), +m_forwards(forwards), +m_startColumn(startColumn), +m_startLine(startLine) { +} + +HistorySearch::~HistorySearch() { +} + +void HistorySearch::search() { + bool found = false; + +#if QT_VERSION >= 0x060000 + if( ! m_regExp.isValid()) +#else + if (! m_regExp.isEmpty()) +#endif + { + if (m_forwards) { + found = search(m_startColumn, m_startLine, -1, m_emulation->lineCount()) || search(0, 0, m_startColumn, m_startLine); + } else { + found = search(0, 0, m_startColumn, m_startLine) || search(m_startColumn, m_startLine, -1, m_emulation->lineCount()); + } + + if (found) { + emit matchFound(m_foundStartColumn, m_foundStartLine, m_foundEndColumn, m_foundEndLine); + } + else { + emit noMatchFound(); + } + } + + deleteLater(); +} + +bool HistorySearch::search(int startColumn, int startLine, int endColumn, int endLine) { + qDebug() << "search from" << startColumn << "," << startLine + << "to" << endColumn << "," << endLine; + + int linesRead = 0; + int linesToRead = endLine - startLine + 1; + + qDebug() << "linesToRead:" << linesToRead; + + // We read process history from (and including) startLine to (and including) endLine in + // blocks of at most 10K lines so that we do not use unhealthy amounts of memory + int blockSize; + while ((blockSize = qMin(10000, linesToRead - linesRead)) > 0) { + + QString string; + QTextStream searchStream(&string); + PlainTextDecoder decoder; + decoder.begin(&searchStream); + decoder.setRecordLinePositions(true); + + // Calculate lines to read and read them + int blockStartLine = m_forwards ? startLine + linesRead : endLine - linesRead - blockSize + 1; + int chunkEndLine = blockStartLine + blockSize - 1; + m_emulation->writeToStream(&decoder, blockStartLine, chunkEndLine); + + // We search between startColumn in the first line of the string and endColumn in the last + // line of the string. First we calculate the position (in the string) of endColumn in the + // last line of the string + int endPosition; + + // The String that Emulator.writeToStream produces has a newline at the end, and so ends with an + // empty line - we ignore that. + int numberOfLinesInString = decoder.linePositions().size() - 1; + if (numberOfLinesInString > 0 && endColumn > -1 ) + { + endPosition = decoder.linePositions().at(numberOfLinesInString - 1) + endColumn; + } + else + { + endPosition = string.size(); + } + + // So now we can log for m_regExp in the string between startColumn and endPosition + int matchStart; + if (m_forwards) + { + matchStart = string.indexOf(m_regExp, startColumn); + if (matchStart >= endPosition) + matchStart = -1; + } + else + { + matchStart = string.lastIndexOf(m_regExp, endPosition - 1); + if (matchStart < startColumn) + matchStart = -1; + } + + if (matchStart > -1) + { +#if QT_VERSION >= 0x060000 + auto match = m_regExp.match(string); + int matchEnd = matchStart + match.capturedLength() - 1; +#else + int matchEnd = matchStart + m_regExp.matchedLength() - 1; +#endif + qDebug() << "Found in string from" << matchStart << "to" << matchEnd; + + // Translate startPos and endPos to startColum, startLine, endColumn and endLine in history. + int startLineNumberInString = findLineNumberInString(decoder.linePositions(), matchStart); + m_foundStartColumn = matchStart - decoder.linePositions().at(startLineNumberInString); + m_foundStartLine = startLineNumberInString + startLine + linesRead; + + int endLineNumberInString = findLineNumberInString(decoder.linePositions(), matchEnd); + m_foundEndColumn = matchEnd - decoder.linePositions().at(endLineNumberInString); + m_foundEndLine = endLineNumberInString + startLine + linesRead; + + qDebug() << "m_foundStartColumn" << m_foundStartColumn + << "m_foundStartLine" << m_foundEndLine + << "m_foundEndColumn" << m_foundEndColumn + << "m_foundEndLine" << m_foundEndLine; + + return true; + } + + + linesRead += blockSize; + } + + qDebug() << "Not found"; + return false; +} + + +int HistorySearch::findLineNumberInString(QList linePositions, int position) { + int lineNum = 0; + while (lineNum + 1 < linePositions.size() && linePositions[lineNum + 1] <= position) + lineNum++; + + return lineNum; +} diff --git a/qtermwidget/lib/HistorySearch.h b/qtermwidget/lib/HistorySearch.h new file mode 100644 index 0000000..0cf6ab7 --- /dev/null +++ b/qtermwidget/lib/HistorySearch.h @@ -0,0 +1,79 @@ +/* + Copyright 2013 Christian Surlykke + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. +*/ +#ifndef TASK_H +#define TASK_H + +#include +#include +#include + +#include +#include + +#include "Emulation.h" +#include "TerminalCharacterDecoder.h" + +#if QT_VERSION >= 0x060000 +#include +#include +#endif + +using namespace Konsole; + +typedef QPointer EmulationPtr; +#if QT_VERSION >= 0x060000 +typedef QRegularExpression RegExp; +#else +typedef QRegExp RegExp; +#endif +class HistorySearch : public QObject +{ + Q_OBJECT + +public: + explicit HistorySearch(EmulationPtr emulation, const RegExp& regExp, bool forwards, + int startColumn, int startLine, QObject* parent); + + ~HistorySearch() override; + + void search(); + +signals: + void matchFound(int startColumn, int startLine, int endColumn, int endLine); + void noMatchFound(); + +private: + bool search(int startColumn, int startLine, int endColumn, int endLine); + int findLineNumberInString(QList linePositions, int position); + + + EmulationPtr m_emulation; + RegExp m_regExp; + bool m_forwards; + int m_startColumn; + int m_startLine; + + int m_foundStartColumn; + int m_foundStartLine; + int m_foundEndColumn; + int m_foundEndLine; +}; + +#endif /* TASK_H */ + diff --git a/qtermwidget/src/KeyboardTranslator.cpp b/qtermwidget/lib/KeyboardTranslator.cpp similarity index 65% rename from qtermwidget/src/KeyboardTranslator.cpp rename to qtermwidget/lib/KeyboardTranslator.cpp index 1f7f112..fa9d46e 100644 --- a/qtermwidget/src/KeyboardTranslator.cpp +++ b/qtermwidget/lib/KeyboardTranslator.cpp @@ -1,9 +1,7 @@ /* - This source file was part of Konsole, a terminal emulator. + This source file is part of Konsole, a terminal emulator. - Copyright (C) 2007 by Robert Knight - - Rewritten for QT4 by e_k , Copyright (C)2008 + Copyright 2007-2008 by Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -25,16 +23,22 @@ #include "KeyboardTranslator.h" // System -#include -#include +#include +#include // Qt -#include -//#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#if QT_VERSION >= 0x060000 +#include +#include +#endif +#include "tools.h" // KDE //#include @@ -43,16 +47,18 @@ using namespace Konsole; -//this is for default REALLY fallback translator. -//const char* KeyboardTranslatorManager::defaultTranslatorText = -//#include "DefaultTranslatorText.h" -//; +const QByteArray KeyboardTranslatorManager::defaultTranslatorText( +"keyboard \"Fallback Key Translator\"\n" +"key Tab : \"\\t\"" +); -//and this is default now translator - default.keytab from original Konsole -const char* KeyboardTranslatorManager::defaultTranslatorText = -#include "ExtendedDefaultTranslator.h" -; +#ifdef Q_OS_MAC +// On Mac, Qt::ControlModifier means Cmd, and MetaModifier means Ctrl +const Qt::KeyboardModifier KeyboardTranslator::CTRL_MOD = Qt::MetaModifier; +#else +const Qt::KeyboardModifier KeyboardTranslator::CTRL_MOD = Qt::ControlModifier; +#endif KeyboardTranslatorManager::KeyboardTranslatorManager() : _haveLoadedAll(false) @@ -60,22 +66,25 @@ KeyboardTranslatorManager::KeyboardTranslatorManager() } KeyboardTranslatorManager::~KeyboardTranslatorManager() { - qDeleteAll(_translators.values()); + qDeleteAll(_translators); } QString KeyboardTranslatorManager::findTranslatorPath(const QString& name) { - return QString("kb-layouts/" + name + ".keytab"); + return QString(get_kb_layout_dir() + name + QLatin1String(".keytab")); + //return KGlobal::dirs()->findResource("data","konsole/"+name+".keytab"); } + void KeyboardTranslatorManager::findTranslators() { - QDir dir("kb-layouts/"); + QDir dir(get_kb_layout_dir()); QStringList filters; - filters << "*.keytab"; + filters << QLatin1String("*.keytab"); dir.setNameFilters(filters); - QStringList list = dir.entryList(filters); //(".keytab"); // = KGlobal::dirs()->findAllResources("data", - // "konsole/*.keytab", - // KStandardDirs::NoDuplicates); - list = dir.entryList(filters); + QStringList list = dir.entryList(filters); +// QStringList list = KGlobal::dirs()->findAllResources("data", +// "konsole/*.keytab", +// KStandardDirs::NoDuplicates); + // add the name of each translator to the list and associated // the name with a null pointer to indicate that the translator // has not yet been loaded from disk @@ -85,11 +94,11 @@ void KeyboardTranslatorManager::findTranslators() QString translatorPath = listIter.next(); QString name = QFileInfo(translatorPath).baseName(); - - if ( !_translators.contains(name) ) { + + if ( !_translators.contains(name) ) _translators.insert(name,0); - } } + _haveLoadedAll = true; } @@ -98,51 +107,48 @@ const KeyboardTranslator* KeyboardTranslatorManager::findTranslator(const QStrin if ( name.isEmpty() ) return defaultTranslator(); -//here was smth wrong in original Konsole source - findTranslators(); - - if ( _translators.contains(name) && _translators[name] != 0 ) { + if ( _translators.contains(name) && _translators[name] != 0 ) return _translators[name]; - } KeyboardTranslator* translator = loadTranslator(name); - if ( translator != 0 ) + if ( translator != nullptr ) _translators[name] = translator; else if ( !name.isEmpty() ) - qWarning() << "Unable to load translator" << name; + qDebug() << "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() << "KeyboardTranslatorManager::saveTranslator" << "unimplemented"; +Q_UNUSED(translator); +#if 0 + const QString path = KGlobal::dirs()->saveLocation("data","konsole/")+translator->name() + +".keytab"; - qDebug() << "Saving translator to" << path; + //kDebug() << "Saving translator to" << path; QFile destination(path); - if (!destination.open(QIODevice::WriteOnly | QIODevice::Text)) { - qWarning() << "Unable to save keyboard translation:" + qDebug() << "Unable to save keyboard translation:" << destination.errorString(); - return false; } { KeyboardTranslatorWriter writer(&destination); writer.writeHeader(translator->description()); - + QListIterator iter(translator->entries()); while ( iter.hasNext() ) writer.writeEntry(iter.next()); } destination.close(); - +#endif return true; } @@ -150,24 +156,26 @@ KeyboardTranslator* KeyboardTranslatorManager::loadTranslator(const QString& nam { const QString& path = findTranslatorPath(name); - QFile source(path); - + QFile source(path); if (name.isEmpty() || !source.open(QIODevice::ReadOnly | QIODevice::Text)) - return 0; + return nullptr; 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"); + // Try to find the default.keytab file if it exists, otherwise + // fall back to the hard-coded one + const KeyboardTranslator* translator = findTranslator(QLatin1String("default")); + if (!translator) + { + QBuffer textBuffer; + textBuffer.setData(defaultTranslatorText); + textBuffer.open(QIODevice::ReadOnly); + translator = loadTranslator(&textBuffer,QLatin1String("fallback")); + } + return translator; } KeyboardTranslator* KeyboardTranslatorManager::loadTranslator(QIODevice* source,const QString& name) @@ -175,10 +183,8 @@ KeyboardTranslator* KeyboardTranslatorManager::loadTranslator(QIODevice* source, KeyboardTranslator* translator = new KeyboardTranslator(name); KeyboardTranslatorReader reader(source); translator->setDescription( reader.description() ); - - while ( reader.hasNextEntry() ) { + while ( reader.hasNextEntry() ) translator->addEntry(reader.nextEntry()); - } source->close(); @@ -189,7 +195,7 @@ KeyboardTranslator* KeyboardTranslatorManager::loadTranslator(QIODevice* source, else { delete translator; - return 0; + return nullptr; } } @@ -211,13 +217,12 @@ void KeyboardTranslatorWriter::writeHeader( const QString& description ) void KeyboardTranslatorWriter::writeEntry( const KeyboardTranslator::Entry& entry ) { QString result; - if ( entry.command() != KeyboardTranslator::NoCommand ) result = entry.resultToString(); else - result = '\"' + entry.resultToString() + '\"'; + result = QLatin1Char('\"') + entry.resultToString() + QLatin1Char('\"'); - *_writer << "key " << entry.conditionToString() << " : " << result << '\n'; + *_writer << QLatin1String("key ") << entry.conditionToString() << QLatin1String(" : ") << result << QLatin1Char('\n'); } @@ -230,7 +235,7 @@ void KeyboardTranslatorWriter::writeEntry( const KeyboardTranslator::Entry& entr // KeySequence begins with the name of the key ( taken from the Qt::Key enum ) // and is followed by the keyboard modifiers and state flags ( with + or - in front // of each modifier or flag to indicate whether it is required ). All keyboard modifiers -// and flags are optional, if a particular modifier or state is not specified it is +// and flags are optional, if a particular modifier or state is not specified it is // assumed not to be a part of the sequence. The key sequence may contain whitespace // // eg: "key Up+Shift : scrollLineUp" @@ -247,22 +252,19 @@ KeyboardTranslatorReader::KeyboardTranslatorReader( QIODevice* source ) // read input until we find the description while ( _description.isEmpty() && !source->atEnd() ) { - const QList& tokens = tokenize( QString(source->readLine()) ); - + QList tokens = tokenize( QString::fromUtf8(source->readLine()) ); if ( !tokens.isEmpty() && tokens.first().type == Token::TitleKeyword ) - { - _description = (tokens[1].text.toUtf8()); - } + _description = tokens[1].text; } - + // read first entry (if any) readNext(); } -void KeyboardTranslatorReader::readNext() +void KeyboardTranslatorReader::readNext() { // find next entry while ( !_source->atEnd() ) { - const QList& tokens = tokenize( QString(_source->readLine()) ); + const QList& tokens = tokenize( QString::fromUtf8(_source->readLine()) ); if ( !tokens.isEmpty() && tokens.first().type == Token::KeyKeyword ) { KeyboardTranslator::States flags = KeyboardTranslator::NoState; @@ -277,7 +279,7 @@ void KeyboardTranslatorReader::readNext() modifiers, modifierMask, flags, - flagMask); + flagMask); KeyboardTranslator::Command command = KeyboardTranslator::NoCommand; QByteArray text; @@ -290,8 +292,8 @@ void KeyboardTranslatorReader::readNext() else if ( tokens[2].type == Token::Command ) { // identify command - if (!parseAsCommand(tokens[2].text,command)) - qWarning() << "Command" << tokens[2].text << "not understood."; + if (!parseAsCommand(tokens[2].text,command)) + qDebug() << "Command" << tokens[2].text << "not understood."; } KeyboardTranslator::Entry newEntry; @@ -309,29 +311,33 @@ void KeyboardTranslatorReader::readNext() return; } - } + } _hasNext = false; } -bool KeyboardTranslatorReader::parseAsCommand(const QString& text,KeyboardTranslator::Command& command) +bool KeyboardTranslatorReader::parseAsCommand(const QString& text,KeyboardTranslator::Command& command) { - if ( text.compare("erase",Qt::CaseInsensitive) == 0 ) - command = KeyboardTranslator::EraseCommand; - else if ( text.compare("scrollpageup",Qt::CaseInsensitive) == 0 ) + if ( text.compare(QLatin1String("erase"),Qt::CaseInsensitive) == 0 ) + command = KeyboardTranslator::EraseCommand; + else if ( text.compare(QLatin1String("scrollpageup"),Qt::CaseInsensitive) == 0 ) command = KeyboardTranslator::ScrollPageUpCommand; - else if ( text.compare("scrollpagedown",Qt::CaseInsensitive) == 0 ) + else if ( text.compare(QLatin1String("scrollpagedown"),Qt::CaseInsensitive) == 0 ) command = KeyboardTranslator::ScrollPageDownCommand; - else if ( text.compare("scrolllineup",Qt::CaseInsensitive) == 0 ) + else if ( text.compare(QLatin1String("scrolllineup"),Qt::CaseInsensitive) == 0 ) command = KeyboardTranslator::ScrollLineUpCommand; - else if ( text.compare("scrolllinedown",Qt::CaseInsensitive) == 0 ) + else if ( text.compare(QLatin1String("scrolllinedown"),Qt::CaseInsensitive) == 0 ) command = KeyboardTranslator::ScrollLineDownCommand; - else if ( text.compare("scrolllock",Qt::CaseInsensitive) == 0 ) + else if ( text.compare(QLatin1String("scrolllock"),Qt::CaseInsensitive) == 0 ) command = KeyboardTranslator::ScrollLockCommand; + else if ( text.compare(QLatin1String("scrolluptotop"),Qt::CaseInsensitive) == 0) + command = KeyboardTranslator::ScrollUpToTopCommand; + else if ( text.compare(QLatin1String("scrolldowntobottom"),Qt::CaseInsensitive) == 0) + command = KeyboardTranslator::ScrollDownToBottomCommand; else - return false; + return false; - return true; + return true; } bool KeyboardTranslatorReader::decodeSequence(const QString& text, @@ -341,7 +347,7 @@ bool KeyboardTranslatorReader::decodeSequence(const QString& text, KeyboardTranslator::States& flags, KeyboardTranslator::States& flagMask) { - bool isWanted = true; + bool isWanted = true; bool endOfItem = false; QString buffer; @@ -350,16 +356,19 @@ bool KeyboardTranslatorReader::decodeSequence(const QString& text, KeyboardTranslator::States tempFlags = flags; KeyboardTranslator::States tempFlagMask = flagMask; - for ( int i = 0 ; i < text.count() ; i++ ) + for ( int i = 0 ; i < text.length() ; i++ ) { const QChar& ch = text[i]; - bool isLastLetter = ( i == text.count()-1 ); - + bool isFirstLetter = i == 0; + bool isLastLetter = ( i == text.length()-1 ); endOfItem = true; if ( ch.isLetterOrNumber() ) { endOfItem = false; buffer.append(ch); + } else if ( isFirstLetter ) + { + buffer.append(ch); } if ( (endOfItem || isLastLetter) && !buffer.isEmpty() ) @@ -390,13 +399,13 @@ bool KeyboardTranslatorReader::decodeSequence(const QString& text, buffer.clear(); } - // check if this is a wanted / not-wanted flag and update the + // check if this is a wanted / not-wanted flag and update the // state ready for the next item - if ( ch == '+' ) + if ( ch == QLatin1Char('+') ) isWanted = true; - else if ( ch == '-' ) - isWanted = false; - } + else if ( ch == QLatin1Char('-') ) + isWanted = false; + } modifiers = tempModifiers; modifierMask = tempModifierMask; @@ -408,16 +417,16 @@ bool KeyboardTranslatorReader::decodeSequence(const QString& text, bool KeyboardTranslatorReader::parseAsModifier(const QString& item , Qt::KeyboardModifier& modifier) { - if ( item == "shift" ) + if ( item == QLatin1String("shift") ) modifier = Qt::ShiftModifier; - else if ( item == "ctrl" || item == "control" ) + else if ( item == QLatin1String("ctrl") || item == QLatin1String("control") ) modifier = Qt::ControlModifier; - else if ( item == "alt" ) + else if ( item == QLatin1String("alt") ) modifier = Qt::AltModifier; - else if ( item == "meta" ) + else if ( item == QLatin1String("meta") ) modifier = Qt::MetaModifier; - else if ( item == "keypad" ) - modifier = Qt::KeypadModifier; + else if ( item == QLatin1String("keypad") ) + modifier = Qt::KeypadModifier; else return false; @@ -425,16 +434,18 @@ bool KeyboardTranslatorReader::parseAsModifier(const QString& item , Qt::Keyboar } bool KeyboardTranslatorReader::parseAsStateFlag(const QString& item , KeyboardTranslator::State& flag) { - if ( item == "appcukeys" ) + if ( item == QLatin1String("appcukeys") || item == QLatin1String("appcursorkeys") ) flag = KeyboardTranslator::CursorKeysState; - else if ( item == "ansi" ) + else if ( item == QLatin1String("ansi") ) flag = KeyboardTranslator::AnsiState; - else if ( item == "newline" ) + else if ( item == QLatin1String("newline") ) flag = KeyboardTranslator::NewLineState; - else if ( item == "appscreen" ) + else if ( item == QLatin1String("appscreen") ) flag = KeyboardTranslator::AlternateScreenState; - else if ( item == "anymod" ) + else if ( item == QLatin1String("anymod") || item == QLatin1String("anymodifier") ) flag = KeyboardTranslator::AnyModifierState; + else if ( item == QLatin1String("appkeypad") ) + flag = KeyboardTranslator::ApplicationKeypadState; else return false; @@ -445,17 +456,20 @@ bool KeyboardTranslatorReader::parseAsKeyCode(const QString& item , int& keyCode QKeySequence sequence = QKeySequence::fromString(item); if ( !sequence.isEmpty() ) { +#if QT_VERSION >= 0x060000 + keyCode = sequence[0].toCombined(); +#else keyCode = sequence[0]; - +#endif if ( sequence.count() > 1 ) { qDebug() << "Unhandled key codes in sequence: " << item; } } // additional cases implemented for backwards compatibility with KDE 3 - else if ( item == "prior" ) + else if ( item == QLatin1String("prior") ) keyCode = Qt::Key_PageUp; - else if ( item == "next" ) + else if ( item == QLatin1String("next") ) keyCode = Qt::Key_PageDown; else return false; @@ -467,49 +481,43 @@ QString KeyboardTranslatorReader::description() const { return _description; } -bool KeyboardTranslatorReader::hasNextEntry() +bool KeyboardTranslatorReader::hasNextEntry() const { return _hasNext; } -KeyboardTranslator::Entry KeyboardTranslatorReader::createEntry( const QString& condition , +KeyboardTranslator::Entry KeyboardTranslatorReader::createEntry( const QString& condition , const QString& result ) { - QString entryString("keyboard \"temporary\"\nkey "); + QString entryString = QString::fromLatin1("keyboard \"temporary\"\nkey "); entryString.append(condition); - entryString.append(" : "); + entryString.append(QLatin1String(" : ")); - // if 'result' is the name of a command then the entry result will be that command, - // otherwise the result will be treated as a string to echo when the key sequence - // specified by 'condition' is pressed - KeyboardTranslator::Command command; - if (parseAsCommand(result,command)) - entryString.append(result); - else - entryString.append('\"' + result + '\"'); + // if 'result' is the name of a command then the entry result will be that command, + // otherwise the result will be treated as a string to echo when the key sequence + // specified by 'condition' is pressed + KeyboardTranslator::Command command; + if (parseAsCommand(result,command)) + entryString.append(result); + else + entryString.append(QLatin1Char('\"') + result + QLatin1Char('\"')); QByteArray array = entryString.toUtf8(); - - KeyboardTranslator::Entry entry; - QBuffer buffer(&array); buffer.open(QIODevice::ReadOnly); KeyboardTranslatorReader reader(&buffer); + KeyboardTranslator::Entry entry; if ( reader.hasNextEntry() ) entry = reader.nextEntry(); return entry; } -KeyboardTranslator::Entry KeyboardTranslatorReader::nextEntry() +KeyboardTranslator::Entry KeyboardTranslatorReader::nextEntry() { Q_ASSERT( _hasNext ); - - KeyboardTranslator::Entry entry = _nextEntry; - readNext(); - return entry; } bool KeyboardTranslatorReader::parseError() @@ -518,19 +526,32 @@ bool KeyboardTranslatorReader::parseError() } QList KeyboardTranslatorReader::tokenize(const QString& line) { - QString text = line.simplified(); + QString text = line; + + // remove comments + bool inQuotes = false; + int commentPos = -1; + for (int i=text.length()-1;i>=0;i--) + { + QChar ch = text[i]; + if (ch == QLatin1Char('\"')) + inQuotes = !inQuotes; + else if (ch == QLatin1Char('#') && !inQuotes) + commentPos = i; + } + if (commentPos != -1) + text.remove(commentPos,text.length()); + + text = text.simplified(); - // comment line: # comment - static QRegExp comment("\\#.*"); // title line: keyboard "title" - static QRegExp title("keyboard\\s+\"(.*)\""); + static QRegExp title(QLatin1String("keyboard\\s+\"(.*)\"")); // key line: key KeySequence : "output" // key line: key KeySequence : command - static QRegExp key("key\\s+([\\w\\+\\s\\-]+)\\s*:\\s*(\"(.*)\"|\\w+)"); + static QRegExp key(QLatin1String("key\\s+([\\w\\+\\s\\-\\*\\.]+)\\s*:\\s*(\"(.*)\"|\\w+)")); QList list; - - if ( text.isEmpty() || comment.exactMatch(text) ) + if ( text.isEmpty() ) { return list; } @@ -538,39 +559,39 @@ QList KeyboardTranslatorReader::tokenize(const if ( title.exactMatch(text) ) { Token titleToken = { Token::TitleKeyword , QString() }; - Token textToken = { Token::TitleText , title.capturedTexts()[1] }; - + Token textToken = { Token::TitleText , title.capturedTexts().at(1) }; + list << titleToken << textToken; } else if ( key.exactMatch(text) ) { Token keyToken = { Token::KeyKeyword , QString() }; - Token sequenceToken = { Token::KeySequence , key.capturedTexts()[1].remove(' ') }; + Token sequenceToken = { Token::KeySequence , key.capturedTexts().value(1).remove(QLatin1Char(' ')) }; list << keyToken << sequenceToken; - if ( key.capturedTexts()[3].isEmpty() ) + if ( key.capturedTexts().at(3).isEmpty() ) { // capturedTexts()[2] is a command - Token commandToken = { Token::Command , key.capturedTexts()[2] }; - list << commandToken; - } + Token commandToken = { Token::Command , key.capturedTexts().at(2) }; + list << commandToken; + } else { // capturedTexts()[3] is the output string - Token outputToken = { Token::OutputText , key.capturedTexts()[3] }; + Token outputToken = { Token::OutputText , key.capturedTexts().at(3) }; list << outputToken; - } + } } else { - qWarning() << "Line in keyboard translator file could not be understood:" << text; + qDebug() << "Line in keyboard translator file could not be understood:" << text; } return list; } -QList KeyboardTranslatorManager::allTranslators() +QList KeyboardTranslatorManager::allTranslators() { if ( !_haveLoadedAll ) { @@ -601,35 +622,36 @@ bool KeyboardTranslator::Entry::operator==(const Entry& rhs) const _text == rhs._text; } -bool KeyboardTranslator::Entry::matches(int keyCode , +bool KeyboardTranslator::Entry::matches(int keyCode , Qt::KeyboardModifiers modifiers, - States state) const + States testState) const { +#ifdef Q_OS_MAC + // On Mac, arrow keys are considered part of keypad. Ignore that. + modifiers &= ~Qt::KeypadModifier; +#endif + if ( _keyCode != keyCode ) return false; - if ( (modifiers & _modifierMask) != (_modifiers & _modifierMask) ) + if ( (modifiers & _modifierMask) != (_modifiers & _modifierMask) ) return false; // if modifiers is non-zero, the 'any modifier' state is implicit - if ( modifiers != 0 ) - state |= AnyModifierState; + if ( (modifiers & ~Qt::KeypadModifier) != 0 ) + testState |= AnyModifierState; - if ( (state & _stateMask) != (_state & _stateMask) ) + if ( (testState & _stateMask) != (_state & _stateMask) ) return false; - // special handling for the 'Any Modifier' state, which checks for the presence of + // special handling for the 'Any Modifier' state, which checks for the presence of // any or no modifiers. In this context, the 'keypad' modifier does not count. bool anyModifiersSet = modifiers != 0 && modifiers != Qt::KeypadModifier; + bool wantAnyModifier = _state & KeyboardTranslator::AnyModifierState; if ( _stateMask & KeyboardTranslator::AnyModifierState ) { - // test fails if any modifier is required but none are set - if ( (_state & KeyboardTranslator::AnyModifierState) && !anyModifiersSet ) + if ( wantAnyModifier != anyModifiersSet ) return false; - - // test fails if no modifier is allowed but one or more are set - if ( !(_state & KeyboardTranslator::AnyModifierState) && anyModifiersSet ) - return false; } return true; @@ -638,7 +660,7 @@ QByteArray KeyboardTranslator::Entry::escapedText(bool expandWildCards,Qt::Keybo { QByteArray result(text(expandWildCards,modifiers)); - for ( int i = 0 ; i < result.count() ; i++ ) + for ( int i = 0 ; i < result.length() ; i++ ) { char ch = result[i]; char replacement = 0; @@ -654,13 +676,14 @@ QByteArray KeyboardTranslator::Entry::escapedText(bool expandWildCards,Qt::Keybo 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() ) + if ( !QChar(QLatin1Char(ch)).isPrint() ) replacement = 'x'; } if ( replacement == 'x' ) { - result.replace(i,1,"\\x"+QByteArray(1,ch).toInt(0, 16)); + QByteArray data = "\\x"+QByteArray(1,ch).toHex(); + result.replace(i,1,data); } else if ( replacement != 0 ) { result.remove(i,1); @@ -675,15 +698,15 @@ QByteArray KeyboardTranslator::Entry::unescape(const QByteArray& input) const { QByteArray result(input); - for ( int i = 0 ; i < result.count()-1 ; i++ ) + for ( int i = 0 ; i < result.length()-1 ; i++ ) { - QByteRef ch = result[i]; + auto ch = result[i]; if ( ch == '\\' ) { char replacement[2] = {0,0}; int charsToRemove = 2; - bool escapedChar = true; + bool escapedChar = true; switch ( result[i+1] ) { @@ -694,34 +717,33 @@ QByteArray KeyboardTranslator::Entry::unescape(const QByteArray& input) const 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]) ) + if ( (i < result.length()-2) && isxdigit(result[i+2]) ) hexDigits[0] = result[i+2]; - if ( (i < result.count()-3) && isxdigit(result[i+3]) ) + if ( (i < result.length()-3) && isxdigit(result[i+3]) ) hexDigits[1] = result[i+3]; - int charValue = 0; + unsigned charValue = 0; sscanf(hexDigits,"%x",&charValue); - - replacement[0] = (char)charValue; + replacement[0] = (char)charValue; charsToRemove = 2 + strlen(hexDigits); - } + } break; - default: - escapedChar = false; + default: + escapedChar = false; } if ( escapedChar ) result.replace(i,charsToRemove,replacement); } } - + return result; } @@ -731,20 +753,20 @@ void KeyboardTranslator::Entry::insertModifier( QString& item , int modifier ) c return; if ( modifier & _modifiers ) - item += '+'; + item += QLatin1Char('+'); else - item += '-'; + item += QLatin1Char('-'); if ( modifier == Qt::ShiftModifier ) - item += "Shift"; + item += QLatin1String("Shift"); else if ( modifier == Qt::ControlModifier ) - item += "Ctrl"; + item += QLatin1String("Ctrl"); else if ( modifier == Qt::AltModifier ) - item += "Alt"; + item += QLatin1String("Alt"); else if ( modifier == Qt::MetaModifier ) - item += "Meta"; - else if ( modifier == Qt::KeypadModifier ) - item += "KeyPad"; + item += QLatin1String("Meta"); + else if ( modifier == Qt::KeypadModifier ) + item += QLatin1String("KeyPad"); } void KeyboardTranslator::Entry::insertState( QString& item , int state ) const { @@ -752,37 +774,43 @@ void KeyboardTranslator::Entry::insertState( QString& item , int state ) const return; if ( state & _state ) - item += '+' ; + item += QLatin1Char('+') ; else - item += '-' ; + item += QLatin1Char('-') ; if ( state == KeyboardTranslator::AlternateScreenState ) - item += "AppScreen"; + item += QLatin1String("AppScreen"); else if ( state == KeyboardTranslator::NewLineState ) - item += "NewLine"; + item += QLatin1String("NewLine"); else if ( state == KeyboardTranslator::AnsiState ) - item += "Ansi"; + item += QLatin1String("Ansi"); else if ( state == KeyboardTranslator::CursorKeysState ) - item += "AppCuKeys"; + item += QLatin1String("AppCursorKeys"); else if ( state == KeyboardTranslator::AnyModifierState ) - item += "AnyMod"; + item += QLatin1String("AnyModifier"); + else if ( state == KeyboardTranslator::ApplicationKeypadState ) + item += QLatin1String("AppKeypad"); } QString KeyboardTranslator::Entry::resultToString(bool expandWildCards,Qt::KeyboardModifiers modifiers) const { if ( !_text.isEmpty() ) - return escapedText(expandWildCards,modifiers); - else if ( _command == EraseCommand ) - return "Erase"; + return QString::fromLatin1(escapedText(expandWildCards,modifiers)); + else if ( _command == EraseCommand ) + return QLatin1String("Erase"); else if ( _command == ScrollPageUpCommand ) - return "ScrollPageUp"; + return QLatin1String("ScrollPageUp"); else if ( _command == ScrollPageDownCommand ) - return "ScrollPageDown"; + return QLatin1String("ScrollPageDown"); else if ( _command == ScrollLineUpCommand ) - return "ScrollLineUp"; + return QLatin1String("ScrollLineUp"); else if ( _command == ScrollLineDownCommand ) - return "ScrollLineDown"; + return QLatin1String("ScrollLineDown"); else if ( _command == ScrollLockCommand ) - return "ScrollLock"; + return QLatin1String("ScrollLock"); + else if (_command == ScrollUpToTopCommand) + return QLatin1String("ScrollUpToTop"); + else if (_command == ScrollDownToBottomCommand) + return QLatin1String("ScrollDownToBottom"); return QString(); } @@ -790,18 +818,18 @@ QString KeyboardTranslator::Entry::conditionToString() const { QString result = QKeySequence(_keyCode).toString(); - // add modifiers insertModifier( result , Qt::ShiftModifier ); insertModifier( result , Qt::ControlModifier ); insertModifier( result , Qt::AltModifier ); - insertModifier( result , Qt::MetaModifier ); + insertModifier( result , Qt::MetaModifier ); + insertModifier( result , Qt::KeypadModifier ); - // add states insertState( result , KeyboardTranslator::AlternateScreenState ); insertState( result , KeyboardTranslator::NewLineState ); insertState( result , KeyboardTranslator::AnsiState ); insertState( result , KeyboardTranslator::CursorKeysState ); insertState( result , KeyboardTranslator::AnyModifierState ); + insertState( result , KeyboardTranslator::ApplicationKeypadState ); return result; } @@ -811,7 +839,7 @@ KeyboardTranslator::KeyboardTranslator(const QString& name) { } -void KeyboardTranslator::setDescription(const QString& description) +void KeyboardTranslator::setDescription(const QString& description) { _description = description; } @@ -836,47 +864,34 @@ QList KeyboardTranslator::entries() const void KeyboardTranslator::addEntry(const Entry& entry) { const int keyCode = entry.keyCode(); - _entries.insertMulti(keyCode,entry); + _entries.insert(keyCode,entry); } void KeyboardTranslator::replaceEntry(const Entry& existing , const Entry& replacement) { if ( !existing.isNull() ) - _entries.remove(existing.keyCode()); - _entries.insertMulti(replacement.keyCode(),replacement); + _entries.remove(existing.keyCode(),existing); + _entries.insert(replacement.keyCode(),replacement); } void KeyboardTranslator::removeEntry(const Entry& entry) { - _entries.remove(entry.keyCode()); + _entries.remove(entry.keyCode(),entry); } KeyboardTranslator::Entry KeyboardTranslator::findEntry(int keyCode, Qt::KeyboardModifiers modifiers, States state) const { - if ( _entries.contains(keyCode) ) + for (auto it = _entries.cbegin(), end = _entries.cend(); it != end; ++it) { - QList entriesForKey = _entries.values(keyCode); - - QListIterator iter(entriesForKey); - - while (iter.hasNext()) - { - const Entry& next = iter.next(); - if ( next.matches(keyCode,modifiers,state) ) - return next; - } - - return Entry(); // entry not found + if (it.key() == keyCode) + if ( it.value().matches(keyCode,modifiers,state) ) + return *it; } - else - { - return Entry(); - } - + return Entry(); // entry not found } void KeyboardTranslatorManager::addTranslator(KeyboardTranslator* translator) { _translators.insert(translator->name(),translator); if ( !saveTranslator(translator) ) - qWarning() << "Unable to save translator" << translator->name() + qDebug() << "Unable to save translator" << translator->name() << "to disk."; } bool KeyboardTranslatorManager::deleteTranslator(const QString& name) @@ -888,15 +903,15 @@ bool KeyboardTranslatorManager::deleteTranslator(const QString& name) if ( QFile::remove(path) ) { _translators.remove(name); - return true; + return true; } else { - qWarning() << "Failed to remove translator - " << path; + qDebug() << "Failed to remove translator - " << path; return false; } } -K_GLOBAL_STATIC( KeyboardTranslatorManager , theKeyboardTranslatorManager ) +Q_GLOBAL_STATIC( KeyboardTranslatorManager , theKeyboardTranslatorManager ) KeyboardTranslatorManager* KeyboardTranslatorManager::instance() { return theKeyboardTranslatorManager; diff --git a/qtermwidget/src/KeyboardTranslator.h b/qtermwidget/lib/KeyboardTranslator.h similarity index 74% rename from qtermwidget/src/KeyboardTranslator.h rename to qtermwidget/lib/KeyboardTranslator.h index e0082ae..4ca6b86 100644 --- a/qtermwidget/src/KeyboardTranslator.h +++ b/qtermwidget/lib/KeyboardTranslator.h @@ -1,9 +1,7 @@ /* This source file is part of Konsole, a terminal emulator. - Copyright (C) 2007 by Robert Knight - - Rewritten for QT4 by e_k , Copyright (C)2008 + Copyright 2007-2008 by Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -25,87 +23,15 @@ #define KEYBOARDTRANSLATOR_H // Qt -#include -#include -#include -#include -#include -#include - -typedef void (*CleanUpFunction)(); - -/** - * @internal - * - * Helper class for K_GLOBAL_STATIC to clean up the object on library unload or application - * shutdown. - */ -class CleanUpGlobalStatic -{ - public: - CleanUpFunction func; - - inline ~CleanUpGlobalStatic() { func(); } -}; - - -//these directives are taken from the heart of kdecore - -# define K_GLOBAL_STATIC_STRUCT_NAME(NAME) - -#if QT_VERSION < 0x040400 -# define Q_BASIC_ATOMIC_INITIALIZER Q_ATOMIC_INIT -# define testAndSetOrdered testAndSet -#endif - -#define K_GLOBAL_STATIC(TYPE, NAME) K_GLOBAL_STATIC_WITH_ARGS(TYPE, NAME, ()) - -#define K_GLOBAL_STATIC_WITH_ARGS(TYPE, NAME, ARGS) \ -static QBasicAtomicPointer _k_static_##NAME = Q_BASIC_ATOMIC_INITIALIZER(0); \ -static bool _k_static_##NAME##_destroyed; \ -static struct K_GLOBAL_STATIC_STRUCT_NAME(NAME) \ -{ \ - bool isDestroyed() \ - { \ - return _k_static_##NAME##_destroyed; \ - } \ - inline operator TYPE*() \ - { \ - return operator->(); \ - } \ - inline TYPE *operator->() \ - { \ - if (!_k_static_##NAME) { \ - if (isDestroyed()) { \ - qFatal("Fatal Error: Accessed global static '%s *%s()' after destruction. " \ - "Defined at %s:%d", #TYPE, #NAME, __FILE__, __LINE__); \ - } \ - TYPE *x = new TYPE ARGS; \ - if (!_k_static_##NAME.testAndSetOrdered(0, x) \ - && _k_static_##NAME != x ) { \ - delete x; \ - } else { \ - static CleanUpGlobalStatic cleanUpObject = { destroy }; \ - } \ - } \ - return _k_static_##NAME; \ - } \ - inline TYPE &operator*() \ - { \ - return *operator->(); \ - } \ - static void destroy() \ - { \ - _k_static_##NAME##_destroyed = true; \ - TYPE *x = _k_static_##NAME; \ - _k_static_##NAME = 0; \ - delete x; \ - } \ -} NAME; - - - +#include +#include +#include +#include +#include +// Konsole +//#include "konsole_export.h" +#define KONSOLEPRIVATE_EXPORT class QIODevice; class QTextStream; @@ -113,7 +39,7 @@ class QTextStream; namespace Konsole { -/** +/** * A convertor which maps between key sequences pressed by the user and the * character strings which should be sent to the terminal and commands * which should be invoked when those character sequences are pressed. @@ -129,7 +55,7 @@ namespace Konsole class KeyboardTranslator { public: - /** + /** * The meaning of a particular key sequence may depend upon the state which * the terminal emulation is in. Therefore findEntry() may return a different * Entry depending upon the state flags supplied. @@ -145,7 +71,7 @@ public: * TODO More documentation */ NewLineState = 1, - /** + /** * Indicates that the terminal is in 'Ansi' mode. * TODO: More documentation */ @@ -156,11 +82,13 @@ public: CursorKeysState = 4, /** * Indicates that the alternate screen ( typically used by interactive programs - * such as screen or vim ) is active + * such as screen or vim ) is active */ AlternateScreenState = 8, - /** Indicates that any of the modifier keys is active. */ - AnyModifierState = 16 + /** Indicates that any of the modifier keys is active. */ + AnyModifierState = 16, + /** Indicates that the numpad is in application mode. */ + ApplicationKeypadState = 32 }; Q_DECLARE_FLAGS(States,State) @@ -183,8 +111,12 @@ public: ScrollLineDownCommand = 16, /** Toggles scroll lock mode */ ScrollLockCommand = 32, - /** Echos the operating system specific erase character. */ - EraseCommand = 64 + /** Scroll the terminal display up to the start of history */ + ScrollUpToTopCommand = 64, + /** Scroll the terminal display down to the end of history */ + ScrollDownToBottomCommand = 128, + /** Echos the operating system specific erase character. */ + EraseCommand = 256 }; Q_DECLARE_FLAGS(Commands,Command) @@ -196,14 +128,14 @@ public: class Entry { public: - /** + /** * Constructs a new entry for a keyboard translator. */ Entry(); - /** + /** * Returns true if this entry is null. - * This is true for newly constructed entries which have no properties set. + * This is true for newly constructed entries which have no properties set. */ bool isNull() const; @@ -212,15 +144,15 @@ public: /** Sets the command associated with this entry. */ void setCommand(Command command); - /** - * Returns the character sequence associated with this entry, optionally replacing + /** + * Returns the character sequence associated with this entry, optionally replacing * wildcard '*' characters with numbers to indicate the keyboard modifiers being pressed. * * TODO: The numbers used to replace '*' characters are taken from the Konsole/KDE 3 code. - * Document them. + * Document them. * * @param expandWildCards Specifies whether wild cards (occurrences of the '*' character) in - * the entry should be replaced with a number to indicate the modifier keys being pressed. + * the entry should be replaced with a number to indicate the modifier keys being pressed. * * @param modifiers The keyboard modifiers being pressed. */ @@ -230,7 +162,7 @@ public: /** Sets the character sequence associated with this entry */ void setText(const QByteArray& text); - /** + /** * Returns the character sequence associated with this entry, * with any non-printable characters replaced with escape sequences. * @@ -247,13 +179,13 @@ public: /** Sets the character code associated with this entry */ void setKeyCode(int keyCode); - /** - * Returns a bitwise-OR of the enabled keyboard modifiers associated with this entry. + /** + * Returns a bitwise-OR of the enabled keyboard modifiers associated with this entry. * If a modifier is set in modifierMask() but not in modifiers(), this means that the entry * only matches when that modifier is NOT pressed. * * If a modifier is not set in modifierMask() then the entry matches whether the modifier - * is pressed or not. + * is pressed or not. */ Qt::KeyboardModifiers modifiers() const; @@ -265,13 +197,13 @@ public: /** See modifierMask() and modifiers() */ void setModifierMask( Qt::KeyboardModifiers modifiers ); - /** - * Returns a bitwise-OR of the enabled state flags associated with this entry. - * If flag is set in stateMask() but not in state(), this means that the entry only + /** + * Returns a bitwise-OR of the enabled state flags associated with this entry. + * If flag is set in stateMask() but not in state(), this means that the entry only * matches when the terminal is NOT in that state. * * If a state is not set in stateMask() then the entry matches whether the terminal - * is in that state or not. + * is in that state or not. */ States state() const; @@ -283,13 +215,13 @@ public: /** See stateMask() */ void setStateMask( States mask ); - /** - * Returns the key code and modifiers associated with this entry + /** + * Returns the key code and modifiers associated with this entry * as a QKeySequence */ //QKeySequence keySequence() const; - /** + /** * Returns this entry's conditions ( ie. its key code, modifier and state criteria ) * as a string. */ @@ -305,16 +237,16 @@ public: QString resultToString(bool expandWildCards = false, Qt::KeyboardModifiers modifiers = Qt::NoModifier) const; - /** + /** * Returns true if this entry matches the given key sequence, specified * as a combination of @p keyCode , @p modifiers and @p state. */ - bool matches( int keyCode , - Qt::KeyboardModifiers modifiers , + bool matches( int keyCode , + Qt::KeyboardModifiers modifiers , States flags ) const; bool operator==(const Entry& rhs) const; - + private: void insertModifier( QString& item , int modifier ) const; void insertState( QString& item , int state ) const; @@ -332,7 +264,7 @@ public: /** Constructs a new keyboard translator with the given @p name */ KeyboardTranslator(const QString& name); - + //KeyboardTranslator(const KeyboardTranslator& other); /** Returns the name of this keyboard translator */ @@ -350,7 +282,7 @@ public: /** * Looks for an entry in this keyboard translator which matches the given * key code, keyboard modifiers and state flags. - * + * * Returns the matching entry if found or a null Entry otherwise ( ie. * entry.isNull() will return true ) * @@ -358,11 +290,11 @@ public: * @param modifiers A combination of modifiers * @param state Optional flags which specify the current state of the terminal */ - Entry findEntry(int keyCode , - Qt::KeyboardModifiers modifiers , + Entry findEntry(int keyCode , + Qt::KeyboardModifiers modifiers , States state = NoState) const; - /** + /** * Adds an entry to this keyboard translator's table. Entries can be looked up according * to their key sequence using findEntry() */ @@ -382,9 +314,12 @@ public: /** Returns a list of all entries in the translator. */ QList entries() const; + /** The modifier code for the actual Ctrl key on this OS. */ + static const Qt::KeyboardModifier CTRL_MOD; + private: - QHash _entries; // entries in this keyboard translation, + QMultiHash _entries; // entries in this keyboard translation, // entries are indexed according to // their keycode QString _name; @@ -393,8 +328,8 @@ private: Q_DECLARE_OPERATORS_FOR_FLAGS(KeyboardTranslator::States) Q_DECLARE_OPERATORS_FOR_FLAGS(KeyboardTranslator::Commands) -/** - * Parses the contents of a Keyboard Translator (.keytab) file and +/** + * Parses the contents of a Keyboard Translator (.keytab) file and * returns the entries found in it. * * Usage example: @@ -414,7 +349,7 @@ Q_DECLARE_OPERATORS_FOR_FLAGS(KeyboardTranslator::Commands) * if ( !reader.parseError() ) * { * // parsing succeeded, do something with the translator - * } + * } * else * { * // parsing failed @@ -427,18 +362,18 @@ public: /** Constructs a new reader which parses the given @p source */ KeyboardTranslatorReader( QIODevice* source ); - /** - * Returns the description text. - * TODO: More documentation + /** + * Returns the description text. + * TODO: More documentation */ QString description() const; /** Returns true if there is another entry in the source stream */ - bool hasNextEntry(); + bool hasNextEntry() const; /** Returns the next entry found in the source stream */ - KeyboardTranslator::Entry nextEntry(); + KeyboardTranslator::Entry nextEntry(); - /** + /** * Returns true if an error occurred whilst parsing the input or * false if no error occurred. */ @@ -448,7 +383,7 @@ public: * Parses a condition and result string for a translator entry * and produces a keyboard translator entry. * - * The condition and result strings are in the same format as in + * The condition and result strings are in the same format as in */ static KeyboardTranslator::Entry createEntry( const QString& condition , const QString& result ); @@ -469,7 +404,7 @@ private: }; QList tokenize(const QString&); void readNext(); - bool decodeSequence(const QString& , + bool decodeSequence(const QString& , int& keyCode, Qt::KeyboardModifiers& modifiers, Qt::KeyboardModifiers& modifierMask, @@ -479,7 +414,7 @@ private: static bool parseAsModifier(const QString& item , Qt::KeyboardModifier& modifier); static bool parseAsStateFlag(const QString& item , KeyboardTranslator::State& state); static bool parseAsKeyCode(const QString& item , int& keyCode); - static bool parseAsCommand(const QString& text , KeyboardTranslator::Command& command); + static bool parseAsCommand(const QString& text , KeyboardTranslator::Command& command); QIODevice* _source; QString _description; @@ -491,23 +426,23 @@ private: class KeyboardTranslatorWriter { public: - /** + /** * Constructs a new writer which saves data into @p destination. * The caller is responsible for closing the device when writing is complete. */ KeyboardTranslatorWriter(QIODevice* destination); ~KeyboardTranslatorWriter(); - /** - * Writes the header for the keyboard translator. - * @param description Description of the keyboard translator. + /** + * Writes the header for the keyboard translator. + * @param description Description of the keyboard translator. */ void writeHeader( const QString& description ); /** Writes a translator entry. */ - void writeEntry( const KeyboardTranslator::Entry& entry ); + void writeEntry( const KeyboardTranslator::Entry& entry ); private: - QIODevice* _destination; + QIODevice* _destination; QTextStream* _writer; }; @@ -515,10 +450,10 @@ private: * Manages the keyboard translations available for use by terminal sessions, * see KeyboardTranslator. */ -class KeyboardTranslatorManager +class KONSOLEPRIVATE_EXPORT KeyboardTranslatorManager { public: - /** + /** * Constructs a new KeyboardTranslatorManager and loads the list of * available keyboard translations. * @@ -528,8 +463,11 @@ public: KeyboardTranslatorManager(); ~KeyboardTranslatorManager(); + KeyboardTranslatorManager(const KeyboardTranslatorManager&) = delete; + KeyboardTranslatorManager& operator=(const KeyboardTranslatorManager&) = delete; + /** - * Adds a new translator. If a translator with the same name + * Adds a new translator. If a translator with the same name * already exists, it will be replaced by the new translator. * * TODO: More documentation. @@ -546,18 +484,18 @@ public: /** Returns the default translator for Konsole. */ const KeyboardTranslator* defaultTranslator(); - /** + /** * Returns the keyboard translator with the given name or 0 if no translator * with that name exists. * * The first time that a translator with a particular name is requested, - * the on-disk .keyboard file is loaded and parsed. + * the on-disk .keyboard file is loaded and parsed. */ const KeyboardTranslator* findTranslator(const QString& name); /** * Returns a list of the names of available keyboard translators. * - * The first time this is called, a search for available + * The first time this is called, a search for available * translators is started. */ QList allTranslators(); @@ -566,16 +504,16 @@ public: static KeyboardTranslatorManager* instance(); private: - static const char* defaultTranslatorText; - + static const QByteArray defaultTranslatorText; + void findTranslators(); // locate the available translators - KeyboardTranslator* loadTranslator(const QString& name); // loads the translator + KeyboardTranslator* loadTranslator(const QString& name); // loads the translator // with the given name KeyboardTranslator* loadTranslator(QIODevice* device,const QString& name); bool saveTranslator(const KeyboardTranslator* translator); QString findTranslatorPath(const QString& name); - + QHash _translators; // maps translator-name -> KeyboardTranslator // instance bool _haveLoadedAll; @@ -584,15 +522,15 @@ private: inline int KeyboardTranslator::Entry::keyCode() const { return _keyCode; } inline void KeyboardTranslator::Entry::setKeyCode(int keyCode) { _keyCode = keyCode; } -inline void KeyboardTranslator::Entry::setModifiers( Qt::KeyboardModifiers modifier ) -{ +inline void KeyboardTranslator::Entry::setModifiers( Qt::KeyboardModifiers modifier ) +{ _modifiers = modifier; } inline Qt::KeyboardModifiers KeyboardTranslator::Entry::modifiers() const { return _modifiers; } -inline void KeyboardTranslator::Entry::setModifierMask( Qt::KeyboardModifiers mask ) -{ - _modifierMask = mask; +inline void KeyboardTranslator::Entry::setModifierMask( Qt::KeyboardModifiers mask ) +{ + _modifierMask = mask; } inline Qt::KeyboardModifiers KeyboardTranslator::Entry::modifierMask() const { return _modifierMask; } @@ -602,49 +540,49 @@ inline bool KeyboardTranslator::Entry::isNull() const } inline void KeyboardTranslator::Entry::setCommand( Command command ) -{ - _command = command; +{ + _command = command; } inline KeyboardTranslator::Command KeyboardTranslator::Entry::command() const { return _command; } inline void KeyboardTranslator::Entry::setText( const QByteArray& text ) -{ +{ _text = unescape(text); } inline int oneOrZero(int value) { return value ? 1 : 0; } -inline QByteArray KeyboardTranslator::Entry::text(bool expandWildCards,Qt::KeyboardModifiers modifiers) const +inline QByteArray KeyboardTranslator::Entry::text(bool expandWildCards,Qt::KeyboardModifiers modifiers) const { QByteArray expandedText = _text; - + if (expandWildCards) { int modifierValue = 1; modifierValue += oneOrZero(modifiers & Qt::ShiftModifier); - modifierValue += oneOrZero(modifiers & Qt::AltModifier) << 1; - modifierValue += oneOrZero(modifiers & Qt::ControlModifier) << 2; + modifierValue += oneOrZero(modifiers & Qt::AltModifier) << 1; + modifierValue += oneOrZero(modifiers & KeyboardTranslator::CTRL_MOD) << 2; - for (int i=0;i<_text.length();i++) + for (int i=0;i<_text.length();i++) { if (expandedText[i] == '*') expandedText[i] = '0' + modifierValue; } } - return expandedText; + return expandedText; } inline void KeyboardTranslator::Entry::setState( States state ) -{ - _state = state; +{ + _state = state; } inline KeyboardTranslator::States KeyboardTranslator::Entry::state() const { return _state; } inline void KeyboardTranslator::Entry::setStateMask( States stateMask ) -{ - _stateMask = stateMask; +{ + _stateMask = stateMask; } inline KeyboardTranslator::States KeyboardTranslator::Entry::stateMask() const { return _stateMask; } diff --git a/qtermwidget/lib/LineFont.h b/qtermwidget/lib/LineFont.h new file mode 100644 index 0000000..9c080ea --- /dev/null +++ b/qtermwidget/lib/LineFont.h @@ -0,0 +1,21 @@ +// WARNING: Autogenerated by "fontembedder ./linefont.src". +// You probably do not want to hand-edit this! + +static const quint32 LineChars[] = { + 0x00007c00, 0x000fffe0, 0x00421084, 0x00e739ce, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00427000, 0x004e7380, 0x00e77800, 0x00ef7bc0, + 0x00421c00, 0x00439ce0, 0x00e73c00, 0x00e7bde0, 0x00007084, 0x000e7384, 0x000079ce, 0x000f7bce, + 0x00001c84, 0x00039ce4, 0x00003dce, 0x0007bdee, 0x00427084, 0x004e7384, 0x004279ce, 0x00e77884, + 0x00e779ce, 0x004f7bce, 0x00ef7bc4, 0x00ef7bce, 0x00421c84, 0x00439ce4, 0x00423dce, 0x00e73c84, + 0x00e73dce, 0x0047bdee, 0x00e7bde4, 0x00e7bdee, 0x00427c00, 0x0043fce0, 0x004e7f80, 0x004fffe0, + 0x004fffe0, 0x00e7fde0, 0x006f7fc0, 0x00efffe0, 0x00007c84, 0x0003fce4, 0x000e7f84, 0x000fffe4, + 0x00007dce, 0x0007fdee, 0x000f7fce, 0x000fffee, 0x00427c84, 0x0043fce4, 0x004e7f84, 0x004fffe4, + 0x00427dce, 0x00e77c84, 0x00e77dce, 0x0047fdee, 0x004e7fce, 0x00e7fde4, 0x00ef7f84, 0x004fffee, + 0x00efffe4, 0x00e7fdee, 0x00ef7fce, 0x00efffee, 0x00000000, 0x00000000, 0x00000000, 0x00000000, + 0x000f83e0, 0x00a5294a, 0x004e1380, 0x00a57800, 0x00ad0bc0, 0x004390e0, 0x00a53c00, 0x00a5a1e0, + 0x000e1384, 0x0000794a, 0x000f0b4a, 0x000390e4, 0x00003d4a, 0x0007a16a, 0x004e1384, 0x00a5694a, + 0x00ad2b4a, 0x004390e4, 0x00a52d4a, 0x00a5a16a, 0x004f83e0, 0x00a57c00, 0x00ad83e0, 0x000f83e4, + 0x00007d4a, 0x000f836a, 0x004f93e4, 0x00a57d4a, 0x00ad836a, 0x00000000, 0x00000000, 0x00000000, + 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00001c00, 0x00001084, 0x00007000, 0x00421000, + 0x00039ce0, 0x000039ce, 0x000e7380, 0x00e73800, 0x000e7f80, 0x00e73884, 0x0003fce0, 0x004239ce +}; diff --git a/qtermwidget/src/LineFont.src b/qtermwidget/lib/LineFont.src similarity index 100% rename from qtermwidget/src/LineFont.src rename to qtermwidget/lib/LineFont.src diff --git a/qtermwidget/lib/Pty.cpp b/qtermwidget/lib/Pty.cpp new file mode 100644 index 0000000..1e47ff4 --- /dev/null +++ b/qtermwidget/lib/Pty.cpp @@ -0,0 +1,350 @@ +/* + * This file is a part of QTerminal - http://gitorious.org/qterminal + * + * This file was un-linked from KDE and modified + * by Maxim Bourmistrov + * + */ + +/* + This file is part of Konsole, an X terminal. + Copyright 1997,1998 by Lars Doelle + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is 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" + +// System +#include +#include +#include +#include +#include +#include + +// Qt +#include +#include + +#include "kpty.h" +#include "kptydevice.h" + +using namespace Konsole; + +void Pty::setWindowSize(int lines, int cols) +{ + _windowColumns = cols; + _windowLines = lines; + + if (pty()->masterFd() >= 0) + pty()->setWinSize(lines, cols); +} +QSize Pty::windowSize() const +{ + return {_windowColumns,_windowLines}; +} + +void Pty::setFlowControlEnabled(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."; + } +} +bool Pty::flowControlEnabled() const +{ + if (pty()->masterFd() >= 0) + { + struct ::termios ttmode; + pty()->tcGetAttr(&ttmode); + return ttmode.c_iflag & IXOFF && + ttmode.c_iflag & IXON; + } + qWarning() << "Unable to get flow control status, terminal not connected."; + return false; +} + +void Pty::setUtf8Mode(bool enable) +{ +#ifdef IUTF8 // XXX not a reasonable place to check it. + _utf8 = enable; + + 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) + { + struct ::termios ttyAttributes; + pty()->tcGetAttr(&ttyAttributes); + return ttyAttributes.c_cc[VERASE]; + } + + return _eraseChar; +} + +void Pty::addEnvironmentVariables(const QStringList& environment) +{ + + bool termEnvVarAdded = false; + for (const QString &pair : environment) + { + // split on the first '=' character + int pos = pair.indexOf(QLatin1Char('=')); + + if ( pos >= 0 ) + { + QString variable = pair.left(pos); + QString value = pair.mid(pos+1); + + setEnv(variable,value); + + if (variable == QLatin1String("TERM")) { + termEnvVarAdded = true; + } + } + + // fallback to ensure that $TERM is always set + if (!termEnvVarAdded) { + setEnv(QStringLiteral("TERM"), QStringLiteral("xterm-256color")); + } +} +} + +int Pty::start(const QString& program, + const QStringList& programArguments, + const QStringList& environment, + ulong winid, + bool addToUtmp + //const QString& dbusService, + //const QString& dbusSession + ) +{ + clearProgram(); + + // For historical reasons, the first argument in programArguments is the + // name of the program to execute, so create a list consisting of all + // but the first argument to pass to setProgram() + Q_ASSERT(programArguments.count() >= 1); + setProgram(program, programArguments.mid(1)); + + addEnvironmentVariables(environment); + + setEnv(QLatin1String("WINDOWID"), QString::number(winid)); + setEnv(QLatin1String("COLORTERM"), QLatin1String("truecolor")); + + // unless the LANGUAGE environment variable has been set explicitly + // set it to a null string + // this fixes the problem where KCatalog sets the LANGUAGE environment + // variable during the application's startup to something which + // differs from LANG,LC_* etc. and causes programs run from + // the terminal to display messages in the wrong language + // + // this can happen if LANG contains a language which KDE + // does not have a translation for + // + // BR:149300 + setEnv(QLatin1String("LANGUAGE"),QString(),false /* do not overwrite existing value if any */); + + setUseUtmp(addToUtmp); + + 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); + + KProcess::start(); + + if (!waitForStarted()) + return -1; + + return 0; +} + +void Pty::setEmptyPTYProperties() +{ + struct ::termios ttmode; + pty()->tcGetAttr(&ttmode); + if (!_xonXoff) + ttmode.c_iflag &= ~(IXOFF | IXON); + else + ttmode.c_iflag |= (IXOFF | IXON); + #ifdef IUTF8 // XXX not a reasonable place to check it. + if (!_utf8) + ttmode.c_iflag &= ~IUTF8; + else + ttmode.c_iflag |= IUTF8; + #endif + + if (_eraseChar != 0) + ttmode.c_cc[VERASE] = _eraseChar; + + if (!pty()->tcSetAttr(&ttmode)) + qWarning() << "Unable to set terminal attributes."; +} + +void Pty::setWriteable(bool writeable) +{ + struct stat sbuf; + 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(int masterFd, QObject* parent) + : KPtyProcess(masterFd,parent) +{ + init(); +} +Pty::Pty(QObject* parent) + : KPtyProcess(parent) +{ + init(); +} +void Pty::init() +{ + _windowColumns = 0; + _windowLines = 0; + _eraseChar = 0; + _xonXoff = true; + _utf8 =true; + + connect(pty(), SIGNAL(readyRead()) , this , SLOT(dataReceived())); + setPtyChannels(KPtyProcess::AllChannels); +} + +Pty::~Pty() +{ +} + +void Pty::sendData(const char* data, int length) +{ + if (!length) + return; + + if (!pty()->write(data,length)) + { + qWarning() << "Pty::doSendJobs - Could not send input data to terminal process."; + return; + } +} + +void Pty::dataReceived() +{ + QByteArray data = pty()->readAll(); + emit receivedData(data.constData(),data.length()); +} + +void Pty::lockPty(bool lock) +{ + Q_UNUSED(lock); + +// TODO: Support for locking the Pty + //if (lock) + //suspend(); + //else + //resume(); +} + +int Pty::foregroundProcessGroup() const +{ + int pid = tcgetpgrp(pty()->masterFd()); + + if ( pid != -1 ) + { + return pid; + } + + return 0; +} + +// TODO: we need to handle this +#if QT_VERSION < 0x060000 +void Pty::setupChildProcess() +{ + KPtyProcess::setupChildProcess(); + // reset all signal handlers + // this ensures that terminal applications respond to + // signals generated via key sequences such as Ctrl+C + // (which sends SIGINT) + struct sigaction action; + sigset_t sigset; + sigemptyset(&action.sa_mask); + sigemptyset(&sigset); + action.sa_handler = SIG_DFL; + action.sa_flags = 0; + for (int signal=1;signal < NSIG; signal++) { + sigaction(signal,&action,nullptr); + sigaddset(&sigset, signal); + } + sigprocmask(SIG_UNBLOCK, &sigset, nullptr); +} +#endif diff --git a/qtermwidget/src/Pty.h b/qtermwidget/lib/Pty.h similarity index 60% rename from qtermwidget/src/Pty.h rename to qtermwidget/lib/Pty.h index f3e9432..cddfef7 100644 --- a/qtermwidget/src/Pty.h +++ b/qtermwidget/lib/Pty.h @@ -1,10 +1,16 @@ /* - This file is part of Konsole, KDE's terminal emulator. - - Copyright (C) 2007 by Robert Knight - Copyright (C) 1997,1998 by Lars Doelle + * This file is a part of QTerminal - http://gitorious.org/qterminal + * + * This file was un-linked from KDE and modified + * by Maxim Bourmistrov + * + */ - Rewritten for QT4 by e_k , Copyright (C)2008 +/* + This file is part of Konsole, KDE's terminal emulator. + + Copyright 2007-2008 by Robert Knight + Copyright 1997,1998 by Lars Doelle This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -26,20 +32,19 @@ #define PTY_H // Qt -#include -#include -#include -#include +#include +#include +#include +#include -#include "k3process.h" +// KDE +#include "kptyprocess.h" - -namespace Konsole -{ +namespace Konsole { /** - * The Pty class is used to start the terminal process, - * send data to it, receive data from it and manipulate + * The Pty class is used to start the terminal process, + * send data to it, receive data from it and manipulate * various properties of the pseudo-teletype interface * used to communicate with the process. * @@ -48,28 +53,35 @@ namespace Konsole * send data to or receive data from the process. * * To start the terminal process, call the start() method - * with the program name and appropriate arguments. + * with the program name and appropriate arguments. */ -class Pty: public K3Process +class Pty: public KPtyProcess { Q_OBJECT public: - - /** + + /** * Constructs a new Pty. - * + * * Connect to the sendData() slot and receivedData() signal to prepare * for sending and receiving data from the terminal process. * - * To start the terminal process, call the run() method with the + * To start the terminal process, call the run() method with the * name of the program to start and appropriate arguments. */ - Pty(); - ~Pty(); + explicit Pty(QObject* parent = nullptr); /** - * Starts the terminal process. + * Construct a process using an open pty master. + * See KPtyProcess::KPtyProcess() + */ + explicit Pty(int ptyMasterFd, QObject* parent = nullptr); + + ~Pty() override; + + /** + * Starts the terminal process. * * Returns 0 if the process was started successfully or non-zero * otherwise. @@ -82,43 +94,51 @@ Q_OBJECT * @param winid Specifies the value of the WINDOWID environment variable * in the process's environment. * @param addToUtmp Specifies whether a utmp entry should be created for - * the pty used. See K3Process::setUsePty() - * @param dbusService Specifies the value of the KONSOLE_DBUS_SERVICE + * the pty used. See K3Process::setUsePty() + * @param dbusService Specifies the value of the KONSOLE_DBUS_SERVICE * environment variable in the process's environment. * @param dbusSession Specifies the value of the KONSOLE_DBUS_SESSION - * environment variable in the process's environment. + * environment variable in the process's environment. */ - int start( const QString& program, - const QStringList& arguments, - const QStringList& environment, - ulong winid, + int start( const QString& program, + const QStringList& arguments, + const QStringList& environment, + ulong winid, bool addToUtmp -// const QString& dbusService, -// const QString& dbusSession ); + /** + * set properties for "EmptyPTY" + */ + void setEmptyPTYProperties(); + /** TODO: Document me */ void setWriteable(bool writeable); - /** - * Enables or disables Xon/Xoff flow control. + /** + * Enables or disables Xon/Xoff flow control. The flow control setting + * may be changed later by a terminal application, so flowControlEnabled() + * may not equal the value of @p on in the previous call to setFlowControlEnabled() */ - void setXonXoff(bool on); + void setFlowControlEnabled(bool on); - /** - * Sets the size of the window (in lines and columns of characters) + /** Queries the terminal state and returns true if Xon/Xoff flow control is enabled. */ + bool flowControlEnabled() const; + + /** + * Sets the size of the window (in lines and columns of characters) * used by this teletype. */ void setWindowSize(int lines, int cols); - + /** Returns the size of the window used by this teletype. See setWindowSize() */ QSize windowSize() const; /** TODO Document me */ void setErase(char erase); - /** */ - char erase() const; + /** */ + char erase() const; /** * Returns the process id of the teletype's current foreground @@ -129,13 +149,6 @@ Q_OBJECT * 0 will be returned. */ int foregroundProcessGroup() const; - - /** - * Returns whether the buffer used to send data to the - * terminal process is full. - */ - bool bufferFull() const { return _bufferFull; } - public slots: @@ -145,7 +158,7 @@ Q_OBJECT void setUtf8Mode(bool on); /** - * Suspend or resume processing of data from the standard + * Suspend or resume processing of data from the standard * output of the terminal process. * * See K3Process::suspend() and K3Process::resume() @@ -154,9 +167,9 @@ Q_OBJECT * otherwise processing is resumed. */ void lockPty(bool lock); - - /** - * Sends data to the process currently controlling the + + /** + * Sends data to the process currently controlling the * teletype ( whose id is returned by foregroundProcessGroup() ) * * @param buffer Pointer to the data to send. @@ -166,13 +179,6 @@ Q_OBJECT signals: - /** - * Emitted when the terminal process terminates. - * - * @param exitCode The status code which the process exited with. - */ - void done(int exitCode); - /** * Emitted when a new block of data is received from * the teletype. @@ -181,61 +187,26 @@ Q_OBJECT * @param length Length of @p buffer */ void receivedData(const char* buffer, int length); - - /** - * Emitted when the buffer used to send data to the terminal - * process becomes empty, i.e. all data has been sent. - */ - void bufferEmpty(); - - +#if QT_VERSION < 0x060000 + protected: + void setupChildProcess() override; +#endif private slots: - - // called when terminal process exits - void donePty(); - // called when data is received from the terminal process - void dataReceived(K3Process*, char* buffer, int length); - // sends the first enqueued buffer of data to the - // terminal process - void doSendJobs(); - // called when the terminal process is ready to - // receive more data - void writeReady(); + // called when data is received from the terminal process + void dataReceived(); private: + void init(); + // takes a list of key=value pairs and adds them // to the environment for the process void addEnvironmentVariables(const QStringList& environment); - // enqueues a buffer of data to be sent to the - // terminal process - void appendSendJob(const char* buffer, int length); - - // a buffer of data in the queue to be sent to the - // terminal process - class SendJob { - public: - SendJob() {} - SendJob(const char* b, int len) : buffer(len) - { - memcpy( buffer.data() , b , len ); - } - - const char* data() const { return buffer.constData(); } - int length() const { return buffer.size(); } - private: - QVector buffer; - }; - - QList _pendingSendJobs; - bool _bufferFull; - - int _windowColumns; + int _windowColumns; int _windowLines; char _eraseChar; bool _xonXoff; bool _utf8; - KPty *_pty; }; } diff --git a/qtermwidget/lib/Screen.cpp b/qtermwidget/lib/Screen.cpp new file mode 100644 index 0000000..ec16a05 --- /dev/null +++ b/qtermwidget/lib/Screen.cpp @@ -0,0 +1,1419 @@ +/* + This file is part of Konsole, an X terminal. + + Copyright 2007-2008 by Robert Knight + Copyright 1997,1998 by Lars Doelle + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is 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 +#include +#include +#include +#include + +// Qt +#include +#include + +// KDE +//#include + +// 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), + history(new HistoryScrollNone()), + cuX(0), cuY(0), + currentRendition(0), + _topMargin(0), _bottomMargin(0), + selBegin(0), selTopLeft(0), selBottomRight(0), + blockSelectionMode(false), + effectiveForeground(CharacterColor()), effectiveBackground(CharacterColor()), effectiveRendition(0), + lastPos(-1) +{ + lineProperties.resize(lines+1); + for (int i=0;i _bottomMargin ? lines-1 : _bottomMargin; + cuX = qMin(columns-1,cuX); // nowrap! + cuY = qMin(stop,cuY+n); +} + +void Screen::cursorLeft(int n) + //=CUB +{ + if (n == 0) n = 1; // Default + cuX = qMin(columns-1,cuX); // nowrap! + cuX = qMax(0,cuX-n); +} + +void Screen::cursorNextLine(int n) + //=CNL +{ + if (n == 0) { + n = 1; // Default + } + cuX = 0; + while (n > 0) { + if (cuY < lines - 1) { + cuY += 1; + } + n--; + } + +} + +void Screen::cursorPreviousLine(int n) + //=CPL +{ + if (n == 0) { + n = 1; // Default + } + cuX = 0; + while (n > 0) { + if (cuY > 0) { + cuY -= 1; + } + n--; + } +} + +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 ) ) + { //Debug()<<" setRegion("< 0) + cuY -= 1; +} + +void Screen::nextLine() + //=NEL +{ + toStartOfLine(); index(); +} + +void Screen::eraseChars(int n) +{ + if (n == 0) n = 1; // Default + int p = qMax(0,qMin(cuX+n-1,columns-1)); + clearImage(loc(cuX,cuY),loc(p,cuY),' '); +} + +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() - 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::repeatChars(int count) + //=REP +{ + if (count == 0) + { + count = 1; + } + /** + * From ECMA-48 version 5, section 8.3.103 + * If the character preceding REP is a control function or part of a + * control function, the effect of REP is not defined by this Standard. + * + * So, a "normal" program should always use REP immediately after a visible + * character (those other than escape sequences). So, lastDrawnChar can be + * safely used. + */ + for (int i = 0; i < count; i++) + { + displayCharacter(lastDrawnChar); + } +} + +void Screen::deleteLines(int n) +{ + if (n == 0) n = 1; // Default + scrollUp(cuY,n); +} + +void Screen::insertLines(int n) +{ + if (n == 0) n = 1; // Default + scrollDown(cuY,n); +} + +void Screen::setMode(int m) +{ + currentModes[m] = true; + switch(m) + { + case MODE_Origin : cuX = 0; cuY = _topMargin; break; //FIXME: home + } +} + +void Screen::resetMode(int m) +{ + currentModes[m] = false; + switch(m) + { + case MODE_Origin : cuX = 0; cuY = 0; break; //FIXME: home + } +} + +void Screen::saveMode(int m) +{ + savedModes[m] = currentModes[m]; +} + +void Screen::restoreMode(int m) +{ + currentModes[m] = savedModes[m]; +} + +bool Screen::getMode(int m) const +{ + return currentModes[m]; +} + +void Screen::saveCursor() +{ + savedState.cursorColumn = cuX; + savedState.cursorLine = cuY; + savedState.rendition = currentRendition; + savedState.foreground = currentForeground; + savedState.background = currentBackground; +} + +void Screen::restoreCursor() +{ + cuX = qMin(savedState.cursorColumn,columns-1); + cuY = qMin(savedState.cursorLine,lines-1); + currentRendition = savedState.rendition; + currentForeground = savedState.foreground; + currentBackground = savedState.background; + updateEffectiveRendition(); +} + +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 + _bottomMargin = lines-1; //FIXME: margin lost + for (int i = 0; i < cuY-(new_lines-1); i++) + { + addHistLine(); scrollUp(0,1); + } + } + + // create new screen lines and copy from old to new + + ImageLine* newScreenLines = new ImageLine[new_lines+1]; + for (int i=0; i < qMin(lines,new_lines+1) ;i++) + newScreenLines[i]=screenLines[i]; + for (int i=lines;(i > 0) && (i 0) && (ir &= ~RE_TRANSPARENT; +} + +void Screen::updateEffectiveRendition() +{ + effectiveRendition = currentRendition; + if (currentRendition & RE_REVERSE) + { + effectiveForeground = currentBackground; + effectiveBackground = currentForeground; + } + else + { + effectiveForeground = currentForeground; + effectiveBackground = currentBackground; + } + + if (currentRendition & RE_BOLD) + effectiveForeground.setIntensive(); +} + +void Screen::copyFromHistory(Character* dest, int startLine, int count) const +{ + Q_ASSERT( startLine >= 0 && count > 0 && startLine + count <= history->getLines() ); + + for (int line = startLine; line < startLine + count; line++) + { + const int length = qMin(columns,history->getLineLen(line)); + const int destLineOffset = (line-startLine)*columns; + + history->getCells(line,0,length,dest + destLineOffset); + + for (int column = length; column < columns; column++) + dest[destLineOffset+column] = defaultChar; + + // invert selected text + if (selBegin !=-1) + { + for (int column = 0; column < columns; column++) + { + if (isSelected(column,line)) + { + reverseRendition(dest[destLineOffset + column]); + } + } + } + } +} + +void Screen::copyFromScreen(Character* dest , int startLine , int count) const +{ + Q_ASSERT( startLine >= 0 && count > 0 && startLine + count <= lines ); + + 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 (selBegin != -1 && isSelected(column,line + history->getLines())) + reverseRendition(dest[destIndex]); + } + + } +} + +void Screen::getImage( Character* dest, int size, int startLine, int endLine ) const +{ + Q_ASSERT( startLine >= 0 ); + Q_ASSERT( endLine >= startLine && endLine < history->getLines() + lines ); + + const int mergedLines = endLine - startLine + 1; + + Q_ASSERT( size >= mergedLines * columns ); + Q_UNUSED( size ); + + const int linesInHistoryBuffer = qBound(0,history->getLines()-startLine,mergedLines); + const int linesInScreenBuffer = mergedLines - linesInHistoryBuffer; + + // copy lines from history buffer + if (linesInHistoryBuffer > 0) + copyFromHistory(dest,startLine,linesInHistoryBuffer); + + // copy lines from screen buffer + if (linesInScreenBuffer > 0) + copyFromScreen(dest + linesInHistoryBuffer*columns, + startLine + linesInHistoryBuffer - history->getLines(), + linesInScreenBuffer); + + // invert display when in screen mode + if (getMode(MODE_Screen)) + { + for (int i = 0; i < mergedLines*columns; i++) + reverseRendition(dest[i]); // for reverse display + } + + // 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 Screen::getLineProperties( int startLine , int endLine ) const +{ + Q_ASSERT( startLine >= 0 ); + Q_ASSERT( endLine >= startLine && endLine < history->getLines() + lines ); + + const int mergedLines = endLine-startLine+1; + const int linesInHistory = qBound(0,history->getLines()-startLine,mergedLines); + const int linesInScreen = mergedLines - linesInHistory; + + QVector result(mergedLines); + int index = 0; + + // copy properties for lines in history + for (int line = startLine; line < startLine + linesInHistory; line++) + { + //TODO Support for line properties other than wrapped lines + if (history->isWrappedLine(line)) + { + result[index] = (LineProperty)(result[index] | LINE_WRAPPED); + } + index++; + } + + // copy properties for lines in screen buffer + const int firstScreenLine = startLine + linesInHistory - history->getLines(); + for (int line = firstScreenLine; line < firstScreenLine+linesInScreen; line++) + { + result[index]=lineProperties[line]; + index++; + } + + return result; +} + +void Screen::reset(bool clearScreen) +{ + setMode(MODE_Wrap ); saveMode(MODE_Wrap ); // wrap at end of margin + resetMode(MODE_Origin); saveMode(MODE_Origin); // position refers to [1,1] + resetMode(MODE_Insert); saveMode(MODE_Insert); // overstroke + setMode(MODE_Cursor); // cursor visible + resetMode(MODE_Screen); // screen not inverse + resetMode(MODE_NewLine); + + _topMargin=0; + _bottomMargin=lines-1; + + setDefaultRendition(); + saveCursor(); + + if ( clearScreen ) + clear(); +} + +void Screen::clear() +{ + clearEntireScreen(); + home(); +} + +void Screen::backspace() +{ + cuX = qMin(columns-1,cuX); // nowrap! + cuX = qMax(0,cuX-1); + + if (screenLines[cuY].size() < cuX+1) + screenLines[cuY].resize(cuX+1); + + if (BS_CLEARS) + screenLines[cuY][cuX].character = ' '; +} + +void Screen::tab(int n) +{ + // note that TAB is a format effector (does not write ' '); + if (n == 0) n = 1; + while((n > 0) && (cuX < columns-1)) + { + cursorRight(1); + while((cuX < columns-1) && !tabStops[cuX]) + cursorRight(1); + n--; + } +} + +void Screen::backtab(int n) +{ + // note that TAB is a format effector (does not write ' '); + if (n == 0) n = 1; + while((n > 0) && (cuX > 0)) + { + cursorLeft(1); while((cuX > 0) && !tabStops[cuX]) cursorLeft(1); + n--; + } +} + +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() +{ + tabStops.resize(columns); + + // Arrg! The 1st tabstop has to be one longer than the other. + // i.e. the kids start counting from 0 instead of 1. + // Other programs might behave correctly. Be aware. + for (int i = 0; i < columns; i++) + tabStops[i] = (i%8 == 0 && i != 0); +} + +void Screen::newLine() +{ + if (getMode(MODE_NewLine)) + toStartOfLine(); + index(); +} + +void Screen::checkSelection(int from, int to) +{ + if (selBegin == -1) + return; + int scr_TL = loc(0, history->getLines()); + //Clear entire selection if it overlaps region [from, to] + if ( (selBottomRight >= (from+scr_TL)) && (selTopLeft <= (to+scr_TL)) ) + clearSelection(); +} + +void Screen::displayCharacter(wchar_t 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 < cuX+w) + { + screenLines[cuY].resize(cuX+w); + } + + if (getMode(MODE_Insert)) insertChars(w); + + lastPos = loc(cuX,cuY); + + // check if selection is still valid. + checkSelection(lastPos, lastPos); + + Character& currentChar = screenLines[cuY][cuX]; + + currentChar.character = c; + currentChar.foregroundColor = effectiveForeground; + currentChar.backgroundColor = effectiveBackground; + currentChar.rendition = effectiveRendition; + + lastDrawnChar = c; + + 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 = effectiveForeground; + ch.backgroundColor = effectiveBackground; + ch.rendition = effectiveRendition; + + 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() +{ + _scrolledLines = 0; +} + +void Screen::scrollUp(int n) +{ + if (n == 0) n = 1; // Default + if (_topMargin == 0) addHistLine(); // history.history + scrollUp(_topMargin, n); +} + +QRect Screen::lastScrolledRegion() const +{ + return _lastScrolledRegion; +} + +void Screen::scrollUp(int from, int n) +{ + if (n <= 0) + return; + if (from > _bottomMargin) + return; + if (from + n > _bottomMargin) + n = _bottomMargin + 1 - from; + + _scrolledLines -= n; + _lastScrolledRegion = QRect(0,_topMargin,columns-1,(_bottomMargin-_topMargin)); + + //FIXME: make sure `topMargin', `bottomMargin', `from', `n' is in bounds. + moveImage(loc(0,from),loc(0,from+n),loc(columns,_bottomMargin)); + clearImage(loc(0,_bottomMargin-n+1),loc(columns-1,_bottomMargin),' '); +} + +void Screen::scrollDown(int n) +{ + if (n == 0) n = 1; // Default + scrollDown(_topMargin, n); +} + +void Screen::scrollDown(int from, int n) +{ + _scrolledLines += n; + + //FIXME: make sure `topMargin', `bottomMargin', `from', `n' is in bounds. + if (n <= 0) + return; + if (from > _bottomMargin) + return; + if (from + n > _bottomMargin) + n = _bottomMargin - from; + moveImage(loc(0,from+n),loc(0,from),loc(columns-1,_bottomMargin-n)); + clearImage(loc(0,from),loc(columns-1,from+n-1),' '); +} + +void Screen::setCursorYX(int y, int x) +{ + setCursorY(y); setCursorX(x); +} + +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) ? _topMargin : 0) )); +} + +void Screen::home() +{ + cuX = 0; + cuY = 0; +} + +void Screen::toStartOfLine() +{ + cuX = 0; +} + +int Screen::getCursorX() const +{ + return cuX; +} + +int Screen::getCursorY() const +{ + return cuY; +} + +void Screen::clearImage(int loca, int loce, char c) +{ + int scr_TL=loc(0,history->getLines()); + //FIXME: check positions + + //Clear entire selection if it overlaps region to be moved... + if ( (selBottomRight > (loca+scr_TL) )&&(selTopLeft < (loce+scr_TL)) ) + { + clearSelection(); + } + + int topLine = loca/columns; + int bottomLine = loce/columns; + + Character clearCh(c,currentForeground,currentBackground,DEFAULT_RENDITION); + + //if the character being used to clear the area is the same as the + //default character, the affected lines can simply be shrunk. + bool isDefaultCh = (clearCh == Character()); + + for (int y=topLine;y<=bottomLine;y++) + { + lineProperties[y] = 0; + + int endCol = ( y == bottomLine) ? loce%columns : columns-1; + int startCol = ( y == topLine ) ? loca%columns : 0; + + QVector& 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; + } + } +} + +void Screen::moveImage(int dest, int sourceBegin, int sourceEnd) +{ + 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 (selBegin != -1) + { + bool beginIsTL = (selBegin == selTopLeft); + int diff = dest - sourceBegin; // Scroll by this amount + int scr_TL=loc(0,history->getLines()); + int srca = sourceBegin+scr_TL; // Translate index from screen to global + int srce = sourceEnd+scr_TL; // Translate index from screen to global + int desta = srca+diff; + int deste = srce+diff; + + if ((selTopLeft >= srca) && (selTopLeft <= srce)) + selTopLeft += diff; + else if ((selTopLeft >= desta) && (selTopLeft <= deste)) + selBottomRight = -1; // Clear selection (see below) + + if ((selBottomRight >= srca) && (selBottomRight <= srce)) + selBottomRight += diff; + else if ((selBottomRight >= desta) && (selBottomRight <= deste)) + selBottomRight = -1; // Clear selection (see below) + + if (selBottomRight < 0) + { + clearSelection(); + } + else + { + if (selTopLeft < 0) + selTopLeft = 0; + } + + if (beginIsTL) + selBegin = selTopLeft; + else + selBegin = selBottomRight; + } +} + +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) +{ + currentRendition |= re; + updateEffectiveRendition(); +} + +void Screen::resetRendition(int re) +{ + currentRendition &= ~re; + updateEffectiveRendition(); +} + +void Screen::setDefaultRendition() +{ + setForeColor(COLOR_SPACE_DEFAULT,DEFAULT_FORE_COLOR); + setBackColor(COLOR_SPACE_DEFAULT,DEFAULT_BACK_COLOR); + currentRendition = DEFAULT_RENDITION; + updateEffectiveRendition(); +} + +void Screen::setForeColor(int space, int color) +{ + currentForeground = CharacterColor(space, color); + + if ( currentForeground.isValid() ) + updateEffectiveRendition(); + else + setForeColor(COLOR_SPACE_DEFAULT,DEFAULT_FORE_COLOR); +} + +void Screen::setBackColor(int space, int color) +{ + currentBackground = CharacterColor(space, color); + + if ( currentBackground.isValid() ) + updateEffectiveRendition(); + else + setBackColor(COLOR_SPACE_DEFAULT,DEFAULT_BACK_COLOR); +} + +void Screen::clearSelection() +{ + selBottomRight = -1; + selTopLeft = -1; + selBegin = -1; +} + +void Screen::getSelectionStart(int& column , int& line) const +{ + if ( selTopLeft != -1 ) + { + column = selTopLeft % columns; + line = selTopLeft / columns; + } + else + { + column = cuX + getHistLines(); + line = cuY + getHistLines(); + } +} +void Screen::getSelectionEnd(int& column , int& line) const +{ + if ( selBottomRight != -1 ) + { + column = selBottomRight % columns; + line = selBottomRight / columns; + } + else + { + column = cuX + getHistLines(); + line = cuY + getHistLines(); + } +} +void Screen::setSelectionStart(const int x, const int y, const bool mode) +{ + selBegin = loc(x,y); + /* FIXME, HACK to correct for x too far to the right... */ + if (x == columns) selBegin--; + + selBottomRight = selBegin; + selTopLeft = selBegin; + blockSelectionMode = mode; +} + +void Screen::setSelectionEnd( const int x, const int y) +{ + if (selBegin == -1) + return; + + int endPos = loc(x,y); + + if (endPos < selBegin) + { + selTopLeft = endPos; + selBottomRight = selBegin; + } + else + { + /* FIXME, HACK to correct for x too far to the right... */ + if (x == columns) + endPos--; + + selTopLeft = selBegin; + selBottomRight = endPos; + } + + // Normalize the selection in column mode + if (blockSelectionMode) + { + int topRow = selTopLeft / columns; + int topColumn = selTopLeft % columns; + int bottomRow = selBottomRight / columns; + int bottomColumn = selBottomRight % columns; + + selTopLeft = loc(qMin(topColumn,bottomColumn),topRow); + selBottomRight = loc(qMax(topColumn,bottomColumn),bottomRow); + } +} + +bool Screen::isSelected( const int x,const int y) const +{ + bool columnInSelection = true; + if (blockSelectionMode) + { + columnInSelection = x >= (selTopLeft % columns) && + x <= (selBottomRight % columns); + } + + int pos = loc(x,y); + return pos >= selTopLeft && pos <= selBottomRight && columnInSelection; +} + +QString Screen::selectedText(bool preserveLineBreaks) const +{ + QString result; + QTextStream stream(&result, QIODevice::ReadWrite); + + PlainTextDecoder decoder; + decoder.begin(&stream); + writeSelectionToStream(&decoder , preserveLineBreaks); + decoder.end(); + + return result; +} + +bool Screen::isSelectionValid() const +{ + return selTopLeft >= 0 && selBottomRight >= 0; +} + +void Screen::writeSelectionToStream(TerminalCharacterDecoder* decoder , + bool preserveLineBreaks) const +{ + if (!isSelectionValid()) + return; + writeToStream(decoder,selTopLeft,selBottomRight,preserveLineBreaks); +} + +void Screen::writeToStream(TerminalCharacterDecoder* decoder, + int startIndex, int endIndex, + bool preserveLineBreaks) const +{ + int top = startIndex / columns; + int left = startIndex % columns; + + int bottom = endIndex / columns; + int right = endIndex % columns; + + Q_ASSERT( top >= 0 && left >= 0 && bottom >= 0 && right >= 0 ); + + for (int y=top;y<=bottom;y++) + { + int start = 0; + if ( y == top || blockSelectionMode ) start = left; + + int count = -1; + if ( y == bottom || blockSelectionMode ) count = right - start + 1; + + const bool appendNewLine = ( y != bottom ); + int copied = copyLineToStream( y, + start, + count, + decoder, + appendNewLine, + preserveLineBreaks ); + + // if the selection goes beyond the end of the last line then + // append a new line character. + // + // this makes it possible to 'select' a trailing new line character after + // the text on a line. + if ( y == bottom && + copied < count ) + { + Character newLineChar('\n'); + decoder->decodeLine(&newLineChar,1,0); + } + } +} + +int Screen::copyLineToStream(int line , + int start, + int count, + TerminalCharacterDecoder* decoder, + bool appendNewLine, + bool preserveLineBreaks) const +{ + //buffer to hold characters for decoding + //the buffer is static to avoid initialising every + //element on each call to copyLineToStream + //(which is unnecessary since all elements will be overwritten anyway) + static const int MAX_CHARS = 1024; + static Character characterBuffer[MAX_CHARS]; + + Q_ASSERT( count < MAX_CHARS ); + + LineProperty currentLineProperties = 0; + + //determine if the line is in the history buffer or the screen image + if (line < history->getLines()) + { + const int lineLength = history->getLineLen(line); + + // ensure that start position is before end of line + start = qMin(start,qMax(0,lineLength-1)); + + // retrieve line from history buffer. It is assumed + // that the history buffer does not store trailing white space + // at the end of the line, so it does not need to be trimmed here + if (count == -1) + { + count = lineLength-start; + } + else + { + count = qMin(start+count,lineLength)-start; + } + + // safety checks + Q_ASSERT( start >= 0 ); + Q_ASSERT( count >= 0 ); + Q_ASSERT( (start+count) <= history->getLineLen(line) ); + + history->getCells(line,start,count,characterBuffer); + + if ( history->isWrappedLine(line) ) + currentLineProperties |= LINE_WRAPPED; + } + else + { + if ( count == -1 ) + count = columns - start; + + Q_ASSERT( count >= 0 ); + + const int screenLine = line-history->getLines(); + + Character* data = screenLines[screenLine].data(); + int length = screenLines[screenLine].count(); + + //retrieve line from screen image + for (int i=start;i < qMin(start+count,length);i++) + { + characterBuffer[i-start] = data[i]; + } + + // count cannot be any greater than length + count = qBound(0,count,length-start); + + Q_ASSERT( screenLine < lineProperties.count() ); + currentLineProperties |= lineProperties[screenLine]; + } + + // add new line character at end + const bool omitLineBreak = (currentLineProperties & LINE_WRAPPED) || + !preserveLineBreaks; + + if ( !omitLineBreak && appendNewLine && (count+1 < MAX_CHARS) ) + { + characterBuffer[count] = '\n'; + count++; + } + + //decode line and write to text stream + decoder->decodeLine( (Character*) characterBuffer , + count, currentLineProperties ); + + return count; +} + +void Screen::writeLinesToStream(TerminalCharacterDecoder* decoder, int fromLine, int toLine) const +{ + writeToStream(decoder,loc(0,fromLine),loc(columns-1,toLine)); +} + +void Screen::addHistLine() +{ + // add line to history buffer + // we have to take care about scrolling, too... + + if (hasScroll()) + { + int oldHistLines = history->getLines(); + + history->addCellsVector(screenLines[0]); + history->addLine( lineProperties[0] & LINE_WRAPPED ); + + int newHistLines = history->getLines(); + + bool beginIsTL = (selBegin == selTopLeft); + + // If the history is full, increment the count + // of dropped lines + if ( newHistLines == oldHistLines ) + _droppedLines++; + + // Adjust selection for the new point of reference + if (newHistLines > oldHistLines) + { + if (selBegin != -1) + { + selTopLeft += columns; + selBottomRight += columns; + } + } + + if (selBegin != -1) + { + // Scroll selection in history up + int top_BR = loc(0, 1+newHistLines); + + if (selTopLeft < top_BR) + selTopLeft -= columns; + + if (selBottomRight < top_BR) + selBottomRight -= columns; + + if (selBottomRight < 0) + clearSelection(); + else + { + if (selTopLeft < 0) + selTopLeft = 0; + } + + if (beginIsTL) + selBegin = selTopLeft; + else + selBegin = selBottomRight; + } + } + +} + +int Screen::getHistLines() const +{ + return history->getLines(); +} + +void Screen::setScroll(const HistoryType& t , bool copyPreviousScroll) +{ + clearSelection(); + + if ( copyPreviousScroll ) + history = t.scroll(history); + else + { + HistoryScroll* oldScroll = history; + history = t.scroll(nullptr); + delete oldScroll; + } +} + +bool Screen::hasScroll() const +{ + return history->hasScroll(); +} + +const HistoryType& Screen::getScroll() const +{ + return history->getType(); +} + +void Screen::setLineProperty(LineProperty property , bool enable) +{ + if ( enable ) + lineProperties[cuY] = (LineProperty)(lineProperties[cuY] | property); + else + lineProperties[cuY] = (LineProperty)(lineProperties[cuY] & ~property); +} +void Screen::fillWithDefaultChar(Character* dest, int count) +{ + for (int i=0;i - Copyright (C) 1997,1998 by Lars Doelle - - Rewritten for QT4 by e_k , Copyright (C)2008 + Copyright 2007-2008 by Robert Knight + Copyright 1997,1998 by Lars Doelle This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -26,9 +24,9 @@ #define SCREEN_H // Qt -#include -#include -#include +#include +#include +#include // Konsole #include "Character.h" @@ -45,13 +43,6 @@ namespace Konsole { -/*! -*/ -struct ScreenParm -{ - int mode[MODES_SCREEN]; -}; - class TerminalCharacterDecoder; /** @@ -61,21 +52,21 @@ class TerminalCharacterDecoder; characters from the program currently running in the terminal. From this stream it creates an image of characters which is ultimately rendered by the display widget ( TerminalDisplay ). Some types of emulation - may have more than one screen image. + may have more than one screen image. getImage() is used to retrieve the currently visible image which is then used by the display widget to draw the output from the - terminal. + terminal. The number of lines of output history which are kept in addition to the current - screen image depends on the history scroll being used to store the output. + screen image depends on the history scroll being used to store the output. The scroll is specified using setScroll() The output history can be retrieved using writeToStream() - The screen image has a selection associated with it, specified using + The screen image has a selection associated with it, specified using setSelectionStart() and setSelectionEnd(). The selected text can be retrieved - using selectedText(). When getImage() is used to retrieve the the visible image, - characters which are part of the selection have their colours inverted. + using selectedText(). When getImage() is used to retrieve the visible image, + characters which are part of the selection have their colours inverted. */ class Screen { @@ -84,74 +75,96 @@ public: Screen(int lines, int columns); ~Screen(); - // VT100/2 Operations + // VT100/2 Operations // Cursor Movement - - /** Move the cursor up by @p n lines. */ - void cursorUp (int n); - /** Move the cursor down by @p n lines. */ - void cursorDown (int n); - /** Move the cursor to the left by @p n columns. */ - void cursorLeft (int n); - /** Move the cursor to the right by @p n columns. */ - void cursorRight (int n); + + /** + * Move the cursor up by @p n lines. The cursor will stop at the + * top margin. + */ + void cursorUp(int n); + /** + * Move the cursor down by @p n lines. The cursor will stop at the + * bottom margin. + */ + void cursorDown(int n); + /** + * Move the cursor to the left by @p n columns. + * The cursor will stop at the first column. + */ + void cursorLeft(int n); + /** + * Moves cursor to beginning of the line by @p n lines down. + * The cursor will stop at the beginning of the line. + */ + void cursorNextLine(int n); + /** + * Moves cursor to beginning of the line by @p n lines up. + * The cursor will stop at the beginning of the line. + */ + void cursorPreviousLine(int n); + /** + * Move the cursor to the right by @p n columns. + * The cursor will stop at the right-most column. + */ + void cursorRight(int n); /** Position the cursor on line @p y. */ - void setCursorY (int y); + void setCursorY(int y); /** Position the cursor at column @p x. */ - void setCursorX (int x); + void setCursorX(int x); /** Position the cursor at line @p y, column @p x. */ - void setCursorYX (int y, int x); + void setCursorYX(int y, int x); /** * Sets the margins for scrolling the screen. * - * @param topLine The top line of the new scrolling margin. - * @param bottomLine The bottom line of the new scrolling margin. + * @param topLine The top line of the new scrolling margin. + * @param bottomLine The bottom line of the new scrolling margin. */ - void setMargins (int topLine , int bottomLine); - /** Returns the top line of the scrolling region. */ + void setMargins(int topLine , int bottomLine); + /** Returns the top line of the scrolling region. */ int topMargin() const; /** Returns the bottom line of the scrolling region. */ int bottomMargin() const; - /** + /** * Resets the scrolling margins back to the top and bottom lines * of the screen. */ void setDefaultMargins(); - - /** - * Moves the cursor down one line, if the MODE_NewLine mode + + /** + * Moves the cursor down one line, if the MODE_NewLine mode * flag is enabled then the cursor is returned to the leftmost * column first. * * Equivalent to NextLine() if the MODE_NewLine flag is set - * or index() otherwise. + * or index() otherwise. */ - void NewLine (); + void newLine(); /** * Moves the cursor down one line and positions it at the beginning - * of the line. + * of the line. Equivalent to calling Return() followed by index() */ - void NextLine (); + void nextLine(); - /** + /** * Move the cursor down one line. If the cursor is on the bottom * line of the scrolling region (as returned by bottomMargin()) the * scrolling region is scrolled up by one line instead. */ - void index (); + void index(); /** * Move the cursor up one line. If the cursor is on the top line * of the scrolling region (as returned by topMargin()) the scrolling * region is scrolled down by one line instead. */ void reverseIndex(); - - /** - * Scroll the scrolling region of the screen up by @p n lines. - * The scrolling region is initially the whole screen, but can be changed + + /** + * Scroll the scrolling region of the screen up by @p n lines. + * The scrolling region is initially the whole screen, but can be changed * using setMargins() - */ + */ void scrollUp(int n); /** * Scroll the scrolling region of the screen down by @p n lines. @@ -159,89 +172,89 @@ public: * using setMargins() */ void scrollDown(int n); - - /** - * Moves the cursor to the beginning of the current line. + /** + * Moves the cursor to the beginning of the current line. * Equivalent to setCursorX(0) */ - void Return (); - /** + void toStartOfLine(); + /** * Moves the cursor one column to the left and erases the character * at the new cursor position. */ - void BackSpace (); - /** - * Moves the cursor @p n tab-stops to the right. - */ - void Tabulate (int n = 1); - /** - * Moves the cursor @p n tab-stops to the left. - */ - void backTabulate(int n); - + void backspace(); + /** Moves the cursor @p n tab-stops to the right. */ + void tab(int n = 1); + /** Moves the cursor @p n tab-stops to the left. */ + void backtab(int n); + // Editing - - /** - * Erase @p n characters beginning from the current cursor position. + + /** + * Erase @p n characters beginning from the current cursor position. * This is equivalent to over-writing @p n characters starting with the current * cursor position with spaces. - * If @p n is 0 then one character is erased. + * If @p n is 0 then one character is erased. */ - void eraseChars (int n); - /** - * Delete @p n characters beginning from the current cursor position. - * If @p n is 0 then one character is deleted. + void eraseChars(int n); + /** + * Delete @p n characters beginning from the current cursor position. + * If @p n is 0 then one character is deleted. */ - void deleteChars (int n); + void deleteChars(int n); /** * Insert @p n blank characters beginning from the current cursor position. - * The position of the cursor is not altered. + * The position of the cursor is not altered. * If @p n is 0 then one character is inserted. */ - void insertChars (int n); - /** + void insertChars(int n); + /** + * Repeat the preceding graphic character @count times, including SPACE. + * If @count is 0 then the character is repeated once. + */ + void repeatChars(int count); + /** * Removes @p n lines beginning from the current cursor position. * The position of the cursor is not altered. * If @p n is 0 then one line is removed. */ - void deleteLines (int n); + void deleteLines(int n); /** * Inserts @p lines beginning from the current cursor position. * The position of the cursor is not altered. * If @p n is 0 then one line is inserted. */ - void insertLines (int n); + void insertLines(int n); /** Clears all the tab stops. */ void clearTabStops(); - /** Sets or removes a tab stop at the cursor's current column. */ + /** Sets or removes a tab stop at the cursor's current column. */ void changeTabStop(bool set); - + /** Resets (clears) the specified screen @p mode. */ - void resetMode (int mode); + void resetMode(int mode); /** Sets (enables) the specified screen @p mode. */ - void setMode (int mode); - /** + void setMode(int mode); + /** * Saves the state of the specified screen @p mode. It can be restored * using restoreMode() */ - void saveMode (int mode); + void saveMode(int mode); /** Restores the state of a screen @p mode saved by calling saveMode() */ - void restoreMode (int mode); + void restoreMode(int mode); /** Returns whether the specified screen @p mode is enabled or not .*/ - bool getMode (int mode) const; - - /** - * Saves the current position and appearence (text color and style) of the cursor. - * It can be restored by calling restoreCursor() - */ - void saveCursor (); - /** Restores the position and appearence of the cursor. See saveCursor() */ + bool getMode(int mode) const; + + /** + * Saves the current position and appearance (text color and style) of the cursor. + * It can be restored by calling restoreCursor() + */ + void saveCursor(); + /** Restores the position and appearance of the cursor. See saveCursor() */ void restoreCursor(); - - /** Clear the whole screen, moving the current screen contents into the history first. */ + + /** Clear the whole screen, moving the current screen contents into the history first. */ void clearEntireScreen(); - /** - * Clear the area of the screen from the current cursor position to the end of + /** + * Clear the area of the screen from the current cursor position to the end of * the screen. */ void clearToEndOfScreen(); @@ -256,26 +269,26 @@ public: void clearToEndOfLine(); /** Clears from the current cursor position to the beginning of the line. */ void clearToBeginOfLine(); - + /** Fills the entire screen with the letter 'E' */ - void helpAlign (); - - /** - * Enables the given @p rendition flag. Rendition flags control the appearence + void helpAlign(); + + /** + * Enables the given @p rendition flag. Rendition flags control the appearance * of characters on the screen. * * @see Character::rendition - */ - void setRendition (int rendition); + */ + void setRendition(int rendition); /** - * Disables the given @p rendition flag. Rendition flags control the appearence + * Disables the given @p rendition flag. Rendition flags control the appearance * of characters on the screen. * * @see Character::rendition */ void resetRendition(int rendition); - - /** + + /** * Sets the cursor's foreground color. * @param space The color space used by the @p color argument * @param color The new foreground color. The meaning of this depends on @@ -283,32 +296,34 @@ public: * * @see CharacterColor */ - void setForeColor (int space, int color); + void setForeColor(int space, int color); /** * Sets the cursor's background color. - * @param space The color space used by the @p color argumnet. + * @param space The color space used by the @p color argument. * @param color The new background color. The meaning of this depends on * the color @p space used. * * @see CharacterColor */ - void setBackColor (int space, int color); - /** - * Resets the cursor's color back to the default and sets the + void setBackColor(int space, int color); + /** + * Resets the cursor's color back to the default and sets the * character's rendition flags back to the default settings. */ void setDefaultRendition(); - + /** Returns the column which the cursor is positioned at. */ int getCursorX() const; /** Returns the line which the cursor is positioned on. */ int getCursorY() const; - - /** TODO Document me */ - void clear(); - /** + + /** Clear the entire screen and move the cursor to the home position. + * Equivalent to calling clearEntireScreen() followed by home(). + */ + void clear(); + /** * Sets the position of the cursor to the 'home' position at the top-left - * corner of the screen (0,0) + * corner of the screen (0,0) */ void home(); /** @@ -325,40 +340,41 @@ public: *
  • New line mode is disabled. TODO Document me
  • * * - * If @p clearScreen is true then the screen contents are erased entirely, + * If @p clearScreen is true then the screen contents are erased entirely, * otherwise they are unaltered. */ void reset(bool clearScreen = true); - - /** - * Displays a new character at the current cursor position. - * + + /** + * Displays a new character at the current cursor position. + * * If the cursor is currently positioned at the right-edge of the screen and - * line wrapping is enabled then the character is added at the start of a new + * line wrapping is enabled then the character is added at the start of a new * line below the current one. * - * If the MODE_Insert screen mode is currently enabled then the character - * is inserted at the current cursor position, otherwise it will replace the - * character already at the current cursor position. - */ - void ShowCharacter(unsigned short c); - + * If the MODE_Insert screen mode is currently enabled then the character + * is inserted at the current cursor position, otherwise it will replace the + * character already at the current cursor position. + */ + void displayCharacter(wchar_t c); + // Do composition with last shown character FIXME: Not implemented yet for KDE 4 void compose(const QString& compose); - - /** - * Resizes the image to a new fixed size of @p new_lines by @p new_columns. + + /** + * Resizes the image to a new fixed size of @p new_lines by @p new_columns. * In the case that @p new_columns is smaller than the current number of columns, * existing lines are not truncated. This prevents characters from being lost * if the terminal display is resized smaller and then larger again. * - * (note that in versions of Konsole prior to KDE 4, existing lines were - * truncated when making the screen image smaller) + * The top and bottom margins are reset to the top and bottom of the new + * screen size. Tab stops are also reset and the current selection is + * cleared. */ void resizeImage(int new_lines, int new_columns); - + /** - * Returns the current screen image. + * Returns the current screen image. * The result is an array of Characters of size [getLines()][getColumns()] which * must be freed by the caller after use. * @@ -369,148 +385,153 @@ public: */ void getImage( Character* dest , int size , int startLine , int endLine ) const; - /** + /** * Returns the additional attributes associated with lines in the image. - * The most important attribute is LINE_WRAPPED which specifies that the + * The most important attribute is LINE_WRAPPED which specifies that the * line is wrapped, * other attributes control the size of characters in the line. */ QVector getLineProperties( int startLine , int endLine ) const; - + /** Return the number of lines. */ - int getLines() { return lines; } + int getLines() const + { return lines; } /** Return the number of columns. */ - int getColumns() { return columns; } + int getColumns() const + { return columns; } /** Return the number of lines in the history buffer. */ - int getHistLines (); - /** - * Sets the type of storage used to keep lines in the history. - * If @p copyPreviousScroll is true then the contents of the previous + int getHistLines() const; + /** + * Sets the type of storage used to keep lines in the history. + * If @p copyPreviousScroll is true then the contents of the previous * history buffer are copied into the new scroll. */ void setScroll(const HistoryType& , bool copyPreviousScroll = true); /** Returns the type of storage used to keep lines in the history. */ - const HistoryType& getScroll(); - /** + const HistoryType& getScroll() const; + /** * Returns true if this screen keeps lines that are scrolled off the screen * in a history buffer. */ - bool hasScroll(); + bool hasScroll() const; - /** + /** * Sets the start of the selection. * * @param column The column index of the first character in the selection. * @param line The line index of the first character in the selection. - * @param columnmode True if the selection is in column mode. + * @param blockSelectionMode True if the selection is in column mode. */ - void setSelectionStart(const int column, const int line, const bool columnmode); - + void setSelectionStart(const int column, const int line, const bool blockSelectionMode); + /** * Sets the end of the current selection. * * @param column The column index of the last character in the selection. - * @param line The line index of the last character in the selection. - */ + * @param line The line index of the last character in the selection. + */ void setSelectionEnd(const int column, const int line); - + /** * Retrieves the start of the selection or the cursor position if there * is no selection. */ - void getSelectionStart(int& column , int& line); - + void getSelectionStart(int& column , int& line) const; + /** * Retrieves the end of the selection or the cursor position if there * is no selection. */ - void getSelectionEnd(int& column , int& line); + void getSelectionEnd(int& column , int& line) const; /** Clears the current selection */ void clearSelection(); - void setBusySelecting(bool busy) { sel_busy = busy; } - - /** - * Returns true if the character at (@p column, @p line) is part of the - * current selection. - */ + /** + * Returns true if the character at (@p column, @p line) is part of the + * current selection. + */ bool isSelected(const int column,const int line) const; - /** - * Convenience method. Returns the currently selected text. - * @param preserveLineBreaks Specifies whether new line characters should + /** + * Convenience method. Returns the currently selected text. + * @param preserveLineBreaks Specifies whether new line characters should * be inserted into the returned text at the end of each terminal line. */ - QString selectedText(bool preserveLineBreaks); - - /** - * Copies part of the output to a stream. - * - * @param decoder A decoder which coverts terminal characters into text - * @param from The first line in the history to retrieve - * @param to The last line in the history to retrieve - */ - void writeToStream(TerminalCharacterDecoder* decoder, int from, int to); + QString selectedText(bool preserveLineBreaks) const; - /** - * Sets the selection to line @p no in the history and returns - * the text of that line from the history buffer. + /** + * Copies part of the output to a stream. + * + * @param decoder A decoder which converts terminal characters into text + * @param fromLine The first line in the history to retrieve + * @param toLine The last line in the history to retrieve */ - QString getHistoryLine(int no); + void writeLinesToStream(TerminalCharacterDecoder* decoder, int fromLine, int toLine) const; - /** - * Copies the selected characters, set using @see setSelBeginXY and @see setSelExtentXY - * into a stream. - * - * @param decoder A decoder which converts terminal characters into text. - * PlainTextDecoder is the most commonly used decoder which coverts characters - * into plain text with no formatting. - * @param preserveLineBreaks Specifies whether new line characters should - * be inserted into the returned text at the end of each terminal line. - */ - void writeSelectionToStream(TerminalCharacterDecoder* decoder , bool - preserveLineBreaks = true); + /** + * Copies the selected characters, set using @see setSelBeginXY and @see setSelExtentXY + * into a stream. + * + * @param decoder A decoder which converts terminal characters into text. + * PlainTextDecoder is the most commonly used decoder which converts characters + * into plain text with no formatting. + * @param preserveLineBreaks Specifies whether new line characters should + * be inserted into the returned text at the end of each terminal line. + */ + void writeSelectionToStream(TerminalCharacterDecoder* decoder , bool + preserveLineBreaks = true) const; - /** TODO Document me */ + /** + * Checks if the text between from and to is inside the current + * selection. If this is the case, the selection is cleared. The + * from and to are coordinates in the current viewable window. + * The loc(x,y) macro can be used to generate these values from a + * column,line pair. + * + * @param from The start of the area to check. + * @param to The end of the area to check + */ void checkSelection(int from, int to); - /** - * Sets or clears an attribute of the current line. - * - * @param property The attribute to set or clear - * Possible properties are: - * LINE_WRAPPED: Specifies that the line is wrapped. - * LINE_DOUBLEWIDTH: Specifies that the characters in the current line should be double the normal width. - * LINE_DOUBLEHEIGHT:Specifies that the characters in the current line should be double the normal height. + /** + * Sets or clears an attribute of the current line. + * + * @param property The attribute to set or clear + * Possible properties are: + * LINE_WRAPPED: Specifies that the line is wrapped. + * LINE_DOUBLEWIDTH: Specifies that the characters in the current line + * should be double the normal width. + * LINE_DOUBLEHEIGHT:Specifies that the characters in the current line + * should be double the normal height. * Double-height lines are formed of two lines containing the same characters, - * with both having the LINE_DOUBLEHEIGHT attribute. This allows other parts of the - * code to work on the assumption that all lines are the same height. - * - * @param enable true to apply the attribute to the current line or false to remove it - */ - void setLineProperty(LineProperty property , bool enable); + * with both having the LINE_DOUBLEHEIGHT attribute. + * This allows other parts of the code to work on the + * assumption that all lines are the same height. + * + * @param enable true to apply the attribute to the current line or false to remove it + */ + void setLineProperty(LineProperty property , bool enable); - - /** + /** * Returns the number of lines that the image has been scrolled up or down by, * since the last call to resetScrolledLines(). * * a positive return value indicates that the image has been scrolled up, - * a negative return value indicates that the image has been scrolled down. + * a negative return value indicates that the image has been scrolled down. */ int scrolledLines() const; /** * Returns the region of the image which was last scrolled. * - * This is the area of the image from the top margin to the + * This is the area of the image from the top margin to the * bottom margin when the last scroll occurred. */ QRect lastScrolledRegion() const; - /** + /** * Resets the count of the number of lines that the image has been scrolled up or down by, * see scrolledLines() */ @@ -523,7 +544,7 @@ public: * * If the history is not unlimited then it will drop * the oldest lines of output if new lines are added when - * it is full. + * it is full. */ int droppedLines() const; @@ -533,29 +554,34 @@ public: */ void resetDroppedLines(); - /** - * Fills the buffer @p dest with @p count instances of the default (ie. blank) - * Character style. - */ - static void fillWithDefaultChar(Character* dest, int count); + /** + * Fills the buffer @p dest with @p count instances of the default (ie. blank) + * Character style. + */ + static void fillWithDefaultChar(Character* dest, int count); -private: +private: + Screen(const Screen &) = delete; + Screen &operator=(const Screen &) = delete; - //copies a line of text from the screen or history into a stream using a - //specified character decoder - //line - the line number to copy, from 0 (the earliest line in the history) up to - // hist->getLines() + lines - 1 - //start - the first column on the line to copy - //count - the number of characters on the line to copy - //decoder - a decoder which coverts terminal characters (an Character array) into text + //copies a line of text from the screen or history into a stream using a + //specified character decoder. Returns the number of lines actually copied, + //which may be less than 'count' if (start+count) is more than the number of characters on + //the line + // + //line - the line number to copy, from 0 (the earliest line in the history) up to + // history->getLines() + lines - 1 + //start - the first column on the line to copy + //count - the number of characters on the line to copy + //decoder - a decoder which converts terminal characters (an Character array) into text //appendNewLine - if true a new line character (\n) is appended to the end of the line - void copyLineToStream(int line, - int start, - int count, + int copyLineToStream(int line, + int start, + int count, TerminalCharacterDecoder* decoder, bool appendNewLine, - bool preserveLineBreaks); - + bool preserveLineBreaks) const; + //fills a section of the screen image with the character 'c' //the parameters are specified as offsets from the start of the screen image. //the loc(x,y) macro can be used to generate these values from a column,line pair. @@ -564,26 +590,32 @@ private: //move screen image between 'sourceBegin' and 'sourceEnd' to 'dest'. //the parameters are specified as offsets from the start of the screen image. //the loc(x,y) macro can be used to generate these values from a column,line pair. + // + //NOTE: moveImage() can only move whole lines void moveImage(int dest, int sourceBegin, int sourceEnd); - + // scroll up 'i' lines in current region, clearing the bottom 'i' lines void scrollUp(int from, int i); + // scroll down 'i' lines in current region, clearing the top 'i' lines void scrollDown(int from, int i); void addHistLine(); void initTabStops(); - void effectiveRendition(); + void updateEffectiveRendition(); void reverseRendition(Character& p) const; bool isSelectionValid() const; - - // copies 'count' lines from the screen buffer into 'dest', - // starting from 'startLine', where 0 is the first line in the screen buffer - void copyFromScreen(Character* dest, int startLine, int count) const; - // copies 'count' lines from the history buffer into 'dest', - // starting from 'startLine', where 0 is the first line in the history - void copyFromHistory(Character* dest, int startLine, int count) const; + // copies text from 'startIndex' to 'endIndex' to a stream + // startIndex and endIndex are positions generated using the loc(x,y) macro + void writeToStream(TerminalCharacterDecoder* decoder, int startIndex, + int endIndex, bool preserveLineBreaks = true) const; + // copies 'count' lines from the screen buffer into 'dest', + // starting from 'startLine', where 0 is the first line in the screen buffer + void copyFromScreen(Character* dest, int startLine, int count) const; + // copies 'count' lines from the history buffer into 'dest', + // starting from 'startLine', where 0 is the first line in the history + void copyFromHistory(Character* dest, int startLine, int count) const; // screen image ---------------- @@ -598,61 +630,62 @@ private: int _droppedLines; - QVarLengthArray lineProperties; - + QVarLengthArray lineProperties; + // history buffer --------------- - HistoryScroll *hist; - + HistoryScroll* history; + // cursor location int cuX; int cuY; // cursor color and rendition info - CharacterColor cu_fg; // foreground - CharacterColor cu_bg; // background - quint8 cu_re; // rendition + CharacterColor currentForeground; + CharacterColor currentBackground; + quint8 currentRendition; // margins ---------------- - int tmargin; // top margin - int bmargin; // bottom margin + int _topMargin; + int _bottomMargin; // states ---------------- - ScreenParm currParm; + bool currentModes[MODES_SCREEN]; + bool savedModes[MODES_SCREEN]; // ---------------------------- - bool* tabstops; + QBitArray tabStops; // selection ------------------- - int sel_begin; // The first location selected. - int sel_TL; // TopLeft Location. - int sel_BR; // Bottom Right Location. - bool sel_busy; // Busy making a selection. - bool columnmode; // Column selection mode + int selBegin; // The first location selected. + int selTopLeft; // TopLeft Location. + int selBottomRight; // Bottom Right Location. + bool blockSelectionMode; // Column selection mode // effective colors and rendition ------------ - CharacterColor ef_fg; // These are derived from - CharacterColor ef_bg; // the cu_* variables above - quint8 ef_re; // to speed up operation + CharacterColor effectiveForeground; // These are derived from + CharacterColor effectiveBackground; // the cu_* variables above + quint8 effectiveRendition; // to speed up operation - // - // save cursor, rendition & states ------------ - // + class SavedState + { + public: + SavedState() + : cursorColumn(0),cursorLine(0),rendition(0) {} - // cursor location - int sa_cuX; - int sa_cuY; + int cursorColumn; + int cursorLine; + quint8 rendition; + CharacterColor foreground; + CharacterColor background; + }; + SavedState savedState; - // rendition info - quint8 sa_cu_re; - CharacterColor sa_cu_fg; - CharacterColor sa_cu_bg; - // last position where we added a character int lastPos; - // modes - ScreenParm saveParm; + // used in REP (repeating char) + unsigned short lastDrawnChar; static Character defaultChar; }; diff --git a/qtermwidget/src/ScreenWindow.cpp b/qtermwidget/lib/ScreenWindow.cpp similarity index 60% rename from qtermwidget/src/ScreenWindow.cpp rename to qtermwidget/lib/ScreenWindow.cpp index 2eb1e84..a6ce7c2 100644 --- a/qtermwidget/src/ScreenWindow.cpp +++ b/qtermwidget/lib/ScreenWindow.cpp @@ -1,8 +1,6 @@ /* Copyright (C) 2007 by Robert Knight - Rewritten for QT4 by e_k , Copyright (C)2008 - This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or @@ -23,20 +21,20 @@ #include "ScreenWindow.h" // Qt -#include +#include // Konsole #include "Screen.h" - using namespace Konsole; ScreenWindow::ScreenWindow(QObject* parent) : QObject(parent) - , _windowBuffer(0) - , _windowBufferSize(0) - , _bufferNeedsUpdate(true) - , _windowLines(1) + , _screen(nullptr) + , _windowBuffer(nullptr) + , _windowBufferSize(0) + , _bufferNeedsUpdate(true) + , _windowLines(1) , _currentLine(0) , _trackOutput(true) , _scrollCount(0) @@ -44,7 +42,7 @@ ScreenWindow::ScreenWindow(QObject* parent) } ScreenWindow::~ScreenWindow() { - delete[] _windowBuffer; + delete[] _windowBuffer; } void ScreenWindow::setScreen(Screen* screen) { @@ -60,43 +58,43 @@ Screen* ScreenWindow::screen() const 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; - } + // reallocate internal buffer if the window size has changed + int size = windowLines() * windowColumns(); + if (_windowBuffer == nullptr || _windowBufferSize != size) + { + delete[] _windowBuffer; + _windowBufferSize = size; + _windowBuffer = new Character[size]; + _bufferNeedsUpdate = true; + } - if (!_bufferNeedsUpdate) - return _windowBuffer; - - _screen->getImage(_windowBuffer,size, - currentLine(),endWindowLine()); + if (!_bufferNeedsUpdate) + return _windowBuffer; - // 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(); + _screen->getImage(_windowBuffer,size, + currentLine(),endWindowLine()); - _bufferNeedsUpdate = false; - return _windowBuffer; + // 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 screenEndLine = _screen->getHistLines() + _screen->getLines() - 1; + int windowEndLine = currentLine() + windowLines() - 1; - int unusedLines = windowEndLine - screenEndLine; - int charsToFill = unusedLines * windowColumns(); + int unusedLines = windowEndLine - screenEndLine; + int charsToFill = unusedLines * windowColumns(); - Screen::fillWithDefaultChar(_windowBuffer + _windowBufferSize - charsToFill,charsToFill); + Screen::fillWithDefaultChar(_windowBuffer + _windowBufferSize - charsToFill,charsToFill); } -// return the index of the line at the end of this window, or if this window +// return the index of the line at the end of this window, or if this window // goes beyond the end of the screen, the index of the line at the end // of the screen. // @@ -105,17 +103,17 @@ void ScreenWindow::fillUnusedArea() // int ScreenWindow::endWindowLine() const { - return qMin(currentLine() + windowLines() - 1, - lineCount() - 1); + return qMin(currentLine() + windowLines() - 1, + lineCount() - 1); } QVector ScreenWindow::getLineProperties() { QVector result = _screen->getLineProperties(currentLine(),endWindowLine()); - - if (result.count() != windowLines()) - result.resize(windowLines()); - return result; + if (result.count() != windowLines()) + result.resize(windowLines()); + + return result; } QString ScreenWindow::selectedText( bool preserveLineBreaks ) const @@ -136,8 +134,8 @@ void ScreenWindow::getSelectionEnd( int& column , int& line ) void ScreenWindow::setSelectionStart( int column , int line , bool columnMode ) { _screen->setSelectionStart( column , qMin(line + currentLine(),endWindowLine()) , columnMode); - - _bufferNeedsUpdate = true; + + _bufferNeedsUpdate = true; emit selectionChanged(); } @@ -145,7 +143,7 @@ void ScreenWindow::setSelectionEnd( int column , int line ) { _screen->setSelectionEnd( column , qMin(line + currentLine(),endWindowLine()) ); - _bufferNeedsUpdate = true; + _bufferNeedsUpdate = true; emit selectionChanged(); } @@ -163,12 +161,12 @@ void ScreenWindow::clearSelection() void ScreenWindow::setWindowLines(int lines) { - Q_ASSERT(lines > 0); - _windowLines = lines; + Q_ASSERT(lines > 0); + _windowLines = lines; } int ScreenWindow::windowLines() const { - return _windowLines; + return _windowLines; } int ScreenWindow::windowColumns() const @@ -189,11 +187,11 @@ int ScreenWindow::columnCount() const QPoint ScreenWindow::cursorPosition() const { QPoint position; - + position.setX( _screen->getCursorX() ); position.setY( _screen->getCursorY() ); - return position; + return position; } int ScreenWindow::currentLine() const @@ -209,7 +207,7 @@ void ScreenWindow::scrollBy( RelativeScrollMode mode , int amount ) } else if ( mode == ScrollPages ) { - scrollTo( currentLine() + amount * ( windowLines() / 2 ) ); + scrollTo( currentLine() + amount * ( windowLines() / 2 ) ); } } @@ -220,8 +218,8 @@ bool ScreenWindow::atEndOfOutput() const void ScreenWindow::scrollTo( int line ) { - int maxCurrentLineNumber = lineCount() - windowLines(); - line = qBound(0,line,maxCurrentLineNumber); + int maxCurrentLineNumber = lineCount() - windowLines(); + line = qBound(0,line,maxCurrentLineNumber); const int delta = line - _currentLine; _currentLine = line; @@ -250,19 +248,19 @@ int ScreenWindow::scrollCount() const return _scrollCount; } -void ScreenWindow::resetScrollCount() +void ScreenWindow::resetScrollCount() { _scrollCount = 0; } QRect ScreenWindow::scrollRegion() const { - bool equalToScreenSize = windowLines() == _screen->getLines(); + bool equalToScreenSize = windowLines() == _screen->getLines(); - if ( atEndOfOutput() && equalToScreenSize ) - return _screen->lastScrolledRegion(); - else - return QRect(0,0,windowColumns(),windowLines()); + if ( atEndOfOutput() && equalToScreenSize ) + return _screen->lastScrolledRegion(); + else + return {0,0,windowColumns(),windowLines()}; } void ScreenWindow::notifyOutputChanged() @@ -270,18 +268,18 @@ void ScreenWindow::notifyOutputChanged() // move window to the bottom of the screen and update scroll count // if this window is currently tracking the bottom of the screen if ( _trackOutput ) - { + { _scrollCount -= _screen->scrolledLines(); _currentLine = qMax(0,_screen->getHistLines() - (windowLines()-_screen->getLines())); } else { - // if the history is not unlimited then it may + // if the history is not unlimited then it may // have run out of space and dropped the oldest // lines of output - in this case the screen - // window's current line number will need to + // window's current line number will need to // be adjusted - otherwise the output will scroll - _currentLine = qMax(0,_currentLine - + _currentLine = qMax(0,_currentLine - _screen->droppedLines()); // ensure that the screen window's current position does @@ -289,9 +287,56 @@ void ScreenWindow::notifyOutputChanged() _currentLine = qMin( _currentLine , _screen->getHistLines() ); } - _bufferNeedsUpdate = true; + _bufferNeedsUpdate = true; - emit outputChanged(); + emit outputChanged(); } -//#include "moc_ScreenWindow.cpp" +void ScreenWindow::handleCommandFromKeyboard(KeyboardTranslator::Command command) +{ + // Keyboard-based navigation + bool update = false; + + // EraseCommand is handled in Vt102Emulation + if ( command & KeyboardTranslator::ScrollPageUpCommand ) + { + scrollBy( ScreenWindow::ScrollPages , -1 ); + update = true; + } + if ( command & KeyboardTranslator::ScrollPageDownCommand ) + { + scrollBy( ScreenWindow::ScrollPages , 1 ); + update = true; + } + if ( command & KeyboardTranslator::ScrollLineUpCommand ) + { + scrollBy( ScreenWindow::ScrollLines , -1 ); + update = true; + } + if ( command & KeyboardTranslator::ScrollLineDownCommand ) + { + scrollBy( ScreenWindow::ScrollLines , 1 ); + update = true; + } + if ( command & KeyboardTranslator::ScrollDownToBottomCommand ) + { + Q_EMIT scrollToEnd(); + update = true; + } + if ( command & KeyboardTranslator::ScrollUpToTopCommand) + { + scrollTo(0); + update = true; + } + // TODO: KeyboardTranslator::ScrollLockCommand + // TODO: KeyboardTranslator::SendCommand + + if ( update ) + { + setTrackOutput( atEndOfOutput() ); + + Q_EMIT outputChanged(); + } +} + +//#include "ScreenWindow.moc" diff --git a/qtermwidget/src/ScreenWindow.h b/qtermwidget/lib/ScreenWindow.h similarity index 78% rename from qtermwidget/src/ScreenWindow.h rename to qtermwidget/lib/ScreenWindow.h index d2955ab..3a75c08 100644 --- a/qtermwidget/src/ScreenWindow.h +++ b/qtermwidget/lib/ScreenWindow.h @@ -1,7 +1,5 @@ /* - Copyright (C) 2007 by Robert Knight - - Rewritten for QT4 by e_k , Copyright (C)2008 + Copyright 2007-2008 by Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -23,12 +21,13 @@ #define SCREENWINDOW_H // Qt -#include -#include -#include +#include +#include +#include // Konsole #include "Character.h" +#include "KeyboardTranslator.h" namespace Konsole { @@ -36,13 +35,14 @@ namespace Konsole class Screen; /** - * Provides a window onto a section of a terminal screen. - * This window can then be rendered by a terminal display widget ( TerminalDisplay ). + * Provides a window onto a section of a terminal screen. A terminal widget can then render + * the contents of the window and use the window to change the terminal screen's selection + * in response to mouse or keyboard input. + * + * A new ScreenWindow for a terminal session can be created by calling Emulation::createWindow() * - * To use the screen window, create a new ScreenWindow() instance and associated it with - * a terminal screen using setScreen(). * Use the scrollTo() method to scroll the window up and down on the screen. - * Call the getImage() method to retrieve the character image which is currently visible in the window. + * Use the getImage() method to retrieve the character image which is currently visible in the window. * * setTrackOutput() controls whether the window moves to the bottom of the associated screen when new * lines are added to it. @@ -56,7 +56,7 @@ class ScreenWindow : public QObject Q_OBJECT public: - /** + /** * Constructs a new screen window with the given parent. * A screen must be specified by calling setScreen() before calling getImage() or getLineProperties(). * @@ -65,19 +65,19 @@ public: * to notify the window when the associated screen has changed and synchronize selection updates * between all views on a session. */ - ScreenWindow(QObject* parent = 0); - virtual ~ScreenWindow(); + ScreenWindow(QObject* parent = nullptr); + ~ScreenWindow() override; /** Sets the screen which this window looks onto */ void setScreen(Screen* screen); /** Returns the screen which this window looks onto */ Screen* screen() const; - /** + /** * Returns the image of characters which are currently visible through this window * onto the screen. * - * The buffer is managed by the ScreenWindow instance and does not need to be + * The returned buffer is managed by the ScreenWindow instance and does not need to be * deleted by the caller. */ Character* getImage(); @@ -90,14 +90,14 @@ public: /** * Returns the number of lines which the region of the window - * specified by scrollRegion() has been scrolled by since the last call - * to resetScrollCount(). scrollRegion() is in most cases the + * specified by scrollRegion() has been scrolled by since the last call + * to resetScrollCount(). scrollRegion() is in most cases the * whole window, but will be a smaller area in, for example, applications * which provide split-screen facilities. * - * This is not guaranteed to be accurate, but allows views to optimise + * This is not guaranteed to be accurate, but allows views to optimize * rendering by reducing the amount of costly text rendering that - * needs to be done when the output is scrolled. + * needs to be done when the output is scrolled. */ int scrollCount() const; @@ -107,16 +107,16 @@ public: void resetScrollCount(); /** - * Returns the area of the window which was last scrolled, this is + * Returns the area of the window which was last scrolled, this is * usually the whole window area. * * Like scrollCount(), this is not guaranteed to be accurate, - * but allows views to optimise rendering. + * but allows views to optimize rendering. */ QRect scrollRegion() const; - /** - * Sets the start of the selection to the given @p line and @p column within + /** + * Sets the start of the selection to the given @p line and @p column within * the window. */ void setSelectionStart( int column , int line , bool columnMode ); @@ -124,7 +124,7 @@ public: * Sets the end of the selection to the given @p line and @p column within * the window. */ - void setSelectionEnd( int column , int line ); + void setSelectionEnd( int column , int line ); /** * Retrieves the start of the selection within the window. */ @@ -137,18 +137,18 @@ public: * Returns true if the character at @p line , @p column is part of the selection. */ bool isSelected( int column , int line ); - /** + /** * Clears the current selection */ void clearSelection(); - /** Sets the number of lines in the window */ - void setWindowLines(int lines); + /** Sets the number of lines in the window */ + void setWindowLines(int lines); /** Returns the number of lines in the window */ int windowLines() const; /** Returns the number of columns in the window */ int windowColumns() const; - + /** Returns the total number of lines in the screen */ int lineCount() const; /** Returns the total number of columns in the screen */ @@ -157,13 +157,13 @@ public: /** Returns the index of the line which is currently at the top of this window */ int currentLine() const; - /** - * Returns the position of the cursor + /** + * Returns the position of the cursor * within the window. */ QPoint cursorPosition() const; - /** + /** * Convenience method. Returns true if the window is currently at the bottom * of the screen. */ @@ -172,32 +172,38 @@ public: /** Scrolls the window so that @p line is at the top of the window */ void scrollTo( int line ); + /** Describes the units which scrollBy() moves the window by. */ enum RelativeScrollMode { + /** Scroll the window down by a given number of lines. */ ScrollLines, + /** + * Scroll the window down by a given number of pages, where + * one page is windowLines() lines + */ ScrollPages }; - /** + /** * Scrolls the window relative to its current position on the screen. * * @param mode Specifies whether @p amount refers to the number of lines or the number - * of pages to scroll. + * of pages to scroll. * @param amount The number of lines or pages ( depending on @p mode ) to scroll by. If * this number is positive, the view is scrolled down. If this number is negative, the view * is scrolled up. */ void scrollBy( RelativeScrollMode mode , int amount ); - /** + /** * Specifies whether the window should automatically move to the bottom * of the screen when new output is added. * - * If this is set to true, the window will be moved to the bottom of the associated screen ( see + * If this is set to true, the window will be moved to the bottom of the associated screen ( see * screen() ) when the notifyOutputChanged() method is called. */ void setTrackOutput(bool trackOutput); - /** + /** * Returns whether the window automatically moves to the bottom of the screen as * new output is added. See setTrackOutput() */ @@ -211,43 +217,45 @@ public: QString selectedText( bool preserveLineBreaks ) const; public slots: - /** + /** * Notifies the window that the contents of the associated terminal screen have changed. * This moves the window to the bottom of the screen if trackOutput() is true and causes * the outputChanged() signal to be emitted. */ void notifyOutputChanged(); + void handleCommandFromKeyboard(KeyboardTranslator::Command command); + signals: /** - * Emitted when the contents of the associated terminal screen ( see screen() ) changes. + * Emitted when the contents of the associated terminal screen (see screen()) changes. */ void outputChanged(); /** * Emitted when the screen window is scrolled to a different position. - * + * * @param line The line which is now at the top of the window. */ void scrolled(int line); - /** - * Emitted when the selection is changed. - */ + /** Emitted when the selection is changed. */ void selectionChanged(); + void scrollToEnd(); + private: - int endWindowLine() const; - void fillUnusedArea(); + int endWindowLine() const; + void fillUnusedArea(); Screen* _screen; // see setScreen() , screen() - Character* _windowBuffer; - int _windowBufferSize; - bool _bufferNeedsUpdate; + Character* _windowBuffer; + int _windowBufferSize; + bool _bufferNeedsUpdate; - int _windowLines; + int _windowLines; int _currentLine; // see scrollTo() , currentLine() - bool _trackOutput; // see setTrackOutput() , trackOutput() + bool _trackOutput; // see setTrackOutput() , trackOutput() int _scrollCount; // count of lines which the window has been scrolled by since // the last call to resetScrollCount() }; diff --git a/qtermwidget/lib/SearchBar.cpp b/qtermwidget/lib/SearchBar.cpp new file mode 100644 index 0000000..958ea64 --- /dev/null +++ b/qtermwidget/lib/SearchBar.cpp @@ -0,0 +1,131 @@ +/* + Copyright 2013 Christian Surlykke + + 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. +*/ +#include +#include +#if QT_VERSION > 0x060000 +#include +#else +#include +#endif +#include + +#include "SearchBar.h" + +SearchBar::SearchBar(QWidget *parent) : QWidget(parent) +{ + widget.setupUi(this); + setAutoFillBackground(true); // make it always opaque, especially inside translucent windows + connect(widget.closeButton, &QAbstractButton::clicked, this, &SearchBar::hide); + connect(widget.searchTextEdit, SIGNAL(textChanged(QString)), this, SIGNAL(searchCriteriaChanged())); + connect(widget.findPreviousButton, SIGNAL(clicked()), this, SIGNAL(findPrevious())); + connect(widget.findNextButton, SIGNAL(clicked()), this, SIGNAL(findNext())); + + connect(this, SIGNAL(searchCriteriaChanged()), this, SLOT(clearBackgroundColor())); + + QMenu *optionsMenu = new QMenu(widget.optionsButton); + widget.optionsButton->setMenu(optionsMenu); + + m_matchCaseMenuEntry = optionsMenu->addAction(tr("Match case")); + m_matchCaseMenuEntry->setCheckable(true); + m_matchCaseMenuEntry->setChecked(true); + connect(m_matchCaseMenuEntry, SIGNAL(toggled(bool)), this, SIGNAL(searchCriteriaChanged())); + + + m_useRegularExpressionMenuEntry = optionsMenu->addAction(tr("Regular expression")); + m_useRegularExpressionMenuEntry->setCheckable(true); + connect(m_useRegularExpressionMenuEntry, SIGNAL(toggled(bool)), this, SIGNAL(searchCriteriaChanged())); + + m_highlightMatchesMenuEntry = optionsMenu->addAction(tr("Highlight all matches")); + m_highlightMatchesMenuEntry->setCheckable(true); + m_highlightMatchesMenuEntry->setChecked(true); + connect(m_highlightMatchesMenuEntry, SIGNAL(toggled(bool)), this, SIGNAL(highlightMatchesChanged(bool))); +} + +SearchBar::~SearchBar() { +} + +QString SearchBar::searchText() +{ + return widget.searchTextEdit->text(); +} + + +bool SearchBar::useRegularExpression() +{ + return m_useRegularExpressionMenuEntry->isChecked(); +} + +bool SearchBar::matchCase() +{ + return m_matchCaseMenuEntry->isChecked(); +} + +bool SearchBar::highlightAllMatches() +{ + return m_highlightMatchesMenuEntry->isChecked(); +} + +void SearchBar::show() +{ + QWidget::show(); + widget.searchTextEdit->setFocus(); + widget.searchTextEdit->selectAll(); +} + +void SearchBar::hide() +{ + QWidget::hide(); + if (QWidget *p = parentWidget()) + { + p->setFocus(Qt::OtherFocusReason); // give the focus to the parent widget on hiding + } +} + +void SearchBar::noMatchFound() +{ + QPalette palette; + palette.setColor(widget.searchTextEdit->backgroundRole(), QColor(255, 128, 128)); + widget.searchTextEdit->setPalette(palette); +} + + +void SearchBar::keyReleaseEvent(QKeyEvent* keyEvent) +{ + if (keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Enter) + { + if (keyEvent->modifiers() == Qt::ShiftModifier) + { + Q_EMIT findPrevious(); + } + else + { + Q_EMIT findNext(); + } + } + else if (keyEvent->key() == Qt::Key_Escape) + { + hide(); + } +} + +void SearchBar::clearBackgroundColor() +{ + widget.searchTextEdit->setPalette(QWidget::window()->palette()); + +} diff --git a/qtermwidget/lib/SearchBar.h b/qtermwidget/lib/SearchBar.h new file mode 100644 index 0000000..e6619b9 --- /dev/null +++ b/qtermwidget/lib/SearchBar.h @@ -0,0 +1,65 @@ +/* + Copyright 2013 Christian Surlykke + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. +*/ +#ifndef _SEARCHBAR_H +#define _SEARCHBAR_H + +#include "ui_SearchBar.h" +#include "HistorySearch.h" + +#if QT_VERSION < 0x060000 +#include +#else +#include +#endif + +class SearchBar : public QWidget { + Q_OBJECT +public: + SearchBar(QWidget* parent = nullptr); + ~SearchBar() override; + virtual void show(); + QString searchText(); + bool useRegularExpression(); + bool matchCase(); + bool highlightAllMatches(); + +public slots: + void noMatchFound(); + void hide(); + +signals: + void searchCriteriaChanged(); + void highlightMatchesChanged(bool highlightMatches); + void findNext(); + void findPrevious(); + +protected: + void keyReleaseEvent(QKeyEvent* keyEvent) override; + +private slots: + void clearBackgroundColor(); + +private: + Ui::SearchBar widget; + QAction *m_matchCaseMenuEntry; + QAction *m_useRegularExpressionMenuEntry; + QAction *m_highlightMatchesMenuEntry; +}; + +#endif /* _SEARCHBAR_H */ diff --git a/qtermwidget/lib/SearchBar.ui b/qtermwidget/lib/SearchBar.ui new file mode 100644 index 0000000..91947d9 --- /dev/null +++ b/qtermwidget/lib/SearchBar.ui @@ -0,0 +1,80 @@ + + + SearchBar + + + + 0 + 0 + 399 + 40 + + + + SearchBar + + + + + + X + + + + + + + + + + + + Find: + + + + + + + + + + < + + + + + + + + + + + + > + + + + + + + + + + + + ... + + + + + + QToolButton::InstantPopup + + + + + + + + diff --git a/qtermwidget/lib/Session.cpp b/qtermwidget/lib/Session.cpp new file mode 100644 index 0000000..933e8b5 --- /dev/null +++ b/qtermwidget/lib/Session.cpp @@ -0,0 +1,1068 @@ +/* + This file is part of Konsole + + Copyright (C) 2006-2007 by Robert Knight + Copyright (C) 1997,1998 by Lars Doelle + + Rewritten for QT4 by e_k , Copyright (C)2008 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (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" + +// Standard +#include + +// Qt +#include +#if QT_VERSION < 0x060000 +#include +#include +#else +#include +#endif +#include +#include +#include +#include +#include + +#include "Pty.h" +//#include "kptyprocess.h" +#include "TerminalDisplay.h" +#include "ShellCommand.h" +#include "Vt102Emulation.h" + +using namespace Konsole; + +int Session::lastSessionId = 0; + +Session::Session(QObject* parent) : + QObject(parent), + _shellProcess(nullptr) + , _emulation(nullptr) + , _monitorActivity(false) + , _monitorSilence(false) + , _notifiedActivity(false) + , _autoClose(true) + , _wantedClose(false) + , _silenceSeconds(10) + , _isTitleChanged(false) + , _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(); + ptySlaveFd = _shellProcess->pty()->slaveFd(); + + //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 &)) ); + + connect(_emulation, SIGNAL(imageResizeRequest(QSize)), + this, SLOT(onEmulationSizeChange(QSize))); + connect(_emulation, SIGNAL(imageSizeChanged(int, int)), + this, SLOT(onViewSizeChange(int, int))); + connect(_emulation, &Vt102Emulation::cursorChanged, + this, &Session::cursorChanged); + + //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(finished(int,QProcess::ExitStatus)), this, SLOT(done(int)) ); + // not in kprocess anymore connect( _shellProcess,SIGNAL(done(int)), this, SLOT(done(int)) ); + + //setup timer for monitoring session activity + _monitorTimer = new QTimer(this); + _monitorTimer->setSingleShot(true); + connect(_monitorTimer, SIGNAL(timeout()), this, SLOT(monitorTimerDone())); +} + +WId Session::windowId() const +{ + // On Qt5, requesting window IDs breaks QQuickWidget and the likes, + // for example, see the following bug reports: + // https://bugreports.qt.io/browse/QTBUG-40765 + // https://codereview.qt-project.org/#/c/94880/ + return 0; +} + +void Session::setDarkBackground(bool darkBackground) +{ + _hasDarkBackground = darkBackground; +} +bool Session::hasDarkBackground() const +{ + return _hasDarkBackground; +} +bool Session::isRunning() const +{ + return _shellProcess->state() == QProcess::Running; +} + +void Session::setCodec(QTextCodec * codec) const +{ + 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 Session::views() const +{ + return _views; +} + +void Session::addView(TerminalDisplay * widget) +{ + Q_ASSERT( !_views.contains(widget) ); + + _views.append(widget); + + if ( _emulation != nullptr ) { + // connect emulation - view signals and slots + connect( widget , &TerminalDisplay::keyPressedSignal, _emulation , + &Emulation::sendKeyEvent); + 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() ); + + connect( _emulation , SIGNAL(programBracketedPasteModeChanged(bool)) , + widget , SLOT(setBracketedPasteMode(bool)) ); + + widget->setBracketedPasteMode(_emulation->programBracketedPasteMode()); + + 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,nullptr,this,nullptr); + + if ( _emulation != nullptr ) { + // 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, nullptr, _emulation, nullptr); + + // disconnect state change signals emitted by emulation + disconnect( _emulation , nullptr , widget , nullptr); + } + + // close the session automatically when the last view is removed + if ( _views.count() == 0 ) { + close(); + } +} + +void Session::run() +{ + // Upon a KPty error, there is no description on what that error was... + // Check to see if the given program is executable. + + /* ok I'm not exactly sure where _program comes from - however it was set to /bin/bash on my system + * That's bad for BSD as its /usr/local/bin/bash there - its also bad for arch as its /usr/bin/bash there too! + * So i added a check to see if /bin/bash exists - if no then we use $SHELL - if that does not exist either, we fall back to /bin/sh + * As far as i know /bin/sh exists on every unix system.. You could also just put some ifdef __FREEBSD__ here but i think these 2 filechecks are worth + * their computing time on any system - especially with the problem on arch linux being there too. + */ + QString exec = QString::fromLocal8Bit(QFile::encodeName(_program)); + // if 'exec' is not specified, fall back to default shell. if that + // is not set then fall back to /bin/sh + + // here we expect full path. If there is no fullpath let's expect it's + // a custom shell (eg. python, etc.) available in the PATH. + if (exec.startsWith(QLatin1Char('/')) || exec.isEmpty()) + { + const QString defaultShell{QLatin1String("/bin/sh")}; + + QFile excheck(exec); + if ( exec.isEmpty() || !excheck.exists() ) { + exec = QString::fromLocal8Bit(qgetenv("SHELL")); + } + excheck.setFileName(exec); + + if ( exec.isEmpty() || !excheck.exists() ) { + qWarning() << "Neither default shell nor $SHELL is set to a correct path. Fallback to" << defaultShell; + exec = defaultShell; + } + } + + // _arguments sometimes contain ("") so isEmpty() + // or count() does not work as expected... + QString argsTmp(_arguments.join(QLatin1Char(' ')).trimmed()); + QStringList arguments; + arguments << exec; + if (argsTmp.length()) + arguments << _arguments; + + QString cwd = QDir::currentPath(); + if (!_initialWorkingDir.isEmpty()) { + _shellProcess->setWorkingDirectory(_initialWorkingDir); + } else { + _shellProcess->setWorkingDirectory(cwd); + } + + _shellProcess->setFlowControlEnabled(_flowControl); + _shellProcess->setErase(_emulation->eraseChar()); + + // this is not strictly accurate use of the COLORFGBG variable. This does not + // tell the terminal exactly which colors are being used, but instead approximates + // the color scheme as "black on white" or "white on black" depending on whether + // the background color is deemed dark or not + QString backgroundColorHint = _hasDarkBackground ? QLatin1String("COLORFGBG=15;0") : QLatin1String("COLORFGBG=0;15"); + + /* if we do all the checking if this shell exists then we use it ;) + * Dont know about the arguments though.. maybe youll need some more checking im not sure + * However this works on Arch and FreeBSD now. + */ + int result = _shellProcess->start(exec, + arguments, + _environment << backgroundColorHint, + windowId(), + _addToUtmp); + + if (result < 0) { + qDebug() << "CRASHED! result: " << result; + return; + } + + _shellProcess->setWriteable(false); // We are reachable via kwrited. + emit started(); +} + +void Session::runEmptyPTY() +{ + _shellProcess->setFlowControlEnabled(_flowControl); + _shellProcess->setErase(_emulation->eraseChar()); + _shellProcess->setWriteable(false); + + // disconnect send data from emulator to internal terminal process + disconnect( _emulation,SIGNAL(sendData(const char *,int)), + _shellProcess, SLOT(sendData(const char *,int)) ); + + _shellProcess->setEmptyPTYProperties(); + 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)) { + _isTitleChanged = true; + if ( _userTitle != caption ) { + _userTitle = caption; + modified = true; + } + } + + if ((what == 0) || (what == 1)) { + _isTitleChanged = true; + if ( _iconText != caption ) { + _iconText = caption; + modified = true; + } + } + + if (what == 11) { + QString colorString = caption.section(QLatin1Char(';'),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) { + _isTitleChanged = true; + if ( _nameTitle != caption ) { + setTitle(Session::NameRole,caption); + return; + } + } + + if (what == 31) { + QString cwd=caption; +#if QT_VERSION >= 0x060000 + cwd=cwd.replace( QRegularExpression(QLatin1String("^~")), QDir::homePath() ); +#else + cwd=cwd.replace( QRegExp(QLatin1String("^~")), QDir::homePath() ); +#endif + emit openUrlRequest(cwd); + } + + // change icon via \033]32;Icon\007 + if (what == 32) { + _isTitleChanged = true; + 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) { + emit silence(); + emit stateChanged(NOTIFYSILENCE); + } else { + emit stateChanged(NOTIFYNORMAL); + } + + _notifiedActivity=false; +} + +void Session::activityStateSet(int state) +{ + if (state==NOTIFYBELL) { + emit bellRequest(tr("Bell in session '%1'").arg(_nameTitle)); + } else if (state==NOTIFYACTIVITY) { + if (_monitorSilence) { + _monitorTimer->start(_silenceSeconds*1000); + } + + if ( _monitorActivity ) { + //FIXME: See comments in Session::monitorTimerDone() + if (!_notifiedActivity) { + _notifiedActivity=true; + emit activity(); + } + } + } + + 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(QSize size) +{ + setSize(size); +} + +void Session::updateTerminalSize() +{ + QListIterator 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) +{ + int result = ::kill(static_cast(_shellProcess->processId()),signal); + + if ( result == 0 ) + { + _shellProcess->waitForFinished(); + return true; + } + else + return false; +} + +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); +} + +void Session::sendKeyEvent(QKeyEvent* e) const +{ + _emulation->sendKeyEvent(e, false); +} + +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 = QString::fromLatin1("This session is done. Finished"); + emit titleChanged(); + return; + } + + // message is not being used. But in the original kpty.cpp file + // (https://cgit.kde.org/kpty.git/) it's part of a notification. + // So, we make it translatable, hoping that in the future it will + // be used in some kind of notification. + QString message; + if (!_wantedClose || exitStatus != 0) { + + if (_shellProcess->exitStatus() == QProcess::NormalExit) { + message = tr("Session '%1' exited with status %2.").arg(_nameTitle).arg(exitStatus); + } else { + message = tr("Session '%1' crashed.").arg(_nameTitle); + } + } + + if ( !_wantedClose && _shellProcess->exitStatus() != QProcess::NormalExit ) + message = tr("Session '%1' exited unexpectedly.").arg(_nameTitle); + else + 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; +} + +bool Session::isTitleChanged() const +{ + return _isTitleChanged; +} + +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->setFlowControlEnabled(_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 static_cast(_shellProcess->processId()); +} +int Session::getPtySlaveFd() const +{ + return ptySlaveFd; +} + +SessionGroup::SessionGroup() + : _masterMode(0) +{ +} +SessionGroup::~SessionGroup() +{ + // disconnect all + connectAll(false); +} +int SessionGroup::masterMode() const +{ + return _masterMode; +} +QList 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 masterIter(masters()); + + while ( masterIter.hasNext() ) { + connectPair(masterIter.next(),session); + } +} +void SessionGroup::removeSession(Session * session) +{ + setMasterStatus(session,false); + + QListIterator masterIter(masters()); + + while ( masterIter.hasNext() ) { + disconnectPair(masterIter.next(),session); + } + + _sessions.remove(session); +} +void SessionGroup::setMasterMode(int mode) +{ + _masterMode = mode; + + connectAll(false); + connectAll(true); +} +QList SessionGroup::masters() const +{ + return _sessions.keys(true); +} +void SessionGroup::connectAll(bool connect) +{ + QListIterator masterIter(masters()); + + while ( masterIter.hasNext() ) { + Session * master = masterIter.next(); + + QListIterator 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) { + return; + } + + QListIterator 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) const +{ +// 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) const +{ +// 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/qtermwidget/lib/Session.h b/qtermwidget/lib/Session.h new file mode 100644 index 0000000..2da25c7 --- /dev/null +++ b/qtermwidget/lib/Session.h @@ -0,0 +1,649 @@ +/* + This file is part of Konsole, an X terminal. + + Copyright (C) 2007 by Robert Knight + Copyright (C) 1997,1998 by Lars Doelle + + Rewritten for QT4 by e_k , Copyright (C)2008 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. +*/ + +#ifndef SESSION_H +#define SESSION_H + +#include +#include + +#include "Emulation.h" +#include "History.h" + +class KProcess; + +namespace Konsole { + +class Emulation; +class Pty; +class TerminalDisplay; +//class ZModemDialog; + +/** + * Represents a terminal session consisting of a pseudo-teletype and a terminal emulation. + * The pseudo-teletype (or PTY) handles I/O between the terminal process and Konsole. + * The terminal emulation ( Emulation and subclasses ) processes the output stream from the + * PTY and produces a character image which is then shown on views connected to the session. + * + * Each Session can be connected to one or more views by using the addView() method. + * The attached views can then display output from the program running in the terminal + * or send input to the program in the terminal in the form of keypresses and mouse + * activity. + */ +class Session : public QObject { + Q_OBJECT + +public: + Q_PROPERTY(QString name READ nameTitle) + Q_PROPERTY(int processId READ processId) + Q_PROPERTY(QString keyBindings READ keyBindings WRITE setKeyBindings) + Q_PROPERTY(QSize size READ size WRITE setSize) + + /** + * Constructs a new session. + * + * To start the terminal process, call the run() method, + * after specifying the program and arguments + * using setProgram() and setArguments() + * + * If no program or arguments are specified explicitly, the Session + * falls back to using the program specified in the SHELL environment + * variable. + */ + Session(QObject* parent = nullptr); + ~Session() override; + + /** + * Returns true if the session is currently running. This will be true + * after run() has been called successfully. + */ + bool isRunning() const; + + /** + * Sets the profile associated with this session. + * + * @param profileKey A key which can be used to obtain the current + * profile settings from the SessionManager + */ + void setProfileKey(const QString & profileKey); + /** + * Returns the profile key associated with this session. + * This can be passed to the SessionManager to obtain the current + * profile settings. + */ + QString profileKey() const; + + /** + * Adds a new view for this session. + * + * The viewing widget will display the output from the terminal and + * input from the viewing widget (key presses, mouse activity etc.) + * will be sent to the terminal. + * + * Views can be removed using removeView(). The session is automatically + * closed when the last view is removed. + */ + void addView(TerminalDisplay * widget); + /** + * Removes a view from this session. When the last view is removed, + * the session will be closed automatically. + * + * @p widget will no longer display output from or send input + * to the terminal + */ + void removeView(TerminalDisplay * widget); + + /** + * Returns the views connected to this session + */ + QList views() const; + + /** + * Returns the terminal emulation instance being used to encode / decode + * characters to / from the process. + */ + Emulation * emulation() const; + + /** + * Returns the environment of this session as a list of strings like + * VARIABLE=VALUE + */ + QStringList environment() const; + /** + * Sets the environment for this session. + * @p environment should be a list of strings like + * VARIABLE=VALUE + */ + void setEnvironment(const QStringList & environment); + + /** Returns the unique ID for this session. */ + int sessionId() const; + + /** + * Return the session title set by the user (ie. the program running + * in the terminal), or an empty string if the user has not set a custom title + */ + QString userTitle() const; + + /** + * This enum describes the contexts for which separate + * tab title formats may be specified. + */ + enum TabTitleContext { + /** Default tab title format */ + LocalTabTitle, + /** + * Tab title format used session currently contains + * a connection to a remote computer (via SSH) + */ + RemoteTabTitle + }; + /** + * Sets the format used by this session for tab titles. + * + * @param context The context whose format should be set. + * @param format The tab title format. This may be a mixture + * of plain text and dynamic elements denoted by a '%' character + * followed by a letter. (eg. %d for directory). The dynamic + * elements available depend on the @p context + */ + void setTabTitleFormat(TabTitleContext context , const QString & format); + /** Returns the format used by this session for tab titles. */ + QString tabTitleFormat(TabTitleContext context) const; + + + /** Returns the arguments passed to the shell process when run() is called. */ + QStringList arguments() const; + /** Returns the program name of the shell process started when run() is called. */ + QString program() const; + + /** + * Sets the command line arguments which the session's program will be passed when + * run() is called. + */ + void setArguments(const QStringList & arguments); + /** Sets the program to be executed when run() is called. */ + void setProgram(const QString & program); + + /** Returns the session's current working directory. */ + QString initialWorkingDirectory() { + return _initialWorkingDir; + } + + /** + * Sets the initial working directory for the session when it is run + * This has no effect once the session has been started. + */ + void setInitialWorkingDirectory( const QString & dir ); + + /** + * Sets the type of history store used by this session. + * Lines of output produced by the terminal are added + * to the history store. The type of history store + * used affects the number of lines which can be + * remembered before they are lost and the storage + * (in memory, on-disk etc.) used. + */ + void setHistoryType(const HistoryType & type); + /** + * Returns the type of history store used by this session. + */ + const HistoryType & historyType() const; + /** + * Clears the history store used by this session. + */ + void clearHistory(); + + /** + * Enables monitoring for activity in the session. + * This will cause notifySessionState() to be emitted + * with the NOTIFYACTIVITY state flag when output is + * received from the terminal. + */ + void setMonitorActivity(bool); + /** Returns true if monitoring for activity is enabled. */ + bool isMonitorActivity() const; + + /** + * Enables monitoring for silence in the session. + * This will cause notifySessionState() to be emitted + * with the NOTIFYSILENCE state flag when output is not + * received from the terminal for a certain period of + * time, specified with setMonitorSilenceSeconds() + */ + void setMonitorSilence(bool); + /** + * Returns true if monitoring for inactivity (silence) + * in the session is enabled. + */ + bool isMonitorSilence() const; + /** See setMonitorSilence() */ + void setMonitorSilenceSeconds(int seconds); + + /** + * Sets the key bindings used by this session. The bindings + * specify how input key sequences are translated into + * the character stream which is sent to the terminal. + * + * @param id The name of the key bindings to use. The + * names of available key bindings can be determined using the + * KeyboardTranslatorManager class. + */ + void setKeyBindings(const QString & id); + /** Returns the name of the key bindings used by this session. */ + QString keyBindings() const; + + /** + * This enum describes the available title roles. + */ + enum TitleRole { + /** The name of the session. */ + NameRole, + /** The title of the session which is displayed in tabs etc. */ + DisplayedTitleRole + }; + + /** Sets the session's title for the specified @p role to @p title. */ + void setTitle(TitleRole role , const QString & title); + /** Returns the session's title for the specified @p role. */ + QString title(TitleRole role) const; + /** Convenience method used to read the name property. Returns title(Session::NameRole). */ + QString nameTitle() const { + return title(Session::NameRole); + } + + /** Sets the name of the icon associated with this session. */ + void setIconName(const QString & iconName); + /** Returns the name of the icon associated with this session. */ + QString iconName() const; + + /** Sets the text of the icon associated with this session. */ + void setIconText(const QString & iconText); + /** Returns the text of the icon associated with this session. */ + QString iconText() const; + + /** Flag if the title/icon was changed by user/shell. */ + bool isTitleChanged() const; + + /** Specifies whether a utmp entry should be created for the pty used by this session. */ + void setAddToUtmp(bool); + + /** Sends the specified @p signal to the terminal process. */ + bool sendSignal(int signal); + + /** + * Specifies whether to close the session automatically when the terminal + * process terminates. + */ + void setAutoClose(bool b) { + _autoClose = b; + } + + /** + * Sets whether flow control is enabled for this terminal + * session. + */ + void setFlowControlEnabled(bool enabled); + + /** Returns whether flow control is enabled for this terminal session. */ + bool flowControlEnabled() const; + + /** + * Sends @p text to the current foreground terminal program. + */ + void sendText(const QString & text) const; + + void sendKeyEvent(QKeyEvent* e) const; + + /** + * Returns the process id of the terminal process. + * This is the id used by the system API to refer to the process. + */ + int processId() const; + + /** + * Returns the process id of the terminal's foreground process. + * This is initially the same as processId() but can change + * as the user starts other programs inside the terminal. + */ + int foregroundProcessId() const; + + /** Returns the terminal session's window size in lines and columns. */ + QSize size(); + /** + * Emits a request to resize the session to accommodate + * the specified window size. + * + * @param size The size in lines and columns to request. + */ + void setSize(const QSize & size); + + /** Sets the text codec used by this session's terminal emulation. */ + void setCodec(QTextCodec * codec) const; + + /** + * Sets whether the session has a dark background or not. The session + * uses this information to set the COLORFGBG variable in the process's + * environment, which allows the programs running in the terminal to determine + * whether the background is light or dark and use appropriate colors by default. + * + * This has no effect once the session is running. + */ + void setDarkBackground(bool darkBackground); + /** + * Returns true if the session has a dark background. + * See setDarkBackground() + */ + bool hasDarkBackground() const; + + /** + * Attempts to get the shell program to redraw the current display area. + * This can be used after clearing the screen, for example, to get the + * shell to redraw the prompt line. + */ + void refresh(); + +// void startZModem(const QString &rz, const QString &dir, const QStringList &list); +// void cancelZModem(); +// bool isZModemBusy() { return _zmodemBusy; } + + /** + * Returns a pty slave file descriptor. + * This can be used for display and control + * a remote terminal. + */ + int getPtySlaveFd() const; + +public slots: + + /** + * Starts the terminal session. + * + * This creates the terminal process and connects the teletype to it. + */ + void run(); + + /** + * Starts the terminal session for "as is" PTY + * (without the direction a data to internal terminal process). + * It can be used for control or display a remote/external terminal. + */ + void runEmptyPTY(); + + /** + * Closes the terminal session. This sends a hangup signal + * (SIGHUP) to the terminal process and causes the done(Session*) + * signal to be emitted. + */ + void close(); + + /** + * Changes the session title or other customizable aspects of the terminal + * emulation display. For a list of what may be changed see the + * Emulation::titleChanged() signal. + */ + void setUserTitle( int, const QString & caption ); + +signals: + + /** Emitted when the terminal process starts. */ + void started(); + + /** + * Emitted when the terminal process exits. + */ + void finished(); + + /** + * Emitted when output is received from the terminal process. + */ + void receivedData( const QString & text ); + + /** Emitted when the session's title has changed. */ + void titleChanged(); + + /** Emitted when the session's profile has changed. */ + void profileChanged(const QString & profile); + + /** + * Emitted when the activity state of this session changes. + * + * @param state The new state of the session. This may be one + * of NOTIFYNORMAL, NOTIFYSILENCE or NOTIFYACTIVITY + */ + void stateChanged(int state); + + /** Emitted when a bell event occurs in the session. */ + void bellRequest( const QString & message ); + + /** + * Requests that the color the text for any tabs associated with + * this session should be changed; + * + * TODO: Document what the parameter does + */ + void changeTabTextColorRequest(int); + + /** + * Requests that the background color of views on this session + * should be changed. + */ + void changeBackgroundColorRequest(const QColor &); + + /** TODO: Document me. */ + void openUrlRequest(const QString & url); + + /** TODO: Document me. */ +// void zmodemDetected(); + + /** + * Emitted when the terminal process requests a change + * in the size of the terminal window. + * + * @param size The requested window size in terms of lines and columns. + */ + void resizeRequest(const QSize & size); + + /** + * Emitted when a profile change command is received from the terminal. + * + * @param text The text of the command. This is a string of the form + * "PropertyName=Value;PropertyName=Value ..." + */ + void profileChangeCommandReceived(const QString & text); + + /** + * Emitted when the flow control state changes. + * + * @param enabled True if flow control is enabled or false otherwise. + */ + void flowControlEnabledChanged(bool enabled); + + /** + * Broker for Emulation::cursorChanged() signal + */ + void cursorChanged(Emulation::KeyboardCursorShape cursorShape, bool blinkingCursorEnabled); + + void silence(); + void activity(); + +private slots: + void done(int); + +// void fireZModemDetected(); + + void onReceiveBlock( const char * buffer, int len ); + void monitorTimerDone(); + + void onViewSizeChange(int height, int width); + void onEmulationSizeChange(QSize); + + void activityStateSet(int); + + //automatically detach views from sessions when view is destroyed + void viewDestroyed(QObject * view); + +// void zmodemReadStatus(); +// void zmodemReadAndSendBlock(); +// void zmodemRcvBlock(const char *data, int len); +// void zmodemFinished(); + +private: + + void updateTerminalSize(); + WId windowId() const; + + int _uniqueIdentifier; + + Pty *_shellProcess; + Emulation * _emulation; + + QList _views; + + bool _monitorActivity; + bool _monitorSilence; + bool _notifiedActivity; + bool _masterMode; + bool _autoClose; + bool _wantedClose; + QTimer * _monitorTimer; + + int _silenceSeconds; + + QString _nameTitle; + QString _displayTitle; + QString _userTitle; + + QString _localTabTitleFormat; + QString _remoteTabTitleFormat; + + QString _iconName; + QString _iconText; // as set by: echo -en '\033]1;IconText\007 + bool _isTitleChanged; ///< flag if the title/icon was changed by user + bool _addToUtmp; + bool _flowControl; + bool _fullScripting; + + QString _program; + QStringList _arguments; + + QStringList _environment; + int _sessionId; + + QString _initialWorkingDir; + + // ZModem +// bool _zmodemBusy; +// KProcess* _zmodemProc; +// ZModemDialog* _zmodemProgress; + + // Color/Font Changes by ESC Sequences + + QColor _modifiedBackground; // as set by: echo -en '\033]11;Color\007 + + QString _profileKey; + + bool _hasDarkBackground; + + static int lastSessionId; + + int ptySlaveFd; + +}; + +/** + * Provides a group of sessions which is divided into master and slave sessions. + * Activity in master sessions can be propagated to all sessions within the group. + * The type of activity which is propagated and method of propagation is controlled + * by the masterMode() flags. + */ +class SessionGroup : public QObject { + Q_OBJECT + +public: + /** Constructs an empty session group. */ + SessionGroup(); + /** Destroys the session group and removes all connections between master and slave sessions. */ + ~SessionGroup() override; + + /** Adds a session to the group. */ + void addSession( Session * session ); + /** Removes a session from the group. */ + void removeSession( Session * session ); + + /** Returns the list of sessions currently in the group. */ + QList sessions() const; + + /** + * Sets whether a particular session is a master within the group. + * Changes or activity in the group's master sessions may be propagated + * to all the sessions in the group, depending on the current masterMode() + * + * @param session The session whose master status should be changed. + * @param master True to make this session a master or false otherwise + */ + void setMasterStatus( Session * session , bool master ); + /** Returns the master status of a session. See setMasterStatus() */ + bool masterStatus( Session * session ) const; + + /** + * This enum describes the options for propagating certain activity or + * changes in the group's master sessions to all sessions in the group. + */ + enum MasterMode { + /** + * Any input key presses in the master sessions are sent to all + * sessions in the group. + */ + CopyInputToAll = 1 + }; + + /** + * Specifies which activity in the group's master sessions is propagated + * to all sessions in the group. + * + * @param mode A bitwise OR of MasterMode flags. + */ + void setMasterMode( int mode ); + /** + * Returns a bitwise OR of the active MasterMode flags for this group. + * See setMasterMode() + */ + int masterMode() const; + +private: + void connectPair(Session * master , Session * other) const; + void disconnectPair(Session * master , Session * other) const; + void connectAll(bool connect); + QList masters() const; + + // maps sessions to their master status + QHash _sessions; + + int _masterMode; +}; + +} + +#endif diff --git a/qtermwidget/lib/ShellCommand.cpp b/qtermwidget/lib/ShellCommand.cpp new file mode 100644 index 0000000..d6a0438 --- /dev/null +++ b/qtermwidget/lib/ShellCommand.cpp @@ -0,0 +1,169 @@ +/* + Copyright (C) 2007 by Robert Knight + + Rewritten for QT4 by e_k , Copyright (C)2008 + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (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 + + +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.length() ; i++ ) { + QChar ch = fullCommand[i]; + + const bool isLastChar = ( i == fullCommand.length() - 1 ); + const bool isQuote = ( ch == QLatin1Char('\'') || ch == QLatin1Char('\"') ); + + if ( !isLastChar && isQuote ) { + inQuotes = !inQuotes; + } else { + if ( (!ch.isSpace() || inQuotes) && !isQuote ) { + builder.append(ch); + } + + if ( (ch.isSpace() && !inQuotes) || ( i == fullCommand.length()-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(QLatin1Char(' ')); +} +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; + + for(const 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( qgetenv(key.toLocal8Bit().constData()) ); + + if ( !value.isEmpty() ) { + expanded = true; + text.replace( pos, len, value ); + pos = pos + value.length(); + } else { + pos = pos2; + } + } + } + } + + return expanded; +} diff --git a/qtermwidget/src/ShellCommand.h b/qtermwidget/lib/ShellCommand.h similarity index 83% rename from qtermwidget/src/ShellCommand.h rename to qtermwidget/lib/ShellCommand.h index 44e0db8..3a5804a 100644 --- a/qtermwidget/src/ShellCommand.h +++ b/qtermwidget/lib/ShellCommand.h @@ -23,13 +23,12 @@ #define SHELLCOMMAND_H // Qt -#include +#include -namespace Konsole -{ +namespace Konsole { -/** - * A class to parse and extract information about shell commands. +/** + * A class to parse and extract information about shell commands. * * ShellCommand can be used to: * @@ -38,7 +37,7 @@ namespace Konsole * into its component parts (eg. the command "/bin/sh" and the arguments * "-c","/path/to/my/script") * - *
  • Take a command and a list of arguments and combine them to + *
  • Take a command and a list of arguments and combine them to * form a complete command line. *
  • *
  • Determine whether the binary specified by a command exists in the @@ -47,29 +46,28 @@ namespace Konsole *
  • Determine whether a command-line specifies the execution of * another command as the root user using su/sudo etc. *
  • - * + * */ -class ShellCommand -{ +class ShellCommand { public: /** * Constructs a ShellCommand from a command line. * - * @param fullCommand The command line to parse. + * @param fullCommand The command line to parse. */ - ShellCommand(const QString& fullCommand); + ShellCommand(const QString & fullCommand); /** * Constructs a ShellCommand with the specified @p command and @p arguments. */ - ShellCommand(const QString& command , const QStringList& arguments); + ShellCommand(const QString & command , const QStringList & arguments); /** Returns the command. */ QString command() const; /** Returns the arguments. */ QStringList arguments() const; - /** - * Returns the full command line. + /** + * Returns the full command line. */ QString fullCommand() const; @@ -79,13 +77,13 @@ public: bool isAvailable() const; /** Expands environment variables in @p text .*/ - static QString expand(const QString& text); + static QString expand(const QString & text); /** Expands environment variables in each string in @p list. */ - static QStringList expand(const QStringList& items); + static QStringList expand(const QStringList & items); private: - QStringList _arguments; + QStringList _arguments; }; } diff --git a/qtermwidget/lib/TerminalCharacterDecoder.cpp b/qtermwidget/lib/TerminalCharacterDecoder.cpp new file mode 100644 index 0000000..cf8521f --- /dev/null +++ b/qtermwidget/lib/TerminalCharacterDecoder.cpp @@ -0,0 +1,263 @@ +/* + This file is part of Konsole, an X terminal. + + Copyright 2006-2008 by Robert Knight + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (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 + +// KDE +//#include + +// Konsole +#include "konsole_wcwidth.h" + +#include + +using namespace Konsole; +PlainTextDecoder::PlainTextDecoder() + : _output(nullptr) + , _includeTrailingWhitespace(true) + , _recordLinePositions(false) +{ + +} +void PlainTextDecoder::setTrailingWhitespace(bool enable) +{ + _includeTrailingWhitespace = enable; +} +bool PlainTextDecoder::trailingWhitespace() const +{ + return _includeTrailingWhitespace; +} +void PlainTextDecoder::begin(QTextStream* output) +{ + _output = output; + if (!_linePositions.isEmpty()) + _linePositions.clear(); +} +void PlainTextDecoder::end() +{ + _output = nullptr; +} + +void PlainTextDecoder::setRecordLinePositions(bool record) +{ + _recordLinePositions = record; +} +QList PlainTextDecoder::linePositions() const +{ + return _linePositions; +} +void PlainTextDecoder::decodeLine(const Character* const characters, int count, LineProperty /*properties*/ + ) +{ + Q_ASSERT( _output ); + + if (_recordLinePositions && _output->string()) + { + int pos = _output->string()->length(); + _linePositions << pos; + } + + // check the real length + for (int i = 0 ; i < count ; i++) + { + if (characters[i] == '\0') + { + count = i; + break; + } + } + + //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) + std::wstring 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 != L' ' ) + break; + else + outputCount--; + } + } + + for (int i=0;i') + text.append(L">"); + else + text.push_back(ch); + } + else + { + text.append(L" "); //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(L"
    "); + + *_output << QString::fromStdWString(text); +} +void HTMLDecoder::openSpan(std::wstring& text , const QString& style) +{ + text.append( QString(QLatin1String("")).arg(style).toStdWString() ); +} + +void HTMLDecoder::closeSpan(std::wstring& text) +{ + text.append(L""); +} + +void HTMLDecoder::setColorTable(const ColorEntry* table) +{ + _colorTable = table; +} diff --git a/qtermwidget/src/TerminalCharacterDecoder.h b/qtermwidget/lib/TerminalCharacterDecoder.h similarity index 52% rename from qtermwidget/src/TerminalCharacterDecoder.h rename to qtermwidget/lib/TerminalCharacterDecoder.h index 5d97fc3..c49b3d4 100644 --- a/qtermwidget/src/TerminalCharacterDecoder.h +++ b/qtermwidget/lib/TerminalCharacterDecoder.h @@ -1,9 +1,7 @@ /* This file is part of Konsole, an X terminal. - - Copyright (C) 2006-7 by Robert Knight - - Rewritten for QT4 by e_k , Copyright (C)2008 + + Copyright 2006-2008 by Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by @@ -26,6 +24,8 @@ #include "Character.h" +#include + class QTextStream; namespace Konsole @@ -38,29 +38,29 @@ namespace Konsole * and background colours and other appearance-related properties into text strings. * * Derived classes may produce either plain text with no other colour or appearance information, or - * they may produce text which incorporates these additional properties. + * they may produce text which incorporates these additional properties. */ class TerminalCharacterDecoder { public: - virtual ~TerminalCharacterDecoder() {} + virtual ~TerminalCharacterDecoder() {} /** Begin decoding characters. The resulting text is appended to @p output. */ virtual void begin(QTextStream* output) = 0; /** End decoding. */ virtual void end() = 0; - /** - * Converts a line of terminal characters with associated properties into a text string - * and writes the string into an output QTextStream. - * - * @param characters An array of characters of length @p count. - * @param properties Additional properties which affect all characters in the line - * @param output The output stream which receives the decoded text - */ - virtual void decodeLine(const Character* const characters, - int count, - LineProperty properties) = 0; + /** + * Converts a line of terminal characters with associated properties into a text string + * and writes the string into an output QTextStream. + * + * @param characters An array of characters of length @p count. + * @param count The number of characters + * @param properties Additional properties which affect all characters in the line + */ + virtual void decodeLine(const Character* const characters, + int count, + LineProperty properties) = 0; }; /** @@ -70,10 +70,10 @@ public: class PlainTextDecoder : public TerminalCharacterDecoder { public: - PlainTextDecoder(); + PlainTextDecoder(); - /** - * Set whether trailing whitespace at the end of lines should be included + /** + * Set whether trailing whitespace at the end of lines should be included * in the output. * Defaults to true. */ @@ -83,18 +83,29 @@ public: * in the output. */ bool trailingWhitespace() const; + /** + * Returns of character positions in the output stream + * at which new lines where added. Returns an empty if setTrackLinePositions() is false or if + * the output device is not a string. + */ + QList linePositions() const; + /** Enables recording of character positions at which new lines are added. See linePositions() */ + void setRecordLinePositions(bool record); - virtual void begin(QTextStream* output); - virtual void end(); + void begin(QTextStream* output) override; + void end() override; + + void decodeLine(const Character* const characters, + int count, + LineProperty properties) override; - virtual void decodeLine(const Character* const characters, - int count, - LineProperty properties); - private: QTextStream* _output; bool _includeTrailingWhitespace; + + bool _recordLinePositions; + QList _linePositions; }; /** @@ -103,34 +114,34 @@ private: class HTMLDecoder : public TerminalCharacterDecoder { public: - /** - * Constructs an HTML decoder using a default black-on-white color scheme. - */ - HTMLDecoder(); + /** + * Constructs an HTML decoder using a default black-on-white color scheme. + */ + HTMLDecoder(); - /** - * Sets the colour table which the decoder uses to produce the HTML colour codes in its - * output - */ - void setColorTable( const ColorEntry* table ); - - virtual void decodeLine(const Character* const characters, - int count, - LineProperty properties); + /** + * Sets the colour table which the decoder uses to produce the HTML colour codes in its + * output + */ + void setColorTable( const ColorEntry* table ); - virtual void begin(QTextStream* output); - virtual void end(); + void decodeLine(const Character* const characters, + int count, + LineProperty properties) override; + + void begin(QTextStream* output) override; + void end() override; private: - void openSpan(QString& text , const QString& style); - void closeSpan(QString& text); + void openSpan(std::wstring& text , const QString& style); + void closeSpan(std::wstring& text); QTextStream* _output; - const ColorEntry* _colorTable; - bool _innerSpanOpen; - quint8 _lastRendition; - CharacterColor _lastForeColor; - CharacterColor _lastBackColor; + const ColorEntry* _colorTable; + bool _innerSpanOpen; + quint8 _lastRendition; + CharacterColor _lastForeColor; + CharacterColor _lastBackColor; }; diff --git a/qtermwidget/src/TerminalDisplay.cpp b/qtermwidget/lib/TerminalDisplay.cpp similarity index 52% rename from qtermwidget/src/TerminalDisplay.cpp rename to qtermwidget/lib/TerminalDisplay.cpp index e57d8de..8d14c48 100644 --- a/qtermwidget/src/TerminalDisplay.cpp +++ b/qtermwidget/lib/TerminalDisplay.cpp @@ -1,10 +1,8 @@ /* This file is part of Konsole, a terminal emulator for KDE. - - Copyright (C) 2006-7 by Robert Knight - Copyright (C) 1997,1998 by Lars Doelle - - Rewritten for QT4 by e_k , Copyright (C)2008 + + Copyright 2006-2008 by Robert Knight + Copyright 1997,1998 by Lars Doelle This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -26,29 +24,47 @@ #include "TerminalDisplay.h" // Qt -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +// KDE +//#include +//#include +//#include +//#include +//#include +//#include +//#include +//#include +//#include +//#include + +// Konsole +//#include #include "Filter.h" #include "konsole_wcwidth.h" #include "ScreenWindow.h" #include "TerminalCharacterDecoder.h" -#include "ColorTables.h" - using namespace Konsole; @@ -62,11 +78,35 @@ using namespace Konsole; "abcdefgjijklmnopqrstuvwxyz" \ "0123456789./+@" +const ColorEntry Konsole::base_color_table[TABLE_COLORS] = +// The following are almost IBM standard color codes, with some slight +// gamma correction for the dim colors to compensate for bright X screens. +// It contains the 8 ansiterm/xterm colors in 2 intensities. +{ + // Fixme: could add faint colors here, also. + // normal + ColorEntry(QColor(0x00,0x00,0x00), false), ColorEntry( QColor(0xB2,0xB2,0xB2), true), // Dfore, Dback + ColorEntry(QColor(0x00,0x00,0x00), false), ColorEntry( QColor(0xB2,0x18,0x18), false), // Black, Red + ColorEntry(QColor(0x18,0xB2,0x18), false), ColorEntry( QColor(0xB2,0x68,0x18), false), // Green, Yellow + ColorEntry(QColor(0x18,0x18,0xB2), false), ColorEntry( QColor(0xB2,0x18,0xB2), false), // Blue, Magenta + ColorEntry(QColor(0x18,0xB2,0xB2), false), ColorEntry( QColor(0xB2,0xB2,0xB2), false), // Cyan, White + // intensiv + ColorEntry(QColor(0x00,0x00,0x00), false), ColorEntry( QColor(0xFF,0xFF,0xFF), true), + ColorEntry(QColor(0x68,0x68,0x68), false), ColorEntry( QColor(0xFF,0x54,0x54), false), + ColorEntry(QColor(0x54,0xFF,0x54), false), ColorEntry( QColor(0xFF,0xFF,0x54), false), + ColorEntry(QColor(0x54,0x54,0xFF), false), ColorEntry( QColor(0xFF,0x54,0xFF), false), + ColorEntry(QColor(0x54,0xFF,0xFF), false), ColorEntry( QColor(0xFF,0xFF,0xFF), false) +}; + // scroll increment used when dragging selection at top/bottom of window. // static bool TerminalDisplay::_antialiasText = true; -bool TerminalDisplay::HAVE_TRANSPARENCY = false; +bool TerminalDisplay::HAVE_TRANSPARENCY = true; + +// we use this to force QPainter to display text in LTR mode +// more information can be found in: http://unicode.org/reports/tr9/ +const QChar LTR_OVERRIDE_CHAR( 0x202D ); /* ------------------------------------------------------------------------- */ /* */ @@ -91,17 +131,22 @@ void TerminalDisplay::setScreenWindow(ScreenWindow* window) // disconnect existing screen window if any if ( _screenWindow ) { - disconnect( _screenWindow , 0 , this , 0 ); + disconnect( _screenWindow , nullptr , this , nullptr ); } _screenWindow = window; if ( window ) { + +// TODO: Determine if this is an issue. //#warning "The order here is not specified - does it matter whether updateImage or updateLineProperties comes first?" connect( _screenWindow , SIGNAL(outputChanged()) , this , SLOT(updateLineProperties()) ); connect( _screenWindow , SIGNAL(outputChanged()) , this , SLOT(updateImage()) ); - window->setWindowLines(_lines); + connect( _screenWindow , SIGNAL(outputChanged()) , this , SLOT(updateFilters()) ); + connect( _screenWindow , SIGNAL(scrolled(int)) , this , SLOT(updateFilters()) ); + connect( _screenWindow , &ScreenWindow::scrollToEnd , this , &TerminalDisplay::scrollToEnd ); + window->setWindowLines(_lines); } } @@ -109,20 +154,37 @@ const ColorEntry* TerminalDisplay::colorTable() const { return _colorTable; } +void TerminalDisplay::setBackgroundColor(const QColor& color) +{ + _colorTable[DEFAULT_BACK_COLOR].color = color; + QPalette p = palette(); + p.setColor( backgroundRole(), color ); + setPalette( p ); + + // Avoid propagating the palette change to the scroll bar + _scrollBar->setPalette( QApplication::palette() ); + + update(); +} +void TerminalDisplay::setForegroundColor(const QColor& color) +{ + _colorTable[DEFAULT_FORE_COLOR].color = color; + + update(); +} + +void TerminalDisplay::setColorTableColor(const int colorId, const QColor &color) +{ + _colorTable[colorId].color = color; + update(); +} void TerminalDisplay::setColorTable(const ColorEntry table[]) { for (int i = 0; i < TABLE_COLORS; i++) _colorTable[i] = table[i]; - QPalette p = palette(); - p.setColor( backgroundRole(), _colorTable[DEFAULT_BACK_COLOR].color ); - setPalette( p ); - - // Avoid propagating the palette change to the scroll bar - _scrollBar->setPalette( QApplication::palette() ); - - update(); + setBackgroundColor(_colorTable[DEFAULT_BACK_COLOR].color); } /* ------------------------------------------------------------------------- */ @@ -138,17 +200,19 @@ void TerminalDisplay::setColorTable(const ColorEntry table[]) 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 + We treat non-iso10646 fonts as VT100 extended and do the required 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())); +bool TerminalDisplay::isLineChar(wchar_t c) const { + return _drawLineChars && ((c & 0xFF80) == 0x2500); } - + +bool TerminalDisplay::isLineCharString(const std::wstring& string) const { + return (string.length() > 0) && (isLineChar(string[0])); +} + // assert for i in [0..31] : vt100extended(vt100_graphics[i]) == i. @@ -165,19 +229,18 @@ 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)); + _fontWidth = qRound((double)fm.horizontalAdvance(QLatin1String(REPCHAR))/(double)qstrlen(REPCHAR)); _fixedFont = true; - int fw = fm.width(REPCHAR[0]); - for(unsigned int i=1; i< strlen(REPCHAR); i++) + int fw = fm.horizontalAdvance(QLatin1Char(REPCHAR[0])); + for(unsigned int i=1; i< qstrlen(REPCHAR); i++) { - if (fw != fm.width(REPCHAR[i])) + if (fw != fm.horizontalAdvance(QLatin1Char(REPCHAR[i]))) { _fixedFont = false; break; @@ -191,30 +254,60 @@ void TerminalDisplay::fontChange(const QFont&) emit changedFontMetricSignal( _fontHeight, _fontWidth ); propagateSize(); + + // We will run paint event testing procedure. + // Although this operation will destroy the original content, + // the content will be drawn again after the test. + _drawTextTestFlag = true; update(); } +void TerminalDisplay::calDrawTextAdditionHeight(QPainter& painter) +{ + QRect test_rect, feedback_rect; + test_rect.setRect(1, 1, _fontWidth * 4, _fontHeight); + painter.drawText(test_rect, Qt::AlignBottom, LTR_OVERRIDE_CHAR + QLatin1String("Mq"), &feedback_rect); + + //qDebug() << "test_rect:" << test_rect << "feeback_rect:" << feedback_rect; + + _drawTextAdditionHeight = (feedback_rect.height() - _fontHeight) / 2; + if(_drawTextAdditionHeight < 0) { + _drawTextAdditionHeight = 0; + } + + _drawTextTestFlag = false; +} + void TerminalDisplay::setVTFont(const QFont& f) { QFont font = f; - QFontMetrics metrics(font); + // This was originally set for OS X only: + // mac uses floats for font width specification. + // this ensures the same handling for all platforms + // but then there was revealed that various Linux distros + // have this problem too... +#if QT_VERSION < 0x060000 + font.setStyleStrategy(QFont::ForceIntegerMetrics); +#endif - if ( metrics.height() < height() && metrics.maxWidth() < width() ) + if ( !QFontInfo(font).fixedPitch() ) { - // 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); + qDebug() << "Using a variable-width font in the terminal. This may cause performance degradation and display/alignment errors."; } + + // 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 &) @@ -230,49 +323,63 @@ void TerminalDisplay::setFont(const QFont &) TerminalDisplay::TerminalDisplay(QWidget *parent) :QWidget(parent) -,_screenWindow(0) +,_screenWindow(nullptr) ,_allowBell(true) -,_gridLayout(0) +,_gridLayout(nullptr) ,_fontHeight(1) ,_fontWidth(1) ,_fontAscent(1) +,_boldIntense(true) ,_lines(1) ,_columns(1) ,_usedLines(1) ,_usedColumns(1) ,_contentHeight(1) ,_contentWidth(1) -,_image(0) +,_image(nullptr) ,_randomSeed(0) ,_resizing(false) ,_terminalSizeHint(false) ,_terminalSizeStartup(true) -,_bidiEnabled(false) +,_bidiEnabled(true) +,_mouseMarks(false) +,_disabledBracketedPasteMode(false) ,_actSel(0) ,_wordSelectionMode(false) ,_lineSelectionMode(false) ,_preserveLineBreaks(false) ,_columnSelectionMode(false) -,_scrollbarLocation(NoScrollBar) -,_wordCharacters(":@-./_~") +,_scrollbarLocation(QTermWidget::NoScrollBar) +,_wordCharacters(QLatin1String(":@-./_~")) ,_bellMode(SystemBeepBell) ,_blinking(false) +,_hasBlinker(false) ,_cursorBlinking(false) ,_hasBlinkingCursor(false) +,_allowBlinkingText(true) ,_ctrlDrag(false) ,_tripleClickMode(SelectWholeLine) ,_isFixedSize(false) ,_possibleTripleClick(false) -,_resizeWidget(0) -,_resizeTimer(0) +,_resizeWidget(nullptr) +,_resizeTimer(nullptr) ,_flowControlWarningEnabled(false) -,_outputSuspendedLabel(0) +,_outputSuspendedLabel(nullptr) ,_lineSpacing(0) ,_colorsInverted(false) -,_blendColor(qRgba(0,0,0,0xff)) +,_opacity(static_cast(1)) +,_backgroundMode(None) ,_filterChain(new TerminalImageFilterChain()) -,_cursorShape(BlockCursor) +,_cursorShape(Emulation::KeyboardCursorShape::BlockCursor) +,mMotionAfterPasting(NoMoveScreenWindow) +,_leftBaseMargin(1) +,_topBaseMargin(1) +,_drawLineChars(true) { + // variables for draw text + _drawTextAdditionHeight = 0; + _drawTextTestFlag = false; + // terminal applications are not designed with Right-To-Left in mind, // so the layout is forced to Left-To-Right setLayoutDirection(Qt::LeftToRight); @@ -280,16 +387,23 @@ TerminalDisplay::TerminalDisplay(QWidget *parent) // 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; + _topMargin = _topBaseMargin; + _leftMargin = _leftBaseMargin; // 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); + // since the contrast with the terminal background may not be enough, + // the scrollbar should be auto-filled if not transient + if (!_scrollBar->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, _scrollBar)) + _scrollBar->setAutoFillBackground(true); + setScroll(0,0); _scrollBar->setCursor( Qt::ArrowCursor ); - connect(_scrollBar, SIGNAL(valueChanged(int)), this, - SLOT(scrollBarPositionChanged(int))); + connect(_scrollBar, SIGNAL(valueChanged(int)), this, + SLOT(scrollBarPositionChanged(int))); + // qtermwidget: we have to hide it here due the _scrollbarLocation==NoScrollBar + // check in TerminalDisplay::setScrollBarPosition(ScrollBarPosition position) + _scrollBar->hide(); // setup timers for blinking cursor and text _blinkTimer = new QTimer(this); @@ -297,14 +411,14 @@ TerminalDisplay::TerminalDisplay(QWidget *parent) _blinkCursorTimer = new QTimer(this); connect(_blinkCursorTimer, SIGNAL(timeout()), this, SLOT(blinkCursorEvent())); -// QCursor::setAutoHideCursor( this, true ); - +// KCursor::setAutoHideCursor( this, true ); + setUsesMouse(true); - setColorTable(whiteonblack_color_table); -// setColorTable(blackonlightyellow_color_table); + setBracketedPasteMode(false); + setColorTable(base_color_table); setMouseTracking(true); - // Enable drag and drop + // Enable drag and drop setAcceptDrops(true); // attempt dragInfo.state = diNone; @@ -318,18 +432,19 @@ TerminalDisplay::TerminalDisplay(QWidget *parent) setAttribute(Qt::WA_OpaquePaintEvent); _gridLayout = new QGridLayout(this); - _gridLayout->setMargin(0); + _gridLayout->setContentsMargins(0, 0, 0, 0); - setLayout( _gridLayout ); + setLayout( _gridLayout ); - //set up a warning message when the user presses Ctrl+S to avoid confusion - connect( this,SIGNAL(flowControlKeyPressed(bool)),this,SLOT(outputSuspended(bool)) ); + new AutoScrollHandler(this); } TerminalDisplay::~TerminalDisplay() { + disconnect(_blinkTimer); + disconnect(_blinkCursorTimer); qApp->removeEventFilter( this ); - + delete[] _image; delete _gridLayout; @@ -393,7 +508,7 @@ enum LineEncode #include "LineFont.h" -static void drawLineChar(QPainter& paint, int x, int y, int w, int h, uchar code) +static void drawLineChar(QPainter& paint, int x, int y, int w, int h, uint8_t code) { //Calculate cell midpoints, end points. int cx = x + w/2; @@ -459,33 +574,118 @@ static void drawLineChar(QPainter& paint, int x, int y, int w, int h, uchar code } -void TerminalDisplay::drawLineCharString( QPainter& painter, int x, int y, const QString& str, - const Character* attributes) +static void drawOtherChar(QPainter& paint, int x, int y, int w, int h, uchar code) { - 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); - } + //Calculate cell midpoints, end points. + const int cx = x + w / 2; + const int cy = y + h / 2; + const int ex = x + w - 1; + const int ey = y + h - 1; - painter.setPen( currentPen ); + // Double dashes + if (0x4C <= code && code <= 0x4F) { + const int xHalfGap = qMax(w / 15, 1); + const int yHalfGap = qMax(h / 15, 1); + switch (code) { + case 0x4D: // BOX DRAWINGS HEAVY DOUBLE DASH HORIZONTAL + paint.drawLine(x, cy - 1, cx - xHalfGap - 1, cy - 1); + paint.drawLine(x, cy + 1, cx - xHalfGap - 1, cy + 1); + paint.drawLine(cx + xHalfGap, cy - 1, ex, cy - 1); + paint.drawLine(cx + xHalfGap, cy + 1, ex, cy + 1); + /* Falls through. */ + case 0x4C: // BOX DRAWINGS LIGHT DOUBLE DASH HORIZONTAL + paint.drawLine(x, cy, cx - xHalfGap - 1, cy); + paint.drawLine(cx + xHalfGap, cy, ex, cy); + break; + case 0x4F: // BOX DRAWINGS HEAVY DOUBLE DASH VERTICAL + paint.drawLine(cx - 1, y, cx - 1, cy - yHalfGap - 1); + paint.drawLine(cx + 1, y, cx + 1, cy - yHalfGap - 1); + paint.drawLine(cx - 1, cy + yHalfGap, cx - 1, ey); + paint.drawLine(cx + 1, cy + yHalfGap, cx + 1, ey); + /* Falls through. */ + case 0x4E: // BOX DRAWINGS LIGHT DOUBLE DASH VERTICAL + paint.drawLine(cx, y, cx, cy - yHalfGap - 1); + paint.drawLine(cx, cy + yHalfGap, cx, ey); + break; + } + } + + // Rounded corner characters + else if (0x6D <= code && code <= 0x70) { + const int r = w * 3 / 8; + const int d = 2 * r; + switch (code) { + case 0x6D: // BOX DRAWINGS LIGHT ARC DOWN AND RIGHT + paint.drawLine(cx, cy + r, cx, ey); + paint.drawLine(cx + r, cy, ex, cy); + paint.drawArc(cx, cy, d, d, 90 * 16, 90 * 16); + break; + case 0x6E: // BOX DRAWINGS LIGHT ARC DOWN AND LEFT + paint.drawLine(cx, cy + r, cx, ey); + paint.drawLine(x, cy, cx - r, cy); + paint.drawArc(cx - d, cy, d, d, 0 * 16, 90 * 16); + break; + case 0x6F: // BOX DRAWINGS LIGHT ARC UP AND LEFT + paint.drawLine(cx, y, cx, cy - r); + paint.drawLine(x, cy, cx - r, cy); + paint.drawArc(cx - d, cy - d, d, d, 270 * 16, 90 * 16); + break; + case 0x70: // BOX DRAWINGS LIGHT ARC UP AND RIGHT + paint.drawLine(cx, y, cx, cy - r); + paint.drawLine(cx + r, cy, ex, cy); + paint.drawArc(cx, cy - d, d, d, 180 * 16, 90 * 16); + break; + } + } + + // Diagonals + else if (0x71 <= code && code <= 0x73) { + switch (code) { + case 0x71: // BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT + paint.drawLine(ex, y, x, ey); + break; + case 0x72: // BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT + paint.drawLine(x, y, ex, ey); + break; + case 0x73: // BOX DRAWINGS LIGHT DIAGONAL CROSS + paint.drawLine(ex, y, x, ey); + paint.drawLine(x, y, ex, ey); + break; + } + } } -void TerminalDisplay::setKeyboardCursorShape(KeyboardCursorShape shape) +void TerminalDisplay::drawLineCharString( QPainter& painter, int x, int y, const std::wstring& str, + const Character* attributes) const +{ + const QPen& currentPen = painter.pen(); + + if ( (attributes->rendition & RE_BOLD) && _boldIntense ) + { + QPen boldPen(currentPen); + boldPen.setWidth(3); + painter.setPen( boldPen ); + } + + for (size_t i=0 ; i < str.length(); i++) + { + uint8_t code = static_cast(str[i] & 0xffU); + if (LineChars[code]) + drawLineChar(painter, x + (_fontWidth*i), y, _fontWidth, _fontHeight, code); + else + drawOtherChar(painter, x + (_fontWidth * i), y, _fontWidth, _fontHeight, code); + } + + painter.setPen( currentPen ); +} + +void TerminalDisplay::setKeyboardCursorShape(QTermWidget::KeyboardCursorShape shape) { _cursorShape = shape; + + updateCursor(); } -TerminalDisplay::KeyboardCursorShape TerminalDisplay::keyboardCursorShape() const +QTermWidget::KeyboardCursorShape TerminalDisplay::keyboardCursorShape() const { return _cursorShape; } @@ -507,87 +707,79 @@ QColor TerminalDisplay::keyboardCursorColor() const void TerminalDisplay::setOpacity(qreal opacity) { - QColor color(_blendColor); - color.setAlphaF(opacity); + _opacity = qBound(static_cast(0), opacity, static_cast(1)); +} - // enable automatic background filling to prevent the display - // flickering if there is no transparency - if ( color.alpha() == 255 ) +void TerminalDisplay::setBackgroundImage(const QString& backgroundImage) +{ + if (!backgroundImage.isEmpty()) { - setAutoFillBackground(true); + _backgroundImage.load(backgroundImage); + setAttribute(Qt::WA_OpaquePaintEvent, false); } else { - setAutoFillBackground(false); + _backgroundImage = QPixmap(); + setAttribute(Qt::WA_OpaquePaintEvent, true); } +} - _blendColor = color.rgba(); +void TerminalDisplay::setBackgroundMode(BackgroundMode mode) +{ + _backgroundMode = mode; } 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 ) + // The whole widget rectangle is filled by the background color from + // the color scheme set in setColorTable(), while the scrollbar is + // left to the widget style for a consistent look. + if ( useOpacitySetting ) { - QColor color(backgroundColor); - color.setAlpha(qAlpha(_blendColor)); + if (_backgroundImage.isNull()) { + QColor color(backgroundColor); + color.setAlphaF(_opacity); - painter.save(); - painter.setCompositionMode(QPainter::CompositionMode_Source); - painter.fillRect(contentsRect, color); - painter.restore(); - } - else { - painter.fillRect(contentsRect, backgroundColor); - } - - painter.fillRect(scrollBarArea,_scrollBar->palette().background()); + painter.save(); + painter.setCompositionMode(QPainter::CompositionMode_Source); + painter.fillRect(rect, color); + painter.restore(); + } + } + else + painter.fillRect(rect, backgroundColor); } -void TerminalDisplay::drawCursor(QPainter& painter, +void TerminalDisplay::drawCursor(QPainter& painter, const QRect& rect, const QColor& foregroundColor, const QColor& /*backgroundColor*/, bool& invertCharacterColor) { - QRect cursorRect = rect; + QRectF cursorRect = rect; cursorRect.setHeight(_fontHeight - _lineSpacing - 1); - + if (!_cursorBlinking) { if ( _cursorColor.isValid() ) painter.setPen(_cursorColor); - else { - painter.setPen(foregroundColor); - } + else + painter.setPen(foregroundColor); - if ( _cursorShape == BlockCursor ) + if ( _cursorShape == Emulation::KeyboardCursorShape::BlockCursor ) { // draw the cursor outline, adjusting the area so that // it is draw entirely inside 'rect' - int penWidth = qMax(1,painter.pen().width()); + float penWidth = qMax(1,painter.pen().width()); painter.drawRect(cursorRect.adjusted(penWidth/2, penWidth/2, - - 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 @@ -596,88 +788,110 @@ void TerminalDisplay::drawCursor(QPainter& painter, } } } - else if ( _cursorShape == UnderlineCursor ) + else if ( _cursorShape == Emulation::KeyboardCursorShape::UnderlineCursor ) painter.drawLine(cursorRect.left(), cursorRect.bottom(), cursorRect.right(), cursorRect.bottom()); - else if ( _cursorShape == IBeamCursor ) + else if ( _cursorShape == Emulation::KeyboardCursorShape::IBeamCursor ) painter.drawLine(cursorRect.left(), cursorRect.top(), cursorRect.left(), cursorRect.bottom()); - + } } void TerminalDisplay::drawCharacters(QPainter& painter, const QRect& rect, - const QString& text, + const std::wstring& text, const Character* style, bool invertCharacterColor) { // don't draw text which is currently blinking if ( _blinking && (style->rendition & RE_BLINK) ) + return; + + // don't draw concealed characters + if (style->rendition & RE_CONCEAL) return; - + // setup bold and underline - bool useBold = style->rendition & RE_BOLD || style->isBold(_colorTable) || font().bold(); - bool useUnderline = style->rendition & RE_UNDERLINE || font().underline(); + bool useBold = ((style->rendition & RE_BOLD) && _boldIntense) || font().bold(); + const bool useUnderline = style->rendition & RE_UNDERLINE || font().underline(); + const bool useItalic = style->rendition & RE_ITALIC || font().italic(); + const bool useStrikeOut = style->rendition & RE_STRIKEOUT || font().strikeOut(); + const bool useOverline = style->rendition & RE_OVERLINE || font().overline(); QFont font = painter.font(); - if ( font.bold() != useBold - || font.underline() != useUnderline ) - { + if ( font.bold() != useBold + || font.underline() != useUnderline + || font.italic() != useItalic + || font.strikeOut() != useStrikeOut + || font.overline() != useOverline) { font.setBold(useBold); font.setUnderline(useUnderline); + font.setItalic(useItalic); + font.setStrikeOut(useStrikeOut); + font.setOverline(useOverline); painter.setFont(font); } + // setup pen const CharacterColor& textColor = ( invertCharacterColor ? style->backgroundColor : style->foregroundColor ); const QColor color = textColor.color(_colorTable); - QPen pen = painter.pen(); if ( pen.color() != color ) { pen.setColor(color); painter.setPen(color); } + // draw text - if ( isLineCharString(text) ) { - drawLineCharString(painter,rect.x(),rect.y(),text,style); - } + if ( isLineCharString(text) ) + drawLineCharString(painter,rect.x(),rect.y(),text,style); else - { - // the drawText(rect,flags,string) overload is used here with null flags - // instead of drawText(rect,string) because the (rect,string) overload causes - // the application's default layout direction to be used instead of - // the widget-specific layout direction, which should always be - // Qt::LeftToRight for this widget - painter.drawText(rect,0,text); - } + { + // Force using LTR as the document layout for the terminal area, because + // there is no use cases for RTL emulator and RTL terminal application. + // + // This still allows RTL characters to be rendered in the RTL way. + painter.setLayoutDirection(Qt::LeftToRight); + + if (_bidiEnabled) { + painter.drawText(rect.x(), rect.y() + _fontAscent + _lineSpacing, QString::fromStdWString(text)); + } else { + { + QRect drawRect(rect.topLeft(), rect.size()); + drawRect.setHeight(rect.height() + _drawTextAdditionHeight); + painter.drawText(drawRect, Qt::AlignBottom, LTR_OVERRIDE_CHAR + QString::fromStdWString(text)); + } + } + } } -void TerminalDisplay::drawTextFragment(QPainter& painter , +void TerminalDisplay::drawTextFragment(QPainter& painter , const QRect& rect, - const QString& text, + const std::wstring& text, const Character* style) { painter.save(); - // setup painter + // setup painter const QColor foregroundColor = style->foregroundColor.color(_colorTable); const QColor backgroundColor = style->backgroundColor.color(_colorTable); - + // draw background if different from the display's background color - if ( backgroundColor != palette().background().color() ) - drawBackground(painter,rect,backgroundColor, false /* do not use transparency */); + if ( backgroundColor != palette().window().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); @@ -709,47 +923,69 @@ void TerminalDisplay::setCursorPos(const int curx, const int cury) // scrolls the image by 'lines', down if lines > 0 or up otherwise. // -// the terminal emulation keeps track of the scrolling of the character -// image as it receives input, and when the view is updated, it calls scrollImage() -// with the final scroll amount. this improves performance because scrolling the -// display is much cheaper than re-rendering all the text for the -// part of the image which has moved up or down. +// the terminal emulation keeps track of the scrolling of the character +// image as it receives input, and when the view is updated, it calls scrollImage() +// with the final scroll amount. this improves performance because scrolling the +// display is much cheaper than re-rendering all the text for the +// part of the image which has moved up or down. // Instead only new lines have to be drawn -// -// note: it is important that the area of the display which is -// scrolled aligns properly with the character grid - -// which has a top left point at (_leftMargin,_topMargin) , -// a cell width of _fontWidth and a cell height of _fontHeight). void TerminalDisplay::scrollImage(int lines , const QRect& screenWindowRegion) { - // if the flow control warning is enabled this will interfere with the - // scrolling optimisations and cause artifacts. the simple solution here - // is to just disable the optimisation whilst it is visible - if ( _outputSuspendedLabel && _outputSuspendedLabel->isVisible() ) { - return; - } + // if the flow control warning is enabled this will interfere with the + // scrolling optimizations and cause artifacts. the simple solution here + // is to just disable the optimization whilst it is visible + if ( _outputSuspendedLabel && _outputSuspendedLabel->isVisible() ) + return; // constrain the region to the display // the bottom of the region is capped to the number of lines in the display's // internal image - 2, so that the height of 'region' is strictly less // than the height of the internal image. QRect region = screenWindowRegion; - region.setBottom( qMin(region.bottom(),this->_lines-2) ); + region.setBottom( qMin(region.bottom(),this->_lines-2) ); - if ( lines == 0 - || _image == 0 - || !region.isValid() - || (region.top() + abs(lines)) >= region.bottom() + // return if there is nothing to do + if ( lines == 0 + || _image == nullptr + || !region.isValid() + || (region.top() + abs(lines)) >= region.bottom() || this->_lines <= region.height() ) return; - QRect scrollRect; + // hide terminal size label to prevent it being scrolled + if (_resizeWidget && _resizeWidget->isVisible()) + _resizeWidget->hide(); + // Note: With Qt 4.4 the left edge of the scrolled area must be at 0 + // to get the correct (newly exposed) part of the widget repainted. + // + // The right edge must be before the left edge of the scroll bar to + // avoid triggering a repaint of the entire widget, the distance is + // given by SCROLLBAR_CONTENT_GAP + // + // Set the QT_FLUSH_PAINT environment variable to '1' before starting the + // application to monitor repainting. + // + int scrollBarWidth = _scrollBar->isHidden() ? 0 : + _scrollBar->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, _scrollBar) ? + 0 : _scrollBar->width(); + const int SCROLLBAR_CONTENT_GAP = scrollBarWidth == 0 ? 0 : 1; + QRect scrollRect; + if ( _scrollbarLocation == QTermWidget::ScrollBarLeft ) + { + scrollRect.setLeft(scrollBarWidth+SCROLLBAR_CONTENT_GAP); + scrollRect.setRight(width()); + } + else + { + scrollRect.setLeft(0); + scrollRect.setRight(width() - scrollBarWidth - SCROLLBAR_CONTENT_GAP); + } void* firstCharPos = &_image[ region.top() * this->_columns ]; void* lastCharPos = &_image[ (region.top() + abs(lines)) * this->_columns ]; int top = _topMargin + (region.top() * _fontHeight); int linesToMove = region.height() - abs(lines); - int bytesToMove = linesToMove * + int bytesToMove = linesToMove * this->_columns * sizeof(Character); @@ -760,109 +996,126 @@ void TerminalDisplay::scrollImage(int lines , const QRect& screenWindowRegion) if ( lines > 0 ) { // check that the memory areas that we are going to move are valid - Q_ASSERT( (char*)lastCharPos + bytesToMove < + Q_ASSERT( (char*)lastCharPos + bytesToMove < (char*)(_image + (this->_lines * this->_columns)) ); - - Q_ASSERT( (lines*this->_columns) < _imageSize ); + + Q_ASSERT( (lines*this->_columns) < _imageSize ); //scroll internal image down - memmove( firstCharPos , lastCharPos , bytesToMove ); - - //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 ); + memmove( firstCharPos , lastCharPos , bytesToMove ); + + //set region of display to scroll + scrollRect.setTop(top); } else { // check that the memory areas that we are going to move are valid - Q_ASSERT( (char*)firstCharPos + bytesToMove < + Q_ASSERT( (char*)firstCharPos + bytesToMove < (char*)(_image + (this->_lines * this->_columns)) ); //scroll internal image up - memmove( lastCharPos , firstCharPos , bytesToMove ); - - //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 ); + memmove( lastCharPos , firstCharPos , bytesToMove ); - scrollRect = QRect( topPoint , - QSize( this->_usedColumns*_fontWidth , - linesToMove * _fontHeight )); + //set region of the display to scroll + scrollRect.setTop(top + abs(lines) * _fontHeight); } + scrollRect.setHeight(linesToMove * _fontHeight ); + + Q_ASSERT(scrollRect.isValid() && !scrollRect.isEmpty()); //scroll the display vertically to match internal _image scroll( 0 , _fontHeight * (-lines) , scrollRect ); } -QRegion TerminalDisplay::hotSpotRegion() const +QRegion TerminalDisplay::hotSpotRegion() const { - QRegion region; - foreach( Filter::HotSpot* hotSpot , _filterChain->hotSpots() ) - { - QRect rect; - rect.setLeft(hotSpot->startColumn()); - rect.setTop(hotSpot->startLine()); - rect.setRight(hotSpot->endColumn()); - rect.setBottom(hotSpot->endLine()); - - region |= imageToWidget(rect); - } - return region; + QRegion region; + const auto hotSpots = _filterChain->hotSpots(); + for( Filter::HotSpot* const hotSpot : hotSpots ) + { + QRect r; + if (hotSpot->startLine()==hotSpot->endLine()) { + r.setLeft(hotSpot->startColumn()); + r.setTop(hotSpot->startLine()); + r.setRight(hotSpot->endColumn()); + r.setBottom(hotSpot->endLine()); + region |= imageToWidget(r);; + } else { + r.setLeft(hotSpot->startColumn()); + r.setTop(hotSpot->startLine()); + r.setRight(_columns); + r.setBottom(hotSpot->startLine()); + region |= imageToWidget(r);; + for ( int line = hotSpot->startLine()+1 ; line < hotSpot->endLine() ; line++ ) { + r.setLeft(0); + r.setTop(line); + r.setRight(_columns); + r.setBottom(line); + region |= imageToWidget(r);; + } + r.setLeft(0); + r.setTop(hotSpot->endLine()); + r.setRight(hotSpot->endColumn()); + r.setBottom(hotSpot->endLine()); + region |= imageToWidget(r);; + } + } + return region; } -void TerminalDisplay::processFilters() +void TerminalDisplay::processFilters() { - if (!_screenWindow) - return; + if (!_screenWindow) + return; - QRegion preUpdateHotSpots = hotSpotRegion(); + 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() ); + // 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(); + QRegion postUpdateHotSpots = hotSpotRegion(); - update( preUpdateHotSpots | postUpdateHotSpots ); + update( preUpdateHotSpots | postUpdateHotSpots ); } -void TerminalDisplay::updateImage() +void TerminalDisplay::updateImage() { if ( !_screenWindow ) return; - // optimization - scroll the existing image where possible and - // avoid expensive text drawing for parts of the image that + // optimization - scroll the existing image where possible and + // avoid expensive text drawing for parts of the image that // can simply be moved up or down scrollImage( _screenWindow->scrollCount() , _screenWindow->scrollRegion() ); _screenWindow->resetScrollCount(); + if (!_image) { + // Create _image. + // The emitted changedContentSizeSignal also leads to getImage being recreated, so do this first. + updateImageSize(); + } + Character* const newimg = _screenWindow->getImage(); int lines = _screenWindow->windowLines(); int columns = _screenWindow->windowColumns(); setScroll( _screenWindow->currentLine() , _screenWindow->lineCount() ); - if (!_image) - updateImageSize(); // Create _image - Q_ASSERT( this->_usedLines <= this->_lines ); Q_ASSERT( this->_usedColumns <= this->_columns ); int y,x,len; QPoint tL = contentsRect().topLeft(); - int tLx = tL.x(); int tLy = tL.y(); _hasBlinker = false; @@ -874,8 +1127,8 @@ void TerminalDisplay::updateImage() 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]; + wchar_t *disstrU = new wchar_t[columnsToUpdate]; + char *dirtyMask = new char[columnsToUpdate+2]; QRegion dirtyRegion; // debugging variable, this records the number of lines that are found to @@ -883,37 +1136,39 @@ void TerminalDisplay::updateImage() // which therefore need to be repainted int dirtyLineCount = 0; - for (y = 0; y < linesToUpdate; y++) + for (y = 0; y < linesToUpdate; ++y) { const Character* currentLine = &_image[y*this->_columns]; const Character* const newLine = &newimg[y*columns]; 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++) + + for( x = 0 ; x < columnsToUpdate ; ++x) { - if ( newLine[x] != currentLine[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++) + for (x = 0; x < columnsToUpdate; ++x) { - _hasBlinker |= (newLine[x].rendition & RE_BLINK); - + if ((newLine[x].rendition & RE_BLINK) != 0) { + _hasBlinker = true; + } + // 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; + wchar_t c = newLine[x+0].character; if ( !c ) continue; int p = 0; @@ -924,27 +1179,27 @@ void TerminalDisplay::updateImage() _clipboard = newLine[x].backgroundColor; if (newLine[x].foregroundColor != cf) cf = newLine[x].foregroundColor; int lln = columnsToUpdate - x; - for (len = 1; len < lln; len++) + for (len = 1; len < lln; ++len) { const Character& ch = newLine[x+len]; if (!ch.character) continue; // Skip trailing part of multi-col chars. - bool nextIsDoubleWidth = (x+len+1 == columnsToUpdate) ? false : (newLine[x+len+1].character == 0); + bool nextIsDoubleWidth = (x+len+1 == columnsToUpdate) ? false : (newLine[x+len+1].character == 0); - if ( ch.foregroundColor != cf || - ch.backgroundColor != _clipboard || + if ( ch.foregroundColor != cf || + ch.backgroundColor != _clipboard || ch.rendition != cr || - !dirtyMask[x+len] || - isLineChar(c) != lineDraw || + !dirtyMask[x+len] || + isLineChar(c) != lineDraw || nextIsDoubleWidth != doubleWidth ) break; disstrU[p++] = c; //fontMap(c); } - QString unistr(disstrU, p); + std::wstring unistr(disstrU, p); bool saveFixedFont = _fixedFont; if (lineDraw) @@ -952,58 +1207,61 @@ void TerminalDisplay::updateImage() if (doubleWidth) _fixedFont = false; - updateLine = true; + updateLine = true; - _fixedFont = saveFixedFont; + _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); + //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) { + if ((_lineProperties[y] & LINE_DOUBLEHEIGHT) != 0) { + updateLine = true; + } + } // if the characters on the line are different in the old and the new _image - // then this line must be repainted. + // then this line must be repainted. if (updateLine) { dirtyLineCount++; // add the area occupied by this line to the region which needs to be // repainted - QRect dirtyRect = QRect( _leftMargin+tLx , - _topMargin+tLy+_fontHeight*y , - _fontWidth * columnsToUpdate , - _fontHeight ); + QRect dirtyRect = QRect( _leftMargin+tLx , + _topMargin+tLy+_fontHeight*y , + _fontWidth * columnsToUpdate , + _fontHeight ); dirtyRegion |= dirtyRect; } - // replace the line of characters in the old _image with the - // current line of the new _image + // replace the line of characters in the old _image with the + // current line of the new _image memcpy((void*)currentLine,(const void*)newLine,columnsToUpdate*sizeof(Character)); } // if the new _image is smaller than the previous _image, then ensure that the area - // outside the new _image is cleared + // outside the new _image is cleared if ( linesToUpdate < _usedLines ) { - dirtyRegion |= QRect( _leftMargin+tLx , - _topMargin+tLy+_fontHeight*linesToUpdate , - _fontWidth * this->_columns , + dirtyRegion |= QRect( _leftMargin+tLx , + _topMargin+tLy+_fontHeight*linesToUpdate , + _fontWidth * this->_columns , _fontHeight * (_usedLines-linesToUpdate) ); } _usedLines = linesToUpdate; - + if ( columnsToUpdate < _usedColumns ) { - dirtyRegion |= QRect( _leftMargin+tLx+columnsToUpdate*_fontWidth , - _topMargin+tLy , - _fontWidth * (_usedColumns-columnsToUpdate) , + dirtyRegion |= QRect( _leftMargin+tLx+columnsToUpdate*_fontWidth , + _topMargin+tLy , + _fontWidth * (_usedColumns-columnsToUpdate) , _fontHeight * this->_lines ); } _usedColumns = columnsToUpdate; @@ -1013,7 +1271,7 @@ void TerminalDisplay::updateImage() // update the parts of the display which have changed update(dirtyRegion); - if ( _hasBlinker && !_blinkTimer->isActive()) _blinkTimer->start( BLINK_DELAY ); + if ( _hasBlinker && !_blinkTimer->isActive()) _blinkTimer->start( TEXT_BLINK_DELAY ); if (!_hasBlinker && _blinkTimer->isActive()) { _blinkTimer->stop(); _blinking = false; } delete[] dirtyMask; delete[] disstrU; @@ -1025,26 +1283,24 @@ void TerminalDisplay::showResizeNotification() if (_terminalSizeHint && isVisible()) { if (_terminalSizeStartup) { - _terminalSizeStartup=false; + _terminalSizeStartup=false; return; } if (!_resizeWidget) { - _resizeWidget = new QLabel(("Size: XXX x XXX"), this); - _resizeWidget->setMinimumWidth(_resizeWidget->fontMetrics().width(("Size: XXX x XXX"))); + const QString label = tr("Size: XXX x XXX"); + _resizeWidget = new QLabel(label, this); + _resizeWidget->setMinimumWidth(_resizeWidget->fontMetrics().horizontalAdvance(label)); _resizeWidget->setMinimumHeight(_resizeWidget->sizeHint().height()); - _resizeWidget->setAlignment(Qt::AlignCenter); + _resizeWidget->setAlignment(Qt::AlignCenter); - _resizeWidget->setStyleSheet("background-color:palette(window);border-style:solid;border-width:1px;border-color:palette(dark)"); + _resizeWidget->setStyleSheet(QLatin1String("background-color:palette(window);border-style:solid;border-width:1px;border-color:palette(dark)")); - _resizeTimer = new QTimer(this); - _resizeTimer->setSingleShot(true); + _resizeTimer = new QTimer(this); + _resizeTimer->setSingleShot(true); connect(_resizeTimer, SIGNAL(timeout()), _resizeWidget, SLOT(hide())); - } - QString sizeStr; - sizeStr.sprintf("Size: %d x %d", _columns, _lines); - _resizeWidget->setText(sizeStr); + _resizeWidget->setText(tr("Size: %1 x %2").arg(_columns).arg(_lines)); _resizeWidget->move((width()-_resizeWidget->width())/2, (height()-_resizeWidget->height())/2+20); _resizeWidget->show(); @@ -1055,11 +1311,11 @@ void TerminalDisplay::showResizeNotification() void TerminalDisplay::setBlinkingCursor(bool blink) { _hasBlinkingCursor=blink; - - if (blink && !_blinkCursorTimer->isActive()) - _blinkCursorTimer->start(BLINK_DELAY); - - if (!blink && _blinkCursorTimer->isActive()) + + if (blink && !_blinkCursorTimer->isActive()) + _blinkCursorTimer->start(QApplication::cursorFlashTime() / 2); + + if (!blink && _blinkCursorTimer->isActive()) { _blinkCursorTimer->stop(); if (_cursorBlinking) @@ -1069,30 +1325,156 @@ void TerminalDisplay::setBlinkingCursor(bool blink) } } +void TerminalDisplay::setBlinkingTextEnabled(bool blink) +{ + _allowBlinkingText = blink; + + if (blink && !_blinkTimer->isActive()) + _blinkTimer->start(TEXT_BLINK_DELAY); + + if (!blink && _blinkTimer->isActive()) + { + _blinkTimer->stop(); + _blinking = false; + } +} + +void TerminalDisplay::focusOutEvent(QFocusEvent*) +{ + emit termLostFocus(); + // trigger a repaint of the cursor so that it is both visible (in case + // it was hidden during blinking) + // and drawn in a focused out state + _cursorBlinking = false; + updateCursor(); + + _blinkCursorTimer->stop(); + if (_blinking) + blinkEvent(); + + _blinkTimer->stop(); +} +void TerminalDisplay::focusInEvent(QFocusEvent*) +{ + emit termGetFocus(); + if (_hasBlinkingCursor) + { + _blinkCursorTimer->start(); + } + updateCursor(); + + if (_hasBlinker) + _blinkTimer->start(); +} + void TerminalDisplay::paintEvent( QPaintEvent* pe ) { -//qDebug("%s %d paintEvent", __FILE__, __LINE__); QPainter paint(this); + QRect cr = contentsRect(); - foreach (QRect rect, (pe->region() & contentsRect()).rects()) + if ( !_backgroundImage.isNull() ) { - drawBackground(paint,rect,palette().background().color(), true /* use opacity setting */); - drawContents(paint, rect); + QColor background = _colorTable[DEFAULT_BACK_COLOR].color; + if (_opacity < static_cast(1)) + { + background.setAlphaF(_opacity); + paint.save(); + paint.setCompositionMode(QPainter::CompositionMode_Source); + paint.fillRect(cr, background); + paint.restore(); + } + else + { + paint.fillRect(cr, background); + } + + paint.save(); + paint.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); + + if (_backgroundMode == Stretch) + { // scale the image without keeping its proportions to fill the screen + paint.drawPixmap(cr, _backgroundImage, _backgroundImage.rect()); + } + else if (_backgroundMode == Zoom) + { // zoom in/out the image to fit it + QRect r = _backgroundImage.rect(); + qreal wRatio = static_cast(cr.width()) / r.width(); + qreal hRatio = static_cast(cr.height()) / r.height(); + if (wRatio > hRatio) + { + r.setWidth(qRound(r.width() * hRatio)); + r.setHeight(cr.height()); + } + else + { + r.setHeight(qRound(r.height() * wRatio)); + r.setWidth(cr.width()); + } + r.moveCenter(cr.center()); + paint.drawPixmap(r, _backgroundImage, _backgroundImage.rect()); + } + else if (_backgroundMode == Fit) + { // if the image is bigger than the terminal, zoom it out to fit it + QRect r = _backgroundImage.rect(); + qreal wRatio = static_cast(cr.width()) / r.width(); + qreal hRatio = static_cast(cr.height()) / r.height(); + if (r.width() > cr.width()) + { + if (wRatio <= hRatio) + { + r.setHeight(qRound(r.height() * wRatio)); + r.setWidth(cr.width()); + } + else + { + r.setWidth(qRound(r.width() * hRatio)); + r.setHeight(cr.height()); + } + } + else if (r.height() > cr.height()) + { + r.setWidth(qRound(r.width() * hRatio)); + r.setHeight(cr.height()); + } + r.moveCenter(cr.center()); + paint.drawPixmap(r, _backgroundImage, _backgroundImage.rect()); + } + else if (_backgroundMode == Center) + { // center the image without scaling/zooming + QRect r = _backgroundImage.rect(); + r.moveCenter(cr.center()); + paint.drawPixmap(r.topLeft(), _backgroundImage); + } + else //if (_backgroundMode == None) + { + paint.drawPixmap(0, 0, _backgroundImage); + } + + paint.restore(); + } + + if(_drawTextTestFlag) + { + calDrawTextAdditionHeight(paint); + } + + const QRegion regToDraw = pe->region() & cr; + for (auto rect = regToDraw.begin(); rect != regToDraw.end(); rect++) + { + drawBackground(paint,*rect,palette().window().color(), + true /* use opacity setting */); + drawContents(paint, *rect); } -// drawBackground(paint,contentsRect(),palette().background().color(), true /* use opacity setting */); -// drawContents(paint, contentsRect()); drawInputMethodPreeditString(paint,preeditRect()); paintFilters(paint); - - paint.end(); } QPoint TerminalDisplay::cursorPosition() const { - if (_screenWindow) - return _screenWindow->cursorPosition(); - else - return QPoint(0,0); + if (_screenWindow) + return _screenWindow->cursorPosition(); + else + return {0,0}; } QRect TerminalDisplay::preeditRect() const @@ -1100,20 +1482,20 @@ QRect TerminalDisplay::preeditRect() const const int preeditLength = string_width(_inputMethodData.preeditString); if ( preeditLength == 0 ) - return QRect(); + return {}; 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() ) { + if ( _inputMethodData.preeditString.empty() ) return; - } - const QPoint cursorPos = cursorPosition(); + + const QPoint cursorPos = cursorPosition(); bool invertColors = false; const QColor background = _colorTable[DEFAULT_BACK_COLOR].color; @@ -1124,7 +1506,7 @@ void TerminalDisplay::drawInputMethodPreeditString(QPainter& painter , const QRe drawCursor(painter,rect,foreground,background,invertColors); drawCharacters(painter,rect,_inputMethodData.preeditString,style,invertColors); - _inputMethodData.previousPreeditRect = rect; + _inputMethodData.previousPreeditRect = rect; } FilterChain* TerminalDisplay::filterChain() const @@ -1134,19 +1516,22 @@ FilterChain* TerminalDisplay::filterChain() const void TerminalDisplay::paintFilters(QPainter& painter) { -//qDebug("%s %d paintFilters", __FILE__, __LINE__); - // get color of character under mouse and use it to draw // lines for filters QPoint cursorPos = mapFromGlobal(QCursor::pos()); int cursorLine; int cursorColumn; + int leftMargin = _leftBaseMargin + + ((_scrollbarLocation == QTermWidget::ScrollBarLeft + && !_scrollBar->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, _scrollBar)) + ? _scrollBar->width() : 0); + 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 + // iterate over hotspots identified by the display's currently active filters // and draw appropriate visuals to indicate the presence of the hotspot QList spots = _filterChain->hotSpots(); @@ -1155,17 +1540,47 @@ void TerminalDisplay::paintFilters(QPainter& painter) { Filter::HotSpot* spot = iter.next(); + QRegion region; + if ( spot->type() == Filter::HotSpot::Link ) { + QRect r; + if (spot->startLine()==spot->endLine()) { + r.setCoords( spot->startColumn()*_fontWidth + 1 + leftMargin, + spot->startLine()*_fontHeight + 1 + _topBaseMargin, + spot->endColumn()*_fontWidth - 1 + leftMargin, + (spot->endLine()+1)*_fontHeight - 1 + _topBaseMargin ); + region |= r; + } else { + r.setCoords( spot->startColumn()*_fontWidth + 1 + leftMargin, + spot->startLine()*_fontHeight + 1 + _topBaseMargin, + _columns*_fontWidth - 1 + leftMargin, + (spot->startLine()+1)*_fontHeight - 1 + _topBaseMargin ); + region |= r; + for ( int line = spot->startLine()+1 ; line < spot->endLine() ; line++ ) { + r.setCoords( 0*_fontWidth + 1 + leftMargin, + line*_fontHeight + 1 + _topBaseMargin, + _columns*_fontWidth - 1 + leftMargin, + (line+1)*_fontHeight - 1 + _topBaseMargin ); + region |= r; + } + r.setCoords( 0*_fontWidth + 1 + leftMargin, + spot->endLine()*_fontHeight + 1 + _topBaseMargin, + spot->endColumn()*_fontWidth - 1 + leftMargin, + (spot->endLine()+1)*_fontHeight - 1 + _topBaseMargin ); + region |= r; + } + } + for ( int line = spot->startLine() ; line <= spot->endLine() ; line++ ) { int startColumn = 0; - int endColumn = _columns-1; // TODO use number of _columns which are actually - // occupied on this line rather than the width of the + int endColumn = _columns-1; // TODO use number of _columns which are actually + // occupied on this line rather than the width of the // display in _columns // ignore whitespace at the end of the lines while ( QChar(_image[loc(endColumn,line)].character).isSpace() && endColumn > 0 ) endColumn--; - + // increment here because the column which we want to set 'endColumn' to // is the first whitespace character at the end of the line endColumn++; @@ -1181,27 +1596,28 @@ void TerminalDisplay::paintFilters(QPainter& painter) // hotspots // // subtracting one pixel from all sides also prevents an edge case where - // moving the mouse outside a link could still leave it underlined + // moving the mouse outside a link could still leave it underlined // because the check below for the position of the cursor // finds it on the border of the target area QRect r; - r.setCoords( startColumn*_fontWidth + 1, line*_fontHeight + 1, - endColumn*_fontWidth - 1, (line+1)*_fontHeight - 1 ); - - // Underline link hotspots + r.setCoords( startColumn*_fontWidth + 1 + leftMargin, + line*_fontHeight + 1 + _topBaseMargin, + endColumn*_fontWidth - 1 + leftMargin, + (line+1)*_fontHeight - 1 + _topBaseMargin ); + // 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 , + if ( region.contains( mapFromGlobal(QCursor::pos()) ) ){ + painter.drawLine( r.left() , underlinePos , r.right() , underlinePos ); + } } // Marker hotspots simply have a transparent rectanglular shape // drawn on top of them @@ -1213,28 +1629,44 @@ void TerminalDisplay::paintFilters(QPainter& painter) } } } + +int TerminalDisplay::textWidth(const int startColumn, const int length, const int line) const +{ + QFontMetrics fm(font()); + int result = 0; + for (int column = 0; column < length; column++) { + result += fm.horizontalAdvance(_image[loc(startColumn + column, line)].character); + } + return result; +} + +QRect TerminalDisplay::calculateTextArea(int topLeftX, int topLeftY, int startColumn, int line, int length) { + int left = _fixedFont ? _fontWidth * startColumn : textWidth(0, startColumn, line); + int top = _fontHeight * line; + int width = _fixedFont ? _fontWidth * length : textWidth(startColumn, length, line); + return {_leftMargin + topLeftX + left, + _topMargin + topLeftY + top, + width, + _fontHeight}; +} + void TerminalDisplay::drawContents(QPainter &paint, const QRect &rect) { -//qDebug("%s %d drawContents and rect x=%d y=%d w=%d h=%d", __FILE__, __LINE__, rect.x(), rect.y(),rect.width(),rect.height()); - QPoint tL = contentsRect().topLeft(); -// int tLx = tL.x(); + int tLx = tL.x(); int tLy = tL.y(); - int tLx = (_contentWidth - _usedColumns * _fontWidth)/2; -// int tLy = (_contentHeight - _usedLines * _fontHeight)/2; -//qDebug("%d %d %d %d", tLx, tLy, _contentWidth, _usedColumns * _fontWidth); - int lux = qMin(_usedColumns-1, qMax(0,(rect.left() - tLx - _leftMargin ) / _fontWidth)); - int luy = qMin(_usedLines-1, qMax(0, (rect.top() - tLy - _topMargin ) / _fontHeight)); - int rlx = qMin(_usedColumns-1, qMax(0, (rect.right() - tLx - _leftMargin ) / _fontWidth)); - int rly = qMin(_usedLines-1, qMax(0, (rect.bottom() - tLy - _topMargin ) / _fontHeight)); + int luy = qMin(_usedLines-1, qMax(0,(rect.top() - tLy - _topMargin ) / _fontHeight)); + int rlx = qMin(_usedColumns-1, qMax(0,(rect.right() - tLx - _leftMargin ) / _fontWidth)); + int rly = qMin(_usedLines-1, qMax(0,(rect.bottom() - tLy - _topMargin ) / _fontHeight)); const int bufferSize = _usedColumns; - QChar *disstrU = new QChar[bufferSize]; + std::wstring unistr; + unistr.reserve(bufferSize); for (int y = luy; y <= rly; y++) { - quint16 c = _image[loc(lux,y)].character; + quint32 c = _image[loc(lux,y)].character; int x = lux; if(!c && x) x--; // Search for start of multi-column character @@ -1243,6 +1675,9 @@ void TerminalDisplay::drawContents(QPainter &paint, const QRect &rect) int len = 1; int p = 0; + // reset our buffer to the maximal size + unistr.resize(bufferSize); + // is this a single character or a sequence of characters ? if ( _image[loc(x,y)].rendition & RE_EXTENDED_CHAR ) { @@ -1250,10 +1685,10 @@ void TerminalDisplay::drawContents(QPainter &paint, const QRect &rect) ushort extendedCharLength = 0; ushort* chars = ExtendedCharTable::instance .lookupExtendedChar(_image[loc(x,y)].charSequence,extendedCharLength); - for ( int index = 0 ; index < extendedCharLength ; index++ ) + for ( int index = 0 ; index < extendedCharLength ; index++ ) { Q_ASSERT( p < bufferSize ); - disstrU[p++] = chars[index]; + unistr[p++] = chars[index]; } } else @@ -1263,7 +1698,7 @@ void TerminalDisplay::drawContents(QPainter &paint, const QRect &rect) if (c) { Q_ASSERT( p < bufferSize ); - disstrU[p++] = c; //fontMap(c); + unistr[p++] = c; //fontMap(c); } } @@ -1272,7 +1707,7 @@ void TerminalDisplay::drawContents(QPainter &paint, const QRect &rect) CharacterColor currentForeground = _image[loc(x,y)].foregroundColor; CharacterColor currentBackground = _image[loc(x,y)].backgroundColor; quint8 currentRendition = _image[loc(x,y)].rendition; - + while (x+len <= rlx && _image[loc(x+len,y)].foregroundColor == currentForeground && _image[loc(x+len,y)].backgroundColor == currentBackground && @@ -1281,7 +1716,7 @@ void TerminalDisplay::drawContents(QPainter &paint, const QRect &rect) isLineChar( c = _image[loc(x+len,y)].character) == lineDraw) // Assignment! { if (c) - disstrU[p++] = c; //fontMap(c); + unistr[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++; @@ -1289,76 +1724,73 @@ void TerminalDisplay::drawContents(QPainter &paint, const QRect &rect) if ((x+len < _usedColumns) && (!_image[loc(x+len,y)].character)) len++; // Adjust for trailing part of multi-column character - bool save__fixedFont = _fixedFont; + bool save__fixedFont = _fixedFont; if (lineDraw) _fixedFont = false; - if (doubleWidth) - _fixedFont = false; - QString unistr(disstrU,p); - - if (y < _lineProperties.size()) - { - if (_lineProperties[y] & LINE_DOUBLEWIDTH) { - paint.scale(2,1); - } - - if (_lineProperties[y] & LINE_DOUBLEHEIGHT) { - paint.scale(1,2); - } - } + unistr.resize(p); - //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 + // Create a text scaling matrix for double width and double height lines. + QTransform textScale; + + if (y < _lineProperties.size()) + { + if (_lineProperties[y] & LINE_DOUBLEWIDTH) + textScale.scale(2,1); + + if (_lineProperties[y] & LINE_DOUBLEHEIGHT) + textScale.scale(1,2); + } + + //Apply text scaling matrix. + paint.setWorldTransform(textScale, true); + + //calculate the area in which the text will be drawn + QRect textArea = calculateTextArea(tLx, tLy, x, y, len); + + //move the calculated area to take account of scaling applied to the painter. + //the position of the area from the origin (0,0) is scaled //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()) ); + //transformation has been applied to the painter. this ensures that + //painting does actually start from textArea.topLeft() + //(instead of textArea.topLeft() * painter-scale) + textArea.moveTopLeft( textScale.inverted().map(textArea.topLeft()) ); - - //paint text fragment - drawTextFragment( paint, - textArea, - unistr, - &_image[loc(x,y)] ); //, - //0, - //!_isPrinting ); - - _fixedFont = save__fixedFont; - - //reset back to single-width, single-height _lines - paint.resetMatrix(); + //paint text fragment + drawTextFragment( paint, + textArea, + unistr, + &_image[loc(x,y)] ); //, + //0, + //!_isPrinting ); - if (y < _lineProperties.size()-1) - { - //double-height _lines are represented by two adjacent _lines + _fixedFont = save__fixedFont; + + //reset back to single-width, single-height _lines + paint.setWorldTransform(textScale.inverted(), true); + + if (y < _lineProperties.size()-1) + { + //double-height _lines are represented by two adjacent _lines //containing the same characters - //both _lines will have the LINE_DOUBLEHEIGHT attribute. - //If the current line has the LINE_DOUBLEHEIGHT attribute, + //both _lines will have the LINE_DOUBLEHEIGHT attribute. + //If the current line has the LINE_DOUBLEHEIGHT attribute, //we can therefore skip the next line - if (_lineProperties[y] & LINE_DOUBLEHEIGHT) - y++; - } - - x += len - 1; + if (_lineProperties[y] & LINE_DOUBLEHEIGHT) + y++; + } + + x += len - 1; } } - delete [] disstrU; } void TerminalDisplay::blinkEvent() { + if (!_allowBlinkingText) return; + _blinking = !_blinking; - //TODO: Optimise to only repaint the areas of the widget + //TODO: Optimize to only repaint the areas of the widget // where there is blinking text // rather than repainting the whole widget. update(); @@ -1366,7 +1798,6 @@ void TerminalDisplay::blinkEvent() 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() ); @@ -1376,13 +1807,16 @@ QRect TerminalDisplay::imageToWidget(const QRect& imageArea) const return result; } +void TerminalDisplay::updateCursor() +{ + QRect cursorRect = imageToWidget( QRect(cursorPosition(),QSize(1,1)) ); + update(cursorRect); +} + void TerminalDisplay::blinkCursorEvent() { _cursorBlinking = !_cursorBlinking; - - QRect cursorRect = imageToWidget( QRect(cursorPosition(),QSize(1,1)) ); - - update(cursorRect); + updateCursor(); } /* ------------------------------------------------------------------------- */ @@ -1394,6 +1828,7 @@ void TerminalDisplay::blinkCursorEvent() void TerminalDisplay::resizeEvent(QResizeEvent*) { updateImageSize(); + processFilters(); } void TerminalDisplay::propagateSize() @@ -1412,21 +1847,19 @@ void TerminalDisplay::propagateSize() 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++) + for (int line = 0; line < lines; line++) { memcpy((void*)&_image[_columns*line], (void*)&oldimg[oldcol*line],columns*sizeof(Character)); @@ -1435,25 +1868,24 @@ void TerminalDisplay::updateImageSize() } if (_screenWindow) - _screenWindow->setWindowLines(_lines); + _screenWindow->setWindowLines(_lines); _resizing = (oldlin!=_lines) || (oldcol!=_columns); if ( _resizing ) { - showResizeNotification(); + showResizeNotification(); emit changedContentSizeSignal(_contentHeight, _contentWidth); // expose resizeEvent } - + _resizing = false; } -//showEvent and hideEvent are reimplemented here so that it appears to other classes that the +//showEvent and hideEvent are reimplemented here so that it appears to other classes that the //display has been resized when the display is hidden or shown. // -//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 +//the same signal as the one for a content size change void TerminalDisplay::showEvent(QShowEvent*) { emit changedContentSizeSignal(_contentHeight,_contentWidth); @@ -1471,13 +1903,13 @@ void TerminalDisplay::hideEvent(QHideEvent*) void TerminalDisplay::scrollBarPositionChanged(int) { - if ( !_screenWindow ) + if ( !_screenWindow ) return; _screenWindow->scrollTo( _scrollBar->value() ); // if the thumb has been moved to the bottom of the _scrollBar then set - // the display to automatically track new output, + // the display to automatically track new output, // that is, scroll down automatically // to how new _lines as they are added const bool atEndOfOutput = (_scrollBar->value() == _scrollBar->maximum()); @@ -1488,7 +1920,6 @@ void TerminalDisplay::scrollBarPositionChanged(int) void TerminalDisplay::setScroll(int cursor, int slines) { -//qDebug("%s %d setScroll", __FILE__, __LINE__); // update _scrollBar if the range or value has changed, // otherwise return // @@ -1509,20 +1940,29 @@ void TerminalDisplay::setScroll(int cursor, int slines) connect(_scrollBar, SIGNAL(valueChanged(int)), this, SLOT(scrollBarPositionChanged(int))); } -void TerminalDisplay::setScrollBarPosition(ScrollBarPosition position) +void TerminalDisplay::scrollToEnd() { - if (_scrollbarLocation == position) { -// return; - } - - if ( position == NoScrollBar ) + disconnect(_scrollBar, SIGNAL(valueChanged(int)), this, SLOT(scrollBarPositionChanged(int))); + _scrollBar->setValue( _scrollBar->maximum() ); + connect(_scrollBar, SIGNAL(valueChanged(int)), this, SLOT(scrollBarPositionChanged(int))); + + _screenWindow->scrollTo( _scrollBar->value() + 1 ); + _screenWindow->setTrackOutput( _screenWindow->atEndOfOutput() ); +} + +void TerminalDisplay::setScrollBarPosition(QTermWidget::ScrollBarPosition position) +{ + if (_scrollbarLocation == position) + return; + + if ( position == QTermWidget::NoScrollBar ) _scrollBar->hide(); - else - _scrollBar->show(); + else + _scrollBar->show(); _topMargin = _leftMargin = 1; _scrollbarLocation = position; - + propagateSize(); update(); } @@ -1535,7 +1975,7 @@ void TerminalDisplay::mousePressEvent(QMouseEvent* ev) } if ( !contentsRect().contains(ev->pos()) ) return; - + if ( !_screenWindow ) return; int charLine; @@ -1551,11 +1991,11 @@ void TerminalDisplay::mousePressEvent(QMouseEvent* ev) emit isBusySelecting(true); // Keep it steady... // Drag only when the Control key is hold bool selected = false; - + // The receiver of the testIsSelected() signal will adjust // 'selected' accordingly. //emit testIsSelected(pos.x(), pos.y(), selected); - + selected = _screenWindow->isSelected(pos.x(),pos.y()); if ((!_ctrlDrag || ev->modifiers() & Qt::ControlModifier) && selected ) { @@ -1578,32 +2018,31 @@ void TerminalDisplay::mousePressEvent(QMouseEvent* ev) 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); } + + Filter::HotSpot *spot = _filterChain->hotSpotAt(charLine, charColumn); + if (spot && spot->type() == Filter::HotSpot::Link) + spot->activate(QLatin1String("click-action")); } } - else if ( ev->button() == Qt::MidButton ) + else if ( ev->button() == Qt::MiddleButton ) { - if ( _mouseMarks || (!_mouseMarks && (ev->modifiers() & Qt::ShiftModifier)) ) + if ( _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() - ); - } + if (_mouseMarks || (ev->modifiers() & Qt::ShiftModifier)) + emit configureRequest(ev->pos()); else - emit mouseSignal( 2, charColumn +1, charLine +1 +_scrollBar->value() -_scrollBar->maximum() , 0); + emit mouseSignal( 2, charColumn +1, charLine +1 +_scrollBar->value() -_scrollBar->maximum() , 0); } } @@ -1621,80 +2060,105 @@ void TerminalDisplay::mouseMoveEvent(QMouseEvent* ev) { int charLine = 0; int charColumn = 0; + int leftMargin = _leftBaseMargin + + ((_scrollbarLocation == QTermWidget::ScrollBarLeft + && !_scrollBar->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, _scrollBar)) + ? _scrollBar->width() : 0); - getCharacterPosition(ev->pos(),charLine,charColumn); + getCharacterPosition(ev->pos(),charLine,charColumn); // handle filters // change link hot-spot appearance on mouse-over Filter::HotSpot* spot = _filterChain->hotSpotAt(charLine,charColumn); if ( spot && spot->type() == Filter::HotSpot::Link) { - 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 ); + QRegion previousHotspotArea = _mouseOverHotspotArea; + _mouseOverHotspotArea = QRegion(); + QRect r; + if (spot->startLine()==spot->endLine()) { + r.setCoords( spot->startColumn()*_fontWidth + leftMargin, + spot->startLine()*_fontHeight + _topBaseMargin, + spot->endColumn()*_fontWidth + leftMargin, + (spot->endLine()+1)*_fontHeight - 1 + _topBaseMargin ); + _mouseOverHotspotArea |= r; + } else { + r.setCoords( spot->startColumn()*_fontWidth + leftMargin, + spot->startLine()*_fontHeight + _topBaseMargin, + _columns*_fontWidth - 1 + leftMargin, + (spot->startLine()+1)*_fontHeight + _topBaseMargin ); + _mouseOverHotspotArea |= r; + for ( int line = spot->startLine()+1 ; line < spot->endLine() ; line++ ) { + r.setCoords( 0*_fontWidth + leftMargin, + line*_fontHeight + _topBaseMargin, + _columns*_fontWidth + leftMargin, + (line+1)*_fontHeight + _topBaseMargin ); + _mouseOverHotspotArea |= r; + } + r.setCoords( 0*_fontWidth + leftMargin, + spot->endLine()*_fontHeight + _topBaseMargin, + spot->endColumn()*_fontWidth + leftMargin, + (spot->endLine()+1)*_fontHeight + _topBaseMargin ); + _mouseOverHotspotArea |= r; } update( _mouseOverHotspotArea | previousHotspotArea ); } - else if ( _mouseOverHotspotArea.isValid() ) + else if ( !_mouseOverHotspotArea.isEmpty() ) { update( _mouseOverHotspotArea ); // set hotspot area to an invalid rectangle - _mouseOverHotspotArea = QRect(); + _mouseOverHotspotArea = QRegion(); } - + // for auto-hiding the cursor, we need mouseTracking if (ev->buttons() == Qt::NoButton ) return; - // if the terminal is interested in mouse movements + // if the terminal is interested in mouse movements // then emit a mouse movement signal, unless the shift // key is being held down, which overrides this. if (!_mouseMarks && !(ev->modifiers() & Qt::ShiftModifier)) { - int button = 3; - if (ev->buttons() & Qt::LeftButton) - button = 0; - if (ev->buttons() & Qt::MidButton) - button = 1; - if (ev->buttons() & Qt::RightButton) - button = 2; + int button = 3; + if (ev->buttons() & Qt::LeftButton) + button = 0; + if (ev->buttons() & Qt::MiddleButton) + button = 1; + if (ev->buttons() & Qt::RightButton) + button = 2; - - emit mouseSignal( button, + + emit mouseSignal( button, charColumn + 1, charLine + 1 +_scrollBar->value() -_scrollBar->maximum(), - 1 ); - - return; + 1 ); + + return; } - - if (dragInfo.state == diPending) + + if (dragInfo.state == diPending) { // we had a mouse down, but haven't confirmed a drag yet // if the mouse has moved sufficiently, we will confirm - int distance = 10; //KGlobalSettings::dndEventDelay(); +// int distance = KGlobalSettings::dndEventDelay(); + int distance = QApplication::startDragDistance(); +#if QT_VERSION >= 0x060000 + if ( ev->position().x() > dragInfo.start.x() + distance || ev->position().x() < dragInfo.start.x() - distance || + ev->position().y() > dragInfo.start.y() + distance || ev->position().y() < dragInfo.start.y() - distance) +#else if ( ev->x() > dragInfo.start.x() + distance || ev->x() < dragInfo.start.x() - distance || - ev->y() > dragInfo.start.y() + distance || ev->y() < dragInfo.start.y() - distance) + ev->y() > dragInfo.start.y() + distance || ev->y() < dragInfo.start.y() - distance) +#endif { // we've left the drag square, we can start a real drag operation now emit isBusySelecting(false); // Ok.. we can breath again. - + _screenWindow->clearSelection(); doDrag(); } return; - } - else if (dragInfo.state == diDragging) + } + else if (dragInfo.state == diDragging) { // this isn't technically needed because mouseMoveEvent is suppressed during // Qt drag operations, replaced by dragMoveEvent @@ -1704,18 +2168,11 @@ void TerminalDisplay::mouseMoveEvent(QMouseEvent* ev) if (_actSel == 0) return; // don't extend selection while pasting - if (ev->buttons() & Qt::MidButton) return; + if (ev->buttons() & Qt::MiddleButton) return; extendSelection( ev->pos() ); } -#if 0 -void TerminalDisplay::setSelectionEnd() -{ - extendSelection( _configureRequestPoint ); -} -#endif - void TerminalDisplay::extendSelection( const QPoint& position ) { QPoint pos = position; @@ -1733,24 +2190,28 @@ void TerminalDisplay::extendSelection( const QPoint& position ) // 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 ); + int linesBeyondWidget = 0; - if ( pos.y() == tLy+_topMargin+_usedLines*_fontHeight-1 ) + QRect textBounds(tLx + _leftMargin, + tLy + _topMargin, + _usedColumns*_fontWidth-1, + _usedLines*_fontHeight-1); + + // Adjust position within text area bounds. + QPoint oldpos = pos; + + pos.setX( qBound(textBounds.left(),pos.x(),textBounds.right()) ); + pos.setY( qBound(textBounds.top(),pos.y(),textBounds.bottom()) ); + + if ( oldpos.y() > textBounds.bottom() ) { - _scrollBar->setValue(_scrollBar->value()+yMouseScroll); // scrollforward + linesBeyondWidget = (oldpos.y()-textBounds.bottom()) / _fontHeight; + _scrollBar->setValue(_scrollBar->value()+linesBeyondWidget+1); // scrollforward } - if ( pos.y() == tLy+_topMargin ) + if ( oldpos.y() < textBounds.top() ) { - _scrollBar->setValue(_scrollBar->value()-yMouseScroll); // scrollback + linesBeyondWidget = (textBounds.top()-oldpos.y()) / _fontHeight; + _scrollBar->setValue(_scrollBar->value()-linesBeyondWidget-1); // history } int charColumn = 0; @@ -1769,12 +2230,12 @@ void TerminalDisplay::extendSelection( const QPoint& position ) { // Extend to word boundaries int i; - int selClass; + QChar selClass; bool left_not_right = ( here.y() < _iPntSelCorr.y() || - here.y() == _iPntSelCorr.y() && here.x() < _iPntSelCorr.x() ); + ( here.y() == _iPntSelCorr.y() && here.x() < _iPntSelCorr.x() ) ); bool old_left_not_right = ( _pntSelCorr.y() < _iPntSelCorr.y() || - _pntSelCorr.y() == _iPntSelCorr.y() && _pntSelCorr.x() < _iPntSelCorr.x() ); + ( _pntSelCorr.y() == _iPntSelCorr.y() && _pntSelCorr.x() < _iPntSelCorr.x() ) ); swapping = left_not_right != old_left_not_right; // Find left (left_not_right ? from here : from start) @@ -1782,8 +2243,8 @@ void TerminalDisplay::extendSelection( const QPoint& position ) i = loc(left.x(),left.y()); if (i>=0 && i<=_imageSize) { selClass = charClass(_image[i].character); - while ( ((left.x()>0) || (left.y()>0 && (_lineProperties[left.y()-1] & LINE_WRAPPED) )) - && charClass(_image[i-1].character) == selClass ) + 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()--;} } } @@ -1792,8 +2253,8 @@ void TerminalDisplay::extendSelection( const QPoint& position ) i = loc(right.x(),right.y()); if (i>=0 && i<=_imageSize) { selClass = charClass(_image[i].character); - while( ((right.x()<_usedColumns-1) || (right.y()<_usedLines-1 && (_lineProperties[right.y()] & LINE_WRAPPED) )) - && charClass(_image[i+1].character) == selClass ) + 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()++; } } } @@ -1846,12 +2307,12 @@ void TerminalDisplay::extendSelection( const QPoint& position ) if ( !_wordSelectionMode && !_lineSelectionMode ) { int i; - int selClass; + QChar selClass; bool left_not_right = ( here.y() < _iPntSelCorr.y() || - here.y() == _iPntSelCorr.y() && here.x() < _iPntSelCorr.x() ); + ( here.y() == _iPntSelCorr.y() && here.x() < _iPntSelCorr.x() ) ); bool old_left_not_right = ( _pntSelCorr.y() < _iPntSelCorr.y() || - _pntSelCorr.y() == _iPntSelCorr.y() && _pntSelCorr.x() < _iPntSelCorr.x() ); + ( _pntSelCorr.y() == _iPntSelCorr.y() && _pntSelCorr.x() < _iPntSelCorr.x() ) ); swapping = left_not_right != old_left_not_right; // Find left (left_not_right ? from here : from start) @@ -1864,16 +2325,16 @@ void TerminalDisplay::extendSelection( const QPoint& position ) i = loc(right.x(),right.y()); if (i>=0 && i<=_imageSize) { selClass = charClass(_image[i-1].character); - if (selClass == ' ') + /* if (selClass == ' ') { - while ( right.x() < _usedColumns-1 && charClass(_image[i+1].character) == selClass && (right.y()<_usedLines-1) && - !(_lineProperties[right.y()] & LINE_WRAPPED)) + 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; - } + }*/ } } @@ -1931,7 +2392,7 @@ void TerminalDisplay::mouseReleaseEvent(QMouseEvent* ev) if ( ev->button() == Qt::LeftButton) { - emit isBusySelecting(false); + emit isBusySelecting(false); if(dragInfo.state == diPending) { // We had a drag event pending but never confirmed. Kill selection @@ -1952,39 +2413,45 @@ void TerminalDisplay::mouseReleaseEvent(QMouseEvent* ev) // applies here, too. if (!_mouseMarks && !(ev->modifiers() & Qt::ShiftModifier)) - emit mouseSignal( 3, // release + emit mouseSignal( 0, charColumn + 1, - charLine + 1 +_scrollBar->value() -_scrollBar->maximum() , 0); + charLine + 1 +_scrollBar->value() -_scrollBar->maximum() , 2); } dragInfo.state = diNone; } - - - if ( !_mouseMarks && + + if ( !_mouseMarks && ((ev->button() == Qt::RightButton && !(ev->modifiers() & Qt::ShiftModifier)) - || ev->button() == Qt::MidButton) ) + || ev->button() == Qt::MiddleButton) ) { - emit mouseSignal( 3, - charColumn + 1, - charLine + 1 +_scrollBar->value() -_scrollBar->maximum() , - 0); + emit mouseSignal( ev->button() == Qt::MiddleButton ? 1 : 2, + charColumn + 1, + charLine + 1 +_scrollBar->value() -_scrollBar->maximum() , + 2); } } -void TerminalDisplay::getCharacterPosition(const QPoint& widgetPoint,int& line,int& column) const +void TerminalDisplay::getCharacterPosition(const QPointF& 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 ) + if (line < 0) line = 0; + if (line >= _usedLines) + line = _usedLines - 1; + + int x = widgetPoint.x() + _fontWidth / 2 - contentsRect().left() - _leftMargin; + if ( _fixedFont ) + column = x / _fontWidth; + else + { + column = 0; + while(column + 1 < _usedColumns && x > textWidth(0, column + 1, line)) + column++; + } + 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. // @@ -1994,12 +2461,20 @@ void TerminalDisplay::getCharacterPosition(const QPoint& widgetPoint,int& line,i column = _usedColumns; } -void TerminalDisplay::updateLineProperties() +void TerminalDisplay::updateFilters() { - if ( !_screenWindow ) + if ( !_screenWindow ) return; - _lineProperties = _screenWindow->getLineProperties(); + processFilters(); +} + +void TerminalDisplay::updateLineProperties() +{ + if ( !_screenWindow ) + return; + + _lineProperties = _screenWindow->getLineProperties(); } void TerminalDisplay::mouseDoubleClickEvent(QMouseEvent* ev) @@ -2019,8 +2494,8 @@ void TerminalDisplay::mouseDoubleClickEvent(QMouseEvent* ev) { // Send just _ONE_ click event, since the first click of the double click // was already sent by the click handler - emit mouseSignal( 0, - pos.x()+1, + emit mouseSignal( 0, + pos.x()+1, pos.y()+1 +_scrollBar->value() -_scrollBar->maximum(), 0 ); // left button return; @@ -2036,21 +2511,21 @@ void TerminalDisplay::mouseDoubleClickEvent(QMouseEvent* ev) _wordSelectionMode = true; // find word boundaries... - int selClass = charClass(_image[i].character); + QChar selClass = charClass(_image[i].character); { // find the start of the word int x = bgnSel.x(); - while ( ((x>0) || (bgnSel.y()>0 && (_lineProperties[bgnSel.y()-1] & LINE_WRAPPED) )) - && charClass(_image[i-1].character) == selClass ) - { - i--; - if (x>0) - x--; - else + 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; + x=_usedColumns-1; bgnSel.ry()--; - } + } } bgnSel.setX(x); @@ -2059,31 +2534,32 @@ void TerminalDisplay::mouseDoubleClickEvent(QMouseEvent* ev) // find the end of the word i = loc( endSel.x(), endSel.y() ); x = endSel.x(); - while( ((x<_usedColumns-1) || (endSel.y()<_usedLines-1 && (_lineProperties[endSel.y()] & LINE_WRAPPED) )) - && charClass(_image[i+1].character) == selClass ) - { - i++; - if (x<_usedColumns-1) - x++; - else - { - x=0; - endSel.ry()++; - } + + 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 ) ) + if ( ( QChar( _image[i].character ) == QLatin1Char('@') ) && ( ( endSel.x() - bgnSel.x() ) > 0 ) ) endSel.setX( x - 1 ); _actSel = 2; // within selection - + _screenWindow->setSelectionEnd( endSel.x() , endSel.y() ); - - setSelection( _screenWindow->selectedText(_preserveLineBreaks) ); + + setSelection( _screenWindow->selectedText(_preserveLineBreaks) ); } _possibleTripleClick=true; @@ -2094,20 +2570,49 @@ void TerminalDisplay::mouseDoubleClickEvent(QMouseEvent* ev) void TerminalDisplay::wheelEvent( QWheelEvent* ev ) { - if (ev->orientation() != Qt::Vertical) + if (ev->angleDelta().y() == 0) return; + // if the terminal program is not interested mouse events + // then send the event to the scrollbar if the slider has room to move + // or otherwise send simulated up / down key presses to the terminal program + // for the benefit of programs such as 'less' if ( _mouseMarks ) - _scrollBar->event(ev); + { + bool canScroll = _scrollBar->maximum() > 0; + if (canScroll) + _scrollBar->event(ev); + else + { + // assume that each Up / Down key event will cause the terminal application + // to scroll by one line. + // + // to get a reasonable scrolling speed, scroll by one line for every 5 degrees + // of mouse wheel rotation. Mouse wheels typically move in steps of 15 degrees, + // giving a scroll of 3 lines + int key = ev->angleDelta().y() > 0 ? Qt::Key_Up : Qt::Key_Down; + + // QWheelEvent::angleDelta().y() gives rotation in eighths of a degree + int wheelDegrees = ev->angleDelta().y() / 8; + int linesToScroll = abs(wheelDegrees) / 5; + + QKeyEvent keyScrollEvent(QEvent::KeyPress,key,Qt::NoModifier); + + for (int i=0;ipos() , charLine , charColumn ); - - emit mouseSignal( ev->delta() > 0 ? 4 : 5, - charColumn + 1, - charLine + 1 +_scrollBar->value() -_scrollBar->maximum() , + getCharacterPosition( ev->position() , charLine , charColumn ); + + emit mouseSignal( ev->angleDelta().y() > 0 ? 4 : 5, + charColumn + 1, + charLine + 1 +_scrollBar->value() -_scrollBar->maximum() , 0); } } @@ -2136,26 +2641,26 @@ void TerminalDisplay::mouseTripleClickEvent(QMouseEvent* ev) while (_iPntSel.y()>0 && (_lineProperties[_iPntSel.y()-1] & LINE_WRAPPED) ) _iPntSel.ry()--; - + if (_tripleClickMode == SelectForwardsFromCursor) { // find word boundary start int i = loc(_iPntSel.x(),_iPntSel.y()); - int selClass = charClass(_image[i].character); + QChar selClass = charClass(_image[i].character); int x = _iPntSel.x(); - - while ( ((x>0) || + + while ( ((x>0) || (_iPntSel.y()>0 && (_lineProperties[_iPntSel.y()-1] & LINE_WRAPPED) ) - ) + ) && charClass(_image[i-1].character) == selClass ) { - i--; - if (x>0) - x--; - else + i--; + if (x>0) + x--; + else { - x=_columns-1; + x=_columns-1; _iPntSel.ry()--; - } + } } _screenWindow->setSelectionStart( x , _iPntSel.y() , false ); @@ -2168,7 +2673,7 @@ void TerminalDisplay::mouseTripleClickEvent(QMouseEvent* ev) while (_iPntSel.y()<_lines-1 && (_lineProperties[_iPntSel.y()] & LINE_WRAPPED) ) _iPntSel.ry()++; - + _screenWindow->setSelectionEnd( _columns - 1 , _iPntSel.y() ); setSelection(_screenWindow->selectedText(_preserveLineBreaks)); @@ -2186,33 +2691,43 @@ bool TerminalDisplay::focusNextPrevChild( bool next ) } -int TerminalDisplay::charClass(quint16 ch) const +QChar TerminalDisplay::charClass(QChar qch) const { - QChar qch=QChar(ch); - if ( qch.isSpace() ) return ' '; + if ( qch.isSpace() ) return QLatin1Char(' '); if ( qch.isLetterOrNumber() || _wordCharacters.contains(qch, Qt::CaseInsensitive ) ) - return 'a'; + return QLatin1Char('a'); - // Everything else is weird - return 1; + return qch; } void TerminalDisplay::setWordCharacters(const QString& wc) { - _wordCharacters = wc; + _wordCharacters = wc; } void TerminalDisplay::setUsesMouse(bool on) { - _mouseMarks = on; - setCursor( _mouseMarks ? Qt::IBeamCursor : Qt::ArrowCursor ); + if (_mouseMarks != on) { + _mouseMarks = on; + setCursor( _mouseMarks ? Qt::IBeamCursor : Qt::ArrowCursor ); + emit usesMouseChanged(); + } } bool TerminalDisplay::usesMouse() const { return _mouseMarks; } +void TerminalDisplay::setBracketedPasteMode(bool on) +{ + _bracketedPasteMode = on; +} +bool TerminalDisplay::bracketedPasteMode() const +{ + return _bracketedPasteMode; +} + /* ------------------------------------------------------------------------- */ /* */ /* Clipboard */ @@ -2223,27 +2738,99 @@ bool TerminalDisplay::usesMouse() const void TerminalDisplay::emitSelection(bool useXselection,bool appendReturn) { - if ( !_screenWindow ) + 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"); + text.replace(QLatin1String("\r\n"), QLatin1String("\n")); + text.replace(QLatin1Char('\n'), QLatin1Char('\r')); + + if (_trimPastedTrailingNewlines) { + text.replace(QRegularExpression(QStringLiteral("\\r+$")), QString()); + } + + if (_confirmMultilinePaste && text.contains(QLatin1Char('\r'))) { + if (!multilineConfirmation(text)) { + return; + } + } + + bracketText(text); + + // appendReturn is intentionally handled _after_ enclosing texts with brackets as + // that feature is used to allow execution of commands immediately after paste. + // Ref: https://bugs.kde.org/show_bug.cgi?id=16179 + // Ref: https://github.com/KDE/konsole/commit/83d365f2ebfe2e659c1e857a2f5f247c556ab571 + if(appendReturn) { + text.append(QLatin1Char('\r')); + } + QKeyEvent e(QEvent::KeyPress, 0, Qt::NoModifier, text); - emit keyPressedSignal(&e); // expose as a big fat keypress event - + emit keyPressedSignal(&e, true); // expose as a big fat keypress event + _screenWindow->clearSelection(); + + switch(mMotionAfterPasting) + { + case MoveStartScreenWindow: + // Temporarily stop tracking output, or pasting contents triggers + // ScreenWindow::notifyOutputChanged() and the latter scrolls the + // terminal to the last line. It will be re-enabled when needed + // (e.g., scrolling to the last line). + _screenWindow->setTrackOutput(false); + _screenWindow->scrollTo(0); + break; + case MoveEndScreenWindow: + scrollToEnd(); + break; + case NoMoveScreenWindow: + break; + } } } +void TerminalDisplay::bracketText(QString& text) const +{ + if (bracketedPasteMode() && !_disabledBracketedPasteMode) + { + text.prepend(QLatin1String("\033[200~")); + text.append(QLatin1String("\033[201~")); + } +} + +bool TerminalDisplay::multilineConfirmation(const QString& text) +{ + QMessageBox confirmation(this); + confirmation.setWindowTitle(tr("Paste multiline text")); + confirmation.setText(tr("Are you sure you want to paste this text?")); + confirmation.setDetailedText(text); + confirmation.setStandardButtons(QMessageBox::Yes | QMessageBox::No); + // Click "Show details..." to show those by default + const auto buttons = confirmation.buttons(); + for( QAbstractButton * btn : buttons ) { + if (confirmation.buttonRole(btn) == QMessageBox::ActionRole && btn->text() == QMessageBox::tr("Show Details...")) { + Q_EMIT btn->clicked(); + break; + } + } + confirmation.setDefaultButton(QMessageBox::Yes); + confirmation.exec(); + if (confirmation.standardButton(confirmation.clickedButton()) != QMessageBox::Yes) { + return false; + } + return true; +} + void TerminalDisplay::setSelection(const QString& t) { - QApplication::clipboard()->setText(t, QClipboard::Selection); + if (QApplication::clipboard()->supportsSelection()) + { + QApplication::clipboard()->setText(t, QClipboard::Selection); + } } void TerminalDisplay::copyClipboard() @@ -2252,7 +2839,8 @@ void TerminalDisplay::copyClipboard() return; QString text = _screenWindow->selectedText(_preserveLineBreaks); - QApplication::clipboard()->setText(text); + if (!text.isEmpty()) + QApplication::clipboard()->setText(text); } void TerminalDisplay::pasteClipboard() @@ -2265,6 +2853,15 @@ void TerminalDisplay::pasteSelection() emitSelection(true,false); } + +void TerminalDisplay::setConfirmMultilinePaste(bool confirmMultilinePaste) { + _confirmMultilinePaste = confirmMultilinePaste; +} + +void TerminalDisplay::setTrimPastedTrailingNewlines(bool trimPastedTrailingNewlines) { + _trimPastedTrailingNewlines = trimPastedTrailingNewlines; +} + /* ------------------------------------------------------------------------- */ /* */ /* Keyboard */ @@ -2273,91 +2870,39 @@ void TerminalDisplay::pasteSelection() void TerminalDisplay::setFlowControlWarningEnabled( bool enable ) { - _flowControlWarningEnabled = enable; - - // if the dialog is currently visible and the flow control warning has - // been disabled then hide the dialog - if (!enable) - outputSuspended(false); + _flowControlWarningEnabled = enable; + + // if the dialog is currently visible and the flow control warning has + // been disabled then hide the dialog + if (!enable) + outputSuspended(false); +} + +void TerminalDisplay::setMotionAfterPasting(MotionAfterPasting action) +{ + mMotionAfterPasting = action; +} + +int TerminalDisplay::motionAfterPasting() +{ + return mMotionAfterPasting; } 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) + if (_hasBlinkingCursor) { - _blinkCursorTimer->start(BLINK_DELAY); + _blinkCursorTimer->start(QApplication::cursorFlashTime() / 2); if (_cursorBlinking) blinkCursorEvent(); else _cursorBlinking = false; } - if ( emitKeyPressSignal ) - emit keyPressedSignal(event); + emit keyPressedSignal(event, false); event->accept(); } @@ -2365,19 +2910,19 @@ void TerminalDisplay::keyPressEvent( QKeyEvent* event ) void TerminalDisplay::inputMethodEvent( QInputMethodEvent* event ) { QKeyEvent keyEvent(QEvent::KeyPress,0,Qt::NoModifier,event->commitString()); - emit keyPressedSignal(&keyEvent); + emit keyPressedSignal(&keyEvent, false); - _inputMethodData.preeditString = event->preeditString(); + _inputMethodData.preeditString = event->preeditString().toStdWString(); update(preeditRect() | _inputMethodData.previousPreeditRect); - + event->accept(); } QVariant TerminalDisplay::inputMethodQuery( Qt::InputMethodQuery query ) const { const QPoint cursorPos = _screenWindow ? _screenWindow->cursorPosition() : QPoint(0,0); - switch ( query ) + switch ( query ) { - case Qt::ImMicroFocus: + case Qt::ImCursorRectangle: return imageToWidget(QRect(cursorPos.x(),cursorPos.y(),1,1)); break; case Qt::ImFont: @@ -2394,7 +2939,7 @@ QVariant TerminalDisplay::inputMethodQuery( Qt::InputMethodQuery query ) const QTextStream stream(&lineText); PlainTextDecoder decoder; decoder.begin(&stream); - decoder.decodeLine(&_image[loc(0,cursorPos.y())],_usedColumns,_lineProperties[cursorPos.y()]); + decoder.decodeLine(&_image[loc(0,cursorPos.y())],_usedColumns,0); decoder.end(); return lineText; } @@ -2402,33 +2947,46 @@ QVariant TerminalDisplay::inputMethodQuery( Qt::InputMethodQuery query ) const case Qt::ImCurrentSelection: return QString(); break; + default: + break; } return QVariant(); } -bool TerminalDisplay::event( QEvent *e ) +bool TerminalDisplay::handleShortcutOverrideEvent(QKeyEvent* keyEvent) { - if ( e->type() == QEvent::ShortcutOverride ) - { - QKeyEvent* keyEvent = static_cast( e ); + int modifiers = keyEvent->modifiers(); - // 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() ) + // When a possible shortcut combination is pressed, + // emit the overrideShortcutCheck() signal to allow the host + // to decide whether the terminal should override it or not. + if (modifiers != Qt::NoModifier) { - keyEvent->accept(); - return true; + int modifierCount = 0; + unsigned int currentModifier = Qt::ShiftModifier; + + while (currentModifier <= Qt::KeypadModifier) + { + if (modifiers & currentModifier) + modifierCount++; + currentModifier <<= 1; + } + if (modifierCount < 2) + { + bool override = false; + emit overrideShortcutCheck(keyEvent,override); + if (override) + { + keyEvent->accept(); + return true; + } + } } // Override any of the following shortcuts because // they are needed by the terminal - int keyCode = keyEvent->key() | keyEvent->modifiers(); + int keyCode = keyEvent->key() | modifiers; switch ( keyCode ) { // list is taken from the QLineEdit::event() code @@ -2439,11 +2997,29 @@ bool TerminalDisplay::event( QEvent *e ) case Qt::Key_Backspace: case Qt::Key_Left: case Qt::Key_Right: + case Qt::Key_Escape: keyEvent->accept(); return true; } + return false; +} + +bool TerminalDisplay::event(QEvent* event) +{ + bool eventHandled = false; + switch (event->type()) + { + case QEvent::ShortcutOverride: + eventHandled = handleShortcutOverrideEvent((QKeyEvent*)event); + break; + case QEvent::PaletteChange: + case QEvent::ApplicationPaletteChange: + _scrollBar->setPalette( QApplication::palette() ); + break; + default: + break; } - return QWidget::event( e ); + return eventHandled ? true : QWidget::event(event); } void TerminalDisplay::setBellMode(int mode) @@ -2456,27 +3032,27 @@ void TerminalDisplay::enableBell() _allowBell = true; } -void TerminalDisplay::bell(const QString&) +void TerminalDisplay::bell(const QString& message) { if (_bellMode==NoBell) return; - //limit the rate at which bells can occur - //...mainly for sound effects where rapid bells in sequence + //limit the rate at which bells can occur + //...mainly for sound effects where rapid bells in sequence //produce a horrible noise if ( _allowBell ) { _allowBell = false; QTimer::singleShot(500,this,SLOT(enableBell())); - - if (_bellMode==SystemBeepBell) + + if (_bellMode==SystemBeepBell) { -// KNotification::beep(); - } - else if (_bellMode==NotifyBell) + QApplication::beep(); + } + else if (_bellMode==NotifyBell) { -// KNotification::event("BellVisible", message,QPixmap(),this); - } - else if (_bellMode==VisualBell) + emit notifyBell(message); + } + else if (_bellMode==VisualBell) { swapColorTable(); QTimer::singleShot(200,this,SLOT(swapColorTable())); @@ -2484,6 +3060,11 @@ void TerminalDisplay::bell(const QString&) } } +void TerminalDisplay::selectionChanged() +{ + emit copyAvailable(_screenWindow->selectedText(false).isEmpty() == false); +} + void TerminalDisplay::swapColorTable() { ColorEntry color = _colorTable[1]; @@ -2509,35 +3090,36 @@ void TerminalDisplay::clearImage() void TerminalDisplay::calcGeometry() { - _scrollBar->resize(QApplication::style()->pixelMetric(QStyle::PM_ScrollBarExtent), - contentsRect().height()); + _scrollBar->resize(_scrollBar->sizeHint().width(), contentsRect().height()); + int scrollBarWidth = _scrollBar->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, _scrollBar) + ? 0 : _scrollBar->width(); switch(_scrollbarLocation) { - case NoScrollBar : - _leftMargin = DEFAULT_LEFT_MARGIN; - _contentWidth = contentsRect().width() - 2 * DEFAULT_LEFT_MARGIN; + case QTermWidget::NoScrollBar : + _leftMargin = _leftBaseMargin; + _contentWidth = contentsRect().width() - 2 * _leftBaseMargin; break; - case ScrollBarLeft : - _leftMargin = DEFAULT_LEFT_MARGIN + _scrollBar->width(); - _contentWidth = contentsRect().width() - 2 * DEFAULT_LEFT_MARGIN - _scrollBar->width(); + case QTermWidget::ScrollBarLeft : + _leftMargin = _leftBaseMargin + scrollBarWidth; + _contentWidth = contentsRect().width() - 2 * _leftBaseMargin - scrollBarWidth; _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)); + case QTermWidget::ScrollBarRight: + _leftMargin = _leftBaseMargin; + _contentWidth = contentsRect().width() - 2 * _leftBaseMargin - scrollBarWidth; + _scrollBar->move(contentsRect().topRight() - QPoint(_scrollBar->width()-1, 0)); break; } - _topMargin = DEFAULT_TOP_MARGIN; - _contentHeight = contentsRect().height() - 2 * DEFAULT_TOP_MARGIN + /* mysterious */ 1; + _topMargin = _topBaseMargin; + _contentHeight = contentsRect().height() - 2 * _topBaseMargin + /* 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); @@ -2546,16 +3128,15 @@ void TerminalDisplay::calcGeometry() void TerminalDisplay::makeImage() { -//qDebug("%s %d makeImage", __FILE__, __LINE__); calcGeometry(); - // confirm that array will be of non-zero size, since the painting code + // confirm that array will be of non-zero size, since the painting code // assumes a non-zero array length Q_ASSERT( _lines > 0 && _columns > 0 ); Q_ASSERT( _usedLines <= _lines && _usedColumns <= _columns ); _imageSize=_lines*_columns; - + // We over-commit one character so that we can be more relaxed in dealing with // certain boundary conditions: _image[_imageSize] is a valid but unused position _image = new Character[_imageSize+1]; @@ -2563,16 +3144,17 @@ void TerminalDisplay::makeImage() clearImage(); } -// calculate the needed size +// calculate the needed size, this must be synced with calcGeometry() void TerminalDisplay::setSize(int columns, int lines) { - //FIXME - Not quite correct, a small amount of additional space - // will be used for margins, the scrollbar etc. - // we need to allow for this so that '_size' does allow - // enough room for the specified number of columns and lines to fit + int scrollBarWidth = (_scrollBar->isHidden() + || _scrollBar->style()->styleHint(QStyle::SH_ScrollBar_Transient, nullptr, _scrollBar)) + ? 0 : _scrollBar->sizeHint().width(); + int horizontalMargin = 2 * _leftBaseMargin; + int verticalMargin = 2 * _topBaseMargin; - QSize newSize = QSize( columns * _fontWidth , - lines * _fontHeight ); + QSize newSize = QSize( horizontalMargin + scrollBarWidth + (columns * _fontWidth) , + verticalMargin + (lines * _fontHeight) ); if ( newSize != size() ) { @@ -2584,7 +3166,7 @@ void TerminalDisplay::setSize(int columns, int lines) void TerminalDisplay::setFixedSize(int cols, int lins) { _isFixedSize = true; - + //ensure that display is at least one line by one column in size _columns = qMax(1,cols); _lines = qMax(1,lins); @@ -2614,46 +3196,63 @@ QSize TerminalDisplay::sizeHint() const void TerminalDisplay::dragEnterEvent(QDragEnterEvent* event) { - if (event->mimeData()->hasFormat("text/plain")) + if (event->mimeData()->hasFormat(QLatin1String("text/plain"))) + event->acceptProposedAction(); + if (event->mimeData()->urls().count()) event->acceptProposedAction(); } void TerminalDisplay::dropEvent(QDropEvent* event) { -// KUrl::List urls = KUrl::List::fromMimeData(event->mimeData()); + //KUrl::List urls = KUrl::List::fromMimeData(event->mimeData()); + QList urls = event->mimeData()->urls(); QString dropText; -/* if (!urls.isEmpty()) + if (!urls.isEmpty()) { - for ( int i = 0 ; i < urls.count() ; i++ ) + // TODO/FIXME: escape or quote pasted things if necessary... + qDebug() << "TerminalDisplay: handling urls. It can be broken. Report any errors, please"; + for ( int i = 0 ; i < urls.count() ; i++ ) { - KUrl url = KIO::NetAccess::mostLocalUrl( urls[i] , 0 ); + //KUrl url = KIO::NetAccess::mostLocalUrl( urls[i] , 0 ); + QUrl url = urls[i]; + QString urlText; if (url.isLocalFile()) - urlText = url.path(); + 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; + urlText = url.toString(); - if ( i != urls.count()-1 ) - dropText += ' '; + // 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); + + QChar q(QLatin1Char('\'')); + dropText += q + QString(urlText).replace(q, QLatin1String("'\\''")) + q; + dropText += QLatin1Char(' '); } } - else + else { dropText = event->mimeData()->text(); + + dropText.replace(QLatin1String("\r\n"), QLatin1String("\n")); + dropText.replace(QLatin1Char('\n'), QLatin1Char('\r')); + if (_trimPastedTrailingNewlines) + { + dropText.replace(QRegularExpression(QStringLiteral("\\r+$")), QString()); + } + if (_confirmMultilinePaste && dropText.contains(QLatin1Char('\r'))) + { + if (!multilineConfirmation(dropText)) + { + return; + } + } } -*/ - if(event->mimeData()->hasFormat("text/plain")) - { - emit sendStringToEmu(dropText.toLocal8Bit()); - } + + emit sendStringToEmu(dropText.toLocal8Bit().constData()); } void TerminalDisplay::doDrag() @@ -2663,52 +3262,48 @@ void TerminalDisplay::doDrag() QMimeData *mimeData = new QMimeData; mimeData->setText(QApplication::clipboard()->text(QClipboard::Selection)); dragInfo.dragObject->setMimeData(mimeData); - dragInfo.dragObject->start(Qt::CopyAction); + dragInfo.dragObject->exec(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) - { + //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 + //describing the 'flow control' (Xon/Xoff) feature found in almost //all terminal emulators. //If there isn't a suitable article available in the target language the link //can simply be removed. - _outputSuspendedLabel = new QLabel( ("Output has been " - "suspended" + _outputSuspendedLabel = new QLabel( tr("Output has been " + "suspended" " by pressing Ctrl+S." - " Press Ctrl+Q to resume."), - this ); + " Press Ctrl+Q to resume."), + this ); QPalette palette(_outputSuspendedLabel->palette()); - - palette.setColor(QPalette::Normal, QPalette::WindowText, QColor(Qt::white)); - palette.setColor(QPalette::Normal, QPalette::Window, QColor(Qt::black)); -// KColorScheme::adjustForeground(palette,KColorScheme::NeutralText); -// KColorScheme::adjustBackground(palette,KColorScheme::NeutralBackground); - _outputSuspendedLabel->setPalette(palette); - _outputSuspendedLabel->setAutoFillBackground(true); - _outputSuspendedLabel->setBackgroundRole(QPalette::Base); - _outputSuspendedLabel->setFont(QApplication::font()); - _outputSuspendedLabel->setMargin(5); + //KColorScheme::adjustBackground(palette,KColorScheme::NeutralBackground); + _outputSuspendedLabel->setPalette(palette); + _outputSuspendedLabel->setAutoFillBackground(true); + _outputSuspendedLabel->setBackgroundRole(QPalette::Base); + _outputSuspendedLabel->setFont(QApplication::font()); + _outputSuspendedLabel->setContentsMargins(5, 5, 5, 5); //enable activation of "Xon/Xoff" link in label - _outputSuspendedLabel->setTextInteractionFlags(Qt::LinksAccessibleByMouse | + _outputSuspendedLabel->setTextInteractionFlags(Qt::LinksAccessibleByMouse | Qt::LinksAccessibleByKeyboard); _outputSuspendedLabel->setOpenExternalLinks(true); _outputSuspendedLabel->setVisible(false); - _gridLayout->addWidget(_outputSuspendedLabel); + _gridLayout->addWidget(_outputSuspendedLabel); _gridLayout->addItem( new QSpacerItem(0,0,QSizePolicy::Expanding, QSizePolicy::Expanding), 1,0); } - _outputSuspendedLabel->setVisible(suspended); + _outputSuspendedLabel->setVisible(suspended); } uint TerminalDisplay::lineSpacing() const @@ -2722,4 +3317,74 @@ void TerminalDisplay::setLineSpacing(uint i) setVTFont(font()); // Trigger an update. } -//#include "moc_TerminalDisplay.cpp" +int TerminalDisplay::margin() const +{ + return _topBaseMargin; +} + +void TerminalDisplay::setMargin(int i) +{ + _topBaseMargin = i; + _leftBaseMargin = i; +} + +AutoScrollHandler::AutoScrollHandler(QWidget* parent) +: QObject(parent) +, _timerId(0) +{ + parent->installEventFilter(this); +} +void AutoScrollHandler::timerEvent(QTimerEvent* event) +{ + if (event->timerId() != _timerId) + return; + + QMouseEvent mouseEvent( QEvent::MouseMove, + widget()->mapFromGlobal(QCursor::pos()), + QCursor::pos(), + Qt::NoButton, + Qt::LeftButton, + Qt::NoModifier); + + QApplication::sendEvent(widget(),&mouseEvent); +} +bool AutoScrollHandler::eventFilter(QObject* watched,QEvent* event) +{ + Q_ASSERT( watched == parent() ); + Q_UNUSED( watched ); + + QMouseEvent* mouseEvent = (QMouseEvent*)event; + switch (event->type()) + { + case QEvent::MouseMove: + { + bool mouseInWidget = widget()->rect().contains(mouseEvent->pos()); + + if (mouseInWidget) + { + if (_timerId) + killTimer(_timerId); + _timerId = 0; + } + else + { + if (!_timerId && (mouseEvent->buttons() & Qt::LeftButton)) + _timerId = startTimer(100); + } + break; + } + case QEvent::MouseButtonRelease: + if (_timerId && (mouseEvent->buttons() & ~Qt::LeftButton)) + { + killTimer(_timerId); + _timerId = 0; + } + break; + default: + break; + }; + + return false; +} + +//#include "TerminalDisplay.moc" diff --git a/qtermwidget/src/TerminalDisplay.h b/qtermwidget/lib/TerminalDisplay.h similarity index 65% rename from qtermwidget/src/TerminalDisplay.h rename to qtermwidget/lib/TerminalDisplay.h index 6b3c6d8..150d40a 100644 --- a/qtermwidget/src/TerminalDisplay.h +++ b/qtermwidget/lib/TerminalDisplay.h @@ -1,8 +1,6 @@ /* - Copyright (C) 2007 by Robert Knight - Copyright (C) 1997,1998 by Lars Doelle - - Rewritten for QT4 by e_k , Copyright (C)2008 + Copyright 2007-2008 by Robert Knight + Copyright 1997,1998 by Lars Doelle This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -24,14 +22,16 @@ #define TERMINALDISPLAY_H // Qt -#include -#include -#include +#include +#include +#include // Konsole #include "Filter.h" #include "Character.h" -#include "ColorTables.h" +#include "qtermwidget.h" +//#include "konsole_export.h" +#define KONSOLEPRIVATE_EXPORT class QDrag; class QDragEnterEvent; @@ -39,12 +39,12 @@ class QDropEvent; class QLabel; class QTimer; class QEvent; -class QFrame; class QGridLayout; class QKeyEvent; class QScrollBar; class QShowEvent; class QHideEvent; +class QTimerEvent; class QWidget; //class KMenu; @@ -52,6 +52,24 @@ class QWidget; namespace Konsole { + enum MotionAfterPasting + { + // No move screenwindow after pasting + NoMoveScreenWindow = 0, + // Move start of screenwindow after pasting + MoveStartScreenWindow = 1, + // Move end of screenwindow after pasting + MoveEndScreenWindow = 2 + }; + + enum BackgroundMode { + None, + Stretch, + Zoom, + Fit, + Center + }; + extern unsigned short vt100_graphics[32]; class ScreenWindow; @@ -60,19 +78,19 @@ class ScreenWindow; * A widget which displays output from a terminal emulation and sends input keypresses and mouse activity * to the terminal. * - * When the terminal emulation receives new output from the program running in the terminal, + * When the terminal emulation receives new output from the program running in the terminal, * it will update the display by calling updateImage(). * * TODO More documentation */ -class TerminalDisplay : public QWidget +class KONSOLEPRIVATE_EXPORT TerminalDisplay : public QWidget { Q_OBJECT public: /** Constructs a new terminal display widget with the specified parent. */ - TerminalDisplay(QWidget *parent=0); - virtual ~TerminalDisplay(); + TerminalDisplay(QWidget *parent=nullptr); + ~TerminalDisplay() override; /** Returns the terminal color palette used by the display. */ const ColorEntry* colorTable() const; @@ -92,25 +110,19 @@ public: /** Sets the opacity of the terminal display. */ void setOpacity(qreal opacity); - /** - * This enum describes the location where the scroll bar is positioned in the display widget. - */ - enum ScrollBarPosition - { - /** Do not show the scroll bar. */ - NoScrollBar=0, - /** Show the scroll bar on the left side of the display. */ - ScrollBarLeft=1, - /** Show the scroll bar on the right side of the display. */ - ScrollBarRight=2 - }; - /** + /** Sets the background image of the terminal display. */ + void setBackgroundImage(const QString& backgroundImage); + + /** Sets the background image mode of the terminal display. */ + void setBackgroundMode(BackgroundMode mode); + + /** * Specifies whether the terminal display has a vertical scroll bar, and if so whether it * is shown on the left or right side of the display. */ - void setScrollBarPosition(ScrollBarPosition position); + void setScrollBarPosition(QTermWidget::ScrollBarPosition position); - /** + /** * Sets the current position and range of the display's scroll bar. * * @param cursor The position of the scroll bar's thumb. @@ -118,7 +130,12 @@ public: */ void setScroll(int cursor, int lines); - /** + /** + * Scroll to the bottom of the terminal (reset scrolling). + */ + void scrollToEnd(); + + /** * Returns the display's filter chain. When the image for the display is updated, * the text is passed through each filter in the chain. Each filter can define * hotspots which correspond to certain strings (such as URLs or particular words). @@ -131,11 +148,11 @@ public: */ FilterChain* filterChain() const; - /** + /** * Updates the filters in the display's filter chain. This will cause * the hotspots to be updated to match the current image. * - * WARNING: This function can be expensive depending on the + * WARNING: This function can be expensive depending on the * image size and number of filters in the filterChain() * * TODO - This API does not really allow efficient usage. Revise it so @@ -144,10 +161,10 @@ public: * eg: * - Area of interest may be known ( eg. mouse cursor hovering * over an area ) - */ + */ void processFilters(); - /** + /** * Returns a list of menu actions created by the filters for the content * at the given @p position. */ @@ -158,67 +175,57 @@ public: /** Specifies whether or not the cursor blinks. */ void setBlinkingCursor(bool blink); + /** Specifies whether or not text can blink. */ + void setBlinkingTextEnabled(bool blink); + void setCtrlDrag(bool enable) { _ctrlDrag=enable; } bool ctrlDrag() { return _ctrlDrag; } - /** + /** * This enum describes the methods for selecting text when - * the user triple-clicks within the display. - */ - enum TripleClickMode - { - /** Select the whole line underneath the cursor. */ - SelectWholeLine, - /** Select from the current cursor position to the end of the line. */ - SelectForwardsFromCursor - }; - /** Sets how the text is selected when the user triple clicks within the display. */ + * the user triple-clicks within the display. + */ + enum TripleClickMode + { + /** Select the whole line underneath the cursor. */ + SelectWholeLine, + /** Select from the current cursor position to the end of the line. */ + SelectForwardsFromCursor + }; + /** Sets how the text is selected when the user triple clicks within the display. */ void setTripleClickMode(TripleClickMode mode) { _tripleClickMode = mode; } - /** See setTripleClickSelectionMode() */ + /** See setTripleClickSelectionMode() */ TripleClickMode tripleClickMode() { return _tripleClickMode; } void setLineSpacing(uint); + void setMargin(int); + + int margin() const; uint lineSpacing() const; void emitSelection(bool useXselection,bool appendReturn); + /** change and wrap text corresponding to paste mode **/ + void bracketText(QString& text) const; + /** - * This enum describes the available shapes for the keyboard cursor. - * See setKeyboardCursorShape() - */ - enum KeyboardCursorShape - { - /** A rectangular block which covers the entire area of the cursor character. */ - BlockCursor, - /** - * A single flat line which occupies the space at the bottom of the cursor - * character's area. - */ - UnderlineCursor, - /** - * An cursor shaped like the capital letter 'I', similar to the IBeam - * cursor used in Qt/KDE text editors. - */ - IBeamCursor - }; - /** - * Sets the shape of the keyboard cursor. This is the cursor drawn + * Sets the shape of the keyboard cursor. This is the cursor drawn * at the position in the terminal where keyboard input will appear. * - * In addition the terminal display widget also has a cursor for + * In addition the terminal display widget also has a cursor for * the mouse pointer, which can be set using the QWidget::setCursor() * method. * * Defaults to BlockCursor */ - void setKeyboardCursorShape(KeyboardCursorShape shape); + void setKeyboardCursorShape(QTermWidget::KeyboardCursorShape shape); /** * Returns the shape of the keyboard cursor. See setKeyboardCursorShape() */ - KeyboardCursorShape keyboardCursorShape() const; + QTermWidget::KeyboardCursorShape keyboardCursorShape() const; /** - * Sets the color used to draw the keyboard cursor. + * Sets the color used to draw the keyboard cursor. * * The keyboard cursor defaults to using the foreground color of the character * underneath it. @@ -232,10 +239,10 @@ public: */ void setKeyboardCursorColor(bool useForegroundColor , const QColor& color); - /** + /** * Returns the color of the keyboard cursor, or an invalid color if the keyboard * cursor color is set to change according to the foreground color of the character - * underneath it. + * underneath it. */ QColor keyboardCursorColor() const; @@ -260,19 +267,19 @@ public: */ int fontHeight() { return _fontHeight; } /** - * Returns the width of the characters in the display. + * Returns the width of the characters in the display. * This assumes the use of a fixed-width font. */ int fontWidth() { return _fontWidth; } void setSize(int cols, int lins); void setFixedSize(int cols, int lins); - + // reimplemented - QSize sizeHint() const; + QSize sizeHint() const override; /** - * Sets which characters, in addition to letters and numbers, + * Sets which characters, in addition to letters and numbers, * are regarded as being part of a word for the purposes * of selecting words in the display by double clicking on them. * @@ -283,26 +290,26 @@ public: * of a word ( in addition to letters and numbers ). */ void setWordCharacters(const QString& wc); - /** - * Returns the characters which are considered part of a word for the + /** + * Returns the characters which are considered part of a word for the * purpose of selecting words in the display with the mouse. * * @see setWordCharacters() */ QString wordCharacters() { return _wordCharacters; } - /** - * Sets the type of effect used to alert the user when a 'bell' occurs in the + /** + * Sets the type of effect used to alert the user when a 'bell' occurs in the * terminal session. * * The terminal session can trigger the bell effect by calling bell() with * the alert message. */ void setBellMode(int mode); - /** + /** * Returns the type of effect used to alert the user when a 'bell' occurs in * the terminal session. - * + * * See setBellMode() */ int bellMode() { return _bellMode; } @@ -313,23 +320,23 @@ public: * session. */ enum BellMode - { + { /** A system beep. */ - SystemBeepBell=0, - /** + SystemBeepBell=0, + /** * KDE notification. This may play a sound, show a passive popup * or perform some other action depending on the user's settings. */ - NotifyBell=1, + NotifyBell=1, /** A silent, visual bell (eg. inverting the display's colors briefly) */ - VisualBell=2, + VisualBell=2, /** No bell effects */ - NoBell=3 + NoBell=3 }; void setSelection(const QString &t); - /** + /** * Reimplemented. Has no effect. Use setVTFont() to change the font * used to draw characters in the display. */ @@ -338,9 +345,9 @@ public: /** Returns the font used to draw characters in the display */ QFont getVTFont() { return font(); } - /** + /** * Sets the font used to draw the display. Has no effect if @p font - * is larger than the size of the display itself. + * is larger than the size of the display itself. */ void setVTFont(const QFont& font); @@ -349,24 +356,40 @@ public: * is enabled or not. Defaults to enabled. */ static void setAntialias( bool antialias ) { _antialiasText = antialias; } - /** + /** * Returns true if anti-aliasing of text in the terminal is enabled. */ static bool antialias() { return _antialiasText; } - + /** - * Sets whether or not the current height and width of the + * Specify whether line chars should be drawn by ourselves or left to + * underlying font rendering libraries. + */ + void setDrawLineChars(bool drawLineChars) { _drawLineChars = drawLineChars; } + + /** + * Specifies whether characters with intense colors should be rendered + * as bold. Defaults to true. + */ + void setBoldIntense(bool value) { _boldIntense = value; } + /** + * Returns true if characters with intense colors are rendered in bold. + */ + bool getBoldIntense() { return _boldIntense; } + + /** + * Sets whether or not the current height and width of the * terminal in lines and columns is displayed whilst the widget * is being resized. */ void setTerminalSizeHint(bool on) { _terminalSizeHint=on; } - /** + /** * Returns whether or not the current height and width of * the terminal in lines and columns is displayed whilst the widget * is being resized. */ bool terminalSizeHint() { return _terminalSizeHint; } - /** + /** * Sets whether the terminal size display is shown briefly * after the widget is first shown. * @@ -374,7 +397,14 @@ public: */ void setTerminalSizeStartup(bool on) { _terminalSizeStartup=on; } + /** + * Sets the status of the BiDi rendering inside the terminal display. + * Defaults to disabled. + */ void setBidiEnabled(bool set) { _bidiEnabled=set; } + /** + * Returns the status of the BiDi rendering in this widget. + */ bool isBidiEnabled() { return _bidiEnabled; } /** @@ -391,23 +421,40 @@ public: static bool HAVE_TRANSPARENCY; + void setMotionAfterPasting(MotionAfterPasting action); + int motionAfterPasting(); + void setConfirmMultilinePaste(bool confirmMultilinePaste); + void setTrimPastedTrailingNewlines(bool trimPastedTrailingNewlines); + + // maps a point on the widget to the position ( ie. line and column ) + // of the character at that point. + void getCharacterPosition(const QPointF& widgetPoint,int& line,int& column) const; + + void disableBracketedPasteMode(bool disable) { _disabledBracketedPasteMode = disable; } + bool bracketedPasteModeIsDisabled() const { return _disabledBracketedPasteMode; } + public slots: - /** + /** * Causes the terminal display to fetch the latest character image from the associated * terminal screen ( see setScreenWindow() ) and redraw the display. */ - void updateImage(); + void updateImage(); + + /** Essentially calls processFilters(). + */ + void updateFilters(); + /** - * Causes the terminal display to fetch the latest line status flags from the - * associated terminal screen ( see setScreenWindow() ). - */ + * Causes the terminal display to fetch the latest line status flags from the + * associated terminal screen ( see setScreenWindow() ). + */ void updateLineProperties(); /** Copies the selected text to the clipboard. */ void copyClipboard(); - /** - * Pastes the content of the clipboard into the + /** + * Pastes the content of the clipboard into the * display. */ void pasteClipboard(); @@ -417,30 +464,36 @@ public slots: */ void pasteSelection(); - /** - * Changes whether the flow control warning box should be shown when the flow control - * stop key (Ctrl+S) are pressed. - */ - void setFlowControlWarningEnabled(bool enabled); - - /** - * Causes the widget to display or hide a message informing the user that terminal - * output has been suspended (by using the flow control key combination Ctrl+S) - * - * @param suspended True if terminal output has been suspended and the warning message should - * be shown or false to indicate that terminal output has been resumed and that - * the warning message should disappear. - */ - void outputSuspended(bool suspended); + /** + * Changes whether the flow control warning box should be shown when the flow control + * stop key (Ctrl+S) are pressed. + */ + void setFlowControlWarningEnabled(bool enabled); + /** + * Returns true if the flow control warning box is enabled. + * See outputSuspended() and setFlowControlWarningEnabled() + */ + bool flowControlWarningEnabled() const + { return _flowControlWarningEnabled; } /** - * Sets whether the program whoose output is being displayed in the view + * Causes the widget to display or hide a message informing the user that terminal + * output has been suspended (by using the flow control key combination Ctrl+S) + * + * @param suspended True if terminal output has been suspended and the warning message should + * be shown or false to indicate that terminal output has been resumed and that + * the warning message should disappear. + */ + void outputSuspended(bool suspended); + + /** + * Sets whether the program whose output is being displayed in the view * is interested in mouse events. * * If this is set to true, mouse signals will be emitted by the view when the user clicks, drags * or otherwise moves the mouse inside the view. * The user interaction needed to create selections will also change, and the user will be required - * to hold down the shift key to create a selection or perform other mouse activities inside the + * to hold down the shift key to create a selection or perform other mouse activities inside the * view area - since the program running in the terminal is being allowed to handle normal mouse * events itself. * @@ -448,32 +501,41 @@ public slots: * or false otherwise. */ void setUsesMouse(bool usesMouse); - + /** See setUsesMouse() */ bool usesMouse() const; - /** + void setBracketedPasteMode(bool bracketedPasteMode); + bool bracketedPasteMode() const; + + /** * Shows a notification that a bell event has occurred in the terminal. * TODO: More documentation here */ void bell(const QString& message); + /** + * Sets the background of the display to the specified color. + * @see setColorTable(), setForegroundColor() + */ + void setBackgroundColor(const QColor& color); + + /** + * Sets the text of the display to the specified color. + * @see setColorTable(), setBackgroundColor() + */ + void setForegroundColor(const QColor& color); + void setColorTableColor(const int colorId, const QColor &color); + void selectionChanged(); + signals: /** * Emitted when the user presses a key whilst the terminal widget has focus. */ - void keyPressedSignal(QKeyEvent *e); + void keyPressedSignal(QKeyEvent *e, bool fromPaste); /** - * Emitted when the user presses the suspend or resume flow control key combinations - * - * @param suspend true if the user pressed Ctrl+S (the suspend output key combination) or - * false if the user pressed Ctrl+Q (the resume output key combination) - */ - void flowControlKeyPressed(bool suspend); - - /** * A mouse event occurred. * @param button The mouse button (0 for left button, 1 for middle button, 2 for right button, 3 for release) * @param column The character column where the event occurred @@ -484,41 +546,61 @@ signals: void changedFontMetricSignal(int height, int width); void changedContentSizeSignal(int height, int width); - /** + /** * Emitted when the user right clicks on the display, or right-clicks with the Shift * key held down if usesMouse() is true. * * This can be used to display a context menu. */ - void configureRequest( TerminalDisplay*, int state, const QPoint& position ); + void configureRequest(const QPoint& position); + + /** + * When a shortcut which is also a valid terminal key sequence is pressed while + * the terminal widget has focus, this signal is emitted to allow the host to decide + * whether the shortcut should be overridden. + * When the shortcut is overridden, the key sequence will be sent to the terminal emulation instead + * and the action associated with the shortcut will not be triggered. + * + * @p override is set to false by default and the shortcut will be triggered as normal. + */ + void overrideShortcutCheck(QKeyEvent* keyEvent,bool& override); void isBusySelecting(bool); void sendStringToEmu(const char*); + // qtermwidget signals + void copyAvailable(bool); + void termGetFocus(); + void termLostFocus(); + + void notifyBell(const QString&); + void usesMouseChanged(); + protected: - virtual bool event( QEvent * ); + bool event( QEvent * ) override; - virtual void paintEvent( QPaintEvent * ); + void paintEvent( QPaintEvent * ) override; - virtual void showEvent(QShowEvent*); - virtual void hideEvent(QHideEvent*); - virtual void resizeEvent(QResizeEvent*); + void showEvent(QShowEvent*) override; + void hideEvent(QHideEvent*) override; + void resizeEvent(QResizeEvent*) override; virtual void fontChange(const QFont &font); - - virtual void keyPressEvent(QKeyEvent* event); - virtual void mouseDoubleClickEvent(QMouseEvent* ev); - virtual void mousePressEvent( QMouseEvent* ); - virtual void mouseReleaseEvent( QMouseEvent* ); - virtual void mouseMoveEvent( QMouseEvent* ); + void focusInEvent(QFocusEvent* event) override; + void focusOutEvent(QFocusEvent* event) override; + void keyPressEvent(QKeyEvent* event) override; + void mouseDoubleClickEvent(QMouseEvent* ev) override; + void mousePressEvent( QMouseEvent* ) override; + void mouseReleaseEvent( QMouseEvent* ) override; + void mouseMoveEvent( QMouseEvent* ) override; virtual void extendSelection( const QPoint& pos ); - virtual void wheelEvent( QWheelEvent* ); + void wheelEvent( QWheelEvent* ) override; + + bool focusNextPrevChild( bool next ) override; - virtual bool focusNextPrevChild( bool next ); - // drag and drop - virtual void dragEnterEvent(QDragEnterEvent* event); - virtual void dropEvent(QDropEvent* event); + void dragEnterEvent(QDragEnterEvent* event) override; + void dropEvent(QDropEvent* event) override; void doDrag(); enum DragState { diNone, diPending, diDragging }; @@ -528,22 +610,28 @@ protected: QDrag *dragObject; } dragInfo; - virtual int charClass(quint16) const; + // classifies the 'ch' into one of three categories + // and returns a character to indicate which category it is in + // + // - A space (returns ' ') + // - Part of a word (returns 'a') + // - Other characters (returns the input character) + QChar charClass(QChar ch) const; void clearImage(); void mouseTripleClickEvent(QMouseEvent* ev); // reimplemented - virtual void inputMethodEvent ( QInputMethodEvent* event ); - virtual QVariant inputMethodQuery( Qt::InputMethodQuery query ) const; + void inputMethodEvent ( QInputMethodEvent* event ) override; + QVariant inputMethodQuery( Qt::InputMethodQuery query ) const override; protected slots: void scrollBarPositionChanged(int value); void blinkEvent(); void blinkCursorEvent(); - + //Renables bell noises and visuals. Used to disable further bells for a short period of time //after emitting the first in a sequence of bell events. void enableBell(); @@ -557,42 +645,43 @@ private: // -- Drawing helpers -- + // determine the width of this text + int textWidth(int startColumn, int length, int line) const; + // determine the area that encloses this series of characters + QRect calculateTextArea(int topLeftX, int topLeftY, int startColumn, int line, int length); + // divides the part of the display specified by 'rect' into // fragments according to their colors and styles and calls - // drawTextFragment() to draw the fragments + // drawTextFragment() to draw the fragments void drawContents(QPainter &paint, const QRect &rect); // draws a section of text, all the text in this section // has a common color and style - void drawTextFragment(QPainter& painter, const QRect& rect, - const QString& text, const Character* style); + void drawTextFragment(QPainter& painter, const QRect& rect, + const std::wstring& text, const Character* style); // draws the background for a text fragment // if useOpacitySetting is true then the color's alpha value will be set to // the display's transparency (set with setOpacity()), otherwise the background // will be drawn fully opaque void drawBackground(QPainter& painter, const QRect& rect, const QColor& color, - bool useOpacitySetting); + bool useOpacitySetting); // draws the cursor character - void drawCursor(QPainter& painter, const QRect& rect , const QColor& foregroundColor, + void drawCursor(QPainter& painter, const QRect& rect , const QColor& foregroundColor, const QColor& backgroundColor , bool& invertColors); // draws the characters or line graphics in a text fragment - void drawCharacters(QPainter& painter, const QRect& rect, const QString& text, + void drawCharacters(QPainter& painter, const QRect& rect, const std::wstring& text, const Character* style, bool invertCharacterColor); // draws a string of line graphics - void drawLineCharString(QPainter& painter, int x, int y, - const QString& str, const Character* attributes); + void drawLineCharString(QPainter& painter, int x, int y, + const std::wstring& str, const Character* attributes) const; // draws the preedit string for input methods void drawInputMethodPreeditString(QPainter& painter , const QRect& rect); // -- - // maps an area in the character image to an area on the widget + // maps an area in the character image to an area on the widget QRect imageToWidget(const QRect& imageArea) const; - // maps a point on the widget to the position ( ie. line and column ) - // of the character at that point. - void getCharacterPosition(const QPoint& widgetPoint,int& line,int& column) const; - // the area where the preedit string for input methods will be draw QRect preeditRect() const; @@ -600,30 +689,43 @@ private: // current size in columns and lines void showResizeNotification(); - // scrolls the image by a number of lines. - // 'lines' may be positive ( to scroll the image down ) + // scrolls the image by a number of lines. + // 'lines' may be positive ( to scroll the image down ) // or negative ( to scroll the image up ) // 'region' is the part of the image to scroll - currently only // the top, bottom and height of 'region' are taken into account, // the left and right are ignored. void scrollImage(int lines , const QRect& region); + // shows the multiline prompt + bool multilineConfirmation(const QString& text); + void calcGeometry(); void propagateSize(); void updateImageSize(); void makeImage(); - + void paintFilters(QPainter& painter); - // returns a region covering all of the areas of the widget which contain - // a hotspot - QRegion hotSpotRegion() const; + void calDrawTextAdditionHeight(QPainter& painter); - // returns the position of the cursor in columns and lines - QPoint cursorPosition() const; + // returns a region covering all of the areas of the widget which contain + // a hotspot + QRegion hotSpotRegion() const; + + // returns the position of the cursor in columns and lines + QPoint cursorPosition() const; + + // redraws the cursor + void updateCursor(); + + bool handleShortcutOverrideEvent(QKeyEvent* event); + + bool isLineChar(wchar_t c) const; + bool isLineCharString(const std::wstring& string) const; // the window onto the terminal screen which this display - // is currently showing. + // is currently showing. QPointer _screenWindow; bool _allowBell; @@ -634,13 +736,16 @@ private: int _fontHeight; // height int _fontWidth; // width int _fontAscent; // ascend + bool _boldIntense; // Whether intense colors should be rendered with bold font + int _drawTextAdditionHeight; // additional height to prevent font trancation + bool _drawTextTestFlag; // indicate it is a testing or not int _leftMargin; // offset int _topMargin; // offset int _lines; // the number of lines that can be displayed in the widget int _columns; // the number of columns that can be displayed in the widget - + int _usedLines; // the number of lines that are actually being used, this will be less // than 'lines' if the character image provided with setImage() is smaller // than the maximum image size which can be displayed @@ -648,7 +753,7 @@ private: int _usedColumns; // the number of columns that are actually being used, this will be less // than 'columns' if the character image provided with setImage() is smaller // than the maximum image size which can be displayed - + int _contentHeight; int _contentWidth; Character* _image; // [lines][columns] @@ -665,6 +770,8 @@ private: bool _terminalSizeStartup; bool _bidiEnabled; bool _mouseMarks; + bool _bracketedPasteMode; + bool _disabledBracketedPasteMode; QPoint _iPntSel; // initial selection point QPoint _pntSel; // current selection point @@ -677,7 +784,7 @@ private: QClipboard* _clipboard; QScrollBar* _scrollBar; - ScrollBarPosition _scrollbarLocation; + QTermWidget::ScrollBarPosition _scrollbarLocation; QString _wordCharacters; int _bellMode; @@ -685,13 +792,14 @@ private: bool _hasBlinker; // has characters to blink bool _cursorBlinking; // hide cursor in paintEvent bool _hasBlinkingCursor; // has blinking cursor enabled + bool _allowBlinkingText; // allow text to blink bool _ctrlDrag; // require Ctrl key for drag TripleClickMode _tripleClickMode; bool _isFixedSize; //Columns / lines are locked. QTimer* _blinkTimer; // active when hasBlinker QTimer* _blinkCursorTimer; // active when hasBlinkingCursor -// KMenu* _drop; + //QMenu* _drop; QString _dropText; int _dndFileCount; @@ -702,35 +810,42 @@ private: QLabel* _resizeWidget; QTimer* _resizeTimer; - bool _flowControlWarningEnabled; + bool _flowControlWarningEnabled; //widgets related to the warning message that appears when the user presses Ctrl+S to suspend //terminal output - informing them what has happened and how to resume output - QLabel* _outputSuspendedLabel; - + QLabel* _outputSuspendedLabel; + uint _lineSpacing; bool _colorsInverted; // true during visual bell QSize _size; - - QRgb _blendColor; + + qreal _opacity; + + QPixmap _backgroundImage; + BackgroundMode _backgroundMode; // list of filters currently applied to the display. used for links and // search highlight TerminalImageFilterChain* _filterChain; - QRect _mouseOverHotspotArea; + QRegion _mouseOverHotspotArea; - KeyboardCursorShape _cursorShape; + QTermWidget::KeyboardCursorShape _cursorShape; // custom cursor color. if this is invalid then the foreground // color of the character under the cursor is used - QColor _cursorColor; + QColor _cursorColor; + MotionAfterPasting mMotionAfterPasting; + bool _confirmMultilinePaste; + bool _trimPastedTrailingNewlines; + struct InputMethodData { - QString preeditString; + std::wstring preeditString; QRect previousPreeditRect; }; InputMethodData _inputMethodData; @@ -738,9 +853,12 @@ private: static bool _antialiasText; // do we antialias or not //the delay in milliseconds between redrawing blinking text - static const int BLINK_DELAY = 500; - static const int DEFAULT_LEFT_MARGIN = 1; - static const int DEFAULT_TOP_MARGIN = 1; + static const int TEXT_BLINK_DELAY = 500; + + int _leftBaseMargin; + int _topBaseMargin; + + bool _drawLineChars; public: static void setTransparencyEnabled(bool enable) @@ -749,6 +867,20 @@ public: } }; +class AutoScrollHandler : public QObject +{ +Q_OBJECT + +public: + AutoScrollHandler(QWidget* parent); +protected: + void timerEvent(QTimerEvent* event) override; + bool eventFilter(QObject* watched,QEvent* event) override; +private: + QWidget* widget() const { return static_cast(parent()); } + int _timerId; +}; + } #endif // TERMINALDISPLAY_H diff --git a/qtermwidget/src/Vt102Emulation.cpp b/qtermwidget/lib/Vt102Emulation.cpp similarity index 60% rename from qtermwidget/src/Vt102Emulation.cpp rename to qtermwidget/lib/Vt102Emulation.cpp index 8829b3b..69f4aeb 100644 --- a/qtermwidget/src/Vt102Emulation.cpp +++ b/qtermwidget/lib/Vt102Emulation.cpp @@ -1,8 +1,8 @@ /* This file is part of Konsole, an X terminal. - Copyright (C) 1997,1998 by Lars Doelle - Rewritten for QT4 by e_k , Copyright (C)2008 + Copyright 2007-2008 by Robert Knight + Copyright 1997,1998 by Lars Doelle This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -22,29 +22,36 @@ // Own #include "Vt102Emulation.h" +#include "tools.h" +// XKB //#include - -#if defined(__osf__) || defined(__APPLE__) -#define AVOID_XKB -#endif - // this allows konsole to be compiled without XKB and XTEST extensions // even though it might be available on a particular system. #if defined(AVOID_XKB) -#undef HAVE_XKB + #undef HAVE_XKB #endif -// Standard -#include +#if defined(HAVE_XKB) + void scrolllock_set_off(); + void scrolllock_set_on(); +#endif + +// Standard +#include #include -#include // Qt -#include -#include -#include +#include +#include +#if QT_VERSION >= 0x060000 +#include +#include +#else +#include +#endif +#include // KDE //#include @@ -54,44 +61,16 @@ #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() +Vt102Emulation::Vt102Emulation() : Emulation(), - _titleUpdateTimer(new QTimer(this)) + prevCC(0), + _titleUpdateTimer(new QTimer(this)), + _reportFocusEvents(false) { _titleUpdateTimer->setSingleShot(true); - QObject::connect(_titleUpdateTimer , SIGNAL(timeout()) , this , SLOT(updateTitle())); initTokenizer(); @@ -99,34 +78,24 @@ Vt102Emulation::Vt102Emulation() } Vt102Emulation::~Vt102Emulation() -{ -} +{} void Vt102Emulation::clearEntireScreen() { _currentScreen->clearEntireScreen(); - - bufferedUpdate(); + bufferedUpdate(); } void Vt102Emulation::reset() { - //kDebug(1211)<<"Vt102Emulation::reset() resetToken()"; - resetToken(); - //kDebug(1211)<<"Vt102Emulation::reset() resetModes()"; + resetTokenizer(); resetModes(); - //kDebug(1211)<<"Vt102Emulation::reset() resetCharSet()"; resetCharset(0); - //kDebug(1211)<<"Vt102Emulation::reset() reset screen0()"; _screen[0]->reset(); - //kDebug(1211)<<"Vt102Emulation::reset() resetCharSet()"; resetCharset(1); - //kDebug(1211)<<"Vt102Emulation::reset() reset _screen 1"; _screen[1]->reset(); - //kDebug(1211)<<"Vt102Emulation::reset() setCodec()"; setCodec(LocaleCodec); - //kDebug(1211)<<"Vt102Emulation::reset() done"; - + bufferedUpdate(); } @@ -147,7 +116,7 @@ void Vt102Emulation::reset() - Tokenizing the ESC codes (onReceiveChar) - VT100 code page translation of plain characters (applyCharset) - - Interpretation of ESC codes (tau) + - Interpretation of ESC codes (processToken) The escape codes and their meaning are described in the technical reference of this program. @@ -172,56 +141,64 @@ void Vt102Emulation::reset() - ESC_DE - Escape codes of the form C - CSI_PN - Escape codes of the form '[' {Pn} ';' {Pn} C - CSI_PS - Escape codes of the form '[' {Pn} ';' ... C + - CSI_PS_SP - Escape codes of the form '[' {Pn} ';' ... {Space} C - CSI_PR - Escape codes of the form '[' '?' {Pn} ';' ... C - CSI_PE - Escape codes of the form '[' '!' {Pn} ';' ... C - VT52 - VT52 escape codes - - 'Y'{Pc}{Pc} - - XTE_HA - Xterm hacks `]' {Pn} `;' {Text} - note that this is handled differently + - XTE_HA - Xterm window/terminal attribute commands + of the form `]' {Pn} `;' {Text} + (Note that these are handled differently to the other formats) The last two forms allow list of arguments. Since the elements of the lists are treated individually the same way, they are passed as individual tokens to the interpretation. Further, because the - meaning of the parameters are names (althought represented as numbers), + meaning of the parameters are names (although 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_CONSTRUCT(T,A,N) ( ((((int)N) & 0xffff) << 16) | ((((int)A) & 0xff) << 8) | (((int)T) & 0xff) ) -#define TY_CHR( ) TY_CONSTR(0,0,0) -#define TY_CTL(A ) TY_CONSTR(1,A,0) -#define TY_ESC(A ) TY_CONSTR(2,A,0) -#define TY_ESC_CS(A,B) TY_CONSTR(3,A,B) -#define TY_ESC_DE(A ) TY_CONSTR(4,A,0) -#define TY_CSI_PS(A,N) TY_CONSTR(5,A,N) -#define TY_CSI_PN(A ) TY_CONSTR(6,A,0) -#define TY_CSI_PR(A,N) TY_CONSTR(7,A,N) +#define TY_CHR( ) TY_CONSTRUCT(0,0,0) +#define TY_CTL(A ) TY_CONSTRUCT(1,A,0) +#define TY_ESC(A ) TY_CONSTRUCT(2,A,0) +#define TY_ESC_CS(A,B) TY_CONSTRUCT(3,A,B) +#define TY_ESC_DE(A ) TY_CONSTRUCT(4,A,0) +#define TY_CSI_PS(A,N) TY_CONSTRUCT(5,A,N) +#define TY_CSI_PN(A ) TY_CONSTRUCT(6,A,0) +#define TY_CSI_PR(A,N) TY_CONSTRUCT(7,A,N) +#define TY_CSI_PS_SP(A,N) TY_CONSTRUCT(11,A,N) -#define TY_VT52(A ) TY_CONSTR(8,A,0) +#define TY_VT52(A) TY_CONSTRUCT(8,A,0) +#define TY_CSI_PG(A) TY_CONSTRUCT(9,A,0) +#define TY_CSI_PE(A) TY_CONSTRUCT(10,A,0) -#define TY_CSI_PG(A ) TY_CONSTR(9,A,0) - -#define TY_CSI_PE(A ) TY_CONSTR(10,A,0) +#define MAX_ARGUMENT 4096 // Tokenizer --------------------------------------------------------------- -- -/* The tokenizers state +/* The tokenizer's state - The state is represented by the buffer (pbuf, ppos), + The state is represented by the buffer (tokenBuffer, tokenBufferPos), and accompanied by decoded arguments kept in (argv,argc). Note that they are kept internal in the tokenizer. */ -void Vt102Emulation::resetToken() +void Vt102Emulation::resetTokenizer() { - ppos = 0; argc = 0; argv[0] = 0; argv[1] = 0; + tokenBufferPos = 0; + argc = 0; + argv[0] = 0; + argv[1] = 0; + prevCC = 0; } -void Vt102Emulation::addDigit(int dig) +void Vt102Emulation::addDigit(int digit) { - argv[argc] = 10*argv[argc] + dig; + if (argv[argc] < MAX_ARGUMENT) + argv[argc] = 10*argv[argc] + digit; } void Vt102Emulation::addArgument() @@ -230,34 +207,45 @@ void Vt102Emulation::addArgument() argv[argc] = 0; } -void Vt102Emulation::pushToToken(int cc) +void Vt102Emulation::addToCurrentToken(wchar_t cc) { - pbuf[ppos] = cc; - ppos = qMin(ppos+1,MAXPBUF-1); + tokenBuffer[tokenBufferPos] = cc; + tokenBufferPos = qMin(tokenBufferPos+1,MAX_TOKEN_LENGTH-1); } -// Character Classes used while decoding - -#define CTL 1 -#define CHR 2 -#define CPN 4 -#define DIG 8 -#define SCS 16 -#define GRP 32 -#define CPS 64 +// Character Class flags used while decoding +#define CTL 1 // Control character +#define CHR 2 // Printable character +#define CPN 4 // TODO: Document me +#define DIG 8 // Digit +#define SCS 16 // TODO: Document me +#define GRP 32 // TODO: Document me +#define CPS 64 // Character which indicates end of window resize + // escape sequence '\e[8;;t' void Vt102Emulation::initTokenizer() -{ int i; quint8* s; - for(i = 0; i < 256; i++) tbl[ i] = 0; - for(i = 0; i < 32; i++) tbl[ i] |= CTL; - for(i = 32; i < 256; i++) tbl[ i] |= CHR; - for(s = (quint8*)"@ABCDGHILMPSTXZcdfry"; *s; s++) tbl[*s] |= CPN; -// resize = \e[8;;t - for(s = (quint8*)"t"; *s; s++) tbl[*s] |= CPS; - for(s = (quint8*)"0123456789" ; *s; s++) tbl[*s] |= DIG; - for(s = (quint8*)"()+*%" ; *s; s++) tbl[*s] |= SCS; - for(s = (quint8*)"()+*#[]%" ; *s; s++) tbl[*s] |= GRP; - resetToken(); +{ + int i; + quint8* s; + for(i = 0;i < 256; ++i) + charClass[i] = 0; + for(i = 0;i < 32; ++i) + charClass[i] |= CTL; + for(i = 32;i < 256; ++i) + charClass[i] |= CHR; + for(s = (quint8*)"@ABCDEFGHILMPSTXZbcdfry"; *s; ++s) + charClass[*s] |= CPN; + // resize = \e[8;;t + for(s = (quint8*)"t"; *s; ++s) + charClass[*s] |= CPS; + for(s = (quint8*)"0123456789"; *s; ++s) + charClass[*s] |= DIG; + for(s = (quint8*)"()+*%"; *s; ++s) + charClass[*s] |= SCS; + for(s = (quint8*)"()+*#[]%"; *s; ++s) + charClass[*s] |= GRP; + + resetTokenizer(); } /* Ok, here comes the nasty part of the decoder. @@ -270,125 +258,185 @@ void Vt102Emulation::initTokenizer() - P is the length of the token scanned so far. - L (often P-1) is the position on which contents we base a decision. - - C is a character or a group of characters (taken from 'tbl'). + - C is a character or a group of characters (taken from 'charClass'). + + - 'cc' is the current character + - 's' is a pointer to the start of the token buffer + - 'p' is the current position within the token buffer Note that they need to applied in proper order. */ -#define lec(P,L,C) (p == (P) && s[(L)] == (C)) -#define lun( ) (p == 1 && cc >= 32 ) -#define les(P,L,C) (p == (P) && s[L] < 256 && (tbl[s[(L)]] & (C)) == (C)) -#define eec(C) (p >= 3 && cc == (C)) -#define ees(C) (p >= 3 && cc < 256 && (tbl[ cc ] & (C)) == (C)) -#define eps(C) (p >= 3 && s[2] != '?' && s[2] != '!' && s[2] != '>' && cc < 256 && (tbl[ cc ] & (C)) == (C)) -#define epp( ) (p >= 3 && s[2] == '?' ) -#define epe( ) (p >= 3 && s[2] == '!' ) -#define egt( ) (p >= 3 && s[2] == '>' ) -#define Xpe (ppos>=2 && pbuf[1] == ']' ) -#define Xte (Xpe && cc == 7 ) -#define ces(C) ( cc < 256 && (tbl[ cc ] & (C)) == (C) && !Xte) +#define lec(P,L,C) (p == (P) && s[(L)] == (C)) +#define lun( ) (p == 1 && cc >= 32 ) +#define les(P,L,C) (p == (P) && s[L] < 256 && (charClass[s[(L)]] & (C)) == (C)) +#define eec(C) (p >= 3 && cc == (C)) +#define ees(C) (p >= 3 && cc < 256 && (charClass[cc] & (C)) == (C)) +#define eps(C) (p >= 3 && s[2] != '?' && s[2] != '!' && s[2] != '>' && cc < 256 && (charClass[cc] & (C)) == (C)) +#define epp( ) (p >= 3 && s[2] == '?') +#define epe( ) (p >= 3 && s[2] == '!') +#define egt( ) (p >= 3 && s[2] == '>') +#define esp( ) (p == 4 && s[3] == ' ') +#define Xpe (tokenBufferPos >= 2 && tokenBuffer[1] == ']') +#define Xte (Xpe && (cc == 7 || (prevCC == 27 && cc == 92) )) // 27, 92 => "\e\\" (ST, String Terminator) +#define ces(C) (cc < 256 && (charClass[cc] & (C)) == (C) && !Xte) -#define ESC 27 #define CNTL(c) ((c)-'@') +#define ESC 27 +#define DEL 127 // process an incoming unicode character +void Vt102Emulation::receiveChar(wchar_t cc) +{ + if (cc == DEL) + return; //VT100: ignore. -void Vt102Emulation::receiveChar(int cc) -{ - int i; - if (cc == 127) return; //VT100: ignore. + if (ces(CTL)) + { + // ignore control characters in the text part of Xpe (aka OSC) "ESC]" + // escape sequences; this matches what XTERM docs say + if (Xpe) { + prevCC = cc; + return; + } - if (ces( CTL)) - { // DEC HACK ALERT! Control Characters are allowed *within* esc sequences in VT100 - // This means, they do neither a resetToken nor a pushToToken. Some of them, do + // DEC HACK ALERT! Control Characters are allowed *within* esc sequences in VT100 + // This means, they do neither a resetTokenizer() nor a pushToToken(). Some of them, do // of course. Guess this originates from a weakly layered handling of the X-on // X-off protocol, which comes really below this level. - if (cc == CNTL('X') || cc == CNTL('Z') || cc == ESC) resetToken(); //VT100: CAN or SUB - if (cc != ESC) { tau( TY_CTL(cc+'@' ), 0, 0); return; } - } - - pushToToken(cc); // advance the state - - int* s = pbuf; - int p = ppos; - - if (getMode(MODE_Ansi)) // decide on proper action - { - if (lec(1,0,ESC)) { return; } - if (lec(1,0,ESC+128)) { s[0] = ESC; receiveChar('['); return; } - if (les(2,1,GRP)) { return; } - if (Xte ) { XtermHack(); resetToken(); return; } - if (Xpe ) { return; } - if (lec(3,2,'?')) { return; } - if (lec(3,2,'>')) { return; } - if (lec(3,2,'!')) { return; } - if (lun( )) { tau( TY_CHR(), applyCharset(cc), 0); resetToken(); return; } - if (lec(2,0,ESC)) { tau( TY_ESC(s[1]), 0, 0); resetToken(); return; } - if (les(3,1,SCS)) { tau( TY_ESC_CS(s[1],s[2]), 0, 0); resetToken(); return; } - if (lec(3,1,'#')) { tau( TY_ESC_DE(s[2]), 0, 0); resetToken(); return; } - if (eps( CPN)) { tau( TY_CSI_PN(cc), argv[0],argv[1]); resetToken(); return; } - -// resize = \e[8;;t - if (eps( CPS)) { tau( TY_CSI_PS(cc, argv[0]), argv[1], argv[2]); resetToken(); return; } - - if (epe( )) { tau( TY_CSI_PE(cc), 0, 0); resetToken(); return; } - if (ees( DIG)) { addDigit(cc-'0'); return; } - if (eec( ';')) { addArgument(); return; } - for (i=0;i<=argc;i++) - if ( epp( )) { tau( TY_CSI_PR(cc,argv[i]), 0, 0); } - else if(egt( )) { tau( TY_CSI_PG(cc ), 0, 0); } // spec. case for ESC]>0c or ESC]>c - else if (cc == 'm' && argc - i >= 4 && (argv[i] == 38 || argv[i] == 48) && argv[i+1] == 2) - { // ESC[ ... 48;2;;; ... m -or- ESC[ ... 38;2;;; ... m - i += 2; - tau( TY_CSI_PS(cc, argv[i-2]), COLOR_SPACE_RGB, (argv[i] << 16) | (argv[i+1] << 8) | argv[i+2]); - i += 2; + if (cc == CNTL('X') || cc == CNTL('Z') || cc == ESC) + resetTokenizer(); //VT100: CAN or SUB + if (cc != ESC) + { + processToken(TY_CTL(cc+'@' ),0,0); + return; } - else if (cc == 'm' && argc - i >= 2 && (argv[i] == 38 || argv[i] == 48) && argv[i+1] == 5) - { // ESC[ ... 48;5; ... m -or- ESC[ ... 38;5; ... m - i += 2; - 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 + // advance the state + addToCurrentToken(cc); + + wchar_t* s = tokenBuffer; + int p = tokenBufferPos; + + if (getMode(MODE_Ansi)) { - 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; + if (lec(1,0,ESC)) { return; } + if (lec(1,0,ESC+128)) { s[0] = ESC; receiveChar('['); return; } + if (les(2,1,GRP)) { return; } + if (Xte ) { processWindowAttributeChange(); resetTokenizer(); return; } + if (Xpe ) { prevCC = cc; return; } + if (lec(3,2,'?')) { return; } + if (lec(3,2,'>')) { return; } + if (lec(3,2,'!')) { return; } + if (lun( )) { processToken( TY_CHR(), applyCharset(cc), 0); resetTokenizer(); return; } + if (lec(2,0,ESC)) { processToken( TY_ESC(s[1]), 0, 0); resetTokenizer(); return; } + if (les(3,1,SCS)) { processToken( TY_ESC_CS(s[1],s[2]), 0, 0); resetTokenizer(); return; } + if (lec(3,1,'#')) { processToken( TY_ESC_DE(s[2]), 0, 0); resetTokenizer(); return; } + if (eps( CPN)) { processToken( TY_CSI_PN(cc), argv[0],argv[1]); resetTokenizer(); return; } + if (esp( )) { return; } + if (lec(5, 4, 'q') && s[3] == ' ') { + processToken( TY_CSI_PS_SP(cc, argv[0]), argv[0], 0); + resetTokenizer(); + return; + } + + // resize = \e[8;;t + if (eps(CPS)) + { + processToken( TY_CSI_PS(cc, argv[0]), argv[1], argv[2]); + resetTokenizer(); + return; + } + + if (epe( )) { processToken( TY_CSI_PE(cc), 0, 0); resetTokenizer(); return; } + if (ees(DIG)) { addDigit(cc-'0'); return; } + if (eec(';') || eec(':')) { addArgument(); return; } + for (int i=0;i<=argc;i++) + { + if (epp()) + processToken( TY_CSI_PR(cc,argv[i]), 0, 0); + else if (egt()) + processToken( TY_CSI_PG(cc), 0, 0); // spec. case for ESC]>0c or ESC]>c + else if (cc == 'm' && argc - i >= 4 && (argv[i] == 38 || argv[i] == 48) && argv[i+1] == 2) + { + // ESC[ ... 48;2;;; ... m -or- ESC[ ... 38;2;;; ... m + i += 2; + processToken( TY_CSI_PS(cc, argv[i-2]), COLOR_SPACE_RGB, (argv[i] << 16) | (argv[i+1] << 8) | argv[i+2]); + i += 2; + } + else if (cc == 'm' && argc - i >= 2 && (argv[i] == 38 || argv[i] == 48) && argv[i+1] == 5) + { + // ESC[ ... 48;5; ... m -or- ESC[ ... 38;5; ... m + i += 2; + processToken( TY_CSI_PS(cc, argv[i-2]), COLOR_SPACE_256, argv[i]); + } + else + processToken( TY_CSI_PS(cc,argv[i]), 0, 0); + } + resetTokenizer(); + } + else + { + // VT52 Mode + if (lec(1,0,ESC)) + return; + if (les(1,0,CHR)) + { + processToken( TY_CHR(), s[0], 0); + resetTokenizer(); + return; + } + if (lec(2,1,'Y')) + return; + if (lec(3,1,'Y')) + return; + if (p < 4) + { + processToken( TY_VT52(s[1] ), 0, 0); + resetTokenizer(); + return; + } + processToken( TY_VT52(s[1]), s[2], s[3]); + resetTokenizer(); + return; } } +void Vt102Emulation::processWindowAttributeChange() +{ + // Describes the window or terminal session attribute to change + // See Session::UserTitleChange for possible values + int attributeToChange = 0; + int i; + for (i = 2; i < tokenBufferPos && + tokenBuffer[i] >= '0' && + tokenBuffer[i] <= '9'; i++) + { + attributeToChange = 10 * attributeToChange + (tokenBuffer[i]-'0'); + } -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; + if (tokenBuffer[i] != ';') + { + reportDecodingError(); + return; + } + + // copy from the first char after ';', and skipping the ending delimiter + // 0x07 or 0x92. Note that as control characters in OSC text parts are + // ignored, only the second char in ST ("\e\\") is appended to tokenBuffer. + QString newValue = QString::fromWCharArray(tokenBuffer + i + 1, tokenBufferPos-i-2); + + _pendingTitleUpdates[attributeToChange] = newValue; _titleUpdateTimer->start(20); - - delete [] str; } void Vt102Emulation::updateTitle() { - QListIterator iter( _pendingTitleUpdates.keys() ); - while (iter.hasNext()) { - int arg = iter.next(); - emit titleChanged( arg , _pendingTitleUpdates[arg] ); - } - - _pendingTitleUpdates.clear(); + QListIterator iter( _pendingTitleUpdates.keys() ); + while (iter.hasNext()) { + int arg = iter.next(); + emit titleChanged( arg , _pendingTitleUpdates[arg] ); + } + _pendingTitleUpdates.clear(); } // Interpreting Codes --------------------------------------------------------- @@ -409,44 +457,12 @@ void Vt102Emulation::updateTitle() about this mapping. */ -void Vt102Emulation::tau( int token, int p, int q ) +void Vt102Emulation::processToken(int token, wchar_t 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 + case TY_CHR( ) : _currentScreen->displayCharacter (p ); break; //UTF16 // 127 DEL : ignored on input @@ -459,12 +475,12 @@ switch( N ) case TY_CTL('F' ) : /* ACK: ignored */ break; case TY_CTL('G' ) : emit stateSet(NOTIFYBELL); break; //VT100 - case TY_CTL('H' ) : _currentScreen->BackSpace ( ); break; //VT100 - case TY_CTL('I' ) : _currentScreen->Tabulate ( ); break; //VT100 - case TY_CTL('J' ) : _currentScreen->NewLine ( ); break; //VT100 - case TY_CTL('K' ) : _currentScreen->NewLine ( ); break; //VT100 - case TY_CTL('L' ) : _currentScreen->NewLine ( ); break; //VT100 - case TY_CTL('M' ) : _currentScreen->Return ( ); break; //VT100 + case TY_CTL('H' ) : _currentScreen->backspace ( ); break; //VT100 + case TY_CTL('I' ) : _currentScreen->tab ( ); break; //VT100 + case TY_CTL('J' ) : _currentScreen->newLine ( ); break; //VT100 + case TY_CTL('K' ) : _currentScreen->newLine ( ); break; //VT100 + case TY_CTL('L' ) : _currentScreen->newLine ( ); break; //VT100 + case TY_CTL('M' ) : _currentScreen->toStartOfLine ( ); break; //VT100 case TY_CTL('N' ) : useCharset ( 1); break; //VT100 case TY_CTL('O' ) : useCharset ( 0); break; //VT100 @@ -477,9 +493,9 @@ switch( N ) case TY_CTL('U' ) : /* NAK: ignored */ break; case TY_CTL('V' ) : /* SYN: ignored */ break; case TY_CTL('W' ) : /* ETB: ignored */ break; - case TY_CTL('X' ) : _currentScreen->ShowCharacter ( 0x2592); break; //VT100 + case TY_CTL('X' ) : _currentScreen->displayCharacter ( 0x2592); break; //VT100 case TY_CTL('Y' ) : /* EM : ignored */ break; - case TY_CTL('Z' ) : _currentScreen->ShowCharacter ( 0x2592); break; //VT100 + case TY_CTL('Z' ) : _currentScreen->displayCharacter ( 0x2592); break; //VT100 case TY_CTL('[' ) : /* ESC: cannot be seen here. */ break; case TY_CTL('\\' ) : /* FS : ignored */ break; case TY_CTL(']' ) : /* GS : ignored */ break; @@ -487,7 +503,7 @@ switch( N ) case TY_CTL('_' ) : /* US : ignored */ break; case TY_ESC('D' ) : _currentScreen->index ( ); break; //VT100 - case TY_ESC('E' ) : _currentScreen->NextLine ( ); break; //VT100 + case TY_ESC('E' ) : _currentScreen->nextLine ( ); break; //VT100 case TY_ESC('H' ) : _currentScreen->changeTabStop (true ); break; //VT100 case TY_ESC('M' ) : _currentScreen->reverseIndex ( ); break; //VT100 case TY_ESC('Z' ) : reportTerminalType ( ); break; @@ -521,26 +537,28 @@ switch( N ) case TY_ESC_CS('%', 'G') : setCodec (Utf8Codec ); break; //LINUX case TY_ESC_CS('%', '@') : setCodec (LocaleCodec ); break; //LINUX - case TY_ESC_DE('3' ) : /* Double height line, top half */ - _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , true ); - _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , true ); - break; - case TY_ESC_DE('4' ) : /* Double height line, bottom half */ - _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , true ); - _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , true ); - break; + case TY_ESC_DE('3' ) : /* Double height line, top half */ + _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , true ); + _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , true ); + break; + case TY_ESC_DE('4' ) : /* Double height line, bottom half */ + _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , true ); + _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , true ); + break; case TY_ESC_DE('5' ) : /* Single width, single height line*/ - _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , false); - _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , false); - break; - case TY_ESC_DE('6' ) : /* Double width, single height line*/ - _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , true); - _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , false); - break; + _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , false); + _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , false); + break; + case TY_ESC_DE('6' ) : /* Double width, single height line*/ + _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , true); + _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , false); + break; case TY_ESC_DE('8' ) : _currentScreen->helpAlign ( ); break; // resize = \e[8;;t - case TY_CSI_PS('t', 8) : setImageSize( q /* colums */, p /* lines */ ); break; + case TY_CSI_PS('t', 8) : setImageSize( p /*lines */, q /* columns */ ); + emit imageResizeRequest(QSize(q, p)); + break; // change tab text color : \e[28;t color: 0-16,777,215 case TY_CSI_PS('t', 28) : emit changeTabTextColorRequest ( p ); break; @@ -551,6 +569,7 @@ switch( N ) case TY_CSI_PS('J', 0) : _currentScreen->clearToEndOfScreen ( ); break; case TY_CSI_PS('J', 1) : _currentScreen->clearToBeginOfScreen ( ); break; case TY_CSI_PS('J', 2) : _currentScreen->clearEntireScreen ( ); break; + case TY_CSI_PS('J', 3) : clearHistory(); break; case TY_CSI_PS('g', 0) : _currentScreen->changeTabStop (false ); break; //VT100 case TY_CSI_PS('g', 3) : _currentScreen->clearTabStops ( ); break; //VT100 case TY_CSI_PS('h', 4) : _currentScreen-> setMode (MODE_Insert ); break; @@ -563,16 +582,27 @@ switch( N ) 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', 2) : _currentScreen-> setRendition (RE_FAINT ); break; + case TY_CSI_PS('m', 3) : _currentScreen-> setRendition (RE_ITALIC ); 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', 8) : _currentScreen-> setRendition (RE_CONCEAL ); break; + case TY_CSI_PS('m', 9) : _currentScreen-> setRendition (RE_STRIKEOUT); break; + case TY_CSI_PS('m', 53) : _currentScreen-> setRendition (RE_OVERLINE ); 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', 21) : _currentScreen->resetRendition (RE_BOLD ); break; + case TY_CSI_PS('m', 22) : _currentScreen->resetRendition (RE_BOLD ); + _currentScreen->resetRendition (RE_FAINT ); break; + case TY_CSI_PS('m', 23) : _currentScreen->resetRendition (RE_ITALIC ); break; //VT100 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', 28) : _currentScreen->resetRendition (RE_CONCEAL ); break; + case TY_CSI_PS('m', 29) : _currentScreen->resetRendition (RE_STRIKEOUT); break; + case TY_CSI_PS('m', 55) : _currentScreen->resetRendition (RE_OVERLINE ); 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; @@ -628,21 +658,32 @@ switch( N ) case TY_CSI_PS('x', 0) : reportTerminalParms ( 2); break; //VT100 case TY_CSI_PS('x', 1) : reportTerminalParms ( 3); break; //VT100 + case TY_CSI_PS_SP('q', 0) : /* fall through */ + case TY_CSI_PS_SP('q', 1) : emit cursorChanged(KeyboardCursorShape::BlockCursor, true ); break; + case TY_CSI_PS_SP('q', 2) : emit cursorChanged(KeyboardCursorShape::BlockCursor, false); break; + case TY_CSI_PS_SP('q', 3) : emit cursorChanged(KeyboardCursorShape::UnderlineCursor, true ); break; + case TY_CSI_PS_SP('q', 4) : emit cursorChanged(KeyboardCursorShape::UnderlineCursor, false); break; + case TY_CSI_PS_SP('q', 5) : emit cursorChanged(KeyboardCursorShape::IBeamCursor, true ); break; + case TY_CSI_PS_SP('q', 6) : emit cursorChanged(KeyboardCursorShape::IBeamCursor, false); break; + 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('E' ) : _currentScreen->cursorNextLine (p ); break; //VT100 + case TY_CSI_PN('F' ) : _currentScreen->cursorPreviousLine (p ); break; //VT100 case TY_CSI_PN('G' ) : _currentScreen->setCursorX (p ); break; //LINUX case TY_CSI_PN('H' ) : _currentScreen->setCursorYX (p, q); break; //VT100 - case TY_CSI_PN('I' ) : _currentScreen->Tabulate (p ); break; + case TY_CSI_PN('I' ) : _currentScreen->tab (p ); break; case TY_CSI_PN('L' ) : _currentScreen->insertLines (p ); break; case TY_CSI_PN('M' ) : _currentScreen->deleteLines (p ); break; case TY_CSI_PN('P' ) : _currentScreen->deleteChars (p ); break; case TY_CSI_PN('S' ) : _currentScreen->scrollUp (p ); break; case TY_CSI_PN('T' ) : _currentScreen->scrollDown (p ); break; case TY_CSI_PN('X' ) : _currentScreen->eraseChars (p ); break; - case TY_CSI_PN('Z' ) : _currentScreen->backTabulate (p ); break; + case TY_CSI_PN('Z' ) : _currentScreen->backtab (p ); break; + case TY_CSI_PN('b' ) : _currentScreen->repeatChars (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 @@ -656,8 +697,8 @@ switch( N ) case TY_CSI_PR('l', 2) : resetMode (MODE_Ansi ); break; //VT100 - case TY_CSI_PR('h', 3) : clearScreenAndSetColumns(132); break; //VT100 - case TY_CSI_PR('l', 3) : clearScreenAndSetColumns(80); break; //VT100 + case TY_CSI_PR('h', 3) : setMode (MODE_132Columns);break; //VT100 + case TY_CSI_PR('l', 3) : resetMode (MODE_132Columns);break; //VT100 case TY_CSI_PR('h', 4) : /* IGNORED: soft scrolling */ break; //VT100 case TY_CSI_PR('l', 4) : /* IGNORED: soft scrolling */ break; //VT100 @@ -695,6 +736,9 @@ switch( N ) case TY_CSI_PR('s', 25) : saveMode (MODE_Cursor ); break; //VT100 case TY_CSI_PR('r', 25) : restoreMode (MODE_Cursor ); break; //VT100 + case TY_CSI_PR('h', 40) : setMode(MODE_Allow132Columns ); break; // XTERM + case TY_CSI_PR('l', 40) : resetMode(MODE_Allow132Columns ); break; // XTERM + case TY_CSI_PR('h', 41) : /* IGNORED: obsolete more(1) fix */ break; //XTERM case TY_CSI_PR('l', 41) : /* IGNORED: obsolete more(1) fix */ break; //XTERM case TY_CSI_PR('s', 41) : /* IGNORED: obsolete more(1) fix */ break; //XTERM @@ -716,14 +760,14 @@ switch( N ) // SET_BTN_EVENT_MOUSE 1002 // SET_ANY_EVENT_MOUSE 1003 // - + //Note about mouse modes: //There are four mouse modes which xterm-compatible terminals can support - 1000,1001,1002,1003 //Konsole currently supports mode 1000 (basic mouse press and release) and mode 1002 (dragging the mouse). - //TODO: Implementation of mouse modes 1001 (something called hilight tracking) and + //TODO: Implementation of mouse modes 1001 (something called highlight 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 @@ -744,6 +788,26 @@ switch( N ) 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', 1004) : _reportFocusEvents = true; break; + case TY_CSI_PR('l', 1004) : _reportFocusEvents = false; break; + + case TY_CSI_PR('h', 1005) : setMode (MODE_Mouse1005); break; //XTERM + case TY_CSI_PR('l', 1005) : resetMode (MODE_Mouse1005); break; //XTERM + case TY_CSI_PR('s', 1005) : saveMode (MODE_Mouse1005); break; //XTERM + case TY_CSI_PR('r', 1005) : restoreMode (MODE_Mouse1005); break; //XTERM + + case TY_CSI_PR('h', 1006) : setMode (MODE_Mouse1006); break; //XTERM + case TY_CSI_PR('l', 1006) : resetMode (MODE_Mouse1006); break; //XTERM + case TY_CSI_PR('s', 1006) : saveMode (MODE_Mouse1006); break; //XTERM + case TY_CSI_PR('r', 1006) : restoreMode (MODE_Mouse1006); break; //XTERM + + case TY_CSI_PR('h', 1015) : setMode (MODE_Mouse1015); break; //URXVT + case TY_CSI_PR('l', 1015) : resetMode (MODE_Mouse1015); break; //URXVT + case TY_CSI_PR('s', 1015) : saveMode (MODE_Mouse1015); break; //URXVT + case TY_CSI_PR('r', 1015) : restoreMode (MODE_Mouse1015); break; //URXVT + + case TY_CSI_PR('h', 1034) : /* IGNORED: 8bitinput activation */ break; //XTERM + case TY_CSI_PR('h', 1047) : setMode (MODE_AppScreen); break; //XTERM case TY_CSI_PR('l', 1047) : _screen[1]->clearEntireScreen(); resetMode(MODE_AppScreen); break; //XTERM case TY_CSI_PR('s', 1047) : saveMode (MODE_AppScreen); break; //XTERM @@ -760,6 +824,11 @@ switch( N ) 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 + case TY_CSI_PR('h', 2004) : setMode (MODE_BracketedPaste); break; //XTERM + case TY_CSI_PR('l', 2004) : resetMode (MODE_BracketedPaste); break; //XTERM + case TY_CSI_PR('s', 2004) : saveMode (MODE_BracketedPaste); break; //XTERM + case TY_CSI_PR('r', 2004) : restoreMode (MODE_BracketedPaste); break; //XTERM + //FIXME: weird DEC reset sequence case TY_CSI_PE('p' ) : /* IGNORED: reset ( ) */ break; @@ -784,35 +853,20 @@ switch( N ) case TY_CSI_PG('c' ) : reportSecondaryAttributes( ); break; //VT100 - default : ReportErrorToken(); break; + default: + reportDecodingError(); + break; }; } void Vt102Emulation::clearScreenAndSetColumns(int columnCount) { - setImageSize(_currentScreen->getLines(),columnCount); + setImageSize(_currentScreen->getLines(),columnCount); clearEntireScreen(); - setDefaultMargins(); + setDefaultMargins(); _currentScreen->setCursorYX(0,0); } -/* ------------------------------------------------------------------------- */ -/* */ -/* Terminal to Host protocol */ -/* */ -/* ------------------------------------------------------------------------- */ - -/* - Outgoing bytes originate from several sources: - - - Replies to Enquieries. - - Mouse Events - - Keyboard Events -*/ - -/*! -*/ - void Vt102Emulation::sendString(const char* s , int length) { if ( length >= 0 ) @@ -821,43 +875,33 @@ void Vt102Emulation::sendString(const char* s , int length) 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); +{ + const size_t sz = 20; + char tmp[sz]; + const size_t r = snprintf(tmp, sz, "\033[%d;%dR",_currentScreen->getCursorY()+1,_currentScreen->getCursorX()+1); + if (sz <= r) { + qWarning("Vt102Emulation::reportCursorPosition: Buffer too small\n"); + } sendString(tmp); } -/* - What follows here is rather obsolete and faked stuff. - The correspondent enquieries are neverthenless issued. -*/ - -/*! -*/ - void Vt102Emulation::reportTerminalType() { // Primary device attribute response (Request was: ^[[0c or ^[[c (from TT321 Users Guide)) - // VT220: ^[[?63;1;2;3;6;7;8c (list deps on emul. capabilities) - // VT100: ^[[?1;2c - // VT101: ^[[?1;0c - // VT102: ^[[?6v + // VT220: ^[[?63;1;2;3;6;7;8c (list deps on emul. capabilities) + // VT100: ^[[?1;2c + // VT101: ^[[?1;0c + // VT102: ^[[?6v if (getMode(MODE_Ansi)) - sendString("\033[?1;2c"); // I'm a VT100 + sendString("\033[?1;2c"); // I'm a VT100 else - sendString("\033/Z"); // I'm a VT52 + sendString("\033/Z"); // I'm a VT52 } void Vt102Emulation::reportSecondaryAttributes() { - // Seconday device attribute response (Request was: ^[[>0c or ^[[>c) + // Secondary device attribute response (Request was: ^[[>0c or ^[[>c) if (getMode(MODE_Ansi)) sendString("\033[>0;115;0c"); // Why 115? ;) else @@ -867,95 +911,153 @@ void Vt102Emulation::reportSecondaryAttributes() void Vt102Emulation::reportTerminalParms(int p) // DECREPTPARM -{ char tmp[100]; - sprintf(tmp,"\033[%d;1;1;112;112;1;0x",p); // not really true. +{ + const size_t sz = 100; + char tmp[sz]; + const size_t r = snprintf(tmp, sz, "\033[%d;1;1;112;112;1;0x",p); // not really true. + if (sz <= r) { + qWarning("Vt102Emulation::reportTerminalParms: Buffer too small\n"); + } sendString(tmp); } -/*! -*/ - void Vt102Emulation::reportStatus() { sendString("\033[0n"); //VT100. Device status report. 0 = Ready. } -/*! -*/ - -#define ANSWER_BACK "" // This is really obsolete VT100 stuff. - void Vt102Emulation::reportAnswerBack() { + // FIXME - Test this with VTTEST + // This is really obsolete VT100 stuff. + const char* ANSWER_BACK = ""; sendString(ANSWER_BACK); } -// Mouse Handling ---------------------------------------------------------- -- - /*! - Mouse clicks are possibly reported to the client - application if it has issued interest in them. - They are normally consumed by the widget for copy - and paste, but may be propagated from the widget - when gui->setMouseMarks is set via setMode(MODE_Mouse1000). - - `x',`y' are 1-based. - `ev' (event) indicates the button pressed (0-2) - or a general mouse release (3). + `cx',`cy' are 1-based. + `cb' indicates the button pressed or released (0-2) or scroll event (4-5). eventType represents the kind of mouse action that occurred: - 0 = Mouse button press or release - 1 = Mouse drag + 0 = Mouse button press + 1 = Mouse drag + 2 = Mouse button release */ void Vt102Emulation::sendMouseEvent( int cb, int cx, int cy , int eventType ) -{ char tmp[20]; - if ( cx<1 || cy<1 ) return; - // normal buttons are passed as 0x20 + button, - // mouse wheel (buttons 4,5) as 0x5c + button - if (cb >= 4) cb += 0x3c; +{ + if (cx < 1 || cy < 1) + return; - //Mouse motion handling - if ( (getMode(MODE_Mouse1002) || getMode(MODE_Mouse1003)) && eventType == 1 ) - cb += 0x20; //add 32 to signify motion event + // With the exception of the 1006 mode, button release is encoded in cb. + // Note that if multiple extensions are enabled, the 1006 is used, so it's okay to check for only that. + if (eventType == 2 && !getMode(MODE_Mouse1006)) + cb = 3; - sprintf(tmp,"\033[M%c%c%c",cb+0x20,cx+0x20,cy+0x20); - sendString(tmp); + // 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 + + char command[64]; + command[0] = '\0'; + // Check the extensions in decreasing order of preference. Encoding the release event above assumes that 1006 comes first. + if (getMode(MODE_Mouse1006)) { + snprintf(command, sizeof(command), "\033[<%d;%d;%d%c", cb, cx, cy, eventType == 2 ? 'm' : 'M'); + } else if (getMode(MODE_Mouse1015)) { + snprintf(command, sizeof(command), "\033[%d;%d;%dM", cb + 0x20, cx, cy); + } else if (getMode(MODE_Mouse1005)) { + if (cx <= 2015 && cy <= 2015) { + // The xterm extension uses UTF-8 (up to 2 bytes) to encode + // coordinate+32, no matter what the locale is. We could easily + // convert manually, but QString can also do it for us. + QChar coords[2]; + coords[0] = QChar(cx + 0x20); + coords[1] = QChar(cy + 0x20); + QString coordsStr = QString(coords, 2); + QByteArray utf8 = coordsStr.toUtf8(); + snprintf(command, sizeof(command), "\033[M%c%s", cb + 0x20, utf8.constData()); + } + } else if (cx <= 223 && cy <= 223) { + snprintf(command, sizeof(command), "\033[M%c%c%c", cb + 0x20, cx + 0x20, cy + 0x20); + } + + sendString(command); } -// Keyboard Handling ------------------------------------------------------- -- +/** + * The focus lost event can be used by Vim (or other terminal applications) + * to recognize that the konsole window has lost focus. + * The escape sequence is also used by iTerm2. + * Vim needs the following plugin to be installed to convert the escape + * sequence into the FocusLost autocmd: https://github.com/sjl/vitality.vim + */ +void Vt102Emulation::focusLost(void) +{ + if (_reportFocusEvents) + sendString("\033[O"); +} -#define encodeMode(M,B) BITS(B,getMode(M)) -#define encodeStat(M,B) BITS(B,((ev->modifiers() & (M)) == (M))) +/** + * The focus gained event can be used by Vim (or other terminal applications) + * to recognize that the konsole window has gained focus again. + * The escape sequence is also used by iTerm2. + * Vim needs the following plugin to be installed to convert the escape + * sequence into the FocusGained autocmd: https://github.com/sjl/vitality.vim + */ +void Vt102Emulation::focusGained(void) +{ + if (_reportFocusEvents) + sendString("\033[I"); +} void Vt102Emulation::sendText( const QString& text ) { - if (!text.isEmpty()) { - QKeyEvent event(QEvent::KeyPress, - 0, - Qt::NoModifier, + if (!text.isEmpty()) + { + QKeyEvent event(QEvent::KeyPress, + 0, + Qt::NoModifier, text); - sendKeyEvent(&event); // expose as a big fat keypress event + sendKeyEvent(&event, false); // expose as a big fat keypress event } - } - -void Vt102Emulation::sendKeyEvent( QKeyEvent* event ) +void Vt102Emulation::sendKeyEvent(QKeyEvent* event, bool fromPaste) { Qt::KeyboardModifiers modifiers = event->modifiers(); KeyboardTranslator::States states = KeyboardTranslator::NoState; // get current states - if ( getMode(MODE_NewLine) ) states |= KeyboardTranslator::NewLineState; - if ( getMode(MODE_Ansi) ) states |= KeyboardTranslator::AnsiState; - if ( getMode(MODE_AppCuKeys)) states |= KeyboardTranslator::CursorKeysState; - if ( getMode(MODE_AppScreen)) states |= KeyboardTranslator::AlternateScreenState; + if (getMode(MODE_NewLine) ) states |= KeyboardTranslator::NewLineState; + if (getMode(MODE_Ansi) ) states |= KeyboardTranslator::AnsiState; + if (getMode(MODE_AppCuKeys)) states |= KeyboardTranslator::CursorKeysState; + if (getMode(MODE_AppScreen)) states |= KeyboardTranslator::AlternateScreenState; + if (getMode(MODE_AppKeyPad) && (modifiers & Qt::KeypadModifier)) + states |= KeyboardTranslator::ApplicationKeypadState; + + // check flow control state + if (modifiers & KeyboardTranslator::CTRL_MOD) + { + switch (event->key()) { + case Qt::Key_S: + emit flowControlKeyPressed(true); + break; + case Qt::Key_Q: + case Qt::Key_C: // cancel flow control + emit flowControlKeyPressed(false); + break; + } + } // lookup key binding if ( _keyTranslator ) { - KeyboardTranslator::Entry entry = _keyTranslator->findEntry( - event->key() , + KeyboardTranslator::Entry entry = _keyTranslator->findEntry( + event->key() , modifiers, states ); @@ -967,40 +1069,66 @@ void Vt102Emulation::sendKeyEvent( QKeyEvent* event ) // (unless there is an entry defined for this particular combination // in the keyboard modifier) bool wantsAltModifier = entry.modifiers() & entry.modifierMask() & Qt::AltModifier; - bool wantsAnyModifier = entry.state() & entry.stateMask() & KeyboardTranslator::AnyModifierState; + bool wantsMetaModifier = entry.modifiers() & entry.modifierMask() & Qt::MetaModifier; + bool wantsAnyModifier = entry.state() & + entry.stateMask() & KeyboardTranslator::AnyModifierState; - if ( modifiers & Qt::AltModifier && !(wantsAltModifier || wantsAnyModifier) + if ( modifiers & Qt::AltModifier && !(wantsAltModifier || wantsAnyModifier) && !event->text().isEmpty() ) { textToSend.prepend("\033"); } + if ( modifiers & Qt::MetaModifier && !(wantsMetaModifier || wantsAnyModifier) + && !event->text().isEmpty() ) + { + textToSend.prepend("\030@s"); + } if ( entry.command() != KeyboardTranslator::NoCommand ) { - if (entry.command() & KeyboardTranslator::EraseCommand) - textToSend += getErase(); + if (entry.command() & KeyboardTranslator::EraseCommand) { + textToSend += eraseChar(); + } else { + Q_EMIT handleCommandFromKeyboard(entry.command()); + } + // TODO command handling } - else if ( !entry.text().isEmpty() ) + else if ( !entry.text().isEmpty() ) { - textToSend += _codec->fromUnicode(entry.text(true,modifiers)); + textToSend += _codec->fromUnicode(QString::fromUtf8(entry.text(true,modifiers))); } - else + else if((modifiers & KeyboardTranslator::CTRL_MOD) && event->key() >= 0x40 && event->key() < 0x5f) { + textToSend += (event->key() & 0x1f); + } + else if(event->key() == Qt::Key_Tab) { + textToSend += 0x09; + } + else if (event->key() == Qt::Key_PageUp) { + textToSend += "\033[5~"; + } + else if (event->key() == Qt::Key_PageDown) { + textToSend += "\033[6~"; + } + else { textToSend += _codec->fromUnicode(event->text()); + } - sendData( textToSend.constData() , textToSend.length() ); + if (!fromPaste && textToSend.length()) { + Q_EMIT outputFromKeypressEvent(); + } + Q_EMIT 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. " + QString translatorError = tr("No keyboard translator available. " "The information needed to convert key presses " - "into characters to send to the terminal " + "into characters to send to the terminal " "is missing."); - reset(); - receiveData( translatorError.toAscii().constData() , translatorError.count() ); + receiveData( translatorError.toUtf8().constData() , translatorError.length() ); } } @@ -1012,7 +1140,7 @@ void Vt102Emulation::sendKeyEvent( QKeyEvent* event ) // Character Set Conversion ------------------------------------------------ -- -/* +/* The processing contains a VT100 specific code translation layer. It's still in use and mainly responsible for the line drawing graphics. @@ -1023,7 +1151,7 @@ void Vt102Emulation::sendKeyEvent( QKeyEvent* event ) in the pipeline. It only applies to tokens, which represent plain characters. - This conversion it eventually continued in TerminalDisplay.C, since + This conversion it eventually continued in TerminalDisplay.C, since it might involve VT100 enhanced fonts, which have these particular glyphs allocated in (0x00-0x1f) in their code page. */ @@ -1032,16 +1160,16 @@ void Vt102Emulation::sendKeyEvent( QKeyEvent* event ) // Apply current character map. -unsigned short Vt102Emulation::applyCharset(unsigned short c) +wchar_t Vt102Emulation::applyCharset(wchar_t c) { if (CHARSET.graphic && 0x5f <= c && c <= 0x7e) return vt100_graphics[c-0x5f]; - if (CHARSET.pound && c == '#' ) return 0xa3; //This mode is obsolete + if (CHARSET.pound && c == '#' ) return 0xa3; //This mode is obsolete return c; } /* "Charset" related part of the emulation state. - This configures the VT100 _charset filter. + This configures the VT100 charset filter. While most operation work on the current _screen, the following two are different. @@ -1049,12 +1177,12 @@ unsigned short Vt102Emulation::applyCharset(unsigned short c) void Vt102Emulation::resetCharset(int scrno) { - _charset[scrno].cu_cs = 0; - strncpy(_charset[scrno].charset,"BBBB",4); + _charset[scrno].cu_cs = 0; + qstrncpy(_charset[scrno].charset,"BBBB",4); _charset[scrno].sa_graphic = false; - _charset[scrno].sa_pound = false; + _charset[scrno].sa_pound = false; _charset[scrno].graphic = false; - _charset[scrno].pound = false; + _charset[scrno].pound = false; } void Vt102Emulation::setCharset(int n, int cs) // on both screens. @@ -1078,8 +1206,8 @@ void Vt102Emulation::useCharset(int n) void Vt102Emulation::setDefaultMargins() { - _screen[0]->setDefaultMargins(); - _screen[1]->setDefaultMargins(); + _screen[0]->setDefaultMargins(); + _screen[1]->setDefaultMargins(); } void Vt102Emulation::setMargins(int t, int b) @@ -1088,8 +1216,6 @@ void Vt102Emulation::setMargins(int t, int b) _screen[1]->setMargins(t, b); } -/*! Save the cursor position and the rendition attribute settings. */ - void Vt102Emulation::saveCursor() { CHARSET.sa_graphic = CHARSET.graphic; @@ -1100,8 +1226,6 @@ void Vt102Emulation::saveCursor() _currentScreen->saveCursor(); } -/*! Restore the cursor position and the rendition attribute settings. */ - void Vt102Emulation::restoreCursor() { CHARSET.graphic = CHARSET.sa_graphic; @@ -1131,28 +1255,46 @@ void Vt102Emulation::restoreCursor() void Vt102Emulation::resetModes() { - resetMode(MODE_Mouse1000); saveMode(MODE_Mouse1000); - resetMode(MODE_Mouse1001); saveMode(MODE_Mouse1001); - resetMode(MODE_Mouse1002); saveMode(MODE_Mouse1002); - resetMode(MODE_Mouse1003); saveMode(MODE_Mouse1003); + // MODE_Allow132Columns is not reset here + // to match Xterm's behaviour (see Xterm's VTReset() function) - resetMode(MODE_AppScreen); saveMode(MODE_AppScreen); - // here come obsolete modes - resetMode(MODE_AppCuKeys); saveMode(MODE_AppCuKeys); - resetMode(MODE_NewLine ); - setMode(MODE_Ansi ); + resetMode(MODE_132Columns); saveMode(MODE_132Columns); + resetMode(MODE_Mouse1000); saveMode(MODE_Mouse1000); + resetMode(MODE_Mouse1001); saveMode(MODE_Mouse1001); + resetMode(MODE_Mouse1002); saveMode(MODE_Mouse1002); + resetMode(MODE_Mouse1003); saveMode(MODE_Mouse1003); + resetMode(MODE_Mouse1005); saveMode(MODE_Mouse1005); + resetMode(MODE_Mouse1006); saveMode(MODE_Mouse1006); + resetMode(MODE_Mouse1015); saveMode(MODE_Mouse1015); + resetMode(MODE_BracketedPaste); saveMode(MODE_BracketedPaste); + + resetMode(MODE_AppScreen); saveMode(MODE_AppScreen); + resetMode(MODE_AppCuKeys); saveMode(MODE_AppCuKeys); + resetMode(MODE_AppKeyPad); saveMode(MODE_AppKeyPad); + resetMode(MODE_NewLine); + setMode(MODE_Ansi); } void Vt102Emulation::setMode(int m) { - _currParm.mode[m] = true; + _currentModes.mode[m] = true; switch (m) { + case MODE_132Columns: + if (getMode(MODE_Allow132Columns)) + clearScreenAndSetColumns(132); + else + _currentModes.mode[m] = false; + break; case MODE_Mouse1000: case MODE_Mouse1001: case MODE_Mouse1002: case MODE_Mouse1003: - emit programUsesMouseChanged(false); + emit programUsesMouseChanged(false); + break; + + case MODE_BracketedPaste: + emit programBracketedPasteModeChanged(true); break; case MODE_AppScreen : _screen[1]->clearSelection(); @@ -1168,18 +1310,27 @@ void Vt102Emulation::setMode(int m) void Vt102Emulation::resetMode(int m) { - _currParm.mode[m] = false; + _currentModes.mode[m] = false; switch (m) { - case MODE_Mouse1000 : + case MODE_132Columns: + if (getMode(MODE_Allow132Columns)) + clearScreenAndSetColumns(80); + break; + case MODE_Mouse1000 : case MODE_Mouse1001 : case MODE_Mouse1002 : case MODE_Mouse1003 : - emit programUsesMouseChanged(true); + emit programUsesMouseChanged(true); break; - case MODE_AppScreen : _screen[0]->clearSelection(); - setScreen(0); + case MODE_BracketedPaste: + emit programBracketedPasteModeChanged(false); + break; + + case MODE_AppScreen : + _screen[0]->clearSelection(); + setScreen(0); break; } if (m < MODES_SCREEN || m == MODE_NewLine) @@ -1191,77 +1342,40 @@ void Vt102Emulation::resetMode(int m) void Vt102Emulation::saveMode(int m) { - _saveParm.mode[m] = _currParm.mode[m]; + _savedModes.mode[m] = _currentModes.mode[m]; } void Vt102Emulation::restoreMode(int m) { - if (_saveParm.mode[m]) - setMode(m); - else + if (_savedModes.mode[m]) + setMode(m); + else resetMode(m); } bool Vt102Emulation::getMode(int m) { - return _currParm.mode[m]; + return _currentModes.mode[m]; } -char Vt102Emulation::getErase() const +char Vt102Emulation::eraseChar() const { KeyboardTranslator::Entry entry = _keyTranslator->findEntry( Qt::Key_Backspace, - 0, - 0); - if ( entry.text().count() > 0 ) - return entry.text()[0]; + Qt::NoModifier, + KeyboardTranslator::NoState); + if ( entry.text().length() > 0 ) + return entry.text().at(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() +void Vt102Emulation::reportDecodingError() { - if (ppos == 0 || ppos == 1 && (pbuf[0] & 0xff) >= 32) return; - printf("token: "); hexdump(pbuf,ppos); printf("\n"); + if (tokenBufferPos == 0 || ( tokenBufferPos == 1 && (tokenBuffer[0] & 0xff) >= 32) ) + return; + qCDebug(qtermwidgetLogger) << "Undecodable sequence:" << QString::fromWCharArray(tokenBuffer, tokenBufferPos); } -/*! -*/ - -void Vt102Emulation::ReportErrorToken() -{ -#ifndef NDEBUG - printf("undecodable "); scan_buffer_report(); -#endif -} - -//#include "moc_Vt102Emulation.cpp" +//#include "Vt102Emulation.moc" diff --git a/qtermwidget/src/Vt102Emulation.h b/qtermwidget/lib/Vt102Emulation.h similarity index 51% rename from qtermwidget/src/Vt102Emulation.h rename to qtermwidget/lib/Vt102Emulation.h index 4554c1b..fdbcecd 100644 --- a/qtermwidget/src/Vt102Emulation.h +++ b/qtermwidget/lib/Vt102Emulation.h @@ -1,10 +1,8 @@ /* This file is part of Konsole, an X terminal. - - Copyright (C) 2007 by Robert Knight - Copyright (C) 1997,1998 by Lars Doelle - Rewritten for QT4 by e_k , Copyright (C)2008 + Copyright 2007-2008 by Robert Knight + Copyright 1997,1998 by Lars Doelle This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by @@ -26,35 +24,36 @@ #define VT102EMULATION_H // Standard Library -#include +#include -// Qt -#include -#include -#include +// Qt +#include +#include +#include // Konsole #include "Emulation.h" #include "Screen.h" -#define MODE_AppScreen (MODES_SCREEN+0) -#define MODE_AppCuKeys (MODES_SCREEN+1) -#define MODE_AppKeyPad (MODES_SCREEN+2) -#define MODE_Mouse1000 (MODES_SCREEN+3) -#define MODE_Mouse1001 (MODES_SCREEN+4) -#define MODE_Mouse1002 (MODES_SCREEN+5) -#define MODE_Mouse1003 (MODES_SCREEN+6) -#define MODE_Ansi (MODES_SCREEN+7) -#define MODE_total (MODES_SCREEN+8) +#define MODE_AppScreen (MODES_SCREEN+0) // Mode #1 +#define MODE_AppCuKeys (MODES_SCREEN+1) // Application cursor keys (DECCKM) +#define MODE_AppKeyPad (MODES_SCREEN+2) // +#define MODE_Mouse1000 (MODES_SCREEN+3) // Send mouse X,Y position on press and release +#define MODE_Mouse1001 (MODES_SCREEN+4) // Use Highlight mouse tracking +#define MODE_Mouse1002 (MODES_SCREEN+5) // Use cell motion mouse tracking +#define MODE_Mouse1003 (MODES_SCREEN+6) // Use all motion mouse tracking +#define MODE_Mouse1005 (MODES_SCREEN+7) // Xterm-style extended coordinates +#define MODE_Mouse1006 (MODES_SCREEN+8) // 2nd Xterm-style extended coordinates +#define MODE_Mouse1015 (MODES_SCREEN+9) // Urxvt-style extended coordinates +#define MODE_Ansi (MODES_SCREEN+10) // Use US Ascii for character sets G0-G3 (DECANM) +#define MODE_132Columns (MODES_SCREEN+11) // 80 <-> 132 column mode switch (DECCOLM) +#define MODE_Allow132Columns (MODES_SCREEN+12) // Allow DECCOLM mode +#define MODE_BracketedPaste (MODES_SCREEN+13) // Xterm-style bracketed paste mode +#define MODE_total (MODES_SCREEN+14) namespace Konsole { -struct DECpar -{ - bool mode[MODE_total]; -}; - struct CharCodes { // coding info @@ -69,56 +68,49 @@ struct CharCodes /** * Provides an xterm compatible terminal emulation based on the DEC VT102 terminal. * A full description of this terminal can be found at http://vt100.net/docs/vt102-ug/ - * - * In addition, various additional xterm escape sequences are supported to provide + * + * In addition, various additional xterm escape sequences are supported to provide * features such as mouse input handling. * See http://rtfm.etla.org/xterm/ctlseq.html for a description of xterm's escape - * sequences. + * sequences. * */ class Vt102Emulation : public Emulation -{ +{ Q_OBJECT public: - /** Constructs a new emulation */ Vt102Emulation(); - ~Vt102Emulation(); - - // reimplemented - virtual void clearEntireScreen(); - virtual void reset(); - - // reimplemented - virtual char getErase() const; - -public slots: + ~Vt102Emulation() override; + + // reimplemented from Emulation + void clearEntireScreen() override; + void reset() override; + char eraseChar() const override; + +public slots: + // reimplemented from Emulation + void sendString(const char*,int length = -1) override; + void sendText(const QString& text) override; + void sendKeyEvent(QKeyEvent*, bool fromPaste) override; + void sendMouseEvent(int buttons, int column, int line, int eventType) override; + virtual void focusLost(); + virtual void focusGained(); - // reimplemented - virtual void sendString(const char*,int length = -1); - virtual void sendText(const QString& text); - virtual void sendKeyEvent(QKeyEvent*); - virtual void sendMouseEvent( int buttons, int column, int line , int eventType ); - protected: - // reimplemented - virtual void setMode (int mode); - virtual void resetMode (int mode); - - // reimplemented - virtual void receiveChar(int cc); - + // reimplemented from Emulation + void setMode(int mode) override; + void resetMode(int mode) override; + void receiveChar(wchar_t cc) override; private slots: - //causes changeTitle() to be emitted for each (int,QString) pair in pendingTitleUpdates //used to buffer multiple title updates void updateTitle(); - private: - unsigned short applyCharset(unsigned short c); + wchar_t applyCharset(wchar_t c); void setCharset(int n, int cs); void useCharset(int n); void setAndUseCharset(int n, int cs); @@ -134,29 +126,35 @@ private: bool getMode (int mode); // saves the current boolean value of 'mode' void saveMode (int mode); - // restores the boolean value of 'mode' + // restores the boolean value of 'mode' void restoreMode(int mode); // resets all modes + // (except MODE_Allow132Columns) void resetModes(); - void resetToken(); -#define MAXPBUF 80 - void pushToToken(int cc); - int pbuf[MAXPBUF]; //FIXME: overflow? - int ppos; + void resetTokenizer(); + #define MAX_TOKEN_LENGTH 256 // Max length of tokens (e.g. window title) + void addToCurrentToken(wchar_t cc); + wchar_t tokenBuffer[MAX_TOKEN_LENGTH]; //FIXME: overflow? + int tokenBufferPos; #define MAXARGS 15 void addDigit(int dig); void addArgument(); int argv[MAXARGS]; int argc; void initTokenizer(); - int tbl[256]; + int prevCC; - void scan_buffer_report(); //FIXME: rename - void ReportErrorToken(); //FIXME: rename + // Set of flags for each of the ASCII characters which indicates + // what category they fall into (printable character, control, digit etc.) + // for the purposes of decoding terminal output + int charClass[256]; - void tau(int code, int p, int q); - void XtermHack(); + void reportDecodingError(); + + void processToken(int code, wchar_t p, int q); + void processWindowAttributeChange(); + void requestWindowAttribute(int); void reportTerminalType(); void reportSecondaryAttributes(); @@ -174,17 +172,28 @@ private: CharCodes _charset[2]; - DECpar _currParm; - DECpar _saveParm; + class TerminalState + { + public: + // Initializes all modes to false + TerminalState() + { memset(&mode,false,MODE_total * sizeof(bool)); } - //hash table and timer for buffering calls to the session instance + bool mode[MODE_total]; + }; + + TerminalState _currentModes; + TerminalState _savedModes; + + //hash table and timer for buffering calls to the session instance //to update the name of the session //or window title. - //these calls occur when certain escape sequences are seen in the + //these calls occur when certain escape sequences are seen in the //output from the terminal QHash _pendingTitleUpdates; QTimer* _titleUpdateTimer; - + + bool _reportFocusEvents; }; } diff --git a/qtermwidget/lib/color-schemes/BlackOnLightYellow.colorscheme b/qtermwidget/lib/color-schemes/BlackOnLightYellow.colorscheme new file mode 100644 index 0000000..5150ea1 --- /dev/null +++ b/qtermwidget/lib/color-schemes/BlackOnLightYellow.colorscheme @@ -0,0 +1,94 @@ +[Background] +Color=255,255,221 + +[BackgroundIntense] +Color=255,255,221 + +[BackgroundFaint] +Color=255,255,221 + +[Color0] +Color=0,0,0 + +[Color0Intense] +Color=104,104,104 + +[Color0Faint] +Color=192,192,192 + +[Color1] +Color=178,24,24 + +[Color1Intense] +Color=255,84,84 + +[Color1Faint] +Color=224,142,142 + +[Color2] +Color=24,178,24 + +[Color2Intense] +Color=84,255,84 + +[Color2Faint] +Color=142,224,142 + +[Color3] +Color=178,104,24 + +[Color3Intense] +Color=255,255,84 + +[Color3Faint] +Color=224,224,142 + +[Color4] +Color=24,24,178 + +[Color4Intense] +Color=84,84,255 + +[Color4Faint] +Color=142,142,224 + +[Color5] +Color=178,24,178 + +[Color5Intense] +Color=255,84,255 + +[Color5Faint] +Color=224,142,224 + +[Color6] +Color=24,178,178 + +[Color6Intense] +Color=84,255,255 + +[Color6Faint] +Color=142,224,224 + +[Color7] +Color=178,178,178 + +[Color7Intense] +Color=255,255,255 + +[Color7Faint] +Color=142,142,142 + +[Foreground] +Color=0,0,0 + +[ForegroundIntense] +Bold=true +Color=0,0,0 + +[ForegroundFaint] +Color=0,0,0 + +[General] +Description=Black on Light Yellow +Opacity=1 diff --git a/qtermwidget/lib/color-schemes/BlackOnRandomLight.colorscheme b/qtermwidget/lib/color-schemes/BlackOnRandomLight.colorscheme new file mode 100644 index 0000000..4d6f831 --- /dev/null +++ b/qtermwidget/lib/color-schemes/BlackOnRandomLight.colorscheme @@ -0,0 +1,104 @@ +[Background] +Bold=false +Color=247,247,214 +Transparency=true +MaxRandomHue=340 + +[BackgroundIntense] +Bold=false +Color=255,255,221 +Transparency=true + +[Color0] +Bold=false +Color=0,0,0 +Transparency=false + +[Color0Intense] +Bold=false +Color=104,104,104 +Transparency=false + +[Color1] +Bold=false +Color=178,24,24 +Transparency=false + +[Color1Intense] +Bold=false +Color=255,84,84 +Transparency=false + +[Color2] +Bold=false +Color=24,178,24 +Transparency=false + +[Color2Intense] +Bold=false +Color=84,255,84 +Transparency=false + +[Color3] +Bold=false +Color=178,104,24 +Transparency=false + +[Color3Intense] +Bold=false +Color=255,255,84 +Transparency=false + +[Color4] +Bold=false +Color=24,24,178 +Transparency=false + +[Color4Intense] +Bold=false +Color=84,84,255 +Transparency=false + +[Color5] +Bold=false +Color=178,24,178 +Transparency=false + +[Color5Intense] +Bold=false +Color=255,84,255 +Transparency=false + +[Color6] +Bold=false +Color=24,178,178 +Transparency=false + +[Color6Intense] +Bold=false +Color=84,255,255 +Transparency=false + +[Color7] +Bold=false +Color=178,178,178 +Transparency=false + +[Color7Intense] +Bold=false +Color=255,255,255 +Transparency=false + +[Foreground] +Bold=false +Color=0,0,0 +Transparency=false + +[ForegroundIntense] +Bold=true +Color=0,0,0 +Transparency=false + +[General] +Description=Black on Random Light +Opacity=1 diff --git a/qtermwidget/lib/color-schemes/BlackOnWhite.colorscheme b/qtermwidget/lib/color-schemes/BlackOnWhite.colorscheme new file mode 100644 index 0000000..73cc3c8 --- /dev/null +++ b/qtermwidget/lib/color-schemes/BlackOnWhite.colorscheme @@ -0,0 +1,94 @@ +[Background] +Color=255,255,255 + +[BackgroundIntense] +Color=255,255,255 + +[BackgroundFaint] +Color=255,255,255 + +[Color0] +Color=0,0,0 + +[Color0Intense] +Color=104,104,104 + +[Color0Faint] +Color=192,192,192 + +[Color1] +Color=178,24,24 + +[Color1Intense] +Color=255,84,84 + +[Color1Faint] +Color=224,142,142 + +[Color2] +Color=24,178,24 + +[Color2Intense] +Color=84,255,84 + +[Color2Faint] +Color=142,224,142 + +[Color3] +Color=178,104,24 + +[Color3Intense] +Color=255,255,84 + +[Color3Faint] +Color=224,224,142 + +[Color4] +Color=24,24,178 + +[Color4Intense] +Color=84,84,255 + +[Color4Faint] +Color=142,142,224 + +[Color5] +Color=178,24,178 + +[Color5Intense] +Color=255,84,255 + +[Color5Faint] +Color=224,142,224 + +[Color6] +Color=24,178,178 + +[Color6Intense] +Color=84,255,255 + +[Color6Faint] +Color=142,224,224 + +[Color7] +Color=178,178,178 + +[Color7Intense] +Color=255,255,255 + +[Color7Faint] +Color=142,142,142 + +[Foreground] +Color=0,0,0 + +[ForegroundIntense] +Bold=true +Color=0,0,0 + +[ForegroundFaint] +Color=0,0,0 + +[General] +Description=Black on White +Opacity=1 diff --git a/qtermwidget/lib/color-schemes/BreezeModified.colorscheme b/qtermwidget/lib/color-schemes/BreezeModified.colorscheme new file mode 100644 index 0000000..bb53443 --- /dev/null +++ b/qtermwidget/lib/color-schemes/BreezeModified.colorscheme @@ -0,0 +1,95 @@ +[Background] +Color=49,54,59 + +[BackgroundFaint] +Color=49,54,59 + +[BackgroundIntense] +Color=35,38,41 + +[Color0] +Color=7,54,66 + +[Color0Faint] +Color=32,43,54 + +[Color0Intense] +Color=255,85,0 + +[Color1] +Color=237,21,21 + +[Color1Faint] +Color=120,50,40 + +[Color1Intense] +Color=192,57,43 + +[Color2] +Color=17,209,22 + +[Color2Faint] +Color=23,162,98 + +[Color2Intense] +Color=28,220,154 + +[Color3] +Color=246,116,0 + +[Color3Faint] +Color=182,86,25 + +[Color3Intense] +Color=253,188,75 + +[Color4] +Color=29,153,243 + +[Color4Faint] +Color=27,102,143 + +[Color4Intense] +Color=61,174,233 + +[Color5] +Color=155,89,182 + +[Color5Faint] +Color=97,74,115 + +[Color5Intense] +Color=142,68,173 + +[Color6] +Color=26,188,156 + +[Color6Faint] +Color=24,108,96 + +[Color6Intense] +Color=22,160,133 + +[Color7] +Color=239,240,241 + +[Color7Faint] +Color=99,104,109 + +[Color7Intense] +Color=252,252,252 + +[Foreground] +Color=239,240,241 + +[ForegroundFaint] +Color=220,230,231 + +[ForegroundIntense] +Color=252,252,252 + +[General] +Description=BreezeModified +Opacity=0.95 +Wallpaper= + diff --git a/qtermwidget/lib/color-schemes/DarkPastels.colorscheme b/qtermwidget/lib/color-schemes/DarkPastels.colorscheme new file mode 100644 index 0000000..fdcb02a --- /dev/null +++ b/qtermwidget/lib/color-schemes/DarkPastels.colorscheme @@ -0,0 +1,103 @@ +[Background] +Bold=false +Color=44,44,44 +Transparency=false + +[BackgroundIntense] +Bold=true +Color=44,44,44 +Transparency=false + +[Color0] +Bold=false +Color=63,63,63 +Transparency=false + +[Color0Intense] +Bold=true +Color=112,144,128 +Transparency=false + +[Color1] +Bold=false +Color=112,80,80 +Transparency=false + +[Color1Intense] +Bold=true +Color=220,163,163 +Transparency=false + +[Color2] +Bold=false +Color=96,180,138 +Transparency=false + +[Color2Intense] +Bold=true +Color=114,213,163 +Transparency=false + +[Color3] +Bold=false +Color=223,175,143 +Transparency=false + +[Color3Intense] +Bold=true +Color=240,223,175 +Transparency=false + +[Color4] +Bold=false +Color=154,184,215 +Transparency=false + +[Color4Intense] +Bold=true +Color=148,191,243 +Transparency=false + +[Color5] +Bold=false +Color=220,140,195 +Transparency=false + +[Color5Intense] +Bold=true +Color=236,147,211 +Transparency=false + +[Color6] +Bold=false +Color=140,208,211 +Transparency=false + +[Color6Intense] +Bold=true +Color=147,224,227 +Transparency=false + +[Color7] +Bold=false +Color=220,220,204 +Transparency=false + +[Color7Intense] +Bold=true +Color=255,255,255 +Transparency=false + +[Foreground] +Bold=false +Color=220,220,204 +Transparency=false + +[ForegroundIntense] +Bold=true +Color=220,220,204 +Transparency=false + +[General] +Description=Dark Pastels +Opacity=1 diff --git a/qtermwidget/lib/color-schemes/GreenOnBlack.colorscheme b/qtermwidget/lib/color-schemes/GreenOnBlack.colorscheme new file mode 100644 index 0000000..4d55b3a --- /dev/null +++ b/qtermwidget/lib/color-schemes/GreenOnBlack.colorscheme @@ -0,0 +1,104 @@ + +[Background] +Bold=false +Color=0,0,0 +Transparency=false + +[BackgroundIntense] +Bold=false +Color=0,0,0 +Transparency=false + +[Color0] +Bold=false +Color=0,0,0 +Transparency=false + +[Color0Intense] +Bold=false +Color=104,104,104 +Transparency=false + +[Color1] +Bold=false +Color=250,75,75 +Transparency=false + +[Color1Intense] +Bold=false +Color=255,84,84 +Transparency=false + +[Color2] +Bold=false +Color=24,178,24 +Transparency=false + +[Color2Intense] +Bold=false +Color=84,255,84 +Transparency=false + +[Color3] +Bold=false +Color=178,104,24 +Transparency=false + +[Color3Intense] +Bold=false +Color=255,255,84 +Transparency=false + +[Color4] +Bold=false +Color=92,167,251 +Transparency=false + +[Color4Intense] +Bold=false +Color=84,84,255 +Transparency=false + +[Color5] +Bold=false +Color=225,30,225 +Transparency=false + +[Color5Intense] +Bold=false +Color=255,84,255 +Transparency=false + +[Color6] +Bold=false +Color=24,178,178 +Transparency=false + +[Color6Intense] +Bold=false +Color=84,255,255 +Transparency=false + +[Color7] +Bold=false +Color=178,178,178 +Transparency=false + +[Color7Intense] +Bold=false +Color=255,255,255 +Transparency=false + +[Foreground] +Bold=false +Color=24,240,24 +Transparency=false + +[ForegroundIntense] +Bold=true +Color=24,240,24 +Transparency=false + +[General] +Description=Green on Black +Opacity=1 diff --git a/qtermwidget/lib/color-schemes/Linux.colorscheme b/qtermwidget/lib/color-schemes/Linux.colorscheme new file mode 100644 index 0000000..c9afb14 --- /dev/null +++ b/qtermwidget/lib/color-schemes/Linux.colorscheme @@ -0,0 +1,100 @@ +[Background] +Bold=false +Color=0,0,0 + +[BackgroundIntense] +Bold=false +Color=104,104,104 + +[Color0] +Bold=false +Color=0,0,0 + + +[Color0Intense] +Bold=false +Color=104,104,104 + + +[Color1] +Bold=false +Color=178,24,24 + + +[Color1Intense] +Bold=false +Color=255,84,84 + + +[Color2] +Bold=false +Color=24,178,24 + + +[Color2Intense] +Bold=false +Color=84,255,84 + + +[Color3] +Bold=false +Color=178,104,24 + + +[Color3Intense] +Bold=false +Color=255,255,84 + + +[Color4] +Bold=false +Color=24,24,178 + + +[Color4Intense] +Bold=false +Color=84,84,255 + + +[Color5] +Bold=false +Color=178,24,178 + + +[Color5Intense] +Bold=false +Color=255,84,255 + + +[Color6] +Bold=false +Color=24,178,178 + + +[Color6Intense] +Bold=false +Color=84,255,255 + + +[Color7] +Bold=false +Color=178,178,178 + + +[Color7Intense] +Bold=false +Color=255,255,255 + + +[Foreground] +Bold=false +Color=178,178,178 + + +[ForegroundIntense] +Bold=false +Color=255,255,255 + + +[General] +Description=Linux Colors diff --git a/qtermwidget/lib/color-schemes/Solarized.colorscheme b/qtermwidget/lib/color-schemes/Solarized.colorscheme new file mode 100644 index 0000000..36529dd --- /dev/null +++ b/qtermwidget/lib/color-schemes/Solarized.colorscheme @@ -0,0 +1,93 @@ +[Color0] +Color=7,54,66 + +[Color0Intense] +Color=0,43,54 + +[Color0Faint] +Color=6,48,59 + +[Color1] +Color=220,50,47 + +[Color1Intense] +Color=203,75,22 + +[Color1Faint] +Color=147,33,31 + +[Color2] +Color=133,153,0 + +[Color2Intense] +Color=88,110,117 + +[Color2Faint] +Color=94,106,0 + +[Color3] +Color=181,137,0 + +[Color3Intense] +Color=101,123,131 + +[Color3Faint] +Color=138,103,0 + +[Color4] +Color=38,139,210 + +[Color4Intense] +Color=131,148,150 + +[Color4Faint] +Color=20,77,115 + +[Color5] +Color=211,54,130 + +[Color5Intense] +Color=108,113,196 + +[Color5Faint] +Color=120,30,75 + +[Color6] +Color=42,161,152 + +[Color6Intense] +Color=147,161,161 + +[Color6Faint] +Color=24,94,88 + +[Color7] +Color=238,232,213 + +[Color7Intense] +Color=253,246,227 + +[Color7Faint] +Color=171,167,154 + +[Background] +Color=0,43,54 + +[BackgroundIntense] +Color=7,54,66 + +[BackgroundFaint] +Color=0,43,54 + +[Foreground] +Color=131,148,150 + +[ForegroundIntense] +Color=147,161,161 + +[ForegroundFaint] +Color=106,119,121 + +[General] +Description=Solarized +Opacity=1 diff --git a/qtermwidget/lib/color-schemes/SolarizedLight.colorscheme b/qtermwidget/lib/color-schemes/SolarizedLight.colorscheme new file mode 100644 index 0000000..cd19002 --- /dev/null +++ b/qtermwidget/lib/color-schemes/SolarizedLight.colorscheme @@ -0,0 +1,93 @@ +[Color0] +Color=7,54,66 + +[Color0Intense] +Color=0,43,54 + +[Color0Faint] +Color=8,65,80 + +[Color1] +Color=220,50,47 + +[Color1Intense] +Color=203,75,22 + +[Color1Faint] +Color=222,81,81 + +[Color2] +Color=133,153,0 + +[Color2Intense] +Color=88,110,117 + +[Color2Faint] +Color=153,168,39 + +[Color3] +Color=181,137,0 + +[Color3Intense] +Color=101,123,131 + +[Color3Faint] +Color=213,170,49 + +[Color4] +Color=38,139,210 + +[Color4Intense] +Color=131,148,150 + +[Color4Faint] +Color=80,173,226 + +[Color5] +Color=211,54,130 + +[Color5Intense] +Color=108,113,196 + +[Color5Faint] +Color=223,92,158 + +[Color6] +Color=42,161,152 + +[Color6Intense] +Color=147,161,161 + +[Color6Faint] +Color=78,211,200 + +[Color7] +Color=238,232,213 + +[Color7Intense] +Color=253,246,227 + +[Color7Faint] +Color=238,232,213 + +[Background] +Color=253,246,227 + +[BackgroundIntense] +Color=238,232,213 + +[BackgroundFaint] +Color=253,246,227 + +[Foreground] +Color=101,123,131 + +[ForegroundIntense] +Color=88,110,117 + +[ForegroundFaint] +Color=141,172,182 + +[General] +Description=Solarized Light +Opacity=1 diff --git a/qtermwidget/lib/color-schemes/Tango.colorscheme b/qtermwidget/lib/color-schemes/Tango.colorscheme new file mode 100644 index 0000000..0a23d4c --- /dev/null +++ b/qtermwidget/lib/color-schemes/Tango.colorscheme @@ -0,0 +1,71 @@ +[General] +Description=Tango + +[Background] +Color=0,0,0 + +[BackgroundIntense] +Color=104,104,104 + +[Foreground] +;Color=211,215,207 +Color=255,255,255 + +[ForegroundIntense] +Color=255,255,255 + +; black +[Color0] +Color=0,0,0 + +[Color0Intense] +Color=85,87,83 + +; red +[Color1] +Color=204,0,0 + +[Color1Intense] +Color=239,41,41 + +; green +[Color2] +Color=78,154,6 + +[Color2Intense] +Color=138,226,52 + +; yellow +[Color3] +Color=196,160,0 + +[Color3Intense] +Color=252,233,79 + +; blue +[Color4] +Color=52,101,164 + +[Color4Intense] +Color=114,159,207 + +; magenta +[Color5] +Color=117,80,123 + +[Color5Intense] +Color=173,127,168 + +; aqua +[Color6] +Color=6,152,154 + +[Color6Intense] +Color=52,226,226 + +; grey +[Color7] +Color=211,215,207 + +[Color7Intense] +Color=238,238,236 diff --git a/qtermwidget/lib/color-schemes/Ubuntu.colorscheme b/qtermwidget/lib/color-schemes/Ubuntu.colorscheme new file mode 100644 index 0000000..3652506 --- /dev/null +++ b/qtermwidget/lib/color-schemes/Ubuntu.colorscheme @@ -0,0 +1,67 @@ +[General] +Description=Ubuntu +Opacity=1 +Wallpaper= + +[Background] +Color=48,10,36 +MaxRandomHue=0 +MaxRandomSaturation=0 +MaxRandomValue=0 + +[BackgroundIntense] +Color=48,10,36 + +[Color0] +Color=46,52,54 + +[Color0Intense] +Color=85,87,83 + +[Color1] +Color=204,0,0 + +[Color1Intense] +Color=239,41,41 + +[Color2] +Color=78,154,6 + +[Color2Intense] +Color=138,226,52 + +[Color3] +Color=196,160,0 + +[Color3Intense] +Color=252,233,79 + +[Color4] +Color=52,101,164 + +[Color4Intense] +Color=114,159,207 + +[Color5] +Color=117,80,123 + +[Color5Intense] +Color=173,127,168 + +[Color6] +Color=6,152,154 + +[Color6Intense] +Color=52,226,226 + +[Color7] +Color=211,215,207 + +[Color7Intense] +Color=238,238,236 + +[Foreground] +Color=238,238,236 + +[ForegroundIntense] +Color=238,238,236 \ No newline at end of file diff --git a/qtermwidget/lib/color-schemes/WhiteOnBlack.colorscheme b/qtermwidget/lib/color-schemes/WhiteOnBlack.colorscheme new file mode 100644 index 0000000..c3d801d --- /dev/null +++ b/qtermwidget/lib/color-schemes/WhiteOnBlack.colorscheme @@ -0,0 +1,94 @@ +[Background] +Color=0,0,0 + +[BackgroundIntense] +Color=0,0,0 + +[BackgroundFaint] +Color=0,0,0 + +[Color0] +Color=0,0,0 + +[Color0Intense] +Color=104,104,104 + +[Color0Faint] +Color=24,24,24 + +[Color1] +Color=178,24,24 + +[Color1Intense] +Color=255,84,84 + +[Color1Faint] +Color=101,0,0 + +[Color2] +Color=24,178,24 + +[Color2Intense] +Color=84,255,84 + +[Color2Faint] +Color=0,101,0 + +[Color3] +Color=178,104,24 + +[Color3Intense] +Color=255,255,84 + +[Color3Faint] +Color=101,74,0 + +[Color4] +Color=24,24,178 + +[Color4Intense] +Color=84,84,255 + +[Color4Faint] +Color=0,0,101 + +[Color5] +Color=178,24,178 + +[Color5Intense] +Color=255,84,255 + +[Color5Faint] +Color=95,5,95 + +[Color6] +Color=24,178,178 + +[Color6Intense] +Color=84,255,255 + +[Color6Faint] +Color=24,178,178 + +[Color7] +Color=178,178,178 + +[Color7Intense] +Color=255,255,255 + +[Color7Faint] +Color=101,101,101 + +[Foreground] +Color=255,255,255 + +[ForegroundIntense] +Bold=true +Color=255,255,255 + +[ForegroundFaint] +Color=255,255,255 + +[General] +Description=White on Black +Opacity=1 diff --git a/qtermwidget/lib/color-schemes/historic/BlackOnLightColor.schema b/qtermwidget/lib/color-schemes/historic/BlackOnLightColor.schema new file mode 100644 index 0000000..954d403 --- /dev/null +++ b/qtermwidget/lib/color-schemes/historic/BlackOnLightColor.schema @@ -0,0 +1,42 @@ +# example scheme for konsole + +# the title is to appear in the menu. + +title Black on Light Color + +# foreground colors + +# note that the default background color is flagged +# to become transparent when an image is present. + +# slot transparent bold +# | | | +# V V--color--V V V + +color 0 0 0 0 0 0 # regular foreground color (Black) +rcolor 1 30 255 1 0 # regular background color (Light Color) + +color 2 0 0 0 0 0 # regular color 0 Black +color 3 178 24 24 0 0 # regular color 1 Red +color 4 24 178 24 0 0 # regular color 2 Green +color 5 178 104 24 0 0 # regular color 3 Yellow +color 6 24 24 178 0 0 # regular color 4 Blue +color 7 178 24 178 0 0 # regular color 5 Magenta +color 8 24 178 178 0 0 # regular color 6 Cyan +color 9 178 178 178 0 0 # regular color 7 White + +# intensive colors + +# instead of changing the colors, we've flagged the text to become bold + +color 10 0 0 0 0 1 # intensive foreground color +color 11 255 255 221 1 0 # intensive background color + +color 12 104 104 104 0 0 # intensive color 0 +color 13 255 84 84 0 0 # intensive color 1 +color 14 84 255 84 0 0 # intensive color 2 +color 15 255 255 84 0 0 # intensive color 3 +color 16 84 84 255 0 0 # intensive color 4 +color 17 255 84 255 0 0 # intensive color 5 +color 18 84 255 255 0 0 # intensive color 6 +color 19 255 255 255 0 0 # intensive color 7 diff --git a/qtermwidget/lib/color-schemes/historic/DarkPicture.schema b/qtermwidget/lib/color-schemes/historic/DarkPicture.schema new file mode 100644 index 0000000..1ab6386 --- /dev/null +++ b/qtermwidget/lib/color-schemes/historic/DarkPicture.schema @@ -0,0 +1,44 @@ +# example scheme for konsole + +# the title is to appear in the menu. + +title Marble + +image tile Blkmarble.jpg + +# foreground colors + +# note that the default background color is flagged +# to become transparent when an image is present. + +# slot transparent bold +# | | | +# V V--color--V V V + +color 0 255 255 255 0 0 # regular foreground color (White) +color 1 0 0 0 1 0 # regular background color (Black) + +color 2 0 0 0 0 0 # regular color 0 Black +color 3 178 24 24 0 0 # regular color 1 Red +color 4 24 178 24 0 0 # regular color 2 Green +color 5 178 104 24 0 0 # regular color 3 Yellow +color 6 24 24 178 0 0 # regular color 4 Blue +color 7 178 24 178 0 0 # regular color 5 Magenta +color 8 24 178 178 0 0 # regular color 6 Cyan +color 9 178 178 178 0 0 # regular color 7 White + +# intensive colors + +# instead of changing the colors, we've flagged the text to become bold + +color 10 255 255 255 0 1 # intensive foreground color +color 11 0 0 0 1 0 # intensive background color + +color 12 104 104 104 0 0 # intensive color 0 +color 13 255 84 84 0 0 # intensive color 1 +color 14 84 255 84 0 0 # intensive color 2 +color 15 255 255 84 0 0 # intensive color 3 +color 16 84 84 255 0 0 # intensive color 4 +color 17 255 84 255 0 0 # intensive color 5 +color 18 84 255 255 0 0 # intensive color 6 +color 19 255 255 255 0 0 # intensive color 7 diff --git a/qtermwidget/lib/color-schemes/historic/Example.Schema b/qtermwidget/lib/color-schemes/historic/Example.Schema new file mode 100644 index 0000000..0434e98 --- /dev/null +++ b/qtermwidget/lib/color-schemes/historic/Example.Schema @@ -0,0 +1,47 @@ +# example scheme for konsole + +# the title is to appear in the menu. + +title Ugly 1 + +# add a wallpaper, if you like. Second word one of { tile,center,full } + +image tile /opt/kde/share/wallpapers/dancy_pants.jpg + + +# foreground colors + +# note that the default background color is flagged +# to become transparent when an image is present. + +# slot transparent bold +# | | | +# V V--color--V V V + +color 0 0 0 0 0 0 # regular foreground color (Black) +color 1 255 255 255 1 0 # regular background color (White) + +color 2 0 0 0 0 0 # regular color 0 Black +color 3 255 0 0 0 0 # regular color 1 Red +color 4 0 255 0 0 0 # regular color 2 Green +color 5 255 255 0 0 0 # regular color 3 Yellow +color 6 0 0 255 0 0 # regular color 4 Blue +color 7 255 0 255 0 0 # regular color 5 Magenta +color 8 0 255 255 0 0 # regular color 6 Cyan +color 9 255 255 255 0 0 # regular color 7 White + +# intensive colors + +# instead of changing the colors, we've flagged the text to become bold + +color 10 0 0 0 0 1 # intensive foreground color +color 11 255 255 255 1 1 # intensive background color + +color 12 0 0 0 0 1 # intensive color 0 +color 13 255 0 0 0 1 # intensive color 1 +color 14 0 255 0 0 1 # intensive color 2 +color 15 255 255 0 0 1 # intensive color 3 +color 16 0 0 255 0 1 # intensive color 4 +color 17 255 0 255 0 1 # intensive color 5 +color 18 0 255 255 0 1 # intensive color 6 +color 19 255 255 255 0 1 # intensive color 7 diff --git a/qtermwidget/lib/color-schemes/historic/GreenOnBlack.schema b/qtermwidget/lib/color-schemes/historic/GreenOnBlack.schema new file mode 100644 index 0000000..b7b1b21 --- /dev/null +++ b/qtermwidget/lib/color-schemes/historic/GreenOnBlack.schema @@ -0,0 +1,42 @@ +# example scheme for konsole + +# the title is to appear in the menu. + +title Green on Black + +# foreground colors + +# note that the default background color is flagged +# to become transparent when an image is present. + +# slot transparent bold +# | | | +# V V--color--V V V + +color 0 24 240 24 0 0 # regular foreground color (Green) +color 1 0 0 0 1 0 # regular background color (Black) + +color 2 0 0 0 0 0 # regular color 0 Black +color 3 178 24 24 0 0 # regular color 1 Red +color 4 24 178 24 0 0 # regular color 2 Green +color 5 178 104 24 0 0 # regular color 3 Yellow +color 6 24 24 178 0 0 # regular color 4 Blue +color 7 178 24 178 0 0 # regular color 5 Magenta +color 8 24 178 178 0 0 # regular color 6 Cyan +color 9 178 178 178 0 0 # regular color 7 White + +# intensive colors + +# instead of changing the colors, we've flagged the text to become bold + +color 10 24 240 24 0 1 # intensive foreground color +color 11 0 0 0 1 0 # intensive background color + +color 12 104 104 104 0 0 # intensive color 0 +color 13 255 84 84 0 0 # intensive color 1 +color 14 84 255 84 0 0 # intensive color 2 +color 15 255 255 84 0 0 # intensive color 3 +color 16 84 84 255 0 0 # intensive color 4 +color 17 255 84 255 0 0 # intensive color 5 +color 18 84 255 255 0 0 # intensive color 6 +color 19 255 255 255 0 0 # intensive color 7 diff --git a/qtermwidget/lib/color-schemes/historic/GreenTint.schema b/qtermwidget/lib/color-schemes/historic/GreenTint.schema new file mode 100644 index 0000000..f349799 --- /dev/null +++ b/qtermwidget/lib/color-schemes/historic/GreenTint.schema @@ -0,0 +1,49 @@ +# linux color schema for konsole + +title Green Tint + +transparency 0.3 0 150 0 + +# FIXME +# +# The flaw in this schema is that "blick" comes out on the +# Linux console as intensive background, really. +# Since this is not used in clients you'll hardly notice +# it in practice. + +# foreground colors + +# note that the default background color is flagged +# to become transparent when an image is present. + +# slot transparent bold +# | red grn blu | | +# V V--color--V V V + +color 0 178 178 178 0 0 # regular foreground color (White) +color 1 0 0 0 1 0 # regular background color (Black) + +color 2 0 0 0 0 0 # regular color 0 Black +color 3 178 24 24 0 0 # regular color 1 Red +color 4 24 178 24 0 0 # regular color 2 Green +color 5 178 104 24 0 0 # regular color 3 Yellow +color 6 24 24 178 0 0 # regular color 4 Blue +color 7 178 24 178 0 0 # regular color 5 Magenta +color 8 24 178 178 0 0 # regular color 6 Cyan +color 9 178 178 178 0 0 # regular color 7 White + +# intensive colors + +# instead of changing the colors, we've flagged the text to become bold + +color 10 255 255 255 0 0 # intensive foreground color +color 11 104 104 104 1 0 # intensive background color + +color 12 104 104 104 0 0 # intensive color 0 +color 13 255 84 84 0 0 # intensive color 1 +color 14 84 255 84 0 0 # intensive color 2 +color 15 255 255 84 0 0 # intensive color 3 +color 16 84 84 255 0 0 # intensive color 4 +color 17 255 84 255 0 0 # intensive color 5 +color 18 84 255 255 0 0 # intensive color 6 +color 19 255 255 255 0 0 # intensive color 7 diff --git a/qtermwidget/lib/color-schemes/historic/GreenTint_MC.schema b/qtermwidget/lib/color-schemes/historic/GreenTint_MC.schema new file mode 100644 index 0000000..4236019 --- /dev/null +++ b/qtermwidget/lib/color-schemes/historic/GreenTint_MC.schema @@ -0,0 +1,49 @@ +# linux color schema for konsole + +title Green Tint with Transparent MC + +transparency 0.3 0 150 0 + +# FIXME +# +# The flaw in this schema is that "blick" comes out on the +# Linux console as intensive background, really. +# Since this is not used in clients you'll hardly notice +# it in practice. + +# foreground colors + +# note that the default background color is flagged +# to become transparent when an image is present. + +# slot transparent bold +# | red grn blu | | +# V V--color--V V V + +color 0 178 178 178 0 0 # regular foreground color (White) +color 1 0 0 0 1 0 # regular background color (Black) + +color 2 0 0 0 0 0 # regular color 0 Black +color 3 178 24 24 0 0 # regular color 1 Red +color 4 24 178 24 0 0 # regular color 2 Green +color 5 178 104 24 0 0 # regular color 3 Yellow +color 6 0 0 0 1 0 # regular color 4 Blue +color 7 178 24 178 0 0 # regular color 5 Magenta +color 8 24 178 178 0 0 # regular color 6 Cyan +color 9 178 178 178 0 0 # regular color 7 White + +# intensive colors + +# instead of changing the colors, we've flagged the text to become bold + +color 10 255 255 255 0 0 # intensive foreground color +color 11 104 104 104 1 0 # intensive background color + +color 12 104 104 104 0 0 # intensive color 0 +color 13 255 84 84 0 0 # intensive color 1 +color 14 84 255 84 0 0 # intensive color 2 +color 15 255 255 84 0 0 # intensive color 3 +color 16 84 84 255 0 0 # intensive color 4 +color 17 255 84 255 0 0 # intensive color 5 +color 18 84 255 255 0 0 # intensive color 6 +color 19 255 255 255 0 0 # intensive color 7 diff --git a/qtermwidget/lib/color-schemes/historic/LightPicture.schema b/qtermwidget/lib/color-schemes/historic/LightPicture.schema new file mode 100644 index 0000000..922d2c5 --- /dev/null +++ b/qtermwidget/lib/color-schemes/historic/LightPicture.schema @@ -0,0 +1,44 @@ +# example scheme for konsole + +# the title is to appear in the menu. + +title Paper + +image tile Paper01.jpg + +# foreground colors + +# note that the default background color is flagged +# to become transparent when an image is present. + +# slot transparent bold +# | | | +# V V--color--V V V + +color 0 0 0 0 0 0 # regular foreground color (Black) +color 1 255 255 255 1 0 # regular background color (White) + +color 2 0 0 0 0 0 # regular color 0 Black +color 3 178 24 24 0 0 # regular color 1 Red +color 4 24 178 24 0 0 # regular color 2 Green +color 5 178 104 24 0 0 # regular color 3 Yellow +color 6 24 24 178 0 0 # regular color 4 Blue +color 7 178 24 178 0 0 # regular color 5 Magenta +color 8 24 178 178 0 0 # regular color 6 Cyan +color 9 178 178 178 0 0 # regular color 7 White + +# intensive colors + +# instead of changing the colors, we've flagged the text to become bold + +color 10 0 0 0 0 1 # intensive foreground color +color 11 255 255 255 1 0 # intensive background color + +color 12 104 104 104 0 0 # intensive color 0 +color 13 255 84 84 0 0 # intensive color 1 +color 14 84 255 84 0 0 # intensive color 2 +color 15 255 255 84 0 0 # intensive color 3 +color 16 84 84 255 0 0 # intensive color 4 +color 17 255 84 255 0 0 # intensive color 5 +color 18 84 255 255 0 0 # intensive color 6 +color 19 255 255 255 0 0 # intensive color 7 diff --git a/qtermwidget/lib/color-schemes/historic/Linux.schema b/qtermwidget/lib/color-schemes/historic/Linux.schema new file mode 100644 index 0000000..d37ccc5 --- /dev/null +++ b/qtermwidget/lib/color-schemes/historic/Linux.schema @@ -0,0 +1,47 @@ +# linux color schema for konsole + +title Linux Colors + +# FIXME +# +# The flaw in this schema is that "blick" comes out on the +# Linux console as intensive background, really. +# Since this is not used in clients you'll hardly notice +# it in practice. + +# foreground colors + +# note that the default background color is flagged +# to become transparent when an image is present. + +# slot transparent bold +# | red grn blu | | +# V V--color--V V V + +color 0 178 178 178 0 0 # regular foreground color (White) +color 1 0 0 0 1 0 # regular background color (Black) + +color 2 0 0 0 0 0 # regular color 0 Black +color 3 178 24 24 0 0 # regular color 1 Red +color 4 24 178 24 0 0 # regular color 2 Green +color 5 178 104 24 0 0 # regular color 3 Yellow +color 6 24 24 178 0 0 # regular color 4 Blue +color 7 178 24 178 0 0 # regular color 5 Magenta +color 8 24 178 178 0 0 # regular color 6 Cyan +color 9 178 178 178 0 0 # regular color 7 White + +# intensive colors + +# instead of changing the colors, we've flagged the text to become bold + +color 10 255 255 255 0 0 # intensive foreground color +color 11 104 104 104 1 0 # intensive background color + +color 12 104 104 104 0 0 # intensive color 0 +color 13 255 84 84 0 0 # intensive color 1 +color 14 84 255 84 0 0 # intensive color 2 +color 15 255 255 84 0 0 # intensive color 3 +color 16 84 84 255 0 0 # intensive color 4 +color 17 255 84 255 0 0 # intensive color 5 +color 18 84 255 255 0 0 # intensive color 6 +color 19 255 255 255 0 0 # intensive color 7 diff --git a/qtermwidget/lib/color-schemes/historic/README.Schema b/qtermwidget/lib/color-schemes/historic/README.Schema new file mode 100644 index 0000000..21ae01d --- /dev/null +++ b/qtermwidget/lib/color-schemes/historic/README.Schema @@ -0,0 +1,132 @@ +[README.Schema] + +The schemata offered in the Options/Schema menu are +taken from from configurations files with a *.schema +pattern either located in $KDEDIR/share/apps/konsole +or ~/.kde/share/apps/konsole. + +Schemata allow to configure the color set that konsole +uses, together with some more information on rendition +processing. + +Syntax + + File + :: { [Line] ['#' Comment] '\n' } + + Line + :: "title" Title + :: "image" Usage PathToPictureFile + :: "transparency" Fade Red Green Blue + :: "color" Slot Red Green Blue Transparent Bold + :: "rcolor" Slot Saturation Value Transparent Bold + :: "sysfg" Slot Transparent Bold + :: "sysbg" Slot Transparent Bold + +Meaning + + - Title is the text to appear in the Option/Schema menu. + It should be unique among all other schemata therefore. + + - The "image" clause allows to place an image on the + konsole's background. + + - Usage can be either + - "tile" - the image is tilewise replicated. + - "center" - the image is centered. + - "full" - the image is stretched to fit the window size. + + - The Path of the picture can both be relative + (to kde wallpapers) or absolute. + + When a schema uses a background image (or transparency) + one has to make at least one color slot transparent to + achieve any visible effect. Please read below about the + "Transparent" field in color,sysbg,sysfg. + + - The "transparency" clause picks and uses the background + of the desktop as if it where an image together with + a fade effect. This effect will fade the background + to the specified color. + + The "Fade" is a real value between 0 and 1, indicating + the strength of the fade. A value of 0 will not change + the image, a value of 1 will make it the fade color + everywhere, and in between. This will make the "glas" + of the window be of the color given in the clause and + being more(1) or less(0) intransparent. + + - The remaining clauses (color,sysbg,sysfg) are used + to setup konsoles rendition system. + + To this end, konsole offers 20 color slots. + + Slot Meaning + ----- -------------------------- + 0 regular foreground color + 1 regular background color + 2-9 regular bgr color 0-7 + 10 intensive foreground color + 11 intensive background color + 12-19 intensive bgr color 0-7 + + The traditional meaning of the "bgr" color codes + has a bitwise interpretation of an additive three + primary color scheme inherited from early EGA + color terminals. + + Color Bits Colors + ----- ---- ------- + 0 000 Black + 1 001 Red + 2 010 Green + 3 011 Yellow + 4 100 Blue + 5 101 Magenta + 6 110 Cyan + 7 111 White + + One may or may not stick to this tradition. + Konsole allows to assign colors freely to slots. + + The slots fall apart into two groups, regular + and intensive colors. The later are used when + BOLD rendition is used by the client. + + Each of the groups have a default fore- and + background color and the said bgr colors. + Normal terminal processing will simply use + the default colors. + + The color desired for a slot is indicated + in the Red Green Blue fields of the color + clause. Use the sysfg or the sysbg clause + to indicate the default fore and background + colors of the desktop. + + To specify randomized color for a slot use + the clause rcolor. The two parameters to it + being Saturation - the amount of colour, + and Value, the darkness of the colour. + + To use transparency/images and to simulate + the behavior of the xterm, one can supply + two additional tags to each slot: + - Transparent (0/1) meaning to show the + background picture, if any. + - Bold (0/1) to render characters bold. + + +If you know about the escape codes, you might have +noticed that intensive and bold rendition are sort +of confused. This is inherited by the xterm which +konsole is simulating. + +One can use the colortest.sh script supplied +with the konsole source distribution to test +a schema. + +The schema installed with konsole are more or +less demonstrations and not really beauty, +beside the Linux.schema, perhaps, which is +made after the VGA colors. diff --git a/qtermwidget/lib/color-schemes/historic/README.default.Schema b/qtermwidget/lib/color-schemes/historic/README.default.Schema new file mode 100644 index 0000000..7bfa9dc --- /dev/null +++ b/qtermwidget/lib/color-schemes/historic/README.default.Schema @@ -0,0 +1,44 @@ +# default scheme for konsole (only here for documentation purposes) + +# the title is to appear in the menu. + +title Konsole Defaults + +# image tile /opt/kde/share/wallpapers/gray2.jpg + +# foreground colors + +# note that the default background color is flagged +# to become transparent when an image is present. + +# slot transparent bold +# | | | +# V V--color--V V V + +color 0 0 0 0 0 0 # regular foreground color (Black) +color 1 255 255 255 1 0 # regular background color (White) + +color 2 0 0 0 0 0 # regular color 0 Black +color 3 178 24 24 0 0 # regular color 1 Red +color 4 24 178 24 0 0 # regular color 2 Green +color 5 178 104 24 0 0 # regular color 3 Yellow +color 6 24 24 178 0 0 # regular color 4 Blue +color 7 178 24 178 0 0 # regular color 5 Magenta +color 8 24 178 178 0 0 # regular color 6 Cyan +color 9 178 178 178 0 0 # regular color 7 White + +# intensive colors + +# instead of changing the colors, we've flagged the text to become bold + +color 10 0 0 0 0 1 # intensive foreground color +color 11 255 255 255 1 0 # intensive background color + +color 12 104 104 104 0 0 # intensive color 0 +color 13 255 84 84 0 0 # intensive color 1 +color 14 84 255 84 0 0 # intensive color 2 +color 15 255 255 84 0 0 # intensive color 3 +color 16 84 84 255 0 0 # intensive color 4 +color 17 255 84 255 0 0 # intensive color 5 +color 18 84 255 255 0 0 # intensive color 6 +color 19 255 255 255 0 0 # intensive color 7 diff --git a/qtermwidget/lib/color-schemes/historic/Transparent.schema b/qtermwidget/lib/color-schemes/historic/Transparent.schema new file mode 100644 index 0000000..625fd4c --- /dev/null +++ b/qtermwidget/lib/color-schemes/historic/Transparent.schema @@ -0,0 +1,49 @@ +# linux color schema for konsole + +title Transparent Konsole + +transparency 0.35 0 0 0 + +# FIXME +# +# The flaw in this schema is that "blick" comes out on the +# Linux console as intensive background, really. +# Since this is not used in clients you'll hardly notice +# it in practice. + +# foreground colors + +# note that the default background color is flagged +# to become transparent when an image is present. + +# slot transparent bold +# | red grn blu | | +# V V--color--V V V + +color 0 178 178 178 0 0 # regular foreground color (White) +color 1 0 0 0 1 0 # regular background color (Black) + +color 2 0 0 0 0 0 # regular color 0 Black +color 3 178 24 24 0 0 # regular color 1 Red +color 4 24 178 24 0 0 # regular color 2 Green +color 5 178 104 24 0 0 # regular color 3 Yellow +color 6 24 24 178 0 0 # regular color 4 Blue +color 7 178 24 178 0 0 # regular color 5 Magenta +color 8 24 178 178 0 0 # regular color 6 Cyan +color 9 178 178 178 0 0 # regular color 7 White + +# intensive colors + +# instead of changing the colors, we've flagged the text to become bold + +color 10 255 255 255 0 0 # intensive foreground color +color 11 104 104 104 1 0 # intensive background color + +color 12 104 104 104 0 0 # intensive color 0 +color 13 255 84 84 0 0 # intensive color 1 +color 14 84 255 84 0 0 # intensive color 2 +color 15 255 255 84 0 0 # intensive color 3 +color 16 84 84 255 0 0 # intensive color 4 +color 17 255 84 255 0 0 # intensive color 5 +color 18 84 255 255 0 0 # intensive color 6 +color 19 255 255 255 0 0 # intensive color 7 diff --git a/qtermwidget/lib/color-schemes/historic/Transparent_MC.schema b/qtermwidget/lib/color-schemes/historic/Transparent_MC.schema new file mode 100644 index 0000000..393e3d2 --- /dev/null +++ b/qtermwidget/lib/color-schemes/historic/Transparent_MC.schema @@ -0,0 +1,51 @@ +# linux color schema for konsole + +title Transparent for MC + +transparency 0.35 0 0 0 + +# FIXME +# +# The flaw in this schema is that "blick" comes out on the +# Linux console as intensive background, really. +# Since this is not used in clients you'll hardly notice +# it in practice. + +# foreground colors + +# note that the default background color is flagged +# to become transparent when an image is present. + +# slot transparent bold +# | red grn blu | | +# V V--color--V V V + +color 0 178 178 178 0 0 # regular foreground color (White) +color 1 0 0 0 1 0 # regular background color (Black) + +color 2 0 0 0 0 0 # regular color 0 Black +color 3 178 24 24 0 0 # regular color 1 Red +color 4 24 178 24 0 0 # regular color 2 Green +color 5 178 104 24 0 0 # regular color 3 Yellow +#color 6 24 24 178 0 0 # regular color 4 Blue +color 6 0 0 0 1 0 # regular color 4 Blue + +color 7 178 24 178 0 0 # regular color 5 Magenta +color 8 24 178 178 0 0 # regular color 6 Cyan +color 9 178 178 178 0 0 # regular color 7 White + +# intensive colors + +# instead of changing the colors, we've flagged the text to become bold + +color 10 255 255 255 0 0 # intensive foreground color +color 11 104 104 104 1 0 # intensive background color + +color 12 104 104 104 0 0 # intensive color 0 +color 13 255 84 84 0 0 # intensive color 1 +color 14 84 255 84 0 0 # intensive color 2 +color 15 255 255 84 0 0 # intensive color 3 +color 16 84 84 255 0 0 # intensive color 4 +color 17 255 84 255 0 0 # intensive color 5 +color 18 84 255 255 0 0 # intensive color 6 +color 19 255 255 255 0 0 # intensive color 7 diff --git a/qtermwidget/lib/color-schemes/historic/Transparent_darkbg.schema b/qtermwidget/lib/color-schemes/historic/Transparent_darkbg.schema new file mode 100644 index 0000000..d3ec5a7 --- /dev/null +++ b/qtermwidget/lib/color-schemes/historic/Transparent_darkbg.schema @@ -0,0 +1,42 @@ +# linux color schema for konsole + +title Transparent, Dark Background + +transparency 0.75 0 0 0 + +# foreground colors + +# note that the default background color is flagged +# to become transparent when an image is present. + +# slot transparent bold +# | red grn blu | | +# V V--color--V V V + +color 0 255 255 255 0 0 # regular foreground color (White) +color 1 0 0 0 1 0 # regular background color (Black) + +color 2 0 0 0 0 0 # regular color 0 Black +color 3 178 24 24 0 0 # regular color 1 Red +color 4 24 178 24 0 0 # regular color 2 Green +color 5 178 104 24 0 0 # regular color 3 Yellow +color 6 24 24 178 0 0 # regular color 4 Blue +color 7 178 24 178 0 0 # regular color 5 Magenta +color 8 24 178 178 0 0 # regular color 6 Cyan +color 9 178 178 178 0 0 # regular color 7 White + +# intensive colors + +# instead of changing the colors, we've flagged the text to become bold + +color 10 255 255 255 0 0 # intensive foreground color +color 11 104 104 104 1 0 # intensive background color + +color 12 104 104 104 0 0 # intensive color 0 +color 13 255 84 84 0 0 # intensive color 1 +color 14 84 255 84 0 0 # intensive color 2 +color 15 255 255 84 0 0 # intensive color 3 +color 16 84 84 255 0 0 # intensive color 4 +color 17 255 84 255 0 0 # intensive color 5 +color 18 84 255 255 0 0 # intensive color 6 +color 19 255 255 255 0 0 # intensive color 7 diff --git a/qtermwidget/lib/color-schemes/historic/Transparent_lightbg.schema b/qtermwidget/lib/color-schemes/historic/Transparent_lightbg.schema new file mode 100644 index 0000000..b31d7b8 --- /dev/null +++ b/qtermwidget/lib/color-schemes/historic/Transparent_lightbg.schema @@ -0,0 +1,51 @@ +# linux color schema for konsole + +title Transparent, Light Background + +transparency 0.1 0 0 0 + +# This is a schema for very light backgrounds. It makes some +# hacks about the colors to make Midnight Commander transparent +# and with suitable colors. + +# foreground colors + +# note that the default background color is flagged +# to become transparent when an image is present. + +# slot transparent bold +# | red grn blu | | +# V V--color--V V V + +color 0 50 50 50 0 0 # regular foreground color (DarkGray) +color 1 200 200 200 1 0 # regular background color (White) + +# color 2 0 0 0 0 0 # regular color 0 Black +color 2 200 200 200 1 0 # regular background color (White) +color 3 178 24 24 0 0 # regular color 1 Red +color 4 24 178 24 0 0 # regular color 2 Green +color 5 178 104 24 0 0 # regular color 3 Yellow +#color 6 24 24 178 0 0 # regular color 4 Blue +color 6 0 0 0 1 0 # regular color 4 Blue +# Blue is transparent, to make MC transparent + +color 7 178 24 178 0 0 # regular color 5 Magenta +color 8 24 178 178 0 0 # regular color 6 Cyan +# color 9 178 178 178 0 0 # regular color 7 White +color 9 50 50 50 0 0 # regular foreground color (DarkGray) + +# intensive colors + +# instead of changing the colors, we've flagged the text to become bold + +color 10 0 0 0 0 0 # intensive foreground color +color 11 255 255 255 1 0 # intensive background color + +color 12 104 104 104 0 0 # intensive color 0 +color 13 255 84 84 0 0 # intensive color 1 +color 14 84 255 84 0 0 # intensive color 2 +color 15 255 255 84 0 0 # intensive color 3 +color 16 84 84 255 0 0 # intensive color 4 +color 17 255 84 255 0 0 # intensive color 5 +color 18 84 255 255 0 0 # intensive color 6 +color 19 255 255 255 0 0 # intensive color 7 diff --git a/qtermwidget/lib/color-schemes/historic/XTerm.schema b/qtermwidget/lib/color-schemes/historic/XTerm.schema new file mode 100644 index 0000000..92cae21 --- /dev/null +++ b/qtermwidget/lib/color-schemes/historic/XTerm.schema @@ -0,0 +1,46 @@ +# xterm color schema for konsole + +# xterm colors can be configured (almost) like +# konsole colors can. This is the uncustomized +# xterm schema. +# Please refer to your local xterm setup files +# if this schema differs. + +title XTerm Colors + +# foreground colors ------------------------------- + +# note that the default background color is flagged +# to become transparent when an image is present. + +# slot transparent bold +# | red grn blu | | +# V V--color--V V V + +color 0 0 0 0 0 0 # regular foreground color (Black) +color 1 255 255 255 1 0 # regular background color (White) + +color 2 0 0 0 0 0 # regular color 0 Black +color 3 205 0 0 0 0 # regular color 1 Red +color 4 0 205 0 0 0 # regular color 2 Green +color 5 205 205 0 0 0 # regular color 3 Yellow +color 6 0 0 205 0 0 # regular color 4 Blue +color 7 205 0 205 0 0 # regular color 5 Magenta +color 8 0 205 205 0 0 # regular color 6 Cyan +color 9 229 229 229 0 0 # regular color 7 White + +# intensive colors ------------------------------------------- + +# for some strange reason, intensive colors are bold, also. + +color 10 77 77 77 0 1 # intensive foreground color +color 11 255 255 255 1 1 # intensive background color + +color 12 77 77 77 0 1 # intensive color 0 +color 13 255 0 0 0 1 # intensive color 1 +color 14 0 255 0 0 1 # intensive color 2 +color 15 255 255 0 0 1 # intensive color 3 +color 16 0 0 255 0 1 # intensive color 4 +color 17 255 0 255 0 1 # intensive color 5 +color 18 0 255 255 0 1 # intensive color 6 +color 19 255 255 255 0 1 # intensive color 7 diff --git a/qtermwidget/lib/color-schemes/historic/syscolor.schema b/qtermwidget/lib/color-schemes/historic/syscolor.schema new file mode 100644 index 0000000..9a29db6 --- /dev/null +++ b/qtermwidget/lib/color-schemes/historic/syscolor.schema @@ -0,0 +1,44 @@ +# schema that uses system colors + +# the title is to appear in the menu. + +title System Colors + +# image none + +# foreground colors + +# note that the default background color is flagged +# to become transparent when an image is present. + +# slot transparent bold +# | | | +# V V--color--V V V + +sysfg 0 0 0 # regular foreground color (system) +sysbg 1 1 0 # regular background color (system) + +color 2 0 0 0 0 0 # regular color 0 Black +color 3 178 24 24 0 0 # regular color 1 Red +color 4 24 178 24 0 0 # regular color 2 Green +color 5 178 104 24 0 0 # regular color 3 Yellow +color 6 24 24 178 0 0 # regular color 4 Blue +color 7 178 24 178 0 0 # regular color 5 Magenta +color 8 24 178 178 0 0 # regular color 6 Cyan +color 9 178 178 178 0 0 # regular color 7 White + +# intensive colors + +# instead of changing the colors, we've flagged the text to become bold + +color 10 0 0 0 0 1 # intensive foreground color +color 11 255 255 255 1 0 # intensive background color + +color 12 104 104 104 0 0 # intensive color 0 +color 13 255 84 84 0 0 # intensive color 1 +color 14 84 255 84 0 0 # intensive color 2 +color 15 255 255 84 0 0 # intensive color 3 +color 16 84 84 255 0 0 # intensive color 4 +color 17 255 84 255 0 0 # intensive color 5 +color 18 84 255 255 0 0 # intensive color 6 +color 19 255 255 255 0 0 # intensive color 7 diff --git a/qtermwidget/lib/color-schemes/historic/vim.schema b/qtermwidget/lib/color-schemes/historic/vim.schema new file mode 100644 index 0000000..f29e3f7 --- /dev/null +++ b/qtermwidget/lib/color-schemes/historic/vim.schema @@ -0,0 +1,40 @@ +# VIM-recommended color schema for konsole + +# VIM (VI improved) in "help xiterm" recommends these colors for xterm. + +title VIM Colors + +# foreground colors ------------------------------- + +# note that the default background color is flagged +# to become transparent when an image is present. + +# slot transparent bold +# | red grn blu | | +# V V--color--V V V + +color 0 0 0 0 0 0 # regular foreground color (Black) +color 1 255 255 255 1 0 # regular background color (White) + +color 2 0 0 0 0 0 # regular color 0 Black +color 3 192 0 0 0 0 # regular color 1 Red +color 4 0 128 0 0 0 # regular color 2 Green +color 5 128 128 0 0 0 # regular color 3 Yellow +color 6 0 0 192 0 0 # regular color 4 Blue +color 7 192 0 192 0 0 # regular color 5 Magenta +color 8 0 128 128 0 0 # regular color 6 Cyan +color 9 192 192 192 0 0 # regular color 7 White + +# intensive colors ------------------------------------------- + +color 10 77 77 77 0 1 # intensive foreground color +color 11 255 255 255 1 1 # intensive background color + +color 12 128 128 128 0 0 # intensive color 0 +color 13 255 96 96 0 0 # intensive color 1 +color 14 0 255 0 0 0 # intensive color 2 +color 15 255 255 0 0 0 # intensive color 3 +color 16 128 128 255 0 0 # intensive color 4 +color 17 255 64 255 0 0 # intensive color 5 +color 18 0 255 255 0 0 # intensive color 6 +color 19 255 255 255 0 0 # intensive color 7 diff --git a/qtermwidget/src/default.keytab b/qtermwidget/lib/default.keytab similarity index 100% rename from qtermwidget/src/default.keytab rename to qtermwidget/lib/default.keytab diff --git a/qtermwidget/lib/kb-layouts/README b/qtermwidget/lib/kb-layouts/README new file mode 100644 index 0000000..e556b9a --- /dev/null +++ b/qtermwidget/lib/kb-layouts/README @@ -0,0 +1,72 @@ +[README.KeyTab] + +The keytabs offered in the Options/Keyboard menu are +taken from from configurations files with a *.keytab +pattern either located in $KDEDIR/share/apps/konsole +or ~/.kde/share/apps/konsole. + +Keytabs allow to configure the behavior of konsole +on keyboard events, especially for functions keys. +Please have a look into the README.keyboard file, too. + +The syntax is that each entry has the form : + + "key" Keyname { ("+"|"-") Modename } ":" (String|Operation) + +Keynames are those defined in with the +"Qt::Key_" prefix removed. + +Mode names are: + + - Shift : Shift Key pressed + - Alt : Alt Key pressed + - Control : Control Key pressed + + ( The VT100 emulation has 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). + + Since sending a state to a program that has set the state + itself is positivly wrong and obsolete design, better forget + about this nasty detail. I may well remove this "feature" + in a future clean up round. ) + + A "+" preceding a Modename means the Key is pressed. + A "-" preceding a Modename means the Key is not pressed. + If no mode is given it means don't care. + + Note that the combination of Key and Modes (set/reset) + has to be unique. This means, that + + key A + Shift : "A" + key A : "a" + + will not accept the small letter "a" rule as expected, + one has to add a "- Shift" to the last clause. Use + the stdout/stderr diagnostics of konsole when modifying + keytabs to find problems like this. + +Operations are + + - scrollUpLine : scroll up one line in the history log + - scrollUpPage : scroll up one page in the history log + - scrollDownLine : scroll down one line in the history log + - scrollDownPage : scroll down one page in the history log + - emitClipboard : "paste" the current clipboard + - emitSelection : "paste" the current selection + +Strings have the syntax of C strings, +one may use the following escapes: + + - \E - escape + - \\ - backslash + - \" - double quote + - \t - tab + - \r - return + - \n - newline + - \b - backspace + - \xHH - where HH are two hex digits diff --git a/qtermwidget/lib/kb-layouts/default.keytab b/qtermwidget/lib/kb-layouts/default.keytab new file mode 100644 index 0000000..4d18dc1 --- /dev/null +++ b/qtermwidget/lib/kb-layouts/default.keytab @@ -0,0 +1,183 @@ +# [README.default.Keytab] Default 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. +# +# Backspace without CTRL sends '^H'; this matches XTerm behaviour +# BS, hex \x08, \b +key Backspace -Control : "\b" + +# Match xterm behaviour: Backspace sends '^?' when Control is pressed +key Backspace +Control : "\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" + +key Up +Shift+AppScreen : "\E[1;*A" +key Down +Shift+AppScreen : "\E[1;*B" +key Left +Shift+AppScreen : "\E[1;*D" +key Right +Shift+AppScreen : "\E[1;*C" + +# Keypad keys with NumLock ON +# (see "Numeric Keypad" section at http://www.nw.com/nw/WWW/products/wizcon/vt100.html ) +# +# Not enabled for now because it breaks the keypad in Vim. +# +#key 0 +KeyPad+AppKeyPad : "\EOp" +#key 1 +KeyPad+AppKeyPad : "\EOq" +#key 2 +KeyPad+AppKeyPad : "\EOr" +#key 3 +KeyPad+AppKeyPad : "\EOs" +#key 4 +KeyPad+AppKeyPad : "\EOt" +#key 5 +KeyPad+AppKeyPad : "\EOu" +#key 6 +KeyPad+AppKeyPad : "\EOv" +#key 7 +KeyPad+AppKeyPad : "\EOw" +#key 8 +KeyPad+AppKeyPad : "\EOx" +#key 9 +KeyPad+AppKeyPad : "\EOy" +#key + +KeyPad+AppKeyPad : "\EOl" +#key - +KeyPad+AppKeyPad : "\EOm" +#key . +KeyPad+AppKeyPad : "\EOn" +#key * +KeyPad+AppKeyPad : "\EOM" +#key Enter +KeyPad+AppKeyPad : "\r" + +# Keypad keys with NumLock Off +key Up -Shift+Ansi+AppCuKeys+KeyPad : "\EOA" +key Down -Shift+Ansi+AppCuKeys+KeyPad : "\EOB" +key Right -Shift+Ansi+AppCuKeys+KeyPad : "\EOC" +key Left -Shift+Ansi+AppCuKeys+KeyPad : "\EOD" + +key Up -Shift+Ansi-AppCuKeys+KeyPad : "\E[A" +key Down -Shift+Ansi-AppCuKeys+KeyPad : "\E[B" +key Right -Shift+Ansi-AppCuKeys+KeyPad : "\E[C" +key Left -Shift+Ansi-AppCuKeys+KeyPad : "\E[D" + +key Home +AppCuKeys+KeyPad : "\EOH" +key End +AppCuKeys+KeyPad : "\EOF" +key Home -AppCuKeys+KeyPad : "\E[H" +key End -AppCuKeys+KeyPad : "\E[F" + +key Insert +KeyPad : "\E[2~" +key Delete +KeyPad : "\E[3~" +key PgUp -Shift+KeyPad : "\E[5~" +key PgDown -Shift+KeyPad : "\E[6~" + +key Clear -AnyMod+KeyPad+AppKeyPad : "\E[OE" +key Clear +AnyMod+KeyPad+AppKeyPad : "\E[1;*E" + +# 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 PgUp -Shift-AnyMod : "\E[5~" +key PgDown -Shift-AnyMod : "\E[6~" +key PgUp -Shift+AnyMod : "\E[5;*~" +key PgDown -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 PgUp +Shift-AppScreen : scrollPageUp +key Home +Shift-AppScreen : scrollUpToTop +key Down +Shift-AppScreen : scrollLineDown +key PgDown +Shift-AppScreen : scrollPageDown +key End +Shift-AppScreen : scrollDownToBottom + +key ScrollLock : scrollLock diff --git a/qtermwidget/lib/kb-layouts/historic/vt100.keytab b/qtermwidget/lib/kb-layouts/historic/vt100.keytab new file mode 100644 index 0000000..590e45d --- /dev/null +++ b/qtermwidget/lib/kb-layouts/historic/vt100.keytab @@ -0,0 +1,133 @@ +# [vt100.keytab] Konsole Keyboard Table (VT100 keys) +# +# -------------------------------------------------------------- + +keyboard "vt100 (historical)" + +# -------------------------------------------------------------- +# +# 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 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 +# preceded 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" + +# function keys (FIXME: make pf1-pf4) + +key F1 : "\E[11~" +key F2 : "\E[12~" +key F3 : "\E[13~" +key F4 : "\E[14~" +key F5 : "\E[15~" + +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[H" +key End : "\E[F" + +key PgUp -Shift : "\E[5~" +key PgDown -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 PgUp +Shift : scrollPageUp +key Down +Shift : scrollLineDown +key PgDown +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/qtermwidget/lib/kb-layouts/historic/x11r5.keytab b/qtermwidget/lib/kb-layouts/historic/x11r5.keytab new file mode 100644 index 0000000..e17da0d --- /dev/null +++ b/qtermwidget/lib/kb-layouts/historic/x11r5.keytab @@ -0,0 +1,71 @@ +# [x11r5.Keytab] Keyboard Table for X11 R5 + +keyboard "XTerm (XFree 3.x.x)" + +# -------------------------------------------------------------- +# +# 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 : "\t" + +key Return : "\r" + +# Backspace and Delete codes are preserving CTRL-H. + +key Backspace : "\x7f" + +# cursor keys + +key Up -Shift : "\EOA" +key Down -Shift : "\EOB" +key Right -Shift : "\EOC" +key Left -Shift : "\EOD" + +# other grey PC keys + +key Enter : "\r" + +key Home : "\E[1~" +key Insert-Shift : "\E[2~" +key Delete : "\E[3~" +key End : "\E[4~" +key PgUp -Shift : "\E[5~" +key PgDown -Shift : "\E[6~" + +# function keys + +key F1 : "\E[11~" +key F2 : "\E[12~" +key F3 : "\E[13~" +key F4 : "\E[14~" +key F5 : "\E[15~" +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~" + +# 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 : scrollLineUp +key PgUp +Shift : scrollPageUp +key Down +Shift : scrollLineDown +key PgDown +Shift : scrollPageDown + +key ScrollLock : scrollLock + +# keypad characters are not offered differently by Qt. diff --git a/qtermwidget/src/kb-layouts/linux.keytab b/qtermwidget/lib/kb-layouts/linux.keytab similarity index 85% rename from qtermwidget/src/kb-layouts/linux.keytab rename to qtermwidget/lib/kb-layouts/linux.keytab index c0fe444..9638da6 100644 --- a/qtermwidget/src/kb-layouts/linux.keytab +++ b/qtermwidget/lib/kb-layouts/linux.keytab @@ -43,7 +43,7 @@ keyboard "Linux console" # # 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. +# preceded by ESC if the Alt key is pressed. # # -------------------------------------------------------------- @@ -84,6 +84,11 @@ key Down -Shift+Ansi-AppCuKeys : "\E[B" key Right-Shift+Ansi-AppCuKeys : "\E[C" key Left -Shift+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" + # linux functions keys F1-F5 differ from xterm key F1 : "\E[[A" @@ -103,9 +108,9 @@ 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~" +key PgUp -Shift : "\E[5~" +key PgDown -Shift : "\E[6~" +key Insert -Shift : "\E[2~" # Keypad-Enter. See comment on Return above. @@ -116,10 +121,10 @@ 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 Up +Shift : scrollLineUp +key PgUp +Shift : scrollPageUp +key Down +Shift : scrollLineDown +key PgDown +Shift : scrollPageDown key ScrollLock : scrollLock diff --git a/qtermwidget/lib/kb-layouts/macbook.keytab b/qtermwidget/lib/kb-layouts/macbook.keytab new file mode 100644 index 0000000..71e61ae --- /dev/null +++ b/qtermwidget/lib/kb-layouts/macbook.keytab @@ -0,0 +1,175 @@ +# [README.default.Keytab] Buildin Keyboard Table +# +# To customize your keyboard, copy this file to something +# ending with .keytab and change it to meet you needs. +# Please read the README.KeyTab and the README.keyboard +# in this case. +# +# -------------------------------------------------------------- + +keyboard "Default (XFree 4)" + +# -------------------------------------------------------------- +# +# Note that this particular table is a "risc" version made to +# ease customization without bothering with obsolete details. +# See VT100.keytab for the more hairy stuff. +# +# -------------------------------------------------------------- + +# common keys + +key Escape : "\x1b" + +#key Control : "^" + +key Tab -Shift : "\t" +key Tab +Shift+Ansi : "\E[Z" +key Tab +Shift-Ansi : "\t" +key Backtab +Ansi : "\E[Z" +key Backtab -Ansi : "\t" + +key Return-Shift-NewLine : "\r" +key Return-Shift+NewLine : "\r\n" + +key Return+Shift : "\EOM" + +# Backspace and Delete codes are preserving CTRL-H. + +key Backspace : "\x7f" + +# Arrow keys in VT52 mode +# shift up/down are reserved for scrolling. +# shift left/right are reserved for switching between tabs (this is hardcoded). + + +# Command + C +# on mac - Control=Command, Meta=Ctrl +# do not use Control+C for interrupt signal - it's used for "Copy to clipboard" +#key Control +C : "\x03" +key Meta +C: "\x03" + + +# Arrow keys in ANSI mode with Application - and Normal Cursor Mode) + +key Up -Shift+Ansi-AppCuKeys : "\E[A" +key Down -Shift+Ansi-AppCuKeys : "\E[B" +key Right-Shift+Ansi-AppCuKeys : "\E[C" +key Left -Shift+Ansi-AppCuKeys : "\E[D" + +key Up -Ansi : "\E[1;*A" +key Down -Ansi : "\E[1;*B" +key Right -Ansi : "\E[1;*C" +key Left -Ansi : "\E[1;*D" + +#key Up -Shift-Ansi : "\EA" +#key Down -Shift-Ansi : "\EB" +#key Right-Shift-Ansi : "\EC" +#key Left -Shift-Ansi : "\ED" + +#key Up -Shift-AnyMod+Ansi-AppCuKeys : "\E[A" +#key Down -Shift-AnyMod+Ansi-AppCuKeys : "\E[B" +#key Right -Shift-AnyMod+Ansi-AppCuKeys : "\E[C" +#key Left -Shift-AnyMod+Ansi-AppCuKeys : "\E[D" + +#key Up -Shift-AnyMod+Ansi-AppCuKeys : "\EOA" +#key Down -Shift-AnyMod+Ansi-AppCuKeys : "\EOB" +#key Right -Shift-AnyMod+Ansi-AppCuKeys : "\EOC" +#key Left -Shift-AnyMod+Ansi-AppCuKeys : "\EOD" + +#key Up -Shift-AnyMod+Ansi : "\E[1;*A" +#key Down -Shift-AnyMod+Ansi : "\E[1;*B" +#key Right -Shift-AnyMod+Ansi : "\E[1;*C" +#key Left -Shift-AnyMod+Ansi : "\E[1;*D" + +# other grey PC keys + +key Enter+NewLine : "\r\n" +key Enter-NewLine : "\r" + +key Home -AnyMod -AppCuKeys : "\E[H" +key End -AnyMod -AppCuKeys : "\E[F" +key Home -AnyMod +AppCuKeys : "\EOH" +key End -AnyMod +AppCuKeys : "\EOF" +key Home +AnyMod : "\E[1;*H" +key End +AnyMod : "\E[1;*F" + +key Insert -AnyMod : "\E[2~" +key Delete -AnyMod : "\E[3~" +key Insert +AnyMod : "\E[2;*~" +key Delete +AnyMod : "\E[3;*~" + +key PgUp -Shift-AnyMod : "\E[5~" +key PgDown -Shift-AnyMod : "\E[6~" +key PgUp -Shift+AnyMod : "\E[5;*~" +key PgDown -Shift+AnyMod : "\E[6;*~" + +# Function keys +#key F1 -AnyMod : "\EOP" +#key F2 -AnyMod : "\EOQ" +#key F3 -AnyMod : "\EOR" +#key F4 -AnyMod : "\EOS" +#define ALT_KP_0 "\033Op" +#define ALT_KP_1 "\033Oq" +#define ALT_KP_2 "\033Or" +#define ALT_KP_3 "\033Os" +#define ALT_KP_4 "\033Ot" +#define ALT_KP_5 "\033Ou" +#define ALT_KP_6 "\033Ov" +#define ALT_KP_7 "\033Ow" +#define ALT_KP_8 "\033Ox" +#define ALT_KP_9 "\033Oy" + +key F1 -AnyMod : "\EOP" +key F2 -AnyMod : "\EOQ" +key F3 -AnyMod : "\EOR" +key F4 -AnyMod : "\EOS" +key F5 -AnyMod : "\EOT" +key F6 -AnyMod : "\EOU" +key F7 -AnyMod : "\EOV" +key F8 -AnyMod : "\EOW" +key F9 -AnyMod : "\EOX" +key F10 -AnyMod : "\EOY" + +#key F5 -AnyMod : "\E[15~" +#key F6 -AnyMod : "\E[17~" +#key F7 -AnyMod : "\E[18~" +#key F8 -AnyMod : "\E[19~" +#key F9 -AnyMod : "\E[20~" +#key F10 -AnyMod : "\E[21~" +#key F11 -AnyMod : "\E[23~" +#key F12 -AnyMod : "\E[24~" + +#key F1 +AnyMod : "\EO*P" +#key F2 +AnyMod : "\EO*Q" +#key F3 +AnyMod : "\EO*R" +#key F4 +AnyMod : "\EO*S" +#key F5 +AnyMod : "\E[15;*~" +#key F6 +AnyMod : "\E[17;*~" +#key F7 +AnyMod : "\E[18;*~" +#key F8 +AnyMod : "\E[19;*~" +#key F9 +AnyMod : "\E[20;*~" +#key F10 +AnyMod : "\E[21;*~" +#key F11 +AnyMod : "\E[23;*~" +#key F12 +AnyMod : "\E[24;*~" + +# Work around dead keys + +key Space +Control : "\x00" + +# Some keys are used by konsole to cause operations. +# The scroll* operations refer to the history buffer. + +key Up +Shift-AppScreen : scrollLineUp +key PgUp +Shift-AppScreen : scrollPageUp +key Down +Shift-AppScreen : scrollLineDown +key PgDown +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/qtermwidget/lib/kb-layouts/solaris.keytab b/qtermwidget/lib/kb-layouts/solaris.keytab new file mode 100644 index 0000000..0f0da02 --- /dev/null +++ b/qtermwidget/lib/kb-layouts/solaris.keytab @@ -0,0 +1,108 @@ +# [solaris.keytab] Konsole Keyboard Table +# + +keyboard "Solaris 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 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 +# preceded by ESC if the Alt key is pressed. +# +# -------------------------------------------------------------- + +key Escape : "\E" +key Tab : "\t" + +key Return-Alt : "\r" +key Return+Alt : "\E\r" + +# Backspace and Delete codes are preserving CTRL-H. + +key Backspace : "\x08" +#key Delete : "\x7F" + +# cursor keys + +key Up -Shift : "\EOA" +key Down -Shift : "\EOB" +key Right -Shift : "\EOC" +key Left -Shift : "\EOD" + +# other grey PC keys + +key Enter : "\r" + +key Home : "\E[1~" +key Insert-Shift : "\E[2~" +key Delete : "\E[3~" +key End : "\E[4~" +key PgUp -Shift : "\E[5~" +key PgDown -Shift : "\E[6~" + +# function keys + +key F1 : "\E[11~" +key F2 : "\E[12~" +key F3 : "\E[13~" +key F4 : "\E[14~" +key F5 : "\E[15~" +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~" + +# 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 Left +Shift : prevSession +#key Right +Shift : nextSession +key Up +Shift : scrollLineUp +key PgUp +Shift : scrollPageUp +key Down +Shift : scrollLineDown +key PgDown +Shift : scrollPageDown +#key Insert+Shift : emitSelection + +# keypad characters are not offered differently by Qt. diff --git a/qtermwidget/src/kb-layouts/vt420pc.keytab b/qtermwidget/lib/kb-layouts/vt420pc.keytab similarity index 89% rename from qtermwidget/src/kb-layouts/vt420pc.keytab rename to qtermwidget/lib/kb-layouts/vt420pc.keytab index 2b7102f..33e8a23 100644 --- a/qtermwidget/src/kb-layouts/vt420pc.keytab +++ b/qtermwidget/lib/kb-layouts/vt420pc.keytab @@ -1,10 +1,15 @@ +# +# NOTE: This keyboard binding is not installed because it +# apparently doesn't work with actual VT420 systems +# (see BUG:170220) +# # [vt420pc.keytab] Konsole Keyboard Table (VT420pc keys) # adapted by ferdinand gassauer f.gassauer@aon.at # Nov 2000 # ################################################################ # -# The escape sequences emmited by the +# The escape sequences emitted by the # keys Shift+F1 to Shift+F12 might not fit your needs # ################# IMPORTANT NOTICE ############################# @@ -57,7 +62,7 @@ keyboard "DEC VT420 Terminal" # # 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. +# preceded by ESC if the Alt key is pressed. # # -------------------------------------------------------------- @@ -133,9 +138,9 @@ 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~" +key PgUp -Shift : "\E[5~" +key PgDown -Shift : "\E[6~" +key Insert -Shift : "\E[2~" # Keypad-Enter. See comment on Return above. @@ -146,10 +151,10 @@ 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 Up +Shift : scrollLineUp +key PgUp +Shift : scrollPageUp +key Down +Shift : scrollLineDown +key PgDown +Shift : scrollPageDown key ScrollLock : scrollLock diff --git a/qtermwidget/lib/konsole_wcwidth.cpp b/qtermwidget/lib/konsole_wcwidth.cpp new file mode 100644 index 0000000..cfb6c07 --- /dev/null +++ b/qtermwidget/lib/konsole_wcwidth.cpp @@ -0,0 +1,43 @@ +/* $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" + * + * + * Markus Kuhn -- 2001-01-12 -- public domain + */ + +#include + +#ifdef HAVE_UTF8PROC +#include +#else +#include +#endif + +#include "konsole_wcwidth.h" + +int konsole_wcwidth(wchar_t ucs) +{ +#ifdef HAVE_UTF8PROC + utf8proc_category_t cat = utf8proc_category( ucs ); + if (cat == UTF8PROC_CATEGORY_CO) { + // Co: Private use area. libutf8proc makes them zero width, while tmux + // assumes them to be width 1, and glibc's default width is also 1 + return 1; + } + return utf8proc_charwidth( ucs ); +#else + return wcwidth( ucs ); +#endif +} + +// single byte char: +1, multi byte char: +2 +int string_width( const std::wstring & wstr ) +{ + int w = 0; + for ( size_t i = 0; i < wstr.length(); ++i ) { + w += konsole_wcwidth( wstr[ i ] ); + } + return w; +} diff --git a/qtermwidget/lib/konsole_wcwidth.h b/qtermwidget/lib/konsole_wcwidth.h new file mode 100644 index 0000000..5885ce2 --- /dev/null +++ b/qtermwidget/lib/konsole_wcwidth.h @@ -0,0 +1,20 @@ +/* $XFree86: xc/programs/xterm/wcwidth.h,v 1.2 2001/06/18 19:09:27 dickey Exp $ */ + +/* Markus Kuhn -- 2001-01-12 -- public domain */ +/* Adaptations for KDE by Waldo Bastian */ +/* + Rewritten for QT4 by e_k +*/ + + +#ifndef _KONSOLE_WCWIDTH_H_ +#define _KONSOLE_WCWIDTH_H_ + +// Standard +#include + +int konsole_wcwidth(wchar_t ucs); + +int string_width( const std::wstring & wstr ); + +#endif diff --git a/qtermwidget/lib/kprocess.cpp b/qtermwidget/lib/kprocess.cpp new file mode 100644 index 0000000..6e8406e --- /dev/null +++ b/qtermwidget/lib/kprocess.cpp @@ -0,0 +1,310 @@ +/* + * This file is a part of QTerminal - http://gitorious.org/qterminal + * + * This file was un-linked from KDE and modified + * by Maxim Bourmistrov + * + */ + +/* + This file is part of the KDE libraries + + Copyright (C) 2007 Oswald Buddenhagen + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include "kprocess.h" + +#include + +///////////////////////////// +// public member functions // +///////////////////////////// + +KProcess::KProcess(QObject *parent) : + QProcess(parent), + d_ptr(new KProcessPrivate(this)) +{ + setOutputChannelMode(ForwardedChannels); +} + +KProcess::KProcess(KProcessPrivate *d, QObject *parent) : + QProcess(parent), + d_ptr(d) +{ + d_ptr->q_ptr = this; + setOutputChannelMode(ForwardedChannels); +} + +KProcess::~KProcess() = default; + +void KProcess::setOutputChannelMode(OutputChannelMode mode) +{ + QProcess::setProcessChannelMode(static_cast(mode)); +} + +KProcess::OutputChannelMode KProcess::outputChannelMode() const +{ + return static_cast(QProcess::processChannelMode()); +} + +void KProcess::setNextOpenMode(QIODevice::OpenMode mode) +{ + Q_D(KProcess); + + d->openMode = mode; +} + +#define DUMMYENV "_KPROCESS_DUMMY_=" + +void KProcess::clearEnvironment() +{ + setEnvironment(QStringList() << QString::fromLatin1(DUMMYENV)); +} + +void KProcess::setEnv(const QString &name, const QString &value, bool overwrite) +{ + QStringList env = environment(); + if (env.isEmpty()) { + env = systemEnvironment(); + env.removeAll(QString::fromLatin1(DUMMYENV)); + } + QString fname(name); + fname.append(QLatin1Char('=')); + for (QStringList::Iterator it = env.begin(); it != env.end(); ++it) + if ((*it).startsWith(fname)) { + if (overwrite) { + *it = fname.append(value); + setEnvironment(env); + } + return; + } + env.append(fname.append(value)); + setEnvironment(env); +} + +void KProcess::unsetEnv(const QString &name) +{ + QStringList env = environment(); + if (env.isEmpty()) { + env = systemEnvironment(); + env.removeAll(QString::fromLatin1(DUMMYENV)); + } + QString fname(name); + fname.append(QLatin1Char('=')); + for (QStringList::Iterator it = env.begin(); it != env.end(); ++it) + if ((*it).startsWith(fname)) { + env.erase(it); + if (env.isEmpty()) + env.append(QString::fromLatin1(DUMMYENV)); + setEnvironment(env); + return; + } +} + +void KProcess::setProgram(const QString &exe, const QStringList &args) +{ + Q_D(KProcess); + + d->prog = exe; + d->args = args; +#ifdef Q_OS_WIN + setNativeArguments(QString()); +#endif +} + +void KProcess::setProgram(const QStringList &argv) +{ + Q_D(KProcess); + + Q_ASSERT( !argv.isEmpty() ); + d->args = argv; + d->prog = d->args.takeFirst(); +#ifdef Q_OS_WIN + setNativeArguments(QString()); +#endif +} + +KProcess &KProcess::operator<<(const QString &arg) +{ + Q_D(KProcess); + + if (d->prog.isEmpty()) + d->prog = arg; + else + d->args << arg; + return *this; +} + +KProcess &KProcess::operator<<(const QStringList &args) +{ + Q_D(KProcess); + + if (d->prog.isEmpty()) + setProgram(args); + else + d->args << args; + return *this; +} + +void KProcess::clearProgram() +{ + Q_D(KProcess); + + d->prog.clear(); + d->args.clear(); +#ifdef Q_OS_WIN + setNativeArguments(QString()); +#endif +} + +#if 0 +void KProcess::setShellCommand(const QString &cmd) +{ + Q_D(KProcess); + + KShell::Errors err; + d->args = KShell::splitArgs( + cmd, KShell::AbortOnMeta | KShell::TildeExpand, &err); + if (err == KShell::NoError && !d->args.isEmpty()) { + d->prog = KStandardDirs::findExe(d->args[0]); + if (!d->prog.isEmpty()) { + d->args.removeFirst(); +#ifdef Q_OS_WIN + setNativeArguments(QString()); +#endif + return; + } + } + + d->args.clear(); + +#ifdef Q_OS_UNIX +// #ifdef NON_FREE // ... as they ship non-POSIX /bin/sh +# if !defined(__linux__) && !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && !defined(__DragonFly__) && !defined(__GNU__) + // If /bin/sh is a symlink, we can be pretty sure that it points to a + // POSIX shell - the original bourne shell is about the only non-POSIX + // shell still in use and it is always installed natively as /bin/sh. + d->prog = QFile::symLinkTarget(QString::fromLatin1("/bin/sh")); + if (d->prog.isEmpty()) { + // Try some known POSIX shells. + d->prog = KStandardDirs::findExe(QString::fromLatin1("ksh")); + if (d->prog.isEmpty()) { + d->prog = KStandardDirs::findExe(QString::fromLatin1("ash")); + if (d->prog.isEmpty()) { + d->prog = KStandardDirs::findExe(QString::fromLatin1("bash")); + if (d->prog.isEmpty()) { + d->prog = KStandardDirs::findExe(QString::fromLatin1("zsh")); + if (d->prog.isEmpty()) + // We're pretty much screwed, to be honest ... + d->prog = QString::fromLatin1("/bin/sh"); + } + } + } + } +# else + d->prog = QString::fromLatin1("/bin/sh"); +# endif + + d->args << QString::fromLatin1("-c") << cmd; +#else // Q_OS_UNIX + // KMacroExpander::expandMacrosShellQuote(), KShell::quoteArg() and + // KShell::joinArgs() may generate these for security reasons. + setEnv(PERCENT_VARIABLE, QLatin1String("%")); + +#ifndef _WIN32_WCE + WCHAR sysdir[MAX_PATH + 1]; + UINT size = GetSystemDirectoryW(sysdir, MAX_PATH + 1); + d->prog = QString::fromUtf16((const ushort *) sysdir, size); + d->prog += QLatin1String("\\cmd.exe"); + setNativeArguments(QLatin1String("/V:OFF /S /C \"") + cmd + QLatin1Char('"')); +#else + d->prog = QLatin1String("\\windows\\cmd.exe"); + setNativeArguments(QLatin1String("/S /C \"") + cmd + QLatin1Char('"')); +#endif +#endif +} +#endif +QStringList KProcess::program() const +{ + Q_D(const KProcess); + + QStringList argv = d->args; + argv.prepend(d->prog); + return argv; +} + +void KProcess::start() +{ + Q_D(KProcess); + + QProcess::start(d->prog, d->args, d->openMode); +} + +int KProcess::execute(int msecs) +{ + start(); + if (!waitForFinished(msecs)) { + kill(); + waitForFinished(-1); + return -2; + } + return (exitStatus() == QProcess::NormalExit) ? exitCode() : -1; +} + +// static +int KProcess::execute(const QString &exe, const QStringList &args, int msecs) +{ + KProcess p; + p.setProgram(exe, args); + return p.execute(msecs); +} + +// static +int KProcess::execute(const QStringList &argv, int msecs) +{ + KProcess p; + p.setProgram(argv); + return p.execute(msecs); +} + +int KProcess::startDetached() +{ + Q_D(KProcess); + + qint64 pid; + if (!QProcess::startDetached(d->prog, d->args, workingDirectory(), &pid)) + return 0; + return static_cast(pid); +} + +// static +int KProcess::startDetached(const QString &exe, const QStringList &args) +{ + qint64 pid; + if (!QProcess::startDetached(exe, args, QString(), &pid)) + return 0; + return static_cast(pid); +} + +// static +int KProcess::startDetached(const QStringList &argv) +{ + QStringList args = argv; + QString prog = args.takeFirst(); + return startDetached(prog, args); +} diff --git a/qtermwidget/lib/kprocess.h b/qtermwidget/lib/kprocess.h new file mode 100644 index 0000000..b61fc3f --- /dev/null +++ b/qtermwidget/lib/kprocess.h @@ -0,0 +1,358 @@ +/* + * This file is a part of QTerminal - http://gitorious.org/qterminal + * + * This file was un-linked from KDE and modified + * by Maxim Bourmistrov + * + */ + +/* + This file is part of the KDE libraries + + Copyright (C) 2007 Oswald Buddenhagen + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#ifndef KPROCESS_H +#define KPROCESS_H + +//#include + +#include + +#include + +class KProcessPrivate; + +/** + * \class KProcess kprocess.h + * + * Child process invocation, monitoring and control. + * + * This class extends QProcess by some useful functionality, overrides + * some defaults with saner values and wraps parts of the API into a more + * accessible one. + * This is the preferred way of spawning child processes in KDE; don't + * use QProcess directly. + * + * @author Oswald Buddenhagen + **/ +class KProcess : public QProcess +{ + Q_OBJECT + Q_DECLARE_PRIVATE(KProcess) + +public: + + /** + * Modes in which the output channels can be opened. + */ + enum OutputChannelMode { + SeparateChannels = QProcess::SeparateChannels, + /**< Standard output and standard error are handled by KProcess + as separate channels */ + MergedChannels = QProcess::MergedChannels, + /**< Standard output and standard error are handled by KProcess + as one channel */ + ForwardedChannels = QProcess::ForwardedChannels, + /**< Both standard output and standard error are forwarded + to the parent process' respective channel */ + OnlyStdoutChannel = QProcess::ForwardedErrorChannel, + /**< Only standard output is handled; standard error is forwarded */ + OnlyStderrChannel = QProcess::ForwardedOutputChannel + /**< Only standard error is handled; standard output is forwarded */ + }; + + /** + * Constructor + */ + explicit KProcess(QObject *parent = nullptr); + + /** + * Destructor + */ + ~KProcess() override; + + /** + * Set how to handle the output channels of the child process. + * + * The default is ForwardedChannels, which is unlike in QProcess. + * Do not request more than you actually handle, as this output is + * simply lost otherwise. + * + * This function must be called before starting the process. + * + * @param mode the output channel handling mode + */ + void setOutputChannelMode(OutputChannelMode mode); + + /** + * Query how the output channels of the child process are handled. + * + * @return the output channel handling mode + */ + OutputChannelMode outputChannelMode() const; + + /** + * Set the QIODevice open mode the process will be opened in. + * + * This function must be called before starting the process, obviously. + * + * @param mode the open mode. Note that this mode is automatically + * "reduced" according to the channel modes and redirections. + * The default is QIODevice::ReadWrite. + */ + void setNextOpenMode(QIODevice::OpenMode mode); + + /** + * Adds the variable @p name to the process' environment. + * + * This function must be called before starting the process. + * + * @param name the name of the environment variable + * @param value the new value for the environment variable + * @param overwrite if @c false and the environment variable is already + * set, the old value will be preserved + */ + void setEnv(const QString &name, const QString &value, bool overwrite = true); + + /** + * Removes the variable @p name from the process' environment. + * + * This function must be called before starting the process. + * + * @param name the name of the environment variable + */ + void unsetEnv(const QString &name); + + /** + * Empties the process' environment. + * + * Note that LD_LIBRARY_PATH/DYLD_LIBRARY_PATH is automatically added + * on *NIX. + * + * This function must be called before starting the process. + */ + void clearEnvironment(); + + /** + * Set the program and the command line arguments. + * + * This function must be called before starting the process, obviously. + * + * @param exe the program to execute + * @param args the command line arguments for the program, + * one per list element + */ + void setProgram(const QString &exe, const QStringList &args = QStringList()); + + /** + * @overload + * + * @param argv the program to execute and the command line arguments + * for the program, one per list element + */ + void setProgram(const QStringList &argv); + + /** + * Append an element to the command line argument list for this process. + * + * If no executable is set yet, it will be set instead. + * + * For example, doing an "ls -l /usr/local/bin" can be achieved by: + * \code + * KProcess p; + * p << "ls" << "-l" << "/usr/local/bin"; + * ... + * \endcode + * + * This function must be called before starting the process, obviously. + * + * @param arg the argument to add + * @return a reference to this KProcess + */ + KProcess &operator<<(const QString& arg); + + /** + * @overload + * + * @param args the arguments to add + * @return a reference to this KProcess + */ + KProcess &operator<<(const QStringList& args); + + /** + * Clear the program and command line argument list. + */ + void clearProgram(); + + /** + * Set a command to execute through a shell (a POSIX sh on *NIX + * and cmd.exe on Windows). + * + * Using this for anything but user-supplied commands is usually a bad + * idea, as the command's syntax depends on the platform. + * Redirections including pipes, etc. are better handled by the + * respective functions provided by QProcess. + * + * If KProcess determines that the command does not really need a + * shell, it will transparently execute it without one for performance + * reasons. + * + * This function must be called before starting the process, obviously. + * + * @param cmd the command to execute through a shell. + * The caller must make sure that all filenames etc. are properly + * quoted when passed as argument. Failure to do so often results in + * serious security holes. See KShell::quoteArg(). + */ + void setShellCommand(const QString &cmd); + + /** + * Obtain the currently set program and arguments. + * + * @return a list, the first element being the program, the remaining ones + * being command line arguments to the program. + */ + QStringList program() const; + + /** + * Start the process. + * + * @see QProcess::start(const QString &, const QStringList &, OpenMode) + */ + void start(); + + /** + * Start the process, wait for it to finish, and return the exit code. + * + * This method is roughly equivalent to the sequence: + * + * start(); + * waitForFinished(msecs); + * return exitCode(); + * + * + * Unlike the other execute() variants this method is not static, + * so the process can be parametrized properly and talked to. + * + * @param msecs time to wait for process to exit before killing it + * @return -2 if the process could not be started, -1 if it crashed, + * otherwise its exit code + */ + int execute(int msecs = -1); + + /** + * @overload + * + * @param exe the program to execute + * @param args the command line arguments for the program, + * one per list element + * @param msecs time to wait for process to exit before killing it + * @return -2 if the process could not be started, -1 if it crashed, + * otherwise its exit code + */ + static int execute(const QString &exe, const QStringList &args = QStringList(), int msecs = -1); + + /** + * @overload + * + * @param argv the program to execute and the command line arguments + * for the program, one per list element + * @param msecs time to wait for process to exit before killing it + * @return -2 if the process could not be started, -1 if it crashed, + * otherwise its exit code + */ + static int execute(const QStringList &argv, int msecs = -1); + + /** + * Start the process and detach from it. See QProcess::startDetached() + * for details. + * + * Unlike the other startDetached() variants this method is not static, + * so the process can be parametrized properly. + * @note Currently, only the setProgram()/setShellCommand() and + * setWorkingDirectory() parametrizations are supported. + * + * The KProcess object may be re-used immediately after calling this + * function. + * + * @return the PID of the started process or 0 on error + */ + int startDetached(); + + /** + * @overload + * + * @param exe the program to start + * @param args the command line arguments for the program, + * one per list element + * @return the PID of the started process or 0 on error + */ + static int startDetached(const QString &exe, const QStringList &args = QStringList()); + + /** + * @overload + * + * @param argv the program to start and the command line arguments + * for the program, one per list element + * @return the PID of the started process or 0 on error + */ + static int startDetached(const QStringList &argv); + +protected: + /** + * @internal + */ + KProcess(KProcessPrivate *d, QObject *parent); + + /** + * @internal + */ + std::unique_ptr const d_ptr; + +private: + // hide those +#if QT_VERSION < 0x060000 + using QProcess::setReadChannelMode; + using QProcess::readChannelMode; +#endif + using QProcess::setProcessChannelMode; + using QProcess::processChannelMode; +}; + +/* ----------- kprocess_p.h ---------------- */ +class KProcessPrivate { + + Q_DECLARE_PUBLIC(KProcess) + +protected: + KProcessPrivate(KProcess *qq) : + openMode(QIODevice::ReadWrite), + q_ptr(qq) + { + } + + QString prog; + QStringList args; + QIODevice::OpenMode openMode; + + KProcess *q_ptr; +}; +/* ------------------------------------------- */ +#endif + diff --git a/qtermwidget/src/kpty.cpp b/qtermwidget/lib/kpty.cpp similarity index 50% rename from qtermwidget/src/kpty.cpp rename to qtermwidget/lib/kpty.cpp index 953b956..d34764f 100644 --- a/qtermwidget/src/kpty.cpp +++ b/qtermwidget/lib/kpty.cpp @@ -24,6 +24,30 @@ #include "kpty_p.h" +#include + + +#if defined(__FreeBSD__) || defined(__DragonFly__) +#define HAVE_LOGIN +#define HAVE_LIBUTIL_H +#endif + +#if defined(__OpenBSD__) +#define HAVE_LOGIN +#define HAVE_UTIL_H +#endif + +#if defined(__NetBSD__) +#define HAVE_LOGIN +#define HAVE_UTIL_H +#define HAVE_OPENPTY +#endif + +#if defined(__APPLE__) +#define HAVE_OPENPTY +#define HAVE_UTIL_H +#endif + #ifdef __sgi #define __svr4__ #endif @@ -52,12 +76,12 @@ #include #include -#include +#include #include -#include -#include -#include -#include +#include +#include +#include +#include #include #include @@ -83,8 +107,10 @@ extern "C" { # 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 +# ifdef HAVE_UPDWTMPX +# if !defined(_PATH_WTMPX) && defined(_WTMPX_FILE) +# define _PATH_WTMPX _WTMPX_FILE +# endif # endif #endif @@ -103,24 +129,24 @@ extern "C" { #endif #ifdef HAVE_SYS_STROPTS_H -# include // Defines I_PUSH +# include // Defines I_PUSH # define _NEW_TTY_CTRL #endif -#if defined (__FreeBSD__) || defined (__NetBSD__) || defined (__OpenBSD__) || defined (__bsdi__) || defined(__APPLE__) || defined (__DragonFly__) +#if defined (__FreeBSD__) || defined(__FreeBSD_kernel__) || defined (__NetBSD__) || defined (__OpenBSD__) || defined (__bsdi__) || defined(__APPLE__) || defined (__DragonFly__) # define _tcgetattr(fd, ttmode) ioctl(fd, TIOCGETA, (char *)ttmode) #else -# if defined(_HPUX_SOURCE) || defined(__Lynx__) || defined (__CYGWIN__) +# if defined(_HPUX_SOURCE) || defined(__Lynx__) || defined (__CYGWIN__) || defined(__GNU__) # 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__) +#if defined (__FreeBSD__) || defined(__FreeBSD_kernel__) || defined (__NetBSD__) || defined (__OpenBSD__) || defined (__bsdi__) || defined(__APPLE__) || defined (__DragonFly__) # define _tcsetattr(fd, ttmode) ioctl(fd, TIOCSETA, (char *)ttmode) #else -# if defined(_HPUX_SOURCE) || defined(__CYGWIN__) +# if defined(_HPUX_SOURCE) || defined(__CYGWIN__) || defined(__GNU__) # define _tcsetattr(fd, ttmode) tcsetattr(fd, TCSANOW, ttmode) # else # define _tcsetattr(fd, ttmode) ioctl(fd, TCSETS, (char *)ttmode) @@ -128,9 +154,7 @@ extern "C" { #endif //#include -//#include // findExe - -#include +//#include // findExe // not defined on HP-UX for example #ifndef CTRL @@ -147,8 +171,12 @@ extern "C" { // private data // ////////////////// -KPtyPrivate::KPtyPrivate() : - masterFd(-1), slaveFd(-1) +KPtyPrivate::KPtyPrivate(KPty* parent) : + masterFd(-1), slaveFd(-1), ownMaster(true), q_ptr(parent) +{ +} + +KPtyPrivate::~KPtyPrivate() { } @@ -164,13 +192,12 @@ bool KPtyPrivate::chownpty(bool) ///////////////////////////// KPty::KPty() : - d_ptr(new KPtyPrivate) + d_ptr(new KPtyPrivate(this)) { - d_ptr->q_ptr = this; } KPty::KPty(KPtyPrivate *d) : - d_ptr(d) + d_ptr(d) { d_ptr->q_ptr = this; } @@ -178,216 +205,278 @@ KPty::KPty(KPtyPrivate *d) : KPty::~KPty() { close(); - delete d_ptr; } bool KPty::open() { - Q_D(KPty); + Q_D(KPty); - if (d->masterFd >= 0) - return true; + if (d->masterFd >= 0) + return true; - QByteArray ptyName; + d->ownMaster = true; - // Find a master pty that we can open //////////////////////////////// + QByteArray ptyName; - // Because not all the pty animals are created equal, they want to - // be opened by several different methods. + // Find a master pty that we can open //////////////////////////////// - // We try, as we know them, one by one. + // 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; + char ptsn[PATH_MAX]; + if (::openpty( &d->masterFd, &d->slaveFd, ptsn, 0, 0)) { + d->masterFd = -1; + d->slaveFd = -1; + qWarning() << "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; - } + 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); + d->masterFd = ::posix_openpt(O_RDWR|O_NOCTTY); #elif defined(HAVE_GETPT) - d->masterFd = ::getpt(); + d->masterFd = ::getpt(); #elif defined(PTM_DEVICE) - d->masterFd = ::open(PTM_DEVICE, O_RDWR|O_NOCTTY); + d->masterFd = ::open(PTM_DEVICE, O_RDWR|O_NOCTTY); #else # error No method to open a PTY master detected. #endif - - if (d->masterFd >= 0) - { - + if (d->masterFd >= 0) { #ifdef HAVE_PTSNAME - char *ptsn = ptsname(d->masterFd); - if (ptsn) { - d->ttyName = ptsn; + char *ptsn = ptsname(d->masterFd); + if (ptsn) { + d->ttyName = ptsn; #else int ptyno; - if (!ioctl(d->masterFd, TIOCGPTN, &ptyno)) { + if (ioctl(d->masterFd, TIOCGPTN, &ptyno) != -1) { d->ttyName = QByteArray("/dev/pts/") + QByteArray::number(ptyno); #endif #ifdef HAVE_GRANTPT - if (!grantpt(d->masterFd)) - goto grantedpt; + if (!grantpt(d->masterFd)) { + goto grantedpt; + } #else - goto gotpty; + 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; - } } - } +#endif // HAVE_PTSNAME || TIOCGPTN - qWarning() << "Can't open a pseudo teletype"; - return false; + // Linux device names, FIXME: Trouble on other systems? + for (const char * s3 = "pqrstuvwxyzabcde"; *s3; s3++) { + for (const char * s4 = "0123456789abcdef"; *s4; s4++) { + ptyName = QByteArrayLiteral("/dev/pty") + *s3 + *s4; + d->ttyName = QByteArrayLiteral("/dev/tty") + *s3 + *s4; - 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. + 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) != -1 || 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 (); + + if (!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." + << Qt::endl; } - 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 +grantedpt: +#endif #ifdef HAVE_REVOKE - revoke(d->ttyName.data()); + revoke(d->ttyName.data()); #endif #ifdef HAVE_UNLOCKPT - unlockpt(d->masterFd); + unlockpt(d->masterFd); #elif defined(TIOCSPTLCK) - int flag = 0; - ioctl(d->masterFd, TIOCSPTLCK, &flag); + 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; - } + 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"); + // 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); + fcntl(d->masterFd, F_SETFD, FD_CLOEXEC); + fcntl(d->slaveFd, F_SETFD, FD_CLOEXEC); - return true; + return true; +} + +bool KPty::open(int fd) +{ +#if !defined(HAVE_PTSNAME) && !defined(TIOCGPTN) + qWarning() << "Unsupported attempt to open pty with fd" << fd; + return false; +#else + Q_D(KPty); + + if (d->masterFd >= 0) { + qWarning() << "Attempting to open an already open pty"; + return false; + } + + d->ownMaster = false; + +# ifdef HAVE_PTSNAME + char *ptsn = ptsname(fd); + if (ptsn) { + d->ttyName = ptsn; +# else + int ptyno; + if (ioctl(fd, TIOCGPTN, &ptyno) != -1) { + const size_t sz = 32; + char buf[sz]; + const size_t r = snprintf(buf, sz, "/dev/pts/%d", ptyno); + if (sz <= r) { + qWarning("KPty::open: Buffer too small\n"); + } + d->ttyName = buf; +# endif + } else { + qWarning() << "Failed to determine pty slave device for fd" << fd; + return false; + } + + d->masterFd = fd; + if (!openSlave()) { + + d->masterFd = -1; + return false; + } + + return true; +#endif } void KPty::closeSlave() { Q_D(KPty); - if (d->slaveFd < 0) + if (d->slaveFd < 0) { return; + } ::close(d->slaveFd); d->slaveFd = -1; } +bool KPty::openSlave() +{ + Q_D(KPty); + + if (d->slaveFd >= 0) + return true; + if (d->masterFd < 0) { + qDebug() << "Attempting to open pty slave while master is closed"; + return false; + } + //d->slaveFd = KDE_open(d->ttyName.data(), O_RDWR | O_NOCTTY); + d->slaveFd = ::open(d->ttyName.data(), O_RDWR | O_NOCTTY); + if (d->slaveFd < 0) { + qDebug() << "Can't open slave pseudo teletype"; + return false; + } + fcntl(d->slaveFd, F_SETFD, FD_CLOEXEC); + return true; +} + void KPty::close() { - Q_D(KPty); + Q_D(KPty); - if (d->masterFd < 0) - return; - closeSlave(); - // don't bother resetting unix98 pty, it will go away after closing master anyway. - if (memcmp(d->ttyName.data(), "/dev/pts/", 9)) { - if (!geteuid()) { - struct stat st; - if (!stat(d->ttyName.data(), &st)) { - chown(d->ttyName.data(), 0, st.st_gid == getgid() ? 0 : -1); - chmod(d->ttyName.data(), S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH); - } - } else { - fcntl(d->masterFd, F_SETFD, 0); - d->chownpty(false); - } - } - ::close(d->masterFd); - d->masterFd = -1; + if (d->masterFd < 0) { + return; + } + closeSlave(); + // 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() @@ -417,12 +506,12 @@ void KPty::setCTty() #endif } -void KPty::login(const char *user, const char *remotehost) +void KPty::login(const char * user, const char * remotehost) { #ifdef HAVE_UTEMPTER Q_D(KPty); - addToUtmp(d->ttyName, remotehost, d->masterFd); + addToUtmp(d->ttyName.constData(), remotehost, d->masterFd); Q_UNUSED(user); #else # ifdef HAVE_UTMPX @@ -433,21 +522,27 @@ void KPty::login(const char *user, const char *remotehost) 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 (user) { +# ifdef HAVE_UTMPX + strncpy(l_struct.ut_user, user, sizeof(l_struct.ut_user)); +# else + strncpy(l_struct.ut_name, user, sizeof(l_struct.ut_name)); +# endif + } if (remotehost) { - strncpy(l_struct.ut_host, remotehost, sizeof(l_struct.ut_host)); + 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)); + 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)) + 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, @@ -459,7 +554,7 @@ void KPty::login(const char *user, const char *remotehost) # ifdef HAVE_UTMPX gettimeofday(&l_struct.ut_tv, 0); # else - l_struct.ut_time = time(0); + l_struct.ut_time = time(nullptr); # endif # ifdef HAVE_LOGIN @@ -483,7 +578,9 @@ void KPty::login(const char *user, const char *remotehost) setutxent(); pututxline(&l_struct); endutxent(); +# ifdef HAVE_UPDWTMPX updwtmpx(_PATH_WTMPX, &l_struct); +# endif # else utmpname(_PATH_UTMP); setutent(); @@ -500,18 +597,20 @@ void KPty::logout() #ifdef HAVE_UTEMPTER Q_D(KPty); - removeLineFromUtmp(d->ttyName, d->masterFd); + removeLineFromUtmp(d->ttyName.constData(), d->masterFd); #else Q_D(KPty); const char *str_ptr = d->ttyName.data(); - if (!memcmp(str_ptr, "/dev/", 5)) + if (!memcmp(str_ptr, "/dev/", 5)) { str_ptr += 5; + } # ifdef __GLIBC__ else { - const char *sl_ptr = strrchr(str_ptr, '/'); - if (sl_ptr) + const char * sl_ptr = strrchr(str_ptr, '/'); + if (sl_ptr) { str_ptr = sl_ptr + 1; + } } # endif # ifdef HAVE_LOGIN @@ -539,7 +638,11 @@ void KPty::logout() setutent(); if ((ut = getutline(&l_struct))) { # endif +# ifdef HAVE_UTMPX + memset(ut->ut_user, 0, sizeof(*ut->ut_user)); +# else memset(ut->ut_name, 0, sizeof(*ut->ut_name)); +# endif memset(ut->ut_host, 0, sizeof(*ut->ut_host)); # ifdef HAVE_STRUCT_UTMP_UT_SYSLEN ut->ut_syslen = 0; @@ -548,15 +651,15 @@ void KPty::logout() ut->ut_type = DEAD_PROCESS; # endif # ifdef HAVE_UTMPX - gettimeofday(ut->ut_tv, 0); + gettimeofday(&ut->ut_tv, 0); pututxline(ut); } endutxent(); # else - ut->ut_time = time(0); - pututline(ut); - } - endutent(); + ut->ut_time = time(nullptr); + pututline(ut); +} +endutent(); # endif # endif #endif @@ -565,14 +668,14 @@ void KPty::logout() // XXX Supposedly, tc[gs]etattr do not work with the master on Solaris. // Please verify. -bool KPty::tcGetAttr(struct ::termios *ttmode) const +bool KPty::tcGetAttr(struct ::termios * ttmode) const { Q_D(const KPty); return _tcgetattr(d->masterFd, ttmode) == 0; } -bool KPty::tcSetAttr(struct ::termios *ttmode) +bool KPty::tcSetAttr(struct ::termios * ttmode) { Q_D(KPty); @@ -587,22 +690,24 @@ bool KPty::setWinSize(int lines, int columns) 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; + return ioctl(d->masterFd, TIOCSWINSZ, (char *)&winSize) != -1; } bool KPty::setEcho(bool echo) { struct ::termios ttmode; - if (!tcGetAttr(&ttmode)) + if (!tcGetAttr(&ttmode)) { return false; - if (!echo) + } + if (!echo) { ttmode.c_lflag &= ~ECHO; - else + } else { ttmode.c_lflag |= ECHO; + } return tcSetAttr(&ttmode); } -const char *KPty::ttyName() const +const char * KPty::ttyName() const { Q_D(const KPty); diff --git a/qtermwidget/lib/kpty.h b/qtermwidget/lib/kpty.h new file mode 100644 index 0000000..648461c --- /dev/null +++ b/qtermwidget/lib/kpty.h @@ -0,0 +1,196 @@ +/* This file is part of the KDE libraries + + Copyright (C) 2003,2007 Oswald Buddenhagen + + Rewritten for QT4 by e_k , Copyright (C)2008 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#ifndef kpty_h +#define kpty_h + +#include + +#include + +class KPtyPrivate; +struct termios; + +/** + * Provides primitives for opening & closing a pseudo TTY pair, assigning the + * controlling TTY, utmp registration and setting various terminal attributes. + */ +class KPty { + Q_DECLARE_PRIVATE(KPty) + +public: + + /** + * Constructor + */ + KPty(); + + /** + * Destructor: + * + * If the pty is still open, it will be closed. Note, however, that + * an utmp registration is @em not undone. + */ + ~KPty(); + + KPty(const KPty &) = delete; + KPty &operator=(const KPty &) = delete; + + /** + * Create a pty master/slave pair. + * + * @return true if a pty pair was successfully opened + */ + bool open(); + + bool open(int fd); + + /** + * Close the pty master/slave pair. + */ + void close(); + + /** + * Close the pty slave descriptor. + * + * When creating the pty, KPty also opens the slave and keeps it open. + * Consequently the master will never receive an EOF notification. + * Usually this is the desired behavior, as a closed pty slave can be + * reopened any time - unlike a pipe or socket. However, in some cases + * pipe-alike behavior might be desired. + * + * After this function was called, slaveFd() and setCTty() cannot be + * used. + */ + void closeSlave(); + bool openSlave(); + + /** + * Creates a new session and process group and makes this pty the + * controlling tty. + */ + void setCTty(); + + /** + * Creates an utmp entry for the tty. + * This function must be called after calling setCTty and + * making this pty the stdin. + * @param user the user to be logged on + * @param remotehost the host from which the login is coming. This is + * @em not the local host. For remote logins it should be the hostname + * of the client. For local logins from inside an X session it should + * be the name of the X display. Otherwise it should be empty. + */ + void login(const char * user = nullptr, const char * remotehost = nullptr); + + /** + * Removes the utmp entry for this tty. + */ + void logout(); + + /** + * Wrapper around tcgetattr(3). + * + * This function can be used only while the PTY is open. + * You will need an #include <termios.h> to do anything useful + * with it. + * + * @param ttmode a pointer to a termios structure. + * Note: when declaring ttmode, @c struct @c ::termios must be used - + * without the '::' some version of HP-UX thinks, this declares + * the struct in your class, in your method. + * @return @c true on success, false otherwise + */ + bool tcGetAttr(struct ::termios * ttmode) const; + + /** + * Wrapper around tcsetattr(3) with mode TCSANOW. + * + * This function can be used only while the PTY is open. + * + * @param ttmode a pointer to a termios structure. + * @return @c true on success, false otherwise. Note that success means + * that @em at @em least @em one attribute could be set. + */ + bool tcSetAttr(struct ::termios * ttmode); + + /** + * Change the logical (screen) size of the pty. + * The default is 24 lines by 80 columns. + * + * This function can be used only while the PTY is open. + * + * @param lines the number of rows + * @param columns the number of columns + * @return @c true on success, false otherwise + */ + bool setWinSize(int lines, int columns); + + /** + * Set whether the pty should echo input. + * + * Echo is on by default. + * If the output of automatically fed (non-interactive) PTY clients + * needs to be parsed, disabling echo often makes it much simpler. + * + * This function can be used only while the PTY is open. + * + * @param echo true if input should be echoed. + * @return @c true on success, false otherwise + */ + bool setEcho(bool echo); + + /** + * @return the name of the slave pty device. + * + * This function should be called only while the pty is open. + */ + const char * ttyName() const; + + /** + * @return the file descriptor of the master pty + * + * This function should be called only while the pty is open. + */ + int masterFd() const; + + /** + * @return the file descriptor of the slave pty + * + * This function should be called only while the pty slave is open. + */ + int slaveFd() const; + +protected: + /** + * @internal + */ + KPty(KPtyPrivate * d); + + /** + * @internal + */ + std::unique_ptr const d_ptr; +}; + +#endif + diff --git a/qtermwidget/src/kpty_p.h b/qtermwidget/lib/kpty_p.h similarity index 89% rename from qtermwidget/src/kpty_p.h rename to qtermwidget/lib/kpty_p.h index 1702b44..28ed2a5 100644 --- a/qtermwidget/src/kpty_p.h +++ b/qtermwidget/lib/kpty_p.h @@ -25,16 +25,21 @@ #include "kpty.h" -#include +#include + +class KPtyPrivate { +public: -struct KPtyPrivate { Q_DECLARE_PUBLIC(KPty) - KPtyPrivate(); + KPtyPrivate(KPty* parent); + virtual ~KPtyPrivate(); + bool chownpty(bool grant); int masterFd; int slaveFd; + bool ownMaster:1; QByteArray ttyName; diff --git a/qtermwidget/lib/kptydevice.cpp b/qtermwidget/lib/kptydevice.cpp new file mode 100644 index 0000000..9af1545 --- /dev/null +++ b/qtermwidget/lib/kptydevice.cpp @@ -0,0 +1,422 @@ +/* + * This file is a part of QTerminal - http://gitorious.org/qterminal + * + * This file was un-linked from KDE and modified + * by Maxim Bourmistrov + * + */ + +/* + + This file is part of the KDE libraries + Copyright (C) 2007 Oswald Buddenhagen + Copyright (C) 2010 KDE e.V. + Author Adriaan de Groot + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include "kptydevice.h" +#include "kpty_p.h" + +#include + +#include +#include +#include +#include +#include +#include +#ifdef HAVE_SYS_FILIO_H +# include +#endif +#ifdef HAVE_SYS_TIME_H +# include +#endif + +#if defined(Q_OS_FREEBSD) || defined(Q_OS_MAC) + // "the other end's output queue size" - kinda braindead, huh? +# define PTY_BYTES_AVAILABLE TIOCOUTQ +#elif defined(TIOCINQ) + // "our end's input queue size" +# define PTY_BYTES_AVAILABLE TIOCINQ +#else + // likewise. more generic ioctl (theoretically) +# define PTY_BYTES_AVAILABLE FIONREAD +#endif + + + + +////////////////// +// private data // +////////////////// + +// Lifted from Qt. I don't think they would mind. ;) +// Re-lift again from Qt whenever a proper replacement for pthread_once appears +static void qt_ignore_sigpipe() +{ + static QBasicAtomicInt atom = Q_BASIC_ATOMIC_INITIALIZER(0); + if (atom.testAndSetRelaxed(0, 1)) { + struct sigaction noaction; + memset(&noaction, 0, sizeof(noaction)); + noaction.sa_handler = SIG_IGN; + sigaction(SIGPIPE, &noaction, nullptr); + } +} + +#define NO_INTR(ret,func) do { ret = func; } while (ret < 0 && errno == EINTR) + +bool KPtyDevicePrivate::_k_canRead() +{ + Q_Q(KPtyDevice); + qint64 readBytes = 0; + +#ifdef Q_OS_IRIX // this should use a config define, but how to check it? + size_t available; +#else + int available; +#endif + if (::ioctl(q->masterFd(), PTY_BYTES_AVAILABLE, (char *) &available) != -1) { +#ifdef Q_OS_SOLARIS + // A Pty is a STREAMS module, and those can be activated + // with 0 bytes available. This happens either when ^C is + // pressed, or when an application does an explicit write(a,b,0) + // which happens in experiments fairly often. When 0 bytes are + // available, you must read those 0 bytes to clear the STREAMS + // module, but we don't want to hit the !readBytes case further down. + if (!available) { + char c; + // Read the 0-byte STREAMS message + NO_INTR(readBytes, read(q->masterFd(), &c, 0)); + // Should return 0 bytes read; -1 is error + if (readBytes < 0) { + readNotifier->setEnabled(false); + emit q->readEof(); + return false; + } + return true; + } +#endif + + char *ptr = readBuffer.reserve(available); +#ifdef Q_OS_SOLARIS + // Even if available > 0, it is possible for read() + // to return 0 on Solaris, due to 0-byte writes in the stream. + // Ignore them and keep reading until we hit *some* data. + // In Solaris it is possible to have 15 bytes available + // and to (say) get 0, 0, 6, 0 and 9 bytes in subsequent reads. + // Because the stream is set to O_NONBLOCK in finishOpen(), + // an EOF read will return -1. + readBytes = 0; + while (!readBytes) +#endif + // Useless block braces except in Solaris + { + NO_INTR(readBytes, read(q->masterFd(), ptr, available)); + } + if (readBytes < 0) { + readBuffer.unreserve(available); + q->setErrorString(QLatin1String("Error reading from PTY")); + return false; + } + readBuffer.unreserve(available - readBytes); // *should* be a no-op + } + + if (!readBytes) { + readNotifier->setEnabled(false); + emit q->readEof(); + return false; + } else { + if (!emittedReadyRead) { + emittedReadyRead = true; + emit q->readyRead(); + emittedReadyRead = false; + } + return true; + } +} + +bool KPtyDevicePrivate::_k_canWrite() +{ + Q_Q(KPtyDevice); + + writeNotifier->setEnabled(false); + if (writeBuffer.isEmpty()) + return false; + + qt_ignore_sigpipe(); + int wroteBytes; + NO_INTR(wroteBytes, + write(q->masterFd(), + writeBuffer.readPointer(), writeBuffer.readSize())); + if (wroteBytes < 0) { + q->setErrorString(QLatin1String("Error writing to PTY")); + return false; + } + writeBuffer.free(wroteBytes); + + if (!emittedBytesWritten) { + emittedBytesWritten = true; + emit q->bytesWritten(wroteBytes); + emittedBytesWritten = false; + } + + if (!writeBuffer.isEmpty()) + writeNotifier->setEnabled(true); + return true; +} + +#ifndef timeradd +// Lifted from GLIBC +# define timeradd(a, b, result) \ + do { \ + (result)->tv_sec = (a)->tv_sec + (b)->tv_sec; \ + (result)->tv_usec = (a)->tv_usec + (b)->tv_usec; \ + if ((result)->tv_usec >= 1000000) { \ + ++(result)->tv_sec; \ + (result)->tv_usec -= 1000000; \ + } \ + } while (0) +# define timersub(a, b, result) \ + do { \ + (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \ + (result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \ + if ((result)->tv_usec < 0) { \ + --(result)->tv_sec; \ + (result)->tv_usec += 1000000; \ + } \ + } while (0) +#endif + +bool KPtyDevicePrivate::doWait(int msecs, bool reading) +{ + Q_Q(KPtyDevice); +#ifndef __linux__ + struct timeval etv; +#endif + struct timeval tv, *tvp; + + if (msecs < 0) + tvp = nullptr; + else { + tv.tv_sec = msecs / 1000; + tv.tv_usec = (msecs % 1000) * 1000; +#ifndef __linux__ + gettimeofday(&etv, 0); + timeradd(&tv, &etv, &etv); +#endif + tvp = &tv; + } + + while (reading ? readNotifier->isEnabled() : !writeBuffer.isEmpty()) { + fd_set rfds; + fd_set wfds; + + FD_ZERO(&rfds); + FD_ZERO(&wfds); + + if (readNotifier->isEnabled()) + FD_SET(q->masterFd(), &rfds); + if (!writeBuffer.isEmpty()) + FD_SET(q->masterFd(), &wfds); + +#ifndef __linux__ + if (tvp) { + gettimeofday(&tv, 0); + timersub(&etv, &tv, &tv); + if (tv.tv_sec < 0) + tv.tv_sec = tv.tv_usec = 0; + } +#endif + + switch (select(q->masterFd() + 1, &rfds, &wfds, nullptr, tvp)) { + case -1: + if (errno == EINTR) + break; + return false; + case 0: + q->setErrorString(QLatin1String("PTY operation timed out")); + return false; + default: + if (FD_ISSET(q->masterFd(), &rfds)) { + bool canRead = _k_canRead(); + if (reading && canRead) + return true; + } + if (FD_ISSET(q->masterFd(), &wfds)) { + bool canWrite = _k_canWrite(); + if (!reading) + return canWrite; + } + break; + } + } + return false; +} + +void KPtyDevicePrivate::finishOpen(QIODevice::OpenMode mode) +{ + Q_Q(KPtyDevice); + + q->QIODevice::open(mode); + fcntl(q->masterFd(), F_SETFL, O_NONBLOCK); + readBuffer.clear(); + readNotifier = new QSocketNotifier(q->masterFd(), QSocketNotifier::Read, q); + writeNotifier = new QSocketNotifier(q->masterFd(), QSocketNotifier::Write, q); + QObject::connect(readNotifier, SIGNAL(activated(int)), q, SLOT(_k_canRead())); + QObject::connect(writeNotifier, SIGNAL(activated(int)), q, SLOT(_k_canWrite())); + readNotifier->setEnabled(true); +} + +///////////////////////////// +// public member functions // +///////////////////////////// + +KPtyDevice::KPtyDevice(QObject *parent) : + QIODevice(parent), + KPty(new KPtyDevicePrivate(this)) +{ +} + +KPtyDevice::~KPtyDevice() +{ + close(); +} + +bool KPtyDevice::open(OpenMode mode) +{ + Q_D(KPtyDevice); + + if (masterFd() >= 0) + return true; + + if (!KPty::open()) { + setErrorString(QLatin1String("Error opening PTY")); + return false; + } + + d->finishOpen(mode); + + return true; +} + +bool KPtyDevice::open(int fd, OpenMode mode) +{ + Q_D(KPtyDevice); + + if (!KPty::open(fd)) { + setErrorString(QLatin1String("Error opening PTY")); + return false; + } + + d->finishOpen(mode); + + return true; +} + +void KPtyDevice::close() +{ + Q_D(KPtyDevice); + + if (masterFd() < 0) + return; + + delete d->readNotifier; + delete d->writeNotifier; + + QIODevice::close(); + + KPty::close(); +} + +bool KPtyDevice::isSequential() const +{ + return true; +} + +bool KPtyDevice::canReadLine() const +{ + Q_D(const KPtyDevice); + return QIODevice::canReadLine() || d->readBuffer.canReadLine(); +} + +bool KPtyDevice::atEnd() const +{ + Q_D(const KPtyDevice); + return QIODevice::atEnd() && d->readBuffer.isEmpty(); +} + +qint64 KPtyDevice::bytesAvailable() const +{ + Q_D(const KPtyDevice); + return QIODevice::bytesAvailable() + d->readBuffer.size(); +} + +qint64 KPtyDevice::bytesToWrite() const +{ + Q_D(const KPtyDevice); + return d->writeBuffer.size(); +} + +bool KPtyDevice::waitForReadyRead(int msecs) +{ + Q_D(KPtyDevice); + return d->doWait(msecs, true); +} + +bool KPtyDevice::waitForBytesWritten(int msecs) +{ + Q_D(KPtyDevice); + return d->doWait(msecs, false); +} + +void KPtyDevice::setSuspended(bool suspended) +{ + Q_D(KPtyDevice); + d->readNotifier->setEnabled(!suspended); +} + +bool KPtyDevice::isSuspended() const +{ + Q_D(const KPtyDevice); + return !d->readNotifier->isEnabled(); +} + +// protected +qint64 KPtyDevice::readData(char *data, qint64 maxlen) +{ + Q_D(KPtyDevice); + return d->readBuffer.read(data, (int)qMin(maxlen, KMAXINT)); +} + +// protected +qint64 KPtyDevice::readLineData(char *data, qint64 maxlen) +{ + Q_D(KPtyDevice); + return d->readBuffer.readLine(data, (int)qMin(maxlen, KMAXINT)); +} + +// protected +qint64 KPtyDevice::writeData(const char *data, qint64 len) +{ + Q_D(KPtyDevice); + Q_ASSERT(len <= KMAXINT); + + d->writeBuffer.write(data, len); + d->writeNotifier->setEnabled(true); + return len; +} diff --git a/qtermwidget/lib/kptydevice.h b/qtermwidget/lib/kptydevice.h new file mode 100644 index 0000000..5ef7753 --- /dev/null +++ b/qtermwidget/lib/kptydevice.h @@ -0,0 +1,357 @@ +/* + * This file is a part of QTerminal - http://gitorious.org/qterminal + * + * This file was un-linked from KDE and modified + * by Maxim Bourmistrov + * + */ + +/* This file is part of the KDE libraries + + Copyright (C) 2007 Oswald Buddenhagen + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#ifndef kptydev_h +#define kptydev_h + +#include "kpty_p.h" + +#include + +#define KMAXINT ((int)(~0U >> 1)) + +class KPtyDevicePrivate; +class QSocketNotifier; + +/** + * Encapsulates KPty into a QIODevice, so it can be used with Q*Stream, etc. + */ +class KPtyDevice : public QIODevice, public KPty { + Q_OBJECT + Q_DECLARE_PRIVATE_D(KPty::d_ptr, KPtyDevice) + +public: + + /** + * Constructor + */ + KPtyDevice(QObject *parent = nullptr); + + /** + * Destructor: + * + * If the pty is still open, it will be closed. Note, however, that + * an utmp registration is @em not undone. + */ + ~KPtyDevice() override; + + /** + * Create a pty master/slave pair. + * + * @return true if a pty pair was successfully opened + */ + bool open(OpenMode mode = ReadWrite | Unbuffered) override; + + /** + * Open using an existing pty master. The ownership of the fd + * remains with the caller, i.e., close() will not close the fd. + * + * This is useful if you wish to attach a secondary "controller" to an + * existing pty device such as a terminal widget. + * Note that you will need to use setSuspended() on both devices to + * control which one gets the incoming data from the pty. + * + * @param fd an open pty master file descriptor. + * @param mode the device mode to open the pty with. + * @return true if a pty pair was successfully opened + */ + bool open(int fd, OpenMode mode = ReadWrite | Unbuffered); + + /** + * Close the pty master/slave pair. + */ + void close() override; + + /** + * Sets whether the KPtyDevice monitors the pty for incoming data. + * + * When the KPtyDevice is suspended, it will no longer attempt to buffer + * data that becomes available from the pty and it will not emit any + * signals. + * + * Do not use on closed ptys. + * After a call to open(), the pty is not suspended. If you need to + * ensure that no data is read, call this function before the main loop + * is entered again (i.e., immediately after opening the pty). + */ + void setSuspended(bool suspended); + + /** + * Returns true if the KPtyDevice is not monitoring the pty for incoming + * data. + * + * Do not use on closed ptys. + * + * See setSuspended() + */ + bool isSuspended() const; + + /** + * @return always true + */ + bool isSequential() const override; + + /** + * @reimp + */ + bool canReadLine() const override; + + /** + * @reimp + */ + bool atEnd() const override; + + /** + * @reimp + */ + qint64 bytesAvailable() const override; + + /** + * @reimp + */ + qint64 bytesToWrite() const override; + + bool waitForBytesWritten(int msecs = -1) override; + bool waitForReadyRead(int msecs = -1) override; + + +Q_SIGNALS: + /** + * Emitted when EOF is read from the PTY. + * + * Data may still remain in the buffers. + */ + void readEof(); + +protected: + qint64 readData(char *data, qint64 maxSize) override; + qint64 readLineData(char *data, qint64 maxSize) override; + qint64 writeData(const char *data, qint64 maxSize) override; + +private: + Q_PRIVATE_SLOT(d_func(), bool _k_canRead()) + Q_PRIVATE_SLOT(d_func(), bool _k_canWrite()) +}; + +///////////////////////////////////////////////////// +// Helper. Remove when QRingBuffer becomes public. // +///////////////////////////////////////////////////// + +#include +#include + +#define CHUNKSIZE 4096 + +class KRingBuffer +{ +public: + KRingBuffer() + { + clear(); + } + + void clear() + { + buffers.clear(); + QByteArray tmp; + tmp.resize(CHUNKSIZE); + buffers.push_back(tmp); + head = tail = 0; + totalSize = 0; + } + + inline bool isEmpty() const + { + return buffers.size() == 1 && !tail; + } + + inline int size() const + { + return totalSize; + } + + inline int readSize() const + { + return (buffers.size() == 1 ? tail : buffers.front().size()) - head; + } + + inline const char *readPointer() const + { + Q_ASSERT(totalSize > 0); + return buffers.front().constData() + head; + } + + void free(int bytes) + { + totalSize -= bytes; + Q_ASSERT(totalSize >= 0); + + forever { + int nbs = readSize(); + + if (bytes < nbs) { + head += bytes; + if (head == tail && buffers.size() == 1) { + buffers.front().resize(CHUNKSIZE); + head = tail = 0; + } + break; + } + + bytes -= nbs; + if (buffers.size() == 1) { + buffers.front().resize(CHUNKSIZE); + head = tail = 0; + break; + } + + buffers.pop_front(); + head = 0; + } + } + + char *reserve(int bytes) + { + totalSize += bytes; + + char *ptr; + if (tail + bytes <= buffers.back().size()) { + ptr = buffers.back().data() + tail; + tail += bytes; + } else { + buffers.back().resize(tail); + QByteArray tmp; + tmp.resize(qMax(CHUNKSIZE, bytes)); + ptr = tmp.data(); + buffers.push_back(tmp); + tail = bytes; + } + return ptr; + } + + // release a trailing part of the last reservation + inline void unreserve(int bytes) + { + totalSize -= bytes; + tail -= bytes; + } + + inline void write(const char *data, int len) + { + memcpy(reserve(len), data, len); + } + + // Find the first occurrence of c and return the index after it. + // If c is not found until maxLength, maxLength is returned, provided + // it is smaller than the buffer size. Otherwise -1 is returned. + int indexAfter(char c, int maxLength = KMAXINT) const + { + int index = 0; + int start = head; + std::list::const_iterator it = buffers.cbegin(); + forever { + if (!maxLength) + return index; + if (index == size()) + return -1; + const QByteArray &buf = *it; + ++it; + int len = qMin((it == buffers.cend() ? tail : buf.size()) - start, + maxLength); + const char *ptr = buf.data() + start; + if (const char *rptr = (const char *)memchr(ptr, c, len)) + return index + (rptr - ptr) + 1; + index += len; + maxLength -= len; + start = 0; + } + } + + inline int lineSize(int maxLength = KMAXINT) const + { + return indexAfter('\n', maxLength); + } + + inline bool canReadLine() const + { + return lineSize() != -1; + } + + int read(char *data, int maxLength) + { + int bytesToRead = qMin(size(), maxLength); + int readSoFar = 0; + while (readSoFar < bytesToRead) { + const char *ptr = readPointer(); + int bs = qMin(bytesToRead - readSoFar, readSize()); + memcpy(data + readSoFar, ptr, bs); + readSoFar += bs; + free(bs); + } + return readSoFar; + } + + int readLine(char *data, int maxLength) + { + return read(data, lineSize(qMin(maxLength, size()))); + } + +private: + std::list buffers; + int head, tail; + int totalSize; +}; + +class KPtyDevicePrivate : public KPtyPrivate { + + Q_DECLARE_PUBLIC(KPtyDevice) + +public: + KPtyDevicePrivate(KPty* parent) : + KPtyPrivate(parent), + emittedReadyRead(false), emittedBytesWritten(false), + readNotifier(nullptr), writeNotifier(nullptr) + { + } + + bool _k_canRead(); + bool _k_canWrite(); + + bool doWait(int msecs, bool reading); + void finishOpen(QIODevice::OpenMode mode); + + bool emittedReadyRead; + bool emittedBytesWritten; + QSocketNotifier *readNotifier; + QSocketNotifier *writeNotifier; + KRingBuffer readBuffer; + KRingBuffer writeBuffer; +}; + +#endif + diff --git a/qtermwidget/lib/kptyprocess.cpp b/qtermwidget/lib/kptyprocess.cpp new file mode 100644 index 0000000..a285797 --- /dev/null +++ b/qtermwidget/lib/kptyprocess.cpp @@ -0,0 +1,172 @@ +/* + * This file is a part of QTerminal - http://gitorious.org/qterminal + * + * This file was un-linked from KDE and modified + * by Maxim Bourmistrov + * + */ + +/* + This file is part of the KDE libraries + + Copyright (C) 2007 Oswald Buddenhagen + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + + +#include "kptyprocess.h" +#include "kprocess.h" +#include "kptydevice.h" + +#include +#include +#include +#include + +KPtyProcess::KPtyProcess(QObject *parent) : + KPtyProcess(-1, parent) +{ + Q_D(KPtyProcess); + + d->pty = std::make_unique(this); + d->pty->open(); + connect(this, SIGNAL(stateChanged(QProcess::ProcessState)), + SLOT(_k_onStateChanged(QProcess::ProcessState))); + + setChildProcessModifier([this] { + Q_D(KPtyProcess); + d->pty->setCTty(); + + #if 0 + if (d->addUtmp) + d->pty->login(KUser(KUser::UseRealUserID).loginName().toLocal8Bit().data(), qgetenv("DISPLAY")); + #endif + if (d->ptyChannels & StdinChannel) + dup2(d->pty->slaveFd(), 0); + + if (d->ptyChannels & StdoutChannel) + dup2(d->pty->slaveFd(), 1); + + if (d->ptyChannels & StderrChannel) + dup2(d->pty->slaveFd(), 2); + }); +} + +KPtyProcess::KPtyProcess(int ptyMasterFd, QObject *parent) : + KProcess(parent), + d_ptr(new KPtyProcessPrivate) +{ + Q_D(KPtyProcess); + + d->pty = std::make_unique(this); + + if (ptyMasterFd == -1) { + d->pty->open(); + } else { + d->pty->open(ptyMasterFd); + } + + connect(this, &QProcess::stateChanged, this, [this](QProcess::ProcessState state) { + if (state == QProcess::NotRunning && d_ptr->addUtmp) { + d_ptr->pty->logout(); + } + }); +} + +KPtyProcess::~KPtyProcess() +{ + Q_D(KPtyProcess); + + if (state() != QProcess::NotRunning) + { + if (d->addUtmp) + { + d->pty->logout(); + disconnect(this, &QProcess::stateChanged, this, nullptr); + } + } + waitForFinished(300); // give it some time to finish + if (state() != QProcess::NotRunning) + { + qWarning() << Q_FUNC_INFO << "the terminal process is still running, trying to stop it by SIGHUP"; + ::kill(static_cast(processId()), SIGHUP); + waitForFinished(300); + if (state() != QProcess::NotRunning) + qCritical() << Q_FUNC_INFO << "process didn't stop upon SIGHUP and will be SIGKILL-ed"; + } +} + +void KPtyProcess::setPtyChannels(PtyChannels channels) +{ + Q_D(KPtyProcess); + + d->ptyChannels = channels; +} + +KPtyProcess::PtyChannels KPtyProcess::ptyChannels() const +{ + Q_D(const KPtyProcess); + + return d->ptyChannels; +} + +void KPtyProcess::setUseUtmp(bool value) +{ + Q_D(KPtyProcess); + + d->addUtmp = value; +} + +bool KPtyProcess::isUseUtmp() const +{ + Q_D(const KPtyProcess); + + return d->addUtmp; +} + +KPtyDevice *KPtyProcess::pty() const +{ + Q_D(const KPtyProcess); + + return d->pty.get(); +} + +#if QT_VERSION < 0x060000 +void KPtyProcess::setupChildProcess() +{ + Q_D(KPtyProcess); + + d->pty->setCTty(); + +#if 0 + if (d->addUtmp) + d->pty->login(KUser(KUser::UseRealUserID).loginName().toLocal8Bit().data(), qgetenv("DISPLAY")); +#endif + if (d->ptyChannels & StdinChannel) + dup2(d->pty->slaveFd(), 0); + + if (d->ptyChannels & StdoutChannel) + dup2(d->pty->slaveFd(), 1); + + if (d->ptyChannels & StderrChannel) + dup2(d->pty->slaveFd(), 2); + + KProcess::setupChildProcess(); +} +#endif + +//#include "kptyprocess.moc" diff --git a/qtermwidget/lib/kptyprocess.h b/qtermwidget/lib/kptyprocess.h new file mode 100644 index 0000000..7ca2f76 --- /dev/null +++ b/qtermwidget/lib/kptyprocess.h @@ -0,0 +1,173 @@ +/* + * This file is a part of QTerminal - http://gitorious.org/qterminal + * + * This file was un-linked from KDE and modified + * by Maxim Bourmistrov + * + */ + +/* + This file is part of the KDE libraries + + Copyright (C) 2007 Oswald Buddenhagen + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#ifndef KPTYPROCESS_H +#define KPTYPROCESS_H + +#include "kprocess.h" +#include "kptydevice.h" + +#include +#include + +class KPtyDevice; + +class KPtyProcessPrivate; + +/** + * This class extends KProcess by support for PTYs (pseudo TTYs). + * + * The PTY is opened as soon as the class is instantiated. Verify that + * it was opened successfully by checking that pty()->masterFd() is not -1. + * + * The PTY is always made the process' controlling TTY. + * Utmp registration and connecting the stdio handles to the PTY are optional. + * + * No attempt to integrate with QProcess' waitFor*() functions was made, + * for it is impossible. Note that execute() does not work with the PTY, too. + * Use the PTY device's waitFor*() functions or use it asynchronously. + * + * @author Oswald Buddenhagen + */ +class KPtyProcess : public KProcess +{ + Q_OBJECT + Q_DECLARE_PRIVATE(KPtyProcess) + +public: + enum PtyChannelFlag { + NoChannels = 0, /**< The PTY is not connected to any channel. */ + StdinChannel = 1, /**< Connect PTY to stdin. */ + StdoutChannel = 2, /**< Connect PTY to stdout. */ + StderrChannel = 4, /**< Connect PTY to stderr. */ + AllOutputChannels = 6, /**< Connect PTY to all output channels. */ + AllChannels = 7 /**< Connect PTY to all channels. */ + }; + + Q_DECLARE_FLAGS(PtyChannels, PtyChannelFlag) + + /** + * Constructor + */ + explicit KPtyProcess(QObject *parent = nullptr); + + /** + * Construct a process using an open pty master. + * + * @param ptyMasterFd an open pty master file descriptor. + * The process does not take ownership of the descriptor; + * it will not be automatically closed at any point. + */ + KPtyProcess(int ptyMasterFd, QObject *parent = nullptr); + + /** + * Destructor + */ + ~KPtyProcess() override; + + /** + * Set to which channels the PTY should be assigned. + * + * This function must be called before starting the process. + * + * @param channels the output channel handling mode + */ + void setPtyChannels(PtyChannels channels); + + bool isRunning() const + { + bool rval; + (processId() > 0) ? rval= true : rval= false; + return rval; + + } + /** + * Query to which channels the PTY is assigned. + * + * @return the output channel handling mode + */ + PtyChannels ptyChannels() const; + + /** + * Set whether to register the process as a TTY login in utmp. + * + * Utmp is disabled by default. + * It should enabled for interactively fed processes, like terminal + * emulations. + * + * This function must be called before starting the process. + * + * @param value whether to register in utmp. + */ + void setUseUtmp(bool value); + + /** + * Get whether to register the process as a TTY login in utmp. + * + * @return whether to register in utmp + */ + bool isUseUtmp() const; + + /** + * Get the PTY device of this process. + * + * @return the PTY device + */ + KPtyDevice *pty() const; + +protected: + /** + * @reimp + */ +#if QT_VERSION < 0x060000 + void setupChildProcess() override; +#endif +private: + std::unique_ptr const d_ptr; +}; + + +////////////////// +// private data // +////////////////// + +class KPtyProcessPrivate { +public: + KPtyProcessPrivate() + { + } + + std::unique_ptr pty; + KPtyProcess::PtyChannels ptyChannels = KPtyProcess::NoChannels; + bool addUtmp = false; +}; + +Q_DECLARE_OPERATORS_FOR_FLAGS(KPtyProcess::PtyChannels) + +#endif diff --git a/qtermwidget/lib/qtermwidget.cpp b/qtermwidget/lib/qtermwidget.cpp new file mode 100644 index 0000000..101ca6f --- /dev/null +++ b/qtermwidget/lib/qtermwidget.cpp @@ -0,0 +1,860 @@ +/* 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 +#include +#include +#include +#include +#if QT_VERSION >= 0x060000 +#include +#endif + +#include "ColorTables.h" +#include "Session.h" +#include "Screen.h" +#include "ScreenWindow.h" +#include "Emulation.h" +#include "TerminalDisplay.h" +#include "KeyboardTranslator.h" +#include "ColorScheme.h" +#include "SearchBar.h" +#include "qtermwidget.h" + +#ifdef Q_OS_MACOS +// Qt does not support fontconfig on macOS, so we need to use a "real" font name. +#define DEFAULT_FONT_FAMILY "Menlo" +#else +#define DEFAULT_FONT_FAMILY "Monospace" +#endif + +#define STEP_ZOOM 1 + +using namespace Konsole; + +void *createTermWidget(int startnow, void *parent) +{ + return (void*) new QTermWidget(startnow, (QWidget*)parent); +} + +class TermWidgetImpl { + +public: + TermWidgetImpl(QWidget* parent = nullptr); + + TerminalDisplay *m_terminalDisplay; + Session *m_session; + + Session* createSession(QWidget* parent); + TerminalDisplay* createTerminalDisplay(Session *session, QWidget* parent); +}; + +TermWidgetImpl::TermWidgetImpl(QWidget* parent) +{ + this->m_session = createSession(parent); + this->m_terminalDisplay = createTerminalDisplay(this->m_session, parent); +} + + +Session *TermWidgetImpl::createSession(QWidget* parent) +{ + Session *session = new Session(parent); + + session->setTitle(Session::NameRole, QLatin1String("QTermWidget")); + + /* That's a freaking bad idea!!!! + * /bin/bash is not there on every system + * better set it to the current $SHELL + * Maybe you can also make a list available and then let the widget-owner decide what to use. + * By setting it to $SHELL right away we actually make the first filecheck obsolete. + * But as I'm not sure if you want to do anything else I'll just let both checks in and set this to $SHELL anyway. + */ + //session->setProgram("/bin/bash"); + + session->setProgram(QString::fromLocal8Bit(qgetenv("SHELL"))); + + + + QStringList args = QStringList(QString()); + session->setArguments(args); + session->setAutoClose(true); + + session->setCodec(QTextCodec::codecForName("UTF-8")); + + session->setFlowControlEnabled(true); + session->setHistoryType(HistoryTypeBuffer(1000)); + + session->setDarkBackground(true); + + session->setKeyBindings(QString()); + 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) +{ + init(startnow); +} + +QTermWidget::QTermWidget(QWidget *parent) + : QWidget(parent) +{ + init(1); +} + +void QTermWidget::selectionChanged(bool textSelected) +{ + emit copyAvailable(textSelected); +} + +void QTermWidget::find() +{ + search(true, false); +} + +void QTermWidget::findNext() +{ + search(true, true); +} + +void QTermWidget::findPrevious() +{ + search(false, false); +} + +void QTermWidget::search(bool forwards, bool next) +{ + int startColumn, startLine; + + if (next) // search from just after current selection + { + m_impl->m_terminalDisplay->screenWindow()->screen()->getSelectionEnd(startColumn, startLine); + startColumn++; + } + else // search from start of current selection + { + m_impl->m_terminalDisplay->screenWindow()->screen()->getSelectionStart(startColumn, startLine); + } + + //qDebug() << "current selection starts at: " << startColumn << startLine; + //qDebug() << "current cursor position: " << m_impl->m_terminalDisplay->screenWindow()->cursorPosition(); + +#if QT_VERSION < 0x060000 + QRegExp regExp(m_searchBar->searchText()); + regExp.setPatternSyntax(m_searchBar->useRegularExpression() ? QRegExp::RegExp : QRegExp::FixedString); + regExp.setCaseSensitivity(m_searchBar->matchCase() ? Qt::CaseSensitive : Qt::CaseInsensitive); +#else + QRegularExpression regExp(m_searchBar->searchText(), + m_searchBar->matchCase() ? QRegularExpression::CaseInsensitiveOption| + QRegularExpression::UseUnicodePropertiesOption + : QRegularExpression::UseUnicodePropertiesOption); +#endif + HistorySearch *historySearch = + new HistorySearch(m_impl->m_session->emulation(), regExp, forwards, startColumn, startLine, this); + connect(historySearch, SIGNAL(matchFound(int, int, int, int)), this, SLOT(matchFound(int, int, int, int))); + connect(historySearch, SIGNAL(noMatchFound()), this, SLOT(noMatchFound())); + connect(historySearch, SIGNAL(noMatchFound()), m_searchBar, SLOT(noMatchFound())); + historySearch->search(); +} + + +void QTermWidget::matchFound(int startColumn, int startLine, int endColumn, int endLine) +{ + ScreenWindow* sw = m_impl->m_terminalDisplay->screenWindow(); + //qDebug() << "Scroll to" << startLine; + sw->scrollTo(startLine); + sw->setTrackOutput(false); + sw->notifyOutputChanged(); + sw->setSelectionStart(startColumn, startLine - sw->currentLine(), false); + sw->setSelectionEnd(endColumn, endLine - sw->currentLine()); +} + +void QTermWidget::noMatchFound() +{ + m_impl->m_terminalDisplay->screenWindow()->clearSelection(); +} + +int QTermWidget::getShellPID() +{ + return m_impl->m_session->processId(); +} + +int QTermWidget::getForegroundProcessId() +{ + return m_impl->m_session->foregroundProcessId(); +} + +void QTermWidget::changeDir(const QString & dir) +{ + /* + this is a very hackish way of trying to determine if the shell is in + the foreground before attempting to change the directory. It may not + be portable to anything other than Linux. + */ + QString strCmd; + strCmd.setNum(getShellPID()); + strCmd.prepend(QLatin1String("ps -j ")); + strCmd.append(QLatin1String(" | tail -1 | awk '{ print $5 }' | grep -q \\+")); + int retval = system(strCmd.toStdString().c_str()); + + if (!retval) { + QString cmd = QLatin1String("cd ") + dir + QLatin1Char('\n'); + sendText(cmd); + } +} + +QSize QTermWidget::sizeHint() const +{ + QSize size = m_impl->m_terminalDisplay->sizeHint(); + size.rheight() = 150; + return size; +} + +void QTermWidget::setTerminalSizeHint(bool enabled) +{ + m_impl->m_terminalDisplay->setTerminalSizeHint(enabled); +} + +bool QTermWidget::terminalSizeHint() +{ + return m_impl->m_terminalDisplay->terminalSizeHint(); +} + +void QTermWidget::startShellProgram() +{ + if ( m_impl->m_session->isRunning() ) { + return; + } + + m_impl->m_session->run(); +} + +void QTermWidget::startTerminalTeletype() +{ + if ( m_impl->m_session->isRunning() ) { + return; + } + + m_impl->m_session->runEmptyPTY(); + // redirect data from TTY to external recipient + connect( m_impl->m_session->emulation(), SIGNAL(sendData(const char *,int)), + this, SIGNAL(sendData(const char *,int)) ); +} + +void QTermWidget::init(int startnow) +{ + m_layout = new QVBoxLayout(); +#if QT_VERSION < 0x060000 + m_layout->setMargin(0); +#else + m_layout->setContentsMargins(0,0,0,0); +#endif + setLayout(m_layout); + + // translations + // First check $XDG_DATA_DIRS. This follows the implementation in libqtxdg + QString d = QFile::decodeName(qgetenv("XDG_DATA_DIRS")); + QStringList dirs = d.split(QLatin1Char(':'), Qt::SkipEmptyParts); + if (dirs.isEmpty()) { + dirs.append(QString::fromLatin1("/usr/local/share")); + dirs.append(QString::fromLatin1("/usr/share")); + } + dirs.append(QFile::decodeName(TRANSLATIONS_DIR)); + + m_translator = new QTranslator(this); + + for (const QString& dir : qAsConst(dirs)) { + //qDebug() << "Trying to load translation file from dir" << dir; + if (m_translator->load(QLocale::system(), QLatin1String("qtermwidget"), QLatin1String(QLatin1String("_")), dir)) { + qApp->installTranslator(m_translator); + //qDebug() << "Translations found in" << dir; + break; + } + } + + m_impl = new TermWidgetImpl(this); + m_layout->addWidget(m_impl->m_terminalDisplay); + + connect(m_impl->m_session, SIGNAL(bellRequest(QString)), m_impl->m_terminalDisplay, SLOT(bell(QString))); + connect(m_impl->m_terminalDisplay, SIGNAL(notifyBell(QString)), this, SIGNAL(bell(QString))); + + connect(m_impl->m_session, SIGNAL(activity()), this, SIGNAL(activity())); + connect(m_impl->m_session, SIGNAL(silence()), this, SIGNAL(silence())); + connect(m_impl->m_session, &Session::profileChangeCommandReceived, this, &QTermWidget::profileChanged); + connect(m_impl->m_session, &Session::receivedData, this, &QTermWidget::receivedData); + + // That's OK, FilterChain's dtor takes care of UrlFilter. + UrlFilter *urlFilter = new UrlFilter(); + connect(urlFilter, &UrlFilter::activated, this, &QTermWidget::urlActivated); + m_impl->m_terminalDisplay->filterChain()->addFilter(urlFilter); + + m_searchBar = new SearchBar(this); + m_searchBar->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Maximum); + connect(m_searchBar, SIGNAL(searchCriteriaChanged()), this, SLOT(find())); + connect(m_searchBar, SIGNAL(findNext()), this, SLOT(findNext())); + connect(m_searchBar, SIGNAL(findPrevious()), this, SLOT(findPrevious())); + m_layout->addWidget(m_searchBar); + m_searchBar->hide(); + + if (startnow && m_impl->m_session) { + m_impl->m_session->run(); + } + + this->setFocus( Qt::OtherFocusReason ); + this->setFocusPolicy( Qt::WheelFocus ); + m_impl->m_terminalDisplay->resize(this->size()); + + this->setFocusProxy(m_impl->m_terminalDisplay); + connect(m_impl->m_terminalDisplay, SIGNAL(copyAvailable(bool)), + this, SLOT(selectionChanged(bool))); + connect(m_impl->m_terminalDisplay, SIGNAL(termGetFocus()), + this, SIGNAL(termGetFocus())); + connect(m_impl->m_terminalDisplay, SIGNAL(termLostFocus()), + this, SIGNAL(termLostFocus())); + connect(m_impl->m_terminalDisplay, &TerminalDisplay::keyPressedSignal, this, + [this] (QKeyEvent* e, bool) { Q_EMIT termKeyPressed(e); }); +// m_impl->m_terminalDisplay->setSize(80, 40); + + QFont font = QApplication::font(); + font.setFamily(QLatin1String(DEFAULT_FONT_FAMILY)); + font.setPointSize(10); + font.setStyleHint(QFont::TypeWriter); + setTerminalFont(font); + m_searchBar->setFont(font); + + setScrollBarPosition(NoScrollBar); + setKeyboardCursorShape(Emulation::KeyboardCursorShape::BlockCursor); + + m_impl->m_session->addView(m_impl->m_terminalDisplay); + + connect(m_impl->m_session, SIGNAL(resizeRequest(QSize)), this, SLOT(setSize(QSize))); + connect(m_impl->m_session, SIGNAL(finished()), this, SLOT(sessionFinished())); + connect(m_impl->m_session, &Session::titleChanged, this, &QTermWidget::titleChanged); + connect(m_impl->m_session, &Session::cursorChanged, this, &QTermWidget::cursorChanged); +} + + +QTermWidget::~QTermWidget() +{ + delete m_impl; + emit destroyed(); +} + + +void QTermWidget::setTerminalFont(const QFont &font) +{ + m_impl->m_terminalDisplay->setVTFont(font); +} + +QFont QTermWidget::getTerminalFont() +{ + return m_impl->m_terminalDisplay->getVTFont(); +} + +void QTermWidget::setTerminalOpacity(qreal level) +{ + m_impl->m_terminalDisplay->setOpacity(level); +} + +void QTermWidget::setTerminalBackgroundImage(const QString& backgroundImage) +{ + m_impl->m_terminalDisplay->setBackgroundImage(backgroundImage); +} + +void QTermWidget::setTerminalBackgroundMode(int mode) +{ + m_impl->m_terminalDisplay->setBackgroundMode((Konsole::BackgroundMode)mode); +} + +void QTermWidget::setShellProgram(const QString &program) +{ + if (!m_impl->m_session) + return; + m_impl->m_session->setProgram(program); +} + +void QTermWidget::setWorkingDirectory(const QString& dir) +{ + if (!m_impl->m_session) + return; + m_impl->m_session->setInitialWorkingDirectory(dir); +} + +QString QTermWidget::workingDirectory() +{ + if (!m_impl->m_session) + return QString(); + +#ifdef Q_OS_LINUX + // Christian Surlykke: On linux we could look at /proc//cwd which should be a link to current + // working directory (: process id of the shell). I don't know about BSD. + // Maybe we could just offer it when running linux, for a start. + QDir d(QString::fromLatin1("/proc/%1/cwd").arg(getShellPID())); + if (!d.exists()) + { + qDebug() << "Cannot find" << d.dirName(); + goto fallback; + } + return d.canonicalPath(); +#endif + +fallback: + // fallback, initial WD + return m_impl->m_session->initialWorkingDirectory(); +} + +void QTermWidget::setArgs(const 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(const QString& origName) +{ + const ColorScheme *cs = nullptr; + + const bool isFile = QFile::exists(origName); + const QString& name = isFile ? + QFileInfo(origName).baseName() : + origName; + + // avoid legacy (int) solution + if (!availableColorSchemes().contains(name)) + { + if (isFile) + { + if (ColorSchemeManager::instance()->loadCustomColorScheme(origName)) + cs = ColorSchemeManager::instance()->findColorScheme(name); + else + qWarning () << Q_FUNC_INFO + << "cannot load color scheme from" + << origName; + } + + if (!cs) + cs = ColorSchemeManager::instance()->defaultColorScheme(); + } + else + cs = ColorSchemeManager::instance()->findColorScheme(name); + + if (! cs) + { + QMessageBox::information(this, + tr("Color Scheme Error"), + tr("Cannot load color scheme: %1").arg(name)); + return; + } + ColorEntry table[TABLE_COLORS]; + cs->getColorTable(table); + m_impl->m_terminalDisplay->setColorTable(table); + m_impl->m_session->setDarkBackground(cs->hasDarkBackground()); +} + +QStringList QTermWidget::getAvailableColorSchemes() +{ + return QTermWidget::availableColorSchemes(); +} + +QStringList QTermWidget::availableColorSchemes() +{ + QStringList ret; + const auto allColorSchemes = ColorSchemeManager::instance()->allColorSchemes(); + for (const ColorScheme* cs : allColorSchemes) + ret.append(cs->name()); + return ret; +} + +void QTermWidget::addCustomColorSchemeDir(const QString& custom_dir) +{ + ColorSchemeManager::instance()->addCustomColorSchemeDir(custom_dir); +} + +void QTermWidget::setBackgroundColor(const QColor &color) +{ + m_impl->m_terminalDisplay->setBackgroundColor(color); +} + +void QTermWidget::setForegroundColor(const QColor &color) +{ + m_impl->m_terminalDisplay->setForegroundColor(color); +} + +void QTermWidget::setANSIColor(const int ansiColorId, const QColor &color) +{ + m_impl->m_terminalDisplay->setColorTableColor(ansiColorId, color); +} + +void QTermWidget::setSize(const QSize &size) +{ + m_impl->m_terminalDisplay->setSize(size.width(), size.height()); +} + +void QTermWidget::setHistorySize(int lines) +{ + if (lines < 0) + m_impl->m_session->setHistoryType(HistoryTypeFile()); + else if (lines == 0) + m_impl->m_session->setHistoryType(HistoryTypeNone()); + else + m_impl->m_session->setHistoryType(HistoryTypeBuffer(lines)); +} + +int QTermWidget::historySize() const +{ + const HistoryType& currentHistory = m_impl->m_session->historyType(); + + if (currentHistory.isEnabled()) { + if (currentHistory.isUnlimited()) { + return -1; + } else { + return currentHistory.maximumLineCount(); + } + } else { + return 0; + } +} + +void QTermWidget::setScrollBarPosition(ScrollBarPosition pos) +{ + m_impl->m_terminalDisplay->setScrollBarPosition(pos); +} + +void QTermWidget::scrollToEnd() +{ + m_impl->m_terminalDisplay->scrollToEnd(); +} + +void QTermWidget::sendText(const QString &text) +{ + m_impl->m_session->sendText(text); +} + +void QTermWidget::sendKeyEvent(QKeyEvent *e) +{ + m_impl->m_session->sendKeyEvent(e); +} + +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(); +} + +void QTermWidget::bracketText(QString& text) +{ + m_impl->m_terminalDisplay->bracketText(text); +} + +void QTermWidget::disableBracketedPasteMode(bool disable) +{ + m_impl->m_terminalDisplay->disableBracketedPasteMode(disable); +} + +bool QTermWidget::bracketedPasteModeIsDisabled() const +{ + return m_impl->m_terminalDisplay->bracketedPasteModeIsDisabled(); +} + +void QTermWidget::copyClipboard() +{ + m_impl->m_terminalDisplay->copyClipboard(); +} + +void QTermWidget::pasteClipboard() +{ + m_impl->m_terminalDisplay->pasteClipboard(); +} + +void QTermWidget::pasteSelection() +{ + m_impl->m_terminalDisplay->pasteSelection(); +} + +void QTermWidget::setZoom(int step) +{ + QFont font = m_impl->m_terminalDisplay->getVTFont(); + + font.setPointSize(font.pointSize() + step); + setTerminalFont(font); +} + +void QTermWidget::zoomIn() +{ + setZoom(STEP_ZOOM); +} + +void QTermWidget::zoomOut() +{ + setZoom(-STEP_ZOOM); +} + +void QTermWidget::setKeyBindings(const QString & kb) +{ + m_impl->m_session->setKeyBindings(kb); +} + +void QTermWidget::clear() +{ + m_impl->m_session->emulation()->reset(); + m_impl->m_session->refresh(); + m_impl->m_session->clearHistory(); +} + +void QTermWidget::setFlowControlEnabled(bool enabled) +{ + m_impl->m_session->setFlowControlEnabled(enabled); +} + +QStringList QTermWidget::availableKeyBindings() +{ + return KeyboardTranslatorManager::instance()->allTranslators(); +} + +QString QTermWidget::keyBindings() +{ + return m_impl->m_session->keyBindings(); +} + +void QTermWidget::toggleShowSearchBar() +{ + m_searchBar->isHidden() ? m_searchBar->show() : m_searchBar->hide(); +} + +bool QTermWidget::flowControlEnabled(void) +{ + return m_impl->m_session->flowControlEnabled(); +} + +void QTermWidget::setFlowControlWarningEnabled(bool enabled) +{ + if (flowControlEnabled()) { + // Do not show warning label if flow control is disabled + m_impl->m_terminalDisplay->setFlowControlWarningEnabled(enabled); + } +} + +void QTermWidget::setEnvironment(const QStringList& environment) +{ + m_impl->m_session->setEnvironment(environment); +} + +void QTermWidget::setMotionAfterPasting(int action) +{ + m_impl->m_terminalDisplay->setMotionAfterPasting((Konsole::MotionAfterPasting) action); +} + +int QTermWidget::historyLinesCount() +{ + return m_impl->m_terminalDisplay->screenWindow()->screen()->getHistLines(); +} + +int QTermWidget::screenColumnsCount() +{ + return m_impl->m_terminalDisplay->screenWindow()->screen()->getColumns(); +} + +int QTermWidget::screenLinesCount() +{ + return m_impl->m_terminalDisplay->screenWindow()->screen()->getLines(); +} + +void QTermWidget::setSelectionStart(int row, int column) +{ + m_impl->m_terminalDisplay->screenWindow()->screen()->setSelectionStart(column, row, true); +} + +void QTermWidget::setSelectionEnd(int row, int column) +{ + m_impl->m_terminalDisplay->screenWindow()->screen()->setSelectionEnd(column, row); +} + +void QTermWidget::getSelectionStart(int& row, int& column) +{ + m_impl->m_terminalDisplay->screenWindow()->screen()->getSelectionStart(column, row); +} + +void QTermWidget::getSelectionEnd(int& row, int& column) +{ + m_impl->m_terminalDisplay->screenWindow()->screen()->getSelectionEnd(column, row); +} + +QString QTermWidget::selectedText(bool preserveLineBreaks) +{ + return m_impl->m_terminalDisplay->screenWindow()->screen()->selectedText(preserveLineBreaks); +} + +void QTermWidget::setMonitorActivity(bool enabled) +{ + m_impl->m_session->setMonitorActivity(enabled); +} + +void QTermWidget::setMonitorSilence(bool enabled) +{ + m_impl->m_session->setMonitorSilence(enabled); +} + +void QTermWidget::setSilenceTimeout(int seconds) +{ + m_impl->m_session->setMonitorSilenceSeconds(seconds); +} + +Filter::HotSpot* QTermWidget::getHotSpotAt(const QPoint &pos) const +{ + int row = 0, column = 0; + m_impl->m_terminalDisplay->getCharacterPosition(pos, row, column); + return getHotSpotAt(row, column); +} + +Filter::HotSpot* QTermWidget::getHotSpotAt(int row, int column) const +{ + return m_impl->m_terminalDisplay->filterChain()->hotSpotAt(row, column); +} + +QList QTermWidget::filterActions(const QPoint& position) +{ + return m_impl->m_terminalDisplay->filterActions(position); +} + +int QTermWidget::getPtySlaveFd() const +{ + return m_impl->m_session->getPtySlaveFd(); +} + +void QTermWidget::setKeyboardCursorShape(KeyboardCursorShape shape) +{ + m_impl->m_terminalDisplay->setKeyboardCursorShape(shape); +} + +void QTermWidget::setBlinkingCursor(bool blink) +{ + m_impl->m_terminalDisplay->setBlinkingCursor(blink); +} + +void QTermWidget::setBidiEnabled(bool enabled) +{ + m_impl->m_terminalDisplay->setBidiEnabled(enabled); +} + +bool QTermWidget::isBidiEnabled() +{ + return m_impl->m_terminalDisplay->isBidiEnabled(); +} + +QString QTermWidget::title() const +{ + QString title = m_impl->m_session->userTitle(); + if (title.isEmpty()) + title = m_impl->m_session->title(Konsole::Session::NameRole); + return title; +} + +QString QTermWidget::icon() const +{ + QString icon = m_impl->m_session->iconText(); + if (icon.isEmpty()) + icon = m_impl->m_session->iconName(); + return icon; +} + +bool QTermWidget::isTitleChanged() const +{ + return m_impl->m_session->isTitleChanged(); +} + +void QTermWidget::setAutoClose(bool enabled) +{ + m_impl->m_session->setAutoClose(enabled); +} + +void QTermWidget::cursorChanged(Konsole::Emulation::KeyboardCursorShape cursorShape, bool blinkingCursorEnabled) +{ + // TODO: A switch to enable/disable DECSCUSR? + setKeyboardCursorShape(cursorShape); + setBlinkingCursor(blinkingCursorEnabled); +} + +void QTermWidget::setMargin(int margin) +{ + m_impl->m_terminalDisplay->setMargin(margin); +} + +int QTermWidget::getMargin() const +{ + return m_impl->m_terminalDisplay->margin(); +} + +void QTermWidget::saveHistory(QIODevice *device) +{ + QTextStream stream(device); + PlainTextDecoder decoder; + decoder.begin(&stream); + m_impl->m_session->emulation()->writeToStream(&decoder, 0, m_impl->m_session->emulation()->lineCount()); +} + +void QTermWidget::setDrawLineChars(bool drawLineChars) +{ + m_impl->m_terminalDisplay->setDrawLineChars(drawLineChars); +} + +void QTermWidget::setBoldIntense(bool boldIntense) +{ + m_impl->m_terminalDisplay->setBoldIntense(boldIntense); +} + +void QTermWidget::setConfirmMultilinePaste(bool confirmMultilinePaste) { + m_impl->m_terminalDisplay->setConfirmMultilinePaste(confirmMultilinePaste); +} + +void QTermWidget::setTrimPastedTrailingNewlines(bool trimPastedTrailingNewlines) { + m_impl->m_terminalDisplay->setTrimPastedTrailingNewlines(trimPastedTrailingNewlines); +} + +QTermWidgetInterface* QTermWidget::createWidget(int startnow) const +{ + return new QTermWidget(startnow); +} diff --git a/qtermwidget/lib/qtermwidget.h b/qtermwidget/lib/qtermwidget.h new file mode 100644 index 0000000..12d8bf1 --- /dev/null +++ b/qtermwidget/lib/qtermwidget.h @@ -0,0 +1,365 @@ +/* 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. +*/ + + +#ifndef _Q_TERM_WIDGET +#define _Q_TERM_WIDGET + +#include +#include +#include "Emulation.h" +#include "Filter.h" +#include "qtermwidget_export.h" +#include "qtermwidget_version.h" +#include "qtermwidget_interface.h" + +class QVBoxLayout; +class TermWidgetImpl; +class SearchBar; +class QUrl; + +class QTERMWIDGET_EXPORT QTermWidget : public QWidget, public QTermWidgetInterface { + Q_OBJECT + Q_PLUGIN_METADATA(IID "lxqt.qtermwidget" FILE "qtermwidget.json") + Q_INTERFACES(QTermWidgetInterface) + +public: + + using KeyboardCursorShape = Konsole::Emulation::KeyboardCursorShape; + + //Creation of widget + QTermWidget(int startnow, // 1 = start shell program immediately + QWidget * parent = nullptr); + // A dummy constructor for Qt Designer. startnow is 1 by default + QTermWidget(QWidget *parent = nullptr); + + ~QTermWidget() override; + + //Initial size + QSize sizeHint() const override; + + // expose TerminalDisplay::TerminalSizeHint, setTerminalSizeHint + void setTerminalSizeHint(bool enabled) override; + bool terminalSizeHint() override; + + //start shell program if it was not started in constructor + void startShellProgram() override; + + /** + * Start terminal teletype as is + * and redirect data for external recipient. + * It can be used for display and control a remote terminal. + */ + void startTerminalTeletype() override; + + int getShellPID() override; + + /** + * Get the PID of the foreground process + */ + int getForegroundProcessId() override; + + void changeDir(const QString & dir) override; + + //look-n-feel, if you don`t like defaults + + // Terminal font + // Default is application font with family Monospace, size 10 + // Beware of a performance penalty and display/alignment issues when using a proportional font. + void setTerminalFont(const QFont & font) override; + QFont getTerminalFont() override; + void setTerminalOpacity(qreal level) override; + void setTerminalBackgroundImage(const QString& backgroundImage) override; + void setTerminalBackgroundMode(int mode) override; + + //environment + void setEnvironment(const QStringList & environment) override; + + // Shell program, default is /bin/bash + void setShellProgram(const QString & program) override; + + //working directory + void setWorkingDirectory(const QString & dir) override; + QString workingDirectory() override; + + // Shell program args, default is none + void setArgs(const QStringList & args) override; + + //Text codec, default is UTF-8 + void setTextCodec(QTextCodec * codec) override; + + /** @brief Sets the color scheme, default is white on black + * + * @param[in] name The name of the color scheme, either returned from + * availableColorSchemes() or a full path to a color scheme. + */ + void setColorScheme(const QString & name) override; + + /** + * @brief Retrieves the available color schemes in the OS for the terminal. + * + * @note This function is needed in addition to the static one for making it availble when accessing QTermWidget as a plugin. + * + * @return A list of color schemes. + */ + QStringList getAvailableColorSchemes() override; + static QStringList availableColorSchemes(); + static void addCustomColorSchemeDir(const QString& custom_dir); + + void setBackgroundColor(const QColor &color); + void setForegroundColor(const QColor &color); + void setANSIColor(const int ansiColorId, const QColor &color); + + + /** Sets the history size (in lines) + * + * @param lines history size + * lines = 0, no history + * lies < 0, infinite history + */ + void setHistorySize(int lines) override; + + // Returns the history size (in lines) + int historySize() const override; + + // Presence of scrollbar + void setScrollBarPosition(QTermWidgetInterface::ScrollBarPosition) override; + + // Wrapped, scroll to end. + void scrollToEnd() override; + + // Send some text to terminal + void sendText(const QString & text) override; + + // Send key event to terminal + void sendKeyEvent(QKeyEvent* e) override; + + // Sets whether flow control is enabled + void setFlowControlEnabled(bool enabled) override; + + // Returns whether flow control is enabled + bool flowControlEnabled(void) override; + + /** + * Sets whether the flow control warning box should be shown + * when the flow control stop key (Ctrl+S) is pressed. + */ + void setFlowControlWarningEnabled(bool enabled) override; + + /*! Get all available keyboard bindings + */ + static QStringList availableKeyBindings(); + + //! Return current key bindings + QString keyBindings() override; + + void setMotionAfterPasting(int) override; + + /** Return the number of lines in the history buffer. */ + int historyLinesCount() override; + + int screenColumnsCount() override; + int screenLinesCount() override; + + void setSelectionStart(int row, int column) override; + void setSelectionEnd(int row, int column) override; + void getSelectionStart(int& row, int& column) override; + void getSelectionEnd(int& row, int& column) override; + + /** + * Returns the currently selected text. + * @param preserveLineBreaks Specifies whether new line characters should + * be inserted into the returned text at the end of each terminal line. + */ + QString selectedText(bool preserveLineBreaks = true) override; + + void setMonitorActivity(bool) override; + void setMonitorSilence(bool) override; + void setSilenceTimeout(int seconds) override; + + /** Returns the available hotspot for the given point \em pos. + * + * This method may return a nullptr if no hotspot is available. + * + * @param[in] pos The point of interest in the QTermWidget coordinates. + * @return Hotspot for the given position, or nullptr if no hotspot. + */ + Filter::HotSpot* getHotSpotAt(const QPoint& pos) const; + + /** Returns the available hotspots for the given row and column. + * + * @return Hotspot for the given position, or nullptr if no hotspot. + */ + Filter::HotSpot* getHotSpotAt(int row, int column) const; + + /* + * Proxy for TerminalDisplay::filterActions + * */ + QList filterActions(const QPoint& position) override; + + /** + * Returns a pty slave file descriptor. + * This can be used for display and control + * a remote terminal. + */ + int getPtySlaveFd() const override; + + /** + * Sets the shape of the keyboard cursor. This is the cursor drawn + * at the position in the terminal where keyboard input will appear. + */ + void setKeyboardCursorShape(KeyboardCursorShape shape); + + void setBlinkingCursor(bool blink) override; + + /** Enables or disables bidi text in the terminal. */ + void setBidiEnabled(bool enabled) override; + bool isBidiEnabled() override; + + /** + * Automatically close the terminal session after the shell process exits or + * keep it running. + */ + void setAutoClose(bool) override; + + QString title() const override; + QString icon() const override; + + /** True if the title() or icon() was (ever) changed by the session. */ + bool isTitleChanged() const override; + + /** change and wrap text corresponding to paste mode **/ + void bracketText(QString& text) override; + + /** forcefully disable bracketed paste mode **/ + void disableBracketedPasteMode(bool disable) override; + bool bracketedPasteModeIsDisabled() const override; + + /** Set the empty space outside the terminal */ + void setMargin(int) override; + + /** Get the empty space outside the terminal */ + int getMargin() const override; + + void setDrawLineChars(bool drawLineChars) override; + + void setBoldIntense(bool boldIntense) override; + + void setConfirmMultilinePaste(bool confirmMultilinePaste) override; + void setTrimPastedTrailingNewlines(bool trimPastedTrailingNewlines) override; + + QTermWidgetInterface *createWidget(int startnow) const override; +signals: + void finished(); + void copyAvailable(bool); + + void termGetFocus(); + void termLostFocus(); + + void termKeyPressed(QKeyEvent *); + + void urlActivated(const QUrl&, bool fromContextMenu); + + void bell(const QString& message); + + void activity(); + void silence(); + + /** + * Emitted when emulator send data to the terminal process + * (redirected for external recipient). It can be used for + * control and display the remote terminal. + */ + void sendData(const char *,int); + + void profileChanged(const QString & profile); + + void titleChanged(); + + /** + * Signals that we received new data from the process running in the + * terminal emulator + */ + void receivedData(const QString &text); + +public slots: + // Copy selection to clipboard + void copyClipboard(); + + // Paste clipboard to terminal + void pasteClipboard(); + + // Paste selection to terminal + void pasteSelection(); + + // Set zoom + void zoomIn(); + void zoomOut(); + + // Set size + void setSize(const QSize &); + + /*! Set named key binding for given widget + */ + void setKeyBindings(const QString & kb); + + /*! Clear the terminal content and move to home position + */ + void clear(); + + void toggleShowSearchBar(); + + void saveHistory(QIODevice *device); +protected: + void resizeEvent(QResizeEvent *) override; + +protected slots: + void sessionFinished(); + void selectionChanged(bool textSelected); + +private slots: + void find(); + void findNext(); + void findPrevious(); + void matchFound(int startColumn, int startLine, int endColumn, int endLine); + void noMatchFound(); + /** + * Emulation::cursorChanged() signal propagates to here and QTermWidget + * sends the specified cursor states to the terminal display + */ + void cursorChanged(Konsole::Emulation::KeyboardCursorShape cursorShape, bool blinkingCursorEnabled); + +private: + void search(bool forwards, bool next); + void setZoom(int step); + void init(int startnow); + TermWidgetImpl * m_impl; + SearchBar* m_searchBar; + QVBoxLayout *m_layout; + QTranslator *m_translator; +}; + + +//Maybe useful, maybe not + +#ifdef __cplusplus +extern "C" +#endif +void * createTermWidget(int startnow, void * parent); + +#endif diff --git a/qtermwidget/lib/qtermwidget.json b/qtermwidget/lib/qtermwidget.json new file mode 100644 index 0000000..3e9454b --- /dev/null +++ b/qtermwidget/lib/qtermwidget.json @@ -0,0 +1,8 @@ +{ + "Name" : "QTermWidget", + "Version" : "1.3.0", + "Vendor" : "LXQt", + "Copyright" : "(C) 2022 LXQt", + "Url" : "https://github.com/lxqt/qtermwidget", + "License" : "GPLv2" +} diff --git a/qtermwidget/lib/qtermwidget_interface.h b/qtermwidget/lib/qtermwidget_interface.h new file mode 100644 index 0000000..2b9f19b --- /dev/null +++ b/qtermwidget/lib/qtermwidget_interface.h @@ -0,0 +1,107 @@ +/* Copyright (C) 2022 Francesc Martinez (info@francescmm.com) + + 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. +*/ + +#pragma once + +#include + +class QKeyEvent; +class QAction; + +class QTermWidgetInterface { + public: + /** + * This enum describes the location where the scroll bar is positioned in the display widget. + */ + enum ScrollBarPosition { + /** Do not show the scroll bar. */ + NoScrollBar = 0, + /** Show the scroll bar on the left side of the display. */ + ScrollBarLeft = 1, + /** Show the scroll bar on the right side of the display. */ + ScrollBarRight = 2 + }; + + virtual ~QTermWidgetInterface() = default; + + virtual void setTerminalSizeHint(bool enabled) = 0; + virtual bool terminalSizeHint() = 0; + virtual void startShellProgram() = 0; + virtual void startTerminalTeletype() = 0; + virtual int getShellPID() = 0; + virtual int getForegroundProcessId() = 0; + virtual void changeDir(const QString & dir) = 0; + virtual void setTerminalFont(const QFont & font) = 0; + virtual QFont getTerminalFont() = 0; + virtual void setTerminalOpacity(qreal level) = 0; + virtual void setTerminalBackgroundImage(const QString& backgroundImage) = 0; + virtual void setTerminalBackgroundMode(int mode) = 0; + virtual void setEnvironment(const QStringList & environment) = 0; + virtual void setShellProgram(const QString & program) = 0; + virtual void setWorkingDirectory(const QString & dir) = 0; + virtual QString workingDirectory() = 0; + virtual void setArgs(const QStringList & args) = 0; + virtual void setTextCodec(QTextCodec * codec) = 0; + virtual void setColorScheme(const QString & name) = 0; + virtual QStringList getAvailableColorSchemes() = 0; + virtual void setHistorySize(int lines) = 0; + virtual int historySize() const = 0; + virtual void setScrollBarPosition(ScrollBarPosition) = 0; + virtual void scrollToEnd() = 0; + virtual void sendText(const QString & text) = 0; + virtual void sendKeyEvent(QKeyEvent* e) = 0; + virtual void setFlowControlEnabled(bool enabled) = 0; + virtual bool flowControlEnabled(void) = 0; + virtual void setFlowControlWarningEnabled(bool enabled) = 0; + virtual QString keyBindings() = 0; + virtual void setMotionAfterPasting(int) = 0; + virtual int historyLinesCount() = 0; + virtual int screenColumnsCount() = 0; + virtual int screenLinesCount() = 0; + virtual void setSelectionStart(int row, int column) = 0; + virtual void setSelectionEnd(int row, int column) = 0; + virtual void getSelectionStart(int& row, int& column) = 0; + virtual void getSelectionEnd(int& row, int& column) = 0; + virtual QString selectedText(bool preserveLineBreaks = true) = 0; + virtual void setMonitorActivity(bool) = 0; + virtual void setMonitorSilence(bool) = 0; + virtual void setSilenceTimeout(int seconds) = 0; + virtual QList filterActions(const QPoint& position) = 0; + virtual int getPtySlaveFd() const = 0; + virtual void setBlinkingCursor(bool blink) = 0; + virtual void setBidiEnabled(bool enabled) = 0; + virtual bool isBidiEnabled() = 0; + virtual void setAutoClose(bool) = 0; + virtual QString title() const = 0; + virtual QString icon() const = 0; + virtual bool isTitleChanged() const = 0; + virtual void bracketText(QString& text) = 0; + virtual void disableBracketedPasteMode(bool disable) = 0; + virtual bool bracketedPasteModeIsDisabled() const = 0; + virtual void setMargin(int) = 0; + virtual int getMargin() const = 0; + virtual void setDrawLineChars(bool drawLineChars) = 0; + virtual void setBoldIntense(bool boldIntense) = 0; + virtual void setConfirmMultilinePaste(bool confirmMultilinePaste) = 0; + virtual void setTrimPastedTrailingNewlines(bool trimPastedTrailingNewlines) = 0; + virtual QTermWidgetInterface* createWidget(int startnow) const = 0; +}; + +#define QTermWidgetInterface_iid "lxqt.qtermwidget.QTermWidgetInterface/1.0" + +Q_DECLARE_INTERFACE(QTermWidgetInterface, QTermWidgetInterface_iid) diff --git a/qtermwidget/lib/qtermwidget_version.h.in b/qtermwidget/lib/qtermwidget_version.h.in new file mode 100644 index 0000000..00e2a74 --- /dev/null +++ b/qtermwidget/lib/qtermwidget_version.h.in @@ -0,0 +1,33 @@ +/* Copyright (C) 2020 Axel Kittenberger (axel.kittenberger@univie.ac.at) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + + +#ifndef _Q_TERM_WIDGET_VERSION +#define _Q_TERM_WIDGET_VERSION + +#include +#define QTERMWIDGET_VERSION_MAJOR @QTERMWIDGET_VERSION_MAJOR@ +#define QTERMWIDGET_VERSION_MINOR @QTERMWIDGET_VERSION_MINOR@ +#define QTERMWIDGET_VERSION_PATCH @QTERMWIDGET_VERSION_PATCH@ +#define QTERMWIDGET_VERSION QT_VERSION_CHECK(\ + QTERMWIDGET_VERSION_MAJOR,\ + QTERMWIDGET_VERSION_MINOR,\ + QTERMWIDGET_VERSION_PATCH) + +#endif + diff --git a/qtermwidget/lib/tools.cpp b/qtermwidget/lib/tools.cpp new file mode 100644 index 0000000..4291fae --- /dev/null +++ b/qtermwidget/lib/tools.cpp @@ -0,0 +1,106 @@ +#include "tools.h" + +#include +#include +#include + + +Q_LOGGING_CATEGORY(qtermwidgetLogger, "qtermwidget", QtWarningMsg) + +/*! Helper function to get possible location of layout files. +By default the KB_LAYOUT_DIR is used (linux/BSD/macports). +But in some cases (apple bundle) there can be more locations). +*/ +QString get_kb_layout_dir() +{ +// qDebug() << __FILE__ << __FUNCTION__; + + QString rval = QString(); + QString k(QLatin1String(KB_LAYOUT_DIR)); + QDir d(k); + + //qDebug() << "default KB_LAYOUT_DIR: " << k; + + if (d.exists()) + { + rval = k.append(QLatin1Char('/')); + return rval; + } + +#ifdef Q_OS_MAC + // subdir in the app location + d.setPath(QCoreApplication::applicationDirPath() + QLatin1String("/kb-layouts/")); + //qDebug() << d.path(); + if (d.exists()) + return QCoreApplication::applicationDirPath() + QLatin1String("/kb-layouts/"); + + d.setPath(QCoreApplication::applicationDirPath() + QLatin1String("/../Resources/kb-layouts/")); + if (d.exists()) + return QCoreApplication::applicationDirPath() + QLatin1String("/../Resources/kb-layouts/"); +#endif + //qDebug() << "Cannot find KB_LAYOUT_DIR. Default:" << k; + return QString(); +} + +/*! Helper function to add custom location of color schemes. +*/ +namespace { + QStringList custom_color_schemes_dirs; +} +void add_custom_color_scheme_dir(const QString& custom_dir) +{ + if (!custom_color_schemes_dirs.contains(custom_dir)) + custom_color_schemes_dirs << custom_dir; +} + +/*! Helper function to get possible locations of color schemes. +By default the COLORSCHEMES_DIR is used (linux/BSD/macports). +But in some cases (apple bundle) there can be more locations). +*/ +const QStringList get_color_schemes_dirs() +{ +// qDebug() << __FILE__ << __FUNCTION__; + + QStringList rval; + QString k(QLatin1String(COLORSCHEMES_DIR)); + QDir d(k); + +// qDebug() << "default COLORSCHEMES_DIR: " << k; + + if (d.exists()) + rval << k.append(QLatin1Char('/')); + +#ifdef Q_OS_MAC + // subdir in the app location + d.setPath(QCoreApplication::applicationDirPath() + QLatin1String("/color-schemes/")); + //qDebug() << d.path(); + if (d.exists()) + { + if (!rval.isEmpty()) + rval.clear(); + rval << (QCoreApplication::applicationDirPath() + QLatin1String("/color-schemes/")); + } + d.setPath(QCoreApplication::applicationDirPath() + QLatin1String("/../Resources/color-schemes/")); + if (d.exists()) + { + if (!rval.isEmpty()) + rval.clear(); + rval << (QCoreApplication::applicationDirPath() + QLatin1String("/../Resources/color-schemes/")); + } +#endif + + for (const QString& custom_dir : qAsConst(custom_color_schemes_dirs)) + { + d.setPath(custom_dir); + if (d.exists()) + rval << custom_dir; + } +#ifdef QT_DEBUG + if(!rval.isEmpty()) { + qDebug() << "Using color-schemes: " << rval; + } else { + qDebug() << "Cannot find color-schemes in any location!"; + } +#endif + return rval; +} diff --git a/qtermwidget/lib/tools.h b/qtermwidget/lib/tools.h new file mode 100644 index 0000000..239689b --- /dev/null +++ b/qtermwidget/lib/tools.h @@ -0,0 +1,14 @@ +#ifndef TOOLS_H +#define TOOLS_H + +#include +#include +#include + +QString get_kb_layout_dir(); +void add_custom_color_scheme_dir(const QString& custom_dir); +const QStringList get_color_schemes_dirs(); + +Q_DECLARE_LOGGING_CATEGORY(qtermwidgetLogger) + +#endif diff --git a/qtermwidget/lib/translations/CMakeLists.txt b/qtermwidget/lib/translations/CMakeLists.txt new file mode 100644 index 0000000..84bb691 --- /dev/null +++ b/qtermwidget/lib/translations/CMakeLists.txt @@ -0,0 +1,3 @@ +project(qtermwidget) + +build_component("." "${CMAKE_INSTALL_FULL_DATADIR}/qtermwidget/translations") diff --git a/qtermwidget/lib/translations/qtermwidget.ts b/qtermwidget/lib/translations/qtermwidget.ts new file mode 100644 index 0000000..6794455 --- /dev/null +++ b/qtermwidget/lib/translations/qtermwidget.ts @@ -0,0 +1,166 @@ + + + + + Konsole::Session + + + Bell in session '%1' + + + + + Session '%1' exited with status %2. + + + + + Session '%1' crashed. + + + + + Session '%1' exited unexpectedly. + + + + + Konsole::TerminalDisplay + + + Size: XXX x XXX + + + + + Size: %1 x %2 + + + + + Paste multiline text + + + + + Are you sure you want to paste this text? + + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + + + + + Konsole::Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + + + + + QMessageBox + + + Show Details... + + + + + QObject + + + + Un-named Color Scheme + + + + + Accessible Color Scheme + + + + + Open Link + + + + + Copy Link Address + + + + + Send Email To... + + + + + Copy Email Address + + + + + QTermWidget + + + Color Scheme Error + + + + + Cannot load color scheme: %1 + + + + + SearchBar + + + Match case + + + + + Regular expression + + + + + Highlight all matches + + + + + SearchBar + + + + + X + + + + + Find: + + + + + < + + + + + > + + + + + ... + + + + diff --git a/qtermwidget/lib/translations/qtermwidget_ar.ts b/qtermwidget/lib/translations/qtermwidget_ar.ts new file mode 100644 index 0000000..805040a --- /dev/null +++ b/qtermwidget/lib/translations/qtermwidget_ar.ts @@ -0,0 +1,166 @@ + + + + + Konsole::Session + + + Bell in session '%1' + جرس في الجلسة '%1' + + + + Session '%1' exited with status %2. + تم إنهاء الجلسة '%1' بالحالة%2. + + + + Session '%1' crashed. + تعطلت الجلسة '%1'. + + + + Session '%1' exited unexpectedly. + تم إنهاء الجلسة '%1' بشكل غير متوقع. + + + + Konsole::TerminalDisplay + + + Size: XXX x XXX + الحجم: XXX x XXX + + + + Size: %1 x %2 + الحجم: %1 x%2 + + + + Paste multiline text + لصق نص متعدد الأسطر + + + + Are you sure you want to paste this text? + هل أنت متأكد أنك تريد لصق هذا النص؟ + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>تم <a href="http://en.wikipedia.org/wiki/Flow_control">تعليق</a> الإخراج بالضغط على Ctrl + S. اضغط على <b>Ctrl + Q</b> للاستئناف.</qt> + + + + Konsole::Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + لا يوجد مترجم لوحة مفاتيح متاح. المعلومات اللازمة لتحويل ضغطات المفاتيح إلى أحرف لإرسالها إلى الجهاز مفقودة. + + + + QMessageBox + + + Show Details... + اظهر التفاصيل... + + + + QObject + + + + Un-named Color Scheme + نظام ألوان غير مسمى + + + + Accessible Color Scheme + نظام الألوان الذي يمكن الوصول إليه + + + + Open Link + فتح رابط + + + + Copy Link Address + نسخ عنوان الرابط + + + + Send Email To... + إرسال بريد إلكتروني إلى ... + + + + Copy Email Address + نسخ عنوان البريد الإلكتروني + + + + QTermWidget + + + Color Scheme Error + خطأ في نظام الألوان + + + + Cannot load color scheme: %1 + لا يمكن تحميل نظام الألوان:%1 + + + + SearchBar + + + Match case + مطابقة الحالة + + + + Regular expression + عبارت منظم + + + + Highlight all matches + قم بتمييز جميع التطابقات + + + + SearchBar + شريط البحث + + + + X + X + + + + Find: + ابحث: + + + + < + < + + + + > + > + + + + ... + ... + + + diff --git a/qtermwidget/lib/translations/qtermwidget_arn.ts b/qtermwidget/lib/translations/qtermwidget_arn.ts new file mode 100644 index 0000000..1c67c6a --- /dev/null +++ b/qtermwidget/lib/translations/qtermwidget_arn.ts @@ -0,0 +1,166 @@ + + + + + Konsole::Session + + + Bell in session '%1' + + + + + Session '%1' exited with status %2. + + + + + Session '%1' crashed. + + + + + Session '%1' exited unexpectedly. + + + + + Konsole::TerminalDisplay + + + Size: XXX x XXX + + + + + Size: %1 x %2 + + + + + Paste multiline text + + + + + Are you sure you want to paste this text? + + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + + + + + Konsole::Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + + + + + QMessageBox + + + Show Details... + + + + + QObject + + + + Un-named Color Scheme + + + + + Accessible Color Scheme + + + + + Open Link + + + + + Copy Link Address + + + + + Send Email To... + + + + + Copy Email Address + + + + + QTermWidget + + + Color Scheme Error + + + + + Cannot load color scheme: %1 + + + + + SearchBar + + + Match case + + + + + Regular expression + + + + + Highlight all matches + + + + + SearchBar + + + + + X + + + + + Find: + + + + + < + + + + + > + + + + + ... + + + + diff --git a/qtermwidget/lib/translations/qtermwidget_ast.ts b/qtermwidget/lib/translations/qtermwidget_ast.ts new file mode 100644 index 0000000..979a064 --- /dev/null +++ b/qtermwidget/lib/translations/qtermwidget_ast.ts @@ -0,0 +1,166 @@ + + + + + Konsole::Session + + + Bell in session '%1' + + + + + Session '%1' exited with status %2. + + + + + Session '%1' crashed. + + + + + Session '%1' exited unexpectedly. + + + + + Konsole::TerminalDisplay + + + Size: XXX x XXX + + + + + Size: %1 x %2 + + + + + Paste multiline text + + + + + Are you sure you want to paste this text? + + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + + + + + Konsole::Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + + + + + QMessageBox + + + Show Details... + + + + + QObject + + + + Un-named Color Scheme + + + + + Accessible Color Scheme + + + + + Open Link + + + + + Copy Link Address + + + + + Send Email To... + + + + + Copy Email Address + + + + + QTermWidget + + + Color Scheme Error + + + + + Cannot load color scheme: %1 + + + + + SearchBar + + + Match case + + + + + Regular expression + + + + + Highlight all matches + + + + + SearchBar + + + + + X + + + + + Find: + + + + + < + + + + + > + + + + + ... + + + + diff --git a/qtermwidget/lib/translations/qtermwidget_bg.ts b/qtermwidget/lib/translations/qtermwidget_bg.ts new file mode 100644 index 0000000..6a9c668 --- /dev/null +++ b/qtermwidget/lib/translations/qtermwidget_bg.ts @@ -0,0 +1,166 @@ + + + + + Konsole::Session + + + Bell in session '%1' + Звънец в сесия '%1' + + + + Session '%1' exited with status %2. + Сесия '%1' завърши със статус %2. + + + + Session '%1' crashed. + Сесия '%1' се срина. + + + + Session '%1' exited unexpectedly. + Сесия '%1' завърши неочаквано. + + + + Konsole::TerminalDisplay + + + Size: XXX x XXX + Размер: XXX x XXX + + + + Size: %1 x %2 + Размер: %1 x %2 + + + + Paste multiline text + Поставяне на многоредов текст + + + + Are you sure you want to paste this text? + Сигурни ли сте, че искате да поставите този текст? + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>Предаването на данни <a href="http://en.wikipedia.org/wiki/Flow_control">прекъсна</a> при натискане на Ctrl+S. Натиснете <b>Ctrl+Q</b> за възстановяване.</qt> + + + + Konsole::Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + Няма наличен транслатор за клавиатура. Липсва информацията, необходима за преобразуване на клавишите в символи за изпращане до терминала. + + + + QMessageBox + + + Show Details... + Показване на детайли... + + + + QObject + + + + Un-named Color Scheme + Цветна схема без име + + + + Accessible Color Scheme + Достъпна цветна схема + + + + Open Link + Отваряне на Връзка + + + + Copy Link Address + Копиране адреса на връзката + + + + Send Email To... + Изпращане E-Mail на... + + + + Copy Email Address + Копиране E-Mail адреса + + + + QTermWidget + + + Color Scheme Error + Грешка в цветовата схема + + + + Cannot load color scheme: %1 + Цветна схема %1 не може да се зареди + + + + SearchBar + + + Match case + Зачитане на регистъра + + + + Regular expression + Регулярен израз + + + + Highlight all matches + Маркиране всички съвпадения + + + + SearchBar + Лента за търсене + + + + X + X + + + + Find: + Търсене: + + + + < + < + + + + > + > + + + + ... + ... + + + diff --git a/qtermwidget/lib/translations/qtermwidget_ca.ts b/qtermwidget/lib/translations/qtermwidget_ca.ts new file mode 100644 index 0000000..b08bd55 --- /dev/null +++ b/qtermwidget/lib/translations/qtermwidget_ca.ts @@ -0,0 +1,166 @@ + + + + + Konsole::Session + + + Bell in session '%1' + Error de senyal en sessió '%1' + + + + Session '%1' exited with status %2. + La sessió '%1' ha sortit amb l'estat %2. + + + + Session '%1' crashed. + Fallada a la sessió '%1'. + + + + Session '%1' exited unexpectedly. + La sessió '%1' s' ha tancat inesperadament. + + + + Konsole::TerminalDisplay + + + Size: XXX x XXX + Mida: XXX x XXX + + + + Size: %1 x %2 + Mida: %1 x %2 + + + + Paste multiline text + Enganxa text multilínia + + + + Are you sure you want to paste this text? + Segur que voleu enganxar aquest text? + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>La sortida ha estat <a href="http://en.wikipedia.org/wiki/Flow_control">suspesa</a> en prémer Ctrl+S. Premeu <b>Ctrl+Q</b> per reprendre-la.</qt> + + + + Konsole::Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + No hi ha disponible cap traductor de teclat. No es disposa de la informació necessària per convertir la pressió de les tecles a caràcters al terminal. + + + + QMessageBox + + + Show Details... + Mostra els detalls... + + + + QObject + + + + Un-named Color Scheme + Esquema de color sense nom + + + + Accessible Color Scheme + Esquema de color accessible + + + + Open Link + Obre l'enllaç + + + + Copy Link Address + Copia l'adreça de l'enllaç + + + + Send Email To... + Envia un correu electrònic a... + + + + Copy Email Address + Copia l'adreça de correu electrònic + + + + QTermWidget + + + Color Scheme Error + Error de l'esquema de color + + + + Cannot load color scheme: %1 + No es pot carregar l'esquema de color: %1 + + + + SearchBar + + + Match case + Coincidència + + + + Regular expression + Expressió regular + + + + Highlight all matches + Ressalta totes les coincidències + + + + SearchBar + Barra de cerca + + + + X + X + + + + Find: + Troba: + + + + < + < + + + + > + > + + + + ... + ... + + + diff --git a/qtermwidget/lib/translations/qtermwidget_cs.ts b/qtermwidget/lib/translations/qtermwidget_cs.ts new file mode 100644 index 0000000..21655b8 --- /dev/null +++ b/qtermwidget/lib/translations/qtermwidget_cs.ts @@ -0,0 +1,166 @@ + + + + + Konsole::Session + + + Bell in session '%1' + Zvonek v sezení „%1“ + + + + Session '%1' exited with status %2. + Sezení „%1“ ukončeno se stavem %2. + + + + Session '%1' crashed. + Sezení „%1“ zhavarovalo. + + + + Session '%1' exited unexpectedly. + Sezení „%1“ neočekávaně ukončeno. + + + + Konsole::TerminalDisplay + + + Size: XXX x XXX + Velikost: XXX x XXX + + + + Size: %1 x %2 + Velikost: %1 x %2 + + + + Paste multiline text + Vložit víceřádkový text + + + + Are you sure you want to paste this text? + Opravdu chcete tento text vložit? + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>Výstup byl <a href="http://en.wikipedia.org/wiki/Flow_control">pozastaven</a> stisknutím Ctrl+S. Znovu ho spustíte stisknutím <b>Ctrl+Q</b>.</qt> + + + + Konsole::Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + Není k dispozici žádný překladač klávesnice. Chybí tak informace pro převod kódů ze stisknutých kláves na znaky posílané na terminál. + + + + QMessageBox + + + Show Details... + Zobrazit podrobnosti… + + + + QObject + + + + Un-named Color Scheme + Nepojmenované schéma barev + + + + Accessible Color Scheme + Schéma barev pro uživatele se zrakovou vadou + + + + Open Link + Otevřít odkaz + + + + Copy Link Address + Zkopírovat adresu odkazu + + + + Send Email To... + Poslat e-mail na… + + + + Copy Email Address + Zkopírovat e-mailovou adresu + + + + QTermWidget + + + Color Scheme Error + Chyba schéma barev + + + + Cannot load color scheme: %1 + Nedaří se načíst schéma barev: %1 + + + + SearchBar + + + Match case + Rozlišovat malá/VELKÁ písmena + + + + Regular expression + Regulární výraz + + + + Highlight all matches + Zvýraznit všechny shody + + + + SearchBar + Lišta hledání + + + + X + + + + + Find: + Najít: + + + + < + + + + + > + + + + + ... + + + + diff --git a/qtermwidget/lib/translations/qtermwidget_cy.ts b/qtermwidget/lib/translations/qtermwidget_cy.ts new file mode 100644 index 0000000..4665213 --- /dev/null +++ b/qtermwidget/lib/translations/qtermwidget_cy.ts @@ -0,0 +1,166 @@ + + + + + Konsole::Session + + + Bell in session '%1' + + + + + Session '%1' exited with status %2. + + + + + Session '%1' crashed. + + + + + Session '%1' exited unexpectedly. + + + + + Konsole::TerminalDisplay + + + Size: XXX x XXX + + + + + Size: %1 x %2 + + + + + Paste multiline text + + + + + Are you sure you want to paste this text? + + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + + + + + Konsole::Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + + + + + QMessageBox + + + Show Details... + + + + + QObject + + + + Un-named Color Scheme + + + + + Accessible Color Scheme + + + + + Open Link + + + + + Copy Link Address + + + + + Send Email To... + + + + + Copy Email Address + + + + + QTermWidget + + + Color Scheme Error + + + + + Cannot load color scheme: %1 + + + + + SearchBar + + + Match case + + + + + Regular expression + + + + + Highlight all matches + + + + + SearchBar + + + + + X + + + + + Find: + + + + + < + + + + + > + + + + + ... + + + + diff --git a/qtermwidget/lib/translations/qtermwidget_da.ts b/qtermwidget/lib/translations/qtermwidget_da.ts new file mode 100644 index 0000000..0604e75 --- /dev/null +++ b/qtermwidget/lib/translations/qtermwidget_da.ts @@ -0,0 +1,166 @@ + + + + + Konsole::Session + + + Bell in session '%1' + Bell i session '%1' + + + + Session '%1' exited with status %2. + Session '%1' afsluttede med status %2. + + + + Session '%1' crashed. + Session '%1' holdt op med at virke. + + + + Session '%1' exited unexpectedly. + Session '%1' afsluttede uventet. + + + + Konsole::TerminalDisplay + + + Size: XXX x XXX + Størrelse: XXX x XXX + + + + Size: %1 x %2 + Størrelse: %1 x %2 + + + + Paste multiline text + Indsæt multilinjetekst + + + + Are you sure you want to paste this text? + Er du sikker på, at du vil indsætte teksten? + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>Output er blevet <a href="http://en.wikipedia.org/wiki/Flow_control">suspenderet</a> ved tryk på Ctrl+S. Tryk på <b>Ctrl+Q</b> for at genoptage.</qt> + + + + Konsole::Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + Ingen tastaturoversætter tilgængelig. Informationen, som er nødvendig for at konvertere tastetryk til tegn, som sendes til terminalen, mangler. + + + + QMessageBox + + + Show Details... + Vis detaljer ... + + + + QObject + + + + Un-named Color Scheme + Unavngivet farveskema + + + + Accessible Color Scheme + Tilgængeligt farveskema + + + + Open Link + Åbn link + + + + Copy Link Address + Kopiér linkadresse + + + + Send Email To... + Send e-mail til... + + + + Copy Email Address + Kopiér e-mailadresse + + + + QTermWidget + + + Color Scheme Error + Fejl ved farveskema + + + + Cannot load color scheme: %1 + Kan ikke indlæse farveskema: %1 + + + + SearchBar + + + Match case + Der skelnes mellem store og små bogstaver + + + + Regular expression + Regulært udtryk + + + + Highlight all matches + Fremhæv alle match + + + + SearchBar + SøgeLinje + + + + X + X + + + + Find: + Find: + + + + < + < + + + + > + > + + + + ... + ... + + + diff --git a/qtermwidget/lib/translations/qtermwidget_de.ts b/qtermwidget/lib/translations/qtermwidget_de.ts new file mode 100644 index 0000000..b19bb5b --- /dev/null +++ b/qtermwidget/lib/translations/qtermwidget_de.ts @@ -0,0 +1,166 @@ + + + + + Konsole::Session + + + Bell in session '%1' + Glocke in Sitzung '%1' + + + + Session '%1' exited with status %2. + SItzung '%1' wurde mit Status %2 beendet. + + + + Session '%1' crashed. + Sitzung '%1' ist abgestürzt. + + + + Session '%1' exited unexpectedly. + Sitzung '%1' wurde unerwartet beendet. + + + + Konsole::TerminalDisplay + + + Size: XXX x XXX + Größe: XXX x XXX + + + + Size: %1 x %2 + Größe: %1 x %2 + + + + Paste multiline text + mehrzeiligen Text einfügen + + + + Are you sure you want to paste this text? + Sie wollen diesen Text einfügen? + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>Druch drücken von Strg+S wurde die Ausgabe <a href="http://en.wikipedia.org/wiki/Flow_control">unterbrochen</a>. <b>Strg+Q</b> drücken um fortzufahren.</qt> + + + + Konsole::Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + Kein Tastaturinterpreter verfügbar. Die benötigte Information, um Tastenbefehle in Zeichen umzuwandeln und anschließend zum Terminal zu senden, fehlt. + + + + QMessageBox + + + Show Details... + Details... + + + + QObject + + + + Un-named Color Scheme + Unbenanntes Farbschema + + + + Accessible Color Scheme + Zugängliches Farbschema + + + + Open Link + Link öffnen + + + + Copy Link Address + Link-Adresse kopieren + + + + Send Email To... + E-Mail senden an... + + + + Copy Email Address + E-Mail-Adresse kopieren + + + + QTermWidget + + + Color Scheme Error + Fehler im Farbschema + + + + Cannot load color scheme: %1 + Kann Farbschema nicht laden: %1 + + + + SearchBar + + + Match case + Groß-/Kleinschreibung beachten + + + + Regular expression + Regulärer Ausdruck + + + + Highlight all matches + Alle Treffer hervorheben + + + + SearchBar + Suchleiste + + + + X + + + + + Find: + Finde: + + + + < + + + + + > + + + + + ... + + + + diff --git a/qtermwidget/lib/translations/qtermwidget_de_CH.ts b/qtermwidget/lib/translations/qtermwidget_de_CH.ts new file mode 100644 index 0000000..cf0f7a2 --- /dev/null +++ b/qtermwidget/lib/translations/qtermwidget_de_CH.ts @@ -0,0 +1,166 @@ + + + + + Konsole::Session + + + Bell in session '%1' + Glocke in Sitzung '%1' + + + + Session '%1' exited with status %2. + Sitzung '%1' wurde mit Status %2 beendet. + + + + Session '%1' crashed. + Sitzung '%1' ist abgestürzt. + + + + Session '%1' exited unexpectedly. + Sitzung '%1' wurde unerwartet beendet. + + + + Konsole::TerminalDisplay + + + Size: XXX x XXX + Grösse: XXX x XXX + + + + Size: %1 x %2 + Grösse: %1 x %2 + + + + Paste multiline text + mehrzeiligen Text einfügen + + + + Are you sure you want to paste this text? + Sie wollen diesen Text einfügen? + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>Druch drücken von Strg+S wurde die Ausgabe <a href="http://en.wikipedia.org/wiki/Flow_control">unterbrochen</a>. <b>Strg+Q</b> drücken um fortzufahren.</qt> + + + + Konsole::Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + Kein Tastaturinterpreter verfügbar. Die benötigte Information, um Tastenbefehle in Zeichen umzuwandeln und anschliessend zum Terminal zu senden, fehlt. + + + + QMessageBox + + + Show Details... + Details... + + + + QObject + + + + Un-named Color Scheme + Unbenanntes Farbschema + + + + Accessible Color Scheme + Zugängliches Farbschema + + + + Open Link + Link öffnen + + + + Copy Link Address + Link-Adresse kopieren + + + + Send Email To... + E-Mail senden an... + + + + Copy Email Address + E-Mail-Adresse kopieren + + + + QTermWidget + + + Color Scheme Error + Fehler im Farbschema + + + + Cannot load color scheme: %1 + Kann Farbschema nicht laden: %1 + + + + SearchBar + + + Match case + Gross-/Kleinschreibung beachten + + + + Regular expression + Regulärer Ausdruck + + + + Highlight all matches + Alle Treffer hervorheben + + + + SearchBar + Suchleiste + + + + X + + + + + Find: + Finde: + + + + < + + + + + > + + + + + ... + + + + diff --git a/qtermwidget/lib/translations/qtermwidget_el.ts b/qtermwidget/lib/translations/qtermwidget_el.ts new file mode 100644 index 0000000..ad071f8 --- /dev/null +++ b/qtermwidget/lib/translations/qtermwidget_el.ts @@ -0,0 +1,166 @@ + + + + + Konsole::Session + + + Bell in session '%1' + Κουδούνι στην συνεδρία '%1' + + + + Session '%1' exited with status %2. + Η συνεδρία '%1' τερματίστηκε με την κατάσταση %2. + + + + Session '%1' crashed. + Η συνεδρία '%1' κατέρρευσε. + + + + Session '%1' exited unexpectedly. + Η συνεδρία '%1' τερματίστηκε απροσδόκητα. + + + + Konsole::TerminalDisplay + + + Size: XXX x XXX + Μέγεθος: XXX x XXX + + + + Size: %1 x %2 + Μέγεθος: %1 x %2 + + + + Paste multiline text + Επικόλληση κειμένου πολλαπλών γραμμών + + + + Are you sure you want to paste this text? + Επιθυμείτε σίγουρα την επικόλληση του κειμένου; + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>Η έξοδος έχει <a href="http://en.wikipedia.org/wiki/Flow_control">ανασταλεί</a> με τον συνδυασμό πλήκτρων Ctrl+S. Πιέστε <b>Ctrl+Q</b> για επαναφορά.</qt> + + + + Konsole::Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + Δεν υπάρχει κάποιος μεταφραστής πληκτρολογίου διαθέσιμος. Η απαιτούμενη πληροφορία για την μετατροπή των πατημάτων πλήκτρων σε χαρακτήρες στο τερματικό λείπει. + + + + QMessageBox + + + Show Details... + Εμφάνιση λεπτομερειών... + + + + QObject + + + + Un-named Color Scheme + Ανώνυμος χρωματικός συνδυασμός + + + + Accessible Color Scheme + Προσπελάσιμος χρωματικός σχηματισμός + + + + Open Link + Άνοιγμα του δεσμού + + + + Copy Link Address + Αντιγραφή διεύθυνσης του δεσμού + + + + Send Email To... + Αποστολή ηλ. αλληλογραφίας προς... + + + + Copy Email Address + Αντιγραφή της ηλ. διεύθυνσης + + + + QTermWidget + + + Color Scheme Error + Σφάλμα του χρωματικού συνδυασμού + + + + Cannot load color scheme: %1 + Αδύνατη η φόρτωση του χρωματικού συνδυασμού: %1 + + + + SearchBar + + + Match case + Ταίριασμα πεζών/κεφαλαίων + + + + Regular expression + Κανονική έκφραση + + + + Highlight all matches + Τονισμός όλων των ταιριαστών + + + + SearchBar + Γραμμή αναζήτησης + + + + X + X + + + + Find: + Εύρεση: + + + + < + < + + + + > + > + + + + ... + ... + + + diff --git a/qtermwidget/lib/translations/qtermwidget_es.ts b/qtermwidget/lib/translations/qtermwidget_es.ts new file mode 100644 index 0000000..1509c94 --- /dev/null +++ b/qtermwidget/lib/translations/qtermwidget_es.ts @@ -0,0 +1,166 @@ + + + + + Konsole::Session + + + Bell in session '%1' + Campana en sesión «%1» + + + + Session '%1' exited with status %2. + La sesión «%1» ha terminado con el estado %2. + + + + Session '%1' crashed. + Cesó el funcionamiento de la sesión «%1». + + + + Session '%1' exited unexpectedly. + La sesión «%1» ha terminado inesperadamente. + + + + Konsole::TerminalDisplay + + + Size: XXX x XXX + Tamaño: XXX × XXX + + + + Size: %1 x %2 + Tamaño: %1 × %2 + + + + Paste multiline text + Pegar texto con varias líneas + + + + Are you sure you want to paste this text? + ¿Esta seguro que quiere pegar este texto? + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>La salida se ha <a href="http://en.wikipedia.org/wiki/Flow_control">suspendido</a> al presionar Ctrl+S. Presione <b>Ctrl+Q</b> para reanudarla.</qt> + + + + Konsole::Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + No hay traductor de teclado disponible. La información necesaria para convertir pulsaciones de tecla en caracteres para enviarlos a la terminal está ausente. + + + + QMessageBox + + + Show Details... + Mostrar detalles... + + + + QObject + + + + Un-named Color Scheme + Combinación de colores sin nombre + + + + Accessible Color Scheme + Combinación de colores accesible + + + + Open Link + Abrir el enlace + + + + Copy Link Address + Copiar la dirección del enlace + + + + Send Email To... + Enviar correo a... + + + + Copy Email Address + Copiar la dirección de correo + + + + QTermWidget + + + Color Scheme Error + Error de la combinación de colores + + + + Cannot load color scheme: %1 + No se puede cargar la combinación de colores: %1 + + + + SearchBar + + + Match case + Distinguir mayúsculas y minúsculas + + + + Regular expression + Expresión regular + + + + Highlight all matches + Resaltar todas las coincidencias + + + + SearchBar + Barra de búsqueda + + + + X + X + + + + Find: + Buscar: + + + + < + < + + + + > + > + + + + ... + ... + + + diff --git a/qtermwidget/lib/translations/qtermwidget_et.ts b/qtermwidget/lib/translations/qtermwidget_et.ts new file mode 100644 index 0000000..d0f588d --- /dev/null +++ b/qtermwidget/lib/translations/qtermwidget_et.ts @@ -0,0 +1,166 @@ + + + + + Konsole::Session + + + Bell in session '%1' + Signaal sessioonis „%1“ + + + + Session '%1' exited with status %2. + Sessioon „%1“ lõpetas töö olekuga %2. + + + + Session '%1' crashed. + Sessioon „%1“ jooksis kokku. + + + + Session '%1' exited unexpectedly. + Sessioon „%1“ lõpetas ootamatult töö. + + + + Konsole::TerminalDisplay + + + Size: XXX x XXX + Suurus: XXX x XXX + + + + Size: %1 x %2 + Suurus: %1 x %2 + + + + Paste multiline text + Aseta mitmerealine tekst + + + + Are you sure you want to paste this text? + Kas sa oled kindel, et soovid asetada seda teksti? + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>Vajutades Ctrl+S jääb väljundi kuvamine <a href="http://en.wikipedia.org/wiki/Flow_control">pausile</a>. Jätkamiseks vajuta <b>Ctrl+Q</b>.</qt> + + + + Konsole::Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + Klaviatuurisisendi tõlgendaja pole saadaval. Hetkel ei leidu teavet kuidas muuta klahvivajutused terminali saadetavateks tähemärkideks. + + + + QMessageBox + + + Show Details... + Näita üksikasju... + + + + QObject + + + + Un-named Color Scheme + Nimeta värvikombinatsioon + + + + Accessible Color Scheme + Hõlpsalt kasutatav värvikombinatsioon + + + + Open Link + Ava link + + + + Copy Link Address + Kopeeri lingi aadress + + + + Send Email To... + Saada e-kiri aadressile... + + + + Copy Email Address + Kopeeri e-posti aadress + + + + QTermWidget + + + Color Scheme Error + Värvikombinatsiooni viga + + + + Cannot load color scheme: %1 + Värvikombinatsiooni laadimine ei õnnestu: %1 + + + + SearchBar + + + Match case + Tõstutundlik + + + + Regular expression + Regulaaravaldis + + + + Highlight all matches + Tõsta kõik vasted esile + + + + SearchBar + Otsinguriba + + + + X + X + + + + Find: + Otsi: + + + + < + < + + + + > + > + + + + ... + ... + + + diff --git a/qtermwidget/lib/translations/qtermwidget_fi.ts b/qtermwidget/lib/translations/qtermwidget_fi.ts new file mode 100644 index 0000000..a847344 --- /dev/null +++ b/qtermwidget/lib/translations/qtermwidget_fi.ts @@ -0,0 +1,166 @@ + + + + + Konsole::Session + + + Bell in session '%1' + Äänimerkki istunnossa '%1' + + + + Session '%1' exited with status %2. + Istunto '%1' päättyi paluuarvolla %2. + + + + Session '%1' crashed. + Istunto '%1' kaatui. + + + + Session '%1' exited unexpectedly. + Istunto '%1' päättyi odottamattomasti. + + + + Konsole::TerminalDisplay + + + Size: XXX x XXX + Koko: XXX x XXX + + + + Size: %1 x %2 + Koko: %1 x %2 + + + + Paste multiline text + Liitä monirivinen teksti + + + + Are you sure you want to paste this text? + Haluatko varmasti liittää tämän tekstin? + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>Tuloste on <a href="http://en.wikipedia.org/wiki/Flow_control">keskeytetty</a> painamalla Ctrl+S. Jatka suoritusta painamalla <b>Ctrl+Q</b>.</qt> + + + + Konsole::Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + Näppäimistökääntäjä ei ole käytettävissä. Tieto siitä, miten näppäimenpainallukset muutetaan päätteelle lähetettäviksi merkeiksi, puuttuu. + + + + QMessageBox + + + Show Details... + Näytä yksityiskohdat... + + + + QObject + + + + Un-named Color Scheme + Nimetön väriteema + + + + Accessible Color Scheme + Esteetön väriteema + + + + Open Link + Avaa linkki + + + + Copy Link Address + Kopioi linkin osoite + + + + Send Email To... + Lähetä sähköposti osoitteeseen... + + + + Copy Email Address + Kopioi sähköpostiosoite + + + + QTermWidget + + + Color Scheme Error + Väriteemavirhe + + + + Cannot load color scheme: %1 + Väriteemaa ei voi ladata: %1 + + + + SearchBar + + + Match case + Erota pien- ja suuraakkoset + + + + Regular expression + Säännöllinen lauseke + + + + Highlight all matches + Korosta kaikki osumat + + + + SearchBar + SearchBar + + + + X + X + + + + Find: + Hae: + + + + < + < + + + + > + > + + + + ... + ... + + + diff --git a/qtermwidget/lib/translations/qtermwidget_fr.ts b/qtermwidget/lib/translations/qtermwidget_fr.ts new file mode 100644 index 0000000..411ec12 --- /dev/null +++ b/qtermwidget/lib/translations/qtermwidget_fr.ts @@ -0,0 +1,166 @@ + + + + + Konsole::Session + + + Bell in session '%1' + Sonnerie dans la session '%1' + + + + Session '%1' exited with status %2. + La session '%1' s'est terminée avec le statut %2. + + + + Session '%1' crashed. + La session '%1' a planté. + + + + Session '%1' exited unexpectedly. + La session '%1' s'est fermée de manière inattendue. + + + + Konsole::TerminalDisplay + + + Size: XXX x XXX + Taille : XXX x XXX + + + + Size: %1 x %2 + Taille : %1 x %2 + + + + Paste multiline text + Coller des textes multiligne + + + + Are you sure you want to paste this text? + Êtes-vous sûr de vouloir coller ce texte ? + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>La sortie a été <a href="http://en.wikipedia.org/wiki/Flow_control">suspendue</a> en pressant Ctrl+S. Presser <b>Ctrl+Q</b> pour reprendre.</qt> + + + + Konsole::Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + Aucun traducteur de clavier disponible. Les informations nécessaires pour convertir les touches utilisées en caractères à envoyer au terminal sont manquantes. + + + + QMessageBox + + + Show Details... + Voir les détails... + + + + QObject + + + + Un-named Color Scheme + Jeu de couleurs non nommé + + + + Accessible Color Scheme + Schéma de couleur accessible + + + + Open Link + Ouvrir le lien + + + + Copy Link Address + Copier l'adresse du lien + + + + Send Email To... + Envoyer un courriel à... + + + + Copy Email Address + Copier l'adresse du courriel + + + + QTermWidget + + + Color Scheme Error + Erreur du schéma des couleurs + + + + Cannot load color scheme: %1 + Impossible de charger le schéma de couleurs : %1 + + + + SearchBar + + + SearchBar + Barre de recherche + + + + X + X + + + + Find: + Trouver : + + + + < + < + + + + > + > + + + + ... + ... + + + + Match case + Sensible à la casse + + + + Regular expression + Expression régulière + + + + Highlight all matches + Surbrillance de toutes les concordances + + + diff --git a/qtermwidget/lib/translations/qtermwidget_gl.ts b/qtermwidget/lib/translations/qtermwidget_gl.ts new file mode 100644 index 0000000..789a526 --- /dev/null +++ b/qtermwidget/lib/translations/qtermwidget_gl.ts @@ -0,0 +1,166 @@ + + + + + Konsole::Session + + + Bell in session '%1' + Campana na sesión '% 1' + + + + Session '%1' exited with status %2. + Saíuse da sesión '% 1' co estado % 2. + + + + Session '%1' crashed. + A sesión '% 1' fallou. + + + + Session '%1' exited unexpectedly. + A sesión "% 1" saíu de forma inesperada. + + + + Konsole::TerminalDisplay + + + Size: XXX x XXX + Tamaño: XXX x XXX + + + + Size: %1 x %2 + Tamaño: %1 x %2 + + + + Paste multiline text + Pegar texto multiliña + + + + Are you sure you want to paste this text? + Estás seguro de que queres pegar este texto? + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>A saída foi <a href="http://en.wikipedia.org/wiki/Flow_control">suspendida</a> ao premer Ctrl+S. Prema <b>Ctrl+Q</b> para continuar.</qt> + + + + Konsole::Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + Non hai dispoñíbel ningún tradutor de teclado. Non está dispoñíbel a información necesaria para converter pulsacións de tecla en caracteres para envialos o terminal. + + + + QMessageBox + + + Show Details... + Ver detalles... + + + + QObject + + + + Un-named Color Scheme + Esquema de cor sen nome + + + + Accessible Color Scheme + Esquema de cor accesíbel + + + + Open Link + Abrir a ligazón + + + + Copy Link Address + Copiar o enderezo da ligazón + + + + Send Email To... + Enviar correo a... + + + + Copy Email Address + Copiar o enderezo de correo + + + + QTermWidget + + + Color Scheme Error + Produciuse un erro no esquema de cor + + + + Cannot load color scheme: %1 + Non é posíbel cargar o esquema de cor: %1 + + + + SearchBar + + + Match case + Distinguir maiúsculas de minúsculas + + + + Regular expression + Expresión regular + + + + Highlight all matches + Resaltar todas as coincidencias + + + + SearchBar + Barra de buscas + + + + X + + + + + Find: + Atopar: + + + + < + + + + + > + + + + + ... + + + + diff --git a/qtermwidget/lib/translations/qtermwidget_he.ts b/qtermwidget/lib/translations/qtermwidget_he.ts new file mode 100644 index 0000000..f50239d --- /dev/null +++ b/qtermwidget/lib/translations/qtermwidget_he.ts @@ -0,0 +1,166 @@ + + + + + Konsole::Session + + + Bell in session '%1' + צלצול בהפעלה ‚%1’ + + + + Session '%1' exited with status %2. + ההפעלה ‚%1’ נסגרה עם הכרזת המצב %2. + + + + Session '%1' crashed. + ההפעלה ‚%1’ קרסה. + + + + Session '%1' exited unexpectedly. + ההפעלה ‚%1’ נסגרה במפתיע. + + + + Konsole::TerminalDisplay + + + Size: XXX x XXX + גודל: XXX × XXX + + + + Size: %1 x %2 + גודל: %1 × %2 + + + + Paste multiline text + הדבקת מקבץ שורות + + + + Are you sure you want to paste this text? + להדביק את הטקסט הזה? + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>הפלט <a href="http://en.wikipedia.org/wiki/Flow_control">הושהה</a> בלחיצה על Ctrl+S. יש ללחוץ על <b>Ctrl+Q</b> כדי להמשיך.</qt> + + + + Konsole::Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + אין מתרגם מקלדת זמין. המידע שנדרש לצורך המרת לחיצות מקשים לתווים לשליחה למסוף חסר. + + + + QMessageBox + + + Show Details... + להציג פרטים… + + + + QObject + + + + Un-named Color Scheme + ערכת צבעים ללא שם + + + + Accessible Color Scheme + ערכת צבעים נגישה + + + + Open Link + פתיחת קישור + + + + Copy Link Address + העתקת כתובת קישור + + + + Send Email To... + שליחת דוא״ל אל… + + + + Copy Email Address + העתקת כתובת דוא״ל + + + + QTermWidget + + + Color Scheme Error + שגיאת ערכת צבעים + + + + Cannot load color scheme: %1 + לא ניתן לטעון ערכת צבעים: %1 + + + + SearchBar + + + Match case + התאמת רישיות + + + + Regular expression + ביטוי רגולרי + + + + Highlight all matches + הדגשת כל המופעים + + + + SearchBar + סרגל חיפוש + + + + X + + + + + Find: + חיפוש: + + + + < + + + + + > + + + + + ... + + + + diff --git a/qtermwidget/lib/translations/qtermwidget_hr.ts b/qtermwidget/lib/translations/qtermwidget_hr.ts new file mode 100644 index 0000000..484257c --- /dev/null +++ b/qtermwidget/lib/translations/qtermwidget_hr.ts @@ -0,0 +1,166 @@ + + + + + Konsole::Session + + + Bell in session '%1' + Zvono u sesiji „%1“ + + + + Session '%1' exited with status %2. + Sesija „%1“ je prekinuta sa stanjem %2. + + + + Session '%1' crashed. + Fatalna greška u sesiji „%1“. + + + + Session '%1' exited unexpectedly. + Sesija „%1“ je nenadano prekinuta. + + + + Konsole::TerminalDisplay + + + Size: XXX x XXX + Veličina: XXX × XXX + + + + Size: %1 x %2 + Veličina: %1 × %2 + + + + Paste multiline text + Umetni višeredan tekst + + + + Are you sure you want to paste this text? + Stvarno želiš umetnuti ovaj tekst? + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>Rezultat je <a href="http://en.wikipedia.org/wiki/Flow_control">obustavljen</a> pritiskom Ctrl+S. Pritisni <b>Ctrl+Q</b> za nastavak.</qt> + + + + Konsole::Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + Nema interpretera tipkovnice. Nedostaju podaci za pretvaranje tipki u znakove koji se šalju u terminal. + + + + QMessageBox + + + Show Details... + Prikaži detalje … + + + + QObject + + + + Un-named Color Scheme + Neimenovana shema boja + + + + Accessible Color Scheme + Dostupna shema boja + + + + Open Link + Otvori poveznicu + + + + Copy Link Address + Otvori adresu poveznice + + + + Send Email To... + Pošalji e-mail na … + + + + Copy Email Address + Kopiraj e-adresu + + + + QTermWidget + + + Color Scheme Error + Greška u shemi boja + + + + Cannot load color scheme: %1 + Nije moguće učitati shemu boja: %1 + + + + SearchBar + + + Match case + Razlikuj velika/mala slova + + + + Regular expression + Regularni izrazi + + + + Highlight all matches + Istakni sva poklapanja + + + + SearchBar + Traka pretrage + + + + X + X + + + + Find: + Traži: + + + + < + < + + + + > + > + + + + ... + + + + diff --git a/qtermwidget/lib/translations/qtermwidget_hu.ts b/qtermwidget/lib/translations/qtermwidget_hu.ts new file mode 100644 index 0000000..ddf94e8 --- /dev/null +++ b/qtermwidget/lib/translations/qtermwidget_hu.ts @@ -0,0 +1,166 @@ + + + + + Konsole::Session + + + Bell in session '%1' + Jelzés a '%1' munkamenetben + + + + Session '%1' exited with status %2. + A(z) '%1' munkamenet %2 állapottal lépett ki. + + + + Session '%1' crashed. + A(z) '%1' munkamenet összeomlott. + + + + Session '%1' exited unexpectedly. + A '%1' munkamenet váratlanul kilépett. + + + + Konsole::TerminalDisplay + + + Size: XXX x XXX + Méret: XXX x XXX + + + + Size: %1 x %2 + Méret: %1 x %2 + + + + Paste multiline text + Többsoros szöveg beillesztése + + + + Are you sure you want to paste this text? + Biztosan beilleszti ezt a szöveget? + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>A kimenet <a href="http://en.wikipedia.org/wiki/Flow_control">fel van függesztve</a> a Ctrl+S megnyomásával. Nyomjon <b>Ctrl+Q-t</b> a folytatáshoz.</qt> + + + + Konsole::Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + Nincs elérhető billentyűzet-átalakító. Hiányzik az információ, amely a billentyű lenyomások a terminálhoz küldendő karakterekké alakításához szükséges. + + + + QMessageBox + + + Show Details... + Részletek megjelenítése... + + + + QObject + + + + Un-named Color Scheme + Névtelen Színséma + + + + Accessible Color Scheme + Elérhető színséma + + + + Open Link + Link megnyitása + + + + Copy Link Address + Link másolása + + + + Send Email To... + Email küldése ... + + + + Copy Email Address + Email cím másolása + + + + QTermWidget + + + Color Scheme Error + Színséma hiba + + + + Cannot load color scheme: %1 + Nem sikerült betölteni a színsémát. %1 + + + + SearchBar + + + Match case + Nagybetűérzékeny + + + + Regular expression + Reguláris kifejezés + + + + Highlight all matches + Találatok kiemelése + + + + SearchBar + Keresősáv + + + + X + + + + + Find: + Keresés: + + + + < + + + + + > + + + + + ... + + + + diff --git a/qtermwidget/lib/translations/qtermwidget_it.ts b/qtermwidget/lib/translations/qtermwidget_it.ts new file mode 100644 index 0000000..9424bf1 --- /dev/null +++ b/qtermwidget/lib/translations/qtermwidget_it.ts @@ -0,0 +1,166 @@ + + + + + Konsole::Session + + + Bell in session '%1' + Campanello in sessione '%1' + + + + Session '%1' exited with status %2. + Sessione '%1' terminata con stato %2. + + + + Session '%1' crashed. + Sessione '%1' terminata inaspettatamente. + + + + Session '%1' exited unexpectedly. + Sessione '%1' terminata inaspettatamente. + + + + Konsole::TerminalDisplay + + + Size: XXX x XXX + Dimensione: XXX x XXX + + + + Size: %1 x %2 + Dimensione: %1 x %2 + + + + Paste multiline text + Incolla testo multi-righe + + + + Are you sure you want to paste this text? + Si è sicuro di voler incollare questo testo? + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>L'output è stato <a href="https://it.wikipedia.org/wiki/Controllo_di_flusso">sospeso</a> premendo Ctrl+S. Premi <b>Ctrl+Q</b> per riprendere.</qt> + + + + Konsole::Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + Nessuno traduttore di tastiera disponibile. L'informazione necessaria per convertire tasti in caratteri da inviare al terminale è mancante. + + + + QMessageBox + + + Show Details... + Mostra dettagli... + + + + QObject + + + + Un-named Color Scheme + Schema Colore senza nome + + + + Accessible Color Scheme + Schema Colore Accessibile + + + + Open Link + Apri collegamento + + + + Copy Link Address + Copia indirizzo collegamento + + + + Send Email To... + Invia email a... + + + + Copy Email Address + Copia indirizzo email + + + + QTermWidget + + + Color Scheme Error + Errore su Schema Colori + + + + Cannot load color scheme: %1 + Caricamento schema colore %1 non riuscito + + + + SearchBar + + + Match case + Rispetta maiuscolo/minuscolo + + + + Regular expression + Espressione regolare + + + + Highlight all matches + Evidenzia tutte le corrispondenze + + + + SearchBar + Barra di ricerca + + + + X + X + + + + Find: + Trova: + + + + < + < + + + + > + > + + + + ... + ... + + + diff --git a/qtermwidget/lib/translations/qtermwidget_ja.ts b/qtermwidget/lib/translations/qtermwidget_ja.ts new file mode 100644 index 0000000..1b4d21e --- /dev/null +++ b/qtermwidget/lib/translations/qtermwidget_ja.ts @@ -0,0 +1,166 @@ + + + + + Konsole::Session + + + Bell in session '%1' + セッション '%1' のベル + + + + Session '%1' exited with status %2. + セッション '%1' はステータス %2 で終了しました。 + + + + Session '%1' crashed. + セッション '%1' がクラッシュしました。 + + + + Session '%1' exited unexpectedly. + セッション '%1' が予期せず終了しました。 + + + + Konsole::TerminalDisplay + + + Size: XXX x XXX + サイズ: XXX x XXX + + + + Size: %1 x %2 + サイズ: %1 x %2 + + + + Paste multiline text + 複数行テキストの貼り付け + + + + Are you sure you want to paste this text? + このテキストを貼り付けますか? + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>Ctrl+S を押して出力を<a href="http://en.wikipedia.org/wiki/Flow_control">中断</a> しました 。再開するには <b>Ctrl+Q</b> を押します。</qt> + + + + Konsole::Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + キーボードトランスレーターがありません。押されたキーを文字に変換してターミナルへ送信するために必要な情報がありません。 + + + + QMessageBox + + + Show Details... + 詳細の表示... + + + + QObject + + + + Un-named Color Scheme + 名前のない配色 + + + + Accessible Color Scheme + アクセス可能な配色 + + + + Open Link + リンクを開く + + + + Copy Link Address + リンクのアドレスをコピー + + + + Send Email To... + メールを送信... + + + + Copy Email Address + メールアドレスをコピー + + + + QTermWidget + + + Color Scheme Error + 配色のエラー + + + + Cannot load color scheme: %1 + 配色をロードできません: %1 + + + + SearchBar + + + Match case + 大文字と小文字の区別 + + + + Regular expression + 正規表現 + + + + Highlight all matches + 一致する全ての文字列を強調表示 + + + + SearchBar + サーチバー + + + + X + + + + + Find: + 検索: + + + + < + < + + + + > + > + + + + ... + ... + + + diff --git a/qtermwidget/lib/translations/qtermwidget_ko.ts b/qtermwidget/lib/translations/qtermwidget_ko.ts new file mode 100644 index 0000000..24d9a8c --- /dev/null +++ b/qtermwidget/lib/translations/qtermwidget_ko.ts @@ -0,0 +1,166 @@ + + + + + Konsole::Session + + + Bell in session '%1' + 세션 '%1'의 벨소리 + + + + Session '%1' exited with status %2. + '%1' 세션이 %2 상태로 종료되었습니다. + + + + Session '%1' crashed. + '%1' 세션이 충돌했습니다. + + + + Session '%1' exited unexpectedly. + '%1' 세션이 예기치 않게 종료되었습니다. + + + + Konsole::TerminalDisplay + + + Size: XXX x XXX + 크기: XXX x XXX + + + + Size: %1 x %2 + 크기: %1 x %2 + + + + Paste multiline text + 여러 줄 텍스트 붙여넣기 + + + + Are you sure you want to paste this text? + 이 텍스트를 붙여넣으시겠습니까? + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>Ctrl+S를 눌러 출력이 <a href="http://en.wikipedia.org/wiki/Flow_control">일시 중단</a>되었습니다. 재개하려면 <b>Ctrl+Q</b>를 누르십시오.</qt> + + + + Konsole::Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + 키보드 번역기를 사용할 수 없습니다. 터미널에 보내기 위해 키 누름을 문자로 변환하는 데 필요한 정보가 누락되었습니다. + + + + QMessageBox + + + Show Details... + 세부정보 표시하기... + + + + QObject + + + + Un-named Color Scheme + 이름 지정되지 않은 색 구성표 + + + + Accessible Color Scheme + 접근 가능한 색 구성표 + + + + Open Link + 링크 열기 + + + + Copy Link Address + 링크 주소 복사하기 + + + + Send Email To... + 이메일 보내기... + + + + Copy Email Address + 이메일 주소 복사하기 + + + + QTermWidget + + + Color Scheme Error + 색 구성표 오류 + + + + Cannot load color scheme: %1 + 색 구성표를 불러올 수 없음: %1 + + + + SearchBar + + + Match case + 대소문자 일치 + + + + Regular expression + 정규식 + + + + Highlight all matches + 모든 일치 항목 강조표시 + + + + SearchBar + 검색 창 + + + + X + X + + + + Find: + 찾기: + + + + < + < + + + + > + > + + + + ... + ... + + + diff --git a/qtermwidget/lib/translations/qtermwidget_lt.ts b/qtermwidget/lib/translations/qtermwidget_lt.ts new file mode 100644 index 0000000..cb401f6 --- /dev/null +++ b/qtermwidget/lib/translations/qtermwidget_lt.ts @@ -0,0 +1,166 @@ + + + + + Konsole::Session + + + Bell in session '%1' + Skambutis “%1„ seanse + + + + Session '%1' exited with status %2. + Seansas „%1“ išėjo su būsena %2. + + + + Session '%1' crashed. + Seansas „%1“ užstrigo. + + + + Session '%1' exited unexpectedly. + Seansas „%1“ netikėtai išėjo. + + + + Konsole::TerminalDisplay + + + Size: XXX x XXX + Dydis: XXX x XXX + + + + Size: %1 x %2 + Dydis: %1 x %2 + + + + Paste multiline text + Įdėti kelių eilučių tekstą + + + + Are you sure you want to paste this text? + Ar tikrai norite įdėti šį tekstą? + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>Išvestis buvo <a href="http://en.wikipedia.org/wiki/Flow_control">pristabdyta,</a> paspaudžiant Ctrl+S. Paspauskite <b>Ctrl+Q</b>, norėdami pratęsti.</qt> + + + + Konsole::Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + Nėra prieinamas joks klaviatūros vertėjas. Informacijos, kurios reikia, norint konvertuoti klavišų paspaudimus į simbolius ir siųsti į terminalą, nėra. + + + + QMessageBox + + + Show Details... + Rodyti išsamiau... + + + + QObject + + + + Un-named Color Scheme + Nepavadintas spalvų rinkinys + + + + Accessible Color Scheme + Pasiekiamas spalvų rinkinys + + + + Open Link + Atverti nuorodą + + + + Copy Link Address + Kopijuoti nuorodos adresą + + + + Send Email To... + Siųsti el. paštą... + + + + Copy Email Address + Kopijuoti el. pašto adresą + + + + QTermWidget + + + Color Scheme Error + Spalvų rinkinio klaida + + + + Cannot load color scheme: %1 + Nepavyksta įkelti spalvų rinkinio: %1 + + + + SearchBar + + + Match case + Skirti raidžių dydį + + + + Regular expression + Reguliarusis reiškinys + + + + Highlight all matches + Paryškinti visus atitikmenis + + + + SearchBar + Paieškos juosta + + + + X + X + + + + Find: + Rasti: + + + + < + < + + + + > + > + + + + ... + ... + + + diff --git a/qtermwidget/lib/translations/qtermwidget_nb_NO.ts b/qtermwidget/lib/translations/qtermwidget_nb_NO.ts new file mode 100644 index 0000000..813ff4f --- /dev/null +++ b/qtermwidget/lib/translations/qtermwidget_nb_NO.ts @@ -0,0 +1,166 @@ + + + + + Konsole::Session + + + Bell in session '%1' + Klokke i økt «%1» + + + + Session '%1' exited with status %2. + Økt «%1» avsluttet med status %2. + + + + Session '%1' crashed. + Økt «%1» krasjet. + + + + Session '%1' exited unexpectedly. + Økt «%1» avsluttet uventet. + + + + Konsole::TerminalDisplay + + + Size: XXX x XXX + Størrelse: XXX x XXX + + + + Size: %1 x %2 + Størrelse: %1 x %2 + + + + Paste multiline text + Lim inn flerlinjerstekst + + + + Are you sure you want to paste this text? + Er du sikker på at du vil lime inn denne teksten? + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>Utgangssignalet ble <a href="http://en.wikipedia.org/wiki/Flow_control">stoppet</a> da Ctrl+S ble trykket. Trykk <b>Ctrl+Q</b> for å fortsette.</qt> + + + + Konsole::Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + Ingen tastaturoversetter er tilgjengelig. Nødvendig info for å gjøre om tastetrykk til tegn å sende terminalen mangler. + + + + QMessageBox + + + Show Details... + Vis detaljer … + + + + QObject + + + + Un-named Color Scheme + Fargemønster uten navn + + + + Accessible Color Scheme + Fargemønster for funksjonshemmede + + + + Open Link + Åpne lenke + + + + Copy Link Address + Kopier lenkeadresse + + + + Send Email To... + Send epost til... + + + + Copy Email Address + Kopier epostadressen + + + + QTermWidget + + + Color Scheme Error + Feil med fargemønster + + + + Cannot load color scheme: %1 + Kan ikke åpne fargemønster: %1 + + + + SearchBar + + + Match case + Bruk STORE og små bokstaver + + + + Regular expression + Bokstavmønstre (regex) + + + + Highlight all matches + Lys opp alle søkeresultat + + + + SearchBar + Søkelinje + + + + X + + + + + Find: + Finn: + + + + < + + + + + > + + + + + ... + + + + diff --git a/qtermwidget/lib/translations/qtermwidget_nl.ts b/qtermwidget/lib/translations/qtermwidget_nl.ts new file mode 100644 index 0000000..2016d7d --- /dev/null +++ b/qtermwidget/lib/translations/qtermwidget_nl.ts @@ -0,0 +1,166 @@ + + + + + Konsole::Session + + + Bell in session '%1' + Bel in sessie ‘%1’ + + + + Session '%1' exited with status %2. + Sessie ‘%1’ is afgesloten met status ‘%2’. + + + + Session '%1' crashed. + Sessie ‘%1’ is gecrasht. + + + + Session '%1' exited unexpectedly. + Sessie ‘%1’ is onverwachts afgebroken. + + + + Konsole::TerminalDisplay + + + Size: XXX x XXX + Grootte: XXX x XXX + + + + Size: %1 x %2 + Grootte: %1x%2 + + + + Paste multiline text + Meerregelige tekst plakken + + + + Are you sure you want to paste this text? + Weet u zeker dat u deze tekst wilt plakken? + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>Door op Ctrl+S te drukken is de uitvoer <a href="http://en.wikipedia.org/wiki/Flow_control">onderbroken</a>. Druk op <b>Ctrl+Q</b> om te hervatten.</qt> + + + + Konsole::Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + Er is geen toetsaanslagomzetting beschikbaar, waardoor toetsaanslagen niet kunnen worden omgezet in tekens. + + + + QMessageBox + + + Show Details... + Details tonen… + + + + QObject + + + + Un-named Color Scheme + Naamloos kleurenschema + + + + Accessible Color Scheme + Toegankelijk kleurenschema + + + + Open Link + Link openen + + + + Copy Link Address + Linkadres kopiëren + + + + Send Email To... + E-mail versturen naar… + + + + Copy Email Address + E-mailadres kopiëren + + + + QTermWidget + + + Color Scheme Error + Kleurenschemafout + + + + Cannot load color scheme: %1 + Het kleurenschema kan niet worden geladen: %1 + + + + SearchBar + + + Match case + Hoofdlettergevoelig + + + + Regular expression + Reguliere uitdrukking + + + + Highlight all matches + Alle overeenkomsten markeren + + + + SearchBar + Zoekbalk + + + + X + X + + + + Find: + Zoeken: + + + + < + < + + + + > + > + + + + ... + + + + diff --git a/qtermwidget/lib/translations/qtermwidget_oc.ts b/qtermwidget/lib/translations/qtermwidget_oc.ts new file mode 100644 index 0000000..7cdc53e --- /dev/null +++ b/qtermwidget/lib/translations/qtermwidget_oc.ts @@ -0,0 +1,166 @@ + + + + + Konsole::Session + + + Bell in session '%1' + + + + + Session '%1' exited with status %2. + + + + + Session '%1' crashed. + + + + + Session '%1' exited unexpectedly. + + + + + Konsole::TerminalDisplay + + + Size: XXX x XXX + Talha : XXX x XXX + + + + Size: %1 x %2 + Talha : %1 x %2 + + + + Paste multiline text + + + + + Are you sure you want to paste this text? + + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + + + + + Konsole::Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + + + + + QMessageBox + + + Show Details... + Veire los detalhs... + + + + QObject + + + + Un-named Color Scheme + + + + + Accessible Color Scheme + + + + + Open Link + Dobrir lo ligam + + + + Copy Link Address + Copiar l’adreça del ligam + + + + Send Email To... + + + + + Copy Email Address + + + + + QTermWidget + + + Color Scheme Error + + + + + Cannot load color scheme: %1 + + + + + SearchBar + + + Match case + + + + + Regular expression + + + + + Highlight all matches + + + + + SearchBar + Barra de recèrca + + + + X + X + + + + Find: + Cercar : + + + + < + < + + + + > + > + + + + ... + ... + + + diff --git a/qtermwidget/lib/translations/qtermwidget_pl.ts b/qtermwidget/lib/translations/qtermwidget_pl.ts new file mode 100644 index 0000000..5d40496 --- /dev/null +++ b/qtermwidget/lib/translations/qtermwidget_pl.ts @@ -0,0 +1,166 @@ + + + + + Konsole::Session + + + Bell in session '%1' + Dzwonek w sesji '%1' + + + + Session '%1' exited with status %2. + Sesja '%1' zakończona ze statusem %2. + + + + Session '%1' crashed. + Sesja '%1' uległa awarii. + + + + Session '%1' exited unexpectedly. + Sesja '%1' nieoczekiwanie zakończyła działanie. + + + + Konsole::TerminalDisplay + + + Size: XXX x XXX + Rozmiar: XXX x XXX + + + + Size: %1 x %2 + Rozmiar: %1 x %2 + + + + Paste multiline text + Wklej wielowierszowy tekst + + + + Are you sure you want to paste this text? + Czy na pewno chcesz wkleić ten tekst? + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>Wyjście zostało <a href="http://en.wikipedia.org/wiki/Flow_control">wstrzymane</a> skrótem Ctrl+S. Wciśnij <b>Ctrl+Q</b> aby wznowić.</qt> + + + + Konsole::Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + Brak sterownika klawiatury. Nie wiadomo jak przełożyć wciśniecia przycisków na znaki wysyłane do terminalu. + + + + QMessageBox + + + Show Details... + Pokaż szczegóły... + + + + QObject + + + + Un-named Color Scheme + Nienazwana paleta + + + + Accessible Color Scheme + Paleta o zwiększonej przystępności + + + + Open Link + Przejdź pod adres + + + + Copy Link Address + Kopiuj adres łącza + + + + Send Email To... + Wyślij e-mail do… + + + + Copy Email Address + Kopiuj adres e-mail + + + + QTermWidget + + + Color Scheme Error + Błąd w palecie + + + + Cannot load color scheme: %1 + Nie można wczytać palety: %1 + + + + SearchBar + + + Match case + Rozróżniaj wielkość liter + + + + Regular expression + Wyrażenie regularne + + + + Highlight all matches + Podświetl wszystkie dopasowania + + + + SearchBar + Pasek wyszukiwania + + + + X + X + + + + Find: + Znajdź: + + + + < + < + + + + > + > + + + + ... + + + + diff --git a/qtermwidget/lib/translations/qtermwidget_pt.ts b/qtermwidget/lib/translations/qtermwidget_pt.ts new file mode 100644 index 0000000..fd4453d --- /dev/null +++ b/qtermwidget/lib/translations/qtermwidget_pt.ts @@ -0,0 +1,166 @@ + + + + + Konsole::Session + + + Bell in session '%1' + Campainha na sessão '%1' + + + + Session '%1' exited with status %2. + A sessão '%1' terminou com o estado %2. + + + + Session '%1' crashed. + A sessão '%1' terminou. + + + + Session '%1' exited unexpectedly. + A sessão '%1' terminou inesperadamente. + + + + Konsole::TerminalDisplay + + + Size: XXX x XXX + Tamanho: XXX x XXX + + + + Size: %1 x %2 + Tamanho: %1 x %2 + + + + Paste multiline text + Colar texto com várias linhas + + + + Are you sure you want to paste this text? + Tem a certeza que deseja colar este texto? + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>A saída foi <a href="http://en.wikipedia.org/wiki/Flow_control"> suspendida</a> com Ctrl+S. Prima <b>Ctrl+Q</b> para continuar.</qt> + + + + Konsole::Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + Não há um tradutor de teclado disponível. A informação necessária para converter a pressão da tecla nos caracteres a enviar ao terminal não existe. + + + + QMessageBox + + + Show Details... + Mostrar detalhes... + + + + QObject + + + + Un-named Color Scheme + Esquema de cores sem nome + + + + Accessible Color Scheme + Esquema de cores acessível + + + + Open Link + Abrir ligação + + + + Copy Link Address + Copiar endereço da ligação + + + + Send Email To... + Enviar e-mail para... + + + + Copy Email Address + Copiar endereço de e-mail + + + + QTermWidget + + + Color Scheme Error + Erro no esquema de cores + + + + Cannot load color scheme: %1 + Não foi possível carregar o esquema de cores: %1 + + + + SearchBar + + + Match case + Diferenciar maiúsculas/minúsculas + + + + Regular expression + Expressão regular + + + + Highlight all matches + Realçar todas as ocorrências + + + + SearchBar + Barra de pesquisa + + + + X + X + + + + Find: + Localizar: + + + + < + < + + + + > + > + + + + ... + ... + + + diff --git a/qtermwidget/lib/translations/qtermwidget_pt_BR.ts b/qtermwidget/lib/translations/qtermwidget_pt_BR.ts new file mode 100644 index 0000000..7aa2c5d --- /dev/null +++ b/qtermwidget/lib/translations/qtermwidget_pt_BR.ts @@ -0,0 +1,166 @@ + + + + + Konsole::Session + + + Bell in session '%1' + Campainha na sessão '%1' + + + + Session '%1' exited with status %2. + A sessão '%1' encerrada com status %2. + + + + Session '%1' crashed. + A sessão '%1' travada. + + + + Session '%1' exited unexpectedly. + A sessão '%1' foi encerrada inesperadamente. + + + + Konsole::TerminalDisplay + + + Size: XXX x XXX + Tamanho: XXX x XXX + + + + Size: %1 x %2 + Tamanho: %1 x %2 + + + + Paste multiline text + Cole texto multilinha + + + + Are you sure you want to paste this text? + Tem certeza que deseja colar este texto? + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>A saída foi <a href="http://en.wikipedia.org/wiki/Flow_control">suspensa</a> pressionando Ctrl+S. Pressione <b>Ctrl+Q</b> para continuar.</qt> + + + + Konsole::Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + Nenhum tradutor de teclado disponível. A informação necessária para converter a tecla pressionada em caracteres para enviar para o terminal está faltando. + + + + QMessageBox + + + Show Details... + Mostrar Detalhes... + + + + QObject + + + + Un-named Color Scheme + Esquema de cor sem nome + + + + Accessible Color Scheme + Esquema de cor acessível + + + + Open Link + Abrir Link + + + + Copy Link Address + Copiar Endereço do Link + + + + Send Email To... + Enviar E-mail Para... + + + + Copy Email Address + Copiar Endereço de E-mail + + + + QTermWidget + + + Color Scheme Error + Erro no esquema de cor + + + + Cannot load color scheme: %1 + Não foi possível carregar o esquema de cor: %1 + + + + SearchBar + + + Match case + Caso de compatibilidade + + + + Regular expression + Expressão Regular + + + + Highlight all matches + Destacar todas as correspondências + + + + SearchBar + Barra de Pesquisa + + + + X + X + + + + Find: + Encontrar: + + + + < + < + + + + > + > + + + + ... + ... + + + diff --git a/qtermwidget/lib/translations/qtermwidget_ru.ts b/qtermwidget/lib/translations/qtermwidget_ru.ts new file mode 100644 index 0000000..d98bf28 --- /dev/null +++ b/qtermwidget/lib/translations/qtermwidget_ru.ts @@ -0,0 +1,166 @@ + + + + + Konsole::Session + + + Bell in session '%1' + Звуковой сигнал в сеансе «%1» + + + + Session '%1' exited with status %2. + Сеанс «%1» завершилась со статусом %2. + + + + Session '%1' crashed. + Сбой сеанса «%1». + + + + Session '%1' exited unexpectedly. + Сеанс «%1» завершился неожиданно. + + + + Konsole::TerminalDisplay + + + Size: XXX x XXX + Размер: XXX x XXX + + + + Size: %1 x %2 + Размер: %1 x %2 + + + + Paste multiline text + Вставить многострочный текст + + + + Are you sure you want to paste this text? + Вы уверены, что хотите вставить этот текст? + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>Вывод был <a href="https://ru.wikipedia.org/wiki/%D0%9A%D0%BE%D0%BD%D1%82%D1%80%D0%BE%D0%BB%D1%8C_%D0%BF%D0%BE%D1%82%D0%BE%D0%BA%D0%B0">приостановлен</a> нажатием Ctrl+S. Нажмите <b>Ctrl+Q</b> для продолжения.</qt> + + + + Konsole::Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + Нет доступных трансляторов клавиатуры. Информация, необходимая, чтобы преобразовать нажатия клавиш в символы, которые будут отправлены на терминал, не найдена. + + + + QMessageBox + + + Show Details... + Показать подробности... + + + + QObject + + + + Un-named Color Scheme + Безымянная цветовая схема + + + + Accessible Color Scheme + Упрощённая цветовая схема + + + + Open Link + Открыть ссылку + + + + Copy Link Address + Скопировать адрес ссылки + + + + Send Email To... + Отправить e-mail на... + + + + Copy Email Address + Скопировать e-mail адрес + + + + QTermWidget + + + Color Scheme Error + Ошибка цветовой схемы + + + + Cannot load color scheme: %1 + Не удалось загрузить цветовую схему: %1 + + + + SearchBar + + + Match case + С учётом регистра + + + + Regular expression + Регулярное выражение + + + + Highlight all matches + Подсвечивать все совпадения + + + + SearchBar + ПанельПоиска + + + + X + X + + + + Find: + Найти: + + + + < + < + + + + > + > + + + + ... + ... + + + diff --git a/qtermwidget/lib/translations/qtermwidget_si.ts b/qtermwidget/lib/translations/qtermwidget_si.ts new file mode 100644 index 0000000..2ec493f --- /dev/null +++ b/qtermwidget/lib/translations/qtermwidget_si.ts @@ -0,0 +1,166 @@ + + + + + Konsole::Session + + + Bell in session '%1' + + + + + Session '%1' exited with status %2. + + + + + Session '%1' crashed. + + + + + Session '%1' exited unexpectedly. + + + + + Konsole::TerminalDisplay + + + Size: XXX x XXX + + + + + Size: %1 x %2 + + + + + Paste multiline text + + + + + Are you sure you want to paste this text? + + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + + + + + Konsole::Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + + + + + QMessageBox + + + Show Details... + + + + + QObject + + + + Un-named Color Scheme + + + + + Accessible Color Scheme + + + + + Open Link + + + + + Copy Link Address + + + + + Send Email To... + + + + + Copy Email Address + + + + + QTermWidget + + + Color Scheme Error + + + + + Cannot load color scheme: %1 + + + + + SearchBar + + + Match case + + + + + Regular expression + + + + + Highlight all matches + + + + + SearchBar + + + + + X + + + + + Find: + + + + + < + + + + + > + + + + + ... + + + + diff --git a/qtermwidget/lib/translations/qtermwidget_sk.ts b/qtermwidget/lib/translations/qtermwidget_sk.ts new file mode 100644 index 0000000..81d4212 --- /dev/null +++ b/qtermwidget/lib/translations/qtermwidget_sk.ts @@ -0,0 +1,166 @@ + + + + + Konsole::Session + + + Bell in session '%1' + Zvonček v relácií '%1' + + + + Session '%1' exited with status %2. + Relácia '%1' bola ukončená so stavom %2. + + + + Session '%1' crashed. + Relácia '%1' spadla. + + + + Session '%1' exited unexpectedly. + Relácia '%1' bola neočakávane ukončená. + + + + Konsole::TerminalDisplay + + + Size: XXX x XXX + Veľkosť: XXX x XXX + + + + Size: %1 x %2 + Veľkosť: %1 x %2 + + + + Paste multiline text + Prilepiť viacriadkový text + + + + Are you sure you want to paste this text? + Prajete si prilepiť tento text? + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>Výstup bol <a href="http://en.wikipedia.org/wiki/Flow_control">pozastavený</a> stlačením Ctrl+S. Stlačte<b>Ctrl+Q</b> pre opätovné spustenie.</qt> + + + + Konsole::Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + Prekladač klávesnice nie je dostupný. Chýbajú preto informácie potrebné na prevod kódov stlačených kláves na znaky poslané na terminál. + + + + QMessageBox + + + Show Details... + Zobraziť podrobnosti... + + + + QObject + + + + Un-named Color Scheme + Farebná schéma bez mena + + + + Accessible Color Scheme + Farebná schéma pre zjednodušený prístup + + + + Open Link + Otvoriť odkaz + + + + Copy Link Address + Kopírovať adresu odkazu + + + + Send Email To... + Poslať email na adresu... + + + + Copy Email Address + Kopírovať e-mailovú adresu + + + + QTermWidget + + + Color Scheme Error + Chyba vo farebnej schéme + + + + Cannot load color scheme: %1 + Nepodarilo sa načítať schému: %1 + + + + SearchBar + + + Match case + Rozlišovať veľké a malé písmená + + + + Regular expression + Regulárny výraz + + + + Highlight all matches + Zvýrazniť všetky zhody + + + + SearchBar + Hľadanie + + + + X + X + + + + Find: + Hľadať: + + + + < + < + + + + > + > + + + + ... + ... + + + diff --git a/qtermwidget/lib/translations/qtermwidget_tr.ts b/qtermwidget/lib/translations/qtermwidget_tr.ts new file mode 100644 index 0000000..b5672f1 --- /dev/null +++ b/qtermwidget/lib/translations/qtermwidget_tr.ts @@ -0,0 +1,166 @@ + + + + + Konsole::Session + + + Bell in session '%1' + '%1'. oturumda zil + + + + Session '%1' exited with status %2. + '%1' oturum %2 koduyla kapandı. + + + + Session '%1' crashed. + '%1' oturumu çöktü. + + + + Session '%1' exited unexpectedly. + '%1' oturumu beklenmedik şekilde kapandı. + + + + Konsole::TerminalDisplay + + + Size: XXX x XXX + Boyut: XXX x XXX + + + + Size: %1 x %2 + Boyut: %1 x %2 + + + + Paste multiline text + Çok satırlı metni yapıştır + + + + Are you sure you want to paste this text? + Bu metni yapıştırmak istediğinizden emin misiniz? + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>Çıktı, Ctrl+S'ye basılarak <a href="http://en.wikipedia.org/wiki/Flow_control">durduruldu</a>. Sürdürmek için <b>Ctrl+Q</b>'a basınız.</qt> + + + + Konsole::Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + Hiçbir klavye çeviricisi yok. Tuş vuruşlarını karaktere dönüştürüp uçbirime göndermek için gereken bilgi eksik. + + + + QMessageBox + + + Show Details... + Detayları göster... + + + + QObject + + + + Un-named Color Scheme + Adsız Renk Şeması + + + + Accessible Color Scheme + Erişilebilir Renk Şeması + + + + Open Link + Bağlantıyı Aç + + + + Copy Link Address + Bağlantı Adresini Kopyala + + + + Send Email To... + E-posta Gönder... + + + + Copy Email Address + E-posta Adresini Kopyala + + + + QTermWidget + + + Color Scheme Error + Renk Şeması Hatası + + + + Cannot load color scheme: %1 + Renk şeması yüklenemedi: %1 + + + + SearchBar + + + Match case + Büyük/küçük harf eşleştir + + + + Regular expression + Düzenli ifade + + + + Highlight all matches + Tüm eşleşenleri vurgula + + + + SearchBar + Arama Çubuğu + + + + X + X + + + + Find: + Bul: + + + + < + < + + + + > + > + + + + ... + ... + + + diff --git a/qtermwidget/lib/translations/qtermwidget_uk.ts b/qtermwidget/lib/translations/qtermwidget_uk.ts new file mode 100644 index 0000000..3e16d4d --- /dev/null +++ b/qtermwidget/lib/translations/qtermwidget_uk.ts @@ -0,0 +1,166 @@ + + + + + Konsole::Session + + + Bell in session '%1' + Сигнал у сеансі '%1' + + + + Session '%1' exited with status %2. + Сеанс '%1' завершився зі статусом %2. + + + + Session '%1' crashed. + Збій сеансу '%1'. + + + + Session '%1' exited unexpectedly. + Сеанс '%1' раптово завершився. + + + + Konsole::TerminalDisplay + + + Size: XXX x XXX + Розмір: XXX x XXX + + + + Size: %1 x %2 + Розмір: %1 x %2 + + + + Paste multiline text + Вставити багаторядковий текст + + + + Are you sure you want to paste this text? + Ви впевнені, що хочете вставити цей текст? + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>Виведення було <a href="http://en.wikipedia.org/wiki/Flow_control">призупинено</a> натисканням Ctrl+S. Натисніть <b>Ctrl+Q</b> для продовження.</qt> + + + + Konsole::Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + Не доступний транслятор клавіатури. Відсутня інформація, необхідна для перетворення натискання клавіш у символи та надсилання у термінал. + + + + QMessageBox + + + Show Details... + Показати подробиці... + + + + QObject + + + + Un-named Color Scheme + Колірна схема без назви + + + + Accessible Color Scheme + Колірна схема для людей з вадами зору + + + + Open Link + Відкрити посилання + + + + Copy Link Address + Копіювати адресу посилання + + + + Send Email To... + Надіслати е-поштою... + + + + Copy Email Address + Копіювати адресу е-пошти + + + + QTermWidget + + + Color Scheme Error + Помилка колірної схеми + + + + Cannot load color scheme: %1 + Не вдалося завантажити колірну схему: %1 + + + + SearchBar + + + Match case + Враховувати регістр + + + + Regular expression + Регулярний вираз + + + + Highlight all matches + Підсвітити всі збіги + + + + SearchBar + ПанельПошуку + + + + X + X + + + + Find: + Знайти: + + + + < + < + + + + > + > + + + + ... + ... + + + diff --git a/qtermwidget/lib/translations/qtermwidget_zh_CN.ts b/qtermwidget/lib/translations/qtermwidget_zh_CN.ts new file mode 100644 index 0000000..946393a --- /dev/null +++ b/qtermwidget/lib/translations/qtermwidget_zh_CN.ts @@ -0,0 +1,166 @@ + + + + + Konsole::Session + + + Bell in session '%1' + 在会话中响铃 '%1' + + + + Session '%1' exited with status %2. + 会话'%1' 以状态 %2 退出。 + + + + Session '%1' crashed. + 会话 '%1' 崩溃了。 + + + + Session '%1' exited unexpectedly. + 会话 '%1' 意外退出了。 + + + + Konsole::TerminalDisplay + + + Size: XXX x XXX + 大小: XXX x XXX + + + + Size: %1 x %2 + 大小: %1 x %2 + + + + Paste multiline text + 粘帖多行文本 + + + + Are you sure you want to paste this text? + 确定你想要粘贴此文本? + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>输出已被 Ctrl+S <a href="http://en.wikipedia.org/wiki/Flow_control">暂停</a>。按 <b>Ctrl+Q</b> 复原。</qt> + + + + Konsole::Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + 没有可用的键码转换表。找不到需要把按键转换至符号以传送至终端的信息。 + + + + QMessageBox + + + Show Details... + 显示详情... + + + + QObject + + + + Un-named Color Scheme + 未命名配色 + + + + Accessible Color Scheme + 可用配色 + + + + Open Link + 打开链接 + + + + Copy Link Address + 复制链接地址 + + + + Send Email To... + 发送邮件至... + + + + Copy Email Address + 复制邮件地址 + + + + QTermWidget + + + Color Scheme Error + 配色错误 + + + + Cannot load color scheme: %1 + 无法加载配色: %1 + + + + SearchBar + + + Match case + 匹配大小写 + + + + Regular expression + 正则表达式 + + + + Highlight all matches + 高亮所有匹配项 + + + + SearchBar + 搜索栏 + + + + X + + + + + Find: + 寻找: + + + + < + + + + + > + + + + + ... + + + + diff --git a/qtermwidget/lib/translations/qtermwidget_zh_TW.ts b/qtermwidget/lib/translations/qtermwidget_zh_TW.ts new file mode 100644 index 0000000..6f4c6af --- /dev/null +++ b/qtermwidget/lib/translations/qtermwidget_zh_TW.ts @@ -0,0 +1,166 @@ + + + + + Konsole::Session + + + Bell in session '%1' + 在會話中響鈴 '%1' + + + + Session '%1' exited with status %2. + 會話 '%1' 以狀態 %2 退出。 + + + + Session '%1' crashed. + 會話 '%1' 已崩潰。 + + + + Session '%1' exited unexpectedly. + 會話 '%1' 意外退出。 + + + + Konsole::TerminalDisplay + + + Size: XXX x XXX + 大小:XXX x XXX + + + + Size: %1 x %2 + 大小:%1 x %2 + + + + Paste multiline text + 粘貼多行文本 + + + + Are you sure you want to paste this text? + 你確定要粘貼這段文本嗎? + + + + <qt>Output has been <a href="http://en.wikipedia.org/wiki/Flow_control">suspended</a> by pressing Ctrl+S. Press <b>Ctrl+Q</b> to resume.</qt> + <qt>輸出已被Ctrl+S<a href="http://en.wikipedia.org/wiki/Flow_control">暫停</a>。按<b>Ctrl+Q</b>復原。</qt> + + + + Konsole::Vt102Emulation + + + No keyboard translator available. The information needed to convert key presses into characters to send to the terminal is missing. + 沒有可用的鍵碼轉換表。用來將按鍵轉換成終端機字元的資訊遺失。 + + + + QMessageBox + + + Show Details... + 展示細節 ... + + + + QObject + + + + Un-named Color Scheme + 未命名的配色 + + + + Accessible Color Scheme + 可用的配色 + + + + Open Link + 開啟連結 + + + + Copy Link Address + 複製網址 + + + + Send Email To... + 傳送郵件給… + + + + Copy Email Address + 複製信箱地址 + + + + QTermWidget + + + Color Scheme Error + 配色錯誤 + + + + Cannot load color scheme: %1 + 無法載入配色:%1 + + + + SearchBar + + + Match case + 符合大小寫 + + + + Regular expression + 正規表示式 + + + + Highlight all matches + 標亮所有相符的項目 + + + + SearchBar + 搜尋列 + + + + X + X + + + + Find: + 搜尋: + + + + < + < + + + + > + > + + + + ... + ... + + + diff --git a/qtermwidget/pyqt/project.py b/qtermwidget/pyqt/project.py new file mode 100644 index 0000000..11798c6 --- /dev/null +++ b/qtermwidget/pyqt/project.py @@ -0,0 +1,15 @@ +from pyqtbuild import PyQtBindings, PyQtProject + +class QTermWidget(PyQtProject): + def __init__(self): + super().__init__() + self.bindings_factories = [QTermWidgetBindings] + +class QTermWidgetBindings(PyQtBindings): + def __init__(self, project): + super().__init__(project, name='QTermWidget', sip_file='qtermwidget.sip', qmake_QT=['widgets']) + self._project = project + + def apply_user_defaults(self, tool): + self.libraries.append('qtermwidget5') + super().apply_user_defaults(tool) diff --git a/qtermwidget/pyqt/pyproject.toml b/qtermwidget/pyqt/pyproject.toml new file mode 100644 index 0000000..e6b33ed --- /dev/null +++ b/qtermwidget/pyqt/pyproject.toml @@ -0,0 +1,10 @@ +# https://www.riverbankcomputing.com/static/Docs/sip/index.html + +[build-system] +requires = ["sip", "PyQt-builder"] +build-backend = "sipbuild.api" + +[tool.sip.metadata] +name = "QTermWidget" +version = "1.3.0" +requires-dist = ["PyQt5"] diff --git a/qtermwidget/pyqt/sip/qtermwidget.sip b/qtermwidget/pyqt/sip/qtermwidget.sip new file mode 100644 index 0000000..21a10f8 --- /dev/null +++ b/qtermwidget/pyqt/sip/qtermwidget.sip @@ -0,0 +1,119 @@ +%Module(name=QTermWidget, use_limited_api=True) + +%ModuleHeaderCode +#pragma GCC visibility push(default) +%End + +%Import QtGui/QtGuimod.sip +%Import QtCore/QtCoremod.sip +%Import QtWidgets/QtWidgetsmod.sip + +class QTermWidget : QWidget { + +%TypeHeaderCode +#include +%End + +public: + enum ScrollBarPosition + { + NoScrollBar=0, + ScrollBarLeft=1, + ScrollBarRight=2 + }; + + enum class KeyboardCursorShape + { + BlockCursor=0, + UnderlineCursor=1, + IBeamCursor=2 + }; + + QTermWidget(int startnow = 1, QWidget *parent = 0); + ~QTermWidget(); + void startTerminalTeletype(); + QSize sizeHint() const; + void setTerminalSizeHint(bool on); + bool terminalSizeHint(); + void startShellProgram(); + int getShellPID(); + int getForegroundProcessId(); + void changeDir(const QString & dir); + void setTerminalFont(QFont &font); + QFont getTerminalFont(); + void setTerminalOpacity(qreal level); + void setEnvironment(const QStringList & environment); + void setShellProgram(const QString & progname); + void setWorkingDirectory(const QString & dir); + QString workingDirectory(); + void setArgs(QStringList & args); + void setTextCodec(QTextCodec *codec); + void setColorScheme(const QString & name); + QStringList getAvailableColorSchemes(); + static QStringList availableColorSchemes(); + static void addCustomColorSchemeDir(const QString& custom_dir); + void setHistorySize(int lines); + void setScrollBarPosition(ScrollBarPosition); + void scrollToEnd(); + void sendText(QString &text); + void setFlowControlEnabled(bool enabled); + bool flowControlEnabled(); + void setFlowControlWarningEnabled(bool enabled); + static QStringList availableKeyBindings(); + QString keyBindings(); + void setMotionAfterPasting(int); + int historyLinesCount(); + int screenColumnsCount(); + void setSelectionStart(int row, int column); + void setSelectionEnd(int row, int column); + void getSelectionStart(int& row, int& column); + void getSelectionEnd(int& row, int& column); + QString selectedText(bool preserveLineBreaks = true); + void setMonitorActivity(bool); + void setMonitorSilence(bool); + void setSilenceTimeout(int seconds); + int getPtySlaveFd() const; + void setKeyboardCursorShape(KeyboardCursorShape shape); + void setAutoClose(bool); + QString title() const; + QString icon() const; +signals: + void finished(); + void copyAvailable(bool); + void termGetFocus(); + void termLostFocus(); + void termKeyPressed(QKeyEvent *); + void urlActivated(const QUrl&, bool fromContextMenu); + void bell(const QString& message); + void activity(); + void silence(); + void sendData(const char *,int); + void titleChanged(); + void receivedData(const QString &text); + void profileChanged(const QString & profile); +public slots: + void copyClipboard(); + void pasteClipboard(); + void pasteSelection(); + void zoomIn(); + void zoomOut(); + void setSize(const QSize &); + void setKeyBindings(const QString & kb); + void clear(); + void toggleShowSearchBar(); +protected: + virtual void resizeEvent(QResizeEvent *); +protected slots: + void sessionFinished(); + void selectionChanged(bool textSelected); +private: + void search(bool forwards, bool next); + void setZoom(int step); + void init(int startnow); +private slots: + void find(); + void findNext(); + void findPrevious(); + void matchFound(int startColumn, int startLine, int endColumn, int endLine); + void noMatchFound(); +}; diff --git a/qtermwidget/qtermwidget.pro b/qtermwidget/qtermwidget.pro deleted file mode 100644 index a4c19e5..0000000 --- a/qtermwidget/qtermwidget.pro +++ /dev/null @@ -1,4 +0,0 @@ -TEMPLATE = subdirs -SUBDIRS = src - -OPTIONS += ordered diff --git a/qtermwidget/qtermwidget.spec b/qtermwidget/qtermwidget.spec new file mode 100644 index 0000000..96cff22 --- /dev/null +++ b/qtermwidget/qtermwidget.spec @@ -0,0 +1,100 @@ +# norootforbuild + +%define libname libqtermwidget0 + +Name: qtermwidget +Summary: Qt4 terminal widget +Version: 0.2.0 +Release: 1 +License: GPL +Source: %{name}-%{version}.tar.bz2 +Group: Utility +URL: https://github.com/qterminal +Vendor: petr@yarpen.cz + + +%if 0%{?fedora_version} + %define breq qt4-devel + %define pref %{buildroot}/usr +%endif +%if 0%{?mandriva_version} + %define breq libqt4-devel + %define pref %{buildroot}/usr +%endif +%if 0%{?suse_version} + %define breq libqt4-devel + %define pref %{_prefix} +%endif + + +BuildRequires: gcc-c++, %{breq}, cmake +BuildRoot: %{_tmppath}/%{name}-%{version}-build +Prefix: %{_prefix} + +%description +QTermWidget is an opensource project based on KDE4 Konsole application. The main goal of this project is to provide unicode-enabled, embeddable QT4 widget for using as a built-in console (or terminal emulation widget). +Of course I`m aware about embedding abilities of original Konsole, but once I had Qt without KDE, and it was a serious problem. I decided not to rely on a chance. I could not find any interesting related project, so I had to write it. +The original Konsole`s code was rewritten entirely with QT4 only; also I have to include in the project some parts of code from kde core library. All code dealing with user interface parts and session management was removed (maybe later I bring it back somehow), and the result is quite useful, I suppose. +This library was compiled and tested on three linux systems, based on 2.4.32, 2.6.20, 2.6.23 kernels, x86 and amd64. There is also a sample application provided for quick start. + +%package -n %{libname} +Summary: Qt4 terminal widget - base package +Group: "Development/Libraries/C and C++" +%description -n %{libname} +QTermWidget is an opensource project based on KDE4 Konsole application. +The main goal of this project is to provide unicode-enabled, embeddable +QT4 widget for using as a built-in console (or terminal emulation widget). + +%package devel +Summary: Qt4 terminal widget - development package +Group: "Development/Libraries/C and C++" +Requires: %{libname} +%description devel +Development package for QTermWidget. Contains headers and dev-libs. + +%prep +%setup + +%build +cmake \ + -DCMAKE_C_FLAGS="%{optflags}" \ + -DCMAKE_CXX_FLAGS="%{optflags}" \ + -DCMAKE_BUILD_TYPE=Debug \ + -DCMAKE_INSTALL_PREFIX=%{pref} \ + %{_builddir}/%{name}-%{version} + +%{__make} %{?jobs:-j%jobs} + + +%install +%makeinstall + + +%clean +%{__rm} -rf %{buildroot} + +%post -n %{libname} +ldconfig + +%postun -n %{libname} +ldconfig + +%files -n %{libname} +%defattr(-,root,root,-) +%doc AUTHORS LICENSE Changelog INSTALL README +%{_libdir}/lib%{name}.so.%{version} +%{_datadir}/%{name} +%{_datadir}/%{name}/* + +%files devel +%defattr(-,root,root,-) +%{_includedir}/*.h +%{_libdir}/*.so +%{_libdir}/*.so.0 + +%changelog +* Mon Oct 29 2010 Petr Vanek 0.2 +- version bump, cmake builds + +* Sat Jul 26 2008 TI_Eugene 0.100 +- Initial build diff --git a/qtermwidget/src/ColorTables.h b/qtermwidget/src/ColorTables.h deleted file mode 100644 index 321d6db..0000000 --- a/qtermwidget/src/ColorTables.h +++ /dev/null @@ -1,58 +0,0 @@ -#ifndef _COLOR_TABLE_H -#define _COLOR_TABLE_H - -#include "CharacterColor.h" - -using namespace Konsole; - -static const ColorEntry whiteonblack_color_table[TABLE_COLORS] = -{ - // normal - ColorEntry(QColor(0xFF,0xFF,0xFF), 0, 0 ), ColorEntry( QColor(0x00,0x00,0x00), 1, 0 ), // Dfore, Dback - ColorEntry(QColor(0x00,0x00,0x00), 0, 0 ), ColorEntry( QColor(0xB2,0x18,0x18), 0, 0 ), // Black, Red - ColorEntry(QColor(0x18,0xB2,0x18), 0, 0 ), ColorEntry( QColor(0xB2,0x68,0x18), 0, 0 ), // Green, Yellow - ColorEntry(QColor(0x18,0x18,0xB2), 0, 0 ), ColorEntry( QColor(0xB2,0x18,0xB2), 0, 0 ), // Blue, Magenta - ColorEntry(QColor(0x18,0xB2,0xB2), 0, 0 ), ColorEntry( QColor(0xB2,0xB2,0xB2), 0, 0 ), // Cyan, White - // intensiv - ColorEntry(QColor(0x00,0x00,0x00), 0, 1 ), ColorEntry( QColor(0xFF,0xFF,0xFF), 1, 0 ), - ColorEntry(QColor(0x68,0x68,0x68), 0, 0 ), ColorEntry( QColor(0xFF,0x54,0x54), 0, 0 ), - ColorEntry(QColor(0x54,0xFF,0x54), 0, 0 ), ColorEntry( QColor(0xFF,0xFF,0x54), 0, 0 ), - ColorEntry(QColor(0x54,0x54,0xFF), 0, 0 ), ColorEntry( QColor(0xFF,0x54,0xFF), 0, 0 ), - ColorEntry(QColor(0x54,0xFF,0xFF), 0, 0 ), ColorEntry( QColor(0xFF,0xFF,0xFF), 0, 0 ) -}; - -static const ColorEntry greenonblack_color_table[TABLE_COLORS] = -{ - ColorEntry(QColor( 24, 240, 24), 0, 0), ColorEntry(QColor( 0, 0, 0), 1, 0), - ColorEntry(QColor( 0, 0, 0), 0, 0), ColorEntry(QColor( 178, 24, 24), 0, 0), - ColorEntry(QColor( 24, 178, 24), 0, 0), ColorEntry(QColor( 178, 104, 24), 0, 0), - ColorEntry(QColor( 24, 24, 178), 0, 0), ColorEntry(QColor( 178, 24, 178), 0, 0), - ColorEntry(QColor( 24, 178, 178), 0, 0), ColorEntry(QColor( 178, 178, 178), 0, 0), - // intensive colors - ColorEntry(QColor( 24, 240, 24), 0, 1 ), ColorEntry(QColor( 0, 0, 0), 1, 0 ), - ColorEntry(QColor( 104, 104, 104), 0, 0 ), ColorEntry(QColor( 255, 84, 84), 0, 0 ), - ColorEntry(QColor( 84, 255, 84), 0, 0 ), ColorEntry(QColor( 255, 255, 84), 0, 0 ), - ColorEntry(QColor( 84, 84, 255), 0, 0 ), ColorEntry(QColor( 255, 84, 255), 0, 0 ), - ColorEntry(QColor( 84, 255, 255), 0, 0 ), ColorEntry(QColor( 255, 255, 255), 0, 0 ) -}; - -static const ColorEntry blackonlightyellow_color_table[TABLE_COLORS] = -{ - ColorEntry(QColor( 0, 0, 0), 0, 0), ColorEntry(QColor( 255, 255, 221), 1, 0), - ColorEntry(QColor( 0, 0, 0), 0, 0), ColorEntry(QColor( 178, 24, 24), 0, 0), - ColorEntry(QColor( 24, 178, 24), 0, 0), ColorEntry(QColor( 178, 104, 24), 0, 0), - ColorEntry(QColor( 24, 24, 178), 0, 0), ColorEntry(QColor( 178, 24, 178), 0, 0), - ColorEntry(QColor( 24, 178, 178), 0, 0), ColorEntry(QColor( 178, 178, 178), 0, 0), - ColorEntry(QColor( 0, 0, 0), 0, 1), ColorEntry(QColor( 255, 255, 221), 1, 0), - ColorEntry(QColor(104, 104, 104), 0, 0), ColorEntry(QColor( 255, 84, 84), 0, 0), - ColorEntry(QColor( 84, 255, 84), 0, 0), ColorEntry(QColor( 255, 255, 84), 0, 0), - ColorEntry(QColor( 84, 84, 255), 0, 0), ColorEntry(QColor( 255, 84, 255), 0, 0), - ColorEntry(QColor( 84, 255, 255), 0, 0), ColorEntry(QColor( 255, 255, 255), 0, 0) -}; - - - - - -#endif - diff --git a/qtermwidget/src/LineFont.h b/qtermwidget/src/LineFont.h deleted file mode 100644 index 9b64143..0000000 --- a/qtermwidget/src/LineFont.h +++ /dev/null @@ -1,21 +0,0 @@ -// WARNING: Autogenerated by "fontembedder ./linefont.src". -// You probably do not want to hand-edit this! - -static const quint32 LineChars[] = { - 0x00007c00, 0x000fffe0, 0x00421084, 0x00e739ce, 0x00000000, 0x00000000, 0x00000000, 0x00000000, - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00427000, 0x004e7380, 0x00e77800, 0x00ef7bc0, - 0x00421c00, 0x00439ce0, 0x00e73c00, 0x00e7bde0, 0x00007084, 0x000e7384, 0x000079ce, 0x000f7bce, - 0x00001c84, 0x00039ce4, 0x00003dce, 0x0007bdee, 0x00427084, 0x004e7384, 0x004279ce, 0x00e77884, - 0x00e779ce, 0x004f7bce, 0x00ef7bc4, 0x00ef7bce, 0x00421c84, 0x00439ce4, 0x00423dce, 0x00e73c84, - 0x00e73dce, 0x0047bdee, 0x00e7bde4, 0x00e7bdee, 0x00427c00, 0x0043fce0, 0x004e7f80, 0x004fffe0, - 0x004fffe0, 0x00e7fde0, 0x006f7fc0, 0x00efffe0, 0x00007c84, 0x0003fce4, 0x000e7f84, 0x000fffe4, - 0x00007dce, 0x0007fdee, 0x000f7fce, 0x000fffee, 0x00427c84, 0x0043fce4, 0x004e7f84, 0x004fffe4, - 0x00427dce, 0x00e77c84, 0x00e77dce, 0x0047fdee, 0x004e7fce, 0x00e7fde4, 0x00ef7f84, 0x004fffee, - 0x00efffe4, 0x00e7fdee, 0x00ef7fce, 0x00efffee, 0x00000000, 0x00000000, 0x00000000, 0x00000000, - 0x000f83e0, 0x00a5294a, 0x004e1380, 0x00a57800, 0x00ad0bc0, 0x004390e0, 0x00a53c00, 0x00a5a1e0, - 0x000e1384, 0x0000794a, 0x000f0b4a, 0x000390e4, 0x00003d4a, 0x0007a16a, 0x004e1384, 0x00a5694a, - 0x00ad2b4a, 0x004390e4, 0x00a52d4a, 0x00a5a16a, 0x004f83e0, 0x00a57c00, 0x00ad83e0, 0x000f83e4, - 0x00007d4a, 0x000f836a, 0x004f93e4, 0x00a57d4a, 0x00ad836a, 0x00000000, 0x00000000, 0x00000000, - 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00001c00, 0x00001084, 0x00007000, 0x00421000, - 0x00039ce0, 0x000039ce, 0x000e7380, 0x00e73800, 0x000e7f80, 0x00e73884, 0x0003fce0, 0x004239ce -}; diff --git a/qtermwidget/src/Pty.cpp b/qtermwidget/src/Pty.cpp deleted file mode 100644 index 144e5e2..0000000 --- a/qtermwidget/src/Pty.cpp +++ /dev/null @@ -1,320 +0,0 @@ -/* - This file is part of Konsole, an X terminal. - Copyright (C) 1997,1998 by Lars Doelle - - Rewritten for QT4 by e_k , Copyright (C)2008 - - 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" - -// System -#include -#include -#include -#include -#include - -// Qt -#include - -// KDE -//#include -//#include -//#include -#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 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/qtermwidget/src/README b/qtermwidget/src/README deleted file mode 100644 index 1801361..0000000 --- a/qtermwidget/src/README +++ /dev/null @@ -1,7 +0,0 @@ -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/qtermwidget/src/Screen.cpp b/qtermwidget/src/Screen.cpp deleted file mode 100644 index ead0066..0000000 --- a/qtermwidget/src/Screen.cpp +++ /dev/null @@ -1,1567 +0,0 @@ -/* - This file is part of Konsole, an X terminal. - Copyright (C) 1997,1998 by Lars Doelle - - Rewritten for QT4 by e_k , Copyright (C)2008 - - 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 -#include -#include -#include -#include -#include - -// Qt -#include -#include - -// 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 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("< 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 0) && (ir &= ~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 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 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& 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 - Copyright (C) 1997,1998 by Lars Doelle - - Rewritten for QT4 by e_k , Copyright (C)2008 - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (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" - -// Standard -#include -#include - -// Qt -#include -#include -#include -#include -#include -#include -#include - -#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 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 "<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 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 = (""); - 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 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 masterIter(masters()); - - while ( masterIter.hasNext() ) - connectPair(masterIter.next(),session); -} -void SessionGroup::removeSession(Session* session) -{ - setMasterStatus(session,false); - - QListIterator masterIter(masters()); - - while ( masterIter.hasNext() ) - disconnectPair(masterIter.next(),session); - - _sessions.remove(session); -} -void SessionGroup::setMasterMode(int mode) -{ - _masterMode = mode; - - connectAll(false); - connectAll(true); -} -QList SessionGroup::masters() const -{ - return _sessions.keys(true); -} -void SessionGroup::connectAll(bool connect) -{ - QListIterator masterIter(masters()); - - while ( masterIter.hasNext() ) - { - Session* master = masterIter.next(); - - QListIterator 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 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/qtermwidget/src/Session.h b/qtermwidget/src/Session.h deleted file mode 100644 index 7b2ae25..0000000 --- a/qtermwidget/src/Session.h +++ /dev/null @@ -1,621 +0,0 @@ -/* - This file is part of Konsole, an X terminal. - - Copyright (C) 2007 by Robert Knight - Copyright (C) 1997,1998 by Lars Doelle - - Rewritten for QT4 by e_k , Copyright (C)2008 - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA - 02110-1301 USA. -*/ - -#ifndef SESSION_H -#define SESSION_H - -// Qt -#include -#include -#include - -// Konsole -#include "History.h" - -class KProcess; - -namespace Konsole -{ - -class Emulation; -class Pty; -class TerminalDisplay; -//class ZModemDialog; - -/** - * Represents a terminal session consisting of a pseudo-teletype and a terminal emulation. - * The pseudo-teletype (or PTY) handles I/O between the terminal process and Konsole. - * The terminal emulation ( Emulation and subclasses ) processes the output stream from the - * PTY and produces a character image which is then shown on views connected to the session. - * - * Each Session can be connected to one or more views by using the addView() method. - * The attached views can then display output from the program running in the terminal - * or send input to the program in the terminal in the form of keypresses and mouse - * activity. - */ -class Session : public QObject -{ -Q_OBJECT - -public: - Q_PROPERTY(QString name READ nameTitle) - Q_PROPERTY(int processId READ processId) - Q_PROPERTY(QString keyBindings READ keyBindings WRITE setKeyBindings) - Q_PROPERTY(QSize size READ size WRITE setSize) - - /** - * Constructs a new session. - * - * To start the terminal process, call the run() method, - * after specifying the program and arguments - * using setProgram() and setArguments() - * - * If no program or arguments are specified explicitly, the Session - * falls back to using the program specified in the SHELL environment - * variable. - */ - Session(); - ~Session(); - - /** - * Returns true if the session is currently running. This will be true - * after run() has been called successfully. - */ - bool isRunning() const; - - /** - * Sets the profile associated with this session. - * - * @param profileKey A key which can be used to obtain the current - * profile settings from the SessionManager - */ - void setProfileKey(const QString& profileKey); - /** - * Returns the profile key associated with this session. - * This can be passed to the SessionManager to obtain the current - * profile settings. - */ - QString profileKey() const; - - /** - * Adds a new view for this session. - * - * The viewing widget will display the output from the terminal and - * input from the viewing widget (key presses, mouse activity etc.) - * will be sent to the terminal. - * - * Views can be removed using removeView(). The session is automatically - * closed when the last view is removed. - */ - void addView(TerminalDisplay* widget); - /** - * Removes a view from this session. When the last view is removed, - * the session will be closed automatically. - * - * @p widget will no longer display output from or send input - * to the terminal - */ - void removeView(TerminalDisplay* widget); - - /** - * Returns the views connected to this session - */ - QList views() const; - - /** - * Returns the terminal emulation instance being used to encode / decode - * characters to / from the process. - */ - Emulation* emulation() const; - - /** - * Returns the environment of this session as a list of strings like - * VARIABLE=VALUE - */ - QStringList environment() const; - /** - * Sets the environment for this session. - * @p environment should be a list of strings like - * VARIABLE=VALUE - */ - void setEnvironment(const QStringList& environment); - - /** Returns the unique ID for this session. */ - int sessionId() const; - - /** - * Return the session title set by the user (ie. the program running - * in the terminal), or an empty string if the user has not set a custom title - */ - QString userTitle() const; - - /** - * This enum describes the contexts for which separate - * tab title formats may be specified. - */ - enum TabTitleContext - { - /** Default tab title format */ - LocalTabTitle, - /** - * Tab title format used session currently contains - * a connection to a remote computer (via SSH) - */ - RemoteTabTitle - }; - /** - * Sets the format used by this session for tab titles. - * - * @param context The context whoose format should be set. - * @param format The tab title format. This may be a mixture - * of plain text and dynamic elements denoted by a '%' character - * followed by a letter. (eg. %d for directory). The dynamic - * elements available depend on the @p context - */ - void setTabTitleFormat(TabTitleContext context , const QString& format); - /** Returns the format used by this session for tab titles. */ - QString tabTitleFormat(TabTitleContext context) const; - - - /** Returns the arguments passed to the shell process when run() is called. */ - QStringList arguments() const; - /** Returns the program name of the shell process started when run() is called. */ - QString program() const; - - /** - * Sets the command line arguments which the session's program will be passed when - * run() is called. - */ - void setArguments(const QStringList& arguments); - /** Sets the program to be executed when run() is called. */ - void setProgram(const QString& program); - - /** Returns the session's current working directory. */ - QString initialWorkingDirectory() { return _initialWorkingDir; } - - /** - * Sets the initial working directory for the session when it is run - * This has no effect once the session has been started. - */ - void setInitialWorkingDirectory( const QString& dir ); - - /** - * Sets the type of history store used by this session. - * Lines of output produced by the terminal are added - * to the history store. The type of history store - * used affects the number of lines which can be - * remembered before they are lost and the storage - * (in memory, on-disk etc.) used. - */ - void setHistoryType(const HistoryType& type); - /** - * Returns the type of history store used by this session. - */ - const HistoryType& historyType() const; - /** - * Clears the history store used by this session. - */ - void clearHistory(); - - /** - * Enables monitoring for activity in the session. - * This will cause notifySessionState() to be emitted - * with the NOTIFYACTIVITY state flag when output is - * received from the terminal. - */ - void setMonitorActivity(bool); - /** Returns true if monitoring for activity is enabled. */ - bool isMonitorActivity() const; - - /** - * Enables monitoring for silence in the session. - * This will cause notifySessionState() to be emitted - * with the NOTIFYSILENCE state flag when output is not - * received from the terminal for a certain period of - * time, specified with setMonitorSilenceSeconds() - */ - void setMonitorSilence(bool); - /** - * Returns true if monitoring for inactivity (silence) - * in the session is enabled. - */ - bool isMonitorSilence() const; - /** See setMonitorSilence() */ - void setMonitorSilenceSeconds(int seconds); - - /** - * Sets the key bindings used by this session. The bindings - * specify how input key sequences are translated into - * the character stream which is sent to the terminal. - * - * @param id The name of the key bindings to use. The - * names of available key bindings can be determined using the - * KeyboardTranslatorManager class. - */ - void setKeyBindings(const QString& id); - /** Returns the name of the key bindings used by this session. */ - QString keyBindings() const; - - /** - * This enum describes the available title roles. - */ - enum TitleRole - { - /** The name of the session. */ - NameRole, - /** The title of the session which is displayed in tabs etc. */ - DisplayedTitleRole - }; - - /** Sets the session's title for the specified @p role to @p title. */ - void setTitle(TitleRole role , const QString& title); - /** Returns the session's title for the specified @p role. */ - QString title(TitleRole role) const; - /** Convenience method used to read the name property. Returns title(Session::NameRole). */ - QString nameTitle() const { return title(Session::NameRole); } - - /** Sets the name of the icon associated with this session. */ - void setIconName(const QString& iconName); - /** Returns the name of the icon associated with this session. */ - QString iconName() const; - - /** Sets the text of the icon associated with this session. */ - void setIconText(const QString& iconText); - /** Returns the text of the icon associated with this session. */ - QString iconText() const; - - /** Specifies whether a utmp entry should be created for the pty used by this session. */ - void setAddToUtmp(bool); - - /** Sends the specified @p signal to the terminal process. */ - bool sendSignal(int signal); - - /** - * Specifies whether to close the session automatically when the terminal - * process terminates. - */ - void setAutoClose(bool b) { _autoClose = b; } - - /** - * Sets whether flow control is enabled for this terminal - * session. - */ - void setFlowControlEnabled(bool enabled); - - /** Returns whether flow control is enabled for this terminal session. */ - bool flowControlEnabled() const; - - /** - * Sends @p text to the current foreground terminal program. - */ - void sendText(const QString& text) const; - - /** - * Returns the process id of the terminal process. - * This is the id used by the system API to refer to the process. - */ - int processId() const; - - /** - * Returns the process id of the terminal's foreground process. - * This is initially the same as processId() but can change - * as the user starts other programs inside the terminal. - */ - int foregroundProcessId() const; - - /** Returns the terminal session's window size in lines and columns. */ - QSize size(); - /** - * Emits a request to resize the session to accommodate - * the specified window size. - * - * @param size The size in lines and columns to request. - */ - void setSize(const QSize& size); - - /** Sets the text codec used by this session's terminal emulation. */ - void setCodec(QTextCodec* codec); - - /** - * Sets whether the session has a dark background or not. The session - * uses this information to set the COLORFGBG variable in the process's - * environment, which allows the programs running in the terminal to determine - * whether the background is light or dark and use appropriate colors by default. - * - * This has no effect once the session is running. - */ - void setDarkBackground(bool darkBackground); - /** - * Returns true if the session has a dark background. - * See setDarkBackground() - */ - bool hasDarkBackground() const; - - /** - * Attempts to get the shell program to redraw the current display area. - * This can be used after clearing the screen, for example, to get the - * shell to redraw the prompt line. - */ - void refresh(); - -// void startZModem(const QString &rz, const QString &dir, const QStringList &list); -// void cancelZModem(); -// bool isZModemBusy() { return _zmodemBusy; } - -public slots: - - /** - * Starts the terminal session. - * - * This creates the terminal process and connects the teletype to it. - */ - void run(); - - /** - * Closes the terminal session. This sends a hangup signal - * (SIGHUP) to the terminal process and causes the done(Session*) - * signal to be emitted. - */ - void close(); - - /** - * Changes the session title or other customizable aspects of the terminal - * emulation display. For a list of what may be changed see the - * Emulation::titleChanged() signal. - */ - void setUserTitle( int, const QString &caption ); - -signals: - - /** Emitted when the terminal process starts. */ - void started(); - - /** - * Emitted when the terminal process exits. - */ - void finished(); - - /** - * Emitted when output is received from the terminal process. - */ - void receivedData( const QString& text ); - - /** Emitted when the session's title has changed. */ - void titleChanged(); - - /** Emitted when the session's profile has changed. */ - void profileChanged(const QString& profile); - - /** - * Emitted when the activity state of this session changes. - * - * @param state The new state of the session. This may be one - * of NOTIFYNORMAL, NOTIFYSILENCE or NOTIFYACTIVITY - */ - void stateChanged(int state); - - /** Emitted when a bell event occurs in the session. */ - void bellRequest( const QString& message ); - - /** - * Requests that the color the text for any tabs associated with - * this session should be changed; - * - * TODO: Document what the parameter does - */ - void changeTabTextColorRequest(int); - - /** - * Requests that the background color of views on this session - * should be changed. - */ - void changeBackgroundColorRequest(const QColor&); - - /** TODO: Document me. */ - void openUrlRequest(const QString& url); - - /** TODO: Document me. */ -// void zmodemDetected(); - - /** - * Emitted when the terminal process requests a change - * in the size of the terminal window. - * - * @param size The requested window size in terms of lines and columns. - */ - void resizeRequest(const QSize& size); - - /** - * Emitted when a profile change command is received from the terminal. - * - * @param text The text of the command. This is a string of the form - * "PropertyName=Value;PropertyName=Value ..." - */ - void profileChangeCommandReceived(const QString& text); - - /** - * Emitted when the flow control state changes. - * - * @param enabled True if flow control is enabled or false otherwise. - */ - void flowControlEnabledChanged(bool enabled); - -private slots: - void done(int); - -// void fireZModemDetected(); - - void onReceiveBlock( const char* buffer, int len ); - void monitorTimerDone(); - - void onViewSizeChange(int height, int width); - void onEmulationSizeChange(int lines , int columns); - - void activityStateSet(int); - - //automatically detach views from sessions when view is destroyed - void viewDestroyed(QObject* view); - -// void zmodemReadStatus(); -// void zmodemReadAndSendBlock(); -// void zmodemRcvBlock(const char *data, int len); -// void zmodemFinished(); - -private: - - void updateTerminalSize(); - WId windowId() const; - - int _uniqueIdentifier; - - Pty* _shellProcess; - Emulation* _emulation; - - QList _views; - - bool _monitorActivity; - bool _monitorSilence; - bool _notifiedActivity; - bool _masterMode; - bool _autoClose; - bool _wantedClose; - QTimer* _monitorTimer; - - int _silenceSeconds; - - QString _nameTitle; - QString _displayTitle; - QString _userTitle; - - QString _localTabTitleFormat; - QString _remoteTabTitleFormat; - - QString _iconName; - QString _iconText; // as set by: echo -en '\033]1;IconText\007 - bool _addToUtmp; - bool _flowControl; - bool _fullScripting; - - QString _program; - QStringList _arguments; - - QStringList _environment; - int _sessionId; - - QString _initialWorkingDir; - - // ZModem -// bool _zmodemBusy; -// KProcess* _zmodemProc; -// ZModemDialog* _zmodemProgress; - - // Color/Font Changes by ESC Sequences - - QColor _modifiedBackground; // as set by: echo -en '\033]11;Color\007 - - QString _profileKey; - - bool _hasDarkBackground; - - static int lastSessionId; - -}; - -/** - * Provides a group of sessions which is divided into master and slave sessions. - * Activity in master sessions can be propagated to all sessions within the group. - * The type of activity which is propagated and method of propagation is controlled - * by the masterMode() flags. - */ -class SessionGroup : public QObject -{ -Q_OBJECT - -public: - /** Constructs an empty session group. */ - SessionGroup(); - /** Destroys the session group and removes all connections between master and slave sessions. */ - ~SessionGroup(); - - /** Adds a session to the group. */ - void addSession( Session* session ); - /** Removes a session from the group. */ - void removeSession( Session* session ); - - /** Returns the list of sessions currently in the group. */ - QList sessions() const; - - /** - * Sets whether a particular session is a master within the group. - * Changes or activity in the group's master sessions may be propagated - * to all the sessions in the group, depending on the current masterMode() - * - * @param session The session whoose master status should be changed. - * @param master True to make this session a master or false otherwise - */ - void setMasterStatus( Session* session , bool master ); - /** Returns the master status of a session. See setMasterStatus() */ - bool masterStatus( Session* session ) const; - - /** - * This enum describes the options for propagating certain activity or - * changes in the group's master sessions to all sessions in the group. - */ - enum MasterMode - { - /** - * Any input key presses in the master sessions are sent to all - * sessions in the group. - */ - CopyInputToAll = 1 - }; - - /** - * Specifies which activity in the group's master sessions is propagated - * to all sessions in the group. - * - * @param mode A bitwise OR of MasterMode flags. - */ - void setMasterMode( int mode ); - /** - * Returns a bitwise OR of the active MasterMode flags for this group. - * See setMasterMode() - */ - int masterMode() const; - -private: - void connectPair(Session* master , Session* other); - void disconnectPair(Session* master , Session* other); - void connectAll(bool connect); - QList masters() const; - - // maps sessions to their master status - QHash _sessions; - - int _masterMode; -}; - -} - -#endif diff --git a/qtermwidget/src/ShellCommand.cpp b/qtermwidget/src/ShellCommand.cpp deleted file mode 100644 index 764dd66..0000000 --- a/qtermwidget/src/ShellCommand.cpp +++ /dev/null @@ -1,168 +0,0 @@ -/* - Copyright (C) 2007 by Robert Knight - - Rewritten for QT4 by e_k , Copyright (C)2008 - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (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 - - -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/qtermwidget/src/TerminalCharacterDecoder.cpp b/qtermwidget/src/TerminalCharacterDecoder.cpp deleted file mode 100644 index 18571d9..0000000 --- a/qtermwidget/src/TerminalCharacterDecoder.cpp +++ /dev/null @@ -1,227 +0,0 @@ -/* - This file is part of Konsole, an X terminal. - - Copyright (C) 2006 by Robert Knight - - Rewritten for QT4 by e_k , Copyright (C)2008 - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU 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 - - -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') - 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("
    "); - - *_output << text; -} - -void HTMLDecoder::openSpan(QString& text , const QString& style) -{ - text.append( QString("").arg(style) ); -} - -void HTMLDecoder::closeSpan(QString& text) -{ - text.append(""); -} - -void HTMLDecoder::setColorTable(const ColorEntry* table) -{ - _colorTable = table; -} diff --git a/qtermwidget/src/k3process.cpp b/qtermwidget/src/k3process.cpp deleted file mode 100644 index 0f36a70..0000000 --- a/qtermwidget/src/k3process.cpp +++ /dev/null @@ -1,1054 +0,0 @@ -/* - This file is part of the KDE libraries - Copyright (C) 1997 Christian Czezatke (e9025461@student.tuwien.ac.at) - - Rewritten for QT4 by e_k , Copyright (C)2008 - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - - -#include "k3process.h" -//#include - -#include "k3processcontroller.h" -#include "kpty.h" - -#ifdef __osf__ -#define _OSF_SOURCE -#include -#endif - -#ifdef _AIX -#define _ALL_SOURCE -#endif - -#include -#include - -#include -#include -#include -#include -#include - -#ifdef HAVE_SYS_SELECT_H -#include -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -//#include -//#include -//#include - - - -////////////////// -// private data // -////////////////// - -class K3ProcessPrivate { -public: - K3ProcessPrivate() : - usePty(K3Process::NoCommunication), - addUtmp(false), useShell(false), - pty(0), - priority(0) - { - } - - K3Process::Communication usePty; - bool addUtmp : 1; - bool useShell : 1; - - KPty *pty; - - int priority; - - QMap env; - QString wd; - QByteArray shell; - QByteArray executable; -}; - -///////////////////////////// -// public member functions // -///////////////////////////// - -K3Process::K3Process( QObject* parent ) - : QObject( parent ), - run_mode(NotifyOnExit), - runs(false), - pid_(0), - status(0), - keepPrivs(false), - innot(0), - outnot(0), - errnot(0), - communication(NoCommunication), - input_data(0), - input_sent(0), - input_total(0), - d(new K3ProcessPrivate) -{ - K3ProcessController::ref(); - K3ProcessController::instance()->addKProcess(this); - - - out[0] = out[1] = -1; - in[0] = in[1] = -1; - err[0] = err[1] = -1; -} - -void -K3Process::setEnvironment(const QString &name, const QString &value) -{ - d->env.insert(name, value); -} - -void -K3Process::setWorkingDirectory(const QString &dir) -{ - d->wd = dir; -} - -void -K3Process::setupEnvironment() -{ - QMap::Iterator it; - for(it = d->env.begin(); it != d->env.end(); ++it) - { - setenv(QFile::encodeName(it.key()).data(), - QFile::encodeName(it.value()).data(), 1); - } - if (!d->wd.isEmpty()) - { - 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(malloc( 4 * sizeof(char *))); - arglist[0] = d->shell.data(); - arglist[1] = (char *) "-c"; - arglist[2] = shellCmd.data(); - arglist[3] = 0; - } - else - { - arglist = static_cast(malloc( (n + 1) * sizeof(char *))); - for (uint i = 0; i < n; i++) - arglist[i] = arguments[i].data(); - arglist[n] = 0; - } - - run_mode = runmode; - - if (!setupCommunication(comm)) - { - qDebug() << "Could not setup Communication!" << endl; - free(arglist); - return false; - } - - // We do this in the parent because if we do it in the child process - // gdb gets confused when the application runs from gdb. -#ifdef HAVE_INITGROUPS - struct passwd *pw = geteuid() ? 0 : getpwuid(getuid()); -#endif - - int fd[2]; - if (pipe(fd)) - fd[0] = fd[1] = -1; // Pipe failed.. continue - - // we don't use vfork() because - // - it has unclear semantics and is not standardized - // - we do way too much magic in the child - pid_ = fork(); - if (pid_ == 0) { - // The child process - - close(fd[0]); - // Closing of fd[1] indicates that the execvp() succeeded! - fcntl(fd[1], F_SETFD, FD_CLOEXEC); - - if (!commSetupDoneC()) - qDebug() << "Could not finish comm setup in child!" << endl; - - // reset all signal handlers - struct sigaction act; - sigemptyset(&act.sa_mask); - act.sa_handler = SIG_DFL; - act.sa_flags = 0; - for (int sig = 1; sig < NSIG; sig++) - sigaction(sig, &act, 0L); - - if (d->priority) - setpriority(PRIO_PROCESS, 0, d->priority); - - if (!runPrivileged()) - { - setgid(getgid()); -#ifdef HAVE_INITGROUPS - if (pw) - initgroups(pw->pw_name, pw->pw_gid); -#endif - if (geteuid() != getuid()) - setuid(getuid()); - if (geteuid() != getuid()) - _exit(1); - } - - setupEnvironment(); - - if (runmode == DontCare || runmode == OwnGroup) - setsid(); - - const char *executable = arglist[0]; - if (!d->executable.isEmpty()) - executable = d->executable.data(); - execvp(executable, arglist); - - char resultByte = 1; - write(fd[1], &resultByte, 1); - _exit(-1); - } else if (pid_ == -1) { - // forking failed - - // commAbort(); - pid_ = 0; - free(arglist); - return false; - } - // the parent continues here - free(arglist); - - if (!commSetupDoneP()) - qDebug() << "Could not finish comm setup in parent!" << endl; - - // Check whether client could be started. - close(fd[1]); - for(;;) - { - char resultByte; - int n = ::read(fd[0], &resultByte, 1); - if (n == 1) - { - // exec() failed - close(fd[0]); - waitpid(pid_, 0, 0); - pid_ = 0; - commClose(); - return false; - } - if (n == -1) - { - if (errno == EINTR) - continue; // Ignore - } - break; // success - } - close(fd[0]); - - runs = true; - switch (runmode) - { - case Block: - for (;;) - { - commClose(); // drain only, unless obsolete reimplementation - if (!runs) - { - // commClose detected data on the process exit notifification pipe - K3ProcessController::instance()->unscheduleCheck(); - if (waitpid(pid_, &status, WNOHANG) != 0) // error finishes, too - { - commClose(); // this time for real (runs is false) - K3ProcessController::instance()->rescheduleCheck(); - break; - } - runs = true; // for next commClose() iteration - } - else - { - // commClose is an obsolete reimplementation and waited until - // all output channels were closed (or it was interrupted). - // there is a chance that it never gets here ... - waitpid(pid_, &status, 0); - runs = false; - break; - } - } - // why do we do this? i think this signal should be emitted _only_ - // after the process has successfully run _asynchronously_ --ossi - emit processExited(this); - break; - default: // NotifyOnExit & OwnGroup - input_data = 0; // Discard any data for stdin that might still be there - break; - } - return true; -} - - - -bool K3Process::kill(int signo) -{ - if (runs && pid_ > 0 && !::kill(run_mode == OwnGroup ? -pid_ : pid_, signo)) - return true; - return false; -} - - - -bool K3Process::isRunning() const -{ - return runs; -} - - - -pid_t K3Process::pid() const -{ - return pid_; -} - -#ifndef timersub -# define timersub(a, b, result) \ - do { \ - (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \ - (result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \ - if ((result)->tv_usec < 0) { \ - --(result)->tv_sec; \ - (result)->tv_usec += 1000000; \ - } \ - } while (0) -#endif - -bool K3Process::wait(int timeout) -{ - if (!runs) - return true; - -#ifndef __linux__ - struct timeval etv; -#endif - struct timeval tv, *tvp; - if (timeout < 0) - tvp = 0; - else - { -#ifndef __linux__ - gettimeofday(&etv, 0); - etv.tv_sec += timeout; -#else - tv.tv_sec = timeout; - tv.tv_usec = 0; -#endif - tvp = &tv; - } - - int fd = K3ProcessController::instance()->notifierFd(); - for(;;) - { - fd_set fds; - FD_ZERO( &fds ); - FD_SET( fd, &fds ); - -#ifndef __linux__ - if (tvp) - { - gettimeofday(&tv, 0); - timersub(&etv, &tv, &tv); - if (tv.tv_sec < 0) - tv.tv_sec = tv.tv_usec = 0; - } -#endif - - switch( select( fd+1, &fds, 0, 0, tvp ) ) - { - case -1: - if( errno == EINTR ) - break; - // fall through; should happen if tvp->tv_sec < 0 - case 0: - K3ProcessController::instance()->rescheduleCheck(); - return false; - default: - K3ProcessController::instance()->unscheduleCheck(); - if (waitpid(pid_, &status, WNOHANG) != 0) // error finishes, too - { - processHasExited(status); - K3ProcessController::instance()->rescheduleCheck(); - return true; - } - } - } - return false; -} - - - -bool K3Process::normalExit() const -{ - return (pid_ != 0) && !runs && WIFEXITED(status); -} - - -bool K3Process::signalled() const -{ - return (pid_ != 0) && !runs && WIFSIGNALED(status); -} - - -bool K3Process::coreDumped() const -{ -#ifdef WCOREDUMP - return signalled() && WCOREDUMP(status); -#else - return false; -#endif -} - - -int K3Process::exitStatus() const -{ - return WEXITSTATUS(status); -} - - -int K3Process::exitSignal() const -{ - return WTERMSIG(status); -} - - -bool K3Process::writeStdin(const char *buffer, int buflen) -{ - // if there is still data pending, writing new data - // to stdout is not allowed (since it could also confuse - // kprocess ...) - if (input_data != 0) - return false; - - if (communication & Stdin) { - input_data = buffer; - input_sent = 0; - input_total = buflen; - innot->setEnabled(true); - if (input_total) - slotSendData(0); - return true; - } else - return false; -} - -void K3Process::suspend() -{ - if (outnot) - outnot->setEnabled(false); -} - -void K3Process::resume() -{ - if (outnot) - outnot->setEnabled(true); -} - -bool K3Process::closeStdin() -{ - if (communication & Stdin) { - communication = communication & ~Stdin; - delete innot; - innot = 0; - if (!(d->usePty & Stdin)) - close(in[1]); - in[1] = -1; - return true; - } else - return false; -} - -bool K3Process::closeStdout() -{ - if (communication & Stdout) { - communication = communication & ~Stdout; - delete outnot; - outnot = 0; - if (!(d->usePty & Stdout)) - close(out[0]); - out[0] = -1; - return true; - } else - return false; -} - -bool K3Process::closeStderr() -{ - if (communication & Stderr) { - communication = communication & ~Stderr; - delete errnot; - errnot = 0; - if (!(d->usePty & Stderr)) - close(err[0]); - err[0] = -1; - return true; - } else - return false; -} - -bool K3Process::closePty() -{ - if (d->pty && d->pty->masterFd() >= 0) { - if (d->addUtmp) - d->pty->logout(); - d->pty->close(); - return true; - } else - return false; -} - -void K3Process::closeAll() -{ - closeStdin(); - closeStdout(); - closeStderr(); - closePty(); -} - -///////////////////////////// -// protected slots // -///////////////////////////// - - - -void K3Process::slotChildOutput(int fdno) -{ - if (!childOutput(fdno)) - closeStdout(); -} - - -void K3Process::slotChildError(int fdno) -{ - if (!childError(fdno)) - closeStderr(); -} - - -void K3Process::slotSendData(int) -{ - if (input_sent == input_total) { - innot->setEnabled(false); - input_data = 0; - emit wroteStdin(this); - } else { - int result = ::write(in[1], input_data+input_sent, input_total-input_sent); - if (result >= 0) - { - input_sent += result; - } - else if ((errno != EAGAIN) && (errno != EINTR)) - { - qDebug() << "Error writing to stdin of child process" << endl; - closeStdin(); - } - } -} - -void K3Process::setUseShell(bool useShell, const char *shell) -{ - d->useShell = useShell; - if (shell && *shell) - d->shell = shell; - else -// #ifdef NON_FREE // ... as they ship non-POSIX /bin/sh -#if !defined(__linux__) && !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__) && !defined(__GNU__) && !defined(__DragonFly__) - // Solaris POSIX ... - if (!access( "/usr/xpg4/bin/sh", X_OK )) - d->shell = "/usr/xpg4/bin/sh"; - else - // ... which links here anyway - if (!access( "/bin/ksh", X_OK )) - d->shell = "/bin/ksh"; - else - // dunno, maybe superfluous? - if (!access( "/usr/ucb/sh", X_OK )) - d->shell = "/usr/ucb/sh"; - else -#endif - d->shell = "/bin/sh"; -} - -void K3Process::setUsePty(Communication usePty, bool addUtmp) -{ - d->usePty = usePty; - d->addUtmp = addUtmp; - if (usePty) { - if (!d->pty) - d->pty = new KPty; - } else { - delete d->pty; - d->pty = 0; - } -} - -KPty *K3Process::pty() const -{ - return d->pty; -} - -QString K3Process::quote(const QString &arg) -{ - QChar q('\''); - return QString(arg).replace(q, "'\\''").prepend(q).append(q); -} - - -////////////////////////////// -// private member functions // -////////////////////////////// - - -void K3Process::processHasExited(int state) -{ - // only successfully run NotifyOnExit processes ever get here - - status = state; - runs = false; // do this before commClose, so it knows we're dead - - commClose(); // cleanup communication sockets - - if (run_mode != DontCare) - emit processExited(this); -} - - - -int K3Process::childOutput(int fdno) -{ - if (communication & NoRead) { - int len = -1; - emit receivedStdout(fdno, len); - errno = 0; // Make sure errno doesn't read "EAGAIN" - return len; - } - else - { - char buffer[1025]; - int len; - - len = ::read(fdno, buffer, 1024); - - if (len > 0) { - buffer[len] = 0; // Just in case. - emit receivedStdout(this, buffer, len); - } - return len; - } -} - -int K3Process::childError(int fdno) -{ - char buffer[1025]; - int len; - - len = ::read(fdno, buffer, 1024); - - if (len > 0) { - buffer[len] = 0; // Just in case. - emit receivedStderr(this, buffer, len); - } - return len; -} - - -int K3Process::setupCommunication(Communication comm) -{ - // PTY stuff // - if (d->usePty) - { - // cannot communicate on both stderr and stdout if they are both on the pty - if (!(~(comm & d->usePty) & (Stdout | Stderr))) { - qWarning() << "Invalid usePty/communication combination (" << d->usePty << "/" << comm << ")" << endl; - return 0; - } - if (!d->pty->open()) - return 0; - - int rcomm = comm & d->usePty; - int mfd = d->pty->masterFd(); - if (rcomm & Stdin) - in[1] = mfd; - if (rcomm & Stdout) - out[0] = mfd; - if (rcomm & Stderr) - err[0] = mfd; - } - - communication = comm; - - comm = comm & ~d->usePty; - if (comm & Stdin) { - if (socketpair(AF_UNIX, SOCK_STREAM, 0, in)) - goto fail0; - fcntl(in[0], F_SETFD, FD_CLOEXEC); - fcntl(in[1], F_SETFD, FD_CLOEXEC); - } - if (comm & Stdout) { - if (socketpair(AF_UNIX, SOCK_STREAM, 0, out)) - goto fail1; - fcntl(out[0], F_SETFD, FD_CLOEXEC); - fcntl(out[1], F_SETFD, FD_CLOEXEC); - } - if (comm & Stderr) { - if (socketpair(AF_UNIX, SOCK_STREAM, 0, err)) - goto fail2; - fcntl(err[0], F_SETFD, FD_CLOEXEC); - fcntl(err[1], F_SETFD, FD_CLOEXEC); - } - return 1; // Ok - fail2: - if (comm & Stdout) - { - close(out[0]); - close(out[1]); - out[0] = out[1] = -1; - } - fail1: - if (comm & Stdin) - { - close(in[0]); - close(in[1]); - in[0] = in[1] = -1; - } - fail0: - communication = NoCommunication; - return 0; // Error -} - - - -int K3Process::commSetupDoneP() -{ - int rcomm = communication & ~d->usePty; - if (rcomm & Stdin) - close(in[0]); - if (rcomm & Stdout) - close(out[1]); - if (rcomm & Stderr) - close(err[1]); - in[0] = out[1] = err[1] = -1; - - // Don't create socket notifiers if no interactive comm is to be expected - if (run_mode != NotifyOnExit && run_mode != OwnGroup) - return 1; - - if (communication & Stdin) { - fcntl(in[1], F_SETFL, O_NONBLOCK | fcntl(in[1], F_GETFL)); - innot = new QSocketNotifier(in[1], QSocketNotifier::Write, this); - Q_CHECK_PTR(innot); - innot->setEnabled(false); // will be enabled when data has to be sent - QObject::connect(innot, SIGNAL(activated(int)), - this, SLOT(slotSendData(int))); - } - - if (communication & Stdout) { - outnot = new QSocketNotifier(out[0], QSocketNotifier::Read, this); - Q_CHECK_PTR(outnot); - QObject::connect(outnot, SIGNAL(activated(int)), - this, SLOT(slotChildOutput(int))); - if (communication & NoRead) - suspend(); - } - - if (communication & Stderr) { - errnot = new QSocketNotifier(err[0], QSocketNotifier::Read, this ); - Q_CHECK_PTR(errnot); - QObject::connect(errnot, SIGNAL(activated(int)), - this, SLOT(slotChildError(int))); - } - - return 1; -} - - - -int K3Process::commSetupDoneC() -{ - int ok = 1; - if (d->usePty & Stdin) { - if (dup2(d->pty->slaveFd(), STDIN_FILENO) < 0) ok = 0; - } else if (communication & Stdin) { - if (dup2(in[0], STDIN_FILENO) < 0) ok = 0; - } else { - int null_fd = open( "/dev/null", O_RDONLY ); - if (dup2( null_fd, STDIN_FILENO ) < 0) ok = 0; - close( null_fd ); - } - struct linger so; - memset(&so, 0, sizeof(so)); - if (d->usePty & Stdout) { - if (dup2(d->pty->slaveFd(), STDOUT_FILENO) < 0) ok = 0; - } else if (communication & Stdout) { - if (dup2(out[1], STDOUT_FILENO) < 0 || - setsockopt(out[1], SOL_SOCKET, SO_LINGER, (char *)&so, sizeof(so))) - ok = 0; - if (communication & MergedStderr) { - if (dup2(out[1], STDERR_FILENO) < 0) - ok = 0; - } - } - if (d->usePty & Stderr) { - if (dup2(d->pty->slaveFd(), STDERR_FILENO) < 0) ok = 0; - } else if (communication & Stderr) { - if (dup2(err[1], STDERR_FILENO) < 0 || - setsockopt(err[1], SOL_SOCKET, SO_LINGER, (char *)&so, sizeof(so))) - ok = 0; - } - - // don't even think about closing all open fds here or anywhere else - - // PTY stuff // - if (d->usePty) { - d->pty->setCTty(); - if (d->addUtmp) - d->pty->login(getenv("USER"), getenv("DISPLAY")); - } - - return ok; -} - - - -void K3Process::commClose() -{ - closeStdin(); - - if (pid_) { // detached, failed, and killed processes have no output. basta. :) - // If both channels are being read we need to make sure that one socket - // buffer doesn't fill up whilst we are waiting for data on the other - // (causing a deadlock). Hence we need to use select. - - int notfd = K3ProcessController::instance()->notifierFd(); - - while ((communication & (Stdout | Stderr)) || runs) { - fd_set rfds; - FD_ZERO(&rfds); - struct timeval timeout, *p_timeout; - - int max_fd = 0; - if (communication & Stdout) { - FD_SET(out[0], &rfds); - max_fd = out[0]; - } - if (communication & Stderr) { - FD_SET(err[0], &rfds); - if (err[0] > max_fd) - max_fd = err[0]; - } - if (runs) { - FD_SET(notfd, &rfds); - if (notfd > max_fd) - max_fd = notfd; - // If the process is still running we block until we - // receive data or the process exits. - p_timeout = 0; // no timeout - } else { - // If the process has already exited, we only check - // the available data, we don't wait for more. - timeout.tv_sec = timeout.tv_usec = 0; // timeout immediately - p_timeout = &timeout; - } - - int fds_ready = select(max_fd+1, &rfds, 0, 0, p_timeout); - if (fds_ready < 0) { - if (errno == EINTR) - continue; - break; - } else if (!fds_ready) - break; - - if ((communication & Stdout) && FD_ISSET(out[0], &rfds)) - slotChildOutput(out[0]); - - if ((communication & Stderr) && FD_ISSET(err[0], &rfds)) - slotChildError(err[0]); - - if (runs && FD_ISSET(notfd, &rfds)) { - runs = false; // hack: signal potential exit - return; // don't close anything, we will be called again - } - } - } - - closeStdout(); - closeStderr(); - - closePty(); -} - - - -/////////////////////////// -// CC: Class K3ShellProcess -/////////////////////////// - -K3ShellProcess::K3ShellProcess(const char *shellname): - K3Process(), d(0) -{ - setUseShell( true, shellname ? shellname : getenv("SHELL") ); -} - -K3ShellProcess::~K3ShellProcess() { -} - -QString K3ShellProcess::quote(const QString &arg) -{ - return K3Process::quote(arg); -} - -bool K3ShellProcess::start(RunMode runmode, Communication comm) -{ - return K3Process::start(runmode, comm); -} - - -//#include "moc_k3process.cpp" diff --git a/qtermwidget/src/k3process.h b/qtermwidget/src/k3process.h deleted file mode 100644 index f8388ea..0000000 --- a/qtermwidget/src/k3process.h +++ /dev/null @@ -1,890 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 1997 Christian Czezakte (e9025461@student.tuwien.ac.at) - - Rewritten for QT4 by e_k , Copyright (C)2008 - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef K3PROCESS_H -#define K3PROCESS_H - -#include - -#include // for pid_t -#include -#include -#include - -class QSocketNotifier; -class K3ProcessPrivate; -class KPty; - -/** - * @obsolete Use KProcess and KPtyProcess instead. - * - * Child process invocation, monitoring and control. - * This class works only in the application's main thread. - * - * General usage and features:\n - * - * This class allows a KDE application to start child processes without having - * to worry about UN*X signal handling issues and zombie process reaping. - * - * @see K3ProcIO - * - * Basically, this class distinguishes three different ways of running - * child processes: - * - * @li DontCare -- The child process is invoked and both the child - * process and the parent process continue concurrently. - * - * The process is started in an own session (see setsid(2)). - * - * @li NotifyOnExit -- The child process is invoked and both the - * child and the parent process run concurrently. - * - * When the child process exits, the K3Process instance - * corresponding to it emits the Qt signal processExited(). - * Since this signal is @em not emitted from within a UN*X - * signal handler, arbitrary function calls can be made. - * - * Be aware: When the K3Process object gets destructed, the child - * process will be killed if it is still running! - * This means in particular, that it usually makes no sense to use - * a K3Process on the stack with NotifyOnExit. - * - * @li OwnGroup -- like NotifyOnExit, but the child process is started - * in an own process group (and an own session, FWIW). The behavior of - * kill() changes to killing the whole process group - this makes - * this mode useful for implementing primitive job management. It can be - * used to work around broken wrapper scripts that don't propagate signals - * to the "real" program. However, use this with care, as you disturb the - * shell's job management if your program is started from the command line. - * - * @li Block -- The child process starts and the parent process - * is suspended until the child process exits. (@em Really not recommended - * for programs with a GUI.) - * In this mode the parent can read the child's output, but can't send it any - * input. - * - * K3Process also provides several functions for determining the exit status - * and the pid of the child process it represents. - * - * Furthermore it is possible to supply command-line arguments to the process - * in a clean fashion (no null-terminated stringlists and such...) - * - * A small usage example: - * \code - * K3Process *proc = new K3Process; - * - * *proc << "my_executable"; - * *proc << "These" << "are" << "the" << "command" << "line" << "args"; - * QApplication::connect(proc, SIGNAL(processExited(K3Process *)), - * pointer_to_my_object, SLOT(my_objects_slot(K3Process *))); - * proc->start(); - * \endcode - * - * This will start "my_executable" with the commandline arguments "These"... - * - * When the child process exits, the slot will be invoked. - * - * Communication with the child process:\n - * - * K3Process supports communication with the child process through - * stdin/stdout/stderr. - * - * The following functions are provided for getting data from the child - * process or sending data to the child's stdin (For more information, - * have a look at the documentation of each function): - * - * @li writeStdin() - * -- Transmit data to the child process' stdin. When all data was sent, the - * signal wroteStdin() is emitted. - * - * @li When data arrives at stdout or stderr, the signal receivedStdout() - * resp. receivedStderr() is emitted. - * - * @li You can shut down individual communication channels with - * closeStdin(), closeStdout(), and closeStderr(), resp. - * - * @author Christian Czezatke e9025461@student.tuwien.ac.at - * - **/ -class K3Process : public QObject -{ - Q_OBJECT - -public: - - /** - * Modes in which the communication channels can be opened. - * - * If communication for more than one channel is required, - * the values should be or'ed together, for example to get - * communication with stdout as well as with stdin, you would - * specify @p Stdin | @p Stdout - * - */ - enum CommunicationFlag { - NoCommunication = 0, /**< No communication with the process. */ - Stdin = 1, /**< Connect to write to the process with writeStdin(). */ - Stdout = 2, /**< Connect to read from the process' output. */ - Stderr = 4, /**< Connect to read from the process' stderr. */ - AllOutput = 6, /**< Connects to all output channels. */ - All = 7, /**< Connects to all channels. */ - NoRead = 8, /**< If specified with Stdout, no data is actually read from stdout, - * only the signal receivedStdout(int fd, int &len) is emitted. */ - CTtyOnly = NoRead, /**< Tells setUsePty() to create a PTY for the process - * and make it the process' controlling TTY, but does not - * redirect any I/O channel to the PTY. */ - MergedStderr = 16 /**< If specified with Stdout, the process' stderr will be - * redirected onto the same file handle as its stdout, i.e., - * all error output will be signalled with receivedStdout(). - * Don't specify Stderr if you specify MergedStderr. */ - }; - - Q_DECLARE_FLAGS(Communication, CommunicationFlag) - - /** - * Run-modes for a child process. - */ - enum RunMode { - /** - * The application does not receive notifications from the subprocess when - * it is finished or aborted. - */ - DontCare, - /** - * The application is notified when the subprocess dies. - */ - NotifyOnExit, - /** - * The application is suspended until the started process is finished. - */ - Block, - /** - * Same as NotifyOnExit, but the process is run in an own session, - * just like with DontCare. - */ - OwnGroup - }; - - /** - * Constructor - */ - explicit K3Process( QObject* parent=0L ); - - /** - *Destructor: - * - * If the process is running when the destructor for this class - * is called, the child process is killed with a SIGKILL, but - * only if the run mode is not of type @p DontCare. - * Processes started as @p DontCare keep running anyway. - */ - virtual ~K3Process(); - - /** - * Sets the executable and the command line argument list for this process. - * - * For example, doing an "ls -l /usr/local/bin" can be achieved by: - * \code - * K3Process p; - * ... - * p << "ls" << "-l" << "/usr/local/bin" - * \endcode - * - * @param arg the argument to add - * @return a reference to this K3Process - **/ - K3Process &operator<<(const QString& arg); - /** - * Similar to previous method, takes a char *, supposed to be in locale 8 bit already. - */ - K3Process &operator<<(const char * arg); - /** - * Similar to previous method, takes a QByteArray, supposed to be in locale 8 bit already. - * @param arg the argument to add - * @return a reference to this K3Process - */ - K3Process &operator<<(const QByteArray & arg); - - /** - * Sets the executable and the command line argument list for this process, - * in a single method call, or add a list of arguments. - * @param args the arguments to add - * @return a reference to this K3Process - **/ - K3Process &operator<<(const QStringList& args); - - /** - * Clear a command line argument list that has been set by using - * operator<<. - */ - void clearArguments(); - - /** - * Starts the process. - * For a detailed description of the - * various run modes and communication semantics, have a look at the - * general description of the K3Process class. Note that if you use - * setUsePty( Stdout | Stderr, \ ), you cannot use Stdout | Stderr - * here - instead, use Stdout only to receive the mixed output. - * - * The following problems could cause this function to - * return false: - * - * @li The process is already running. - * @li The command line argument list is empty. - * @li The the @p comm parameter is incompatible with the selected pty usage. - * @li The starting of the process failed (could not fork). - * @li The executable was not found. - * - * @param runmode The Run-mode for the process. - * @param comm Specifies which communication channels should be - * established to the child process (stdin/stdout/stderr). By default, - * no communication takes place and the respective communication - * signals will never get emitted. - * - * @return true on success, false on error - * (see above for error conditions) - **/ - virtual bool start(RunMode runmode = NotifyOnExit, - Communication comm = NoCommunication); - - /** - * Stop the process (by sending it a signal). - * - * @param signo The signal to send. The default is SIGTERM. - * @return true if the signal was delivered successfully. - */ - virtual bool kill(int signo = SIGTERM); - - /** - * Checks whether the process is running. - * @return true if the process is (still) considered to be running - */ - bool isRunning() const; - - /** Returns the process id of the process. - * - * If it is called after - * the process has exited, it returns the process id of the last - * child process that was created by this instance of K3Process. - * - * Calling it before any child process has been started by this - * K3Process instance causes pid() to return 0. - * @return the pid of the process or 0 if no process has been started yet. - **/ - pid_t pid() const; - - /** - * Suspend processing of data from stdout of the child process. - */ - void suspend(); - - /** - * Resume processing of data from stdout of the child process. - */ - void resume(); - - /** - * Suspend execution of the current thread until the child process dies - * or the timeout hits. This function is not recommended for programs - * with a GUI. - * @param timeout timeout in seconds. -1 means wait indefinitely. - * @return true if the process exited, false if the timeout hit. - */ - bool wait(int timeout = -1); - - /** - * Checks whether the process exited cleanly. - * - * @return true if the process has already finished and has exited - * "voluntarily", ie: it has not been killed by a signal. - */ - bool normalExit() const; - - /** - * Checks whether the process was killed by a signal. - * - * @return true if the process has already finished and has not exited - * "voluntarily", ie: it has been killed by a signal. - */ - bool signalled() const; - - /** - * Checks whether a killed process dumped core. - * - * @return true if signalled() returns true and the process - * dumped core. Note that on systems that don't define the - * WCOREDUMP macro, the return value is always false. - */ - bool coreDumped() const; - - /** - * Returns the exit status of the process. - * - * @return the exit status of the process. Note that this value - * is not valid if normalExit() returns false. - */ - int exitStatus() const; - - /** - * Returns the signal the process was killed by. - * - * @return the signal number that caused the process to exit. - * Note that this value is not valid if signalled() returns false. - */ - int exitSignal() const; - - /** - * Transmit data to the child process' stdin. - * - * This function may return false in the following cases: - * - * @li The process is not currently running. - * This implies that you cannot use this function in Block mode. - * - * @li Communication to stdin has not been requested in the start() call. - * - * @li Transmission of data to the child process by a previous call to - * writeStdin() is still in progress. - * - * Please note that the data is sent to the client asynchronously, - * so when this function returns, the data might not have been - * processed by the child process. - * That means that you must not free @p buffer or call writeStdin() - * again until either a wroteStdin() signal indicates that the - * data has been sent or a processExited() signal shows that - * the child process is no longer alive. - * - * If all the data has been sent to the client, the signal - * wroteStdin() will be emitted. - * - * This function does not work when the process is start()ed in Block mode. - * - * @param buffer the buffer to write - * @param buflen the length of the buffer - * @return false if an error has occurred - **/ - bool writeStdin(const char *buffer, int buflen); - - /** - * Shuts down the Stdin communication link. If no pty is used, this - * causes "EOF" to be indicated on the child's stdin file descriptor. - * - * @return false if no Stdin communication link exists (any more). - */ - bool closeStdin(); - - /** - * Shuts down the Stdout communication link. If no pty is used, any further - * attempts by the child to write to its stdout file descriptor will cause - * it to receive a SIGPIPE. - * - * @return false if no Stdout communication link exists (any more). - */ - bool closeStdout(); - - /** - * Shuts down the Stderr communication link. If no pty is used, any further - * attempts by the child to write to its stderr file descriptor will cause - * it to receive a SIGPIPE. - * - * @return false if no Stderr communication link exists (any more). - */ - bool closeStderr(); - - /** - * Deletes the optional utmp entry and closes the pty. - * - * Make sure to shut down any communication links that are using the pty - * before calling this function. - * - * @return false if the pty is not open (any more). - */ - bool closePty(); - - /** - * @brief Close stdin, stdout, stderr and the pty - * - * This is the same that calling all close* functions in a row: - * @see closeStdin, @see closeStdout, @see closeStderr and @see closePty - */ - void closeAll(); - - /** - * Lets you see what your arguments are for debugging. - * @return the list of arguments - */ - const QList &args() /* const */ { return arguments; } - - /** - * Controls whether the started process should drop any - * setuid/setgid privileges or whether it should keep them. - * Note that this function is mostly a dummy, as the KDE libraries - * currently refuse to run with setuid/setgid privileges. - * - * The default is false: drop privileges - * @param keepPrivileges true to keep the privileges - */ - void setRunPrivileged(bool keepPrivileges); - - /** - * Returns whether the started process will drop any - * setuid/setgid privileges or whether it will keep them. - * @return true if the process runs privileged - */ - bool runPrivileged() const; - - /** - * Adds the variable @p name to the process' environment. - * This function must be called before starting the process. - * @param name the name of the environment variable - * @param value the new value for the environment variable - */ - void setEnvironment(const QString &name, const QString &value); - - /** - * Changes the current working directory (CWD) of the process - * to be started. - * This function must be called before starting the process. - * @param dir the new directory - */ - void setWorkingDirectory(const QString &dir); - - /** - * Specify whether to start the command via a shell or directly. - * The default is to start the command directly. - * If @p useShell is true @p shell will be used as shell, or - * if shell is empty, /bin/sh will be used. - * - * When using a shell, the caller should make sure that all filenames etc. - * are properly quoted when passed as argument. - * @see quote() - * @param useShell true if the command should be started via a shell - * @param shell the path to the shell that will execute the process, or - * 0 to use /bin/sh. Use getenv("SHELL") to use the user's - * default shell, but note that doing so is usually a bad idea - * for shell compatibility reasons. - */ - void setUseShell(bool useShell, const char *shell = 0); - - /** - * This function can be used to quote an argument string such that - * the shell processes it properly. This is e. g. necessary for - * user-provided file names which may contain spaces or quotes. - * It also prevents expansion of wild cards and environment variables. - * @param arg the argument to quote - * @return the quoted argument - */ - static QString quote(const QString &arg); - - /** - * Detaches K3Process from child process. All communication is closed. - * No exit notification is emitted any more for the child process. - * Deleting the K3Process will no longer kill the child process. - * Note that the current process remains the parent process of the - * child process. - */ - void detach(); - - /** - * Specify whether to create a pty (pseudo-terminal) for running the - * command. - * This function should be called before starting the process. - * - * @param comm for which stdio handles to use a pty. Note that it is not - * allowed to specify Stdout and Stderr at the same time both here and to - * start (there is only one pty, so they cannot be distinguished). - * @param addUtmp true if a utmp entry should be created for the pty - */ - void setUsePty(Communication comm, bool addUtmp); - - /** - * Obtains the pty object used by this process. The return value is - * valid only after setUsePty() was used with a non-zero argument. - * The pty is open only while the process is running. - * @return a pointer to the pty object - */ - KPty *pty() const; - - /** - * More or less intuitive constants for use with setPriority(). - */ - enum { PrioLowest = 20, PrioLow = 10, PrioLower = 5, PrioNormal = 0, - PrioHigher = -5, PrioHigh = -10, PrioHighest = -19 }; - - /** - * Sets the scheduling priority of the process. - * @param prio the new priority in the range -20 (high) to 19 (low). - * @return false on error; see setpriority(2) for possible reasons. - */ - bool setPriority(int prio); - -Q_SIGNALS: - /** - * Emitted after the process has terminated when - * the process was run in the @p NotifyOnExit (==default option to - * start() ) or the Block mode. - * @param proc a pointer to the process that has exited - **/ - void processExited(K3Process *proc); - - - /** - * Emitted, when output from the child process has - * been received on stdout. - * - * To actually get this signal, the Stdout communication link - * has to be turned on in start(). - * - * @param proc a pointer to the process that has received the output - * @param buffer The data received. - * @param buflen The number of bytes that are available. - * - * You should copy the information contained in @p buffer to your private - * data structures before returning from the slot. - * Example: - * \code - * QString myBuf = QLatin1String(buffer, buflen); - * \endcode - **/ - void receivedStdout(K3Process *proc, char *buffer, int buflen); - - /** - * Emitted when output from the child process has - * been received on stdout. - * - * To actually get this signal, the Stdout communication link - * has to be turned on in start() and the - * NoRead flag must have been passed. - * - * You will need to explicitly call resume() after your call to start() - * to begin processing data from the child process' stdout. This is - * to ensure that this signal is not emitted when no one is connected - * to it, otherwise this signal will not be emitted. - * - * The data still has to be read from file descriptor @p fd. - * @param fd the file descriptor that provides the data - * @param len the number of bytes that have been read from @p fd must - * be written here - **/ - void receivedStdout(int fd, int &len); // KDE4: change, broken API - - - /** - * Emitted, when output from the child process has - * been received on stderr. - * - * To actually get this signal, the Stderr communication link - * has to be turned on in start(). - * - * You should copy the information contained in @p buffer to your private - * data structures before returning from the slot. - * - * @param proc a pointer to the process that has received the data - * @param buffer The data received. - * @param buflen The number of bytes that are available. - **/ - void receivedStderr(K3Process *proc, char *buffer, int buflen); - - /** - * Emitted after all the data that has been - * specified by a prior call to writeStdin() has actually been - * written to the child process. - * @param proc a pointer to the process - **/ - void wroteStdin(K3Process *proc); - - -protected Q_SLOTS: - - /** - * This slot gets activated when data from the child's stdout arrives. - * It usually calls childOutput(). - * @param fdno the file descriptor for the output - */ - void slotChildOutput(int fdno); - - /** - * This slot gets activated when data from the child's stderr arrives. - * It usually calls childError(). - * @param fdno the file descriptor for the output - */ - void slotChildError(int fdno); - - /** - * Called when another bulk of data can be sent to the child's - * stdin. If there is no more data to be sent to stdin currently - * available, this function must disable the QSocketNotifier innot. - * @param dummy ignore this argument - */ - void slotSendData(int dummy); // KDE 4: remove dummy - -protected: - - /** - * Sets up the environment according to the data passed via - * setEnvironment() - */ - void setupEnvironment(); - - /** - * The list of the process' command line arguments. The first entry - * in this list is the executable itself. - */ - QList arguments; - /** - * How to run the process (Block, NotifyOnExit, DontCare). You should - * not modify this data member directly from derived classes. - */ - RunMode run_mode; - /** - * true if the process is currently running. You should not - * modify this data member directly from derived classes. Please use - * isRunning() for reading the value of this data member since it - * will probably be made private in later versions of K3Process. - */ - bool runs; - - /** - * The PID of the currently running process. - * You should not modify this data member in derived classes. - * Please use pid() instead of directly accessing this - * member since it will probably be made private in - * later versions of K3Process. - */ - pid_t pid_; - - /** - * The process' exit status as returned by waitpid(). You should not - * modify the value of this data member from derived classes. You should - * rather use exitStatus() than accessing this data member directly - * since it will probably be made private in further versions of - * K3Process. - */ - int status; - - - /** - * If false, the child process' effective uid & gid will be reset to the - * real values. - * @see setRunPrivileged() - */ - bool keepPrivs; - - /** - * This function is called from start() right before a fork() takes - * place. According to the @p comm parameter this function has to initialize - * the in, out and err data members of K3Process. - * - * This function should return 1 if setting the needed communication channels - * was successful. - * - * The default implementation is to create UNIX STREAM sockets for the - * communication, but you could reimplement this function to establish a - * TCP/IP communication for network communication, for example. - */ - virtual int setupCommunication(Communication comm); - - /** - * Called right after a (successful) fork() on the parent side. This function - * will usually do some communications cleanup, like closing in[0], - * out[1] and out[1]. - * - * Furthermore, it must also create the QSocketNotifiers innot, - * outnot and errnot and connect their Qt signals to the respective - * K3Process slots. - * - * For a more detailed explanation, it is best to have a look at the default - * implementation in kprocess.cpp. - */ - virtual int commSetupDoneP(); - - /** - * Called right after a (successful) fork(), but before an exec() on the child - * process' side. It usually duplicates the in[0], out[1] and - * err[1] file handles to the respective standard I/O handles. - */ - virtual int commSetupDoneC(); - - - /** - * Immediately called after a successfully started process in NotifyOnExit - * mode has exited. This function normally calls commClose() - * and emits the processExited() signal. - * @param state the exit code of the process as returned by waitpid() - */ - virtual void processHasExited(int state); - - /** - * Cleans up the communication links to the child after it has exited. - * This function should act upon the values of pid() and runs. - * See the kprocess.cpp source for details. - * @li If pid() returns zero, the communication links should be closed - * only. - * @li if pid() returns non-zero and runs is false, all data - * immediately available from the communication links should be processed - * before closing them. - * @li if pid() returns non-zero and runs is true, the communication - * links should be monitored for data until the file handle returned by - * K3ProcessController::theKProcessController->notifierFd() becomes ready - * for reading - when it triggers, runs should be reset to false, and - * the function should be immediately left without closing anything. - * - * The previous semantics of this function are forward-compatible, but should - * be avoided, as they are prone to race conditions and can cause K3Process - * (and thus the whole program) to lock up under certain circumstances. At the - * end the function closes the communication links in any case. Additionally - * @li if runs is true, the communication links are monitored for data - * until all of them have returned EOF. Note that if any system function is - * interrupted (errno == EINTR) the polling loop should be aborted. - * @li if runs is false, all data immediately available from the - * communication links is processed. - */ - virtual void commClose(); - - /* KDE 4 - commClose will be changed to perform cleanup only in all cases * - * If @p notfd is -1, all data immediately available from the - * communication links should be processed. - * If @p notfd is not -1, the communication links should be monitored - * for data until the file handle @p notfd becomes ready for reading. - */ -// virtual void commDrain(int notfd); - - /** - * Specify the actual executable that should be started (first argument to execve) - * Normally the the first argument is the executable but you can - * override that with this function. - */ - void setBinaryExecutable(const char *filename); - - /** - * The socket descriptors for stdout. - */ - int out[2]; - /** - * The socket descriptors for stdin. - */ - int in[2]; - /** - * The socket descriptors for stderr. - */ - int err[2]; - - /** - * The socket notifier for in[1]. - */ - QSocketNotifier *innot; - /** - * The socket notifier for out[0]. - */ - QSocketNotifier *outnot; - /** - * The socket notifier for err[0]. - */ - QSocketNotifier *errnot; - - /** - * Lists the communication links that are activated for the child - * process. Should not be modified from derived classes. - */ - Communication communication; - - /** - * Called by slotChildOutput() this function copies data arriving from - * the child process' stdout to the respective buffer and emits the signal - * receivedStdout(). - */ - int childOutput(int fdno); - - /** - * Called by slotChildError() this function copies data arriving from - * the child process' stderr to the respective buffer and emits the signal - * receivedStderr(). - */ - int childError(int fdno); - - /** - * The buffer holding the data that has to be sent to the child - */ - const char *input_data; - /** - * The number of bytes already transmitted - */ - int input_sent; - /** - * The total length of input_data - */ - int input_total; - - /** - * K3ProcessController is a friend of K3Process because it has to have - * access to various data members. - */ - friend class K3ProcessController; - -private: - K3ProcessPrivate* const d; -}; - -Q_DECLARE_OPERATORS_FOR_FLAGS(K3Process::Communication) - -class K3ShellProcessPrivate; - -/** -* @obsolete -* -* Use K3Process and K3Process::setUseShell(true) instead. -* -* @short A class derived from K3Process to start child -* processes through a shell. -* @author Christian Czezatke -*/ -class K3ShellProcess : public K3Process -{ - Q_OBJECT - -public: - - /** - * Constructor - * - * If no shellname is specified, the user's default shell is used. - */ - explicit K3ShellProcess(const char *shellname=0); - - /** - * Destructor. - */ - ~K3ShellProcess(); - - virtual bool start(RunMode runmode = NotifyOnExit, - Communication comm = NoCommunication); - - static QString quote(const QString &arg); - -private: - K3ShellProcessPrivate* const d; -}; - - - -#endif - diff --git a/qtermwidget/src/k3processcontroller.cpp b/qtermwidget/src/k3processcontroller.cpp deleted file mode 100644 index 7792b6c..0000000 --- a/qtermwidget/src/k3processcontroller.cpp +++ /dev/null @@ -1,335 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 1997 Christian Czezakte (e9025461@student.tuwien.ac.at) - - Rewritten for QT4 by e_k , Copyright (C)2008 - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#include "k3processcontroller.h" -#include "k3process.h" - -//#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include - - -class K3ProcessController::Private -{ -public: - Private() - : needcheck( false ), - notifier( 0 ) - { - } - - ~Private() - { - delete notifier; - } - - int fd[2]; - bool needcheck; - QSocketNotifier *notifier; - QList kProcessList; - QList unixProcessList; - static struct sigaction oldChildHandlerData; - static bool handlerSet; - static int refCount; - static K3ProcessController* instance; -}; - -K3ProcessController *K3ProcessController::Private::instance = 0; -int K3ProcessController::Private::refCount = 0; - -void K3ProcessController::ref() -{ - if ( !Private::refCount ) { - Private::instance = new K3ProcessController; - setupHandlers(); - } - Private::refCount++; -} - -void K3ProcessController::deref() -{ - Private::refCount--; - if( !Private::refCount ) { - resetHandlers(); - delete Private::instance; - Private::instance = 0; - } -} - -K3ProcessController* K3ProcessController::instance() -{ - /* - * there were no safety guards in previous revisions, is that ok? - if ( !Private::instance ) { - ref(); - } - */ - - return Private::instance; -} - -K3ProcessController::K3ProcessController() - : d( new Private ) -{ - if( pipe( d->fd ) ) - { - perror( "pipe" ); - abort(); - } - - fcntl( d->fd[0], F_SETFL, O_NONBLOCK ); // in case slotDoHousekeeping is called without polling first - fcntl( d->fd[1], F_SETFL, O_NONBLOCK ); // in case it fills up - fcntl( d->fd[0], F_SETFD, FD_CLOEXEC ); - fcntl( d->fd[1], F_SETFD, FD_CLOEXEC ); - - d->notifier = new QSocketNotifier( d->fd[0], QSocketNotifier::Read ); - d->notifier->setEnabled( true ); - QObject::connect( d->notifier, SIGNAL(activated(int)), - SLOT(slotDoHousekeeping())); -} - -K3ProcessController::~K3ProcessController() -{ -#ifndef Q_OS_MAC -/* not sure why, but this is causing lockups */ - close( d->fd[0] ); - close( d->fd[1] ); -#else -#warning FIXME: why does close() freeze up destruction? -#endif - - delete d; -} - - -extern "C" { -static void theReaper( int num ) -{ - K3ProcessController::theSigCHLDHandler( num ); -} -} - -#ifdef Q_OS_UNIX -struct sigaction K3ProcessController::Private::oldChildHandlerData; -#endif -bool K3ProcessController::Private::handlerSet = false; - -void K3ProcessController::setupHandlers() -{ - if( Private::handlerSet ) - return; - Private::handlerSet = true; - -#ifdef Q_OS_UNIX - struct sigaction act; - sigemptyset( &act.sa_mask ); - - act.sa_handler = SIG_IGN; - act.sa_flags = 0; - sigaction( SIGPIPE, &act, 0L ); - - act.sa_handler = theReaper; - act.sa_flags = SA_NOCLDSTOP; - // CC: take care of SunOS which automatically restarts interrupted system - // calls (and thus does not have SA_RESTART) -#ifdef SA_RESTART - act.sa_flags |= SA_RESTART; -#endif - sigaction( SIGCHLD, &act, &Private::oldChildHandlerData ); - - sigaddset( &act.sa_mask, SIGCHLD ); - // Make sure we don't block this signal. gdb tends to do that :-( - sigprocmask( SIG_UNBLOCK, &act.sa_mask, 0 ); -#else - //TODO: win32 -#endif -} - -void K3ProcessController::resetHandlers() -{ - if( !Private::handlerSet ) - return; - Private::handlerSet = false; - -#ifdef Q_OS_UNIX - sigset_t mask, omask; - sigemptyset( &mask ); - sigaddset( &mask, SIGCHLD ); - sigprocmask( SIG_BLOCK, &mask, &omask ); - - struct sigaction act; - sigaction( SIGCHLD, &Private::oldChildHandlerData, &act ); - if (act.sa_handler != theReaper) { - sigaction( SIGCHLD, &act, 0 ); - Private::handlerSet = true; - } - - sigprocmask( SIG_SETMASK, &omask, 0 ); -#else - //TODO: win32 -#endif - // there should be no problem with SIGPIPE staying SIG_IGN -} - -// the pipe is needed to sync the child reaping with our event processing, -// as otherwise there are race conditions, locking requirements, and things -// generally get harder -void K3ProcessController::theSigCHLDHandler( int arg ) -{ - int saved_errno = errno; - - char dummy = 0; - ::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::iterator it( d->kProcessList.begin() ); - QList::iterator eit( d->kProcessList.end() ); - while( it != eit ) - { - K3Process *prc = *it; - if( prc->runs && waitpid( prc->pid_, &status, WNOHANG ) > 0 ) - { - prc->processHasExited( status ); - // the callback can nuke the whole process list and even 'this' - if (!instance()) - return; - goto again; - } - ++it; - } - QList::iterator uit( d->unixProcessList.begin() ); - QList::iterator ueit( d->unixProcessList.end() ); - while( uit != ueit ) - { - if( waitpid( *uit, 0, WNOHANG ) > 0 ) - { - uit = d->unixProcessList.erase( uit ); - deref(); // counterpart to addProcess, can invalidate 'this' - } else - ++uit; - } -} - -bool K3ProcessController::waitForProcessExit( int timeout ) -{ -#ifdef Q_OS_UNIX - for(;;) - { - struct timeval tv, *tvp; - if (timeout < 0) - tvp = 0; - else - { - tv.tv_sec = timeout; - tv.tv_usec = 0; - tvp = &tv; - } - - fd_set fds; - FD_ZERO( &fds ); - FD_SET( d->fd[0], &fds ); - - switch( select( d->fd[0]+1, &fds, 0, 0, tvp ) ) - { - case -1: - if( errno == EINTR ) - continue; - // fall through; should never happen - case 0: - return false; - default: - slotDoHousekeeping(); - return true; - } - } -#else - //TODO: win32 - return false; -#endif -} - -void K3ProcessController::addKProcess( K3Process* p ) -{ - d->kProcessList.append( p ); -} - -void K3ProcessController::removeKProcess( K3Process* p ) -{ - d->kProcessList.removeAll( p ); -} - -void K3ProcessController::addProcess( int pid ) -{ - d->unixProcessList.append( pid ); - ref(); // make sure we stay around when the K3Process goes away -} - -//#include "moc_k3processcontroller.cpp" diff --git a/qtermwidget/src/k3processcontroller.h b/qtermwidget/src/k3processcontroller.h deleted file mode 100644 index c077af2..0000000 --- a/qtermwidget/src/k3processcontroller.h +++ /dev/null @@ -1,137 +0,0 @@ -/* This file is part of the KDE libraries - Copyright (C) 1997 Christian Czezakte (e9025461@student.tuwien.ac.at) - - Rewritten for QT4 by e_k , Copyright (C)2008 - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef K3PROCCTRL_H -#define K3PROCCTRL_H - -#include -#include - - -/** - * @short Used internally by K3Process - * @internal - * @author Christian Czezatke - * - * A class for internal use by K3Process only. -- Exactly one instance - * of this class is created by KApplication. - * - * This class takes care of the actual (UN*X) signal handling. - */ -class K3ProcessController : public QObject -{ - Q_OBJECT - -public: - /** - * Create an instance if none exists yet. - * Called by KApplication::KApplication() - */ - static void ref(); - - /** - * Destroy the instance if one exists and it is not referenced any more. - * Called by KApplication::~KApplication() - */ - static void deref(); - - /** - * Only a single instance of this class is allowed at a time. - * This method provides access to that instance. - */ - static K3ProcessController *instance(); - - /** - * Automatically called upon SIGCHLD. Never call it directly. - * If your application (or some library it uses) redirects SIGCHLD, - * the new signal handler (and only it) should call the old handler - * returned by sigaction(). - * @internal - */ - static void theSigCHLDHandler(int signal); // KDE4: private - - /** - * Wait for any process to exit and handle their exit without - * starting an event loop. - * This function may cause K3Process to emit any of its signals. - * - * @param timeout the timeout in seconds. -1 means no timeout. - * @return true if a process exited, false - * if no process exited within @p timeout seconds. - */ - bool waitForProcessExit(int timeout); - - /** - * Call this function to defer processing of the data that became available - * on notifierFd(). - */ - void unscheduleCheck(); - - /** - * This function @em must be called at some point after calling - * unscheduleCheck(). - */ - void rescheduleCheck(); - - /* - * Obtain the file descriptor K3ProcessController uses to get notified - * about process exits. select() or poll() on it if you create a custom - * event loop that needs to act upon SIGCHLD. - * @return the file descriptor of the reading end of the notification pipe - */ - int notifierFd() const; - - /** - * @internal - */ - void addKProcess( K3Process* ); - /** - * @internal - */ - void removeKProcess( K3Process* ); - /** - * @internal - */ - void addProcess( int pid ); - -private Q_SLOTS: - void slotDoHousekeeping(); - -private: - friend class I_just_love_gcc; - - static void setupHandlers(); - static void resetHandlers(); - - // Disallow instantiation - K3ProcessController(); - ~K3ProcessController(); - - // Disallow assignment and copy-construction - K3ProcessController( const K3ProcessController& ); - K3ProcessController& operator= ( const K3ProcessController& ); - - class Private; - Private * const d; -}; - -#endif - diff --git a/qtermwidget/src/kb-layouts/CVS/Entries b/qtermwidget/src/kb-layouts/CVS/Entries deleted file mode 100644 index 1595129..0000000 --- a/qtermwidget/src/kb-layouts/CVS/Entries +++ /dev/null @@ -1,4 +0,0 @@ -/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/qtermwidget/src/kb-layouts/CVS/Repository b/qtermwidget/src/kb-layouts/CVS/Repository deleted file mode 100644 index f49cd95..0000000 --- a/qtermwidget/src/kb-layouts/CVS/Repository +++ /dev/null @@ -1 +0,0 @@ -qtermwidget/lib/kb-layouts diff --git a/qtermwidget/src/kb-layouts/CVS/Root b/qtermwidget/src/kb-layouts/CVS/Root deleted file mode 100644 index 41f2928..0000000 --- a/qtermwidget/src/kb-layouts/CVS/Root +++ /dev/null @@ -1 +0,0 @@ -:ext:e_k@qtermwidget.cvs.sourceforge.net:/cvsroot/qtermwidget diff --git a/qtermwidget/src/kb-layouts/default.keytab b/qtermwidget/src/kb-layouts/default.keytab deleted file mode 100644 index 76362cd..0000000 --- a/qtermwidget/src/kb-layouts/default.keytab +++ /dev/null @@ -1,133 +0,0 @@ -# [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/qtermwidget/src/konsole_wcwidth.cpp b/qtermwidget/src/konsole_wcwidth.cpp deleted file mode 100644 index e4ef117..0000000 --- a/qtermwidget/src/konsole_wcwidth.cpp +++ /dev/null @@ -1,216 +0,0 @@ -/* $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" - * - * - * 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/qtermwidget/src/konsole_wcwidth.h b/qtermwidget/src/konsole_wcwidth.h deleted file mode 100644 index 6f4e46a..0000000 --- a/qtermwidget/src/konsole_wcwidth.h +++ /dev/null @@ -1,24 +0,0 @@ -/* $XFree86: xc/programs/xterm/wcwidth.h,v 1.2 2001/06/18 19:09:27 dickey Exp $ */ - -/* Markus Kuhn -- 2001-01-12 -- public domain */ -/* Adaptions for KDE by Waldo Bastian */ -/* - Rewritten for QT4 by e_k -*/ - - -#ifndef _KONSOLE_WCWIDTH_H_ -#define _KONSOLE_WCWIDTH_H_ - -// Qt -#include -#include - -int konsole_wcwidth(quint16 ucs); -#if 0 -int konsole_wcwidth_cjk(Q_UINT16 ucs); -#endif - -int string_width( const QString &txt ); - -#endif diff --git a/qtermwidget/src/kpty.h b/qtermwidget/src/kpty.h deleted file mode 100644 index 8286834..0000000 --- a/qtermwidget/src/kpty.h +++ /dev/null @@ -1,188 +0,0 @@ -/* This file is part of the KDE libraries - - Copyright (C) 2003,2007 Oswald Buddenhagen - - Rewritten for QT4 by e_k , Copyright (C)2008 - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING.LIB. If not, write to - the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - Boston, MA 02110-1301, USA. -*/ - -#ifndef kpty_h -#define kpty_h - -#include - -struct KPtyPrivate; -struct termios; - -/** - * Provides primitives for opening & closing a pseudo TTY pair, assigning the - * controlling TTY, utmp registration and setting various terminal attributes. - */ -class KPty { - Q_DECLARE_PRIVATE(KPty) - -public: - - /** - * Constructor - */ - KPty(); - - /** - * Destructor: - * - * If the pty is still open, it will be closed. Note, however, that - * an utmp registration is @em not undone. - */ - ~KPty(); - - /** - * Create a pty master/slave pair. - * - * @return true if a pty pair was successfully opened - */ - bool open(); - - /** - * Close the pty master/slave pair. - */ - void close(); - - /** - * Close the pty slave descriptor. - * - * When creating the pty, KPty also opens the slave and keeps it open. - * Consequently the master will never receive an EOF notification. - * Usually this is the desired behavior, as a closed pty slave can be - * reopened any time - unlike a pipe or socket. However, in some cases - * pipe-alike behavior might be desired. - * - * After this function was called, slaveFd() and setCTty() cannot be - * used. - */ - void closeSlave(); - - /** - * Creates a new session and process group and makes this pty the - * controlling tty. - */ - void setCTty(); - - /** - * Creates an utmp entry for the tty. - * This function must be called after calling setCTty and - * making this pty the stdin. - * @param user the user to be logged on - * @param remotehost the host from which the login is coming. This is - * @em not the local host. For remote logins it should be the hostname - * of the client. For local logins from inside an X session it should - * be the name of the X display. Otherwise it should be empty. - */ - void login(const char *user = 0, const char *remotehost = 0); - - /** - * Removes the utmp entry for this tty. - */ - void logout(); - - /** - * Wrapper around tcgetattr(3). - * - * This function can be used only while the PTY is open. - * You will need an #include <termios.h> to do anything useful - * with it. - * - * @param ttmode a pointer to a termios structure. - * Note: when declaring ttmode, @c struct @c ::termios must be used - - * without the '::' some version of HP-UX thinks, this declares - * the struct in your class, in your method. - * @return @c true on success, false otherwise - */ - bool tcGetAttr(struct ::termios *ttmode) const; - - /** - * Wrapper around tcsetattr(3) with mode TCSANOW. - * - * This function can be used only while the PTY is open. - * - * @param ttmode a pointer to a termios structure. - * @return @c true on success, false otherwise. Note that success means - * that @em at @em least @em one attribute could be set. - */ - bool tcSetAttr(struct ::termios *ttmode); - - /** - * Change the logical (screen) size of the pty. - * The default is 24 lines by 80 columns. - * - * This function can be used only while the PTY is open. - * - * @param lines the number of rows - * @param columns the number of columns - * @return @c true on success, false otherwise - */ - bool setWinSize(int lines, int columns); - - /** - * Set whether the pty should echo input. - * - * Echo is on by default. - * If the output of automatically fed (non-interactive) PTY clients - * needs to be parsed, disabling echo often makes it much simpler. - * - * This function can be used only while the PTY is open. - * - * @param echo true if input should be echoed. - * @return @c true on success, false otherwise - */ - bool setEcho(bool echo); - - /** - * @return the name of the slave pty device. - * - * This function should be called only while the pty is open. - */ - const char *ttyName() const; - - /** - * @return the file descriptor of the master pty - * - * This function should be called only while the pty is open. - */ - int masterFd() const; - - /** - * @return the file descriptor of the slave pty - * - * This function should be called only while the pty slave is open. - */ - int slaveFd() const; - -protected: - /** - * @internal - */ - KPty(KPtyPrivate *d); - - /** - * @internal - */ - KPtyPrivate * const d_ptr; -}; - -#endif - diff --git a/qtermwidget/src/qtermwidget.cpp b/qtermwidget/src/qtermwidget.cpp deleted file mode 100644 index ea5f92a..0000000 --- a/qtermwidget/src/qtermwidget.cpp +++ /dev/null @@ -1,223 +0,0 @@ -/* 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 "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/qtermwidget/src/qtermwidget.h b/qtermwidget/src/qtermwidget.h deleted file mode 100644 index 1a11c4d..0000000 --- a/qtermwidget/src/qtermwidget.h +++ /dev/null @@ -1,108 +0,0 @@ -/* 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. -*/ - - -#ifndef _Q_TERM_WIDGET -#define _Q_TERM_WIDGET - -#include - -struct TermWidgetImpl; - -enum COLOR_SCHEME { COLOR_SCHEME_WHITE_ON_BLACK = 1, - COLOR_SCHEME_GREEN_ON_BLACK, - COLOR_SCHEME_BLACK_ON_LIGHT_YELLOW }; - -class QTermWidget : public QWidget -{ - Q_OBJECT -public: - - enum ScrollBarPosition - { - /** Do not show the scroll bar. */ - NoScrollBar=0, - /** Show the scroll bar on the left side of the display. */ - ScrollBarLeft=1, - /** Show the scroll bar on the right side of the display. */ - ScrollBarRight=2 - }; - - - //Creation of widget - QTermWidget(int startnow = 1, //start shell programm immediatelly - QWidget *parent = 0); - ~QTermWidget(); - - //start shell program if it was not started in constructor - void startShellProgram(); - - //look-n-feel, if you don`t like defaults - - // Terminal font - // Default is application font with family Monospace, size 10 - void setTerminalFont(QFont &font); - - // Shell program, default is /bin/bash - void setShellProgram(QString &progname); - - // Shell program args, default is none - void setArgs(QStringList &args); - - //Text codec, default is UTF-8 - void setTextCodec(QTextCodec *codec); - - //Color scheme, default is white on black - void setColorScheme(int scheme); - - //set size - void setSize(int h, int v); - - // History size for scrolling - void setHistorySize(int lines); //infinite if lines < 0 - - // Presence of scrollbar - void setScrollBarPosition(ScrollBarPosition); - - // Send some text to terminal - void sendText(QString &text); - -signals: - void finished(); - -protected: - virtual void resizeEvent(QResizeEvent *); - -protected slots: - void sessionFinished(); - -private: - void init(); - TermWidgetImpl *m_impl; -}; - - -//Maybe useful, maybe not - -#ifdef __cplusplus -extern "C" -#endif -void *createTermWidget(int startnow, void *parent); - -#endif - diff --git a/qtermwidget/src/src.pro b/qtermwidget/src/src.pro deleted file mode 100644 index 041b6ee..0000000 --- a/qtermwidget/src/src.pro +++ /dev/null @@ -1,48 +0,0 @@ -TEMPLATE = lib -VERSION = 0.1.0 -DESTDIR = ../.. - -TARGET = qtermwidget - -CONFIG += qt debug_and_release warn_on build_all staticlib #dll - -QT += core gui - -MOC_DIR = ../../.moc - -CONFIG(debug, debug|release) { - OBJECTS_DIR = ../../.objs_d - TARGET = qtermwidget_d -} else { - OBJECTS_DIR = ../../.objs - TARGET = qtermwidget -} - -DEFINES += HAVE_POSIX_OPENPT -#or DEFINES += HAVE_GETPT - -HEADERS = TerminalCharacterDecoder.h Character.h CharacterColor.h \ - KeyboardTranslator.h \ - ExtendedDefaultTranslator.h \ - Screen.h History.h BlockArray.h konsole_wcwidth.h \ - ScreenWindow.h \ - Emulation.h \ - Vt102Emulation.h TerminalDisplay.h Filter.h LineFont.h \ - Pty.h kpty.h kpty_p.h k3process.h k3processcontroller.h \ - Session.h ShellCommand.h \ - qtermwidget.h - -SOURCES = TerminalCharacterDecoder.cpp \ - KeyboardTranslator.cpp \ - Screen.cpp History.cpp BlockArray.cpp konsole_wcwidth.cpp \ - ScreenWindow.cpp \ - Emulation.cpp \ - Vt102Emulation.cpp TerminalDisplay.cpp Filter.cpp \ - Pty.cpp kpty.cpp k3process.cpp k3processcontroller.cpp \ - Session.cpp ShellCommand.cpp \ - qtermwidget.cpp - - - - - diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt new file mode 100644 index 0000000..1b81c6d --- /dev/null +++ b/src/CMakeLists.txt @@ -0,0 +1,38 @@ +cmake_minimum_required(VERSION 3.16) + +project(OGBrowser LANGUAGES CXX) + +set(CMAKE_INCLUDE_CURRENT_DIR ON) + +set(CMAKE_AUTOUIC ON) +set(CMAKE_AUTOMOC ON) +set(CMAKE_AUTORCC ON) + + +find_package(QT NAMES Qt6 COMPONENTS Widgets LinguistTools Network WebEngineWidgets REQUIRED) +find_package(Qt${QT_VERSION_MAJOR} COMPONENTS Widgets LinguistTools Network WebEngineWidgets REQUIRED) + + +message(STATUS "Building browser with Qt ${QT_VERSION}") + +set(SOURCES + main.cpp + mainwindow.cpp + ogurlhandler.cpp + ) + + +add_executable(OGBrowser ${SOURCES} ) + +set_property(TARGET OGBrowser PROPERTY CXX_STANDARD 17) +set_property(TARGET OGBrowser PROPERTY CXX_STANDARD_REQUIRED ON) + +target_include_directories(OGBrowser PRIVATE "digitalclock" "qtermwidget/lib") +target_link_libraries(OGBrowser PRIVATE Qt${QT_VERSION_MAJOR}::Widgets Qt${QT_VERSION_MAJOR}::Network Qt${QT_VERSION_MAJOR}::WebEngineWidgets DigitalClock qtermwidget6) + +message(STATUS "Looking for headers in ${PROJECT_BINARY_DIR}") +target_include_directories(OGBrowser PRIVATE ${qtermwidget_INCLUDE_DIRS} ${DigitalClock_INCLUDE_DIRS} ${qtermwidget_LIB_DIRS}/lib ${PROJECT_BINARY_DIR}/../lib) +target_link_directories(OGBrowser PRIVATE ${qtermwidget_LIB_DIRS} ${DigitalClock_LIB_DIRS}) + + + diff --git a/src/main.cpp b/src/main.cpp index 2104e65..3b56a47 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,7 +1,6 @@ -#include +#include #include #include "mainwindow.h" -#include // Internacionalización con GNU Gettext. #include #define TEXTDOMAIN "browser" @@ -21,10 +20,10 @@ int main(int argc, char *argv[]) return -1; } // Codificación de caracteres. - QTextCodec::setCodecForTr(QTextCodec::codecForName(CHARSET)); - QTextCodec::setCodecForCStrings(QTextCodec::codecForName(CHARSET)); - QTextCodec::setCodecForLocale(QTextCodec::codecForName(CHARSET)); - + //QTextCodec::setCodecForTr(QTextCodec::codecForName(CHARSET)); + // QTextCodec::setCodecForCStrings(QTextCodec::codecForName(CHARSET)); + //QTextCodec::setCodecForLocale(QTextCodec::codecForName(CHARSET)); + QApplication a(argc, argv); MainWindow w; w.show(); diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index 1d89a1a..f1aeb90 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -1,10 +1,10 @@ #include "mainwindow.h" -#include +#include #include -#include +#include #include #include -#include +#include #include #include #include @@ -16,10 +16,16 @@ #include #include #include +#include +#include +#include + + #include #include "qtermwidget.h" #include "digitalclock.h" +#include "ogurlhandler.h" #define BUFFERSIZE 2048 #define REGEXP_STRING "^\\[(\\d+)\\]" @@ -27,16 +33,16 @@ #define CURRENT_TIME() QDateTime::currentDateTime().toString("dd/MM/yyyy hh:mm:ss") MainWindow::MainWindow(QWidget *parent) - : QMainWindow(parent),m_web(new QWebView()),m_output(new QTextEdit()), - m_process(new QProcess(this)), + : QMainWindow(parent),m_web(new QWebEngineView()),m_output(new QTextEdit()), m_logfile(0),m_logstream(0),m_numberTerminal(0) { // Graphic - showFullScreen(); setWindowTitle(tr("OpenGnsys Browser")); setCentralWidget(m_web); readEnvironmentValues(); + m_is_admin = qgetenv("ogactiveadmin") == "true"; + // Open the log file for append if(m_env.contains("OGLOGFILE") && m_env["OGLOGFILE"]!="") { @@ -74,7 +80,7 @@ MainWindow::MainWindow(QWidget *parent) // Assign tabs to dock dock->setWidget(m_tabs); // Assign tabs dock to the mainwindow if admin mode is active - if(m_env.contains("ogactiveadmin") && m_env["ogactiveadmin"] == "true") + if(isAdmin()) addDockWidget(Qt::BottomDockWidgetArea,dock); // Top Dock @@ -88,7 +94,7 @@ MainWindow::MainWindow(QWidget *parent) // WebBar to dock dock->setWidget(m_webBar); // Assign top dock to the mainwindow if admin mode is active - if(m_env.contains("ogactiveadmin") && m_env["ogactiveadmin"] == "true") + if(isAdmin()) addDockWidget(Qt::TopDockWidgetArea,dock); // Status bar @@ -115,37 +121,47 @@ MainWindow::MainWindow(QWidget *parent) // Clock m_clock=new DigitalClock(this); - m_web->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks); - - // Web signals - connect(m_web,SIGNAL(linkClicked(const QUrl&)),this, - SLOT(slotLinkHandle(const QUrl&))); connect(m_web,SIGNAL(loadStarted()),this,SLOT(slotWebLoadStarted())); connect(m_web,SIGNAL(loadFinished(bool)),this,SLOT(slotWebLoadFinished(bool))); connect(m_web,SIGNAL(loadProgress(int)),this,SLOT(slotWebLoadProgress(int))); connect(m_web,SIGNAL(urlChanged(const QUrl&)),this,SLOT(slotUrlChanged(const QUrl&))); // Ignore SSL errors. - connect(m_web->page()->networkAccessManager(), - SIGNAL(sslErrors(QNetworkReply*, const QList &)), this, - SLOT(slotSslErrors(QNetworkReply*))); - // Process signals - connect(m_process,SIGNAL(started()),this,SLOT(slotProcessStarted())); - connect(m_process,SIGNAL(finished(int,QProcess::ExitStatus)), - this,SLOT(slotProcessFinished(int,QProcess::ExitStatus))); - connect(m_process,SIGNAL(error(QProcess::ProcessError)), - this,SLOT(slotProcessError(QProcess::ProcessError))); - connect(m_process,SIGNAL(readyReadStandardOutput()),this,SLOT(slotProcessOutput())); - connect(m_process,SIGNAL(readyReadStandardError()), - this,SLOT(slotProcessErrorOutput())); + + // Qindel: + //connect(m_web->page()->networkAccessManager(), +// SIGNAL(sslErrors(QNetworkReply*, const QList &)), this, +// SLOT(slotSslErrors(QNetworkReply*))); + // Dock signals connect(button,SIGNAL(clicked()),this,SLOT(slotCreateTerminal())); - connect(m_webBar,SIGNAL(returnPressed()),this,SLOT(slotWebBarReturnPressed())); + + // All schemes need registering first, then their handlers. + registerScheme("command"); + registerScheme("command+output"); + registerScheme("command+confirm"); + registerScheme("command+confirm+output"); + registerScheme("command+output+confirm"); + + + registerHandler("command", false, false); + registerHandler("command+output", false, true); + registerHandler("command+confirm", true, false); + registerHandler("command+confirm+output", true, true); + registerHandler("command+output+confirm", true, true); + QStringList arguments=QCoreApplication::arguments(); - m_webBar->setText(arguments[1]); - m_web->load(QUrl(arguments[1])); + m_webBar->setText(arguments.at(1)); + m_web->load(QUrl(arguments.at(1))); + + + + + + showMaximized(); + showFullScreen(); } MainWindow::~MainWindow() @@ -159,25 +175,29 @@ MainWindow::~MainWindow() delete m_logstream; } -void MainWindow::slotLinkHandle(const QUrl &url) -{ - // Check if it's executing another process - if(m_process->state() != QProcess::NotRunning) - { - print(tr(gettext("Hay otro proceso en ejecución. Por favor espere."))); - return; - } - QString urlString = url.toString(); - QString urlScheme = url.scheme(); - // Clear the output widget for a normal user - if(! m_env.contains("ogactiveadmin") || m_env["ogactiveadmin"] != "true") - { - m_output->clear(); - } - if(urlScheme == COMMAND_CONFIRM || urlScheme == COMMAND_CONFIRM_OUTPUT || - urlScheme == COMMAND_OUTPUT_CONFIRM || urlScheme == COMMAND_WITH_CONFIRMATION) - { - // For all command with confirmation links, show a popup box +void MainWindow::registerScheme(const QString &name) { + QWebEngineUrlScheme scheme(name.toLatin1()); + scheme.setSyntax(QWebEngineUrlScheme::Syntax::Path); + scheme.setDefaultPort(0); + scheme.setFlags(QWebEngineUrlScheme::LocalScheme); + QWebEngineUrlScheme::registerScheme(scheme); +} + + +void MainWindow::registerHandler(const QString &commandName, bool confirm, bool returnOutput) { + OGBrowserUrlHandlerCommand *handler = new OGBrowserUrlHandlerCommand(this); + connect(handler, &OGBrowserUrlHandlerCommand::command, this, &MainWindow::commandQueued); + handler->setAskConfirmation(confirm); + handler->setReturnOutput(returnOutput); + QWebEngineProfile::defaultProfile()->installUrlSchemeHandler(commandName.toLatin1(), handler); +} + +void MainWindow::commandQueued(const QString &command, bool confirm, bool returnOutput) { + //PendingCommand cmd; + + qInfo() << "Queued command:" << command; + + if (confirm) { QMessageBox msgBox; msgBox.setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowTitleHint); msgBox.setWindowTitle(tr(gettext("AVISO"))); @@ -188,43 +208,55 @@ void MainWindow::slotLinkHandle(const QUrl &url) msgBox.addButton(tr(gettext("Cancelar")), QMessageBox::RejectRole); msgBox.setDefaultButton(execButton); msgBox.exec(); - // Continue if user press the execution button - if (msgBox.clickedButton() == execButton) - { - // For command with confirmation and output link, show an output window to non-admin user - if((urlScheme == COMMAND_CONFIRM_OUTPUT || urlScheme == COMMAND_OUTPUT_CONFIRM) && - (! m_env.contains("ogactiveadmin") || m_env["ogactiveadmin"] != "true")) - { - int w=MainWindow::width(), h=MainWindow::height(); - m_output->setWindowFlags(Qt::Window); - m_output->move(100, 100); - m_output->setFixedSize(w*0.8-100, h*0.8-100); - m_output->show(); - } - // Execute the command - executeCommand(urlString.remove(0, urlScheme.length()+1)); + + if (msgBox.clickedButton() != execButton) { + qInfo() << "User rejected running the command"; + return; } } - else if(urlScheme == COMMAND || urlScheme == COMMAND_OUTPUT) - { - // For command with output link, show an output window to non-admin user - if(urlScheme == COMMAND_OUTPUT && - (! m_env.contains("ogactiveadmin") || m_env["ogactiveadmin"] != "true")) - { - int w=MainWindow::width(), h=MainWindow::height(); - m_output->setWindowFlags(Qt::Window); - m_output->move(100, 100); - m_output->setFixedSize(w*0.8-100, h*0.8-100); - m_output->show(); - } - // Execute the command - executeCommand(urlString.remove(0, urlScheme.length()+1)); + + if (returnOutput && !isAdmin()) { + int w=MainWindow::width(), h=MainWindow::height(); + m_output->setWindowFlags(Qt::Window); + m_output->move(100, 100); + m_output->setFixedSize(w*0.8-100, h*0.8-100); + m_output->show(); } - else - { - // For other link, load webpage - m_web->load(url); + + + m_command.command = command; + m_command.confirm = confirm; + m_command.returnOutput = returnOutput; + + + + + QStringList list=command.split(" ",Qt::SkipEmptyParts); + QString program=list.takeFirst(); + + m_command.process = new QProcess(this); + m_command.process->setReadChannel(QProcess::StandardOutput); + m_command.process->setEnvironment(QProcess::systemEnvironment()); + + // Process signals + connect(m_command.process, &QProcess::started,this, &MainWindow::slotProcessStarted); + connect(m_command.process, &QProcess::finished,this,&MainWindow::slotProcessFinished); + connect(m_command.process, &QProcess::errorOccurred, this,&MainWindow::slotProcessError); + connect(m_command.process, &QProcess::readyReadStandardOutput,this,&MainWindow::slotProcessOutput); + connect(m_command.process, &QProcess::readyReadStandardError,this,&MainWindow::slotProcessErrorOutput); + + + if(isAdmin()) { + m_output->setTextColor(QColor(Qt::darkGreen)); + print(tr(gettext("Lanzando el comando: "))+command); + m_output->setTextColor(QColor(Qt::black)); + } else { + write(tr(gettext("Lanzando el comando: "))+command); } + + m_command.process->start(program,list); + startProgressBar(); + } void MainWindow::slotWebLoadStarted() @@ -243,32 +275,10 @@ 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) - { - QMessageBox msgBox; - msgBox.setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowTitleHint); - msgBox.setWindowTitle(tr(gettext("AVISO"))); - msgBox.setIcon(QMessageBox::Question); - msgBox.setTextFormat(Qt::RichText); - msgBox.setText(tr(gettext("La página no se puede cargar."))); + qWarning() << "Load finished. URL: " << m_web->url() << "; ok = " << ok; - QPushButton *reloadButton = msgBox.addButton(tr(gettext("Recargar")), QMessageBox::ActionRole); - msgBox.addButton(tr(gettext("Abortar")), QMessageBox::RejectRole); - msgBox.exec(); + finishProgressBar(); - if (msgBox.clickedButton() == reloadButton) - { - m_web->reload(); - } - else - { - close(); - } - } - else - { - finishProgressBar(); - } } void MainWindow::slotUrlChanged(const QUrl &url) @@ -288,12 +298,14 @@ void MainWindow::slotProcessStarted() void MainWindow::slotProcessOutput() { - m_process->setReadChannel(QProcess::StandardOutput); + m_command.process->setReadChannel(QProcess::StandardOutput); char buf[BUFFERSIZE]; - while((m_process->readLine(buf,BUFFERSIZE) > 0)) + while((m_command.process->readLine(buf,BUFFERSIZE) > 0)) { QString s(buf); - if(m_env.contains("ogactiveadmin") && m_env["ogactiveadmin"] == "true") + qInfo() << "OUT: " << buf; + + if(isAdmin()) { m_output->insertPlainText(tr("Proc. stdout: ")); } @@ -304,12 +316,18 @@ void MainWindow::slotProcessOutput() void MainWindow::slotProcessErrorOutput() { - m_process->setReadChannel(QProcess::StandardError); + + // QProcess *process = qobject_cast(sender()); + // QVector::iterator it=std::find(m_commands.begin(), m_commands.end(), []()) + + m_command.process->setReadChannel(QProcess::StandardError); char buf[BUFFERSIZE]; - while((m_process->readLine(buf,BUFFERSIZE) > 0)) + while((m_command.process->readLine(buf,BUFFERSIZE) > 0)) { QString s(buf); - if(m_env.contains("ogactiveadmin") && m_env["ogactiveadmin"] == "true") + qInfo() << "ERR: " << buf; + + if(isAdmin()) { m_output->insertPlainText(tr("Proc. stderr: ")); } @@ -321,7 +339,10 @@ void MainWindow::slotProcessErrorOutput() void MainWindow::slotProcessFinished(int code, QProcess::ExitStatus status) { - if(m_env.contains("ogactiveadmin") && m_env["ogactiveadmin"] == "true") + + qInfo() << "Finished: " << m_command.command << "with status" << status; + + if(isAdmin()) { // Admin user: show process status if(status==QProcess::NormalExit) @@ -357,6 +378,8 @@ void MainWindow::slotProcessFinished(int code, QProcess::ExitStatus status) void MainWindow::slotProcessError(QProcess::ProcessError error) { + qCritical() << "Error: " << m_command.command << "with status" << error; + QString errorMsg; switch(error) { @@ -394,7 +417,7 @@ void MainWindow::slotCreateTerminal() QFont font = QApplication::font(); font.setFamily("DejaVu Sans Mono"); font.setPointSize(12); - + console->setTerminalFont(font); console->setFocusPolicy(Qt::StrongFocus); console->setScrollBarPosition(QTermWidget::ScrollBarRight); @@ -415,13 +438,6 @@ void MainWindow::slotDeleteTerminal() delete widget; } -void MainWindow::slotWebBarReturnPressed() -{ - QUrl url(m_webBar->text()); - if(url.isValid()) - slotLinkHandle(url); -} - int MainWindow::readEnvironmentValues() { // The return value @@ -437,7 +453,7 @@ int MainWindow::readEnvironmentValues() foreach (QString str,variablelist) { - // Look for the variable in the environment + // Look for the variable in the environment stringlist=environmentlist.filter(str+"="); if(stringlist.isEmpty()) @@ -483,10 +499,12 @@ void MainWindow::captureOutputForStatusBar(QString output) // Modify the status bar output=output.trimmed(); // Get percentage (string starts with "[Number]") - QRegExp regexp(REGEXP_STRING); - if(regexp.indexIn(output) != -1) + QRegularExpression regexp(REGEXP_STRING); + QRegularExpressionMatch match = regexp.match(output); + + if(match.hasMatch()) { - int pass=regexp.cap(1).toInt(); + int pass=match.captured(1).toInt(); output.replace(regexp,""); m_progressBar->setValue(pass); m_progressBar->setFormat("%p%"+output); @@ -514,37 +532,15 @@ void MainWindow::finishProgressBar() m_web->setEnabled(true); } -// Execute a command -void MainWindow::executeCommand(QString &string) -{ - QStringList list=string.split(" ",QString::SkipEmptyParts); - QString program=list.takeFirst(); - m_process->setReadChannel(QProcess::StandardOutput); - // Assign the same Browser's environment to the process - m_process->setEnvironment(QProcess::systemEnvironment()); - m_process->start(program,list); - // Only show the command line to admin user - if(m_env.contains("ogactiveadmin") && m_env["ogactiveadmin"] == "true") - { - m_output->setTextColor(QColor(Qt::darkGreen)); - print(tr(gettext("Lanzando el comando: "))+string); - m_output->setTextColor(QColor(Qt::black)); - } - else - { - write(tr(gettext("Lanzando el comando: "))+string); - } - startProgressBar(); -} // Returns communication speed QString MainWindow::readSpeed() { if(m_env.contains("OGLOGFILE")) { QString infoFile=m_env["OGLOGFILE"].replace(".log", ".info.html"); - QString command="grep -hoe \"[0-9]*Mb/s\" "+infoFile+" 2>/dev/null"; + //QString command="grep -hoe \"[0-9]*Mb/s\" "+infoFile+" 2>/dev/null"; QProcess process; - process.start(command); + process.start("grep", QStringList({"-hoe", "[0-9]*Mb/s", infoFile})); process.waitForFinished(); QString speed(process.readAllStandardOutput()); return speed.simplified(); diff --git a/src/mainwindow.h b/src/mainwindow.h index 664d2f0..0a8d2b1 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -9,27 +9,38 @@ #define COMMAND_OUTPUT_CONFIRM "command+output+confirm" #define ENVIRONMENT "OGLOGFILE,ogactiveadmin,DEFAULTSPEED" + #include #include #include #include #include #include +#include +#include +#include +#include +#include +#include +#include + + #include "digitalclock.h" -class QWebView; -class QTextEdit; -class QVBoxLayout; -class QProcess; -class QStringList; -class QString; -class QUrl; -class QFile; -class QTextStream; -class QTermWidget; -class QProgressBar; -class QLineEdit; -class QLabel; + + +struct PendingCommand { + QString command = ""; + bool confirm = false; + bool returnOutput = false; + + QProcess *process = nullptr; + + bool operator==(const PendingCommand &other) { + return other.process == process; + } +}; + class MainWindow : public QMainWindow { @@ -41,7 +52,6 @@ class MainWindow : public QMainWindow public slots: // Funcion que maneja los links - void slotLinkHandle(const QUrl& url); void slotWebLoadStarted(); void slotWebLoadFinished(bool ok); void slotWebLoadProgress(int progress); @@ -59,9 +69,19 @@ class MainWindow : public QMainWindow void slotDeleteTerminal(); // Funcion para el webar - void slotWebBarReturnPressed(); void slotUrlChanged(const QUrl &url); + void commandQueued(const QString &command, bool confirm, bool returnOutput); + + + private: + bool isAdmin() const { return m_is_admin; } + void registerScheme(const QString &name); + void registerHandler(const QString &name, bool confirm, bool output); + + bool m_is_admin{false}; + + //Functions protected: int readEnvironmentValues(); @@ -75,7 +95,7 @@ class MainWindow : public QMainWindow void showErrorMessage(QString string); protected: - QWebView *m_web; + QWebEngineView *m_web; QTextEdit *m_output; QLabel *m_logo; QProgressBar *m_progressBar; @@ -84,12 +104,16 @@ class MainWindow : public QMainWindow QTabWidget *m_tabs; QLineEdit *m_webBar; - QProcess *m_process; + //QProcess *m_process; QMap m_env; QFile *m_logfile; QTextStream *m_logstream; + PendingCommand m_command; + //QVector m_commands; + + int m_numberTerminal; }; diff --git a/src/ogbrowser.h b/src/ogbrowser.h new file mode 100644 index 0000000..59827fe --- /dev/null +++ b/src/ogbrowser.h @@ -0,0 +1,4 @@ + +#pragma once + +#include < \ No newline at end of file diff --git a/src/ogurlhandler.cpp b/src/ogurlhandler.cpp new file mode 100644 index 0000000..3d3548b --- /dev/null +++ b/src/ogurlhandler.cpp @@ -0,0 +1,72 @@ + + +#include "ogurlhandler.h" +#include +#include +#include + + +void OGBrowserUrlHandlerCommand::requestStarted(QWebEngineUrlRequestJob *job) { + + qInfo() << "Command request: " << job->requestUrl(); + + + emit command(job->requestUrl().path(), askConfirmation(), returnOuput()); + //job->redirect(QUrl()); + job->fail(QWebEngineUrlRequestJob::NoError); + + return; + /* + // For all command with confirmation links, show a popup box + if (askConfirmation()) { + QMessageBox msgBox; + msgBox.setWindowFlags(Qt::CustomizeWindowHint | Qt::WindowTitleHint); + msgBox.setWindowTitle(tr(gettext("AVISO"))); + msgBox.setIcon(QMessageBox::Question); + msgBox.setTextFormat(Qt::RichText); + msgBox.setText(tr(gettext("La siguiente acción puede modificar datos o tardar varios minutos. El equipo no podrá ser utilizado durante su ejecución."))); + QPushButton *execButton = msgBox.addButton(tr(gettext("Ejecutar")), QMessageBox::ActionRole); + msgBox.addButton(tr(gettext("Cancelar")), QMessageBox::RejectRole); + msgBox.setDefaultButton(execButton); + msgBox.exec(); + // Continue if user press the execution button + if (msgBox.clickedButton() == execButton) + { + // For command with confirmation and output link, show an output window to non-admin user + if((urlScheme == COMMAND_CONFIRM_OUTPUT || urlScheme == COMMAND_OUTPUT_CONFIRM) && + (! m_env.contains("ogactiveadmin") || m_env["ogactiveadmin"] != "true")) + { + int w=MainWindow::width(), h=MainWindow::height(); + m_output->setWindowFlags(Qt::Window); + m_output->move(100, 100); + m_output->setFixedSize(w*0.8-100, h*0.8-100); + m_output->show(); + } + } else { + job->fail(QWebEngineUrlRequestJob::RequestDenied); + return; + } + } + + // Execute the command + executeCommand(urlString.remove(0, urlScheme.length()+1)); + + + + + else if(urlScheme == COMMAND || urlScheme == COMMAND_OUTPUT) + { + // For command with output link, show an output window to non-admin user + if(urlScheme == COMMAND_OUTPUT && + (! m_env.contains("ogactiveadmin") || m_env["ogactiveadmin"] != "true")) + { + int w=MainWindow::width(), h=MainWindow::height(); + m_output->setWindowFlags(Qt::Window); + m_output->move(100, 100); + m_output->setFixedSize(w*0.8-100, h*0.8-100); + m_output->show(); + } + // Execute the command + executeCommand(urlString.remove(0, urlScheme.length()+1)); + } */ +} \ No newline at end of file diff --git a/src/ogurlhandler.h b/src/ogurlhandler.h new file mode 100644 index 0000000..adb08b9 --- /dev/null +++ b/src/ogurlhandler.h @@ -0,0 +1,44 @@ +#pragma once + +#include +#include + +#define COMMAND "command" +#define COMMAND_CONFIRM "command+confirm" +#define COMMAND_WITH_CONFIRMATION "commandwithconfirmation" // Backwards compatibility +#define COMMAND_OUTPUT "command+output" +#define COMMAND_CONFIRM_OUTPUT "command+confirm+output" +#define COMMAND_OUTPUT_CONFIRM "command+output+confirm" +#define ENVIRONMENT "OGLOGFILE,ogactiveadmin,DEFAULTSPEED" + +class OGBrowserUrlHandlerCommand : public QWebEngineUrlSchemeHandler { + Q_OBJECT +public: + + OGBrowserUrlHandlerCommand(QObject *parent = nullptr) : QWebEngineUrlSchemeHandler(parent) { + + }; + + virtual ~OGBrowserUrlHandlerCommand() { + + }; + + virtual void requestStarted(QWebEngineUrlRequestJob *job); + bool askConfirmation() const { return m_ask_confirmation; } + bool returnOuput() const { return m_return_output; } + + void setAskConfirmation(const bool ask) { m_ask_confirmation = ask; } + void setReturnOutput(const bool retOutput) { m_return_output = retOutput; } + +signals: + void command(const QString &command, bool confirm, bool returnOutput); + + +private: + + bool m_ask_confirmation = false; + bool m_return_output = false; + +}; + + diff --git a/src/src.pro b/src/src.pro deleted file mode 100644 index ed5cc82..0000000 --- a/src/src.pro +++ /dev/null @@ -1,28 +0,0 @@ -TEMPLATE = app -DESTDIR = .. - -CONFIG += qt release warn_on build_all - -QT += core gui webkit - -MOC_DIR = ../.moc - -# CONFIG(debug, debug|release) { -# OBJECTS_DIR = ../.objs_d -# TARGET = browser_d -# LIBS += -L.. #../libqtermwidget_d.a -#} else { -# OBJECTS_DIR = ../.objs -# TARGET = browser -# LIBS += -L.. #../libqtermwidget.a -#} - -OBJECTS_DIR = ../.objs -TARGET = browser -LIBS += -L.. -lqtermwidget -ldigitalclock - -SOURCES = main.cpp mainwindow.cpp - -HEADERS = mainwindow.h - -INCLUDEPATH = ../qtermwidget/src ../digitalclock diff --git a/src/test.html b/src/test.html new file mode 100644 index 0000000..6994cb6 --- /dev/null +++ b/src/test.html @@ -0,0 +1,73 @@ + + + OGBrowser tests + + + +

    Tests

    +

    Tests de funcionalidad de comandos de OGBrowser

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    SchemeTestDescripcion
    commandEjecutarEjecutar comando (exito)
    commandEjecutarEjecutar comando (fallo)
    commandEjecutarEjecutar comando (no encontrado)
    command+outputEjecutarEjecutar comando con captura de salida
    command+confirmEjecutarEjecutar comando con confirmacion
    commandEjecutarEjecutar comando con confirmacion y largo tiempo (10s)
    commandEjecutarEjecutar comando con confirmacion, salida y largo tiempo (5s)
    + + + \ No newline at end of file