diff --git a/CMakeLists.txt b/CMakeLists.txt index fb28fb032..f7334ff1e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -135,11 +135,7 @@ ecm_qt_install_logging_categories( feature_summary(WHAT ALL INCLUDE_QUIET_PACKAGES FATAL_ON_MISSING_REQUIRED_PACKAGES) -# Do not do bulk whitespace/style changes without MRs and maintainer(s) -# approval. clang-format executeable needs to be installed prior to initial -# building; then do make clang-format. # add clang-format target for all our real source files file(GLOB_RECURSE ALL_CLANG_FORMAT_SOURCE_FILES *.c *.cpp *.h *.hpp) kde_clang_format(${ALL_CLANG_FORMAT_SOURCE_FILES}) -# Let's not do pre-hooks yet -#kde_configure_git_pre_commit_hook(CHECKS CLANG_FORMAT) +kde_configure_git_pre_commit_hook(CHECKS CLANG_FORMAT) diff --git a/src/Application.cpp b/src/Application.cpp index 71d100c9c..9bcbe428c 100644 --- a/src/Application.cpp +++ b/src/Application.cpp @@ -9,10 +9,10 @@ // Qt #include -#include -#include -#include #include +#include +#include +#include #include #include #include @@ -28,8 +28,8 @@ #include "ShellCommand.h" #include "ViewManager.h" #include "WindowSystemInfo.h" -#include "profile/ProfileManager.h" #include "profile/ProfileCommandParser.h" +#include "profile/ProfileManager.h" #include "session/Session.h" #include "session/SessionManager.h" #include "terminalDisplay/TerminalDisplay.h" @@ -39,88 +39,48 @@ using namespace Konsole; -Application::Application(QSharedPointer parser, - const QStringList &customCommand) : - _backgroundInstance(nullptr), - m_parser(parser), - m_customCommand(customCommand) +Application::Application(QSharedPointer parser, const QStringList &customCommand) + : _backgroundInstance(nullptr) + , m_parser(parser) + , m_customCommand(customCommand) { m_pluginManager.loadAllPlugins(); } void Application::populateCommandLineParser(QCommandLineParser *parser) { - const auto options = QVector { - { { QStringLiteral("profile") }, - i18nc("@info:shell", "Name of profile to use for new Konsole instance"), - QStringLiteral("name") - }, - { { QStringLiteral("layout") }, - i18nc("@info:shell", "json layoutfile to be loaded to use for new Konsole instance"), - QStringLiteral("file") - }, - { { QStringLiteral("fallback-profile") }, - i18nc("@info:shell", "Use the internal FALLBACK profile") - }, - { { QStringLiteral("workdir") }, - i18nc("@info:shell", "Set the initial working directory of the new tab or window to 'dir'"), - QStringLiteral("dir") - }, - { { QStringLiteral("hold"), QStringLiteral("noclose") }, - i18nc("@info:shell", "Do not close the initial session automatically when it ends.") - }, - { {QStringLiteral("new-tab") }, - i18nc("@info:shell", "Create a new tab in an existing window rather than creating a new window") - }, - { { QStringLiteral("tabs-from-file") }, - i18nc("@info:shell","Create tabs as specified in given tabs configuration"" file"), - QStringLiteral("file") - }, - { { QStringLiteral("background-mode") }, - i18nc("@info:shell", "Start Konsole in the background and bring to the front when Ctrl+Shift+F12 (by default) is pressed") - }, - { { QStringLiteral("separate"), QStringLiteral("nofork") }, - i18nc("@info:shell", "Run in a separate process") - }, - { { QStringLiteral("show-menubar") }, - i18nc("@info:shell", "Show the menubar, overriding the default setting") - }, - { { QStringLiteral("hide-menubar") }, - i18nc("@info:shell", "Hide the menubar, overriding the default setting") - }, - { { QStringLiteral("show-tabbar") }, - i18nc("@info:shell", "Show the tabbar, overriding the default setting") - }, - { { QStringLiteral("hide-tabbar") }, - i18nc("@info:shell", "Hide the tabbar, overriding the default setting") - }, - { { QStringLiteral("fullscreen") }, - i18nc("@info:shell", "Start Konsole in fullscreen mode") - }, - { { QStringLiteral("notransparency") }, - i18nc("@info:shell", "Disable transparent backgrounds, even if the system supports them.") - }, - { { QStringLiteral("list-profiles") }, - i18nc("@info:shell", "List the available profiles") - }, - { { QStringLiteral("list-profile-properties") }, - i18nc("@info:shell", "List all the profile properties names and their type (for use with -p)") - }, - { { QStringLiteral("p") }, - i18nc("@info:shell", "Change the value of a profile property."), - QStringLiteral("property=value") - }, - { { QStringLiteral("e") }, - i18nc("@info:shell", "Command to execute. This option will catch all following arguments, so use it as the last option."), - QStringLiteral("cmd") - } - }; + const auto options = QVector{ + {{QStringLiteral("profile")}, i18nc("@info:shell", "Name of profile to use for new Konsole instance"), QStringLiteral("name")}, + {{QStringLiteral("layout")}, i18nc("@info:shell", "json layoutfile to be loaded to use for new Konsole instance"), QStringLiteral("file")}, + {{QStringLiteral("fallback-profile")}, i18nc("@info:shell", "Use the internal FALLBACK profile")}, + {{QStringLiteral("workdir")}, i18nc("@info:shell", "Set the initial working directory of the new tab or window to 'dir'"), QStringLiteral("dir")}, + {{QStringLiteral("hold"), QStringLiteral("noclose")}, i18nc("@info:shell", "Do not close the initial session automatically when it ends.")}, + {{QStringLiteral("new-tab")}, i18nc("@info:shell", "Create a new tab in an existing window rather than creating a new window")}, + {{QStringLiteral("tabs-from-file")}, + i18nc("@info:shell", + "Create tabs as specified in given tabs configuration" + " file"), + QStringLiteral("file")}, + {{QStringLiteral("background-mode")}, + i18nc("@info:shell", "Start Konsole in the background and bring to the front when Ctrl+Shift+F12 (by default) is pressed")}, + {{QStringLiteral("separate"), QStringLiteral("nofork")}, i18nc("@info:shell", "Run in a separate process")}, + {{QStringLiteral("show-menubar")}, i18nc("@info:shell", "Show the menubar, overriding the default setting")}, + {{QStringLiteral("hide-menubar")}, i18nc("@info:shell", "Hide the menubar, overriding the default setting")}, + {{QStringLiteral("show-tabbar")}, i18nc("@info:shell", "Show the tabbar, overriding the default setting")}, + {{QStringLiteral("hide-tabbar")}, i18nc("@info:shell", "Hide the tabbar, overriding the default setting")}, + {{QStringLiteral("fullscreen")}, i18nc("@info:shell", "Start Konsole in fullscreen mode")}, + {{QStringLiteral("notransparency")}, i18nc("@info:shell", "Disable transparent backgrounds, even if the system supports them.")}, + {{QStringLiteral("list-profiles")}, i18nc("@info:shell", "List the available profiles")}, + {{QStringLiteral("list-profile-properties")}, i18nc("@info:shell", "List all the profile properties names and their type (for use with -p)")}, + {{QStringLiteral("p")}, i18nc("@info:shell", "Change the value of a profile property."), QStringLiteral("property=value")}, + {{QStringLiteral("e")}, + i18nc("@info:shell", "Command to execute. This option will catch all following arguments, so use it as the last option."), + QStringLiteral("cmd")}}; for (const auto &option : options) { parser->addOption(option); } - parser->addPositionalArgument(QStringLiteral("[args]"), - i18nc("@info:shell", "Arguments passed to command")); + parser->addPositionalArgument(QStringLiteral("[args]"), i18nc("@info:shell", "Arguments passed to command")); // Add a no-op compatibility option to make Konsole compatible with // Debian's policy on X terminal emulators. @@ -129,9 +89,7 @@ void Application::populateCommandLineParser(QCommandLineParser *parser) // the title and overriding whatever is set elsewhere. // https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=532029 // https://www.debian.org/doc/debian-policy/ch-customized-programs.html#s11.8.3 - auto titleOption = QCommandLineOption({ QStringLiteral("T") }, - QStringLiteral("Debian policy compatibility, not used"), - QStringLiteral("value")); + auto titleOption = QCommandLineOption({QStringLiteral("T")}, QStringLiteral("Debian policy compatibility, not used"), QStringLiteral("value")); titleOption.setFlags(QCommandLineOption::HiddenFromHelp); parser->addOption(titleOption); } @@ -164,8 +122,7 @@ MainWindow *Application::newMainWindow() auto window = new MainWindow(); - connect(window, &Konsole::MainWindow::newWindowRequest, this, - &Konsole::Application::createWindow); + connect(window, &Konsole::MainWindow::newWindowRequest, this, &Konsole::Application::createWindow); connect(window, &Konsole::MainWindow::terminalsDetached, this, &Konsole::Application::detachTerminals); if (!m_pluginManager.plugins().empty()) { @@ -191,14 +148,14 @@ void Application::createWindow(const Profile::Ptr &profile, const QString &direc window->show(); } -void Application::detachTerminals(ViewSplitter *splitter,const QHash& sessionsMap) +void Application::detachTerminals(ViewSplitter *splitter, const QHash &sessionsMap) { - auto *currentWindow = qobject_cast(sender()); + auto *currentWindow = qobject_cast(sender()); MainWindow *window = newMainWindow(); ViewManager *manager = window->viewManager(); const QList displays = splitter->findChildren(); - for (TerminalDisplay* terminal : displays) { + for (TerminalDisplay *terminal : displays) { manager->attachView(terminal, sessionsMap[terminal]); } manager->activeContainer()->addSplitter(splitter); @@ -255,8 +212,7 @@ int Application::newInstance() } } - - // if the background-mode argument is supplied, start the background + // if the background-mode argument is supplied, start the background // session ( or bring to the front if it already exists ) if (m_parser->isSet(QStringLiteral("background-mode"))) { startBackgroundMode(window); @@ -312,8 +268,7 @@ bool Application::processTabsFromFileArgs(MainWindow *window) const QString tabsFileName(m_parser->value(QStringLiteral("tabs-from-file"))); QFile tabsFile(tabsFileName); if (!tabsFile.open(QFile::ReadOnly)) { - qWarning() << "ERROR: Cannot open tabs file " - << tabsFileName.toLocal8Bit().data(); + qWarning() << "ERROR: Cannot open tabs file " << tabsFileName.toLocal8Bit().data(); return false; } @@ -333,8 +288,7 @@ bool Application::processTabsFromFileArgs(MainWindow *window) lineTokens[key] = value; } // should contain at least one of 'command' and 'profile' - if (lineTokens.contains(QStringLiteral("command")) - || lineTokens.contains(QStringLiteral("profile"))) { + if (lineTokens.contains(QStringLiteral("command")) || lineTokens.contains(QStringLiteral("profile"))) { createTabFromArgs(window, lineTokens); sessions++; } else { @@ -344,8 +298,7 @@ bool Application::processTabsFromFileArgs(MainWindow *window) tabsFile.close(); if (sessions < 1) { - qWarning() << "No valid lines found in " - << tabsFileName.toLocal8Bit().data(); + qWarning() << "No valid lines found in " << tabsFileName.toLocal8Bit().data(); return false; } @@ -453,8 +406,7 @@ MainWindow *Application::processWindowArgs(bool &createdNewMainWindow) } if (m_parser->isSet(QStringLiteral("show-tabbar"))) { window->viewManager()->setNavigationVisibility(ViewManager::AlwaysShowNavigation); - } - else if (m_parser->isSet(QStringLiteral("hide-tabbar"))) { + } else if (m_parser->isSet(QStringLiteral("hide-tabbar"))) { window->viewManager()->setNavigationVisibility(ViewManager::AlwaysHideNavigation); } } @@ -470,8 +422,7 @@ Profile::Ptr Application::processProfileSelectArgs() Profile::Ptr defaultProfile = ProfileManager::instance()->defaultProfile(); if (m_parser->isSet(QStringLiteral("profile"))) { - Profile::Ptr profile = ProfileManager::instance()->loadProfile( - m_parser->value(QStringLiteral("profile"))); + Profile::Ptr profile = ProfileManager::instance()->loadProfile(m_parser->value(QStringLiteral("profile"))); if (profile) { return profile; } @@ -543,8 +494,7 @@ Profile::Ptr Application::processProfileChangeArgs(Profile::Ptr baseProfile) // Example: konsole -e man ls QString commandExec = m_customCommand[0]; QStringList commandArguments(m_customCommand); - if ((m_customCommand.size() == 1) - && (QStandardPaths::findExecutable(commandExec).isEmpty())) { + if ((m_customCommand.size() == 1) && (QStandardPaths::findExecutable(commandExec).isEmpty())) { // Example: konsole -e "man ls" ShellCommand shellCommand(commandExec); commandExec = shellCommand.command(); @@ -573,8 +523,8 @@ void Application::startBackgroundMode(MainWindow *window) return; } - KActionCollection* collection = window->actionCollection(); - QAction* action = collection->addAction(QStringLiteral("toggle-background-window")); + KActionCollection *collection = window->actionCollection(); + QAction *action = collection->addAction(QStringLiteral("toggle-background-window")); action->setObjectName(QStringLiteral("Konsole Background Mode")); action->setText(i18nc("@item", "Toggle Background Window")); KGlobalAccel::self()->setGlobalShortcut(action, QKeySequence(Konsole::ACCEL | Qt::SHIFT | Qt::Key_F12)); @@ -614,4 +564,3 @@ void Application::slotActivateRequested(QStringList args, const QString & /*work newInstance(); } - diff --git a/src/Application.h b/src/Application.h index 27c4590e7..728fcc31d 100644 --- a/src/Application.h +++ b/src/Application.h @@ -17,7 +17,8 @@ #include "konsole_export.h" -namespace Konsole { +namespace Konsole +{ class MainWindow; class Session; class Profile; @@ -40,8 +41,7 @@ class KONSOLE_EXPORT Application : public QObject public: /** Constructs a new Konsole application. */ - explicit Application(QSharedPointer parser, - const QStringList &customCommand); + explicit Application(QSharedPointer parser, const QStringList &customCommand); static void populateCommandLineParser(QCommandLineParser *parser); static QStringList getCustomCommand(QStringList &args); @@ -60,7 +60,7 @@ public: private Q_SLOTS: void createWindow(const QExplicitlySharedDataPointer &profile, const QString &directory); - void detachTerminals(ViewSplitter *splitter, const QHash& sessionsMap); + void detachTerminals(ViewSplitter *splitter, const QHash &sessionsMap); void toggleBackgroundInstance(); @@ -84,7 +84,6 @@ private: QSharedPointer m_parser; QStringList m_customCommand; PluginManager m_pluginManager; - }; } -#endif // APPLICATION_H +#endif // APPLICATION_H diff --git a/src/BookmarkHandler.cpp b/src/BookmarkHandler.cpp index d169d71c8..f0b11f0b8 100644 --- a/src/BookmarkHandler.cpp +++ b/src/BookmarkHandler.cpp @@ -12,14 +12,14 @@ #include "BookmarkHandler.h" // Qt +#include #include #include -#include // KDE -#include #include #include +#include // Konsole #include "BookmarkMenu.h" @@ -27,24 +27,21 @@ using namespace Konsole; -BookmarkHandler::BookmarkHandler(KActionCollection *collection, QMenu *menu, bool toplevel, - QObject *parent) : - QObject(parent), - KBookmarkOwner(), - _menu(menu), - _file(QString()), - _toplevel(toplevel), - _activeView(nullptr), - _views(QList()) +BookmarkHandler::BookmarkHandler(KActionCollection *collection, QMenu *menu, bool toplevel, QObject *parent) + : QObject(parent) + , KBookmarkOwner() + , _menu(menu) + , _file(QString()) + , _toplevel(toplevel) + , _activeView(nullptr) + , _views(QList()) { setObjectName(QStringLiteral("BookmarkHandler")); - _file = QStandardPaths::locate(QStandardPaths::GenericDataLocation, - QStringLiteral("konsole/bookmarks.xml")); + _file = QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("konsole/bookmarks.xml")); if (_file.isEmpty()) { - _file = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) - + QStringLiteral("/konsole"); + _file = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QStringLiteral("/konsole"); QDir().mkpath(_file); _file += QStringLiteral("/bookmarks.xml"); } @@ -107,8 +104,7 @@ QString BookmarkHandler::titleForView(ViewProperties *view) const } if (!url.host().isEmpty()) { if (!url.userName().isEmpty()) { - return i18nc("@item:inmenu The user's name and host they are connected to via ssh", - "%1 on %2", url.userName(), url.host()); + return i18nc("@item:inmenu The user's name and host they are connected to via ssh", "%1 on %2", url.userName(), url.host()); } return i18nc("@item:inmenu The host the user is connected to via ssh", "%1", url.host()); } @@ -135,7 +131,7 @@ QList BookmarkHandler::currentBookmarkList() con list.reserve(_views.size()); const QList views = _views; - for (ViewProperties* view : views) { + for (ViewProperties *view : views) { list << KBookmarkOwner::FutureBookmark(titleForView(view), urlForView(view), iconForView(view)); } diff --git a/src/BookmarkHandler.h b/src/BookmarkHandler.h index 5c8c5bba5..d6d4fc1bf 100644 --- a/src/BookmarkHandler.h +++ b/src/BookmarkHandler.h @@ -22,7 +22,8 @@ class QMenu; class QUrl; class KActionCollection; -namespace Konsole { +namespace Konsole +{ class ViewProperties; /** diff --git a/src/BookmarkMenu.cpp b/src/BookmarkMenu.cpp index 3b51714e4..0016fcc13 100644 --- a/src/BookmarkMenu.cpp +++ b/src/BookmarkMenu.cpp @@ -12,18 +12,18 @@ // KDE #include +#include #include #include -#include // Qt #include #include -#include // std::any_of +#include // std::any_of -BookmarkMenu::BookmarkMenu (KBookmarkManager *mgr, KBookmarkOwner *owner, QMenu *parentMenu, KActionCollection *collection) : - KBookmarkMenu (mgr, owner, parentMenu) +BookmarkMenu::BookmarkMenu(KBookmarkManager *mgr, KBookmarkOwner *owner, QMenu *parentMenu, KActionCollection *collection) + : KBookmarkMenu(mgr, owner, parentMenu) { QAction *bookmarkAction; collection->addActions(parentMenu->actions()); @@ -52,8 +52,9 @@ void BookmarkMenu::maybeAddBookmark() const KBookmarkGroup rootGroup = manager()->root(); const QUrl currUrl = owner()->currentUrl(); const auto urlList = rootGroup.groupUrlList(); - if (std::any_of(urlList.constBegin(), urlList.constEnd(), - [currUrl] (const QUrl &url) { return url == currUrl; })) { + if (std::any_of(urlList.constBegin(), urlList.constEnd(), [currUrl](const QUrl &url) { + return url == currUrl; + })) { return; } diff --git a/src/BookmarkMenu.h b/src/BookmarkMenu.h index 5f8b1d125..32daa0bd2 100644 --- a/src/BookmarkMenu.h +++ b/src/BookmarkMenu.h @@ -26,10 +26,10 @@ class KONSOLEPRIVATE_EXPORT BookmarkMenu : public KBookmarkMenu Q_OBJECT public: - BookmarkMenu (KBookmarkManager *mgr, KBookmarkOwner *owner, QMenu *parentMenu, KActionCollection *collection); + BookmarkMenu(KBookmarkManager *mgr, KBookmarkOwner *owner, QMenu *parentMenu, KActionCollection *collection); private Q_SLOTS: void maybeAddBookmark(); }; -#endif//BOOKMARKMENU_H +#endif // BOOKMARKMENU_H diff --git a/src/CheckableSessionModel.cpp b/src/CheckableSessionModel.cpp index d01b0b811..5a00abb34 100644 --- a/src/CheckableSessionModel.cpp +++ b/src/CheckableSessionModel.cpp @@ -8,11 +8,11 @@ using namespace Konsole; -CheckableSessionModel::CheckableSessionModel(QObject *parent) : - SessionListModel(parent), - _checkedSessions(QSet()), - _fixedSessions(QSet()), - _checkColumn(0) +CheckableSessionModel::CheckableSessionModel(QObject *parent) + : SessionListModel(parent) + , _checkedSessions(QSet()) + , _fixedSessions(QSet()) + , _checkColumn(0) { } @@ -30,16 +30,14 @@ Qt::ItemFlags CheckableSessionModel::flags(const QModelIndex &index) const if (_fixedSessions.contains(session)) { return SessionListModel::flags(index) & ~Qt::ItemIsEnabled; } - return SessionListModel::flags(index) | Qt::ItemIsUserCheckable; + return SessionListModel::flags(index) | Qt::ItemIsUserCheckable; } QVariant CheckableSessionModel::data(const QModelIndex &index, int role) const { if (role == Qt::CheckStateRole && index.column() == _checkColumn) { auto *session = static_cast(index.internalPointer()); - return QVariant::fromValue(static_cast( - _checkedSessions.contains(session) ? Qt::Checked : Qt::Unchecked) - ); + return QVariant::fromValue(static_cast(_checkedSessions.contains(session) ? Qt::Checked : Qt::Unchecked)); } return SessionListModel::data(index, role); } diff --git a/src/CheckableSessionModel.h b/src/CheckableSessionModel.h index cb35e2099..d29657817 100644 --- a/src/CheckableSessionModel.h +++ b/src/CheckableSessionModel.h @@ -17,51 +17,50 @@ namespace Konsole { +/** + * A list of sessions with a checkbox next to each one which allows the + * user to select a subset of the available sessions to perform + * some action on them. + */ +class CheckableSessionModel : public SessionListModel +{ + Q_OBJECT + +public: + explicit CheckableSessionModel(QObject *parent); + + void setCheckColumn(int column); + int checkColumn() const; /** - * A list of sessions with a checkbox next to each one which allows the - * user to select a subset of the available sessions to perform - * some action on them. + * Sets whether a session can be checked or un-checked. + * Non-checkable items have the Qt::ItemIsEnabled flag unset. */ - class CheckableSessionModel : public SessionListModel - { - Q_OBJECT + void setCheckable(Session *session, bool checkable); - public: - explicit CheckableSessionModel(QObject *parent); + /** Sets the list of sessions which are currently checked. */ + void setCheckedSessions(const QSet &sessions); + /** Returns the set of checked sessions. */ + QSet checkedSessions() const; - void setCheckColumn(int column); - int checkColumn() const; + // reimplemented from QAbstractItemModel + Qt::ItemFlags flags(const QModelIndex &index) const override; + QVariant data(const QModelIndex &index, int role) const override; + bool setData(const QModelIndex &index, const QVariant &value, int role) override; - /** - * Sets whether a session can be checked or un-checked. - * Non-checkable items have the Qt::ItemIsEnabled flag unset. - */ - void setCheckable(Session *session, bool checkable); +protected: + void sessionRemoved(Session *) override; - /** Sets the list of sessions which are currently checked. */ - void setCheckedSessions(const QSet &sessions); - /** Returns the set of checked sessions. */ - QSet checkedSessions() const; +private: + QSet _checkedSessions; + QSet _fixedSessions; + int _checkColumn; +}; - // reimplemented from QAbstractItemModel - Qt::ItemFlags flags(const QModelIndex &index) const override; - QVariant data(const QModelIndex &index, int role) const override; - bool setData(const QModelIndex &index, const QVariant &value, int role) override; - - protected: - void sessionRemoved(Session *) override; - - private: - QSet _checkedSessions; - QSet _fixedSessions; - int _checkColumn; - }; - - inline int CheckableSessionModel::checkColumn() const - { - return _checkColumn; - } +inline int CheckableSessionModel::checkColumn() const +{ + return _checkColumn; +} } diff --git a/src/CopyInputDialog.cpp b/src/CopyInputDialog.cpp index 1dc115848..a811db715 100644 --- a/src/CopyInputDialog.cpp +++ b/src/CopyInputDialog.cpp @@ -11,8 +11,8 @@ #include // Konsole -#include "ui_CopyInputDialog.h" #include "CheckableSessionModel.h" +#include "ui_CopyInputDialog.h" #include #include @@ -21,14 +21,14 @@ using namespace Konsole; -CopyInputDialog::CopyInputDialog(QWidget *parent) : - QDialog(parent) +CopyInputDialog::CopyInputDialog(QWidget *parent) + : QDialog(parent) , _ui(nullptr) , _model(nullptr) , _masterSession(nullptr) { setWindowTitle(i18n("Copy Input")); - auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel); + auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); auto mainWidget = new QWidget(this); auto mainLayout = new QVBoxLayout; setLayout(mainLayout); @@ -44,10 +44,8 @@ CopyInputDialog::CopyInputDialog(QWidget *parent) : _ui = new Ui::CopyInputDialog(); _ui->setupUi(mainWidget); - connect(_ui->selectAllButton, &QPushButton::clicked, this, - &Konsole::CopyInputDialog::selectAll); - connect(_ui->deselectAllButton, &QPushButton::clicked, this, - &Konsole::CopyInputDialog::deselectAll); + connect(_ui->selectAllButton, &QPushButton::clicked, this, &Konsole::CopyInputDialog::selectAll); + connect(_ui->deselectAllButton, &QPushButton::clicked, this, &Konsole::CopyInputDialog::deselectAll); _ui->filterEdit->setClearButtonEnabled(true); _ui->filterEdit->setFocus(); @@ -62,8 +60,7 @@ CopyInputDialog::CopyInputDialog(QWidget *parent) : filterProxyModel->setSourceModel(_model); filterProxyModel->setFilterKeyColumn(-1); - connect(_ui->filterEdit, &QLineEdit::textChanged, filterProxyModel, - &QSortFilterProxyModel::setFilterFixedString); + connect(_ui->filterEdit, &QLineEdit::textChanged, filterProxyModel, &QSortFilterProxyModel::setFilterFixedString); _ui->sessionList->setModel(filterProxyModel); _ui->sessionList->setColumnHidden(0, true); // Hide number column @@ -126,5 +123,5 @@ void CopyInputDialog::setRowChecked(int row, bool checked) { QAbstractItemModel *model = _ui->sessionList->model(); QModelIndex index = model->index(row, _model->checkColumn()); - model->setData(index, static_cast( checked ? Qt::Checked : Qt::Unchecked), Qt::CheckStateRole); + model->setData(index, static_cast(checked ? Qt::Checked : Qt::Unchecked), Qt::CheckStateRole); } diff --git a/src/CopyInputDialog.h b/src/CopyInputDialog.h index 7dccf9ecb..34e2c3f25 100644 --- a/src/CopyInputDialog.h +++ b/src/CopyInputDialog.h @@ -15,15 +15,17 @@ #include // Konsole -#include "session/SessionManager.h" #include "session/Session.h" #include "session/SessionListModel.h" +#include "session/SessionManager.h" -namespace Ui { +namespace Ui +{ class CopyInputDialog; } -namespace Konsole { +namespace Konsole +{ class CheckableSessionModel; /** diff --git a/src/Emulation.cpp b/src/Emulation.cpp index ffb6e7f1b..dee6007a3 100644 --- a/src/Emulation.cpp +++ b/src/Emulation.cpp @@ -13,25 +13,25 @@ #include // Konsole -#include "keyboardtranslator/KeyboardTranslator.h" -#include "keyboardtranslator/KeyboardTranslatorManager.h" #include "Screen.h" #include "ScreenWindow.h" +#include "keyboardtranslator/KeyboardTranslator.h" +#include "keyboardtranslator/KeyboardTranslatorManager.h" using namespace Konsole; -Emulation::Emulation() : - _windows(QList()), - _currentScreen(nullptr), - _codec(nullptr), - _keyTranslator(nullptr), - _usesMouseTracking(false), - _bracketedPasteMode(false), - _bulkTimer1(QTimer(this)), - _bulkTimer2(QTimer(this)), - _imageSizeInitialized(false), - _peekingPrimary(false), - _activeScreenIndex(0) +Emulation::Emulation() + : _windows(QList()) + , _currentScreen(nullptr) + , _codec(nullptr) + , _keyTranslator(nullptr) + , _usesMouseTracking(false) + , _bracketedPasteMode(false) + , _bulkTimer1(QTimer(this)) + , _bulkTimer2(QTimer(this)) + , _imageSizeInitialized(false) + , _peekingPrimary(false) + , _activeScreenIndex(0) { // create screens with a default size _screen[0] = new Screen(40, 80); @@ -42,10 +42,8 @@ Emulation::Emulation() : QObject::connect(&_bulkTimer2, &QTimer::timeout, this, &Konsole::Emulation::showBulk); // listen for mouse status changes - connect(this, &Konsole::Emulation::programRequestsMouseTracking, this, - &Konsole::Emulation::setUsesMouseTracking); - connect(this, &Konsole::Emulation::programBracketedPasteModeChanged, this, - &Konsole::Emulation::bracketedPasteModeChanged); + connect(this, &Konsole::Emulation::programRequestsMouseTracking, this, &Konsole::Emulation::setUsesMouseTracking); + connect(this, &Konsole::Emulation::programBracketedPasteModeChanged, this, &Konsole::Emulation::bracketedPasteModeChanged); } bool Emulation::programUsesMouseTracking() const @@ -73,13 +71,10 @@ ScreenWindow *Emulation::createWindow() auto window = new ScreenWindow(_currentScreen); _windows << window; - connect(window, &Konsole::ScreenWindow::selectionChanged, this, - &Konsole::Emulation::bufferedUpdate); - connect(window, &Konsole::ScreenWindow::selectionChanged, this, - &Konsole::Emulation::checkSelectedText); + connect(window, &Konsole::ScreenWindow::selectionChanged, this, &Konsole::Emulation::bufferedUpdate); + connect(window, &Konsole::ScreenWindow::selectionChanged, this, &Konsole::Emulation::checkSelectedText); - connect(this, &Konsole::Emulation::outputChanged, window, - &Konsole::ScreenWindow::notifyOutputChanged); + connect(this, &Konsole::Emulation::outputChanged, window, &Konsole::ScreenWindow::notifyOutputChanged); return window; } @@ -238,14 +233,14 @@ void Emulation::receiveData(const char *text, int length) bufferedUpdate(); - //send characters to terminal emulator + // send characters to terminal emulator for (const uint i : _decoder->toUnicode(text, length).toUcs4()) { receiveChar(i); } - //look for z-modem indicator + // 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? + // this check into the above for loop? for (int i = 0; i < length - 4; i++) { if (text[i] == '\030') { if (qstrncmp(text + i + 1, "B00", 3) == 0) { @@ -303,12 +298,7 @@ void Emulation::setImageSize(int lines, int columns) return; } - QSize screenSize[2] = { - QSize(_screen[0]->getColumns(), - _screen[0]->getLines()), - QSize(_screen[1]->getColumns(), - _screen[1]->getLines()) - }; + 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]) { diff --git a/src/Emulation.h b/src/Emulation.h index e3b10c413..2b6d6faeb 100644 --- a/src/Emulation.h +++ b/src/Emulation.h @@ -15,14 +15,15 @@ // Konsole #include "Enumeration.h" -#include "terminalDisplay/TerminalDisplay.h" #include "konsoleprivate_export.h" +#include "terminalDisplay/TerminalDisplay.h" #include class QKeyEvent; -namespace Konsole { +namespace Konsole +{ class KeyboardTranslator; class HistoryType; class Screen; @@ -401,12 +402,12 @@ Q_SIGNALS: * to the terminal. * @p shape cursor shape * @p isBlinking if true, the cursor will be set to blink - */ + */ void setCursorStyleRequest(Enum::CursorShapeEnum shape = Enum::BlockCursor, bool isBlinking = false); /** * Emitted when reset() is called to reset the cursor style to the * current profile cursor shape and blinking settings. - */ + */ void resetCursorStyleRequest(); protected: @@ -428,25 +429,22 @@ protected: */ void setScreen(int index); - enum EmulationCodec { - LocaleCodec = 0, - Utf8Codec = 1 - }; + enum EmulationCodec { LocaleCodec = 0, Utf8Codec = 1, }; void setCodec(EmulationCodec codec); 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 + Screen *_screen[2]; // 0 = primary screen ( used by most programs, including the shell // scrollbars are enabled in this mode ) // 1 = alternate ( used by vi , emacs etc. // scrollbars are not enabled in this mode ) - //decodes an incoming C-style character stream into a unicode QString using - //the current text codec. (this allows for rendering of non-ASCII characters in text files etc.) + // 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; std::unique_ptr _decoder; const KeyboardTranslator *_keyTranslator; // the keyboard layout diff --git a/src/Enumeration.h b/src/Enumeration.h index 6f07797cf..070e47377 100644 --- a/src/Enumeration.h +++ b/src/Enumeration.h @@ -7,7 +7,8 @@ #ifndef ENUMERATION_H #define ENUMERATION_H -namespace Konsole { +namespace Konsole +{ /** * This class serves as a place for putting enum definitions that are * used or referenced in multiple places in the code. Keep it small. @@ -32,7 +33,7 @@ public: * Typically this means that lines are recorded to * a file as they are scrolled off-screen. */ - UnlimitedHistory = 2 + UnlimitedHistory = 2, }; /** @@ -45,7 +46,7 @@ public: /** Show the scroll-bar on the right of the terminal display. */ ScrollBarRight = 1, /** Do not show the scroll-bar. */ - ScrollBarHidden = 2 + ScrollBarHidden = 2, }; /** @@ -55,7 +56,7 @@ public: /** Scroll half page */ ScrollPageHalf = 0, /** Scroll full page */ - ScrollPageFull = 1 + ScrollPageFull = 1, }; /** This enum describes the shapes used to draw the cursor in terminal @@ -69,7 +70,7 @@ public: */ IBeamCursor = 1, /** Draw a line underneath the cursor's position. */ - UnderlineCursor = 2 + UnderlineCursor = 2, }; /** This enum describes the behavior of triple click action . */ @@ -77,7 +78,7 @@ public: /** Select the whole line underneath the cursor. */ SelectWholeLine = 0, /** Select from the current cursor position to the end of the line. */ - SelectForwardsFromCursor = 1 + SelectForwardsFromCursor = 1, }; /** This enum describes the source from which mouse middle click pastes data . */ @@ -85,7 +86,7 @@ public: /** Paste from X11 Selection. */ PasteFromX11Selection = 0, /** Paste from Clipboard. */ - PasteFromClipboard = 1 + PasteFromClipboard = 1, }; /** @@ -116,7 +117,7 @@ public: /** trigger visual bell(inverting the display's colors briefly). */ VisualBell = 2, /** No bell effects */ - NoBell = 3 + NoBell = 3, }; /** @@ -131,7 +132,7 @@ public: /** Searches backwards through the output, starting at the * current selection. */ - BackwardsSearch + BackwardsSearch, }; }; } diff --git a/src/EscapeSequenceUrlExtractor.cpp b/src/EscapeSequenceUrlExtractor.cpp index c91f0548d..56819702a 100644 --- a/src/EscapeSequenceUrlExtractor.cpp +++ b/src/EscapeSequenceUrlExtractor.cpp @@ -9,11 +9,11 @@ #include -namespace Konsole { -EscapeSequenceUrlExtractor::EscapeSequenceUrlExtractor() -= default; +namespace Konsole +{ +EscapeSequenceUrlExtractor::EscapeSequenceUrlExtractor() = default; -void Konsole::EscapeSequenceUrlExtractor::setScreen(Konsole::Screen* screen) +void Konsole::EscapeSequenceUrlExtractor::setScreen(Konsole::Screen *screen) { _screen = screen; clear(); @@ -44,7 +44,7 @@ void EscapeSequenceUrlExtractor::appendUrlText(QChar c) _currentUrl.text += c; } -void EscapeSequenceUrlExtractor::setUrl(const QString& url) +void EscapeSequenceUrlExtractor::setUrl(const QString &url) { if (_allowedUriSchemas.contains(QUrl(url).scheme() + QLatin1String("://"))) { _currentUrl.url = url; @@ -78,7 +78,7 @@ void EscapeSequenceUrlExtractor::clear() _history.clear(); } -void EscapeSequenceUrlExtractor::setAllowedLinkSchema(const QStringList& schema) +void EscapeSequenceUrlExtractor::setAllowedLinkSchema(const QStringList &schema) { _allowedUriSchemas = schema; } @@ -88,14 +88,14 @@ void EscapeSequenceUrlExtractor::historyLinesRemoved(int lines) for (auto &url : _history) { url.begin.row -= lines; url.end.row -= lines; - } - _history.erase( - std::remove_if(std::begin(_history), std::end(_history), [](const ExtractedUrl& url) { - const bool toRemove = url.begin.row < 0; - return toRemove; - - }), - std::end(_history)); + } + _history.erase(std::remove_if(std::begin(_history), + std::end(_history), + [](const ExtractedUrl &url) { + const bool toRemove = url.begin.row < 0; + return toRemove; + }), + std::end(_history)); } QVector EscapeSequenceUrlExtractor::history() const diff --git a/src/EscapeSequenceUrlExtractor.h b/src/EscapeSequenceUrlExtractor.h index fd6311eac..0f0c09dfa 100644 --- a/src/EscapeSequenceUrlExtractor.h +++ b/src/EscapeSequenceUrlExtractor.h @@ -8,15 +8,15 @@ SPDX-License-Identifier: GPL-2.0-or-later */ +#include "Screen.h" #include #include -#include "Screen.h" - -namespace Konsole { +namespace Konsole +{ /* Like QPoint, but with Row / Col -* easier to read than x / y -*/ + * easier to read than x / y + */ struct Coordinate { int row; int col; @@ -35,7 +35,8 @@ struct ExtractedUrl { /* Stored in Screen, but used in V10Emulation to * store extracted URL's. Perhaps this should be a Model? */ -class EscapeSequenceUrlExtractor { +class EscapeSequenceUrlExtractor +{ private: /* Tell us if we are currently reading or not a URL. */ bool _reading = false; @@ -52,7 +53,7 @@ private: * that will take over the history file. * TODO: make it configurable. */ - //Not used ATM const int _maximumUrlHistory = 200; + // Not used ATM const int _maximumUrlHistory = 200; /* All of the extracted URL's. */ QVector _history; @@ -72,7 +73,7 @@ public: /* This is a list of URI schemas that are going to be supported, separated by semicolon. * like https://;file:// */ - void setAllowedLinkSchema(const QStringList& allowedSchemas); + void setAllowedLinkSchema(const QStringList &allowedSchemas); void setScreen(Screen *screen); @@ -93,7 +94,7 @@ public: void appendUrlText(QChar c); /* The URL is parsed at once, store it at once. */ - void setUrl(const QString& url); + void setUrl(const QString &url); /* All of the parsedURL's, used by TerminalDisplay to paint them * on screen. */ diff --git a/src/FontDialog.cpp b/src/FontDialog.cpp index 2ec33c8ba..aa2e4cb4f 100644 --- a/src/FontDialog.cpp +++ b/src/FontDialog.cpp @@ -17,8 +17,8 @@ using namespace Konsole; -FontDialog::FontDialog(QWidget *parent) : - QDialog(parent) +FontDialog::FontDialog(QWidget *parent) + : QDialog(parent) , _fontChooser(nullptr) , _showAllFonts(nullptr) , _buttonBox(nullptr) @@ -33,16 +33,13 @@ FontDialog::FontDialog(QWidget *parent) : _showAllFonts = new QCheckBox(i18nc("@action:button", "Show all fonts"), this); _showAllFontsWarningButton = new QToolButton(this); - _buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | - QDialogButtonBox::Cancel, - Qt::Horizontal, this); + _buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, Qt::Horizontal, this); - _fontChooser->setSampleText(QStringLiteral( - "0OQ 1Il!| 5S 8B rnm :; ,. \"'` ~-= ({[<>]})\n" - "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~\n" - "ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789\n" - "abcdefghijklmnopqrstuvwxyz" - )); + _fontChooser->setSampleText( + QStringLiteral("0OQ 1Il!| 5S 8B rnm :; ,. \"'` ~-= ({[<>]})\n" + "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~\n" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789\n" + "abcdefghijklmnopqrstuvwxyz")); _showAllFontsWarningButton->setIcon(QIcon::fromTheme(QStringLiteral("emblem-warning"))); _showAllFontsWarningButton->setAutoRaise(true); @@ -51,7 +48,9 @@ FontDialog::FontDialog(QWidget *parent) : _fontChooser->setFont(_fontChooser->font(), !enable); }); connect(_showAllFontsWarningButton, &QToolButton::clicked, this, [this](bool) { - const QString message = i18nc("@info:status", "By its very nature, a terminal program requires font characters that are equal width (monospace). Any non monospaced font may cause display issues. This should not be necessary except in rare cases."); + const QString message = i18nc("@info:status", + "By its very nature, a terminal program requires font characters that are equal width (monospace). Any non monospaced " + "font may cause display issues. This should not be necessary except in rare cases."); const QPoint pos = QPoint(_showAllFonts->width() / 2, _showAllFonts->height()); QWhatsThis::showText(_showAllFonts->mapToGlobal(pos), message, _showAllFonts); }); diff --git a/src/FontDialog.h b/src/FontDialog.h index fde84b4a1..c29a973c2 100644 --- a/src/FontDialog.h +++ b/src/FontDialog.h @@ -8,21 +8,25 @@ #define FONTDIALOG_H // Qt -#include -#include #include +#include +#include #include #include -namespace Konsole { -class FontDialog: public QDialog +namespace Konsole +{ +class FontDialog : public QDialog { Q_OBJECT public: explicit FontDialog(QWidget *parent = nullptr); - QFont font() const { return _fontChooser->font(); } + QFont font() const + { + return _fontChooser->font(); + } void setFont(const QFont &font); Q_SIGNALS: diff --git a/src/HistorySizeDialog.cpp b/src/HistorySizeDialog.cpp index 17102464a..75b3525eb 100644 --- a/src/HistorySizeDialog.cpp +++ b/src/HistorySizeDialog.cpp @@ -9,8 +9,8 @@ #include "HistorySizeDialog.h" // Konsole -#include "ui_HistorySizeDialog.h" #include "Shortcut_p.h" +#include "ui_HistorySizeDialog.h" #include #include @@ -19,12 +19,12 @@ using namespace Konsole; -HistorySizeDialog::HistorySizeDialog(QWidget *parent) : - QDialog(parent), - _ui(nullptr) +HistorySizeDialog::HistorySizeDialog(QWidget *parent) + : QDialog(parent) + , _ui(nullptr) { setWindowTitle(i18nc("@title:window", "Adjust Scrollback")); - auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel); + auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); auto mainWidget = new QWidget(this); auto mainLayout = new QVBoxLayout; setLayout(mainLayout); @@ -44,8 +44,7 @@ HistorySizeDialog::HistorySizeDialog(QWidget *parent) : _ui->tempWarningWidget->setWordWrap(false); _ui->tempWarningWidget->setCloseButtonVisible(false); _ui->tempWarningWidget->setMessageType(KMessageWidget::Information); - _ui->tempWarningWidget->setText(i18nc("@info:status", - "Any adjustments are only temporary to this session.")); + _ui->tempWarningWidget->setText(i18nc("@info:status", "Any adjustments are only temporary to this session.")); } HistorySizeDialog::~HistorySizeDialog() @@ -73,7 +72,7 @@ void HistorySizeDialog::setLineCount(int lines) _ui->historySizeWidget->setLineCount(lines); } -QSize HistorySizeDialog::sizeHint() const { +QSize HistorySizeDialog::sizeHint() const +{ return {_ui->tempWarningWidget->sizeHint().width(), 0}; } - diff --git a/src/HistorySizeDialog.h b/src/HistorySizeDialog.h index 9ff936c03..71490b788 100644 --- a/src/HistorySizeDialog.h +++ b/src/HistorySizeDialog.h @@ -14,11 +14,13 @@ // Konsole #include "Enumeration.h" -namespace Ui { +namespace Ui +{ class HistorySizeDialog; } -namespace Konsole { +namespace Konsole +{ class HistorySizeDialog : public QDialog { Q_OBJECT diff --git a/src/KeyBindingEditor.cpp b/src/KeyBindingEditor.cpp index 1ff9ce2d8..a5df10a4a 100644 --- a/src/KeyBindingEditor.cpp +++ b/src/KeyBindingEditor.cpp @@ -8,28 +8,28 @@ // Qt #include -#include #include +#include // KDE #include #include // Konsole -#include "ui_KeyBindingEditor.h" #include "keyboardtranslator/KeyboardTranslator.h" -#include "keyboardtranslator/KeyboardTranslatorReader.h" #include "keyboardtranslator/KeyboardTranslatorManager.h" +#include "keyboardtranslator/KeyboardTranslatorReader.h" +#include "ui_KeyBindingEditor.h" #include "widgets/EditProfileDialog.h" using namespace Konsole; -KeyBindingEditor::KeyBindingEditor(QWidget *parent) : - QDialog(parent), - _ui(nullptr), - _translator(new KeyboardTranslator(QString())), - _isNewTranslator(false) +KeyBindingEditor::KeyBindingEditor(QWidget *parent) + : QDialog(parent) + , _ui(nullptr) + , _translator(new KeyboardTranslator(QString())) + , _isNewTranslator(false) { auto layout = new QVBoxLayout; @@ -52,11 +52,9 @@ KeyBindingEditor::KeyBindingEditor(QWidget *parent) : // description edit _ui->descriptionEdit->setPlaceholderText(i18nc("@label:textbox", "Enter descriptive label")); - connect(_ui->descriptionEdit, &QLineEdit::textChanged, this, - &Konsole::KeyBindingEditor::setTranslatorDescription); + connect(_ui->descriptionEdit, &QLineEdit::textChanged, this, &Konsole::KeyBindingEditor::setTranslatorDescription); // filter edit - connect(_ui->filterEdit, &QLineEdit::textChanged, this, - &Konsole::KeyBindingEditor::filterRows); + connect(_ui->filterEdit, &QLineEdit::textChanged, this, &Konsole::KeyBindingEditor::filterRows); // key bindings table _ui->keyBindingTable->setColumnCount(2); @@ -74,10 +72,8 @@ KeyBindingEditor::KeyBindingEditor(QWidget *parent) : _ui->addEntryButton->setIcon(QIcon::fromTheme(QStringLiteral("list-add"))); _ui->removeEntryButton->setIcon(QIcon::fromTheme(QStringLiteral("list-remove"))); - connect(_ui->removeEntryButton, &QPushButton::clicked, this, - &Konsole::KeyBindingEditor::removeSelectedEntry); - connect(_ui->addEntryButton, &QPushButton::clicked, this, - &Konsole::KeyBindingEditor::addNewEntry); + connect(_ui->removeEntryButton, &QPushButton::clicked, this, &Konsole::KeyBindingEditor::removeSelectedEntry); + connect(_ui->addEntryButton, &QPushButton::clicked, this, &Konsole::KeyBindingEditor::addNewEntry); // test area _ui->testAreaInputEdit->installEventFilter(this); @@ -113,7 +109,7 @@ void KeyBindingEditor::removeSelectedEntry() QList uniqueList; const QList selectedItems = _ui->keyBindingTable->selectedItems(); for (QTableWidgetItem *item : selectedItems) { - if (item->column() == 1) { //Select item at the first column + if (item->column() == 1) { // Select item at the first column item = _ui->keyBindingTable->item(item->row(), 0); } @@ -125,8 +121,7 @@ void KeyBindingEditor::removeSelectedEntry() for (QTableWidgetItem *item : qAsConst(uniqueList)) { // get the first item in the row which has the entry - KeyboardTranslator::Entry existing = item->data(Qt::UserRole). - value(); + KeyboardTranslator::Entry existing = item->data(Qt::UserRole).value(); _translator->removeEntry(existing); @@ -169,9 +164,7 @@ bool KeyBindingEditor::eventFilter(QObject *watched, QEvent *event) // const KeyboardTranslator::States states = KeyboardTranslator::AnsiState; - KeyboardTranslator::Entry entry = _translator->findEntry(keyEvent->key(), - keyEvent->modifiers(), - states); + KeyboardTranslator::Entry entry = _translator->findEntry(keyEvent->key(), keyEvent->modifiers(), states); if (!entry.isNull()) { _ui->testAreaInputEdit->setText(entry.conditionToString()); @@ -207,14 +200,13 @@ QString KeyBindingEditor::description() const return _ui->descriptionEdit->text(); } -void KeyBindingEditor::setup(const KeyboardTranslator *translator, - const QString ¤tProfileTranslator, bool isNewTranslator) +void KeyBindingEditor::setup(const KeyboardTranslator *translator, const QString ¤tProfileTranslator, bool isNewTranslator) { delete _translator; _isNewTranslator = isNewTranslator; - _currentProfileTranslator = currentProfileTranslator; + _currentProfileTranslator = currentProfileTranslator; _translator = new KeyboardTranslator(*translator); @@ -261,8 +253,7 @@ void KeyBindingEditor::bindingTableItemChanged(QTableWidgetItem *item) void KeyBindingEditor::setupKeyBindingTable(const KeyboardTranslator *translator) { - disconnect(_ui->keyBindingTable, &QTableWidget::itemChanged, this, - &Konsole::KeyBindingEditor::bindingTableItemChanged); + disconnect(_ui->keyBindingTable, &QTableWidget::itemChanged, this, &Konsole::KeyBindingEditor::bindingTableItemChanged); QList entries = translator->entries(); _ui->keyBindingTable->setRowCount(entries.count()); @@ -280,8 +271,7 @@ void KeyBindingEditor::setupKeyBindingTable(const KeyboardTranslator *translator } _ui->keyBindingTable->sortItems(0); - connect(_ui->keyBindingTable, &QTableWidget::itemChanged, this, - &Konsole::KeyBindingEditor::bindingTableItemChanged); + connect(_ui->keyBindingTable, &QTableWidget::itemChanged, this, &Konsole::KeyBindingEditor::bindingTableItemChanged); } void KeyBindingEditor::accept() @@ -319,8 +309,7 @@ QSize KeyBindingEditor::sizeHint() const { const auto parent = parentWidget(); if (parent != nullptr) { - return {static_cast(parent->width() * 0.9), - static_cast(parent->height() * 0.95)}; + return {static_cast(parent->width() * 0.9), static_cast(parent->height() * 0.95)}; } return {}; diff --git a/src/KeyBindingEditor.h b/src/KeyBindingEditor.h index e00efbce0..bf9023ce1 100644 --- a/src/KeyBindingEditor.h +++ b/src/KeyBindingEditor.h @@ -11,16 +11,18 @@ #include // Konsole -//TODO: Move away Profile::Property from the profile header. +// TODO: Move away Profile::Property from the profile header. #include "profile/Profile.h" class QTableWidgetItem; -namespace Ui { +namespace Ui +{ class KeyBindingEditor; } -namespace Konsole { +namespace Konsole +{ class KeyboardTranslator; /** @@ -54,8 +56,7 @@ public: * is an already existing one or a newly created * one, defaults to false. */ - void setup(const KeyboardTranslator *translator, const QString ¤tProfileTranslator, - bool isNewTranslator = false); + void setup(const KeyboardTranslator *translator, const QString ¤tProfileTranslator, bool isNewTranslator = false); /** * Returns the modified translator describing the changes to the bindings @@ -134,4 +135,4 @@ private: }; } -#endif //KEYBINDINGEDITOR_H +#endif // KEYBINDINGEDITOR_H diff --git a/src/LabelsAligner.cpp b/src/LabelsAligner.cpp index 831d35fe9..78aa247d8 100644 --- a/src/LabelsAligner.cpp +++ b/src/LabelsAligner.cpp @@ -9,8 +9,8 @@ #include "LabelsAligner.h" // Qt -#include #include +#include using namespace Konsole; @@ -24,7 +24,6 @@ void LabelsAligner::addLayout(QGridLayout *layout) _layouts.append(layout); } - void LabelsAligner::addLayouts(const QVector &layouts) { _layouts.append(layouts); @@ -37,7 +36,7 @@ void LabelsAligner::setReferenceWidget(QWidget *refWidget) void LabelsAligner::updateLayouts() { - for (const auto *layout: qAsConst(_layouts)) { + for (const auto *layout : qAsConst(_layouts)) { QWidget *widget = layout->parentWidget(); Q_ASSERT(widget); do { @@ -60,7 +59,7 @@ void LabelsAligner::align() } int maxRight = 0; - for (const auto *layout: qAsConst(_layouts)) { + for (const auto *layout : qAsConst(_layouts)) { int left = getLeftMargin(layout); for (int row = 0; row < layout->rowCount(); ++row) { QLayoutItem *layoutItem = layout->itemAtPosition(row, LABELS_COLUMN); @@ -85,7 +84,7 @@ void LabelsAligner::align() } } - for (auto *l: qAsConst(_layouts)) { + for (auto *l : qAsConst(_layouts)) { int left = getLeftMargin(l); l->setColumnMinimumWidth(LABELS_COLUMN, maxRight - left); } diff --git a/src/LabelsAligner.h b/src/LabelsAligner.h index 93d94e874..63c94e75a 100644 --- a/src/LabelsAligner.h +++ b/src/LabelsAligner.h @@ -13,41 +13,43 @@ class QWidget; class QGridLayout; -template class QVector; +template +class QVector; namespace Konsole { - /** - * An utility class for aligning 0th column in multiple QGridLayouts. - * - * Limitations: - * - a layout can't be nested in another layout - * - reference widget must be an ancestor of all added layouts - * - only 0th column is processed (widgets spanning multiple columns - * are ignored) - */ - class LabelsAligner: public QObject { - Q_OBJECT +/** + * An utility class for aligning 0th column in multiple QGridLayouts. + * + * Limitations: + * - a layout can't be nested in another layout + * - reference widget must be an ancestor of all added layouts + * - only 0th column is processed (widgets spanning multiple columns + * are ignored) + */ +class LabelsAligner : public QObject +{ + Q_OBJECT - public: - explicit LabelsAligner(QWidget *refWidget); +public: + explicit LabelsAligner(QWidget *refWidget); - void addLayout(QGridLayout *layout); - void addLayouts(const QVector &layouts); - void setReferenceWidget(QWidget *refWidget); + void addLayout(QGridLayout *layout); + void addLayouts(const QVector &layouts); + void setReferenceWidget(QWidget *refWidget); - public Q_SLOTS: - void updateLayouts(); - void align(); +public Q_SLOTS: + void updateLayouts(); + void align(); - private: - int getLeftMargin(const QGridLayout *layout); +private: + int getLeftMargin(const QGridLayout *layout); - static constexpr int LABELS_COLUMN = 0; + static constexpr int LABELS_COLUMN = 0; - QWidget *_refWidget; - QVector _layouts; - }; + QWidget *_refWidget; + QVector _layouts; +}; } diff --git a/src/MainWindow.cpp b/src/MainWindow.cpp index 02afb7040..023beab2c 100644 --- a/src/MainWindow.cpp +++ b/src/MainWindow.cpp @@ -8,9 +8,9 @@ #include "MainWindow.h" // Qt -#include #include #include +#include // KDE #include @@ -18,17 +18,16 @@ #include #include #include -#include #include +#include #include - #include +#include #include #include #include #include -#include #include #include @@ -60,14 +59,14 @@ using namespace Konsole; -MainWindow::MainWindow() : - KXmlGuiWindow(), - _viewManager(nullptr), - _bookmarkHandler(nullptr), - _toggleMenuBarAction(nullptr), - _newTabMenuAction(nullptr), - _pluggedController(nullptr), - _menuBarInitialVisibility(true) +MainWindow::MainWindow() + : KXmlGuiWindow() + , _viewManager(nullptr) + , _bookmarkHandler(nullptr) + , _toggleMenuBarAction(nullptr) + , _newTabMenuAction(nullptr) + , _pluggedController(nullptr) + , _menuBarInitialVisibility(true) { KSharedConfigPtr konsoleConfig = KSharedConfig::openConfig(QStringLiteral("konsolerc")); KConfigGroup cg = konsoleConfig->group(QStringLiteral("MainWindow")); @@ -92,12 +91,9 @@ MainWindow::MainWindow() : // After https://bugs.kde.org/show_bug.cgi?id=415150 was fixed in 5.74, // the config file keys changed #if KIO_VERSION < QT_VERSION_CHECK(5, 75, 0) - if (i.key().startsWith(QLatin1String("Width")) - || i.key().startsWith(QLatin1String("Height")) + if (i.key().startsWith(QLatin1String("Width")) || i.key().startsWith(QLatin1String("Height")) #else - if (i.key().contains(QLatin1String(" Width")) - || i.key().contains(QLatin1String(" Height")) - || i.key().contains(QLatin1String(" XPosition")) + if (i.key().contains(QLatin1String(" Width")) || i.key().contains(QLatin1String(" Height")) || i.key().contains(QLatin1String(" XPosition")) || i.key().contains(QLatin1String(" YPosition")) #endif ) { @@ -114,23 +110,15 @@ MainWindow::MainWindow() : // create view manager _viewManager = new ViewManager(this, actionCollection()); connect(_viewManager, &Konsole::ViewManager::empty, this, &QWidget::close); - connect(_viewManager, &Konsole::ViewManager::activeViewChanged, this, - &Konsole::MainWindow::activeViewChanged); - connect(_viewManager, &Konsole::ViewManager::unplugController, this, - &Konsole::MainWindow::disconnectController); - connect(_viewManager, &Konsole::ViewManager::viewPropertiesChanged, - bookmarkHandler(), &Konsole::BookmarkHandler::setViews); - connect(_viewManager, &Konsole::ViewManager::blurSettingChanged, - this, &Konsole::MainWindow::setBlur); + connect(_viewManager, &Konsole::ViewManager::activeViewChanged, this, &Konsole::MainWindow::activeViewChanged); + connect(_viewManager, &Konsole::ViewManager::unplugController, this, &Konsole::MainWindow::disconnectController); + connect(_viewManager, &Konsole::ViewManager::viewPropertiesChanged, bookmarkHandler(), &Konsole::BookmarkHandler::setViews); + connect(_viewManager, &Konsole::ViewManager::blurSettingChanged, this, &Konsole::MainWindow::setBlur); - connect(_viewManager, &Konsole::ViewManager::updateWindowIcon, this, - &Konsole::MainWindow::updateWindowIcon); - connect(_viewManager, &Konsole::ViewManager::newViewWithProfileRequest, - this, &Konsole::MainWindow::newFromProfile); - connect(_viewManager, &Konsole::ViewManager::newViewRequest, - this, &Konsole::MainWindow::newTab); - connect(_viewManager, &Konsole::ViewManager::terminalsDetached, this, - &Konsole::MainWindow::terminalsDetached); + connect(_viewManager, &Konsole::ViewManager::updateWindowIcon, this, &Konsole::MainWindow::updateWindowIcon); + connect(_viewManager, &Konsole::ViewManager::newViewWithProfileRequest, this, &Konsole::MainWindow::newFromProfile); + connect(_viewManager, &Konsole::ViewManager::newViewRequest, this, &Konsole::MainWindow::newTab); + connect(_viewManager, &Konsole::ViewManager::terminalsDetached, this, &Konsole::MainWindow::terminalsDetached); setCentralWidget(_viewManager->widget()); @@ -155,8 +143,7 @@ MainWindow::MainWindow() : // this must come at the end applyKonsoleSettings(); - connect(KonsoleSettings::self(), &Konsole::KonsoleSettings::configChanged, this, - &Konsole::MainWindow::applyKonsoleSettings); + connect(KonsoleSettings::self(), &Konsole::KonsoleSettings::configChanged, this, &Konsole::MainWindow::applyKonsoleSettings); KCrash::initialize(); } @@ -224,12 +211,9 @@ ViewManager *MainWindow::viewManager() const void MainWindow::disconnectController(SessionController *controller) { - disconnect(controller, &Konsole::SessionController::titleChanged, - this, &Konsole::MainWindow::activeViewTitleChanged); - disconnect(controller, &Konsole::SessionController::rawTitleChanged, - this, &Konsole::MainWindow::updateWindowCaption); - disconnect(controller, &Konsole::SessionController::iconChanged, - this, &Konsole::MainWindow::updateWindowIcon); + disconnect(controller, &Konsole::SessionController::titleChanged, this, &Konsole::MainWindow::activeViewTitleChanged); + disconnect(controller, &Konsole::SessionController::rawTitleChanged, this, &Konsole::MainWindow::updateWindowCaption); + disconnect(controller, &Konsole::SessionController::iconChanged, this, &Konsole::MainWindow::updateWindowIcon); if (auto view = controller->view()) { view->removeEventFilter(this); @@ -256,8 +240,7 @@ void MainWindow::activeViewChanged(SessionController *controller) // associate bookmark menu with current session bookmarkHandler()->setActiveView(controller); disconnect(bookmarkHandler(), &Konsole::BookmarkHandler::openUrl, nullptr, nullptr); - connect(bookmarkHandler(), &Konsole::BookmarkHandler::openUrl, controller, - &Konsole::SessionController::openUrl); + connect(bookmarkHandler(), &Konsole::BookmarkHandler::openUrl, controller, &Konsole::SessionController::openUrl); if (!_pluggedController.isNull()) { disconnectController(_pluggedController); @@ -270,12 +253,9 @@ void MainWindow::activeViewChanged(SessionController *controller) setBlur(ViewManager::profileHasBlurEnabled(SessionManager::instance()->sessionProfile(_pluggedController->session()))); // listen for title changes from the current session - connect(controller, &Konsole::SessionController::titleChanged, this, - &Konsole::MainWindow::activeViewTitleChanged); - connect(controller, &Konsole::SessionController::rawTitleChanged, this, - &Konsole::MainWindow::updateWindowCaption); - connect(controller, &Konsole::SessionController::iconChanged, this, - &Konsole::MainWindow::updateWindowIcon); + connect(controller, &Konsole::SessionController::titleChanged, this, &Konsole::MainWindow::activeViewTitleChanged); + connect(controller, &Konsole::SessionController::rawTitleChanged, this, &Konsole::MainWindow::updateWindowCaption); + connect(controller, &Konsole::SessionController::iconChanged, this, &Konsole::MainWindow::updateWindowIcon); controller->setShowMenuAction(_toggleMenuBarAction); guiFactory()->addClient(controller); @@ -328,8 +308,7 @@ void MainWindow::setupActions() KActionCollection *collection = actionCollection(); // File Menu - _newTabMenuAction = new KActionMenu(QIcon::fromTheme(QStringLiteral("tab-new")), - i18nc("@action:inmenu", "&New Tab"), collection); + _newTabMenuAction = new KActionMenu(QIcon::fromTheme(QStringLiteral("tab-new")), i18nc("@action:inmenu", "&New Tab"), collection); collection->setDefaultShortcut(_newTabMenuAction, Konsole::ACCEL | Qt::SHIFT | Qt::Key_T); collection->setShortcutsConfigurable(_newTabMenuAction, true); _newTabMenuAction->setAutoRepeat(false); @@ -337,7 +316,7 @@ void MainWindow::setupActions() collection->addAction(QStringLiteral("new-tab"), _newTabMenuAction); collection->setShortcutsConfigurable(_newTabMenuAction, true); - QAction* menuAction = collection->addAction(QStringLiteral("clone-tab")); + QAction *menuAction = collection->addAction(QStringLiteral("clone-tab")); menuAction->setIcon(QIcon::fromTheme(QStringLiteral("tab-duplicate"))); menuAction->setText(i18nc("@action:inmenu", "&Clone Tab")); collection->setDefaultShortcut(menuAction, QKeySequence()); @@ -361,8 +340,7 @@ void MainWindow::setupActions() KActionMenu *bookmarkMenu = new KActionMenu(i18nc("@title:menu", "&Bookmarks"), collection); _bookmarkHandler = new BookmarkHandler(collection, bookmarkMenu->menu(), true, this); collection->addAction(QStringLiteral("bookmark"), bookmarkMenu); - connect(_bookmarkHandler, &Konsole::BookmarkHandler::openUrls, this, - &Konsole::MainWindow::openUrls); + connect(_bookmarkHandler, &Konsole::BookmarkHandler::openUrls, this, &Konsole::MainWindow::openUrls); // Settings Menu _toggleMenuBarAction = KStandardAction::showMenubar(menuBar(), &QMenuBar::setVisible, collection); @@ -391,14 +369,18 @@ void MainWindow::setupActions() action->setEnabled(true); action->setText(i18nc("@action:inmenu", "Save tab layout to file")); connect(action, &QAction::triggered, this, [this]() { - if (viewManager()) { viewManager()->saveLayoutFile(); } + if (viewManager()) { + viewManager()->saveLayoutFile(); + } }); action = collection->addAction(QStringLiteral("load-layout")); action->setEnabled(true); action->setText(i18nc("@action:inmenu", "Load tab layout from file")); connect(action, &QAction::triggered, this, [this]() { - if (viewManager()) { viewManager()->loadLayoutFile(); } + if (viewManager()) { + viewManager()->loadLayoutFile(); + } }); } @@ -483,8 +465,7 @@ void MainWindow::newTab() void MainWindow::addPlugin(IKonsolePlugin *plugin) { _plugins.append(plugin); - connect(_viewManager, &Konsole::ViewManager::activeViewChanged, plugin, - &IKonsolePlugin::activeViewChanged); + connect(_viewManager, &Konsole::ViewManager::activeViewChanged, plugin, &IKonsolePlugin::activeViewChanged); } void MainWindow::cloneTab() @@ -574,8 +555,8 @@ bool MainWindow::queryClose() // Check what processes are running, excluding the shell QStringList processesRunning; // Need to make a local copy so the begin() and end() point to the same QList - const QList sessionList = _viewManager->sessions(); - const QSet uniqueSessions(sessionList.begin(), sessionList.end()); + const QList sessionList = _viewManager->sessions(); + const QSet uniqueSessions(sessionList.begin(), sessionList.end()); for (Session *session : uniqueSessions) { if ((session == nullptr) || !session->isForegroundProcessActive()) { @@ -615,21 +596,19 @@ bool MainWindow::queryClose() if (!processesRunning.isEmpty()) { if (openTabs == 1) { result = KMessageBox::warningYesNoList(this, - i18ncp("@info", - "There is a process running in this window. " - "Do you still want to quit?", - "There are %1 processes running in this window. " - "Do you still want to quit?", - processesRunning.count()), - processesRunning, - i18nc("@title", "Confirm Close"), - KGuiItem(i18nc("@action:button", - "Close &Window"), - QStringLiteral("window-close")), - KStandardGuiItem::cancel(), - // don't ask again name is wrong but I can't update. - // this is not about tabs anymore. it's about empty tabs *or* splits. - QStringLiteral("CloseAllTabs")); + i18ncp("@info", + "There is a process running in this window. " + "Do you still want to quit?", + "There are %1 processes running in this window. " + "Do you still want to quit?", + processesRunning.count()), + processesRunning, + i18nc("@title", "Confirm Close"), + KGuiItem(i18nc("@action:button", "Close &Window"), QStringLiteral("window-close")), + KStandardGuiItem::cancel(), + // don't ask again name is wrong but I can't update. + // this is not about tabs anymore. it's about empty tabs *or* splits. + QStringLiteral("CloseAllTabs")); if (result == KMessageBox::No) // No is equal to cancel closing result = KMessageBox::Cancel; } else { @@ -642,12 +621,8 @@ bool MainWindow::queryClose() processesRunning.count()), processesRunning, i18nc("@title", "Confirm Close"), - KGuiItem(i18nc("@action:button", - "Close &Window"), - QStringLiteral("window-close")), - KGuiItem(i18nc("@action:button", - "Close Current &Tab"), - QStringLiteral("tab-close")), + KGuiItem(i18nc("@action:button", "Close &Window"), QStringLiteral("window-close")), + KGuiItem(i18nc("@action:button", "Close Current &Tab"), QStringLiteral("tab-close")), KStandardGuiItem::cancel(), // don't ask again name is wrong but I can't update. // this is not about tabs anymore. it's about empty tabs *or* splits. @@ -660,11 +635,8 @@ bool MainWindow::queryClose() "Do you still want to quit?", openTabs), i18nc("@title", "Confirm Close"), - KGuiItem(i18nc("@action:button", "Close &Window"), - QStringLiteral("window-close")), - KGuiItem(i18nc("@action:button", - "Close Current &Tab"), - QStringLiteral("tab-close")), + KGuiItem(i18nc("@action:button", "Close &Window"), QStringLiteral("window-close")), + KGuiItem(i18nc("@action:button", "Close Current &Tab"), QStringLiteral("tab-close")), KStandardGuiItem::cancel(), // don't ask again name is wrong but I can't update. // this is not about tabs anymore. it's about empty tabs *or* splits. @@ -722,8 +694,7 @@ void MainWindow::syncActiveShortcuts(KActionCollection *dest, const KActionColle void MainWindow::showShortcutsDialog() { - KShortcutsDialog dialog(KShortcutsEditor::AllActions, - KShortcutsEditor::LetterShortcutsDisallowed, this); + KShortcutsDialog dialog(KShortcutsEditor::AllActions, KShortcutsEditor::LetterShortcutsDisallowed, this); // add actions from this window and the current session controller const QList clientsList = guiFactory()->clients(); @@ -871,7 +842,7 @@ void MainWindow::setBlur(bool blur) _blurEnabled = blur; if (!_pluggedController->isKonsolePart()) { -#if KWINDOWSYSTEM_VERSION < QT_VERSION_CHECK(5,82,0) +#if KWINDOWSYSTEM_VERSION < QT_VERSION_CHECK(5, 82, 0) KWindowEffects::enableBlurBehind(winId(), blur); #else // Set the WA_NativeWindow attribute to force the creation of the QWindow. @@ -900,7 +871,7 @@ void MainWindow::setRemoveWindowTitleBarAndFrame(bool frameless) if (!isVisible()) { setWindowFlags(newFlags); - // The window is visible and the setting changed + // The window is visible and the setting changed } else if (windowFlags().testFlag(Qt::FramelessWindowHint) != frameless) { const auto oldGeometry = saveGeometry(); // This happens for every Konsole window. It depends on @@ -954,19 +925,19 @@ void MainWindow::triggerAction(const QString &name) const bool MainWindow::eventFilter(QObject *obj, QEvent *event) { if (!_pluggedController.isNull() && obj == _pluggedController->view()) { - switch(event->type()) { - case QEvent::MouseButtonPress: - case QEvent::MouseButtonDblClick: - switch(static_cast(event)->button()) { - case Qt::ForwardButton: - triggerAction(QStringLiteral("next-view")); - break; - case Qt::BackButton: - triggerAction(QStringLiteral("previous-view")); - break; - default: ; + switch (event->type()) { + case QEvent::MouseButtonPress: + case QEvent::MouseButtonDblClick: + switch (static_cast(event)->button()) { + case Qt::ForwardButton: + triggerAction(QStringLiteral("next-view")); + break; + case Qt::BackButton: + triggerAction(QStringLiteral("previous-view")); + break; + default:; } - default: ; + default:; } } @@ -975,7 +946,7 @@ bool MainWindow::eventFilter(QObject *obj, QEvent *event) bool MainWindow::focusNextPrevChild(bool v) { - if (qobject_cast(focusWidget())) { + if (qobject_cast(focusWidget())) { return false; } diff --git a/src/MainWindow.h b/src/MainWindow.h index e598b3b6f..b7b6e75f7 100644 --- a/src/MainWindow.h +++ b/src/MainWindow.h @@ -8,9 +8,9 @@ #define MAINWINDOW_H // Qt +#include #include #include -#include // KDE #include @@ -26,7 +26,8 @@ class QAction; class KActionMenu; class KToggleAction; -namespace Konsole { +namespace Konsole +{ class ViewManager; class ViewProperties; class Session; @@ -77,7 +78,7 @@ public: * @param profile The profile to use to create the new session. * @param url the URL representing the new SSH connection */ - Session *createSSHSession(QExplicitlySharedDataPointer profile , const QUrl &url); + Session *createSSHSession(QExplicitlySharedDataPointer profile, const QUrl &url); /** * Helper method to make this window get input focus @@ -89,7 +90,6 @@ public: */ void setMenuBarInitialVisibility(bool visible); - /** * @brief Set the frameless state * @@ -124,7 +124,7 @@ Q_SIGNALS: /** * Emitted when a view for one session is detached from this window */ - void terminalsDetached(ViewSplitter *splitter, QHash sessionsMap); + void terminalsDetached(ViewSplitter *splitter, QHash sessionsMap); protected: // Reimplemented for internal reasons. @@ -196,7 +196,7 @@ private: KActionMenu *_newTabMenuAction; QPointer _pluggedController; - QList _plugins; + QList _plugins; bool _menuBarInitialVisibility; bool _firstShowEvent = true; bool _blurEnabled = false; diff --git a/src/NullProcessInfo.h b/src/NullProcessInfo.h index 81b5b4cfd..a131a8116 100644 --- a/src/NullProcessInfo.h +++ b/src/NullProcessInfo.h @@ -11,27 +11,27 @@ namespace Konsole { - +/** + * Implementation of ProcessInfo which does nothing. + * Used on platforms where a suitable ProcessInfo subclass is not + * available. + * + * isValid() will always return false for instances of NullProcessInfo + */ +class NullProcessInfo : public ProcessInfo +{ +public: /** - * Implementation of ProcessInfo which does nothing. - * Used on platforms where a suitable ProcessInfo subclass is not - * available. - * - * isValid() will always return false for instances of NullProcessInfo + * Constructs a new NullProcessInfo instance. + * See ProcessInfo::newInstance() */ - class NullProcessInfo : public ProcessInfo - { - public: - /** - * Constructs a new NullProcessInfo instance. - * See ProcessInfo::newInstance() - */ - explicit NullProcessInfo(int pid); - protected: - void readProcessInfo(int pid) override; - bool readCurrentDir(int pid) override; - void readUserName(void) override; - }; + explicit NullProcessInfo(int pid); + +protected: + void readProcessInfo(int pid) override; + bool readCurrentDir(int pid) override; + void readUserName(void) override; +}; } diff --git a/src/Part.cpp b/src/Part.cpp index b6cbe1e43..b0c808882 100644 --- a/src/Part.cpp +++ b/src/Part.cpp @@ -8,18 +8,18 @@ #include "Part.h" // Qt -#include #include #include #include +#include #include // KDE -#include #include -#include -#include #include +#include +#include +#include // Konsole #include "Emulation.h" @@ -30,27 +30,24 @@ #include "session/SessionManager.h" #include "settings/PartInfo.h" #include "settings/ProfileSettings.h" -#include "widgets/EditProfileDialog.h" #include "terminalDisplay/TerminalDisplay.h" +#include "widgets/EditProfileDialog.h" #include "widgets/ViewContainer.h" using namespace Konsole; -K_PLUGIN_FACTORY_WITH_JSON(KonsolePartFactory, - "konsolepart.json", - registerPlugin();) +K_PLUGIN_FACTORY_WITH_JSON(KonsolePartFactory, "konsolepart.json", registerPlugin();) -Part::Part(QWidget *parentWidget, QObject *parent, const QVariantList &) : - KParts::ReadOnlyPart(parent), - _viewManager(nullptr), - _pluggedController(nullptr) +Part::Part(QWidget *parentWidget, QObject *parent, const QVariantList &) + : KParts::ReadOnlyPart(parent) + , _viewManager(nullptr) + , _pluggedController(nullptr) { // create view widget _viewManager = new ViewManager(this, actionCollection()); _viewManager->setNavigationMethod(ViewManager::NoNavigation); - connect(_viewManager, &Konsole::ViewManager::activeViewChanged, this, - &Konsole::Part::activeViewChanged); + connect(_viewManager, &Konsole::ViewManager::activeViewChanged, this, &Konsole::Part::activeViewChanged); connect(_viewManager, &Konsole::ViewManager::empty, this, &Konsole::Part::terminalExited); connect(_viewManager, &Konsole::ViewManager::newViewRequest, this, &Konsole::Part::newTab); @@ -207,9 +204,8 @@ QString Part::currentProfileName() const bool Part::setCurrentProfile(const QString &profileName) { - Profile::Ptr profile; - for(auto p : ProfileManager::instance()->allProfiles()) { + for (auto p : ProfileManager::instance()->allProfiles()) { if (p->name() == profileName) { profile = p; break; @@ -253,20 +249,16 @@ void Part::activeViewChanged(SessionController *controller) // remove existing controller if (_pluggedController != nullptr) { removeChildClient(_pluggedController); - disconnect(_pluggedController, &Konsole::SessionController::titleChanged, this, - &Konsole::Part::activeViewTitleChanged); - disconnect(_pluggedController, &Konsole::SessionController::currentDirectoryChanged, this, - &Konsole::Part::currentDirectoryChanged); + disconnect(_pluggedController, &Konsole::SessionController::titleChanged, this, &Konsole::Part::activeViewTitleChanged); + disconnect(_pluggedController, &Konsole::SessionController::currentDirectoryChanged, this, &Konsole::Part::currentDirectoryChanged); } // insert new controller insertChildClient(controller); - connect(controller, &Konsole::SessionController::titleChanged, this, - &Konsole::Part::activeViewTitleChanged); + connect(controller, &Konsole::SessionController::titleChanged, this, &Konsole::Part::activeViewTitleChanged); activeViewTitleChanged(controller); - connect(controller, &Konsole::SessionController::currentDirectoryChanged, this, - &Konsole::Part::currentDirectoryChanged); + connect(controller, &Konsole::SessionController::currentDirectoryChanged, this, &Konsole::Part::currentDirectoryChanged); disconnect(controller->view(), &TerminalDisplay::overrideShortcutCheck, this, &Part::overrideTerminalShortcut); connect(controller->view(), &TerminalDisplay::overrideShortcutCheck, this, &Part::overrideTerminalShortcut); @@ -279,8 +271,7 @@ void Part::overrideTerminalShortcut(QKeyEvent *event, bool &override) // Shift+Insert is commonly used as the alternate shortcut for // pasting in KDE apps(including konsole), so it deserves some // special treatment. - if (((event->modifiers() & Qt::ShiftModifier) != 0U) - && (event->key() == Qt::Key_Insert)) { + if (((event->modifiers() & Qt::ShiftModifier) != 0U) && (event->key() == Qt::Key_Insert)) { override = false; return; } @@ -302,21 +293,14 @@ void Part::showManageProfilesDialog(QWidget *parent) return; } - KConfigDialog *settingsDialog = new KConfigDialog(parent, QStringLiteral("konsolepartmanageprofiles"), - KonsoleSettings::self()); + KConfigDialog *settingsDialog = new KConfigDialog(parent, QStringLiteral("konsolepartmanageprofiles"), KonsoleSettings::self()); settingsDialog->setFaceType(KPageDialog::Tabbed); auto profileSettings = new ProfileSettings(settingsDialog); - settingsDialog->addPage(profileSettings, - i18nc("@title Preferences page name", - "Profiles"), - QStringLiteral("configure")); + settingsDialog->addPage(profileSettings, i18nc("@title Preferences page name", "Profiles"), QStringLiteral("configure")); auto partInfoSettings = new PartInfoSettings(settingsDialog); - settingsDialog->addPage(partInfoSettings, - i18nc("@title Preferences page name", - "Part Info"), - QStringLiteral("dialog-information")); + settingsDialog->addPage(partInfoSettings, i18nc("@title Preferences page name", "Part Info"), QStringLiteral("dialog-information")); settingsDialog->show(); } @@ -372,14 +356,11 @@ void Part::setMonitorSilenceEnabled(bool enabled) if (enabled) { activeSession()->setMonitorSilence(true); - connect(activeSession(), &Konsole::Session::notificationsChanged, - this, &Konsole::Part::notificationChanged, - Qt::UniqueConnection); + connect(activeSession(), &Konsole::Session::notificationsChanged, this, &Konsole::Part::notificationChanged, Qt::UniqueConnection); } else { activeSession()->setMonitorSilence(false); if (!activeSession()->isMonitorActivity()) { - disconnect(activeSession(), &Konsole::Session::notificationsChanged, - this, &Konsole::Part::notificationChanged); + disconnect(activeSession(), &Konsole::Session::notificationsChanged, this, &Konsole::Part::notificationChanged); } } } @@ -390,15 +371,11 @@ void Part::setMonitorActivityEnabled(bool enabled) if (enabled) { activeSession()->setMonitorActivity(true); - connect(activeSession(), &Konsole::Session::notificationsChanged, - this, &Konsole::Part::notificationChanged, - Qt::UniqueConnection); + connect(activeSession(), &Konsole::Session::notificationsChanged, this, &Konsole::Part::notificationChanged, Qt::UniqueConnection); } else { activeSession()->setMonitorActivity(false); if (!activeSession()->isMonitorSilence()) { - disconnect(activeSession(), &Konsole::Session::notificationsChanged, - this, - &Konsole::Part::notificationChanged); + disconnect(activeSession(), &Konsole::Session::notificationsChanged, this, &Konsole::Part::notificationChanged); } } } diff --git a/src/Part.h b/src/Part.h index 2cb42fef5..50497c56c 100644 --- a/src/Part.h +++ b/src/Part.h @@ -15,13 +15,14 @@ #include // Konsole -#include "session/Session.h" #include "config-konsole.h" +#include "session/Session.h" class QStringList; class QKeyEvent; -namespace Konsole { +namespace Konsole +{ class Session; class SessionController; class ViewManager; @@ -90,10 +91,9 @@ public Q_SLOTS: * * This is highly experimental. Do not use it at the moment */ - void createSession(const QString &profileName = QString(), - const QString &directory = QString()); + void createSession(const QString &profileName = QString(), const QString &directory = QString()); - void showManageProfilesDialog(QWidget* parent); + void showManageProfilesDialog(QWidget *parent); /** * Shows the dialog used to edit the profile used by the active session. The @@ -137,11 +137,11 @@ public Q_SLOTS: void setMonitorSilenceEnabled(bool enabled); /** - * Toggles monitoring for activity in the active session. If activity is detected, - * the activityDetected() signal is emitted. - * - * @param enabled Whether to enable or disable monitoring for activity. - * */ + * Toggles monitoring for activity in the active session. If activity is detected, + * the activityDetected() signal is emitted. + * + * @param enabled Whether to enable or disable monitoring for activity. + * */ void setMonitorActivityEnabled(bool enabled); /** @@ -200,6 +200,7 @@ private Q_SLOTS: void newTab(); void overrideTerminalShortcut(QKeyEvent *, bool &override); void notificationChanged(Session::Notification notification, bool enabled); + private: Session *activeSession() const; diff --git a/src/PopStackOnExit.h b/src/PopStackOnExit.h index 40788c77c..daef63223 100644 --- a/src/PopStackOnExit.h +++ b/src/PopStackOnExit.h @@ -13,36 +13,36 @@ namespace Konsole { - /** - * PopStackOnExit is a utility to remove all values from a QStack which are added during - * the lifetime of a PopStackOnExit instance. - * - * When a PopStackOnExit instance is destroyed, elements are removed from the stack - * until the stack count is reduced the value when the PopStackOnExit instance was created. - */ - template - class PopStackOnExit +/** + * PopStackOnExit is a utility to remove all values from a QStack which are added during + * the lifetime of a PopStackOnExit instance. + * + * When a PopStackOnExit instance is destroyed, elements are removed from the stack + * until the stack count is reduced the value when the PopStackOnExit instance was created. + */ +template +class PopStackOnExit +{ +public: + explicit PopStackOnExit(QStack &stack) + : _stack(stack) + , _count(stack.count()) { - public: - explicit PopStackOnExit(QStack &stack) - : _stack(stack) - , _count(stack.count()) - { + } + + ~PopStackOnExit() + { + while (_stack.count() > _count) { + _stack.pop(); } + } - ~PopStackOnExit() - { - while (_stack.count() > _count) { - _stack.pop(); - } - } +private: + Q_DISABLE_COPY(PopStackOnExit) - private: - Q_DISABLE_COPY(PopStackOnExit) - - QStack &_stack; - int _count; - }; + QStack &_stack; + int _count; +}; } #endif diff --git a/src/PrintOptions.cpp b/src/PrintOptions.cpp index d7391cd65..b26afb2a6 100644 --- a/src/PrintOptions.cpp +++ b/src/PrintOptions.cpp @@ -13,7 +13,8 @@ using namespace Konsole; -PrintOptions::PrintOptions(QWidget *parent) : QWidget(parent) +PrintOptions::PrintOptions(QWidget *parent) + : QWidget(parent) { setupUi(this); diff --git a/src/PrintOptions.h b/src/PrintOptions.h index 5ff1a888c..0031c2a22 100644 --- a/src/PrintOptions.h +++ b/src/PrintOptions.h @@ -9,7 +9,8 @@ #include "ui_PrintOptions.h" -namespace Konsole { +namespace Konsole +{ class PrintOptions : public QWidget, private Ui::PrintOptions { Q_OBJECT diff --git a/src/ProcessInfo.cpp b/src/ProcessInfo.cpp index 8dc6bcd73..3aee5515f 100644 --- a/src/ProcessInfo.cpp +++ b/src/ProcessInfo.cpp @@ -8,28 +8,28 @@ #include "config-konsole.h" // Own -#include "ProcessInfo.h" #include "NullProcessInfo.h" +#include "ProcessInfo.h" #if !defined(Q_OS_WIN) - #include "UnixProcessInfo.h" +#include "UnixProcessInfo.h" #endif #include "SSHProcessInfo.h" // Unix -#include -#include #include -#include +#include +#include #include #include -#include +#include +#include // Qt #include #include -#include -#include #include +#include +#include // KDE #include @@ -46,37 +46,36 @@ #endif #if defined(Q_OS_FREEBSD) || defined(Q_OS_OPENBSD) +#include #include #include -#include -# if defined(Q_OS_FREEBSD) -# include -# include -# include -# endif +#if defined(Q_OS_FREEBSD) +#include +#include +#include +#endif #endif using namespace Konsole; -ProcessInfo::ProcessInfo(int pid) : - _fields(ARGUMENTS) // arguments +ProcessInfo::ProcessInfo(int pid) + : _fields(ARGUMENTS) // arguments // are currently always valid, // they just return an empty // vector / map respectively // if no arguments // have been explicitly set - , - _pid(pid), - _parentPid(0), - _foregroundPid(0), - _userId(0), - _lastError(NoError), - _name(QString()), - _userName(QString()), - _userHomeDir(QString()), - _currentDir(QString()), - _userNameRequired(true), - _arguments(QVector()) + , _pid(pid) + , _parentPid(0) + , _foregroundPid(0) + , _userId(0) + , _lastError(NoError) + , _name(QString()) + , _userName(QString()) + , _userHomeDir(QString()) + , _currentDir(QString()) + , _userNameRequired(true) + , _arguments(QVector()) { } @@ -135,7 +134,7 @@ QSet ProcessInfo::commonDirNames() QString ProcessInfo::formatShortDir(const QString &input) const { - if(input == QStringLiteral("/")) { + if (input == QStringLiteral("/")) { return QStringLiteral("/"); } @@ -327,8 +326,8 @@ void ProcessInfo::setFileError(QFile::FileError error) class LinuxProcessInfo : public UnixProcessInfo { public: - explicit LinuxProcessInfo(int pid) : - UnixProcessInfo(pid) + explicit LinuxProcessInfo(int pid) + : UnixProcessInfo(pid) { } @@ -504,8 +503,8 @@ private: class FreeBSDProcessInfo : public UnixProcessInfo { public: - explicit FreeBSDProcessInfo(int pid) : - UnixProcessInfo(pid) + explicit FreeBSDProcessInfo(int pid) + : UnixProcessInfo(pid) { } @@ -570,10 +569,10 @@ private: return false; } - kInfoProc = new struct kinfo_proc [mibLength]; + kInfoProc = new struct kinfo_proc[mibLength]; if (sysctl(managementInfoBase, 4, kInfoProc, &mibLength, NULL, 0) == -1) { - delete [] kInfoProc; + delete[] kInfoProc; return false; } @@ -593,7 +592,7 @@ private: readUserName(); - delete [] kInfoProc; + delete[] kInfoProc; return true; } @@ -629,8 +628,8 @@ private: class OpenBSDProcessInfo : public UnixProcessInfo { public: - explicit OpenBSDProcessInfo(int pid) : - UnixProcessInfo(pid) + explicit OpenBSDProcessInfo(int pid) + : UnixProcessInfo(pid) { } @@ -747,8 +746,8 @@ private: class MacProcessInfo : public UnixProcessInfo { public: - explicit MacProcessInfo(int pid) : - UnixProcessInfo(pid) + explicit MacProcessInfo(int pid) + : UnixProcessInfo(pid) { } @@ -781,19 +780,18 @@ private: if (sysctl(managementInfoBase, 4, nullptr, &mibLength, nullptr, 0) == -1) { return false; } else { - kInfoProc = new struct kinfo_proc [mibLength]; + kInfoProc = new struct kinfo_proc[mibLength]; if (sysctl(managementInfoBase, 4, kInfoProc, &mibLength, nullptr, 0) == -1) { - delete [] kInfoProc; + delete[] kInfoProc; return false; } else { const QString deviceNumber = QString::fromUtf8(devname(((&kInfoProc->kp_eproc)->e_tdev), S_IFCHR)); - const QString fullDeviceName = QStringLiteral("/dev/") - + deviceNumber.rightJustified(3, QLatin1Char('0')); + const QString fullDeviceName = QStringLiteral("/dev/") + deviceNumber.rightJustified(3, QLatin1Char('0')); setParentPid(kInfoProc->kp_eproc.e_ppid); setForegroundPid(kInfoProc->kp_eproc.e_pgid); - delete [] kInfoProc; + delete[] kInfoProc; const QByteArray deviceName = fullDeviceName.toLatin1(); const char *ttyName = deviceName.data(); @@ -809,21 +807,19 @@ private: managementInfoBase[3] = statInfo.st_rdev; mibLength = 0; - if (sysctl(managementInfoBase, sizeof(managementInfoBase) / sizeof(int), nullptr, - &mibLength, nullptr, 0) == -1) { + if (sysctl(managementInfoBase, sizeof(managementInfoBase) / sizeof(int), nullptr, &mibLength, nullptr, 0) == -1) { return false; } - kInfoProc = new struct kinfo_proc [mibLength]; - if (sysctl(managementInfoBase, sizeof(managementInfoBase) / sizeof(int), kInfoProc, - &mibLength, nullptr, 0) == -1) { + kInfoProc = new struct kinfo_proc[mibLength]; + if (sysctl(managementInfoBase, sizeof(managementInfoBase) / sizeof(int), kInfoProc, &mibLength, nullptr, 0) == -1) { return false; } // The foreground program is the first one setName(QString::fromUtf8(kInfoProc->kp_proc.p_comm)); - delete [] kInfoProc; + delete[] kInfoProc; } setPid(pid); } @@ -852,8 +848,8 @@ private: class SolarisProcessInfo : public UnixProcessInfo { public: - explicit SolarisProcessInfo(int pid) : - UnixProcessInfo(pid) + explicit SolarisProcessInfo(int pid) + : UnixProcessInfo(pid) { } diff --git a/src/ProcessInfo.h b/src/ProcessInfo.h index 833fc06de..da1d27036 100644 --- a/src/ProcessInfo.h +++ b/src/ProcessInfo.h @@ -12,7 +12,8 @@ #include #include -namespace Konsole { +namespace Konsole +{ /** * Takes a snapshot of the state of a process and provides access to * information such as the process name, parent process, @@ -152,7 +153,7 @@ public: /** The nature of the error is unknown. */ UnknownError, /** Konsole does not have permission to obtain the process information. */ - PermissionsError + PermissionsError, }; /** @@ -160,15 +161,7 @@ public: */ Error error() const; - enum Field { - PROCESS_ID = 1, - PARENT_PID = 2, - FOREGROUND_PID = 4, - ARGUMENTS = 8, - NAME = 16, - CURRENT_DIR = 32, - UID = 64 - }; + enum Field { PROCESS_ID = 1, PARENT_PID = 2, FOREGROUND_PID = 4, ARGUMENTS = 8, NAME = 16, CURRENT_DIR = 32, UID = 64, }; Q_DECLARE_FLAGS(Fields, Field) // takes a full directory path and returns a @@ -251,7 +244,6 @@ protected: bool userNameRequired() const; private: - Fields _fields; int _pid; @@ -277,4 +269,4 @@ Q_DECLARE_OPERATORS_FOR_FLAGS(ProcessInfo::Fields) } -#endif //PROCESSINFO_H +#endif // PROCESSINFO_H diff --git a/src/Pty.cpp b/src/Pty.cpp index 106f76a37..d06ab1341 100644 --- a/src/Pty.cpp +++ b/src/Pty.cpp @@ -10,8 +10,8 @@ #include "konsoledebug.h" // System -#include #include +#include // Qt #include @@ -22,14 +22,14 @@ using Konsole::Pty; -Pty::Pty(int masterFd, QObject *aParent) : - KPtyProcess(masterFd, aParent) +Pty::Pty(int masterFd, QObject *aParent) + : KPtyProcess(masterFd, aParent) { init(); } -Pty::Pty(QObject *aParent) : - KPtyProcess(aParent) +Pty::Pty(QObject *aParent) + : KPtyProcess(aParent) { init(); } @@ -117,8 +117,7 @@ bool Pty::flowControlEnabled() const if (pty()->masterFd() >= 0) { struct ::termios ttmode; pty()->tcGetAttr(&ttmode); - return ((ttmode.c_iflag & IXOFF) != 0U) - && ((ttmode.c_iflag & IXON) != 0U); + return ((ttmode.c_iflag & IXOFF) != 0U) && ((ttmode.c_iflag & IXON) != 0U); } else { qCDebug(KonsoleDebug) << "Unable to get flow control status, terminal not connected."; return _xonXoff; @@ -219,8 +218,7 @@ void Pty::addEnvironmentVariables(const QStringList &environmentVariables) } } -int Pty::start(const QString &programName, const QStringList &programArguments, - const QStringList &environmentList) +int Pty::start(const QString &programName, const QStringList &programArguments, const QStringList &environmentList) { clearProgram(); @@ -243,8 +241,7 @@ int Pty::start(const QString &programName, const QStringList &programArguments, // does not have a translation for // // BR:149300 - setEnv(QStringLiteral("LANGUAGE"), QString(), - false /* do not overwrite existing value if any */); + setEnv(QStringLiteral("LANGUAGE"), QString(), false /* do not overwrite existing value if any */); KProcess::start(); @@ -261,15 +258,15 @@ void Pty::setWriteable(bool writeable) if (QT_STAT(pty()->ttyName(), &sbuf) == 0) { if (writeable) { if (::chmod(pty()->ttyName(), sbuf.st_mode | S_IWGRP) < 0) { - qCDebug(KonsoleDebug) << "Could not set writeable on "<ttyName(); + qCDebug(KonsoleDebug) << "Could not set writeable on " << pty()->ttyName(); } } else { if (::chmod(pty()->ttyName(), sbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) { - qCDebug(KonsoleDebug) << "Could not unset writeable on "<ttyName(); + qCDebug(KonsoleDebug) << "Could not unset writeable on " << pty()->ttyName(); } } } else { - qCDebug(KonsoleDebug) << "Could not stat "<ttyName(); + qCDebug(KonsoleDebug) << "Could not stat " << pty()->ttyName(); } } diff --git a/src/Pty.h b/src/Pty.h index be406c62e..64dd39bb0 100644 --- a/src/Pty.h +++ b/src/Pty.h @@ -19,7 +19,8 @@ class QStringList; -namespace Konsole { +namespace Konsole +{ /** * The Pty class is used to start the terminal process, * send data to it, receive data from it and manipulate diff --git a/src/RenameTabDialog.cpp b/src/RenameTabDialog.cpp index 756547dba..58f8beaf9 100644 --- a/src/RenameTabDialog.cpp +++ b/src/RenameTabDialog.cpp @@ -8,8 +8,8 @@ #include "RenameTabDialog.h" // Konsole -#include "ui_RenameTabDialog.h" #include "Shortcut_p.h" +#include "ui_RenameTabDialog.h" #include #include @@ -18,12 +18,12 @@ using Konsole::RenameTabDialog; -RenameTabDialog::RenameTabDialog(QWidget *parent) : - QDialog(parent), - _ui(nullptr) +RenameTabDialog::RenameTabDialog(QWidget *parent) + : QDialog(parent) + , _ui(nullptr) { setWindowTitle(i18n("Tab Properties")); - auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel); + auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); auto mainWidget = new QWidget(this); auto mainLayout = new QVBoxLayout; setLayout(mainLayout); diff --git a/src/RenameTabDialog.h b/src/RenameTabDialog.h index 297967e69..e49a860b0 100644 --- a/src/RenameTabDialog.h +++ b/src/RenameTabDialog.h @@ -10,11 +10,13 @@ // KDE #include -namespace Ui { +namespace Ui +{ class RenameTabDialog; } -namespace Konsole { +namespace Konsole +{ class RenameTabDialog : public QDialog { Q_OBJECT diff --git a/src/SSHProcessInfo.cpp b/src/SSHProcessInfo.cpp index 7870a1b6f..c7aa3a4a8 100644 --- a/src/SSHProcessInfo.cpp +++ b/src/SSHProcessInfo.cpp @@ -8,25 +8,25 @@ #include "SSHProcessInfo.h" // Unix -#include -#include #include -#include +#include +#include #include #include -#include +#include +#include // Qt #include using namespace Konsole; -SSHProcessInfo::SSHProcessInfo(const ProcessInfo &process) : - _process(process), - _user(QString()), - _host(QString()), - _port(QString()), - _command(QString()) +SSHProcessInfo::SSHProcessInfo(const ProcessInfo &process) + : _process(process) + , _user(QString()) + , _host(QString()) + , _port(QString()) + , _command(QString()) { bool ok = false; @@ -194,4 +194,3 @@ QString SSHProcessInfo::format(const QString &input) const return output; } - diff --git a/src/SSHProcessInfo.h b/src/SSHProcessInfo.h index 88d2e07fa..07d8bc3bd 100644 --- a/src/SSHProcessInfo.h +++ b/src/SSHProcessInfo.h @@ -11,64 +11,64 @@ namespace Konsole { +/** + * Lightweight class which provides additional information about SSH processes. + */ +class SSHProcessInfo +{ +public: /** - * Lightweight class which provides additional information about SSH processes. + * Constructs a new SSHProcessInfo instance which provides additional + * information about the specified SSH process. + * + * @param process A ProcessInfo instance for a SSH process. */ - class SSHProcessInfo - { - public: - /** - * Constructs a new SSHProcessInfo instance which provides additional - * information about the specified SSH process. - * - * @param process A ProcessInfo instance for a SSH process. - */ - explicit SSHProcessInfo(const ProcessInfo &process); + explicit SSHProcessInfo(const ProcessInfo &process); - /** - * Returns the user name which the user initially logged into on - * the remote computer. - */ - QString userName() const; + /** + * Returns the user name which the user initially logged into on + * the remote computer. + */ + QString userName() const; - /** - * Returns the host which the user has connected to. - */ - QString host() const; + /** + * Returns the host which the user has connected to. + */ + QString host() const; - /** - * Returns the port on host which the user has connected to. - */ - QString port() const; + /** + * Returns the port on host which the user has connected to. + */ + QString port() const; - /** - * Returns the command which the user specified to execute on the - * remote computer when starting the SSH process. - */ - QString command() const; + /** + * Returns the command which the user specified to execute on the + * remote computer when starting the SSH process. + */ + QString command() const; - /** - * Operates in the same way as ProcessInfo::format(), except - * that the set of markers understood is different: - * - * %u - Replaced with user name which the user initially logged - * into on the remote computer. - * %h - Replaced with the first part of the host name which - * is connected to. - * %H - Replaced with the full host name of the computer which - * is connected to. - * %c - Replaced with the command which the user specified - * to execute when starting the SSH process. - */ - QString format(const QString &input) const; + /** + * Operates in the same way as ProcessInfo::format(), except + * that the set of markers understood is different: + * + * %u - Replaced with user name which the user initially logged + * into on the remote computer. + * %h - Replaced with the first part of the host name which + * is connected to. + * %H - Replaced with the full host name of the computer which + * is connected to. + * %c - Replaced with the command which the user specified + * to execute when starting the SSH process. + */ + QString format(const QString &input) const; - private: - const ProcessInfo &_process; - QString _user; - QString _host; - QString _port; - QString _command; - }; +private: + const ProcessInfo &_process; + QString _user; + QString _host; + QString _port; + QString _command; +}; } diff --git a/src/SaveHistoryTask.cpp b/src/SaveHistoryTask.cpp index 6dc20684a..5a1489cbe 100644 --- a/src/SaveHistoryTask.cpp +++ b/src/SaveHistoryTask.cpp @@ -7,27 +7,27 @@ #include "SaveHistoryTask.h" -#include #include +#include #include -#include -#include -#include #include #include +#include +#include +#include -#include "session/SessionManager.h" #include "Emulation.h" +#include "session/SessionManager.h" -#include "../decoders/PlainTextDecoder.h" #include "../decoders/HTMLDecoder.h" +#include "../decoders/PlainTextDecoder.h" -namespace Konsole { - +namespace Konsole +{ QString SaveHistoryTask::_saveDialogRecentURL; -SaveHistoryTask::SaveHistoryTask(QObject* parent) +SaveHistoryTask::SaveHistoryTask(QObject *parent) : SessionTask(parent) { } @@ -40,13 +40,10 @@ void SaveHistoryTask::execute() // three then providing a URL for each one will be tedious // TODO - show a warning ( preferably passive ) if saving the history output fails - QFileDialog* dialog = new QFileDialog(QApplication::activeWindow()); + QFileDialog *dialog = new QFileDialog(QApplication::activeWindow()); dialog->setAcceptMode(QFileDialog::AcceptSave); - QStringList mimeTypes { - QStringLiteral("text/plain"), - QStringLiteral("text/html") - }; + QStringList mimeTypes{QStringLiteral("text/plain"), QStringLiteral("text/html")}; dialog->setMimeTypeFilters(mimeTypes); KSharedConfigPtr konsoleConfig = KSharedConfig::openConfig(); @@ -80,16 +77,16 @@ void SaveHistoryTask::execute() if (!url.isValid()) { // UI: Can we make this friendlier? - KMessageBox::sorry(nullptr , i18n("%1 is an invalid URL, the output could not be saved.", url.url())); + KMessageBox::sorry(nullptr, i18n("%1 is an invalid URL, the output could not be saved.", url.url())); continue; } // Save selected URL for next time - _saveDialogRecentURL = url.adjusted(QUrl::RemoveFilename|QUrl::StripTrailingSlash).toString(); + _saveDialogRecentURL = url.adjusted(QUrl::RemoveFilename | QUrl::StripTrailingSlash).toString(); group.writePathEntry("Recent URLs", _saveDialogRecentURL); - KIO::TransferJob* job = KIO::put(url, - -1, // no special permissions + KIO::TransferJob *job = KIO::put(url, + -1, // no special permissions // overwrite existing files // do not resume an existing transfer // show progress information only for remote @@ -100,18 +97,18 @@ void SaveHistoryTask::execute() // instead, since the overall speed of transfer // depends on factors other than just the protocol // used - ); + ); SaveJob jobInfo; jobInfo.session = session; - jobInfo.lastLineFetched = -1; // when each request for data comes in from the KIO subsystem + jobInfo.lastLineFetched = -1; // when each request for data comes in from the KIO subsystem // lastLineFetched is used to keep track of how much of the history // has already been sent, and where the next request should continue // from. // this is set to -1 to indicate the job has just been started - if (((dialog->selectedNameFilter()).contains(QLatin1String("html"), Qt::CaseInsensitive)) || - ((dialog->selectedFiles()).at(0).endsWith(QLatin1String("html"), Qt::CaseInsensitive))) { + if (((dialog->selectedNameFilter()).contains(QLatin1String("html"), Qt::CaseInsensitive)) + || ((dialog->selectedFiles()).at(0).endsWith(QLatin1String("html"), Qt::CaseInsensitive))) { Profile::Ptr profile = SessionManager::instance()->sessionProfile(session); jobInfo.decoder = new HTMLDecoder(profile->colorScheme(), profile->font()); } else { @@ -127,14 +124,14 @@ void SaveHistoryTask::execute() dialog->deleteLater(); } -void SaveHistoryTask::jobDataRequested(KIO::Job* job , QByteArray& data) +void SaveHistoryTask::jobDataRequested(KIO::Job *job, QByteArray &data) { // TODO - Report progress information for the job // PERFORMANCE: Do some tests and tweak this value to get faster saving const int LINES_PER_REQUEST = 500; - SaveJob& info = _jobSession[job]; + SaveJob &info = _jobSession[job]; // transfer LINES_PER_REQUEST lines from the session's history // to the save location @@ -148,24 +145,23 @@ void SaveHistoryTask::jobDataRequested(KIO::Job* job , QByteArray& data) return; // if there is no more data to transfer then stop the job } - int copyUpToLine = qMin(info.lastLineFetched + LINES_PER_REQUEST , - sessionLines - 1); + int copyUpToLine = qMin(info.lastLineFetched + LINES_PER_REQUEST, sessionLines - 1); QTextStream stream(&data, QIODevice::ReadWrite); info.decoder->begin(&stream); - info.session->emulation()->writeToStream(info.decoder , info.lastLineFetched + 1 , copyUpToLine); + info.session->emulation()->writeToStream(info.decoder, info.lastLineFetched + 1, copyUpToLine); info.decoder->end(); info.lastLineFetched = copyUpToLine; } } -void SaveHistoryTask::jobResult(KJob* job) +void SaveHistoryTask::jobResult(KJob *job) { if (job->error() != 0) { - KMessageBox::sorry(nullptr , i18n("A problem occurred when saving the output.\n%1", job->errorString())); + KMessageBox::sorry(nullptr, i18n("A problem occurred when saving the output.\n%1", job->errorString())); } - TerminalCharacterDecoder * decoder = _jobSession[job].decoder; + TerminalCharacterDecoder *decoder = _jobSession[job].decoder; _jobSession.remove(job); diff --git a/src/SaveHistoryTask.h b/src/SaveHistoryTask.h index be6cd6f57..0eeb1bc25 100644 --- a/src/SaveHistoryTask.h +++ b/src/SaveHistoryTask.h @@ -14,7 +14,6 @@ namespace Konsole { - class TerminalCharacterDecoder; /** @@ -44,15 +43,15 @@ private Q_SLOTS: private: class SaveJob // structure to keep information needed to process - // incoming data requests from jobs + // incoming data requests from jobs { public: - QPointer session; // the session associated with a history save job - int lastLineFetched; // the last line processed in the previous data request - // set this to -1 at the start of the save job + QPointer session; // the session associated with a history save job + int lastLineFetched; // the last line processed in the previous data request + // set this to -1 at the start of the save job - TerminalCharacterDecoder *decoder; // decoder used to convert terminal characters - // into output + TerminalCharacterDecoder *decoder; // decoder used to convert terminal characters + // into output }; QHash _jobSession; diff --git a/src/Screen.cpp b/src/Screen.cpp index aa57fc8e2..c73510918 100644 --- a/src/Screen.cpp +++ b/src/Screen.cpp @@ -13,74 +13,71 @@ #include // Konsole decoders -#include #include +#include -#include "terminalDisplay/TerminalDisplay.h" -#include "session/SessionController.h" #include "session/Session.h" +#include "session/SessionController.h" #include "session/SessionManager.h" +#include "terminalDisplay/TerminalDisplay.h" -#include "history/HistoryType.h" -#include "history/HistoryScrollNone.h" +#include "EscapeSequenceUrlExtractor.h" #include "characters/ExtendedCharTable.h" +#include "history/HistoryScrollNone.h" +#include "history/HistoryType.h" #include "profile/Profile.h" #include "profile/ProfileManager.h" -#include "EscapeSequenceUrlExtractor.h" using namespace Konsole; -//Macro to convert x,y position on screen to position within an image. +// Macro to convert x,y position on screen to position within an image. // -//Originally the image was stored as one large contiguous block of -//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. +// 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)) +#define loc(X, Y) ((Y)*_columns + (X)) #endif -const Character Screen::DefaultChar = Character(' ', - CharacterColor(COLOR_SPACE_DEFAULT, DEFAULT_FORE_COLOR), - CharacterColor(COLOR_SPACE_DEFAULT, DEFAULT_BACK_COLOR), - DEFAULT_RENDITION, - false); +const Character Screen::DefaultChar = + Character(' ', CharacterColor(COLOR_SPACE_DEFAULT, DEFAULT_FORE_COLOR), CharacterColor(COLOR_SPACE_DEFAULT, DEFAULT_BACK_COLOR), DEFAULT_RENDITION, false); -Screen::Screen(int lines, int columns): - _currentTerminalDisplay(nullptr), - _lines(lines), - _columns(columns), - _screenLines(_lines + 1), - _screenLinesSize(_lines), - _scrolledLines(0), - _lastScrolledRegion(QRect()), - _droppedLines(0), - _oldTotalLines(0), - _isResize(false), - _enableReflowLines(false), - _lineProperties(_lines + 1), - _history(std::make_unique()), - _cuX(0), - _cuY(0), - _currentForeground(CharacterColor()), - _currentBackground(CharacterColor()), - _currentRendition(DEFAULT_RENDITION), - _topMargin(0), - _bottomMargin(0), - _tabStops(QBitArray()), - _selBegin(0), - _selTopLeft(0), - _selBottomRight(0), - _blockSelectionMode(false), - _effectiveForeground(CharacterColor()), - _effectiveBackground(CharacterColor()), - _effectiveRendition(DEFAULT_RENDITION), - _lastPos(-1), - _lastDrawnChar(0), - _escapeSequenceUrlExtractor(std::make_unique()) +Screen::Screen(int lines, int columns) + : _currentTerminalDisplay(nullptr) + , _lines(lines) + , _columns(columns) + , _screenLines(_lines + 1) + , _screenLinesSize(_lines) + , _scrolledLines(0) + , _lastScrolledRegion(QRect()) + , _droppedLines(0) + , _oldTotalLines(0) + , _isResize(false) + , _enableReflowLines(false) + , _lineProperties(_lines + 1) + , _history(std::make_unique()) + , _cuX(0) + , _cuY(0) + , _currentForeground(CharacterColor()) + , _currentBackground(CharacterColor()) + , _currentRendition(DEFAULT_RENDITION) + , _topMargin(0) + , _bottomMargin(0) + , _tabStops(QBitArray()) + , _selBegin(0) + , _selTopLeft(0) + , _selBottomRight(0) + , _blockSelectionMode(false) + , _effectiveForeground(CharacterColor()) + , _effectiveBackground(CharacterColor()) + , _effectiveRendition(DEFAULT_RENDITION) + , _lastPos(-1) + , _lastDrawnChar(0) + , _escapeSequenceUrlExtractor(std::make_unique()) { _escapeSequenceUrlExtractor->setScreen(this); std::fill(_lineProperties.begin(), _lineProperties.end(), LINE_DEFAULT); @@ -106,7 +103,7 @@ void Screen::cursorDown(int n) //=CUD { if (n < 1) { - n = 1; // Default + n = 1; // Default } if (n > MAX_SCREEN_ARGUMENT) { n = MAX_SCREEN_ARGUMENT; @@ -163,16 +160,16 @@ void Screen::setMargins(int top, int bot) //=STBM { if (top < 1) { - top = 1; // Default + top = 1; // Default } if (bot < 1) { - bot = _lines; // Default + bot = _lines; // Default } - top = top - 1; // Adjust to internal lineno - bot = bot - 1; // Adjust to internal lineno + top = top - 1; // Adjust to internal lineno + bot = bot - 1; // Adjust to internal lineno if (!(0 <= top && top < bot && bot < _lines)) { - //Debug()<<" setRegion("<r &= ~RE_TRANSPARENT; + p.backgroundColor = f; // p->r &= ~RE_TRANSPARENT; } void Screen::updateEffectiveRendition() @@ -601,13 +596,13 @@ void Screen::updateEffectiveRendition() } } -void Screen::copyFromHistory(Character* dest, int startLine, int count) const +void Screen::copyFromHistory(Character *dest, int startLine, int count) const { Q_ASSERT(startLine >= 0 && count > 0 && startLine + count <= _history->getLines()); for (int line = startLine; line < startLine + count; ++line) { const int length = qMin(_columns, _history->getLineLen(line)); - const int destLineOffset = (line - startLine) * _columns; + const int destLineOffset = (line - startLine) * _columns; const int lastColumn = (_history->getLineProperty(line) & LINE_DOUBLEWIDTH) ? _columns / 2 : _columns; _history->getCells(line, 0, length, dest + destLineOffset); @@ -629,14 +624,14 @@ void Screen::copyFromHistory(Character* dest, int startLine, int count) const } } -void Screen::copyFromScreen(Character* dest , int startLine , int count) const +void Screen::copyFromScreen(Character *dest, int startLine, int count) const { const int endLine = startLine + count; Q_ASSERT(startLine >= 0 && count > 0 && endLine <= _lines); for (int line = startLine; line < endLine; ++line) { - const int srcLineStartIndex = line * _columns; + const int srcLineStartIndex = line * _columns; const int destLineStartIndex = (line - startLine) * _columns; const int lastColumn = (line < _lineProperties.size() && _lineProperties[line] & LINE_DOUBLEWIDTH) ? _columns / 2 : _columns; @@ -658,8 +653,7 @@ void Screen::setTextSelectionRendition(Character &ch) const Q_ASSERT(_currentTerminalDisplay); auto currentProfile = SessionManager::instance()->sessionProfile(_currentTerminalDisplay->session()); - const bool isInvert = currentProfile ? currentProfile->property(Profile::InvertSelectionColors) - : false; + const bool isInvert = currentProfile ? currentProfile->property(Profile::InvertSelectionColors) : false; if (isInvert) { reverseRendition(ch); @@ -668,7 +662,7 @@ void Screen::setTextSelectionRendition(Character &ch) const } } -void Screen::getImage(Character* dest, int size, int startLine, int endLine) const +void Screen::getImage(Character *dest, int size, int startLine, int endLine) const { Q_ASSERT(startLine >= 0); Q_ASSERT(endLine >= startLine && endLine < _history->getLines() + _lines); @@ -688,9 +682,7 @@ void Screen::getImage(Character* dest, int size, int startLine, int endLine) con // copy _lines from screen buffer if (linesInScreenBuffer > 0) { - copyFromScreen(dest + linesInHistoryBuffer * _columns, - startLine + linesInHistoryBuffer - _history->getLines(), - linesInScreenBuffer); + copyFromScreen(dest + linesInHistoryBuffer * _columns, startLine + linesInHistoryBuffer - _history->getLines(), linesInScreenBuffer); } // invert display when in screen mode @@ -708,7 +700,7 @@ void Screen::getImage(Character* dest, int size, int startLine, int endLine) con } } -QVector Screen::getLineProperties(int startLine , int endLine) const +QVector Screen::getLineProperties(int startLine, int endLine) const { Q_ASSERT(startLine >= 0); Q_ASSERT(endLine >= startLine && endLine < _history->getLines() + _lines); @@ -755,20 +747,20 @@ void Screen::reset() _savedModes[MODE_Origin] = 0; setMode(MODE_Wrap); - saveMode(MODE_Wrap); // wrap at end of margin + saveMode(MODE_Wrap); // wrap at end of margin resetMode(MODE_Insert); - saveMode(MODE_Insert); // overstroke + saveMode(MODE_Insert); // overstroke - setMode(MODE_Cursor); // cursor visible - resetMode(MODE_Screen); // screen not inverse + setMode(MODE_Cursor); // cursor visible + resetMode(MODE_Screen); // screen not inverse resetMode(MODE_NewLine); _topMargin = 0; _bottomMargin = _lines - 1; // Other terminal emulators reset the entire scroll history during a reset -// setScroll(getScroll(), false); + // setScroll(getScroll(), false); setDefaultRendition(); saveCursor(); @@ -854,7 +846,7 @@ void Screen::checkSelection(int from, int to) return; } const int scr_TL = loc(0, _history->getLines()); - //Clear entire selection if it overlaps region [from, to] + // Clear entire selection if it overlaps region [from, to] if ((_selBottomRight >= (from + scr_TL)) && (_selTopLeft <= (to + scr_TL))) { clearSelection(); } @@ -895,17 +887,19 @@ void Screen::displayCharacter(uint c) if (charToCombineWithX < 0) { return; } - } while(!_screenLines.at(charToCombineWithY).at(charToCombineWithX).isRealCharacter); + } while (!_screenLines.at(charToCombineWithY).at(charToCombineWithX).isRealCharacter); - Character& currentChar = _screenLines[charToCombineWithY][charToCombineWithX]; + Character ¤tChar = _screenLines[charToCombineWithY][charToCombineWithX]; if ((currentChar.rendition & RE_EXTENDED_CHAR) == 0) { - const uint chars[2] = { currentChar.character, c }; + const uint chars[2] = {currentChar.character, c}; currentChar.rendition |= RE_EXTENDED_CHAR; - auto extChars = [this]() { return usedExtendedChars(); }; + auto extChars = [this]() { + return usedExtendedChars(); + }; currentChar.character = ExtendedCharTable::instance.createExtendedChar(chars, 2, extChars); } else { ushort extendedCharLength; - const uint* oldChars = ExtendedCharTable::instance.lookupExtendedChar(currentChar.character, extendedCharLength); + const uint *oldChars = ExtendedCharTable::instance.lookupExtendedChar(currentChar.character, extendedCharLength); Q_ASSERT(oldChars); if (((oldChars) != nullptr) && extendedCharLength < 3) { Q_ASSERT(extendedCharLength > 1); @@ -913,7 +907,9 @@ void Screen::displayCharacter(uint c) auto chars = std::make_unique(extendedCharLength + 1); std::copy_n(oldChars, extendedCharLength, chars.get()); chars[extendedCharLength] = c; - auto extChars = [this]() { return usedExtendedChars(); }; + auto extChars = [this]() { + return usedExtendedChars(); + }; currentChar.character = ExtendedCharTable::instance.createExtendedChar(chars.get(), extendedCharLength + 1, extChars); } } @@ -944,7 +940,7 @@ void Screen::displayCharacter(uint c) // check if selection is still valid. checkSelection(_lastPos, _lastPos); - Character& currentChar = _screenLines[_cuY][_cuX]; + Character ¤tChar = _screenLines[_cuY][_cuX]; currentChar.character = c; currentChar.foregroundColor = _effectiveForeground; @@ -963,7 +959,7 @@ void Screen::displayCharacter(uint c) _screenLines[_cuY].resize(_cuX + i + 1); } - Character& ch = _screenLines[_cuY][_cuX + i]; + Character &ch = _screenLines[_cuY][_cuX + i]; ch.character = 0; ch.foregroundColor = _effectiveForeground; ch.backgroundColor = _effectiveBackground; @@ -1024,7 +1020,7 @@ void Screen::scrollUp(int from, int n) _scrolledLines -= n; _lastScrolledRegion = QRect(0, _topMargin, _columns - 1, (_bottomMargin - _topMargin)); - //FIXME: make sure `topMargin', `bottomMargin', `from', `n' is in bounds. + // 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), ' '); } @@ -1041,7 +1037,7 @@ void Screen::scrollDown(int from, int n) { _scrolledLines += n; - //FIXME: make sure `topMargin', `bottomMargin', `from', `n' is in bounds. + // FIXME: make sure `topMargin', `bottomMargin', `from', `n' is in bounds. if (n <= 0) { return; } @@ -1099,9 +1095,9 @@ int Screen::getCursorY() const void Screen::clearImage(int loca, int loce, char c, bool resetLineRendition) { const int scr_TL = loc(0, _history->getLines()); - //FIXME: check positions + // FIXME: check positions - //Clear entire selection if it overlaps region to be moved... + // Clear entire selection if it overlaps region to be moved... if ((_selBottomRight > (loca + scr_TL)) && (_selTopLeft < (loce + scr_TL))) { clearSelection(); } @@ -1111,8 +1107,8 @@ void Screen::clearImage(int loca, int loce, char c, bool resetLineRendition) Character clearCh(uint(c), _currentForeground, _currentBackground, DEFAULT_RENDITION, false); - //if the character being used to clear the area is the same as the - //default character, the affected _lines can simply be shrunk. + // if the character being used to clear the area is the same as the + // default character, the affected _lines can simply be shrunk. const bool isDefaultCh = (clearCh == Screen::DefaultChar); for (int y = topLine; y <= bottomLine; ++y) { @@ -1121,7 +1117,7 @@ void Screen::clearImage(int loca, int loce, char c, bool resetLineRendition) const int endCol = (y == bottomLine) ? loce % _columns : _columns - 1; const int startCol = (y == topLine) ? loca % _columns : 0; - QVector& line = _screenLines[y]; + QVector &line = _screenLines[y]; if (isDefaultCh && endCol == _columns - 1) { line.resize(startCol); @@ -1140,7 +1136,7 @@ void Screen::clearImage(int loca, int loce, char c, bool resetLineRendition) } if (resetLineRendition && startCol == 0 && endCol == _columns - 1) { - _lineProperties[y] &= ~(LINE_DOUBLEWIDTH | LINE_DOUBLEHEIGHT_TOP | LINE_DOUBLEHEIGHT_BOTTOM); + _lineProperties[y] &= ~(LINE_DOUBLEWIDTH | LINE_DOUBLEHEIGHT_TOP | LINE_DOUBLEHEIGHT_BOTTOM); } } } @@ -1151,10 +1147,10 @@ void Screen::moveImage(int dest, int sourceBegin, int sourceEnd) const 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. + // 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) const int destY = dest / _columns; const int srcY = sourceBegin / _columns; @@ -1165,7 +1161,7 @@ void Screen::moveImage(int dest, int sourceBegin, int sourceEnd) } } else { for (int i = lines; i >= 0; --i) { - _screenLines[destY + i ] = std::move(_screenLines[srcY + i]); + _screenLines[destY + i] = std::move(_screenLines[srcY + i]); _lineProperties[destY + i] = _lineProperties.at(srcY + i); } } @@ -1309,7 +1305,7 @@ bool Screen::hasSelection() const return _selBegin != -1; } -void Screen::getSelectionStart(int& column , int& line) const +void Screen::getSelectionStart(int &column, int &line) const { if (_selTopLeft != -1) { column = _selTopLeft % _columns; @@ -1319,7 +1315,7 @@ void Screen::getSelectionStart(int& column , int& line) const line = _cuY + getHistLines(); } } -void Screen::getSelectionEnd(int& column , int& line) const +void Screen::getSelectionEnd(int &column, int &line) const { if (_selBottomRight != -1) { column = _selBottomRight % _columns; @@ -1348,7 +1344,7 @@ void Screen::setSelectionEnd(const int x, const int y) return; } - int endPos = loc(x, y); + int endPos = loc(x, y); if (endPos < _selBegin) { _selTopLeft = endPos; @@ -1379,8 +1375,7 @@ bool Screen::isSelected(const int x, const int y) const { bool columnInSelection = true; if (_blockSelectionMode) { - columnInSelection = x >= (_selTopLeft % _columns) && - x <= (_selBottomRight % _columns); + columnInSelection = x >= (_selTopLeft % _columns) && x <= (_selBottomRight % _columns); } const int pos = loc(x, y); @@ -1405,7 +1400,7 @@ QString Screen::text(int startIndex, int endIndex, const DecodingOptions options PlainTextDecoder plainTextDecoder; TerminalCharacterDecoder *decoder; - if((options & ConvertToHtml) != 0U) { + if ((options & ConvertToHtml) != 0U) { decoder = &htmlDecoder; } else { decoder = &plainTextDecoder; @@ -1423,9 +1418,7 @@ bool Screen::isSelectionValid() const return _selTopLeft >= 0 && _selBottomRight >= 0; } -void Screen::writeToStream(TerminalCharacterDecoder* decoder, - int startIndex, int endIndex, - const DecodingOptions options) const +void Screen::writeToStream(TerminalCharacterDecoder *decoder, int startIndex, int endIndex, const DecodingOptions options) const { const int top = startIndex / _columns; const int left = startIndex % _columns; @@ -1447,22 +1440,14 @@ void Screen::writeToStream(TerminalCharacterDecoder* decoder, } const bool appendNewLine = (y != bottom); - int copied = copyLineToStream(y, - start, - count, - decoder, - appendNewLine, - _blockSelectionMode, - options); + int copied = copyLineToStream(y, start, count, decoder, appendNewLine, _blockSelectionMode, options); // 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 && - !options.testFlag(TrimTrailingWhitespace)) { + if (y == bottom && copied < count && !options.testFlag(TrimTrailingWhitespace)) { Character newLineChar('\n'); decoder->decodeLine(&newLineChar, 1, 0); } @@ -1471,36 +1456,36 @@ void Screen::writeToStream(TerminalCharacterDecoder* decoder, int Screen::getLineLength(const int line) const { - // determine if the line is in the history buffer or the screen image - const bool isInHistoryBuffer = line < _history->getLines(); + // determine if the line is in the history buffer or the screen image + const bool isInHistoryBuffer = line < _history->getLines(); - if (isInHistoryBuffer) { - return _history->getLineLen(line); - } + if (isInHistoryBuffer) { + return _history->getLineLen(line); + } - return _columns; + return _columns; } Character *Screen::getCharacterBuffer(const int size) { - // buffer to hold characters for decoding - // the buffer is static to avoid initializing every - // element on each call to copyLineToStream - // (which is unnecessary since all elements will be overwritten anyway) - static const int MAX_CHARS = 1024; - static QVector characterBuffer(MAX_CHARS); + // buffer to hold characters for decoding + // the buffer is static to avoid initializing every + // element on each call to copyLineToStream + // (which is unnecessary since all elements will be overwritten anyway) + static const int MAX_CHARS = 1024; + static QVector characterBuffer(MAX_CHARS); - if (characterBuffer.count() < size) { - characterBuffer.resize(size); - } + if (characterBuffer.count() < size) { + characterBuffer.resize(size); + } - return characterBuffer.data(); + return characterBuffer.data(); } -int Screen::copyLineToStream(int line , +int Screen::copyLineToStream(int line, int start, int count, - TerminalCharacterDecoder* decoder, + TerminalCharacterDecoder *decoder, bool appendNewLine, bool isBlockSelectionMode, const DecodingOptions options) const @@ -1548,19 +1533,18 @@ int Screen::copyLineToStream(int line , screenLine = qMin(screenLine, _screenLinesSize); - auto* data = _screenLines[screenLine].data(); + auto *data = _screenLines[screenLine].data(); int length = _screenLines.at(screenLine).count(); // Don't remove end spaces in lines that wrap - if (options.testFlag(TrimTrailingWhitespace) && ((_lineProperties.at(screenLine) & LINE_WRAPPED) == 0)) - { + if (options.testFlag(TrimTrailingWhitespace) && ((_lineProperties.at(screenLine) & LINE_WRAPPED) == 0)) { // ignore trailing white space at the end of the line while (length > 0 && QChar(data[length - 1].character).isSpace()) { length--; } } - //retrieve line from screen image + // retrieve line from screen image auto end = qMin(start + count, length); if (start < end) { std::copy(data + start, data + end, characterBuffer); @@ -1601,14 +1585,13 @@ int Screen::copyLineToStream(int line , count -= spacesCount; } - //decode line and write to text stream - decoder->decodeLine(characterBuffer, - count, currentLineProperties); + // decode line and write to text stream + decoder->decodeLine(characterBuffer, count, currentLineProperties); return count; } -void Screen::writeLinesToStream(TerminalCharacterDecoder* decoder, int fromLine, int toLine) const +void Screen::writeLinesToStream(TerminalCharacterDecoder *decoder, int fromLine, int toLine) const { writeToStream(decoder, loc(0, fromLine), loc(_columns - 1, toLine), PreserveLineBreaks); } @@ -1719,7 +1702,7 @@ const HistoryType &Screen::getScroll() const return _history->getType(); } -void Screen::setLineProperty(LineProperty property , bool enable) +void Screen::setLineProperty(LineProperty property, bool enable) { if (enable) { _lineProperties[_cuY] = static_cast(_lineProperties.at(_cuY) | property); @@ -1727,12 +1710,12 @@ void Screen::setLineProperty(LineProperty property , bool enable) _lineProperties[_cuY] = static_cast(_lineProperties.at(_cuY) & ~property); } } -void Screen::fillWithDefaultChar(Character* dest, int count) +void Screen::fillWithDefaultChar(Character *dest, int count) { std::fill_n(dest, count, Screen::DefaultChar); } -Konsole::EscapeSequenceUrlExtractor * Konsole::Screen::urlExtractor() const +Konsole::EscapeSequenceUrlExtractor *Konsole::Screen::urlExtractor() const { return _escapeSequenceUrlExtractor.get(); } diff --git a/src/Screen.h b/src/Screen.h index 557e70709..edaf8c3e7 100644 --- a/src/Screen.h +++ b/src/Screen.h @@ -12,26 +12,27 @@ #include // Qt +#include #include #include -#include -#include #include +#include // Konsole #include "../characters/Character.h" #include "konsoleprivate_export.h" -#define MODE_Origin 0 -#define MODE_Wrap 1 -#define MODE_Insert 2 -#define MODE_Screen 3 -#define MODE_Cursor 4 -#define MODE_NewLine 5 +#define MODE_Origin 0 +#define MODE_Wrap 1 +#define MODE_Insert 2 +#define MODE_Screen 3 +#define MODE_Cursor 4 +#define MODE_NewLine 5 #define MODE_AppScreen 6 -#define MODES_SCREEN 7 +#define MODES_SCREEN 7 -namespace Konsole { +namespace Konsole +{ class TerminalCharacterDecoder; class TerminalDisplay; class HistoryType; @@ -73,13 +74,7 @@ public: * TrimTrailingWhitespace: Specifies whether trailing spaces should be * trimmed in the returned text. */ - enum DecodingOption { - PlainText = 0x0, - ConvertToHtml = 0x1, - PreserveLineBreaks = 0x2, - TrimLeadingWhitespace = 0x4, - TrimTrailingWhitespace = 0x8 - }; + enum DecodingOption { PlainText = 0x0, ConvertToHtml = 0x1, PreserveLineBreaks = 0x2, TrimLeadingWhitespace = 0x4, TrimTrailingWhitespace = 0x8, }; Q_DECLARE_FLAGS(DecodingOptions, DecodingOption) /** Construct a new screen image of size @p lines by @p columns. */ @@ -329,9 +324,9 @@ public: void setDefaultRendition(); /** Returns the column which the cursor is positioned at. */ - int getCursorX() const; + int getCursorX() const; /** Returns the line which the cursor is positioned on. */ - int getCursorY() const; + int getCursorY() const; /** * Resets the state of the screen. This resets the various screen modes @@ -461,9 +456,9 @@ public: bool hasSelection() const; /** - * Returns true if the character at (@p x, @p y) is part of the - * current selection. - */ + * Returns true if the character at (@p x, @p y) is part of the + * current selection. + */ bool isSelected(const int x, const int y) const; /** @@ -563,9 +558,9 @@ public: void resetDroppedLines(); /** - * Fills the buffer @p dest with @p count instances of the default (ie. blank) - * Character style. - */ + * Fills the buffer @p dest with @p count instances of the default (ie. blank) + * Character style. + */ static void fillWithDefaultChar(Character *dest, int count); void setCurrentTerminalDisplay(TerminalDisplay *display) @@ -602,39 +597,44 @@ public: void setReflowLines(bool enable); private: - //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 + // 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 + // 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 - //isBlockSelectionMode - takes that in consideration while appending a new line. - int copyLineToStream(int line, int start, int count, TerminalCharacterDecoder *decoder, - bool appendNewLine, bool isBlockSelectionMode, const DecodingOptions options) const; + // 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 + // isBlockSelectionMode - takes that in consideration while appending a new line. + int copyLineToStream(int line, + int start, + int count, + TerminalCharacterDecoder *decoder, + bool appendNewLine, + bool isBlockSelectionMode, + const DecodingOptions options) 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. - //if resetLineRendition is true, all completely cleared lines will be set to single-width. + // 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. + // if resetLineRendition is true, all completely cleared lines will be set to single-width. void clearImage(int loca, int loce, char c, bool resetLineRendition = true); - //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. + // 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 + // NOTE: moveImage() can only move whole lines void moveImage(int dest, int sourceBegin, int sourceEnd); // scroll up 'n' lines in current region, clearing the bottom 'n' lines void scrollUp(int from, int n); // scroll down 'n' lines in current region, clearing the top 'n' lines void scrollDown(int from, int n); - //when we handle scroll commands, we need to know which screenwindow will scroll + // when we handle scroll commands, we need to know which screenwindow will scroll TerminalDisplay *_currentTerminalDisplay; void addHistLine(); @@ -649,8 +649,7 @@ private: bool isSelectionValid() const; // copies text from 'startIndex' to 'endIndex' to a stream // startIndex and endIndex are positions generated using the loc(x,y) macro - void writeToStream(TerminalCharacterDecoder *decoder, int startIndex, int endIndex, - const DecodingOptions options) const; + void writeToStream(TerminalCharacterDecoder *decoder, int startIndex, int endIndex, const DecodingOptions options) 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; @@ -678,7 +677,7 @@ private: // Get the cursor line after checking if its app mode or not int getCursorLine(); // Set the cursor line after checking if its app mode or not - void setCursorLine (int newLine); + void setCursorLine(int newLine); int getLineLength(const int line) const; @@ -690,9 +689,9 @@ private: int _lines; int _columns; - typedef QVector ImageLine; // [0..columns] - QVector _screenLines; // [lines] - int _screenLinesSize; // _screenLines.size() + typedef QVector ImageLine; // [0..columns] + QVector _screenLines; // [lines] + int _screenLinesSize; // _screenLines.size() int _scrolledLines; QRect _lastScrolledRegion; @@ -731,24 +730,24 @@ private: // selection ------------------- int _selBegin; // The first location selected. - int _selTopLeft; // TopLeft Location. - int _selBottomRight; // Bottom Right Location. - bool _blockSelectionMode; // Column selection mode + int _selTopLeft; // TopLeft Location. + int _selBottomRight; // Bottom Right Location. + bool _blockSelectionMode; // Column selection mode // effective colors and rendition ------------ CharacterColor _effectiveForeground; // These are derived from CharacterColor _effectiveBackground; // the cu_* variables above - RenditionFlags _effectiveRendition; // to speed up operation + RenditionFlags _effectiveRendition; // to speed up operation class SavedState { public: - SavedState() : - cursorColumn(0), - cursorLine(0), - rendition(0), - foreground(CharacterColor()), - background(CharacterColor()) + SavedState() + : cursorColumn(0) + , cursorLine(0) + , rendition(0) + , foreground(CharacterColor()) + , background(CharacterColor()) { } @@ -769,13 +768,11 @@ private: void toggleUrlInput(); // Vt102Emulation defined max argument value that can be passed to a Screen function - const int MAX_SCREEN_ARGUMENT = 40960; + const int MAX_SCREEN_ARGUMENT = 40960; }; Q_DECLARE_OPERATORS_FOR_FLAGS(Screen::DecodingOptions) } - - #endif // SCREEN_H diff --git a/src/ScreenWindow.cpp b/src/ScreenWindow.cpp index b6c40be15..f32489cfa 100644 --- a/src/ScreenWindow.cpp +++ b/src/ScreenWindow.cpp @@ -11,17 +11,17 @@ using namespace Konsole; -ScreenWindow::ScreenWindow(Screen *screen, QObject *parent) : - QObject(parent), - _screen(nullptr), - _windowBuffer(nullptr), - _windowBufferSize(0), - _bufferNeedsUpdate(true), - _windowLines(1), - _currentLine(0), - _currentResultLine(-1), - _trackOutput(true), - _scrollCount(0) +ScreenWindow::ScreenWindow(Screen *screen, QObject *parent) + : QObject(parent) + , _screen(nullptr) + , _windowBuffer(nullptr) + , _windowBufferSize(0) + , _bufferNeedsUpdate(true) + , _windowLines(1) + , _currentLine(0) + , _currentResultLine(-1) + , _trackOutput(true) + , _scrollCount(0) { setScreen(screen); } @@ -63,8 +63,7 @@ Character *ScreenWindow::getImage() return _windowBuffer; } - _screen->getImage(_windowBuffer, size, - currentLine(), endWindowLine()); + _screen->getImage(_windowBuffer, size, currentLine(), endWindowLine()); // this window may look beyond the end of the screen, in which // case there will be an unused area which needs to be filled @@ -102,8 +101,7 @@ void ScreenWindow::fillUnusedArea() // int ScreenWindow::endWindowLine() const { - return qMin(currentLine() + windowLines() - 1, - lineCount() - 1); + return qMin(currentLine() + windowLines() - 1, lineCount() - 1); } QVector ScreenWindow::getLineProperties() @@ -318,8 +316,7 @@ void ScreenWindow::notifyOutputChanged() // lines of output - in this case the screen // window's current line number will need to // be adjusted - otherwise the output will scroll - _currentLine = qMax(0, _currentLine - -_screen->droppedLines()); + _currentLine = qMax(0, _currentLine - _screen->droppedLines()); // ensure that the screen window's current position does // not go beyond the bottom of the screen diff --git a/src/ScreenWindow.h b/src/ScreenWindow.h index 445cd50c6..7edfd820f 100644 --- a/src/ScreenWindow.h +++ b/src/ScreenWindow.h @@ -16,8 +16,8 @@ #include "../characters/Character.h" #include "Screen.h" -namespace Konsole { - +namespace Konsole +{ /** * 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 @@ -182,7 +182,7 @@ public: * Scroll the window down by a given number of pages, where * one page is windowLines() lines */ - ScrollPages + ScrollPages, }; /** @@ -263,10 +263,10 @@ private: bool _bufferNeedsUpdate; int _windowLines; - int _currentLine; // see scrollTo() , currentLine() + int _currentLine; // see scrollTo() , currentLine() int _currentResultLine; bool _trackOutput; // see setTrackOutput() , trackOutput() - int _scrollCount; // count of lines which the window has been scrolled by since + int _scrollCount; // count of lines which the window has been scrolled by since // the last call to resetScrollCount() }; } diff --git a/src/ScrollState.h b/src/ScrollState.h index 358bf09c7..9000e7b0b 100644 --- a/src/ScrollState.h +++ b/src/ScrollState.h @@ -9,7 +9,8 @@ class QWheelEvent; -namespace Konsole { +namespace Konsole +{ /** * Represents accumulation of wheel scroll from scroll events. * @@ -22,14 +23,9 @@ namespace Konsole { * been reached (ideally 1 for pixel scroll values towards any action * that can be mapped to a pixel movement). */ -struct ScrollState -{ - enum { - DEFAULT_ANGLE_SCROLL_LINE = 120 - }; - enum { - DEGREES_PER_ANGLE_UNIT = 8 - }; +struct ScrollState { + enum { DEFAULT_ANGLE_SCROLL_LINE = 120, }; + enum { DEGREES_PER_ANGLE_UNIT = 8, }; static inline int degreesToAngle(const int angle) { return angle * DEGREES_PER_ANGLE_UNIT; @@ -59,8 +55,9 @@ struct ScrollState * the accumulated total. The other scroll style value is cleared. */ int consumeSteps(int pixelStepSize, int angleStepSize); - ScrollState() : _remainingScrollAngle(0), - _remainingScrollPixel(0) + ScrollState() + : _remainingScrollAngle(0) + , _remainingScrollPixel(0) { } diff --git a/src/SearchHistoryTask.cpp b/src/SearchHistoryTask.cpp index e9886986b..4997843b8 100644 --- a/src/SearchHistoryTask.cpp +++ b/src/SearchHistoryTask.cpp @@ -10,23 +10,23 @@ #include #include -#include "Emulation.h" #include "../decoders/PlainTextDecoder.h" +#include "Emulation.h" -namespace Konsole { - -void SearchHistoryTask::addScreenWindow(Session* session , ScreenWindow* searchWindow) +namespace Konsole +{ +void SearchHistoryTask::addScreenWindow(Session *session, ScreenWindow *searchWindow) { _windows.insert(session, searchWindow); } void SearchHistoryTask::execute() { - auto iter = QMapIterator,ScreenWindowPtr>(_windows); + auto iter = QMapIterator, ScreenWindowPtr>(_windows); while (iter.hasNext()) { iter.next(); - executeOnScreenWindow(iter.key() , iter.value()); + executeOnScreenWindow(iter.key(), iter.value()); } if (autoDelete()) { @@ -34,12 +34,12 @@ void SearchHistoryTask::execute() } } -void SearchHistoryTask::executeOnScreenWindow(const QPointer &session , const ScreenWindowPtr& window) +void SearchHistoryTask::executeOnScreenWindow(const QPointer &session, const ScreenWindowPtr &window) { Q_ASSERT(session); Q_ASSERT(window); - Emulation* emulation = session->emulation(); + Emulation *emulation = session->emulation(); if (!_regExp.pattern().isEmpty()) { int pos = -1; @@ -57,28 +57,28 @@ void SearchHistoryTask::executeOnScreenWindow(const QPointer &session , QString string; - //text stream to read history into string for pattern or regular expression searching + // text stream to read history into string for pattern or regular expression searching QTextStream searchStream(&string); PlainTextDecoder decoder; decoder.setRecordLinePositions(true); - //setup first and last lines depending on search direction + // setup first and last lines depending on search direction int line = startLine; - //read through and search history in blocks of 10K lines. - //this balances the need to retrieve lots of data from the history each time + // read through and search history in blocks of 10K lines. + // this balances the need to retrieve lots of data from the history each time //(for efficient searching) - //without using silly amounts of memory if the history is very large. + // without using silly amounts of memory if the history is very large. const int maxDelta = qMin(window->lineCount(), 10000); int delta = forwards ? maxDelta : -maxDelta; int endLine = line; - bool hasWrapped = false; // set to true when we reach the top/bottom + bool hasWrapped = false; // set to true when we reach the top/bottom // of the output and continue from the other // end - //loop through history in blocks of lines. + // loop through history in blocks of lines. do { // ensure that application does not appear to hang // if searching through a lengthy output @@ -95,9 +95,9 @@ void SearchHistoryTask::executeOnScreenWindow(const QPointer &session , endLine += delta; if (forwards) { - endLine = qMin(startLine , endLine); + endLine = qMin(startLine, endLine); } else { - endLine = qMax(startLine , endLine); + endLine = qMax(startLine, endLine); } } else { endLine += delta; @@ -112,7 +112,7 @@ void SearchHistoryTask::executeOnScreenWindow(const QPointer &session , } decoder.begin(&searchStream); - emulation->writeToStream(&decoder, qMin(endLine, line) , qMax(endLine, line)); + emulation->writeToStream(&decoder, qMin(endLine, line), qMax(endLine, line)); decoder.end(); // line number search below assumes that the buffer ends with a new-line @@ -124,7 +124,7 @@ void SearchHistoryTask::executeOnScreenWindow(const QPointer &session , pos = string.lastIndexOf(_regExp); } - //if a match is found, position the cursor on that line and update the screen + // if a match is found, position the cursor on that line and update the screen if (pos != -1) { int newLines = 0; QList linePositions = decoder.linePositions(); @@ -144,7 +144,7 @@ void SearchHistoryTask::executeOnScreenWindow(const QPointer &session , return; } - //clear the current block of text and move to the next one + // clear the current block of text and move to the next one string.clear(); line = endLine; } while (startLine != endLine); @@ -156,16 +156,15 @@ void SearchHistoryTask::executeOnScreenWindow(const QPointer &session , Q_EMIT completed(false); } -void SearchHistoryTask::highlightResult(const ScreenWindowPtr& window , int findPos) +void SearchHistoryTask::highlightResult(const ScreenWindowPtr &window, int findPos) { - //work out how many lines into the current block of text the search result was found + // work out how many lines into the current block of text the search result was found //- looks a little painful, but it only has to be done once per search. ////qDebug() << "Found result at line " << findPos; - //update display to show area of history containing selection - if ((findPos < window->currentLine()) || - (findPos >= (window->currentLine() + window->windowLines()))) { + // update display to show area of history containing selection + if ((findPos < window->currentLine()) || (findPos >= (window->currentLine() + window->windowLines()))) { int centeredScrollPos = findPos - window->windowLines() / 2; if (centeredScrollPos < 0) { centeredScrollPos = 0; @@ -179,7 +178,7 @@ void SearchHistoryTask::highlightResult(const ScreenWindowPtr& window , int find window->setCurrentResultLine(findPos); } -SearchHistoryTask::SearchHistoryTask(QObject* parent) +SearchHistoryTask::SearchHistoryTask(QObject *parent) : SessionTask(parent) , _direction(Enum::BackwardsSearch) , _startLine(0) diff --git a/src/SearchHistoryTask.h b/src/SearchHistoryTask.h index 75ed1436c..fd5e2eae2 100644 --- a/src/SearchHistoryTask.h +++ b/src/SearchHistoryTask.h @@ -8,19 +8,18 @@ #ifndef SEARCHHISTORYTASK_H #define SEARCHHISTORYTASK_H -#include #include +#include #include -#include "session/SessionTask.h" #include "Enumeration.h" #include "ScreenWindow.h" #include "session/Session.h" +#include "session/SessionTask.h" namespace Konsole { - -//class SearchHistoryThread; +// class SearchHistoryThread; /** * A task which searches through the output of sessions for matches for a given regular expression. * SearchHistoryTask operates on ScreenWindow instances rather than sessions added by addSession(). @@ -76,10 +75,10 @@ public: private: using ScreenWindowPtr = QPointer; - void executeOnScreenWindow(const QPointer &session, const ScreenWindowPtr& window); - void highlightResult(const ScreenWindowPtr& window, int findPos); + void executeOnScreenWindow(const QPointer &session, const ScreenWindowPtr &window); + void highlightResult(const ScreenWindowPtr &window, int findPos); - QMap< QPointer, ScreenWindowPtr > _windows; + QMap, ScreenWindowPtr> _windows; QRegularExpression _regExp; Enum::SearchDirection _direction; int _startLine; diff --git a/src/ShellCommand.cpp b/src/ShellCommand.cpp index 63f130f4b..07a706c41 100644 --- a/src/ShellCommand.cpp +++ b/src/ShellCommand.cpp @@ -48,7 +48,7 @@ QString ShellCommand::command() const { if (!_arguments.isEmpty()) { return _arguments[0]; - } + } return QString(); } diff --git a/src/ShellCommand.h b/src/ShellCommand.h index 773445743..d5e9e47eb 100644 --- a/src/ShellCommand.h +++ b/src/ShellCommand.h @@ -13,7 +13,8 @@ // Konsole #include "konsoleprivate_export.h" -namespace Konsole { +namespace Konsole +{ /** * A class to parse and extract information about shell commands. * diff --git a/src/Shortcut_p.h b/src/Shortcut_p.h index 0fdb87526..734add40e 100644 --- a/src/Shortcut_p.h +++ b/src/Shortcut_p.h @@ -9,7 +9,8 @@ #include -namespace Konsole { +namespace Konsole +{ /** * Platform-specific main shortcut "opcode": */ @@ -21,9 +22,9 @@ enum Modifier { #else ACCEL = Qt::CTRL, LEFT = Qt::Key_Left, - RIGHT = Qt::Key_Right + RIGHT = Qt::Key_Right, #endif }; } -#endif //SHORTCUT_H +#endif // SHORTCUT_H diff --git a/src/ShouldApplyProperty.h b/src/ShouldApplyProperty.h index 46b3b1676..d1f3eab44 100644 --- a/src/ShouldApplyProperty.h +++ b/src/ShouldApplyProperty.h @@ -13,18 +13,18 @@ namespace Konsole { - /** Utility class to simplify code in SessionManager::applyProfile(). */ - class ShouldApplyProperty - { - public: - ShouldApplyProperty(const Profile::Ptr &profile, bool modifiedOnly); +/** Utility class to simplify code in SessionManager::applyProfile(). */ +class ShouldApplyProperty +{ +public: + ShouldApplyProperty(const Profile::Ptr &profile, bool modifiedOnly); - bool shouldApply(Profile::Property property) const; + bool shouldApply(Profile::Property property) const; - private: - const Profile::Ptr _profile; - bool _modifiedPropertiesOnly; - }; +private: + const Profile::Ptr _profile; + bool _modifiedPropertiesOnly; +}; } #endif diff --git a/src/UnixProcessInfo.cpp b/src/UnixProcessInfo.cpp index d62b85198..c1240185e 100644 --- a/src/UnixProcessInfo.cpp +++ b/src/UnixProcessInfo.cpp @@ -6,17 +6,17 @@ // Own #if !defined(Q_OS_WIN) - #include "UnixProcessInfo.h" +#include "UnixProcessInfo.h" #endif // Unix -#include -#include #include -#include +#include +#include #include #include -#include +#include +#include // Qt #include @@ -45,7 +45,7 @@ void UnixProcessInfo::readProcessInfo(int pid) const QString &processNameString = name(&ok); if (ok && processNameString == QLatin1String("sudo")) { - //Append process name along with sudo + // Append process name along with sudo const QVector &args = arguments(&ok); if (ok && args.size() > 1) { @@ -85,7 +85,7 @@ void UnixProcessInfo::readUserName() setUserName(QString()); qWarning() << "getpwuid_r returned error : " << getpwStatus; } - delete [] getpwBuffer; + delete[] getpwBuffer; } #endif diff --git a/src/UnixProcessInfo.h b/src/UnixProcessInfo.h index e9fc6168b..4e8b344f7 100644 --- a/src/UnixProcessInfo.h +++ b/src/UnixProcessInfo.h @@ -11,44 +11,43 @@ namespace Konsole { +/** + * Implementation of ProcessInfo for Unix platforms which uses + * the /proc filesystem + */ +class UnixProcessInfo : public ProcessInfo +{ +public: + /** + * Constructs a new instance of UnixProcessInfo. + * See ProcessInfo::newInstance() + */ + explicit UnixProcessInfo(int pid); + +protected: + /** + * Implementation of ProcessInfo::readProcessInfo(); calls the + * four private methods below in turn. + */ + void readProcessInfo(int pid) override; + + void readUserName(void) override; + +private: + /** + * Read the standard process information -- PID, parent PID, foreground PID. + * @param pid process ID to use + * @return true on success + */ + virtual bool readProcInfo(int pid) = 0; /** - * Implementation of ProcessInfo for Unix platforms which uses - * the /proc filesystem + * Determine what arguments were passed to the process. Sets _arguments. + * @param pid process ID to use + * @return true on success */ - class UnixProcessInfo : public ProcessInfo - { - public: - /** - * Constructs a new instance of UnixProcessInfo. - * See ProcessInfo::newInstance() - */ - explicit UnixProcessInfo(int pid); - - protected: - /** - * Implementation of ProcessInfo::readProcessInfo(); calls the - * four private methods below in turn. - */ - void readProcessInfo(int pid) override; - - void readUserName(void) override; - - private: - /** - * Read the standard process information -- PID, parent PID, foreground PID. - * @param pid process ID to use - * @return true on success - */ - virtual bool readProcInfo(int pid) = 0; - - /** - * Determine what arguments were passed to the process. Sets _arguments. - * @param pid process ID to use - * @return true on success - */ - virtual bool readArguments(int pid) = 0; - }; + virtual bool readArguments(int pid) = 0; +}; } diff --git a/src/ViewManager.cpp b/src/ViewManager.cpp index 3ffbe6ba0..b657cd0c9 100644 --- a/src/ViewManager.cpp +++ b/src/ViewManager.cpp @@ -10,21 +10,20 @@ #include "config-konsole.h" // Qt -#include -#include -#include #include #include - +#include +#include +#include #include #include // KDE -#include -#include #include #include +#include +#include // Konsole #include @@ -46,16 +45,16 @@ using namespace Konsole; int ViewManager::lastManagerId = 0; -ViewManager::ViewManager(QObject *parent, KActionCollection *collection) : - QObject(parent), - _viewContainer(nullptr), - _pluggedController(nullptr), - _sessionMap(QHash()), - _actionCollection(collection), - _navigationMethod(TabbedNavigation), - _navigationVisibility(NavigationNotSet), - _managerId(0), - _terminalDisplayHistoryIndex(-1) +ViewManager::ViewManager(QObject *parent, KActionCollection *collection) + : QObject(parent) + , _viewContainer(nullptr) + , _pluggedController(nullptr) + , _sessionMap(QHash()) + , _actionCollection(collection) + , _navigationMethod(TabbedNavigation) + , _navigationVisibility(NavigationNotSet) + , _managerId(0) + , _terminalDisplayHistoryIndex(-1) { _viewContainer = createContainer(); // setup actions which are related to the views @@ -64,21 +63,17 @@ ViewManager::ViewManager(QObject *parent, KActionCollection *collection) : /* TODO: Reconnect // emit a signal when all of the views held by this view manager are destroyed */ - connect(_viewContainer.data(), &Konsole::TabbedViewContainer::empty, - this, &Konsole::ViewManager::empty); + connect(_viewContainer.data(), &Konsole::TabbedViewContainer::empty, this, &Konsole::ViewManager::empty); // listen for profile changes - connect(ProfileManager::instance(), &Konsole::ProfileManager::profileChanged, - this, &Konsole::ViewManager::profileChanged); - connect(SessionManager::instance(), &Konsole::SessionManager::sessionUpdated, - this, &Konsole::ViewManager::updateViewsForSession); + connect(ProfileManager::instance(), &Konsole::ProfileManager::profileChanged, this, &Konsole::ViewManager::profileChanged); + connect(SessionManager::instance(), &Konsole::SessionManager::sessionUpdated, this, &Konsole::ViewManager::updateViewsForSession); - //prepare DBus communication + // prepare DBus communication new WindowAdaptor(this); _managerId = ++lastManagerId; - QDBusConnection::sessionBus().registerObject(QLatin1String("/Windows/") - + QString::number(_managerId), this); + QDBusConnection::sessionBus().registerObject(QLatin1String("/Windows/") + QString::number(_managerId), this); } ViewManager::~ViewManager() = default; @@ -124,25 +119,25 @@ void ViewManager::setupActions() action = new QAction(this); action->setIcon(QIcon::fromTheme(QStringLiteral("view-split-top-bottom"))); action->setText(i18nc("@action:inmenu", "Load a new tab with layout 2x2 terminals")); - connect(action, &QAction::triggered, - this, [this](){ - this->loadLayout(QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("konsole/2x2-terminals.json"))); }); + connect(action, &QAction::triggered, this, [this]() { + this->loadLayout(QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("konsole/2x2-terminals.json"))); + }); collection->addAction(QStringLiteral("load-terminals-layout-2x2"), action); action = new QAction(this); action->setIcon(QIcon::fromTheme(QStringLiteral("view-split-left-right"))); action->setText(i18nc("@action:inmenu", "Load a new tab with layout 2x1 terminals")); - connect(action, &QAction::triggered, - this, [this](){ - this->loadLayout(QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("konsole/2x1-terminals.json"))); }); + connect(action, &QAction::triggered, this, [this]() { + this->loadLayout(QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("konsole/2x1-terminals.json"))); + }); collection->addAction(QStringLiteral("load-terminals-layout-2x1"), action); action = new QAction(this); action->setIcon(QIcon::fromTheme(QStringLiteral("view-split-top-bottom"))); action->setText(i18nc("@action:inmenu", "Load a new tab with layout 2x1 terminals")); - connect(action, &QAction::triggered, - this, [this](){ - this->loadLayout(QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("konsole/1x2-terminals.json"))); }); + connect(action, &QAction::triggered, this, [this]() { + this->loadLayout(QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("konsole/1x2-terminals.json"))); + }); collection->addAction(QStringLiteral("load-terminals-layout-1x2"), action); action = new QAction(this); @@ -166,7 +161,6 @@ void ViewManager::setupActions() action->setIcon(QIcon::fromTheme(QStringLiteral("tab-detach"))); action->setText(i18nc("@action:inmenu", "Detach Current &View")); - connect(action, &QAction::triggered, this, &ViewManager::detachActiveView); _multiSplitterOnlyActions << action; @@ -271,7 +265,9 @@ void ViewManager::setupActions() const int SWITCH_TO_TAB_COUNT = 19; for (int i = 0; i < SWITCH_TO_TAB_COUNT; ++i) { action = new QAction(i18nc("@action Shortcut entry", "Switch to Tab %1", i + 1), this); - connect(action, &QAction::triggered, this, [this, i]() { switchToView(i); }); + connect(action, &QAction::triggered, this, [this, i]() { + switchToView(i); + }); collection->addAction(QStringLiteral("switch-to-tab-%1").arg(i), action); _multiTabOnlyActions << action; @@ -290,18 +286,15 @@ void ViewManager::setupActions() toggleActionsBasedOnState(); } -void ViewManager::toggleActionsBasedOnState() { +void ViewManager::toggleActionsBasedOnState() +{ const int count = _viewContainer->count(); for (QAction *tabOnlyAction : qAsConst(_multiTabOnlyActions)) { tabOnlyAction->setEnabled(count > 1); } if ((_viewContainer != nullptr) && (_viewContainer->activeViewSplitter() != nullptr)) { - const int splitCount = _viewContainer - ->activeViewSplitter() - ->getToplevelSplitter() - ->findChildren() - .count(); + const int splitCount = _viewContainer->activeViewSplitter()->getToplevelSplitter()->findChildren().count(); for (QAction *action : qAsConst(_multiSplitterOnlyActions)) { action->setEnabled(splitCount > 1); @@ -314,9 +307,9 @@ void ViewManager::switchToView(int index) _viewContainer->setCurrentIndex(index); } -void ViewManager::switchToTerminalDisplay(Konsole::TerminalDisplay* terminalDisplay) +void ViewManager::switchToTerminalDisplay(Konsole::TerminalDisplay *terminalDisplay) { - auto splitter = qobject_cast(terminalDisplay->parentWidget()); + auto splitter = qobject_cast(terminalDisplay->parentWidget()); auto toplevelSplitter = splitter->getToplevelSplitter(); // Focus the TermialDisplay @@ -360,7 +353,7 @@ void ViewManager::moveActiveViewRight() void ViewManager::nextContainer() { -// _viewSplitter->activateNextContainer(); + // _viewSplitter->activateNextContainer(); } void ViewManager::nextView() @@ -425,12 +418,12 @@ void ViewManager::toggleTwoViews() void ViewManager::detachActiveView() { // find the currently active view and remove it from its container - if ((_viewContainer->findChildren()).count() > 1) { + if ((_viewContainer->findChildren()).count() > 1) { auto activeSplitter = _viewContainer->activeViewSplitter(); auto terminal = activeSplitter->activeTerminalDisplay(); auto newSplitter = new ViewSplitter(); newSplitter->addTerminalDisplay(terminal, Qt::Horizontal); - QHash detachedSessions = forgetAll(newSplitter); + QHash detachedSessions = forgetAll(newSplitter); Q_EMIT terminalsDetached(newSplitter, detachedSessions); focusAnotherTerminal(activeSplitter->getToplevelSplitter()); toggleActionsBasedOnState(); @@ -445,23 +438,24 @@ void ViewManager::detachActiveTab() void ViewManager::detachTab(int tabIdx) { - ViewSplitter* splitter = _viewContainer->viewSplitterAt(tabIdx); - QHash detachedSessions = forgetAll(_viewContainer->viewSplitterAt(tabIdx)); + ViewSplitter *splitter = _viewContainer->viewSplitterAt(tabIdx); + QHash detachedSessions = forgetAll(_viewContainer->viewSplitterAt(tabIdx)); Q_EMIT terminalsDetached(splitter, detachedSessions); } -QHash ViewManager::forgetAll(ViewSplitter* splitter) { +QHash ViewManager::forgetAll(ViewSplitter *splitter) +{ splitter->setParent(nullptr); - QHash detachedSessions; - const QList displays = splitter->findChildren(); + QHash detachedSessions; + const QList displays = splitter->findChildren(); for (TerminalDisplay *terminal : displays) { - Session* session = forgetTerminal(terminal); + Session *session = forgetTerminal(terminal); detachedSessions[terminal] = session; } return detachedSessions; } -Session* ViewManager::forgetTerminal(TerminalDisplay* terminal) +Session *ViewManager::forgetTerminal(TerminalDisplay *terminal) { unregisterTerminal(terminal); @@ -475,7 +469,7 @@ Session* ViewManager::forgetTerminal(TerminalDisplay* terminal) return session; } -Session* ViewManager::createSession(const Profile::Ptr &profile, const QString &directory) +Session *ViewManager::createSession(const Profile::Ptr &profile, const QString &directory) { Session *session = SessionManager::instance()->createSession(profile); Q_ASSERT(session); @@ -509,12 +503,12 @@ void ViewManager::sessionFinished() auto view = _sessionMap.key(session); _sessionMap.remove(view); - if (SessionManager::instance()->isClosingAllSessions()){ + if (SessionManager::instance()->isClosingAllSessions()) { return; } // Before deleting the view, let's unmaximize if it's maximized. - auto *splitter = qobject_cast(view->parentWidget()); + auto *splitter = qobject_cast(view->parentWidget()); if (splitter == nullptr) { return; } @@ -523,7 +517,9 @@ void ViewManager::sessionFinished() toplevelSplitter->handleMinimizeMaximize(false); view->deleteLater(); - connect(view, &QObject::destroyed, this, [this]() { toggleActionsBasedOnState(); }); + connect(view, &QObject::destroyed, this, [this]() { + toggleActionsBasedOnState(); + }); // Only remove the controller from factory() if it's actually controlling // the session from the sender. @@ -542,7 +538,7 @@ void ViewManager::sessionFinished() void ViewManager::focusAnotherTerminal(ViewSplitter *toplevelSplitter) { - auto tabTterminalDisplays = toplevelSplitter->findChildren(); + auto tabTterminalDisplays = toplevelSplitter->findChildren(); if (tabTterminalDisplays.count() == 0) { return; } @@ -594,9 +590,7 @@ void ViewManager::splitView(Qt::Orientation orientation) auto profile = SessionManager::instance()->sessionProfile(activeSession); - const QString directory = profile->startInCurrentSessionDir() - ? activeSession->currentWorkingDirectory() - : QString(); + const QString directory = profile->startInCurrentSessionDir() ? activeSession->currentWorkingDirectory() : QString(); auto *session = createSession(profile, directory); auto terminalDisplay = createView(session); @@ -624,16 +618,11 @@ SessionController *ViewManager::createController(Session *session, TerminalDispl // create a new controller for the session, and ensure that this view manager // is notified when the view gains the focus auto controller = new SessionController(session, view, this); - connect(controller, &Konsole::SessionController::viewFocused, this, - &Konsole::ViewManager::controllerChanged); - connect(session, &Konsole::Session::destroyed, controller, - &Konsole::SessionController::deleteLater); - connect(session, &Konsole::Session::primaryScreenInUse, controller, - &Konsole::SessionController::setupPrimaryScreenSpecificActions); - connect(session, &Konsole::Session::selectionChanged, controller, - &Konsole::SessionController::selectionChanged); - connect(view, &Konsole::TerminalDisplay::destroyed, controller, - &Konsole::SessionController::deleteLater); + connect(controller, &Konsole::SessionController::viewFocused, this, &Konsole::ViewManager::controllerChanged); + connect(session, &Konsole::Session::destroyed, controller, &Konsole::SessionController::deleteLater); + connect(session, &Konsole::Session::primaryScreenInUse, controller, &Konsole::SessionController::setupPrimaryScreenSpecificActions); + connect(session, &Konsole::Session::selectionChanged, controller, &Konsole::SessionController::selectionChanged); + connect(view, &Konsole::TerminalDisplay::destroyed, controller, &Konsole::SessionController::deleteLater); // if this is the first controller created then set it as the active controller if (_pluggedController.isNull()) { @@ -644,7 +633,7 @@ SessionController *ViewManager::createController(Session *session, TerminalDispl } // should this be handed by ViewManager::unplugController signal -void ViewManager::removeController(SessionController* controller) +void ViewManager::removeController(SessionController *controller) { if (_pluggedController == controller) { _pluggedController.clear(); @@ -672,8 +661,7 @@ SessionController *ViewManager::activeViewController() const void ViewManager::attachView(TerminalDisplay *terminal, Session *session) { - connect(session, &Konsole::Session::finished, this, &Konsole::ViewManager::sessionFinished, - Qt::UniqueConnection); + connect(session, &Konsole::Session::finished, this, &Konsole::ViewManager::sessionFinished, Qt::UniqueConnection); // Disconnect from the other viewcontainer. unregisterTerminal(terminal); @@ -693,8 +681,7 @@ TerminalDisplay *ViewManager::createView(Session *session) // can be deleted // // Use Qt::UniqueConnection to avoid duplicate connection - connect(session, &Konsole::Session::finished, this, &Konsole::ViewManager::sessionFinished, - Qt::UniqueConnection); + connect(session, &Konsole::Session::finished, this, &Konsole::ViewManager::sessionFinished, Qt::UniqueConnection); TerminalDisplay *display = createTerminalDisplay(session); const Profile::Ptr profile = SessionManager::instance()->sessionProfile(session); @@ -713,7 +700,7 @@ TerminalDisplay *ViewManager::createView(Session *session) // tell the session whether it has a light or dark background session->setDarkBackground(colorSchemeForProfile(profile)->hasDarkBackground()); display->setFocus(Qt::OtherFocusReason); -// updateDetachViewState(); + // updateDetachViewState(); return display; } @@ -725,21 +712,16 @@ TabbedViewContainer *ViewManager::createContainer() connect(container, &TabbedViewContainer::detachTab, this, &ViewManager::detachTab); // connect signals and slots - connect(container, &Konsole::TabbedViewContainer::viewAdded, this, - [this, container]() { - containerViewsChanged(container); - }); - connect(container, &Konsole::TabbedViewContainer::viewRemoved, this, - [this, container]() { - containerViewsChanged(container); - }); + connect(container, &Konsole::TabbedViewContainer::viewAdded, this, [this, container]() { + containerViewsChanged(container); + }); + connect(container, &Konsole::TabbedViewContainer::viewRemoved, this, [this, container]() { + containerViewsChanged(container); + }); - connect(container, &TabbedViewContainer::newViewRequest, - this, &ViewManager::newViewRequest); - connect(container, &Konsole::TabbedViewContainer::newViewWithProfileRequest, - this, &Konsole::ViewManager::newViewWithProfileRequest); - connect(container, &Konsole::TabbedViewContainer::activeViewChanged, this, - &Konsole::ViewManager::activateView); + connect(container, &TabbedViewContainer::newViewRequest, this, &ViewManager::newViewRequest); + connect(container, &Konsole::TabbedViewContainer::newViewWithProfileRequest, this, &Konsole::ViewManager::newViewWithProfileRequest); + connect(container, &Konsole::TabbedViewContainer::activeViewChanged, this, &Konsole::ViewManager::activateView); return container; } @@ -765,7 +747,7 @@ void ViewManager::setNavigationMethod(NavigationMethod method) const bool enable = (method != NoNavigation); - auto enableAction = [&enable, &collection](const QString& actionName) { + auto enableAction = [&enable, &collection](const QString &actionName) { auto *action = collection->action(actionName); if (action != nullptr) { action->setEnabled(enable); @@ -805,7 +787,7 @@ void ViewManager::viewDestroyed(QWidget *view) // 1. detach view from session // 2. if the session has no views left, close it - Session *session = _sessionMap[ display ]; + Session *session = _sessionMap[display]; _sessionMap.remove(display); if (session != nullptr) { if (session->views().count() == 0) { @@ -813,13 +795,13 @@ void ViewManager::viewDestroyed(QWidget *view) } } - //we only update the focus if the splitter is still alive + // we only update the focus if the splitter is still alive toggleActionsBasedOnState(); // The below causes the menus to be messed up // Only happens when using the tab bar close button -// if (_pluggedController) -// Q_EMIT unplugController(_pluggedController); + // if (_pluggedController) + // Q_EMIT unplugController(_pluggedController); } TerminalDisplay *ViewManager::createTerminalDisplay(Session *session) @@ -833,8 +815,7 @@ TerminalDisplay *ViewManager::createTerminalDisplay(Session *session) const ColorScheme *ViewManager::colorSchemeForProfile(const Profile::Ptr &profile) { - const ColorScheme *colorScheme = ColorSchemeManager::instance()-> - findColorScheme(profile->colorScheme()); + const ColorScheme *colorScheme = ColorSchemeManager::instance()->findColorScheme(profile->colorScheme()); if (colorScheme == nullptr) { colorScheme = ColorSchemeManager::instance()->defaultColorScheme(); } @@ -874,9 +855,7 @@ void ViewManager::profileChanged(const Profile::Ptr &profile) iter.next(); // if session uses this profile, update the display - if (iter.key() != nullptr - && iter.value() != nullptr - && SessionManager::instance()->sessionProfile(iter.value()) == profile) { + if (iter.key() != nullptr && iter.value() != nullptr && SessionManager::instance()->sessionProfile(iter.value()) == profile) { applyProfileToView(iter.key(), profile); } } @@ -891,17 +870,18 @@ QList ViewManager::viewProperties() const return {}; } - auto terminalContainers = _viewContainer->findChildren(); + auto terminalContainers = _viewContainer->findChildren(); list.reserve(terminalContainers.size()); - for(auto terminalDisplay : _viewContainer->findChildren()) { + for (auto terminalDisplay : _viewContainer->findChildren()) { list.append(terminalDisplay->sessionController()); } return list; } -namespace { +namespace +{ QJsonObject saveSessionTerminal(TerminalDisplay *terminalDisplay) { QJsonObject thisTerminal; @@ -911,19 +891,16 @@ QJsonObject saveSessionTerminal(TerminalDisplay *terminalDisplay) return thisTerminal; } -QJsonObject saveSessionsRecurse(QSplitter *splitter) { +QJsonObject saveSessionsRecurse(QSplitter *splitter) +{ QJsonObject thisSplitter; - thisSplitter.insert( - QStringLiteral("Orientation"), - splitter->orientation() == Qt::Horizontal ? QStringLiteral("Horizontal") - : QStringLiteral("Vertical") - ); + thisSplitter.insert(QStringLiteral("Orientation"), splitter->orientation() == Qt::Horizontal ? QStringLiteral("Horizontal") : QStringLiteral("Vertical")); QJsonArray internalWidgets; for (int i = 0; i < splitter->count(); i++) { auto *widget = splitter->widget(i); - auto *maybeSplitter = qobject_cast(widget); - auto *maybeTerminalDisplay = qobject_cast(widget); + auto *maybeSplitter = qobject_cast(widget); + auto *maybeTerminalDisplay = qobject_cast(widget); if (maybeSplitter != nullptr) { internalWidgets.append(saveSessionsRecurse(maybeSplitter)); @@ -937,9 +914,9 @@ QJsonObject saveSessionsRecurse(QSplitter *splitter) { } // namespace -void ViewManager::saveLayoutFile() { - QFile file(QFileDialog::getSaveFileName(this->widget(), i18n("Save File"), QStringLiteral("~/"), - i18n("Konsole View Layout (*.json)"))); +void ViewManager::saveLayoutFile() +{ + QFile file(QFileDialog::getSaveFileName(this->widget(), i18n("Save File"), QStringLiteral("~/"), i18n("Konsole View Layout (*.json)"))); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { KMessageBox::sorry(this->widget(), i18n("A problem occurred when saving the Layout.\n%1", file.fileName())); @@ -947,18 +924,17 @@ void ViewManager::saveLayoutFile() { QJsonObject jsonSplit = saveSessionsRecurse(_viewContainer->activeViewSplitter()); - if (!jsonSplit.isEmpty()){ + if (!jsonSplit.isEmpty()) { file.write(QJsonDocument(jsonSplit).toJson()); qDebug() << "Maybe was saved"; } } - void ViewManager::saveSessions(KConfigGroup &group) { QJsonArray rootArray; - for(int i = 0; i < _viewContainer->count(); i++) { - auto *splitter = qobject_cast(_viewContainer->widget(i)); + for (int i = 0; i < _viewContainer->count(); i++) { + auto *splitter = qobject_cast(_viewContainer->widget(i)); rootArray.append(saveSessionsRecurse(splitter)); } @@ -966,13 +942,12 @@ void ViewManager::saveSessions(KConfigGroup &group) group.writeEntry("Active", _viewContainer->currentIndex()); } -namespace { - -ViewSplitter *restoreSessionsSplitterRecurse(const QJsonObject& jsonSplitter, ViewManager *manager, bool useSessionId) +namespace +{ +ViewSplitter *restoreSessionsSplitterRecurse(const QJsonObject &jsonSplitter, ViewManager *manager, bool useSessionId) { const QJsonArray splitterWidgets = jsonSplitter[QStringLiteral("Widgets")].toArray(); - auto orientation = (jsonSplitter[QStringLiteral("Orientation")].toString() == QStringLiteral("Horizontal")) - ? Qt::Horizontal : Qt::Vertical; + auto orientation = (jsonSplitter[QStringLiteral("Orientation")].toString() == QStringLiteral("Horizontal")) ? Qt::Horizontal : Qt::Vertical; auto *currentSplitter = new ViewSplitter(); currentSplitter->setOrientation(orientation); @@ -982,9 +957,7 @@ ViewSplitter *restoreSessionsSplitterRecurse(const QJsonObject& jsonSplitter, Vi const auto sessionIterator = widgetJsonObject.constFind(QStringLiteral("SessionRestoreId")); if (sessionIterator != widgetJsonObject.constEnd()) { - Session *session = useSessionId - ? SessionManager::instance()->idToSession(sessionIterator->toInt()) - : SessionManager::instance()->createSession(); + Session *session = useSessionId ? SessionManager::instance()->idToSession(sessionIterator->toInt()) : SessionManager::instance()->createSession(); auto newView = manager->createView(session); currentSplitter->addWidget(newView); @@ -997,29 +970,29 @@ ViewSplitter *restoreSessionsSplitterRecurse(const QJsonObject& jsonSplitter, Vi } } // namespace -void ViewManager::loadLayout(QString file) { +void ViewManager::loadLayout(QString file) +{ QFile jsonFile(file); if (!jsonFile.open(QIODevice::ReadOnly | QIODevice::Text)) { KMessageBox::sorry(this->widget(), i18n("A problem occurred when loading the Layout.\n%1", jsonFile.fileName())); } auto json = QJsonDocument::fromJson(jsonFile.readAll()); - if (!json.isEmpty()){ + if (!json.isEmpty()) { auto splitter = restoreSessionsSplitterRecurse(json.object(), this, false); _viewContainer->addSplitter(splitter, _viewContainer->count()); } } -void ViewManager::loadLayoutFile() { - - loadLayout(QFileDialog::getOpenFileName(this->widget(), i18n("Open File"), QStringLiteral("~/"), - i18n("Konsole View Layout (*.json)"))); +void ViewManager::loadLayoutFile() +{ + loadLayout(QFileDialog::getOpenFileName(this->widget(), i18n("Open File"), QStringLiteral("~/"), i18n("Konsole View Layout (*.json)"))); } void ViewManager::restoreSessions(const KConfigGroup &group) { const auto tabList = group.readEntry("Tabs", QByteArray("[]")); const auto jsonTabs = QJsonDocument::fromJson(tabList).array(); - for (const auto& jsonSplitter : jsonTabs) { + for (const auto &jsonSplitter : jsonTabs) { auto topLevelSplitter = restoreSessionsSplitterRecurse(jsonSplitter.toObject(), this, true); _viewContainer->addSplitter(topLevelSplitter, _viewContainer->count()); } @@ -1114,7 +1087,7 @@ void ViewManager::setCurrentSession(int sessionId) auto *splitter = qobject_cast(display->parent()); if (splitter != nullptr) { - _viewContainer->setCurrentWidget(splitter->getToplevelSplitter()); + _viewContainer->setCurrentWidget(splitter->getToplevelSplitter()); } } } @@ -1132,7 +1105,7 @@ int ViewManager::newSession(const QString &profile) int ViewManager::newSession(const QString &profile, const QString &directory) { Profile::Ptr profileptr = ProfileManager::instance()->defaultProfile(); - if(!profile.isEmpty()) { + if (!profile.isEmpty()) { const QList profilelist = ProfileManager::instance()->allProfiles(); for (const auto &i : profilelist) { @@ -1198,14 +1171,15 @@ void ViewManager::setTabWidthToText(bool setTabWidthToText) _viewContainer->tabBar()->update(); } -void ViewManager::setNavigationVisibility(NavigationVisibility navigationVisibility) { +void ViewManager::setNavigationVisibility(NavigationVisibility navigationVisibility) +{ if (_navigationVisibility != navigationVisibility) { _navigationVisibility = navigationVisibility; _viewContainer->setNavigationVisibility(navigationVisibility); } } -void ViewManager::updateTerminalDisplayHistory(TerminalDisplay* terminalDisplay, bool remove) +void ViewManager::updateTerminalDisplayHistory(TerminalDisplay *terminalDisplay, bool remove) { if (terminalDisplay == nullptr) { if (_terminalDisplayHistoryIndex >= 0) { @@ -1236,10 +1210,8 @@ void ViewManager::updateTerminalDisplayHistory(TerminalDisplay* terminalDisplay, void ViewManager::registerTerminal(TerminalDisplay *terminal) { - connect(terminal, &TerminalDisplay::requestToggleExpansion, - _viewContainer, &TabbedViewContainer::toggleMaximizeCurrentTerminal, Qt::UniqueConnection); - connect(terminal, &TerminalDisplay::requestMoveToNewTab, - _viewContainer, &TabbedViewContainer::moveToNewTab, Qt::UniqueConnection); + connect(terminal, &TerminalDisplay::requestToggleExpansion, _viewContainer, &TabbedViewContainer::toggleMaximizeCurrentTerminal, Qt::UniqueConnection); + connect(terminal, &TerminalDisplay::requestMoveToNewTab, _viewContainer, &TabbedViewContainer::moveToNewTab, Qt::UniqueConnection); } void ViewManager::unregisterTerminal(TerminalDisplay *terminal) diff --git a/src/ViewManager.h b/src/ViewManager.h index f7cc3a092..e3842b6c1 100644 --- a/src/ViewManager.h +++ b/src/ViewManager.h @@ -19,8 +19,8 @@ class KActionCollection; class KConfigGroup; -namespace Konsole { - +namespace Konsole +{ class ColorScheme; class Profile; class Session; @@ -108,24 +108,24 @@ public: */ TabbedNavigation, /** The container has no navigation widget. */ - NoNavigation + NoNavigation, }; /** * Describes the options for showing or hiding the container's navigation widget. - */ + */ enum NavigationVisibility { - NavigationNotSet, // Don't rely on this information, Only use the settings. + NavigationNotSet, // Don't rely on this information, Only use the settings. AlwaysShowNavigation, ShowNavigationAsNeeded, - AlwaysHideNavigation + AlwaysHideNavigation, }; /** - * Sets the visibility of the view container's navigation widget. - * The ViewContainer subclass is responsible for ensuring that this - * setting is respected as views are dded or removed from the container - */ + * Sets the visibility of the view container's navigation widget. + * The ViewContainer subclass is responsible for ensuring that this + * setting is respected as views are dded or removed from the container + */ void setNavigationVisibility(NavigationVisibility navigationVisibility); /** Returns the current mode for controlling the visibility of the @@ -174,7 +174,7 @@ public: static bool profileHasBlurEnabled(const QExplicitlySharedDataPointer &profile); /** returns the active tab from the view - */ + */ TabbedViewContainer *activeContainer(); TerminalDisplay *createView(Session *session); void attachView(TerminalDisplay *terminal, Session *session); @@ -183,8 +183,8 @@ public: /** Reorder the terminal display history list */ void updateTerminalDisplayHistory(TerminalDisplay *terminalDisplay = nullptr, bool remove = false); - QHash forgetAll(ViewSplitter* splitter); - Session* forgetTerminal(TerminalDisplay* terminal); + QHash forgetAll(ViewSplitter *splitter); + Session *forgetTerminal(TerminalDisplay *terminal); /** * Creates and returns new session @@ -192,14 +192,14 @@ public: * The session has specified @p profile, working @p directory * and configured environment. */ - Session* createSession(const QExplicitlySharedDataPointer &profile, const QString &directory = QString()); + Session *createSession(const QExplicitlySharedDataPointer &profile, const QString &directory = QString()); Q_SIGNALS: /** Emitted when the last view is removed from the view manager */ void empty(); /** Emitted when a session is detached from a view owned by this ViewManager */ - void terminalsDetached(ViewSplitter *splitter, QHash sessionsMap); + void terminalsDetached(ViewSplitter *splitter, QHash sessionsMap); /** * Emitted when the active view changes. @@ -257,8 +257,8 @@ public Q_SLOTS: Q_SCRIPTABLE void setCurrentSession(int sessionId); /** DBus slot that creates a new session in the current view with the associated - * default profile and the default working directory - */ + * default profile and the default working directory + */ Q_SCRIPTABLE int newSession(); /** DBus slot that creates a new session in the current view. @@ -293,15 +293,15 @@ public Q_SLOTS: Q_SCRIPTABLE void prevSession(); /** DBus slot that switches the current session (as returned by - * currentSession()) with the left (or previous) one in the - * navigation tab. - */ + * currentSession()) with the left (or previous) one in the + * navigation tab. + */ Q_SCRIPTABLE void moveSessionLeft(); /** DBus slot that Switches the current session (as returned by - * currentSession()) with the right (or next) one in the navigation - * tab. - */ + * currentSession()) with the right (or next) one in the navigation + * tab. + */ Q_SCRIPTABLE void moveSessionRight(); /** DBus slot that sets ALL tabs' width to match their text */ @@ -332,7 +332,7 @@ private Q_SLOTS: // controller detects when an associated view is given the focus // and emits a signal. ViewManager listens for that signal // and then plugs the action into the UI - //void viewFocused( SessionController* controller ); + // void viewFocused( SessionController* controller ); // called when the active view in a ViewContainer changes, so // that we can plug the appropriate actions into the UI @@ -398,8 +398,7 @@ private: // takes a view from a view container owned by a different manager and places it in // newContainer owned by this manager - void takeView(ViewManager *otherManager, TabbedViewContainer *otherContainer, - TabbedViewContainer *newContainer, TerminalDisplay *view); + void takeView(ViewManager *otherManager, TabbedViewContainer *otherContainer, TabbedViewContainer *newContainer, TerminalDisplay *view); void splitView(Qt::Orientation orientation); // creates a new container which can hold terminal displays @@ -414,7 +413,7 @@ private: // actions associated with that view, and exposes basic information // about the session ( such as title and associated icon ) to the display. SessionController *createController(Session *session, TerminalDisplay *view); - void removeController(SessionController* controller); + void removeController(SessionController *controller); // Activates a different terminal when the TerminalDisplay // closes or is detached and another one should be focused. @@ -446,7 +445,6 @@ private: // containers open QList _multiTabOnlyActions; QList _multiSplitterOnlyActions; - }; } diff --git a/src/ViewProperties.cpp b/src/ViewProperties.cpp index 8a6367182..55dfff659 100644 --- a/src/ViewProperties.cpp +++ b/src/ViewProperties.cpp @@ -11,11 +11,11 @@ using Konsole::ViewProperties; QHash ViewProperties::_viewProperties; -ViewProperties::ViewProperties(QObject *parent) : - QObject(parent), - _icon(QIcon()), - _title(QString()), - _identifier(0) +ViewProperties::ViewProperties(QObject *parent) + : QObject(parent) + , _icon(QIcon()) + , _title(QString()) + , _identifier(0) { } diff --git a/src/ViewProperties.h b/src/ViewProperties.h index 3614450d7..b31b9a303 100644 --- a/src/ViewProperties.h +++ b/src/ViewProperties.h @@ -8,17 +8,18 @@ #define VIEWPROPERTIES_H // Qt +#include +#include #include #include -#include #include -#include // Konsole #include "konsoleprivate_export.h" #include "session/Session.h" -namespace Konsole { +namespace Konsole +{ /** * Encapsulates user-visible information about the terminal session currently being displayed in a view, * such as the associated title and icon. @@ -118,6 +119,7 @@ protected: void setColor(const QColor &color); /** Subclasses may call this method to change the identifier. */ void setIdentifier(int id); + private: Q_DISABLE_COPY(ViewProperties) @@ -130,4 +132,4 @@ private: }; } -#endif //VIEWPROPERTIES_H +#endif // VIEWPROPERTIES_H diff --git a/src/Vt102Emulation.cpp b/src/Vt102Emulation.cpp index f4e6bcb62..11465661c 100644 --- a/src/Vt102Emulation.cpp +++ b/src/Vt102Emulation.cpp @@ -14,17 +14,17 @@ // Qt #include -#include #include +#include // KDE #include // Konsole +#include "EscapeSequenceUrlExtractor.h" #include "keyboardtranslator/KeyboardTranslator.h" #include "session/SessionController.h" #include "terminalDisplay/TerminalDisplay.h" -#include "EscapeSequenceUrlExtractor.h" using Konsole::Vt102Emulation; @@ -44,27 +44,21 @@ using Konsole::Vt102Emulation; unsigned short Konsole::vt100_graphics[32] = { // 0/8 1/9 2/10 3/11 4/12 5/13 6/14 7/15 - 0x0020, 0x25C6, 0x2592, 0x2409, 0x240c, 0x240d, 0x240a, 0x00b0, - 0x00b1, 0x2424, 0x240b, 0x2518, 0x2510, 0x250c, 0x2514, 0x253c, - 0xF800, 0xF801, 0x2500, 0xF803, 0xF804, 0x251c, 0x2524, 0x2534, - 0x252c, 0x2502, 0x2264, 0x2265, 0x03C0, 0x2260, 0x00A3, 0x00b7 -}; + 0x0020, 0x25C6, 0x2592, 0x2409, 0x240c, 0x240d, 0x240a, 0x00b0, 0x00b1, 0x2424, 0x240b, 0x2518, 0x2510, 0x250c, 0x2514, 0x253c, + 0xF800, 0xF801, 0x2500, 0xF803, 0xF804, 0x251c, 0x2524, 0x2534, 0x252c, 0x2502, 0x2264, 0x2265, 0x03C0, 0x2260, 0x00A3, 0x00b7}; -enum XTERM_EXTENDED { - URL_LINK = '8' -}; +enum XTERM_EXTENDED { URL_LINK = '8', }; -Vt102Emulation::Vt102Emulation() : - Emulation(), - _currentModes(TerminalState()), - _savedModes(TerminalState()), - _pendingSessionAttributesUpdates(QHash()), - _sessionAttributesUpdateTimer(new QTimer(this)), - _reportFocusEvents(false) +Vt102Emulation::Vt102Emulation() + : Emulation() + , _currentModes(TerminalState()) + , _savedModes(TerminalState()) + , _pendingSessionAttributesUpdates(QHash()) + , _sessionAttributesUpdateTimer(new QTimer(this)) + , _reportFocusEvents(false) { _sessionAttributesUpdateTimer->setSingleShot(true); - QObject::connect(_sessionAttributesUpdateTimer, &QTimer::timeout, this, - &Konsole::Vt102Emulation::updateSessionAttributes); + QObject::connect(_sessionAttributesUpdateTimer, &QTimer::timeout, this, &Konsole::Vt102Emulation::updateSessionAttributes); initTokenizer(); } @@ -258,13 +252,13 @@ void Vt102Emulation::addToCurrentToken(uint cc) } // Character Class flags used while decoding -const int CTL = 1; // Control character -const int CHR = 2; // Printable character -const int CPN = 4; // TODO: Document me -const int DIG = 8; // Digit -const int SCS = 16; // Select Character Set -const int GRP = 32; // TODO: Document me -const int CPS = 64; // Character which indicates end of window resize +const int CTL = 1; // Control character +const int CHR = 2; // Printable character +const int CPN = 4; // TODO: Document me +const int DIG = 8; // Digit +const int SCS = 16; // Select Character Set +const int GRP = 32; // TODO: Document me +const int CPS = 64; // Character which indicates end of window resize void Vt102Emulation::initTokenizer() { @@ -318,211 +312,265 @@ void Vt102Emulation::initTokenizer() 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 && (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[2] == SP ) -#define epsp( ) (p >= 5 && s[3] == SP ) -#define osc (tokenBufferPos >= 2 && tokenBuffer[1] == ']') -#define ces(C) (cc < 256 && (charClass[cc] & (C)) == (C)) -#define dcs (p >= 2 && s[0] == ESC && s[1] == 'P') +#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[2] == SP) +#define epsp() (p >= 5 && s[3] == SP) +#define osc (tokenBufferPos >= 2 && tokenBuffer[1] == ']') +#define ces(C) (cc < 256 && (charClass[cc] & (C)) == (C)) +#define dcs (p >= 2 && s[0] == ESC && s[1] == 'P') -#define CNTL(c) ((c)-'@') +#define CNTL(c) ((c) - '@') const int ESC = 27; const int DEL = 127; -const int SP = 32; +const int SP = 32; // process an incoming unicode character void Vt102Emulation::receiveChar(uint cc) { - if (cc == DEL) { - return; //VT100: ignore. - } - - if (ces(CTL)) - { - // ignore control characters in the text part of osc (aka OSC) "ESC]" - // escape sequences; this matches what XTERM docs say - // Allow BEL and ESC here, it will either end the text or be removed later. - if (osc && cc != 0x1b && cc != 0x07) { - return; + if (cc == DEL) { + return; // VT100: ignore. } - if (!osc) { - // DEC HACK ALERT! Control Characters are allowed *within* esc sequences in VT100 - // This means, they do neither a resetTokenizer() nor a pushToToken(). Some of them, do - // of course. Guess this originates from a weakly layered handling of the X-on - // X-off protocol, which comes really below this level. - if (cc == CNTL('X') || cc == CNTL('Z') || cc == ESC) { - resetTokenizer(); //VT100: CAN or SUB - } - if (cc != ESC) - { - processToken(token_ctl(cc+'@'), 0, 0); - return; - } - } - } - // advance the state - addToCurrentToken(cc); - - - uint* s = tokenBuffer; - const int p = tokenBufferPos; - - if (getMode(MODE_Ansi)) - { - if (lec(1,0,ESC)) { return; } - if (lec(1,0,ESC+128)) { s[0] = ESC; receiveChar('['); return; } - if (les(2,1,GRP)) { return; } - // Operating System Command - if (p > 2 && s[1] == ']') { - // ']' ... '\' - if (s[p-2] == ESC && s[p-1] == '\\') { - // This runs two times per link, the first prepares the link to be read, - // the second finalizes it. - if (s[2] == XTERM_EXTENDED::URL_LINK) { - // printf '\e]8;;https://example.com\e\\This is a link\e]8;;\e\\\n' - _currentScreen->urlExtractor()->toggleUrlInput(); - } - processSessionAttributeRequest(p-1); - resetTokenizer(); - return; - } - // ']' ... + one character for reprocessing - if (s[p-2] == ESC) { processSessionAttributeRequest(p-1); resetTokenizer(); receiveChar(cc); return; } - // ']' ... - if (s[p-1] == 0x07) { processSessionAttributeRequest(p); resetTokenizer(); return; } - } - // ']' ... - if (osc ) { return; } - if (lec(3,2,'?')) { return; } - if (lec(3,2,'>')) { return; } - if (lec(3,2,'!')) { return; } - if (lec(3,2,SP )) { return; } - if (lec(4,3,SP )) { return; } - if (lun( )) { processToken(token_chr(), applyCharset(cc), 0); resetTokenizer(); return; } - if (dcs ) { return; /* TODO We don't xterm DCS, so we just eat it */ } - if (lec(2,0,ESC)) { processToken(token_esc(s[1]), 0, 0); resetTokenizer(); return; } - if (les(3,1,SCS)) { processToken(token_esc_cs(s[1],s[2]), 0, 0); resetTokenizer(); return; } - if (lec(3,1,'#')) { processToken(token_esc_de(s[2]), 0, 0); resetTokenizer(); return; } - if (eps( CPN)) { processToken(token_csi_pn(cc), argv[0],argv[1]); resetTokenizer(); return; } - - // resize = \e[8;;t - if (eps(CPS)) - { - processToken(token_csi_ps(cc, argv[0]), argv[1], argv[2]); - resetTokenizer(); - return; - } - - if (epe( )) { processToken(token_csi_pe(cc), 0, 0); resetTokenizer(); return; } - - if (esp ( )) { processToken(token_csi_sp(cc), 0, 0); resetTokenizer(); return; } - if (epsp( )) { processToken(token_csi_psp(cc, argv[0]), 0, 0); resetTokenizer(); return; } - - if (ees(DIG)) { addDigit(cc-'0'); return; } - if (eec(';')) { addArgument(); return; } - for (int i = 0; i <= argc; i++) - { - if (epp()) { - processToken(token_csi_pr(cc,argv[i]), 0, 0); - } else if (egt()) { - processToken(token_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(token_csi_ps(cc, argv[i-2]), COLOR_SPACE_RGB, (argv[i] << 16) | (argv[i+1] << 8) | argv[i+2]); - i += 2; + if (ces(CTL)) { + // ignore control characters in the text part of osc (aka OSC) "ESC]" + // escape sequences; this matches what XTERM docs say + // Allow BEL and ESC here, it will either end the text or be removed later. + if (osc && cc != 0x1b && cc != 0x07) { + return; } - else if (cc == 'm' && argc - i >= 2 && (argv[i] == 38 || argv[i] == 48) && argv[i+1] == 5) - { - // ESC[ ... 48;5; ... m -or- ESC[ ... 38;5; ... m - i += 2; - processToken(token_csi_ps(cc, argv[i-2]), COLOR_SPACE_256, argv[i]); - } else { - processToken(token_csi_ps(cc,argv[i]), 0, 0); + + if (!osc) { + // DEC HACK ALERT! Control Characters are allowed *within* esc sequences in VT100 + // This means, they do neither a resetTokenizer() nor a pushToToken(). Some of them, do + // of course. Guess this originates from a weakly layered handling of the X-on + // X-off protocol, which comes really below this level. + if (cc == CNTL('X') || cc == CNTL('Z') || cc == ESC) { + resetTokenizer(); // VT100: CAN or SUB + } + if (cc != ESC) { + processToken(token_ctl(cc + '@'), 0, 0); + return; + } } } - resetTokenizer(); - } else { - // VT52 Mode - if (lec(1,0,ESC)) { - return; - } - if (les(1,0,CHR)) - { - processToken(token_chr(), s[0], 0); + // advance the state + addToCurrentToken(cc); + + uint *s = tokenBuffer; + const int p = tokenBufferPos; + + if (getMode(MODE_Ansi)) { + if (lec(1, 0, ESC)) { + return; + } + if (lec(1, 0, ESC + 128)) { + s[0] = ESC; + receiveChar('['); + return; + } + if (les(2, 1, GRP)) { + return; + } + // Operating System Command + if (p > 2 && s[1] == ']') { + // ']' ... '\' + if (s[p - 2] == ESC && s[p - 1] == '\\') { + // This runs two times per link, the first prepares the link to be read, + // the second finalizes it. + if (s[2] == XTERM_EXTENDED::URL_LINK) { + // printf '\e]8;;https://example.com\e\\This is a link\e]8;;\e\\\n' + _currentScreen->urlExtractor()->toggleUrlInput(); + } + processSessionAttributeRequest(p - 1); + resetTokenizer(); + return; + } + // ']' ... + one character for reprocessing + if (s[p - 2] == ESC) { + processSessionAttributeRequest(p - 1); + resetTokenizer(); + receiveChar(cc); + return; + } + // ']' ... + if (s[p - 1] == 0x07) { + processSessionAttributeRequest(p); + resetTokenizer(); + return; + } + } + // ']' ... + if (osc) { + return; + } + if (lec(3, 2, '?')) { + return; + } + if (lec(3, 2, '>')) { + return; + } + if (lec(3, 2, '!')) { + return; + } + if (lec(3, 2, SP)) { + return; + } + if (lec(4, 3, SP)) { + return; + } + if (lun()) { + processToken(token_chr(), applyCharset(cc), 0); + resetTokenizer(); + return; + } + if (dcs) { + return; /* TODO We don't xterm DCS, so we just eat it */ + } + if (lec(2, 0, ESC)) { + processToken(token_esc(s[1]), 0, 0); + resetTokenizer(); + return; + } + if (les(3, 1, SCS)) { + processToken(token_esc_cs(s[1], s[2]), 0, 0); + resetTokenizer(); + return; + } + if (lec(3, 1, '#')) { + processToken(token_esc_de(s[2]), 0, 0); + resetTokenizer(); + return; + } + if (eps(CPN)) { + processToken(token_csi_pn(cc), argv[0], argv[1]); + resetTokenizer(); + return; + } + + // resize = \e[8;;t + if (eps(CPS)) { + processToken(token_csi_ps(cc, argv[0]), argv[1], argv[2]); + resetTokenizer(); + return; + } + + if (epe()) { + processToken(token_csi_pe(cc), 0, 0); + resetTokenizer(); + return; + } + + if (esp()) { + processToken(token_csi_sp(cc), 0, 0); + resetTokenizer(); + return; + } + if (epsp()) { + processToken(token_csi_psp(cc, argv[0]), 0, 0); + resetTokenizer(); + return; + } + + if (ees(DIG)) { + addDigit(cc - '0'); + return; + } + if (eec(';')) { + addArgument(); + return; + } + for (int i = 0; i <= argc; i++) { + if (epp()) { + processToken(token_csi_pr(cc, argv[i]), 0, 0); + } else if (egt()) { + processToken(token_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(token_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(token_csi_ps(cc, argv[i - 2]), COLOR_SPACE_256, argv[i]); + } else { + processToken(token_csi_ps(cc, argv[i]), 0, 0); + } + } + resetTokenizer(); + } else { + // VT52 Mode + if (lec(1, 0, ESC)) { + return; + } + if (les(1, 0, CHR)) { + processToken(token_chr(), s[0], 0); + resetTokenizer(); + return; + } + if (lec(2, 1, 'Y')) { + return; + } + if (lec(3, 1, 'Y')) { + return; + } + if (p < 4) { + processToken(token_vt52(s[1]), 0, 0); + resetTokenizer(); + return; + } + processToken(token_vt52(s[1]), s[2], s[3]); resetTokenizer(); return; } - if (lec(2,1,'Y')) { - return; - } - if (lec(3,1,'Y')) { - return; - } - if (p < 4) - { - processToken(token_vt52(s[1] ), 0, 0); - resetTokenizer(); - return; - } - processToken(token_vt52(s[1]), s[2], s[3]); - resetTokenizer(); - return; - } } void Vt102Emulation::processSessionAttributeRequest(int tokenSize) { - // Describes the window or terminal session attribute to change - // See Session::SessionAttributes for possible values - int attribute = 0; - int i; + // Describes the window or terminal session attribute to change + // See Session::SessionAttributes for possible values + int attribute = 0; + int i; - // ignore last character (ESC or BEL) - --tokenSize; + // ignore last character (ESC or BEL) + --tokenSize; - // skip first two characters (ESC, ']') - for (i = 2; i < tokenSize && - tokenBuffer[i] >= '0' && - tokenBuffer[i] <= '9'; i++) - { - attribute = 10 * attribute + (tokenBuffer[i]-'0'); - } + // skip first two characters (ESC, ']') + for (i = 2; i < tokenSize && tokenBuffer[i] >= '0' && tokenBuffer[i] <= '9'; i++) { + attribute = 10 * attribute + (tokenBuffer[i] - '0'); + } - if (tokenBuffer[i] != ';') - { - reportDecodingError(); - return; - } - // skip ';' - ++i; + if (tokenBuffer[i] != ';') { + reportDecodingError(); + return; + } + // skip ';' + ++i; - QString value = QString::fromUcs4(&tokenBuffer[i], tokenSize - i); - if (_currentScreen->urlExtractor()->reading()) { - value.remove(0,1); - _currentScreen->urlExtractor()->setUrl(value); - return; - } + QString value = QString::fromUcs4(&tokenBuffer[i], tokenSize - i); + if (_currentScreen->urlExtractor()->reading()) { + value.remove(0, 1); + _currentScreen->urlExtractor()->setUrl(value); + return; + } - if (value == QLatin1String("?")) { - // pass terminator type indication here, because OSC response terminator - // should match the terminator of OSC request. - Q_EMIT sessionAttributeRequest(attribute, tokenBuffer[tokenSize]); - return; - } + if (value == QLatin1String("?")) { + // pass terminator type indication here, because OSC response terminator + // should match the terminator of OSC request. + Q_EMIT sessionAttributeRequest(attribute, tokenBuffer[tokenSize]); + return; + } - _pendingSessionAttributesUpdates[attribute] = value; - _sessionAttributesUpdateTimer->start(20); + _pendingSessionAttributesUpdates[attribute] = value; + _sessionAttributesUpdateTimer->start(20); } void Vt102Emulation::updateSessionAttributes() @@ -530,7 +578,7 @@ void Vt102Emulation::updateSessionAttributes() QListIterator iter(_pendingSessionAttributesUpdates.keys()); while (iter.hasNext()) { int arg = iter.next(); - Q_EMIT sessionAttributeChanged(arg , _pendingSessionAttributesUpdates[arg]); + Q_EMIT sessionAttributeChanged(arg, _pendingSessionAttributesUpdates[arg]); } _pendingSessionAttributesUpdates.clear(); } @@ -555,462 +603,989 @@ void Vt102Emulation::updateSessionAttributes() void Vt102Emulation::processToken(int token, int p, int q) { - switch (token) - { - case token_chr( ) : - _currentScreen->displayCharacter (p ); break; //UTF16 + switch (token) { + case token_chr(): + _currentScreen->displayCharacter(p); + break; // UTF16 - // 127 DEL : ignored on input + // 127 DEL : ignored on input - case token_ctl('@' ) : /* NUL: ignored */ break; - case token_ctl('A' ) : /* SOH: ignored */ break; - case token_ctl('B' ) : /* STX: ignored */ break; - case token_ctl('C' ) : /* ETX: ignored */ break; - case token_ctl('D' ) : /* EOT: ignored */ break; - case token_ctl('E' ) : reportAnswerBack ( ); break; //VT100 - case token_ctl('F' ) : /* ACK: ignored */ break; - case token_ctl('G' ) : Q_EMIT bell(); - break; //VT100 - case token_ctl('H' ) : _currentScreen->backspace ( ); break; //VT100 - case token_ctl('I' ) : _currentScreen->tab ( ); break; //VT100 - case token_ctl('J' ) : _currentScreen->newLine ( ); break; //VT100 - case token_ctl('K' ) : _currentScreen->newLine ( ); break; //VT100 - case token_ctl('L' ) : _currentScreen->newLine ( ); break; //VT100 - case token_ctl('M' ) : _currentScreen->toStartOfLine ( ); break; //VT100 + case token_ctl('@'): /* NUL: ignored */ + break; + case token_ctl('A'): /* SOH: ignored */ + break; + case token_ctl('B'): /* STX: ignored */ + break; + case token_ctl('C'): /* ETX: ignored */ + break; + case token_ctl('D'): /* EOT: ignored */ + break; + case token_ctl('E'): + reportAnswerBack(); + break; // VT100 + case token_ctl('F'): /* ACK: ignored */ + break; + case token_ctl('G'): + Q_EMIT bell(); + break; // VT100 + case token_ctl('H'): + _currentScreen->backspace(); + break; // VT100 + case token_ctl('I'): + _currentScreen->tab(); + break; // VT100 + case token_ctl('J'): + _currentScreen->newLine(); + break; // VT100 + case token_ctl('K'): + _currentScreen->newLine(); + break; // VT100 + case token_ctl('L'): + _currentScreen->newLine(); + break; // VT100 + case token_ctl('M'): + _currentScreen->toStartOfLine(); + break; // VT100 - case token_ctl('N' ) : useCharset ( 1); break; //VT100 - case token_ctl('O' ) : useCharset ( 0); break; //VT100 + case token_ctl('N'): + useCharset(1); + break; // VT100 + case token_ctl('O'): + useCharset(0); + break; // VT100 - case token_ctl('P' ) : /* DLE: ignored */ break; - case token_ctl('Q' ) : /* DC1: XON continue */ break; //VT100 - case token_ctl('R' ) : /* DC2: ignored */ break; - case token_ctl('S' ) : /* DC3: XOFF halt */ break; //VT100 - case token_ctl('T' ) : /* DC4: ignored */ break; - case token_ctl('U' ) : /* NAK: ignored */ break; - case token_ctl('V' ) : /* SYN: ignored */ break; - case token_ctl('W' ) : /* ETB: ignored */ break; - case token_ctl('X' ) : _currentScreen->displayCharacter ( 0x2592); break; //VT100 - case token_ctl('Y' ) : /* EM : ignored */ break; - case token_ctl('Z' ) : _currentScreen->displayCharacter ( 0x2592); break; //VT100 - case token_ctl('[' ) : /* ESC: cannot be seen here. */ break; - case token_ctl('\\' ) : /* FS : ignored */ break; - case token_ctl(']' ) : /* GS : ignored */ break; - case token_ctl('^' ) : /* RS : ignored */ break; - case token_ctl('_' ) : /* US : ignored */ break; + case token_ctl('P'): /* DLE: ignored */ + break; + case token_ctl('Q'): /* DC1: XON continue */ + break; // VT100 + case token_ctl('R'): /* DC2: ignored */ + break; + case token_ctl('S'): /* DC3: XOFF halt */ + break; // VT100 + case token_ctl('T'): /* DC4: ignored */ + break; + case token_ctl('U'): /* NAK: ignored */ + break; + case token_ctl('V'): /* SYN: ignored */ + break; + case token_ctl('W'): /* ETB: ignored */ + break; + case token_ctl('X'): + _currentScreen->displayCharacter(0x2592); + break; // VT100 + case token_ctl('Y'): /* EM : ignored */ + break; + case token_ctl('Z'): + _currentScreen->displayCharacter(0x2592); + break; // VT100 + case token_ctl('['): /* ESC: cannot be seen here. */ + break; + case token_ctl('\\'): /* FS : ignored */ + break; + case token_ctl(']'): /* GS : ignored */ + break; + case token_ctl('^'): /* RS : ignored */ + break; + case token_ctl('_'): /* US : ignored */ + break; - case token_esc('D' ) : _currentScreen->index ( ); break; //VT100 - case token_esc('E' ) : _currentScreen->nextLine ( ); break; //VT100 - case token_esc('H' ) : _currentScreen->changeTabStop (true ); break; //VT100 - case token_esc('M' ) : _currentScreen->reverseIndex ( ); break; //VT100 - case token_esc('Z' ) : reportTerminalType ( ); break; - case token_esc('c' ) : reset ( ); break; + case token_esc('D'): + _currentScreen->index(); + break; // VT100 + case token_esc('E'): + _currentScreen->nextLine(); + break; // VT100 + case token_esc('H'): + _currentScreen->changeTabStop(true); + break; // VT100 + case token_esc('M'): + _currentScreen->reverseIndex(); + break; // VT100 + case token_esc('Z'): + reportTerminalType(); + break; + case token_esc('c'): + reset(); + break; - case token_esc('n' ) : useCharset ( 2); break; - case token_esc('o' ) : useCharset ( 3); break; - case token_esc('7' ) : saveCursor ( ); break; - case token_esc('8' ) : restoreCursor ( ); break; + case token_esc('n'): + useCharset(2); + break; + case token_esc('o'): + useCharset(3); + break; + case token_esc('7'): + saveCursor(); + break; + case token_esc('8'): + restoreCursor(); + break; - case token_esc('=' ) : setMode (MODE_AppKeyPad); break; - case token_esc('>' ) : resetMode (MODE_AppKeyPad); break; - case token_esc('<' ) : setMode (MODE_Ansi ); break; //VT100 + case token_esc('='): + setMode(MODE_AppKeyPad); + break; + case token_esc('>'): + resetMode(MODE_AppKeyPad); + break; + case token_esc('<'): + setMode(MODE_Ansi); + break; // VT100 - case token_esc_cs('(', '0') : setCharset (0, '0'); break; //VT100 - case token_esc_cs('(', 'A') : setCharset (0, 'A'); break; //VT100 - case token_esc_cs('(', 'B') : setCharset (0, 'B'); break; //VT100 + case token_esc_cs('(', '0'): + setCharset(0, '0'); + break; // VT100 + case token_esc_cs('(', 'A'): + setCharset(0, 'A'); + break; // VT100 + case token_esc_cs('(', 'B'): + setCharset(0, 'B'); + break; // VT100 - case token_esc_cs(')', '0') : setCharset (1, '0'); break; //VT100 - case token_esc_cs(')', 'A') : setCharset (1, 'A'); break; //VT100 - case token_esc_cs(')', 'B') : setCharset (1, 'B'); break; //VT100 + case token_esc_cs(')', '0'): + setCharset(1, '0'); + break; // VT100 + case token_esc_cs(')', 'A'): + setCharset(1, 'A'); + break; // VT100 + case token_esc_cs(')', 'B'): + setCharset(1, 'B'); + break; // VT100 - case token_esc_cs('*', '0') : setCharset (2, '0'); break; //VT100 - case token_esc_cs('*', 'A') : setCharset (2, 'A'); break; //VT100 - case token_esc_cs('*', 'B') : setCharset (2, 'B'); break; //VT100 + case token_esc_cs('*', '0'): + setCharset(2, '0'); + break; // VT100 + case token_esc_cs('*', 'A'): + setCharset(2, 'A'); + break; // VT100 + case token_esc_cs('*', 'B'): + setCharset(2, 'B'); + break; // VT100 - case token_esc_cs('+', '0') : setCharset (3, '0'); break; //VT100 - case token_esc_cs('+', 'A') : setCharset (3, 'A'); break; //VT100 - case token_esc_cs('+', 'B') : setCharset (3, 'B'); break; //VT100 + case token_esc_cs('+', '0'): + setCharset(3, '0'); + break; // VT100 + case token_esc_cs('+', 'A'): + setCharset(3, 'A'); + break; // VT100 + case token_esc_cs('+', 'B'): + setCharset(3, 'B'); + break; // VT100 - case token_esc_cs('%', 'G') : setCodec (Utf8Codec ); break; //LINUX - case token_esc_cs('%', '@') : setCodec (LocaleCodec ); break; //LINUX + case token_esc_cs('%', 'G'): + setCodec(Utf8Codec); + break; // LINUX + case token_esc_cs('%', '@'): + setCodec(LocaleCodec); + break; // LINUX - case token_esc_de('3' ) : /* Double height line, top half */ - _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , true ); - _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT_TOP , true ); - _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT_BOTTOM , false ); - break; - case token_esc_de('4' ) : /* Double height line, bottom half */ - _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , true ); - _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT_TOP , false ); - _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT_BOTTOM , true ); - break; - case token_esc_de('5' ) : /* Single width, single height line*/ - _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , false); - _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT_TOP , false); - _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT_BOTTOM , false); - break; - case token_esc_de('6' ) : /* Double width, single height line*/ - _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , true); - _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT_TOP , false); - _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT_BOTTOM , false); - break; - case token_esc_de('8' ) : _currentScreen->helpAlign ( ); break; + case token_esc_de('3'): /* Double height line, top half */ + _currentScreen->setLineProperty(LINE_DOUBLEWIDTH, true); + _currentScreen->setLineProperty(LINE_DOUBLEHEIGHT_TOP, true); + _currentScreen->setLineProperty(LINE_DOUBLEHEIGHT_BOTTOM, false); + break; + case token_esc_de('4'): /* Double height line, bottom half */ + _currentScreen->setLineProperty(LINE_DOUBLEWIDTH, true); + _currentScreen->setLineProperty(LINE_DOUBLEHEIGHT_TOP, false); + _currentScreen->setLineProperty(LINE_DOUBLEHEIGHT_BOTTOM, true); + break; + case token_esc_de('5'): /* Single width, single height line*/ + _currentScreen->setLineProperty(LINE_DOUBLEWIDTH, false); + _currentScreen->setLineProperty(LINE_DOUBLEHEIGHT_TOP, false); + _currentScreen->setLineProperty(LINE_DOUBLEHEIGHT_BOTTOM, false); + break; + case token_esc_de('6'): /* Double width, single height line*/ + _currentScreen->setLineProperty(LINE_DOUBLEWIDTH, true); + _currentScreen->setLineProperty(LINE_DOUBLEHEIGHT_TOP, false); + _currentScreen->setLineProperty(LINE_DOUBLEHEIGHT_BOTTOM, false); + break; + case token_esc_de('8'): + _currentScreen->helpAlign(); + break; -// resize = \e[8;;t - case token_csi_ps('t', 8) : setImageSize( p /*lines */, q /* columns */ ); - Q_EMIT imageResizeRequest(QSize(q, p)); - break; + // resize = \e[8;;t + case token_csi_ps('t', 8): + setImageSize(p /*lines */, q /* columns */); + Q_EMIT imageResizeRequest(QSize(q, p)); + break; -// change tab text color : \e[28;t color: 0-16,777,215 - case token_csi_ps('t', 28) : Q_EMIT changeTabTextColorRequest ( p ); break; + // change tab text color : \e[28;t color: 0-16,777,215 + case token_csi_ps('t', 28): + Q_EMIT changeTabTextColorRequest(p); + break; - case token_csi_ps('K', 0) : _currentScreen->clearToEndOfLine ( ); break; - case token_csi_ps('K', 1) : _currentScreen->clearToBeginOfLine ( ); break; - case token_csi_ps('K', 2) : _currentScreen->clearEntireLine ( ); break; - case token_csi_ps('J', 0) : _currentScreen->clearToEndOfScreen ( ); break; - case token_csi_ps('J', 1) : _currentScreen->clearToBeginOfScreen ( ); break; - case token_csi_ps('J', 2) : _currentScreen->clearEntireScreen ( ); break; - case token_csi_ps('J', 3) : clearHistory(); break; - case token_csi_ps('g', 0) : _currentScreen->changeTabStop (false ); break; //VT100 - case token_csi_ps('g', 3) : _currentScreen->clearTabStops ( ); break; //VT100 - case token_csi_ps('h', 4) : _currentScreen-> setMode (MODE_Insert ); break; - case token_csi_ps('h', 20) : setMode (MODE_NewLine ); break; - case token_csi_ps('i', 0) : /* IGNORE: attached printer */ break; //VT100 - case token_csi_ps('l', 4) : _currentScreen-> resetMode (MODE_Insert ); break; - case token_csi_ps('l', 20) : resetMode (MODE_NewLine ); break; - case token_csi_ps('s', 0) : saveCursor ( ); break; - case token_csi_ps('u', 0) : restoreCursor ( ); break; + case token_csi_ps('K', 0): + _currentScreen->clearToEndOfLine(); + break; + case token_csi_ps('K', 1): + _currentScreen->clearToBeginOfLine(); + break; + case token_csi_ps('K', 2): + _currentScreen->clearEntireLine(); + break; + case token_csi_ps('J', 0): + _currentScreen->clearToEndOfScreen(); + break; + case token_csi_ps('J', 1): + _currentScreen->clearToBeginOfScreen(); + break; + case token_csi_ps('J', 2): + _currentScreen->clearEntireScreen(); + break; + case token_csi_ps('J', 3): + clearHistory(); + break; + case token_csi_ps('g', 0): + _currentScreen->changeTabStop(false); + break; // VT100 + case token_csi_ps('g', 3): + _currentScreen->clearTabStops(); + break; // VT100 + case token_csi_ps('h', 4): + _currentScreen->setMode(MODE_Insert); + break; + case token_csi_ps('h', 20): + setMode(MODE_NewLine); + break; + case token_csi_ps('i', 0): /* IGNORE: attached printer */ + break; // VT100 + case token_csi_ps('l', 4): + _currentScreen->resetMode(MODE_Insert); + break; + case token_csi_ps('l', 20): + resetMode(MODE_NewLine); + break; + case token_csi_ps('s', 0): + saveCursor(); + break; + case token_csi_ps('u', 0): + restoreCursor(); + break; - case token_csi_ps('m', 0) : _currentScreen->setDefaultRendition ( ); break; - case token_csi_ps('m', 1) : _currentScreen-> setRendition (RE_BOLD ); break; //VT100 - case token_csi_ps('m', 2) : _currentScreen-> setRendition (RE_FAINT ); break; - case token_csi_ps('m', 3) : _currentScreen-> setRendition (RE_ITALIC ); break; //VT100 - case token_csi_ps('m', 4) : _currentScreen-> setRendition (RE_UNDERLINE); break; //VT100 - case token_csi_ps('m', 5) : _currentScreen-> setRendition (RE_BLINK ); break; //VT100 - case token_csi_ps('m', 7) : _currentScreen-> setRendition (RE_REVERSE ); break; - case token_csi_ps('m', 8) : _currentScreen-> setRendition (RE_CONCEAL ); break; - case token_csi_ps('m', 9) : _currentScreen-> setRendition (RE_STRIKEOUT); break; - case token_csi_ps('m', 53) : _currentScreen-> setRendition (RE_OVERLINE ); break; - case token_csi_ps('m', 10) : /* IGNORED: mapping related */ break; //LINUX - case token_csi_ps('m', 11) : /* IGNORED: mapping related */ break; //LINUX - case token_csi_ps('m', 12) : /* IGNORED: mapping related */ break; //LINUX - case token_csi_ps('m', 21) : _currentScreen->resetRendition (RE_BOLD ); break; - case token_csi_ps('m', 22) : _currentScreen->resetRendition (RE_BOLD ); - _currentScreen->resetRendition (RE_FAINT ); break; - case token_csi_ps('m', 23) : _currentScreen->resetRendition (RE_ITALIC ); break; //VT100 - case token_csi_ps('m', 24) : _currentScreen->resetRendition (RE_UNDERLINE); break; - case token_csi_ps('m', 25) : _currentScreen->resetRendition (RE_BLINK ); break; - case token_csi_ps('m', 27) : _currentScreen->resetRendition (RE_REVERSE ); break; - case token_csi_ps('m', 28) : _currentScreen->resetRendition (RE_CONCEAL ); break; - case token_csi_ps('m', 29) : _currentScreen->resetRendition (RE_STRIKEOUT); break; - case token_csi_ps('m', 55) : _currentScreen->resetRendition (RE_OVERLINE ); break; + case token_csi_ps('m', 0): + _currentScreen->setDefaultRendition(); + break; + case token_csi_ps('m', 1): + _currentScreen->setRendition(RE_BOLD); + break; // VT100 + case token_csi_ps('m', 2): + _currentScreen->setRendition(RE_FAINT); + break; + case token_csi_ps('m', 3): + _currentScreen->setRendition(RE_ITALIC); + break; // VT100 + case token_csi_ps('m', 4): + _currentScreen->setRendition(RE_UNDERLINE); + break; // VT100 + case token_csi_ps('m', 5): + _currentScreen->setRendition(RE_BLINK); + break; // VT100 + case token_csi_ps('m', 7): + _currentScreen->setRendition(RE_REVERSE); + break; + case token_csi_ps('m', 8): + _currentScreen->setRendition(RE_CONCEAL); + break; + case token_csi_ps('m', 9): + _currentScreen->setRendition(RE_STRIKEOUT); + break; + case token_csi_ps('m', 53): + _currentScreen->setRendition(RE_OVERLINE); + break; + case token_csi_ps('m', 10): /* IGNORED: mapping related */ + break; // LINUX + case token_csi_ps('m', 11): /* IGNORED: mapping related */ + break; // LINUX + case token_csi_ps('m', 12): /* IGNORED: mapping related */ + break; // LINUX + case token_csi_ps('m', 21): + _currentScreen->resetRendition(RE_BOLD); + break; + case token_csi_ps('m', 22): + _currentScreen->resetRendition(RE_BOLD); + _currentScreen->resetRendition(RE_FAINT); + break; + case token_csi_ps('m', 23): + _currentScreen->resetRendition(RE_ITALIC); + break; // VT100 + case token_csi_ps('m', 24): + _currentScreen->resetRendition(RE_UNDERLINE); + break; + case token_csi_ps('m', 25): + _currentScreen->resetRendition(RE_BLINK); + break; + case token_csi_ps('m', 27): + _currentScreen->resetRendition(RE_REVERSE); + break; + case token_csi_ps('m', 28): + _currentScreen->resetRendition(RE_CONCEAL); + break; + case token_csi_ps('m', 29): + _currentScreen->resetRendition(RE_STRIKEOUT); + break; + case token_csi_ps('m', 55): + _currentScreen->resetRendition(RE_OVERLINE); + break; - case token_csi_ps('m', 30) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 0); break; - case token_csi_ps('m', 31) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 1); break; - case token_csi_ps('m', 32) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 2); break; - case token_csi_ps('m', 33) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 3); break; - case token_csi_ps('m', 34) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 4); break; - case token_csi_ps('m', 35) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 5); break; - case token_csi_ps('m', 36) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 6); break; - case token_csi_ps('m', 37) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 7); break; + case token_csi_ps('m', 30): + _currentScreen->setForeColor(COLOR_SPACE_SYSTEM, 0); + break; + case token_csi_ps('m', 31): + _currentScreen->setForeColor(COLOR_SPACE_SYSTEM, 1); + break; + case token_csi_ps('m', 32): + _currentScreen->setForeColor(COLOR_SPACE_SYSTEM, 2); + break; + case token_csi_ps('m', 33): + _currentScreen->setForeColor(COLOR_SPACE_SYSTEM, 3); + break; + case token_csi_ps('m', 34): + _currentScreen->setForeColor(COLOR_SPACE_SYSTEM, 4); + break; + case token_csi_ps('m', 35): + _currentScreen->setForeColor(COLOR_SPACE_SYSTEM, 5); + break; + case token_csi_ps('m', 36): + _currentScreen->setForeColor(COLOR_SPACE_SYSTEM, 6); + break; + case token_csi_ps('m', 37): + _currentScreen->setForeColor(COLOR_SPACE_SYSTEM, 7); + break; - case token_csi_ps('m', 38) : _currentScreen->setForeColor (p, q); break; + case token_csi_ps('m', 38): + _currentScreen->setForeColor(p, q); + break; - case token_csi_ps('m', 39) : _currentScreen->setForeColor (COLOR_SPACE_DEFAULT, 0); break; + case token_csi_ps('m', 39): + _currentScreen->setForeColor(COLOR_SPACE_DEFAULT, 0); + break; - case token_csi_ps('m', 40) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 0); break; - case token_csi_ps('m', 41) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 1); break; - case token_csi_ps('m', 42) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 2); break; - case token_csi_ps('m', 43) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 3); break; - case token_csi_ps('m', 44) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 4); break; - case token_csi_ps('m', 45) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 5); break; - case token_csi_ps('m', 46) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 6); break; - case token_csi_ps('m', 47) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 7); break; + case token_csi_ps('m', 40): + _currentScreen->setBackColor(COLOR_SPACE_SYSTEM, 0); + break; + case token_csi_ps('m', 41): + _currentScreen->setBackColor(COLOR_SPACE_SYSTEM, 1); + break; + case token_csi_ps('m', 42): + _currentScreen->setBackColor(COLOR_SPACE_SYSTEM, 2); + break; + case token_csi_ps('m', 43): + _currentScreen->setBackColor(COLOR_SPACE_SYSTEM, 3); + break; + case token_csi_ps('m', 44): + _currentScreen->setBackColor(COLOR_SPACE_SYSTEM, 4); + break; + case token_csi_ps('m', 45): + _currentScreen->setBackColor(COLOR_SPACE_SYSTEM, 5); + break; + case token_csi_ps('m', 46): + _currentScreen->setBackColor(COLOR_SPACE_SYSTEM, 6); + break; + case token_csi_ps('m', 47): + _currentScreen->setBackColor(COLOR_SPACE_SYSTEM, 7); + break; - case token_csi_ps('m', 48) : _currentScreen->setBackColor (p, q); break; + case token_csi_ps('m', 48): + _currentScreen->setBackColor(p, q); + break; - case token_csi_ps('m', 49) : _currentScreen->setBackColor (COLOR_SPACE_DEFAULT, 1); break; + case token_csi_ps('m', 49): + _currentScreen->setBackColor(COLOR_SPACE_DEFAULT, 1); + break; - case token_csi_ps('m', 90) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 8); break; - case token_csi_ps('m', 91) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 9); break; - case token_csi_ps('m', 92) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 10); break; - case token_csi_ps('m', 93) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 11); break; - case token_csi_ps('m', 94) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 12); break; - case token_csi_ps('m', 95) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 13); break; - case token_csi_ps('m', 96) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 14); break; - case token_csi_ps('m', 97) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 15); break; + case token_csi_ps('m', 90): + _currentScreen->setForeColor(COLOR_SPACE_SYSTEM, 8); + break; + case token_csi_ps('m', 91): + _currentScreen->setForeColor(COLOR_SPACE_SYSTEM, 9); + break; + case token_csi_ps('m', 92): + _currentScreen->setForeColor(COLOR_SPACE_SYSTEM, 10); + break; + case token_csi_ps('m', 93): + _currentScreen->setForeColor(COLOR_SPACE_SYSTEM, 11); + break; + case token_csi_ps('m', 94): + _currentScreen->setForeColor(COLOR_SPACE_SYSTEM, 12); + break; + case token_csi_ps('m', 95): + _currentScreen->setForeColor(COLOR_SPACE_SYSTEM, 13); + break; + case token_csi_ps('m', 96): + _currentScreen->setForeColor(COLOR_SPACE_SYSTEM, 14); + break; + case token_csi_ps('m', 97): + _currentScreen->setForeColor(COLOR_SPACE_SYSTEM, 15); + break; - case token_csi_ps('m', 100) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 8); break; - case token_csi_ps('m', 101) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 9); break; - case token_csi_ps('m', 102) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 10); break; - case token_csi_ps('m', 103) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 11); break; - case token_csi_ps('m', 104) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 12); break; - case token_csi_ps('m', 105) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 13); break; - case token_csi_ps('m', 106) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 14); break; - case token_csi_ps('m', 107) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 15); break; + case token_csi_ps('m', 100): + _currentScreen->setBackColor(COLOR_SPACE_SYSTEM, 8); + break; + case token_csi_ps('m', 101): + _currentScreen->setBackColor(COLOR_SPACE_SYSTEM, 9); + break; + case token_csi_ps('m', 102): + _currentScreen->setBackColor(COLOR_SPACE_SYSTEM, 10); + break; + case token_csi_ps('m', 103): + _currentScreen->setBackColor(COLOR_SPACE_SYSTEM, 11); + break; + case token_csi_ps('m', 104): + _currentScreen->setBackColor(COLOR_SPACE_SYSTEM, 12); + break; + case token_csi_ps('m', 105): + _currentScreen->setBackColor(COLOR_SPACE_SYSTEM, 13); + break; + case token_csi_ps('m', 106): + _currentScreen->setBackColor(COLOR_SPACE_SYSTEM, 14); + break; + case token_csi_ps('m', 107): + _currentScreen->setBackColor(COLOR_SPACE_SYSTEM, 15); + break; - case token_csi_ps('n', 5) : reportStatus ( ); break; - case token_csi_ps('n', 6) : reportCursorPosition ( ); break; - case token_csi_ps('q', 0) : /* IGNORED: LEDs off */ break; //VT100 - case token_csi_ps('q', 1) : /* IGNORED: LED1 on */ break; //VT100 - case token_csi_ps('q', 2) : /* IGNORED: LED2 on */ break; //VT100 - case token_csi_ps('q', 3) : /* IGNORED: LED3 on */ break; //VT100 - case token_csi_ps('q', 4) : /* IGNORED: LED4 on */ break; //VT100 - case token_csi_ps('x', 0) : reportTerminalParms ( 2); break; //VT100 - case token_csi_ps('x', 1) : reportTerminalParms ( 3); break; //VT100 + case token_csi_ps('n', 5): + reportStatus(); + break; + case token_csi_ps('n', 6): + reportCursorPosition(); + break; + case token_csi_ps('q', 0): /* IGNORED: LEDs off */ + break; // VT100 + case token_csi_ps('q', 1): /* IGNORED: LED1 on */ + break; // VT100 + case token_csi_ps('q', 2): /* IGNORED: LED2 on */ + break; // VT100 + case token_csi_ps('q', 3): /* IGNORED: LED3 on */ + break; // VT100 + case token_csi_ps('q', 4): /* IGNORED: LED4 on */ + break; // VT100 + case token_csi_ps('x', 0): + reportTerminalParms(2); + break; // VT100 + case token_csi_ps('x', 1): + reportTerminalParms(3); + break; // VT100 - case token_csi_pn('@' ) : _currentScreen->insertChars (p ); break; - case token_csi_pn('A' ) : _currentScreen->cursorUp (p ); break; //VT100 - case token_csi_pn('B' ) : _currentScreen->cursorDown (p ); break; //VT100 - case token_csi_pn('C' ) : _currentScreen->cursorRight (p ); break; //VT100 - case token_csi_pn('D' ) : _currentScreen->cursorLeft (p ); break; //VT100 - case token_csi_pn('E' ) : _currentScreen->cursorNextLine (p ); break; //VT100 - case token_csi_pn('F' ) : _currentScreen->cursorPreviousLine (p ); break; //VT100 - case token_csi_pn('G' ) : _currentScreen->setCursorX (p ); break; //LINUX - case token_csi_pn('H' ) : _currentScreen->setCursorYX (p, q); break; //VT100 - case token_csi_pn('I' ) : _currentScreen->tab (p ); break; - case token_csi_pn('L' ) : _currentScreen->insertLines (p ); break; - case token_csi_pn('M' ) : _currentScreen->deleteLines (p ); break; - case token_csi_pn('P' ) : _currentScreen->deleteChars (p ); break; - case token_csi_pn('S' ) : _currentScreen->scrollUp (p ); break; - case token_csi_pn('T' ) : _currentScreen->scrollDown (p ); break; - case token_csi_pn('X' ) : _currentScreen->eraseChars (p ); break; - case token_csi_pn('Z' ) : _currentScreen->backtab (p ); break; - case token_csi_pn('b' ) : _currentScreen->repeatChars (p ); break; - case token_csi_pn('c' ) : reportTerminalType ( ); break; //VT100 - case token_csi_pn('d' ) : _currentScreen->setCursorY (p ); break; //LINUX - case token_csi_pn('f' ) : _currentScreen->setCursorYX (p, q); break; //VT100 - case token_csi_pn('r' ) : setMargins (p, q); break; //VT100 - case token_csi_pn('y' ) : /* IGNORED: Confidence test */ break; //VT100 + case token_csi_pn('@'): + _currentScreen->insertChars(p); + break; + case token_csi_pn('A'): + _currentScreen->cursorUp(p); + break; // VT100 + case token_csi_pn('B'): + _currentScreen->cursorDown(p); + break; // VT100 + case token_csi_pn('C'): + _currentScreen->cursorRight(p); + break; // VT100 + case token_csi_pn('D'): + _currentScreen->cursorLeft(p); + break; // VT100 + case token_csi_pn('E'): + _currentScreen->cursorNextLine(p); + break; // VT100 + case token_csi_pn('F'): + _currentScreen->cursorPreviousLine(p); + break; // VT100 + case token_csi_pn('G'): + _currentScreen->setCursorX(p); + break; // LINUX + case token_csi_pn('H'): + _currentScreen->setCursorYX(p, q); + break; // VT100 + case token_csi_pn('I'): + _currentScreen->tab(p); + break; + case token_csi_pn('L'): + _currentScreen->insertLines(p); + break; + case token_csi_pn('M'): + _currentScreen->deleteLines(p); + break; + case token_csi_pn('P'): + _currentScreen->deleteChars(p); + break; + case token_csi_pn('S'): + _currentScreen->scrollUp(p); + break; + case token_csi_pn('T'): + _currentScreen->scrollDown(p); + break; + case token_csi_pn('X'): + _currentScreen->eraseChars(p); + break; + case token_csi_pn('Z'): + _currentScreen->backtab(p); + break; + case token_csi_pn('b'): + _currentScreen->repeatChars(p); + break; + case token_csi_pn('c'): + reportTerminalType(); + break; // VT100 + case token_csi_pn('d'): + _currentScreen->setCursorY(p); + break; // LINUX + case token_csi_pn('f'): + _currentScreen->setCursorYX(p, q); + break; // VT100 + case token_csi_pn('r'): + setMargins(p, q); + break; // VT100 + case token_csi_pn('y'): /* IGNORED: Confidence test */ + break; // VT100 - case token_csi_pr('h', 1) : setMode (MODE_AppCuKeys); break; //VT100 - case token_csi_pr('l', 1) : resetMode (MODE_AppCuKeys); break; //VT100 - case token_csi_pr('s', 1) : saveMode (MODE_AppCuKeys); break; //FIXME - case token_csi_pr('r', 1) : restoreMode (MODE_AppCuKeys); break; //FIXME + case token_csi_pr('h', 1): + setMode(MODE_AppCuKeys); + break; // VT100 + case token_csi_pr('l', 1): + resetMode(MODE_AppCuKeys); + break; // VT100 + case token_csi_pr('s', 1): + saveMode(MODE_AppCuKeys); + break; // FIXME + case token_csi_pr('r', 1): + restoreMode(MODE_AppCuKeys); + break; // FIXME - case token_csi_pr('l', 2) : resetMode (MODE_Ansi ); break; //VT100 + case token_csi_pr('l', 2): + resetMode(MODE_Ansi); + break; // VT100 - case token_csi_pr('h', 3) : setMode (MODE_132Columns); break; //VT100 - case token_csi_pr('l', 3) : resetMode (MODE_132Columns); break; //VT100 + case token_csi_pr('h', 3): + setMode(MODE_132Columns); + break; // VT100 + case token_csi_pr('l', 3): + resetMode(MODE_132Columns); + break; // VT100 - case token_csi_pr('h', 4) : /* IGNORED: soft scrolling */ break; //VT100 - case token_csi_pr('l', 4) : /* IGNORED: soft scrolling */ break; //VT100 + case token_csi_pr('h', 4): /* IGNORED: soft scrolling */ + break; // VT100 + case token_csi_pr('l', 4): /* IGNORED: soft scrolling */ + break; // VT100 - case token_csi_pr('h', 5) : _currentScreen-> setMode (MODE_Screen ); break; //VT100 - case token_csi_pr('l', 5) : _currentScreen-> resetMode (MODE_Screen ); break; //VT100 + case token_csi_pr('h', 5): + _currentScreen->setMode(MODE_Screen); + break; // VT100 + case token_csi_pr('l', 5): + _currentScreen->resetMode(MODE_Screen); + break; // VT100 - case token_csi_pr('h', 6) : _currentScreen-> setMode (MODE_Origin ); break; //VT100 - case token_csi_pr('l', 6) : _currentScreen-> resetMode (MODE_Origin ); break; //VT100 - case token_csi_pr('s', 6) : _currentScreen-> saveMode (MODE_Origin ); break; //FIXME - case token_csi_pr('r', 6) : _currentScreen->restoreMode (MODE_Origin ); break; //FIXME + case token_csi_pr('h', 6): + _currentScreen->setMode(MODE_Origin); + break; // VT100 + case token_csi_pr('l', 6): + _currentScreen->resetMode(MODE_Origin); + break; // VT100 + case token_csi_pr('s', 6): + _currentScreen->saveMode(MODE_Origin); + break; // FIXME + case token_csi_pr('r', 6): + _currentScreen->restoreMode(MODE_Origin); + break; // FIXME - case token_csi_pr('h', 7) : _currentScreen-> setMode (MODE_Wrap ); break; //VT100 - case token_csi_pr('l', 7) : _currentScreen-> resetMode (MODE_Wrap ); break; //VT100 - case token_csi_pr('s', 7) : _currentScreen-> saveMode (MODE_Wrap ); break; //FIXME - case token_csi_pr('r', 7) : _currentScreen->restoreMode (MODE_Wrap ); break; //FIXME + case token_csi_pr('h', 7): + _currentScreen->setMode(MODE_Wrap); + break; // VT100 + case token_csi_pr('l', 7): + _currentScreen->resetMode(MODE_Wrap); + break; // VT100 + case token_csi_pr('s', 7): + _currentScreen->saveMode(MODE_Wrap); + break; // FIXME + case token_csi_pr('r', 7): + _currentScreen->restoreMode(MODE_Wrap); + break; // FIXME - case token_csi_pr('h', 8) : /* IGNORED: autorepeat on */ break; //VT100 - case token_csi_pr('l', 8) : /* IGNORED: autorepeat off */ break; //VT100 - case token_csi_pr('s', 8) : /* IGNORED: autorepeat on */ break; //VT100 - case token_csi_pr('r', 8) : /* IGNORED: autorepeat off */ break; //VT100 + case token_csi_pr('h', 8): /* IGNORED: autorepeat on */ + break; // VT100 + case token_csi_pr('l', 8): /* IGNORED: autorepeat off */ + break; // VT100 + case token_csi_pr('s', 8): /* IGNORED: autorepeat on */ + break; // VT100 + case token_csi_pr('r', 8): /* IGNORED: autorepeat off */ + break; // VT100 - case token_csi_pr('h', 9) : /* IGNORED: interlace */ break; //VT100 - case token_csi_pr('l', 9) : /* IGNORED: interlace */ break; //VT100 - case token_csi_pr('s', 9) : /* IGNORED: interlace */ break; //VT100 - case token_csi_pr('r', 9) : /* IGNORED: interlace */ break; //VT100 + case token_csi_pr('h', 9): /* IGNORED: interlace */ + break; // VT100 + case token_csi_pr('l', 9): /* IGNORED: interlace */ + break; // VT100 + case token_csi_pr('s', 9): /* IGNORED: interlace */ + break; // VT100 + case token_csi_pr('r', 9): /* IGNORED: interlace */ + break; // VT100 - case token_csi_pr('h', 12) : /* IGNORED: Cursor blink */ break; //att610 - case token_csi_pr('l', 12) : /* IGNORED: Cursor blink */ break; //att610 - case token_csi_pr('s', 12) : /* IGNORED: Cursor blink */ break; //att610 - case token_csi_pr('r', 12) : /* IGNORED: Cursor blink */ break; //att610 + case token_csi_pr('h', 12): /* IGNORED: Cursor blink */ + break; // att610 + case token_csi_pr('l', 12): /* IGNORED: Cursor blink */ + break; // att610 + case token_csi_pr('s', 12): /* IGNORED: Cursor blink */ + break; // att610 + case token_csi_pr('r', 12): /* IGNORED: Cursor blink */ + break; // att610 - case token_csi_pr('h', 25) : setMode (MODE_Cursor ); break; //VT100 - case token_csi_pr('l', 25) : resetMode (MODE_Cursor ); break; //VT100 - case token_csi_pr('s', 25) : saveMode (MODE_Cursor ); break; //VT100 - case token_csi_pr('r', 25) : restoreMode (MODE_Cursor ); break; //VT100 + case token_csi_pr('h', 25): + setMode(MODE_Cursor); + break; // VT100 + case token_csi_pr('l', 25): + resetMode(MODE_Cursor); + break; // VT100 + case token_csi_pr('s', 25): + saveMode(MODE_Cursor); + break; // VT100 + case token_csi_pr('r', 25): + restoreMode(MODE_Cursor); + break; // VT100 - case token_csi_pr('h', 40) : setMode(MODE_Allow132Columns ); break; // XTERM - case token_csi_pr('l', 40) : resetMode(MODE_Allow132Columns ); break; // XTERM + case token_csi_pr('h', 40): + setMode(MODE_Allow132Columns); + break; // XTERM + case token_csi_pr('l', 40): + resetMode(MODE_Allow132Columns); + break; // XTERM - case token_csi_pr('h', 41) : /* IGNORED: obsolete more(1) fix */ break; //XTERM - case token_csi_pr('l', 41) : /* IGNORED: obsolete more(1) fix */ break; //XTERM - case token_csi_pr('s', 41) : /* IGNORED: obsolete more(1) fix */ break; //XTERM - case token_csi_pr('r', 41) : /* IGNORED: obsolete more(1) fix */ break; //XTERM + case token_csi_pr('h', 41): /* IGNORED: obsolete more(1) fix */ + break; // XTERM + case token_csi_pr('l', 41): /* IGNORED: obsolete more(1) fix */ + break; // XTERM + case token_csi_pr('s', 41): /* IGNORED: obsolete more(1) fix */ + break; // XTERM + case token_csi_pr('r', 41): /* IGNORED: obsolete more(1) fix */ + break; // XTERM - case token_csi_pr('h', 47) : setMode (MODE_AppScreen); break; //VT100 - case token_csi_pr('l', 47) : resetMode (MODE_AppScreen); break; //VT100 - case token_csi_pr('s', 47) : saveMode (MODE_AppScreen); break; //XTERM - case token_csi_pr('r', 47) : restoreMode (MODE_AppScreen); break; //XTERM + case token_csi_pr('h', 47): + setMode(MODE_AppScreen); + break; // VT100 + case token_csi_pr('l', 47): + resetMode(MODE_AppScreen); + break; // VT100 + case token_csi_pr('s', 47): + saveMode(MODE_AppScreen); + break; // XTERM + case token_csi_pr('r', 47): + restoreMode(MODE_AppScreen); + break; // XTERM - case token_csi_pr('h', 67) : /* IGNORED: DECBKM */ break; //XTERM - case token_csi_pr('l', 67) : /* IGNORED: DECBKM */ break; //XTERM - case token_csi_pr('s', 67) : /* IGNORED: DECBKM */ break; //XTERM - case token_csi_pr('r', 67) : /* IGNORED: DECBKM */ break; //XTERM + case token_csi_pr('h', 67): /* IGNORED: DECBKM */ + break; // XTERM + case token_csi_pr('l', 67): /* IGNORED: DECBKM */ + break; // XTERM + case token_csi_pr('s', 67): /* IGNORED: DECBKM */ + break; // XTERM + case token_csi_pr('r', 67): /* IGNORED: DECBKM */ + break; // XTERM - // XTerm defines the following modes: - // SET_VT200_MOUSE 1000 - // SET_VT200_HIGHLIGHT_MOUSE 1001 - // SET_BTN_EVENT_MOUSE 1002 - // SET_ANY_EVENT_MOUSE 1003 - // + // XTerm defines the following modes: + // SET_VT200_MOUSE 1000 + // SET_VT200_HIGHLIGHT_MOUSE 1001 + // SET_BTN_EVENT_MOUSE 1002 + // SET_ANY_EVENT_MOUSE 1003 + // - //Note about mouse modes: - //There are four mouse modes which xterm-compatible terminals can support - 1000,1001,1002,1003 - //Konsole currently supports mode 1000 (basic mouse press and release), mode 1002 (dragging the mouse) - //and mode 1003 (moving the mouse). - //TODO: Implementation of mouse mode 1001 (something called hilight tracking). - // + // 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), mode 1002 (dragging the mouse) + // and mode 1003 (moving the mouse). + // TODO: Implementation of mouse mode 1001 (something called hilight tracking). + // - case token_csi_pr('h', 1000) : setMode (MODE_Mouse1000); break; //XTERM - case token_csi_pr('l', 1000) : resetMode (MODE_Mouse1000); break; //XTERM - case token_csi_pr('s', 1000) : saveMode (MODE_Mouse1000); break; //XTERM - case token_csi_pr('r', 1000) : restoreMode (MODE_Mouse1000); break; //XTERM + case token_csi_pr('h', 1000): + setMode(MODE_Mouse1000); + break; // XTERM + case token_csi_pr('l', 1000): + resetMode(MODE_Mouse1000); + break; // XTERM + case token_csi_pr('s', 1000): + saveMode(MODE_Mouse1000); + break; // XTERM + case token_csi_pr('r', 1000): + restoreMode(MODE_Mouse1000); + break; // XTERM - case token_csi_pr('h', 1001) : /* IGNORED: hilite mouse tracking */ break; //XTERM - case token_csi_pr('l', 1001) : resetMode (MODE_Mouse1001); break; //XTERM - case token_csi_pr('s', 1001) : /* IGNORED: hilite mouse tracking */ break; //XTERM - case token_csi_pr('r', 1001) : /* IGNORED: hilite mouse tracking */ break; //XTERM + case token_csi_pr('h', 1001): /* IGNORED: hilite mouse tracking */ + break; // XTERM + case token_csi_pr('l', 1001): + resetMode(MODE_Mouse1001); + break; // XTERM + case token_csi_pr('s', 1001): /* IGNORED: hilite mouse tracking */ + break; // XTERM + case token_csi_pr('r', 1001): /* IGNORED: hilite mouse tracking */ + break; // XTERM - case token_csi_pr('h', 1002) : setMode (MODE_Mouse1002); break; //XTERM - case token_csi_pr('l', 1002) : resetMode (MODE_Mouse1002); break; //XTERM - case token_csi_pr('s', 1002) : saveMode (MODE_Mouse1002); break; //XTERM - case token_csi_pr('r', 1002) : restoreMode (MODE_Mouse1002); break; //XTERM + case token_csi_pr('h', 1002): + setMode(MODE_Mouse1002); + break; // XTERM + case token_csi_pr('l', 1002): + resetMode(MODE_Mouse1002); + break; // XTERM + case token_csi_pr('s', 1002): + saveMode(MODE_Mouse1002); + break; // XTERM + case token_csi_pr('r', 1002): + restoreMode(MODE_Mouse1002); + break; // XTERM - case token_csi_pr('h', 1003) : setMode (MODE_Mouse1003); break; //XTERM - case token_csi_pr('l', 1003) : resetMode (MODE_Mouse1003); break; //XTERM - case token_csi_pr('s', 1003) : saveMode (MODE_Mouse1003); break; //XTERM - case token_csi_pr('r', 1003) : restoreMode (MODE_Mouse1003); break; //XTERM + case token_csi_pr('h', 1003): + setMode(MODE_Mouse1003); + break; // XTERM + case token_csi_pr('l', 1003): + resetMode(MODE_Mouse1003); + break; // XTERM + case token_csi_pr('s', 1003): + saveMode(MODE_Mouse1003); + break; // XTERM + case token_csi_pr('r', 1003): + restoreMode(MODE_Mouse1003); + break; // XTERM - case token_csi_pr('h', 1004) : _reportFocusEvents = true; break; - case token_csi_pr('l', 1004) : _reportFocusEvents = false; break; + case token_csi_pr('h', 1004): + _reportFocusEvents = true; + break; + case token_csi_pr('l', 1004): + _reportFocusEvents = false; + break; - case token_csi_pr('h', 1005) : setMode (MODE_Mouse1005); break; //XTERM - case token_csi_pr('l', 1005) : resetMode (MODE_Mouse1005); break; //XTERM - case token_csi_pr('s', 1005) : saveMode (MODE_Mouse1005); break; //XTERM - case token_csi_pr('r', 1005) : restoreMode (MODE_Mouse1005); break; //XTERM + case token_csi_pr('h', 1005): + setMode(MODE_Mouse1005); + break; // XTERM + case token_csi_pr('l', 1005): + resetMode(MODE_Mouse1005); + break; // XTERM + case token_csi_pr('s', 1005): + saveMode(MODE_Mouse1005); + break; // XTERM + case token_csi_pr('r', 1005): + restoreMode(MODE_Mouse1005); + break; // XTERM - case token_csi_pr('h', 1006) : setMode (MODE_Mouse1006); break; //XTERM - case token_csi_pr('l', 1006) : resetMode (MODE_Mouse1006); break; //XTERM - case token_csi_pr('s', 1006) : saveMode (MODE_Mouse1006); break; //XTERM - case token_csi_pr('r', 1006) : restoreMode (MODE_Mouse1006); break; //XTERM + case token_csi_pr('h', 1006): + setMode(MODE_Mouse1006); + break; // XTERM + case token_csi_pr('l', 1006): + resetMode(MODE_Mouse1006); + break; // XTERM + case token_csi_pr('s', 1006): + saveMode(MODE_Mouse1006); + break; // XTERM + case token_csi_pr('r', 1006): + restoreMode(MODE_Mouse1006); + break; // XTERM - case token_csi_pr('h', 1007) : setMode (MODE_Mouse1007); break; //XTERM - case token_csi_pr('l', 1007) : resetMode (MODE_Mouse1007); break; //XTERM - case token_csi_pr('s', 1007) : saveMode (MODE_Mouse1007); break; //XTERM - case token_csi_pr('r', 1007) : restoreMode (MODE_Mouse1007); break; //XTERM + case token_csi_pr('h', 1007): + setMode(MODE_Mouse1007); + break; // XTERM + case token_csi_pr('l', 1007): + resetMode(MODE_Mouse1007); + break; // XTERM + case token_csi_pr('s', 1007): + saveMode(MODE_Mouse1007); + break; // XTERM + case token_csi_pr('r', 1007): + restoreMode(MODE_Mouse1007); + break; // XTERM - case token_csi_pr('h', 1015) : setMode (MODE_Mouse1015); break; //URXVT - case token_csi_pr('l', 1015) : resetMode (MODE_Mouse1015); break; //URXVT - case token_csi_pr('s', 1015) : saveMode (MODE_Mouse1015); break; //URXVT - case token_csi_pr('r', 1015) : restoreMode (MODE_Mouse1015); break; //URXVT + case token_csi_pr('h', 1015): + setMode(MODE_Mouse1015); + break; // URXVT + case token_csi_pr('l', 1015): + resetMode(MODE_Mouse1015); + break; // URXVT + case token_csi_pr('s', 1015): + saveMode(MODE_Mouse1015); + break; // URXVT + case token_csi_pr('r', 1015): + restoreMode(MODE_Mouse1015); + break; // URXVT - case token_csi_pr('h', 1034) : /* IGNORED: 8bitinput activation */ break; //XTERM + case token_csi_pr('h', 1034): /* IGNORED: 8bitinput activation */ + break; // XTERM - case token_csi_pr('h', 1047) : setMode (MODE_AppScreen); break; //XTERM - case token_csi_pr('l', 1047) : _screen[1]->clearEntireScreen(); resetMode(MODE_AppScreen); break; //XTERM - case token_csi_pr('s', 1047) : saveMode (MODE_AppScreen); break; //XTERM - case token_csi_pr('r', 1047) : restoreMode (MODE_AppScreen); break; //XTERM + case token_csi_pr('h', 1047): + setMode(MODE_AppScreen); + break; // XTERM + case token_csi_pr('l', 1047): + _screen[1]->clearEntireScreen(); + resetMode(MODE_AppScreen); + break; // XTERM + case token_csi_pr('s', 1047): + saveMode(MODE_AppScreen); + break; // XTERM + case token_csi_pr('r', 1047): + restoreMode(MODE_AppScreen); + break; // XTERM - //FIXME: Unitoken: save translations - case token_csi_pr('h', 1048) : saveCursor ( ); break; //XTERM - case token_csi_pr('l', 1048) : restoreCursor ( ); break; //XTERM - case token_csi_pr('s', 1048) : saveCursor ( ); break; //XTERM - case token_csi_pr('r', 1048) : restoreCursor ( ); break; //XTERM + // FIXME: Unitoken: save translations + case token_csi_pr('h', 1048): + saveCursor(); + break; // XTERM + case token_csi_pr('l', 1048): + restoreCursor(); + break; // XTERM + case token_csi_pr('s', 1048): + saveCursor(); + break; // XTERM + case token_csi_pr('r', 1048): + restoreCursor(); + break; // XTERM - //FIXME: every once new sequences like this pop up in xterm. + // FIXME: every once new sequences like this pop up in xterm. // Here's a guess of what they could mean. - case token_csi_pr('h', 1049) : saveCursor(); _screen[1]->clearEntireScreen(); setMode(MODE_AppScreen); break; //XTERM - case token_csi_pr('l', 1049) : resetMode(MODE_AppScreen); restoreCursor(); break; //XTERM + case token_csi_pr('h', 1049): + saveCursor(); + _screen[1]->clearEntireScreen(); + setMode(MODE_AppScreen); + break; // XTERM + case token_csi_pr('l', 1049): + resetMode(MODE_AppScreen); + restoreCursor(); + break; // XTERM - case token_csi_pr('h', 2004) : setMode (MODE_BracketedPaste); break; //XTERM - case token_csi_pr('l', 2004) : resetMode (MODE_BracketedPaste); break; //XTERM - case token_csi_pr('s', 2004) : saveMode (MODE_BracketedPaste); break; //XTERM - case token_csi_pr('r', 2004) : restoreMode (MODE_BracketedPaste); break; //XTERM + case token_csi_pr('h', 2004): + setMode(MODE_BracketedPaste); + break; // XTERM + case token_csi_pr('l', 2004): + resetMode(MODE_BracketedPaste); + break; // XTERM + case token_csi_pr('s', 2004): + saveMode(MODE_BracketedPaste); + break; // XTERM + case token_csi_pr('r', 2004): + restoreMode(MODE_BracketedPaste); + break; // XTERM // Set Cursor Style (DECSCUSR), VT520, with the extra xterm sequences // the first one is a special case, 'ESC[ q', which mimics 'ESC[1 q' // Using 0 to reset to default is matching VTE, but not any official standard. - case token_csi_sp ('q' ) : Q_EMIT setCursorStyleRequest(Enum::BlockCursor, true); break; - case token_csi_psp('q', 0) : Q_EMIT resetCursorStyleRequest(); break; - case token_csi_psp('q', 1) : Q_EMIT setCursorStyleRequest(Enum::BlockCursor, true); break; - case token_csi_psp('q', 2) : Q_EMIT setCursorStyleRequest(Enum::BlockCursor, false); break; - case token_csi_psp('q', 3) : Q_EMIT setCursorStyleRequest(Enum::UnderlineCursor, true); break; - case token_csi_psp('q', 4) : Q_EMIT setCursorStyleRequest(Enum::UnderlineCursor, false); break; - case token_csi_psp('q', 5) : Q_EMIT setCursorStyleRequest(Enum::IBeamCursor, true); break; - case token_csi_psp('q', 6) : Q_EMIT setCursorStyleRequest(Enum::IBeamCursor, false); break; + case token_csi_sp('q'): + Q_EMIT setCursorStyleRequest(Enum::BlockCursor, true); + break; + case token_csi_psp('q', 0): + Q_EMIT resetCursorStyleRequest(); + break; + case token_csi_psp('q', 1): + Q_EMIT setCursorStyleRequest(Enum::BlockCursor, true); + break; + case token_csi_psp('q', 2): + Q_EMIT setCursorStyleRequest(Enum::BlockCursor, false); + break; + case token_csi_psp('q', 3): + Q_EMIT setCursorStyleRequest(Enum::UnderlineCursor, true); + break; + case token_csi_psp('q', 4): + Q_EMIT setCursorStyleRequest(Enum::UnderlineCursor, false); + break; + case token_csi_psp('q', 5): + Q_EMIT setCursorStyleRequest(Enum::IBeamCursor, true); + break; + case token_csi_psp('q', 6): + Q_EMIT setCursorStyleRequest(Enum::IBeamCursor, false); + break; - //FIXME: weird DEC reset sequence - case token_csi_pe('p' ) : /* IGNORED: reset ( ) */ break; + // FIXME: weird DEC reset sequence + case token_csi_pe('p'): /* IGNORED: reset ( ) */ + break; - //FIXME: when changing between vt52 and ansi mode evtl do some resetting. - case token_vt52('A' ) : _currentScreen->cursorUp ( 1); break; //VT52 - case token_vt52('B' ) : _currentScreen->cursorDown ( 1); break; //VT52 - case token_vt52('C' ) : _currentScreen->cursorRight ( 1); break; //VT52 - case token_vt52('D' ) : _currentScreen->cursorLeft ( 1); break; //VT52 + // FIXME: when changing between vt52 and ansi mode evtl do some resetting. + case token_vt52('A'): + _currentScreen->cursorUp(1); + break; // VT52 + case token_vt52('B'): + _currentScreen->cursorDown(1); + break; // VT52 + case token_vt52('C'): + _currentScreen->cursorRight(1); + break; // VT52 + case token_vt52('D'): + _currentScreen->cursorLeft(1); + break; // VT52 - case token_vt52('F' ) : setAndUseCharset (0, '0'); break; //VT52 - case token_vt52('G' ) : setAndUseCharset (0, 'B'); break; //VT52 + case token_vt52('F'): + setAndUseCharset(0, '0'); + break; // VT52 + case token_vt52('G'): + setAndUseCharset(0, 'B'); + break; // VT52 - case token_vt52('H' ) : _currentScreen->setCursorYX (1,1 ); break; //VT52 - case token_vt52('I' ) : _currentScreen->reverseIndex ( ); break; //VT52 - case token_vt52('J' ) : _currentScreen->clearToEndOfScreen ( ); break; //VT52 - case token_vt52('K' ) : _currentScreen->clearToEndOfLine ( ); break; //VT52 - case token_vt52('Y' ) : _currentScreen->setCursorYX (p-31,q-31 ); break; //VT52 - case token_vt52('Z' ) : reportTerminalType ( ); break; //VT52 - case token_vt52('<' ) : setMode (MODE_Ansi ); break; //VT52 - case token_vt52('=' ) : setMode (MODE_AppKeyPad); break; //VT52 - case token_vt52('>' ) : resetMode (MODE_AppKeyPad); break; //VT52 + case token_vt52('H'): + _currentScreen->setCursorYX(1, 1); + break; // VT52 + case token_vt52('I'): + _currentScreen->reverseIndex(); + break; // VT52 + case token_vt52('J'): + _currentScreen->clearToEndOfScreen(); + break; // VT52 + case token_vt52('K'): + _currentScreen->clearToEndOfLine(); + break; // VT52 + case token_vt52('Y'): + _currentScreen->setCursorYX(p - 31, q - 31); + break; // VT52 + case token_vt52('Z'): + reportTerminalType(); + break; // VT52 + case token_vt52('<'): + setMode(MODE_Ansi); + break; // VT52 + case token_vt52('='): + setMode(MODE_AppKeyPad); + break; // VT52 + case token_vt52('>'): + resetMode(MODE_AppKeyPad); + break; // VT52 - case token_csi_pg('c' ) : reportSecondaryAttributes( ); break; //VT100 + case token_csi_pg('c'): + reportSecondaryAttributes(); + break; // VT100 default: reportDecodingError(); break; - } + } } void Vt102Emulation::clearScreenAndSetColumns(int columnCount) { - setImageSize(_currentScreen->getLines(),columnCount); + setImageSize(_currentScreen->getLines(), columnCount); clearEntireScreen(); setDefaultMargins(); - _currentScreen->setCursorYX(0,0); + _currentScreen->setCursorYX(0, 0); } -void Vt102Emulation::sendString(const QByteArray& s) +void Vt102Emulation::sendString(const QByteArray &s) { Q_EMIT sendData(s); } void Vt102Emulation::reportCursorPosition() { - char tmp[30]; - snprintf(tmp, sizeof(tmp), "\033[%d;%dR", _currentScreen->getCursorY()+1, _currentScreen->getCursorX()+1); - sendString(tmp); + char tmp[30]; + snprintf(tmp, sizeof(tmp), "\033[%d;%dR", _currentScreen->getCursorY() + 1, _currentScreen->getCursorX() + 1); + sendString(tmp); } void Vt102Emulation::reportTerminalType() { - // Primary device attribute response (Request was: ^[[0c or ^[[c (from TT321 Users Guide)) - // VT220: ^[[?63;1;2;3;6;7;8c (list deps on emul. capabilities) - // VT100: ^[[?1;2c - // VT101: ^[[?1;0c - // VT102: ^[[?6v - if (getMode(MODE_Ansi)) { - sendString("\033[?1;2c"); // I'm a VT100 - } else { - sendString("\033/Z"); // I'm a VT52 - } + // Primary device attribute response (Request was: ^[[0c or ^[[c (from TT321 Users Guide)) + // VT220: ^[[?63;1;2;3;6;7;8c (list deps on emul. capabilities) + // VT100: ^[[?1;2c + // VT101: ^[[?1;0c + // VT102: ^[[?6v + if (getMode(MODE_Ansi)) { + sendString("\033[?1;2c"); // I'm a VT100 + } else { + sendString("\033/Z"); // I'm a VT52 + } } void Vt102Emulation::reportSecondaryAttributes() { - // Secondary device attribute response (Request was: ^[[>0c or ^[[>c) - if (getMode(MODE_Ansi)) { - sendString("\033[>0;115;0c"); // Why 115? ;) - } else { - sendString("\033/Z"); // FIXME I don't think VT52 knows about it but kept for - } - // konsoles backward compatibility. + // Secondary device attribute response (Request was: ^[[>0c or ^[[>c) + if (getMode(MODE_Ansi)) { + sendString("\033[>0;115;0c"); // Why 115? ;) + } else { + sendString("\033/Z"); // FIXME I don't think VT52 knows about it but kept for + } + // konsoles backward compatibility. } /* DECREPTPARM – Report Terminal Parameters @@ -1021,22 +1596,22 @@ void Vt102Emulation::reportSecondaryAttributes() void Vt102Emulation::reportTerminalParms(int p) { char tmp[100]; -/* - sol=1: This message is a request; report in response to a request. - par=1: No parity set - nbits=1: 8 bits per character - xspeed=112: 9600 - rspeed=112: 9600 - clkmul=1: The bit rate multiplier is 16. - flags=0: None -*/ + /* + sol=1: This message is a request; report in response to a request. + par=1: No parity set + nbits=1: 8 bits per character + xspeed=112: 9600 + rspeed=112: 9600 + clkmul=1: The bit rate multiplier is 16. + flags=0: None + */ snprintf(tmp, sizeof(tmp), "\033[%d;1;1;112;112;1;0x", p); // not really true. sendString(tmp); } void Vt102Emulation::reportStatus() { - sendString("\033[0n"); //VT100. Device status report. 0 = Ready. + sendString("\033[0n"); // VT100. Device status report. 0 = Ready. } void Vt102Emulation::reportAnswerBack() @@ -1084,16 +1659,15 @@ void Vt102Emulation::sendMouseEvent(int cb, int cx, int cy, int eventType) cb += 0x3c; } - //Mouse motion handling + // Mouse motion handling if ((getMode(MODE_Mouse1002) || getMode(MODE_Mouse1003)) && eventType == 1) { - cb += 0x20; //add 32 to signify motion event + cb += 0x20; // add 32 to signify motion event } char command[40]; 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'); + 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)) { @@ -1123,7 +1697,8 @@ void Vt102Emulation::sendMouseEvent(int cb, int cx, int cy, int eventType) * sequence into the FocusLost/FocusGained autocmd: * https://github.com/sjl/vitality.vim */ -void Vt102Emulation::focusChanged(bool focused) { +void Vt102Emulation::focusChanged(bool focused) +{ if (_reportFocusEvents) { sendString(focused ? "\033[I" : "\033[O"); } @@ -1132,10 +1707,7 @@ void Vt102Emulation::focusChanged(bool focused) { void Vt102Emulation::sendText(const QString &text) { if (!text.isEmpty()) { - QKeyEvent event(QEvent::KeyPress, - 0, - Qt::NoModifier, - text); + QKeyEvent event(QEvent::KeyPress, 0, Qt::NoModifier, text); sendKeyEvent(&event); // expose as a big fat keypress event } } @@ -1145,7 +1717,7 @@ void Vt102Emulation::sendKeyEvent(QKeyEvent *event) const Qt::KeyboardModifiers modifiers = event->modifiers(); KeyboardTranslator::States states = KeyboardTranslator::NoState; - TerminalDisplay * currentView = _currentScreen->currentTerminalDisplay(); + TerminalDisplay *currentView = _currentScreen->currentTerminalDisplay(); bool isReadOnly = false; if (currentView != nullptr && currentView->sessionController() != nullptr) { isReadOnly = currentView->sessionController()->isReadOnly(); @@ -1164,13 +1736,13 @@ void Vt102Emulation::sendKeyEvent(QKeyEvent *event) if (getMode(MODE_AppScreen)) { states |= KeyboardTranslator::AlternateScreenState; } - if (getMode(MODE_AppKeyPad) && ((modifiers &Qt::KeypadModifier) != 0U)) { + if (getMode(MODE_AppKeyPad) && ((modifiers & Qt::KeypadModifier) != 0U)) { states |= KeyboardTranslator::ApplicationKeypadState; } if (!isReadOnly) { // check flow control state - if ((modifiers &Qt::ControlModifier) != 0U) { + if ((modifiers & Qt::ControlModifier) != 0U) { switch (event->key()) { case Qt::Key_S: Q_EMIT flowControlKeyPressed(true); @@ -1185,10 +1757,7 @@ void Vt102Emulation::sendKeyEvent(QKeyEvent *event) // look up key binding if (_keyTranslator != nullptr) { - KeyboardTranslator::Entry entry = _keyTranslator->findEntry( - event->key(), - modifiers, - states); + KeyboardTranslator::Entry entry = _keyTranslator->findEntry(event->key(), modifiers, states); // send result to terminal QByteArray textToSend; @@ -1199,22 +1768,16 @@ void Vt102Emulation::sendKeyEvent(QKeyEvent *event) // in the keyboard modifier) const bool wantsAltModifier = ((entry.modifiers() & entry.modifierMask() & Qt::AltModifier) != 0U); const bool wantsMetaModifier = ((entry.modifiers() & entry.modifierMask() & Qt::MetaModifier) != 0U); - const bool wantsAnyModifier = ((entry.state() & - entry.stateMask() & KeyboardTranslator::AnyModifierState) != 0); + const bool wantsAnyModifier = ((entry.state() & entry.stateMask() & KeyboardTranslator::AnyModifierState) != 0); - if ( ((modifiers & Qt::AltModifier) != 0U) && !(wantsAltModifier || wantsAnyModifier) - && !event->text().isEmpty() ) - { + if (((modifiers & Qt::AltModifier) != 0U) && !(wantsAltModifier || wantsAnyModifier) && !event->text().isEmpty()) { textToSend.prepend("\033"); } - if ( ((modifiers & Qt::MetaModifier) != 0U) && !(wantsMetaModifier || wantsAnyModifier) - && !event->text().isEmpty() ) - { + if (((modifiers & Qt::MetaModifier) != 0U) && !(wantsMetaModifier || wantsAnyModifier) && !event->text().isEmpty()) { textToSend.prepend("\030@s"); } - if ( entry.command() != KeyboardTranslator::NoCommand ) - { + if (entry.command() != KeyboardTranslator::NoCommand) { if ((entry.command() & KeyboardTranslator::EraseCommand) != 0) { textToSend += eraseChar(); } @@ -1228,14 +1791,13 @@ void Vt102Emulation::sendKeyEvent(QKeyEvent *event) } else if ((entry.command() & KeyboardTranslator::ScrollLineDownCommand) != 0) { currentView->scrollScreenWindow(ScreenWindow::ScrollLines, 1); } else if ((entry.command() & KeyboardTranslator::ScrollUpToTopCommand) != 0) { - currentView->scrollScreenWindow(ScreenWindow::ScrollLines, - - currentView->screenWindow()->currentLine()); + currentView->scrollScreenWindow(ScreenWindow::ScrollLines, -currentView->screenWindow()->currentLine()); } else if ((entry.command() & KeyboardTranslator::ScrollDownToBottomCommand) != 0) { currentView->scrollScreenWindow(ScreenWindow::ScrollLines, lineCount()); } } } else if (!entry.text().isEmpty()) { - textToSend += entry.text(true,modifiers); + textToSend += entry.text(true, modifiers); } else { Q_ASSERT(_codec); textToSend += _codec->fromUnicode(event->text()); @@ -1248,10 +1810,11 @@ void Vt102Emulation::sendKeyEvent(QKeyEvent *event) if (!isReadOnly) { // print an error message to the terminal if no key translator has been // set - QString translatorError = i18n("No keyboard translator available. " - "The information needed to convert key presses " - "into characters to send to the terminal " - "is missing."); + QString translatorError = i18n( + "No keyboard translator available. " + "The information needed to convert key presses " + "into characters to send to the terminal " + "is missing."); reset(); receiveData(translatorError.toLatin1().constData(), translatorError.count()); } @@ -1292,7 +1855,7 @@ unsigned int Vt102Emulation::applyCharset(uint c) return vt100_graphics[c - 0x5f]; } if (CHARSET.pound && c == '#') { - return 0xa3; //This mode is obsolete + return 0xa3; // This mode is obsolete } return c; } @@ -1333,7 +1896,7 @@ void Vt102Emulation::useCharset(int n) { CHARSET.cu_cs = n & 3; CHARSET.graphic = (CHARSET.charset[n & 3] == '0'); - CHARSET.pound = (CHARSET.charset[n & 3] == 'A'); //This mode is obsolete + CHARSET.pound = (CHARSET.charset[n & 3] == 'A'); // This mode is obsolete } void Vt102Emulation::setDefaultMargins() @@ -1351,17 +1914,17 @@ void Vt102Emulation::setMargins(int t, int b) void Vt102Emulation::saveCursor() { CHARSET.sa_graphic = CHARSET.graphic; - CHARSET.sa_pound = CHARSET.pound; //This mode is obsolete + CHARSET.sa_pound = CHARSET.pound; // This mode is obsolete // we are not clear about these - //sa_charset = charsets[cScreen->_charset]; - //sa_charset_num = cScreen->_charset; + // sa_charset = charsets[cScreen->_charset]; + // sa_charset_num = cScreen->_charset; _currentScreen->saveCursor(); } void Vt102Emulation::restoreCursor() { CHARSET.graphic = CHARSET.sa_graphic; - CHARSET.pound = CHARSET.sa_pound; //This mode is obsolete + CHARSET.pound = CHARSET.sa_pound; // This mode is obsolete _currentScreen->restoreCursor(); } @@ -1394,19 +1957,31 @@ void Vt102Emulation::resetModes() // the profile alternate scrolling property after reset() is called, which // makes more sense; also this matches XTerm behavior. - 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_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_AppScreen); + saveMode(MODE_AppScreen); + resetMode(MODE_AppCuKeys); + saveMode(MODE_AppCuKeys); + resetMode(MODE_AppKeyPad); + saveMode(MODE_AppKeyPad); resetMode(MODE_NewLine); setMode(MODE_Ansi); } @@ -1526,10 +2101,7 @@ bool Vt102Emulation::getMode(int m) char Vt102Emulation::eraseChar() const { - KeyboardTranslator::Entry entry = _keyTranslator->findEntry( - Qt::Key_Backspace, - Qt::NoModifier, - KeyboardTranslator::NoState); + KeyboardTranslator::Entry entry = _keyTranslator->findEntry(Qt::Key_Backspace, Qt::NoModifier, KeyboardTranslator::NoState); if (entry.text().count() > 0) { return entry.text().at(0); } else { diff --git a/src/Vt102Emulation.h b/src/Vt102Emulation.h index ada456476..05fa631f1 100644 --- a/src/Vt102Emulation.h +++ b/src/Vt102Emulation.h @@ -20,33 +20,34 @@ class QTimer; class QKeyEvent; -#define MODE_AppCuKeys (MODES_SCREEN+0) // Application cursor keys (DECCKM) -#define MODE_AppKeyPad (MODES_SCREEN+1) // -#define MODE_Mouse1000 (MODES_SCREEN+2) // Send mouse X,Y position on press and release -#define MODE_Mouse1001 (MODES_SCREEN+3) // Use Hilight mouse tracking -#define MODE_Mouse1002 (MODES_SCREEN+4) // Use cell motion mouse tracking -#define MODE_Mouse1003 (MODES_SCREEN+5) // Use all motion mouse tracking -#define MODE_Mouse1005 (MODES_SCREEN+6) // Xterm-style extended coordinates -#define MODE_Mouse1006 (MODES_SCREEN+7) // 2nd Xterm-style extended coordinates -#define MODE_Mouse1007 (MODES_SCREEN+8) // XTerm Alternate Scroll mode; also check AlternateScrolling profile property -#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) +#define MODE_AppCuKeys (MODES_SCREEN + 0) // Application cursor keys (DECCKM) +#define MODE_AppKeyPad (MODES_SCREEN + 1) // +#define MODE_Mouse1000 (MODES_SCREEN + 2) // Send mouse X,Y position on press and release +#define MODE_Mouse1001 (MODES_SCREEN + 3) // Use Hilight mouse tracking +#define MODE_Mouse1002 (MODES_SCREEN + 4) // Use cell motion mouse tracking +#define MODE_Mouse1003 (MODES_SCREEN + 5) // Use all motion mouse tracking +#define MODE_Mouse1005 (MODES_SCREEN + 6) // Xterm-style extended coordinates +#define MODE_Mouse1006 (MODES_SCREEN + 7) // 2nd Xterm-style extended coordinates +#define MODE_Mouse1007 (MODES_SCREEN + 8) // XTerm Alternate Scroll mode; also check AlternateScrolling profile property +#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 { +namespace Konsole +{ extern unsigned short vt100_graphics[32]; struct CharCodes { // coding info char charset[4]; // - int cu_cs; // actual charset. - bool graphic; // Some VT100 tricks - bool pound; // Some VT100 tricks + int cu_cs; // actual charset. + bool graphic; // Some VT100 tricks + bool pound; // Some VT100 tricks bool sa_graphic; // saved graphic - bool sa_pound; // saved pound + bool sa_pound; // saved pound }; /** @@ -103,7 +104,7 @@ private: void resetCharset(int scrno); void setMargins(int top, int bottom); - //set margins for all screens back to their defaults + // set margins for all screens back to their defaults void setDefaultMargins(); // returns true if 'mode' is set or false otherwise @@ -119,7 +120,7 @@ private: void resetTokenizer(); #define MAX_TOKEN_LENGTH 256 // Max length of tokens (e.g. window title) void addToCurrentToken(uint cc); - uint tokenBuffer[MAX_TOKEN_LENGTH]; //FIXME: overflow? + uint tokenBuffer[MAX_TOKEN_LENGTH]; // FIXME: overflow? int tokenBufferPos; #define MAXARGS 15 void addDigit(int dig); diff --git a/src/WindowSystemInfo.h b/src/WindowSystemInfo.h index ec56aed68..9409c99a8 100644 --- a/src/WindowSystemInfo.h +++ b/src/WindowSystemInfo.h @@ -9,7 +9,8 @@ #include "konsoleprivate_export.h" -namespace Konsole { +namespace Konsole +{ class KONSOLEPRIVATE_EXPORT WindowSystemInfo { public: diff --git a/src/ZModemDialog.cpp b/src/ZModemDialog.cpp index afc2ea26f..36a58cd69 100644 --- a/src/ZModemDialog.cpp +++ b/src/ZModemDialog.cpp @@ -15,10 +15,10 @@ using Konsole::ZModemDialog; -ZModemDialog::ZModemDialog(QWidget *aParent, bool modal, const QString &caption) : - QDialog(aParent), - _textEdit(nullptr), - mButtonBox(nullptr) +ZModemDialog::ZModemDialog(QWidget *aParent, bool modal, const QString &caption) + : QDialog(aParent) + , _textEdit(nullptr) + , mButtonBox(nullptr) { setObjectName(QStringLiteral("zmodem_progress")); setModal(modal); diff --git a/src/ZModemDialog.h b/src/ZModemDialog.h index 8a14ca8b2..4c4b1bad0 100644 --- a/src/ZModemDialog.h +++ b/src/ZModemDialog.h @@ -11,7 +11,8 @@ class KTextEdit; class QDialogButtonBox; -namespace Konsole { +namespace Konsole +{ class ZModemDialog : public QDialog { Q_OBJECT diff --git a/src/autotests/BookMarkTest.cpp b/src/autotests/BookMarkTest.cpp index 82fd7a2e5..a27ab4050 100644 --- a/src/autotests/BookMarkTest.cpp +++ b/src/autotests/BookMarkTest.cpp @@ -17,7 +17,7 @@ using namespace Konsole; /* This does not use Konsole's BookmarkHandler directly; it is used to * test the code copied from there and to test any changes. -*/ + */ /* Test that the URL (command) does not get mangled by KBookMark's encoding */ void BookMarkTest::testBookMarkURLs_data() @@ -27,22 +27,26 @@ void BookMarkTest::testBookMarkURLs_data() auto groupUrlList = bookmarkManager->root().groupUrlList(); // text explaining test, correct test result - QStringList bm_urls = { - QStringLiteral("simple command"), QStringLiteral("ssh machine"), - QStringLiteral("command with pipe (|)"), QStringLiteral("ssh machine | tee -a /var/log/system.log"), - QStringLiteral("file URL w/ non ASCII part"), QStringLiteral("file:///home/user/aκόσμε"), - QStringLiteral("command with double quotes"), QStringLiteral("isql-fb -u sysdba -p example \"test\""), - QStringLiteral("command with single quotes"), QStringLiteral("isql-fb -u sysdba -p example 'test'"), - QStringLiteral("command with %"), QStringLiteral("date +%m-%d-%Y") - }; + QStringList bm_urls = {QStringLiteral("simple command"), + QStringLiteral("ssh machine"), + QStringLiteral("command with pipe (|)"), + QStringLiteral("ssh machine | tee -a /var/log/system.log"), + QStringLiteral("file URL w/ non ASCII part"), + QStringLiteral("file:///home/user/aκόσμε"), + QStringLiteral("command with double quotes"), + QStringLiteral("isql-fb -u sysdba -p example \"test\""), + QStringLiteral("command with single quotes"), + QStringLiteral("isql-fb -u sysdba -p example 'test'"), + QStringLiteral("command with %"), + QStringLiteral("date +%m-%d-%Y")}; QTest::addColumn("text"); QTest::addColumn("result"); for (int i = 0; i < groupUrlList.size(); ++i) { - const auto& bm_url = groupUrlList.at(i); + const auto &bm_url = groupUrlList.at(i); // Verify this line matching SessionControll.cpp to validate tests auto bm = QUrl::fromPercentEncoding(bm_url.toEncoded()); - QTest::newRow(bm_urls.at(i * 2).toUtf8().data())<< bm_urls.at((i * 2) +1) << bm; + QTest::newRow(bm_urls.at(i * 2).toUtf8().data()) << bm_urls.at((i * 2) + 1) << bm; } } diff --git a/src/autotests/BookMarkTest.h b/src/autotests/BookMarkTest.h index b0233ce33..0b344a839 100644 --- a/src/autotests/BookMarkTest.h +++ b/src/autotests/BookMarkTest.h @@ -11,7 +11,6 @@ namespace Konsole { - class BookMarkTest : public QObject { Q_OBJECT diff --git a/src/autotests/CharacterColorTest.cpp b/src/autotests/CharacterColorTest.cpp index 494750f61..0c0a82c75 100644 --- a/src/autotests/CharacterColorTest.cpp +++ b/src/autotests/CharacterColorTest.cpp @@ -14,41 +14,39 @@ using namespace Konsole; -const QColor CharacterColorTest::DefaultColorTable[TABLE_COLORS] = { - QColor(0x00, 0x00, 0x00), // Dfore - QColor(0xFF, 0xFF, 0xFF), // Dback - QColor(0x00, 0x00, 0x00), // Black - QColor(0xB2, 0x18, 0x18), // Red - QColor(0x18, 0xB2, 0x18), // Green - QColor(0xB2, 0x68, 0x18), // Yellow - QColor(0x18, 0x18, 0xB2), // Blue - QColor(0xB2, 0x18, 0xB2), // Magenta - QColor(0x18, 0xB2, 0xB2), // Cyan - QColor(0xB2, 0xB2, 0xB2), // White - // intensive versions - QColor(0x00, 0x00, 0x00), - QColor(0xFF, 0xFF, 0xFF), - QColor(0x68, 0x68, 0x68), - QColor(0xFF, 0x54, 0x54), - QColor(0x54, 0xFF, 0x54), - QColor(0xFF, 0xFF, 0x54), - QColor(0x54, 0x54, 0xFF), - QColor(0xFF, 0x54, 0xFF), - QColor(0x54, 0xFF, 0xFF), - QColor(0xFF, 0xFF, 0xFF), - // Here are faint intensities, which may not be good. - // faint versions - QColor(0x00, 0x00, 0x00), - QColor(0xFF, 0xFF, 0xFF), - QColor(0x00, 0x00, 0x00), - QColor(0x65, 0x00, 0x00), - QColor(0x00, 0x65, 0x00), - QColor(0x65, 0x5E, 0x00), - QColor(0x00, 0x00, 0x65), - QColor(0x65, 0x00, 0x65), - QColor(0x00, 0x65, 0x65), - QColor(0x65, 0x65, 0x65) -}; +const QColor CharacterColorTest::DefaultColorTable[TABLE_COLORS] = {QColor(0x00, 0x00, 0x00), // Dfore + QColor(0xFF, 0xFF, 0xFF), // Dback + QColor(0x00, 0x00, 0x00), // Black + QColor(0xB2, 0x18, 0x18), // Red + QColor(0x18, 0xB2, 0x18), // Green + QColor(0xB2, 0x68, 0x18), // Yellow + QColor(0x18, 0x18, 0xB2), // Blue + QColor(0xB2, 0x18, 0xB2), // Magenta + QColor(0x18, 0xB2, 0xB2), // Cyan + QColor(0xB2, 0xB2, 0xB2), // White + // intensive versions + QColor(0x00, 0x00, 0x00), + QColor(0xFF, 0xFF, 0xFF), + QColor(0x68, 0x68, 0x68), + QColor(0xFF, 0x54, 0x54), + QColor(0x54, 0xFF, 0x54), + QColor(0xFF, 0xFF, 0x54), + QColor(0x54, 0x54, 0xFF), + QColor(0xFF, 0x54, 0xFF), + QColor(0x54, 0xFF, 0xFF), + QColor(0xFF, 0xFF, 0xFF), + // Here are faint intensities, which may not be good. + // faint versions + QColor(0x00, 0x00, 0x00), + QColor(0xFF, 0xFF, 0xFF), + QColor(0x00, 0x00, 0x00), + QColor(0x65, 0x00, 0x00), + QColor(0x00, 0x65, 0x00), + QColor(0x65, 0x5E, 0x00), + QColor(0x00, 0x00, 0x65), + QColor(0x65, 0x00, 0x65), + QColor(0x00, 0x65, 0x65), + QColor(0x65, 0x65, 0x65)}; void CharacterColorTest::init() { @@ -62,7 +60,7 @@ void CharacterColorTest::testColorEntry() { QColor black = QColor(0x00, 0x00, 0x00); QColor white = QColor(0xFF, 0xFF, 0xFF); - QColor red = QColor(0xB2, 0x18, 0x18); + QColor red = QColor(0xB2, 0x18, 0x18); QColor green = QColor(0x18, 0xB2, 0x18); // Test operator== operator!= @@ -174,8 +172,8 @@ void CharacterColorTest::testColor256_data() const QString name = QStringLiteral("color256 color %1").arg(i); const auto u = i - 16; const auto color = QColor(((u / 36) % 6) != 0 ? (40 * ((u / 36) % 6) + 55) : 0, - ((u / 6) % 6) != 0 ? (40 * ((u / 6) % 6) + 55) : 0, - ((u / 1) % 6) != 0 ? (40 * ((u / 1) % 6) + 55) : 0); + ((u / 6) % 6) != 0 ? (40 * ((u / 6) % 6) + 55) : 0, + ((u / 1) % 6) != 0 ? (40 * ((u / 1) % 6) + 55) : 0); QTest::newRow(qPrintable(name)) << i << color; } for (int i = 232; i < 256; ++i) { diff --git a/src/autotests/CharacterColorTest.h b/src/autotests/CharacterColorTest.h index 2ab738c4d..9f25cedd1 100644 --- a/src/autotests/CharacterColorTest.h +++ b/src/autotests/CharacterColorTest.h @@ -13,7 +13,6 @@ namespace Konsole { - class CharacterColorTest : public QObject { Q_OBJECT @@ -41,4 +40,3 @@ private: } #endif // CHARACTERCOLORTEST_H - diff --git a/src/autotests/CharacterWidthTest.cpp b/src/autotests/CharacterWidthTest.cpp index 361139b8c..6b981f97c 100644 --- a/src/autotests/CharacterWidthTest.cpp +++ b/src/autotests/CharacterWidthTest.cpp @@ -53,7 +53,6 @@ void CharacterWidthTest::testWidth_data() QTest::newRow("0x2615 hot beverage (BUG 392171)") << uint(0x02615) << 2; QTest::newRow("0x26EA church (BUG 392171)") << uint(0x026EA) << 2; QTest::newRow("0x1D11E musical symbol g clef (BUG 339439)") << uint(0x1D11E) << 1; - } void CharacterWidthTest::testWidth() diff --git a/src/autotests/CharacterWidthTest.h b/src/autotests/CharacterWidthTest.h index 26c25fec7..300090835 100644 --- a/src/autotests/CharacterWidthTest.h +++ b/src/autotests/CharacterWidthTest.h @@ -11,7 +11,6 @@ namespace Konsole { - class CharacterWidthTest : public QObject { Q_OBJECT @@ -20,10 +19,8 @@ private Q_SLOTS: void testWidth_data(); void testWidth(); - }; } #endif // CHARACTERWIDTHTEST_H - diff --git a/src/autotests/DBusTest.cpp b/src/autotests/DBusTest.cpp index 8f646fdaa..92feb52e8 100644 --- a/src/autotests/DBusTest.cpp +++ b/src/autotests/DBusTest.cpp @@ -6,14 +6,14 @@ // Own #include "DBusTest.h" -#include "../session/Session.h" #include "../profile/Profile.h" #include "../profile/ProfileWriter.h" +#include "../session/Session.h" // Qt #include -#include #include +#include #include using namespace Konsole; @@ -27,8 +27,7 @@ void DBusTest::initTestCase() QDBusConnectionInterface *bus = nullptr; QStringList konsoleServices; - if (!QDBusConnection::sessionBus().isConnected() - || ((bus = QDBusConnection::sessionBus().interface()) == nullptr)) { + if (!QDBusConnection::sessionBus().isConnected() || ((bus = QDBusConnection::sessionBus().interface()) == nullptr)) { QFAIL("Session bus not found"); } @@ -37,8 +36,7 @@ void DBusTest::initTestCase() // Find all current Konsoles' services running QStringList allServices = serviceReply; - for (QStringList::const_iterator it = allServices.constBegin(), - end = allServices.constEnd(); it != end; ++it) { + for (QStringList::const_iterator it = allServices.constBegin(), end = allServices.constEnd(); it != end; ++it) { const QString service = *it; if (service.startsWith(interfaceName)) { konsoleServices << service; @@ -50,8 +48,7 @@ void DBusTest::initTestCase() auto profileWriter = new ProfileWriter(); do { - _testProfileName = QStringLiteral("konsole-dbus-test-profile-%1") - .arg(QRandomGenerator::global()->generate()); + _testProfileName = QStringLiteral("konsole-dbus-test-profile-%1").arg(QRandomGenerator::global()->generate()); profile->setProperty(Profile::UntranslatedName, _testProfileName); profile->setProperty(Profile::Name, _testProfileName); _testProfilePath = profileWriter->getPath(profile); @@ -79,8 +76,7 @@ void DBusTest::initTestCase() // Find dbus service of above Konsole allServices = serviceReply; - for (QStringList::const_iterator it = allServices.constBegin(), - end = allServices.constEnd(); it != end; ++it) { + for (QStringList::const_iterator it = allServices.constBegin(), end = allServices.constEnd(); it != end; ++it) { const QString service = *it; if (service.startsWith(interfaceName)) { if (!konsoleServices.contains(service)) { @@ -89,12 +85,9 @@ void DBusTest::initTestCase() } } - QVERIFY2(!_interfaceName.isEmpty(), - "This test will only work in a Konsole window with a new PID. A new Konsole PID can't be found."); + QVERIFY2(!_interfaceName.isEmpty(), "This test will only work in a Konsole window with a new PID. A new Konsole PID can't be found."); - QDBusInterface iface(_interfaceName, - QStringLiteral("/Windows/1"), - QStringLiteral("org.kde.konsole.Konsole")); + QDBusInterface iface(_interfaceName, QStringLiteral("/Windows/1"), QStringLiteral("org.kde.konsole.Konsole")); QVERIFY(iface.isValid()); } @@ -107,13 +100,11 @@ void DBusTest::cleanupTestCase() // Need to take care of when user has CloseAllTabs=False otherwise // they will get a popup dialog when we try to close this. - QSignalSpy quitSpy(_process, SIGNAL(finished(int,QProcess::ExitStatus))); + QSignalSpy quitSpy(_process, SIGNAL(finished(int, QProcess::ExitStatus))); // Do not use QWidget::close(), as it shows question popup when // CloseAllTabs is set to false (default). - QDBusInterface iface(_interfaceName, - QStringLiteral("/MainApplication"), - QStringLiteral("org.qtproject.Qt.QCoreApplication")); + QDBusInterface iface(_interfaceName, QStringLiteral("/MainApplication"), QStringLiteral("org.qtproject.Qt.QCoreApplication")); QVERIFY2(iface.isValid(), "Unable to get a dbus interface to Konsole!"); QDBusReply instanceReply = iface.call(QStringLiteral("quit")); @@ -133,9 +124,7 @@ void DBusTest::testSessions() QDBusReply stringReply; QDBusReply listReply; - QDBusInterface iface(_interfaceName, - QStringLiteral("/Sessions/1"), - QStringLiteral("org.kde.konsole.Session")); + QDBusInterface iface(_interfaceName, QStringLiteral("/Sessions/1"), QStringLiteral("org.kde.konsole.Session")); QVERIFY(iface.isValid()); //****************** Test is/set MonitorActivity @@ -183,8 +172,7 @@ void DBusTest::testSessions() QVERIFY(arrayReply.isValid()); // Compare result with name due to aliases issue // Better way to do this? - QCOMPARE((QTextCodec::codecForName(arrayReply.value()))->name(), - (QTextCodec::codecForName(availableCodecs[i]))->name()); + QCOMPARE((QTextCodec::codecForName(arrayReply.value()))->name(), (QTextCodec::codecForName(availableCodecs[i]))->name()); } //****************** Test is/set flowControlEnabled @@ -207,7 +195,7 @@ void DBusTest::testSessions() QVERIFY(listReply.isValid()); QStringList prevEnv = listReply.value(); - //for (int i = 0; i < prevEnv.size(); ++i) + // for (int i = 0; i < prevEnv.size(); ++i) // qDebug()<< prevEnv.at(i).toLocal8Bit().constData() << endl; voidReply = iface.call(QStringLiteral("setEnvironment"), QStringList()); @@ -275,9 +263,7 @@ void DBusTest::testWindows() int sessionCount = -1; int initialSessionId = -1; - QDBusInterface iface(_interfaceName, - QStringLiteral("/Windows/1"), - QStringLiteral("org.kde.konsole.Window")); + QDBusInterface iface(_interfaceName, QStringLiteral("/Windows/1"), QStringLiteral("org.kde.konsole.Window")); QVERIFY(iface.isValid()); intReply = iface.call(QStringLiteral("sessionCount")); @@ -309,9 +295,7 @@ void DBusTest::testWindows() newSessionId = intReply.value(); QVERIFY(newSessionId != initialSessionId); { - QDBusInterface sessionIface(_interfaceName, - QStringLiteral("/Sessions/%1").arg(newSessionId), - QStringLiteral("org.kde.konsole.Session")); + QDBusInterface sessionIface(_interfaceName, QStringLiteral("/Sessions/%1").arg(newSessionId), QStringLiteral("org.kde.konsole.Session")); QVERIFY(iface.isValid()); listReply = sessionIface.call(QStringLiteral("environment")); @@ -328,9 +312,7 @@ void DBusTest::testWindows() newSessionId = intReply.value(); QVERIFY(newSessionId != initialSessionId); { - QDBusInterface sessionIface(_interfaceName, - QStringLiteral("/Sessions/%1").arg(newSessionId), - QStringLiteral("org.kde.konsole.Session")); + QDBusInterface sessionIface(_interfaceName, QStringLiteral("/Sessions/%1").arg(newSessionId), QStringLiteral("org.kde.konsole.Session")); QVERIFY(iface.isValid()); listReply = sessionIface.call(QStringLiteral("environment")); diff --git a/src/autotests/DBusTest.h b/src/autotests/DBusTest.h index 2895e2d7a..5aa8034f4 100644 --- a/src/autotests/DBusTest.h +++ b/src/autotests/DBusTest.h @@ -7,10 +7,10 @@ #ifndef DBUSTEST_H #define DBUSTEST_H -#include -#include #include +#include #include +#include #include #include @@ -19,19 +19,17 @@ class QProcess; namespace Konsole { - class DBusTest : public QObject { Q_OBJECT public: - private Q_SLOTS: void initTestCase(); void cleanupTestCase(); void testSessions(); void testWindows(); -// protected slots are not treated as test cases + // protected slots are not treated as test cases protected Q_SLOTS: private: @@ -46,4 +44,3 @@ private: } #endif // DBUSTEST_H - diff --git a/src/autotests/HistoryTest.cpp b/src/autotests/HistoryTest.cpp index f43833927..a681da552 100644 --- a/src/autotests/HistoryTest.cpp +++ b/src/autotests/HistoryTest.cpp @@ -10,14 +10,14 @@ #include "qtest.h" // Konsole -#include "../session/Session.h" #include "../Emulation.h" -#include "../history/HistoryTypeNone.h" -#include "../history/HistoryTypeFile.h" -#include "../history/compact/CompactHistoryType.h" -#include "../history/HistoryScrollNone.h" #include "../history/HistoryScrollFile.h" +#include "../history/HistoryScrollNone.h" +#include "../history/HistoryTypeFile.h" +#include "../history/HistoryTypeNone.h" #include "../history/compact/CompactHistoryScroll.h" +#include "../history/compact/CompactHistoryType.h" +#include "../session/Session.h" using namespace Konsole; diff --git a/src/autotests/HistoryTest.h b/src/autotests/HistoryTest.h index 4a61d2847..d453e75c8 100644 --- a/src/autotests/HistoryTest.h +++ b/src/autotests/HistoryTest.h @@ -11,7 +11,6 @@ namespace Konsole { - class HistoryTest : public QObject { Q_OBJECT @@ -31,4 +30,3 @@ private: } #endif // HISTORYTEST_H - diff --git a/src/autotests/KeyboardTranslatorTest.cpp b/src/autotests/KeyboardTranslatorTest.cpp index 672aefef9..1fa6e9ec4 100644 --- a/src/autotests/KeyboardTranslatorTest.cpp +++ b/src/autotests/KeyboardTranslatorTest.cpp @@ -28,48 +28,51 @@ void KeyboardTranslatorTest::testEntryTextWildcards_data() QTest::addColumn("wildcards"); QTest::addColumn("modifiers"); - QTest::newRow("Home no wildcards no modifiers")<< QByteArray("Home") << QByteArray("Home") << false << Qt::KeyboardModifiers(Qt::NoModifier); - QTest::newRow("Home no wildcards Shift modifiers")<< QByteArray("Home") << QByteArray("Home") << false << Qt::KeyboardModifiers(Qt::ShiftModifier); - QTest::newRow("Home no wildcards Alt modifiers")<< QByteArray("Home") << QByteArray("Home") << false << Qt::KeyboardModifiers(Qt::AltModifier); - QTest::newRow("Home no wildcards Control modifiers")<< QByteArray("Home") << QByteArray("Home") << false << Qt::KeyboardModifiers(Qt::ControlModifier); + QTest::newRow("Home no wildcards no modifiers") << QByteArray("Home") << QByteArray("Home") << false << Qt::KeyboardModifiers(Qt::NoModifier); + QTest::newRow("Home no wildcards Shift modifiers") << QByteArray("Home") << QByteArray("Home") << false << Qt::KeyboardModifiers(Qt::ShiftModifier); + QTest::newRow("Home no wildcards Alt modifiers") << QByteArray("Home") << QByteArray("Home") << false << Qt::KeyboardModifiers(Qt::AltModifier); + QTest::newRow("Home no wildcards Control modifiers") << QByteArray("Home") << QByteArray("Home") << false << Qt::KeyboardModifiers(Qt::ControlModifier); - QTest::newRow("Home yes wildcards no modifiers")<< QByteArray("Home") << QByteArray("Home") << true << Qt::KeyboardModifiers(Qt::NoModifier); - QTest::newRow("Home yes wildcards Shift modifiers")<< QByteArray("Home") << QByteArray("Home") << true << Qt::KeyboardModifiers(Qt::ShiftModifier); - QTest::newRow("Home yes wildcards Alt modifiers")<< QByteArray("Home") << QByteArray("Home") << true << Qt::KeyboardModifiers(Qt::AltModifier); - QTest::newRow("Home yes wildcards Control modifiers")<< QByteArray("Home") << QByteArray("Home") << true << Qt::KeyboardModifiers(Qt::ControlModifier); + QTest::newRow("Home yes wildcards no modifiers") << QByteArray("Home") << QByteArray("Home") << true << Qt::KeyboardModifiers(Qt::NoModifier); + QTest::newRow("Home yes wildcards Shift modifiers") << QByteArray("Home") << QByteArray("Home") << true << Qt::KeyboardModifiers(Qt::ShiftModifier); + QTest::newRow("Home yes wildcards Alt modifiers") << QByteArray("Home") << QByteArray("Home") << true << Qt::KeyboardModifiers(Qt::AltModifier); + QTest::newRow("Home yes wildcards Control modifiers") << QByteArray("Home") << QByteArray("Home") << true << Qt::KeyboardModifiers(Qt::ControlModifier); // text, results: no mod, shift, alt, control QList entry; entry << QByteArray("E*") << QByteArray("E1") << QByteArray("E2") << QByteArray("E3") << QByteArray("E5"); - QTest::newRow("E* yes wildcards no modifiers")<< entry[0] << entry[1] << true << Qt::KeyboardModifiers(Qt::NoModifier); - QTest::newRow("E* yes wildcards Shift modifiers")<< entry[0] << entry[2] << true << Qt::KeyboardModifiers(Qt::ShiftModifier); - QTest::newRow("E* yes wildcards Alt modifiers")<< entry[0] << entry[3] << true << Qt::KeyboardModifiers(Qt::AltModifier); - QTest::newRow("E* yes wildcards Control modifiers")<< entry[0] << entry[4] << true << Qt::KeyboardModifiers(Qt::ControlModifier); + QTest::newRow("E* yes wildcards no modifiers") << entry[0] << entry[1] << true << Qt::KeyboardModifiers(Qt::NoModifier); + QTest::newRow("E* yes wildcards Shift modifiers") << entry[0] << entry[2] << true << Qt::KeyboardModifiers(Qt::ShiftModifier); + QTest::newRow("E* yes wildcards Alt modifiers") << entry[0] << entry[3] << true << Qt::KeyboardModifiers(Qt::AltModifier); + QTest::newRow("E* yes wildcards Control modifiers") << entry[0] << entry[4] << true << Qt::KeyboardModifiers(Qt::ControlModifier); // combinations entry.clear(); entry << QByteArray("E*") << QByteArray("E4") << QByteArray("E6") << QByteArray("E8") << QByteArray("E7"); - QTest::newRow("E* yes wildcards Shift+Alt modifiers")<< entry[0] << entry[1] << true << Qt::KeyboardModifiers(Qt::ShiftModifier | Qt::AltModifier); - QTest::newRow("E* yes wildcards Shift+Control modifiers")<< entry[0] << entry[2] << true << Qt::KeyboardModifiers(Qt::ShiftModifier | Qt::ControlModifier); - QTest::newRow("E* yes wildcards Shift+Alt+Control modifiers")<< entry[0] << entry[3] << true << Qt::KeyboardModifiers(Qt::ShiftModifier | Qt::AltModifier | Qt::ControlModifier); - QTest::newRow("E* yes wildcards Alt+Control modifiers")<< entry[0] << entry[4] << true << Qt::KeyboardModifiers(Qt::AltModifier | Qt::ControlModifier); + QTest::newRow("E* yes wildcards Shift+Alt modifiers") << entry[0] << entry[1] << true << Qt::KeyboardModifiers(Qt::ShiftModifier | Qt::AltModifier); + QTest::newRow("E* yes wildcards Shift+Control modifiers") << entry[0] << entry[2] << true << Qt::KeyboardModifiers(Qt::ShiftModifier | Qt::ControlModifier); + QTest::newRow("E* yes wildcards Shift+Alt+Control modifiers") + << entry[0] << entry[3] << true << Qt::KeyboardModifiers(Qt::ShiftModifier | Qt::AltModifier | Qt::ControlModifier); + QTest::newRow("E* yes wildcards Alt+Control modifiers") << entry[0] << entry[4] << true << Qt::KeyboardModifiers(Qt::AltModifier | Qt::ControlModifier); // text, results: no mod, shift, alt, control entry.clear(); entry << QByteArray("\033[24;*~") << QByteArray("\033[24;1~") << QByteArray("\033[24;2~") << QByteArray("\033[24;3~") << QByteArray("\033[24;5~"); - QTest::newRow("\033[24;*~ yes wildcards no modifiers")<< entry[0] << entry[1] << true << Qt::KeyboardModifiers(Qt::NoModifier); - QTest::newRow("\033[24;*~ yes wildcards Shift modifiers")<< entry[0] << entry[2] << true << Qt::KeyboardModifiers(Qt::ShiftModifier); - QTest::newRow("\033[24;*~ yes wildcards Alt modifiers")<< entry[0] << entry[3] << true << Qt::KeyboardModifiers(Qt::AltModifier); - QTest::newRow("\033[24;*~ yes wildcards Control modifiers")<< entry[0] << entry[4] << true << Qt::KeyboardModifiers(Qt::ControlModifier); + QTest::newRow("\033[24;*~ yes wildcards no modifiers") << entry[0] << entry[1] << true << Qt::KeyboardModifiers(Qt::NoModifier); + QTest::newRow("\033[24;*~ yes wildcards Shift modifiers") << entry[0] << entry[2] << true << Qt::KeyboardModifiers(Qt::ShiftModifier); + QTest::newRow("\033[24;*~ yes wildcards Alt modifiers") << entry[0] << entry[3] << true << Qt::KeyboardModifiers(Qt::AltModifier); + QTest::newRow("\033[24;*~ yes wildcards Control modifiers") << entry[0] << entry[4] << true << Qt::KeyboardModifiers(Qt::ControlModifier); // combinations entry.clear(); entry << QByteArray("\033[24;*~") << QByteArray("\033[24;4~") << QByteArray("\033[24;6~") << QByteArray("\033[24;8~") << QByteArray("\033[24;7~"); - QTest::newRow("\033[24;*~ yes wildcards Shift+Alt modifiers")<< entry[0] << entry[1] << true << Qt::KeyboardModifiers(Qt::ShiftModifier | Qt::AltModifier); - QTest::newRow("\033[24;*~ yes wildcards Shift+Control modifiers")<< entry[0] << entry[2] << true << Qt::KeyboardModifiers(Qt::ShiftModifier | Qt::ControlModifier); - QTest::newRow("\033[24;*~ yes wildcards Shift+Alt+Control modifiers")<< entry[0] << entry[3] << true << Qt::KeyboardModifiers(Qt::ShiftModifier | Qt::AltModifier | Qt::ControlModifier); - QTest::newRow("\033[24;*~ yes wildcards Alt+Control modifiers")<< entry[0] << entry[4] << true << Qt::KeyboardModifiers(Qt::AltModifier | Qt::ControlModifier); - + QTest::newRow("\033[24;*~ yes wildcards Shift+Alt modifiers") << entry[0] << entry[1] << true << Qt::KeyboardModifiers(Qt::ShiftModifier | Qt::AltModifier); + QTest::newRow("\033[24;*~ yes wildcards Shift+Control modifiers") + << entry[0] << entry[2] << true << Qt::KeyboardModifiers(Qt::ShiftModifier | Qt::ControlModifier); + QTest::newRow("\033[24;*~ yes wildcards Shift+Alt+Control modifiers") + << entry[0] << entry[3] << true << Qt::KeyboardModifiers(Qt::ShiftModifier | Qt::AltModifier | Qt::ControlModifier); + QTest::newRow("\033[24;*~ yes wildcards Alt+Control modifiers") + << entry[0] << entry[4] << true << Qt::KeyboardModifiers(Qt::AltModifier | Qt::ControlModifier); } void KeyboardTranslatorTest::testEntryTextWildcards() @@ -118,7 +121,7 @@ void KeyboardTranslatorTest::testHexKeys() QVERIFY(linuxkeytab.exists()); QVERIFY(linuxkeytab.open(QIODevice::ReadOnly)); - KeyboardTranslator* translator = new KeyboardTranslator(QStringLiteral("testtranslator")); + KeyboardTranslator *translator = new KeyboardTranslator(QStringLiteral("testtranslator")); KeyboardTranslatorReader reader(&linuxkeytab); while (reader.hasNextEntry()) { @@ -185,4 +188,3 @@ void KeyboardTranslatorTest::testHexKeys() } QTEST_GUILESS_MAIN(KeyboardTranslatorTest) - diff --git a/src/autotests/KeyboardTranslatorTest.h b/src/autotests/KeyboardTranslatorTest.h index 86e42f6b1..be295b676 100644 --- a/src/autotests/KeyboardTranslatorTest.h +++ b/src/autotests/KeyboardTranslatorTest.h @@ -12,7 +12,6 @@ namespace Konsole { - class KeyboardTranslatorTest : public QObject { Q_OBJECT @@ -27,4 +26,3 @@ private Q_SLOTS: } #endif // KEYBOARDTRANSLATORTEST_H - diff --git a/src/autotests/PartTest.cpp b/src/autotests/PartTest.cpp index 3d1a9afca..18c97fb7f 100644 --- a/src/autotests/PartTest.cpp +++ b/src/autotests/PartTest.cpp @@ -8,16 +8,16 @@ #include "PartTest.h" // Qt -#include -#include -#include -#include #include +#include +#include +#include +#include // KDE -#include #include -#include +#include #include +#include #include // Konsole @@ -92,13 +92,11 @@ void PartTest::testFd(bool runShell) // to run without shell if (runShell) { // connect to an existing pty - bool result = QMetaObject::invokeMethod(terminalPart, "openTeletype", - Qt::DirectConnection, Q_ARG(int, fd)); + bool result = QMetaObject::invokeMethod(terminalPart, "openTeletype", Qt::DirectConnection, Q_ARG(int, fd)); QVERIFY(result); } else { // test the optional 2nd argument of openTeletype, to run without shell - bool result = QMetaObject::invokeMethod(terminalPart, "openTeletype", - Qt::DirectConnection, Q_ARG(int, fd), Q_ARG(bool, false)); + bool result = QMetaObject::invokeMethod(terminalPart, "openTeletype", Qt::DirectConnection, Q_ARG(int, fd), Q_ARG(bool, false)); QVERIFY(result); } @@ -109,9 +107,8 @@ void PartTest::testFd(bool runShell) QPointer dialog = new QDialog(); auto layout = new QVBoxLayout(dialog.data()); - auto explanation = runShell - ? QStringLiteral("Output of 'ping localhost' should appear in a terminal below for 5 seconds") - : QStringLiteral("Output of 'ping localhost' should appear standalone below for 5 seconds"); + auto explanation = runShell ? QStringLiteral("Output of 'ping localhost' should appear in a terminal below for 5 seconds") + : QStringLiteral("Output of 'ping localhost' should appear standalone below for 5 seconds"); layout->addWidget(new QLabel(explanation)); layout->addWidget(terminalPart->widget()); QTimer::singleShot(5000, dialog.data(), &QDialog::close); @@ -131,7 +128,7 @@ KParts::Part *PartTest::createPart() } KPluginFactory *factory = KPluginLoader(konsolePartPlugin).factory(); - if (factory == nullptr) { // not found + if (factory == nullptr) { // not found return nullptr; } diff --git a/src/autotests/PartTest.h b/src/autotests/PartTest.h index b6b13a6e9..55c237e56 100644 --- a/src/autotests/PartTest.h +++ b/src/autotests/PartTest.h @@ -7,12 +7,11 @@ #ifndef PARTTEST_H #define PARTTEST_H -#include #include +#include namespace Konsole { - class PartTest : public QObject { Q_OBJECT @@ -24,10 +23,9 @@ private Q_SLOTS: private: void testFd(bool runShell); - KParts::Part* createPart(); + KParts::Part *createPart(); }; } #endif // PARTTEST_H - diff --git a/src/autotests/ProfileTest.cpp b/src/autotests/ProfileTest.cpp index b84fb13bb..96ec0858f 100644 --- a/src/autotests/ProfileTest.cpp +++ b/src/autotests/ProfileTest.cpp @@ -8,8 +8,8 @@ #include "ProfileTest.h" // KDE -#include #include +#include // Konsole #include "../profile/Profile.h" @@ -99,24 +99,19 @@ void ProfileTest::testClone() target->clone(source, true); // check that properties from source have been cloned into target - QCOMPARE(source->property(Profile::AntiAliasFonts), - target->property(Profile::AntiAliasFonts)); - QCOMPARE(source->property(Profile::HistorySize), - target->property(Profile::HistorySize)); + QCOMPARE(source->property(Profile::AntiAliasFonts), target->property(Profile::AntiAliasFonts)); + QCOMPARE(source->property(Profile::HistorySize), target->property(Profile::HistorySize)); // check that Name and Path properties are handled specially and not cloned - QVERIFY(source->property(Profile::Name) - != target->property(Profile::Name)); - QVERIFY(source->property(Profile::Path) - != target->property(Profile::Path)); + QVERIFY(source->property(Profile::Name) != target->property(Profile::Name)); + QVERIFY(source->property(Profile::Path) != target->property(Profile::Path)); // check that Command property is not set in target because the values // are the same QVERIFY(!target->isPropertySet(Profile::Command)); // check that ColorScheme property is cloned because the inherited values // from the source parent and target parent differ - QCOMPARE(source->property(Profile::ColorScheme), - target->property(Profile::ColorScheme)); + QCOMPARE(source->property(Profile::ColorScheme), target->property(Profile::ColorScheme)); } void ProfileTest::testProfileGroup() diff --git a/src/autotests/ProfileTest.h b/src/autotests/ProfileTest.h index 2d1f94401..adde47d0f 100644 --- a/src/autotests/ProfileTest.h +++ b/src/autotests/ProfileTest.h @@ -11,7 +11,6 @@ namespace Konsole { - class ProfileTest : public QObject { Q_OBJECT @@ -27,4 +26,3 @@ private Q_SLOTS: } #endif // PROFILETEST_H - diff --git a/src/autotests/PtyTest.cpp b/src/autotests/PtyTest.cpp index 8b6bfaa9a..684c158b2 100644 --- a/src/autotests/PtyTest.cpp +++ b/src/autotests/PtyTest.cpp @@ -12,8 +12,8 @@ #include // KDE -#include #include +#include using namespace Konsole; diff --git a/src/autotests/PtyTest.h b/src/autotests/PtyTest.h index 13ae3691b..d5946f8a2 100644 --- a/src/autotests/PtyTest.h +++ b/src/autotests/PtyTest.h @@ -11,7 +11,6 @@ namespace Konsole { - class PtyTest : public QObject { Q_OBJECT @@ -31,4 +30,3 @@ private Q_SLOTS: } #endif // PTYTEST_H - diff --git a/src/autotests/ScreenTest.cpp b/src/autotests/ScreenTest.cpp index a37fb6ffe..ab3eb9904 100644 --- a/src/autotests/ScreenTest.cpp +++ b/src/autotests/ScreenTest.cpp @@ -17,37 +17,34 @@ using namespace Konsole; void ScreenTest::doLargeScreenCopyVerification(const QString &putToScreen, const QString &expectedSelection) { - Screen screen(largeScreenLines, largeScreenColumns); + Screen screen(largeScreenLines, largeScreenColumns); - for(const auto &lineCharacter : putToScreen) { - screen.displayCharacter(lineCharacter.toLatin1()); - } + for (const auto &lineCharacter : putToScreen) { + screen.displayCharacter(lineCharacter.toLatin1()); + } - screen.setSelectionStart(0,0, false); - screen.setSelectionEnd(largeScreenColumns,0); - QCOMPARE(screen.selectedText(Screen::PlainText), expectedSelection); + screen.setSelectionStart(0, 0, false); + screen.setSelectionEnd(largeScreenColumns, 0); + QCOMPARE(screen.selectedText(Screen::PlainText), expectedSelection); } void ScreenTest::testLargeScreenCopyShortLine() { - const QString putToScreen = QStringLiteral("0123456789abcde"); - const QString expectedSelection = QStringLiteral("0123456789abcde\n"); - doLargeScreenCopyVerification(putToScreen, expectedSelection); + const QString putToScreen = QStringLiteral("0123456789abcde"); + const QString expectedSelection = QStringLiteral("0123456789abcde\n"); + doLargeScreenCopyVerification(putToScreen, expectedSelection); } void ScreenTest::testBlockSelection() { Screen screen(largeScreenLines, largeScreenColumns); - const QString reallyBigTextForReflow = QStringLiteral( - "abcd efgh ijkl mnop qrst uvxz ABCD EFGH IJKL MNOP QRST UVXZ" - ); + const QString reallyBigTextForReflow = QStringLiteral("abcd efgh ijkl mnop qrst uvxz ABCD EFGH IJKL MNOP QRST UVXZ"); - for(const auto c : reallyBigTextForReflow) { + for (const auto c : reallyBigTextForReflow) { screen.displayCharacter(c.toLatin1()); } - // this breaks the lines in `abcd efgh ` // reflowing everything to the lines below. screen.setReflowLines(true); @@ -72,23 +69,23 @@ void ScreenTest::testBlockSelection() void ScreenTest::testLargeScreenCopyEmptyLine() { - const QString putToScreen; - const QString expectedSelection = QStringLiteral("\n"); + const QString putToScreen; + const QString expectedSelection = QStringLiteral("\n"); - doLargeScreenCopyVerification(putToScreen, expectedSelection); + doLargeScreenCopyVerification(putToScreen, expectedSelection); } void ScreenTest::testLargeScreenCopyLongLine() { - QString putToScreen; + QString putToScreen; - // Make the line longer than screen size (1300 characters) - for(int i = 0; i <130; ++i) { - putToScreen.append(QStringLiteral("0123456789")); - } - const QString expectedSelection = putToScreen.left(1200); + // Make the line longer than screen size (1300 characters) + for (int i = 0; i < 130; ++i) { + putToScreen.append(QStringLiteral("0123456789")); + } + const QString expectedSelection = putToScreen.left(1200); - doLargeScreenCopyVerification(putToScreen, expectedSelection); + doLargeScreenCopyVerification(putToScreen, expectedSelection); } void ScreenTest::doComparePosition(Screen *screen, int y, int x) @@ -97,9 +94,9 @@ void ScreenTest::doComparePosition(Screen *screen, int y, int x) QCOMPARE(screen->getCursorX(), x); } -// Test: setCursorYX, setCursorX, setCursorY, cursorDown, cursorUp, +// Test: setCursorYX, setCursorX, setCursorY, cursorDown, cursorUp, // cursorRight, cursorLeft, cursorNextLine and cursorPreviousLine -void ScreenTest::testCursorPosition() +void ScreenTest::testCursorPosition() { Screen *screen = new Screen(largeScreenLines, largeScreenColumns); diff --git a/src/autotests/ScreenTest.h b/src/autotests/ScreenTest.h index c7747143c..0fab07f38 100644 --- a/src/autotests/ScreenTest.h +++ b/src/autotests/ScreenTest.h @@ -13,7 +13,6 @@ namespace Konsole { - class ScreenTest : public QObject { Q_OBJECT @@ -36,4 +35,3 @@ private: } #endif // SCREENTEST_H - diff --git a/src/autotests/SessionManagerTest.h b/src/autotests/SessionManagerTest.h index be211a5b5..8f3619b8b 100644 --- a/src/autotests/SessionManagerTest.h +++ b/src/autotests/SessionManagerTest.h @@ -9,7 +9,6 @@ namespace Konsole { - class SessionManagerTest : public QObject { Q_OBJECT @@ -24,4 +23,3 @@ private Q_SLOTS: } #endif // SESSIONMANAGERTEST_H - diff --git a/src/autotests/SessionTest.cpp b/src/autotests/SessionTest.cpp index b34295b9e..2c4bce209 100644 --- a/src/autotests/SessionTest.cpp +++ b/src/autotests/SessionTest.cpp @@ -10,8 +10,8 @@ #include "qtest.h" // Konsole -#include "../session/Session.h" #include "../Emulation.h" +#include "../session/Session.h" using namespace Konsole; diff --git a/src/autotests/SessionTest.h b/src/autotests/SessionTest.h index fa3ee1fc0..e804a3753 100644 --- a/src/autotests/SessionTest.h +++ b/src/autotests/SessionTest.h @@ -11,7 +11,6 @@ namespace Konsole { - class SessionTest : public QObject { Q_OBJECT @@ -26,4 +25,3 @@ private: } #endif // SESSIONTEST_H - diff --git a/src/autotests/ShellCommandTest.h b/src/autotests/ShellCommandTest.h index 125d2753e..61e535156 100644 --- a/src/autotests/ShellCommandTest.h +++ b/src/autotests/ShellCommandTest.h @@ -14,7 +14,6 @@ namespace Konsole { - class ShellCommandTest : public QObject { Q_OBJECT @@ -30,10 +29,8 @@ private Q_SLOTS: void testValidLeadingEnvCharacter(); void testArgumentsWithSpaces(); void testEmptyCommand(); - }; } #endif // SHELLCOMMANDTEST_H - diff --git a/src/autotests/TerminalCharacterDecoderTest.cpp b/src/autotests/TerminalCharacterDecoderTest.cpp index 6bbefc4dc..3930806a9 100644 --- a/src/autotests/TerminalCharacterDecoderTest.cpp +++ b/src/autotests/TerminalCharacterDecoderTest.cpp @@ -9,8 +9,8 @@ #include "TerminalCharacterDecoderTest.h" // Konsole -#include "../decoders/PlainTextDecoder.h" #include "../decoders/HTMLDecoder.h" +#include "../decoders/PlainTextDecoder.h" // Qt #include @@ -20,7 +20,7 @@ using namespace Konsole; -Character* TerminalCharacterDecoderTest::convertToCharacter(const QString &text, QVector renditions) +Character *TerminalCharacterDecoderTest::convertToCharacter(const QString &text, QVector renditions) { auto charResult = new Character[text.size()]; @@ -48,7 +48,7 @@ void TerminalCharacterDecoderTest::testPlainTextDecoder_data() */ QTest::newRow("simple text with default rendition") << "hello" << QVector(6).fill(DEFAULT_RENDITION) << "hello"; QTest::newRow("simple text with bold rendition") << "hello" << QVector(6).fill(RE_BOLD) << "hello"; - QTest::newRow("simple text with underline and italic rendition") << "hello" << QVector(6).fill(RE_UNDERLINE|RE_ITALIC) << "hello"; + QTest::newRow("simple text with underline and italic rendition") << "hello" << QVector(6).fill(RE_UNDERLINE | RE_ITALIC) << "hello"; QTest::newRow("simple text with default rendition (shorten)") << "hello" << QVector(4).fill(DEFAULT_RENDITION) << "hello"; QTest::newRow("simple text with underline rendition (shorten)") << "hello" << QVector(4).fill(RE_UNDERLINE) << "hello"; @@ -81,12 +81,20 @@ void TerminalCharacterDecoderTest::testHTMLDecoder_data() /* Notes: * TODO: need to add foregroundColor, backgroundColor, and isRealCharacter */ - QTest::newRow("simple text with default rendition") << "hello" << QVector(6).fill(DEFAULT_RENDITION) << R"(hello
)"; - QTest::newRow("simple text with bold rendition") << "hello" << QVector(6).fill(RE_BOLD) << R"(hello
)"; + QTest::newRow("simple text with default rendition") + << "hello" << QVector(6).fill(DEFAULT_RENDITION) + << R"(hello
)"; + QTest::newRow("simple text with bold rendition") + << "hello" << QVector(6).fill(RE_BOLD) + << R"(hello
)"; // The below is wrong; only the first rendition is used (eg ignores the |) - QTest::newRow("simple text with underline and italic rendition") << "hello" << QVector(6).fill(RE_UNDERLINE|RE_ITALIC) << R"(hello
)"; + QTest::newRow("simple text with underline and italic rendition") + << "hello" << QVector(6).fill(RE_UNDERLINE | RE_ITALIC) + << R"(hello
)"; - QTest::newRow("text with &") << "hello &there" << QVector(6).fill(DEFAULT_RENDITION) << R"(hello &there
)"; + QTest::newRow("text with &") + << "hello &there" << QVector(6).fill(DEFAULT_RENDITION) + << R"(hello &there
)"; } void TerminalCharacterDecoderTest::testHTMLDecoder() diff --git a/src/autotests/TerminalCharacterDecoderTest.h b/src/autotests/TerminalCharacterDecoderTest.h index 5ef427e18..788cf6fba 100644 --- a/src/autotests/TerminalCharacterDecoderTest.h +++ b/src/autotests/TerminalCharacterDecoderTest.h @@ -14,13 +14,12 @@ namespace Konsole { - class TerminalCharacterDecoderTest : public QObject { Q_OBJECT private Q_SLOTS: - Character* convertToCharacter(const QString &text, QVector renditions); + Character *convertToCharacter(const QString &text, QVector renditions); void testPlainTextDecoder(); void testPlainTextDecoder_data(); void testHTMLDecoder(); @@ -30,4 +29,3 @@ private Q_SLOTS: } #endif // TERMINALCHARACTERDECODERTEST_H - diff --git a/src/autotests/TerminalInterfaceTest.cpp b/src/autotests/TerminalInterfaceTest.cpp index d7c79de74..890270d90 100644 --- a/src/autotests/TerminalInterfaceTest.cpp +++ b/src/autotests/TerminalInterfaceTest.cpp @@ -11,9 +11,9 @@ #include "config-konsole.h" // Qt +#include #include #include -#include // KDE #include @@ -32,7 +32,7 @@ using namespace Konsole; * int foregroundProcessId() * QString foregroundProcessName() * QString currentWorkingDirectory() const -*/ + */ void TerminalInterfaceTest::initTestCase() { @@ -201,7 +201,7 @@ void TerminalInterfaceTest::testTerminalInterfaceV2() QFAIL("konsolepart not found."); } - TerminalInterfaceV2 *terminal = qobject_cast(_terminalPart); + TerminalInterfaceV2 *terminal = qobject_cast(_terminalPart); QVERIFY(terminal); QVERIFY(terminal->setCurrentProfile(testProfile->name())); @@ -226,7 +226,7 @@ KParts::Part *TerminalInterfaceTest::createPart() } KPluginFactory *factory = KPluginLoader(konsolePartPlugin).factory(); - if (factory == nullptr) { // not found + if (factory == nullptr) { // not found return nullptr; } diff --git a/src/autotests/TerminalInterfaceTest.h b/src/autotests/TerminalInterfaceTest.h index 6ec73f5c4..16d62cbac 100644 --- a/src/autotests/TerminalInterfaceTest.h +++ b/src/autotests/TerminalInterfaceTest.h @@ -7,18 +7,16 @@ #ifndef TERMINALINTERFACETEST_H #define TERMINALINTERFACETEST_H -#include #include +#include namespace Konsole { - class TerminalInterfaceTest : public QObject { Q_OBJECT public: - private Q_SLOTS: void initTestCase(); void testTerminalInterfaceNoShell(); @@ -26,13 +24,11 @@ private Q_SLOTS: void testTerminalInterfaceV2(); private: - KParts::Part* createPart(); - - KParts::Part* _terminalPart; + KParts::Part *createPart(); + KParts::Part *_terminalPart; }; } #endif // TERMINALINTERFACETEST_H - diff --git a/src/autotests/TerminalTest.cpp b/src/autotests/TerminalTest.cpp index 0e4c7db1c..4f13deb17 100644 --- a/src/autotests/TerminalTest.cpp +++ b/src/autotests/TerminalTest.cpp @@ -10,9 +10,9 @@ #include "qtest.h" // Konsole +#include "../terminalDisplay/TerminalColor.h" #include "../terminalDisplay/TerminalDisplay.h" #include "../terminalDisplay/TerminalScrollBar.h" -#include "../terminalDisplay/TerminalColor.h" #include "../characters/CharacterColor.h" #include "colorscheme/ColorScheme.h" @@ -37,18 +37,11 @@ void TerminalTest::testScrollBarPositions() void TerminalTest::testColorTable() { // These are from ColorScheme.cpp but they can be anything to test - const QColor defaultTable[TABLE_COLORS] = { - QColor(0x00, 0x00, 0x00), QColor(0xFF, 0xFF, 0xFF), - QColor(0x00, 0x00, 0x00), QColor(0xB2, 0x18, 0x18), - QColor(0x18, 0xB2, 0x18), QColor(0xB2, 0x68, 0x18), - QColor(0x18, 0x18, 0xB2), QColor(0xB2, 0x18, 0xB2), - QColor(0x18, 0xB2, 0xB2), QColor(0xB2, 0xB2, 0xB2), - QColor(0x00, 0x00, 0x00), QColor(0xFF, 0xFF, 0xFF), - QColor(0x68, 0x68, 0x68), QColor(0xFF, 0x54, 0x54), - QColor(0x54, 0xFF, 0x54), QColor(0xFF, 0xFF, 0x54), - QColor(0x54, 0x54, 0xFF), QColor(0xFF, 0x54, 0xFF), - QColor(0x54, 0xFF, 0xFF), QColor(0x00, 0xFF, 0xFF) - }; + const QColor defaultTable[TABLE_COLORS] = {QColor(0x00, 0x00, 0x00), QColor(0xFF, 0xFF, 0xFF), QColor(0x00, 0x00, 0x00), QColor(0xB2, 0x18, 0x18), + QColor(0x18, 0xB2, 0x18), QColor(0xB2, 0x68, 0x18), QColor(0x18, 0x18, 0xB2), QColor(0xB2, 0x18, 0xB2), + QColor(0x18, 0xB2, 0xB2), QColor(0xB2, 0xB2, 0xB2), QColor(0x00, 0x00, 0x00), QColor(0xFF, 0xFF, 0xFF), + QColor(0x68, 0x68, 0x68), QColor(0xFF, 0x54, 0x54), QColor(0x54, 0xFF, 0x54), QColor(0xFF, 0xFF, 0x54), + QColor(0x54, 0x54, 0xFF), QColor(0xFF, 0x54, 0xFF), QColor(0x54, 0xFF, 0xFF), QColor(0x00, 0xFF, 0xFF)}; auto display = new TerminalDisplay(nullptr); @@ -74,7 +67,7 @@ void TerminalTest::testSize() QCOMPARE(display->lines(), 1); // TODO: setSize doesn't change size... - //display->setSize(80, 25); + // display->setSize(80, 25); delete display; } diff --git a/src/autotests/TerminalTest.h b/src/autotests/TerminalTest.h index 10266f5ec..410bab70a 100644 --- a/src/autotests/TerminalTest.h +++ b/src/autotests/TerminalTest.h @@ -11,7 +11,6 @@ namespace Konsole { - class TerminalTest : public QObject { Q_OBJECT @@ -27,4 +26,3 @@ private: } #endif // TERMINALTEST_H - diff --git a/src/autotests/Vt102EmulationTest.cpp b/src/autotests/Vt102EmulationTest.cpp index e04be024c..14ed14d0c 100644 --- a/src/autotests/Vt102EmulationTest.cpp +++ b/src/autotests/Vt102EmulationTest.cpp @@ -11,18 +11,18 @@ // The below is to verify the old #defines match the new constexprs // Just copy/paste for now from Vt102Emulation.cpp -#define TY_CONSTRUCT(T,A,N) ( ((((int)(N)) & 0xffff) << 16) | ((((int)(A)) & 0xff) << 8) | (((int)(T)) & 0xff) ) -#define TY_CHR( ) TY_CONSTRUCT(0,0,0) -#define TY_CTL(A ) TY_CONSTRUCT(1,A,0) -#define TY_ESC(A ) TY_CONSTRUCT(2,A,0) -#define TY_ESC_CS(A,B) TY_CONSTRUCT(3,A,B) -#define TY_ESC_DE(A ) TY_CONSTRUCT(4,A,0) -#define TY_CSI_PS(A,N) TY_CONSTRUCT(5,A,N) -#define TY_CSI_PN(A ) TY_CONSTRUCT(6,A,0) -#define TY_CSI_PR(A,N) TY_CONSTRUCT(7,A,N) -#define TY_VT52(A) TY_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_CONSTRUCT(T, A, N) (((((int)(N)) & 0xffff) << 16) | ((((int)(A)) & 0xff) << 8) | (((int)(T)) & 0xff)) +#define TY_CHR() TY_CONSTRUCT(0, 0, 0) +#define TY_CTL(A) TY_CONSTRUCT(1, A, 0) +#define TY_ESC(A) TY_CONSTRUCT(2, A, 0) +#define TY_ESC_CS(A, B) TY_CONSTRUCT(3, A, B) +#define TY_ESC_DE(A) TY_CONSTRUCT(4, A, 0) +#define TY_CSI_PS(A, N) TY_CONSTRUCT(5, A, N) +#define TY_CSI_PN(A) TY_CONSTRUCT(6, A, 0) +#define TY_CSI_PR(A, N) TY_CONSTRUCT(7, A, N) +#define TY_VT52(A) TY_CONSTRUCT(8, A, 0) +#define TY_CSI_PG(A) TY_CONSTRUCT(9, A, 0) +#define TY_CSI_PE(A) TY_CONSTRUCT(10, A, 0) using namespace Konsole; @@ -75,12 +75,7 @@ constexpr int token_csi_pe(int a) return token_construct(10, a, 0); } -void Vt102EmulationTest::sendAndCompare(TestEmulation *em, - const char *input, - size_t inputLen, - const QString &expectedPrint, - const QByteArray &expectedSent - ) +void Vt102EmulationTest::sendAndCompare(TestEmulation *em, const char *input, size_t inputLen, const QString &expectedPrint, const QByteArray &expectedSent) { em->_currentScreen->clearEntireScreen(); @@ -99,9 +94,7 @@ void Vt102EmulationTest::testParse() sendAndCompare(&em, "a", 1, QStringLiteral("a"), ""); - const char tertiaryDeviceAttributes[] = { - 0x1b, '[', '=', '0', 'c' - }; + const char tertiaryDeviceAttributes[] = {0x1b, '[', '=', '0', 'c'}; QEXPECT_FAIL("", "Fixed by https://invent.kde.org/utilities/konsole/-/merge_requests/416", Abort); sendAndCompare(&em, tertiaryDeviceAttributes, sizeof tertiaryDeviceAttributes, QStringLiteral(""), "\033P!|00000000\033\\"); } @@ -110,7 +103,7 @@ void Vt102EmulationTest::testTokenFunctions() { QCOMPARE(token_construct(0, 0, 0), TY_CONSTRUCT(0, 0, 0)); QCOMPARE(token_chr(), TY_CHR()); - QCOMPARE(token_ctl(8+'@'), TY_CTL(8+'@')); + QCOMPARE(token_ctl(8 + '@'), TY_CTL(8 + '@')); QCOMPARE(token_ctl('G'), TY_CTL('G')); QCOMPARE(token_csi_pe('p'), TY_CSI_PE('p')); QCOMPARE(token_csi_pg('c'), TY_CSI_PG('c')); diff --git a/src/autotests/Vt102EmulationTest.h b/src/autotests/Vt102EmulationTest.h index a5b9abfef..9e9729a63 100644 --- a/src/autotests/Vt102EmulationTest.h +++ b/src/autotests/Vt102EmulationTest.h @@ -13,7 +13,6 @@ namespace Konsole { - class TestEmulation; class Vt102EmulationTest : public QObject @@ -26,22 +25,19 @@ private Q_SLOTS: void testParse(); private: - static void sendAndCompare(TestEmulation *em, - const char *input, size_t inputLen, - const QString &expectedPrint, - const QByteArray &expectedSent - ); + static void sendAndCompare(TestEmulation *em, const char *input, size_t inputLen, const QString &expectedPrint, const QByteArray &expectedSent); }; -struct TestEmulation : public Vt102Emulation -{ +struct TestEmulation : public Vt102Emulation { Q_OBJECT // Give us access to protected functions friend class Vt102EmulationTest; QByteArray lastSent; + public: - void sendString(const QByteArray &string) override { + void sendString(const QByteArray &string) override + { lastSent = string; Vt102Emulation::sendString(string); } @@ -50,4 +46,3 @@ public: } #endif // VT102EMULATIONTEST_H - diff --git a/src/characters/Character.h b/src/characters/Character.h index 69953ec6e..31c754258 100644 --- a/src/characters/Character.h +++ b/src/characters/Character.h @@ -15,29 +15,30 @@ // Qt #include -namespace Konsole { +namespace Konsole +{ typedef unsigned char LineProperty; typedef quint16 RenditionFlags; -const int LINE_DEFAULT = 0; -const int LINE_WRAPPED = (1 << 0); -const int LINE_DOUBLEWIDTH = (1 << 1); -const int LINE_DOUBLEHEIGHT_TOP = (1 << 2); +const int LINE_DEFAULT = 0; +const int LINE_WRAPPED = (1 << 0); +const int LINE_DOUBLEWIDTH = (1 << 1); +const int LINE_DOUBLEHEIGHT_TOP = (1 << 2); const int LINE_DOUBLEHEIGHT_BOTTOM = (1 << 3); const RenditionFlags DEFAULT_RENDITION = 0; -const RenditionFlags RE_BOLD = (1 << 0); -const RenditionFlags RE_BLINK = (1 << 1); -const RenditionFlags RE_UNDERLINE = (1 << 2); -const RenditionFlags RE_REVERSE = (1 << 3); // Screen only -const RenditionFlags RE_ITALIC = (1 << 4); -const RenditionFlags RE_CURSOR = (1 << 5); -const RenditionFlags RE_EXTENDED_CHAR = (1 << 6); -const RenditionFlags RE_FAINT = (1 << 7); -const RenditionFlags RE_STRIKEOUT = (1 << 8); -const RenditionFlags RE_CONCEAL = (1 << 9); -const RenditionFlags RE_OVERLINE = (1 << 10); +const RenditionFlags RE_BOLD = (1 << 0); +const RenditionFlags RE_BLINK = (1 << 1); +const RenditionFlags RE_UNDERLINE = (1 << 2); +const RenditionFlags RE_REVERSE = (1 << 3); // Screen only +const RenditionFlags RE_ITALIC = (1 << 4); +const RenditionFlags RE_CURSOR = (1 << 5); +const RenditionFlags RE_EXTENDED_CHAR = (1 << 6); +const RenditionFlags RE_FAINT = (1 << 7); +const RenditionFlags RE_STRIKEOUT = (1 << 8); +const RenditionFlags RE_CONCEAL = (1 << 9); +const RenditionFlags RE_OVERLINE = (1 << 10); const RenditionFlags RE_BLEND_SELECTION_COLORS = (1 << 11); /** @@ -60,15 +61,17 @@ public: * simply as place holder. */ explicit inline Character(uint _c = ' ', - CharacterColor _f = CharacterColor(COLOR_SPACE_DEFAULT, DEFAULT_FORE_COLOR), - CharacterColor _b = CharacterColor(COLOR_SPACE_DEFAULT, DEFAULT_BACK_COLOR), - RenditionFlags _r = DEFAULT_RENDITION, + CharacterColor _f = CharacterColor(COLOR_SPACE_DEFAULT, DEFAULT_FORE_COLOR), + CharacterColor _b = CharacterColor(COLOR_SPACE_DEFAULT, DEFAULT_BACK_COLOR), + RenditionFlags _r = DEFAULT_RENDITION, bool _real = true) : character(_c) , rendition(_r) , foregroundColor(_f) , backgroundColor(_b) - , isRealCharacter(_real) { } + , isRealCharacter(_real) + { + } /** The unicode character value for this character. * @@ -107,13 +110,13 @@ public: * Compares two characters and returns true if they have the same unicode character value, * rendition and colors. */ - friend bool operator ==(const Character &a, const Character &b); + friend bool operator==(const Character &a, const Character &b); /** * Compares two characters and returns true if they have different unicode character values, * renditions or colors. */ - friend bool operator !=(const Character &a, const Character &b); + friend bool operator!=(const Character &a, const Character &b); inline bool isSpace() const { @@ -124,15 +127,18 @@ public: } } - inline int width() const { + inline int width() const + { return width(character); } - static int width(uint ucs4) { + static int width(uint ucs4) + { return characterWidth(ucs4); } - static int stringWidth(const uint *ucs4Str, int len) { + static int stringWidth(const uint *ucs4Str, int len) + { int w = 0; for (int i = 0; i < len; ++i) { w += width(ucs4Str[i]); @@ -140,27 +146,26 @@ public: return w; } - inline static int stringWidth(const QString &str) { + inline static int stringWidth(const QString &str) + { QVector ucs4Str = str.toUcs4(); return stringWidth(ucs4Str.constData(), ucs4Str.length()); } }; -inline bool operator ==(const Character &a, const Character &b) +inline bool operator==(const Character &a, const Character &b) { return a.character == b.character && a.equalsFormat(b); } -inline bool operator !=(const Character &a, const Character &b) +inline bool operator!=(const Character &a, const Character &b) { return !operator==(a, b); } inline bool Character::equalsFormat(const Character &other) const { - return backgroundColor == other.backgroundColor - && foregroundColor == other.foregroundColor - && rendition == other.rendition; + return backgroundColor == other.backgroundColor && foregroundColor == other.foregroundColor && rendition == other.rendition; } } Q_DECLARE_TYPEINFO(Konsole::Character, Q_MOVABLE_TYPE); diff --git a/src/characters/CharacterColor.h b/src/characters/CharacterColor.h index 5d0364461..cfce76574 100644 --- a/src/characters/CharacterColor.h +++ b/src/characters/CharacterColor.h @@ -11,15 +11,15 @@ // Qt #include -namespace Konsole { - +namespace Konsole +{ // Attributed Character Representations /////////////////////////////// // Colors -#define BASE_COLORS (2+8) -#define INTENSITIES 3 -#define TABLE_COLORS (INTENSITIES*BASE_COLORS) +#define BASE_COLORS (2 + 8) +#define INTENSITIES 3 +#define TABLE_COLORS (INTENSITIES * BASE_COLORS) enum ColorTableIndex { ColorFgIndex, @@ -77,11 +77,11 @@ enum ColorTableIndex { default foreground and default background color. */ -#define COLOR_SPACE_UNDEFINED 0 -#define COLOR_SPACE_DEFAULT 1 -#define COLOR_SPACE_SYSTEM 2 -#define COLOR_SPACE_256 3 -#define COLOR_SPACE_RGB 4 +#define COLOR_SPACE_UNDEFINED 0 +#define COLOR_SPACE_DEFAULT 1 +#define COLOR_SPACE_SYSTEM 2 +#define COLOR_SPACE_256 3 +#define COLOR_SPACE_RGB 4 /** * Describes the color of a single character in the terminal. @@ -92,11 +92,11 @@ class CharacterColor public: /** Constructs a new CharacterColor whose color and color space are undefined. */ - CharacterColor() : - _colorSpace(COLOR_SPACE_UNDEFINED), - _u(0), - _v(0), - _w(0) + CharacterColor() + : _colorSpace(COLOR_SPACE_UNDEFINED) + , _u(0) + , _v(0) + , _w(0) { } @@ -110,11 +110,11 @@ public: * * TODO : Add documentation about available color spaces. */ - CharacterColor(quint8 colorSpace, int co) : - _colorSpace(colorSpace), - _u(0), - _v(0), - _w(0) + CharacterColor(quint8 colorSpace, int co) + : _colorSpace(colorSpace) + , _u(0) + , _v(0) + , _w(0) { switch (colorSpace) { case COLOR_SPACE_DEFAULT: @@ -137,8 +137,16 @@ public: } } - quint8 colorSpace() const { return _colorSpace; } - void termColor(int *u, int *v, int *w) { *u = _u; *v = _v; *w = _w; } + quint8 colorSpace() const + { + return _colorSpace; + } + void termColor(int *u, int *v, int *w) + { + *u = _u; + *v = _v; + *w = _w; + } /** * Returns true if this character color entry is valid. @@ -176,12 +184,12 @@ public: * Compares two colors and returns true if they represent the same color value and * use the same color space. */ - friend bool operator ==(const CharacterColor &a, const CharacterColor &b); + friend bool operator==(const CharacterColor &a, const CharacterColor &b); /** * Compares two colors and returns true if they represent different color values * or use different color spaces. */ - friend bool operator !=(const CharacterColor &a, const CharacterColor &b); + friend bool operator!=(const CharacterColor &a, const CharacterColor &b); private: quint8 _colorSpace; @@ -192,15 +200,12 @@ private: quint8 _w; }; -inline bool operator ==(const CharacterColor &a, const CharacterColor &b) +inline bool operator==(const CharacterColor &a, const CharacterColor &b) { - return a._colorSpace == b._colorSpace - && a._u == b._u - && a._v == b._v - && a._w == b._w; + 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) +inline bool operator!=(const CharacterColor &a, const CharacterColor &b) { return !operator==(a, b); } diff --git a/src/characters/CharacterFormat.cpp b/src/characters/CharacterFormat.cpp index fb5fcb4af..bc3202a9e 100644 --- a/src/characters/CharacterFormat.cpp +++ b/src/characters/CharacterFormat.cpp @@ -10,14 +10,12 @@ using namespace Konsole; bool CharacterFormat::equalsFormat(const CharacterFormat &other) const { - return (other.rendition & ~RE_EXTENDED_CHAR) == (rendition & ~RE_EXTENDED_CHAR) - && other.fgColor == fgColor && other.bgColor == bgColor; + return (other.rendition & ~RE_EXTENDED_CHAR) == (rendition & ~RE_EXTENDED_CHAR) && other.fgColor == fgColor && other.bgColor == bgColor; } bool CharacterFormat::equalsFormat(const Character &c) const { - return (c.rendition & ~RE_EXTENDED_CHAR) == (rendition & ~RE_EXTENDED_CHAR) - && c.foregroundColor == fgColor && c.backgroundColor == bgColor; + return (c.rendition & ~RE_EXTENDED_CHAR) == (rendition & ~RE_EXTENDED_CHAR) && c.foregroundColor == fgColor && c.backgroundColor == bgColor; } void CharacterFormat::setFormat(const Character &c) diff --git a/src/characters/CharacterFormat.h b/src/characters/CharacterFormat.h index d89884f12..2e5ce40f8 100644 --- a/src/characters/CharacterFormat.h +++ b/src/characters/CharacterFormat.h @@ -11,7 +11,6 @@ namespace Konsole { - class CharacterFormat { public: diff --git a/src/characters/CharacterWidth.cpp b/src/characters/CharacterWidth.cpp index 84d868325..2fc2a9be9 100644 --- a/src/characters/CharacterWidth.cpp +++ b/src/characters/CharacterWidth.cpp @@ -15,20 +15,21 @@ // To change anything here, edit CharacterWidth.src.cpp and regenerate the file // using following command: // -// uni2characterwidth -U "https://unicode.org/Public/13.0.0/ucd/UnicodeData.txt" -A "https://unicode.org/Public/13.0.0/ucd/EastAsianWidth.txt" -E "https://unicode.org/Public/13.0.0/ucd/emoji/emoji-data.txt" -W "tools/uni2characterwidth/overrides.txt" --ambiguous-width=1 --emoji=presentation -g "code:src/characters/CharacterWidth.src.cpp" "src/characters/CharacterWidth.cpp" +// uni2characterwidth -U "https://unicode.org/Public/13.0.0/ucd/UnicodeData.txt" -A "https://unicode.org/Public/13.0.0/ucd/EastAsianWidth.txt" -E +// "https://unicode.org/Public/13.0.0/ucd/emoji/emoji-data.txt" -W "tools/uni2characterwidth/overrides.txt" --ambiguous-width=1 --emoji=presentation -g +// "code:src/characters/CharacterWidth.src.cpp" "src/characters/CharacterWidth.cpp" // #include "CharacterWidth.h" #include "konsolecharacters_export.h" - struct Range { uint first, last; }; struct RangeLut { int8_t width; - const Range * const lut; + const Range *const lut; int size; }; @@ -36,110 +37,114 @@ enum { InvalidWidth = INT8_MIN, }; - static constexpr const int8_t DIRECT_LUT[] = { - 0,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,-1, - -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, }; - static constexpr const Range LUT_NONPRINTABLE[] = { - {0x00d800,0x00dfff}, + {0x00d800, 0x00dfff}, }; static constexpr const Range LUT_2[] = { - {0x001100,0x00115f},{0x00231a,0x00231b},{0x002329,0x00232a},{0x0023e9,0x0023ec},{0x0023f0,0x0023f0},{0x0023f3,0x0023f3},{0x0025fd,0x0025fe},{0x002614,0x002615}, - {0x002648,0x002653},{0x00267f,0x00267f},{0x002693,0x002693},{0x0026a1,0x0026a1},{0x0026aa,0x0026ab},{0x0026bd,0x0026be},{0x0026c4,0x0026c5},{0x0026ce,0x0026ce}, - {0x0026d4,0x0026d4},{0x0026ea,0x0026ea},{0x0026f2,0x0026f3},{0x0026f5,0x0026f5},{0x0026fa,0x0026fa},{0x0026fd,0x0026fd},{0x002705,0x002705},{0x00270a,0x00270b}, - {0x002728,0x002728},{0x00274c,0x00274c},{0x00274e,0x00274e},{0x002753,0x002755},{0x002757,0x002757},{0x002795,0x002797},{0x0027b0,0x0027b0},{0x0027bf,0x0027bf}, - {0x002b1b,0x002b1c},{0x002b50,0x002b50},{0x002b55,0x002b55},{0x002e80,0x002e99},{0x002e9b,0x002ef3},{0x002f00,0x002fd5},{0x002ff0,0x002ffb},{0x003000,0x003029}, - {0x00302e,0x00303e},{0x003041,0x003096},{0x00309b,0x0030ff},{0x003105,0x00312f},{0x003131,0x00318e},{0x003190,0x0031e3},{0x0031f0,0x00321e},{0x003220,0x003247}, - {0x003250,0x004dbf},{0x004e00,0x00a48c},{0x00a490,0x00a4c6},{0x00a960,0x00a97c},{0x00ac00,0x00d7a3},{0x00f900,0x00faff},{0x00fe10,0x00fe19},{0x00fe30,0x00fe52}, - {0x00fe54,0x00fe66},{0x00fe68,0x00fe6b},{0x00ff01,0x00ff60},{0x00ffe0,0x00ffe6},{0x016fe0,0x016fe3},{0x016ff0,0x016ff1},{0x017000,0x0187f7},{0x018800,0x018cd5}, - {0x018d00,0x018d08},{0x01b000,0x01b11e},{0x01b150,0x01b152},{0x01b164,0x01b167},{0x01b170,0x01b2fb},{0x01f004,0x01f004},{0x01f0cf,0x01f0cf},{0x01f18e,0x01f18e}, - {0x01f191,0x01f19a},{0x01f1e6,0x01f202},{0x01f210,0x01f23b},{0x01f240,0x01f248},{0x01f250,0x01f251},{0x01f260,0x01f265},{0x01f300,0x01f320},{0x01f32d,0x01f335}, - {0x01f337,0x01f37c},{0x01f37e,0x01f393},{0x01f3a0,0x01f3ca},{0x01f3cf,0x01f3d3},{0x01f3e0,0x01f3f0},{0x01f3f4,0x01f3f4},{0x01f3f8,0x01f43e},{0x01f440,0x01f440}, - {0x01f442,0x01f4fc},{0x01f4ff,0x01f53d},{0x01f54b,0x01f54e},{0x01f550,0x01f567},{0x01f57a,0x01f57a},{0x01f595,0x01f596},{0x01f5a4,0x01f5a4},{0x01f5fb,0x01f64f}, - {0x01f680,0x01f6c5},{0x01f6cc,0x01f6cc},{0x01f6d0,0x01f6d2},{0x01f6d5,0x01f6d7},{0x01f6eb,0x01f6ec},{0x01f6f4,0x01f6fc},{0x01f7e0,0x01f7eb},{0x01f90c,0x01f93a}, - {0x01f93c,0x01f945},{0x01f947,0x01f978},{0x01f97a,0x01f9cb},{0x01f9cd,0x01f9ff},{0x01fa70,0x01fa74},{0x01fa78,0x01fa7a},{0x01fa80,0x01fa86},{0x01fa90,0x01faa8}, - {0x01fab0,0x01fab6},{0x01fac0,0x01fac2},{0x01fad0,0x01fad6},{0x020000,0x02fffd},{0x030000,0x03fffd}, + {0x001100, 0x00115f}, {0x00231a, 0x00231b}, {0x002329, 0x00232a}, {0x0023e9, 0x0023ec}, {0x0023f0, 0x0023f0}, {0x0023f3, 0x0023f3}, {0x0025fd, 0x0025fe}, + {0x002614, 0x002615}, {0x002648, 0x002653}, {0x00267f, 0x00267f}, {0x002693, 0x002693}, {0x0026a1, 0x0026a1}, {0x0026aa, 0x0026ab}, {0x0026bd, 0x0026be}, + {0x0026c4, 0x0026c5}, {0x0026ce, 0x0026ce}, {0x0026d4, 0x0026d4}, {0x0026ea, 0x0026ea}, {0x0026f2, 0x0026f3}, {0x0026f5, 0x0026f5}, {0x0026fa, 0x0026fa}, + {0x0026fd, 0x0026fd}, {0x002705, 0x002705}, {0x00270a, 0x00270b}, {0x002728, 0x002728}, {0x00274c, 0x00274c}, {0x00274e, 0x00274e}, {0x002753, 0x002755}, + {0x002757, 0x002757}, {0x002795, 0x002797}, {0x0027b0, 0x0027b0}, {0x0027bf, 0x0027bf}, {0x002b1b, 0x002b1c}, {0x002b50, 0x002b50}, {0x002b55, 0x002b55}, + {0x002e80, 0x002e99}, {0x002e9b, 0x002ef3}, {0x002f00, 0x002fd5}, {0x002ff0, 0x002ffb}, {0x003000, 0x003029}, {0x00302e, 0x00303e}, {0x003041, 0x003096}, + {0x00309b, 0x0030ff}, {0x003105, 0x00312f}, {0x003131, 0x00318e}, {0x003190, 0x0031e3}, {0x0031f0, 0x00321e}, {0x003220, 0x003247}, {0x003250, 0x004dbf}, + {0x004e00, 0x00a48c}, {0x00a490, 0x00a4c6}, {0x00a960, 0x00a97c}, {0x00ac00, 0x00d7a3}, {0x00f900, 0x00faff}, {0x00fe10, 0x00fe19}, {0x00fe30, 0x00fe52}, + {0x00fe54, 0x00fe66}, {0x00fe68, 0x00fe6b}, {0x00ff01, 0x00ff60}, {0x00ffe0, 0x00ffe6}, {0x016fe0, 0x016fe3}, {0x016ff0, 0x016ff1}, {0x017000, 0x0187f7}, + {0x018800, 0x018cd5}, {0x018d00, 0x018d08}, {0x01b000, 0x01b11e}, {0x01b150, 0x01b152}, {0x01b164, 0x01b167}, {0x01b170, 0x01b2fb}, {0x01f004, 0x01f004}, + {0x01f0cf, 0x01f0cf}, {0x01f18e, 0x01f18e}, {0x01f191, 0x01f19a}, {0x01f1e6, 0x01f202}, {0x01f210, 0x01f23b}, {0x01f240, 0x01f248}, {0x01f250, 0x01f251}, + {0x01f260, 0x01f265}, {0x01f300, 0x01f320}, {0x01f32d, 0x01f335}, {0x01f337, 0x01f37c}, {0x01f37e, 0x01f393}, {0x01f3a0, 0x01f3ca}, {0x01f3cf, 0x01f3d3}, + {0x01f3e0, 0x01f3f0}, {0x01f3f4, 0x01f3f4}, {0x01f3f8, 0x01f43e}, {0x01f440, 0x01f440}, {0x01f442, 0x01f4fc}, {0x01f4ff, 0x01f53d}, {0x01f54b, 0x01f54e}, + {0x01f550, 0x01f567}, {0x01f57a, 0x01f57a}, {0x01f595, 0x01f596}, {0x01f5a4, 0x01f5a4}, {0x01f5fb, 0x01f64f}, {0x01f680, 0x01f6c5}, {0x01f6cc, 0x01f6cc}, + {0x01f6d0, 0x01f6d2}, {0x01f6d5, 0x01f6d7}, {0x01f6eb, 0x01f6ec}, {0x01f6f4, 0x01f6fc}, {0x01f7e0, 0x01f7eb}, {0x01f90c, 0x01f93a}, {0x01f93c, 0x01f945}, + {0x01f947, 0x01f978}, {0x01f97a, 0x01f9cb}, {0x01f9cd, 0x01f9ff}, {0x01fa70, 0x01fa74}, {0x01fa78, 0x01fa7a}, {0x01fa80, 0x01fa86}, {0x01fa90, 0x01faa8}, + {0x01fab0, 0x01fab6}, {0x01fac0, 0x01fac2}, {0x01fad0, 0x01fad6}, {0x020000, 0x02fffd}, {0x030000, 0x03fffd}, }; static constexpr const Range LUT_0[] = { - {0x000300,0x00036f},{0x000483,0x000489},{0x000591,0x0005bd},{0x0005bf,0x0005bf},{0x0005c1,0x0005c2},{0x0005c4,0x0005c5},{0x0005c7,0x0005c7},{0x000600,0x000605}, - {0x000610,0x00061a},{0x00061c,0x00061c},{0x00064b,0x00065f},{0x000670,0x000670},{0x0006d6,0x0006dd},{0x0006df,0x0006e4},{0x0006e7,0x0006e8},{0x0006ea,0x0006ed}, - {0x00070f,0x00070f},{0x000711,0x000711},{0x000730,0x00074a},{0x0007a6,0x0007b0},{0x0007eb,0x0007f3},{0x0007fd,0x0007fd},{0x000816,0x000819},{0x00081b,0x000823}, - {0x000825,0x000827},{0x000829,0x00082d},{0x000859,0x00085b},{0x0008d3,0x000902},{0x00093a,0x00093a},{0x00093c,0x00093c},{0x000941,0x000948},{0x00094d,0x00094d}, - {0x000951,0x000957},{0x000962,0x000963},{0x000981,0x000981},{0x0009bc,0x0009bc},{0x0009c1,0x0009c4},{0x0009cd,0x0009cd},{0x0009e2,0x0009e3},{0x0009fe,0x0009fe}, - {0x000a01,0x000a02},{0x000a3c,0x000a3c},{0x000a41,0x000a42},{0x000a47,0x000a48},{0x000a4b,0x000a4d},{0x000a51,0x000a51},{0x000a70,0x000a71},{0x000a75,0x000a75}, - {0x000a81,0x000a82},{0x000abc,0x000abc},{0x000ac1,0x000ac5},{0x000ac7,0x000ac8},{0x000acd,0x000acd},{0x000ae2,0x000ae3},{0x000afa,0x000aff},{0x000b01,0x000b01}, - {0x000b3c,0x000b3c},{0x000b3f,0x000b3f},{0x000b41,0x000b44},{0x000b4d,0x000b4d},{0x000b55,0x000b56},{0x000b62,0x000b63},{0x000b82,0x000b82},{0x000bc0,0x000bc0}, - {0x000bcd,0x000bcd},{0x000c00,0x000c00},{0x000c04,0x000c04},{0x000c3e,0x000c40},{0x000c46,0x000c48},{0x000c4a,0x000c4d},{0x000c55,0x000c56},{0x000c62,0x000c63}, - {0x000c81,0x000c81},{0x000cbc,0x000cbc},{0x000cbf,0x000cbf},{0x000cc6,0x000cc6},{0x000ccc,0x000ccd},{0x000ce2,0x000ce3},{0x000d00,0x000d01},{0x000d3b,0x000d3c}, - {0x000d41,0x000d44},{0x000d4d,0x000d4d},{0x000d62,0x000d63},{0x000d81,0x000d81},{0x000dca,0x000dca},{0x000dd2,0x000dd4},{0x000dd6,0x000dd6},{0x000e31,0x000e31}, - {0x000e34,0x000e3a},{0x000e47,0x000e4e},{0x000eb1,0x000eb1},{0x000eb4,0x000ebc},{0x000ec8,0x000ecd},{0x000f18,0x000f19},{0x000f35,0x000f35},{0x000f37,0x000f37}, - {0x000f39,0x000f39},{0x000f71,0x000f7e},{0x000f80,0x000f84},{0x000f86,0x000f87},{0x000f8d,0x000f97},{0x000f99,0x000fbc},{0x000fc6,0x000fc6},{0x00102d,0x001030}, - {0x001032,0x001037},{0x001039,0x00103a},{0x00103d,0x00103e},{0x001058,0x001059},{0x00105e,0x001060},{0x001071,0x001074},{0x001082,0x001082},{0x001085,0x001086}, - {0x00108d,0x00108d},{0x00109d,0x00109d},{0x001160,0x001160},{0x00135d,0x00135f},{0x001712,0x001714},{0x001732,0x001734},{0x001752,0x001753},{0x001772,0x001773}, - {0x0017b4,0x0017b5},{0x0017b7,0x0017bd},{0x0017c6,0x0017c6},{0x0017c9,0x0017d3},{0x0017dd,0x0017dd},{0x00180b,0x00180e},{0x001885,0x001886},{0x0018a9,0x0018a9}, - {0x001920,0x001922},{0x001927,0x001928},{0x001932,0x001932},{0x001939,0x00193b},{0x001a17,0x001a18},{0x001a1b,0x001a1b},{0x001a56,0x001a56},{0x001a58,0x001a5e}, - {0x001a60,0x001a60},{0x001a62,0x001a62},{0x001a65,0x001a6c},{0x001a73,0x001a7c},{0x001a7f,0x001a7f},{0x001ab0,0x001ac0},{0x001b00,0x001b03},{0x001b34,0x001b34}, - {0x001b36,0x001b3a},{0x001b3c,0x001b3c},{0x001b42,0x001b42},{0x001b6b,0x001b73},{0x001b80,0x001b81},{0x001ba2,0x001ba5},{0x001ba8,0x001ba9},{0x001bab,0x001bad}, - {0x001be6,0x001be6},{0x001be8,0x001be9},{0x001bed,0x001bed},{0x001bef,0x001bf1},{0x001c2c,0x001c33},{0x001c36,0x001c37},{0x001cd0,0x001cd2},{0x001cd4,0x001ce0}, - {0x001ce2,0x001ce8},{0x001ced,0x001ced},{0x001cf4,0x001cf4},{0x001cf8,0x001cf9},{0x001dc0,0x001df9},{0x001dfb,0x001dff},{0x00200b,0x00200f},{0x00202a,0x00202e}, - {0x002060,0x002064},{0x002066,0x00206f},{0x0020d0,0x0020f0},{0x002cef,0x002cf1},{0x002d7f,0x002d7f},{0x002de0,0x002dff},{0x00302a,0x00302d},{0x003099,0x00309a}, - {0x00a66f,0x00a672},{0x00a674,0x00a67d},{0x00a69e,0x00a69f},{0x00a6f0,0x00a6f1},{0x00a802,0x00a802},{0x00a806,0x00a806},{0x00a80b,0x00a80b},{0x00a825,0x00a826}, - {0x00a82c,0x00a82c},{0x00a8c4,0x00a8c5},{0x00a8e0,0x00a8f1},{0x00a8ff,0x00a8ff},{0x00a926,0x00a92d},{0x00a947,0x00a951},{0x00a980,0x00a982},{0x00a9b3,0x00a9b3}, - {0x00a9b6,0x00a9b9},{0x00a9bc,0x00a9bd},{0x00a9e5,0x00a9e5},{0x00aa29,0x00aa2e},{0x00aa31,0x00aa32},{0x00aa35,0x00aa36},{0x00aa43,0x00aa43},{0x00aa4c,0x00aa4c}, - {0x00aa7c,0x00aa7c},{0x00aab0,0x00aab0},{0x00aab2,0x00aab4},{0x00aab7,0x00aab8},{0x00aabe,0x00aabf},{0x00aac1,0x00aac1},{0x00aaec,0x00aaed},{0x00aaf6,0x00aaf6}, - {0x00abe5,0x00abe5},{0x00abe8,0x00abe8},{0x00abed,0x00abed},{0x00fb1e,0x00fb1e},{0x00fe00,0x00fe0f},{0x00fe20,0x00fe2f},{0x00feff,0x00feff},{0x00fff9,0x00fffb}, - {0x0101fd,0x0101fd},{0x0102e0,0x0102e0},{0x010376,0x01037a},{0x010a01,0x010a03},{0x010a05,0x010a06},{0x010a0c,0x010a0f},{0x010a38,0x010a3a},{0x010a3f,0x010a3f}, - {0x010ae5,0x010ae6},{0x010d24,0x010d27},{0x010eab,0x010eac},{0x010f46,0x010f50},{0x011001,0x011001},{0x011038,0x011046},{0x01107f,0x011081},{0x0110b3,0x0110b6}, - {0x0110b9,0x0110ba},{0x0110bd,0x0110bd},{0x0110cd,0x0110cd},{0x011100,0x011102},{0x011127,0x01112b},{0x01112d,0x011134},{0x011173,0x011173},{0x011180,0x011181}, - {0x0111b6,0x0111be},{0x0111c9,0x0111cc},{0x0111cf,0x0111cf},{0x01122f,0x011231},{0x011234,0x011234},{0x011236,0x011237},{0x01123e,0x01123e},{0x0112df,0x0112df}, - {0x0112e3,0x0112ea},{0x011300,0x011301},{0x01133b,0x01133c},{0x011340,0x011340},{0x011366,0x01136c},{0x011370,0x011374},{0x011438,0x01143f},{0x011442,0x011444}, - {0x011446,0x011446},{0x01145e,0x01145e},{0x0114b3,0x0114b8},{0x0114ba,0x0114ba},{0x0114bf,0x0114c0},{0x0114c2,0x0114c3},{0x0115b2,0x0115b5},{0x0115bc,0x0115bd}, - {0x0115bf,0x0115c0},{0x0115dc,0x0115dd},{0x011633,0x01163a},{0x01163d,0x01163d},{0x01163f,0x011640},{0x0116ab,0x0116ab},{0x0116ad,0x0116ad},{0x0116b0,0x0116b5}, - {0x0116b7,0x0116b7},{0x01171d,0x01171f},{0x011722,0x011725},{0x011727,0x01172b},{0x01182f,0x011837},{0x011839,0x01183a},{0x01193b,0x01193c},{0x01193e,0x01193e}, - {0x011943,0x011943},{0x0119d4,0x0119d7},{0x0119da,0x0119db},{0x0119e0,0x0119e0},{0x011a01,0x011a0a},{0x011a33,0x011a38},{0x011a3b,0x011a3e},{0x011a47,0x011a47}, - {0x011a51,0x011a56},{0x011a59,0x011a5b},{0x011a8a,0x011a96},{0x011a98,0x011a99},{0x011c30,0x011c36},{0x011c38,0x011c3d},{0x011c3f,0x011c3f},{0x011c92,0x011ca7}, - {0x011caa,0x011cb0},{0x011cb2,0x011cb3},{0x011cb5,0x011cb6},{0x011d31,0x011d36},{0x011d3a,0x011d3a},{0x011d3c,0x011d3d},{0x011d3f,0x011d45},{0x011d47,0x011d47}, - {0x011d90,0x011d91},{0x011d95,0x011d95},{0x011d97,0x011d97},{0x011ef3,0x011ef4},{0x013430,0x013438},{0x016af0,0x016af4},{0x016b30,0x016b36},{0x016f4f,0x016f4f}, - {0x016f8f,0x016f92},{0x016fe4,0x016fe4},{0x01bc9d,0x01bc9e},{0x01bca0,0x01bca3},{0x01d167,0x01d169},{0x01d173,0x01d182},{0x01d185,0x01d18b},{0x01d1aa,0x01d1ad}, - {0x01d242,0x01d244},{0x01da00,0x01da36},{0x01da3b,0x01da6c},{0x01da75,0x01da75},{0x01da84,0x01da84},{0x01da9b,0x01da9f},{0x01daa1,0x01daaf},{0x01e000,0x01e006}, - {0x01e008,0x01e018},{0x01e01b,0x01e021},{0x01e023,0x01e024},{0x01e026,0x01e02a},{0x01e130,0x01e136},{0x01e2ec,0x01e2ef},{0x01e8d0,0x01e8d6},{0x01e944,0x01e94a}, - {0x0e0001,0x0e0001},{0x0e0020,0x0e007f},{0x0e0100,0x0e01ef}, + {0x000300, 0x00036f}, {0x000483, 0x000489}, {0x000591, 0x0005bd}, {0x0005bf, 0x0005bf}, {0x0005c1, 0x0005c2}, {0x0005c4, 0x0005c5}, {0x0005c7, 0x0005c7}, + {0x000600, 0x000605}, {0x000610, 0x00061a}, {0x00061c, 0x00061c}, {0x00064b, 0x00065f}, {0x000670, 0x000670}, {0x0006d6, 0x0006dd}, {0x0006df, 0x0006e4}, + {0x0006e7, 0x0006e8}, {0x0006ea, 0x0006ed}, {0x00070f, 0x00070f}, {0x000711, 0x000711}, {0x000730, 0x00074a}, {0x0007a6, 0x0007b0}, {0x0007eb, 0x0007f3}, + {0x0007fd, 0x0007fd}, {0x000816, 0x000819}, {0x00081b, 0x000823}, {0x000825, 0x000827}, {0x000829, 0x00082d}, {0x000859, 0x00085b}, {0x0008d3, 0x000902}, + {0x00093a, 0x00093a}, {0x00093c, 0x00093c}, {0x000941, 0x000948}, {0x00094d, 0x00094d}, {0x000951, 0x000957}, {0x000962, 0x000963}, {0x000981, 0x000981}, + {0x0009bc, 0x0009bc}, {0x0009c1, 0x0009c4}, {0x0009cd, 0x0009cd}, {0x0009e2, 0x0009e3}, {0x0009fe, 0x0009fe}, {0x000a01, 0x000a02}, {0x000a3c, 0x000a3c}, + {0x000a41, 0x000a42}, {0x000a47, 0x000a48}, {0x000a4b, 0x000a4d}, {0x000a51, 0x000a51}, {0x000a70, 0x000a71}, {0x000a75, 0x000a75}, {0x000a81, 0x000a82}, + {0x000abc, 0x000abc}, {0x000ac1, 0x000ac5}, {0x000ac7, 0x000ac8}, {0x000acd, 0x000acd}, {0x000ae2, 0x000ae3}, {0x000afa, 0x000aff}, {0x000b01, 0x000b01}, + {0x000b3c, 0x000b3c}, {0x000b3f, 0x000b3f}, {0x000b41, 0x000b44}, {0x000b4d, 0x000b4d}, {0x000b55, 0x000b56}, {0x000b62, 0x000b63}, {0x000b82, 0x000b82}, + {0x000bc0, 0x000bc0}, {0x000bcd, 0x000bcd}, {0x000c00, 0x000c00}, {0x000c04, 0x000c04}, {0x000c3e, 0x000c40}, {0x000c46, 0x000c48}, {0x000c4a, 0x000c4d}, + {0x000c55, 0x000c56}, {0x000c62, 0x000c63}, {0x000c81, 0x000c81}, {0x000cbc, 0x000cbc}, {0x000cbf, 0x000cbf}, {0x000cc6, 0x000cc6}, {0x000ccc, 0x000ccd}, + {0x000ce2, 0x000ce3}, {0x000d00, 0x000d01}, {0x000d3b, 0x000d3c}, {0x000d41, 0x000d44}, {0x000d4d, 0x000d4d}, {0x000d62, 0x000d63}, {0x000d81, 0x000d81}, + {0x000dca, 0x000dca}, {0x000dd2, 0x000dd4}, {0x000dd6, 0x000dd6}, {0x000e31, 0x000e31}, {0x000e34, 0x000e3a}, {0x000e47, 0x000e4e}, {0x000eb1, 0x000eb1}, + {0x000eb4, 0x000ebc}, {0x000ec8, 0x000ecd}, {0x000f18, 0x000f19}, {0x000f35, 0x000f35}, {0x000f37, 0x000f37}, {0x000f39, 0x000f39}, {0x000f71, 0x000f7e}, + {0x000f80, 0x000f84}, {0x000f86, 0x000f87}, {0x000f8d, 0x000f97}, {0x000f99, 0x000fbc}, {0x000fc6, 0x000fc6}, {0x00102d, 0x001030}, {0x001032, 0x001037}, + {0x001039, 0x00103a}, {0x00103d, 0x00103e}, {0x001058, 0x001059}, {0x00105e, 0x001060}, {0x001071, 0x001074}, {0x001082, 0x001082}, {0x001085, 0x001086}, + {0x00108d, 0x00108d}, {0x00109d, 0x00109d}, {0x001160, 0x001160}, {0x00135d, 0x00135f}, {0x001712, 0x001714}, {0x001732, 0x001734}, {0x001752, 0x001753}, + {0x001772, 0x001773}, {0x0017b4, 0x0017b5}, {0x0017b7, 0x0017bd}, {0x0017c6, 0x0017c6}, {0x0017c9, 0x0017d3}, {0x0017dd, 0x0017dd}, {0x00180b, 0x00180e}, + {0x001885, 0x001886}, {0x0018a9, 0x0018a9}, {0x001920, 0x001922}, {0x001927, 0x001928}, {0x001932, 0x001932}, {0x001939, 0x00193b}, {0x001a17, 0x001a18}, + {0x001a1b, 0x001a1b}, {0x001a56, 0x001a56}, {0x001a58, 0x001a5e}, {0x001a60, 0x001a60}, {0x001a62, 0x001a62}, {0x001a65, 0x001a6c}, {0x001a73, 0x001a7c}, + {0x001a7f, 0x001a7f}, {0x001ab0, 0x001ac0}, {0x001b00, 0x001b03}, {0x001b34, 0x001b34}, {0x001b36, 0x001b3a}, {0x001b3c, 0x001b3c}, {0x001b42, 0x001b42}, + {0x001b6b, 0x001b73}, {0x001b80, 0x001b81}, {0x001ba2, 0x001ba5}, {0x001ba8, 0x001ba9}, {0x001bab, 0x001bad}, {0x001be6, 0x001be6}, {0x001be8, 0x001be9}, + {0x001bed, 0x001bed}, {0x001bef, 0x001bf1}, {0x001c2c, 0x001c33}, {0x001c36, 0x001c37}, {0x001cd0, 0x001cd2}, {0x001cd4, 0x001ce0}, {0x001ce2, 0x001ce8}, + {0x001ced, 0x001ced}, {0x001cf4, 0x001cf4}, {0x001cf8, 0x001cf9}, {0x001dc0, 0x001df9}, {0x001dfb, 0x001dff}, {0x00200b, 0x00200f}, {0x00202a, 0x00202e}, + {0x002060, 0x002064}, {0x002066, 0x00206f}, {0x0020d0, 0x0020f0}, {0x002cef, 0x002cf1}, {0x002d7f, 0x002d7f}, {0x002de0, 0x002dff}, {0x00302a, 0x00302d}, + {0x003099, 0x00309a}, {0x00a66f, 0x00a672}, {0x00a674, 0x00a67d}, {0x00a69e, 0x00a69f}, {0x00a6f0, 0x00a6f1}, {0x00a802, 0x00a802}, {0x00a806, 0x00a806}, + {0x00a80b, 0x00a80b}, {0x00a825, 0x00a826}, {0x00a82c, 0x00a82c}, {0x00a8c4, 0x00a8c5}, {0x00a8e0, 0x00a8f1}, {0x00a8ff, 0x00a8ff}, {0x00a926, 0x00a92d}, + {0x00a947, 0x00a951}, {0x00a980, 0x00a982}, {0x00a9b3, 0x00a9b3}, {0x00a9b6, 0x00a9b9}, {0x00a9bc, 0x00a9bd}, {0x00a9e5, 0x00a9e5}, {0x00aa29, 0x00aa2e}, + {0x00aa31, 0x00aa32}, {0x00aa35, 0x00aa36}, {0x00aa43, 0x00aa43}, {0x00aa4c, 0x00aa4c}, {0x00aa7c, 0x00aa7c}, {0x00aab0, 0x00aab0}, {0x00aab2, 0x00aab4}, + {0x00aab7, 0x00aab8}, {0x00aabe, 0x00aabf}, {0x00aac1, 0x00aac1}, {0x00aaec, 0x00aaed}, {0x00aaf6, 0x00aaf6}, {0x00abe5, 0x00abe5}, {0x00abe8, 0x00abe8}, + {0x00abed, 0x00abed}, {0x00fb1e, 0x00fb1e}, {0x00fe00, 0x00fe0f}, {0x00fe20, 0x00fe2f}, {0x00feff, 0x00feff}, {0x00fff9, 0x00fffb}, {0x0101fd, 0x0101fd}, + {0x0102e0, 0x0102e0}, {0x010376, 0x01037a}, {0x010a01, 0x010a03}, {0x010a05, 0x010a06}, {0x010a0c, 0x010a0f}, {0x010a38, 0x010a3a}, {0x010a3f, 0x010a3f}, + {0x010ae5, 0x010ae6}, {0x010d24, 0x010d27}, {0x010eab, 0x010eac}, {0x010f46, 0x010f50}, {0x011001, 0x011001}, {0x011038, 0x011046}, {0x01107f, 0x011081}, + {0x0110b3, 0x0110b6}, {0x0110b9, 0x0110ba}, {0x0110bd, 0x0110bd}, {0x0110cd, 0x0110cd}, {0x011100, 0x011102}, {0x011127, 0x01112b}, {0x01112d, 0x011134}, + {0x011173, 0x011173}, {0x011180, 0x011181}, {0x0111b6, 0x0111be}, {0x0111c9, 0x0111cc}, {0x0111cf, 0x0111cf}, {0x01122f, 0x011231}, {0x011234, 0x011234}, + {0x011236, 0x011237}, {0x01123e, 0x01123e}, {0x0112df, 0x0112df}, {0x0112e3, 0x0112ea}, {0x011300, 0x011301}, {0x01133b, 0x01133c}, {0x011340, 0x011340}, + {0x011366, 0x01136c}, {0x011370, 0x011374}, {0x011438, 0x01143f}, {0x011442, 0x011444}, {0x011446, 0x011446}, {0x01145e, 0x01145e}, {0x0114b3, 0x0114b8}, + {0x0114ba, 0x0114ba}, {0x0114bf, 0x0114c0}, {0x0114c2, 0x0114c3}, {0x0115b2, 0x0115b5}, {0x0115bc, 0x0115bd}, {0x0115bf, 0x0115c0}, {0x0115dc, 0x0115dd}, + {0x011633, 0x01163a}, {0x01163d, 0x01163d}, {0x01163f, 0x011640}, {0x0116ab, 0x0116ab}, {0x0116ad, 0x0116ad}, {0x0116b0, 0x0116b5}, {0x0116b7, 0x0116b7}, + {0x01171d, 0x01171f}, {0x011722, 0x011725}, {0x011727, 0x01172b}, {0x01182f, 0x011837}, {0x011839, 0x01183a}, {0x01193b, 0x01193c}, {0x01193e, 0x01193e}, + {0x011943, 0x011943}, {0x0119d4, 0x0119d7}, {0x0119da, 0x0119db}, {0x0119e0, 0x0119e0}, {0x011a01, 0x011a0a}, {0x011a33, 0x011a38}, {0x011a3b, 0x011a3e}, + {0x011a47, 0x011a47}, {0x011a51, 0x011a56}, {0x011a59, 0x011a5b}, {0x011a8a, 0x011a96}, {0x011a98, 0x011a99}, {0x011c30, 0x011c36}, {0x011c38, 0x011c3d}, + {0x011c3f, 0x011c3f}, {0x011c92, 0x011ca7}, {0x011caa, 0x011cb0}, {0x011cb2, 0x011cb3}, {0x011cb5, 0x011cb6}, {0x011d31, 0x011d36}, {0x011d3a, 0x011d3a}, + {0x011d3c, 0x011d3d}, {0x011d3f, 0x011d45}, {0x011d47, 0x011d47}, {0x011d90, 0x011d91}, {0x011d95, 0x011d95}, {0x011d97, 0x011d97}, {0x011ef3, 0x011ef4}, + {0x013430, 0x013438}, {0x016af0, 0x016af4}, {0x016b30, 0x016b36}, {0x016f4f, 0x016f4f}, {0x016f8f, 0x016f92}, {0x016fe4, 0x016fe4}, {0x01bc9d, 0x01bc9e}, + {0x01bca0, 0x01bca3}, {0x01d167, 0x01d169}, {0x01d173, 0x01d182}, {0x01d185, 0x01d18b}, {0x01d1aa, 0x01d1ad}, {0x01d242, 0x01d244}, {0x01da00, 0x01da36}, + {0x01da3b, 0x01da6c}, {0x01da75, 0x01da75}, {0x01da84, 0x01da84}, {0x01da9b, 0x01da9f}, {0x01daa1, 0x01daaf}, {0x01e000, 0x01e006}, {0x01e008, 0x01e018}, + {0x01e01b, 0x01e021}, {0x01e023, 0x01e024}, {0x01e026, 0x01e02a}, {0x01e130, 0x01e136}, {0x01e2ec, 0x01e2ef}, {0x01e8d0, 0x01e8d6}, {0x01e944, 0x01e94a}, + {0x0e0001, 0x0e0001}, {0x0e0020, 0x0e007f}, {0x0e0100, 0x0e01ef}, }; - static constexpr const RangeLut RANGE_LUT_LIST[] = { {-1, LUT_NONPRINTABLE, 1}, - { 2, LUT_2 , 117}, - { 0, LUT_0 , 339}, - { 1, nullptr , 1}, + {2, LUT_2, 117}, + {0, LUT_0, 339}, + {1, nullptr, 1}, }; static constexpr const int RANGE_LUT_LIST_SIZE = 4; - -int KONSOLECHARACTERS_EXPORT characterWidth(uint ucs4) { - if(Q_LIKELY(ucs4 < sizeof(DIRECT_LUT))) { +int KONSOLECHARACTERS_EXPORT characterWidth(uint ucs4) +{ + if (Q_LIKELY(ucs4 < sizeof(DIRECT_LUT))) { return DIRECT_LUT[ucs4]; } - for(auto rl = RANGE_LUT_LIST; rl->lut != nullptr; ++rl) { + for (auto rl = RANGE_LUT_LIST; rl->lut != nullptr; ++rl) { int l = 0; int r = rl->size - 1; - while(l <= r) { + while (l <= r) { const int m = (l + r) / 2; - if(rl->lut[m].last < ucs4) { + if (rl->lut[m].last < ucs4) { l = m + 1; - } else if(rl->lut[m].first > ucs4) { + } else if (rl->lut[m].first > ucs4) { r = m - 1; } else { return rl->width; @@ -149,4 +154,3 @@ int KONSOLECHARACTERS_EXPORT characterWidth(uint ucs4) { return RANGE_LUT_LIST[RANGE_LUT_LIST_SIZE - 1].width; } - diff --git a/src/characters/CharacterWidth.src.cpp b/src/characters/CharacterWidth.src.cpp index ce8eb4cac..379b8a49b 100644 --- a/src/characters/CharacterWidth.src.cpp +++ b/src/characters/CharacterWidth.src.cpp @@ -3,21 +3,22 @@ SPDX-License-Identifier: GPL-2.0-or-later */ -«*NOTE:-----------------------------------------------------------------------*» -// Typing in "«" and "»" characters in some keyboard layouts (X11): -// -// English/UK: AltGr+Z AltGr+X -// EurKEY: AltGr+[ AltGr+] -// German: AltGr+X AltGr+Y -// Polish: AltGr+9 AltGr+0 -// English/US: N/A; You can try EurKEY which extends En/US layout with extra -// characters available with AltGr[+Shift]. -// -// Alternatively, you can use e.g. "<<<" and ">>>" and convert it to the valid -// characters using sed or your editor's replace function. -// -// This text will not appear in an output file. -«*-----------------------------------------------------------------------:NOTE*» +«*NOTE : -----------------------------------------------------------------------*» + // Typing in "«" and "»" characters in some keyboard layouts (X11): + // + // English/UK: AltGr+Z AltGr+X + // EurKEY: AltGr+[ AltGr+] + // German: AltGr+X AltGr+Y + // Polish: AltGr+9 AltGr+0 + // English/US: N/A; You can try EurKEY which extends En/US layout with extra + // characters available with AltGr[+Shift]. + // + // Alternatively, you can use e.g. "<<<" and ">>>" and convert it to the valid + // characters using sed or your editor's replace function. + // + // This text will not appear in an output file. +« + * ----------------------------------------------------------------------- : NOTE *» // // «gen-file-warning» // @@ -35,14 +36,13 @@ #include "CharacterWidth.h" #include "konsolecharacters_export.h" - -struct Range { + struct Range { uint first, last; }; struct RangeLut { int8_t width; - const Range * const lut; + const Range *const lut; int size; }; @@ -50,36 +50,34 @@ enum { InvalidWidth = INT8_MIN, }; - -static constexpr const int8_t DIRECT_LUT[] = {«!fmt "% d":«direct-lut: - «!repeat 32:«:«»,»» +static constexpr const int8_t DIRECT_LUT[] = {«!fmt "% d" :«direct - lut : + «!repeat 32 :«:«»,»» »»}; -«ranges-luts:«: -static constexpr const Range «name»[] = {«!fmt "%#.6x":«ranges: - «!repeat 8:«:{«first»,«last»},»» +«ranges - luts :«: static constexpr const Range «name»[] = {«!fmt "%#.6x" :«ranges : + «!repeat 8 :«: {«first»,«last»},»» »»}; »» -static constexpr const RangeLut RANGE_LUT_LIST[] = {«ranges-lut-list: - «:{«!fmt "% d":«width»», «!fmt "%-16s":«name»», «size»},» + static constexpr const RangeLut RANGE_LUT_LIST[] = {«ranges - lut - list : + «: {«!fmt "% d" :«width»», «!fmt "%-16s" :«name»», «size»},» »}; -static constexpr const int RANGE_LUT_LIST_SIZE = «ranges-lut-list-size»; +static constexpr const int RANGE_LUT_LIST_SIZE = «ranges - lut - list - size»; - -int KONSOLECHARACTERS_EXPORT characterWidth(uint ucs4) { - if(Q_LIKELY(ucs4 < sizeof(DIRECT_LUT))) { +int KONSOLECHARACTERS_EXPORT characterWidth(uint ucs4) +{ + if (Q_LIKELY(ucs4 < sizeof(DIRECT_LUT))) { return DIRECT_LUT[ucs4]; } - for(auto rl = RANGE_LUT_LIST; rl->lut != nullptr; ++rl) { + for (auto rl = RANGE_LUT_LIST; rl->lut != nullptr; ++rl) { int l = 0; int r = rl->size - 1; - while(l <= r) { + while (l <= r) { const int m = (l + r) / 2; - if(rl->lut[m].last < ucs4) { + if (rl->lut[m].last < ucs4) { l = m + 1; - } else if(rl->lut[m].first > ucs4) { + } else if (rl->lut[m].first > ucs4) { r = m - 1; } else { return rl->width; @@ -89,4 +87,3 @@ int KONSOLECHARACTERS_EXPORT characterWidth(uint ucs4) { return RANGE_LUT_LIST[RANGE_LUT_LIST_SIZE - 1].width; } - diff --git a/src/characters/ExtendedCharTable.cpp b/src/characters/ExtendedCharTable.cpp index a606b9886..649b33731 100644 --- a/src/characters/ExtendedCharTable.cpp +++ b/src/characters/ExtendedCharTable.cpp @@ -11,8 +11,8 @@ using namespace Konsole; -ExtendedCharTable::ExtendedCharTable() : - _extendedCharTable(QHash()) +ExtendedCharTable::ExtendedCharTable() + : _extendedCharTable(QHash()) { } @@ -42,7 +42,7 @@ uint ExtendedCharTable::createExtendedChar(const uint *unicodePoints, ushort len // this sequence already has an entry in the table, // return its hash return hash; - } + } // if hash is already used by another, different sequence of unicode character // points then try next hash hash++; @@ -90,7 +90,7 @@ uint *ExtendedCharTable::lookupExtendedChar(uint hash, ushort &length) const if (buffer != nullptr) { length = ushort(buffer[0]); return buffer + 1; - } + } length = 0; return nullptr; } @@ -104,8 +104,7 @@ uint ExtendedCharTable::extendedCharHash(const uint *unicodePoints, ushort lengt return hash; } -bool ExtendedCharTable::extendedCharMatch(uint hash, const uint *unicodePoints, - ushort length) const +bool ExtendedCharTable::extendedCharMatch(uint hash, const uint *unicodePoints, ushort length) const { uint *entry = _extendedCharTable[hash]; diff --git a/src/characters/ExtendedCharTable.h b/src/characters/ExtendedCharTable.h index cbd9fc35b..c0d5effc0 100644 --- a/src/characters/ExtendedCharTable.h +++ b/src/characters/ExtendedCharTable.h @@ -8,12 +8,13 @@ #define EXTENDEDCHARTABLE_H // Qt -#include #include +#include #include -namespace Konsole { +namespace Konsole +{ /** * A table which stores sequences of unicode characters, referenced * by hash keys. The hash key itself is the same size as a unicode @@ -23,7 +24,7 @@ namespace Konsole { class ExtendedCharTable { public: - typedef std::function ()> pExtendedChars; + typedef std::function()> pExtendedChars; /** Constructs a new character table. */ ExtendedCharTable(); @@ -55,6 +56,7 @@ public: /** The global ExtendedCharTable instance. */ static ExtendedCharTable instance; + private: // calculates the hash key of a sequence of unicode points of size 'length' uint extendedCharHash(const uint *unicodePoints, ushort length) const; @@ -69,4 +71,4 @@ private: } -#endif // end of EXTENDEDCHARTABLE_H +#endif // end of EXTENDEDCHARTABLE_H diff --git a/src/characters/LineBlockCharacters.cpp b/src/characters/LineBlockCharacters.cpp index 69d5c9ed0..7fc5169be 100644 --- a/src/characters/LineBlockCharacters.cpp +++ b/src/characters/LineBlockCharacters.cpp @@ -13,15 +13,11 @@ // Qt #include -namespace Konsole { -namespace LineBlockCharacters { - -enum LineType { - LtNone = 0, - LtDouble = 1, - LtLight = 2, - LtHeavy = 3 -}; +namespace Konsole +{ +namespace LineBlockCharacters +{ +enum LineType { LtNone = 0, LtDouble = 1, LtLight = 2, LtHeavy = 3, }; // PackedLineTypes is an 8-bit number representing types of 4 line character's lines. Each line is // represented by 2 bits. Lines order, starting from MSB: top, right, bottom, left. @@ -32,127 +28,141 @@ static inline constexpr quint8 makePackedLineTypes(LineType top, LineType right, static constexpr const quint8 PackedLineTypesLut[] = { // top right bottom left - makePackedLineTypes(LtNone , LtLight , LtNone , LtLight ), /* U+2500 ─ */ - makePackedLineTypes(LtNone , LtHeavy , LtNone , LtHeavy ), /* U+2501 ━ */ - makePackedLineTypes(LtLight , LtNone , LtLight , LtNone ), /* U+2502 │ */ - makePackedLineTypes(LtHeavy , LtNone , LtHeavy , LtNone ), /* U+2503 ┃ */ - 0, 0, 0, 0, 0, 0, 0, 0, /* U+2504-0x250b */ - makePackedLineTypes(LtNone , LtLight , LtLight , LtNone ), /* U+250C ┌ */ - makePackedLineTypes(LtNone , LtHeavy , LtLight , LtNone ), /* U+250D ┍ */ - makePackedLineTypes(LtNone , LtLight , LtHeavy , LtNone ), /* U+250E ┎ */ - makePackedLineTypes(LtNone , LtHeavy , LtHeavy , LtNone ), /* U+250F ┏ */ - makePackedLineTypes(LtNone , LtNone , LtLight , LtLight ), /* U+2510 ┐ */ - makePackedLineTypes(LtNone , LtNone , LtLight , LtHeavy ), /* U+2511 ┑ */ - makePackedLineTypes(LtNone , LtNone , LtHeavy , LtLight ), /* U+2512 ┒ */ - makePackedLineTypes(LtNone , LtNone , LtHeavy , LtHeavy ), /* U+2513 ┓ */ - makePackedLineTypes(LtLight , LtLight , LtNone , LtNone ), /* U+2514 └ */ - makePackedLineTypes(LtLight , LtHeavy , LtNone , LtNone ), /* U+2515 ┕ */ - makePackedLineTypes(LtHeavy , LtLight , LtNone , LtNone ), /* U+2516 ┖ */ - makePackedLineTypes(LtHeavy , LtHeavy , LtNone , LtNone ), /* U+2517 ┗ */ - makePackedLineTypes(LtLight , LtNone , LtNone , LtLight ), /* U+2518 ┘ */ - makePackedLineTypes(LtLight , LtNone , LtNone , LtHeavy ), /* U+2519 ┙ */ - makePackedLineTypes(LtHeavy , LtNone , LtNone , LtLight ), /* U+251A ┚ */ - makePackedLineTypes(LtHeavy , LtNone , LtNone , LtHeavy ), /* U+251B ┛ */ - makePackedLineTypes(LtLight , LtLight , LtLight , LtNone ), /* U+251C ├ */ - makePackedLineTypes(LtLight , LtHeavy , LtLight , LtNone ), /* U+251D ┝ */ - makePackedLineTypes(LtHeavy , LtLight , LtLight , LtNone ), /* U+251E ┞ */ - makePackedLineTypes(LtLight , LtLight , LtHeavy , LtNone ), /* U+251F ┟ */ - makePackedLineTypes(LtHeavy , LtLight , LtHeavy , LtNone ), /* U+2520 ┠ */ - makePackedLineTypes(LtHeavy , LtHeavy , LtLight , LtNone ), /* U+2521 ┡ */ - makePackedLineTypes(LtLight , LtHeavy , LtHeavy , LtNone ), /* U+2522 ┢ */ - makePackedLineTypes(LtHeavy , LtHeavy , LtHeavy , LtNone ), /* U+2523 ┣ */ - makePackedLineTypes(LtLight , LtNone , LtLight , LtLight ), /* U+2524 ┤ */ - makePackedLineTypes(LtLight , LtNone , LtLight , LtHeavy ), /* U+2525 ┥ */ - makePackedLineTypes(LtHeavy , LtNone , LtLight , LtLight ), /* U+2526 ┦ */ - makePackedLineTypes(LtLight , LtNone , LtHeavy , LtLight ), /* U+2527 ┧ */ - makePackedLineTypes(LtHeavy , LtNone , LtHeavy , LtLight ), /* U+2528 ┨ */ - makePackedLineTypes(LtHeavy , LtNone , LtLight , LtHeavy ), /* U+2529 ┩ */ - makePackedLineTypes(LtLight , LtNone , LtHeavy , LtHeavy ), /* U+252A ┪ */ - makePackedLineTypes(LtHeavy , LtNone , LtHeavy , LtHeavy ), /* U+252B ┫ */ - makePackedLineTypes(LtNone , LtLight , LtLight , LtLight ), /* U+252C ┬ */ - makePackedLineTypes(LtNone , LtLight , LtLight , LtHeavy ), /* U+252D ┭ */ - makePackedLineTypes(LtNone , LtHeavy , LtLight , LtLight ), /* U+252E ┮ */ - makePackedLineTypes(LtNone , LtHeavy , LtLight , LtHeavy ), /* U+252F ┯ */ - makePackedLineTypes(LtNone , LtLight , LtHeavy , LtLight ), /* U+2530 ┰ */ - makePackedLineTypes(LtNone , LtLight , LtHeavy , LtHeavy ), /* U+2531 ┱ */ - makePackedLineTypes(LtNone , LtHeavy , LtHeavy , LtLight ), /* U+2532 ┲ */ - makePackedLineTypes(LtNone , LtHeavy , LtHeavy , LtHeavy ), /* U+2533 ┳ */ - makePackedLineTypes(LtLight , LtLight , LtNone , LtLight ), /* U+2534 ┴ */ - makePackedLineTypes(LtLight , LtLight , LtNone , LtHeavy ), /* U+2535 ┵ */ - makePackedLineTypes(LtLight , LtHeavy , LtNone , LtLight ), /* U+2536 ┶ */ - makePackedLineTypes(LtLight , LtHeavy , LtNone , LtHeavy ), /* U+2537 ┷ */ - makePackedLineTypes(LtHeavy , LtLight , LtNone , LtLight ), /* U+2538 ┸ */ - makePackedLineTypes(LtHeavy , LtLight , LtNone , LtHeavy ), /* U+2539 ┹ */ - makePackedLineTypes(LtHeavy , LtHeavy , LtNone , LtLight ), /* U+253A ┺ */ - makePackedLineTypes(LtHeavy , LtHeavy , LtNone , LtHeavy ), /* U+253B ┻ */ - makePackedLineTypes(LtLight , LtLight , LtLight , LtLight ), /* U+253C ┼ */ - makePackedLineTypes(LtLight , LtLight , LtLight , LtHeavy ), /* U+253D ┽ */ - makePackedLineTypes(LtLight , LtHeavy , LtLight , LtLight ), /* U+253E ┾ */ - makePackedLineTypes(LtLight , LtHeavy , LtLight , LtHeavy ), /* U+253F ┿ */ - makePackedLineTypes(LtHeavy , LtLight , LtLight , LtLight ), /* U+2540 ╀ */ - makePackedLineTypes(LtLight , LtLight , LtHeavy , LtLight ), /* U+2541 ╁ */ - makePackedLineTypes(LtHeavy , LtLight , LtHeavy , LtLight ), /* U+2542 ╂ */ - makePackedLineTypes(LtHeavy , LtLight , LtLight , LtHeavy ), /* U+2543 ╃ */ - makePackedLineTypes(LtHeavy , LtHeavy , LtLight , LtLight ), /* U+2544 ╄ */ - makePackedLineTypes(LtLight , LtLight , LtHeavy , LtHeavy ), /* U+2545 ╅ */ - makePackedLineTypes(LtLight , LtHeavy , LtHeavy , LtLight ), /* U+2546 ╆ */ - makePackedLineTypes(LtHeavy , LtHeavy , LtLight , LtHeavy ), /* U+2547 ╇ */ - makePackedLineTypes(LtLight , LtHeavy , LtHeavy , LtHeavy ), /* U+2548 ╈ */ - makePackedLineTypes(LtHeavy , LtLight , LtHeavy , LtHeavy ), /* U+2549 ╉ */ - makePackedLineTypes(LtHeavy , LtHeavy , LtHeavy , LtLight ), /* U+254A ╊ */ - makePackedLineTypes(LtHeavy , LtHeavy , LtHeavy , LtHeavy ), /* U+254B ╋ */ - 0, 0, 0, 0, /* U+254C - U+254F */ - makePackedLineTypes(LtNone , LtDouble, LtNone , LtDouble), /* U+2550 ═ */ - makePackedLineTypes(LtDouble, LtNone , LtDouble, LtNone ), /* U+2551 ║ */ - makePackedLineTypes(LtNone , LtDouble, LtLight , LtNone ), /* U+2552 ╒ */ - makePackedLineTypes(LtNone , LtLight , LtDouble, LtNone ), /* U+2553 ╓ */ - makePackedLineTypes(LtNone , LtDouble, LtDouble, LtNone ), /* U+2554 ╔ */ - makePackedLineTypes(LtNone , LtNone , LtLight , LtDouble), /* U+2555 ╕ */ - makePackedLineTypes(LtNone , LtNone , LtDouble, LtLight ), /* U+2556 ╖ */ - makePackedLineTypes(LtNone , LtNone , LtDouble, LtDouble), /* U+2557 ╗ */ - makePackedLineTypes(LtLight , LtDouble, LtNone , LtNone ), /* U+2558 ╘ */ - makePackedLineTypes(LtDouble, LtLight , LtNone , LtNone ), /* U+2559 ╙ */ - makePackedLineTypes(LtDouble, LtDouble, LtNone , LtNone ), /* U+255A ╚ */ - makePackedLineTypes(LtLight , LtNone , LtNone , LtDouble), /* U+255B ╛ */ - makePackedLineTypes(LtDouble, LtNone , LtNone , LtLight ), /* U+255C ╜ */ - makePackedLineTypes(LtDouble, LtNone , LtNone , LtDouble), /* U+255D ╝ */ - makePackedLineTypes(LtLight , LtDouble, LtLight , LtNone ), /* U+255E ╞ */ - makePackedLineTypes(LtDouble, LtLight , LtDouble, LtNone ), /* U+255F ╟ */ - makePackedLineTypes(LtDouble, LtDouble, LtDouble, LtNone ), /* U+2560 ╠ */ - makePackedLineTypes(LtLight , LtNone , LtLight , LtDouble), /* U+2561 ╡ */ - makePackedLineTypes(LtDouble, LtNone , LtDouble, LtLight ), /* U+2562 ╢ */ - makePackedLineTypes(LtDouble, LtNone , LtDouble, LtDouble), /* U+2563 ╣ */ - makePackedLineTypes(LtNone , LtDouble, LtLight , LtDouble), /* U+2564 ╤ */ - makePackedLineTypes(LtNone , LtLight , LtDouble, LtLight ), /* U+2565 ╥ */ - makePackedLineTypes(LtNone , LtDouble, LtDouble, LtDouble), /* U+2566 ╦ */ - makePackedLineTypes(LtLight , LtDouble, LtNone , LtDouble), /* U+2567 ╧ */ - makePackedLineTypes(LtDouble, LtLight , LtNone , LtLight ), /* U+2568 ╨ */ - makePackedLineTypes(LtDouble, LtDouble, LtNone , LtDouble), /* U+2569 ╩ */ - makePackedLineTypes(LtLight , LtDouble, LtLight , LtDouble), /* U+256A ╪ */ - makePackedLineTypes(LtDouble, LtLight , LtDouble, LtLight ), /* U+256B ╫ */ + makePackedLineTypes(LtNone, LtLight, LtNone, LtLight), /* U+2500 ─ */ + makePackedLineTypes(LtNone, LtHeavy, LtNone, LtHeavy), /* U+2501 ━ */ + makePackedLineTypes(LtLight, LtNone, LtLight, LtNone), /* U+2502 │ */ + makePackedLineTypes(LtHeavy, LtNone, LtHeavy, LtNone), /* U+2503 ┃ */ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, /* U+2504-0x250b */ + makePackedLineTypes(LtNone, LtLight, LtLight, LtNone), /* U+250C ┌ */ + makePackedLineTypes(LtNone, LtHeavy, LtLight, LtNone), /* U+250D ┍ */ + makePackedLineTypes(LtNone, LtLight, LtHeavy, LtNone), /* U+250E ┎ */ + makePackedLineTypes(LtNone, LtHeavy, LtHeavy, LtNone), /* U+250F ┏ */ + makePackedLineTypes(LtNone, LtNone, LtLight, LtLight), /* U+2510 ┐ */ + makePackedLineTypes(LtNone, LtNone, LtLight, LtHeavy), /* U+2511 ┑ */ + makePackedLineTypes(LtNone, LtNone, LtHeavy, LtLight), /* U+2512 ┒ */ + makePackedLineTypes(LtNone, LtNone, LtHeavy, LtHeavy), /* U+2513 ┓ */ + makePackedLineTypes(LtLight, LtLight, LtNone, LtNone), /* U+2514 └ */ + makePackedLineTypes(LtLight, LtHeavy, LtNone, LtNone), /* U+2515 ┕ */ + makePackedLineTypes(LtHeavy, LtLight, LtNone, LtNone), /* U+2516 ┖ */ + makePackedLineTypes(LtHeavy, LtHeavy, LtNone, LtNone), /* U+2517 ┗ */ + makePackedLineTypes(LtLight, LtNone, LtNone, LtLight), /* U+2518 ┘ */ + makePackedLineTypes(LtLight, LtNone, LtNone, LtHeavy), /* U+2519 ┙ */ + makePackedLineTypes(LtHeavy, LtNone, LtNone, LtLight), /* U+251A ┚ */ + makePackedLineTypes(LtHeavy, LtNone, LtNone, LtHeavy), /* U+251B ┛ */ + makePackedLineTypes(LtLight, LtLight, LtLight, LtNone), /* U+251C ├ */ + makePackedLineTypes(LtLight, LtHeavy, LtLight, LtNone), /* U+251D ┝ */ + makePackedLineTypes(LtHeavy, LtLight, LtLight, LtNone), /* U+251E ┞ */ + makePackedLineTypes(LtLight, LtLight, LtHeavy, LtNone), /* U+251F ┟ */ + makePackedLineTypes(LtHeavy, LtLight, LtHeavy, LtNone), /* U+2520 ┠ */ + makePackedLineTypes(LtHeavy, LtHeavy, LtLight, LtNone), /* U+2521 ┡ */ + makePackedLineTypes(LtLight, LtHeavy, LtHeavy, LtNone), /* U+2522 ┢ */ + makePackedLineTypes(LtHeavy, LtHeavy, LtHeavy, LtNone), /* U+2523 ┣ */ + makePackedLineTypes(LtLight, LtNone, LtLight, LtLight), /* U+2524 ┤ */ + makePackedLineTypes(LtLight, LtNone, LtLight, LtHeavy), /* U+2525 ┥ */ + makePackedLineTypes(LtHeavy, LtNone, LtLight, LtLight), /* U+2526 ┦ */ + makePackedLineTypes(LtLight, LtNone, LtHeavy, LtLight), /* U+2527 ┧ */ + makePackedLineTypes(LtHeavy, LtNone, LtHeavy, LtLight), /* U+2528 ┨ */ + makePackedLineTypes(LtHeavy, LtNone, LtLight, LtHeavy), /* U+2529 ┩ */ + makePackedLineTypes(LtLight, LtNone, LtHeavy, LtHeavy), /* U+252A ┪ */ + makePackedLineTypes(LtHeavy, LtNone, LtHeavy, LtHeavy), /* U+252B ┫ */ + makePackedLineTypes(LtNone, LtLight, LtLight, LtLight), /* U+252C ┬ */ + makePackedLineTypes(LtNone, LtLight, LtLight, LtHeavy), /* U+252D ┭ */ + makePackedLineTypes(LtNone, LtHeavy, LtLight, LtLight), /* U+252E ┮ */ + makePackedLineTypes(LtNone, LtHeavy, LtLight, LtHeavy), /* U+252F ┯ */ + makePackedLineTypes(LtNone, LtLight, LtHeavy, LtLight), /* U+2530 ┰ */ + makePackedLineTypes(LtNone, LtLight, LtHeavy, LtHeavy), /* U+2531 ┱ */ + makePackedLineTypes(LtNone, LtHeavy, LtHeavy, LtLight), /* U+2532 ┲ */ + makePackedLineTypes(LtNone, LtHeavy, LtHeavy, LtHeavy), /* U+2533 ┳ */ + makePackedLineTypes(LtLight, LtLight, LtNone, LtLight), /* U+2534 ┴ */ + makePackedLineTypes(LtLight, LtLight, LtNone, LtHeavy), /* U+2535 ┵ */ + makePackedLineTypes(LtLight, LtHeavy, LtNone, LtLight), /* U+2536 ┶ */ + makePackedLineTypes(LtLight, LtHeavy, LtNone, LtHeavy), /* U+2537 ┷ */ + makePackedLineTypes(LtHeavy, LtLight, LtNone, LtLight), /* U+2538 ┸ */ + makePackedLineTypes(LtHeavy, LtLight, LtNone, LtHeavy), /* U+2539 ┹ */ + makePackedLineTypes(LtHeavy, LtHeavy, LtNone, LtLight), /* U+253A ┺ */ + makePackedLineTypes(LtHeavy, LtHeavy, LtNone, LtHeavy), /* U+253B ┻ */ + makePackedLineTypes(LtLight, LtLight, LtLight, LtLight), /* U+253C ┼ */ + makePackedLineTypes(LtLight, LtLight, LtLight, LtHeavy), /* U+253D ┽ */ + makePackedLineTypes(LtLight, LtHeavy, LtLight, LtLight), /* U+253E ┾ */ + makePackedLineTypes(LtLight, LtHeavy, LtLight, LtHeavy), /* U+253F ┿ */ + makePackedLineTypes(LtHeavy, LtLight, LtLight, LtLight), /* U+2540 ╀ */ + makePackedLineTypes(LtLight, LtLight, LtHeavy, LtLight), /* U+2541 ╁ */ + makePackedLineTypes(LtHeavy, LtLight, LtHeavy, LtLight), /* U+2542 ╂ */ + makePackedLineTypes(LtHeavy, LtLight, LtLight, LtHeavy), /* U+2543 ╃ */ + makePackedLineTypes(LtHeavy, LtHeavy, LtLight, LtLight), /* U+2544 ╄ */ + makePackedLineTypes(LtLight, LtLight, LtHeavy, LtHeavy), /* U+2545 ╅ */ + makePackedLineTypes(LtLight, LtHeavy, LtHeavy, LtLight), /* U+2546 ╆ */ + makePackedLineTypes(LtHeavy, LtHeavy, LtLight, LtHeavy), /* U+2547 ╇ */ + makePackedLineTypes(LtLight, LtHeavy, LtHeavy, LtHeavy), /* U+2548 ╈ */ + makePackedLineTypes(LtHeavy, LtLight, LtHeavy, LtHeavy), /* U+2549 ╉ */ + makePackedLineTypes(LtHeavy, LtHeavy, LtHeavy, LtLight), /* U+254A ╊ */ + makePackedLineTypes(LtHeavy, LtHeavy, LtHeavy, LtHeavy), /* U+254B ╋ */ + 0, + 0, + 0, + 0, /* U+254C - U+254F */ + makePackedLineTypes(LtNone, LtDouble, LtNone, LtDouble), /* U+2550 ═ */ + makePackedLineTypes(LtDouble, LtNone, LtDouble, LtNone), /* U+2551 ║ */ + makePackedLineTypes(LtNone, LtDouble, LtLight, LtNone), /* U+2552 ╒ */ + makePackedLineTypes(LtNone, LtLight, LtDouble, LtNone), /* U+2553 ╓ */ + makePackedLineTypes(LtNone, LtDouble, LtDouble, LtNone), /* U+2554 ╔ */ + makePackedLineTypes(LtNone, LtNone, LtLight, LtDouble), /* U+2555 ╕ */ + makePackedLineTypes(LtNone, LtNone, LtDouble, LtLight), /* U+2556 ╖ */ + makePackedLineTypes(LtNone, LtNone, LtDouble, LtDouble), /* U+2557 ╗ */ + makePackedLineTypes(LtLight, LtDouble, LtNone, LtNone), /* U+2558 ╘ */ + makePackedLineTypes(LtDouble, LtLight, LtNone, LtNone), /* U+2559 ╙ */ + makePackedLineTypes(LtDouble, LtDouble, LtNone, LtNone), /* U+255A ╚ */ + makePackedLineTypes(LtLight, LtNone, LtNone, LtDouble), /* U+255B ╛ */ + makePackedLineTypes(LtDouble, LtNone, LtNone, LtLight), /* U+255C ╜ */ + makePackedLineTypes(LtDouble, LtNone, LtNone, LtDouble), /* U+255D ╝ */ + makePackedLineTypes(LtLight, LtDouble, LtLight, LtNone), /* U+255E ╞ */ + makePackedLineTypes(LtDouble, LtLight, LtDouble, LtNone), /* U+255F ╟ */ + makePackedLineTypes(LtDouble, LtDouble, LtDouble, LtNone), /* U+2560 ╠ */ + makePackedLineTypes(LtLight, LtNone, LtLight, LtDouble), /* U+2561 ╡ */ + makePackedLineTypes(LtDouble, LtNone, LtDouble, LtLight), /* U+2562 ╢ */ + makePackedLineTypes(LtDouble, LtNone, LtDouble, LtDouble), /* U+2563 ╣ */ + makePackedLineTypes(LtNone, LtDouble, LtLight, LtDouble), /* U+2564 ╤ */ + makePackedLineTypes(LtNone, LtLight, LtDouble, LtLight), /* U+2565 ╥ */ + makePackedLineTypes(LtNone, LtDouble, LtDouble, LtDouble), /* U+2566 ╦ */ + makePackedLineTypes(LtLight, LtDouble, LtNone, LtDouble), /* U+2567 ╧ */ + makePackedLineTypes(LtDouble, LtLight, LtNone, LtLight), /* U+2568 ╨ */ + makePackedLineTypes(LtDouble, LtDouble, LtNone, LtDouble), /* U+2569 ╩ */ + makePackedLineTypes(LtLight, LtDouble, LtLight, LtDouble), /* U+256A ╪ */ + makePackedLineTypes(LtDouble, LtLight, LtDouble, LtLight), /* U+256B ╫ */ makePackedLineTypes(LtDouble, LtDouble, LtDouble, LtDouble), /* U+256C ╬ */ - 0, 0, 0, 0, 0, 0, 0, /* U+256D - U+2573 */ - makePackedLineTypes(LtNone , LtNone , LtNone , LtLight ), /* U+2574 ╴ */ - makePackedLineTypes(LtLight , LtNone , LtNone , LtNone ), /* U+2575 ╵ */ - makePackedLineTypes(LtNone , LtLight , LtNone , LtNone ), /* U+2576 ╶ */ - makePackedLineTypes(LtNone , LtNone , LtLight , LtNone ), /* U+2577 ╷ */ - makePackedLineTypes(LtNone , LtNone , LtNone , LtHeavy ), /* U+2578 ╸ */ - makePackedLineTypes(LtHeavy , LtNone , LtNone , LtNone ), /* U+2579 ╹ */ - makePackedLineTypes(LtNone , LtHeavy , LtNone , LtNone ), /* U+257A ╺ */ - makePackedLineTypes(LtNone , LtNone , LtHeavy , LtNone ), /* U+257B ╻ */ - makePackedLineTypes(LtNone , LtHeavy , LtNone , LtLight ), /* U+257C ╼ */ - makePackedLineTypes(LtLight , LtNone , LtHeavy , LtNone ), /* U+257D ╽ */ - makePackedLineTypes(LtNone , LtLight , LtNone , LtHeavy ), /* U+257E ╾ */ - makePackedLineTypes(LtHeavy , LtNone , LtLight , LtNone ), /* U+257F ╿ */ + 0, + 0, + 0, + 0, + 0, + 0, + 0, /* U+256D - U+2573 */ + makePackedLineTypes(LtNone, LtNone, LtNone, LtLight), /* U+2574 ╴ */ + makePackedLineTypes(LtLight, LtNone, LtNone, LtNone), /* U+2575 ╵ */ + makePackedLineTypes(LtNone, LtLight, LtNone, LtNone), /* U+2576 ╶ */ + makePackedLineTypes(LtNone, LtNone, LtLight, LtNone), /* U+2577 ╷ */ + makePackedLineTypes(LtNone, LtNone, LtNone, LtHeavy), /* U+2578 ╸ */ + makePackedLineTypes(LtHeavy, LtNone, LtNone, LtNone), /* U+2579 ╹ */ + makePackedLineTypes(LtNone, LtHeavy, LtNone, LtNone), /* U+257A ╺ */ + makePackedLineTypes(LtNone, LtNone, LtHeavy, LtNone), /* U+257B ╻ */ + makePackedLineTypes(LtNone, LtHeavy, LtNone, LtLight), /* U+257C ╼ */ + makePackedLineTypes(LtLight, LtNone, LtHeavy, LtNone), /* U+257D ╽ */ + makePackedLineTypes(LtNone, LtLight, LtNone, LtHeavy), /* U+257E ╾ */ + makePackedLineTypes(LtHeavy, LtNone, LtLight, LtNone), /* U+257F ╿ */ }; - - // Bitwise rotate left -template +template inline static T rotateBitsLeft(T value, quint8 amount) { - static_assert (std::is_unsigned(), "T must be unsigned type"); + static_assert(std::is_unsigned(), "T must be unsigned type"); Q_ASSERT(amount < sizeof(value) * 8); return value << amount | value >> (sizeof(value) * 8 - amount); } @@ -162,40 +172,37 @@ inline static const QPen pen(const QPainter &paint, uint lineWidth) return QPen(paint.pen().brush(), lineWidth, Qt::SolidLine, Qt::FlatCap, Qt::MiterJoin); } - - static inline uint lineWidth(uint fontWidth, bool heavy, bool bold) { static const qreal LightWidthToFontWidthRatio = 1.0 / 6.5; static const qreal HeavyHalfExtraToLightRatio = 1.0 / 3.0; - static const qreal BoldCoefficient = 1.5; + static const qreal BoldCoefficient = 1.5; // ▄▄▄▄▄▄▄ } heavyHalfExtraWidth ⎫ // ██████████████ } lightWidth ⎬ heavyWidth // ▀▀▀▀▀▀▀ ⎭ // light heavy - const qreal baseWidth = fontWidth * LightWidthToFontWidthRatio; - const qreal boldCoeff = bold ? BoldCoefficient : 1.0; + const qreal baseWidth = fontWidth * LightWidthToFontWidthRatio; + const qreal boldCoeff = bold ? BoldCoefficient : 1.0; // Unless font size is too small, make bold lines at least 1px wider than regular lines - const qreal minWidth = bold && fontWidth >= 7 ? baseWidth + 1.0 : 1.0; - const uint lightWidth = qRound(qMax(baseWidth * boldCoeff, minWidth)); - const uint heavyHalfExtraWidth = qRound(qMax(lightWidth * HeavyHalfExtraToLightRatio, 1.0)); + const qreal minWidth = bold && fontWidth >= 7 ? baseWidth + 1.0 : 1.0; + const uint lightWidth = qRound(qMax(baseWidth * boldCoeff, minWidth)); + const uint heavyHalfExtraWidth = qRound(qMax(lightWidth * HeavyHalfExtraToLightRatio, 1.0)); return heavy ? lightWidth + 2 * heavyHalfExtraWidth : lightWidth; } // Draws characters composed of straight solid lines -static bool drawBasicLineCharacter(QPainter& paint, int x, int y, int w, int h, uchar code, - bool bold) +static bool drawBasicLineCharacter(QPainter &paint, int x, int y, int w, int h, uchar code, bool bold) { quint8 packedLineTypes = code >= sizeof(PackedLineTypesLut) ? 0 : PackedLineTypesLut[code]; if (packedLineTypes == 0) { return false; } - const uint lightLineWidth = lineWidth(w, false, bold); - const uint heavyLineWidth = lineWidth(w, true, bold); + const uint lightLineWidth = lineWidth(w, false, bold); + const uint heavyLineWidth = lineWidth(w, true, bold); // Distance from double line's parallel axis to each line's parallel axis const uint doubleLinesDistance = lightLineWidth; @@ -206,25 +213,25 @@ static bool drawBasicLineCharacter(QPainter& paint, int x, int y, int w, int h, // Pixel aligned center point const QPointF center = { - x + int(w/2) + 0.5 * (lightLineWidth % 2), - y + int(h/2) + 0.5 * (lightLineWidth % 2), + x + int(w / 2) + 0.5 * (lightLineWidth % 2), + y + int(h / 2) + 0.5 * (lightLineWidth % 2), }; // Lines starting points, on the cell edges const QPointF origin[] = { - QPointF(center.x(), y ), - QPointF(x+w , center.y() ), - QPointF(center.x(), y+h ), - QPointF(x , center.y() ), + QPointF(center.x(), y), + QPointF(x + w, center.y()), + QPointF(center.x(), y + h), + QPointF(x, center.y()), }; // Unit vectors with directions from center to the line's origin point static const QPointF dir[] = {{0, -1}, {1, 0}, {0, 1}, {-1, 0}}; - const auto removeLineType = [&packedLineTypes](quint8 lineId)->void { + const auto removeLineType = [&packedLineTypes](quint8 lineId) -> void { lineId = LinesNum - 1 - lineId % LinesNum; packedLineTypes &= ~(3 << (2 * lineId)); }; - const auto getLineType = [&packedLineTypes](quint8 lineId)->LineType { + const auto getLineType = [&packedLineTypes](quint8 lineId) -> LineType { lineId = LinesNum - 1 - lineId % LinesNum; return LineType(packedLineTypes >> 2 * lineId & 3); }; @@ -232,7 +239,7 @@ static bool drawBasicLineCharacter(QPainter& paint, int x, int y, int w, int h, QPainterPath lightPath; // PainterPath for light lines (Painter Path Light) QPainterPath heavyPath; // PainterPath for heavy lines (Painter Path Heavy) // Returns ppl or pph depending on line type - const auto pathForLine = [&](quint8 lineId) -> QPainterPath& { + const auto pathForLine = [&](quint8 lineId) -> QPainterPath & { Q_ASSERT(getLineType(lineId) != LtNone); return getLineType(lineId) == LtHeavy ? heavyPath : lightPath; }; @@ -240,10 +247,9 @@ static bool drawBasicLineCharacter(QPainter& paint, int x, int y, int w, int h, // Process all single up-down/left-right lines for every character that has them. Doing it here // reduces amount of combinations below. // Fully draws: ╋ ╂ ┃ ┿ ┼ │ ━ ─ - for (unsigned int topIndex = 0; topIndex < LinesNum/2; topIndex++) { + for (unsigned int topIndex = 0; topIndex < LinesNum / 2; topIndex++) { unsigned iB = (topIndex + 2) % LinesNum; - const bool isSingleLine = (getLineType(topIndex) == LtLight - || getLineType(topIndex) == LtHeavy); + const bool isSingleLine = (getLineType(topIndex) == LtLight || getLineType(topIndex) == LtHeavy); if (isSingleLine && getLineType(topIndex) == getLineType(iB)) { pathForLine(topIndex).moveTo(origin[topIndex]); pathForLine(topIndex).lineTo(origin[iB]); @@ -265,9 +271,9 @@ static bool drawBasicLineCharacter(QPainter& paint, int x, int y, int w, int h, basePackedLineTypes = rotatedPackedLineTypes; } } - uint rightIndex = (topIndex + 1) % LinesNum; + uint rightIndex = (topIndex + 1) % LinesNum; uint bottomIndex = (topIndex + 2) % LinesNum; - uint leftIndex = (topIndex + 3) % LinesNum; + uint leftIndex = (topIndex + 3) % LinesNum; // Common paths const auto drawDoubleUpRightShorterLine = [&](quint8 top, quint8 right) { // ╚ @@ -282,38 +288,38 @@ static bool drawBasicLineCharacter(QPainter& paint, int x, int y, int w, int h, }; switch (basePackedLineTypes) { - case makePackedLineTypes(LtHeavy , LtNone , LtLight , LtNone ): // ╿ ; ╼ ╽ ╾ ╊ ╇ ╉ ╈ ╀ ┾ ╁ ┽ + case makePackedLineTypes(LtHeavy, LtNone, LtLight, LtNone): // ╿ ; ╼ ╽ ╾ ╊ ╇ ╉ ╈ ╀ ┾ ╁ ┽ lightPath.moveTo(origin[bottomIndex]); lightPath.lineTo(center + dir[topIndex] * lightLineWidth / 2.0); Q_FALLTHROUGH(); - case makePackedLineTypes(LtHeavy , LtNone , LtNone , LtNone ): // ╹ ; ╺ ╻ ╸ ┻ ┣ ┳ ┫ ┸ ┝ ┰ ┥ - case makePackedLineTypes(LtLight , LtNone , LtNone , LtNone ): // ╵ ; ╶ ╷ ╴ ┷ ┠ ┯ ┨ ┴ ├ ┬ ┤ + case makePackedLineTypes(LtHeavy, LtNone, LtNone, LtNone): // ╹ ; ╺ ╻ ╸ ┻ ┣ ┳ ┫ ┸ ┝ ┰ ┥ + case makePackedLineTypes(LtLight, LtNone, LtNone, LtNone): // ╵ ; ╶ ╷ ╴ ┷ ┠ ┯ ┨ ┴ ├ ┬ ┤ pathForLine(topIndex).moveTo(origin[topIndex]); pathForLine(topIndex).lineTo(center); break; - case makePackedLineTypes(LtHeavy , LtHeavy , LtLight , LtLight ): // ╄ ; ╃ ╆ ╅ + case makePackedLineTypes(LtHeavy, LtHeavy, LtLight, LtLight): // ╄ ; ╃ ╆ ╅ drawUpRight(bottomIndex, leftIndex); Q_FALLTHROUGH(); - case makePackedLineTypes(LtHeavy , LtHeavy , LtNone , LtNone ): // ┗ ; ┛ ┏ ┓ - case makePackedLineTypes(LtLight , LtLight , LtNone , LtNone ): // └ ; ┘ ┌ ┐ + case makePackedLineTypes(LtHeavy, LtHeavy, LtNone, LtNone): // ┗ ; ┛ ┏ ┓ + case makePackedLineTypes(LtLight, LtLight, LtNone, LtNone): // └ ; ┘ ┌ ┐ drawUpRight(topIndex, rightIndex); break; - case makePackedLineTypes(LtHeavy , LtLight , LtNone , LtNone ): // ┖ ; ┙ ┍ ┒ + case makePackedLineTypes(LtHeavy, LtLight, LtNone, LtNone): // ┖ ; ┙ ┍ ┒ qSwap(leftIndex, rightIndex); Q_FALLTHROUGH(); - case makePackedLineTypes(LtHeavy , LtNone , LtNone , LtLight ): // ┚ ; ┕ ┎ ┑ + case makePackedLineTypes(LtHeavy, LtNone, LtNone, LtLight): // ┚ ; ┕ ┎ ┑ lightPath.moveTo(origin[leftIndex]); lightPath.lineTo(center); heavyPath.moveTo(origin[topIndex]); heavyPath.lineTo(center + dir[bottomIndex] * lightLineWidth / 2.0); break; - case makePackedLineTypes(LtLight , LtDouble, LtNone , LtNone ): // ╘ ; ╜ ╓ ╕ + case makePackedLineTypes(LtLight, LtDouble, LtNone, LtNone): // ╘ ; ╜ ╓ ╕ qSwap(leftIndex, rightIndex); Q_FALLTHROUGH(); - case makePackedLineTypes(LtLight , LtNone , LtNone , LtDouble): // ╛ ; ╙ ╒ ╖ + case makePackedLineTypes(LtLight, LtNone, LtNone, LtDouble): // ╛ ; ╙ ╒ ╖ lightPath.moveTo(origin[topIndex]); lightPath.lineTo(center + dir[bottomIndex] * doubleLinesDistance); lightPath.lineTo(origin[leftIndex] + dir[bottomIndex] * doubleLinesDistance); @@ -321,39 +327,39 @@ static bool drawBasicLineCharacter(QPainter& paint, int x, int y, int w, int h, lightPath.lineTo(center - dir[bottomIndex] * doubleLinesDistance); break; - case makePackedLineTypes(LtHeavy , LtHeavy , LtLight , LtNone ): // ┡ ; ┹ ┪ ┲ + case makePackedLineTypes(LtHeavy, LtHeavy, LtLight, LtNone): // ┡ ; ┹ ┪ ┲ qSwap(leftIndex, bottomIndex); qSwap(rightIndex, topIndex); Q_FALLTHROUGH(); - case makePackedLineTypes(LtHeavy , LtHeavy , LtNone , LtLight ): // ┺ ; ┩ ┢ ┱ + case makePackedLineTypes(LtHeavy, LtHeavy, LtNone, LtLight): // ┺ ; ┩ ┢ ┱ drawUpRight(topIndex, rightIndex); lightPath.moveTo(origin[leftIndex]); lightPath.lineTo(center); break; - case makePackedLineTypes(LtHeavy , LtLight , LtLight , LtNone ): // ┞ ; ┵ ┧ ┮ + case makePackedLineTypes(LtHeavy, LtLight, LtLight, LtNone): // ┞ ; ┵ ┧ ┮ qSwap(leftIndex, rightIndex); Q_FALLTHROUGH(); - case makePackedLineTypes(LtHeavy , LtNone , LtLight , LtLight ): // ┦ ; ┶ ┟ ┭ + case makePackedLineTypes(LtHeavy, LtNone, LtLight, LtLight): // ┦ ; ┶ ┟ ┭ heavyPath.moveTo(origin[topIndex]); heavyPath.lineTo(center + dir[bottomIndex] * lightLineWidth / 2.0); drawUpRight(bottomIndex, leftIndex); break; - case makePackedLineTypes(LtLight , LtDouble, LtNone , LtDouble): // ╧ ; ╟ ╢ ╤ + case makePackedLineTypes(LtLight, LtDouble, LtNone, LtDouble): // ╧ ; ╟ ╢ ╤ lightPath.moveTo(origin[topIndex]); lightPath.lineTo(center - dir[bottomIndex] * doubleLinesDistance); qSwap(leftIndex, bottomIndex); qSwap(rightIndex, topIndex); Q_FALLTHROUGH(); - case makePackedLineTypes(LtDouble, LtNone , LtDouble, LtNone ): // ║ ; ╫ ═ ╪ + case makePackedLineTypes(LtDouble, LtNone, LtDouble, LtNone): // ║ ; ╫ ═ ╪ lightPath.moveTo(origin[topIndex] + dir[leftIndex] * doubleLinesDistance); lightPath.lineTo(origin[bottomIndex] + dir[leftIndex] * doubleLinesDistance); lightPath.moveTo(origin[topIndex] + dir[rightIndex] * doubleLinesDistance); lightPath.lineTo(origin[bottomIndex] + dir[rightIndex] * doubleLinesDistance); break; - case makePackedLineTypes(LtDouble, LtNone , LtNone , LtNone ): // ╨ ; ╞ ╥ ╡ + case makePackedLineTypes(LtDouble, LtNone, LtNone, LtNone): // ╨ ; ╞ ╥ ╡ lightPath.moveTo(origin[topIndex] + dir[leftIndex] * doubleLinesDistance); lightPath.lineTo(center + dir[leftIndex] * doubleLinesDistance); lightPath.moveTo(origin[topIndex] + dir[rightIndex] * doubleLinesDistance); @@ -367,14 +373,14 @@ static bool drawBasicLineCharacter(QPainter& paint, int x, int y, int w, int h, drawDoubleUpRightShorterLine(bottomIndex, leftIndex); break; - case makePackedLineTypes(LtDouble, LtDouble, LtDouble, LtNone ): // ╠ ; ╩ ╣ ╦ + case makePackedLineTypes(LtDouble, LtDouble, LtDouble, LtNone): // ╠ ; ╩ ╣ ╦ lightPath.moveTo(origin[topIndex] + dir[leftIndex] * doubleLinesDistance); lightPath.lineTo(origin[bottomIndex] + dir[leftIndex] * doubleLinesDistance); drawDoubleUpRightShorterLine(topIndex, rightIndex); drawDoubleUpRightShorterLine(bottomIndex, rightIndex); break; - case makePackedLineTypes(LtDouble, LtDouble, LtNone , LtNone ): // ╚ ; ╝ ╔ ╗ + case makePackedLineTypes(LtDouble, LtDouble, LtNone, LtNone): // ╚ ; ╝ ╔ ╗ lightPath.moveTo(origin[topIndex] + dir[leftIndex] * doubleLinesDistance); lightPath.lineTo(center + (dir[leftIndex] + dir[bottomIndex]) * doubleLinesDistance); lightPath.lineTo(origin[rightIndex] + dir[bottomIndex] * doubleLinesDistance); @@ -393,8 +399,7 @@ static bool drawBasicLineCharacter(QPainter& paint, int x, int y, int w, int h, return true; } -static inline bool drawDashedLineCharacter(QPainter &paint, int x, int y, int w, int h, uchar code, - bool bold) +static inline bool drawDashedLineCharacter(QPainter &paint, int x, int y, int w, int h, uchar code, bool bold) { if (!((0x04 <= code && code <= 0x0B) || (0x4C <= code && code <= 0x4F))) { return false; @@ -408,54 +413,76 @@ static inline bool drawDashedLineCharacter(QPainter &paint, int x, int y, int w, // Pixel aligned center point const QPointF center = { - int(x + w/2.0) + 0.5 * (lightLineWidth%2), - int(y + h/2.0) + 0.5 * (lightLineWidth%2), + int(x + w / 2.0) + 0.5 * (lightLineWidth % 2), + int(y + h / 2.0) + 0.5 * (lightLineWidth % 2), }; - const qreal halfGapH = qMax(w / 20.0, 0.5); - const qreal halfGapV = qMax(h / 26.0, 0.5); + const qreal halfGapH = qMax(w / 20.0, 0.5); + const qreal halfGapV = qMax(h / 26.0, 0.5); // For some reason vertical double dash has bigger gap const qreal halfGapDDV = qMax(h / 14.0, 0.5); static const int LinesNumMax = 4; - enum Orientation {Horizontal, Vertical}; + enum Orientation { Horizontal, Vertical, }; struct { - int linesNum; + int linesNum; Orientation orientation; - QPen pen; - qreal halfGap; + QPen pen; + qreal halfGap; } lineProps; switch (code) { - case 0x4C: lineProps = {2, Horizontal, lightPen, halfGapH }; break; // ╌ - case 0x4D: lineProps = {2, Horizontal, heavyPen, halfGapH }; break; // ╍ - case 0x4E: lineProps = {2, Vertical , lightPen, halfGapDDV}; break; // ╎ - case 0x4F: lineProps = {2, Vertical , heavyPen, halfGapDDV}; break; // ╏ - case 0x04: lineProps = {3, Horizontal, lightPen, halfGapH }; break; // ┄ - case 0x05: lineProps = {3, Horizontal, heavyPen, halfGapH }; break; // ┅ - case 0x06: lineProps = {3, Vertical , lightPen, halfGapV }; break; // ┆ - case 0x07: lineProps = {3, Vertical , heavyPen, halfGapV }; break; // ┇ - case 0x08: lineProps = {4, Horizontal, lightPen, halfGapH }; break; // ┈ - case 0x09: lineProps = {4, Horizontal, heavyPen, halfGapH }; break; // ┉ - case 0x0A: lineProps = {4, Vertical , lightPen, halfGapV }; break; // ┊ - case 0x0B: lineProps = {4, Vertical , heavyPen, halfGapV }; break; // ┋ + case 0x4C: + lineProps = {2, Horizontal, lightPen, halfGapH}; + break; // ╌ + case 0x4D: + lineProps = {2, Horizontal, heavyPen, halfGapH}; + break; // ╍ + case 0x4E: + lineProps = {2, Vertical, lightPen, halfGapDDV}; + break; // ╎ + case 0x4F: + lineProps = {2, Vertical, heavyPen, halfGapDDV}; + break; // ╏ + case 0x04: + lineProps = {3, Horizontal, lightPen, halfGapH}; + break; // ┄ + case 0x05: + lineProps = {3, Horizontal, heavyPen, halfGapH}; + break; // ┅ + case 0x06: + lineProps = {3, Vertical, lightPen, halfGapV}; + break; // ┆ + case 0x07: + lineProps = {3, Vertical, heavyPen, halfGapV}; + break; // ┇ + case 0x08: + lineProps = {4, Horizontal, lightPen, halfGapH}; + break; // ┈ + case 0x09: + lineProps = {4, Horizontal, heavyPen, halfGapH}; + break; // ┉ + case 0x0A: + lineProps = {4, Vertical, lightPen, halfGapV}; + break; // ┊ + case 0x0B: + lineProps = {4, Vertical, heavyPen, halfGapV}; + break; // ┋ } Q_ASSERT(lineProps.linesNum <= LinesNumMax); const int size = (lineProps.orientation == Horizontal ? w : h); - const int pos = (lineProps.orientation == Horizontal ? x : y); + const int pos = (lineProps.orientation == Horizontal ? x : y); QLineF lines[LinesNumMax]; for (int i = 0; i < lineProps.linesNum; i++) { - const qreal start = pos + qreal(size * (i )) / lineProps.linesNum; - const qreal end = pos + qreal(size * (i+1)) / lineProps.linesNum; + const qreal start = pos + qreal(size * (i)) / lineProps.linesNum; + const qreal end = pos + qreal(size * (i + 1)) / lineProps.linesNum; if (lineProps.orientation == Horizontal) { - lines[i] = QLineF{start + lineProps.halfGap, center.y(), - end - lineProps.halfGap, center.y()}; + lines[i] = QLineF{start + lineProps.halfGap, center.y(), end - lineProps.halfGap, center.y()}; } else { - lines[i] = QLineF{center.x(), start + lineProps.halfGap, - center.x(), end - lineProps.halfGap}; + lines[i] = QLineF{center.x(), start + lineProps.halfGap, center.x(), end - lineProps.halfGap}; } } @@ -468,8 +495,7 @@ static inline bool drawDashedLineCharacter(QPainter &paint, int x, int y, int w, return true; } -static inline bool drawRoundedCornerLineCharacter(QPainter &paint, int x, int y, int w, int h, - uchar code, bool bold) +static inline bool drawRoundedCornerLineCharacter(QPainter &paint, int x, int y, int w, int h, uchar code, bool bold) { if (!(0x6D <= code && code <= 0x70)) { return false; @@ -480,8 +506,8 @@ static inline bool drawRoundedCornerLineCharacter(QPainter &paint, int x, int y, // Pixel aligned center point const QPointF center = { - int(x + w/2.0) + 0.5 * (lightLineWidth%2), - int(y + h/2.0) + 0.5 * (lightLineWidth%2), + int(x + w / 2.0) + 0.5 * (lightLineWidth % 2), + int(y + h / 2.0) + 0.5 * (lightLineWidth % 2), }; const int r = w * 3 / 8; @@ -518,8 +544,7 @@ static inline bool drawRoundedCornerLineCharacter(QPainter &paint, int x, int y, return true; } -static inline bool drawDiagonalLineCharacter(QPainter &paint, int x, int y, int w, int h, - uchar code, bool bold) +static inline bool drawDiagonalLineCharacter(QPainter &paint, int x, int y, int w, int h, uchar code, bool bold) { if (!(0x71 <= code && code <= 0x73)) { return false; @@ -529,8 +554,8 @@ static inline bool drawDiagonalLineCharacter(QPainter &paint, int x, int y, int const auto lightPen = pen(paint, lightLineWidth); const QLineF lines[] = { - QLineF(x+w, y, x , y+h), // '/' - QLineF(x , y, x+w, y+h), // '\' + QLineF(x + w, y, x, y + h), // '/' + QLineF(x, y, x + w, y + h), // '\' }; const auto origPen = paint.pen(); @@ -552,8 +577,7 @@ static inline bool drawDiagonalLineCharacter(QPainter &paint, int x, int y, int return true; } -static inline bool drawBlockCharacter(QPainter &paint, int x, int y, int w, int h, uchar code, - bool bold) +static inline bool drawBlockCharacter(QPainter &paint, int x, int y, int w, int h, uchar code, bool bold) { Q_UNUSED(bold) @@ -561,8 +585,8 @@ static inline bool drawBlockCharacter(QPainter &paint, int x, int y, int w, int // Center point const QPointF center = { - x + w/2.0, - y + h/2.0, + x + w / 2.0, + y + h / 2.0, }; // Default rect fills entire cell @@ -586,10 +610,10 @@ static inline bool drawBlockCharacter(QPainter &paint, int x, int y, int w, int // Combinations of quarter squares // LEFT ONE EIGHTH BLOCK to QUADRANT UPPER RIGHT AND LOWER LEFT AND LOWER RIGHT if (code >= 0x96 && code <= 0x9F) { - const QRectF upperLeft (x , y , w/2.0, h/2.0); - const QRectF upperRight(center.x(), y , w/2.0, h/2.0); - const QRectF lowerLeft (x , center.y(), w/2.0, h/2.0); - const QRectF lowerRight(center.x(), center.y(), w/2.0, h/2.0); + const QRectF upperLeft(x, y, w / 2.0, h / 2.0); + const QRectF upperRight(center.x(), y, w / 2.0, h / 2.0); + const QRectF lowerLeft(x, center.y(), w / 2.0, h / 2.0); + const QRectF lowerRight(center.x(), center.y(), w / 2.0, h / 2.0); QPainterPath path; @@ -644,18 +668,18 @@ static inline bool drawBlockCharacter(QPainter &paint, int x, int y, int w, int QBrush mediumShade; QBrush darkShade; if (paint.testRenderHint(QPainter::Antialiasing)) { - lightShade = QColor(color.red(), color.green(), color.blue(), 64); + lightShade = QColor(color.red(), color.green(), color.blue(), 64); mediumShade = QColor(color.red(), color.green(), color.blue(), 128); - darkShade = QColor(color.red(), color.green(), color.blue(), 192); + darkShade = QColor(color.red(), color.green(), color.blue(), 192); } else { - lightShade = QBrush(color, Qt::Dense6Pattern); + lightShade = QBrush(color, Qt::Dense6Pattern); mediumShade = QBrush(color, Qt::Dense4Pattern); - darkShade = QBrush(color, Qt::Dense2Pattern); + darkShade = QBrush(color, Qt::Dense2Pattern); } // And the random stuff switch (code) { case 0x80: // Top half block - rect.setHeight(h/2.0); + rect.setHeight(h / 2.0); paint.fillRect(rect, color); return true; case 0x90: // Right half block @@ -663,15 +687,15 @@ static inline bool drawBlockCharacter(QPainter &paint, int x, int y, int w, int paint.fillRect(rect, color); return true; case 0x94: // Top one eighth block - rect.setHeight(h/8.0); + rect.setHeight(h / 8.0); paint.fillRect(rect, color); return true; case 0x95: { // Right one eighth block - const qreal width = 7 * w / 8.0; - rect.moveLeft(x + width); - paint.fillRect(rect, color); - return true; - } + const qreal width = 7 * w / 8.0; + rect.moveLeft(x + width); + paint.fillRect(rect, color); + return true; + } case 0x91: // Light shade paint.fillRect(rect, lightShade); return true; @@ -698,11 +722,9 @@ void draw(QPainter &paint, const QRect &cellRect, const QChar &chr, bool bold) int h = cellRect.height(); // Each function below returns true when it has drawn the character, false otherwise. - drawBasicLineCharacter(paint, x, y, w, h, code, bold) - || drawDashedLineCharacter(paint, x, y, w, h, code, bold) - || drawRoundedCornerLineCharacter(paint, x, y, w, h, code, bold) - || drawDiagonalLineCharacter(paint, x, y, w, h, code, bold) - || drawBlockCharacter(paint, x, y, w, h, code, bold); + drawBasicLineCharacter(paint, x, y, w, h, code, bold) || drawDashedLineCharacter(paint, x, y, w, h, code, bold) + || drawRoundedCornerLineCharacter(paint, x, y, w, h, code, bold) || drawDiagonalLineCharacter(paint, x, y, w, h, code, bold) + || drawBlockCharacter(paint, x, y, w, h, code, bold); } } // namespace LineBlockCharacters diff --git a/src/characters/LineBlockCharacters.h b/src/characters/LineBlockCharacters.h index 6cc4e6ba7..1726ccf2b 100644 --- a/src/characters/LineBlockCharacters.h +++ b/src/characters/LineBlockCharacters.h @@ -10,31 +10,32 @@ // Qt #include -namespace Konsole { - +namespace Konsole +{ /** * Helper functions for drawing characters from "Box Drawing" and "Block Elements" Unicode blocks. */ -namespace LineBlockCharacters { +namespace LineBlockCharacters +{ +/** + * Returns true if the character can be drawn by draw() function. + * + * @param ucs4cp Character to test's UCS4 code point + */ +inline static bool canDraw(uint ucs4cp) +{ + return (0x2500 <= ucs4cp && ucs4cp <= 0x259F); +} - /** - * Returns true if the character can be drawn by draw() function. - * - * @param ucs4cp Character to test's UCS4 code point - */ - inline static bool canDraw(uint ucs4cp) { - return (0x2500 <= ucs4cp && ucs4cp <= 0x259F); - } - - /** - * Draws character. - * - * @param paint QPainter to draw on - * @param cellRect Rectangle to draw in - * @param chr Character to be drawn - * @param bold Whether the character should be boldface - */ - void draw(QPainter &paint, const QRect &cellRect, const QChar &chr, bool bold); +/** + * Draws character. + * + * @param paint QPainter to draw on + * @param cellRect Rectangle to draw in + * @param chr Character to be drawn + * @param bold Whether the character should be boldface + */ +void draw(QPainter &paint, const QRect &cellRect, const QChar &chr, bool bold); } // namespace LineBlockCharacters } // namespace Konsole diff --git a/src/colorscheme/ColorScheme.cpp b/src/colorscheme/ColorScheme.cpp index 9f70c1d21..cf8a96c2b 100644 --- a/src/colorscheme/ColorScheme.cpp +++ b/src/colorscheme/ColorScheme.cpp @@ -8,16 +8,16 @@ // Own #include "ColorScheme.h" -#include "hsluv.h" #include "RandomizationRange.h" +#include "hsluv.h" // Qt #include // KDE #include -#include #include +#include // STL #include @@ -25,18 +25,19 @@ // Konsole #include "colorschemedebug.h" -namespace { +namespace +{ const int FGCOLOR_INDEX = 0; const int BGCOLOR_INDEX = 1; -const char RandomHueRangeKey[] = "RandomHueRange"; -const char RandomSaturationRangeKey[] = "RandomSaturationRange"; -const char RandomLightnessRangeKey[] = "RandomLightnessRange"; +const char RandomHueRangeKey[] = "RandomHueRange"; +const char RandomSaturationRangeKey[] = "RandomSaturationRange"; +const char RandomLightnessRangeKey[] = "RandomLightnessRange"; const char EnableColorRandomizationKey[] = "ColorRandomization"; -const double MaxHue = 360.0; +const double MaxHue = 360.0; const double MaxSaturation = 100.0; -const double MaxLightness = 100.0; +const double MaxLightness = 100.0; } using namespace Konsole; @@ -44,106 +45,100 @@ using namespace Konsole; // 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. -const QColor ColorScheme::defaultTable[TABLE_COLORS] = { - QColor(0x00, 0x00, 0x00), // Dfore - QColor(0xFF, 0xFF, 0xFF), // Dback - QColor(0x00, 0x00, 0x00), // Black - QColor(0xB2, 0x18, 0x18), // Red - QColor(0x18, 0xB2, 0x18), // Green - QColor(0xB2, 0x68, 0x18), // Yellow - QColor(0x18, 0x18, 0xB2), // Blue - QColor(0xB2, 0x18, 0xB2), // Magenta - QColor(0x18, 0xB2, 0xB2), // Cyan - QColor(0xB2, 0xB2, 0xB2), // White - // intensive versions - QColor(0x00, 0x00, 0x00), - QColor(0xFF, 0xFF, 0xFF), - QColor(0x68, 0x68, 0x68), - QColor(0xFF, 0x54, 0x54), - QColor(0x54, 0xFF, 0x54), - QColor(0xFF, 0xFF, 0x54), - QColor(0x54, 0x54, 0xFF), - QColor(0xFF, 0x54, 0xFF), - QColor(0x54, 0xFF, 0xFF), - QColor(0xFF, 0xFF, 0xFF), - // Here are faint intensities, which may not be good. - // faint versions - QColor(0x00, 0x00, 0x00), - QColor(0xFF, 0xFF, 0xFF), - QColor(0x00, 0x00, 0x00), - QColor(0x65, 0x00, 0x00), - QColor(0x00, 0x65, 0x00), - QColor(0x65, 0x5E, 0x00), - QColor(0x00, 0x00, 0x65), - QColor(0x65, 0x00, 0x65), - QColor(0x00, 0x65, 0x65), - QColor(0x65, 0x65, 0x65) -}; +const QColor ColorScheme::defaultTable[TABLE_COLORS] = {QColor(0x00, 0x00, 0x00), // Dfore + QColor(0xFF, 0xFF, 0xFF), // Dback + QColor(0x00, 0x00, 0x00), // Black + QColor(0xB2, 0x18, 0x18), // Red + QColor(0x18, 0xB2, 0x18), // Green + QColor(0xB2, 0x68, 0x18), // Yellow + QColor(0x18, 0x18, 0xB2), // Blue + QColor(0xB2, 0x18, 0xB2), // Magenta + QColor(0x18, 0xB2, 0xB2), // Cyan + QColor(0xB2, 0xB2, 0xB2), // White + // intensive versions + QColor(0x00, 0x00, 0x00), + QColor(0xFF, 0xFF, 0xFF), + QColor(0x68, 0x68, 0x68), + QColor(0xFF, 0x54, 0x54), + QColor(0x54, 0xFF, 0x54), + QColor(0xFF, 0xFF, 0x54), + QColor(0x54, 0x54, 0xFF), + QColor(0xFF, 0x54, 0xFF), + QColor(0x54, 0xFF, 0xFF), + QColor(0xFF, 0xFF, 0xFF), + // Here are faint intensities, which may not be good. + // faint versions + QColor(0x00, 0x00, 0x00), + QColor(0xFF, 0xFF, 0xFF), + QColor(0x00, 0x00, 0x00), + QColor(0x65, 0x00, 0x00), + QColor(0x00, 0x65, 0x00), + QColor(0x65, 0x5E, 0x00), + QColor(0x00, 0x00, 0x65), + QColor(0x65, 0x00, 0x65), + QColor(0x00, 0x65, 0x65), + QColor(0x65, 0x65, 0x65)}; -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", - "ForegroundFaint", - "BackgroundFaint", - "Color0Faint", - "Color1Faint", - "Color2Faint", - "Color3Faint", - "Color4Faint", - "Color5Faint", - "Color6Faint", - "Color7Faint" -}; -const char * const ColorScheme::translatedColorNames[TABLE_COLORS] = { - I18N_NOOP2("@item:intable palette", "Foreground"), - I18N_NOOP2("@item:intable palette", "Background"), - I18N_NOOP2("@item:intable palette", "Color 1"), - I18N_NOOP2("@item:intable palette", "Color 2"), - I18N_NOOP2("@item:intable palette", "Color 3"), - I18N_NOOP2("@item:intable palette", "Color 4"), - I18N_NOOP2("@item:intable palette", "Color 5"), - I18N_NOOP2("@item:intable palette", "Color 6"), - I18N_NOOP2("@item:intable palette", "Color 7"), - I18N_NOOP2("@item:intable palette", "Color 8"), - I18N_NOOP2("@item:intable palette", "Foreground (Intense)"), - I18N_NOOP2("@item:intable palette", "Background (Intense)"), - I18N_NOOP2("@item:intable palette", "Color 1 (Intense)"), - I18N_NOOP2("@item:intable palette", "Color 2 (Intense)"), - I18N_NOOP2("@item:intable palette", "Color 3 (Intense)"), - I18N_NOOP2("@item:intable palette", "Color 4 (Intense)"), - I18N_NOOP2("@item:intable palette", "Color 5 (Intense)"), - I18N_NOOP2("@item:intable palette", "Color 6 (Intense)"), - I18N_NOOP2("@item:intable palette", "Color 7 (Intense)"), - I18N_NOOP2("@item:intable palette", "Color 8 (Intense)"), - I18N_NOOP2("@item:intable palette", "Foreground (Faint)"), - I18N_NOOP2("@item:intable palette", "Background (Faint)"), - I18N_NOOP2("@item:intable palette", "Color 1 (Faint)"), - I18N_NOOP2("@item:intable palette", "Color 2 (Faint)"), - I18N_NOOP2("@item:intable palette", "Color 3 (Faint)"), - I18N_NOOP2("@item:intable palette", "Color 4 (Faint)"), - I18N_NOOP2("@item:intable palette", "Color 5 (Faint)"), - I18N_NOOP2("@item:intable palette", "Color 6 (Faint)"), - I18N_NOOP2("@item:intable palette", "Color 7 (Faint)"), - I18N_NOOP2("@item:intable palette", "Color 8 (Faint)") -}; +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", + "ForegroundFaint", + "BackgroundFaint", + "Color0Faint", + "Color1Faint", + "Color2Faint", + "Color3Faint", + "Color4Faint", + "Color5Faint", + "Color6Faint", + "Color7Faint"}; +const char *const ColorScheme::translatedColorNames[TABLE_COLORS] = {I18N_NOOP2("@item:intable palette", "Foreground"), + I18N_NOOP2("@item:intable palette", "Background"), + I18N_NOOP2("@item:intable palette", "Color 1"), + I18N_NOOP2("@item:intable palette", "Color 2"), + I18N_NOOP2("@item:intable palette", "Color 3"), + I18N_NOOP2("@item:intable palette", "Color 4"), + I18N_NOOP2("@item:intable palette", "Color 5"), + I18N_NOOP2("@item:intable palette", "Color 6"), + I18N_NOOP2("@item:intable palette", "Color 7"), + I18N_NOOP2("@item:intable palette", "Color 8"), + I18N_NOOP2("@item:intable palette", "Foreground (Intense)"), + I18N_NOOP2("@item:intable palette", "Background (Intense)"), + I18N_NOOP2("@item:intable palette", "Color 1 (Intense)"), + I18N_NOOP2("@item:intable palette", "Color 2 (Intense)"), + I18N_NOOP2("@item:intable palette", "Color 3 (Intense)"), + I18N_NOOP2("@item:intable palette", "Color 4 (Intense)"), + I18N_NOOP2("@item:intable palette", "Color 5 (Intense)"), + I18N_NOOP2("@item:intable palette", "Color 6 (Intense)"), + I18N_NOOP2("@item:intable palette", "Color 7 (Intense)"), + I18N_NOOP2("@item:intable palette", "Color 8 (Intense)"), + I18N_NOOP2("@item:intable palette", "Foreground (Faint)"), + I18N_NOOP2("@item:intable palette", "Background (Faint)"), + I18N_NOOP2("@item:intable palette", "Color 1 (Faint)"), + I18N_NOOP2("@item:intable palette", "Color 2 (Faint)"), + I18N_NOOP2("@item:intable palette", "Color 3 (Faint)"), + I18N_NOOP2("@item:intable palette", "Color 4 (Faint)"), + I18N_NOOP2("@item:intable palette", "Color 5 (Faint)"), + I18N_NOOP2("@item:intable palette", "Color 6 (Faint)"), + I18N_NOOP2("@item:intable palette", "Color 7 (Faint)"), + I18N_NOOP2("@item:intable palette", "Color 8 (Faint)")}; QString ColorScheme::colorNameForIndex(int index) { @@ -159,28 +154,28 @@ QString ColorScheme::translatedColorNameForIndex(int index) return i18nc("@item:intable palette", translatedColorNames[index]); } -ColorScheme::ColorScheme() : - _description(QString()), - _name(QString()), - _table(nullptr), - _randomTable(nullptr), - _opacity(1.0), - _blur(false), - _colorRandomization(false), - _wallpaper(nullptr) +ColorScheme::ColorScheme() + : _description(QString()) + , _name(QString()) + , _table(nullptr) + , _randomTable(nullptr) + , _opacity(1.0) + , _blur(false) + , _colorRandomization(false) + , _wallpaper(nullptr) { setWallpaper(QString()); } -ColorScheme::ColorScheme(const ColorScheme &other) : - _description(QString()), - _name(QString()), - _table(nullptr), - _randomTable(nullptr), - _opacity(other._opacity), - _blur(other._blur), - _colorRandomization(other._colorRandomization), - _wallpaper(other._wallpaper) +ColorScheme::ColorScheme(const ColorScheme &other) + : _description(QString()) + , _name(QString()) + , _table(nullptr) + , _randomTable(nullptr) + , _opacity(other._opacity) + , _blur(other._blur) + , _colorRandomization(other._colorRandomization) + , _wallpaper(other._wallpaper) { setName(other.name()); setDescription(other.description()); @@ -239,7 +234,7 @@ void ColorScheme::setColorTableEntry(int index, const QColor &entry) _table[index] = entry; } else { _table[index] = defaultTable[index]; - qCDebug(ColorSchemeDebug)<<"ColorScheme"< saturationDistribution({minSaturation, maxSaturation}, - [](double v) { return v; }); + std::piecewise_linear_distribution<> saturationDistribution({minSaturation, maxSaturation}, [](double v) { + return v; + }); saturation = saturationDistribution(randomEngine); } // Lightness range has base value at its center. The base // value is clamped to prevent the range from shrinking. // L=0 [=|= ] L=50 [ =|= ] L=100 [ =|=] - baseLightness = qBound(range.lightness / 2.0, baseLightness , MaxLightness - range.lightness); + baseLightness = qBound(range.lightness / 2.0, baseLightness, MaxLightness - range.lightness); const double minLightness = qMax(baseLightness - range.lightness / 2.0, 0.0); const double maxLightness = qMin(baseLightness + range.lightness / 2.0, MaxLightness); // Use triangular distribution with peak at L=50.0. @@ -307,7 +301,9 @@ QColor ColorScheme::colorEntry(int index, uint randomSeed) const if (qFuzzyCompare(minLightness, maxLightness)) { lightness = baseLightness; } else { - static const auto lightnessWeightsFunc = [](double v) { return 50.0 - qAbs(v - 50.0); }; + static const auto lightnessWeightsFunc = [](double v) { + return 50.0 - qAbs(v - 50.0); + }; std::piecewise_linear_distribution<> lightnessDistribution; if (minLightness < 50.0 && 50.0 < maxLightness) { lightnessDistribution = std::piecewise_linear_distribution<>({minLightness, 50.0, maxLightness}, lightnessWeightsFunc); @@ -350,11 +346,14 @@ void ColorScheme::setColorRandomization(bool randomize) // Set default randomization settings if (!hasAnyRandomizationEntries) { static const int ColorIndexesForRandomization[] = { - ColorFgIndex, ColorBgIndex, - ColorFgIntenseIndex, ColorBgIntenseIndex, - ColorFgFaintIndex, ColorBgFaintIndex, + ColorFgIndex, + ColorBgIndex, + ColorFgIntenseIndex, + ColorBgIntenseIndex, + ColorFgFaintIndex, + ColorBgFaintIndex, }; - for (int index: ColorIndexesForRandomization) { + for (int index : ColorIndexesForRandomization) { setRandomizationRange(index, MaxHue, MaxSaturation, 0.0); } } @@ -408,7 +407,7 @@ bool ColorScheme::hasDarkBackground() const void ColorScheme::setOpacity(qreal opacity) { if (opacity < 0.0 || opacity > 1.0) { - qCDebug(ColorSchemeDebug)<<"ColorScheme"< value || value > max) { qCDebug(ColorSchemeDebug) << QStringLiteral( - "Color scheme \"%1\": color index 2 has an invalid value: %3 = %4. " - "Allowed value range: %5 - %6. Using %7.") - .arg(name()).arg(index).arg(QLatin1String(key)).arg(value, 0, 'g', 1) - .arg(min, 0, 'g', 1).arg(max, 0, 'g', 1).arg(min, 0, 'g', 1); + "Color scheme \"%1\": color index 2 has an invalid value: %3 = %4. " + "Allowed value range: %5 - %6. Using %7.") + .arg(name()) + .arg(index) + .arg(QLatin1String(key)) + .arg(value, 0, 'g', 1) + .arg(min, 0, 'g', 1) + .arg(max, 0, 'g', 1) + .arg(min, 0, 'g', 1); return min; } return value; }; - double hue = readAndCheckConfigEntry(RandomHueRangeKey, 0.0, MaxHue); + double hue = readAndCheckConfigEntry(RandomHueRangeKey, 0.0, MaxHue); double saturation = readAndCheckConfigEntry(RandomSaturationRangeKey, 0.0, MaxSaturation); - double lightness = readAndCheckConfigEntry(RandomLightnessRangeKey, 0.0, MaxLightness); + double lightness = readAndCheckConfigEntry(RandomLightnessRangeKey, 0.0, MaxLightness); if (!qFuzzyIsNull(hue) || !qFuzzyIsNull(saturation) || !qFuzzyIsNull(lightness)) { setRandomizationRange(index, hue, saturation, lightness); @@ -515,7 +519,7 @@ void ColorScheme::writeColorEntry(KConfig &config, int index) const // "MaxRandomValue", // "MaxRandomSaturation" }; - for (const auto key: obsoleteKeys) { + for (const auto key : obsoleteKeys) { if (configGroup.hasKey(key)) { configGroup.deleteEntry(key); } @@ -526,16 +530,15 @@ void ColorScheme::writeColorEntry(KConfig &config, int index) const const auto checkAndMaybeSaveValue = [&](const char *key, double value) { const bool valueIsNull = qFuzzyCompare(value, 0.0); const bool keyExists = configGroup.hasKey(key); - const bool keyExistsAndHasDifferentValue = !qFuzzyCompare(configGroup.readEntry(key, value), - value); + const bool keyExistsAndHasDifferentValue = !qFuzzyCompare(configGroup.readEntry(key, value), value); if ((!valueIsNull && !keyExists) || keyExistsAndHasDifferentValue) { configGroup.writeEntry(key, value); } }; - checkAndMaybeSaveValue(RandomHueRangeKey, random.hue); + checkAndMaybeSaveValue(RandomHueRangeKey, random.hue); checkAndMaybeSaveValue(RandomSaturationRangeKey, random.saturation); - checkAndMaybeSaveValue(RandomLightnessRangeKey, random.lightness); + checkAndMaybeSaveValue(RandomLightnessRangeKey, random.lightness); } void ColorScheme::setWallpaper(const QString &path) diff --git a/src/colorscheme/ColorScheme.h b/src/colorscheme/ColorScheme.h index 4d5d3e0ab..661390cf9 100644 --- a/src/colorscheme/ColorScheme.h +++ b/src/colorscheme/ColorScheme.h @@ -20,8 +20,8 @@ class KConfig; class QPixmap; class QPainter; -namespace Konsole { - +namespace Konsole +{ class RandomizationRange; /** * Represents a color scheme for a terminal display. @@ -38,7 +38,7 @@ public: */ ColorScheme(); ColorScheme(const ColorScheme &other); - ColorScheme& operator=(const ColorScheme &other) = delete; + ColorScheme &operator=(const ColorScheme &other) = delete; ~ColorScheme(); /** Sets the descriptive name of the color scheme. */ @@ -181,11 +181,11 @@ private: ColorSchemeWallpaper::Ptr _wallpaper; - static const char * const colorNames[TABLE_COLORS]; - static const char * const translatedColorNames[TABLE_COLORS]; + static const char *const colorNames[TABLE_COLORS]; + static const char *const translatedColorNames[TABLE_COLORS]; }; } Q_DECLARE_METATYPE(const Konsole::ColorScheme *) -#endif //COLORSCHEME_H +#endif // COLORSCHEME_H diff --git a/src/colorscheme/ColorSchemeEditor.cpp b/src/colorscheme/ColorSchemeEditor.cpp index 326d680ac..31b859d27 100644 --- a/src/colorscheme/ColorSchemeEditor.cpp +++ b/src/colorscheme/ColorSchemeEditor.cpp @@ -8,26 +8,26 @@ #include "ColorSchemeEditor.h" // Qt -#include -#include #include -#include -#include #include +#include +#include +#include +#include #include // KDE -#include -#include #include +#include +#include #include #include #include // Konsole -#include "ui_ColorSchemeEditor.h" -#include "ColorScheme.h" #include "../characters/CharacterColor.h" +#include "ColorScheme.h" +#include "ui_ColorSchemeEditor.h" using namespace Konsole; @@ -35,18 +35,18 @@ using namespace Konsole; // because intense and faint colors are in separate columns const int COLOR_TABLE_ROW_LENGTH = TABLE_COLORS / 3; -const int NAME_COLUMN = 0; // column 0 : color names -const int COLOR_COLUMN = 1; // column 1 : actual colors -const int INTENSE_COLOR_COLUMN = 2; // column 2 : intense colors -const int FAINT_COLOR_COLUMN = 3; // column 2 : faint colors +const int NAME_COLUMN = 0; // column 0 : color names +const int COLOR_COLUMN = 1; // column 1 : actual colors +const int INTENSE_COLOR_COLUMN = 2; // column 2 : intense colors +const int FAINT_COLOR_COLUMN = 3; // column 2 : faint colors -ColorSchemeEditor::ColorSchemeEditor(QWidget *parent) : - QDialog(parent), - _isNewScheme(false), - _ui(nullptr), - _colors(nullptr) +ColorSchemeEditor::ColorSchemeEditor(QWidget *parent) + : QDialog(parent) + , _isNewScheme(false) + , _ui(nullptr) + , _colors(nullptr) { - auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok|QDialogButtonBox::Cancel|QDialogButtonBox::Apply); + auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel | QDialogButtonBox::Apply); auto mainWidget = new QWidget(this); auto mainLayout = new QVBoxLayout; setLayout(mainLayout); @@ -56,9 +56,7 @@ ColorSchemeEditor::ColorSchemeEditor(QWidget *parent) : connect(buttonBox, &QDialogButtonBox::accepted, this, &ColorSchemeEditor::accept); connect(buttonBox, &QDialogButtonBox::rejected, this, &ColorSchemeEditor::reject); mainLayout->addWidget(buttonBox); - connect(buttonBox->button(QDialogButtonBox::Apply), - &QPushButton::clicked, this, - &Konsole::ColorSchemeEditor::saveColorScheme); + connect(buttonBox->button(QDialogButtonBox::Apply), &QPushButton::clicked, this, &Konsole::ColorSchemeEditor::saveColorScheme); connect(okButton, &QPushButton::clicked, this, &Konsole::ColorSchemeEditor::saveColorScheme); // ui @@ -67,23 +65,19 @@ ColorSchemeEditor::ColorSchemeEditor(QWidget *parent) : // description edit _ui->descriptionEdit->setClearButtonEnabled(true); - connect(_ui->descriptionEdit, &QLineEdit::textChanged, this, - &Konsole::ColorSchemeEditor::setDescription); + connect(_ui->descriptionEdit, &QLineEdit::textChanged, this, &Konsole::ColorSchemeEditor::setDescription); // transparency slider QFontMetrics metrics(font()); _ui->transparencyPercentLabel->setMinimumWidth(metrics.boundingRect(QStringLiteral("100%")).width()); - connect(_ui->transparencySlider, &QSlider::valueChanged, this, - &Konsole::ColorSchemeEditor::setTransparencyPercentLabel); + connect(_ui->transparencySlider, &QSlider::valueChanged, this, &Konsole::ColorSchemeEditor::setTransparencyPercentLabel); // blur behind window - connect(_ui->blurCheckBox, &QCheckBox::toggled, this, - &Konsole::ColorSchemeEditor::setBlur); + connect(_ui->blurCheckBox, &QCheckBox::toggled, this, &Konsole::ColorSchemeEditor::setBlur); // randomized background - connect(_ui->randomizedBackgroundCheck, &QCheckBox::toggled, this, - &Konsole::ColorSchemeEditor::setRandomizedBackgroundColor); + connect(_ui->randomizedBackgroundCheck, &QCheckBox::toggled, this, &Konsole::ColorSchemeEditor::setRandomizedBackgroundColor); // wallpaper stuff auto dirModel = new QFileSystemModel(this); @@ -96,38 +90,31 @@ ColorSchemeEditor::ColorSchemeEditor(QWidget *parent) : _ui->wallpaperPath->setClearButtonEnabled(true); _ui->wallpaperSelectButton->setIcon(QIcon::fromTheme(QStringLiteral("image-x-generic"))); - connect(_ui->wallpaperSelectButton, &QToolButton::clicked, this, - &Konsole::ColorSchemeEditor::selectWallpaper); - connect(_ui->wallpaperPath, &QLineEdit::textChanged, this, - &Konsole::ColorSchemeEditor::wallpaperPathChanged); + connect(_ui->wallpaperSelectButton, &QToolButton::clicked, this, &Konsole::ColorSchemeEditor::selectWallpaper); + connect(_ui->wallpaperPath, &QLineEdit::textChanged, this, &Konsole::ColorSchemeEditor::wallpaperPathChanged); // color table _ui->colorTable->setColumnCount(4); _ui->colorTable->setRowCount(COLOR_TABLE_ROW_LENGTH); QStringList labels; - labels << i18nc("@label:listbox Column header text for color names", "Name") - << i18nc("@label:listbox Column header text for the actual colors", "Color") + labels << i18nc("@label:listbox Column header text for color names", "Name") << i18nc("@label:listbox Column header text for the actual colors", "Color") << i18nc("@label:listbox Column header text for the actual intense colors", "Intense color") << i18nc("@label:listbox Column header text for the actual faint colors", "Faint color"); _ui->colorTable->setHorizontalHeaderLabels(labels); // Set resize mode for colorTable columns - _ui->colorTable->horizontalHeader()->setSectionResizeMode(NAME_COLUMN, - QHeaderView::ResizeToContents); + _ui->colorTable->horizontalHeader()->setSectionResizeMode(NAME_COLUMN, QHeaderView::ResizeToContents); _ui->colorTable->horizontalHeader()->setSectionResizeMode(COLOR_COLUMN, QHeaderView::Stretch); - _ui->colorTable->horizontalHeader()->setSectionResizeMode(INTENSE_COLOR_COLUMN, - QHeaderView::Stretch); - _ui->colorTable->horizontalHeader()->setSectionResizeMode(FAINT_COLOR_COLUMN, - QHeaderView::Stretch); + _ui->colorTable->horizontalHeader()->setSectionResizeMode(INTENSE_COLOR_COLUMN, QHeaderView::Stretch); + _ui->colorTable->horizontalHeader()->setSectionResizeMode(FAINT_COLOR_COLUMN, QHeaderView::Stretch); QTableWidgetItem *item = new QTableWidgetItem(QStringLiteral("Test")); _ui->colorTable->setItem(0, 0, item); _ui->colorTable->verticalHeader()->hide(); - connect(_ui->colorTable, &QTableWidget::itemClicked, this, - &Konsole::ColorSchemeEditor::editColorItem); + connect(_ui->colorTable, &QTableWidget::itemClicked, this, &Konsole::ColorSchemeEditor::editColorItem); // warning label when transparency is not available _ui->transparencyWarningWidget->setWordWrap(true); @@ -153,8 +140,7 @@ ColorSchemeEditor::~ColorSchemeEditor() void ColorSchemeEditor::editColorItem(QTableWidgetItem *item) { // ignore if this is not a color column - if (item->column() != COLOR_COLUMN && item->column() != INTENSE_COLOR_COLUMN - && item->column() != FAINT_COLOR_COLUMN) { + if (item->column() != COLOR_COLUMN && item->column() != INTENSE_COLOR_COLUMN && item->column() != FAINT_COLOR_COLUMN) { return; } @@ -171,7 +157,7 @@ void ColorSchemeEditor::editColorItem(QTableWidgetItem *item) // and the faint color rows are in the final third of the color table if (item->column() == FAINT_COLOR_COLUMN) { - colorSchemeRow += 2*COLOR_TABLE_ROW_LENGTH; + colorSchemeRow += 2 * COLOR_TABLE_ROW_LENGTH; } _colors->setColorTableEntry(colorSchemeRow, color); @@ -191,11 +177,9 @@ void ColorSchemeEditor::selectWallpaper() fileFormats += QLatin1String(")"); const QString fileName = QFileDialog::getOpenFileName(this, - i18nc("@title:window", - "Select wallpaper image file"), + i18nc("@title:window", "Select wallpaper image file"), _ui->wallpaperPath->text(), - i18nc("@label:textbox Filter in file open dialog", - "Supported Images") + fileFormats); + i18nc("@label:textbox Filter in file open dialog", "Supported Images") + fileFormats); if (!fileName.isEmpty()) { _ui->wallpaperPath->setText(fileName); @@ -296,12 +280,11 @@ void ColorSchemeEditor::setupColorTable(const ColorScheme *colors) auto colorItemIntense = new QTableWidgetItem(); colorItemIntense->setBackground(table[COLOR_TABLE_ROW_LENGTH + row]); - colorItemIntense->setFlags(colorItem->flags() - & ~Qt::ItemIsEditable & ~Qt::ItemIsSelectable); + colorItemIntense->setFlags(colorItem->flags() & ~Qt::ItemIsEditable & ~Qt::ItemIsSelectable); colorItemIntense->setToolTip(i18nc("@info:tooltip", "Click to choose intense color")); auto colorItemFaint = new QTableWidgetItem(); - colorItemFaint->setBackground(table[2*COLOR_TABLE_ROW_LENGTH + row]); + colorItemFaint->setBackground(table[2 * COLOR_TABLE_ROW_LENGTH + row]); colorItemFaint->setFlags(colorItem->flags() & ~Qt::ItemIsEditable & ~Qt::ItemIsSelectable); colorItemFaint->setToolTip(i18nc("@info:tooltip", "Click to choose Faint color")); diff --git a/src/colorscheme/ColorSchemeEditor.h b/src/colorscheme/ColorSchemeEditor.h index 26ed8126c..e3e9faf88 100644 --- a/src/colorscheme/ColorSchemeEditor.h +++ b/src/colorscheme/ColorSchemeEditor.h @@ -17,11 +17,13 @@ class QTableWidgetItem; -namespace Ui { +namespace Ui +{ class ColorSchemeEditor; } -namespace Konsole { +namespace Konsole +{ class ColorScheme; /** diff --git a/src/colorscheme/ColorSchemeManager.cpp b/src/colorscheme/ColorSchemeManager.cpp index 4c49fe02a..663eb8bfe 100644 --- a/src/colorscheme/ColorSchemeManager.cpp +++ b/src/colorscheme/ColorSchemeManager.cpp @@ -13,18 +13,18 @@ #include "colorschemedebug.h" // Qt -#include -#include #include +#include +#include // KDE #include using namespace Konsole; -ColorSchemeManager::ColorSchemeManager() : - _colorSchemes(QHash()), - _haveLoadedAll(false) +ColorSchemeManager::ColorSchemeManager() + : _colorSchemes(QHash()) + , _haveLoadedAll(false) { } @@ -35,7 +35,7 @@ ColorSchemeManager::~ColorSchemeManager() Q_GLOBAL_STATIC(ColorSchemeManager, theColorSchemeManager) -ColorSchemeManager* ColorSchemeManager::instance() +ColorSchemeManager *ColorSchemeManager::instance() { return theColorSchemeManager; } @@ -81,8 +81,7 @@ bool ColorSchemeManager::loadColorScheme(const QString &filePath) scheme->read(config); if (scheme->name().isEmpty()) { - qCDebug(ColorSchemeDebug) << "Color scheme in" << filePath - << "does not have a valid name and was not loaded."; + qCDebug(ColorSchemeDebug) << "Color scheme in" << filePath << "does not have a valid name and was not loaded."; delete scheme; return false; } @@ -90,7 +89,7 @@ bool ColorSchemeManager::loadColorScheme(const QString &filePath) if (!_colorSchemes.contains(name)) { _colorSchemes.insert(scheme->name(), scheme); } else { - //qDebug() << "color scheme with name" << scheme->name() << "has already been" << + // qDebug() << "color scheme with name" << scheme->name() << "has already been" << // "found, ignoring."; delete scheme; @@ -120,8 +119,7 @@ QString ColorSchemeManager::colorSchemeNameFromPath(const QString &path) QStringList ColorSchemeManager::listColorSchemes() { QStringList colorschemes; - const QStringList dirs = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QStringLiteral("konsole"), - QStandardPaths::LocateDirectory); + const QStringList dirs = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QStringLiteral("konsole"), QStandardPaths::LocateDirectory); colorschemes.reserve(dirs.size()); for (const QString &dir : dirs) { @@ -150,8 +148,7 @@ void ColorSchemeManager::addColorScheme(ColorScheme *scheme) // save changes to disk - const QString dir = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) - + QStringLiteral("/konsole/"); + const QString dir = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QStringLiteral("/konsole/"); QDir().mkpath(dir); const QString path = dir + scheme->name() + QStringLiteral(".colorscheme"); KConfig config(path, KConfig::NoGlobals); @@ -168,8 +165,8 @@ bool ColorSchemeManager::deleteColorScheme(const QString &name) if (QFile::remove(path)) { delete _colorSchemes.take(name); return true; - } - qCDebug(ColorSchemeDebug)<<"Failed to remove color scheme -"< #include +#include // Qt -#include #include +#include using namespace Konsole; @@ -42,8 +42,7 @@ void ColorSchemeViewDelegate::paint(QPainter *painter, const QStyleOptionViewIte style->drawPrimitive(QStyle::PE_PanelItemViewItem, &option, painter, option.widget); // Draw name - QPalette::ColorRole textColor = ((option.state & QStyle::State_Selected) != 0) - ? QPalette::HighlightedText : QPalette::Text; + QPalette::ColorRole textColor = ((option.state & QStyle::State_Selected) != 0) ? QPalette::HighlightedText : QPalette::Text; painter->setPen(option.palette.color(textColor)); painter->setFont(option.font); @@ -52,9 +51,7 @@ void ColorSchemeViewDelegate::paint(QPainter *painter, const QStyleOptionViewIte QFontMetrics profileFontMetrics(profileFont); const int sampleTextWidth = profileFontMetrics.boundingRect(sampleText).width(); - painter->drawText(option.rect.adjusted(sampleTextWidth + 15, 0, 0, 0), - Qt::AlignLeft | Qt::AlignVCenter, - index.data(Qt::DisplayRole).toString()); + painter->drawText(option.rect.adjusted(sampleTextWidth + 15, 0, 0, 0), Qt::AlignLeft | Qt::AlignVCenter, index.data(Qt::DisplayRole).toString()); // Draw the preview const int x = option.rect.left(); diff --git a/src/colorscheme/ColorSchemeViewDelegate.h b/src/colorscheme/ColorSchemeViewDelegate.h index 586f3548f..00353c184 100644 --- a/src/colorscheme/ColorSchemeViewDelegate.h +++ b/src/colorscheme/ColorSchemeViewDelegate.h @@ -12,20 +12,20 @@ namespace Konsole { - /** - * A delegate which can display and edit color schemes in a view. - */ - class ColorSchemeViewDelegate : public QAbstractItemDelegate - { - Q_OBJECT +/** + * A delegate which can display and edit color schemes in a view. + */ +class ColorSchemeViewDelegate : public QAbstractItemDelegate +{ + Q_OBJECT - public: - explicit ColorSchemeViewDelegate(QObject *parent = nullptr); +public: + explicit ColorSchemeViewDelegate(QObject *parent = nullptr); - // reimplemented - void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override; - QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override; - }; + // reimplemented + void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override; + QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override; +}; } diff --git a/src/colorscheme/ColorSchemeWallpaper.cpp b/src/colorscheme/ColorSchemeWallpaper.cpp index 72c598fca..bf2c5c8e5 100644 --- a/src/colorscheme/ColorSchemeWallpaper.cpp +++ b/src/colorscheme/ColorSchemeWallpaper.cpp @@ -17,9 +17,9 @@ using namespace Konsole; -ColorSchemeWallpaper::ColorSchemeWallpaper(const QString &path) : - _path(path), - _picture(nullptr) +ColorSchemeWallpaper::ColorSchemeWallpaper(const QString &path) + : _path(path) + , _picture(nullptr) { } diff --git a/src/colorscheme/ColorSchemeWallpaper.h b/src/colorscheme/ColorSchemeWallpaper.h index 603de20e3..efbccd493 100644 --- a/src/colorscheme/ColorSchemeWallpaper.h +++ b/src/colorscheme/ColorSchemeWallpaper.h @@ -23,33 +23,33 @@ class QPainter; namespace Konsole { - /** - * This class holds the wallpaper pixmap associated with a color scheme. - * The wallpaper object is shared between multiple TerminalDisplay. - */ - class ColorSchemeWallpaper : public QSharedData - { - public: - typedef QExplicitlySharedDataPointer Ptr; +/** + * This class holds the wallpaper pixmap associated with a color scheme. + * The wallpaper object is shared between multiple TerminalDisplay. + */ +class ColorSchemeWallpaper : public QSharedData +{ +public: + typedef QExplicitlySharedDataPointer Ptr; - explicit ColorSchemeWallpaper(const QString &path); - ~ColorSchemeWallpaper(); + explicit ColorSchemeWallpaper(const QString &path); + ~ColorSchemeWallpaper(); - void load(); + void load(); - /** Returns true if wallpaper available and drawn */ - bool draw(QPainter &painter, const QRect rect, qreal opacity = 1.0); + /** Returns true if wallpaper available and drawn */ + bool draw(QPainter &painter, const QRect rect, qreal opacity = 1.0); - bool isNull() const; + bool isNull() const; - QString path() const; + QString path() const; - private: - Q_DISABLE_COPY(ColorSchemeWallpaper) +private: + Q_DISABLE_COPY(ColorSchemeWallpaper) - QString _path; - std::unique_ptr _picture; - }; + QString _path; + std::unique_ptr _picture; +}; } diff --git a/src/colorscheme/RandomizationRange.cpp b/src/colorscheme/RandomizationRange.cpp index e150fee0b..193ca0608 100644 --- a/src/colorscheme/RandomizationRange.cpp +++ b/src/colorscheme/RandomizationRange.cpp @@ -15,16 +15,16 @@ namespace Konsole { +RandomizationRange::RandomizationRange() + : hue(0.0) + , saturation(0.0) + , lightness(0.0) +{ +} - RandomizationRange::RandomizationRange() - : hue(0.0) - , saturation(0.0) - , lightness(0.0) - {} - - bool RandomizationRange::isNull() const - { - return qFuzzyIsNull(hue) && qFuzzyIsNull(saturation) && qFuzzyIsNull(lightness); - } +bool RandomizationRange::isNull() const +{ + return qFuzzyIsNull(hue) && qFuzzyIsNull(saturation) && qFuzzyIsNull(lightness); +} } diff --git a/src/colorscheme/RandomizationRange.h b/src/colorscheme/RandomizationRange.h index 9faf863c4..1a3f5787b 100644 --- a/src/colorscheme/RandomizationRange.h +++ b/src/colorscheme/RandomizationRange.h @@ -12,18 +12,17 @@ namespace Konsole { +// specifies how much a particular color can be randomized by +class RandomizationRange +{ +public: + RandomizationRange(); + bool isNull() const; - // specifies how much a particular color can be randomized by - class RandomizationRange - { - public: - RandomizationRange(); - bool isNull() const; - - double hue; - double saturation; - double lightness; - }; + double hue; + double saturation; + double lightness; +}; } diff --git a/src/colorscheme/hsluv.c b/src/colorscheme/hsluv.c index c7f37123c..26a10d933 100644 --- a/src/colorscheme/hsluv.c +++ b/src/colorscheme/hsluv.c @@ -14,7 +14,6 @@ #include #include - typedef struct Triplet_tag Triplet; struct Triplet_tag { double a; @@ -23,18 +22,14 @@ struct Triplet_tag { }; /* for RGB */ -static const Triplet m[3] = { - { 3.24096994190452134377, -1.53738317757009345794, -0.49861076029300328366 }, - { -0.96924363628087982613, 1.87596750150772066772, 0.04155505740717561247 }, - { 0.05563007969699360846, -0.20397695888897656435, 1.05697151424287856072 } -}; +static const Triplet m[3] = {{3.24096994190452134377, -1.53738317757009345794, -0.49861076029300328366}, + {-0.96924363628087982613, 1.87596750150772066772, 0.04155505740717561247}, + {0.05563007969699360846, -0.20397695888897656435, 1.05697151424287856072}}; /* for XYZ */ -static const Triplet m_inv[3] = { - { 0.41239079926595948129, 0.35758433938387796373, 0.18048078840183428751 }, - { 0.21263900587151035754, 0.71516867876775592746, 0.07219231536073371500 }, - { 0.01933081871559185069, 0.11919477979462598791, 0.95053215224966058086 } -}; +static const Triplet m_inv[3] = {{0.41239079926595948129, 0.35758433938387796373, 0.18048078840183428751}, + {0.21263900587151035754, 0.71516867876775592746, 0.07219231536073371500}, + {0.01933081871559185069, 0.11919477979462598791, 0.95053215224966058086}}; static const double ref_u = 0.19783000664283680764; static const double ref_v = 0.46831999493879100370; @@ -42,16 +37,13 @@ static const double ref_v = 0.46831999493879100370; static const double kappa = 903.29629629629629629630; static const double epsilon = 0.00885645167903563082; - typedef struct Bounds_tag Bounds; struct Bounds_tag { double a; double b; }; - -static void -get_bounds(double l, Bounds bounds[6]) +static void get_bounds(double l, Bounds bounds[6]) { double tl = l + 16.0; double sub1 = (tl * tl * tl) / 1560896.0; @@ -59,14 +51,14 @@ get_bounds(double l, Bounds bounds[6]) int channel; int t; - for(channel = 0; channel < 3; channel++) { + for (channel = 0; channel < 3; channel++) { double m1 = m[channel].a; double m2 = m[channel].b; double m3 = m[channel].c; for (t = 0; t < 2; t++) { double top1 = (284517.0 * m1 - 94839.0 * m3) * sub2; - double top2 = (838422.0 * m3 + 769860.0 * m2 + 731718.0 * m1) * l * sub2 - 769860.0 * t * l; + double top2 = (838422.0 * m3 + 769860.0 * m2 + 731718.0 * m1) * l * sub2 - 769860.0 * t * l; double bottom = (632260.0 * m3 - 126452.0 * m2) * sub2 + 126452.0 * t; bounds[channel * 2 + t].a = top1 / bottom; @@ -75,49 +67,44 @@ get_bounds(double l, Bounds bounds[6]) } } -static double -intersect_line_line(const Bounds* line1, const Bounds* line2) +static double intersect_line_line(const Bounds *line1, const Bounds *line2) { return (line1->b - line2->b) / (line2->a - line1->a); } -static double -dist_from_pole_squared(double x, double y) +static double dist_from_pole_squared(double x, double y) { return x * x + y * y; } -static double -ray_length_until_intersect(double theta, const Bounds* line) +static double ray_length_until_intersect(double theta, const Bounds *line) { return line->b / (sin(theta) - line->a * cos(theta)); } -static double -max_safe_chroma_for_l(double l) +static double max_safe_chroma_for_l(double l) { double min_len_squared = DBL_MAX; Bounds bounds[6]; int i; get_bounds(l, bounds); - for(i = 0; i < 6; i++) { + for (i = 0; i < 6; i++) { double m1 = bounds[i].a; double b1 = bounds[i].b; /* x where line intersects with perpendicular running though (0, 0) */ - Bounds line2 = { -1.0 / m1, 0.0 }; + Bounds line2 = {-1.0 / m1, 0.0}; double x = intersect_line_line(&bounds[i], &line2); double distance = dist_from_pole_squared(x, b1 + x * m1); - if(distance < min_len_squared) + if (distance < min_len_squared) min_len_squared = distance; } return sqrt(min_len_squared); } -static double -max_chroma_for_lh(double l, double h) +static double max_chroma_for_lh(double l, double h) { double min_len = DBL_MAX; double hrad = h * 0.01745329251994329577; /* (2 * pi / 360) */ @@ -125,33 +112,30 @@ max_chroma_for_lh(double l, double h) int i; get_bounds(l, bounds); - for(i = 0; i < 6; i++) { + for (i = 0; i < 6; i++) { double len = ray_length_until_intersect(hrad, &bounds[i]); - if(len >= 0 && len < min_len) + if (len >= 0 && len < min_len) min_len = len; } return min_len; } -static double -dot_product(const Triplet* t1, const Triplet* t2) +static double dot_product(const Triplet *t1, const Triplet *t2) { return (t1->a * t2->a + t1->b * t2->b + t1->c * t2->c); } /* Used for rgb conversions */ -static double -from_linear(double c) +static double from_linear(double c) { - if(c <= 0.0031308) + if (c <= 0.0031308) return 12.92 * c; else return 1.055 * pow(c, 1.0 / 2.4) - 0.055; } -static double -to_linear(double c) +static double to_linear(double c) { if (c > 0.04045) return pow((c + 0.055) / 1.055, 2.4); @@ -159,8 +143,7 @@ to_linear(double c) return c / 12.92; } -static void -xyz2rgb(Triplet* in_out) +static void xyz2rgb(Triplet *in_out) { double r = from_linear(dot_product(&m[0], in_out)); double g = from_linear(dot_product(&m[1], in_out)); @@ -170,10 +153,9 @@ xyz2rgb(Triplet* in_out) in_out->c = b; } -static void -rgb2xyz(Triplet* in_out) +static void rgb2xyz(Triplet *in_out) { - Triplet rgbl = { to_linear(in_out->a), to_linear(in_out->b), to_linear(in_out->c) }; + Triplet rgbl = {to_linear(in_out->a), to_linear(in_out->b), to_linear(in_out->c)}; double x = dot_product(&m_inv[0], &rgbl); double y = dot_product(&m_inv[1], &rgbl); double z = dot_product(&m_inv[2], &rgbl); @@ -187,19 +169,17 @@ rgb2xyz(Triplet* in_out) * illuminant D65, so Yn (see refY in Maxima file) equals 1. The formula is * simplified accordingly. */ -static double -y2l(double y) +static double y2l(double y) { - if(y <= epsilon) + if (y <= epsilon) return y * kappa; else return 116.0 * cbrt(y) - 16.0; } -static double -l2y(double l) +static double l2y(double l) { - if(l <= 8.0) { + if (l <= 8.0) { return l / kappa; } else { double x = (l + 16.0) / 116.0; @@ -207,8 +187,7 @@ l2y(double l) } } -static void -xyz2luv(Triplet* in_out) +static void xyz2luv(Triplet *in_out) { double var_u = (4.0 * in_out->a) / (in_out->a + (15.0 * in_out->b) + (3.0 * in_out->c)); double var_v = (9.0 * in_out->b) / (in_out->a + (15.0 * in_out->b) + (3.0 * in_out->c)); @@ -217,7 +196,7 @@ xyz2luv(Triplet* in_out) double v = 13.0 * l * (var_v - ref_v); in_out->a = l; - if(l < 0.00000001) { + if (l < 0.00000001) { in_out->b = 0.0; in_out->c = 0.0; } else { @@ -226,10 +205,9 @@ xyz2luv(Triplet* in_out) } } -static void -luv2xyz(Triplet* in_out) +static void luv2xyz(Triplet *in_out) { - if(in_out->a <= 0.00000001) { + if (in_out->a <= 0.00000001) { /* Black will create a divide-by-zero error. */ in_out->a = 0.0; in_out->b = 0.0; @@ -247,8 +225,7 @@ luv2xyz(Triplet* in_out) in_out->c = z; } -static void -luv2lch(Triplet* in_out) +static void luv2lch(Triplet *in_out) { double l = in_out->a; double u = in_out->b; @@ -257,11 +234,11 @@ luv2lch(Triplet* in_out) double c = sqrt(u * u + v * v); /* Grays: disambiguate hue */ - if(c < 0.00000001) { + if (c < 0.00000001) { h = 0; } else { - h = atan2(v, u) * 57.29577951308232087680; /* (180 / pi) */ - if(h < 0.0) + h = atan2(v, u) * 57.29577951308232087680; /* (180 / pi) */ + if (h < 0.0) h += 360.0; } @@ -270,10 +247,9 @@ luv2lch(Triplet* in_out) in_out->c = h; } -static void -lch2luv(Triplet* in_out) +static void lch2luv(Triplet *in_out) { - double hrad = in_out->c * 0.01745329251994329577; /* (pi / 180.0) */ + double hrad = in_out->c * 0.01745329251994329577; /* (pi / 180.0) */ double u = cos(hrad) * in_out->b; double v = sin(hrad) * in_out->b; @@ -281,8 +257,7 @@ lch2luv(Triplet* in_out) in_out->c = v; } -static void -hsluv2lch(Triplet* in_out) +static void hsluv2lch(Triplet *in_out) { double h = in_out->a; double s = in_out->b; @@ -290,7 +265,7 @@ hsluv2lch(Triplet* in_out) double c; /* White and black: disambiguate chroma */ - if(l > 99.9999999 || l < 0.00000001) + if (l > 99.9999999 || l < 0.00000001) c = 0.0; else c = max_chroma_for_lh(l, h) / 100.0 * s; @@ -304,8 +279,7 @@ hsluv2lch(Triplet* in_out) in_out->c = h; } -static void -lch2hsluv(Triplet* in_out) +static void lch2hsluv(Triplet *in_out) { double l = in_out->a; double c = in_out->b; @@ -313,7 +287,7 @@ lch2hsluv(Triplet* in_out) double s; /* White and black: disambiguate saturation */ - if(l > 99.9999999 || l < 0.00000001) + if (l > 99.9999999 || l < 0.00000001) s = 0.0; else s = c / max_chroma_for_lh(l, h) * 100.0; @@ -327,8 +301,7 @@ lch2hsluv(Triplet* in_out) in_out->c = l; } -static void -hpluv2lch(Triplet* in_out) +static void hpluv2lch(Triplet *in_out) { double h = in_out->a; double s = in_out->b; @@ -336,7 +309,7 @@ hpluv2lch(Triplet* in_out) double c; /* White and black: disambiguate chroma */ - if(l > 99.9999999 || l < 0.00000001) + if (l > 99.9999999 || l < 0.00000001) c = 0.0; else c = max_safe_chroma_for_l(l) / 100.0 * s; @@ -350,8 +323,7 @@ hpluv2lch(Triplet* in_out) in_out->c = h; } -static void -lch2hpluv(Triplet* in_out) +static void lch2hpluv(Triplet *in_out) { double l = in_out->a; double c = in_out->b; @@ -373,12 +345,9 @@ lch2hpluv(Triplet* in_out) in_out->c = l; } - - -void -hsluv2rgb(double h, double s, double l, double* pr, double* pg, double* pb) +void hsluv2rgb(double h, double s, double l, double *pr, double *pg, double *pb) { - Triplet tmp = { h, s, l }; + Triplet tmp = {h, s, l}; hsluv2lch(&tmp); lch2luv(&tmp); @@ -390,10 +359,9 @@ hsluv2rgb(double h, double s, double l, double* pr, double* pg, double* pb) *pb = tmp.c; } -void -hpluv2rgb(double h, double s, double l, double* pr, double* pg, double* pb) +void hpluv2rgb(double h, double s, double l, double *pr, double *pg, double *pb) { - Triplet tmp = { h, s, l }; + Triplet tmp = {h, s, l}; hpluv2lch(&tmp); lch2luv(&tmp); @@ -405,10 +373,9 @@ hpluv2rgb(double h, double s, double l, double* pr, double* pg, double* pb) *pb = tmp.c; } -void -rgb2hsluv(double r, double g, double b, double* ph, double* ps, double* pl) +void rgb2hsluv(double r, double g, double b, double *ph, double *ps, double *pl) { - Triplet tmp = { r, g, b }; + Triplet tmp = {r, g, b}; rgb2xyz(&tmp); xyz2luv(&tmp); @@ -420,10 +387,9 @@ rgb2hsluv(double r, double g, double b, double* ph, double* ps, double* pl) *pl = tmp.c; } -void -rgb2hpluv(double r, double g, double b, double* ph, double* ps, double* pl) +void rgb2hpluv(double r, double g, double b, double *ph, double *ps, double *pl) { - Triplet tmp = { r, g, b }; + Triplet tmp = {r, g, b}; rgb2xyz(&tmp); xyz2luv(&tmp); diff --git a/src/colorscheme/hsluv.h b/src/colorscheme/hsluv.h index 08e359153..f9233c22f 100644 --- a/src/colorscheme/hsluv.h +++ b/src/colorscheme/hsluv.h @@ -16,7 +16,6 @@ extern "C" { #endif - /** * Convert HSLuv to RGB. * @@ -27,7 +26,7 @@ extern "C" { * @param[out] pg Green component. Between 0.0 and 1.0. * @param[out] pb Blue component. Between 0.0 and 1.0. */ -void hsluv2rgb(double h, double s, double l, double* pr, double* pg, double* pb); +void hsluv2rgb(double h, double s, double l, double *pr, double *pg, double *pb); /** * Convert RGB to HSLuv. @@ -39,7 +38,7 @@ void hsluv2rgb(double h, double s, double l, double* pr, double* pg, double* pb) * @param[out] ps Saturation. Between 0.0 and 100.0. * @param[out] pl Lightness. Between 0.0 and 100.0. */ -void rgb2hsluv(double r, double g, double b, double* ph, double* ps, double* pl); +void rgb2hsluv(double r, double g, double b, double *ph, double *ps, double *pl); /** * Convert HPLuv to RGB. @@ -51,7 +50,7 @@ void rgb2hsluv(double r, double g, double b, double* ph, double* ps, double* pl) * @param[out] pg Green component. Between 0.0 and 1.0. * @param[out] pb Blue component. Between 0.0 and 1.0. */ -void hpluv2rgb(double h, double s, double l, double* pr, double* pg, double* pb); +void hpluv2rgb(double h, double s, double l, double *pr, double *pg, double *pb); /** * Convert RGB to HPLuv. @@ -66,11 +65,10 @@ void hpluv2rgb(double h, double s, double l, double* pr, double* pg, double* pb) * Note that HPLuv does not contain all the colors of RGB, so converting * arbitrary RGB to it may generate invalid HPLuv colors. */ -void rgb2hpluv(double r, double g, double b, double* ph, double* ps, double* pl); - +void rgb2hpluv(double r, double g, double b, double *ph, double *ps, double *pl); #ifdef __cplusplus } #endif -#endif /* HSLUV_H */ +#endif /* HSLUV_H */ diff --git a/src/decoders/HTMLDecoder.cpp b/src/decoders/HTMLDecoder.cpp index af8aac3c5..0f81b0940 100644 --- a/src/decoders/HTMLDecoder.cpp +++ b/src/decoders/HTMLDecoder.cpp @@ -14,8 +14,8 @@ #include // Qt -#include #include +#include using namespace Konsole; @@ -48,11 +48,10 @@ HTMLDecoder::HTMLDecoder(const QString &colorSchemeName, const QFont &profileFon } } -void HTMLDecoder::begin(QTextStream* output) +void HTMLDecoder::begin(QTextStream *output) { _output = output; - if (_validProfile) { QString style; @@ -65,7 +64,6 @@ void HTMLDecoder::begin(QTextStream* output) style.append(QStringLiteral("font-size:%1px;").arg(_profileFont.pixelSize())); } - style.append(QStringLiteral("color:%1;").arg(_colorTable[DEFAULT_FORE_COLOR].name())); style.append(QStringLiteral("background-color:%1;").arg(_colorTable[DEFAULT_BACK_COLOR].name())); @@ -92,8 +90,8 @@ void HTMLDecoder::end() _output = nullptr; } -//TODO: Support for LineProperty (mainly double width , double height) -void HTMLDecoder::decodeLine(const Character* const characters, int count, LineProperty /*properties*/) +// TODO: Support for LineProperty (mainly double width , double height) +void HTMLDecoder::decodeLine(const Character *const characters, int count, LineProperty /*properties*/) { Q_ASSERT(_output); @@ -102,10 +100,8 @@ void HTMLDecoder::decodeLine(const Character* const characters, int count, LineP int spaceCount = 0; for (int i = 0; i < count; i++) { - //check if appearance of character is different from previous char - if (characters[i].rendition != _lastRendition || - characters[i].foregroundColor != _lastForeColor || - characters[i].backgroundColor != _lastBackColor) { + // check if appearance of character is different from previous char + if (characters[i].rendition != _lastRendition || characters[i].foregroundColor != _lastForeColor || characters[i].backgroundColor != _lastBackColor) { if (_innerSpanOpen) { closeSpan(text); _innerSpanOpen = false; @@ -115,7 +111,7 @@ void HTMLDecoder::decodeLine(const Character* const characters, int count, LineP _lastForeColor = characters[i].foregroundColor; _lastBackColor = characters[i].backgroundColor; - //build up style string + // build up style string QString style; bool useBold = (_lastRendition & RE_BOLD) != 0; @@ -131,28 +127,28 @@ void HTMLDecoder::decodeLine(const Character* const characters, int count, LineP style.append(QStringLiteral("background-color:%1;").arg(_lastBackColor.color(_colorTable).name())); - //open the span with the current style + // open the span with the current style openSpan(text, style); _innerSpanOpen = true; } - //handle whitespace + // handle whitespace if (characters[i].isSpace()) { spaceCount++; } else { spaceCount = 0; } - //output current character + // output current character if (spaceCount < 2) { if ((characters[i].rendition & RE_EXTENDED_CHAR) != 0) { ushort extendedCharLength = 0; - const uint* chars = ExtendedCharTable::instance.lookupExtendedChar(characters[i].character, extendedCharLength); + const uint *chars = ExtendedCharTable::instance.lookupExtendedChar(characters[i].character, extendedCharLength); if (chars != nullptr) { text.append(QString::fromUcs4(chars, extendedCharLength)); } } else { - //escape HTML tag characters and just display others as they are + // escape HTML tag characters and just display others as they are const QChar ch = characters[i].character; if (ch == QLatin1Char('<')) { text.append(QLatin1String("<")); @@ -171,24 +167,24 @@ void HTMLDecoder::decodeLine(const Character* const characters, int count, LineP } } - //close any remaining open inner spans + // close any remaining open inner spans if (_innerSpanOpen) { closeSpan(text); _innerSpanOpen = false; } - //start new line + // start new line text.append(QLatin1String("
")); *_output << text; } -void HTMLDecoder::openSpan(QString& text , const QString& style) +void HTMLDecoder::openSpan(QString &text, const QString &style) { text.append(QStringLiteral("").arg(style)); } -void HTMLDecoder::closeSpan(QString& text) +void HTMLDecoder::closeSpan(QString &text) { text.append(QLatin1String("")); } diff --git a/src/decoders/HTMLDecoder.h b/src/decoders/HTMLDecoder.h index 414ef1f84..758444d49 100644 --- a/src/decoders/HTMLDecoder.h +++ b/src/decoders/HTMLDecoder.h @@ -15,37 +15,36 @@ class QString; namespace Konsole { +/** + * A terminal character decoder which produces pretty HTML markup + */ +class KONSOLEDECODERS_EXPORT HTMLDecoder : public TerminalCharacterDecoder +{ +public: /** - * A terminal character decoder which produces pretty HTML markup + * Constructs an HTML decoder using a default black-on-white color scheme. */ - class KONSOLEDECODERS_EXPORT HTMLDecoder : public TerminalCharacterDecoder - { - public: - /** - * Constructs an HTML decoder using a default black-on-white color scheme. - */ - explicit HTMLDecoder(const QString &colorSchemeName = QString(), const QFont &profileFont = QFont()); + explicit HTMLDecoder(const QString &colorSchemeName = QString(), const QFont &profileFont = QFont()); - void decodeLine(const Character * const characters, int count, - LineProperty properties) override; + void decodeLine(const Character *const characters, int count, LineProperty properties) override; - void begin(QTextStream *output) override; - void end() override; + void begin(QTextStream *output) override; + void end() override; - private: - void openSpan(QString &text, const QString &style); - void closeSpan(QString &text); +private: + void openSpan(QString &text, const QString &style); + void closeSpan(QString &text); - QTextStream *_output; - QString _colorSchemeName; - QFont _profileFont; - QColor _colorTable[TABLE_COLORS]; - bool _innerSpanOpen; - RenditionFlags _lastRendition; - CharacterColor _lastForeColor; - CharacterColor _lastBackColor; - bool _validProfile; - }; + QTextStream *_output; + QString _colorSchemeName; + QFont _profileFont; + QColor _colorTable[TABLE_COLORS]; + bool _innerSpanOpen; + RenditionFlags _lastRendition; + CharacterColor _lastForeColor; + CharacterColor _lastBackColor; + bool _validProfile; +}; } #endif diff --git a/src/decoders/PlainTextDecoder.cpp b/src/decoders/PlainTextDecoder.cpp index d28906eb1..9fcfc0271 100644 --- a/src/decoders/PlainTextDecoder.cpp +++ b/src/decoders/PlainTextDecoder.cpp @@ -35,7 +35,7 @@ void PlainTextDecoder::setTrailingWhitespace(bool enable) _includeTrailingWhitespace = enable; } -void PlainTextDecoder::begin(QTextStream* output) +void PlainTextDecoder::begin(QTextStream *output) { _output = output; if (!_linePositions.isEmpty()) { @@ -58,7 +58,7 @@ QList PlainTextDecoder::linePositions() const return _linePositions; } -void PlainTextDecoder::decodeLine(const Character* const characters, int count, LineProperty /*properties*/) +void PlainTextDecoder::decodeLine(const Character *const characters, int count, LineProperty /*properties*/) { Q_ASSERT(_output); @@ -67,10 +67,10 @@ void PlainTextDecoder::decodeLine(const Character* const characters, int count, _linePositions << pos; } - //TODO should we ignore or respect the LINE_WRAPPED line property? + // 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. + // 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); @@ -92,14 +92,14 @@ void PlainTextDecoder::decodeLine(const Character* const characters, int count, // if inclusion of trailing whitespace is disabled then find the end of the // line if (!_includeTrailingWhitespace) { - while(outputCount > 0 && characters[start + outputCount - 1].isSpace()) { + while (outputCount > 0 && characters[start + outputCount - 1].isSpace()) { outputCount--; } } // find out the last technically real character in the line int realCharacterGuard = -1; - for (int i = count - 1 ; i >= start ; i--) { + for (int i = count - 1; i >= start; i--) { // FIXME: the special case of '\n' here is really ugly // Maybe the '\n' should be added after calling this method in // Screen::copyLineToStream() @@ -112,7 +112,7 @@ void PlainTextDecoder::decodeLine(const Character* const characters, int count, for (int i = start; i < outputCount;) { if ((characters[i].rendition & RE_EXTENDED_CHAR) != 0) { ushort extendedCharLength = 0; - const uint* chars = ExtendedCharTable::instance.lookupExtendedChar(characters[i].character, extendedCharLength); + const uint *chars = ExtendedCharTable::instance.lookupExtendedChar(characters[i].character, extendedCharLength); if (chars != nullptr) { const QString s = QString::fromUcs4(chars, extendedCharLength); plainText.append(s); @@ -132,7 +132,7 @@ void PlainTextDecoder::decodeLine(const Character* const characters, int count, plainText.append(QString::fromUcs4(&characters[i].character, 1)); i += qMax(1, characters[i].width()); } else { - ++i; // should we 'break' directly here? + ++i; // should we 'break' directly here? } } } diff --git a/src/decoders/PlainTextDecoder.h b/src/decoders/PlainTextDecoder.h index 132033bd6..b84a547ca 100644 --- a/src/decoders/PlainTextDecoder.h +++ b/src/decoders/PlainTextDecoder.h @@ -11,54 +11,54 @@ #include "TerminalCharacterDecoder.h" class QTextStream; -template class QList; +template +class QList; namespace Konsole { +/** + * A terminal character decoder which produces plain text, ignoring colors and other appearance-related + * properties of the original characters. + */ +class KONSOLEDECODERS_EXPORT PlainTextDecoder : public TerminalCharacterDecoder +{ +public: + PlainTextDecoder(); + /** - * A terminal character decoder which produces plain text, ignoring colors and other appearance-related - * properties of the original characters. + * Set whether leading whitespace at the end of lines should be included + * in the output. + * Defaults to true. */ - class KONSOLEDECODERS_EXPORT PlainTextDecoder : public TerminalCharacterDecoder - { - public: - PlainTextDecoder(); + void setLeadingWhitespace(bool enable); + /** + * Set whether trailing whitespace at the end of lines should be included + * in the output. + * Defaults to true. + */ + void setTrailingWhitespace(bool enable); + /** + * 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); - /** - * Set whether leading whitespace at the end of lines should be included - * in the output. - * Defaults to true. - */ - void setLeadingWhitespace(bool enable); - /** - * Set whether trailing whitespace at the end of lines should be included - * in the output. - * Defaults to true. - */ - void setTrailingWhitespace(bool enable); - /** - * 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); + void begin(QTextStream *output) override; + void end() override; - void begin(QTextStream *output) override; - void end() override; + void decodeLine(const Character *const characters, int count, LineProperty properties) override; - void decodeLine(const Character * const characters, int count, - LineProperty properties) override; +private: + QTextStream *_output; + bool _includeLeadingWhitespace; + bool _includeTrailingWhitespace; - private: - QTextStream *_output; - bool _includeLeadingWhitespace; - bool _includeTrailingWhitespace; - - bool _recordLinePositions; - QList _linePositions; - }; + bool _recordLinePositions; + QList _linePositions; +}; } #endif diff --git a/src/decoders/TerminalCharacterDecoder.h b/src/decoders/TerminalCharacterDecoder.h index f61593633..8d2c8ee38 100644 --- a/src/decoders/TerminalCharacterDecoder.h +++ b/src/decoders/TerminalCharacterDecoder.h @@ -8,8 +8,8 @@ #define TERMINAL_CHARACTER_DECODER_H // Qt -#include #include +#include // Konsole characters #include @@ -19,8 +19,8 @@ class QTextStream; -namespace Konsole { - +namespace Konsole +{ /** * Base class for terminal character decoders * @@ -50,8 +50,7 @@ public: * @param count The number of characters * @param properties Additional properties which affect all characters in the line */ - virtual void decodeLine(const Character * const characters, int count, - LineProperty properties) = 0; + virtual void decodeLine(const Character *const characters, int count, LineProperty properties) = 0; }; } diff --git a/src/delegates/ProfileShortcutDelegate.cpp b/src/delegates/ProfileShortcutDelegate.cpp index d37bde193..6a4a16f98 100644 --- a/src/delegates/ProfileShortcutDelegate.cpp +++ b/src/delegates/ProfileShortcutDelegate.cpp @@ -13,22 +13,21 @@ using namespace Konsole; ShortcutItemDelegate::ShortcutItemDelegate(QObject *parent) - : QStyledItemDelegate(parent), - _modifiedEditors(QSet()), - _itemsBeingEdited(QSet()) + : QStyledItemDelegate(parent) + , _modifiedEditors(QSet()) + , _itemsBeingEdited(QSet()) { } void ShortcutItemDelegate::editorModified() { - auto *editor = qobject_cast(sender()); + auto *editor = qobject_cast(sender()); Q_ASSERT(editor); _modifiedEditors.insert(editor); Q_EMIT commitData(editor); Q_EMIT closeEditor(editor); } -void ShortcutItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, - const QModelIndex &index) const +void ShortcutItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { _itemsBeingEdited.remove(index); @@ -42,7 +41,7 @@ void ShortcutItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *mod _modifiedEditors.remove(editor); } -QWidget* ShortcutItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem&, const QModelIndex &index) const +QWidget *ShortcutItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &, const QModelIndex &index) const { _itemsBeingEdited.insert(index); @@ -56,8 +55,7 @@ QWidget* ShortcutItemDelegate::createEditor(QWidget *parent, const QStyleOptionV return editor; } -void ShortcutItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, - const QModelIndex &index) const +void ShortcutItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { if (_itemsBeingEdited.contains(index)) { StyledBackgroundPainter::drawBackground(painter, option, index); @@ -72,8 +70,7 @@ QSize ShortcutItemDelegate::sizeHint(const QStyleOptionViewItem &option, const Q const auto fm = option.fontMetrics; static const int editorMargins = 16; // chosen empirically - const int width = fm.boundingRect(shortcutString + QStringLiteral(", ...")).width() - + editorMargins; + const int width = fm.boundingRect(shortcutString + QStringLiteral(", ...")).width() + editorMargins; return {width, QStyledItemDelegate::sizeHint(option, index).height()}; } @@ -85,11 +82,10 @@ void ShortcutItemDelegate::destroyEditor(QWidget *editor, const QModelIndex &ind editor->deleteLater(); } - void FilteredKeySequenceEdit::keyPressEvent(QKeyEvent *event) { - if(event->modifiers() == Qt::NoModifier) { - switch(event->key()) { + if (event->modifiers() == Qt::NoModifier) { + switch (event->key()) { case Qt::Key_Enter: case Qt::Key_Return: Q_EMIT editingFinished(); @@ -108,14 +104,12 @@ void FilteredKeySequenceEdit::keyPressEvent(QKeyEvent *event) QKeySequenceEdit::keyPressEvent(event); } -void StyledBackgroundPainter::drawBackground(QPainter *painter, const QStyleOptionViewItem &option, - const QModelIndex&) +void StyledBackgroundPainter::drawBackground(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &) { - const auto* opt = qstyleoption_cast(&option); - const QWidget* widget = opt != nullptr ? opt->widget : nullptr; + const auto *opt = qstyleoption_cast(&option); + const QWidget *widget = opt != nullptr ? opt->widget : nullptr; - QStyle* style = widget != nullptr ? widget->style() : QApplication::style(); + QStyle *style = widget != nullptr ? widget->style() : QApplication::style(); style->drawPrimitive(QStyle::PE_PanelItemViewItem, &option, painter, widget); } - diff --git a/src/delegates/ProfileShortcutDelegate.h b/src/delegates/ProfileShortcutDelegate.h index 9a993a0df..1455b1611 100644 --- a/src/delegates/ProfileShortcutDelegate.h +++ b/src/delegates/ProfileShortcutDelegate.h @@ -7,10 +7,10 @@ #ifndef PROFILESHORTCUTDELEGATE_H #define PROFILESHORTCUTDELEGATE_H -#include +#include #include #include -#include +#include class QWidget; class QKeyEvent; @@ -18,20 +18,21 @@ class QPainter; namespace Konsole { - class StyledBackgroundPainter { public: - static void drawBackground(QPainter *painter, const QStyleOptionViewItem &option, - const QModelIndex &index); + static void drawBackground(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index); }; -class FilteredKeySequenceEdit: public QKeySequenceEdit +class FilteredKeySequenceEdit : public QKeySequenceEdit { Q_OBJECT public: - explicit FilteredKeySequenceEdit(QWidget *parent = nullptr): QKeySequenceEdit(parent) {} + explicit FilteredKeySequenceEdit(QWidget *parent = nullptr) + : QKeySequenceEdit(parent) + { + } protected: void keyPressEvent(QKeyEvent *event) override; @@ -44,14 +45,10 @@ class ShortcutItemDelegate : public QStyledItemDelegate public: explicit ShortcutItemDelegate(QObject *parent = nullptr); - void setModelData(QWidget *editor, QAbstractItemModel *model, - const QModelIndex &index) const override; - QWidget *createEditor(QWidget *aParent, const QStyleOptionViewItem &option, - const QModelIndex &index) const override; - void paint(QPainter *painter, const QStyleOptionViewItem &option, - const QModelIndex &index) const override; - QSize sizeHint(const QStyleOptionViewItem &option, - const QModelIndex &index) const override; + void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const override; + QWidget *createEditor(QWidget *aParent, const QStyleOptionViewItem &option, const QModelIndex &index) const override; + void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override; + QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override; void destroyEditor(QWidget *editor, const QModelIndex &index) const override; private Q_SLOTS: diff --git a/src/filterHotSpots/ColorFilter.cpp b/src/filterHotSpots/ColorFilter.cpp index 2ff130289..6a0518fc1 100644 --- a/src/filterHotSpots/ColorFilter.cpp +++ b/src/filterHotSpots/ColorFilter.cpp @@ -10,24 +10,22 @@ using namespace Konsole; #include "ColorFilterHotSpot.h" - // This matches: // - an RGB-style string (e.g., #3e3, #feed) delimited by non-alphanumerics; // - or, a sequence of ASCII characters (e.g., foobar, Aquamarine, TOMATO). // See the docs for `QColor::setNamedColor`. -const QRegularExpression ColorFilter::ColorRegExp( - QStringLiteral("((? ColorFilter::newHotSpot(int startLine, int startColumn, int endLine, - int endColumn, const QStringList &capturedTexts) +QSharedPointer ColorFilter::newHotSpot(int startLine, int startColumn, int endLine, int endColumn, const QStringList &capturedTexts) { QColor color(capturedTexts.at(1)); @@ -36,6 +34,5 @@ QSharedPointer ColorFilter::newHotSpot(int startLine, int startColumn, return nullptr; } - return QSharedPointer( - new ColorFilterHotSpot(startLine, startColumn, endLine, endColumn, capturedTexts, color)); + return QSharedPointer(new ColorFilterHotSpot(startLine, startColumn, endLine, endColumn, capturedTexts, color)); } diff --git a/src/filterHotSpots/ColorFilter.h b/src/filterHotSpots/ColorFilter.h index b1003572f..b93709a85 100644 --- a/src/filterHotSpots/ColorFilter.h +++ b/src/filterHotSpots/ColorFilter.h @@ -11,17 +11,16 @@ namespace Konsole { - class ColorFilter : public RegExpFilter - { - public: - ColorFilter(); +class ColorFilter : public RegExpFilter +{ +public: + ColorFilter(); - static const QRegularExpression ColorRegExp; + static const QRegularExpression ColorRegExp; - protected: - QSharedPointer newHotSpot(int startLine, int startColumn, int endLine, - int endColumn, const QStringList &capturedTexts) override; - }; +protected: + QSharedPointer newHotSpot(int startLine, int startColumn, int endLine, int endColumn, const QStringList &capturedTexts) override; +}; } #endif diff --git a/src/filterHotSpots/ColorFilterHotSpot.cpp b/src/filterHotSpots/ColorFilterHotSpot.cpp index 87c4d485b..8901e3bfe 100644 --- a/src/filterHotSpots/ColorFilterHotSpot.cpp +++ b/src/filterHotSpots/ColorFilterHotSpot.cpp @@ -7,12 +7,12 @@ #include "ColorFilterHotSpot.h" #include -#include #include -#include #include -#include #include +#include +#include +#include #include "KonsoleSettings.h" @@ -20,8 +20,7 @@ using namespace Konsole; bool ColorFilterHotSpot::_canGenerateTooltip = false; -ColorFilterHotSpot::ColorFilterHotSpot(int startLine, int startColumn, int endLine, int endColumn, - const QStringList &capturedTexts, const QColor &color) +ColorFilterHotSpot::ColorFilterHotSpot(int startLine, int startColumn, int endLine, int endColumn, const QStringList &capturedTexts, const QColor &color) : RegExpFilterHotSpot(startLine, startColumn, endLine, endColumn, capturedTexts) , _color(color) { @@ -34,7 +33,7 @@ void ColorFilterHotSpot::mouseEnterEvent(TerminalDisplay *td, QMouseEvent *ev) _toolPos = ev->globalPos(); _canGenerateTooltip = true; - QTimer::singleShot(100, this, [&]{ + QTimer::singleShot(100, this, [&] { tooltipRequested(); }); } @@ -79,8 +78,7 @@ void ColorFilterHotSpot::tooltipRequested() QBuffer buffer(&data); pix.save(&buffer, "PNG"); - const auto tooltipString = QStringLiteral("") - .arg(QString::fromLocal8Bit(data.toBase64())); + const auto tooltipString = QStringLiteral("").arg(QString::fromLocal8Bit(data.toBase64())); QPoint tooltipPosition = QPoint(_toolPos.x(), _toolPos.y()); QToolTip::showText(tooltipPosition, tooltipString, qApp->focusWidget()); diff --git a/src/filterHotSpots/ColorFilterHotSpot.h b/src/filterHotSpots/ColorFilterHotSpot.h index dd458cb3c..f37620ca1 100644 --- a/src/filterHotSpots/ColorFilterHotSpot.h +++ b/src/filterHotSpots/ColorFilterHotSpot.h @@ -9,29 +9,28 @@ #include "RegExpFilterHotspot.h" +#include #include #include -#include - namespace Konsole { - class ColorFilterHotSpot : public RegExpFilterHotSpot - { - public: - ColorFilterHotSpot(int startLine, int startColumn, int endLine, int endColumn, const QStringList &capturedTexts, const QColor &color); - ~ColorFilterHotSpot() override = default; +class ColorFilterHotSpot : public RegExpFilterHotSpot +{ +public: + ColorFilterHotSpot(int startLine, int startColumn, int endLine, int endColumn, const QStringList &capturedTexts, const QColor &color); + ~ColorFilterHotSpot() override = default; - void mouseEnterEvent(TerminalDisplay *td, QMouseEvent *ev) override; - void mouseLeaveEvent(TerminalDisplay *td, QMouseEvent *ev) override; + void mouseEnterEvent(TerminalDisplay *td, QMouseEvent *ev) override; + void mouseLeaveEvent(TerminalDisplay *td, QMouseEvent *ev) override; - private: - void tooltipRequested(); +private: + void tooltipRequested(); - QColor _color; - QPoint _toolPos; - static bool _canGenerateTooltip; - }; + QColor _color; + QPoint _toolPos; + static bool _canGenerateTooltip; +}; } #endif diff --git a/src/filterHotSpots/EscapeSequenceUrlFilter.cpp b/src/filterHotSpots/EscapeSequenceUrlFilter.cpp index f41f20213..1d13b143f 100644 --- a/src/filterHotSpots/EscapeSequenceUrlFilter.cpp +++ b/src/filterHotSpots/EscapeSequenceUrlFilter.cpp @@ -7,14 +7,14 @@ #include "EscapeSequenceUrlFilter.h" -#include "session/Session.h" -#include "terminalDisplay/TerminalDisplay.h" #include "EscapeSequenceUrlExtractor.h" #include "EscapeSequenceUrlFilterHotSpot.h" +#include "session/Session.h" +#include "terminalDisplay/TerminalDisplay.h" using namespace Konsole; -EscapeSequenceUrlFilter::EscapeSequenceUrlFilter(Session* session, TerminalDisplay *window) +EscapeSequenceUrlFilter::EscapeSequenceUrlFilter(Session *session, TerminalDisplay *window) { _session = session; _window = window; @@ -39,12 +39,7 @@ void EscapeSequenceUrlFilter::process() // TODO: // This uses Column / Row while everything else uses Row/Column. // Move everything else to QPoint begin / QPoint End. - new EscapeSequenceUrlHotSpot(beginRow, escapedUrl.begin.col, - endRow, escapedUrl.end.col, - escapedUrl.text, - escapedUrl.url - ) - ); + new EscapeSequenceUrlHotSpot(beginRow, escapedUrl.begin.col, endRow, escapedUrl.end.col, escapedUrl.text, escapedUrl.url)); addHotSpot(spot); } diff --git a/src/filterHotSpots/EscapeSequenceUrlFilter.h b/src/filterHotSpots/EscapeSequenceUrlFilter.h index 4cd474294..9988a4e81 100644 --- a/src/filterHotSpots/EscapeSequenceUrlFilter.h +++ b/src/filterHotSpots/EscapeSequenceUrlFilter.h @@ -12,11 +12,12 @@ #include -namespace Konsole { +namespace Konsole +{ class Session; class TerminalDisplay; - /* This filter is different from the Url filter as there's no +/* This filter is different from the Url filter as there's no * URL's in the screen. Vt102Emulation will store a vector of * URL/Text, we need to match if this is in the screen. For that we need a pointer * for the Vt102Emulation or at least the data structure that holds the information @@ -28,6 +29,7 @@ public: EscapeSequenceUrlFilter(Session *session, TerminalDisplay *display); void process() override; + private: QPointer _session; QPointer _window; diff --git a/src/filterHotSpots/EscapeSequenceUrlFilterHotSpot.cpp b/src/filterHotSpots/EscapeSequenceUrlFilterHotSpot.cpp index f24f9064f..9072f338c 100644 --- a/src/filterHotSpots/EscapeSequenceUrlFilterHotSpot.cpp +++ b/src/filterHotSpots/EscapeSequenceUrlFilterHotSpot.cpp @@ -11,23 +11,17 @@ #include #include -#include #include +#include #include "terminalDisplay/TerminalDisplay.h" using namespace Konsole; -EscapeSequenceUrlHotSpot::EscapeSequenceUrlHotSpot( - int startLine, - int startColumn, - int endLine, - int endColumn, - const QString &text, - const QString &url) : - HotSpot(startLine, startColumn, endLine, endColumn), - _text(text), - _url(url) +EscapeSequenceUrlHotSpot::EscapeSequenceUrlHotSpot(int startLine, int startColumn, int endLine, int endColumn, const QString &text, const QString &url) + : HotSpot(startLine, startColumn, endLine, endColumn) + , _text(text) + , _url(url) { setType(EscapedUrl); } diff --git a/src/filterHotSpots/EscapeSequenceUrlFilterHotSpot.h b/src/filterHotSpots/EscapeSequenceUrlFilterHotSpot.h index f1e3d1ae3..5d26b535e 100644 --- a/src/filterHotSpots/EscapeSequenceUrlFilterHotSpot.h +++ b/src/filterHotSpots/EscapeSequenceUrlFilterHotSpot.h @@ -10,13 +10,12 @@ #include "HotSpot.h" -namespace Konsole { - +namespace Konsole +{ class EscapeSequenceUrlHotSpot : public HotSpot { public: - EscapeSequenceUrlHotSpot(int startLine, int startColumn, int endLine, int endColumn, - const QString &text, const QString &url); + EscapeSequenceUrlHotSpot(int startLine, int startColumn, int endLine, int endColumn, const QString &text, const QString &url); void activate(QObject *obj) override; private: diff --git a/src/filterHotSpots/FileFilter.cpp b/src/filterHotSpots/FileFilter.cpp index 17ef0f229..f479dc149 100644 --- a/src/filterHotSpots/FileFilter.cpp +++ b/src/filterHotSpots/FileFilter.cpp @@ -9,9 +9,9 @@ #include +#include "profile/Profile.h" #include "session/Session.h" #include "session/SessionManager.h" -#include "profile/Profile.h" #include "FileFilterHotspot.h" @@ -20,8 +20,8 @@ using namespace Konsole; // static QRegularExpression FileFilter::_regex; -FileFilter::FileFilter(Session *session, const QString &wordCharacters) : - _session(session) +FileFilter::FileFilter(Session *session, const QString &wordCharacters) + : _session(session) , _dirPath(QString()) , _currentDirContents() { @@ -41,7 +41,7 @@ QString FileFilter::concatRegexPattern(QString wordCharacters) const } // Add minus at the end. - if (wordCharacters.contains(QLatin1Char('-'))){ + if (wordCharacters.contains(QLatin1Char('-'))) { wordCharacters.remove(QLatin1Char('-')); wordCharacters.append(QLatin1Char('-')); } @@ -54,33 +54,32 @@ QString FileFilter::concatRegexPattern(QString wordCharacters) const * on the HotSpot creation we verify if this is indeed a file, so there's * no problem on testing on random words on the screen. */ - QStringLiteral(R"RX('[^'\n]+')RX") // Matches everything between single quotes. - + QStringLiteral(R"RX(|"[^\n"]+")RX") // Matches everything inside double quotes - // Matches a contiguous line of alphanumeric characters plus some special ones - // defined in the profile. With a special case for strings starting with '/' which - // denotes a path on Linux. - // Takes into account line numbers: - // - grep output with line numbers: "/path/to/file:123" - // - compiler error output: ":/path/to/file:123:123" - // - // ([^\n/\[]/) to not match "https://", and urls starting with "[" are matched by the - // next | branch (ctest stuff) - + QStringLiteral(R"RX(|([^\n\s/\[]/)?[\p{L}\w%1]+(:\d+)?(:\d+:)?)RX").arg(wordCharacters) - // - ctest error output: "[/path/to/file(123)]" - + QStringLiteral(R"RX(|\[[/\w%1]+\(\d+\)\])RX").arg(wordCharacters); + QStringLiteral(R"RX('[^'\n]+')RX") // Matches everything between single quotes. + + QStringLiteral(R"RX(|"[^\n"]+")RX") // Matches everything inside double quotes + // Matches a contiguous line of alphanumeric characters plus some special ones + // defined in the profile. With a special case for strings starting with '/' which + // denotes a path on Linux. + // Takes into account line numbers: + // - grep output with line numbers: "/path/to/file:123" + // - compiler error output: ":/path/to/file:123:123" + // + // ([^\n/\[]/) to not match "https://", and urls starting with "[" are matched by the + // next | branch (ctest stuff) + + QStringLiteral(R"RX(|([^\n\s/\[]/)?[\p{L}\w%1]+(:\d+)?(:\d+:)?)RX").arg(wordCharacters) + // - ctest error output: "[/path/to/file(123)]" + + QStringLiteral(R"RX(|\[[/\w%1]+\(\d+\)\])RX").arg(wordCharacters); return pattern; } /** - * File Filter - Construct a filter that works on local file paths using the - * posix portable filename character set combined with KDE's mimetype filename - * extension blob patterns. - * https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_267 - */ + * File Filter - Construct a filter that works on local file paths using the + * posix portable filename character set combined with KDE's mimetype filename + * extension blob patterns. + * https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_267 + */ -QSharedPointer FileFilter::newHotSpot(int startLine, int startColumn, int endLine, - int endColumn, const QStringList &capturedTexts) +QSharedPointer FileFilter::newHotSpot(int startLine, int startColumn, int endLine, int endColumn, const QStringList &capturedTexts) { if (_session.isNull()) { return nullptr; @@ -104,21 +103,19 @@ QSharedPointer FileFilter::newHotSpot(int startLine, int startColumn, i const bool absolute = filename.startsWith(QLatin1Char('/')); if (!absolute) { - auto match = std::find_if(_currentDirContents.cbegin(), _currentDirContents.cend(), - [&filename](const QString &s) { - return filename == s // It's a direct child file or dir - || filename.startsWith(s + QLatin1Char{':'}) // filename:lineNumber (output of grep -n) - || filename.startsWith(s + QLatin1Char{'/'}); // It's inside a child dir - }); + auto match = std::find_if(_currentDirContents.cbegin(), _currentDirContents.cend(), [&filename](const QString &s) { + return filename == s // It's a direct child file or dir + || filename.startsWith(s + QLatin1Char{':'}) // filename:lineNumber (output of grep -n) + || filename.startsWith(s + QLatin1Char{'/'}); // It's inside a child dir + }); if (match == _currentDirContents.cend()) { return nullptr; } } - return QSharedPointer(new FileFilterHotSpot(startLine, startColumn, endLine, endColumn, capturedTexts, - !absolute ? _dirPath + filename : filename, - _session)); + return QSharedPointer( + new FileFilterHotSpot(startLine, startColumn, endLine, endColumn, capturedTexts, !absolute ? _dirPath + filename : filename, _session)); } void FileFilter::process() diff --git a/src/filterHotSpots/FileFilter.h b/src/filterHotSpots/FileFilter.h index 4bc89c823..a5493bce4 100644 --- a/src/filterHotSpots/FileFilter.h +++ b/src/filterHotSpots/FileFilter.h @@ -9,12 +9,13 @@ #define FILE_FILTER #include -#include #include +#include #include "RegExpFilter.h" -namespace Konsole { +namespace Konsole +{ class Session; class HotSpot; diff --git a/src/filterHotSpots/FileFilterHotspot.cpp b/src/filterHotSpots/FileFilterHotspot.cpp index 86898d753..3945cf491 100644 --- a/src/filterHotSpots/FileFilterHotspot.cpp +++ b/src/filterHotSpots/FileFilterHotspot.cpp @@ -7,47 +7,50 @@ #include "FileFilterHotspot.h" -#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 "konsoledebug.h" #include "KonsoleSettings.h" +#include "konsoledebug.h" #include "profile/Profile.h" #include "session/SessionManager.h" #include "terminalDisplay/TerminalDisplay.h" using namespace Konsole; - -FileFilterHotSpot::FileFilterHotSpot(int startLine, int startColumn, int endLine, int endColumn, - const QStringList &capturedTexts, const QString &filePath, +FileFilterHotSpot::FileFilterHotSpot(int startLine, + int startColumn, + int endLine, + int endColumn, + const QStringList &capturedTexts, + const QString &filePath, Session *session) - : RegExpFilterHotSpot(startLine, startColumn, endLine, endColumn, capturedTexts), - _filePath(filePath), - _session(session), - _thumbnailFinished(false) + : RegExpFilterHotSpot(startLine, startColumn, endLine, endColumn, capturedTexts) + , _filePath(filePath) + , _session(session) + , _thumbnailFinished(false) { setType(Link); } @@ -111,8 +114,7 @@ void FileFilterHotSpot::activate(QObject *) // There was no match, i.e. regular url "path/to/file" // Clean up the file path; the second branch in the regex is for "path/to/file:" QString path(_filePath); - static const QRegularExpression cleanupRe(QStringLiteral(R"foo((:\d+[:]?|:)$)foo"), - QRegularExpression::DontCaptureOption); + static const QRegularExpression cleanupRe(QStringLiteral(R"foo((:\d+[:]?|:)$)foo"), QRegularExpression::DontCaptureOption); path.remove(cleanupRe); if (!editorExecPath.isEmpty()) { // Use the editor from the profile settings const QString fCmd = editorExecPath + QLatin1Char(' ') + path; @@ -155,8 +157,8 @@ void FileFilterHotSpot::openWithEditorFromProfile(const QString &fullCmd, const if (job->error() != 0) { // TODO: use KMessageWidget (like the "terminal is read-only" message) KMessageBox::sorry(QApplication::activeWindow(), - i18n("Could not open file with the text editor specified in the profile settings;\n" - "it will be opened with the system default editor.")); + i18n("Could not open file with the text editor specified in the profile settings;\n" + "it will be opened with the system default editor.")); openWithSysDefaultApp(path); } @@ -186,7 +188,7 @@ QList FileFilterHotSpot::setupMenu(QMenu *menu) const KFileItemListProperties itemProperties(itemList); _menuActions.setParent(this); _menuActions.setItemListProperties(itemProperties); -#if KIO_VERSION < QT_VERSION_CHECK(5,82,0) +#if KIO_VERSION < QT_VERSION_CHECK(5, 82, 0) _menuActions.addOpenWithActionsTo(menu); // Here we added the actions to the last part of the menu, but we need to move them up. @@ -231,7 +233,7 @@ void FileFilterHotSpot::requestThumbnail(Qt::KeyboardModifiers modifiers, const _eventPos = pos; // Defer the real creation of the thumbnail by a few msec. - QTimer::singleShot(250, this, [this]{ + QTimer::singleShot(250, this, [this] { thumbnailRequested(); }); } @@ -245,7 +247,7 @@ void FileFilterHotSpot::stopThumbnailGeneration() } } -void FileFilterHotSpot::showThumbnail(const KFileItem& item, const QPixmap& preview) +void FileFilterHotSpot::showThumbnail(const KFileItem &item, const QPixmap &preview) { if (!_canGenerateThumbnail) { return; @@ -256,13 +258,13 @@ void FileFilterHotSpot::showThumbnail(const KFileItem& item, const QPixmap& prev QBuffer buffer(&data); preview.save(&buffer, "PNG", 100); - const auto tooltipString = QStringLiteral("") - .arg(QString::fromLocal8Bit(data.toBase64())); + const auto tooltipString = QStringLiteral("").arg(QString::fromLocal8Bit(data.toBase64())); QToolTip::showText(_thumbnailPos, tooltipString, qApp->focusWidget()); } -void FileFilterHotSpot::thumbnailRequested() { +void FileFilterHotSpot::thumbnailRequested() +{ if (!_canGenerateThumbnail) { return; } @@ -287,7 +289,7 @@ void FileFilterHotSpot::thumbnailRequested() { _thumbnailFinished = false; // Show a "Loading" if Preview takes a long time. - QTimer::singleShot(10, this, [this]{ + QTimer::singleShot(10, this, [this] { if (_previewJob == nullptr) { return; } @@ -298,7 +300,7 @@ void FileFilterHotSpot::thumbnailRequested() { _previewJob = new KIO::PreviewJob(KFileItemList({fileItem()}), QSize(size, size)); connect(_previewJob, &KIO::PreviewJob::gotPreview, this, &FileFilterHotSpot::showThumbnail); - connect(_previewJob, &KIO::PreviewJob::failed, this, []{ + connect(_previewJob, &KIO::PreviewJob::failed, this, [] { qCDebug(KonsoleDebug) << "Error generating the preview" << _previewJob->errorString(); QToolTip::hideText(); }); @@ -324,13 +326,12 @@ void FileFilterHotSpot::mouseLeaveEvent(TerminalDisplay *td, QMouseEvent *ev) stopThumbnailGeneration(); } -void FileFilterHotSpot::keyPressEvent(Konsole::TerminalDisplay* td, QKeyEvent* ev) +void FileFilterHotSpot::keyPressEvent(Konsole::TerminalDisplay *td, QKeyEvent *ev) { HotSpot::keyPressEvent(td, ev); requestThumbnail(ev->modifiers(), QCursor::pos()); } - bool FileFilterHotSpot::hasDragOperation() const { return true; diff --git a/src/filterHotSpots/FileFilterHotspot.h b/src/filterHotSpots/FileFilterHotspot.h index b527f59c5..9d8ff9f76 100644 --- a/src/filterHotSpots/FileFilterHotspot.h +++ b/src/filterHotSpots/FileFilterHotspot.h @@ -11,11 +11,11 @@ #include "RegExpFilterHotspot.h" #include -#include #include +#include -#include #include +#include #include class QAction; @@ -23,25 +23,25 @@ class QPixmap; class QKeyEvent; class QMouseEvent; -namespace Konsole { +namespace Konsole +{ class Session; class TerminalDisplay; /** -* Hotspot type created by FileFilter instances. -*/ + * Hotspot type created by FileFilter instances. + */ class FileFilterHotSpot : public RegExpFilterHotSpot { public: - FileFilterHotSpot(int startLine, int startColumn, int endLine, int endColumn, - const QStringList &capturedTexts, const QString &filePath, Session *session); + FileFilterHotSpot(int startLine, int startColumn, int endLine, int endColumn, const QStringList &capturedTexts, const QString &filePath, Session *session); ~FileFilterHotSpot() override; QList actions() override; /** - * Opens kate for editing the file. - */ + * Opens kate for editing the file. + */ void activate(QObject *object = nullptr) override; QList setupMenu(QMenu *menu) override; @@ -63,7 +63,7 @@ private: void openWithSysDefaultApp(const QString &filePath) const; void openWithEditorFromProfile(const QString &fullCmd, const QString &path) const; - void showThumbnail(const KFileItem& item, const QPixmap& preview); + void showThumbnail(const KFileItem &item, const QPixmap &preview); QString _filePath; Session *_session = nullptr; KFileItemActions _menuActions; @@ -74,9 +74,9 @@ private: bool _thumbnailFinished; /* This variable stores the pointer of the active HotSpot that - * is generating the thumbnail now, so we can bail out early. - * it's not used for pointer access. - */ + * is generating the thumbnail now, so we can bail out early. + * it's not used for pointer access. + */ static qintptr currentThumbnailHotspot; static bool _canGenerateThumbnail; static QPointer _previewJob; diff --git a/src/filterHotSpots/Filter.cpp b/src/filterHotSpots/Filter.cpp index 1cbe7845f..37be0b337 100644 --- a/src/filterHotSpots/Filter.cpp +++ b/src/filterHotSpots/Filter.cpp @@ -11,11 +11,9 @@ using namespace Konsole; - - -Filter::Filter() : - _linePositions(nullptr), - _buffer(nullptr) +Filter::Filter() + : _linePositions(nullptr) + , _buffer(nullptr) { } @@ -42,13 +40,10 @@ std::pair Filter::getLineColumn(int position) Q_ASSERT(_buffer); for (int i = 0; i < _linePositions->count(); i++) { - const int nextLine = i == _linePositions->count() - 1 - ? _buffer->length() + 1 - : _linePositions->value(i + 1); + const int nextLine = i == _linePositions->count() - 1 ? _buffer->length() + 1 : _linePositions->value(i + 1); if (_linePositions->value(i) <= position && position < nextLine) { - return {i, Character::stringWidth(buffer()->mid(_linePositions->value(i), - position - _linePositions->value(i)))}; + return {i, Character::stringWidth(buffer()->mid(_linePositions->value(i), position - _linePositions->value(i)))}; } } return {-1, -1}; @@ -59,7 +54,6 @@ const QString *Filter::buffer() return _buffer; } - void Filter::addHotSpot(QSharedPointer spot) { _hotspotList << spot; diff --git a/src/filterHotSpots/Filter.h b/src/filterHotSpots/Filter.h index 6393072a2..f4dfb52ba 100644 --- a/src/filterHotSpots/Filter.h +++ b/src/filterHotSpots/Filter.h @@ -10,18 +10,18 @@ // Qt #include -#include -#include -#include -#include -#include #include -#include +#include #include +#include +#include +#include +#include +#include // KDE -#include #include +#include #include #include @@ -33,7 +33,8 @@ class QAction; class QMenu; class QMouseEvent; -namespace Konsole { +namespace Konsole +{ class Session; class HotSpot; @@ -90,7 +91,7 @@ protected: /** Returns the internal buffer */ const QString *buffer(); /** Converts a character position within buffer() to a line and column */ - std::pair getLineColumn(int position); + std::pair getLineColumn(int position); private: Q_DISABLE_COPY(Filter) diff --git a/src/filterHotSpots/FilterChain.cpp b/src/filterHotSpots/FilterChain.cpp index 5a607fdee..e45cf6a09 100644 --- a/src/filterHotSpots/FilterChain.cpp +++ b/src/filterHotSpots/FilterChain.cpp @@ -8,27 +8,25 @@ #include "FilterChain.h" #include "Filter.h" -#include "terminalDisplay/TerminalDisplay.h" #include "terminalDisplay/TerminalColor.h" +#include "terminalDisplay/TerminalDisplay.h" #include "terminalDisplay/TerminalFonts.h" -#include +#include #include #include #include -#include +#include #include - using namespace Konsole; FilterChain::FilterChain(TerminalDisplay *terminalDisplay) - : _terminalDisplay(terminalDisplay), - _showUrlHint(false), - _reverseUrlHints(false), - _urlHintsModifiers(Qt::NoModifier) + : _terminalDisplay(terminalDisplay) + , _showUrlHint(false) + , _reverseUrlHints(false) + , _urlHintsModifiers(Qt::NoModifier) { - } FilterChain::~FilterChain() { @@ -47,21 +45,21 @@ void FilterChain::removeFilter(Filter *filter) void FilterChain::reset() { - for(auto *filter : _filters) { + for (auto *filter : _filters) { filter->reset(); } } void FilterChain::setBuffer(const QString *buffer, const QList *linePositions) { - for(auto *filter : _filters) { + for (auto *filter : _filters) { filter->setBuffer(buffer, linePositions); } } void FilterChain::process() { - for( auto *filter : _filters) { + for (auto *filter : _filters) { filter->process(); } } @@ -73,10 +71,10 @@ void FilterChain::clear() QSharedPointer FilterChain::hotSpotAt(int line, int column) const { - for(auto *filter : _filters) { + for (auto *filter : _filters) { QSharedPointer spot = filter->hotSpotAt(line, column); if (spot != nullptr) { - return spot; + return spot; } } return nullptr; @@ -87,11 +85,10 @@ QList> FilterChain::hotSpots() const QList> list; for (auto *filter : _filters) { list.append(filter->hotSpots()); - } + } return list; } - QRegion FilterChain::hotSpotRegion() const { QRegion region; @@ -110,7 +107,7 @@ QRegion FilterChain::hotSpotRegion() const r.setLeft(0); - for (int line = hotSpot->startLine() + 1 ; line < hotSpot->endLine(); line++) { + for (int line = hotSpot->startLine() + 1; line < hotSpot->endLine(); line++) { r.moveTop(line); region |= _terminalDisplay->imageToWidget(r); } @@ -126,10 +123,9 @@ QRegion FilterChain::hotSpotRegion() const int FilterChain::count(HotSpot::Type type) const { const auto hSpots = hotSpots(); - return std::count_if(std::begin(hSpots), std::end(hSpots), - [type](const QSharedPointer &s) { - return s->type() == type; - }); + return std::count_if(std::begin(hSpots), std::end(hSpots), [type](const QSharedPointer &s) { + return s->type() == type; + }); } QList> FilterChain::filterBy(HotSpot::Type type) const @@ -195,7 +191,7 @@ bool FilterChain::keyPressEvent(TerminalDisplay *td, QKeyEvent *ev, int charLine return false; } -void FilterChain::mouseMoveEvent(TerminalDisplay *td, QMouseEvent *ev, int charLine, int charColumn) +void FilterChain::mouseMoveEvent(TerminalDisplay *td, QMouseEvent *ev, int charLine, int charColumn) { auto spot = hotSpotAt(charLine, charColumn); if (_hotSpotUnderMouse != spot) { @@ -222,7 +218,7 @@ void FilterChain::mouseReleaseEvent(TerminalDisplay *td, QMouseEvent *ev, int ch spot->mouseReleaseEvent(td, ev); } -void FilterChain::paint(TerminalDisplay* td, QPainter& painter) +void FilterChain::paint(TerminalDisplay *td, QPainter &painter) { // get color of character under mouse and use it to draw // lines for filters @@ -230,7 +226,7 @@ void FilterChain::paint(TerminalDisplay* td, QPainter& painter) auto [cursorLine, cursorColumn] = td->getCharacterPosition(cursorPos, false); - Character cursorCharacter = td->getCursorCharacter( std::min(cursorColumn, td->columns() - 1), cursorLine); + Character cursorCharacter = td->getCursorCharacter(std::min(cursorColumn, td->columns() - 1), cursorLine); painter.setPen(QPen(cursorCharacter.foregroundColor.color(td->terminalColor()->colorTable()))); // iterate over hotspots identified by the display's currently active filters @@ -256,7 +252,8 @@ void FilterChain::paint(TerminalDisplay* td, QPainter& painter) for (const auto &spot : spots) { QRegion region; if (spot->type() == HotSpot::Link || spot->type() == HotSpot::EMailAddress || spot->type() == HotSpot::EscapedUrl) { - QPair spotRegion = spot->region(td->terminalFont()->fontWidth(), td->terminalFont()->fontHeight(), td->columns(), td->contentRect()); + QPair spotRegion = + spot->region(td->terminalFont()->fontWidth(), td->terminalFont()->fontHeight(), td->columns(), td->contentRect()); region = spotRegion.first; QRect r = spotRegion.second; @@ -281,7 +278,7 @@ void FilterChain::paint(TerminalDisplay* td, QPainter& painter) spot->debug(); } - for (int line = spot->startLine() ; line <= spot->endLine() ; line++) { + for (int line = spot->startLine(); line <= spot->endLine(); line++) { int startColumn = 0; int endColumn = td->columns() - 1; // TODO use number of _columns which are actually // occupied on this line rather than the width of the @@ -322,7 +319,7 @@ void FilterChain::paint(TerminalDisplay* td, QPainter& painter) r.setCoords(startColumn * td->terminalFont()->fontWidth() + td->contentRect().left(), line * td->terminalFont()->fontHeight() + td->contentRect().top(), endColumn * td->terminalFont()->fontWidth() + td->contentRect().left() - 1, - (line + 1)* td->terminalFont()->fontHeight() + td->contentRect().top() - 1); + (line + 1) * td->terminalFont()->fontHeight() + td->contentRect().top() - 1); // Underline link hotspots // TODO: Fix accessing the urlHint here. @@ -336,12 +333,12 @@ void FilterChain::paint(TerminalDisplay* td, QPainter& painter) const int baseline = r.bottom() - metrics.descent(); // find the position of the underline below that const int underlinePos = baseline + metrics.underlinePos(); - painter.drawLine(r.left() , underlinePos, r.right() , underlinePos); + painter.drawLine(r.left(), underlinePos, r.right(), underlinePos); // Marker hotspots simply have a transparent rectangular shape // drawn on top of them } else if (spot->type() == HotSpot::Marker) { - //TODO - Do not use a hardcoded color for this + // TODO - Do not use a hardcoded color for this const bool isCurrentResultLine = (td->screenWindow()->currentResultLine() == (spot->startLine() + td->screenWindow()->currentLine())); QColor color = isCurrentResultLine ? QColor(255, 255, 0, 120) : QColor(255, 0, 0, 120); painter.fillRect(r, color); diff --git a/src/filterHotSpots/FilterChain.h b/src/filterHotSpots/FilterChain.h index 8926a2049..f854a4253 100644 --- a/src/filterHotSpots/FilterChain.h +++ b/src/filterHotSpots/FilterChain.h @@ -8,10 +8,10 @@ #ifndef FILTER_CHAIN #define FILTER_CHAIN -#include #include -#include #include +#include +#include #include "HotSpot.h" @@ -86,15 +86,16 @@ public: void setReverseUrlHints(bool value); void setUrlHintsModifiers(Qt::KeyboardModifiers value); + protected: QList _filters; TerminalDisplay *_terminalDisplay; QSharedPointer _hotSpotUnderMouse; /* TODO: this should be profile related, not here. but - * currently this removes a bit of code from TerminalDisplay, - * so it's a good compromise - * */ + * currently this removes a bit of code from TerminalDisplay, + * so it's a good compromise + * */ bool _showUrlHint; bool _reverseUrlHints; Qt::KeyboardModifiers _urlHintsModifiers; diff --git a/src/filterHotSpots/HotSpot.cpp b/src/filterHotSpots/HotSpot.cpp index e4777841c..24292c0ae 100644 --- a/src/filterHotSpots/HotSpot.cpp +++ b/src/filterHotSpots/HotSpot.cpp @@ -7,23 +7,23 @@ #include "HotSpot.h" -#include #include +#include +#include "FileFilterHotspot.h" #include "terminalDisplay/TerminalDisplay.h" #include "terminalDisplay/TerminalFonts.h" -#include "FileFilterHotspot.h" using namespace Konsole; HotSpot::~HotSpot() = default; -HotSpot::HotSpot(int startLine, int startColumn, int endLine, int endColumn) : - _startLine(startLine), - _startColumn(startColumn), - _endLine(endLine), - _endColumn(endColumn), - _type(NotSpecified) +HotSpot::HotSpot(int startLine, int startColumn, int endLine, int endColumn) + : _startLine(startLine) + , _startColumn(startColumn) + , _endLine(endLine) + , _endColumn(endColumn) + , _type(NotSpecified) { } @@ -81,22 +81,13 @@ QPair HotSpot::region(int fontWidth, int fontHeight, int columns (endLine() + 1) * fontHeight + top - 1); region |= r; } else { - r.setCoords(startColumn() * fontWidth + left, - startLine() * fontHeight + top, - (columns) * fontWidth + left - 1, - (startLine() + 1) *fontHeight + top - 1); + r.setCoords(startColumn() * fontWidth + left, startLine() * fontHeight + top, (columns)*fontWidth + left - 1, (startLine() + 1) * fontHeight + top - 1); region |= r; - for (int line = startLine() + 1 ; line < endLine() ; line++) { - r.setCoords(0 * fontWidth + left, - line * fontHeight + top, - (columns)* fontWidth + left - 1, - (line + 1)* fontHeight + top - 1); + for (int line = startLine() + 1; line < endLine(); line++) { + r.setCoords(0 * fontWidth + left, line * fontHeight + top, (columns)*fontWidth + left - 1, (line + 1) * fontHeight + top - 1); region |= r; } - r.setCoords(0 * fontWidth + left, - endLine()* fontHeight + top, - (endColumn()) * fontWidth + left - 1, - (endLine() + 1) * fontHeight + top - 1); + r.setCoords(0 * fontWidth + left, endLine() * fontHeight + top, (endColumn()) * fontWidth + left - 1, (endLine() + 1) * fontHeight + top - 1); region |= r; } return {region, r}; @@ -119,8 +110,7 @@ void HotSpot::mouseEnterEvent(TerminalDisplay *td, QMouseEvent *ev) return; } - if (td->cursor().shape() != Qt::PointingHandCursor - && ((td->openLinksByDirectClick() || ((ev->modifiers() & Qt::ControlModifier) != 0u)))) { + if (td->cursor().shape() != Qt::PointingHandCursor && ((td->openLinksByDirectClick() || ((ev->modifiers() & Qt::ControlModifier) != 0u)))) { td->setCursor(Qt::PointingHandCursor); } @@ -153,7 +143,7 @@ void HotSpot::mouseReleaseEvent(TerminalDisplay *td, QMouseEvent *ev) } } -void HotSpot::keyPressEvent(TerminalDisplay* td, QKeyEvent *ev) +void HotSpot::keyPressEvent(TerminalDisplay *td, QKeyEvent *ev) { if (!isUrl()) { return; @@ -180,9 +170,10 @@ void HotSpot::keyReleaseEvent(TerminalDisplay *td, QKeyEvent *ev) td->resetCursor(); } -void HotSpot::debug() { +void HotSpot::debug() +{ qDebug() << this; - qDebug() << type(); + qDebug() << type(); qDebug() << _startLine << _endLine << _startColumn << _endColumn; } @@ -194,4 +185,3 @@ bool Konsole::HotSpot::hasDragOperation() const void Konsole::HotSpot::startDrag() { } - diff --git a/src/filterHotSpots/HotSpot.h b/src/filterHotSpots/HotSpot.h index d7ce32308..5e67858b0 100644 --- a/src/filterHotSpots/HotSpot.h +++ b/src/filterHotSpots/HotSpot.h @@ -11,8 +11,8 @@ #include #include -#include #include +#include #include class QAction; @@ -20,21 +20,22 @@ class QMenu; class QMouseEvent; class QKeyEvent; -namespace Konsole { +namespace Konsole +{ class TerminalDisplay; /** -* Represents an area of text which matched the pattern a particular filter has been looking for. -* -* Each hotspot has a type identifier associated with it ( such as a link or a highlighted section ), -* and an action. When the user performs some activity such as a mouse-click in a hotspot area ( the exact -* action will depend on what is displaying the block of text which the filter is processing ), the hotspot's -* 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. -*/ + * Represents an area of text which matched the pattern a particular filter has been looking for. + * + * Each hotspot has a type identifier associated with it ( such as a link or a highlighted section ), + * and an action. When the user performs some activity such as a mouse-click in a hotspot area ( the exact + * action will depend on what is displaying the block of text which the filter is processing ), the hotspot's + * 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. + */ class HotSpot : public QObject { // krazy suggest using Q_OBJECT here but moc can not handle @@ -43,9 +44,9 @@ class HotSpot : public QObject public: /** - * Constructs a new hotspot which covers the area from (@p startLine,@p startColumn) to (@p endLine,@p endColumn) - * in a block of text. - */ + * Constructs a new hotspot which covers the area from (@p startLine,@p startColumn) to (@p endLine,@p endColumn) + * in a block of text. + */ HotSpot(int startLine, int startColumn, int endLine, int endColumn); virtual ~HotSpot(); @@ -73,23 +74,23 @@ public: /** 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 - */ + * 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 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. - */ + * Causes the action associated with a hotspot to be triggered. + * + * @param object The object which caused the hotspot to be triggered. This is + * typically null ( in which case the default action should be performed ) or + * one of the objects from the actions() list. In which case the associated + * action should be performed. + */ virtual void activate(QObject *object = nullptr) = 0; /** - * Returns a list of actions associated with the hotspot which can be used in a - * menu or toolbar - */ + * Returns a list of actions associated with the hotspot which can be used in a + * menu or toolbar + */ virtual QList actions(); virtual bool hasDragOperation() const; @@ -113,7 +114,7 @@ public: * Type enum), otherwise returns false; mainly used in the input events, e.g. to not * change the shape of the mouse pointer to a pointing hand if the HotSpot doesn't * represent a clickable URI. - */ + */ bool isUrl(); /** The base implementation does nothing */ @@ -122,20 +123,20 @@ public: /** * The mouse pointer shape is changed to a pointing hand; also because the underline * is painted under the link, update() is called on the TerminalDisplay widget. - */ + */ virtual void mouseEnterEvent(TerminalDisplay *td, QMouseEvent *ev); /** * The mouse pointer is reset to the default shape, see TerminalDisplay::resetCursor(); * also because the underline is hidden from under the link, update() is called on the * TerminalDisplay widget. - */ + */ virtual void mouseLeaveEvent(TerminalDisplay *td, QMouseEvent *ev); /** * If the Ctrl key is pressed or TerminalDisplay::openLinksByDirectClick() is * true, the activate() method is called to handle/open the link, see activate(). - */ + */ virtual void mouseReleaseEvent(TerminalDisplay *td, QMouseEvent *ev); /** @@ -143,7 +144,7 @@ public: * * Note that if TerminalDisplay::openLinksByDirectClick() is true the mouse pointer shape is always * changed to a pointing hand when hovering over a link, regardless of the state of the Ctrl key. - */ + */ virtual void keyPressEvent(TerminalDisplay *td, QKeyEvent *ev); /** @@ -152,7 +153,7 @@ public: * * Note that if TerminalDisplay::openLinksByDirectClick() is true the mouse pointer shape is always * changed to a pointing hand when hovering over a link, regardless of the state of the Ctrl key. - */ + */ virtual void keyReleaseEvent(TerminalDisplay *, QKeyEvent *ev); void debug(); diff --git a/src/filterHotSpots/RegExpFilter.cpp b/src/filterHotSpots/RegExpFilter.cpp index 4068a15ed..f453afbb0 100644 --- a/src/filterHotSpots/RegExpFilter.cpp +++ b/src/filterHotSpots/RegExpFilter.cpp @@ -7,17 +7,15 @@ #include "RegExpFilter.h" - #include "RegExpFilterHotspot.h" using namespace Konsole; -RegExpFilter::RegExpFilter() : - _searchText(QRegularExpression()) +RegExpFilter::RegExpFilter() + : _searchText(QRegularExpression()) { } - void RegExpFilter::setRegExp(const QRegularExpression ®Exp) { _searchText = regExp; @@ -45,12 +43,7 @@ void RegExpFilter::process() std::pair start = getLineColumn(match.capturedStart()); std::pair end = getLineColumn(match.capturedEnd()); - QSharedPointer spot( - newHotSpot(start.first, start.second, - end.first, end.second, - match.capturedTexts() - ) - ); + QSharedPointer spot(newHotSpot(start.first, start.second, end.first, end.second, match.capturedTexts())); if (spot == nullptr) { continue; @@ -60,9 +53,7 @@ void RegExpFilter::process() } } -QSharedPointer RegExpFilter::newHotSpot(int startLine, int startColumn, int endLine, - int endColumn, const QStringList &capturedTexts) +QSharedPointer RegExpFilter::newHotSpot(int startLine, int startColumn, int endLine, int endColumn, const QStringList &capturedTexts) { - return QSharedPointer(new RegExpFilterHotSpot(startLine, startColumn, - endLine, endColumn, capturedTexts)); + return QSharedPointer(new RegExpFilterHotSpot(startLine, startColumn, endLine, endColumn, capturedTexts)); } diff --git a/src/filterHotSpots/RegExpFilter.h b/src/filterHotSpots/RegExpFilter.h index 3e772dc6e..d28ff6ba4 100644 --- a/src/filterHotSpots/RegExpFilter.h +++ b/src/filterHotSpots/RegExpFilter.h @@ -13,7 +13,8 @@ #include #include -namespace Konsole { +namespace Konsole +{ class HotSpot; /** * A filter which searches for sections of text matching a regular expression and creates a new RegExpFilter::HotSpot @@ -51,8 +52,7 @@ protected: * Called when a match for the regular expression is encountered. Subclasses should reimplement this * to return custom hotspot types */ - virtual QSharedPointer newHotSpot(int startLine, int startColumn, int endLine, - int endColumn, const QStringList &capturedTexts); + virtual QSharedPointer newHotSpot(int startLine, int startColumn, int endLine, int endColumn, const QStringList &capturedTexts); private: QRegularExpression _searchText; diff --git a/src/filterHotSpots/RegExpFilterHotspot.cpp b/src/filterHotSpots/RegExpFilterHotspot.cpp index d62953df1..576c560fd 100644 --- a/src/filterHotSpots/RegExpFilterHotspot.cpp +++ b/src/filterHotSpots/RegExpFilterHotspot.cpp @@ -9,15 +9,9 @@ using namespace Konsole; - -RegExpFilterHotSpot::RegExpFilterHotSpot( - int startLine, - int startColumn, - int endLine, - int endColumn, - const QStringList &capturedTexts) : - HotSpot(startLine, startColumn, endLine, endColumn), - _capturedTexts(capturedTexts) +RegExpFilterHotSpot::RegExpFilterHotSpot(int startLine, int startColumn, int endLine, int endColumn, const QStringList &capturedTexts) + : HotSpot(startLine, startColumn, endLine, endColumn) + , _capturedTexts(capturedTexts) { setType(Marker); } diff --git a/src/filterHotSpots/RegExpFilterHotspot.h b/src/filterHotSpots/RegExpFilterHotspot.h index 9cffb145b..d68ec604b 100644 --- a/src/filterHotSpots/RegExpFilterHotspot.h +++ b/src/filterHotSpots/RegExpFilterHotspot.h @@ -11,25 +11,22 @@ #include "HotSpot.h" #include -namespace Konsole { +namespace Konsole +{ /** - * Type of hotspot created by RegExpFilter. The capturedTexts() method can be used to find the text - * matched by the filter's regular expression. - */ + * Type of hotspot created by RegExpFilter. The capturedTexts() method can be used to find the text + * matched by the filter's regular expression. + */ class RegExpFilterHotSpot : public HotSpot { public: - RegExpFilterHotSpot( - int startLine, - int startColumn, - int endLine, - int endColumn, - const QStringList &capturedTexts); + RegExpFilterHotSpot(int startLine, int startColumn, int endLine, int endColumn, const QStringList &capturedTexts); void activate(QObject *object = nullptr) override; /** Returns the texts found by the filter when matching the filter's regular expression */ QStringList capturedTexts() const; + private: QStringList _capturedTexts; }; diff --git a/src/filterHotSpots/TerminalImageFilterChain.cpp b/src/filterHotSpots/TerminalImageFilterChain.cpp index 41e5598a3..bd6b72e8f 100644 --- a/src/filterHotSpots/TerminalImageFilterChain.cpp +++ b/src/filterHotSpots/TerminalImageFilterChain.cpp @@ -15,18 +15,16 @@ using namespace Konsole; - -TerminalImageFilterChain::TerminalImageFilterChain(TerminalDisplay *terminalDisplay) : - FilterChain(terminalDisplay), - _buffer(nullptr), - _linePositions(nullptr) +TerminalImageFilterChain::TerminalImageFilterChain(TerminalDisplay *terminalDisplay) + : FilterChain(terminalDisplay) + , _buffer(nullptr) + , _linePositions(nullptr) { } TerminalImageFilterChain::~TerminalImageFilterChain() = default; -void TerminalImageFilterChain::setImage(const Character * const image, int lines, int columns, - const QVector &lineProperties) +void TerminalImageFilterChain::setImage(const Character *const image, int lines, int columns, const QVector &lineProperties) { if (_filters.empty()) { return; diff --git a/src/filterHotSpots/TerminalImageFilterChain.h b/src/filterHotSpots/TerminalImageFilterChain.h index 63448fc38..a1e1f4318 100644 --- a/src/filterHotSpots/TerminalImageFilterChain.h +++ b/src/filterHotSpots/TerminalImageFilterChain.h @@ -8,13 +8,14 @@ #ifndef TERMINAL_IMAGE_FILTER_CHAIN #define TERMINAL_IMAGE_FILTER_CHAIN -#include #include +#include -#include "FilterChain.h" #include "../characters/Character.h" +#include "FilterChain.h" -namespace Konsole { +namespace Konsole +{ class TerminalDisplay; /** A filter chain which processes character images from terminal displays */ @@ -32,14 +33,13 @@ public: * @param columns The number of columns in the terminal image * @param lineProperties The line properties to set for image */ - void setImage(const Character * const image, int lines, int columns, - const QVector &lineProperties); + void setImage(const Character *const image, int lines, int columns, const QVector &lineProperties); private: Q_DISABLE_COPY(TerminalImageFilterChain) -/* usually QStrings and QLists are not supposed to be in the heap, here we have a problem: - we need a shared memory space between many filter objeccts, defined by this TerminalImage. */ + /* usually QStrings and QLists are not supposed to be in the heap, here we have a problem: + we need a shared memory space between many filter objeccts, defined by this TerminalImage. */ std::unique_ptr _buffer; std::unique_ptr> _linePositions; }; diff --git a/src/filterHotSpots/UrlFilter.cpp b/src/filterHotSpots/UrlFilter.cpp index 8db8af847..35db3e314 100644 --- a/src/filterHotSpots/UrlFilter.cpp +++ b/src/filterHotSpots/UrlFilter.cpp @@ -16,27 +16,22 @@ using namespace Konsole; // pieces of text. // Please be careful when altering them. // protocolname:// or www. followed by anything other than whitespaces, <, >, ' or ", and ends before whitespaces, <, >, ', ", ], !, ), :, comma and dot -const QRegularExpression UrlFilter::FullUrlRegExp( - QStringLiteral("(www\\.(?!\\.)|[a-z][a-z0-9+.-]*://)[^\\s<>'\"]+[^!,\\.\\s<>'\"\\]\\)\\:]")); +const QRegularExpression UrlFilter::FullUrlRegExp(QStringLiteral("(www\\.(?!\\.)|[a-z][a-z0-9+.-]*://)[^\\s<>'\"]+[^!,\\.\\s<>'\"\\]\\)\\:]")); // email address: // [word chars, dots or dashes]@[word chars, dots or dashes].[word chars] -const QRegularExpression UrlFilter::EmailAddressRegExp( - QStringLiteral("\\b(\\w|\\.|-|\\+)+@(\\w|\\.|-)+\\.\\w+\\b")); +const QRegularExpression UrlFilter::EmailAddressRegExp(QStringLiteral("\\b(\\w|\\.|-|\\+)+@(\\w|\\.|-)+\\.\\w+\\b")); // matches full url or email address -const QRegularExpression UrlFilter::CompleteUrlRegExp( - QLatin1Char('(') + FullUrlRegExp.pattern() + QLatin1Char('|') + EmailAddressRegExp.pattern() + QLatin1Char(')')); - +const QRegularExpression UrlFilter::CompleteUrlRegExp(QLatin1Char('(') + FullUrlRegExp.pattern() + QLatin1Char('|') + EmailAddressRegExp.pattern() + + QLatin1Char(')')); UrlFilter::UrlFilter() { setRegExp(CompleteUrlRegExp); } -QSharedPointer UrlFilter::newHotSpot(int startLine, int startColumn, int endLine, - int endColumn, const QStringList &capturedTexts) +QSharedPointer UrlFilter::newHotSpot(int startLine, int startColumn, int endLine, int endColumn, const QStringList &capturedTexts) { - return QSharedPointer(new UrlFilterHotSpot(startLine, startColumn, - endLine, endColumn, capturedTexts)); + return QSharedPointer(new UrlFilterHotSpot(startLine, startColumn, endLine, endColumn, capturedTexts)); } diff --git a/src/filterHotSpots/UrlFilter.h b/src/filterHotSpots/UrlFilter.h index 3a96272f6..3779740cd 100644 --- a/src/filterHotSpots/UrlFilter.h +++ b/src/filterHotSpots/UrlFilter.h @@ -10,7 +10,8 @@ #include "RegExpFilter.h" -namespace Konsole { +namespace Konsole +{ /** A filter which matches URLs in blocks of text */ class UrlFilter : public RegExpFilter { @@ -18,7 +19,7 @@ public: UrlFilter(); protected: - QSharedPointer newHotSpot(int beginRow, int beginColumn, int endRow, int endColumn, const QStringList & list) override; + QSharedPointer newHotSpot(int beginRow, int beginColumn, int endRow, int endColumn, const QStringList &list) override; public: static const QRegularExpression FullUrlRegExp; diff --git a/src/filterHotSpots/UrlFilterHotspot.cpp b/src/filterHotSpots/UrlFilterHotspot.cpp index 0e51546d2..4df6f1bd6 100644 --- a/src/filterHotSpots/UrlFilterHotspot.cpp +++ b/src/filterHotSpots/UrlFilterHotspot.cpp @@ -15,24 +15,21 @@ #include #include -#include #include +#include #include #include "UrlFilter.h" #include "terminalDisplay/TerminalDisplay.h" -//regexp matches: +// regexp matches: // full url: - - using namespace Konsole; UrlFilterHotSpot::~UrlFilterHotSpot() = default; -UrlFilterHotSpot::UrlFilterHotSpot(int startLine, int startColumn, int endLine, int endColumn, - const QStringList &capturedTexts) : - RegExpFilterHotSpot(startLine, startColumn, endLine, endColumn, capturedTexts) +UrlFilterHotSpot::UrlFilterHotSpot(int startLine, int startColumn, int endLine, int endColumn, const QStringList &capturedTexts) + : RegExpFilterHotSpot(startLine, startColumn, endLine, endColumn, capturedTexts) { const UrlType kind = urlType(); if (kind == Email) { @@ -112,8 +109,12 @@ QList UrlFilterHotSpot::actions() openAction->setObjectName(QStringLiteral("open-action")); copyAction->setObjectName(QStringLiteral("copy-action")); - QObject::connect(openAction, &QAction::triggered, this, [this, openAction]{ activate(openAction); }); - QObject::connect(copyAction, &QAction::triggered, this, [this, copyAction]{ activate(copyAction); }); + QObject::connect(openAction, &QAction::triggered, this, [this, openAction] { + activate(openAction); + }); + QObject::connect(copyAction, &QAction::triggered, this, [this, copyAction] { + activate(copyAction); + }); return {openAction, copyAction}; } diff --git a/src/filterHotSpots/UrlFilterHotspot.h b/src/filterHotSpots/UrlFilterHotspot.h index 85bc1d140..0cb480645 100644 --- a/src/filterHotSpots/UrlFilterHotspot.h +++ b/src/filterHotSpots/UrlFilterHotspot.h @@ -13,32 +13,28 @@ #include class QAction; -namespace Konsole { +namespace Konsole +{ /** - * Hotspot type created by UrlFilter instances. The activate() method opens a web browser - * at the given URL when called. - */ + * Hotspot type created by UrlFilter instances. The activate() method opens a web browser + * at the given URL when called. + */ class UrlFilterHotSpot : public RegExpFilterHotSpot { public: - UrlFilterHotSpot(int startLine, int startColumn, int endLine, int endColumn, - const QStringList &capturedTexts); + UrlFilterHotSpot(int startLine, int startColumn, int endLine, int endColumn, const QStringList &capturedTexts); ~UrlFilterHotSpot() override; QList actions() override; /** - * Open a web browser at the current URL. The url itself can be determined using - * the capturedTexts() method. - */ + * Open a web browser at the current URL. The url itself can be determined using + * the capturedTexts() method. + */ void activate(QObject *object = nullptr) override; private: - enum UrlType { - StandardUrl, - Email, - Unknown - }; + enum UrlType { StandardUrl, Email, Unknown, }; UrlType urlType() const; }; diff --git a/src/history/HistoryFile.cpp b/src/history/HistoryFile.cpp index e43842dbf..a387b47d6 100644 --- a/src/history/HistoryFile.cpp +++ b/src/history/HistoryFile.cpp @@ -8,8 +8,8 @@ #include "HistoryFile.h" // Konsole -#include "konsoledebug.h" #include "KonsoleSettings.h" +#include "konsoledebug.h" // System #include @@ -28,10 +28,10 @@ using namespace Konsole; Q_GLOBAL_STATIC(QString, historyFileLocation) // History File /////////////////////////////////////////// -HistoryFile::HistoryFile() : - _length(0), - _fileMap(nullptr), - _readWriteBalance(0) +HistoryFile::HistoryFile() + : _length(0) + , _fileMap(nullptr) + , _readWriteBalance(0) { // Determine the temp directory once // This class is called 3 times for each "unlimited" scrollback. @@ -61,14 +61,15 @@ HistoryFile::HistoryFile() : // Validate file location const QFileInfo fi(fileLocation); if (fileLocation.isEmpty() || !fi.exists() || !fi.isDir() || !fi.isWritable()) { - qCWarning(KonsoleDebug)<<"Invalid scrollback folder "< INT_MIN) { _readWriteBalance--; } diff --git a/src/history/HistoryFile.h b/src/history/HistoryFile.h index 6f889af41..c86c3e5a7 100644 --- a/src/history/HistoryFile.h +++ b/src/history/HistoryFile.h @@ -14,7 +14,6 @@ namespace Konsole { - /* An extendable tmpfile(1) based buffer. */ @@ -29,25 +28,25 @@ public: virtual void removeLast(qint64 loc); virtual qint64 len() const; - //mmaps the file in read-only mode + // mmaps the file in read-only mode void map(); - //un-mmaps the file + // un-mmaps the file void unmap(); private: qint64 _length; QTemporaryFile _tmpFile; - //pointer to start of mmap'ed file data, or 0 if the file is not mmap'ed + // pointer to start of mmap'ed file data, or 0 if the file is not mmap'ed uchar *_fileMap; - //incremented whenever '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). + // this is used to detect when a large number of lines are being read and processed from the history + // and automatically mmap the file for better performance (saves the overhead of many lseek-read calls). int _readWriteBalance; - //when _readWriteBalance goes below this threshold, the file will be mmap'ed automatically + // when _readWriteBalance goes below this threshold, the file will be mmap'ed automatically static const int MAP_THRESHOLD = -1000; }; diff --git a/src/history/HistoryScroll.cpp b/src/history/HistoryScroll.cpp index a07c72bcc..1d79f2cb7 100644 --- a/src/history/HistoryScroll.cpp +++ b/src/history/HistoryScroll.cpp @@ -11,8 +11,8 @@ using namespace Konsole; -HistoryScroll::HistoryScroll(HistoryType *t) : - _historyType(t) +HistoryScroll::HistoryScroll(HistoryType *t) + : _historyType(t) { } diff --git a/src/history/HistoryScroll.h b/src/history/HistoryScroll.h index 9f5b3b682..82d53235e 100644 --- a/src/history/HistoryScroll.h +++ b/src/history/HistoryScroll.h @@ -34,9 +34,9 @@ public: virtual bool hasScroll() const; // access to history - virtual int getLines() const = 0; - virtual int getMaxLines() const = 0; - virtual int getLineLen(const int lineno) const = 0; + virtual int getLines() const = 0; + virtual int getMaxLines() const = 0; + virtual int getLineLen(const int lineno) const = 0; virtual void getCells(const int lineno, const int colno, const int count, Character res[]) const = 0; virtual bool isWrappedLine(const int lineNumber) const = 0; virtual LineProperty getLineProperty(const int lineno) const = 0; diff --git a/src/history/HistoryScrollFile.cpp b/src/history/HistoryScrollFile.cpp index 266646a86..510618227 100644 --- a/src/history/HistoryScrollFile.cpp +++ b/src/history/HistoryScrollFile.cpp @@ -21,8 +21,8 @@ using namespace Konsole; -HistoryScrollFile::HistoryScrollFile() : - HistoryScroll(new HistoryTypeFile()) +HistoryScrollFile::HistoryScrollFile() + : HistoryScroll(new HistoryTypeFile()) { } @@ -52,8 +52,7 @@ LineProperty HistoryScrollFile::getLineProperty(const int lineno) const { if (lineno >= 0 && lineno <= getLines()) { LineProperty flag = 0; - _lineflags.get(reinterpret_cast(&flag), sizeof(unsigned char), - (lineno) * sizeof(unsigned char)); + _lineflags.get(reinterpret_cast(&flag), sizeof(unsigned char), (lineno) * sizeof(unsigned char)); return flag; } return 0; diff --git a/src/history/HistoryScrollFile.h b/src/history/HistoryScrollFile.h index f7a0d161e..502a29cf3 100644 --- a/src/history/HistoryScrollFile.h +++ b/src/history/HistoryScrollFile.h @@ -15,7 +15,6 @@ namespace Konsole { - ////////////////////////////////////////////////////////////////////// // File-based history (e.g. file log, no limitation in length) ////////////////////////////////////////////////////////////////////// @@ -26,9 +25,9 @@ public: explicit HistoryScrollFile(); ~HistoryScrollFile() override; - int getLines() const override; - int getMaxLines() const override; - int getLineLen(const int lineno) const override; + int getLines() const override; + int getMaxLines() const override; + int getLineLen(const int lineno) const override; void getCells(const int lineno, const int colno, const int count, Character res[]) const override; bool isWrappedLine(const int lineno) const override; LineProperty getLineProperty(const int lineno) const override; diff --git a/src/history/HistoryScrollNone.cpp b/src/history/HistoryScrollNone.cpp index 899d3b2c6..b3e05df1f 100644 --- a/src/history/HistoryScrollNone.cpp +++ b/src/history/HistoryScrollNone.cpp @@ -13,8 +13,8 @@ using namespace Konsole; // History Scroll None ////////////////////////////////////// -HistoryScrollNone::HistoryScrollNone() : - HistoryScroll(new HistoryTypeNone()) +HistoryScrollNone::HistoryScrollNone() + : HistoryScroll(new HistoryTypeNone()) { } @@ -50,11 +50,11 @@ LineProperty HistoryScrollNone::getLineProperty(int /*lineno*/) const return 0; } -void HistoryScrollNone::getCells(int, int, int, Character []) const +void HistoryScrollNone::getCells(int, int, int, Character[]) const { } -void HistoryScrollNone::addCells(const Character [], int) +void HistoryScrollNone::addCells(const Character[], int) { } diff --git a/src/history/HistoryScrollNone.h b/src/history/HistoryScrollNone.h index eb4192c70..34f8177a6 100644 --- a/src/history/HistoryScrollNone.h +++ b/src/history/HistoryScrollNone.h @@ -13,7 +13,6 @@ namespace Konsole { - ////////////////////////////////////////////////////////////////////// // Nothing-based history (no history :-) ////////////////////////////////////////////////////////////////////// @@ -25,9 +24,9 @@ public: bool hasScroll() const override; - int getLines() const override; - int getMaxLines() const override; - int getLineLen(const int lineno) const override; + int getLines() const override; + int getMaxLines() const override; + int getLineLen(const int lineno) const override; void getCells(const int lineno, const int colno, const int count, Character res[]) const override; bool isWrappedLine(const int lineno) const override; LineProperty getLineProperty(const int lineno) const override; diff --git a/src/history/HistoryType.h b/src/history/HistoryType.h index af799a506..a7a61a70a 100644 --- a/src/history/HistoryType.h +++ b/src/history/HistoryType.h @@ -12,7 +12,6 @@ namespace Konsole { - class KONSOLEPRIVATE_EXPORT HistoryType { public: diff --git a/src/history/HistoryTypeFile.h b/src/history/HistoryTypeFile.h index 5e02b79e2..8d6514507 100644 --- a/src/history/HistoryTypeFile.h +++ b/src/history/HistoryTypeFile.h @@ -12,7 +12,6 @@ namespace Konsole { - class KONSOLEPRIVATE_EXPORT HistoryTypeFile : public HistoryType { public: diff --git a/src/history/HistoryTypeNone.h b/src/history/HistoryTypeNone.h index 84e9c903a..fc7f94705 100644 --- a/src/history/HistoryTypeNone.h +++ b/src/history/HistoryTypeNone.h @@ -12,7 +12,6 @@ namespace Konsole { - class KONSOLEPRIVATE_EXPORT HistoryTypeNone : public HistoryType { public: diff --git a/src/history/compact/CompactHistoryScroll.cpp b/src/history/compact/CompactHistoryScroll.cpp index 3c3ef66ce..76f694625 100644 --- a/src/history/compact/CompactHistoryScroll.cpp +++ b/src/history/compact/CompactHistoryScroll.cpp @@ -16,12 +16,12 @@ struct reflowData { // data to reflow lines QList flags; }; -CompactHistoryScroll::CompactHistoryScroll(const unsigned int maxLineCount) : - HistoryScroll(new CompactHistoryType(maxLineCount)), - _cells(), - _index(), - _flags(), - _maxLineCount(0) +CompactHistoryScroll::CompactHistoryScroll(const unsigned int maxLineCount) + : HistoryScroll(new CompactHistoryType(maxLineCount)) + , _cells() + , _index() + , _flags() + , _maxLineCount(0) { setMaxNbLines(maxLineCount); } @@ -33,7 +33,9 @@ void CompactHistoryScroll::removeFirstLine() const int removing = _index.first(); _index.removeFirst(); - std::transform(_index.begin(), _index.end(), _index.begin(), [removing](int i) { return i - removing; }); + std::transform(_index.begin(), _index.end(), _index.begin(), [removing](int i) { + return i - removing; + }); _cells.erase(_cells.begin(), _cells.begin() + removing); } else { diff --git a/src/history/compact/CompactHistoryScroll.h b/src/history/compact/CompactHistoryScroll.h index bb84fb9b7..ae98d79bd 100644 --- a/src/history/compact/CompactHistoryScroll.h +++ b/src/history/compact/CompactHistoryScroll.h @@ -8,12 +8,11 @@ #ifndef COMPACTHISTORYSCROLL_H #define COMPACTHISTORYSCROLL_H -#include "konsoleprivate_export.h" #include "history/HistoryScroll.h" +#include "konsoleprivate_export.h" namespace Konsole { - class KONSOLEPRIVATE_EXPORT CompactHistoryScroll : public HistoryScroll { typedef QVector TextLine; @@ -22,9 +21,9 @@ public: explicit CompactHistoryScroll(const unsigned int maxLineCount = 1000); ~CompactHistoryScroll() = default; - int getLines() const override; - int getMaxLines() const override; - int getLineLen(const int lineNumber) const override; + int getLines() const override; + int getMaxLines() const override; + int getLineLen(const int lineNumber) const override; void getCells(const int lineNumber, const int startColumn, const int count, Character buffer[]) const override; bool isWrappedLine(const int lineNumber) const override; LineProperty getLineProperty(const int lineNumber) const override; diff --git a/src/history/compact/CompactHistoryType.cpp b/src/history/compact/CompactHistoryType.cpp index 481c4b37b..bf4f0d672 100644 --- a/src/history/compact/CompactHistoryType.cpp +++ b/src/history/compact/CompactHistoryType.cpp @@ -14,8 +14,8 @@ using namespace Konsole; // Reasonable line size static const int LINE_SIZE = 1024; -CompactHistoryType::CompactHistoryType(unsigned int nbLines) : - _maxLines(nbLines) +CompactHistoryType::CompactHistoryType(unsigned int nbLines) + : _maxLines(nbLines) { } diff --git a/src/history/compact/CompactHistoryType.h b/src/history/compact/CompactHistoryType.h index f3fdf69be..c2b6864a4 100644 --- a/src/history/compact/CompactHistoryType.h +++ b/src/history/compact/CompactHistoryType.h @@ -12,7 +12,6 @@ namespace Konsole { - class KONSOLEPRIVATE_EXPORT CompactHistoryType : public HistoryType { public: diff --git a/src/keyboardtranslator/FallbackKeyboardTranslator.cpp b/src/keyboardtranslator/FallbackKeyboardTranslator.cpp index ac34f0fdb..1ba523bed 100644 --- a/src/keyboardtranslator/FallbackKeyboardTranslator.cpp +++ b/src/keyboardtranslator/FallbackKeyboardTranslator.cpp @@ -11,8 +11,8 @@ using namespace Konsole; -FallbackKeyboardTranslator::FallbackKeyboardTranslator() : - KeyboardTranslator(QStringLiteral("fallback")) +FallbackKeyboardTranslator::FallbackKeyboardTranslator() + : KeyboardTranslator(QStringLiteral("fallback")) { setDescription(QStringLiteral("Fallback Keyboard Translator")); diff --git a/src/keyboardtranslator/FallbackKeyboardTranslator.h b/src/keyboardtranslator/FallbackKeyboardTranslator.h index 0fb1f5da0..a76441e5d 100644 --- a/src/keyboardtranslator/FallbackKeyboardTranslator.h +++ b/src/keyboardtranslator/FallbackKeyboardTranslator.h @@ -14,12 +14,11 @@ namespace Konsole { - - class KONSOLEPRIVATE_EXPORT FallbackKeyboardTranslator : public KeyboardTranslator - { - public: - FallbackKeyboardTranslator(); - }; +class KONSOLEPRIVATE_EXPORT FallbackKeyboardTranslator : public KeyboardTranslator +{ +public: + FallbackKeyboardTranslator(); +}; } diff --git a/src/keyboardtranslator/KeyboardTranslator.cpp b/src/keyboardtranslator/KeyboardTranslator.cpp index 6524a5cfc..ccc0d7cf2 100644 --- a/src/keyboardtranslator/KeyboardTranslator.cpp +++ b/src/keyboardtranslator/KeyboardTranslator.cpp @@ -17,40 +17,33 @@ // Qt #include -#include -#include #include +#include +#include // KDE #include using namespace Konsole; -KeyboardTranslator::Entry::Entry() : - _keyCode(0), - _modifiers(Qt::NoModifier), - _modifierMask(Qt::NoModifier), - _state(NoState), - _stateMask(NoState), - _command(NoCommand), - _text(QByteArray()) +KeyboardTranslator::Entry::Entry() + : _keyCode(0) + , _modifiers(Qt::NoModifier) + , _modifierMask(Qt::NoModifier) + , _state(NoState) + , _stateMask(NoState) + , _command(NoCommand) + , _text(QByteArray()) { } bool KeyboardTranslator::Entry::operator==(const Entry &rhs) const { - return _keyCode == rhs._keyCode - && _modifiers == rhs._modifiers - && _modifierMask == rhs._modifierMask - && _state == rhs._state - && _stateMask == rhs._stateMask - && _command == rhs._command - && _text == rhs._text; + return _keyCode == rhs._keyCode && _modifiers == rhs._modifiers && _modifierMask == rhs._modifierMask && _state == rhs._state + && _stateMask == rhs._stateMask && _command == rhs._command && _text == rhs._text; } -bool KeyboardTranslator::Entry::matches(int testKeyCode, - Qt::KeyboardModifiers testKeyboardModifiers, - States testState) const +bool KeyboardTranslator::Entry::matches(int testKeyCode, Qt::KeyboardModifiers testKeyboardModifiers, States testState) const { if (_keyCode != testKeyCode) { return false; @@ -71,10 +64,9 @@ bool KeyboardTranslator::Entry::matches(int testKeyCode, // 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 = (testKeyboardModifiers != 0) - && (testKeyboardModifiers != Qt::KeypadModifier); - bool wantAnyModifier = (_state &KeyboardTranslator::AnyModifierState) != 0; - if ((_stateMask &KeyboardTranslator::AnyModifierState) != 0) { + bool anyModifiersSet = (testKeyboardModifiers != 0) && (testKeyboardModifiers != Qt::KeypadModifier); + bool wantAnyModifier = (_state & KeyboardTranslator::AnyModifierState) != 0; + if ((_stateMask & KeyboardTranslator::AnyModifierState) != 0) { if (wantAnyModifier != anyModifiersSet) { return false; } @@ -83,8 +75,7 @@ bool KeyboardTranslator::Entry::matches(int testKeyCode, return true; } -QByteArray KeyboardTranslator::Entry::escapedText(bool expandWildCards, - Qt::KeyboardModifiers keyboardModifiers) const +QByteArray KeyboardTranslator::Entry::escapedText(bool expandWildCards, Qt::KeyboardModifiers keyboardModifiers) const { QByteArray result(text(expandWildCards, keyboardModifiers)); @@ -161,8 +152,7 @@ QByteArray KeyboardTranslator::Entry::unescape(const QByteArray &text) const case 'n': replacement[0] = 10; break; - case 'x': - { + 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 @@ -247,8 +237,7 @@ void KeyboardTranslator::Entry::insertState(QString &item, int state) const } } -QString KeyboardTranslator::Entry::resultToString(bool expandWildCards, - Qt::KeyboardModifiers keyboardModifiers) const +QString KeyboardTranslator::Entry::resultToString(bool expandWildCards, Qt::KeyboardModifiers keyboardModifiers) const { if (!_text.isEmpty()) { return QString::fromLatin1(escapedText(expandWildCards, keyboardModifiers)); @@ -291,10 +280,10 @@ QString KeyboardTranslator::Entry::conditionToString() const return result; } -KeyboardTranslator::KeyboardTranslator(const QString &name) : - _entries(QMultiHash()), - _name(name), - _description(QString()) +KeyboardTranslator::KeyboardTranslator(const QString &name) + : _entries(QMultiHash()) + , _name(name) + , _description(QString()) { } @@ -343,9 +332,7 @@ void KeyboardTranslator::removeEntry(const Entry &entry) _entries.remove(entry.keyCode(), entry); } -KeyboardTranslator::Entry KeyboardTranslator::findEntry(int keyCode, - Qt::KeyboardModifiers modifiers, - States state) const +KeyboardTranslator::Entry KeyboardTranslator::findEntry(int keyCode, Qt::KeyboardModifiers modifiers, States state) const { QHash::const_iterator i = _entries.find(keyCode); while (i != _entries.constEnd() && i.key() == keyCode) { diff --git a/src/keyboardtranslator/KeyboardTranslator.h b/src/keyboardtranslator/KeyboardTranslator.h index c7d9d4ed7..192eb15dc 100644 --- a/src/keyboardtranslator/KeyboardTranslator.h +++ b/src/keyboardtranslator/KeyboardTranslator.h @@ -21,7 +21,8 @@ class QIODevice; class QTextStream; -namespace Konsole { +namespace Konsole +{ /** * A converter which maps between key sequences pressed by the user and the * character strings which should be sent to the terminal and commands @@ -70,7 +71,7 @@ public: /** Indicates that any of the modifier keys is active. */ AnyModifierState = 16, /** Indicates that the numpad is in application mode. */ - ApplicationKeypadState = 32 + ApplicationKeypadState = 32, }; Q_DECLARE_FLAGS(States, State) @@ -95,7 +96,7 @@ public: /** Scroll the terminal display down to the end of history */ ScrollDownToBottomCommand = 64, /** Echos the operating system specific erase character. */ - EraseCommand = 256 + EraseCommand = 256, }; Q_DECLARE_FLAGS(Commands, Command) @@ -135,8 +136,7 @@ public: * * @param keyboardModifiers The keyboard modifiers being pressed. */ - QByteArray text(bool expandWildCards = false, - Qt::KeyboardModifiers keyboardModifiers = Qt::NoModifier) const; + QByteArray text(bool expandWildCards = false, Qt::KeyboardModifiers keyboardModifiers = Qt::NoModifier) const; /** Sets the character sequence associated with this entry */ void setText(const QByteArray &aText); @@ -150,8 +150,7 @@ public: * @param expandWildCards See text() * @param keyboardModifiers The keyboard modifiers being pressed. */ - QByteArray escapedText(bool expandWildCards = false, - Qt::KeyboardModifiers keyboardModifiers = Qt::NoModifier) const; + QByteArray escapedText(bool expandWildCards = false, Qt::KeyboardModifiers keyboardModifiers = Qt::NoModifier) const; /** Returns the character code ( from the Qt::Key enum ) associated with this entry */ int keyCode() const; @@ -207,8 +206,7 @@ public: * @param expandWildCards See text() * @param keyboardModifiers The keyboard modifiers being pressed. */ - QString resultToString(bool expandWildCards = false, - Qt::KeyboardModifiers keyboardModifiers = Qt::NoModifier) const; + QString resultToString(bool expandWildCards = false, Qt::KeyboardModifiers keyboardModifiers = Qt::NoModifier) const; /** * Returns true if this entry matches the given key sequence, specified @@ -346,8 +344,7 @@ inline int oneOrZero(int value) return value ? 1 : 0; } -inline QByteArray KeyboardTranslator::Entry::text(bool expandWildCards, - Qt::KeyboardModifiers keyboardModifiers) const +inline QByteArray KeyboardTranslator::Entry::text(bool expandWildCards, Qt::KeyboardModifiers keyboardModifiers) const { QByteArray expandedText = _text; diff --git a/src/keyboardtranslator/KeyboardTranslatorManager.cpp b/src/keyboardtranslator/KeyboardTranslatorManager.cpp index f547519f7..1e1a16621 100644 --- a/src/keyboardtranslator/KeyboardTranslatorManager.cpp +++ b/src/keyboardtranslator/KeyboardTranslatorManager.cpp @@ -16,17 +16,17 @@ #include "../konsoledebug.h" // Qt +#include #include #include -#include #include using namespace Konsole; -KeyboardTranslatorManager::KeyboardTranslatorManager() : - _haveLoadedAll(false), - _fallbackTranslator(nullptr), - _translators(QHash()) +KeyboardTranslatorManager::KeyboardTranslatorManager() + : _haveLoadedAll(false) + , _fallbackTranslator(nullptr) + , _translators(QHash()) { _fallbackTranslator = new FallbackKeyboardTranslator(); } @@ -38,7 +38,7 @@ KeyboardTranslatorManager::~KeyboardTranslatorManager() } Q_GLOBAL_STATIC(KeyboardTranslatorManager, theKeyboardTranslatorManager) -KeyboardTranslatorManager* KeyboardTranslatorManager::instance() +KeyboardTranslatorManager *KeyboardTranslatorManager::instance() { return theKeyboardTranslatorManager; } @@ -48,8 +48,7 @@ void KeyboardTranslatorManager::addTranslator(KeyboardTranslator *translator) _translators.insert(translator->name(), translator); if (!saveTranslator(translator)) { - qCDebug(KonsoleDebug) << "Unable to save translator" << translator->name() - << "to disk."; + qCDebug(KonsoleDebug) << "Unable to save translator" << translator->name() << "to disk."; } } @@ -88,8 +87,7 @@ const QString KeyboardTranslatorManager::findTranslatorPath(const QString &name) void KeyboardTranslatorManager::findTranslators() { QStringList list; - const QStringList dirs = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QStringLiteral("konsole"), - QStandardPaths::LocateDirectory); + const QStringList dirs = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QStringLiteral("konsole"), QStandardPaths::LocateDirectory); list.reserve(dirs.size()); for (const QString &dir : dirs) { @@ -136,8 +134,7 @@ const KeyboardTranslator *KeyboardTranslatorManager::findTranslator(const QStrin bool KeyboardTranslatorManager::saveTranslator(const KeyboardTranslator *translator) { - const QString dir = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) - + QStringLiteral("/konsole/"); + const QString dir = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QStringLiteral("/konsole/"); QDir().mkpath(dir); const QString path = dir + translator->name() + QStringLiteral(".keytab"); @@ -145,8 +142,7 @@ bool KeyboardTranslatorManager::saveTranslator(const KeyboardTranslator *transla QFile destination(path); if (!destination.open(QIODevice::WriteOnly | QIODevice::Text)) { - qCDebug(KonsoleDebug) << "Unable to save keyboard translation:" - << destination.errorString(); + qCDebug(KonsoleDebug) << "Unable to save keyboard translation:" << destination.errorString(); return false; } @@ -176,8 +172,7 @@ KeyboardTranslator *KeyboardTranslatorManager::loadTranslator(const QString &nam return loadTranslator(&source, name); } -KeyboardTranslator *KeyboardTranslatorManager::loadTranslator(QIODevice *source, - const QString &name) +KeyboardTranslator *KeyboardTranslatorManager::loadTranslator(QIODevice *source, const QString &name) { auto translator = new KeyboardTranslator(name); KeyboardTranslatorReader reader(source); diff --git a/src/keyboardtranslator/KeyboardTranslatorManager.h b/src/keyboardtranslator/KeyboardTranslatorManager.h index 687719d4a..54524950e 100644 --- a/src/keyboardtranslator/KeyboardTranslatorManager.h +++ b/src/keyboardtranslator/KeyboardTranslatorManager.h @@ -19,7 +19,8 @@ class QIODevice; -namespace Konsole { +namespace Konsole +{ /** * Manages the keyboard translations available for use by terminal sessions, * see KeyboardTranslator. diff --git a/src/keyboardtranslator/KeyboardTranslatorReader.cpp b/src/keyboardtranslator/KeyboardTranslatorReader.cpp index 28729c70b..45b509e14 100644 --- a/src/keyboardtranslator/KeyboardTranslatorReader.cpp +++ b/src/keyboardtranslator/KeyboardTranslatorReader.cpp @@ -12,8 +12,8 @@ // Qt #include -#include #include +#include // KDE #include @@ -39,11 +39,11 @@ using namespace Konsole; // already been removed) // -KeyboardTranslatorReader::KeyboardTranslatorReader(QIODevice *source) : - _source(source), - _description(QString()), - _nextEntry(), - _hasNext(false) +KeyboardTranslatorReader::KeyboardTranslatorReader(QIODevice *source) + : _source(source) + , _description(QString()) + , _nextEntry() + , _hasNext(false) { // read input until we find the description while (_description.isEmpty() && !source->atEnd()) { @@ -71,12 +71,7 @@ void KeyboardTranslatorReader::readNext() int keyCode = Qt::Key_unknown; - decodeSequence(tokens[1].text.toLower(), - keyCode, - modifiers, - modifierMask, - flags, - flagMask); + decodeSequence(tokens[1].text.toLower(), keyCode, modifiers, modifierMask, flags, flagMask); KeyboardTranslator::Command command = KeyboardTranslator::NoCommand; QByteArray text; @@ -87,8 +82,7 @@ void KeyboardTranslatorReader::readNext() } else if (tokens[2].type == Token::Command) { // identify command if (!parseAsCommand(tokens[2].text, command)) { - qCDebug(KonsoleDebug) << "Key" << tokens[1].text << ", Command" - << tokens[2].text << "not understood. "; + qCDebug(KonsoleDebug) << "Key" << tokens[1].text << ", Command" << tokens[2].text << "not understood. "; } } @@ -112,8 +106,7 @@ void KeyboardTranslatorReader::readNext() _hasNext = false; } -bool KeyboardTranslatorReader::parseAsCommand(const QString &text, - KeyboardTranslator::Command &command) +bool KeyboardTranslatorReader::parseAsCommand(const QString &text, KeyboardTranslator::Command &command) { if (text.compare(QLatin1String("erase"), Qt::CaseInsensitive) == 0) { command = KeyboardTranslator::EraseCommand; @@ -136,7 +129,8 @@ bool KeyboardTranslatorReader::parseAsCommand(const QString &text, return true; } -bool KeyboardTranslatorReader::decodeSequence(const QString &text, int &keyCode, +bool KeyboardTranslatorReader::decodeSequence(const QString &text, + int &keyCode, Qt::KeyboardModifiers &modifiers, Qt::KeyboardModifiers &modifierMask, KeyboardTranslator::States &flags, @@ -224,8 +218,7 @@ bool KeyboardTranslatorReader::parseAsModifier(const QString &item, Qt::Keyboard return true; } -bool KeyboardTranslatorReader::parseAsStateFlag(const QString &item, - KeyboardTranslator::State &flag) +bool KeyboardTranslatorReader::parseAsStateFlag(const QString &item, KeyboardTranslator::State &flag) { if (item == QLatin1String("appcukeys") || item == QLatin1String("appcursorkeys")) { flag = KeyboardTranslator::CursorKeysState; @@ -272,8 +265,7 @@ bool KeyboardTranslatorReader::hasNextEntry() const return _hasNext; } -KeyboardTranslator::Entry KeyboardTranslatorReader::createEntry(const QString &condition, - const QString &result) +KeyboardTranslator::Entry KeyboardTranslatorReader::createEntry(const QString &condition, const QString &result) { QString entryString(QStringLiteral("keyboard \"temporary\"\nkey ")); entryString.append(condition); @@ -350,8 +342,8 @@ QList KeyboardTranslatorReader::tokenize(const QRegularExpressionMatch titleMatch(title.match(text)); if (titleMatch.hasMatch()) { - Token titleToken = { Token::TitleKeyword, QString() }; - Token textToken = { Token::TitleText, titleMatch.captured(1) }; + Token titleToken = {Token::TitleKeyword, QString()}; + Token textToken = {Token::TitleText, titleMatch.captured(1)}; list << titleToken << textToken; return list; @@ -359,24 +351,23 @@ QList KeyboardTranslatorReader::tokenize(const QRegularExpressionMatch keyMatch(key.match(text)); if (!keyMatch.hasMatch()) { - qCDebug(KonsoleDebug) << "Line in keyboard translator file could not be understood:" - << text; + qCDebug(KonsoleDebug) << "Line in keyboard translator file could not be understood:" << text; return list; } - Token keyToken = { Token::KeyKeyword, QString() }; + Token keyToken = {Token::KeyKeyword, QString()}; QString sequenceTokenString = keyMatch.captured(1); - Token sequenceToken = { Token::KeySequence, sequenceTokenString.remove(QLatin1Char(' ')) }; + Token sequenceToken = {Token::KeySequence, sequenceTokenString.remove(QLatin1Char(' '))}; list << keyToken << sequenceToken; if (keyMatch.capturedRef(3).isEmpty()) { // capturedTexts().at(2) is a command - Token commandToken = { Token::Command, keyMatch.captured(2) }; + Token commandToken = {Token::Command, keyMatch.captured(2)}; list << commandToken; } else { // capturedTexts().at(3) is the output string - Token outputToken = { Token::OutputText, keyMatch.captured(3) }; + Token outputToken = {Token::OutputText, keyMatch.captured(3)}; list << outputToken; } diff --git a/src/keyboardtranslator/KeyboardTranslatorReader.h b/src/keyboardtranslator/KeyboardTranslatorReader.h index 66765f283..7a6467e16 100644 --- a/src/keyboardtranslator/KeyboardTranslatorReader.h +++ b/src/keyboardtranslator/KeyboardTranslatorReader.h @@ -16,97 +16,94 @@ class QIODevice; namespace Konsole { +/** + * Parses the contents of a Keyboard Translator (.keytab) file and + * returns the entries found in it. + * + * Usage example: + * + * @code + * QFile source( "/path/to/keytab" ); + * source.open( QIODevice::ReadOnly ); + * + * KeyboardTranslator* translator = new KeyboardTranslator( "name-of-translator" ); + * + * KeyboardTranslatorReader reader(source); + * while ( reader.hasNextEntry() ) + * translator->addEntry(reader.nextEntry()); + * + * source.close(); + * + * if ( !reader.parseError() ) + * { + * // parsing succeeded, do something with the translator + * } + * else + * { + * // parsing failed + * } + * @endcode + */ +class KONSOLEPRIVATE_EXPORT KeyboardTranslatorReader +{ +public: + /** Constructs a new reader which parses the given @p source */ + explicit KeyboardTranslatorReader(QIODevice *source); + ~KeyboardTranslatorReader(); + + KeyboardTranslatorReader(const KeyboardTranslatorReader &) = delete; + KeyboardTranslatorReader &operator=(const KeyboardTranslatorReader &) = delete; + /** - * Parses the contents of a Keyboard Translator (.keytab) file and - * returns the entries found in it. - * - * Usage example: - * - * @code - * QFile source( "/path/to/keytab" ); - * source.open( QIODevice::ReadOnly ); - * - * KeyboardTranslator* translator = new KeyboardTranslator( "name-of-translator" ); - * - * KeyboardTranslatorReader reader(source); - * while ( reader.hasNextEntry() ) - * translator->addEntry(reader.nextEntry()); - * - * source.close(); - * - * if ( !reader.parseError() ) - * { - * // parsing succeeded, do something with the translator - * } - * else - * { - * // parsing failed - * } - * @endcode + * Returns the description text. + * TODO: More documentation */ - class KONSOLEPRIVATE_EXPORT KeyboardTranslatorReader - { - public: - /** Constructs a new reader which parses the given @p source */ - explicit KeyboardTranslatorReader(QIODevice *source); - ~KeyboardTranslatorReader(); + QString description() const; - KeyboardTranslatorReader(const KeyboardTranslatorReader &) = delete; - KeyboardTranslatorReader &operator=(const KeyboardTranslatorReader &) = delete; + /** Returns true if there is another entry in the source stream */ + bool hasNextEntry() const; + /** Returns the next entry found in the source stream */ + KeyboardTranslator::Entry nextEntry(); - /** - * Returns the description text. - * TODO: More documentation - */ - QString description() const; + /** + * Returns true if an error occurred whilst parsing the input or + * false if no error occurred. + */ + bool parseError(); - /** Returns true if there is another entry in the source stream */ - bool hasNextEntry() const; - /** Returns the next entry found in the source stream */ - KeyboardTranslator::Entry nextEntry(); + /** + * 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 + */ + static KeyboardTranslator::Entry createEntry(const QString &condition, const QString &result); - /** - * Returns true if an error occurred whilst parsing the input or - * false if no error occurred. - */ - bool parseError(); - - /** - * 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 - */ - static KeyboardTranslator::Entry createEntry(const QString &condition, const QString &result); - private: - struct Token { - enum Type { - TitleKeyword, - TitleText, - KeyKeyword, - KeySequence, - Command, - OutputText - }; - Type type; - QString text; - }; - QList tokenize(const QString &); - void readNext(); - bool decodeSequence(const QString &, int &keyCode, Qt::KeyboardModifiers &modifiers, - Qt::KeyboardModifiers &modifierMask, KeyboardTranslator::States &flags, - KeyboardTranslator::States &flagMask); - - static bool parseAsModifier(const QString &item, Qt::KeyboardModifier &modifier); - static bool parseAsStateFlag(const QString &item, KeyboardTranslator::State &flag); - static bool parseAsKeyCode(const QString &item, int &keyCode); - static bool parseAsCommand(const QString &text, KeyboardTranslator::Command &command); - - QIODevice *_source; - QString _description; - KeyboardTranslator::Entry _nextEntry; - bool _hasNext; +private: + struct Token { + enum Type { TitleKeyword, TitleText, KeyKeyword, KeySequence, Command, OutputText, }; + Type type; + QString text; }; + QList tokenize(const QString &); + void readNext(); + bool decodeSequence(const QString &, + int &keyCode, + Qt::KeyboardModifiers &modifiers, + Qt::KeyboardModifiers &modifierMask, + KeyboardTranslator::States &flags, + KeyboardTranslator::States &flagMask); + + static bool parseAsModifier(const QString &item, Qt::KeyboardModifier &modifier); + static bool parseAsStateFlag(const QString &item, KeyboardTranslator::State &flag); + static bool parseAsKeyCode(const QString &item, int &keyCode); + static bool parseAsCommand(const QString &text, KeyboardTranslator::Command &command); + + QIODevice *_source; + QString _description; + KeyboardTranslator::Entry _nextEntry; + bool _hasNext; +}; } diff --git a/src/keyboardtranslator/KeyboardTranslatorWriter.cpp b/src/keyboardtranslator/KeyboardTranslatorWriter.cpp index 00c8bf1f2..cb82051cc 100644 --- a/src/keyboardtranslator/KeyboardTranslatorWriter.cpp +++ b/src/keyboardtranslator/KeyboardTranslatorWriter.cpp @@ -15,9 +15,9 @@ using namespace Konsole; -KeyboardTranslatorWriter::KeyboardTranslatorWriter(QIODevice *destination) : - _destination(destination), - _writer(nullptr) +KeyboardTranslatorWriter::KeyboardTranslatorWriter(QIODevice *destination) + : _destination(destination) + , _writer(nullptr) { Q_ASSERT(destination && destination->isWritable()); diff --git a/src/keyboardtranslator/KeyboardTranslatorWriter.h b/src/keyboardtranslator/KeyboardTranslatorWriter.h index 6be5bcf98..388265851 100644 --- a/src/keyboardtranslator/KeyboardTranslatorWriter.h +++ b/src/keyboardtranslator/KeyboardTranslatorWriter.h @@ -13,32 +13,32 @@ namespace Konsole { - /** Writes a keyboard translation to disk. */ - 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. - */ - explicit KeyboardTranslatorWriter(QIODevice *destination); - ~KeyboardTranslatorWriter(); +/** Writes a keyboard translation to disk. */ +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. + */ + explicit KeyboardTranslatorWriter(QIODevice *destination); + ~KeyboardTranslatorWriter(); - KeyboardTranslatorWriter(const KeyboardTranslatorWriter &) = delete; - KeyboardTranslatorWriter &operator=(const KeyboardTranslatorWriter &) = delete; + KeyboardTranslatorWriter(const KeyboardTranslatorWriter &) = delete; + KeyboardTranslatorWriter &operator=(const KeyboardTranslatorWriter &) = delete; - /** - * 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); + /** + * 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); - private: - QIODevice *_destination; - QTextStream *_writer; - }; +private: + QIODevice *_destination; + QTextStream *_writer; +}; } #endif diff --git a/src/main.cpp b/src/main.cpp index 84b669d6e..24da64f7a 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -10,24 +10,24 @@ // Own #include "Application.h" -#include "MainWindow.h" -#include "config-konsole.h" #include "KonsoleSettings.h" +#include "MainWindow.h" #include "ViewManager.h" +#include "config-konsole.h" #include "widgets/ViewContainer.h" // OS specific -#include #include #include +#include #include #include -#include +#include // KDE #include -#include #include +#include #include #include #include @@ -35,9 +35,9 @@ using Konsole::Application; #ifdef PROFILE_STARTUP +#include #include #include -#include #endif // fill the KAboutData structure with information about contributors to Konsole. @@ -65,14 +65,12 @@ void deleteQApplication() // XDG_CURRENT_DESKTOP ≠ kde, then pressing and immediately releasing Alt // key makes focus get stuck in QMenu. // Upstream report: https://bugreports.qt.io/browse/QTBUG-77355 -class MenuStyle : public QProxyStyle { +class MenuStyle : public QProxyStyle +{ public: - int styleHint(const StyleHint stylehint, - const QStyleOption *opt, - const QWidget *widget, - QStyleHintReturn *returnData) const override { - return (stylehint == QStyle::SH_MenuBar_AltKeyNavigation) - ? 0 : QProxyStyle::styleHint(stylehint, opt, widget, returnData); + int styleHint(const StyleHint stylehint, const QStyleOption *opt, const QWidget *widget, QStyleHintReturn *returnData) const override + { + return (stylehint == QStyle::SH_MenuBar_AltKeyNavigation) ? 0 : QProxyStyle::styleHint(stylehint, opt, widget, returnData); } }; @@ -82,7 +80,8 @@ public: int main(int argc, char *argv[]) { #ifdef PROFILE_STARTUP - QElapsedTimer timer; timer.start(); + QElapsedTimer timer; + timer.start(); #endif // enable high dpi support @@ -141,17 +140,14 @@ int main(int argc, char *argv[]) parser->process(args); about.processCommandLine(parser.data()); - /// ! DON'T TOUCH THIS ! /// - const KDBusService::StartupOption startupOption = Konsole::KonsoleSettings::useSingleInstance() && !needNewProcess ? - KDBusService::Unique : - KDBusService::Multiple; + const KDBusService::StartupOption startupOption = + Konsole::KonsoleSettings::useSingleInstance() && !needNewProcess ? KDBusService::Unique : KDBusService::Multiple; /// ! DON'T TOUCH THIS ! /// // If you need to change something here, add your logic _at the bottom_ of // shouldUseNewProcess(), after reading the explanations there for why you // probably shouldn't. - atexit(deleteQApplication); // Ensure that we only launch a new instance if we need to // If there is already an instance running, we will quit here @@ -192,8 +188,7 @@ int main(int argc, char *argv[]) // The activateRequested() signal is emitted when a second instance // of Konsole is started. - QObject::connect(&dbusService, &KDBusService::activateRequested, &konsoleApp, - &Application::slotActivateRequested); + QObject::connect(&dbusService, &KDBusService::activateRequested, &konsoleApp, &Application::slotActivateRequested); if (app->isSessionRestored()) { restoreSession(konsoleApp); @@ -240,14 +235,10 @@ bool shouldUseNewProcess(int argc, char *argv[]) // take Qt options into consideration QStringList qtProblematicOptions; - qtProblematicOptions << QStringLiteral("--session") - << QStringLiteral("--name") - << QStringLiteral("--reverse") - << QStringLiteral("--stylesheet") + qtProblematicOptions << QStringLiteral("--session") << QStringLiteral("--name") << QStringLiteral("--reverse") << QStringLiteral("--stylesheet") << QStringLiteral("--graphicssystem"); #if HAVE_X11 - qtProblematicOptions << QStringLiteral("--display") - << QStringLiteral("--visual"); + qtProblematicOptions << QStringLiteral("--display") << QStringLiteral("--visual"); #endif for (const QString &option : qAsConst(qtProblematicOptions)) { if (arguments.contains(option)) { @@ -257,8 +248,7 @@ bool shouldUseNewProcess(int argc, char *argv[]) // take KDE options into consideration QStringList kdeProblematicOptions; - kdeProblematicOptions << QStringLiteral("--config") - << QStringLiteral("--style"); + kdeProblematicOptions << QStringLiteral("--config") << QStringLiteral("--style"); #if HAVE_X11 kdeProblematicOptions << QStringLiteral("--waitforwm"); #endif @@ -272,8 +262,7 @@ bool shouldUseNewProcess(int argc, char *argv[]) // if users have explicitly requested starting a new process // Support --nofork to retain argument compatibility with older // versions. - if (arguments.contains(QStringLiteral("--separate")) - || arguments.contains(QStringLiteral("--nofork"))) { + if (arguments.contains(QStringLiteral("--separate")) || arguments.contains(QStringLiteral("--nofork"))) { return true; } @@ -301,15 +290,14 @@ void fillAboutData(KAboutData &aboutData) aboutData.setOrganizationDomain("kde.org"); aboutData.addAuthor(i18nc("@info:credit", "Kurt Hindenburg"), - i18nc("@info:credit", "General maintainer, bug fixes and general" - " improvements"), + i18nc("@info:credit", + "General maintainer, bug fixes and general" + " improvements"), QStringLiteral("kurt.hindenburg@gmail.com")); aboutData.addAuthor(i18nc("@info:credit", "Robert Knight"), i18nc("@info:credit", "Previous maintainer, ported to KDE4"), QStringLiteral("robertknight@gmail.com")); - aboutData.addAuthor(i18nc("@info:credit", "Lars Doelle"), - i18nc("@info:credit", "Original author"), - QStringLiteral("lars.doelle@on-line.de")); + aboutData.addAuthor(i18nc("@info:credit", "Lars Doelle"), i18nc("@info:credit", "Original author"), QStringLiteral("lars.doelle@on-line.de")); aboutData.addCredit(i18nc("@info:credit", "Ahmad Samir"), i18nc("@info:credit", "Major refactoring, bug fixes and major improvements"), QStringLiteral("a.samirh78@gmail.com")); @@ -328,78 +316,49 @@ void fillAboutData(KAboutData &aboutData) aboutData.addCredit(i18nc("@info:credit", "Martin T. H. Sandsmark"), i18nc("@info:credit", "Bug fixes and general improvements"), QStringLiteral("martin.sandsmark@kde.org")); - aboutData.addCredit(i18nc("@info:credit", "Nate Graham"), - i18nc("@info:credit", "Bug fixes and general improvements"), - QStringLiteral("nate@kde.org")); + aboutData.addCredit(i18nc("@info:credit", "Nate Graham"), i18nc("@info:credit", "Bug fixes and general improvements"), QStringLiteral("nate@kde.org")); aboutData.addCredit(i18nc("@info:credit", "Mariusz Glebocki"), i18nc("@info:credit", "Bug fixes and major improvements"), QStringLiteral("mglb@arccos-1.net")); aboutData.addCredit(i18nc("@info:credit", "Thomas Surrel"), i18nc("@info:credit", "Bug fixes and general improvements"), QStringLiteral("thomas.surrel@protonmail.com")); - aboutData.addCredit(i18nc("@info:credit", "Jekyll Wu"), - i18nc("@info:credit", "Bug fixes and general improvements"), - QStringLiteral("adaptee@gmail.com")); - aboutData.addCredit(i18nc("@info:credit", "Waldo Bastian"), - i18nc("@info:credit", "Bug fixes and general improvements"), - QStringLiteral("bastian@kde.org")); - aboutData.addCredit(i18nc("@info:credit", "Stephan Binner"), - i18nc("@info:credit", "Bug fixes and general improvements"), - QStringLiteral("binner@kde.org")); - aboutData.addCredit(i18nc("@info:credit", "Thomas Dreibholz"), - i18nc("@info:credit", "General improvements"), - QStringLiteral("dreibh@iem.uni-due.de")); - aboutData.addCredit(i18nc("@info:credit", "Chris Machemer"), - i18nc("@info:credit", "Bug fixes"), - QStringLiteral("machey@ceinetworks.com")); - aboutData.addCredit(i18nc("@info:credit", "Francesco Cecconi"), - i18nc("@info:credit", "Bug fixes"), - QStringLiteral("francesco.cecconi@gmail.com")); - aboutData.addCredit(i18nc("@info:credit", "Stephan Kulow"), - i18nc("@info:credit", "Solaris support and history"), - QStringLiteral("coolo@kde.org")); + aboutData.addCredit(i18nc("@info:credit", "Jekyll Wu"), i18nc("@info:credit", "Bug fixes and general improvements"), QStringLiteral("adaptee@gmail.com")); + aboutData.addCredit(i18nc("@info:credit", "Waldo Bastian"), i18nc("@info:credit", "Bug fixes and general improvements"), QStringLiteral("bastian@kde.org")); + aboutData.addCredit(i18nc("@info:credit", "Stephan Binner"), i18nc("@info:credit", "Bug fixes and general improvements"), QStringLiteral("binner@kde.org")); + aboutData.addCredit(i18nc("@info:credit", "Thomas Dreibholz"), i18nc("@info:credit", "General improvements"), QStringLiteral("dreibh@iem.uni-due.de")); + aboutData.addCredit(i18nc("@info:credit", "Chris Machemer"), i18nc("@info:credit", "Bug fixes"), QStringLiteral("machey@ceinetworks.com")); + aboutData.addCredit(i18nc("@info:credit", "Francesco Cecconi"), i18nc("@info:credit", "Bug fixes"), QStringLiteral("francesco.cecconi@gmail.com")); + aboutData.addCredit(i18nc("@info:credit", "Stephan Kulow"), i18nc("@info:credit", "Solaris support and history"), QStringLiteral("coolo@kde.org")); aboutData.addCredit(i18nc("@info:credit", "Alexander Neundorf"), i18nc("@info:credit", "Bug fixes and improved startup performance"), QStringLiteral("neundorf@kde.org")); - aboutData.addCredit(i18nc("@info:credit", "Peter Silva"), - i18nc("@info:credit", "Marking improvements"), - QStringLiteral("Peter.A.Silva@gmail.com")); + aboutData.addCredit(i18nc("@info:credit", "Peter Silva"), i18nc("@info:credit", "Marking improvements"), QStringLiteral("Peter.A.Silva@gmail.com")); aboutData.addCredit(i18nc("@info:credit", "Lotzi Boloni"), - i18nc("@info:credit", "Embedded Konsole\n" - "Toolbar and session names"), + i18nc("@info:credit", + "Embedded Konsole\n" + "Toolbar and session names"), QStringLiteral("boloni@cs.purdue.edu")); aboutData.addCredit(i18nc("@info:credit", "David Faure"), - i18nc("@info:credit", "Embedded Konsole\n" - "General improvements"), + i18nc("@info:credit", + "Embedded Konsole\n" + "General improvements"), QStringLiteral("faure@kde.org")); - aboutData.addCredit(i18nc("@info:credit", "Antonio Larrosa"), - i18nc("@info:credit", "Visual effects"), - QStringLiteral("larrosa@kde.org")); + aboutData.addCredit(i18nc("@info:credit", "Antonio Larrosa"), i18nc("@info:credit", "Visual effects"), QStringLiteral("larrosa@kde.org")); aboutData.addCredit(i18nc("@info:credit", "Matthias Ettrich"), - i18nc("@info:credit", "Code from the kvt project\n" - "General improvements"), + i18nc("@info:credit", + "Code from the kvt project\n" + "General improvements"), QStringLiteral("ettrich@kde.org")); aboutData.addCredit(i18nc("@info:credit", "Warwick Allison"), i18nc("@info:credit", "Schema and text selection improvements"), QStringLiteral("warwick@troll.no")); - aboutData.addCredit(i18nc("@info:credit", "Dan Pilone"), - i18nc("@info:credit", "SGI port"), - QStringLiteral("pilone@slac.com")); - aboutData.addCredit(i18nc("@info:credit", "Kevin Street"), - i18nc("@info:credit", "FreeBSD port"), - QStringLiteral("street@iname.com")); - aboutData.addCredit(i18nc("@info:credit", "Sven Fischer"), - i18nc("@info:credit", "Bug fixes"), - QStringLiteral("herpes@kawo2.renditionwth-aachen.de")); - aboutData.addCredit(i18nc("@info:credit", "Dale M. Flaven"), - i18nc("@info:credit", "Bug fixes"), - QStringLiteral("dflaven@netport.com")); - aboutData.addCredit(i18nc("@info:credit", "Martin Jones"), - i18nc("@info:credit", "Bug fixes"), - QStringLiteral("mjones@powerup.com.au")); - aboutData.addCredit(i18nc("@info:credit", "Lars Knoll"), - i18nc("@info:credit", "Bug fixes"), - QStringLiteral("knoll@mpi-hd.mpg.de")); + aboutData.addCredit(i18nc("@info:credit", "Dan Pilone"), i18nc("@info:credit", "SGI port"), QStringLiteral("pilone@slac.com")); + aboutData.addCredit(i18nc("@info:credit", "Kevin Street"), i18nc("@info:credit", "FreeBSD port"), QStringLiteral("street@iname.com")); + aboutData.addCredit(i18nc("@info:credit", "Sven Fischer"), i18nc("@info:credit", "Bug fixes"), QStringLiteral("herpes@kawo2.renditionwth-aachen.de")); + aboutData.addCredit(i18nc("@info:credit", "Dale M. Flaven"), i18nc("@info:credit", "Bug fixes"), QStringLiteral("dflaven@netport.com")); + aboutData.addCredit(i18nc("@info:credit", "Martin Jones"), i18nc("@info:credit", "Bug fixes"), QStringLiteral("mjones@powerup.com.au")); + aboutData.addCredit(i18nc("@info:credit", "Lars Knoll"), i18nc("@info:credit", "Bug fixes"), QStringLiteral("knoll@mpi-hd.mpg.de")); aboutData.addCredit(i18nc("@info:credit", "Thanks to many others.\n")); } @@ -415,8 +374,8 @@ void restoreSession(Application &app) // TODO: HACK without the code below the sessions would be `uninitialized` // and the tabs wouldn't display the correct information. - auto tabbedContainer = qobject_cast(mainWindow->centralWidget()); - for(int i = 0; i < tabbedContainer->count(); i++) { + auto tabbedContainer = qobject_cast(mainWindow->centralWidget()); + for (int i = 0; i < tabbedContainer->count(); i++) { tabbedContainer->setCurrentIndex(i); } } diff --git a/src/plugins/SSHManager/sshconfigurationdata.h b/src/plugins/SSHManager/sshconfigurationdata.h index d02ad3415..cfecd4dda 100644 --- a/src/plugins/SSHManager/sshconfigurationdata.h +++ b/src/plugins/SSHManager/sshconfigurationdata.h @@ -10,7 +10,8 @@ #include -class SSHConfigurationData { +class SSHConfigurationData +{ public: QString name; QString host; diff --git a/src/plugins/SSHManager/sshmanagerfiltermodel.cpp b/src/plugins/SSHManager/sshmanagerfiltermodel.cpp index 491752a34..a88c1f229 100644 --- a/src/plugins/SSHManager/sshmanagerfiltermodel.cpp +++ b/src/plugins/SSHManager/sshmanagerfiltermodel.cpp @@ -7,12 +7,12 @@ #include "sshmanagerfiltermodel.h" -SSHManagerFilterModel::SSHManagerFilterModel(QObject* parent) -: QSortFilterProxyModel(parent) +SSHManagerFilterModel::SSHManagerFilterModel(QObject *parent) + : QSortFilterProxyModel(parent) { } -bool SSHManagerFilterModel::filterAcceptsRow(int sourceRow, const QModelIndex& sourceParent) const +bool SSHManagerFilterModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const { auto text = filterRegularExpression().pattern(); if (text.isEmpty()) { diff --git a/src/plugins/SSHManager/sshmanagerfiltermodel.h b/src/plugins/SSHManager/sshmanagerfiltermodel.h index b7c50d2b4..65cb96508 100644 --- a/src/plugins/SSHManager/sshmanagerfiltermodel.h +++ b/src/plugins/SSHManager/sshmanagerfiltermodel.h @@ -10,7 +10,8 @@ #include -class SSHManagerFilterModel : public QSortFilterProxyModel { +class SSHManagerFilterModel : public QSortFilterProxyModel +{ Q_OBJECT public: SSHManagerFilterModel(QObject *parent); diff --git a/src/plugins/SSHManager/sshmanagermodel.cpp b/src/plugins/SSHManager/sshmanagermodel.cpp index 5ab20473d..8f182e848 100644 --- a/src/plugins/SSHManager/sshmanagermodel.cpp +++ b/src/plugins/SSHManager/sshmanagermodel.cpp @@ -11,25 +11,26 @@ #include -#include #include +#include #include -#include #include -#include #include +#include +#include #include "sshconfigurationdata.h" Q_LOGGING_CATEGORY(SshManagerPlugin, "org.kde.konsole.plugin.sshmanager") -namespace { - const QString SshDir = QStandardPaths::writableLocation(QStandardPaths::HomeLocation) + QStringLiteral("/.ssh/"); +namespace +{ +const QString SshDir = QStandardPaths::writableLocation(QStandardPaths::HomeLocation) + QStringLiteral("/.ssh/"); } SSHManagerModel::SSHManagerModel(QObject *parent) -: QStandardItemModel(parent) + : QStandardItemModel(parent) { load(); if (invisibleRootItem()->rowCount() == 0) { @@ -42,7 +43,7 @@ SSHManagerModel::~SSHManagerModel() noexcept save(); } -QStandardItem *SSHManagerModel::addTopLevelItem(const QString& name) +QStandardItem *SSHManagerModel::addTopLevelItem(const QString &name) { for (int i = 0, end = invisibleRootItem()->rowCount(); i < end; i++) { if (invisibleRootItem()->child(i)->text() == name) { @@ -57,7 +58,7 @@ QStandardItem *SSHManagerModel::addTopLevelItem(const QString& name) return newItem; } -void SSHManagerModel::addChildItem(const SSHConfigurationData &config, const QString& parentName) +void SSHManagerModel::addChildItem(const SSHConfigurationData &config, const QString &parentName) { QStandardItem *item = nullptr; for (int i = 0, end = invisibleRootItem()->rowCount(); i < end; i++) { @@ -85,7 +86,7 @@ bool SSHManagerModel::setData(const QModelIndex &index, const QVariant &value, i return ret; } -void SSHManagerModel::editChildItem(const SSHConfigurationData &config, const QModelIndex& idx) +void SSHManagerModel::editChildItem(const SSHConfigurationData &config, const QModelIndex &idx) { QStandardItem *item = itemFromIndex(idx); item->setData(QVariant::fromValue(config), SSHRole); @@ -96,7 +97,7 @@ void SSHManagerModel::editChildItem(const SSHConfigurationData &config, const QM QStringList SSHManagerModel::folders() const { QStringList retList; - for(int i = 0, end = invisibleRootItem()->rowCount(); i < end; i++) { + for (int i = 0, end = invisibleRootItem()->rowCount(); i < end; i++) { retList.push_back(invisibleRootItem()->child(i)->text()); } return retList; @@ -108,7 +109,7 @@ void SSHManagerModel::load() for (const QString &groupName : config.groupList()) { KConfigGroup group = config.group(groupName); addTopLevelItem(groupName); - for(const QString& sessionName : group.groupList()) { + for (const QString &sessionName : group.groupList()) { SSHConfigurationData data; KConfigGroup sessionGroup = group.group(sessionName); data.host = sessionGroup.readEntry("hostname"); @@ -161,7 +162,7 @@ Qt::ItemFlags SSHManagerModel::flags(const QModelIndex &index) const } } -void SSHManagerModel::removeIndex(const QModelIndex& idx) +void SSHManagerModel::removeIndex(const QModelIndex &idx) { removeRow(idx.row(), idx.parent()); } @@ -179,7 +180,7 @@ void SSHManagerModel::startImportFromSshConfig() importFromSshConfigFile(SshDir + QStringLiteral("config")); } -void SSHManagerModel::importFromSshConfigFile(const QString& file) +void SSHManagerModel::importFromSshConfigFile(const QString &file) { QFile sshConfig(file); if (!sshConfig.open(QIODevice::ReadOnly)) { @@ -216,7 +217,7 @@ void SSHManagerModel::importFromSshConfigFile(const QString& file) if (lists.at(0) == QStringLiteral("Host")) { if (line.contains(QLatin1Char('*'))) { - //Panic, ignore everything untill the next Host appears. + // Panic, ignore everything untill the next Host appears. ignoreEntry = true; continue; } else { @@ -264,5 +265,3 @@ void SSHManagerModel::importFromSshConfigFile(const QString& file) addChildItem(data, tr("SSH Config")); } } - - diff --git a/src/plugins/SSHManager/sshmanagermodel.h b/src/plugins/SSHManager/sshmanagermodel.h index 302649964..423e0b5d6 100644 --- a/src/plugins/SSHManager/sshmanagermodel.h +++ b/src/plugins/SSHManager/sshmanagermodel.h @@ -14,27 +14,26 @@ class SSHConfigurationData; -class SSHManagerModel : public QStandardItemModel { +class SSHManagerModel : public QStandardItemModel +{ Q_OBJECT public: - enum Roles { - SSHRole = Qt::UserRole + 1 - }; + enum Roles { SSHRole = Qt::UserRole + 1, }; SSHManagerModel(QObject *parent = nullptr); ~SSHManagerModel(); - QStandardItem *addTopLevelItem(const QString& toplevel); + QStandardItem *addTopLevelItem(const QString &toplevel); void addChildItem(const SSHConfigurationData &config, const QString &parentName); - void editChildItem(const SSHConfigurationData &config, const QModelIndex& idx); - void removeIndex(const QModelIndex& idx); + void editChildItem(const SSHConfigurationData &config, const QModelIndex &idx); + void removeIndex(const QModelIndex &idx); bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override; QStringList folders() const; Qt::ItemFlags flags(const QModelIndex &index) const override; void startImportFromSshConfig(); - void importFromSshConfigFile(const QString& file); + void importFromSshConfigFile(const QString &file); void load(); void save(); }; diff --git a/src/plugins/SSHManager/sshmanagerplugin.cpp b/src/plugins/SSHManager/sshmanagerplugin.cpp index f72fd4424..e1824fbc6 100644 --- a/src/plugins/SSHManager/sshmanagerplugin.cpp +++ b/src/plugins/SSHManager/sshmanagerplugin.cpp @@ -7,20 +7,20 @@ #include "sshmanagerplugin.h" -#include "sshmanagerpluginwidget.h" #include "sshmanagermodel.h" +#include "sshmanagerpluginwidget.h" -#include "session/SessionController.h" #include "konsoledebug.h" +#include "session/SessionController.h" -#include #include #include -#include +#include #include +#include -#include #include +#include #include "MainWindow.h" @@ -29,13 +29,13 @@ K_PLUGIN_CLASS_WITH_JSON(SSHManagerPlugin, "konsole_sshmanager.json") struct SSHManagerPluginPrivate { SSHManagerModel model; - QMap widgetForWindow; - QMap dockForWindow; + QMap widgetForWindow; + QMap dockForWindow; }; SSHManagerPlugin::SSHManagerPlugin(QObject *object, const QVariantList &args) -: Konsole::IKonsolePlugin(object, args) -, d(std::make_unique()) + : Konsole::IKonsolePlugin(object, args) + , d(std::make_unique()) { setName(QStringLiteral("SshManager")); } @@ -57,22 +57,20 @@ void SSHManagerPlugin::createWidgetsForMainWindow(Konsole::MainWindow *mainWindo d->widgetForWindow[mainWindow] = managerWidget; d->dockForWindow[mainWindow] = sshDockWidget; - connect(managerWidget, &SSHManagerTreeWidget::requestNewTab, this, [mainWindow]{ + connect(managerWidget, &SSHManagerTreeWidget::requestNewTab, this, [mainWindow] { mainWindow->newTab(); }); } -QList SSHManagerPlugin::menuBarActions(Konsole::MainWindow* mainWindow) const +QList SSHManagerPlugin::menuBarActions(Konsole::MainWindow *mainWindow) const { Q_UNUSED(mainWindow); QAction *toggleVisibilityAction = new QAction(i18n("Show SSH Manager"), mainWindow); toggleVisibilityAction->setCheckable(true); - connect(toggleVisibilityAction, &QAction::triggered, - d->dockForWindow[mainWindow], &QDockWidget::setVisible); - connect(d->dockForWindow[mainWindow], &QDockWidget::visibilityChanged, - toggleVisibilityAction, &QAction::setChecked); + connect(toggleVisibilityAction, &QAction::triggered, d->dockForWindow[mainWindow], &QDockWidget::setVisible); + connect(d->dockForWindow[mainWindow], &QDockWidget::visibilityChanged, toggleVisibilityAction, &QAction::setChecked); return {toggleVisibilityAction}; } @@ -94,14 +92,16 @@ void SSHManagerPlugin::activeViewChangedInternal(QPointer(controller->view()->topLevelWidget()); + auto mainWindow = qobject_cast(controller->view()->topLevelWidget()); // HACK: if we don't get a mainwindow here this *might* be just opening, call it again // later on. // We really shouldn't use an arbitrary time delay, and we need to use a // QPointer in case it gets deleted while the timer is running. if (!mainWindow) { - QTimer::singleShot(500, this, [this, controller]{ activeViewChangedInternal(controller); }); + QTimer::singleShot(500, this, [this, controller] { + activeViewChangedInternal(controller); + }); return; } diff --git a/src/plugins/SSHManager/sshmanagerplugin.h b/src/plugins/SSHManager/sshmanagerplugin.h index 9118ff656..46ac98fde 100644 --- a/src/plugins/SSHManager/sshmanagerplugin.h +++ b/src/plugins/SSHManager/sshmanagerplugin.h @@ -12,14 +12,16 @@ #include -namespace Konsole { - class SessionController; - class MainWindow; +namespace Konsole +{ +class SessionController; +class MainWindow; } struct SSHManagerPluginPrivate; -class SSHManagerPlugin : public Konsole::IKonsolePlugin { +class SSHManagerPlugin : public Konsole::IKonsolePlugin +{ Q_OBJECT public: SSHManagerPlugin(QObject *object, const QVariantList &args); @@ -27,7 +29,7 @@ public: void createWidgetsForMainWindow(Konsole::MainWindow *mainWindow) override; void activeViewChanged(Konsole::SessionController *controller) override; - QList menuBarActions(Konsole::MainWindow* mainWindow) const override; + QList menuBarActions(Konsole::MainWindow *mainWindow) const override; private Q_SLOTS: void activeViewChangedInternal(QPointer controller); diff --git a/src/plugins/SSHManager/sshmanagerpluginwidget.cpp b/src/plugins/SSHManager/sshmanagerpluginwidget.cpp index 30c3bf567..cd5f8da0c 100644 --- a/src/plugins/SSHManager/sshmanagerpluginwidget.cpp +++ b/src/plugins/SSHManager/sshmanagerpluginwidget.cpp @@ -7,27 +7,27 @@ #include "sshmanagerpluginwidget.h" -#include "sshmanagermodel.h" -#include "sshconfigurationdata.h" #include "session/SessionController.h" +#include "sshconfigurationdata.h" +#include "sshmanagermodel.h" #include "terminalDisplay/TerminalDisplay.h" #include "profile/ProfileModel.h" -#include "ui_sshwidget.h" #include "sshmanagerfiltermodel.h" +#include "ui_sshwidget.h" #include #include -#include +#include #include #include -#include +#include #include #include -#include -#include +#include +#include #include struct SSHManagerTreeWidget::Private { @@ -37,9 +37,9 @@ struct SSHManagerTreeWidget::Private { }; SSHManagerTreeWidget::SSHManagerTreeWidget(QWidget *parent) -: QWidget(parent), -ui(std::make_unique()), -d(std::make_unique()) + : QWidget(parent) + , ui(std::make_unique()) + , d(std::make_unique()) { ui->setupUi(this); ui->errorPanel->hide(); @@ -47,23 +47,22 @@ d(std::make_unique()) d->filterModel = new SSHManagerFilterModel(this); // https://stackoverflow.com/questions/1418423/the-hostname-regex - const auto hostnameRegex = QRegularExpression( - QStringLiteral(R"(^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$)") - ); + const auto hostnameRegex = + QRegularExpression(QStringLiteral(R"(^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$)")); - const auto* hostnameValidator = new QRegularExpressionValidator(hostnameRegex, this); + const auto *hostnameValidator = new QRegularExpressionValidator(hostnameRegex, this); ui->hostname->setValidator(hostnameValidator); // System and User ports see: // https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml - const auto* portValidator = new QIntValidator(0, 49151); + const auto *portValidator = new QIntValidator(0, 49151); ui->port->setValidator(portValidator); connect(ui->newSSHConfig, &QPushButton::clicked, this, &SSHManagerTreeWidget::showInfoPane); connect(ui->btnCancel, &QPushButton::clicked, this, &SSHManagerTreeWidget::clearSshInfo); connect(ui->btnEdit, &QPushButton::clicked, this, &SSHManagerTreeWidget::editSshInfo); connect(ui->btnImport, &QPushButton::clicked, this, &SSHManagerTreeWidget::requestImport); - connect(ui->btnRemove, &QPushButton::clicked, this, &SSHManagerTreeWidget::triggerRemove); + connect(ui->btnRemove, &QPushButton::clicked, this, &SSHManagerTreeWidget::triggerRemove); connect(ui->btnInvertFilter, &QPushButton::clicked, d->filterModel, &SSHManagerFilterModel::setInvertFilter); connect(ui->filterText, &QLineEdit::textChanged, this, [this] { @@ -74,7 +73,7 @@ d(std::make_unique()) ui->profile->setModel(Konsole::ProfileModel::instance()); ui->treeView->setContextMenuPolicy(Qt::CustomContextMenu); - connect(ui->treeView, &QTreeView::customContextMenuRequested, [this](const QPoint& pos){ + connect(ui->treeView, &QTreeView::customContextMenuRequested, [this](const QPoint &pos) { if (!ui->treeView->indexAt(pos).isValid()) { return; } @@ -122,7 +121,7 @@ void SSHManagerTreeWidget::saveEdit() return; } - auto selection = ui->treeView->selectionModel()->selectedIndexes(); + auto selection = ui->treeView->selectionModel()->selectedIndexes(); auto sourceIdx = d->filterModel->mapToSource(selection.at(0)); d->model->editChildItem(info(), sourceIdx); @@ -149,21 +148,17 @@ SSHConfigurationData SSHManagerTreeWidget::info() const void SSHManagerTreeWidget::triggerRemove() { - auto selection = ui->treeView->selectionModel()->selectedIndexes(); + auto selection = ui->treeView->selectionModel()->selectedIndexes(); if (selection.empty()) { return; } - const QString dialogMessage = i18n(ui->treeView->model()->rowCount(selection.at(0)) - ? "You are about to remove the folder %1,\n with multiple SSH Configurations, are you sure?" - : "You are about to remove %1, are you sure?") + const QString dialogMessage = + i18n(ui->treeView->model()->rowCount(selection.at(0)) ? "You are about to remove the folder %1,\n with multiple SSH Configurations, are you sure?" + : "You are about to remove %1, are you sure?") .arg(selection.at(0).data(Qt::DisplayRole).toString()); - int result = QMessageBox::warning( - this, - i18n("Remove SSH Configurations"), - dialogMessage, - QMessageBox::Ok, QMessageBox::Cancel); + int result = QMessageBox::warning(this, i18n("Remove SSH Configurations"), dialogMessage, QMessageBox::Ok, QMessageBox::Cancel); if (result == QMessageBox::Cancel) { return; @@ -175,7 +170,7 @@ void SSHManagerTreeWidget::triggerRemove() void SSHManagerTreeWidget::editSshInfo() { - auto selection = ui->treeView->selectionModel()->selectedIndexes(); + auto selection = ui->treeView->selectionModel()->selectedIndexes(); if (selection.empty()) { return; } @@ -274,7 +269,7 @@ void SSHManagerTreeWidget::showInfoPane() connect(ui->btnAdd, &QPushButton::clicked, this, &SSHManagerTreeWidget::addSshInfo); } -void SSHManagerTreeWidget::setModel(SSHManagerModel* model) +void SSHManagerTreeWidget::setModel(SSHManagerModel *model) { d->model = model; d->filterModel->setSourceModel(model); @@ -296,34 +291,34 @@ std::pair SSHManagerTreeWidget::checkFields() const if (ui->hostname->text().isEmpty()) { error = true; - errorString += li + i18n("Missing Hostname") + il; + errorString += li + i18n("Missing Hostname") + il; } if (ui->name->text().isEmpty()) { error = true; - errorString += li + i18n("Missing Name") + il; + errorString += li + i18n("Missing Name") + il; } if (ui->port->text().isEmpty()) { error = true; - errorString += li + i18n("Missing Port") + il; + errorString += li + i18n("Missing Port") + il; } if (ui->useSshConfig->checkState() == Qt::Checked) { if (ui->sshkey->text().count() || ui->username->text().count()) { error = true; - errorString += li + i18n("If Use Ssh Config is set, do not specify sshkey or username.") + il; + errorString += li + i18n("If Use Ssh Config is set, do not specify sshkey or username.") + il; } } else { if (ui->sshkey->text().isEmpty() && ui->username->text().isEmpty()) { error = true; - errorString += li + i18n("At least Username or SSHKey must be set") + il; + errorString += li + i18n("At least Username or SSHKey must be set") + il; } } if (ui->folder->currentText().isEmpty()) { error = true; - errorString += li + i18n("Missing Folder") + il; + errorString += li + i18n("Missing Folder") + il; } if (ui->profile->currentText().isEmpty()) { @@ -377,7 +372,7 @@ void SSHManagerTreeWidget::handleTreeClick(Qt::MouseButton btn, const QModelInde } } -void SSHManagerTreeWidget::connectRequested(const QModelIndex& idx) +void SSHManagerTreeWidget::connectRequested(const QModelIndex &idx) { if (!d->controller) { return; diff --git a/src/plugins/SSHManager/sshmanagerpluginwidget.h b/src/plugins/SSHManager/sshmanagerpluginwidget.h index a1a0ff82b..ea04abede 100644 --- a/src/plugins/SSHManager/sshmanagerpluginwidget.h +++ b/src/plugins/SSHManager/sshmanagerpluginwidget.h @@ -13,16 +13,19 @@ #include "sshconfigurationdata.h" -namespace Ui { - class SSHTreeWidget; +namespace Ui +{ +class SSHTreeWidget; } -namespace Konsole { - class SessionController; +namespace Konsole +{ +class SessionController; } class SSHManagerModel; -class SSHManagerTreeWidget : public QWidget { +class SSHManagerTreeWidget : public QWidget +{ Q_OBJECT public: SSHManagerTreeWidget(QWidget *parent = nullptr); @@ -58,7 +61,7 @@ public: void setModel(SSHManagerModel *model); void triggerRemove(); void setCurrentController(Konsole::SessionController *controller); - void connectRequested(const QModelIndex& idx); + void connectRequested(const QModelIndex &idx); void handleImportedData(bool isImported); private: diff --git a/src/plugins/SSHManager/sshtreeview.cpp b/src/plugins/SSHManager/sshtreeview.cpp index f6d338698..0ee695d16 100644 --- a/src/plugins/SSHManager/sshtreeview.cpp +++ b/src/plugins/SSHManager/sshtreeview.cpp @@ -9,14 +9,14 @@ #include -SshTreeView::SshTreeView(QWidget* parent) -: QTreeView(parent) +SshTreeView::SshTreeView(QWidget *parent) + : QTreeView(parent) { } SshTreeView::~SshTreeView() noexcept = default; -void SshTreeView::mouseReleaseEvent(QMouseEvent* ev) +void SshTreeView::mouseReleaseEvent(QMouseEvent *ev) { const QModelIndex idxAt = indexAt(ev->pos()); if (idxAt.isValid()) { diff --git a/src/plugins/SSHManager/sshtreeview.h b/src/plugins/SSHManager/sshtreeview.h index 817102087..e69ea2c89 100644 --- a/src/plugins/SSHManager/sshtreeview.h +++ b/src/plugins/SSHManager/sshtreeview.h @@ -10,14 +10,15 @@ #include -class SshTreeView : public QTreeView { -Q_OBJECT +class SshTreeView : public QTreeView +{ + Q_OBJECT public: SshTreeView(QWidget *parent = nullptr); ~SshTreeView() noexcept; // mouseClicked already exists but only sends QModelIndex - Q_SIGNAL void mouseButtonClicked(Qt::MouseButton button, const QModelIndex& idx); + Q_SIGNAL void mouseButtonClicked(Qt::MouseButton button, const QModelIndex &idx); void mouseReleaseEvent(QMouseEvent *ev) override; }; diff --git a/src/pluginsystem/IKonsolePlugin.cpp b/src/pluginsystem/IKonsolePlugin.cpp index e55f68df4..af121b90e 100644 --- a/src/pluginsystem/IKonsolePlugin.cpp +++ b/src/pluginsystem/IKonsolePlugin.cpp @@ -7,17 +7,18 @@ #include "IKonsolePlugin.h" -#include #include "MainWindow.h" +#include -namespace Konsole { +namespace Konsole +{ struct IKonsolePlugin::Private { QString name; - QList mainWindowList; + QList mainWindowList; }; -IKonsolePlugin::IKonsolePlugin(QObject *parent, const QVariantList &args) : - d(std::make_unique()) +IKonsolePlugin::IKonsolePlugin(QObject *parent, const QVariantList &args) + : d(std::make_unique()) { Q_UNUSED(parent) Q_UNUSED(args) @@ -25,12 +26,13 @@ IKonsolePlugin::IKonsolePlugin(QObject *parent, const QVariantList &args) : IKonsolePlugin::~IKonsolePlugin() = default; -void IKonsolePlugin::setName(const QString& name) +void IKonsolePlugin::setName(const QString &name) { d->name = name; } -QString IKonsolePlugin::name() const { +QString IKonsolePlugin::name() const +{ return d->name; } diff --git a/src/pluginsystem/IKonsolePlugin.h b/src/pluginsystem/IKonsolePlugin.h index f15153bb0..81a83240c 100644 --- a/src/pluginsystem/IKonsolePlugin.h +++ b/src/pluginsystem/IKonsolePlugin.h @@ -8,24 +8,26 @@ #ifndef IKONSOLEPLUGIN_H #define IKONSOLEPLUGIN_H -#include #include +#include #include #include -#include -#include #include +#include +#include #include #include "konsole_export.h" -namespace Konsole { +namespace Konsole +{ class MainWindow; -class KONSOLE_EXPORT IKonsolePlugin : public QObject { +class KONSOLE_EXPORT IKonsolePlugin : public QObject +{ Q_OBJECT public: IKonsolePlugin(QObject *parent, const QVariantList &args); @@ -40,10 +42,14 @@ public: virtual void createWidgetsForMainWindow(Konsole::MainWindow *mainWindow) = 0; virtual void activeViewChanged(Konsole::SessionController *controller) = 0; - virtual QList menuBarActions(Konsole::MainWindow* mainWindow) const { Q_UNUSED(mainWindow); return {}; }; + virtual QList menuBarActions(Konsole::MainWindow *mainWindow) const + { + Q_UNUSED(mainWindow); + return {}; + }; protected: - void setName(const QString& pluginName); + void setName(const QString &pluginName); private: struct Private; diff --git a/src/pluginsystem/PluginManager.cpp b/src/pluginsystem/PluginManager.cpp index e21c9c4c6..5441dc551 100644 --- a/src/pluginsystem/PluginManager.cpp +++ b/src/pluginsystem/PluginManager.cpp @@ -13,14 +13,14 @@ #include #include -namespace Konsole { - +namespace Konsole +{ struct PluginManagerPrivate { - std::vector plugins; + std::vector plugins; }; PluginManager::PluginManager() -: d(std::make_unique()) + : d(std::make_unique()) { } @@ -32,7 +32,7 @@ PluginManager::~PluginManager() void PluginManager::loadAllPlugins() { QVector pluginMetaData = KPluginLoader::findPlugins(QStringLiteral("konsoleplugins")); - for(const auto &metaData : pluginMetaData) { + for (const auto &metaData : pluginMetaData) { KPluginLoader pluginLoader(metaData.fileName()); KPluginFactory *factory = pluginLoader.factory(); if (!factory) { @@ -48,11 +48,11 @@ void PluginManager::loadAllPlugins() } } -void PluginManager::registerMainWindow(Konsole::MainWindow* window) +void PluginManager::registerMainWindow(Konsole::MainWindow *window) { window->unplugActionList(QStringLiteral("plugin-submenu")); - QList internalPluginSubmenus; + QList internalPluginSubmenus; for (auto *plugin : d->plugins) { plugin->addMainWindow(window); internalPluginSubmenus.append(plugin->menuBarActions(window)); @@ -62,7 +62,7 @@ void PluginManager::registerMainWindow(Konsole::MainWindow* window) window->plugActionList(QStringLiteral("plugin-submenu"), internalPluginSubmenus); } -std::vector PluginManager::plugins() const +std::vector PluginManager::plugins() const { return d->plugins; } diff --git a/src/pluginsystem/PluginManager.h b/src/pluginsystem/PluginManager.h index 2155f87eb..60b0afc9e 100644 --- a/src/pluginsystem/PluginManager.h +++ b/src/pluginsystem/PluginManager.h @@ -12,24 +12,26 @@ #include -#include #include "konsole_export.h" +#include -namespace Konsole { +namespace Konsole +{ class IKonsolePlugin; class MainWindow; struct PluginManagerPrivate; -class KONSOLE_EXPORT PluginManager : public QObject { +class KONSOLE_EXPORT PluginManager : public QObject +{ Q_OBJECT public: PluginManager(); ~PluginManager(); void loadAllPlugins(); - void registerMainWindow(Konsole::MainWindow* window); + void registerMainWindow(Konsole::MainWindow *window); - std::vector plugins() const; + std::vector plugins() const; private: std::unique_ptr d; diff --git a/src/profile/Profile.cpp b/src/profile/Profile.cpp index 7168f484e..27aaea1e1 100644 --- a/src/profile/Profile.cpp +++ b/src/profile/Profile.cpp @@ -10,8 +10,8 @@ #include "Profile.h" // Qt -#include #include +#include // KDE #include @@ -31,106 +31,113 @@ using namespace Konsole; // // the other names are usually shorter versions for convenience // when parsing konsoleprofile commands -static const char GENERAL_GROUP[] = "General"; -static const char KEYBOARD_GROUP[] = "Keyboard"; -static const char APPEARANCE_GROUP[] = "Appearance"; -static const char SCROLLING_GROUP[] = "Scrolling"; -static const char TERMINAL_GROUP[] = "Terminal Features"; -static const char CURSOR_GROUP[] = "Cursor Options"; +static const char GENERAL_GROUP[] = "General"; +static const char KEYBOARD_GROUP[] = "Keyboard"; +static const char APPEARANCE_GROUP[] = "Appearance"; +static const char SCROLLING_GROUP[] = "Scrolling"; +static const char TERMINAL_GROUP[] = "Terminal Features"; +static const char CURSOR_GROUP[] = "Cursor Options"; static const char INTERACTION_GROUP[] = "Interaction Options"; -static const char ENCODING_GROUP[] = "Encoding Options"; +static const char ENCODING_GROUP[] = "Encoding Options"; const Profile::PropertyInfo Profile::DefaultPropertyNames[] = { // General - { Path , "Path" , nullptr , QVariant::String } - , { Name , "Name" , GENERAL_GROUP , QVariant::String } - , { UntranslatedName, "UntranslatedName" , nullptr , QVariant::String } - , { Icon , "Icon" , GENERAL_GROUP , QVariant::String } - , { Command , "Command" , nullptr , QVariant::String } - , { Arguments , "Arguments" , nullptr , QVariant::StringList } - , { MenuIndex, "MenuIndex" , nullptr, QVariant::String } - , { Environment , "Environment" , GENERAL_GROUP , QVariant::StringList } - , { Directory , "Directory" , GENERAL_GROUP , QVariant::String } - , { LocalTabTitleFormat , "LocalTabTitleFormat" , GENERAL_GROUP , QVariant::String } - , { LocalTabTitleFormat , "tabtitle" , nullptr , QVariant::String } - , { RemoteTabTitleFormat , "RemoteTabTitleFormat" , GENERAL_GROUP , QVariant::String } - , { ShowTerminalSizeHint , "ShowTerminalSizeHint" , GENERAL_GROUP , QVariant::Bool } - , { StartInCurrentSessionDir , "StartInCurrentSessionDir" , GENERAL_GROUP , QVariant::Bool } - , { SilenceSeconds, "SilenceSeconds" , GENERAL_GROUP , QVariant::Int } - , { TerminalColumns, "TerminalColumns" , GENERAL_GROUP , QVariant::Int } - , { TerminalRows, "TerminalRows" , GENERAL_GROUP , QVariant::Int } - , { TerminalMargin, "TerminalMargin" , GENERAL_GROUP , QVariant::Int } - , { TerminalCenter, "TerminalCenter" , GENERAL_GROUP , QVariant::Bool } + {Path, "Path", nullptr, QVariant::String}, + {Name, "Name", GENERAL_GROUP, QVariant::String}, + {UntranslatedName, "UntranslatedName", nullptr, QVariant::String}, + {Icon, "Icon", GENERAL_GROUP, QVariant::String}, + {Command, "Command", nullptr, QVariant::String}, + {Arguments, "Arguments", nullptr, QVariant::StringList}, + {MenuIndex, "MenuIndex", nullptr, QVariant::String}, + {Environment, "Environment", GENERAL_GROUP, QVariant::StringList}, + {Directory, "Directory", GENERAL_GROUP, QVariant::String}, + {LocalTabTitleFormat, "LocalTabTitleFormat", GENERAL_GROUP, QVariant::String}, + {LocalTabTitleFormat, "tabtitle", nullptr, QVariant::String}, + {RemoteTabTitleFormat, "RemoteTabTitleFormat", GENERAL_GROUP, QVariant::String}, + {ShowTerminalSizeHint, "ShowTerminalSizeHint", GENERAL_GROUP, QVariant::Bool}, + {StartInCurrentSessionDir, "StartInCurrentSessionDir", GENERAL_GROUP, QVariant::Bool}, + {SilenceSeconds, "SilenceSeconds", GENERAL_GROUP, QVariant::Int}, + {TerminalColumns, "TerminalColumns", GENERAL_GROUP, QVariant::Int}, + {TerminalRows, "TerminalRows", GENERAL_GROUP, QVariant::Int}, + {TerminalMargin, "TerminalMargin", GENERAL_GROUP, QVariant::Int}, + {TerminalCenter, "TerminalCenter", GENERAL_GROUP, QVariant::Bool} // Appearance - , { Font , "Font" , APPEARANCE_GROUP , QVariant::Font } - , { ColorScheme , "ColorScheme" , APPEARANCE_GROUP , QVariant::String } - , { ColorScheme , "colors" , nullptr , QVariant::String } - , { AntiAliasFonts, "AntiAliasFonts" , APPEARANCE_GROUP , QVariant::Bool } - , { BoldIntense, "BoldIntense", APPEARANCE_GROUP, QVariant::Bool } - , { UseFontLineCharacters, "UseFontLineChararacters", APPEARANCE_GROUP, QVariant::Bool } - , { LineSpacing , "LineSpacing" , APPEARANCE_GROUP , QVariant::Int } - , { TabColor, "TabColor", APPEARANCE_GROUP, QVariant::Color } - , { DimValue, "DimmValue", APPEARANCE_GROUP, QVariant::Int } - , { DimWhenInactive , "DimWhenInactive" , GENERAL_GROUP , QVariant::Bool } - , { InvertSelectionColors , "InvertSelectionColors" , GENERAL_GROUP , QVariant::Bool } + , + {Font, "Font", APPEARANCE_GROUP, QVariant::Font}, + {ColorScheme, "ColorScheme", APPEARANCE_GROUP, QVariant::String}, + {ColorScheme, "colors", nullptr, QVariant::String}, + {AntiAliasFonts, "AntiAliasFonts", APPEARANCE_GROUP, QVariant::Bool}, + {BoldIntense, "BoldIntense", APPEARANCE_GROUP, QVariant::Bool}, + {UseFontLineCharacters, "UseFontLineChararacters", APPEARANCE_GROUP, QVariant::Bool}, + {LineSpacing, "LineSpacing", APPEARANCE_GROUP, QVariant::Int}, + {TabColor, "TabColor", APPEARANCE_GROUP, QVariant::Color}, + {DimValue, "DimmValue", APPEARANCE_GROUP, QVariant::Int}, + {DimWhenInactive, "DimWhenInactive", GENERAL_GROUP, QVariant::Bool}, + {InvertSelectionColors, "InvertSelectionColors", GENERAL_GROUP, QVariant::Bool} // Keyboard - , { KeyBindings , "KeyBindings" , KEYBOARD_GROUP , QVariant::String } + , + {KeyBindings, "KeyBindings", KEYBOARD_GROUP, QVariant::String} // Scrolling - , { HistoryMode , "HistoryMode" , SCROLLING_GROUP , QVariant::Int } - , { HistorySize , "HistorySize" , SCROLLING_GROUP , QVariant::Int } - , { ScrollBarPosition , "ScrollBarPosition" , SCROLLING_GROUP , QVariant::Int } - , { ScrollFullPage , "ScrollFullPage" , SCROLLING_GROUP , QVariant::Bool } - , { HighlightScrolledLines , "HighlightScrolledLines" , SCROLLING_GROUP , QVariant::Bool } - , { ReflowLines , "ReflowLines" , SCROLLING_GROUP , QVariant::Bool } + , + {HistoryMode, "HistoryMode", SCROLLING_GROUP, QVariant::Int}, + {HistorySize, "HistorySize", SCROLLING_GROUP, QVariant::Int}, + {ScrollBarPosition, "ScrollBarPosition", SCROLLING_GROUP, QVariant::Int}, + {ScrollFullPage, "ScrollFullPage", SCROLLING_GROUP, QVariant::Bool}, + {HighlightScrolledLines, "HighlightScrolledLines", SCROLLING_GROUP, QVariant::Bool}, + {ReflowLines, "ReflowLines", SCROLLING_GROUP, QVariant::Bool} // Terminal Features - , { UrlHintsModifiers , "UrlHintsModifiers" , TERMINAL_GROUP , QVariant::Int } - , { ReverseUrlHints , "ReverseUrlHints" , TERMINAL_GROUP , QVariant::Bool } - , { BlinkingTextEnabled , "BlinkingTextEnabled" , TERMINAL_GROUP , QVariant::Bool } - , { FlowControlEnabled , "FlowControlEnabled" , TERMINAL_GROUP , QVariant::Bool } - , { BidiRenderingEnabled , "BidiRenderingEnabled" , TERMINAL_GROUP , QVariant::Bool } - , { BlinkingCursorEnabled , "BlinkingCursorEnabled" , TERMINAL_GROUP , QVariant::Bool } - , { BellMode , "BellMode" , TERMINAL_GROUP , QVariant::Int } - , { VerticalLine, "VerticalLine", TERMINAL_GROUP, QVariant::Bool } - , { VerticalLineAtChar, "VerticalLineAtChar", TERMINAL_GROUP, QVariant::Int } - , { PeekPrimaryKeySequence, "PeekPrimaryKeySequence", TERMINAL_GROUP, QVariant::String } + , + {UrlHintsModifiers, "UrlHintsModifiers", TERMINAL_GROUP, QVariant::Int}, + {ReverseUrlHints, "ReverseUrlHints", TERMINAL_GROUP, QVariant::Bool}, + {BlinkingTextEnabled, "BlinkingTextEnabled", TERMINAL_GROUP, QVariant::Bool}, + {FlowControlEnabled, "FlowControlEnabled", TERMINAL_GROUP, QVariant::Bool}, + {BidiRenderingEnabled, "BidiRenderingEnabled", TERMINAL_GROUP, QVariant::Bool}, + {BlinkingCursorEnabled, "BlinkingCursorEnabled", TERMINAL_GROUP, QVariant::Bool}, + {BellMode, "BellMode", TERMINAL_GROUP, QVariant::Int}, + {VerticalLine, "VerticalLine", TERMINAL_GROUP, QVariant::Bool}, + {VerticalLineAtChar, "VerticalLineAtChar", TERMINAL_GROUP, QVariant::Int}, + {PeekPrimaryKeySequence, "PeekPrimaryKeySequence", TERMINAL_GROUP, QVariant::String} // Cursor - , { UseCustomCursorColor , "UseCustomCursorColor" , CURSOR_GROUP , QVariant::Bool} - , { CursorShape , "CursorShape" , CURSOR_GROUP , QVariant::Int} - , { CustomCursorColor , "CustomCursorColor" , CURSOR_GROUP , QVariant::Color } - , { CustomCursorTextColor , "CustomCursorTextColor" , CURSOR_GROUP , QVariant::Color } + , + {UseCustomCursorColor, "UseCustomCursorColor", CURSOR_GROUP, QVariant::Bool}, + {CursorShape, "CursorShape", CURSOR_GROUP, QVariant::Int}, + {CustomCursorColor, "CustomCursorColor", CURSOR_GROUP, QVariant::Color}, + {CustomCursorTextColor, "CustomCursorTextColor", CURSOR_GROUP, QVariant::Color} // Interaction - , { WordCharacters , "WordCharacters" , INTERACTION_GROUP , QVariant::String } - , { TripleClickMode , "TripleClickMode" , INTERACTION_GROUP , QVariant::Int } - , { UnderlineLinksEnabled , "UnderlineLinksEnabled" , INTERACTION_GROUP , QVariant::Bool } - , { UnderlineFilesEnabled , "UnderlineFilesEnabled" , INTERACTION_GROUP , QVariant::Bool } - , { OpenLinksByDirectClickEnabled , "OpenLinksByDirectClickEnabled" , INTERACTION_GROUP , QVariant::Bool } - , { TextEditorCmd , "TextEditorCmd" , INTERACTION_GROUP , QVariant::Int } - , { TextEditorCmdCustom , "TextEditorCmdCustom" , INTERACTION_GROUP , QVariant::String } - , { CtrlRequiredForDrag, "CtrlRequiredForDrag" , INTERACTION_GROUP , QVariant::Bool } - , { DropUrlsAsText , "DropUrlsAsText" , INTERACTION_GROUP , QVariant::Bool } - , { AutoCopySelectedText , "AutoCopySelectedText" , INTERACTION_GROUP , QVariant::Bool } - , { CopyTextAsHTML , "CopyTextAsHTML" , INTERACTION_GROUP , QVariant::Bool } - , { TrimLeadingSpacesInSelectedText , "TrimLeadingSpacesInSelectedText" , INTERACTION_GROUP , QVariant::Bool } - , { TrimTrailingSpacesInSelectedText , "TrimTrailingSpacesInSelectedText" , INTERACTION_GROUP , QVariant::Bool } - , { PasteFromSelectionEnabled , "PasteFromSelectionEnabled" , INTERACTION_GROUP , QVariant::Bool } - , { PasteFromClipboardEnabled , "PasteFromClipboardEnabled" , INTERACTION_GROUP , QVariant::Bool } - , { MiddleClickPasteMode, "MiddleClickPasteMode" , INTERACTION_GROUP , QVariant::Int } - , { MouseWheelZoomEnabled, "MouseWheelZoomEnabled", INTERACTION_GROUP, QVariant::Bool } - , { AlternateScrolling, "AlternateScrolling", INTERACTION_GROUP, QVariant::Bool } - , { AllowEscapedLinks, "AllowEscapedLinks", INTERACTION_GROUP, QVariant::Bool } - , { EscapedLinksSchema, "EscapedLinksSchema", INTERACTION_GROUP, QVariant::String } - , { ColorFilterEnabled, "ColorFilterEnabled", INTERACTION_GROUP, QVariant::Bool } + , + {WordCharacters, "WordCharacters", INTERACTION_GROUP, QVariant::String}, + {TripleClickMode, "TripleClickMode", INTERACTION_GROUP, QVariant::Int}, + {UnderlineLinksEnabled, "UnderlineLinksEnabled", INTERACTION_GROUP, QVariant::Bool}, + {UnderlineFilesEnabled, "UnderlineFilesEnabled", INTERACTION_GROUP, QVariant::Bool}, + {OpenLinksByDirectClickEnabled, "OpenLinksByDirectClickEnabled", INTERACTION_GROUP, QVariant::Bool}, + {TextEditorCmd, "TextEditorCmd", INTERACTION_GROUP, QVariant::Int}, + {TextEditorCmdCustom, "TextEditorCmdCustom", INTERACTION_GROUP, QVariant::String}, + {CtrlRequiredForDrag, "CtrlRequiredForDrag", INTERACTION_GROUP, QVariant::Bool}, + {DropUrlsAsText, "DropUrlsAsText", INTERACTION_GROUP, QVariant::Bool}, + {AutoCopySelectedText, "AutoCopySelectedText", INTERACTION_GROUP, QVariant::Bool}, + {CopyTextAsHTML, "CopyTextAsHTML", INTERACTION_GROUP, QVariant::Bool}, + {TrimLeadingSpacesInSelectedText, "TrimLeadingSpacesInSelectedText", INTERACTION_GROUP, QVariant::Bool}, + {TrimTrailingSpacesInSelectedText, "TrimTrailingSpacesInSelectedText", INTERACTION_GROUP, QVariant::Bool}, + {PasteFromSelectionEnabled, "PasteFromSelectionEnabled", INTERACTION_GROUP, QVariant::Bool}, + {PasteFromClipboardEnabled, "PasteFromClipboardEnabled", INTERACTION_GROUP, QVariant::Bool}, + {MiddleClickPasteMode, "MiddleClickPasteMode", INTERACTION_GROUP, QVariant::Int}, + {MouseWheelZoomEnabled, "MouseWheelZoomEnabled", INTERACTION_GROUP, QVariant::Bool}, + {AlternateScrolling, "AlternateScrolling", INTERACTION_GROUP, QVariant::Bool}, + {AllowEscapedLinks, "AllowEscapedLinks", INTERACTION_GROUP, QVariant::Bool}, + {EscapedLinksSchema, "EscapedLinksSchema", INTERACTION_GROUP, QVariant::String}, + {ColorFilterEnabled, "ColorFilterEnabled", INTERACTION_GROUP, QVariant::Bool} // Encoding - , { DefaultEncoding , "DefaultEncoding" , ENCODING_GROUP , QVariant::String } + , + {DefaultEncoding, "DefaultEncoding", ENCODING_GROUP, QVariant::String} - , { static_cast(0) , nullptr , nullptr, QVariant::Invalid } -}; + , + {static_cast(0), nullptr, nullptr, QVariant::Invalid}}; QHash Profile::PropertyInfoByName; QHash Profile::PropertyInfoByProperty; @@ -143,7 +150,7 @@ void Profile::fillTableWithDefaultNames() return; } - const PropertyInfo* iter = DefaultPropertyNames; + const PropertyInfo *iter = DefaultPropertyNames; while (iter->name != nullptr) { registerProperty(*iter); iter++; @@ -250,7 +257,7 @@ Profile::Profile(const Profile::Ptr &parent) void Profile::clone(Profile::Ptr profile, bool differentOnly) { - const PropertyInfo* properties = DefaultPropertyNames; + const PropertyInfo *properties = DefaultPropertyNames; while (properties->name != nullptr) { Property current = properties->property; QVariant otherValue = profile->property(current); @@ -259,8 +266,7 @@ void Profile::clone(Profile::Ptr profile, bool differentOnly) case Path: break; default: - if (!differentOnly || - property(current) != otherValue) { + if (!differentOnly || property(current) != otherValue) { setProperty(current, otherValue); } } @@ -303,7 +309,7 @@ QHash Profile::setProperties() const return _propertyValues; } -void Profile::setProperty(Property p, const QVariant& value) +void Profile::setProperty(Property p, const QVariant &value) { _propertyValues.insert(p, value); } @@ -313,7 +319,7 @@ bool Profile::isPropertySet(Property p) const return _propertyValues.contains(p); } -Profile::Property Profile::lookupByName(const QString& name) +Profile::Property Profile::lookupByName(const QString &name) { // insert default names into table the first time this is called fillTableWithDefaultNames(); @@ -321,7 +327,7 @@ Profile::Property Profile::lookupByName(const QString& name) return PropertyInfoByName[name.toLower()].property; } -void Profile::registerProperty(const PropertyInfo& info) +void Profile::registerProperty(const PropertyInfo &info) { QString name = QLatin1String(info.name); PropertyInfoByName.insert(name.toLower(), info); @@ -336,7 +342,7 @@ void Profile::registerProperty(const PropertyInfo& info) const QStringList Profile::propertiesInfoList() const { QStringList info; - const PropertyInfo* iter = DefaultPropertyNames; + const PropertyInfo *iter = DefaultPropertyNames; while (iter->name != nullptr) { info << QLatin1String(iter->name) + QStringLiteral(" : ") + QLatin1String(QVariant(iter->type).typeName()); iter++; @@ -347,8 +353,7 @@ const QStringList Profile::propertiesInfoList() const const Profile::GroupPtr Profile::asGroup() const { - const Profile::GroupPtr ptr(dynamic_cast( - const_cast(this))); + const Profile::GroupPtr ptr(dynamic_cast(const_cast(this))); return ptr; } @@ -362,7 +367,7 @@ QString Profile::textEditorCmd() const auto current = property(Profile::TextEditorCmd); QString editorCmd; - switch(current) { + switch (current) { case Enum::Kate: editorCmd = QStringLiteral("kate PATH:LINE:COLUMN"); break; diff --git a/src/profile/Profile.h b/src/profile/Profile.h index 1dda8aecc..6dc3c30fa 100644 --- a/src/profile/Profile.h +++ b/src/profile/Profile.h @@ -10,17 +10,18 @@ #define PROFILE_H // Qt +#include +#include #include +#include #include #include -#include -#include -#include // Konsole #include "konsoleprofile_export.h" -namespace Konsole { +namespace Konsole +{ class ProfileGroup; /** @@ -93,8 +94,8 @@ public: */ Directory, /** (QString) The format used for tab titles when running normal - * commands. - */ + * commands. + */ LocalTabTitleFormat, /** (QString) The format used for tab titles when the session is * running a remote command (eg. SSH) @@ -142,11 +143,11 @@ public: ScrollBarPosition, /** (bool) Specifies whether the PageUp/Down will scroll the full * height or half height. - */ + */ ScrollFullPage, /** (bool) Specifies whether the lines that are scrolled into view * should be highlighted. - */ + */ HighlightScrolledLines, /** (bool) Specifies whether the terminal will enable Bidirectional * text display @@ -217,7 +218,7 @@ public: * option if the user wants to use a different editor. * * See Enum::TextEditorCmd - */ + */ TextEditorCmd, /** * (QString) This is the command string corresponding to Enum::CustomTextEditor. @@ -312,7 +313,7 @@ public: * Default value is true. * See also, MODE_Mouse1007 in the Emulation header, which toggles * Alternate Scrolling with escape sequences. - */ + */ AlternateScrolling, /** (int) Keyboard modifiers to show URL hints */ UrlHintsModifiers, @@ -343,7 +344,7 @@ public: /** (bool) If true, text that matches a color in hex format * when hovered by the mouse pointer. */ - ColorFilterEnabled + ColorFilterEnabled, }; Q_ENUM(Property) diff --git a/src/profile/ProfileCommandParser.cpp b/src/profile/ProfileCommandParser.cpp index 335c7437a..82a5b4358 100644 --- a/src/profile/ProfileCommandParser.cpp +++ b/src/profile/ProfileCommandParser.cpp @@ -13,12 +13,12 @@ // Qt #include -#include #include +#include using namespace Konsole; -QHash ProfileCommandParser::parse(const QString& input) +QHash ProfileCommandParser::parse(const QString &input) { QHash changes; diff --git a/src/profile/ProfileCommandParser.h b/src/profile/ProfileCommandParser.h index 5672b7c5d..a4361bae2 100644 --- a/src/profile/ProfileCommandParser.h +++ b/src/profile/ProfileCommandParser.h @@ -10,41 +10,42 @@ #define PROFILECOMMANDPARSER_H // Konsole -#include "konsoleprofile_export.h" #include "Profile.h" +#include "konsoleprofile_export.h" class QVariant; -template class QHash; +template +class QHash; namespace Konsole { +/** + * Parses an input string consisting of property names + * and assigned values and returns a table of properties + * and values. + * + * The input string will typically look like this: + * + * @code + * PropertyName=Value;PropertyName=Value ... + * @endcode + * + * For example: + * + * @code + * Icon=konsole;Directory=/home/bob + * @endcode + */ +class KONSOLEPROFILE_EXPORT ProfileCommandParser +{ +public: /** * Parses an input string consisting of property names - * and assigned values and returns a table of properties - * and values. - * - * The input string will typically look like this: - * - * @code - * PropertyName=Value;PropertyName=Value ... - * @endcode - * - * For example: - * - * @code - * Icon=konsole;Directory=/home/bob - * @endcode + * and assigned values and returns a table of + * properties and values. */ - class KONSOLEPROFILE_EXPORT ProfileCommandParser - { - public: - /** - * Parses an input string consisting of property names - * and assigned values and returns a table of - * properties and values. - */ - QHash parse(const QString &input); - }; + QHash parse(const QString &input); +}; } #endif diff --git a/src/profile/ProfileGroup.cpp b/src/profile/ProfileGroup.cpp index 2ae8724e3..4bd26c7a0 100644 --- a/src/profile/ProfileGroup.cpp +++ b/src/profile/ProfileGroup.cpp @@ -30,15 +30,14 @@ QList ProfileGroup::profiles() const void ProfileGroup::updateValues() { - const PropertyInfo* properties = Profile::DefaultPropertyNames; + const PropertyInfo *properties = Profile::DefaultPropertyNames; while (properties->name != nullptr) { // the profile group does not store a value for some properties // (eg. name, path) if even they are equal between profiles - // // the exception is when the group has only one profile in which // case it behaves like a standard Profile - if (_profiles.count() > 1 && - !canInheritProperty(properties->property)) { + if (_profiles.count() > 1 && !canInheritProperty(properties->property)) { properties++; continue; } @@ -58,7 +57,7 @@ void ProfileGroup::updateValues() } } -void ProfileGroup::setProperty(Property p, const QVariant& value) +void ProfileGroup::setProperty(Property p, const QVariant &value) { if (_profiles.count() > 1 && !canInheritProperty(p)) { return; diff --git a/src/profile/ProfileGroup.h b/src/profile/ProfileGroup.h index 50c3c53b7..d4ba20985 100644 --- a/src/profile/ProfileGroup.h +++ b/src/profile/ProfileGroup.h @@ -10,83 +10,83 @@ #define PROFILEGROUP_H // Konsole -#include "konsoleprofile_export.h" #include "Profile.h" +#include "konsoleprofile_export.h" // Qt +#include +#include #include #include #include -#include -#include namespace Konsole { - /** - * A composite profile which allows a group of profiles to be treated as one. - * When setting a property, the new value is applied to all profiles in the - * group. When reading a property, if all profiles in the group have the same - * value then that value is returned, otherwise the result is null. - * - * Profiles can be added to the group using addProfile(). When all profiles - * have been added updateValues() must be called - * to sync the group's property values with those of the group's profiles. - * - * The Profile::Name and Profile::Path properties are unique to individual - * profiles, setting these properties on a ProfileGroup has no effect. +/** + * A composite profile which allows a group of profiles to be treated as one. + * When setting a property, the new value is applied to all profiles in the + * group. When reading a property, if all profiles in the group have the same + * value then that value is returned, otherwise the result is null. + * + * Profiles can be added to the group using addProfile(). When all profiles + * have been added updateValues() must be called + * to sync the group's property values with those of the group's profiles. + * + * The Profile::Name and Profile::Path properties are unique to individual + * profiles, setting these properties on a ProfileGroup has no effect. + */ +class KONSOLEPROFILE_EXPORT ProfileGroup : public Profile +{ +public: + using Ptr = QExplicitlySharedDataPointer; + + /** Construct a new profile group, which is hidden by default. */ + explicit ProfileGroup(const Profile::Ptr &profileParent = Profile::Ptr()); + + /** Add a profile to the group. Calling setProperty() will update this + * profile. When creating a group, add the profiles to the group then + * call updateValues() to make the group's property values reflect the + * profiles currently in the group. */ - class KONSOLEPROFILE_EXPORT ProfileGroup : public Profile - { - public: - using Ptr = QExplicitlySharedDataPointer; + void addProfile(const Profile::Ptr &profile); - /** Construct a new profile group, which is hidden by default. */ - explicit ProfileGroup(const Profile::Ptr &profileParent = Profile::Ptr()); + /** Remove a profile from the group. Calling setProperty() will no longer + * affect this profile. */ + void removeProfile(const Profile::Ptr &profile); - /** Add a profile to the group. Calling setProperty() will update this - * profile. When creating a group, add the profiles to the group then - * call updateValues() to make the group's property values reflect the - * profiles currently in the group. - */ - void addProfile(const Profile::Ptr &profile); + /** Returns the profiles in this group .*/ + QList profiles() const; - /** Remove a profile from the group. Calling setProperty() will no longer - * affect this profile. */ - void removeProfile(const Profile::Ptr &profile); + /** + * Updates the property values in this ProfileGroup to match those from + * the group's profiles() + * + * For each available property, if each profile in the group has the same + * value then the ProfileGroup will use that value for the property. + * Otherwise the value for the property will be set to a null QVariant + * + * Some properties such as the name and the path of the profile + * will always be set to null if the group has more than one profile. + */ + void updateValues(); - /** Returns the profiles in this group .*/ - QList profiles() const; + /** Sets the value of @p property in each of the group's profiles to + * @p value. + */ + void setProperty(Property p, const QVariant &value) override; - /** - * Updates the property values in this ProfileGroup to match those from - * the group's profiles() - * - * For each available property, if each profile in the group has the same - * value then the ProfileGroup will use that value for the property. - * Otherwise the value for the property will be set to a null QVariant - * - * Some properties such as the name and the path of the profile - * will always be set to null if the group has more than one profile. - */ - void updateValues(); +private: + Q_DISABLE_COPY(ProfileGroup) - /** Sets the value of @p property in each of the group's profiles to - * @p value. - */ - void setProperty(Property p, const QVariant &value) override; + QList _profiles; +}; - private: - Q_DISABLE_COPY(ProfileGroup) - - QList _profiles; - }; - - inline ProfileGroup::ProfileGroup(const Profile::Ptr &profileParent) - : Profile(profileParent) - , _profiles(QList()) - { - setHidden(true); - } +inline ProfileGroup::ProfileGroup(const Profile::Ptr &profileParent) + : Profile(profileParent) + , _profiles(QList()) +{ + setHidden(true); +} } #endif diff --git a/src/profile/ProfileList.cpp b/src/profile/ProfileList.cpp index 67b6b2d46..a6cb7e83a 100644 --- a/src/profile/ProfileList.cpp +++ b/src/profile/ProfileList.cpp @@ -22,7 +22,7 @@ using Konsole::Profile; using Konsole::ProfileList; -ProfileList::ProfileList(bool addShortcuts , QObject* parent) +ProfileList::ProfileList(bool addShortcuts, QObject *parent) : QObject(parent) , _group(nullptr) , _addShortcuts(addShortcuts) @@ -36,15 +36,14 @@ ProfileList::ProfileList(bool addShortcuts , QObject* parent) // create new tabs using the default profile from the menu _emptyListAction = new QAction(i18n("Default profile"), _group); - connect(_group, &QActionGroup::triggered, this, &ProfileList::triggered); - for (const auto& profile : ProfileManager::instance()->allProfiles()) { + for (const auto &profile : ProfileManager::instance()->allProfiles()) { addShortcutAction(profile); } // TODO - Handle re-sorts when user changes profile names - ProfileManager* manager = ProfileManager::instance(); + ProfileManager *manager = ProfileManager::instance(); connect(manager, &ProfileManager::shortcutChanged, this, &ProfileList::shortcutChanged); connect(manager, &ProfileManager::profileChanged, this, &ProfileList::profileChanged); connect(manager, &ProfileManager::profileRemoved, this, &ProfileList::removeShortcutAction); @@ -63,7 +62,7 @@ void ProfileList::updateEmptyAction() _emptyListAction->setVisible(showEmptyAction); } } -QAction* ProfileList::actionForProfile(const Profile::Ptr &profile) const +QAction *ProfileList::actionForProfile(const Profile::Ptr &profile) const { const QList actionsList = _group->actions(); for (QAction *action : actionsList) { @@ -76,13 +75,13 @@ QAction* ProfileList::actionForProfile(const Profile::Ptr &profile) const void ProfileList::profileChanged(const Profile::Ptr &profile) { - QAction* action = actionForProfile(profile); + QAction *action = actionForProfile(profile); if (action != nullptr) { updateAction(action, profile); } } -void ProfileList::updateAction(QAction* action , Profile::Ptr profile) +void ProfileList::updateAction(QAction *action, Profile::Ptr profile) { Q_ASSERT(action); Q_ASSERT(profile); @@ -92,19 +91,19 @@ void ProfileList::updateAction(QAction* action , Profile::Ptr profile) Q_EMIT actionsChanged(actions()); } -void ProfileList::shortcutChanged(const Profile::Ptr &profile, const QKeySequence& sequence) +void ProfileList::shortcutChanged(const Profile::Ptr &profile, const QKeySequence &sequence) { if (!_addShortcuts) { return; } - QAction* action = actionForProfile(profile); + QAction *action = actionForProfile(profile); if (action != nullptr) { action->setShortcut(sequence); } } -void ProfileList::syncWidgetActions(QWidget* widget, bool sync) +void ProfileList::syncWidgetActions(QWidget *widget, bool sync) { if (!sync) { _registeredWidgets.remove(widget); @@ -113,7 +112,7 @@ void ProfileList::syncWidgetActions(QWidget* widget, bool sync) _registeredWidgets.insert(widget); - const QList currentActions = widget->actions(); + const QList currentActions = widget->actions(); for (QAction *currentAction : currentActions) { widget->removeAction(currentAction); } @@ -123,7 +122,7 @@ void ProfileList::syncWidgetActions(QWidget* widget, bool sync) void ProfileList::addShortcutAction(const Profile::Ptr &profile) { - ProfileManager* manager = ProfileManager::instance(); + ProfileManager *manager = ProfileManager::instance(); auto action = new QAction(_group); action->setData(QVariant::fromValue(profile)); @@ -144,7 +143,7 @@ void ProfileList::addShortcutAction(const Profile::Ptr &profile) void ProfileList::removeShortcutAction(const Profile::Ptr &profile) { - QAction* action = actionForProfile(profile); + QAction *action = actionForProfile(profile); if (action != nullptr) { _group->removeAction(action); @@ -156,12 +155,12 @@ void ProfileList::removeShortcutAction(const Profile::Ptr &profile) updateEmptyAction(); } -void ProfileList::triggered(QAction* action) +void ProfileList::triggered(QAction *action) { Q_EMIT profileSelected(action->data().value()); } -QList ProfileList::actions() +QList ProfileList::actions() { auto actionsList = _group->actions(); std::sort(actionsList.begin(), actionsList.end(), [](QAction *a, QAction *b) { diff --git a/src/profile/ProfileList.h b/src/profile/ProfileList.h index c97ca6330..32b752acd 100644 --- a/src/profile/ProfileList.h +++ b/src/profile/ProfileList.h @@ -9,8 +9,8 @@ // Qt #include -#include #include +#include // Konsole #include "Profile.h" @@ -20,7 +20,8 @@ class QAction; class QActionGroup; class QKeySequence; -namespace Konsole { +namespace Konsole +{ /** * ProfileList provides a list of actions which represent session profiles * that a SessionManager can create a session from. diff --git a/src/profile/ProfileManager.cpp b/src/profile/ProfileManager.cpp index 1f44d5930..867b8132a 100644 --- a/src/profile/ProfileManager.cpp +++ b/src/profile/ProfileManager.cpp @@ -18,21 +18,21 @@ #include // KDE -#include #include #include #include #include +#include // Konsole -#include "ProfileReader.h" -#include "ProfileWriter.h" #include "ProfileGroup.h" #include "ProfileModel.h" +#include "ProfileReader.h" +#include "ProfileWriter.h" using namespace Konsole; -static bool stringLessThan(const QString& p1, const QString& p2) +static bool stringLessThan(const QString &p1, const QString &p2) { return QString::localeAwareCompare(p1, p2) < 0; } @@ -43,7 +43,7 @@ ProfileManager::ProfileManager() , _loadedAllProfiles(false) , _shortcuts(QMap()) { - //load fallback profile + // load fallback profile initFallbackProfile(); // lookup the default profile specified in rc @@ -86,7 +86,7 @@ ProfileManager::ProfileManager() ProfileManager::~ProfileManager() = default; Q_GLOBAL_STATIC(ProfileManager, theProfileManager) -ProfileManager* ProfileManager::instance() +ProfileManager *ProfileManager::instance() { return theProfileManager; } @@ -98,7 +98,7 @@ void ProfileManager::initFallbackProfile() addProfile(_fallbackProfile); } -Profile::Ptr ProfileManager::loadProfile(const QString& shortPath) +Profile::Ptr ProfileManager::loadProfile(const QString &shortPath) { // the fallback profile has a 'special' path name, "FALLBACK/" if (shortPath == _fallbackProfile->path()) { @@ -209,7 +209,7 @@ void ProfileManager::loadAllProfiles() return; } - const QStringList& paths = availableProfilePaths(); + const QStringList &paths = availableProfilePaths(); for (const QString &path : paths) { loadProfile(path); } @@ -271,15 +271,13 @@ QString ProfileManager::saveProfile(const Profile::Ptr &profile) QString newPath = writer.getPath(profile); if (!writer.writeProfile(newPath, profile)) { - KMessageBox::sorry(nullptr, - i18n("Konsole does not have permission to save this profile to %1", newPath)); + KMessageBox::sorry(nullptr, i18n("Konsole does not have permission to save this profile to %1", newPath)); } return newPath; } -void ProfileManager::changeProfile(Profile::Ptr profile, - QHash propertyMap, bool persistent) +void ProfileManager::changeProfile(Profile::Ptr profile, QHash propertyMap, bool persistent) { Q_ASSERT(profile); @@ -301,14 +299,14 @@ void ProfileManager::changeProfile(Profile::Ptr profile, // in the name box in the edit profile dialog; i.e. saving the // fallback profile where the user didn't change the name at all, // the uniqueProfileName is used silently a couple of lines above. - if ((property == Profile::Name || property == Profile::UntranslatedName) - && value == QLatin1String("Default")) { + if ((property == Profile::Name || property == Profile::UntranslatedName) && value == QLatin1String("Default")) { value = uniqueProfileName; if (!messageShown) { KMessageBox::sorry(nullptr, i18n("The name \"Default\" is reserved for the built-in" " fallback profile;\nthe profile is going to be" - " saved as \"%1\"", uniqueProfileName)); + " saved as \"%1\"", + uniqueProfileName)); messageShown = true; } } @@ -382,8 +380,7 @@ bool ProfileManager::deleteProfile(Profile::Ptr profile) // try to delete the config file if (profile->isPropertySet(Profile::Path) && QFile::exists(profile->path())) { if (!QFile::remove(profile->path())) { - qCDebug(KonsoleDebug) << "Could not delete profile: " << profile->path() - << "The file is most likely in a directory which is read-only."; + qCDebug(KonsoleDebug) << "Could not delete profile: " << profile->path() << "The file is most likely in a directory which is read-only."; return false; } @@ -467,10 +464,10 @@ void ProfileManager::loadShortcuts() } } -QString ProfileManager::normalizePath(const QString& path) const { +QString ProfileManager::normalizePath(const QString &path) const +{ QFileInfo fileInfo(path); - const QString location = QStandardPaths::locate( - QStandardPaths::GenericDataLocation, QStringLiteral("konsole/") + fileInfo.fileName()); + const QString location = QStandardPaths::locate(QStandardPaths::GenericDataLocation, QStringLiteral("konsole/") + fileInfo.fileName()); return (!fileInfo.isAbsolute()) || location.isEmpty() ? path : fileInfo.fileName(); } @@ -489,8 +486,7 @@ void ProfileManager::saveShortcuts() } } -void ProfileManager::setShortcut(Profile::Ptr profile , - const QKeySequence& keySequence) +void ProfileManager::setShortcut(Profile::Ptr profile, const QKeySequence &keySequence) { QKeySequence existingShortcut = shortcut(profile); _shortcuts.remove(existingShortcut); @@ -514,12 +510,10 @@ QKeySequence ProfileManager::shortcut(Profile::Ptr profile) const QMapIterator iter(_shortcuts); while (iter.hasNext()) { iter.next(); - if (iter.value().profileKey == profile - || iter.value().profilePath == profile->path()) { + if (iter.value().profileKey == profile || iter.value().profilePath == profile->path()) { return iter.key(); } } return QKeySequence(); } - diff --git a/src/profile/ProfileManager.h b/src/profile/ProfileManager.h index b7f2cadfc..18c17294f 100644 --- a/src/profile/ProfileManager.h +++ b/src/profile/ProfileManager.h @@ -10,20 +10,21 @@ #define PROFILEMANAGER_H // Qt -#include #include +#include #include #include +#include #include #include -#include #include // Konsole #include "Profile.h" -namespace Konsole { +namespace Konsole +{ /** * Manages profiles which specify various settings for terminal sessions * and their displays. @@ -53,7 +54,7 @@ public: * Returns a list of all available profiles * * Initially only the profile currently set as the default is loaded. - * + * * When this method is called, it calls loadAllProfiles() internally to * ensure all available profiles are loaded and usable. */ @@ -134,8 +135,7 @@ public: * set this to false if you want to preview possible changes to a profile but do not * wish to make them permanent. */ - void changeProfile(Profile::Ptr profile, QHash propertyMap, - bool persistent = true); + void changeProfile(Profile::Ptr profile, QHash propertyMap, bool persistent = true); /** * Sets the @p profile as the default profile for creating new sessions @@ -241,9 +241,9 @@ private: // finds out if it's a internal profile or an external one, // fixing the path to point to the correct location for the profile. - QString normalizePath(const QString& path) const; + QString normalizePath(const QString &path) const; }; } -#endif //PROFILEMANAGER_H +#endif // PROFILEMANAGER_H diff --git a/src/profile/ProfileModel.cpp b/src/profile/ProfileModel.cpp index 89c8c7dca..4c08957be 100644 --- a/src/profile/ProfileModel.cpp +++ b/src/profile/ProfileModel.cpp @@ -5,17 +5,17 @@ */ #include "ProfileModel.h" -#include "ProfileManager.h" #include "Profile.h" +#include "ProfileManager.h" #include -#include #include +#include using namespace Konsole; -ProfileModel* ProfileModel::instance() +ProfileModel *ProfileModel::instance() { static ProfileModel self; return &self; @@ -23,12 +23,9 @@ ProfileModel* ProfileModel::instance() ProfileModel::ProfileModel() { - connect(ProfileManager::instance(), &ProfileManager::profileAdded, - this, &ProfileModel::add); - connect(ProfileManager::instance(), &ProfileManager::profileRemoved, - this, &ProfileModel::remove); - connect(ProfileManager::instance(), &ProfileManager::profileChanged, - this, &ProfileModel::update); + connect(ProfileManager::instance(), &ProfileManager::profileAdded, this, &ProfileModel::add); + connect(ProfileManager::instance(), &ProfileManager::profileRemoved, this, &ProfileModel::remove); + connect(ProfileManager::instance(), &ProfileManager::profileChanged, this, &ProfileModel::update); populate(); } int ProfileModel::rowCount(const QModelIndex &unused) const @@ -39,7 +36,7 @@ int ProfileModel::rowCount(const QModelIndex &unused) const return m_profiles.count(); } -int ProfileModel::columnCount(const QModelIndex& unused) const +int ProfileModel::columnCount(const QModelIndex &unused) const { Q_UNUSED(unused) return COLUMNS; @@ -54,14 +51,16 @@ QVariant ProfileModel::headerData(int section, Qt::Orientation orientation, int return {}; } - switch(section) { - case NAME: return i18nc("@title:column Profile name", "Name"); - case SHORTCUT: return i18nc("@title:column Profile keyboard shortcut", "Shortcut"); + switch (section) { + case NAME: + return i18nc("@title:column Profile name", "Name"); + case SHORTCUT: + return i18nc("@title:column Profile keyboard shortcut", "Shortcut"); } return {}; } -QVariant ProfileModel::data(const QModelIndex& idx, int role) const +QVariant ProfileModel::data(const QModelIndex &idx, int role) const { if (!idx.isValid()) { return {}; @@ -91,7 +90,7 @@ QVariant ProfileModel::data(const QModelIndex& idx, int role) const case Qt::DecorationRole: return QIcon::fromTheme(profile->icon()); case Qt::FontRole: - if (ProfileManager::instance()->defaultProfile() == profile ) { + if (ProfileManager::instance()->defaultProfile() == profile) { QFont font; font.setBold(true); return font; @@ -100,22 +99,25 @@ QVariant ProfileModel::data(const QModelIndex& idx, int role) const case Qt::ToolTipRole: return profile->isFallback() ? QStringLiteral("Built-in/hardcoded") : profile->path(); } - } - break; + } break; case SHORTCUT: { auto shortcut = ProfileManager::instance()->shortcut(profile); switch (role) { - case Qt::DisplayRole: return shortcut; - case Qt::EditRole: return shortcut; - case Qt::ToolTipRole: return i18nc("@info:tooltip", "Double click to change shortcut"); + case Qt::DisplayRole: + return shortcut; + case Qt::EditRole: + return shortcut; + case Qt::ToolTipRole: + return i18nc("@info:tooltip", "Double click to change shortcut"); } break; } case PROFILE: { - switch(role) { - case ProfilePtrRole: return QVariant::fromValue(profile); + switch (role) { + case ProfilePtrRole: + return QVariant::fromValue(profile); } break; } @@ -124,14 +126,16 @@ QVariant ProfileModel::data(const QModelIndex& idx, int role) const return {}; } -Qt::ItemFlags ProfileModel::flags(const QModelIndex& idx) const +Qt::ItemFlags ProfileModel::flags(const QModelIndex &idx) const { auto currentFlags = QAbstractTableModel::flags(idx); - switch(idx.column()) { - case NAME: return currentFlags & (~Qt::ItemIsEditable); - case SHORTCUT: return currentFlags | Qt::ItemIsEditable; - default: ; + switch (idx.column()) { + case NAME: + return currentFlags & (~Qt::ItemIsEditable); + case SHORTCUT: + return currentFlags | Qt::ItemIsEditable; + default:; } return currentFlags; } @@ -185,11 +189,11 @@ void ProfileModel::remove(QExplicitlySharedDataPointer profile) void ProfileModel::setDefault(QExplicitlySharedDataPointer profile) { Q_UNUSED(profile) - Q_EMIT dataChanged(index(0, 0), index(0, COLUMNS-1), {Qt::DisplayRole}); + Q_EMIT dataChanged(index(0, 0), index(0, COLUMNS - 1), {Qt::DisplayRole}); } void ProfileModel::update(QExplicitlySharedDataPointer profile) { int row = m_profiles.indexOf(profile); - dataChanged(index(row, 0), index(row, COLUMNS-1)); + dataChanged(index(row, 0), index(row, COLUMNS - 1)); } diff --git a/src/profile/ProfileModel.h b/src/profile/ProfileModel.h index 8c6372fb2..a0e6ec9a3 100644 --- a/src/profile/ProfileModel.h +++ b/src/profile/ProfileModel.h @@ -13,28 +13,31 @@ #include #include -namespace Konsole { +namespace Konsole +{ class Profile; -class KONSOLEPROFILE_EXPORT ProfileModel : public QAbstractTableModel { +class KONSOLEPROFILE_EXPORT ProfileModel : public QAbstractTableModel +{ Q_OBJECT public: - static ProfileModel* instance(); + static ProfileModel *instance(); - enum Roles { ProfilePtrRole = Qt::UserRole + 1 }; - enum Column { NAME, SHORTCUT, PROFILE, COLUMNS }; + enum Roles { ProfilePtrRole = Qt::UserRole + 1, }; + enum Column { NAME, SHORTCUT, PROFILE, COLUMNS, }; void populate(); void add(QExplicitlySharedDataPointer profile); void remove(QExplicitlySharedDataPointer profile); void update(QExplicitlySharedDataPointer profile); void setDefault(QExplicitlySharedDataPointer profile); - int rowCount(const QModelIndex& parent) const override; - int columnCount(const QModelIndex& parent) const override; - QVariant data(const QModelIndex& idx, int role) const override; + int rowCount(const QModelIndex &parent) const override; + int columnCount(const QModelIndex &parent) const override; + QVariant data(const QModelIndex &idx, int role) const override; QVariant headerData(int section, Qt::Orientation orientation, int role) const override; Qt::ItemFlags flags(const QModelIndex &index) const override; bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override; + private: QList> m_profiles; ProfileModel(); diff --git a/src/profile/ProfileReader.cpp b/src/profile/ProfileReader.cpp index 274a1ccd8..5f24e6125 100644 --- a/src/profile/ProfileReader.cpp +++ b/src/profile/ProfileReader.cpp @@ -10,8 +10,8 @@ #include "ProfileReader.h" // Qt -#include #include +#include // KDE #include @@ -23,9 +23,9 @@ using namespace Konsole; // FIXME: A dup line from Profile.cpp - redo these -static const char GENERAL_GROUP[] = "General"; -static const char FEATURES_GROUP[] = "Terminal Features"; -static const char URLHINTS_KEY[] = "EnableUrlHints"; +static const char GENERAL_GROUP[] = "General"; +static const char FEATURES_GROUP[] = "Terminal Features"; +static const char URLHINTS_KEY[] = "EnableUrlHints"; static const char URLHINTSMODIFIERS_KEY[] = "UrlHintsModifiers"; ProfileReader::ProfileReader() = default; @@ -37,18 +37,17 @@ QStringList ProfileReader::findProfiles() const QStringList dirs = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QStringLiteral("konsole"), QStandardPaths::LocateDirectory); profiles.reserve(dirs.size()); - for (const QString& dir : dirs) { + for (const QString &dir : dirs) { const QStringList fileNames = QDir(dir).entryList(QStringList() << QStringLiteral("*.profile")); - for (const QString& file : fileNames) { + for (const QString &file : fileNames) { profiles.append(dir + QLatin1Char('/') + file); } } return profiles; } -void ProfileReader::readProperties(const KConfig& config, Profile::Ptr profile, - const Profile::PropertyInfo* properties) +void ProfileReader::readProperties(const KConfig &config, Profile::Ptr profile, const Profile::PropertyInfo *properties) { - const char* groupName = nullptr; + const char *groupName = nullptr; KConfigGroup group; while (properties->name != nullptr) { @@ -61,8 +60,7 @@ void ProfileReader::readProperties(const KConfig& config, Profile::Ptr profile, QString name(QLatin1String(properties->name)); if (group.hasKey(name)) { - profile->setProperty(properties->property, - group.readEntry(name, QVariant(properties->type))); + profile->setProperty(properties->property, group.readEntry(name, QVariant(properties->type))); } } @@ -70,7 +68,7 @@ void ProfileReader::readProperties(const KConfig& config, Profile::Ptr profile, } } -bool ProfileReader::readProfile(const QString& path , Profile::Ptr profile , QString& parentProfile) +bool ProfileReader::readProfile(const QString &path, Profile::Ptr profile, QString &parentProfile) { if (!QFile::exists(path)) { return false; @@ -110,4 +108,3 @@ bool ProfileReader::readProfile(const QString& path , Profile::Ptr profile , QSt return true; } - diff --git a/src/profile/ProfileReader.h b/src/profile/ProfileReader.h index 1d39eaf48..897659ee3 100644 --- a/src/profile/ProfileReader.h +++ b/src/profile/ProfileReader.h @@ -13,7 +13,8 @@ class KConfig; -namespace Konsole { +namespace Konsole +{ /** Interface for all classes which can load profile settings from a file. */ class KONSOLEPROFILE_EXPORT ProfileReader { @@ -37,8 +38,7 @@ public: bool readProfile(const QString &path, Profile::Ptr profile, QString &parentProfile); private: - void readProperties(const KConfig &config, Profile::Ptr profile, - const Profile::PropertyInfo *properties); + void readProperties(const KConfig &config, Profile::Ptr profile, const Profile::PropertyInfo *properties); }; } diff --git a/src/profile/ProfileWriter.cpp b/src/profile/ProfileWriter.cpp index 0f9cfada2..bb8ba9c53 100644 --- a/src/profile/ProfileWriter.cpp +++ b/src/profile/ProfileWriter.cpp @@ -21,7 +21,7 @@ using namespace Konsole; // FIXME: A dup line from Profile.cpp - redo these -static const char GENERAL_GROUP[] = "General"; +static const char GENERAL_GROUP[] = "General"; ProfileWriter::ProfileWriter() = default; ProfileWriter::~ProfileWriter() = default; @@ -35,11 +35,9 @@ QString ProfileWriter::getPath(const Profile::Ptr &profile) return localDataLocation % QLatin1String("/") % profile->untranslatedName() % QLatin1String(".profile"); } -void ProfileWriter::writeProperties(KConfig& config, - const Profile::Ptr &profile, - const Profile::PropertyInfo* properties) +void ProfileWriter::writeProperties(KConfig &config, const Profile::Ptr &profile, const Profile::PropertyInfo *properties) { - const char* groupName = nullptr; + const char *groupName = nullptr; KConfigGroup group; while (properties->name != nullptr) { @@ -50,15 +48,14 @@ void ProfileWriter::writeProperties(KConfig& config, } if (profile->isPropertySet(properties->property)) { - group.writeEntry(QLatin1String(properties->name), - profile->property(properties->property)); + group.writeEntry(QLatin1String(properties->name), profile->property(properties->property)); } } properties++; } } -bool ProfileWriter::writeProfile(const QString& path , const Profile::Ptr &profile) +bool ProfileWriter::writeProfile(const QString &path, const Profile::Ptr &profile) { KConfig config(path, KConfig::NoGlobals); @@ -74,11 +71,9 @@ bool ProfileWriter::writeProfile(const QString& path , const Profile::Ptr &profi general.writeEntry("Parent", profile->parent()->path()); } - if (profile->isPropertySet(Profile::Command) - || profile->isPropertySet(Profile::Arguments)) { - general.writeEntry("Command", - ShellCommand(profile->command(), profile->arguments()).fullCommand()); - } + if (profile->isPropertySet(Profile::Command) || profile->isPropertySet(Profile::Arguments)) { + general.writeEntry("Command", ShellCommand(profile->command(), profile->arguments()).fullCommand()); + } // Write remaining properties writeProperties(config, profile, Profile::DefaultPropertyNames); diff --git a/src/profile/ProfileWriter.h b/src/profile/ProfileWriter.h index 9d1ba1a5e..2ac0d98a4 100644 --- a/src/profile/ProfileWriter.h +++ b/src/profile/ProfileWriter.h @@ -13,7 +13,8 @@ class KConfig; -namespace Konsole { +namespace Konsole +{ /** Interface for all classes which can write profile settings to a file. */ class KONSOLEPROFILE_EXPORT ProfileWriter { @@ -35,8 +36,7 @@ public: bool writeProfile(const QString &path, const Profile::Ptr &profile); private: - void writeProperties(KConfig &config, const Profile::Ptr &profile, - const Profile::PropertyInfo *properties); + void writeProperties(KConfig &config, const Profile::Ptr &profile, const Profile::PropertyInfo *properties); }; } diff --git a/src/session/Session.cpp b/src/session/Session.cpp index ba6dcf467..d72aa5419 100644 --- a/src/session/Session.cpp +++ b/src/session/Session.cpp @@ -10,8 +10,8 @@ #include "Session.h" // Standard -#include #include +#include #include // Qt @@ -22,19 +22,20 @@ #include // KDE -#include -#include -#include -#include #include #include +#include +#include +#include +#include #include // Konsole #include -#include "SSHProcessInfo.h" #include "Pty.h" +#include "SSHProcessInfo.h" +#include "SessionManager.h" #include "ShellCommand.h" #include "Vt102Emulation.h" #include "ZModemDialog.h" @@ -44,15 +45,14 @@ #include "konsoledebug.h" #include "profile/Profile.h" #include "profile/ProfileManager.h" -#include "SessionManager.h" #include "terminalDisplay/TerminalDisplay.h" #include "terminalDisplay/TerminalScrollBar.h" // Linux #ifdef HAVE_GETPWUID -#include #include +#include #endif using namespace Konsole; @@ -62,8 +62,8 @@ static bool show_disallow_certain_dbus_methods_message = true; static const int ZMODEM_BUFFER_SIZE = 1048576; // 1 Mb -Session::Session(QObject* parent) : - QObject(parent) +Session::Session(QObject *parent) + : QObject(parent) , _uniqueIdentifier(QUuid()) , _shellProcess(nullptr) , _emulation(nullptr) @@ -107,12 +107,12 @@ Session::Session(QObject* parent) : { _uniqueIdentifier = QUuid::createUuid(); - //prepare DBus communication + // prepare DBus communication new SessionAdaptor(this); _sessionId = ++lastSessionId; QDBusConnection::sessionBus().registerObject(QLatin1String("/Sessions/") + QString::number(_sessionId), this); - //create emulation backend + // create emulation backend _emulation = new Vt102Emulation(); _emulation->reset(); @@ -131,10 +131,10 @@ Session::Session(QObject* parent) : connect(_emulation, &Konsole::Emulation::imageResizeRequest, this, &Konsole::Session::resizeRequest); connect(_emulation, &Konsole::Emulation::sessionAttributeRequest, this, &Konsole::Session::sessionAttributeRequest); - //create new teletype for I/O with shell process + // create new teletype for I/O with shell process openTeletype(-1, true); - //setup timer for monitoring session activity & silence + // setup timer for monitoring session activity & silence _silenceTimer = new QTimer(this); _silenceTimer->setSingleShot(true); connect(_silenceTimer, &QTimer::timeout, this, &Konsole::Session::silenceTimerDone); @@ -178,9 +178,7 @@ void Session::openTeletype(int fd, bool runShell) connect(_emulation, &Konsole::Emulation::useUtf8Request, _shellProcess, &Konsole::Pty::setUtf8Mode); // get notified when the pty process is finished - connect(_shellProcess, - QOverload::of(&Konsole::Pty::finished), - this, &Konsole::Session::done); + connect(_shellProcess, QOverload::of(&Konsole::Pty::finished), this, &Konsole::Session::done); // emulator size connect(_emulation, &Konsole::Emulation::imageSizeChanged, this, &Konsole::Session::updateWindowSize); @@ -219,7 +217,7 @@ WId Session::windowId() const * creation of a native window, see https://doc.qt.io/qt-5/qwidget.html#winId * instead, use https://doc.qt.io/qt-5/qwidget.html#effectiveWinId */ - QWidget* widget = _views.first(); + QWidget *widget = _views.first(); Q_ASSERT(widget); return widget->effectiveWinId(); } @@ -237,11 +235,12 @@ bool Session::isRunning() const bool Session::hasFocus() const { - return std::any_of(_views.constBegin(), _views.constEnd(), - [](const TerminalDisplay *display) { return display-> hasFocus(); }); + return std::any_of(_views.constBegin(), _views.constEnd(), [](const TerminalDisplay *display) { + return display->hasFocus(); + }); } -void Session::setCodec(QTextCodec* codec) +void Session::setCodec(QTextCodec *codec) { if (isReadOnly()) { return; @@ -252,9 +251,9 @@ void Session::setCodec(QTextCodec* codec) Q_EMIT sessionCodecChanged(codec); } -bool Session::setCodec(const QByteArray& name) +bool Session::setCodec(const QByteArray &name) { - QTextCodec* codec = QTextCodec::codecForName(name); + QTextCodec *codec = QTextCodec::codecForName(name); if (codec != nullptr) { setCodec(codec); @@ -269,17 +268,17 @@ QByteArray Session::codec() return _emulation->codec()->name(); } -void Session::setProgram(const QString& program) +void Session::setProgram(const QString &program) { _program = ShellCommand::expand(program); } -void Session::setArguments(const QStringList& arguments) +void Session::setArguments(const QStringList &arguments) { _arguments = ShellCommand::expand(arguments); } -void Session::setInitialWorkingDirectory(const QString& dir) +void Session::setInitialWorkingDirectory(const QString &dir) { _initialWorkingDir = validDirectory(KShell::tildeExpand(ShellCommand::expand(dir))); } @@ -308,12 +307,12 @@ void Session::updateWorkingDirectory() } } -QList Session::views() const +QList Session::views() const { return _views; } -void Session::addView(TerminalDisplay* widget) +void Session::addView(TerminalDisplay *widget) { Q_ASSERT(!_views.contains(widget)); @@ -341,7 +340,7 @@ void Session::addView(TerminalDisplay* widget) _emulation->setCurrentTerminalDisplay(widget); - //connect view signals and slots + // connect view signals and slots connect(widget, &Konsole::TerminalDisplay::changedContentSizeSignal, this, &Konsole::Session::onViewSizeChange); connect(widget, &Konsole::TerminalDisplay::destroyed, this, &Konsole::Session::viewDestroyed); @@ -354,16 +353,16 @@ void Session::addView(TerminalDisplay* widget) connect(widget, &Konsole::TerminalDisplay::keyPressedSignal, this, &Konsole::Session::resetNotifications); } -void Session::viewDestroyed(QObject* view) +void Session::viewDestroyed(QObject *view) { - auto* display = reinterpret_cast(view); + auto *display = reinterpret_cast(view); Q_ASSERT(_views.contains(display)); removeView(display); } -void Session::removeView(TerminalDisplay* widget) +void Session::removeView(TerminalDisplay *widget) { _views.removeAll(widget); @@ -388,7 +387,7 @@ void Session::removeView(TerminalDisplay* widget) // Upon a KPty error, there is no description on what that error was... // Check to see if the given program is executable. -QString Session::checkProgram(const QString& program) +QString Session::checkProgram(const QString &program) { QString exec = program; @@ -412,7 +411,7 @@ QString Session::checkProgram(const QString& program) return exec; } -void Session::terminalWarning(const QString& message) +void Session::terminalWarning(const QString &message) { static const QByteArray warningText = i18nc("@info:shell Alert the user with red color text", "Warning: ").toLocal8Bit(); QByteArray messageText = message.toLocal8Bit(); @@ -444,7 +443,7 @@ void Session::run() return; } - //check that everything is in place to run the session + // check that everything is in place to run the session if (_program.isEmpty()) { qWarning() << "Program to run not set."; } @@ -483,14 +482,12 @@ void Session::run() // if a program was specified via setProgram(), but it couldn't be found (but a fallback was), print a warning if (exec != checkProgram(_program)) { terminalWarning(i18n("Could not find '%1', starting '%2' instead. Please check your profile settings.", _program, exec)); - } else if ( exec != checkProgram(exec)) { + } else if (exec != checkProgram(exec)) { terminalWarning(i18n("Could not find '%1', starting '%2' instead. Please check your profile settings.", exec, checkProgram(exec))); } // if no arguments are specified, fall back to program name - QStringList arguments = _arguments.join(QLatin1Char(' ')).isEmpty() ? - QStringList() << exec : - _arguments; + QStringList arguments = _arguments.join(QLatin1Char(' ')).isEmpty() ? QStringList() << exec : _arguments; if (!_initialWorkingDir.isEmpty()) { _shellProcess->setInitialWorkingDirectory(_initialWorkingDir); @@ -526,12 +523,12 @@ void Session::run() return; } - _shellProcess->setWriteable(false); // We are reachable via kwrited. + _shellProcess->setWriteable(false); // We are reachable via kwrited. Q_EMIT started(); } -void Session::setSessionAttribute(int what, const QString& caption) +void Session::setSessionAttribute(int what, const QString &caption) { // set to true if anything has actually changed // eg. old _nameTitle != new _nameTitle @@ -604,11 +601,11 @@ QString Session::userTitle() const return _userTitle; } -void Session::setTabTitleFormat(TabTitleContext context , const QString& format) +void Session::setTabTitleFormat(TabTitleContext context, const QString &format) { if (context == LocalTabTitle) { _localTabTitleFormat = format; - ProcessInfo* process = getProcessInfo(); + ProcessInfo *process = getProcessInfo(); process->setUserNameRequired(format.contains(QLatin1String("%u"))); } else if (context == RemoteTabTitle) { _remoteTabTitleFormat = format; @@ -648,22 +645,23 @@ bool Session::isTabColorSetByUser() const void Session::silenceTimerDone() { - //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. + // 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 + // 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. + // FIXME: Make message text for this notification and the activity notification more descriptive. if (!_monitorSilence) { setPendingNotification(Notification::Silence, false); return; } KNotification::event(hasFocus() ? QStringLiteral("Silence") : QStringLiteral("SilenceHidden"), - i18n("Silence in '%1' (Session '%2')", _displayTitle, _nameTitle), QPixmap(), - QApplication::activeWindow(), - KNotification::CloseWhenWidgetActivated); + i18n("Silence in '%1' (Session '%2')", _displayTitle, _nameTitle), + QPixmap(), + QApplication::activeWindow(), + KNotification::CloseWhenWidgetActivated); setPendingNotification(Notification::Silence); } @@ -675,7 +673,7 @@ void Session::activityTimerDone() void Session::resetNotifications() { static const Notification availableNotifications[] = {Activity, Silence, Bell}; - for (auto notification: availableNotifications) { + for (auto notification : availableNotifications) { setPendingNotification(notification, false); } } @@ -699,7 +697,7 @@ void Session::updateFlowControlState(bool suspended) void Session::changeTabTextColor(int i) { - qCDebug(KonsoleDebug) << "Changing tab text color is not implemented "<isHidden() && - 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()); + if (!view->isHidden() && 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()); view->processFilters(); } } // 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); + _emulation->setImageSize(minLines, minColumns); } } void Session::updateWindowSize(int lines, int columns) @@ -789,7 +785,7 @@ void Session::refresh() void Session::sendSignal(int signal) { - const ProcessInfo* process = getProcessInfo(); + const ProcessInfo *process = getProcessInfo(); bool ok = false; int pid; pid = process->foregroundPid(&ok); @@ -797,17 +793,14 @@ void Session::sendSignal(int signal) if (ok) { ::kill(pid, signal); } else { - qWarning()<<"foreground process id not set, unable to send signal "<sendString(msg.toUtf8()); - #undef to65k +#undef to65k } -void Session::reportForegroundColor(const QColor& c, uint terminator) +void Session::reportForegroundColor(const QColor &c, uint terminator) { reportColor(SessionAttributes::TextColor, c, terminator); } -void Session::reportBackgroundColor(const QColor& c, uint terminator) +void Session::reportBackgroundColor(const QColor &c, uint terminator) { reportColor(SessionAttributes::BackgroundColor, c, terminator); } @@ -858,7 +851,7 @@ void Session::close() bool Session::closeInNormalWay() { - _autoClose = true; + _autoClose = true; _closePerUserRequest = true; // for the possible case where following events happen in sequence: @@ -886,7 +879,7 @@ bool Session::closeInNormalWay() bool Session::closeInForceWay() { - _autoClose = true; + _autoClose = true; _closePerUserRequest = true; if (kill(SIGKILL)) { @@ -897,7 +890,7 @@ bool Session::closeInForceWay() } } -void Session::sendTextToTerminal(const QString& text, const QChar& eol) const +void Session::sendTextToTerminal(const QString &text, const QChar &eol) const { if (isReadOnly()) { return; @@ -911,7 +904,7 @@ void Session::sendTextToTerminal(const QString& text, const QChar& eol) const } // Only D-Bus calls this function (via SendText or runCommand) -void Session::sendText(const QString& text) const +void Session::sendText(const QString &text) const { if (isReadOnly()) { return; @@ -919,9 +912,11 @@ void Session::sendText(const QString& text) const #if !defined(REMOVE_SENDTEXT_RUNCOMMAND_DBUS_METHODS) if (show_disallow_certain_dbus_methods_message) { - - KNotification::event(KNotification::Warning, QStringLiteral("Konsole D-Bus Warning"), - i18n("The D-Bus methods sendText/runCommand were just used. There are security concerns about allowing these methods to be public. If desired, these methods can be changed to internal use only by re-compiling Konsole.

This warning will only show once for this Konsole instance.

")); + KNotification::event(KNotification::Warning, + QStringLiteral("Konsole D-Bus Warning"), + i18n("The D-Bus methods sendText/runCommand were just used. There are security concerns about allowing these methods to be " + "public. If desired, these methods can be changed to internal use only by re-compiling Konsole.

This warning will only " + "show once for this Konsole instance.

")); show_disallow_certain_dbus_methods_message = false; } @@ -931,7 +926,7 @@ void Session::sendText(const QString& text) const } // Only D-Bus calls this function -void Session::runCommand(const QString& command) const +void Session::runCommand(const QString &command) const { if (isReadOnly()) { return; @@ -952,9 +947,7 @@ void Session::sendMouseEvent(int buttons, int column, int line, int eventType) void Session::done(int exitCode, QProcess::ExitStatus exitStatus) { // This slot should be triggered only one time - disconnect(_shellProcess, - QOverload::of(&Konsole::Pty::finished), - this, &Konsole::Session::done); + disconnect(_shellProcess, QOverload::of(&Konsole::Pty::finished), this, &Konsole::Session::done); if (!_autoClose) { _userTitle = i18nc("@info:shell This session is done", "Finished"); @@ -976,10 +969,8 @@ void Session::done(int exitCode, QProcess::ExitStatus exitStatus) message = i18n("Program '%1' exited with status %2.", _program, exitCode); } - //FIXME: See comments in Session::silenceTimerDone() - KNotification::event(QStringLiteral("Finished"), message , QPixmap(), - QApplication::activeWindow(), - KNotification::CloseWhenWidgetActivated); + // FIXME: See comments in Session::silenceTimerDone() + KNotification::event(QStringLiteral("Finished"), message, QPixmap(), QApplication::activeWindow(), KNotification::CloseWhenWidgetActivated); } if (exitStatus != QProcess::NormalExit) { @@ -991,7 +982,7 @@ void Session::done(int exitCode, QProcess::ExitStatus exitStatus) } } -Emulation* Session::emulation() const +Emulation *Session::emulation() const { return _emulation; } @@ -1006,7 +997,7 @@ QStringList Session::environment() const return _environment; } -void Session::setEnvironment(const QStringList& environment) +void Session::setEnvironment(const QStringList &environment) { if (isReadOnly()) { return; @@ -1015,7 +1006,7 @@ void Session::setEnvironment(const QStringList& environment) _environment = environment; } -void Session::addEnvironmentEntry(const QString& entry) +void Session::addEnvironmentEntry(const QString &entry) { _environment << entry; } @@ -1025,12 +1016,12 @@ int Session::sessionId() const return _sessionId; } -void Session::setKeyBindings(const QString& name) +void Session::setKeyBindings(const QString &name) { _emulation->setKeyBindings(name); } -void Session::setTitle(TitleRole role , const QString& newTitle) +void Session::setTitle(TitleRole role, const QString &newTitle) { if (title(role) != newTitle) { if (role == NameRole) { @@ -1054,9 +1045,9 @@ QString Session::title(TitleRole role) const } } -ProcessInfo* Session::getProcessInfo() +ProcessInfo *Session::getProcessInfo() { - ProcessInfo* process = nullptr; + ProcessInfo *process = nullptr; if (isForegroundProcessActive() && updateForegroundProcessInfo()) { process = _foregroundProcessInfo; @@ -1076,8 +1067,7 @@ void Session::updateSessionProcessInfo() // The checking for pid changing looks stupid, but it is needed // at the moment to workaround the problem that processId() might // return 0 - if ((_sessionProcessInfo == nullptr) || - (processId() != 0 && processId() != _sessionProcessInfo->pid(&ok))) { + if ((_sessionProcessInfo == nullptr) || (processId() != 0 && processId() != _sessionProcessInfo->pid(&ok))) { delete _sessionProcessInfo; _sessionProcessInfo = ProcessInfo::newInstance(processId()); _sessionProcessInfo->setUserHomeDir(); @@ -1106,7 +1096,7 @@ bool Session::updateForegroundProcessInfo() bool Session::isRemote() { - ProcessInfo* process = getProcessInfo(); + ProcessInfo *process = getProcessInfo(); bool ok = false; return (process->name(&ok) == QLatin1String("ssh") && ok); @@ -1114,8 +1104,7 @@ bool Session::isRemote() QString Session::getDynamicTitle() { - - ProcessInfo* process = getProcessInfo(); + ProcessInfo *process = getProcessInfo(); // format tab titles using process info bool ok = false; @@ -1147,10 +1136,10 @@ QString Session::getDynamicTitle() // search for and replace known marker int UID = process->userId(&ok); - if(!ok) { + if (!ok) { title.replace(QLatin1String("%B"), QStringLiteral("-")); } else { - //title.replace(QLatin1String("%I"), QString::number(UID)); + // title.replace(QLatin1String("%I"), QString::number(UID)); if (UID == 0) { title.replace(QLatin1String("%B"), QStringLiteral("#")); } else { @@ -1158,7 +1147,6 @@ QString Session::getDynamicTitle() } } - title.replace(QLatin1String("%u"), process->userName()); title.replace(QLatin1String("%h"), Konsole::ProcessInfo::localHost()); title.replace(QLatin1String("%n"), process->name(&ok)); @@ -1172,7 +1160,7 @@ QString Session::getDynamicTitle() process = getProcessInfo(); dir = process->currentDir(&ok); } - if(!ok) { + if (!ok) { title.replace(QLatin1String("%d"), QStringLiteral("-")); title.replace(QLatin1String("%D"), QStringLiteral("-")); } else { @@ -1237,7 +1225,7 @@ QUrl Session::getUrl() return QUrl::fromLocalFile(path); } -void Session::setIconName(const QString& iconName) +void Session::setIconName(const QString &iconName) { if (iconName != _iconName) { _iconName = iconName; @@ -1245,7 +1233,7 @@ void Session::setIconName(const QString& iconName) } } -void Session::setIconText(const QString& iconText) +void Session::setIconText(const QString &iconText) { _iconText = iconText; } @@ -1260,12 +1248,12 @@ QString Session::iconText() const return _iconText; } -void Session::setHistoryType(const HistoryType& hType) +void Session::setHistoryType(const HistoryType &hType) { _emulation->setHistory(hType); } -const HistoryType& Session::historyType() const +const HistoryType &Session::historyType() const { return _emulation->history(); } @@ -1289,7 +1277,7 @@ bool Session::isMonitorActivity() const { return _monitorActivity; } -bool Session::isMonitorSilence() const +bool Session::isMonitorSilence() const { return _monitorSilence; } @@ -1300,7 +1288,7 @@ void Session::setMonitorActivity(bool monitor) return; } - _monitorActivity = monitor; + _monitorActivity = monitor; _notifiedActivity = false; // This timer is meaningful only after activity has been notified @@ -1391,7 +1379,7 @@ void Session::cancelZModem() _zmodemBusy = false; } -void Session::startZModem(const QString& zmodem, const QString& dir, const QStringList& list) +void Session::startZModem(const QString &zmodem, const QString &dir, const QStringList &list) { _zmodemBusy = true; _zmodemProc = new KProcess(); @@ -1405,18 +1393,14 @@ void Session::startZModem(const QString& zmodem, const QString& dir, const QStri connect(_zmodemProc, &KProcess::readyReadStandardOutput, this, &Konsole::Session::zmodemReadAndSendBlock); connect(_zmodemProc, &KProcess::readyReadStandardError, this, &Konsole::Session::zmodemReadStatus); - connect(_zmodemProc, - QOverload::of(&KProcess::finished), - this, &Konsole::Session::zmodemFinished); + connect(_zmodemProc, QOverload::of(&KProcess::finished), this, &Konsole::Session::zmodemFinished); _zmodemProc->start(); - disconnect(_shellProcess, &Konsole::Pty::receivedData, - this, &Konsole::Session::onReceiveBlock); + disconnect(_shellProcess, &Konsole::Pty::receivedData, this, &Konsole::Session::onReceiveBlock); connect(_shellProcess, &Konsole::Pty::receivedData, this, &Konsole::Session::zmodemReceiveBlock); - _zmodemProgress = new ZModemDialog(QApplication::activeWindow(), false, - i18n("ZModem Progress")); + _zmodemProgress = new ZModemDialog(QApplication::activeWindow(), false, i18n("ZModem Progress")); connect(_zmodemProgress, &Konsole::ZModemDialog::zmodemCancel, this, &Konsole::Session::zmodemFinished); @@ -1457,7 +1441,7 @@ void Session::zmodemReadStatus() } } -void Session::zmodemReceiveBlock(const char* data, int len) +void Session::zmodemReceiveBlock(const char *data, int len) { static int steps = 0; QByteArray bytes(data, len); @@ -1479,13 +1463,12 @@ void Session::zmodemFinished() user1Clicked() will recursively invoke this function again when the KProcess is deleted! */ if (_zmodemProc != nullptr) { - KProcess* process = _zmodemProc; - _zmodemProc = nullptr; // Set _zmodemProc to 0 avoid recursive invocations! + KProcess *process = _zmodemProc; + _zmodemProc = nullptr; // Set _zmodemProc to 0 avoid recursive invocations! _zmodemBusy = false; - delete process; // Now, the KProcess may be disposed safely. + delete process; // Now, the KProcess may be disposed safely. - disconnect(_shellProcess, &Konsole::Pty::receivedData, - this , &Konsole::Session::zmodemReceiveBlock); + disconnect(_shellProcess, &Konsole::Pty::receivedData, this, &Konsole::Session::zmodemReceiveBlock); connect(_shellProcess, &Konsole::Pty::receivedData, this, &Konsole::Session::onReceiveBlock); _shellProcess->sendData(QByteArrayLiteral("\030\030\030\030")); // Abort @@ -1494,7 +1477,7 @@ void Session::zmodemFinished() } } -void Session::onReceiveBlock(const char* buf, int len) +void Session::onReceiveBlock(const char *buf, int len) { handleActivity(); _emulation->receiveData(buf, len); @@ -1505,7 +1488,7 @@ QSize Session::size() return _emulation->imageSize(); } -void Session::setSize(const QSize& size) +void Session::setSize(const QSize &size) { if ((size.width() <= 1) || (size.height() <= 1)) { return; @@ -1519,7 +1502,7 @@ QSize Session::preferredSize() const return _preferredSize; } -void Session::setPreferredSize(const QSize& size) +void Session::setPreferredSize(const QSize &size) { _preferredSize = size; } @@ -1529,7 +1512,7 @@ int Session::processId() const return _shellProcess->processId(); } -void Session::setTitle(int role , const QString& title) +void Session::setTitle(int role, const QString &title) { switch (role) { case 0: @@ -1559,7 +1542,7 @@ QString Session::title(int role) const } } -void Session::setTabTitleFormat(int context , const QString& format) +void Session::setTabTitleFormat(int context, const QString &format) { switch (context) { case 0: @@ -1600,7 +1583,7 @@ void Session::setHistorySize(int lines) int Session::historySize() const { - const HistoryType& currentHistory = historyType(); + const HistoryType ¤tHistory = historyType(); if (currentHistory.isEnabled()) { if (currentHistory.isUnlimited()) { @@ -1620,12 +1603,12 @@ QString Session::profile() void Session::setProfile(const QString &profileName) { - const QList profiles = ProfileManager::instance()->allProfiles(); - for (const Profile::Ptr &profile : profiles) { - if (profile->name() == profileName) { - SessionManager::instance()->setSessionProfile(this, profile); + const QList profiles = ProfileManager::instance()->allProfiles(); + for (const Profile::Ptr &profile : profiles) { + if (profile->name() == profileName) { + SessionManager::instance()->setSessionProfile(this, profile); + } } - } } int Session::foregroundProcessId() @@ -1666,17 +1649,17 @@ QString Session::foregroundProcessName() return name; } -void Session::saveSession(KConfigGroup& group) +void Session::saveSession(KConfigGroup &group) { group.writePathEntry("WorkingDir", currentWorkingDirectory()); - group.writeEntry("LocalTab", tabTitleFormat(LocalTabTitle)); - group.writeEntry("RemoteTab", tabTitleFormat(RemoteTabTitle)); - group.writeEntry("TabColor", color().isValid() ? color().name(QColor::HexArgb) : QString()); - group.writeEntry("SessionGuid", _uniqueIdentifier.toString()); - group.writeEntry("Encoding", QString::fromUtf8(codec())); + group.writeEntry("LocalTab", tabTitleFormat(LocalTabTitle)); + group.writeEntry("RemoteTab", tabTitleFormat(RemoteTabTitle)); + group.writeEntry("TabColor", color().isValid() ? color().name(QColor::HexArgb) : QString()); + group.writeEntry("SessionGuid", _uniqueIdentifier.toString()); + group.writeEntry("Encoding", QString::fromUtf8(codec())); } -void Session::restoreSession(KConfigGroup& group) +void Session::restoreSession(KConfigGroup &group) { QString value; @@ -1706,7 +1689,7 @@ void Session::restoreSession(KConfigGroup& group) } } -QString Session::validDirectory(const QString& dir) const +QString Session::validDirectory(const QString &dir) const { QString validDir = dir; if (validDir.isEmpty()) { @@ -1723,7 +1706,7 @@ QString Session::validDirectory(const QString& dir) const void Session::setPendingNotification(Session::Notification notification, bool enable) { - if(enable != _activeNotifications.testFlag(notification)) { + if (enable != _activeNotifications.testFlag(notification)) { _activeNotifications.setFlag(notification, enable); Q_EMIT notificationsChanged(notification, enable); } @@ -1736,7 +1719,8 @@ void Session::handleActivity() if (_monitorActivity && !_notifiedActivity) { KNotification::event(hasFocus() ? QStringLiteral("Activity") : QStringLiteral("ActivityHidden"), - i18n("Activity in '%1' (Session '%2')", _displayTitle, _nameTitle), QPixmap(), + i18n("Activity in '%1' (Session '%2')", _displayTitle, _nameTitle), + QPixmap(), QApplication::activeWindow(), KNotification::CloseWhenWidgetActivated); diff --git a/src/session/Session.h b/src/session/Session.h index 653a2e31c..734821ab6 100644 --- a/src/session/Session.h +++ b/src/session/Session.h @@ -10,25 +10,26 @@ #define SESSION_H // Qt -#include #include -#include -#include #include -#include +#include +#include #include +#include +#include // Konsole -#include "konsolesession_export.h" -#include "config-konsole.h" #include "Shortcut_p.h" +#include "config-konsole.h" +#include "konsolesession_export.h" class QColor; class KConfigGroup; class KProcess; -namespace Konsole { +namespace Konsole +{ class Emulation; class Pty; class ProcessInfo; @@ -145,7 +146,7 @@ public: * Tab title format used session currently contains * a connection to a remote computer (via SSH) */ - RemoteTabTitle + RemoteTabTitle, }; /** @@ -169,7 +170,7 @@ public: /** * Sets the color user by this session for tab. - * + * * @param color The background color for the tab. */ void setColor(const QColor &color); @@ -256,7 +257,7 @@ public: /** The name of the session. */ NameRole, /** The title of the session which is displayed in tabs etc. */ - DisplayedTitleRole + DisplayedTitleRole, }; /** @@ -357,20 +358,20 @@ public: } /** - * Possible values of the @p what parameter for setSessionAttribute(). - * See the "Operating System Commands" section at: - * https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Operating-System-Commands - */ + * Possible values of the @p what parameter for setSessionAttribute(). + * See the "Operating System Commands" section at: + * https://invisible-island.net/xterm/ctlseqs/ctlseqs.html#h3-Operating-System-Commands + */ enum SessionAttributes { IconNameAndWindowTitle = 0, IconName = 1, WindowTitle = 2, - CurrentDirectory = 7, // From VTE (supposedly 6 was for dir, 7 for file, but whatever) + CurrentDirectory = 7, // From VTE (supposedly 6 was for dir, 7 for file, but whatever) TextColor = 10, BackgroundColor = 11, - SessionName = 30, // Non-standard - SessionIcon = 32, // Non-standard - ProfileChange = 50 // this clashes with Xterm's font change command + SessionName = 30, // Non-standard + SessionIcon = 32, // Non-standard + ProfileChange = 50, // this clashes with Xterm's font change command }; // Sets the text codec used by this sessions terminal emulation. @@ -382,7 +383,7 @@ public: void sendSignal(int signal); - void reportColor(SessionAttributes r, const QColor& c, uint terminator); + void reportColor(SessionAttributes r, const QColor &c, uint terminator); void reportForegroundColor(const QColor &c, uint terminator); void reportBackgroundColor(const QColor &c, uint terminator); @@ -404,7 +405,10 @@ public: Q_DECLARE_FLAGS(Notifications, Notification) /** Returns active notifications. */ - Notifications activeNotifications() const { return _activeNotifications; } + Notifications activeNotifications() const + { + return _activeNotifications; + } public Q_SLOTS: @@ -438,7 +442,7 @@ public Q_SLOTS: * Closes the terminal session. It kills the terminal process by calling * closeInNormalWay() and, optionally, closeInForceWay(). */ - //Q_SCRIPTABLE void close(); // This cause the menu issues bko 185466 + // Q_SCRIPTABLE void close(); // This cause the menu issues bko 185466 void close(); /** @@ -537,9 +541,9 @@ public Q_SLOTS: Q_SCRIPTABLE void sendMouseEvent(int buttons, int column, int line, int eventType); /** - * Returns the process id of the terminal process. - * This is the id used by the system API to refer to the process. - */ + * Returns the process id of the terminal process. + * This is the id used by the system API to refer to the process. + */ Q_SCRIPTABLE int processId() const; /** @@ -550,9 +554,9 @@ public Q_SLOTS: Q_SCRIPTABLE int foregroundProcessId(); /** Sets the text codec used by this sessions terminal emulation. - * Overloaded to accept a QByteArray for convenience since DBus - * does not accept QTextCodec directly. - */ + * Overloaded to accept a QByteArray for convenience since DBus + * does not accept QTextCodec directly. + */ Q_SCRIPTABLE bool setCodec(const QByteArray &name); /** Returns the codec used to decode incoming characters in this @@ -575,10 +579,10 @@ public Q_SLOTS: Q_SCRIPTABLE QString title(int role) const; /** Returns the "friendly" version of the QUuid of this session. - * This is a QUuid with the braces and dashes removed, so it cannot be - * used to construct a new QUuid. The same text appears in the - * SHELL_SESSION_ID environment variable. - */ + * This is a QUuid with the braces and dashes removed, so it cannot be + * used to construct a new QUuid. The same text appears in the + * SHELL_SESSION_ID environment variable. + */ Q_SCRIPTABLE QString shellSessionId() const; /** Sets the session's tab title format for the specified @p context to @p format. @@ -745,7 +749,7 @@ private Q_SLOTS: void onViewSizeChange(int height, int width); - //automatically detach views from sessions when view is destroyed + // automatically detach views from sessions when view is destroyed void viewDestroyed(QObject *view); void zmodemReadStatus(); @@ -790,7 +794,7 @@ private: QString validDirectory(const QString &dir) const; - QUuid _uniqueIdentifier; // SHELL_SESSION_ID + QUuid _uniqueIdentifier; // SHELL_SESSION_ID Pty *_shellProcess; Emulation *_emulation; @@ -825,7 +829,7 @@ private: bool _tabColorSetByUser; QString _iconName; - QString _iconText; // not actually used + QString _iconText; // not actually used bool _addToUtmp; bool _flowControlEnabled; diff --git a/src/session/SessionController.cpp b/src/session/SessionController.cpp index ea5305dbd..1a101bff7 100644 --- a/src/session/SessionController.cpp +++ b/src/session/SessionController.cpp @@ -8,48 +8,48 @@ // Own #include "SessionController.h" -#include "profile/ProfileManager.h" #include "konsoledebug.h" +#include "profile/ProfileManager.h" #include "terminalDisplay/TerminalColor.h" #include "terminalDisplay/TerminalFonts.h" // Qt -#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 -#include -#include -#include -#include -#include -#include -#include -#include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include #include #include -#include #include +#include // Konsole #include "CopyInputDialog.h" @@ -60,6 +60,7 @@ #include "ScreenWindow.h" #include "SearchHistoryTask.h" +#include "filterHotSpots/ColorFilter.h" #include "filterHotSpots/EscapeSequenceUrlFilter.h" #include "filterHotSpots/FileFilter.h" #include "filterHotSpots/Filter.h" @@ -67,7 +68,6 @@ #include "filterHotSpots/HotSpot.h" #include "filterHotSpots/RegExpFilter.h" #include "filterHotSpots/UrlFilter.h" -#include "filterHotSpots/ColorFilter.h" #include "history/HistoryType.h" #include "history/HistoryTypeFile.h" @@ -82,18 +82,18 @@ #include "widgets/EditProfileDialog.h" #include "widgets/IncrementalSearchBar.h" -#include "terminalDisplay/TerminalDisplay.h" #include "terminalDisplay/TerminalColor.h" +#include "terminalDisplay/TerminalDisplay.h" // For Unix signal names #include using namespace Konsole; -QSet SessionController::_allControllers; +QSet SessionController::_allControllers; int SessionController::_lastControllerId; -SessionController::SessionController(Session* sessionParam, TerminalDisplay* viewParam, QObject* parent) +SessionController::SessionController(Session *sessionParam, TerminalDisplay *viewParam, QObject *parent) : ViewProperties(parent) , KXMLGUIClient() , _copyToGroup(nullptr) @@ -179,7 +179,7 @@ SessionController::SessionController(Session* sessionParam, TerminalDisplay* vie connect(this, &Konsole::SessionController::tabRenamedByUser, session(), &Konsole::Session::tabTitleSetByUser); connect(this, &Konsole::SessionController::tabColoredByUser, session(), &Konsole::Session::tabColorSetByUser); - connect(session() , &Konsole::Session::currentDirectoryChanged , this , &Konsole::SessionController::currentDirectoryChanged); + connect(session(), &Konsole::Session::currentDirectoryChanged, this, &Konsole::SessionController::currentDirectoryChanged); // listen for color changes connect(session(), &Konsole::Session::changeBackgroundColorRequest, view()->terminalColor(), &TerminalColor::setBackgroundColor); @@ -208,10 +208,12 @@ SessionController::SessionController(Session* sessionParam, TerminalDisplay* vie _interactionTimer->setSingleShot(true); _interactionTimer->setInterval(500); connect(_interactionTimer, &QTimer::timeout, this, &Konsole::SessionController::snapshot); - connect(view(), &Konsole::TerminalDisplay::compositeFocusChanged, - this, [this](bool focused) { if (focused) { interactionHandler(); }}); - connect(view(), &Konsole::TerminalDisplay::keyPressedSignal, - this, &Konsole::SessionController::interactionHandler); + connect(view(), &Konsole::TerminalDisplay::compositeFocusChanged, this, [this](bool focused) { + if (focused) { + interactionHandler(); + } + }); + connect(view(), &Konsole::TerminalDisplay::keyPressedSignal, this, &Konsole::SessionController::interactionHandler); // take a snapshot of the session state periodically in the background auto backgroundTimer = new QTimer(session()); @@ -221,23 +223,16 @@ SessionController::SessionController(Session* sessionParam, TerminalDisplay* vie backgroundTimer->start(); // xterm '10;?' request - connect(session(), &Konsole::Session::getForegroundColor, - this, &Konsole::SessionController::sendForegroundColor); + connect(session(), &Konsole::Session::getForegroundColor, this, &Konsole::SessionController::sendForegroundColor); // xterm '11;?' request - connect(session(), &Konsole::Session::getBackgroundColor, - this, &Konsole::SessionController::sendBackgroundColor); + connect(session(), &Konsole::Session::getBackgroundColor, this, &Konsole::SessionController::sendBackgroundColor); _allControllers.insert(this); // A list of programs that accept Ctrl+C to clear command line used // before outputting bookmark. - _bookmarkValidProgramsToClear = QStringList({ - QStringLiteral("bash"), - QStringLiteral("fish"), - QStringLiteral("sh"), - QStringLiteral("tcsh"), - QStringLiteral("zsh") - }); + _bookmarkValidProgramsToClear = + QStringList({QStringLiteral("bash"), QStringLiteral("fish"), QStringLiteral("sh"), QStringLiteral("tcsh"), QStringLiteral("zsh")}); setupSearchBar(); _searchBar->setVisible(_isSearchBarEnabled); @@ -247,31 +242,20 @@ SessionController::~SessionController() { _allControllers.remove(this); - if(factory() != nullptr) { + if (factory() != nullptr) { factory()->removeClient(this); } } -void SessionController::trackOutput(QKeyEvent* event) +void SessionController::trackOutput(QKeyEvent *event) { Q_ASSERT(view()->screenWindow()); // Qt has broken something, so we can't rely on just checking if certain // keys are passed as modifiers anymore. const int key = event->key(); - const bool shouldNotTriggerScroll = - key == Qt::Key_Super_L || - key == Qt::Key_Super_R || - key == Qt::Key_Hyper_L || - key == Qt::Key_Hyper_R || - key == Qt::Key_Shift || - key == Qt::Key_Control || - key == Qt::Key_Meta || - key == Qt::Key_Alt || - key == Qt::Key_AltGr || - key == Qt::Key_CapsLock || - key == Qt::Key_NumLock || - key == Qt::Key_ScrollLock; - + const bool shouldNotTriggerScroll = key == Qt::Key_Super_L || key == Qt::Key_Super_R || key == Qt::Key_Hyper_L || key == Qt::Key_Hyper_R + || key == Qt::Key_Shift || key == Qt::Key_Control || key == Qt::Key_Meta || key == Qt::Key_Alt || key == Qt::Key_AltGr || key == Qt::Key_CapsLock + || key == Qt::Key_NumLock || key == Qt::Key_ScrollLock; // Only jump to the bottom if the user actually typed something in, // not if the user e. g. just pressed a modifier. @@ -315,7 +299,7 @@ void SessionController::snapshot() Q_ASSERT(!session().isNull()); QString title = session()->getDynamicTitle(); - title = title.simplified(); + title = title.simplified(); // Visualize that the session is broadcasting to others if ((_copyToGroup != nullptr) && _copyToGroup->sessions().count() > 1) { @@ -371,11 +355,10 @@ void SessionController::rename() renameSession(); } -void SessionController::openUrl(const QUrl& url) +void SessionController::openUrl(const QUrl &url) { // Clear shell's command line - if (!session()->isForegroundProcessActive() - && _bookmarkValidProgramsToClear.contains(session()->foregroundProcessName())) { + if (!session()->isForegroundProcessActive() && _bookmarkValidProgramsToClear.contains(session()->foregroundProcessName())) { session()->sendTextToTerminal(QChar(0x03), QLatin1Char('\n')); // Ctrl+C } @@ -421,24 +404,22 @@ void SessionController::openUrl(const QUrl& url) session()->sendTextToTerminal(telnetCommand, QLatin1Char('\r')); } else { - //TODO Implement handling for other Url types + // TODO Implement handling for other Url types - KMessageBox::sorry(view()->window(), - i18n("Konsole does not know how to open the bookmark: ") + - url.toDisplayString()); + KMessageBox::sorry(view()->window(), i18n("Konsole does not know how to open the bookmark: ") + url.toDisplayString()); qCDebug(KonsoleDebug) << "Unable to open bookmark at url" << url << ", I do not know" - << " how to handle the protocol " << url.scheme(); + << " how to handle the protocol " << url.scheme(); } } void SessionController::setupPrimaryScreenSpecificActions(bool use) { - KActionCollection* collection = actionCollection(); - QAction* clearAction = collection->action(QStringLiteral("clear-history")); - QAction* resetAction = collection->action(QStringLiteral("clear-history-and-reset")); - QAction* selectAllAction = collection->action(QStringLiteral("select-all")); - QAction* selectLineAction = collection->action(QStringLiteral("select-line")); + KActionCollection *collection = actionCollection(); + QAction *clearAction = collection->action(QStringLiteral("clear-history")); + QAction *resetAction = collection->action(QStringLiteral("clear-history-and-reset")); + QAction *selectAllAction = collection->action(QStringLiteral("select-all")); + QAction *selectLineAction = collection->action(QStringLiteral("select-line")); // these actions are meaningful only when primary screen is used. clearAction->setEnabled(use); @@ -447,16 +428,16 @@ void SessionController::setupPrimaryScreenSpecificActions(bool use) selectLineAction->setEnabled(use); } -void SessionController::selectionChanged(const QString& selectedText) +void SessionController::selectionChanged(const QString &selectedText) { _selectedText = selectedText; updateCopyAction(selectedText); } -void SessionController::updateCopyAction(const QString& selectedText) +void SessionController::updateCopyAction(const QString &selectedText) { - QAction* copyAction = actionCollection()->action(QStringLiteral("edit_copy")); - QAction* copyContextMenu = actionCollection()->action(QStringLiteral("edit_copy_contextmenu")); + QAction *copyAction = actionCollection()->action(QStringLiteral("edit_copy")); + QAction *copyContextMenu = actionCollection()->action(QStringLiteral("edit_copy_contextmenu")); // copy action is meaningful only when some text is selected. copyAction->setEnabled(!selectedText.isEmpty()); copyContextMenu->setVisible(!selectedText.isEmpty()); @@ -491,9 +472,9 @@ void SessionController::updateWebSearchMenu() if (KUriFilter::self()->filterSearchUri(filterData, KUriFilter::NormalTextFilter)) { const QStringList searchProviders = filterData.preferredSearchProviders(); if (!searchProviders.isEmpty()) { - _webSearchMenu->setText(i18n("Search for '%1' with", KStringHandler::rsqueeze(searchText, 16))); + _webSearchMenu->setText(i18n("Search for '%1' with", KStringHandler::rsqueeze(searchText, 16))); - QAction* action = nullptr; + QAction *action = nullptr; for (const QString &searchProvider : searchProviders) { action = new QAction(searchProvider, _webSearchMenu); @@ -517,14 +498,14 @@ void SessionController::updateWebSearchMenu() void SessionController::handleWebShortcutAction() { - auto * action = qobject_cast(sender()); + auto *action = qobject_cast(sender()); if (action == nullptr) { return; } KUriFilterData filterData(action->data().toString()); - if (KUriFilter::self()->filterUri(filterData, { QStringLiteral("kurisearchfilter") })) { + if (KUriFilter::self()->filterUri(filterData, {QStringLiteral("kurisearchfilter")})) { const QUrl url = filterData.uri(); auto *job = new KIO::OpenUrlJob(url); @@ -535,11 +516,11 @@ void SessionController::handleWebShortcutAction() void SessionController::configureWebShortcuts() { - auto job = new KIO::CommandLauncherJob(QStringLiteral("kcmshell5"), { QStringLiteral("webshortcuts") }); + auto job = new KIO::CommandLauncherJob(QStringLiteral("kcmshell5"), {QStringLiteral("webshortcuts")}); job->start(); } -void SessionController::sendSignal(QAction* action) +void SessionController::sendSignal(QAction *action) { const auto signal = action->data().toInt(); session()->sendSignal(signal); @@ -559,7 +540,7 @@ void Konsole::SessionController::sendBackgroundColor(uint terminator) void SessionController::toggleReadOnly() { - auto *action = qobject_cast(sender()); + auto *action = qobject_cast(sender()); if (action != nullptr) { bool readonly = !isReadOnly(); session()->setReadOnly(readonly); @@ -584,22 +565,22 @@ void SessionController::setupSearchBar() connect(_searchBar, &Konsole::IncrementalSearchBar::searchFromClicked, this, &Konsole::SessionController::searchFrom); connect(_searchBar, &Konsole::IncrementalSearchBar::findNextClicked, this, &Konsole::SessionController::findNextInHistory); connect(_searchBar, &Konsole::IncrementalSearchBar::findPreviousClicked, this, &Konsole::SessionController::findPreviousInHistory); - connect(_searchBar, &Konsole::IncrementalSearchBar::highlightMatchesToggled , this , &Konsole::SessionController::highlightMatches); + connect(_searchBar, &Konsole::IncrementalSearchBar::highlightMatchesToggled, this, &Konsole::SessionController::highlightMatches); connect(_searchBar, &Konsole::IncrementalSearchBar::matchCaseToggled, this, &Konsole::SessionController::changeSearchMatch); connect(_searchBar, &Konsole::IncrementalSearchBar::matchRegExpToggled, this, &Konsole::SessionController::changeSearchMatch); } -void SessionController::setShowMenuAction(QAction* action) +void SessionController::setShowMenuAction(QAction *action) { _showMenuAction = action; } void SessionController::setupCommonActions() { - KActionCollection* collection = actionCollection(); + KActionCollection *collection = actionCollection(); // Close Session - QAction* action = collection->addAction(QStringLiteral("close-session"), this, &SessionController::closeSession); + QAction *action = collection->addAction(QStringLiteral("close-session"), this, &SessionController::closeSession); action->setText(i18n("&Close Session")); action->setIcon(QIcon::fromTheme(QStringLiteral("tab-close"))); @@ -654,7 +635,6 @@ void SessionController::setupCommonActions() _webSearchMenu->setVisible(false); collection->addAction(QStringLiteral("web-search"), _webSearchMenu); - action = collection->addAction(QStringLiteral("select-all"), this, &SessionController::selectAll); action->setText(i18n("&Select All")); action->setIcon(QIcon::fromTheme(QStringLiteral("edit-select-all"))); @@ -726,9 +706,11 @@ void SessionController::setupCommonActions() connect(session(), &Konsole::Session::sessionCodecChanged, this, &Konsole::SessionController::updateCodecAction); connect(_codecAction, #if KCONFIGWIDGETS_VERSION >= QT_VERSION_CHECK(5, 78, 0) - QOverload::of(&KCodecAction::codecTriggered), this, + QOverload::of(&KCodecAction::codecTriggered), + this, #else - QOverload::of(&KCodecAction::triggered), this, + QOverload::of(&KCodecAction::triggered), + this, #endif &Konsole::SessionController::changeCodec); @@ -741,29 +723,29 @@ void SessionController::setupCommonActions() void SessionController::setupExtraActions() { - KActionCollection* collection = actionCollection(); + KActionCollection *collection = actionCollection(); // Rename Session - QAction* action = collection->addAction(QStringLiteral("rename-session"), this, &SessionController::renameSession); + QAction *action = collection->addAction(QStringLiteral("rename-session"), this, &SessionController::renameSession); action->setText(i18n("&Configure or Rename Tab...")); action->setIcon(QIcon::fromTheme(QStringLiteral("edit-rename"))); collection->setDefaultShortcut(action, Konsole::ACCEL | Qt::ALT | Qt::Key_S); // Copy input to ==> all tabs - auto* copyInputToAllTabsAction = collection->add(QStringLiteral("copy-input-to-all-tabs")); + auto *copyInputToAllTabsAction = collection->add(QStringLiteral("copy-input-to-all-tabs")); copyInputToAllTabsAction->setText(i18n("&All Tabs in Current Window")); copyInputToAllTabsAction->setData(CopyInputToAllTabsMode); // this action is also used in other place, so remember it _copyInputToAllTabsAction = copyInputToAllTabsAction; // Copy input to ==> selected tabs - auto* copyInputToSelectedTabsAction = collection->add(QStringLiteral("copy-input-to-selected-tabs")); + auto *copyInputToSelectedTabsAction = collection->add(QStringLiteral("copy-input-to-selected-tabs")); copyInputToSelectedTabsAction->setText(i18n("&Select Tabs...")); collection->setDefaultShortcut(copyInputToSelectedTabsAction, Konsole::ACCEL | Qt::SHIFT | Qt::Key_Period); copyInputToSelectedTabsAction->setData(CopyInputToSelectedTabsMode); // Copy input to ==> none - auto* copyInputToNoneAction = collection->add(QStringLiteral("copy-input-to-none")); + auto *copyInputToNoneAction = collection->add(QStringLiteral("copy-input-to-none")); copyInputToNoneAction->setText(i18nc("@action:inmenu Do not select any tabs", "&None")); collection->setDefaultShortcut(copyInputToNoneAction, Konsole::ACCEL | Qt::SHIFT | Qt::Key_Slash); copyInputToNoneAction->setData(CopyInputToNoneMode); @@ -771,14 +753,12 @@ void SessionController::setupExtraActions() // The "Copy Input To" submenu // The above three choices are represented as combo boxes - auto* copyInputActions = collection->add(QStringLiteral("copy-input-to")); + auto *copyInputActions = collection->add(QStringLiteral("copy-input-to")); copyInputActions->setText(i18n("Copy Input To")); copyInputActions->addAction(copyInputToAllTabsAction); copyInputActions->addAction(copyInputToSelectedTabsAction); copyInputActions->addAction(copyInputToNoneAction); - connect(copyInputActions, - QOverload::of(&KSelectAction::triggered), this, - &Konsole::SessionController::copyInputActionsTriggered); + connect(copyInputActions, QOverload::of(&KSelectAction::triggered), this, &Konsole::SessionController::copyInputActionsTriggered); action = collection->addAction(QStringLiteral("zmodem-upload"), this, &SessionController::zmodemUpload); action->setText(i18n("&ZModem Upload...")); @@ -786,7 +766,7 @@ void SessionController::setupExtraActions() collection->setDefaultShortcut(action, Konsole::ACCEL | Qt::ALT | Qt::Key_U); // Monitor - KToggleAction* toggleAction = new KToggleAction(i18n("Monitor for &Activity"), this); + KToggleAction *toggleAction = new KToggleAction(i18n("Monitor for &Activity"), this); collection->setDefaultShortcut(toggleAction, Konsole::ACCEL | Qt::SHIFT | Qt::Key_A); action = collection->addAction(QStringLiteral("monitor-activity"), toggleAction); connect(action, &QAction::toggled, this, &Konsole::SessionController::monitorActivity); @@ -822,24 +802,22 @@ void SessionController::setupExtraActions() collection->setDefaultShortcut(action, Konsole::ACCEL | Qt::ALT | Qt::Key_0); // Send signal - auto* sendSignalActions = collection->add(QStringLiteral("send-signal")); + auto *sendSignalActions = collection->add(QStringLiteral("send-signal")); sendSignalActions->setText(i18n("Send Signal")); - connect(sendSignalActions, - QOverload::of(&KSelectAction::triggered), this, - &Konsole::SessionController::sendSignal); + connect(sendSignalActions, QOverload::of(&KSelectAction::triggered), this, &Konsole::SessionController::sendSignal); action = collection->addAction(QStringLiteral("sigstop-signal")); - action->setText(i18n("&Suspend Task") + QStringLiteral(" (STOP)")); + action->setText(i18n("&Suspend Task") + QStringLiteral(" (STOP)")); action->setData(SIGSTOP); sendSignalActions->addAction(action); action = collection->addAction(QStringLiteral("sigcont-signal")); - action->setText(i18n("&Continue Task") + QStringLiteral(" (CONT)")); + action->setText(i18n("&Continue Task") + QStringLiteral(" (CONT)")); action->setData(SIGCONT); sendSignalActions->addAction(action); action = collection->addAction(QStringLiteral("sighup-signal")); - action->setText(i18n("&Hangup") + QStringLiteral(" (HUP)")); + action->setText(i18n("&Hangup") + QStringLiteral(" (HUP)")); action->setData(SIGHUP); sendSignalActions->addAction(action); @@ -854,17 +832,17 @@ void SessionController::setupExtraActions() sendSignalActions->addAction(action); action = collection->addAction(QStringLiteral("sigkill-signal")); - action->setText(i18n("&Kill Task") + QStringLiteral(" (KILL)")); + action->setText(i18n("&Kill Task") + QStringLiteral(" (KILL)")); action->setData(SIGKILL); sendSignalActions->addAction(action); action = collection->addAction(QStringLiteral("sigusr1-signal")); - action->setText(i18n("User Signal &1") + QStringLiteral(" (USR1)")); + action->setText(i18n("User Signal &1") + QStringLiteral(" (USR1)")); action->setData(SIGUSR1); sendSignalActions->addAction(action); action = collection->addAction(QStringLiteral("sigusr2-signal")); - action->setText(i18n("User Signal &2") + QStringLiteral(" (USR2)")); + action->setText(i18n("User Signal &2") + QStringLiteral(" (USR2)")); action->setData(SIGUSR2); sendSignalActions->addAction(action); } @@ -902,7 +880,7 @@ void SessionController::updateCodecAction(QTextCodec *codec) _codecAction->setCurrentCodec(codec); } -void SessionController::changeCodec(QTextCodec* codec) +void SessionController::changeCodec(QTextCodec *codec) { session()->setCodec(codec); } @@ -967,7 +945,7 @@ void SessionController::renameSession() snapshot(); } - if(remoteTabTitle != sessionRemoteTabTitleFormat) { + if (remoteTabTitle != sessionRemoteTabTitleFormat) { session()->setTabTitleFormat(Session::RemoteTabTitle, remoteTabTitle); Q_EMIT tabRenamedByUser(true); snapshot(); @@ -999,11 +977,14 @@ bool SessionController::confirmClose() const QString question; if (title.isEmpty()) { - question = i18n("A program is currently running in this session." - " Are you sure you want to close it?"); + question = i18n( + "A program is currently running in this session." + " Are you sure you want to close it?"); } else { - question = i18n("The program '%1' is currently running in this session." - " Are you sure you want to close it?", title); + question = i18n( + "The program '%1' is currently running in this session." + " Are you sure you want to close it?", + title); } int result = KMessageBox::warningYesNo(view()->window(), @@ -1031,11 +1012,14 @@ bool SessionController::confirmForceClose() const QString question; if (title.isEmpty()) { - question = i18n("A program in this session would not die." - " Are you sure you want to kill it by force?"); + question = i18n( + "A program in this session would not die." + " Are you sure you want to kill it by force?"); } else { - question = i18n("The program '%1' is in this session would not die." - " Are you sure you want to kill it by force?", title); + question = i18n( + "The program '%1' is in this session would not die." + " Are you sure you want to kill it by force?", + title); } int result = KMessageBox::warningYesNo(view()->window(), question, i18n("Confirm Close")); @@ -1103,20 +1087,20 @@ void SessionController::selectLine() { view()->selectCurrentLine(); } -static const KXmlGuiWindow* findWindow(const QObject* object) +static const KXmlGuiWindow *findWindow(const QObject *object) { // Walk up the QObject hierarchy to find a KXmlGuiWindow. while (object != nullptr) { - const auto* window = qobject_cast(object); + const auto *window = qobject_cast(object); if (window != nullptr) { - return(window); + return (window); } object = object->parent(); } - return(nullptr); + return (nullptr); } -static bool hasTerminalDisplayInSameWindow(const Session* session, const KXmlGuiWindow* window) +static bool hasTerminalDisplayInSameWindow(const Session *session, const KXmlGuiWindow *window) { // Iterate all TerminalDisplays of this Session ... const QList views = session->views(); @@ -1124,13 +1108,13 @@ static bool hasTerminalDisplayInSameWindow(const Session* session, const KXmlGui // ... and check whether a TerminalDisplay has the same // window as given in the parameter if (window == findWindow(terminalDisplay)) { - return(true); + return (true); } } - return(false); + return (false); } -void SessionController::copyInputActionsTriggered(QAction* action) +void SessionController::copyInputActionsTriggered(QAction *action) { const auto mode = action->data().toInt(); @@ -1156,10 +1140,10 @@ void SessionController::copyInputToAllTabs() } // Find our window ... - const KXmlGuiWindow* myWindow = findWindow(view()); + const KXmlGuiWindow *myWindow = findWindow(view()); const QList sessionsList = SessionManager::instance()->sessions(); - QSet group(sessionsList.begin(), sessionsList.end()); + QSet group(sessionsList.begin(), sessionsList.end()); for (auto session : group) { // First, ensure that the session is removed // (necessary to avoid duplicates on addSession()!) @@ -1191,15 +1175,15 @@ void SessionController::copyInputToSelectedTabs() dialog->setModal(true); dialog->setMasterSession(session()); - const QList sessionsList = _copyToGroup->sessions(); - QSet currentGroup(sessionsList.begin(), sessionsList.end()); + const QList sessionsList = _copyToGroup->sessions(); + QSet currentGroup(sessionsList.begin(), sessionsList.end()); currentGroup.remove(session()); dialog->setChosenSessions(currentGroup); connect(dialog, &QDialog::accepted, this, [=]() { - QSet newGroup = dialog->chosenSessions(); + QSet newGroup = dialog->chosenSessions(); newGroup.remove(session()); const QSet completeGroup = newGroup | currentGroup; @@ -1222,13 +1206,13 @@ void SessionController::copyInputToSelectedTabs() void SessionController::copyInputToNone() { - if (_copyToGroup == nullptr) { // No 'Copy To' is active + if (_copyToGroup == nullptr) { // No 'Copy To' is active return; } // Once Qt5.14+ is the mininum, change to use range constructors - const QList groupList = SessionManager::instance()->sessions(); - QSet group(groupList.begin(), groupList.end()); + const QList groupList = SessionManager::instance()->sessions(); + QSet group(groupList.begin(), groupList.end()); for (auto iterator : group) { Session *s = iterator; @@ -1330,9 +1314,7 @@ void SessionController::listenForScreenWindowUpdates() connect(view()->screenWindow(), &Konsole::ScreenWindow::outputChanged, this, &Konsole::SessionController::updateSearchFilter); connect(view()->screenWindow(), &Konsole::ScreenWindow::scrolled, this, &Konsole::SessionController::updateSearchFilter); - connect(view()->screenWindow(), - &Konsole::ScreenWindow::currentResultLineChanged, view(), - QOverload<>::of(&Konsole::TerminalDisplay::update)); + connect(view()->screenWindow(), &Konsole::ScreenWindow::currentResultLineChanged, view(), QOverload<>::of(&Konsole::TerminalDisplay::update)); _listenForScreenWindowUpdates = true; } @@ -1375,19 +1357,15 @@ void SessionController::enableSearchBar(bool showSearchBar) connect(_searchBar, &Konsole::IncrementalSearchBar::searchReturnPressed, this, &Konsole::SessionController::findPreviousInHistory); connect(_searchBar, &Konsole::IncrementalSearchBar::searchShiftPlusReturnPressed, this, &Konsole::SessionController::findNextInHistory); } else { - disconnect(_searchBar, &Konsole::IncrementalSearchBar::searchChanged, this, - &Konsole::SessionController::searchTextChanged); - disconnect(_searchBar, &Konsole::IncrementalSearchBar::searchReturnPressed, this, - &Konsole::SessionController::findPreviousInHistory); - disconnect(_searchBar, &Konsole::IncrementalSearchBar::searchShiftPlusReturnPressed, this, - &Konsole::SessionController::findNextInHistory); + disconnect(_searchBar, &Konsole::IncrementalSearchBar::searchChanged, this, &Konsole::SessionController::searchTextChanged); + disconnect(_searchBar, &Konsole::IncrementalSearchBar::searchReturnPressed, this, &Konsole::SessionController::findPreviousInHistory); + disconnect(_searchBar, &Konsole::IncrementalSearchBar::searchShiftPlusReturnPressed, this, &Konsole::SessionController::findNextInHistory); if ((!view().isNull()) && (view()->screenWindow() != nullptr)) { view()->screenWindow()->setCurrentResultLine(-1); } } } - bool SessionController::reverseSearchChecked() const { Q_ASSERT(_searchBar); @@ -1449,7 +1427,7 @@ void SessionController::setFindNextPrevEnabled(bool enabled) _findNextAction->setEnabled(enabled); _findPreviousAction->setEnabled(enabled); } -void SessionController::searchTextChanged(const QString& text) +void SessionController::searchTextChanged(const QString &text) { Q_ASSERT(view()->screenWindow()); @@ -1466,7 +1444,7 @@ void SessionController::searchTextChanged(const QString& text) // update search. this is called even when the text is // empty to clear the view's filters - beginSearch(text , reverseSearchChecked() ? Enum::BackwardsSearch : Enum::ForwardsSearch); + beginSearch(text, reverseSearchChecked() ? Enum::BackwardsSearch : Enum::ForwardsSearch); } void SessionController::searchCompleted(bool success) { @@ -1477,7 +1455,7 @@ void SessionController::searchCompleted(bool success) } } -void SessionController::beginSearch(const QString& text, Enum::SearchDirection direction) +void SessionController::beginSearch(const QString &text, Enum::SearchDirection direction) { Q_ASSERT(_searchBar); Q_ASSERT(_searchFilter); @@ -1503,7 +1481,7 @@ void SessionController::beginSearch(const QString& text, Enum::SearchDirection d task->setSearchDirection(direction); task->setAutoDelete(true); task->setStartLine(_searchStartLine); - task->addScreenWindow(session() , view()->screenWindow()); + task->addScreenWindow(session(), view()->screenWindow()); task->execute(); } else if (text.isEmpty()) { searchCompleted(false); @@ -1534,7 +1512,6 @@ void SessionController::searchFrom() setSearchStartTo(0); } - beginSearch(_searchBar->searchText(), reverseSearchChecked() ? Enum::BackwardsSearch : Enum::ForwardsSearch); } void SessionController::findNextInHistory() @@ -1588,7 +1565,7 @@ void SessionController::showHistoryOptions() dialog->show(); } -void SessionController::sessionResizeRequest(const QSize& size) +void SessionController::sessionResizeRequest(const QSize &size) { ////qDebug() << "View resize requested to " << size; view()->setSize(size.width(), size.height()); @@ -1610,7 +1587,7 @@ void SessionController::scrollBackOptionsChanged(int mode, int lines) void SessionController::saveHistory() { - SessionTask* task = new SaveHistoryTask(this); + SessionTask *task = new SaveHistoryTask(this); task->setAutoDelete(true); task->addSession(session()); task->execute(); @@ -1619,7 +1596,7 @@ void SessionController::saveHistory() void SessionController::clearHistory() { session()->clearHistory(); - view()->updateImage(); // To reset view scrollbar + view()->updateImage(); // To reset view scrollbar view()->repaint(); } @@ -1628,7 +1605,7 @@ void SessionController::clearHistoryAndReset() Profile::Ptr profile = SessionManager::instance()->sessionProfile(session()); QByteArray name = profile->defaultEncoding().toUtf8(); - Emulation* emulation = session()->emulation(); + Emulation *emulation = session()->emulation(); emulation->reset(); session()->refresh(); session()->setCodec(QTextCodec::codecForName(name)); @@ -1747,7 +1724,8 @@ void SessionController::sessionAttributeChanged() Q_EMIT rawTitleChanged(); } -void SessionController::sessionReadOnlyChanged() { +void SessionController::sessionReadOnlyChanged() +{ updateReadOnlyActionStates(); // Update all views @@ -1760,7 +1738,7 @@ void SessionController::sessionReadOnlyChanged() { } } -void SessionController::showDisplayContextMenu(const QPoint& position) +void SessionController::showDisplayContextMenu(const QPoint &position) { // needed to make sure the popup menu is available, even if a hosting // application did not merge our GUI. @@ -1775,7 +1753,7 @@ void SessionController::showDisplayContextMenu(const QPoint& position) factory->addClient(this); } - QPointer popup = qobject_cast(factory()->container(QStringLiteral("session-popup-menu"), this)); + QPointer popup = qobject_cast(factory()->container(QStringLiteral("session-popup-menu"), this)); if (!popup.isNull()) { updateReadOnlyActionStates(); @@ -1794,7 +1772,7 @@ void SessionController::showDisplayContextMenu(const QPoint& position) // prepend content-specific actions such as "Open Link", "Copy Email Address" etc QSharedPointer hotSpot = view()->filterActions(position); if (hotSpot != nullptr) { - popup->insertActions(popup->actions().value(0, nullptr), hotSpot->actions() << contentSeparator ); + popup->insertActions(popup->actions().value(0, nullptr), hotSpot->actions() << contentSeparator); popup->addAction(contentSeparator); toRemove = hotSpot->setupMenu(popup.data()); } @@ -1807,8 +1785,8 @@ void SessionController::showDisplayContextMenu(const QPoint& position) _preventClose = true; if (_showMenuAction != nullptr) { - if ( _showMenuAction->isChecked() ) { - popup->removeAction( _showMenuAction); + if (_showMenuAction->isChecked()) { + popup->removeAction(_showMenuAction); } else { popup->insertAction(_switchProfileMenu, _showMenuAction); } @@ -1816,7 +1794,7 @@ void SessionController::showDisplayContextMenu(const QPoint& position) // they are here. // qDebug() << popup->actions().indexOf(contentActions[0]) << popup->actions().indexOf(contentActions[1]) << popup->actions()[3]; - QAction* chosen = popup->exec(QCursor::pos()); + QAction *chosen = popup->exec(QCursor::pos()); // check for validity of the pointer to the popup menu if (!popup.isNull()) { @@ -1837,9 +1815,8 @@ void SessionController::showDisplayContextMenu(const QPoint& position) chosen->trigger(); } } else { - qCDebug(KonsoleDebug) << "Unable to display popup menu for session" - << session()->title(Session::NameRole) - << ", no GUI factory available to build the popup."; + qCDebug(KonsoleDebug) << "Unable to display popup menu for session" << session()->title(Session::NameRole) + << ", no GUI factory available to build the popup."; } } @@ -1862,9 +1839,9 @@ void SessionController::zmodemDownload() } if (!zmodem.isEmpty()) { const QString path = QFileDialog::getExistingDirectory(view(), - i18n("Save ZModem Download to..."), - QDir::homePath(), - QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); + i18n("Save ZModem Download to..."), + QDir::homePath(), + QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); if (!path.isEmpty()) { session()->startZModem(zmodem, path, QStringList()); @@ -1882,8 +1859,7 @@ void SessionController::zmodemDownload() void SessionController::zmodemUpload() { if (session()->isZModemBusy()) { - KMessageBox::sorry(view(), - i18n("

The current session already has a ZModem file transfer in progress.

")); + KMessageBox::sorry(view(), i18n("

The current session already has a ZModem file transfer in progress.

")); return; } @@ -1898,9 +1874,7 @@ void SessionController::zmodemUpload() return; } - QStringList files = QFileDialog::getOpenFileNames(view(), - i18n("Select Files for ZModem Upload"), - QDir::homePath()); + QStringList files = QFileDialog::getOpenFileNames(view(), i18n("Select Files for ZModem Upload"), QDir::homePath()); if (!files.isEmpty()) { session()->startZModem(zmodem, QString(), files); } diff --git a/src/session/SessionController.h b/src/session/SessionController.h index 1a2af959f..a1e9634c1 100644 --- a/src/session/SessionController.h +++ b/src/session/SessionController.h @@ -9,10 +9,10 @@ #define SESSIONCONTROLLER_H // Qt -#include #include -#include #include +#include +#include // KDE #include @@ -20,10 +20,10 @@ #include // Konsole -#include "SessionDisplayConnection.h" -#include "ViewProperties.h" #include "Enumeration.h" #include "Session.h" +#include "SessionDisplayConnection.h" +#include "ViewProperties.h" class QAction; class QTextCodec; @@ -35,7 +35,8 @@ class KCodecAction; class QAction; class KActionMenu; -namespace Konsole { +namespace Konsole +{ class EditProfileDialog; class EscapeSequenceUrlFilter; class FileFilter; @@ -76,7 +77,7 @@ public: CopyInputToSelectedTabsMode = 1, /** Do not copy keyboard input to other tabs */ - CopyInputToNoneMode = 2 + CopyInputToNoneMode = 2, }; /** @@ -263,7 +264,8 @@ private Q_SLOTS: void searchTextChanged(const QString &text); void searchCompleted(bool success); - void updateFilterList(const QExplicitlySharedDataPointer &profile); // Called when the profile has changed, so we might need to change the list of filters + void updateFilterList( + const QExplicitlySharedDataPointer &profile); // Called when the profile has changed, so we might need to change the list of filters void viewFocusChangeHandler(bool focused); void interactionHandler(); @@ -274,7 +276,7 @@ private Q_SLOTS: void highlightMatches(bool highlight); void scrollBackOptionsChanged(int mode, int lines); void sessionResizeRequest(const QSize &size); - void trackOutput(QKeyEvent *event); // move view to end of current output + void trackOutput(QKeyEvent *event); // move view to end of current output // when a key press occurs in the // display area @@ -363,4 +365,4 @@ private: } -#endif //SESSIONCONTROLLER_H +#endif // SESSIONCONTROLLER_H diff --git a/src/session/SessionDisplayConnection.cpp b/src/session/SessionDisplayConnection.cpp index 3ca2d21db..f9d2d1691 100644 --- a/src/session/SessionDisplayConnection.cpp +++ b/src/session/SessionDisplayConnection.cpp @@ -13,7 +13,6 @@ namespace Konsole { - SessionDisplayConnection::SessionDisplayConnection(Session *session, TerminalDisplay *view, QObject *parent) : QObject(parent) { @@ -36,4 +35,4 @@ bool SessionDisplayConnection::isValid() const return !_session.isNull() && !_view.isNull(); } -} // namespace Konsole +} // namespace Konsole diff --git a/src/session/SessionDisplayConnection.h b/src/session/SessionDisplayConnection.h index 5415b9c40..fdbed4b3e 100644 --- a/src/session/SessionDisplayConnection.h +++ b/src/session/SessionDisplayConnection.h @@ -15,7 +15,6 @@ namespace Konsole { - class Session; class TerminalDisplay; diff --git a/src/session/SessionGroup.cpp b/src/session/SessionGroup.cpp index 0eb91c4ed..68c528649 100644 --- a/src/session/SessionGroup.cpp +++ b/src/session/SessionGroup.cpp @@ -8,31 +8,32 @@ // Konsole // TODO: Own header should be first, but this breaks compiling. -#include "Session.h" #include "SessionGroup.h" #include "Emulation.h" +#include "Session.h" -namespace Konsole { - -SessionGroup::SessionGroup(QObject* parent) - : QObject(parent), _masterMode(0) +namespace Konsole +{ +SessionGroup::SessionGroup(QObject *parent) + : QObject(parent) + , _masterMode(0) { } SessionGroup::~SessionGroup() = default; -QList SessionGroup::sessions() const +QList SessionGroup::sessions() const { return _sessions.keys(); } -void SessionGroup::addSession(Session* session) +void SessionGroup::addSession(Session *session) { connect(session, &Konsole::Session::finished, this, &Konsole::SessionGroup::sessionFinished); _sessions.insert(session, false); } -void SessionGroup::removeSession(Session* session) +void SessionGroup::removeSession(Session *session) { disconnect(session, &Konsole::Session::finished, this, &Konsole::SessionGroup::sessionFinished); setMasterStatus(session, false); @@ -41,7 +42,7 @@ void SessionGroup::removeSession(Session* session) void SessionGroup::sessionFinished() { - auto* session = qobject_cast(sender()); + auto *session = qobject_cast(sender()); Q_ASSERT(session); removeSession(session); } @@ -51,7 +52,7 @@ void SessionGroup::setMasterMode(int mode) _masterMode = mode; } -void SessionGroup::setMasterStatus(Session* session , bool master) +void SessionGroup::setMasterStatus(Session *session, bool master) { const bool wasMaster = _sessions[session]; @@ -64,15 +65,14 @@ void SessionGroup::setMasterStatus(Session* session , bool master) if (master) { connect(session->emulation(), &Konsole::Emulation::sendData, this, &Konsole::SessionGroup::forwardData); } else { - disconnect(session->emulation(), &Konsole::Emulation::sendData, - this, &Konsole::SessionGroup::forwardData); + disconnect(session->emulation(), &Konsole::Emulation::sendData, this, &Konsole::SessionGroup::forwardData); } } -void SessionGroup::forwardData(const QByteArray& data) +void SessionGroup::forwardData(const QByteArray &data) { static bool _inForwardData = false; - if (_inForwardData) { // Avoid recursive calls among session groups! + if (_inForwardData) { // Avoid recursive calls among session groups! // A recursive call happens when a master in group A calls forwardData() // in group B. If one of the destination sessions in group B is also a // master of a group including the master session of group A, this would @@ -81,7 +81,7 @@ void SessionGroup::forwardData(const QByteArray& data) } _inForwardData = true; - const QList sessionsKeys = _sessions.keys(); + const QList sessionsKeys = _sessions.keys(); for (Session *other : sessionsKeys) { if (!_sessions[other]) { other->emulation()->sendString(data); @@ -90,4 +90,4 @@ void SessionGroup::forwardData(const QByteArray& data) _inForwardData = false; } -} // namespace konsole +} // namespace konsole diff --git a/src/session/SessionGroup.h b/src/session/SessionGroup.h index e38e7f777..00e58293b 100644 --- a/src/session/SessionGroup.h +++ b/src/session/SessionGroup.h @@ -10,11 +10,12 @@ #define SESSIONGROUP_H // Qt -#include #include +#include +#include -namespace Konsole { - +namespace Konsole +{ class Session; /** @@ -60,7 +61,7 @@ public: * Any input key presses in the master sessions are sent to all * sessions in the group. */ - CopyInputToAll = 1 + CopyInputToAll = 1, }; /** @@ -81,6 +82,6 @@ private: int _masterMode; }; -} // namespace Konsole +} // namespace Konsole -#endif // SESSIONGROUP_H +#endif // SESSIONGROUP_H diff --git a/src/session/SessionListModel.cpp b/src/session/SessionListModel.cpp index ccd3b0142..6f23bf268 100644 --- a/src/session/SessionListModel.cpp +++ b/src/session/SessionListModel.cpp @@ -20,9 +20,9 @@ using Konsole::Session; using Konsole::SessionListModel; -SessionListModel::SessionListModel(QObject *parent) : - QAbstractListModel(parent), - _sessions(QList()) +SessionListModel::SessionListModel(QObject *parent) + : QAbstractListModel(parent) + , _sessions(QList()) { } @@ -32,8 +32,7 @@ void SessionListModel::setSessions(const QList &sessions) _sessions = sessions; for (Session *session : sessions) { - connect(session, &Konsole::Session::finished, this, - &Konsole::SessionListModel::sessionFinished); + connect(session, &Konsole::Session::finished, this, &Konsole::SessionListModel::sessionFinished); } endResetModel(); @@ -85,7 +84,7 @@ QVariant SessionListModel::headerData(int section, Qt::Orientation orientation, if (orientation == Qt::Vertical) { return QVariant(); - } + } switch (section) { case 0: return i18nc("@item:intable The session index", "Number"); @@ -128,6 +127,6 @@ QModelIndex SessionListModel::index(int row, int column, const QModelIndex &pare { if (hasIndex(row, column, parent)) { return createIndex(row, column, _sessions[row]); - } + } return {}; } diff --git a/src/session/SessionListModel.h b/src/session/SessionListModel.h index eb757c0fb..899657460 100644 --- a/src/session/SessionListModel.h +++ b/src/session/SessionListModel.h @@ -13,7 +13,8 @@ #include #include -namespace Konsole { +namespace Konsole +{ class Session; /** @@ -60,4 +61,4 @@ private: }; } -#endif //SESSIONLISTMODEL_H +#endif // SESSIONLISTMODEL_H diff --git a/src/session/SessionManager.cpp b/src/session/SessionManager.cpp index 6554ebd88..f2665846d 100644 --- a/src/session/SessionManager.cpp +++ b/src/session/SessionManager.cpp @@ -20,17 +20,17 @@ #include // Konsole -#include "ShouldApplyProperty.h" #include "Enumeration.h" -#include "Screen.h" #include "EscapeSequenceUrlExtractor.h" +#include "Screen.h" +#include "ShouldApplyProperty.h" -#include "history/compact/CompactHistoryType.h" #include "history/HistoryTypeFile.h" #include "history/HistoryTypeNone.h" +#include "history/compact/CompactHistoryType.h" -#include "profile/ProfileManager.h" #include "profile/ProfileCommandParser.h" +#include "profile/ProfileManager.h" #include "Session.h" #include "SessionController.h" @@ -40,24 +40,21 @@ using namespace Konsole; -SessionManager::SessionManager() : - _sessions(QList()), - _sessionProfiles(QHash()), - _sessionRuntimeProfiles(QHash()), - _restoreMapping(QHash()), - _isClosingAllSessions(false) +SessionManager::SessionManager() + : _sessions(QList()) + , _sessionProfiles(QHash()) + , _sessionRuntimeProfiles(QHash()) + , _restoreMapping(QHash()) + , _isClosingAllSessions(false) { ProfileManager *profileMananger = ProfileManager::instance(); - connect(profileMananger, &Konsole::ProfileManager::profileChanged, this, - &Konsole::SessionManager::profileChanged); + connect(profileMananger, &Konsole::ProfileManager::profileChanged, this, &Konsole::SessionManager::profileChanged); } SessionManager::~SessionManager() { if (!_sessions.isEmpty()) { - qCDebug(KonsoleDebug) << "Konsole SessionManager destroyed with" - << _sessions.count() - <<"session(s) still alive"; + qCDebug(KonsoleDebug) << "Konsole SessionManager destroyed with" << _sessions.count() << "session(s) still alive"; // ensure that the Session doesn't later try to call back and do things to the // SessionManager for (Session *session : qAsConst(_sessions)) { @@ -67,7 +64,7 @@ SessionManager::~SessionManager() } Q_GLOBAL_STATIC(SessionManager, theSessionManager) -SessionManager* SessionManager::instance() +SessionManager *SessionManager::instance() { return theSessionManager; } @@ -102,21 +99,19 @@ Session *SessionManager::createSession(Profile::Ptr profile) ProfileManager::instance()->addProfile(profile); } - //configuration information found, create a new session based on this + // configuration information found, create a new session based on this auto session = new Session(); Q_ASSERT(session); applyProfile(session, profile, false); - connect(session, &Konsole::Session::profileChangeCommandReceived, this, - &Konsole::SessionManager::sessionProfileCommandReceived); + connect(session, &Konsole::Session::profileChangeCommandReceived, this, &Konsole::SessionManager::sessionProfileCommandReceived); - //ask for notification when session dies - connect(session, &Konsole::Session::finished, this, - [this, session]() { - sessionTerminated(session); - }); + // ask for notification when session dies + connect(session, &Konsole::Session::finished, this, [this, session]() { + sessionTerminated(session); + }); - //add session to active list + // add session to active list _sessions << session; _sessionProfiles.insert(session, profile); @@ -168,8 +163,7 @@ void SessionManager::setSessionProfile(Session *session, Profile::Ptr profile) Q_EMIT sessionUpdated(session); } -void SessionManager::applyProfile(Session *session, const Profile::Ptr &profile, - bool modifiedPropertiesOnly) +void SessionManager::applyProfile(Session *session, const Profile::Ptr &profile, bool modifiedPropertiesOnly) { Q_ASSERT(profile); _sessionProfiles[session] = profile; @@ -205,7 +199,7 @@ void SessionManager::applyProfile(Session *session, const Profile::Ptr &profile, // 18.08.0 -> 180800 QStringList list = QStringLiteral(KONSOLE_VERSION).split(QLatin1Char('.')); if (list[2].length() < 2) { - list[2].prepend(QLatin1String("0")); + list[2].prepend(QLatin1String("0")); } const QString &numericVersion = list.join(QString()); @@ -216,8 +210,7 @@ void SessionManager::applyProfile(Session *session, const Profile::Ptr &profile, session->setEnvironment(environment); } - if (apply.shouldApply(Profile::TerminalColumns) - || apply.shouldApply(Profile::TerminalRows)) { + if (apply.shouldApply(Profile::TerminalColumns) || apply.shouldApply(Profile::TerminalRows)) { const auto highlightScrolledLines = profile->property(Profile::HighlightScrolledLines); const auto rows = profile->property(Profile::TerminalRows); auto columns = profile->property(Profile::TerminalColumns); @@ -240,12 +233,10 @@ void SessionManager::applyProfile(Session *session, const Profile::Ptr &profile, // Preserve tab title changes, made by the user, when applying profile // changes or previewing color schemes if (apply.shouldApply(Profile::LocalTabTitleFormat) && !session->isTabTitleSetByUser()) { - session->setTabTitleFormat(Session::LocalTabTitle, - profile->localTabTitleFormat()); + session->setTabTitleFormat(Session::LocalTabTitle, profile->localTabTitleFormat()); } if (apply.shouldApply(Profile::RemoteTabTitleFormat) && !session->isTabTitleSetByUser()) { - session->setTabTitleFormat(Session::RemoteTabTitle, - profile->remoteTabTitleFormat()); + session->setTabTitleFormat(Session::RemoteTabTitle, profile->remoteTabTitleFormat()); } if (apply.shouldApply(Profile::TabColor) && !session->isTabColorSetByUser()) { session->setColor(profile->tabColor()); @@ -259,8 +250,7 @@ void SessionManager::applyProfile(Session *session, const Profile::Ptr &profile, session->setHistoryType(HistoryTypeNone()); break; - case Enum::FixedSizeHistory: - { + case Enum::FixedSizeHistory: { int lines = profile->historySize(); session->setHistoryType(CompactHistoryType(lines)); break; @@ -351,8 +341,7 @@ void SessionManager::saveSessions(KConfig *config) QString name = QLatin1String("Session") + QString::number(n); KConfigGroup group(config, name); - group.writePathEntry("Profile", - _sessionProfiles.value(session)->path()); + group.writePathEntry("Profile", _sessionProfiles.value(session)->path()); session->saveSession(group); _restoreMapping.insert(session, n); n++; diff --git a/src/session/SessionManager.h b/src/session/SessionManager.h index 52f21a13d..793fa6663 100644 --- a/src/session/SessionManager.h +++ b/src/session/SessionManager.h @@ -10,9 +10,9 @@ #define SESSIONMANAGER_H // Qt +#include #include #include -#include // TODO: Move the Property away from Profile.h #include "profile/Profile.h" @@ -21,7 +21,8 @@ class KConfig; -namespace Konsole { +namespace Konsole +{ class Session; class Profile; @@ -67,7 +68,7 @@ public: Session *createSession(QExplicitlySharedDataPointer profile = QExplicitlySharedDataPointer()); /** Sets the profile associated with a session. */ - void setSessionProfile(Session *session,QExplicitlySharedDataPointer profile); + void setSessionProfile(Session *session, QExplicitlySharedDataPointer profile); /** Returns the profile associated with a session. */ QExplicitlySharedDataPointer sessionProfile(Session *session) const; @@ -80,7 +81,7 @@ public: // System session management void saveSessions(KConfig *config); void restoreSessions(KConfig *config); - int getRestoreId(Session *session); + int getRestoreId(Session *session); Session *idToSession(int id); bool isClosingAllSessions() const; @@ -129,4 +130,4 @@ private: } -#endif //SESSIONMANAGER_H +#endif // SESSIONMANAGER_H diff --git a/src/session/SessionTask.cpp b/src/session/SessionTask.cpp index c76b0086b..ad1c97d15 100644 --- a/src/session/SessionTask.cpp +++ b/src/session/SessionTask.cpp @@ -9,10 +9,9 @@ namespace Konsole { - -SessionTask::SessionTask(QObject* parent) - : QObject(parent) - , _autoDelete(false) +SessionTask::SessionTask(QObject *parent) + : QObject(parent) + , _autoDelete(false) { } @@ -26,7 +25,7 @@ bool SessionTask::autoDelete() const return _autoDelete; } -void SessionTask::addSession(Session* session) +void SessionTask::addSession(Session *session) { _sessions.append(session); } diff --git a/src/session/SessionTask.h b/src/session/SessionTask.h index b09b27876..a34bab255 100644 --- a/src/session/SessionTask.h +++ b/src/session/SessionTask.h @@ -8,14 +8,14 @@ #ifndef SESSIONTASK_H #define SESSIONTASK_H -#include #include +#include #include #include "Session.h" -namespace Konsole { - +namespace Konsole +{ /** * Abstract class representing a task which can be performed on a group of sessions. * @@ -63,11 +63,11 @@ Q_SIGNALS: protected: /** Returns a list of sessions in the group */ - QList< QPointer > sessions() const; + QList> sessions() const; private: bool _autoDelete; - QList< QPointer > _sessions; + QList> _sessions; }; } diff --git a/src/settings/ConfigDialogButtonGroupManager.cpp b/src/settings/ConfigDialogButtonGroupManager.cpp index 0967defa1..8309965b9 100644 --- a/src/settings/ConfigDialogButtonGroupManager.cpp +++ b/src/settings/ConfigDialogButtonGroupManager.cpp @@ -13,30 +13,28 @@ #include "ConfigDialogButtonGroupManager.h" // Qt -#include -#include -#include #include +#include +#include +#include using namespace Konsole; -//const QString ConfigDialogButtonGroupManager::ManagedNamePrefix; +// const QString ConfigDialogButtonGroupManager::ManagedNamePrefix; const QString ConfigDialogButtonGroupManager::ManagedNamePrefix = QStringLiteral("kcfg_"); - ConfigDialogButtonGroupManager::ConfigDialogButtonGroupManager(QObject *parent, KCoreConfigSkeleton *config) : QObject(parent) , _config(config) { Q_ASSERT(config); - connect(_config, &KCoreConfigSkeleton::configChanged, - this, &ConfigDialogButtonGroupManager::updateWidgets); + connect(_config, &KCoreConfigSkeleton::configChanged, this, &ConfigDialogButtonGroupManager::updateWidgets); } void ConfigDialogButtonGroupManager::addChildren(const QObject *parentObj) { const auto allButtonGroups = parentObj->findChildren(); - for (const auto *buttonGroup: allButtonGroups) { + for (const auto *buttonGroup : allButtonGroups) { if (buttonGroup->objectName().startsWith(ManagedNamePrefix)) { add(buttonGroup); } @@ -46,14 +44,17 @@ void ConfigDialogButtonGroupManager::addChildren(const QObject *parentObj) void ConfigDialogButtonGroupManager::add(const QButtonGroup *obj) { Q_ASSERT(obj->exclusive()); - connect(obj, QOverload::of(&QButtonGroup::buttonToggled), - this, &ConfigDialogButtonGroupManager::setButtonState, Qt::UniqueConnection); + connect(obj, + QOverload::of(&QButtonGroup::buttonToggled), + this, + &ConfigDialogButtonGroupManager::setButtonState, + Qt::UniqueConnection); _groups.append(obj); } bool ConfigDialogButtonGroupManager::hasChanged() const { - for(const QButtonGroup *group: qAsConst(_groups)) { + for (const QButtonGroup *group : qAsConst(_groups)) { if (group->checkedButton() == nullptr) { continue; } @@ -80,29 +81,29 @@ void ConfigDialogButtonGroupManager::updateWidgets() bool prevSignalsBlocked = signalsBlocked(); bool changed = false; blockSignals(true); - for(const QButtonGroup *group: qAsConst(_groups)) { + for (const QButtonGroup *group : qAsConst(_groups)) { auto *enumItem = groupToConfigItemEnum(group); - if(enumItem == nullptr) { + if (enumItem == nullptr) { continue; } int value = enumItem->value(); const QString &valueName = enumItem->choices().at(value).name; QAbstractButton *currentButton = nullptr; - for(auto &button: group->buttons()) { - if(button->objectName() == valueName) { + for (auto &button : group->buttons()) { + if (button->objectName() == valueName) { currentButton = button; break; } } - if(currentButton == nullptr) { + if (currentButton == nullptr) { return; } currentButton->setChecked(true); changed = true; } blockSignals(prevSignalsBlocked); - if(changed) { + if (changed) { QTimer::singleShot(0, this, &ConfigDialogButtonGroupManager::widgetModified); } } @@ -117,17 +118,17 @@ void ConfigDialogButtonGroupManager::updateWidgetsDefault() void ConfigDialogButtonGroupManager::updateSettings() { bool updateConfig = false; - for(const QButtonGroup *group: qAsConst(_groups)) { + for (const QButtonGroup *group : qAsConst(_groups)) { auto *enumItem = groupToConfigItemEnum(group); if (enumItem == nullptr) { continue; } const auto *currentButton = group->checkedButton(); - if(currentButton == nullptr) { + if (currentButton == nullptr) { continue; } const int value = buttonToEnumValue(currentButton); - if(value < 0) { + if (value < 0) { continue; } @@ -136,7 +137,7 @@ void ConfigDialogButtonGroupManager::updateSettings() updateConfig = true; } } - if(updateConfig) { + if (updateConfig) { _config->save(); Q_EMIT settingsChanged(); } @@ -145,12 +146,12 @@ void ConfigDialogButtonGroupManager::updateSettings() void ConfigDialogButtonGroupManager::setButtonState(QAbstractButton *button, bool checked) { Q_ASSERT(button->group()); - if(!checked) { + if (!checked) { // Both deselected and selected buttons trigger this slot, ignore the deselected one return; } auto *enumItem = groupToConfigItemEnum(button->group()); - if(enumItem == nullptr) { + if (enumItem == nullptr) { return; } @@ -163,7 +164,7 @@ void ConfigDialogButtonGroupManager::setButtonState(QAbstractButton *button, boo } // Returns configuration item associated with the group -KCoreConfigSkeleton::ItemEnum * ConfigDialogButtonGroupManager::groupToConfigItemEnum(const QButtonGroup *group) const +KCoreConfigSkeleton::ItemEnum *ConfigDialogButtonGroupManager::groupToConfigItemEnum(const QButtonGroup *group) const { Q_ASSERT(group); const QString key = group->objectName().mid(ManagedNamePrefix.length()); @@ -197,7 +198,7 @@ int ConfigDialogButtonGroupManager::buttonToEnumValue(const QAbstractButton *but const QString buttonName = button->objectName(); int value = -1; for (int i = 0; i < choices.size(); ++i) { - if(buttonName == choices.at(i).name) { + if (buttonName == choices.at(i).name) { value = i; break; } diff --git a/src/settings/ConfigDialogButtonGroupManager.h b/src/settings/ConfigDialogButtonGroupManager.h index 13a5a92c1..88452d46c 100644 --- a/src/settings/ConfigDialogButtonGroupManager.h +++ b/src/settings/ConfigDialogButtonGroupManager.h @@ -21,52 +21,54 @@ class QString; class QButtonGroup; class QAbstractButton; -template class QList; -template class QMap; +template +class QList; +template +class QMap; namespace Konsole { - // KConfigDialogManager-like class for managing QButtonGroups, - // which are not supported by KConfigDialogManager yet. When - // support will be available in minimum KF5 used by Konsole, - // just remove this class and all expressions which refer to it. - class ConfigDialogButtonGroupManager : public QObject - { - Q_OBJECT +// KConfigDialogManager-like class for managing QButtonGroups, +// which are not supported by KConfigDialogManager yet. When +// support will be available in minimum KF5 used by Konsole, +// just remove this class and all expressions which refer to it. +class ConfigDialogButtonGroupManager : public QObject +{ + Q_OBJECT - public: - ConfigDialogButtonGroupManager(QObject *parent, KCoreConfigSkeleton *config); +public: + ConfigDialogButtonGroupManager(QObject *parent, KCoreConfigSkeleton *config); - void addChildren(const QObject *parentObj); - void add(const QButtonGroup *obj); - bool hasChanged() const; - bool isDefault() const; + void addChildren(const QObject *parentObj); + void add(const QButtonGroup *obj); + bool hasChanged() const; + bool isDefault() const; - Q_SIGNALS: - void settingsChanged(); - void widgetModified(); +Q_SIGNALS: + void settingsChanged(); + void widgetModified(); - public Q_SLOTS: - void updateWidgets(); - void updateWidgetsDefault(); - void updateSettings(); +public Q_SLOTS: + void updateWidgets(); + void updateWidgetsDefault(); + void updateSettings(); - protected Q_SLOTS: - void setButtonState(QAbstractButton *button, bool checked); +protected Q_SLOTS: + void setButtonState(QAbstractButton *button, bool checked); - private: - // Returns configuration item associated with the group - KCoreConfigSkeleton::ItemEnum * groupToConfigItemEnum(const QButtonGroup *group) const; +private: + // Returns configuration item associated with the group + KCoreConfigSkeleton::ItemEnum *groupToConfigItemEnum(const QButtonGroup *group) const; - // Returns a value the button represents in its group - int buttonToEnumValue(const QAbstractButton *button) const; + // Returns a value the button represents in its group + int buttonToEnumValue(const QAbstractButton *button) const; - static const QString ManagedNamePrefix; + static const QString ManagedNamePrefix; - mutable QMap _buttonValues; - KCoreConfigSkeleton *_config = nullptr; - QList _groups; - }; + mutable QMap _buttonValues; + KCoreConfigSkeleton *_config = nullptr; + QList _groups; +}; } #endif diff --git a/src/settings/ConfigurationDialog.cpp b/src/settings/ConfigurationDialog.cpp index d5a8e8b36..7f8e8c600 100644 --- a/src/settings/ConfigurationDialog.cpp +++ b/src/settings/ConfigurationDialog.cpp @@ -16,13 +16,12 @@ #include "ConfigDialogButtonGroupManager.h" // Qt -#include #include +#include // KDE -#include #include - +#include using namespace Konsole; @@ -33,42 +32,32 @@ ConfigurationDialog::ConfigurationDialog(QWidget *parent, KCoreConfigSkeleton *c // Setting this after modifying buttonBox results in initial focus set to buttonBox. setFaceType(KPageDialog::List); - buttonBox()->setStandardButtons(QDialogButtonBox::RestoreDefaults - | QDialogButtonBox::Ok - | QDialogButtonBox::Apply - | QDialogButtonBox::Cancel); - connect(buttonBox()->button(QDialogButtonBox::Apply), &QAbstractButton::clicked, - this, &ConfigurationDialog::updateButtons); - connect(buttonBox()->button(QDialogButtonBox::RestoreDefaults), &QAbstractButton::clicked, - this, &ConfigurationDialog::updateButtons); + buttonBox()->setStandardButtons(QDialogButtonBox::RestoreDefaults | QDialogButtonBox::Ok | QDialogButtonBox::Apply | QDialogButtonBox::Cancel); + connect(buttonBox()->button(QDialogButtonBox::Apply), &QAbstractButton::clicked, this, &ConfigurationDialog::updateButtons); + connect(buttonBox()->button(QDialogButtonBox::RestoreDefaults), &QAbstractButton::clicked, this, &ConfigurationDialog::updateButtons); _manager = new KConfigDialogManager(this, config); connect(_manager, QOverload<>::of(&KConfigDialogManager::settingsChanged), this, &ConfigurationDialog::settingsChangedSlot); - connect(_manager, &KConfigDialogManager::widgetModified, this, &ConfigurationDialog::updateButtons); + connect(_manager, &KConfigDialogManager::widgetModified, this, &ConfigurationDialog::updateButtons); - connect(buttonBox()->button(QDialogButtonBox::Ok), &QAbstractButton::clicked, - _manager, &KConfigDialogManager::updateSettings); - connect(buttonBox()->button(QDialogButtonBox::Apply), &QAbstractButton::clicked, - _manager, &KConfigDialogManager::updateSettings); - connect(buttonBox()->button(QDialogButtonBox::Cancel), &QAbstractButton::clicked, - _manager, &KConfigDialogManager::updateWidgets); - connect(buttonBox()->button(QDialogButtonBox::RestoreDefaults), &QAbstractButton::clicked, - _manager, &KConfigDialogManager::updateWidgetsDefault); + connect(buttonBox()->button(QDialogButtonBox::Ok), &QAbstractButton::clicked, _manager, &KConfigDialogManager::updateSettings); + connect(buttonBox()->button(QDialogButtonBox::Apply), &QAbstractButton::clicked, _manager, &KConfigDialogManager::updateSettings); + connect(buttonBox()->button(QDialogButtonBox::Cancel), &QAbstractButton::clicked, _manager, &KConfigDialogManager::updateWidgets); + connect(buttonBox()->button(QDialogButtonBox::RestoreDefaults), &QAbstractButton::clicked, _manager, &KConfigDialogManager::updateWidgetsDefault); _groupManager = new ConfigDialogButtonGroupManager(this, config); connect(_groupManager, &ConfigDialogButtonGroupManager::settingsChanged, this, &ConfigurationDialog::settingsChangedSlot); - connect(_groupManager, &ConfigDialogButtonGroupManager::widgetModified, this, &ConfigurationDialog::updateButtons); + connect(_groupManager, &ConfigDialogButtonGroupManager::widgetModified, this, &ConfigurationDialog::updateButtons); - connect(buttonBox()->button(QDialogButtonBox::Ok), &QAbstractButton::clicked, - _groupManager, &ConfigDialogButtonGroupManager::updateSettings); - connect(buttonBox()->button(QDialogButtonBox::Apply), &QAbstractButton::clicked, - _groupManager, &ConfigDialogButtonGroupManager::updateSettings); - connect(buttonBox()->button(QDialogButtonBox::Cancel), &QAbstractButton::clicked, - _groupManager, &ConfigDialogButtonGroupManager::updateWidgets); - connect(buttonBox()->button(QDialogButtonBox::RestoreDefaults), &QAbstractButton::clicked, - _groupManager, &ConfigDialogButtonGroupManager::updateWidgetsDefault); + connect(buttonBox()->button(QDialogButtonBox::Ok), &QAbstractButton::clicked, _groupManager, &ConfigDialogButtonGroupManager::updateSettings); + connect(buttonBox()->button(QDialogButtonBox::Apply), &QAbstractButton::clicked, _groupManager, &ConfigDialogButtonGroupManager::updateSettings); + connect(buttonBox()->button(QDialogButtonBox::Cancel), &QAbstractButton::clicked, _groupManager, &ConfigDialogButtonGroupManager::updateWidgets); + connect(buttonBox()->button(QDialogButtonBox::RestoreDefaults), + &QAbstractButton::clicked, + _groupManager, + &ConfigDialogButtonGroupManager::updateWidgetsDefault); setApplyButtonEnabled(false); } diff --git a/src/settings/ConfigurationDialog.h b/src/settings/ConfigurationDialog.h index 7245962b9..a0de101de 100644 --- a/src/settings/ConfigurationDialog.h +++ b/src/settings/ConfigurationDialog.h @@ -13,14 +13,14 @@ #define CONFIGURATIONDIALOG_H // Qt -#include #include -#include +#include #include +#include // KDE -#include #include +#include // Konsole #include "konsoleprivate_export.h" @@ -28,15 +28,15 @@ class QWidget; class KConfigDialogManager; -namespace Konsole { - +namespace Konsole +{ class ConfigDialogButtonGroupManager; // KConfigDialog-like class, as the original KConfigDialog wraps // all pages in QScrollArea. KConfigDialog, when fixed, should // be source compatible with this class, so simple class replace // should suffice. -class KONSOLEPRIVATE_EXPORT ConfigurationDialog: public KPageDialog +class KONSOLEPRIVATE_EXPORT ConfigurationDialog : public KPageDialog { Q_OBJECT diff --git a/src/settings/GeneralSettings.cpp b/src/settings/GeneralSettings.cpp index c36a65aec..6da27d383 100644 --- a/src/settings/GeneralSettings.cpp +++ b/src/settings/GeneralSettings.cpp @@ -11,7 +11,8 @@ using namespace Konsole; -GeneralSettings::GeneralSettings(QWidget* aParent) : QWidget(aParent) +GeneralSettings::GeneralSettings(QWidget *aParent) + : QWidget(aParent) { setupUi(this); @@ -26,4 +27,3 @@ void GeneralSettings::slotEnableAllMessages() { KMessageBox::enableAllMessages(); } - diff --git a/src/settings/GeneralSettings.h b/src/settings/GeneralSettings.h index f85304081..b128220c5 100644 --- a/src/settings/GeneralSettings.h +++ b/src/settings/GeneralSettings.h @@ -9,7 +9,8 @@ #include "ui_GeneralSettings.h" -namespace Konsole { +namespace Konsole +{ class GeneralSettings : public QWidget, private Ui::GeneralSettings { Q_OBJECT diff --git a/src/settings/PartInfo.cpp b/src/settings/PartInfo.cpp index c7ac2601d..e180f081f 100644 --- a/src/settings/PartInfo.cpp +++ b/src/settings/PartInfo.cpp @@ -9,10 +9,10 @@ using namespace Konsole; -PartInfoSettings::PartInfoSettings(QWidget* parent) : QWidget(parent) +PartInfoSettings::PartInfoSettings(QWidget *parent) + : QWidget(parent) { setupUi(this); } PartInfoSettings::~PartInfoSettings() = default; - diff --git a/src/settings/PartInfo.h b/src/settings/PartInfo.h index 757a13a34..840886a97 100644 --- a/src/settings/PartInfo.h +++ b/src/settings/PartInfo.h @@ -9,7 +9,8 @@ #include "ui_PartInfo.h" -namespace Konsole { +namespace Konsole +{ class PartInfoSettings : public QWidget, private Ui::PartInfoSettings { Q_OBJECT diff --git a/src/settings/ProfileSettings.cpp b/src/settings/ProfileSettings.cpp index 1cac2fdcc..4af2e3191 100644 --- a/src/settings/ProfileSettings.cpp +++ b/src/settings/ProfileSettings.cpp @@ -9,23 +9,23 @@ // Qt #include -#include -#include #include +#include +#include // Konsole +#include "delegates/ProfileShortcutDelegate.h" #include "profile/ProfileManager.h" #include "profile/ProfileModel.h" #include "session/Session.h" -#include "widgets/EditProfileDialog.h" -#include "terminalDisplay/TerminalDisplay.h" -#include "session/SessionManager.h" #include "session/SessionController.h" -#include "delegates/ProfileShortcutDelegate.h" +#include "session/SessionManager.h" +#include "terminalDisplay/TerminalDisplay.h" +#include "widgets/EditProfileDialog.h" using namespace Konsole; -ProfileSettings::ProfileSettings(QWidget* parent) +ProfileSettings::ProfileSettings(QWidget *parent) : QWidget(parent) { setupUi(this); @@ -173,17 +173,13 @@ void ProfileSettings::editSelected() Profile::Ptr ProfileSettings::currentProfile() const { - QItemSelectionModel* selection = profilesList->selectionModel(); + QItemSelectionModel *selection = profilesList->selectionModel(); if ((selection == nullptr) || !selection->hasSelection()) { return Profile::Ptr(); } - return selection - ->selectedIndexes() - .at(ProfileModel::PROFILE) - .data(ProfileModel::ProfilePtrRole) - .value(); + return selection->selectedIndexes().at(ProfileModel::PROFILE).data(ProfileModel::ProfilePtrRole).value(); } bool ProfileSettings::isProfileDeletable(Profile::Ptr profile) const @@ -193,14 +189,12 @@ bool ProfileSettings::isProfileDeletable(Profile::Ptr profile) const } const QFileInfo fileInfo(profile->path()); - return fileInfo.exists() - && QFileInfo(fileInfo.path()).isWritable(); // To delete a file, parent dir must be writable + return fileInfo.exists() && QFileInfo(fileInfo.path()).isWritable(); // To delete a file, parent dir must be writable } bool ProfileSettings::isProfileWritable(Profile::Ptr profile) const { - return profile - && !profile->isFallback() // Default/fallback profile is hardcoded + return profile && !profile->isFallback() // Default/fallback profile is hardcoded && QFileInfo(profile->path()).isWritable(); } diff --git a/src/settings/ProfileSettings.h b/src/settings/ProfileSettings.h index 8ff683857..0ecf2ef7e 100644 --- a/src/settings/ProfileSettings.h +++ b/src/settings/ProfileSettings.h @@ -8,10 +8,10 @@ #define PROFILESETTINGS_H // Qt -#include -#include -#include #include +#include +#include +#include // KDE @@ -23,7 +23,8 @@ class QItemSelection; class QStandardItem; class QStandardItemModel; -namespace Konsole { +namespace Konsole +{ class Profile; /** @@ -54,7 +55,6 @@ public: void setShortcutEditorVisible(bool visible); protected: - private Q_SLOTS: void slotAccepted(); void deleteSelected(); diff --git a/src/settings/TabBarSettings.cpp b/src/settings/TabBarSettings.cpp index dd1ccce8a..81dbbd102 100644 --- a/src/settings/TabBarSettings.cpp +++ b/src/settings/TabBarSettings.cpp @@ -9,7 +9,8 @@ using namespace Konsole; -TabBarSettings::TabBarSettings(QWidget* parent) : QWidget(parent) +TabBarSettings::TabBarSettings(QWidget *parent) + : QWidget(parent) { setupUi(this); @@ -20,14 +21,10 @@ TabBarSettings::TabBarSettings(QWidget* parent) : QWidget(parent) // Enable CSS file selector only when tabbar is visible and custom css is active const auto updateStyleSheetFileEnable = [this](bool) { - kcfg_TabBarUserStyleSheetFile->setEnabled(kcfg_TabBarUseUserStyleSheet->isChecked() - && !AlwaysHideTabBar->isChecked()); + kcfg_TabBarUserStyleSheetFile->setEnabled(kcfg_TabBarUseUserStyleSheet->isChecked() && !AlwaysHideTabBar->isChecked()); }; - connect(kcfg_TabBarUseUserStyleSheet, &QAbstractButton::toggled, - this, updateStyleSheetFileEnable); - connect(AlwaysHideTabBar, &QAbstractButton::toggled, - this, updateStyleSheetFileEnable); + connect(kcfg_TabBarUseUserStyleSheet, &QAbstractButton::toggled, this, updateStyleSheetFileEnable); + connect(AlwaysHideTabBar, &QAbstractButton::toggled, this, updateStyleSheetFileEnable); } TabBarSettings::~TabBarSettings() = default; - diff --git a/src/settings/TabBarSettings.h b/src/settings/TabBarSettings.h index 2f13c4a09..61b8f01e0 100644 --- a/src/settings/TabBarSettings.h +++ b/src/settings/TabBarSettings.h @@ -9,7 +9,8 @@ #include "ui_TabBarSettings.h" -namespace Konsole { +namespace Konsole +{ class TabBarSettings : public QWidget, private Ui::TabBarSettings { Q_OBJECT diff --git a/src/settings/TemporaryFilesSettings.cpp b/src/settings/TemporaryFilesSettings.cpp index fb273fc1f..5a7ca7e29 100644 --- a/src/settings/TemporaryFilesSettings.cpp +++ b/src/settings/TemporaryFilesSettings.cpp @@ -12,9 +12,8 @@ using namespace Konsole; - - -TemporaryFilesSettings::TemporaryFilesSettings(QWidget* aParent) : QWidget(aParent) +TemporaryFilesSettings::TemporaryFilesSettings(QWidget *aParent) + : QWidget(aParent) { setupUi(this); @@ -24,18 +23,16 @@ TemporaryFilesSettings::TemporaryFilesSettings(QWidget* aParent) : QWidget(aPare // Use "~" instead of full path. It looks nice and helps // in cases when home path is really long. const QString homePath = QStandardPaths::writableLocation(QStandardPaths::HomeLocation); - if(cachePath.startsWith(homePath)) { + if (cachePath.startsWith(homePath)) { cachePath.replace(0, homePath.length(), QStringLiteral("~")); } #endif // There's no way of doing this with strings placed in .ui file kcfg_scrollbackUseSystemLocation->setText( - i18nc("@option:radio File location; %1: path to directory placeholder", - "System temporary directory (%1)", tempPath)); + i18nc("@option:radio File location; %1: path to directory placeholder", "System temporary directory (%1)", tempPath)); kcfg_scrollbackUseCacheLocation->setText( - i18nc("@option:radio File location; %1: path to directory placeholder", - "User cache directory (%1)", cachePath)); + i18nc("@option:radio File location; %1: path to directory placeholder", "User cache directory (%1)", cachePath)); kcfg_scrollbackUseSpecifiedLocationDirectory->setMode(KFile::Directory); } diff --git a/src/settings/TemporaryFilesSettings.h b/src/settings/TemporaryFilesSettings.h index 243780e8c..ebb1410dd 100644 --- a/src/settings/TemporaryFilesSettings.h +++ b/src/settings/TemporaryFilesSettings.h @@ -9,7 +9,8 @@ #include "ui_TemporaryFilesSettings.h" -namespace Konsole { +namespace Konsole +{ class TemporaryFilesSettings : public QWidget, private Ui::TemporaryFilesSettings { Q_OBJECT diff --git a/src/settings/ThumbnailsSettings.cpp b/src/settings/ThumbnailsSettings.cpp index b92a2dfa9..ea6822306 100644 --- a/src/settings/ThumbnailsSettings.cpp +++ b/src/settings/ThumbnailsSettings.cpp @@ -9,7 +9,7 @@ using namespace Konsole; ThumbnailsSettings::ThumbnailsSettings(QWidget *aParent) -: QWidget(aParent) + : QWidget(aParent) { setupUi(this); } diff --git a/src/settings/ThumbnailsSettings.h b/src/settings/ThumbnailsSettings.h index e5ef08e52..04ef30509 100644 --- a/src/settings/ThumbnailsSettings.h +++ b/src/settings/ThumbnailsSettings.h @@ -9,7 +9,8 @@ #include "ui_ThumbnailsSettings.h" -namespace Konsole { +namespace Konsole +{ class ThumbnailsSettings : public QWidget, private Ui::ThumbnailsSettings { Q_OBJECT diff --git a/src/terminalDisplay/TerminalBell.cpp b/src/terminalDisplay/TerminalBell.cpp index 2639d54e1..079d10a09 100644 --- a/src/terminalDisplay/TerminalBell.cpp +++ b/src/terminalDisplay/TerminalBell.cpp @@ -16,8 +16,8 @@ using namespace std::literals::chrono_literals; -namespace Konsole { - +namespace Konsole +{ constexpr auto MASK_TIMEOUT = 500ms; TerminalBell::TerminalBell(Enum::BellModeEnum bellMode) @@ -36,8 +36,7 @@ void TerminalBell::bell(const QString &message, bool terminalHasFocus) // Please note that these event names, "BellVisible" and "BellInvisible", // should not change and should be kept stable, because other applications // that use this code via KPart rely on these names for notifications. - KNotification::event(terminalHasFocus ? QStringLiteral("BellVisible") : QStringLiteral("BellInvisible"), - message, QPixmap()); + KNotification::event(terminalHasFocus ? QStringLiteral("BellVisible") : QStringLiteral("BellInvisible"), message, QPixmap()); break; case Enum::VisualBell: Q_EMIT visualBell(); diff --git a/src/terminalDisplay/TerminalBell.h b/src/terminalDisplay/TerminalBell.h index a0274204b..dbe545ad5 100644 --- a/src/terminalDisplay/TerminalBell.h +++ b/src/terminalDisplay/TerminalBell.h @@ -8,15 +8,14 @@ #pragma once - #include #include namespace Konsole { - -class TerminalBell : public QObject { +class TerminalBell : public QObject +{ Q_OBJECT public: diff --git a/src/terminalDisplay/TerminalColor.cpp b/src/terminalDisplay/TerminalColor.cpp index 0f6d09c4e..5c9f312f6 100644 --- a/src/terminalDisplay/TerminalColor.cpp +++ b/src/terminalDisplay/TerminalColor.cpp @@ -13,144 +13,143 @@ #include "colorscheme/ColorScheme.h" // Qt -#include -#include #include +#include +#include namespace Konsole { +TerminalColor::TerminalColor(QObject *parent) + : QObject(parent) + , m_opacity(1.0) + , m_blendColor(qRgba(0, 0, 0, 0xff)) + , m_cursorColor(QColor()) + , m_cursorTextColor(QColor()) +{ + setColorTable(ColorScheme::defaultTable); +} - TerminalColor::TerminalColor(QObject *parent) - : QObject(parent) - , m_opacity(1.0) - , m_blendColor(qRgba(0, 0, 0, 0xff)) - , m_cursorColor(QColor()) - , m_cursorTextColor(QColor()) - { - setColorTable(ColorScheme::defaultTable); - } - - void TerminalColor::applyProfile(const Profile::Ptr &profile, ColorScheme const *colorScheme, uint randomSeed) - { - QColor table[TABLE_COLORS]; - colorScheme->getColorTable(table, randomSeed); - setColorTable(table); - setOpacity(colorScheme->opacity()); +void TerminalColor::applyProfile(const Profile::Ptr &profile, ColorScheme const *colorScheme, uint randomSeed) +{ + QColor table[TABLE_COLORS]; + colorScheme->getColorTable(table, randomSeed); + setColorTable(table); + setOpacity(colorScheme->opacity()); - m_cursorColor = profile->useCustomCursorColor() ? profile->customCursorColor() : QColor(); - m_cursorTextColor = profile->useCustomCursorColor() ? profile->customCursorTextColor() : QColor(); - } - - QColor TerminalColor::backgroundColor() const - { - return m_colorTable[DEFAULT_BACK_COLOR]; - } - - QColor TerminalColor::foregroundColor() const - { - return m_colorTable[DEFAULT_FORE_COLOR]; - } - - void TerminalColor::setColorTable(const QColor *table) - { - std::copy(table, table + TABLE_COLORS, m_colorTable); - setBackgroundColor(m_colorTable[DEFAULT_BACK_COLOR]); + m_cursorColor = profile->useCustomCursorColor() ? profile->customCursorColor() : QColor(); + m_cursorTextColor = profile->useCustomCursorColor() ? profile->customCursorTextColor() : QColor(); +} + +QColor TerminalColor::backgroundColor() const +{ + return m_colorTable[DEFAULT_BACK_COLOR]; +} + +QColor TerminalColor::foregroundColor() const +{ + return m_colorTable[DEFAULT_FORE_COLOR]; +} + +void TerminalColor::setColorTable(const QColor *table) +{ + std::copy(table, table + TABLE_COLORS, m_colorTable); + setBackgroundColor(m_colorTable[DEFAULT_BACK_COLOR]); + onColorsChanged(); +} + +const QColor *TerminalColor::colorTable() const +{ + return m_colorTable; +} + +void TerminalColor::setOpacity(qreal opacity) +{ + QColor color(m_blendColor); + color.setAlphaF(opacity); + m_opacity = opacity; + + m_blendColor = color.rgba(); + onColorsChanged(); +} + +void TerminalColor::visualBell() +{ + swapFGBGColors(); + QTimer::singleShot(200, this, &TerminalColor::swapFGBGColors); +} + +qreal TerminalColor::opacity() const +{ + return m_opacity; +} + +QRgb TerminalColor::blendColor() const +{ + return m_blendColor; +} + +void TerminalColor::setBackgroundColor(const QColor &color) +{ + m_colorTable[DEFAULT_BACK_COLOR] = color; + onColorsChanged(); +} + +void TerminalColor::setForegroundColor(const QColor &color) +{ + m_colorTable[DEFAULT_FORE_COLOR] = color; + onColorsChanged(); +} + +bool TerminalColor::event(QEvent *event) +{ + switch (event->type()) { + case QEvent::PaletteChange: + case QEvent::ApplicationPaletteChange: onColorsChanged(); - } - - const QColor* TerminalColor::colorTable() const - { - return m_colorTable; - } - - void TerminalColor::setOpacity(qreal opacity) - { - QColor color(m_blendColor); - color.setAlphaF(opacity); - m_opacity = opacity; + break; - m_blendColor = color.rgba(); - onColorsChanged(); + default: + break; } - - void TerminalColor::visualBell() - { - swapFGBGColors(); - QTimer::singleShot(200, this, &TerminalColor::swapFGBGColors); - } - - qreal TerminalColor::opacity() const - { - return m_opacity; - } - - QRgb TerminalColor::blendColor() const - { - return m_blendColor; - } - - void TerminalColor::setBackgroundColor(const QColor &color) - { - m_colorTable[DEFAULT_BACK_COLOR] = color; - onColorsChanged(); - } - - void TerminalColor::setForegroundColor(const QColor &color) - { - m_colorTable[DEFAULT_FORE_COLOR] = color; - onColorsChanged(); - } - - bool TerminalColor::event(QEvent *event) - { - switch (event->type()) { - case QEvent::PaletteChange: - case QEvent::ApplicationPaletteChange: - onColorsChanged(); - break; - - default: - break; - } - return QObject::event(event); - } - - void TerminalColor::onColorsChanged() - { - QPalette palette = QApplication::palette(); + return QObject::event(event); +} - QColor buttonTextColor = m_colorTable[DEFAULT_FORE_COLOR]; - QColor backgroundColor = m_colorTable[DEFAULT_BACK_COLOR]; - backgroundColor.setAlphaF(m_opacity); +void TerminalColor::onColorsChanged() +{ + QPalette palette = QApplication::palette(); - QColor buttonColor = backgroundColor.toHsv(); - if (buttonColor.valueF() < 0.5) { - buttonColor = buttonColor.lighter(); - } else { - buttonColor = buttonColor.darker(); - } - palette.setColor(QPalette::Button, buttonColor); - palette.setColor(QPalette::Window, backgroundColor); - palette.setColor(QPalette::Base, backgroundColor); - palette.setColor(QPalette::WindowText, buttonTextColor); - palette.setColor(QPalette::ButtonText, buttonTextColor); + QColor buttonTextColor = m_colorTable[DEFAULT_FORE_COLOR]; + QColor backgroundColor = m_colorTable[DEFAULT_BACK_COLOR]; + backgroundColor.setAlphaF(m_opacity); - QWidget *widget = qobject_cast(parent()); - - widget->setPalette(palette); - - Q_EMIT onPalette(palette); - - widget->update(); + QColor buttonColor = backgroundColor.toHsv(); + if (buttonColor.valueF() < 0.5) { + buttonColor = buttonColor.lighter(); + } else { + buttonColor = buttonColor.darker(); } - - void TerminalColor::swapFGBGColors() - { - QColor color = m_colorTable[DEFAULT_BACK_COLOR]; - m_colorTable[DEFAULT_BACK_COLOR] = m_colorTable[DEFAULT_FORE_COLOR]; - m_colorTable[DEFAULT_FORE_COLOR] = color; + palette.setColor(QPalette::Button, buttonColor); + palette.setColor(QPalette::Window, backgroundColor); + palette.setColor(QPalette::Base, backgroundColor); + palette.setColor(QPalette::WindowText, buttonTextColor); + palette.setColor(QPalette::ButtonText, buttonTextColor); - onColorsChanged(); - } + QWidget *widget = qobject_cast(parent()); + + widget->setPalette(palette); + + Q_EMIT onPalette(palette); + + widget->update(); +} + +void TerminalColor::swapFGBGColors() +{ + QColor color = m_colorTable[DEFAULT_BACK_COLOR]; + m_colorTable[DEFAULT_BACK_COLOR] = m_colorTable[DEFAULT_FORE_COLOR]; + m_colorTable[DEFAULT_FORE_COLOR] = color; + + onColorsChanged(); +} } diff --git a/src/terminalDisplay/TerminalColor.h b/src/terminalDisplay/TerminalColor.h index c2a2159fe..c5e337ced 100644 --- a/src/terminalDisplay/TerminalColor.h +++ b/src/terminalDisplay/TerminalColor.h @@ -10,73 +10,72 @@ #define TERMINALCOLOR_HPP // Qt -#include #include +#include // Konsole -#include "profile/Profile.h" #include "characters/CharacterColor.h" #include "konsoleprivate_export.h" +#include "profile/Profile.h" namespace Konsole { +class Profile; +class ColorScheme; - class Profile; - class ColorScheme; +class KONSOLEPRIVATE_EXPORT TerminalColor : public QObject +{ + Q_OBJECT +public: + explicit TerminalColor(QObject *parent); - class KONSOLEPRIVATE_EXPORT TerminalColor : public QObject + void applyProfile(const Profile::Ptr &profile, ColorScheme const *colorScheme, uint randomSeed); + + QColor backgroundColor() const; + QColor foregroundColor() const; + void setColorTable(const QColor *table); + const QColor *colorTable() const; + + void setOpacity(qreal opacity); + + void visualBell(); + + qreal opacity() const; + QRgb blendColor() const; + + QColor cursorColor() const { - Q_OBJECT - public: - explicit TerminalColor(QObject *parent); + return m_cursorColor; + } - void applyProfile(const Profile::Ptr &profile, ColorScheme const *colorScheme, uint randomSeed); + QColor cursorTextColor() const + { + return m_cursorTextColor; + } - QColor backgroundColor() const; - QColor foregroundColor() const; - void setColorTable(const QColor *table); - const QColor *colorTable() const; +public Q_SLOTS: + void setBackgroundColor(const QColor &color); + void setForegroundColor(const QColor &color); - void setOpacity(qreal opacity); +Q_SIGNALS: + void onPalette(const QPalette &); - void visualBell(); +protected: + bool event(QEvent *event) override; + void onColorsChanged(); - qreal opacity() const; - QRgb blendColor() const; +private Q_SLOTS: + void swapFGBGColors(); - QColor cursorColor() const - { - return m_cursorColor; - } +private: + qreal m_opacity; + QRgb m_blendColor; - QColor cursorTextColor() const - { - return m_cursorTextColor; - } + QColor m_cursorColor; + QColor m_cursorTextColor; - public Q_SLOTS: - void setBackgroundColor(const QColor &color); - void setForegroundColor(const QColor &color); - - Q_SIGNALS: - void onPalette(const QPalette &); - - protected: - bool event(QEvent *event) override; - void onColorsChanged(); - - private Q_SLOTS: - void swapFGBGColors(); - - private: - qreal m_opacity; - QRgb m_blendColor; - - QColor m_cursorColor; - QColor m_cursorTextColor; - - QColor m_colorTable[TABLE_COLORS]; - }; + QColor m_colorTable[TABLE_COLORS]; +}; } #endif diff --git a/src/terminalDisplay/TerminalDisplay.cpp b/src/terminalDisplay/TerminalDisplay.cpp index e4b8f432c..5788921b5 100644 --- a/src/terminalDisplay/TerminalDisplay.cpp +++ b/src/terminalDisplay/TerminalDisplay.cpp @@ -13,76 +13,77 @@ #include "config-konsole.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 // KDE -#include #include #include -#include -#include #include +#include #include +#include #include #include -#include +#include +#include // Konsole -#include "extras/CompositeWidgetFocusWatcher.h" #include "extras/AutoScrollHandler.h" +#include "extras/CompositeWidgetFocusWatcher.h" -#include "filterHotSpots/Filter.h" -#include "filterHotSpots/TerminalImageFilterChain.h" -#include "filterHotSpots/HotSpot.h" -#include "filterHotSpots/FileFilterHotspot.h" #include "filterHotSpots/EscapeSequenceUrlFilter.h" #include "filterHotSpots/EscapeSequenceUrlFilterHotSpot.h" +#include "filterHotSpots/FileFilterHotspot.h" +#include "filterHotSpots/Filter.h" +#include "filterHotSpots/HotSpot.h" +#include "filterHotSpots/TerminalImageFilterChain.h" -#include "konsoledebug.h" -#include "../decoders/PlainTextDecoder.h" -#include "Screen.h" #include "../characters/ExtendedCharTable.h" +#include "../characters/LineBlockCharacters.h" +#include "../decoders/PlainTextDecoder.h" +#include "../widgets/KonsolePrintManager.h" #include "../widgets/TerminalDisplayAccessible.h" +#include "EscapeSequenceUrlExtractor.h" +#include "PrintOptions.h" +#include "Screen.h" +#include "ViewManager.h" // for colorSchemeForProfile. // TODO: Rewrite this. +#include "WindowSystemInfo.h" +#include "konsoledebug.h" +#include "profile/Profile.h" +#include "session/Session.h" #include "session/SessionController.h" #include "session/SessionManager.h" -#include "session/Session.h" -#include "WindowSystemInfo.h" #include "widgets/IncrementalSearchBar.h" -#include "profile/Profile.h" -#include "ViewManager.h" // for colorSchemeForProfile. // TODO: Rewrite this. -#include "../characters/LineBlockCharacters.h" -#include "PrintOptions.h" -#include "../widgets/KonsolePrintManager.h" -#include "EscapeSequenceUrlExtractor.h" -#include "TerminalPainter.h" -#include "TerminalScrollBar.h" #include "TerminalColor.h" #include "TerminalFonts.h" +#include "TerminalPainter.h" +#include "TerminalScrollBar.h" using namespace Konsole; -inline int TerminalDisplay::loc(int x, int y) const { +inline int TerminalDisplay::loc(int x, int y) const +{ if (y < 0 || y > _lines) { qDebug() << "Y: " << y << "Lines" << _lines; } - if (x < 0 || x > _columns ) { + if (x < 0 || x > _columns) { qDebug() << "X" << x << "Columns" << _columns; } @@ -108,18 +109,18 @@ inline int TerminalDisplay::loc(int x, int y) const { IBMPC (rgb) Black Blue Green Cyan Red Magenta Yellow White */ -void TerminalDisplay::setScreenWindow(ScreenWindow* window) +void TerminalDisplay::setScreenWindow(ScreenWindow *window) { // disconnect existing screen window if any if (!_screenWindow.isNull()) { - disconnect(_screenWindow , nullptr , this , nullptr); + disconnect(_screenWindow, nullptr, this, nullptr); } _screenWindow = window; if (!_screenWindow.isNull()) { - connect(_screenWindow.data() , &Konsole::ScreenWindow::outputChanged , this , &Konsole::TerminalDisplay::updateImage); - connect(_screenWindow.data() , &Konsole::ScreenWindow::currentResultLineChanged , this , &Konsole::TerminalDisplay::updateImage); + connect(_screenWindow.data(), &Konsole::ScreenWindow::outputChanged, this, &Konsole::TerminalDisplay::updateImage); + connect(_screenWindow.data(), &Konsole::ScreenWindow::currentResultLineChanged, this, &Konsole::TerminalDisplay::updateImage); connect(_screenWindow.data(), &Konsole::ScreenWindow::outputChanged, this, [this]() { _filterUpdateRequired = true; }); @@ -150,16 +151,15 @@ void TerminalDisplay::setScreenWindow(ScreenWindow* window) namespace Konsole { - #ifndef QT_NO_ACCESSIBILITY /** * This function installs the factory function which lets Qt instantiate the QAccessibleInterface * for the TerminalDisplay. */ -QAccessibleInterface* accessibleInterfaceFactory(const QString &key, QObject *object) +QAccessibleInterface *accessibleInterfaceFactory(const QString &key, QObject *object) { Q_UNUSED(key) - if (auto *display = qobject_cast(object)) { + if (auto *display = qobject_cast(object)) { return new TerminalDisplayAccessible(display); } return nullptr; @@ -174,7 +174,7 @@ QAccessibleInterface* accessibleInterfaceFactory(const QString &key, QObject *ob /* */ /* ------------------------------------------------------------------------- */ -TerminalDisplay::TerminalDisplay(QWidget* parent) +TerminalDisplay::TerminalDisplay(QWidget *parent) : QWidget(parent) , _screenWindow(nullptr) , _verticalLayout(new QVBoxLayout(this)) @@ -258,7 +258,9 @@ TerminalDisplay::TerminalDisplay(QWidget* parent) _scrollBar->setCursor(Qt::ArrowCursor); _headerBar->setCursor(Qt::ArrowCursor); connect(_headerBar, &TerminalHeaderBar::requestToggleExpansion, this, &Konsole::TerminalDisplay::requestToggleExpansion); - connect(_headerBar, &TerminalHeaderBar::requestMoveToNewTab, this, [this]{requestMoveToNewTab(this);}); + connect(_headerBar, &TerminalHeaderBar::requestMoveToNewTab, this, [this] { + requestMoveToNewTab(this); + }); connect(_scrollBar, &QScrollBar::sliderMoved, this, &Konsole::TerminalDisplay::viewScrolledByUser); // setup timers for blinking text @@ -301,12 +303,11 @@ TerminalDisplay::TerminalDisplay(QWidget* parent) // Keep this last CompositeWidgetFocusWatcher *focusWatcher = new CompositeWidgetFocusWatcher(this); - connect(focusWatcher, &CompositeWidgetFocusWatcher::compositeFocusChanged, - this, [this](bool focused) {_hasCompositeFocus = focused;}); - connect(focusWatcher, &CompositeWidgetFocusWatcher::compositeFocusChanged, - this, &TerminalDisplay::compositeFocusChanged); - connect(focusWatcher, &CompositeWidgetFocusWatcher::compositeFocusChanged, - _headerBar, &TerminalHeaderBar::setFocusIndicatorState); + connect(focusWatcher, &CompositeWidgetFocusWatcher::compositeFocusChanged, this, [this](bool focused) { + _hasCompositeFocus = focused; + }); + connect(focusWatcher, &CompositeWidgetFocusWatcher::compositeFocusChanged, this, &TerminalDisplay::compositeFocusChanged); + connect(focusWatcher, &CompositeWidgetFocusWatcher::compositeFocusChanged, _headerBar, &TerminalHeaderBar::setFocusIndicatorState); connect(&_bell, &TerminalBell::visualBell, this, [this] { _terminalColor->visualBell(); @@ -330,8 +331,7 @@ TerminalDisplay::TerminalDisplay(QWidget* parent) connect(this, &TerminalDisplay::drawCharacters, _terminalPainter, &TerminalPainter::drawCharacters); connect(this, &TerminalDisplay::drawInputMethodPreeditString, _terminalPainter, &TerminalPainter::drawInputMethodPreeditString); - auto ldrawBackground = [this](QPainter &painter, - const QRect &rect, const QColor &backgroundColor, bool useOpacitySetting) { + auto ldrawBackground = [this](QPainter &painter, const QRect &rect, const QColor &backgroundColor, bool useOpacitySetting) { Q_EMIT drawBackground(painter, rect, backgroundColor, useOpacitySetting); }; auto ldrawContents = [this](QPainter &paint, const QRect &rect, bool friendly) { @@ -365,20 +365,14 @@ void TerminalDisplay::hideDragTarget() update(); } -void TerminalDisplay::showDragTarget(const QPoint& cursorPos) +void TerminalDisplay::showDragTarget(const QPoint &cursorPos) { using EdgeDistance = std::pair; auto closerToEdge = std::min( - { - {cursorPos.x(), Qt::LeftEdge}, - {cursorPos.y(), Qt::TopEdge}, - {width() - cursorPos.x(), Qt::RightEdge}, - {height() - cursorPos.y(), Qt::BottomEdge} - }, - [](const EdgeDistance& left, const EdgeDistance& right) -> bool { + {{cursorPos.x(), Qt::LeftEdge}, {cursorPos.y(), Qt::TopEdge}, {width() - cursorPos.x(), Qt::RightEdge}, {height() - cursorPos.y(), Qt::BottomEdge}}, + [](const EdgeDistance &left, const EdgeDistance &right) -> bool { return left.first < right.first; - } - ); + }); if (_overlayEdge == closerToEdge.second) { return; } @@ -452,7 +446,6 @@ uint TerminalDisplay::randomSeed() const void TerminalDisplay::processFilters() { - if (_screenWindow.isNull()) { return; } @@ -468,10 +461,7 @@ void TerminalDisplay::processFilters() // 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->setImage(_screenWindow->getImage(), _screenWindow->windowLines(), _screenWindow->windowColumns(), _screenWindow->getLineProperties()); _filterChain->process(); const QRegion postUpdateHotSpots = _filterChain->hotSpotRegion(); @@ -497,9 +487,8 @@ void TerminalDisplay::updateImage() // 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 (!((_outputSuspendedMessageWidget != nullptr) && _outputSuspendedMessageWidget->isVisible()) && - !((_readOnlyMessageWidget != nullptr) && _readOnlyMessageWidget->isVisible())) { - + if (!((_outputSuspendedMessageWidget != nullptr) && _outputSuspendedMessageWidget->isVisible()) + && !((_readOnlyMessageWidget != nullptr) && _readOnlyMessageWidget->isVisible())) { // hide terminal size label to prevent it being scrolled and show again after scroll const bool viewResizeWidget = (_resizeWidget != nullptr) && _resizeWidget->isVisible(); if (viewResizeWidget) { @@ -518,12 +507,12 @@ void TerminalDisplay::updateImage() updateImageSize(); } - Character* const newimg = _screenWindow->getImage(); + Character *const newimg = _screenWindow->getImage(); const int lines = _screenWindow->windowLines(); const int columns = _screenWindow->windowColumns(); QVector newLineProperties = _screenWindow->getLineProperties(); - _scrollBar->setScroll(_screenWindow->currentLine() , _screenWindow->lineCount()); + _scrollBar->setScroll(_screenWindow->currentLine(), _screenWindow->lineCount()); Q_ASSERT(_usedLines <= _lines); Q_ASSERT(_usedColumns <= _columns); @@ -532,12 +521,12 @@ void TerminalDisplay::updateImage() int x; int len; - const QPoint tL = contentsRect().topLeft(); - const int tLx = tL.x(); - const int tLy = tL.y(); + const QPoint tL = contentsRect().topLeft(); + const int tLx = tL.x(); + const int tLy = tL.y(); _hasTextBlinker = false; - CharacterColor cf; // undefined + CharacterColor cf; // undefined const int linesToUpdate = qBound(0, lines, _lines); const int columnsToUpdate = qBound(0, columns, _columns); @@ -551,8 +540,8 @@ void TerminalDisplay::updateImage() int dirtyLineCount = 0; for (y = 0; y < linesToUpdate; ++y) { - const Character* currentLine = &_image[y * _columns]; - const Character* const newLine = &newimg[y * columns]; + const Character *currentLine = &_image[y * _columns]; + const Character *const newLine = &newimg[y * columns]; bool updateLine = false; @@ -561,7 +550,7 @@ void TerminalDisplay::updateImage() // 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]) { dirtyMask[x] = 1; } @@ -587,7 +576,7 @@ void TerminalDisplay::updateImage() } const int lln = columnsToUpdate - x; for (len = 1; len < lln; ++len) { - const Character& ch = newLine[x + len]; + const Character &ch = newLine[x + len]; if (ch.character == 0u) { continue; // Skip trailing part of multi-col chars. @@ -595,12 +584,8 @@ void TerminalDisplay::updateImage() const bool nextIsDoubleWidth = (x + len + 1 == columnsToUpdate) ? false : (newLine[x + len + 1].character == 0); - if (ch.foregroundColor != cf || - ch.backgroundColor != clipboard || - (ch.rendition & ~RE_EXTENDED_CHAR) != (cr & ~RE_EXTENDED_CHAR) || - (dirtyMask[x + len] == 0) || - LineBlockCharacters::canDraw(ch.character) != lineDraw || - nextIsDoubleWidth != doubleWidth) { + if (ch.foregroundColor != cf || ch.backgroundColor != clipboard || (ch.rendition & ~RE_EXTENDED_CHAR) != (cr & ~RE_EXTENDED_CHAR) + || (dirtyMask[x + len] == 0) || LineBlockCharacters::canDraw(ch.character) != lineDraw || nextIsDoubleWidth != doubleWidth) { break; } } @@ -621,9 +606,9 @@ void TerminalDisplay::updateImage() // add the area occupied by this line to the region which needs to be // repainted - QRect dirtyRect = QRect(_contentRect.left() + tLx , - _contentRect.top() + tLy + _terminalFont->fontHeight() * y , - _terminalFont->fontWidth() * columnsToUpdate , + QRect dirtyRect = QRect(_contentRect.left() + tLx, + _contentRect.top() + tLy + _terminalFont->fontHeight() * y, + _terminalFont->fontWidth() * columnsToUpdate, _terminalFont->fontHeight()); dirtyRegion |= dirtyRect; @@ -631,24 +616,24 @@ void TerminalDisplay::updateImage() // 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)); + memcpy((void *)currentLine, (const void *)newLine, columnsToUpdate * sizeof(Character)); } _lineProperties = newLineProperties; // if the new _image is smaller than the previous _image, then ensure that the area // outside the new _image is cleared if (linesToUpdate < _usedLines) { - dirtyRegion |= QRect(_contentRect.left() + tLx , - _contentRect.top() + tLy + _terminalFont->fontHeight() * linesToUpdate , - _terminalFont->fontWidth() * _columns , + dirtyRegion |= QRect(_contentRect.left() + tLx, + _contentRect.top() + tLy + _terminalFont->fontHeight() * linesToUpdate, + _terminalFont->fontWidth() * _columns, _terminalFont->fontHeight() * (_usedLines - linesToUpdate)); } _usedLines = linesToUpdate; if (columnsToUpdate < _usedColumns) { dirtyRegion |= QRect(_contentRect.left() + tLx + columnsToUpdate * _terminalFont->fontWidth(), - _contentRect.top() + tLy , - _terminalFont->fontWidth() * (_usedColumns - columnsToUpdate) , + _contentRect.top() + tLy, + _terminalFont->fontWidth() * (_usedColumns - columnsToUpdate), _terminalFont->fontHeight() * _lines); } _usedColumns = columnsToUpdate; @@ -659,8 +644,10 @@ void TerminalDisplay::updateImage() // De-highlight previous result region dirtyRegion |= _searchResultRect; // Highlight new result region - dirtyRegion |= QRect(0, _contentRect.top() + (_screenWindow->currentResultLine() - _screenWindow->currentLine()) * _terminalFont->fontHeight(), - _columns * _terminalFont->fontWidth(), _terminalFont->fontHeight()); + dirtyRegion |= QRect(0, + _contentRect.top() + (_screenWindow->currentResultLine() - _screenWindow->currentLine()) * _terminalFont->fontHeight(), + _columns * _terminalFont->fontWidth(), + _terminalFont->fontHeight()); } if (_scrollBar->highlightScrolledLines().isEnabled()) { @@ -706,14 +693,13 @@ void TerminalDisplay::showResizeNotification() } QString sizeStr = i18n("Size: %1 x %2", _columns, _lines); _resizeWidget->setText(sizeStr); - _resizeWidget->move((width() - _resizeWidget->width()) / 2, - (height() - _resizeWidget->height()) / 2 + 20); + _resizeWidget->move((width() - _resizeWidget->width()) / 2, (height() - _resizeWidget->height()) / 2 + 20); _resizeWidget->show(); _resizeTimer->start(); } } -void TerminalDisplay::paintEvent(QPaintEvent* pe) +void TerminalDisplay::paintEvent(QPaintEvent *pe) { QPainter paint(this); @@ -728,7 +714,7 @@ void TerminalDisplay::paintEvent(QPaintEvent* pe) if (_displayVerticalLine) { const int fontWidth = _terminalFont->fontWidth(); - const int x = (fontWidth/2) + (fontWidth * _displayVerticalLineAtChar); + const int x = (fontWidth / 2) + (fontWidth * _displayVerticalLineAtChar); const QColor lineColor = _terminalColor->foregroundColor(); paint.setPen(lineColor); @@ -760,13 +746,13 @@ void TerminalDisplay::paintEvent(QPaintEvent* pe) if (_drawOverlay) { const auto y = _headerBar->isVisible() ? _headerBar->height() : 0; const auto rect = _overlayEdge == Qt::LeftEdge ? QRect(0, y, width() / 2, height()) - : _overlayEdge == Qt::TopEdge ? QRect(0, y, width(), height() / 2) - : _overlayEdge == Qt::RightEdge ? QRect(width() - width() / 2, y, width() / 2, height()) - : QRect(0, height() - height() / 2, width(), height() / 2); + : _overlayEdge == Qt::TopEdge ? QRect(0, y, width(), height() / 2) + : _overlayEdge == Qt::RightEdge ? QRect(width() - width() / 2, y, width() / 2, height()) + : QRect(0, height() - height() / 2, width(), height() / 2); paint.setRenderHint(QPainter::Antialiasing); paint.setPen(Qt::NoPen); - paint.setBrush(QColor(100,100,100, 127)); + paint.setBrush(QColor(100, 100, 100, 127)); paint.drawRect(rect); } } @@ -782,26 +768,24 @@ QPoint TerminalDisplay::cursorPosition() const bool TerminalDisplay::isCursorOnDisplay() const { - return cursorPosition().x() < _columns && - cursorPosition().y() < _lines; + return cursorPosition().x() < _columns && cursorPosition().y() < _lines; } -FilterChain* TerminalDisplay::filterChain() const +FilterChain *TerminalDisplay::filterChain() const { return _filterChain; } -void TerminalDisplay::paintFilters(QPainter& painter) +void TerminalDisplay::paintFilters(QPainter &painter) { if (_filterUpdateRequired) { return; } - _filterChain->paint(this, painter); } -QRect TerminalDisplay::imageToWidget(const QRect& imageArea) const +QRect TerminalDisplay::imageToWidget(const QRect &imageArea) const { QRect result; const int fontWidth = _terminalFont->fontWidth(); @@ -819,10 +803,10 @@ QRect TerminalDisplay::widgetToImage(const QRect &widgetArea) const QRect result; const int fontWidth = _terminalFont->fontWidth(); const int fontHeight = _terminalFont->fontHeight(); - result.setLeft( qBound(0, (widgetArea.left() - contentsRect().left() - _contentRect.left()) / fontWidth, _usedColumns - 1)); - result.setTop( qBound(0, (widgetArea.top() - contentsRect().top() - _contentRect.top() ) / fontHeight, _usedLines - 1)); - result.setRight( qBound(0, (widgetArea.right() - contentsRect().left() - _contentRect.left()) / fontWidth, _usedColumns - 1)); - result.setBottom(qBound(0, (widgetArea.bottom() - contentsRect().top() - _contentRect.top() ) / fontHeight, _usedLines - 1)); + result.setLeft(qBound(0, (widgetArea.left() - contentsRect().left() - _contentRect.left()) / fontWidth, _usedColumns - 1)); + result.setTop(qBound(0, (widgetArea.top() - contentsRect().top() - _contentRect.top()) / fontHeight, _usedLines - 1)); + result.setRight(qBound(0, (widgetArea.right() - contentsRect().left() - _contentRect.left()) / fontWidth, _usedColumns - 1)); + result.setBottom(qBound(0, (widgetArea.bottom() - contentsRect().top() - _contentRect.top()) / fontHeight, _usedLines - 1)); return result; } @@ -865,7 +849,7 @@ void TerminalDisplay::setBlinkingTextEnabled(bool blink) } } -void TerminalDisplay::focusOutEvent(QFocusEvent*) +void TerminalDisplay::focusOutEvent(QFocusEvent *) { // trigger a repaint of the cursor so that it is both: // @@ -888,7 +872,7 @@ void TerminalDisplay::focusOutEvent(QFocusEvent*) Q_ASSERT(!_textBlinking); } -void TerminalDisplay::focusInEvent(QFocusEvent*) +void TerminalDisplay::focusInEvent(QFocusEvent *) { if (_allowBlinkingCursor) { _blinkCursorTimer->start(); @@ -922,7 +906,7 @@ void TerminalDisplay::blinkCursorEvent() void TerminalDisplay::updateCursor() { - if (!isCursorOnDisplay()){ + if (!isCursorOnDisplay()) { return; } @@ -952,9 +936,7 @@ void TerminalDisplay::resizeEvent(QResizeEvent *event) updateImage(); } - const auto scrollBarWidth = _scrollBar->scrollBarPosition() != Enum::ScrollBarHidden - ? _scrollBar->width() - : 0; + const auto scrollBarWidth = _scrollBar->scrollBarPosition() != Enum::ScrollBarHidden ? _scrollBar->width() : 0; const auto headerHeight = _headerBar->isVisible() ? _headerBar->height() : 0; const auto x = width() - scrollBarWidth - _searchBar->width(); @@ -971,7 +953,7 @@ void TerminalDisplay::propagateSize() void TerminalDisplay::updateImageSize() { - Character* oldImage = _image; + Character *oldImage = _image; const int oldLines = _lines; const int oldColumns = _columns; @@ -982,9 +964,7 @@ void TerminalDisplay::updateImageSize() int lines = qMin(oldLines, _lines); int columns = qMin(oldColumns, _columns); for (int line = 0; line < lines; line++) { - memcpy((void*)&_image[_columns * line], - (void*)&oldImage[oldColumns * line], - columns * sizeof(Character)); + memcpy((void *)&_image[_columns * line], (void *)&oldImage[oldColumns * line], columns * sizeof(Character)); } delete[] oldImage; } @@ -1030,28 +1010,26 @@ void TerminalDisplay::calcGeometry() { const auto headerHeight = _headerBar->isVisible() ? _headerBar->height() : 0; - _scrollBar->resize( - _scrollBar->sizeHint().width(), // width - contentsRect().height() - headerHeight // height + _scrollBar->resize(_scrollBar->sizeHint().width(), // width + contentsRect().height() - headerHeight // height ); _contentRect = contentsRect().adjusted( _margin + (_scrollBar->highlightScrolledLines().isEnabled() ? _scrollBar->highlightScrolledLines().HIGHLIGHT_SCROLLED_LINES_WIDTH : 0), - _margin, -_margin - (_scrollBar->highlightScrolledLines().isEnabled() ? _scrollBar->highlightScrolledLines().HIGHLIGHT_SCROLLED_LINES_WIDTH : 0), + _margin, + -_margin - (_scrollBar->highlightScrolledLines().isEnabled() ? _scrollBar->highlightScrolledLines().HIGHLIGHT_SCROLLED_LINES_WIDTH : 0), -_margin); switch (_scrollBar->scrollBarPosition()) { - case Enum::ScrollBarHidden : + case Enum::ScrollBarHidden: break; - case Enum::ScrollBarLeft : + case Enum::ScrollBarLeft: _contentRect.setLeft(_contentRect.left() + _scrollBar->width()); - _scrollBar->move(contentsRect().left(), - contentsRect().top() + headerHeight); + _scrollBar->move(contentsRect().left(), contentsRect().top() + headerHeight); break; case Enum::ScrollBarRight: _contentRect.setRight(_contentRect.right() - _scrollBar->width()); - _scrollBar->move(contentsRect().left() + contentsRect().width() - _scrollBar->width(), - contentsRect().top() + headerHeight); + _scrollBar->move(contentsRect().left() + contentsRect().width() - _scrollBar->width(), contentsRect().top() + headerHeight); break; } @@ -1067,7 +1045,7 @@ void TerminalDisplay::calcGeometry() _lines = qMax(1, _contentRect.height() / _terminalFont->fontHeight()); _usedLines = qMin(_usedLines, _lines); - if(_centerContents) { + if (_centerContents) { QSize unusedPixels = _contentRect.size() - QSize(_columns * fontWidth, _lines * _terminalFont->fontHeight()); _contentRect.adjust(unusedPixels.width() / 2, unusedPixels.height() / 2, 0, 0); } @@ -1080,8 +1058,7 @@ void TerminalDisplay::setSize(int columns, int lines) const int horizontalMargin = _margin * 2; const int verticalMargin = _margin * 2; - QSize newSize = QSize(horizontalMargin + scrollBarWidth + (columns * _terminalFont->fontWidth()), - verticalMargin + (lines * _terminalFont->fontHeight())); + QSize newSize = QSize(horizontalMargin + scrollBarWidth + (columns * _terminalFont->fontWidth()), verticalMargin + (lines * _terminalFont->fontHeight())); if (newSize != size()) { _size = newSize; @@ -1094,17 +1071,17 @@ QSize TerminalDisplay::sizeHint() const return _size; } -//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. +// showEvent and hideEvent are reimplemented here so that it appears to other classes that the +// display has been resized when the display is hidden or shown. // -//TODO: Perhaps it would be better to have separate signals for show and hide instead of using -//the same signal as the one for a content size change -void TerminalDisplay::showEvent(QShowEvent*) +// TODO: Perhaps it would be better to have separate signals for show and hide instead of using +// the same signal as the one for a content size change +void TerminalDisplay::showEvent(QShowEvent *) { propagateSize(); Q_EMIT changedContentSizeSignal(_contentRect.height(), _contentRect.width()); } -void TerminalDisplay::hideEvent(QHideEvent*) +void TerminalDisplay::hideEvent(QHideEvent *) { Q_EMIT changedContentSizeSignal(_contentRect.height(), _contentRect.width()); } @@ -1130,7 +1107,7 @@ void TerminalDisplay::setCenterContents(bool enable) /* Mouse */ /* */ /* ------------------------------------------------------------------------- */ -void TerminalDisplay::mousePressEvent(QMouseEvent* ev) +void TerminalDisplay::mousePressEvent(QMouseEvent *ev) { if (!contentsRect().contains(ev->pos())) { return; @@ -1146,13 +1123,12 @@ void TerminalDisplay::mousePressEvent(QMouseEvent* ev) } // Ignore clicks on the message widget - if (_readOnlyMessageWidget != nullptr && - _readOnlyMessageWidget->isVisible() && _readOnlyMessageWidget->frameGeometry().contains(ev->pos())) { + if (_readOnlyMessageWidget != nullptr && _readOnlyMessageWidget->isVisible() && _readOnlyMessageWidget->frameGeometry().contains(ev->pos())) { return; } - if (_outputSuspendedMessageWidget != nullptr && - _outputSuspendedMessageWidget->isVisible() && _outputSuspendedMessageWidget->frameGeometry().contains(ev->pos())) { + if (_outputSuspendedMessageWidget != nullptr && _outputSuspendedMessageWidget->isVisible() + && _outputSuspendedMessageWidget->frameGeometry().contains(ev->pos())) { return; } @@ -1171,8 +1147,7 @@ void TerminalDisplay::mousePressEvent(QMouseEvent* ev) if (ev->button() == Qt::LeftButton) { // request the software keyboard, if any if (qApp->autoSipEnabled()) { - auto behavior = QStyle::RequestSoftwareInputPanel( - style()->styleHint(QStyle::SH_RequestSoftwareInputPanel)); + auto behavior = QStyle::RequestSoftwareInputPanel(style()->styleHint(QStyle::SH_RequestSoftwareInputPanel)); if (hasFocus() || behavior == QStyle::RSIP_OnMouseClick) { QEvent event(QEvent::RequestSoftwareInputPanel); QApplication::sendEvent(this, &event); @@ -1185,7 +1160,7 @@ void TerminalDisplay::mousePressEvent(QMouseEvent* ev) } // The user clicked inside selected text - bool selected = _screenWindow->isSelected(pos.x(), pos.y()); + bool selected = _screenWindow->isSelected(pos.x(), pos.y()); // Drag only when the Control key is held if ((!_ctrlRequiredForDrag || ((ev->modifiers() & Qt::ControlModifier) != 0u)) && selected) { @@ -1198,25 +1173,23 @@ void TerminalDisplay::mousePressEvent(QMouseEvent* ev) _preserveLineBreaks = !(((ev->modifiers() & Qt::ControlModifier) != 0u) && !(ev->modifiers() & Qt::AltModifier)); _columnSelectionMode = ((ev->modifiers() & Qt::AltModifier) != 0u) && ((ev->modifiers() & Qt::ControlModifier) != 0u); - // There are a couple of use cases when selecting text : - // Normal buffer or Alternate buffer when not using Mouse Tracking: - // select text or extendSelection or columnSelection or columnSelection + extendSelection - // - // Alternate buffer when using Mouse Tracking and with Shift pressed: - // select text or columnSelection - if (!_usesMouseTracking && - ((ev->modifiers() == Qt::ShiftModifier) || - (((ev->modifiers() & Qt::ShiftModifier) != 0u) && _columnSelectionMode))) { - extendSelection(ev->pos()); - } else if ((!_usesMouseTracking && !((ev->modifiers() & Qt::ShiftModifier))) || - (_usesMouseTracking && ((ev->modifiers() & Qt::ShiftModifier) != 0u))) { + // There are a couple of use cases when selecting text : + // Normal buffer or Alternate buffer when not using Mouse Tracking: + // select text or extendSelection or columnSelection or columnSelection + extendSelection + // + // Alternate buffer when using Mouse Tracking and with Shift pressed: + // select text or columnSelection + if (!_usesMouseTracking && ((ev->modifiers() == Qt::ShiftModifier) || (((ev->modifiers() & Qt::ShiftModifier) != 0u) && _columnSelectionMode))) { + extendSelection(ev->pos()); + } else if ((!_usesMouseTracking && !((ev->modifiers() & Qt::ShiftModifier))) + || (_usesMouseTracking && ((ev->modifiers() & Qt::ShiftModifier) != 0u))) { _screenWindow->clearSelection(); pos.ry() += _scrollBar->value(); _iPntSel = _pntSel = pos; _actSel = 1; // left mouse button pressed but nothing selected yet. } else if (_usesMouseTracking && !_readOnly) { - Q_EMIT mouseSignal(0, charColumn + 1, charLine + 1 + _scrollBar->value() - _scrollBar->maximum() , 0); + Q_EMIT mouseSignal(0, charColumn + 1, charLine + 1 + _scrollBar->value() - _scrollBar->maximum(), 0); } } } else if (ev->button() == Qt::MiddleButton) { @@ -1225,23 +1198,23 @@ void TerminalDisplay::mousePressEvent(QMouseEvent* ev) if (!_usesMouseTracking || ((ev->modifiers() & Qt::ShiftModifier) != 0u)) { Q_EMIT configureRequest(ev->pos()); } else { - if(!_readOnly) { - Q_EMIT mouseSignal(2, charColumn + 1, charLine + 1 + _scrollBar->value() - _scrollBar->maximum() , 0); + if (!_readOnly) { + Q_EMIT mouseSignal(2, charColumn + 1, charLine + 1 + _scrollBar->value() - _scrollBar->maximum(), 0); } } } } -QSharedPointer TerminalDisplay::filterActions(const QPoint& position) +QSharedPointer TerminalDisplay::filterActions(const QPoint &position) { auto [charLine, charColumn] = getCharacterPosition(position, false); return _filterChain->hotSpotAt(charLine, charColumn); } -void TerminalDisplay::mouseMoveEvent(QMouseEvent* ev) +void TerminalDisplay::mouseMoveEvent(QMouseEvent *ev) { if (!hasFocus() && KonsoleSettings::focusFollowsMouse()) { - setFocus(); + setFocus(); } auto [charLine, charColumn] = getCharacterPosition(ev->pos(), !_usesMouseTracking); @@ -1250,8 +1223,7 @@ void TerminalDisplay::mouseMoveEvent(QMouseEvent* ev) // but don't ignore the ones generated by AutoScrollHandler (which // allow to extend the selection by dragging the mouse outside the // display). - if (charLine == _prevCharacterLine && charColumn == _prevCharacterColumn && - contentsRect().contains(ev->pos())) { + if (charLine == _prevCharacterLine && charColumn == _prevCharacterColumn && contentsRect().contains(ev->pos())) { return; } @@ -1278,10 +1250,7 @@ void TerminalDisplay::mouseMoveEvent(QMouseEvent* ev) button = 2; } - Q_EMIT mouseSignal(button, - charColumn + 1, - charLine + 1 + _scrollBar->value() - _scrollBar->maximum(), - 1); + Q_EMIT mouseSignal(button, charColumn + 1, charLine + 1 + _scrollBar->value() - _scrollBar->maximum(), 1); } return; @@ -1297,8 +1266,8 @@ void TerminalDisplay::mouseMoveEvent(QMouseEvent* ev) // if the mouse has moved sufficiently, we will confirm const int distance = QApplication::startDragDistance(); - if (ev->x() > _dragInfo.start.x() + distance || ev->x() < _dragInfo.start.x() - distance || - ev->y() > _dragInfo.start.y() + distance || ev->y() < _dragInfo.start.y() - distance) { + if (ev->x() > _dragInfo.start.x() + distance || ev->x() < _dragInfo.start.x() - distance || ev->y() > _dragInfo.start.y() + distance + || ev->y() < _dragInfo.start.y() - distance) { // we've left the drag square, we can start a real drag operation now _screenWindow->clearSelection(); @@ -1315,7 +1284,7 @@ void TerminalDisplay::mouseMoveEvent(QMouseEvent* ev) return; } -// don't extend selection while pasting + // don't extend selection while pasting if ((ev->buttons() & Qt::MiddleButton) != 0u) { return; } @@ -1330,7 +1299,7 @@ void TerminalDisplay::leaveEvent(QEvent *ev) _filterChain->leaveEvent(this, ev); } -void TerminalDisplay::extendSelection(const QPoint& position) +void TerminalDisplay::extendSelection(const QPoint &position) { if (_screenWindow.isNull()) { return; @@ -1341,11 +1310,11 @@ void TerminalDisplay::extendSelection(const QPoint& position) return; } - //if ( !contentsRect().contains(ev->pos()) ) return; - const QPoint tL = contentsRect().topLeft(); - const int tLx = tL.x(); - const int tLy = tL.y(); - const int scroll = _scrollBar->value(); + // if ( !contentsRect().contains(ev->pos()) ) return; + const QPoint tL = contentsRect().topLeft(); + const int tLx = tL.x(); + const int tLy = tL.y(); + const int scroll = _scrollBar->value(); // we're in the process of moving the mouse with the left button pressed // the mouse cursor will kept caught within the bounds of the text in @@ -1387,10 +1356,8 @@ void TerminalDisplay::extendSelection(const QPoint& position) if (_wordSelectionMode) { // Extend to word boundaries - const bool left_not_right = (here.y() < iPntSelCorr.y() || - (here.y() == iPntSelCorr.y() && here.x() < iPntSelCorr.x())); - const bool old_left_not_right = (pntSelCorr.y() < iPntSelCorr.y() || - (pntSelCorr.y() == iPntSelCorr.y() && pntSelCorr.x() < iPntSelCorr.x())); + const bool left_not_right = (here.y() < iPntSelCorr.y() || (here.y() == iPntSelCorr.y() && here.x() < iPntSelCorr.x())); + const bool old_left_not_right = (pntSelCorr.y() < iPntSelCorr.y() || (pntSelCorr.y() == iPntSelCorr.y() && pntSelCorr.x() < iPntSelCorr.x())); swapping = left_not_right != old_left_not_right; // Find left (left_not_right ? from here : from start of word) @@ -1439,10 +1406,8 @@ void TerminalDisplay::extendSelection(const QPoint& position) int offset = 0; if (!_wordSelectionMode && !_lineSelectionMode) { - const bool left_not_right = (here.y() < iPntSelCorr.y() || - (here.y() == iPntSelCorr.y() && here.x() < iPntSelCorr.x())); - const bool old_left_not_right = (pntSelCorr.y() < iPntSelCorr.y() || - (pntSelCorr.y() == iPntSelCorr.y() && pntSelCorr.x() < iPntSelCorr.x())); + const bool left_not_right = (here.y() < iPntSelCorr.y() || (here.y() == iPntSelCorr.y() && here.x() < iPntSelCorr.x())); + const bool old_left_not_right = (pntSelCorr.y() < iPntSelCorr.y() || (pntSelCorr.y() == iPntSelCorr.y() && pntSelCorr.x() < iPntSelCorr.x())); swapping = left_not_right != old_left_not_right; // Find left (left_not_right ? from here : from start) @@ -1473,9 +1438,9 @@ void TerminalDisplay::extendSelection(const QPoint& position) if (_actSel < 2 || swapping) { if (_columnSelectionMode && !_lineSelectionMode && !_wordSelectionMode) { - _screenWindow->setSelectionStart(ohere.x() , ohere.y() , true); + _screenWindow->setSelectionStart(ohere.x(), ohere.y(), true); } else { - _screenWindow->setSelectionStart(ohere.x() - 1 - offset , ohere.y() , false); + _screenWindow->setSelectionStart(ohere.x() - 1 - offset, ohere.y(), false); } } @@ -1484,13 +1449,13 @@ void TerminalDisplay::extendSelection(const QPoint& position) _pntSel.ry() += _scrollBar->value(); if (_columnSelectionMode && !_lineSelectionMode && !_wordSelectionMode) { - _screenWindow->setSelectionEnd(here.x() , here.y()); + _screenWindow->setSelectionEnd(here.x(), here.y()); } else { - _screenWindow->setSelectionEnd(here.x() + offset , here.y()); + _screenWindow->setSelectionEnd(here.x() + offset, here.y()); } } -void TerminalDisplay::mouseReleaseEvent(QMouseEvent* ev) +void TerminalDisplay::mouseReleaseEvent(QMouseEvent *ev) { if (_screenWindow.isNull()) { return; @@ -1509,26 +1474,19 @@ void TerminalDisplay::mouseReleaseEvent(QMouseEvent* ev) _actSel = 0; - //FIXME: emits a release event even if the mouse is + // FIXME: emits a release event even if the mouse is // outside the range. The procedure used in `mouseMoveEvent' // applies here, too. if (_usesMouseTracking && !(ev->modifiers() & Qt::ShiftModifier) && !_readOnly) { - Q_EMIT mouseSignal(0, - charColumn + 1, - charLine + 1 + _scrollBar->value() - _scrollBar->maximum() , 2); + Q_EMIT mouseSignal(0, charColumn + 1, charLine + 1 + _scrollBar->value() - _scrollBar->maximum(), 2); } } _dragInfo.state = diNone; } - if (_usesMouseTracking && !_readOnly && - (ev->button() == Qt::RightButton || ev->button() == Qt::MiddleButton) && - !(ev->modifiers() & Qt::ShiftModifier)) { - Q_EMIT mouseSignal(ev->button() == Qt::MiddleButton ? 1 : 2, - charColumn + 1, - charLine + 1 + _scrollBar->value() - _scrollBar->maximum() , - 2); + if (_usesMouseTracking && !_readOnly && (ev->button() == Qt::RightButton || ev->button() == Qt::MiddleButton) && !(ev->modifiers() & Qt::ShiftModifier)) { + Q_EMIT mouseSignal(ev->button() == Qt::MiddleButton ? 1 : 2, charColumn + 1, charLine + 1 + _scrollBar->value() - _scrollBar->maximum(), 2); } if (!_screenWindow->screen()->hasSelection()) { @@ -1536,7 +1494,7 @@ void TerminalDisplay::mouseReleaseEvent(QMouseEvent* ev) } } -QPair TerminalDisplay::getCharacterPosition(const QPoint& widgetPoint, bool edge) const +QPair TerminalDisplay::getCharacterPosition(const QPoint &widgetPoint, bool edge) const { // the column value returned can be equal to _usedColumns (when edge == true), // which is the position just after the last character displayed in a line. @@ -1547,7 +1505,8 @@ QPair TerminalDisplay::getCharacterPosition(const QPoint& widgetPoint, const int xOffset = edge ? _terminalFont->fontWidth() / 2 : 0; int line = qBound(0, (widgetPoint.y() - contentsRect().top() - _contentRect.top()) / _terminalFont->fontHeight(), _usedLines - 1); bool doubleWidth = line < _lineProperties.count() && _lineProperties[line] & LINE_DOUBLEWIDTH; - int column = qBound(0, (widgetPoint.x() + xOffset - contentsRect().left() - _contentRect.left()) / _terminalFont->fontWidth() / (doubleWidth ? 2 : 1), columnMax); + int column = + qBound(0, (widgetPoint.x() + xOffset - contentsRect().left() - _contentRect.left()) / _terminalFont->fontWidth() / (doubleWidth ? 2 : 1), columnMax); return qMakePair(line, column); } @@ -1557,7 +1516,7 @@ void TerminalDisplay::setExpandedMode(bool expand) _headerBar->setExpandedMode(expand); } -void TerminalDisplay::processMidButtonClick(QMouseEvent* ev) +void TerminalDisplay::processMidButtonClick(QMouseEvent *ev) { if (!_usesMouseTracking || ((ev->modifiers() & Qt::ShiftModifier) != 0u)) { const bool appendEnter = (ev->modifiers() & Qt::ControlModifier) != 0u; @@ -1570,14 +1529,14 @@ void TerminalDisplay::processMidButtonClick(QMouseEvent* ev) Q_ASSERT(false); } } else { - if(!_readOnly) { + if (!_readOnly) { auto [charLine, charColumn] = getCharacterPosition(ev->pos(), !_usesMouseTracking); - Q_EMIT mouseSignal(1, charColumn + 1, charLine + 1 + _scrollBar->value() - _scrollBar->maximum() , 0); + Q_EMIT mouseSignal(1, charColumn + 1, charLine + 1 + _scrollBar->value() - _scrollBar->maximum(), 0); } } } -void TerminalDisplay::mouseDoubleClickEvent(QMouseEvent* ev) +void TerminalDisplay::mouseDoubleClickEvent(QMouseEvent *ev) { // Yes, successive middle click can trigger this event if (ev->button() == Qt::MiddleButton) { @@ -1595,12 +1554,10 @@ void TerminalDisplay::mouseDoubleClickEvent(QMouseEvent* ev) // pass on double click as two clicks. if (_usesMouseTracking && !(ev->modifiers() & Qt::ShiftModifier)) { - if(!_readOnly) { + if (!_readOnly) { // Send just _ONE_ click event, since the first click of the double click // was already sent by the click handler - Q_EMIT mouseSignal(ev->button() == Qt::LeftButton ? 0 : 2, charColumn + 1, - charLine + 1 + _scrollBar->value() - _scrollBar->maximum(), - 0); + Q_EMIT mouseSignal(ev->button() == Qt::LeftButton ? 0 : 2, charColumn + 1, charLine + 1 + _scrollBar->value() - _scrollBar->maximum(), 0); } return; } @@ -1624,8 +1581,8 @@ void TerminalDisplay::mouseDoubleClickEvent(QMouseEvent* ev) _actSel = 2; // within selection - _screenWindow->setSelectionStart(bgnSel.x() , bgnSel.y() , false); - _screenWindow->setSelectionEnd(endSel.x() , endSel.y()); + _screenWindow->setSelectionStart(bgnSel.x(), bgnSel.y(), false); + _screenWindow->setSelectionEnd(endSel.x(), endSel.y()); copyToX11Selection(); } @@ -1637,7 +1594,7 @@ void TerminalDisplay::mouseDoubleClickEvent(QMouseEvent* ev) }); } -void TerminalDisplay::wheelEvent(QWheelEvent* ev) +void TerminalDisplay::wheelEvent(QWheelEvent *ev) { static QElapsedTimer enable_zoom_timer; static bool enable_zoom = true; @@ -1657,11 +1614,11 @@ void TerminalDisplay::wheelEvent(QWheelEvent* ev) _scrollWheelState.addWheelEvent(ev); int steps = _scrollWheelState.consumeLegacySteps(ScrollState::DEFAULT_ANGLE_SCROLL_LINE); - for (;steps > 0; --steps) { + for (; steps > 0; --steps) { // wheel-up for increasing font size _terminalFont->increaseFontSize(); } - for (;steps < 0; ++steps) { + for (; steps < 0; ++steps) { // wheel-down for decreasing font size _terminalFont->decreaseFontSize(); } @@ -1689,7 +1646,7 @@ void TerminalDisplay::wheelEvent(QWheelEvent* ev) Q_ASSERT(!_sessionController->session().isNull()); - if(!_usesMouseTracking && !_sessionController->session()->isPrimaryScreen() && _scrollBar->alternateScrolling()) { + if (!_usesMouseTracking && !_sessionController->session()->isPrimaryScreen() && _scrollBar->alternateScrolling()) { // Send simulated up / down key presses to the terminal program // for the benefit of programs such as 'less' (which use the alternate screen) @@ -1700,7 +1657,8 @@ void TerminalDisplay::wheelEvent(QWheelEvent* ev) // of mouse wheel rotation. Mouse wheels typically move in steps of 15 degrees, // giving a scroll of 3 lines - const int lines = _scrollWheelState.consumeSteps(static_cast(_terminalFont->fontHeight() * qApp->devicePixelRatio()), ScrollState::degreesToAngle(5)); + const int lines = + _scrollWheelState.consumeSteps(static_cast(_terminalFont->fontHeight() * qApp->devicePixelRatio()), ScrollState::degreesToAngle(5)); const int keyCode = lines > 0 ? Qt::Key_Up : Qt::Key_Down; QKeyEvent keyEvent(QEvent::KeyPress, keyCode, Qt::NoModifier); @@ -1714,10 +1672,7 @@ void TerminalDisplay::wheelEvent(QWheelEvent* ev) const int steps = _scrollWheelState.consumeLegacySteps(ScrollState::DEFAULT_ANGLE_SCROLL_LINE); const int button = (steps > 0) ? 4 : 5; for (int i = 0; i < abs(steps); ++i) { - Q_EMIT mouseSignal(button, - charColumn + 1, - charLine + 1 + _scrollBar->value() - _scrollBar->maximum() , - 0); + Q_EMIT mouseSignal(button, charColumn + 1, charLine + 1 + _scrollBar->value() - _scrollBar->maximum(), 0); } } } @@ -1741,7 +1696,7 @@ QPoint TerminalDisplay::findLineStart(const QPoint &pnt) const int topVisibleLine = _screenWindow->currentLine(); Screen *screen = _screenWindow->screen(); int line = pnt.y(); - int lineInHistory= line + topVisibleLine; + int lineInHistory = line + topVisibleLine; QVector lineProperties = _lineProperties; @@ -1775,7 +1730,7 @@ QPoint TerminalDisplay::findLineEnd(const QPoint &pnt) const int maxY = _screenWindow->lineCount() - 1; Screen *screen = _screenWindow->screen(); int line = pnt.y(); - int lineInHistory= line + topVisibleLine; + int lineInHistory = line + topVisibleLine; QVector lineProperties = _lineProperties; @@ -1817,7 +1772,7 @@ QPoint TerminalDisplay::findWordStart(const QPoint &pnt) const int imageSize = regSize * _columns; while (true) { - for (;;imgLoc--, x--) { + for (;; imgLoc--, x--) { if (imgLoc < 1) { // no more chars in this region break; @@ -1895,19 +1850,18 @@ QPoint TerminalDisplay::findWordEnd(const QPoint &pnt) while (true) { const int lineCount = lineProperties.count(); - for (;;j++, x++) { + for (;; j++, x++) { if (x < maxX) { if (charClass(image[j + 1]) == selClass && // A colon right before whitespace is never part of a word - ! (image[j + 1].character == ':' && charClass(image[j + 2]) == QLatin1Char(' '))) { + !(image[j + 1].character == ':' && charClass(image[j + 2]) == QLatin1Char(' '))) { continue; } goto out; } else if (i < lineCount - 1) { - if (((lineProperties[i] & LINE_WRAPPED) != 0) && - charClass(image[j + 1]) == selClass && + if (((lineProperties[i] & LINE_WRAPPED) != 0) && charClass(image[j + 1]) == selClass && // A colon right before whitespace is never part of a word - ! (image[j + 1].character == ':' && charClass(image[j + 2]) == QLatin1Char(' '))) { + !(image[j + 1].character == ':' && charClass(image[j + 2]) == QLatin1Char(' '))) { x = -1; i++; y++; @@ -1937,9 +1891,7 @@ QPoint TerminalDisplay::findWordEnd(const QPoint &pnt) out: y -= curLine; // In word selection mode don't select @ (64) if at end of word. - if (((image[j].rendition & RE_EXTENDED_CHAR) == 0) && - (QChar(image[j].character) == QLatin1Char('@')) && - (y > pnt.y() || x > pnt.x())) { + if (((image[j].rendition & RE_EXTENDED_CHAR) == 0) && (QChar(image[j].character) == QLatin1Char('@')) && (y > pnt.y() || x > pnt.x())) { if (x > 0) { x--; } else { @@ -1967,15 +1919,14 @@ Screen::DecodingOptions TerminalDisplay::currentDecodingOptions() return decodingOptions; } -void TerminalDisplay::mouseTripleClickEvent(QMouseEvent* ev) +void TerminalDisplay::mouseTripleClickEvent(QMouseEvent *ev) { if (_screenWindow.isNull()) { return; } auto [charLine, charColumn] = getCharacterPosition(ev->pos(), true); - selectLine(QPoint(charColumn, charLine), - _tripleClickMode == Enum::SelectWholeLine); + selectLine(QPoint(charColumn, charLine), _tripleClickMode == Enum::SelectWholeLine); } void TerminalDisplay::selectLine(QPoint pos, bool entireLine) @@ -1991,15 +1942,14 @@ void TerminalDisplay::selectLine(QPoint pos, bool entireLine) if (!entireLine) { // Select from cursor to end of line _tripleSelBegin = findWordStart(_iPntSel); - _screenWindow->setSelectionStart(_tripleSelBegin.x(), - _tripleSelBegin.y() , false); + _screenWindow->setSelectionStart(_tripleSelBegin.x(), _tripleSelBegin.y(), false); } else { _tripleSelBegin = findLineStart(_iPntSel); - _screenWindow->setSelectionStart(0 , _tripleSelBegin.y() , false); + _screenWindow->setSelectionStart(0, _tripleSelBegin.y(), false); } _iPntSel = findLineEnd(_iPntSel); - _screenWindow->setSelectionEnd(_iPntSel.x() , _iPntSel.y()); + _screenWindow->setSelectionEnd(_iPntSel.x(), _iPntSel.y()); copyToX11Selection(); @@ -2037,11 +1987,11 @@ bool TerminalDisplay::focusNextPrevChild(bool next) } } -QChar TerminalDisplay::charClass(const Character& ch) const +QChar TerminalDisplay::charClass(const Character &ch) const { if ((ch.rendition & RE_EXTENDED_CHAR) != 0) { ushort extendedCharLength = 0; - const uint* chars = ExtendedCharTable::instance.lookupExtendedChar(ch.character, extendedCharLength); + const uint *chars = ExtendedCharTable::instance.lookupExtendedChar(ch.character, extendedCharLength); if ((chars != nullptr) && extendedCharLength > 0) { const QString s = QString::fromUcs4(chars, extendedCharLength); if (_wordCharacters.contains(s, Qt::CaseInsensitive)) { @@ -2068,7 +2018,7 @@ QChar TerminalDisplay::charClass(const Character& ch) const } } -void TerminalDisplay::setWordCharacters(const QString& wc) +void TerminalDisplay::setWordCharacters(const QString &wc) { _wordCharacters = wc; } @@ -2119,14 +2069,14 @@ void TerminalDisplay::doPaste(QString text, bool appendReturn) } if (text.length() > 8000) { - if (KMessageBox::warningContinueCancel(window(), - i18np("Are you sure you want to paste %1 character?", - "Are you sure you want to paste %1 characters?", - text.length()), - i18n("Confirm Paste"), - KStandardGuiItem::cont(), - KStandardGuiItem::cancel(), - QStringLiteral("ShowPasteHugeTextWarning")) == KMessageBox::Cancel) { + if (KMessageBox::warningContinueCancel( + window(), + i18np("Are you sure you want to paste %1 character?", "Are you sure you want to paste %1 characters?", text.length()), + i18n("Confirm Paste"), + KStandardGuiItem::cont(), + KStandardGuiItem::cancel(), + QStringLiteral("ShowPasteHugeTextWarning")) + == KMessageBox::Cancel) { return; } } @@ -2138,7 +2088,7 @@ void TerminalDisplay::doPaste(QString text, bool appendReturn) // categories which contain such code points), convert text to // UTF-32 using QString::toUcs4() and use QChar static // methods which take "uint ucs4". - static const QVector whitelist = { u'\t', u'\r', u'\n' }; + static const QVector whitelist = {u'\t', u'\r', u'\n'}; static const auto isUnsafe = [](const QChar &c) { return (c.category() == QChar::Category::Other_Control && !whitelist.contains(c.unicode())); }; @@ -2148,7 +2098,7 @@ void TerminalDisplay::doPaste(QString text, bool appendReturn) return QStringLiteral("^%1").arg(QChar(u'@' + c.unicode())); } else if (c.unicode() == 0x7F) { return QStringLiteral("^?"); - } else if (c.unicode() >= 0x80 && c.unicode() <= 0x9F){ + } else if (c.unicode() >= 0x80 && c.unicode() <= 0x9F) { return QStringLiteral("^[%1").arg(QChar(u'@' + c.unicode() - 0x80)); } return QString(); @@ -2171,10 +2121,10 @@ void TerminalDisplay::doPaste(QString text, bool appendReturn) const QString sequence = charToSequence(c); const QString description = characterDescriptions.value(c.unicode(), QString()); QString entry = QStringLiteral("U+%1").arg(c.unicode(), 4, 16, QLatin1Char('0')); - if(!sequence.isEmpty()) { + if (!sequence.isEmpty()) { entry += QStringLiteral("\t%1").arg(sequence); } - if(!description.isEmpty()) { + if (!description.isEmpty()) { entry += QStringLiteral("\t%1").arg(description); } unsafeCharacters.append(entry); @@ -2183,23 +2133,17 @@ void TerminalDisplay::doPaste(QString text, bool appendReturn) unsafeCharacters.removeDuplicates(); if (!unsafeCharacters.isEmpty()) { - int result = KMessageBox::warningYesNoCancelList(window(), - i18n("The text you're trying to paste contains hidden control characters, " - "do you want to filter them out?"), - unsafeCharacters, - i18nc("@title", "Confirm Paste"), - KGuiItem(i18nc("@action:button", - "Paste &without control characters"), - QStringLiteral("filter-symbolic")), - KGuiItem(i18nc("@action:button", - "&Paste everything"), - QStringLiteral("edit-paste")), - KGuiItem(i18nc("@action:button", - "&Cancel"), - QStringLiteral("dialog-cancel")), - QStringLiteral("ShowPasteUnprintableWarning") - ); - switch(result){ + int result = + KMessageBox::warningYesNoCancelList(window(), + i18n("The text you're trying to paste contains hidden control characters, " + "do you want to filter them out?"), + unsafeCharacters, + i18nc("@title", "Confirm Paste"), + KGuiItem(i18nc("@action:button", "Paste &without control characters"), QStringLiteral("filter-symbolic")), + KGuiItem(i18nc("@action:button", "&Paste everything"), QStringLiteral("edit-paste")), + KGuiItem(i18nc("@action:button", "&Cancel"), QStringLiteral("dialog-cancel")), + QStringLiteral("ShowPasteUnprintableWarning")); + switch (result) { case KMessageBox::Cancel: return; case KMessageBox::Yes: { @@ -2256,7 +2200,6 @@ void TerminalDisplay::copyToX11Selection() return; } - const QString &text = _screenWindow->selectedText(currentDecodingOptions()); if (text.isEmpty()) { return; @@ -2339,7 +2282,7 @@ void TerminalDisplay::pasteFromX11Selection(bool appendEnter) /* */ /* ------------------------------------------------------------------------- */ -void TerminalDisplay::inputMethodEvent(QInputMethodEvent* event) +void TerminalDisplay::inputMethodEvent(QInputMethodEvent *event) { if (!event->commitString().isEmpty()) { QKeyEvent keyEvent(QEvent::KeyPress, 0, Qt::NoModifier, event->commitString()); @@ -2419,17 +2362,18 @@ void TerminalDisplay::setFlowControlWarningEnabled(bool enable) void TerminalDisplay::outputSuspended(bool suspended) { - //create the label when this function is first called + // create the label when this function is first called if (_outputSuspendedMessageWidget == nullptr) { - //This label includes a link to an English language website - //describing the 'flow control' (Xon/Xoff) feature found in almost - //all terminal emulators. - //If there isn't a suitable article available in the target language the link - //can simply be removed. - _outputSuspendedMessageWidget = createMessageWidget(i18n("Output has been " - "suspended" - " by pressing Ctrl+S." - " Press Ctrl+Q to resume.")); + // This label includes a link to an English language website + // describing the 'flow control' (Xon/Xoff) feature found in almost + // all terminal emulators. + // If there isn't a suitable article available in the target language the link + // can simply be removed. + _outputSuspendedMessageWidget = + createMessageWidget(i18n("Output has been " + "suspended" + " by pressing Ctrl+S." + " Press Ctrl+Q to resume.")); connect(_outputSuspendedMessageWidget, &KMessageWidget::linkActivated, this, [](const QString &url) { QDesktopServices::openUrl(QUrl(url)); @@ -2446,7 +2390,8 @@ void TerminalDisplay::dismissOutputSuspendedMessage() outputSuspended(false); } -KMessageWidget* TerminalDisplay::createMessageWidget(const QString &text) { +KMessageWidget *TerminalDisplay::createMessageWidget(const QString &text) +{ auto *widget = new KMessageWidget(text, this); widget->setWordWrap(true); widget->setFocusProxy(this); @@ -2459,7 +2404,8 @@ KMessageWidget* TerminalDisplay::createMessageWidget(const QString &text) { return widget; } -void TerminalDisplay::updateReadOnlyState(bool readonly) { +void TerminalDisplay::updateReadOnlyState(bool readonly) +{ if (_readOnly == readonly) { return; } @@ -2479,7 +2425,7 @@ void TerminalDisplay::updateReadOnlyState(bool readonly) { _readOnly = readonly; } -void TerminalDisplay::keyPressEvent(QKeyEvent* event) +void TerminalDisplay::keyPressEvent(QKeyEvent *event) { { auto [charLine, charColumn] = getCharacterPosition(mapFromGlobal(QCursor::pos()), !_usesMouseTracking); @@ -2537,7 +2483,7 @@ void TerminalDisplay::keyReleaseEvent(QKeyEvent *event) QWidget::keyReleaseEvent(event); } -bool TerminalDisplay::handleShortcutOverrideEvent(QKeyEvent* keyEvent) +bool TerminalDisplay::handleShortcutOverrideEvent(QKeyEvent *keyEvent) { const int modifiers = keyEvent->modifiers(); @@ -2585,16 +2531,16 @@ bool TerminalDisplay::handleShortcutOverrideEvent(QKeyEvent* keyEvent) return false; } -bool TerminalDisplay::event(QEvent* event) +bool TerminalDisplay::event(QEvent *event) { bool eventHandled = false; switch (event->type()) { case QEvent::ShortcutOverride: - eventHandled = handleShortcutOverrideEvent(static_cast(event)); + eventHandled = handleShortcutOverrideEvent(static_cast(event)); break; case QEvent::FocusOut: case QEvent::FocusIn: - if(_screenWindow != nullptr) { + if (_screenWindow != nullptr) { // force a redraw on focusIn, fixes the // black screen bug when the view is focused // but doesn't redraws. @@ -2608,7 +2554,7 @@ bool TerminalDisplay::event(QEvent* event) return eventHandled ? true : QWidget::event(event); } -void TerminalDisplay::contextMenuEvent(QContextMenuEvent* event) +void TerminalDisplay::contextMenuEvent(QContextMenuEvent *event) { // the logic for the mouse case is within MousePressEvent() if (event->reason() != QContextMenuEvent::Mouse) { @@ -2622,7 +2568,7 @@ void TerminalDisplay::contextMenuEvent(QContextMenuEvent* event) /* */ /* --------------------------------------------------------------------- */ -void TerminalDisplay::bell(const QString& message) +void TerminalDisplay::bell(const QString &message) { _bell.bell(message, hasFocus()); } @@ -2633,25 +2579,25 @@ void TerminalDisplay::bell(const QString& message) /* */ /* --------------------------------------------------------------------- */ -void TerminalDisplay::dragEnterEvent(QDragEnterEvent* event) +void TerminalDisplay::dragEnterEvent(QDragEnterEvent *event) { // text/plain alone is enough for KDE-apps // text/uri-list is for supporting some non-KDE apps, such as thunar // and pcmanfm // That also applies in dropEvent() const auto mimeData = event->mimeData(); - if ((!_readOnly) && (mimeData != nullptr) - && (mimeData->hasFormat(QStringLiteral("text/plain")) - || mimeData->hasFormat(QStringLiteral("text/uri-list")))) { + if ((!_readOnly) && (mimeData != nullptr) && (mimeData->hasFormat(QStringLiteral("text/plain")) || mimeData->hasFormat(QStringLiteral("text/uri-list")))) { event->acceptProposedAction(); } } -namespace { -QString extractDroppedText(const QList& urls) { +namespace +{ +QString extractDroppedText(const QList &urls) +{ QString dropText; - for (int i = 0 ; i < urls.count() ; i++) { - KIO::StatJob* job = KIO::mostLocalUrl(urls[i], KIO::HideProgressInfo); + for (int i = 0; i < urls.count(); i++) { + KIO::StatJob *job = KIO::mostLocalUrl(urls[i], KIO::HideProgressInfo); if (!job->exec()) { continue; } @@ -2667,8 +2613,9 @@ QString extractDroppedText(const QList& urls) { return dropText; } -void setupCdToUrlAction(const QString& dropText, const QUrl& url, QList& additionalActions, TerminalDisplay *display) { - KIO::StatJob* job = KIO::mostLocalUrl(url, KIO::HideProgressInfo); +void setupCdToUrlAction(const QString &dropText, const QUrl &url, QList &additionalActions, TerminalDisplay *display) +{ + KIO::StatJob *job = KIO::mostLocalUrl(url, KIO::HideProgressInfo); if (!job->exec()) { return; } @@ -2683,16 +2630,17 @@ void setupCdToUrlAction(const QString& dropText, const QUrl& url, QListconnect(cdAction, &QAction::triggered, display, [display, triggerText]{ - Q_EMIT display->sendStringToEmu(triggerText);} ); + display->connect(cdAction, &QAction::triggered, display, [display, triggerText] { + Q_EMIT display->sendStringToEmu(triggerText); + }); additionalActions.append(cdAction); } } -void TerminalDisplay::dropEvent(QDropEvent* event) +void TerminalDisplay::dropEvent(QDropEvent *event) { if (_readOnly) { event->accept(); @@ -2715,10 +2663,12 @@ void TerminalDisplay::dropEvent(QDropEvent* event) // A standard popup with Copy, Move and Link as options - // plus an additional Paste option. - QAction* pasteAction = new QAction(i18n("&Paste Location"), this); - connect(pasteAction, &QAction::triggered, this, [this, dropText]{ Q_EMIT sendStringToEmu(dropText.toLocal8Bit());} ); + QAction *pasteAction = new QAction(i18n("&Paste Location"), this); + connect(pasteAction, &QAction::triggered, this, [this, dropText] { + Q_EMIT sendStringToEmu(dropText.toLocal8Bit()); + }); - QList additionalActions; + QList additionalActions; additionalActions.append(pasteAction); if (urls.count() == 1) { @@ -2727,7 +2677,7 @@ void TerminalDisplay::dropEvent(QDropEvent* event) QUrl target = QUrl::fromLocalFile(_sessionController->currentDir()); - KIO::DropJob* job = KIO::drop(event, target); + KIO::DropJob *job = KIO::drop(event, target); KJobWidgets::setWindow(job, this); job->setApplicationActions(additionalActions); return; @@ -2737,8 +2687,7 @@ void TerminalDisplay::dropEvent(QDropEvent* event) dropText = mimeData->text(); } - if (mimeData->hasFormat(QStringLiteral("text/plain")) || - mimeData->hasFormat(QStringLiteral("text/uri-list"))) { + if (mimeData->hasFormat(QStringLiteral("text/plain")) || mimeData->hasFormat(QStringLiteral("text/uri-list"))) { Q_EMIT sendStringToEmu(dropText.toLocal8Bit()); } @@ -2760,13 +2709,13 @@ void TerminalDisplay::doDrag() _dragInfo.dragObject->exec(Qt::CopyAction); } -void TerminalDisplay::setSessionController(SessionController* controller) +void TerminalDisplay::setSessionController(SessionController *controller) { _sessionController = controller; _headerBar->finishHeaderSetup(controller); } -SessionController* TerminalDisplay::sessionController() +SessionController *TerminalDisplay::sessionController() { return _sessionController; } @@ -2850,8 +2799,12 @@ void TerminalDisplay::printScreen() { auto lprintContent = [this](QPainter &painter, bool friendly) { QPoint columnLines(_usedLines, _usedColumns); - auto lfontget = [this]() { return _terminalFont->getVTFont(); }; - auto lfontset = [this](const QFont &f) { _terminalFont->setVTFont(f); }; + auto lfontget = [this]() { + return _terminalFont->getVTFont(); + }; + auto lfontset = [this](const QFont &f) { + _terminalFont->setVTFont(f); + }; _printManager->printContent(painter, friendly, columnLines, lfontget, lfontset); }; diff --git a/src/terminalDisplay/TerminalDisplay.h b/src/terminalDisplay/TerminalDisplay.h index 9e9332942..932f8d93b 100644 --- a/src/terminalDisplay/TerminalDisplay.h +++ b/src/terminalDisplay/TerminalDisplay.h @@ -17,11 +17,11 @@ // Konsole #include "../characters/Character.h" -#include "konsoleprivate_export.h" -#include "ScreenWindow.h" -#include "colorscheme/ColorScheme.h" #include "Enumeration.h" +#include "ScreenWindow.h" #include "ScrollState.h" +#include "colorscheme/ColorScheme.h" +#include "konsoleprivate_export.h" #include "widgets/TerminalHeaderBar.h" #include "TerminalBell.h" @@ -39,7 +39,8 @@ class QHideEvent; class QTimerEvent; class KMessageWidget; -namespace Konsole { +namespace Konsole +{ class TerminalPainter; class TerminalScrollBar; class TerminalColor; @@ -72,10 +73,10 @@ public: explicit TerminalDisplay(QWidget *parent = nullptr); ~TerminalDisplay() override; - void showDragTarget(const QPoint& cursorPos); + void showDragTarget(const QPoint &cursorPos); void hideDragTarget(); - void applyProfile(const QExplicitlySharedDataPointer& profile); + void applyProfile(const QExplicitlySharedDataPointer &profile); /** * Sets the seed used to generate random colors for the display @@ -155,12 +156,12 @@ public: * Sets the Cursor Style (DECSCUSR) via escape sequences * @p shape cursor shape * @p isBlinking if true, the cursor will be set to blink - */ + */ void setCursorStyle(Enum::CursorShapeEnum shape, bool isBlinking); /** * Resets the cursor style to the current profile cursor shape and * blinking settings - */ + */ void resetCursorStyle(); /** @@ -169,7 +170,7 @@ public: * This will depend upon the height of the widget and the current font. * See fontHeight() */ - int lines() const + int lines() const { return _lines; } @@ -181,7 +182,7 @@ public: * This will depend upon the width of the widget and the current font. * See fontWidth() */ - int columns() const + int columns() const { return _columns; } @@ -217,8 +218,14 @@ public: void resetCursor(); - QRect contentRect() const { return _contentRect; } - bool openLinksByDirectClick() const { return _openLinksByDirectClick; } + QRect contentRect() const + { + return _contentRect; + } + bool openLinksByDirectClick() const + { + return _openLinksByDirectClick; + } /** * Sets the terminal screen section which is displayed in this widget. @@ -369,9 +376,9 @@ public Q_SLOTS: void pasteFromX11Selection(bool appendEnter = false); /** - * Changes whether the flow control warning box should be shown when the flow control - * stop key (Ctrl+S) are pressed. - */ + * Changes whether the flow control warning box should be shown when the flow control + * stop key (Ctrl+S) are pressed. + */ void setFlowControlWarningEnabled(bool enable); /** * Causes the widget to display or hide a message informing the user that terminal @@ -426,7 +433,8 @@ public Q_SLOTS: return _colorScheme; } - Qt::Edge droppedEdge() const { + Qt::Edge droppedEdge() const + { return _overlayEdge; } @@ -442,7 +450,7 @@ public Q_SLOTS: Q_SIGNALS: void requestToggleExpansion(); - void requestMoveToNewTab(TerminalDisplay* display); + void requestMoveToNewTab(TerminalDisplay *display); /** * Emitted when the user presses a key whilst the terminal widget has focus. @@ -484,16 +492,25 @@ Q_SIGNALS: void peekPrimaryRequested(bool doPeek); - void drawContents(Character *image, QPainter &paint, const QRect &rect, bool printerFriendly, int imageSize, bool bidiEnabled, - QVector lineProperties); + void drawContents(Character *image, + QPainter &paint, + const QRect &rect, + bool printerFriendly, + int imageSize, + bool bidiEnabled, + QVector lineProperties); void drawCurrentResultRect(QPainter &painter, QRect searchResultRect); - - void highlightScrolledLines(QPainter& painter, bool isTimerActive, QRect rect); + + void highlightScrolledLines(QPainter &painter, bool isTimerActive, QRect rect); QRegion highlightScrolledLinesRegion(bool nothingChanged, TerminalScrollBar *scrollBar); - + void drawBackground(QPainter &painter, const QRect &rect, const QColor &backgroundColor, bool useOpacitySetting); - void drawCharacters(QPainter &painter, const QRect &rect, const QString &text, - const Character *style, const QColor &characterColor, const LineProperty lineProperty); + void drawCharacters(QPainter &painter, + const QRect &rect, + const QString &text, + const Character *style, + const QColor &characterColor, + const LineProperty lineProperty); void drawInputMethodPreeditString(QPainter &painter, const QRect &rect, TerminalDisplay::InputMethodData &inputMethodData, Character *image); protected: @@ -522,9 +539,7 @@ protected: void dragEnterEvent(QDragEnterEvent *event) override; void dropEvent(QDropEvent *event) override; void doDrag(); - enum DragState { - diNone, diPending, diDragging - }; + enum DragState { diNone, diPending, diDragging, }; struct DragInfo { DragState state; @@ -596,7 +611,7 @@ private: Screen::DecodingOptions currentDecodingOptions(); // Boilerplate setup for MessageWidget - KMessageWidget* createMessageWidget(const QString &text); + KMessageWidget *createMessageWidget(const QString &text); // the window onto the terminal screen which this display // is currently showing. @@ -606,15 +621,15 @@ private: QVBoxLayout *_verticalLayout; - 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 _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 // Character line and character column as per a previous call to // getCharacterPosition() in mouseMoveEvent(). int _prevCharacterLine; int _prevCharacterColumn; - int _usedLines; // the number of lines that are actually being used, this will be less + int _usedLines; // the number of lines that are actually being used, this will be less // than 'lines' if the character image provided with setImage() is smaller // than the maximum image size which can be displayed @@ -639,10 +654,10 @@ private: bool _usesMouseTracking; bool _bracketedPasteMode; - QPoint _iPntSel; // initial selection point - QPoint _pntSel; // current selection point - QPoint _tripleSelBegin; // help avoid flicker - int _actSel; // selection state + QPoint _iPntSel; // initial selection point + QPoint _pntSel; // current selection point + QPoint _tripleSelBegin; // help avoid flicker + int _actSel; // selection state bool _wordSelectionMode; bool _lineSelectionMode; bool _preserveLineBreaks; @@ -655,21 +670,21 @@ private: QString _wordCharacters; TerminalBell _bell; - bool _allowBlinkingText; // allow text to blink - bool _allowBlinkingCursor; // allow cursor to blink - bool _textBlinking; // text is blinking, hide it when drawing - bool _cursorBlinking; // cursor is blinking, hide it when drawing + bool _allowBlinkingText; // allow text to blink + bool _allowBlinkingCursor; // allow cursor to blink + bool _textBlinking; // text is blinking, hide it when drawing + bool _cursorBlinking; // cursor is blinking, hide it when drawing bool _hasTextBlinker; // has characters to blink QTimer *_blinkTextTimer; QTimer *_blinkCursorTimer; - bool _openLinksByDirectClick; // Open URL and hosts by single mouse click + bool _openLinksByDirectClick; // Open URL and hosts by single mouse click bool _ctrlRequiredForDrag; // require Ctrl key for drag selected text bool _dropUrlsAsText; // always paste URLs as text without showing copy/move menu Enum::TripleClickModeEnum _tripleClickMode; - bool _possibleTripleClick; // is set in mouseDoubleClickEvent and deleted + bool _possibleTripleClick; // is set in mouseDoubleClickEvent and deleted // after QApplication::doubleClickInterval() delay QLabel *_resizeWidget; @@ -677,13 +692,13 @@ private: 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 + // 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 KMessageWidget *_outputSuspendedMessageWidget; QSize _size; - ColorScheme const* _colorScheme; + ColorScheme const *_colorScheme; ColorSchemeWallpaper::Ptr _wallpaper; // list of filters currently applied to the display. used for links and @@ -695,20 +710,20 @@ private: InputMethodData _inputMethodData; - //the delay in milliseconds between redrawing blinking text + // the delay in milliseconds between redrawing blinking text static const int TEXT_BLINK_DELAY = 500; - //the duration of the size hint in milliseconds + // the duration of the size hint in milliseconds static const int SIZE_HINT_DURATION = 1000; SessionController *_sessionController; - bool _trimLeadingSpaces; // trim leading spaces in selected text - bool _trimTrailingSpaces; // trim trailing spaces in selected text - bool _mouseWheelZoom; // enable mouse wheel zooming or not + bool _trimLeadingSpaces; // trim leading spaces in selected text + bool _trimTrailingSpaces; // trim trailing spaces in selected text + bool _mouseWheelZoom; // enable mouse wheel zooming or not - int _margin; // the contents margin - bool _centerContents; // center the contents between margins + int _margin; // the contents margin + bool _centerContents; // center the contents between margins KMessageWidget *_readOnlyMessageWidget; // Message shown at the top when read-only mode gets activated diff --git a/src/terminalDisplay/TerminalFonts.cpp b/src/terminalDisplay/TerminalFonts.cpp index 3d5901f6b..08d617677 100644 --- a/src/terminalDisplay/TerminalFonts.cpp +++ b/src/terminalDisplay/TerminalFonts.cpp @@ -11,10 +11,10 @@ // Konsole #include "konsoledebug.h" -#include "terminalDisplay/TerminalDisplay.h" -#include "session/SessionManager.h" -#include "session/SessionController.h" #include "session/Session.h" +#include "session/SessionController.h" +#include "session/SessionManager.h" +#include "terminalDisplay/TerminalDisplay.h" // Qt #include @@ -22,202 +22,197 @@ namespace Konsole { - TerminalFont::TerminalFont(QWidget *parent) - : m_parent(parent) - , m_lineSpacing(0) - , m_fontHeight(1) - , m_fontWidth(1) - , m_fontAscent(1) - , m_boldIntense(false) - , m_antialiasText(true) - , m_useFontLineCharacters(false) - , m_profile(nullptr) - { - } +TerminalFont::TerminalFont(QWidget *parent) + : m_parent(parent) + , m_lineSpacing(0) + , m_fontHeight(1) + , m_fontWidth(1) + , m_fontAscent(1) + , m_boldIntense(false) + , m_antialiasText(true) + , m_useFontLineCharacters(false) + , m_profile(nullptr) +{ +} - void TerminalFont::applyProfile(const Profile::Ptr &profile) - { - m_profile = profile; - m_antialiasText = profile->antiAliasFonts(); - m_boldIntense = profile->boldIntense(); - m_useFontLineCharacters = profile->useFontLineCharacters(); - m_lineSpacing = uint(profile->lineSpacing()); - setVTFont(profile->font()); - } +void TerminalFont::applyProfile(const Profile::Ptr &profile) +{ + m_profile = profile; + m_antialiasText = profile->antiAliasFonts(); + m_boldIntense = profile->boldIntense(); + m_useFontLineCharacters = profile->useFontLineCharacters(); + m_lineSpacing = uint(profile->lineSpacing()); + setVTFont(profile->font()); +} - void TerminalFont::setVTFont(const QFont &f) - { - QFont newFont(f); - int strategy = 0; +void TerminalFont::setVTFont(const QFont &f) +{ + QFont newFont(f); + int strategy = 0; - // hint that text should be drawn with- or without anti-aliasing. - // depending on the user's font configuration, this may not be respected - strategy |= m_antialiasText ? QFont::PreferAntialias : QFont::NoAntialias; + // hint that text should be drawn with- or without anti-aliasing. + // depending on the user's font configuration, this may not be respected + strategy |= m_antialiasText ? QFont::PreferAntialias : QFont::NoAntialias; - // Konsole cannot handle non-integer font metrics + // Konsole cannot handle non-integer font metrics + // TODO: Qt6 will remove ForceIntegerMetrics + // "Use QFontMetrics to retrieve rounded font metrics." + strategy |= QFont::ForceIntegerMetrics; + + // In case the provided font doesn't have some specific characters it should + // fall back to a Monospace fonts. + newFont.setStyleHint(QFont::TypeWriter, QFont::StyleStrategy(strategy)); + + // Try to check that a good font has been loaded. + // For some fonts, ForceIntegerMetrics causes height() == 0 which + // will cause Konsole to crash later. + QFontMetrics fontMetrics2(newFont); + if (fontMetrics2.height() < 1) { + qCDebug(KonsoleDebug) << "The font " << newFont.toString() << " has an invalid height()"; + // Ask for a generic font so at least it is usable. + // Font listed in profile's dialog will not be updated. + newFont = QFont(QStringLiteral("Monospace")); + // Set style strategy without ForceIntegerMetrics for the font // TODO: Qt6 will remove ForceIntegerMetrics // "Use QFontMetrics to retrieve rounded font metrics." - strategy |= QFont::ForceIntegerMetrics; - - // In case the provided font doesn't have some specific characters it should - // fall back to a Monospace fonts. + strategy &= ~QFont::ForceIntegerMetrics; newFont.setStyleHint(QFont::TypeWriter, QFont::StyleStrategy(strategy)); - - // Try to check that a good font has been loaded. - // For some fonts, ForceIntegerMetrics causes height() == 0 which - // will cause Konsole to crash later. - QFontMetrics fontMetrics2(newFont); - if (fontMetrics2.height() < 1) { - qCDebug(KonsoleDebug)<<"The font "<(m_parent)->font()) { - // Do not process the same font again - return; - } - - QFontInfo fontInfo(newFont); - - // QFontInfo::fixedPitch() appears to not match QFont::fixedPitch() - do not test it. - // related? https://bugreports.qt.io/browse/QTBUG-34082 - if (fontInfo.family() != newFont.family() - || !qFuzzyCompare(fontInfo.pointSizeF(), newFont.pointSizeF()) - || fontInfo.styleHint() != newFont.styleHint() - || fontInfo.weight() != newFont.weight() - || fontInfo.style() != newFont.style() - || fontInfo.underline() != newFont.underline() - || fontInfo.strikeOut() != newFont.strikeOut() - || fontInfo.rawMode() != newFont.rawMode()) { - const QString nonMatching = QString::asprintf("%s,%g,%d,%d,%d,%d,%d,%d,%d,%d", - qPrintable(fontInfo.family()), - fontInfo.pointSizeF(), - -1, // pixelSize is not used - static_cast(fontInfo.styleHint()), - fontInfo.weight(), - static_cast(fontInfo.style()), - static_cast(fontInfo.underline()), - static_cast(fontInfo.strikeOut()), - // Intentional newFont use - fixedPitch is bugged, see comment above - static_cast(newFont.fixedPitch()), - static_cast(fontInfo.rawMode())); - qCDebug(KonsoleDebug) << "The font to use in the terminal can not be matched exactly on your system."; - qCDebug(KonsoleDebug) << " Selected: " << newFont.toString(); - qCDebug(KonsoleDebug) << " System : " << nonMatching; - } - - qobject_cast(m_parent)->setFont(newFont); - fontChange(newFont); + qCDebug(KonsoleDebug) << "Font changed to " << newFont.toString(); } - QFont TerminalFont::getVTFont() const - { - return qobject_cast(m_parent)->font(); + // 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. + newFont.setKerning(false); + + // "Draw intense colors in bold font" feature needs to use different font weights. StyleName + // property, when set, doesn't allow weight changes. Since all properties (weight, stretch, + // italic, etc) are stored in QFont independently, in almost all cases styleName is not needed. + newFont.setStyleName(QString()); + + if (newFont == qobject_cast(m_parent)->font()) { + // Do not process the same font again + return; } - void TerminalFont::increaseFontSize() - { - QFont font = qobject_cast(m_parent)->font(); - font.setPointSizeF(font.pointSizeF() + 1); - setVTFont(font); + QFontInfo fontInfo(newFont); + + // QFontInfo::fixedPitch() appears to not match QFont::fixedPitch() - do not test it. + // related? https://bugreports.qt.io/browse/QTBUG-34082 + if (fontInfo.family() != newFont.family() || !qFuzzyCompare(fontInfo.pointSizeF(), newFont.pointSizeF()) || fontInfo.styleHint() != newFont.styleHint() + || fontInfo.weight() != newFont.weight() || fontInfo.style() != newFont.style() || fontInfo.underline() != newFont.underline() + || fontInfo.strikeOut() != newFont.strikeOut() || fontInfo.rawMode() != newFont.rawMode()) { + const QString nonMatching = QString::asprintf("%s,%g,%d,%d,%d,%d,%d,%d,%d,%d", + qPrintable(fontInfo.family()), + fontInfo.pointSizeF(), + -1, // pixelSize is not used + static_cast(fontInfo.styleHint()), + fontInfo.weight(), + static_cast(fontInfo.style()), + static_cast(fontInfo.underline()), + static_cast(fontInfo.strikeOut()), + // Intentional newFont use - fixedPitch is bugged, see comment above + static_cast(newFont.fixedPitch()), + static_cast(fontInfo.rawMode())); + qCDebug(KonsoleDebug) << "The font to use in the terminal can not be matched exactly on your system."; + qCDebug(KonsoleDebug) << " Selected: " << newFont.toString(); + qCDebug(KonsoleDebug) << " System : " << nonMatching; } - void TerminalFont::decreaseFontSize() - { - const qreal MinimumFontSize = 6; + qobject_cast(m_parent)->setFont(newFont); + fontChange(newFont); +} - QFont font = qobject_cast(m_parent)->font(); - font.setPointSizeF(qMax(font.pointSizeF() - 1, MinimumFontSize)); - setVTFont(font); +QFont TerminalFont::getVTFont() const +{ + return qobject_cast(m_parent)->font(); +} + +void TerminalFont::increaseFontSize() +{ + QFont font = qobject_cast(m_parent)->font(); + font.setPointSizeF(font.pointSizeF() + 1); + setVTFont(font); +} + +void TerminalFont::decreaseFontSize() +{ + const qreal MinimumFontSize = 6; + + QFont font = qobject_cast(m_parent)->font(); + font.setPointSizeF(qMax(font.pointSizeF() - 1, MinimumFontSize)); + setVTFont(font); +} + +void TerminalFont::resetFontSize() +{ + const qreal MinimumFontSize = 6; + + TerminalDisplay *display = qobject_cast(m_parent); + QFont font = display->font(); + Profile::Ptr currentProfile = SessionManager::instance()->sessionProfile(display->sessionController()->session()); + const qreal defaultFontSize = currentProfile->font().pointSizeF(); + font.setPointSizeF(qMax(defaultFontSize, MinimumFontSize)); + setVTFont(font); +} + +void TerminalFont::setLineSpacing(uint i) +{ + m_lineSpacing = i; + fontChange(qobject_cast(m_parent)->font()); +} + +uint TerminalFont::lineSpacing() const +{ + return m_lineSpacing; +} + +int TerminalFont::fontHeight() const +{ + return m_fontHeight; +} + +int TerminalFont::fontWidth() const +{ + return m_fontWidth; +} + +int TerminalFont::fontAscent() const +{ + return m_fontAscent; +} + +bool TerminalFont::boldIntense() const +{ + return m_boldIntense; +} + +bool TerminalFont::antialiasText() const +{ + return m_antialiasText; +} + +bool TerminalFont::useFontLineCharacters() const +{ + return m_useFontLineCharacters; +} + +void TerminalFont::fontChange(const QFont &) +{ + QFontMetrics fm(qobject_cast(m_parent)->font()); + m_fontHeight = fm.height() + m_lineSpacing; + + Q_ASSERT(m_fontHeight > 0); + + m_fontWidth = fm.horizontalAdvance(QLatin1Char('M')); + + if (m_fontWidth < 1) { + m_fontWidth = 1; } - void TerminalFont::resetFontSize() - { - const qreal MinimumFontSize = 6; + m_fontAscent = fm.ascent(); - TerminalDisplay *display = qobject_cast(m_parent); - QFont font = display->font(); - Profile::Ptr currentProfile = SessionManager::instance()->sessionProfile(display->sessionController()->session()); - const qreal defaultFontSize = currentProfile->font().pointSizeF(); - font.setPointSizeF(qMax(defaultFontSize, MinimumFontSize)); - setVTFont(font); - } - - void TerminalFont::setLineSpacing(uint i) - { - m_lineSpacing = i; - fontChange(qobject_cast(m_parent)->font()); - } - - uint TerminalFont::lineSpacing() const - { - return m_lineSpacing; - } - - int TerminalFont::fontHeight() const - { - return m_fontHeight; - } - - int TerminalFont::fontWidth() const - { - return m_fontWidth; - } - - int TerminalFont::fontAscent() const - { - return m_fontAscent; - } - - bool TerminalFont::boldIntense() const - { - return m_boldIntense; - } - - bool TerminalFont::antialiasText() const - { - return m_antialiasText; - } - - bool TerminalFont::useFontLineCharacters() const - { - return m_useFontLineCharacters; - } - - void TerminalFont::fontChange(const QFont &) - { - QFontMetrics fm(qobject_cast(m_parent)->font()); - m_fontHeight = fm.height() + m_lineSpacing; - - Q_ASSERT(m_fontHeight > 0); - - m_fontWidth = fm.horizontalAdvance(QLatin1Char('M')); - - if (m_fontWidth < 1) { - m_fontWidth = 1; - } - - m_fontAscent = fm.ascent(); - - qobject_cast(m_parent)->propagateSize(); - } + qobject_cast(m_parent)->propagateSize(); +} } diff --git a/src/terminalDisplay/TerminalFonts.h b/src/terminalDisplay/TerminalFonts.h index 371153e5a..ecdef035a 100644 --- a/src/terminalDisplay/TerminalFonts.h +++ b/src/terminalDisplay/TerminalFonts.h @@ -17,47 +17,46 @@ class QFont; namespace Konsole { +class TerminalFont +{ +public: + explicit TerminalFont(QWidget *parent = nullptr); + ~TerminalFont() = default; - class TerminalFont - { - public: - explicit TerminalFont(QWidget *parent = nullptr); - ~TerminalFont() = default; + void applyProfile(const Profile::Ptr &profile); - void applyProfile(const Profile::Ptr &profile); + void setVTFont(const QFont &f); + QFont getVTFont() const; - void setVTFont(const QFont &f); - QFont getVTFont() const; + void increaseFontSize(); + void decreaseFontSize(); + void resetFontSize(); - void increaseFontSize(); - void decreaseFontSize(); - void resetFontSize(); + void setLineSpacing(uint); + uint lineSpacing() const; - void setLineSpacing(uint); - uint lineSpacing() const; + int fontHeight() const; + int fontWidth() const; + int fontAscent() const; + bool boldIntense() const; + bool antialiasText() const; + bool useFontLineCharacters() const; - int fontHeight() const; - int fontWidth() const; - int fontAscent() const; - bool boldIntense() const; - bool antialiasText() const; - bool useFontLineCharacters() const; +protected: + void fontChange(const QFont &); - protected: - void fontChange(const QFont &); +private: + QWidget *m_parent; + uint m_lineSpacing; + int m_fontHeight; + int m_fontWidth; + int m_fontAscent; + bool m_boldIntense; + bool m_antialiasText; + bool m_useFontLineCharacters; - private: - QWidget *m_parent; - uint m_lineSpacing; - int m_fontHeight; - int m_fontWidth; - int m_fontAscent; - bool m_boldIntense; - bool m_antialiasText; - bool m_useFontLineCharacters; - - Profile::Ptr m_profile; - }; + Profile::Ptr m_profile; +}; } diff --git a/src/terminalDisplay/TerminalPainter.cpp b/src/terminalDisplay/TerminalPainter.cpp index 86468e922..8219b5856 100644 --- a/src/terminalDisplay/TerminalPainter.cpp +++ b/src/terminalDisplay/TerminalPainter.cpp @@ -10,24 +10,24 @@ #include "TerminalPainter.h" // Konsole -#include "TerminalScrollBar.h" #include "../characters/ExtendedCharTable.h" #include "../characters/LineBlockCharacters.h" #include "TerminalColor.h" #include "TerminalFonts.h" +#include "TerminalScrollBar.h" // Qt -#include -#include -#include -#include -#include -#include #include -#include -#include -#include +#include #include +#include +#include +#include +#include +#include +#include +#include +#include #include #include @@ -38,600 +38,600 @@ const QChar LTR_OVERRIDE_CHAR(0x202D); namespace Konsole { +TerminalPainter::TerminalPainter(QObject *parent) + : QObject(parent) +{ +} - TerminalPainter::TerminalPainter(QObject *parent) - : QObject(parent) - {} - - static inline bool isLineCharString(const QString &string) - { - if (string.length() == 0) { - return false; - } - return LineBlockCharacters::canDraw(string.at(0).unicode()); +static inline bool isLineCharString(const QString &string) +{ + if (string.length() == 0) { + return false; } + return LineBlockCharacters::canDraw(string.at(0).unicode()); +} - static int baseCodePoint(const Character &ch) - { - if (ch.rendition & RE_EXTENDED_CHAR) { - ushort extendedCharLength = 0; - const uint *chars = ExtendedCharTable::instance.lookupExtendedChar(ch.character, extendedCharLength); - // FIXME: Coverity-Dereferencing chars, which is known to be nullptr - return chars[0]; - } else { - return ch.character; - } +static int baseCodePoint(const Character &ch) +{ + if (ch.rendition & RE_EXTENDED_CHAR) { + ushort extendedCharLength = 0; + const uint *chars = ExtendedCharTable::instance.lookupExtendedChar(ch.character, extendedCharLength); + // FIXME: Coverity-Dereferencing chars, which is known to be nullptr + return chars[0]; + } else { + return ch.character; } +} - void TerminalPainter::drawContents(Character *image, QPainter &paint, const QRect &rect, - bool printerFriendly, int imageSize, bool bidiEnabled, - QVector lineProperties) - { - const auto display = qobject_cast(sender()); +void TerminalPainter::drawContents(Character *image, + QPainter &paint, + const QRect &rect, + bool printerFriendly, + int imageSize, + bool bidiEnabled, + QVector lineProperties) +{ + const auto display = qobject_cast(sender()); - QVector univec; - univec.reserve(display->usedColumns()); + QVector univec; + univec.reserve(display->usedColumns()); - for (int y = rect.y(); y <= rect.bottom(); y++) { - int x = rect.x(); - bool doubleHeightLinePair = false; + for (int y = rect.y(); y <= rect.bottom(); y++) { + int x = rect.x(); + bool doubleHeightLinePair = false; - // Search for start of multi-column character - if ((image[display->loc(rect.x(), y)].character == 0u) && (x != 0)) { - x--; + // Search for start of multi-column character + if ((image[display->loc(rect.x(), y)].character == 0u) && (x != 0)) { + x--; + } + + for (; x <= rect.right(); x++) { + int len = 1; + + // is this a single character or a sequence of characters ? + if ((image[display->loc(x, y)].rendition & RE_EXTENDED_CHAR) != 0) { + // sequence of characters + ushort extendedCharLength = 0; + const uint *chars = ExtendedCharTable::instance.lookupExtendedChar(image[display->loc(x, y)].character, extendedCharLength); + if (chars != nullptr) { + Q_ASSERT(extendedCharLength > 1); + for (int index = 0; index < extendedCharLength; index++) { + univec << chars[index]; + } + } + } else { + const uint c = image[display->loc(x, y)].character; + if (c != 0u) { + univec << c; + } } - for (; x <= rect.right(); x++) { - int len = 1; + const bool lineDraw = LineBlockCharacters::canDraw(image[display->loc(x, y)].character); + const bool doubleWidth = (image[qMin(display->loc(x, y) + 1, imageSize - 1)].character == 0); + const CharacterColor currentForeground = image[display->loc(x, y)].foregroundColor; + const CharacterColor currentBackground = image[display->loc(x, y)].backgroundColor; + const RenditionFlags currentRendition = image[display->loc(x, y)].rendition; + const QChar::Script currentScript = QChar::script(baseCodePoint(image[display->loc(x, y)])); - // is this a single character or a sequence of characters ? - if ((image[display->loc(x, y)].rendition & RE_EXTENDED_CHAR) != 0) { - // sequence of characters - ushort extendedCharLength = 0; - const uint *chars = ExtendedCharTable::instance.lookupExtendedChar(image[display->loc(x, y)].character, extendedCharLength); - if (chars != nullptr) { - Q_ASSERT(extendedCharLength > 1); - for (int index = 0; index < extendedCharLength; index++) { - univec << chars[index]; - } - } - } else { - const uint c = image[display->loc(x, y)].character; - if (c != 0u) { - univec << c; - } + const auto isInsideDrawArea = [&](int column) { + return column <= rect.right(); + }; + const auto hasSameColors = [&](int column) { + return image[display->loc(column, y)].foregroundColor == currentForeground + && image[display->loc(column, y)].backgroundColor == currentBackground; + }; + const auto hasSameRendition = [&](int column) { + return (image[display->loc(column, y)].rendition & ~RE_EXTENDED_CHAR) == (currentRendition & ~RE_EXTENDED_CHAR); + }; + const auto hasSameWidth = [&](int column) { + const int characterLoc = qMin(display->loc(column, y) + 1, imageSize - 1); + return (image[characterLoc].character == 0) == doubleWidth; + }; + const auto hasSameLineDrawStatus = [&](int column) { + return LineBlockCharacters::canDraw(image[display->loc(column, y)].character) == lineDraw; + }; + const auto isSameScript = [&](int column) { + const QChar::Script script = QChar::script(baseCodePoint(image[display->loc(column, y)])); + if (currentScript == QChar::Script_Common || script == QChar::Script_Common || currentScript == QChar::Script_Inherited + || script == QChar::Script_Inherited) { + return true; } + return currentScript == script; + }; + const auto canBeGrouped = [&](int column) { + return image[display->loc(column, y)].character <= 0x7e || (image[display->loc(column, y)].rendition & RE_EXTENDED_CHAR) + || (bidiEnabled && !doubleWidth); + }; - const bool lineDraw = LineBlockCharacters::canDraw(image[display->loc(x, y)].character); - const bool doubleWidth = (image[qMin(display->loc(x, y) + 1, imageSize - 1)].character == 0); - const CharacterColor currentForeground = image[display->loc(x, y)].foregroundColor; - const CharacterColor currentBackground = image[display->loc(x, y)].backgroundColor; - const RenditionFlags currentRendition = image[display->loc(x, y)].rendition; - const QChar::Script currentScript = QChar::script(baseCodePoint(image[display->loc(x, y)])); - - const auto isInsideDrawArea = [&](int column) { return column <= rect.right(); }; - const auto hasSameColors = [&](int column) { - return image[display->loc(column, y)].foregroundColor == currentForeground - && image[display->loc(column, y)].backgroundColor == currentBackground; - }; - const auto hasSameRendition = [&](int column) { - return (image[display->loc(column, y)].rendition & ~RE_EXTENDED_CHAR) - == (currentRendition & ~RE_EXTENDED_CHAR); - }; - const auto hasSameWidth = [&](int column) { - const int characterLoc = qMin(display->loc(column, y) + 1, imageSize - 1); - return (image[characterLoc].character == 0) == doubleWidth; - }; - const auto hasSameLineDrawStatus = [&](int column) { - return LineBlockCharacters::canDraw(image[display->loc(column, y)].character) - == lineDraw; - }; - const auto isSameScript = [&](int column) { - const QChar::Script script = QChar::script(baseCodePoint(image[display->loc(column, y)])); - if (currentScript == QChar::Script_Common || script == QChar::Script_Common - || currentScript == QChar::Script_Inherited || script == QChar::Script_Inherited) { - return true; - } - return currentScript == script; - }; - const auto canBeGrouped = [&](int column) { - return image[display->loc(column, y)].character <= 0x7e - || (image[display->loc(column, y)].rendition & RE_EXTENDED_CHAR) - || (bidiEnabled && !doubleWidth); - }; - - if (canBeGrouped(x)) { - while (isInsideDrawArea(x + len) && hasSameColors(x + len) - && hasSameRendition(x + len) && hasSameWidth(x + len) - && hasSameLineDrawStatus(x + len) && isSameScript(x + len) - && canBeGrouped(x + len)) { - const uint c = image[display->loc(x + len, y)].character; - if ((image[display->loc(x + len, y)].rendition & RE_EXTENDED_CHAR) != 0) { - // sequence of characters - ushort extendedCharLength = 0; - const uint *chars = ExtendedCharTable::instance.lookupExtendedChar(c, extendedCharLength); - if (chars != nullptr) { - Q_ASSERT(extendedCharLength > 1); - for (int index = 0; index < extendedCharLength; index++) { - univec << chars[index]; - } - } - } else { - // single character - if (c != 0u) { - univec << c; + if (canBeGrouped(x)) { + while (isInsideDrawArea(x + len) && hasSameColors(x + len) && hasSameRendition(x + len) && hasSameWidth(x + len) + && hasSameLineDrawStatus(x + len) && isSameScript(x + len) && canBeGrouped(x + len)) { + const uint c = image[display->loc(x + len, y)].character; + if ((image[display->loc(x + len, y)].rendition & RE_EXTENDED_CHAR) != 0) { + // sequence of characters + ushort extendedCharLength = 0; + const uint *chars = ExtendedCharTable::instance.lookupExtendedChar(c, extendedCharLength); + if (chars != nullptr) { + Q_ASSERT(extendedCharLength > 1); + for (int index = 0; index < extendedCharLength; index++) { + univec << chars[index]; } } - - if (doubleWidth) { - len++; + } else { + // single character + if (c != 0u) { + univec << c; } - len++; } - } else { - // Group spaces following any non-wide character with the character. This allows for - // rendering ambiguous characters with wide glyphs without clipping them. - while (!doubleWidth && isInsideDrawArea(x + len) - && image[display->loc(x + len, y)].character == ' ' && hasSameColors(x + len) - && hasSameRendition(x + len)) { - // univec intentionally not modified - trailing spaces are meaningless - len++; - } - } - // Adjust for trailing part of multi-column character - if ((x + len < display->usedColumns()) && (image[display->loc(x + len, y)].character == 0u)) { + if (doubleWidth) { + len++; + } len++; } - - QMatrix textScale; - bool doubleHeight = false; - bool doubleWidthLine = false; - - if (y < lineProperties.size()) { - if ((lineProperties[y] & LINE_DOUBLEWIDTH) != 0) { - textScale.scale(2, 1); - doubleWidthLine = true; - } - - doubleHeight = lineProperties[y] & (LINE_DOUBLEHEIGHT_TOP | LINE_DOUBLEHEIGHT_BOTTOM); - if (doubleHeight) { - textScale.scale(1, 2); - } - } - - if (y < lineProperties.size() - 1) { - if (((lineProperties[y] & LINE_DOUBLEHEIGHT_TOP) != 0) && ((lineProperties[y+1] & LINE_DOUBLEHEIGHT_BOTTOM) != 0)) { - doubleHeightLinePair = true; - } - } - - // Apply text scaling matrix - paint.setWorldTransform(QTransform(textScale), true); - - // Calculate the area in which the text will be drawn - QRect textArea = QRect(display->contentRect().left() + display->contentsRect().left() + display->terminalFont()->fontWidth() * x * (doubleWidthLine ? 2 : 1), - display->contentRect().top() + display->contentsRect().top() + display->terminalFont()->fontHeight() * y, - display->terminalFont()->fontWidth() * len, - doubleHeight && !doubleHeightLinePair ? display->terminalFont()->fontHeight() / 2 : display->terminalFont()->fontHeight()); - - //move the calculated area to take account of scaling applied to the painter. - //the position of the area from the origin (0,0) is scaled - //by the opposite of whatever - //transformation has been applied to the painter. this ensures that - //painting does actually start from textArea.topLeft() - //(instead of textArea.topLeft() * painter-scale) - textArea.moveTopLeft(textScale.inverted().map(textArea.topLeft())); - - QString unistr = QString::fromUcs4(univec.data(), univec.length()); - - univec.clear(); - - // paint text fragment - if (printerFriendly) { - drawPrinterFriendlyTextFragment(paint, - textArea, - unistr, - &image[display->loc(x, y)], - y < lineProperties.size() ? lineProperties[y] : 0); - } else { - drawTextFragment(paint, - textArea, - unistr, - &image[display->loc(x, y)], - display->terminalColor()->colorTable(), - y < lineProperties.size() ? lineProperties[y] : 0); - } - - paint.setWorldTransform(QTransform(textScale.inverted()), true); - - x += len - 1; - } - - if (doubleHeightLinePair) { - y++; - } - } - } - - void TerminalPainter::drawCurrentResultRect(QPainter &painter, QRect searchResultRect) - { - const auto display = qobject_cast(sender()); - - if (display->screenWindow()->currentResultLine() == -1) { - return; - } - - searchResultRect.setRect(0, display->contentRect().top() + (display->screenWindow()->currentResultLine() - display->screenWindow()->currentLine()) * display->terminalFont()->fontHeight(), - display->columns() * display->terminalFont()->fontWidth(), display->terminalFont()->fontHeight()); - painter.fillRect(searchResultRect, QColor(0, 0, 255, 80)); - } - - void TerminalPainter::highlightScrolledLines(QPainter &painter, bool isTimerActive, QRect rect) - { - const auto display = qobject_cast(sender()); - - QColor color = QColor(display->terminalColor()->colorTable()[Color4Index]); - color.setAlpha(isTimerActive ? 255 : 150); - painter.fillRect(rect, color); - } - - QRegion TerminalPainter::highlightScrolledLinesRegion(bool nothingChanged, TerminalScrollBar* scrollBar) - { - const auto display = qobject_cast(sender()); - - QRegion dirtyRegion; - const int highlightLeftPosition = display->scrollBar()->scrollBarPosition() == Enum::ScrollBarLeft ? display->scrollBar()->width() : 0; - - int start = 0; - int nb_lines = abs(display->screenWindow()->scrollCount()); - if (nb_lines > 0 && display->scrollBar()->maximum() > 0) { - QRect new_highlight; - bool addToCurrentHighlight = scrollBar->highlightScrolledLines().isTimerActive() && - (display->screenWindow()->scrollCount() * scrollBar->highlightScrolledLines().getPreviousScrollCount() > 0); - if (addToCurrentHighlight) { - const int oldScrollCount = scrollBar->highlightScrolledLines().getPreviousScrollCount(); - if (display->screenWindow()->scrollCount() > 0) { - start = -1 * (oldScrollCount + display->screenWindow()->scrollCount()) + display->screenWindow()->windowLines(); - } else { - start = -1 * oldScrollCount; - } - scrollBar->highlightScrolledLines().setPreviousScrollCount(oldScrollCount + display->screenWindow()->scrollCount()); } else { - start = display->screenWindow()->scrollCount() > 0 ? display->screenWindow()->windowLines() - nb_lines : 0; - scrollBar->highlightScrolledLines().setPreviousScrollCount(display->screenWindow()->scrollCount()); + // Group spaces following any non-wide character with the character. This allows for + // rendering ambiguous characters with wide glyphs without clipping them. + while (!doubleWidth && isInsideDrawArea(x + len) && image[display->loc(x + len, y)].character == ' ' && hasSameColors(x + len) + && hasSameRendition(x + len)) { + // univec intentionally not modified - trailing spaces are meaningless + len++; + } } - new_highlight.setRect(highlightLeftPosition, display->contentRect().top() + start * display->terminalFont()->fontHeight(), - scrollBar->highlightScrolledLines().HIGHLIGHT_SCROLLED_LINES_WIDTH, nb_lines * display->terminalFont()->fontHeight()); - new_highlight.setTop(std::max(new_highlight.top(), display->contentRect().top())); - new_highlight.setBottom(std::min(new_highlight.bottom(), display->contentRect().bottom())); - if (!new_highlight.isValid()) { - new_highlight = QRect(0, 0, 0, 0); + // Adjust for trailing part of multi-column character + if ((x + len < display->usedColumns()) && (image[display->loc(x + len, y)].character == 0u)) { + len++; } - if (addToCurrentHighlight) { - scrollBar->highlightScrolledLines().rect() |= new_highlight; + QMatrix textScale; + bool doubleHeight = false; + bool doubleWidthLine = false; + + if (y < lineProperties.size()) { + if ((lineProperties[y] & LINE_DOUBLEWIDTH) != 0) { + textScale.scale(2, 1); + doubleWidthLine = true; + } + + doubleHeight = lineProperties[y] & (LINE_DOUBLEHEIGHT_TOP | LINE_DOUBLEHEIGHT_BOTTOM); + if (doubleHeight) { + textScale.scale(1, 2); + } + } + + if (y < lineProperties.size() - 1) { + if (((lineProperties[y] & LINE_DOUBLEHEIGHT_TOP) != 0) && ((lineProperties[y + 1] & LINE_DOUBLEHEIGHT_BOTTOM) != 0)) { + doubleHeightLinePair = true; + } + } + + // Apply text scaling matrix + paint.setWorldTransform(QTransform(textScale), true); + + // Calculate the area in which the text will be drawn + QRect textArea = + QRect(display->contentRect().left() + display->contentsRect().left() + display->terminalFont()->fontWidth() * x * (doubleWidthLine ? 2 : 1), + display->contentRect().top() + display->contentsRect().top() + display->terminalFont()->fontHeight() * y, + display->terminalFont()->fontWidth() * len, + doubleHeight && !doubleHeightLinePair ? display->terminalFont()->fontHeight() / 2 : display->terminalFont()->fontHeight()); + + // move the calculated area to take account of scaling applied to the painter. + // the position of the area from the origin (0,0) is scaled + // by the opposite of whatever + // transformation has been applied to the painter. this ensures that + // painting does actually start from textArea.topLeft() + //(instead of textArea.topLeft() * painter-scale) + textArea.moveTopLeft(textScale.inverted().map(textArea.topLeft())); + + QString unistr = QString::fromUcs4(univec.data(), univec.length()); + + univec.clear(); + + // paint text fragment + if (printerFriendly) { + drawPrinterFriendlyTextFragment(paint, textArea, unistr, &image[display->loc(x, y)], y < lineProperties.size() ? lineProperties[y] : 0); } else { - dirtyRegion |= scrollBar->highlightScrolledLines().rect(); - scrollBar->highlightScrolledLines().rect() = new_highlight; + drawTextFragment(paint, + textArea, + unistr, + &image[display->loc(x, y)], + display->terminalColor()->colorTable(), + y < lineProperties.size() ? lineProperties[y] : 0); } - dirtyRegion |= new_highlight; - scrollBar->highlightScrolledLines().startTimer(); - } else if (!nothingChanged || scrollBar->highlightScrolledLines().isNeedToClear()) { - dirtyRegion = scrollBar->highlightScrolledLines().rect(); - scrollBar->highlightScrolledLines().rect().setRect(0, 0, 0, 0); - scrollBar->highlightScrolledLines().setNeedToClear(false); + paint.setWorldTransform(QTransform(textScale.inverted()), true); + + x += len - 1; } - return dirtyRegion; + if (doubleHeightLinePair) { + y++; + } + } +} + +void TerminalPainter::drawCurrentResultRect(QPainter &painter, QRect searchResultRect) +{ + const auto display = qobject_cast(sender()); + + if (display->screenWindow()->currentResultLine() == -1) { + return; } - QColor alphaBlend(const QColor &foreground, const QColor &background) { - const auto foregroundAlpha = foreground.alphaF(); - const auto inverseForegroundAlpha = 1.0 - foregroundAlpha; - const auto backgroundAlpha = background.alphaF(); + searchResultRect.setRect(0, + display->contentRect().top() + + (display->screenWindow()->currentResultLine() - display->screenWindow()->currentLine()) + * display->terminalFont()->fontHeight(), + display->columns() * display->terminalFont()->fontWidth(), + display->terminalFont()->fontHeight()); + painter.fillRect(searchResultRect, QColor(0, 0, 255, 80)); +} - if (foregroundAlpha == 0.0) { - return background; - } +void TerminalPainter::highlightScrolledLines(QPainter &painter, bool isTimerActive, QRect rect) +{ + const auto display = qobject_cast(sender()); - if (backgroundAlpha == 1.0) { - return QColor::fromRgb( - (foregroundAlpha*foreground.red()) + (inverseForegroundAlpha*background.red()), - (foregroundAlpha*foreground.green()) + (inverseForegroundAlpha*background.green()), - (foregroundAlpha*foreground.blue()) + (inverseForegroundAlpha*background.blue()), - 0xff - ); + QColor color = QColor(display->terminalColor()->colorTable()[Color4Index]); + color.setAlpha(isTimerActive ? 255 : 150); + painter.fillRect(rect, color); +} + +QRegion TerminalPainter::highlightScrolledLinesRegion(bool nothingChanged, TerminalScrollBar *scrollBar) +{ + const auto display = qobject_cast(sender()); + + QRegion dirtyRegion; + const int highlightLeftPosition = display->scrollBar()->scrollBarPosition() == Enum::ScrollBarLeft ? display->scrollBar()->width() : 0; + + int start = 0; + int nb_lines = abs(display->screenWindow()->scrollCount()); + if (nb_lines > 0 && display->scrollBar()->maximum() > 0) { + QRect new_highlight; + bool addToCurrentHighlight = scrollBar->highlightScrolledLines().isTimerActive() + && (display->screenWindow()->scrollCount() * scrollBar->highlightScrolledLines().getPreviousScrollCount() > 0); + if (addToCurrentHighlight) { + const int oldScrollCount = scrollBar->highlightScrolledLines().getPreviousScrollCount(); + if (display->screenWindow()->scrollCount() > 0) { + start = -1 * (oldScrollCount + display->screenWindow()->scrollCount()) + display->screenWindow()->windowLines(); + } else { + start = -1 * oldScrollCount; + } + scrollBar->highlightScrolledLines().setPreviousScrollCount(oldScrollCount + display->screenWindow()->scrollCount()); } else { - const auto inverseBackgroundAlpha = (backgroundAlpha * inverseForegroundAlpha); - const auto finalAlpha = foregroundAlpha + inverseBackgroundAlpha; - Q_ASSERT(finalAlpha != 0.0); - - return QColor::fromRgb( - (foregroundAlpha*foreground.red()) + (inverseBackgroundAlpha*background.red()), - (foregroundAlpha*foreground.green()) + (inverseBackgroundAlpha*background.green()), - (foregroundAlpha*foreground.blue()) + (inverseBackgroundAlpha*background.blue()), - finalAlpha - ); - } - } - - qreal wcag20AdjustColorPart(qreal v) - { - return v <= 0.03928 ? v/12.92 : qPow((v+0.055)/1.055, 2.4); - } - - qreal wcag20RelativeLuminosity(const QColor &of) - { - auto r = of.redF(), g = of.greenF(), b = of.blueF(); - - const auto a = wcag20AdjustColorPart; - - auto r2 = a(r), g2 = a(g), b2 = a(b); - - return r2 * 0.2126 + g2 * 0.7152 + b2 * 0.0722; - } - - qreal wcag20Contrast(const QColor &c1, const QColor &c2) - { - const auto l1 = wcag20RelativeLuminosity(c1)+0.05, l2 = wcag20RelativeLuminosity(c2)+0.05; - - return (l1 > l2) ? l1/l2 : l2/l1; - } - - std::optional calculateBackgroundColor(const Character* style, const QColor *colorTable) - { - auto c1 = style->backgroundColor.color(colorTable); - if (!(style->rendition & RE_BLEND_SELECTION_COLORS)) { - return c1; + start = display->screenWindow()->scrollCount() > 0 ? display->screenWindow()->windowLines() - nb_lines : 0; + scrollBar->highlightScrolledLines().setPreviousScrollCount(display->screenWindow()->scrollCount()); } - const auto initialBG = c1; - - c1.setAlphaF(0.8); - - const auto blend1 = alphaBlend(c1, colorTable[DEFAULT_FORE_COLOR]), blend2 = alphaBlend(c1, colorTable[DEFAULT_BACK_COLOR]); - const auto fg = style->foregroundColor.color(colorTable); - - const auto contrast1 = wcag20Contrast(fg, blend1), contrast2 = wcag20Contrast(fg, blend2); - const auto contrastBG1 = wcag20Contrast(blend1, initialBG), contrastBG2 = wcag20Contrast(blend2, initialBG); - - const auto fgFactor = 5.5; // if text contrast is too low against our calculated bg, then we flip to reverse - const auto bgFactor = 1.6; // if bg contrast is too low against default bg, then we flip to reverse - - if ((contrast1 < fgFactor && contrast2 < fgFactor) || (contrastBG1 < bgFactor && contrastBG2 < bgFactor)) { - return {}; + new_highlight.setRect(highlightLeftPosition, + display->contentRect().top() + start * display->terminalFont()->fontHeight(), + scrollBar->highlightScrolledLines().HIGHLIGHT_SCROLLED_LINES_WIDTH, + nb_lines * display->terminalFont()->fontHeight()); + new_highlight.setTop(std::max(new_highlight.top(), display->contentRect().top())); + new_highlight.setBottom(std::min(new_highlight.bottom(), display->contentRect().bottom())); + if (!new_highlight.isValid()) { + new_highlight = QRect(0, 0, 0, 0); } - return (contrast1 < contrast2) ? blend1 : blend2; + if (addToCurrentHighlight) { + scrollBar->highlightScrolledLines().rect() |= new_highlight; + } else { + dirtyRegion |= scrollBar->highlightScrolledLines().rect(); + scrollBar->highlightScrolledLines().rect() = new_highlight; + } + dirtyRegion |= new_highlight; + + scrollBar->highlightScrolledLines().startTimer(); + } else if (!nothingChanged || scrollBar->highlightScrolledLines().isNeedToClear()) { + dirtyRegion = scrollBar->highlightScrolledLines().rect(); + scrollBar->highlightScrolledLines().rect().setRect(0, 0, 0, 0); + scrollBar->highlightScrolledLines().setNeedToClear(false); } - void TerminalPainter::drawTextFragment(QPainter &painter, const QRect &rect, const QString &text, - const Character *style, const QColor *colorTable, const LineProperty lineProperty) - { - // setup painter - QColor foregroundColor = style->foregroundColor.color(colorTable); - const QColor backgroundColor = calculateBackgroundColor(style, colorTable).value_or(foregroundColor); - if (backgroundColor == foregroundColor) { - foregroundColor = style->backgroundColor.color(colorTable); - } + return dirtyRegion; +} - if (backgroundColor != colorTable[DEFAULT_BACK_COLOR]) { - drawBackground(painter, rect, backgroundColor, false); - } +QColor alphaBlend(const QColor &foreground, const QColor &background) +{ + const auto foregroundAlpha = foreground.alphaF(); + const auto inverseForegroundAlpha = 1.0 - foregroundAlpha; + const auto backgroundAlpha = background.alphaF(); - QColor characterColor = foregroundColor; - if ((style->rendition & RE_CURSOR) != 0) { - drawCursor(painter, rect, foregroundColor, backgroundColor, characterColor); - } - - // draw text - drawCharacters(painter, rect, text, style, characterColor, lineProperty); + if (foregroundAlpha == 0.0) { + return background; } - void TerminalPainter::drawPrinterFriendlyTextFragment(QPainter &painter, const QRect &rect, const QString &text, - const Character *style, const LineProperty lineProperty) - { - Character print_style = *style; - print_style.foregroundColor = CharacterColor(COLOR_SPACE_RGB, 0x00000000); - print_style.backgroundColor = CharacterColor(COLOR_SPACE_RGB, 0xFFFFFFFF); + if (backgroundAlpha == 1.0) { + return QColor::fromRgb((foregroundAlpha * foreground.red()) + (inverseForegroundAlpha * background.red()), + (foregroundAlpha * foreground.green()) + (inverseForegroundAlpha * background.green()), + (foregroundAlpha * foreground.blue()) + (inverseForegroundAlpha * background.blue()), + 0xff); + } else { + const auto inverseBackgroundAlpha = (backgroundAlpha * inverseForegroundAlpha); + const auto finalAlpha = foregroundAlpha + inverseBackgroundAlpha; + Q_ASSERT(finalAlpha != 0.0); - drawCharacters(painter, rect, text, &print_style, QColor(), lineProperty); + return QColor::fromRgb((foregroundAlpha * foreground.red()) + (inverseBackgroundAlpha * background.red()), + (foregroundAlpha * foreground.green()) + (inverseBackgroundAlpha * background.green()), + (foregroundAlpha * foreground.blue()) + (inverseBackgroundAlpha * background.blue()), + finalAlpha); + } +} + +qreal wcag20AdjustColorPart(qreal v) +{ + return v <= 0.03928 ? v / 12.92 : qPow((v + 0.055) / 1.055, 2.4); +} + +qreal wcag20RelativeLuminosity(const QColor &of) +{ + auto r = of.redF(), g = of.greenF(), b = of.blueF(); + + const auto a = wcag20AdjustColorPart; + + auto r2 = a(r), g2 = a(g), b2 = a(b); + + return r2 * 0.2126 + g2 * 0.7152 + b2 * 0.0722; +} + +qreal wcag20Contrast(const QColor &c1, const QColor &c2) +{ + const auto l1 = wcag20RelativeLuminosity(c1) + 0.05, l2 = wcag20RelativeLuminosity(c2) + 0.05; + + return (l1 > l2) ? l1 / l2 : l2 / l1; +} + +std::optional calculateBackgroundColor(const Character *style, const QColor *colorTable) +{ + auto c1 = style->backgroundColor.color(colorTable); + if (!(style->rendition & RE_BLEND_SELECTION_COLORS)) { + return c1; } - void TerminalPainter::drawBackground(QPainter &painter, const QRect &rect, const QColor &backgroundColor, - bool useOpacitySetting) - { - const auto display = qobject_cast(sender()); + const auto initialBG = c1; - if (useOpacitySetting && !display->wallpaper()->isNull() && - display->wallpaper()->draw(painter, rect, display->terminalColor()->opacity())) { - } else if (qAlpha(display->terminalColor()->blendColor()) < 0xff && useOpacitySetting) { + c1.setAlphaF(0.8); + + const auto blend1 = alphaBlend(c1, colorTable[DEFAULT_FORE_COLOR]), blend2 = alphaBlend(c1, colorTable[DEFAULT_BACK_COLOR]); + const auto fg = style->foregroundColor.color(colorTable); + + const auto contrast1 = wcag20Contrast(fg, blend1), contrast2 = wcag20Contrast(fg, blend2); + const auto contrastBG1 = wcag20Contrast(blend1, initialBG), contrastBG2 = wcag20Contrast(blend2, initialBG); + + const auto fgFactor = 5.5; // if text contrast is too low against our calculated bg, then we flip to reverse + const auto bgFactor = 1.6; // if bg contrast is too low against default bg, then we flip to reverse + + if ((contrast1 < fgFactor && contrast2 < fgFactor) || (contrastBG1 < bgFactor && contrastBG2 < bgFactor)) { + return {}; + } + + return (contrast1 < contrast2) ? blend1 : blend2; +} + +void TerminalPainter::drawTextFragment(QPainter &painter, + const QRect &rect, + const QString &text, + const Character *style, + const QColor *colorTable, + const LineProperty lineProperty) +{ + // setup painter + QColor foregroundColor = style->foregroundColor.color(colorTable); + const QColor backgroundColor = calculateBackgroundColor(style, colorTable).value_or(foregroundColor); + if (backgroundColor == foregroundColor) { + foregroundColor = style->backgroundColor.color(colorTable); + } + + if (backgroundColor != colorTable[DEFAULT_BACK_COLOR]) { + drawBackground(painter, rect, backgroundColor, false); + } + + QColor characterColor = foregroundColor; + if ((style->rendition & RE_CURSOR) != 0) { + drawCursor(painter, rect, foregroundColor, backgroundColor, characterColor); + } + + // draw text + drawCharacters(painter, rect, text, style, characterColor, lineProperty); +} + +void TerminalPainter::drawPrinterFriendlyTextFragment(QPainter &painter, + const QRect &rect, + const QString &text, + const Character *style, + const LineProperty lineProperty) +{ + Character print_style = *style; + print_style.foregroundColor = CharacterColor(COLOR_SPACE_RGB, 0x00000000); + print_style.backgroundColor = CharacterColor(COLOR_SPACE_RGB, 0xFFFFFFFF); + + drawCharacters(painter, rect, text, &print_style, QColor(), lineProperty); +} + +void TerminalPainter::drawBackground(QPainter &painter, const QRect &rect, const QColor &backgroundColor, bool useOpacitySetting) +{ + const auto display = qobject_cast(sender()); + + if (useOpacitySetting && !display->wallpaper()->isNull() && display->wallpaper()->draw(painter, rect, display->terminalColor()->opacity())) { + } else if (qAlpha(display->terminalColor()->blendColor()) < 0xff && useOpacitySetting) { #if defined(Q_OS_MACOS) - // TODO: On MacOS, using CompositionMode doesn't work. Altering the - // transparency in the color scheme alters the brightness. - painter.fillRect(rect, backgroundColor); + // TODO: On MacOS, using CompositionMode doesn't work. Altering the + // transparency in the color scheme alters the brightness. + painter.fillRect(rect, backgroundColor); #else - QColor color(backgroundColor); - color.setAlpha(qAlpha(display->terminalColor()->blendColor())); + QColor color(backgroundColor); + color.setAlpha(qAlpha(display->terminalColor()->blendColor())); - const QPainter::CompositionMode originalMode = painter.compositionMode(); - painter.setCompositionMode(QPainter::CompositionMode_Source); - painter.fillRect(rect, color); - painter.setCompositionMode(originalMode); + const QPainter::CompositionMode originalMode = painter.compositionMode(); + painter.setCompositionMode(QPainter::CompositionMode_Source); + painter.fillRect(rect, color); + painter.setCompositionMode(originalMode); #endif + } else { + painter.fillRect(rect, backgroundColor); + } +} + +void TerminalPainter::drawCursor(QPainter &painter, const QRect &rect, const QColor &foregroundColor, const QColor &backgroundColor, QColor &characterColor) +{ + const auto display = qobject_cast(sender()); + + if (display->cursorBlinking()) { + return; + } + + QRectF cursorRect = rect.adjusted(0, 1, 0, 0); + + QColor color = display->terminalColor()->cursorColor(); + QColor cursorColor = color.isValid() ? color : foregroundColor; + + QPen pen(cursorColor); + // TODO: the relative pen width to draw the cursor is a bit hacky + // and set to 1/12 of the font width. Visually it seems to work at + // all scales but there must be better ways to do it + const qreal width = qMax(display->terminalFont()->fontWidth() / 12.0, 1.0); + const qreal halfWidth = width / 2.0; + pen.setWidthF(width); + painter.setPen(pen); + + if (display->cursorShape() == Enum::BlockCursor) { + painter.drawRect(cursorRect.adjusted(halfWidth, halfWidth, -halfWidth, -halfWidth)); + + if (display->hasFocus()) { + painter.fillRect(cursorRect, cursorColor); + + QColor cursorTextColor = display->terminalColor()->cursorTextColor(); + characterColor = cursorTextColor.isValid() ? cursorTextColor : backgroundColor; + } + } else if (display->cursorShape() == Enum::UnderlineCursor) { + QLineF line(cursorRect.left() + halfWidth, cursorRect.bottom() - halfWidth, cursorRect.right() - halfWidth, cursorRect.bottom() - halfWidth); + painter.drawLine(line); + + } else if (display->cursorShape() == Enum::IBeamCursor) { + QLineF line(cursorRect.left() + halfWidth, cursorRect.top() + halfWidth, cursorRect.left() + halfWidth, cursorRect.bottom() - halfWidth); + painter.drawLine(line); + } +} + +void TerminalPainter::drawCharacters(QPainter &painter, + const QRect &rect, + const QString &text, + const Character *style, + const QColor &characterColor, + const LineProperty lineProperty) +{ + const auto display = qobject_cast(sender()); + + if (display->textBlinking() && ((style->rendition & RE_BLINK) != 0)) { + return; + } + + if ((style->rendition & RE_CONCEAL) != 0) { + return; + } + + static constexpr int MaxFontWeight = 99; + + const int normalWeight = display->font().weight(); + + const int boldWeight = qMin(normalWeight + 26, MaxFontWeight); + + const auto isBold = [boldWeight](const QFont &font) { + return font.weight() >= boldWeight; + }; + + const bool useBold = (((style->rendition & RE_BOLD) != 0) && display->terminalFont()->boldIntense()); + const bool useUnderline = ((style->rendition & RE_UNDERLINE) != 0) || display->font().underline(); + const bool useItalic = ((style->rendition & RE_ITALIC) != 0) || display->font().italic(); + const bool useStrikeOut = ((style->rendition & RE_STRIKEOUT) != 0) || display->font().strikeOut(); + const bool useOverline = ((style->rendition & RE_OVERLINE) != 0) || display->font().overline(); + + QFont currentFont = painter.font(); + + if (isBold(currentFont) != useBold || currentFont.underline() != useUnderline || currentFont.italic() != useItalic + || currentFont.strikeOut() != useStrikeOut || currentFont.overline() != useOverline) { + currentFont.setWeight(useBold ? boldWeight : normalWeight); + currentFont.setUnderline(useUnderline); + currentFont.setItalic(useItalic); + currentFont.setStrikeOut(useStrikeOut); + currentFont.setOverline(useOverline); + painter.setFont(currentFont); + } + + // setup pen + const QColor foregroundColor = style->foregroundColor.color(display->terminalColor()->colorTable()); + const QColor color = characterColor.isValid() ? characterColor : foregroundColor; + QPen pen = painter.pen(); + if (pen.color() != color) { + pen.setColor(color); + painter.setPen(color); + } + + const bool origClipping = painter.hasClipping(); + const auto origClipRegion = painter.clipRegion(); + painter.setClipRect(rect); + // draw text + if (isLineCharString(text) && !display->terminalFont()->useFontLineCharacters()) { + int y = rect.y(); + + if (lineProperty & LINE_DOUBLEHEIGHT_BOTTOM) { + y -= display->terminalFont()->fontHeight() / 2; + } + + drawLineCharString(display, painter, rect.x(), y, text, style); + } else { + painter.setLayoutDirection(Qt::LeftToRight); + int y = rect.y() + display->terminalFont()->fontAscent(); + + if (lineProperty & LINE_DOUBLEHEIGHT_BOTTOM) { + y -= display->terminalFont()->fontHeight() / 2; } else { - painter.fillRect(rect, backgroundColor); - } - } - - void TerminalPainter::drawCursor(QPainter &painter, const QRect &rect, const QColor &foregroundColor, - const QColor &backgroundColor, QColor &characterColor) - { - const auto display = qobject_cast(sender()); - - if (display->cursorBlinking()) { - return; + y += display->terminalFont()->lineSpacing(); } - QRectF cursorRect = rect.adjusted(0, 1, 0, 0); - - QColor color = display->terminalColor()->cursorColor(); - QColor cursorColor = color.isValid() ? color : foregroundColor; - - QPen pen(cursorColor); - // TODO: the relative pen width to draw the cursor is a bit hacky - // and set to 1/12 of the font width. Visually it seems to work at - // all scales but there must be better ways to do it - const qreal width = qMax(display->terminalFont()->fontWidth() / 12.0, 1.0); - const qreal halfWidth = width / 2.0; - pen.setWidthF(width); - painter.setPen(pen); - - if (display->cursorShape() == Enum::BlockCursor) { - painter.drawRect(cursorRect.adjusted(halfWidth, halfWidth, -halfWidth, -halfWidth)); - - if (display->hasFocus()) { - painter.fillRect(cursorRect, cursorColor); - - QColor cursorTextColor = display->terminalColor()->cursorTextColor(); - characterColor = cursorTextColor.isValid() ? cursorTextColor : backgroundColor; - } - } else if (display->cursorShape() == Enum::UnderlineCursor) { - QLineF line(cursorRect.left() + halfWidth, - cursorRect.bottom() - halfWidth, - cursorRect.right() - halfWidth, - cursorRect.bottom() - halfWidth); - painter.drawLine(line); - - } else if (display->cursorShape() == Enum::IBeamCursor) { - QLineF line(cursorRect.left() + halfWidth, - cursorRect.top() + halfWidth, - cursorRect.left() + halfWidth, - cursorRect.bottom() - halfWidth); - painter.drawLine(line); - } - } - - void TerminalPainter::drawCharacters(QPainter &painter, const QRect &rect, const QString &text, - const Character *style, const QColor &characterColor, const LineProperty lineProperty) - { - const auto display = qobject_cast(sender()); - - if (display->textBlinking() && ((style->rendition & RE_BLINK) != 0)) { - return; - } - - if ((style->rendition & RE_CONCEAL) != 0) { - return; - } - - static constexpr int MaxFontWeight = 99; - - const int normalWeight = display->font().weight(); - - const int boldWeight = qMin(normalWeight + 26, MaxFontWeight); - - const auto isBold = [boldWeight](const QFont &font) { return font.weight() >= boldWeight; }; - - const bool useBold = (((style->rendition & RE_BOLD) != 0) && display->terminalFont()->boldIntense()); - const bool useUnderline = ((style->rendition & RE_UNDERLINE) != 0) || display->font().underline(); - const bool useItalic = ((style->rendition & RE_ITALIC) != 0) || display->font().italic(); - const bool useStrikeOut = ((style->rendition & RE_STRIKEOUT) != 0) || display->font().strikeOut(); - const bool useOverline = ((style->rendition & RE_OVERLINE) != 0) || display->font().overline(); - - QFont currentFont = painter.font(); - - if (isBold(currentFont) != useBold - || currentFont.underline() != useUnderline - || currentFont.italic() != useItalic - || currentFont.strikeOut() != useStrikeOut - || currentFont.overline() != useOverline) { - - currentFont.setWeight(useBold ? boldWeight : normalWeight); - currentFont.setUnderline(useUnderline); - currentFont.setItalic(useItalic); - currentFont.setStrikeOut(useStrikeOut); - currentFont.setOverline(useOverline); - painter.setFont(currentFont); - } - - // setup pen - const QColor foregroundColor = style->foregroundColor.color(display->terminalColor()->colorTable()); - const QColor color = characterColor.isValid() ? characterColor : foregroundColor; - QPen pen = painter.pen(); - if (pen.color() != color) { - pen.setColor(color); - painter.setPen(color); - } - - const bool origClipping = painter.hasClipping(); - const auto origClipRegion = painter.clipRegion(); - painter.setClipRect(rect); - // draw text - if (isLineCharString(text) && !display->terminalFont()->useFontLineCharacters()) { - int y = rect.y(); - - if (lineProperty & LINE_DOUBLEHEIGHT_BOTTOM) { - y -= display->terminalFont()->fontHeight() / 2; - } - - drawLineCharString(display, painter, rect.x(), y, text, style); + if (display->bidiEnabled()) { + painter.drawText(rect.x(), y, text); } else { - painter.setLayoutDirection(Qt::LeftToRight); - int y = rect.y() + display->terminalFont()->fontAscent(); - - if (lineProperty & LINE_DOUBLEHEIGHT_BOTTOM) { - y -= display->terminalFont()->fontHeight() / 2; - } else { - y += display->terminalFont()->lineSpacing(); - } - - if (display->bidiEnabled()) { - painter.drawText(rect.x(), y, text); - } else { - painter.drawText(rect.x(), y, LTR_OVERRIDE_CHAR + text); - } + painter.drawText(rect.x(), y, LTR_OVERRIDE_CHAR + text); } - painter.setClipRegion(origClipRegion); - painter.setClipping(origClipping); + } + painter.setClipRegion(origClipRegion); + painter.setClipping(origClipping); +} + +void TerminalPainter::drawLineCharString(TerminalDisplay *display, QPainter &painter, int x, int y, const QString &str, const Character *attributes) +{ + painter.setRenderHint(QPainter::Antialiasing, display->terminalFont()->antialiasText()); + + const bool useBoldPen = (attributes->rendition & RE_BOLD) != 0 && display->terminalFont()->boldIntense(); + + QRect cellRect = {x, y, display->terminalFont()->fontWidth(), display->terminalFont()->fontHeight()}; + for (int i = 0; i < str.length(); i++) { + LineBlockCharacters::draw(painter, cellRect.translated(i * display->terminalFont()->fontWidth(), 0), str[i], useBoldPen); + } + painter.setRenderHint(QPainter::Antialiasing, false); +} + +void TerminalPainter::drawInputMethodPreeditString(QPainter &painter, const QRect &rect, TerminalDisplay::InputMethodData &inputMethodData, Character *image) +{ + const auto display = qobject_cast(sender()); + + if (inputMethodData.preeditString.isEmpty() || !display->isCursorOnDisplay()) { + return; } - void TerminalPainter::drawLineCharString(TerminalDisplay *display, QPainter &painter, int x, int y, const QString &str, const Character *attributes) - { - painter.setRenderHint(QPainter::Antialiasing, display->terminalFont()->antialiasText()); + const QPoint cursorPos = display->cursorPosition(); - const bool useBoldPen = (attributes->rendition & RE_BOLD) != 0 && display->terminalFont()->boldIntense(); + QColor characterColor; + const QColor background = display->terminalColor()->colorTable()[DEFAULT_BACK_COLOR]; + const QColor foreground = display->terminalColor()->colorTable()[DEFAULT_FORE_COLOR]; + const Character *style = &image[display->loc(cursorPos.x(), cursorPos.y())]; - QRect cellRect = {x, y, display->terminalFont()->fontWidth(), display->terminalFont()->fontHeight()}; - for (int i = 0; i < str.length(); i++) { - LineBlockCharacters::draw(painter, cellRect.translated(i * display->terminalFont()->fontWidth(), 0), str[i], useBoldPen); - } - painter.setRenderHint(QPainter::Antialiasing, false); - } + drawBackground(painter, rect, background, true); + drawCursor(painter, rect, foreground, background, characterColor); + drawCharacters(painter, rect, inputMethodData.preeditString, style, characterColor, 0); - void TerminalPainter::drawInputMethodPreeditString(QPainter &painter, const QRect &rect, TerminalDisplay::InputMethodData &inputMethodData, Character *image) - { - const auto display = qobject_cast(sender()); - - if (inputMethodData.preeditString.isEmpty() || !display->isCursorOnDisplay()) { - return; - } - - const QPoint cursorPos = display->cursorPosition(); - - QColor characterColor; - const QColor background = display->terminalColor()->colorTable()[DEFAULT_BACK_COLOR]; - const QColor foreground = display->terminalColor()->colorTable()[DEFAULT_FORE_COLOR]; - const Character *style = &image[display->loc(cursorPos.x(), cursorPos.y())]; - - drawBackground(painter, rect, background, true); - drawCursor(painter, rect, foreground, background, characterColor); - drawCharacters(painter, rect, inputMethodData.preeditString, style, characterColor, 0); - - inputMethodData.previousPreeditRect = rect; - } + inputMethodData.previousPreeditRect = rect; +} } diff --git a/src/terminalDisplay/TerminalPainter.h b/src/terminalDisplay/TerminalPainter.h index 50e34fe06..12580b7d9 100644 --- a/src/terminalDisplay/TerminalPainter.h +++ b/src/terminalDisplay/TerminalPainter.h @@ -10,15 +10,15 @@ #define TERMINALPAINTER_HPP // Qt -#include -#include #include #include +#include +#include // Konsole #include "../characters/Character.h" -#include "ScreenWindow.h" #include "Enumeration.h" +#include "ScreenWindow.h" #include "colorscheme/ColorSchemeWallpaper.h" #include "profile/Profile.h" #include "terminalDisplay/TerminalDisplay.h" @@ -32,65 +32,74 @@ class QTimer; namespace Konsole { +class Character; +class TerminalDisplay; - class Character; - class TerminalDisplay; - - class TerminalPainter : public QObject - { - public: - explicit TerminalPainter(QObject *parent = nullptr); - ~TerminalPainter() = default; +class TerminalPainter : public QObject +{ +public: + explicit TerminalPainter(QObject *parent = nullptr); + ~TerminalPainter() = default; - public Q_SLOTS: - // -- Drawing helpers -- +public Q_SLOTS: + // -- Drawing helpers -- - // divides the part of the display specified by 'rect' into - // fragments according to their colors and styles and calls - // drawTextFragment() or drawPrinterFriendlyTextFragment() - // to draw the fragments - void drawContents(Character *image, QPainter &paint, const QRect &rect, bool PrinterFriendly, int imageSize, bool bidiEnabled, - QVector lineProperties); - - // draw a transparent rectangle over the line of the current match - void drawCurrentResultRect(QPainter &painter, QRect searchResultRect); + // divides the part of the display specified by 'rect' into + // fragments according to their colors and styles and calls + // drawTextFragment() or drawPrinterFriendlyTextFragment() + // to draw the fragments + void drawContents(Character *image, + QPainter &paint, + const QRect &rect, + bool PrinterFriendly, + int imageSize, + bool bidiEnabled, + QVector lineProperties); - // draw a thin highlight on the left of the screen for lines that have been scrolled into view - void highlightScrolledLines(QPainter &painter, bool isTimerActive, QRect rect); + // draw a transparent rectangle over the line of the current match + void drawCurrentResultRect(QPainter &painter, QRect searchResultRect); - // compute which region need to be repainted for scrolled lines highlight - QRegion highlightScrolledLinesRegion(bool nothingChanged, TerminalScrollBar *scrollBar); + // draw a thin highlight on the left of the screen for lines that have been scrolled into view + void highlightScrolledLines(QPainter &painter, bool isTimerActive, QRect rect); - // 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 &backgroundColor, - bool useOpacitySetting); + // compute which region need to be repainted for scrolled lines highlight + QRegion highlightScrolledLinesRegion(bool nothingChanged, TerminalScrollBar *scrollBar); - // draws the characters or line graphics in a text fragment - void drawCharacters(QPainter &painter, const QRect &rect, const QString &text, - const Character *style, const QColor &characterColor, const LineProperty lineProperty); + // 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 &backgroundColor, bool useOpacitySetting); - // draws the preedit string for input methods - void drawInputMethodPreeditString(QPainter &painter, const QRect &rect, TerminalDisplay::InputMethodData &inputMethodData, Character *image); - - private: - // draws a string of line graphics - void drawLineCharString(TerminalDisplay *display, QPainter &painter, int x, int y, const QString &str, const Character *attributes); - - // 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, const QColor *colorTable, const LineProperty lineProperty); - - void drawPrinterFriendlyTextFragment(QPainter &painter, const QRect &rect, const QString &text, - const Character *style, const LineProperty lineProperty); + // draws the characters or line graphics in a text fragment + void drawCharacters(QPainter &painter, + const QRect &rect, + const QString &text, + const Character *style, + const QColor &characterColor, + const LineProperty lineProperty); - // draws the cursor character - void drawCursor(QPainter &painter, const QRect &rect, const QColor &foregroundColor, - const QColor &backgroundColor, QColor &characterColor); - }; + // draws the preedit string for input methods + void drawInputMethodPreeditString(QPainter &painter, const QRect &rect, TerminalDisplay::InputMethodData &inputMethodData, Character *image); + +private: + // draws a string of line graphics + void drawLineCharString(TerminalDisplay *display, QPainter &painter, int x, int y, const QString &str, const Character *attributes); + + // 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, + const QColor *colorTable, + const LineProperty lineProperty); + + void drawPrinterFriendlyTextFragment(QPainter &painter, const QRect &rect, const QString &text, const Character *style, const LineProperty lineProperty); + + // draws the cursor character + void drawCursor(QPainter &painter, const QRect &rect, const QColor &foregroundColor, const QColor &backgroundColor, QColor &characterColor); +}; } diff --git a/src/terminalDisplay/TerminalScrollBar.cpp b/src/terminalDisplay/TerminalScrollBar.cpp index 8ba45dd12..8ea1ab8c6 100644 --- a/src/terminalDisplay/TerminalScrollBar.cpp +++ b/src/terminalDisplay/TerminalScrollBar.cpp @@ -10,214 +10,209 @@ #include "TerminalScrollBar.h" // Konsole +#include "../characters/Character.h" #include "TerminalDisplay.h" #include "TerminalFonts.h" -#include "session/SessionController.h" -#include "../characters/Character.h" #include "extras/HighlightScrolledLines.h" +#include "session/SessionController.h" // KDE #include // Qt +#include #include #include -#include namespace Konsole { - TerminalScrollBar::TerminalScrollBar(QWidget *parent) - : QScrollBar(parent) - , _scrollFullPage(false) - , _alternateScrolling(false) - , _scrollbarLocation(Enum::ScrollBarRight) - { - connect(this, &QScrollBar::valueChanged, this, &TerminalScrollBar::scrollBarPositionChanged); +TerminalScrollBar::TerminalScrollBar(QWidget *parent) + : QScrollBar(parent) + , _scrollFullPage(false) + , _alternateScrolling(false) + , _scrollbarLocation(Enum::ScrollBarRight) +{ + connect(this, &QScrollBar::valueChanged, this, &TerminalScrollBar::scrollBarPositionChanged); +} + +void TerminalScrollBar::setScrollBarPosition(Enum::ScrollBarPositionEnum position) +{ + if (_scrollbarLocation == position) { + return; } - void TerminalScrollBar::setScrollBarPosition(Enum::ScrollBarPositionEnum position) - { - if (_scrollbarLocation == position) { - return; - } + _scrollbarLocation = position; + applyScrollBarPosition(true); +} - _scrollbarLocation = position; - applyScrollBarPosition(true); - } - - void TerminalScrollBar::setScroll(int cursor, int slines) - { - const auto display = qobject_cast(this->parent()); - // update _scrollBar if the range or value has changed, - // otherwise return - // - // setting the range or value of a _scrollBar will always trigger - // a repaint, so it should be avoided if it is not necessary - if (this->minimum() == 0 && - this->maximum() == (slines - display->lines()) && - this->value() == cursor) { - return; - } - - disconnect(this, &QScrollBar::valueChanged, this, &TerminalScrollBar::scrollBarPositionChanged); - setRange(0, slines - display->lines()); - setSingleStep(1); - setPageStep(display->lines()); - setValue(cursor); - connect(this, &QScrollBar::valueChanged, this, &TerminalScrollBar::scrollBarPositionChanged); - } - - void TerminalScrollBar::setScrollFullPage(bool fullPage) - { - _scrollFullPage = fullPage; - } - - bool TerminalScrollBar::scrollFullPage() const - { - return _scrollFullPage; - } - - void TerminalScrollBar::setHighlightScrolledLines(bool highlight) - { - _highlightScrolledLines.setEnabled(highlight); - _highlightScrolledLines.setTimer(this); - _highlightScrolledLines.setNeedToClear(true); - } - - bool TerminalScrollBar::alternateScrolling() const - { - return _alternateScrolling; - } - - void TerminalScrollBar::setAlternateScrolling(bool enable) - { - _alternateScrolling = enable; - } - - void TerminalScrollBar::scrollBarPositionChanged(int) - { - const auto display = qobject_cast(this->parent()); - - if (display->screenWindow().isNull()) { - return; - } - - display->screenWindow()->scrollTo(this->value()); - - // if the thumb has been moved to the bottom of the _scrollBar then set - // the display to automatically track new output, - // that is, scroll down automatically - // to how new _lines as they are added - const bool atEndOfOutput = (this->value() == this->maximum()); - display->screenWindow()->setTrackOutput(atEndOfOutput); - - display->updateImage(); - } - - void TerminalScrollBar::highlightScrolledLinesEvent() - { - const auto display = qobject_cast(this->parent()); - display->update(_highlightScrolledLines.rect()); - } - - void TerminalScrollBar::applyScrollBarPosition(bool propagate) - { - setHidden(_scrollbarLocation == Enum::ScrollBarHidden); - - if (propagate) { - const auto display = qobject_cast(this->parent()); - display->propagateSize(); - display->update(); - } - } - - // scrolls the image by 'lines', down if lines > 0 or up otherwise. +void TerminalScrollBar::setScroll(int cursor, int slines) +{ + const auto display = qobject_cast(this->parent()); + // update _scrollBar if the range or value has changed, + // otherwise return // - // the terminal emulation keeps track of the scrolling of the character - // image as it receives input, and when the view is updated, it calls scrollImage() - // with the final scroll amount. this improves performance because scrolling the - // display is much cheaper than re-rendering all the text for the - // part of the image which has moved up or down. - // Instead only new lines have to be drawn - void TerminalScrollBar::scrollImage(int lines, const QRect &screenWindowRegion, Character *image, int imageSize) - { - // return if there is nothing to do - if ((lines == 0) || (image == nullptr)) { - return; - } - - const auto display = qobject_cast(this->parent()); - // 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(), display->lines() - 2)); - - // return if there is nothing to do - if (!region.isValid() || (region.top() + abs(lines)) >= region.bottom() || display->lines() <= region.bottom()) { - return; - } - - // 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. - // - const int scrollBarWidth = this->isHidden() ? 0 : this->width(); - const int SCROLLBAR_CONTENT_GAP = 1; - QRect scrollRect; - if (_scrollbarLocation == Enum::ScrollBarLeft) { - scrollRect.setLeft(scrollBarWidth + SCROLLBAR_CONTENT_GAP + (_highlightScrolledLines.isEnabled() ? - _highlightScrolledLines.HIGHLIGHT_SCROLLED_LINES_WIDTH : 0)); - scrollRect.setRight(display->width()); - } else { - scrollRect.setLeft(_highlightScrolledLines.isEnabled() ? - _highlightScrolledLines.HIGHLIGHT_SCROLLED_LINES_WIDTH : 0); - - scrollRect.setRight(display->width() - scrollBarWidth - SCROLLBAR_CONTENT_GAP); - } - void *firstCharPos = &image[region.top() * display->columns()]; - void *lastCharPos = &image[(region.top() + abs(lines)) * display->columns()]; - - const int top = display->contentRect().top() + (region.top() * display->terminalFont()->fontHeight()); - const int linesToMove = region.height() - abs(lines); - const int bytesToMove = linesToMove * display->columns() * sizeof(Character); - - Q_ASSERT(linesToMove > 0); - Q_ASSERT(bytesToMove > 0); - - scrollRect.setTop(lines > 0 ? top : top + abs(lines) * display->terminalFont()->fontHeight()); - scrollRect.setHeight(linesToMove * display->terminalFont()->fontHeight()); - - if (!scrollRect.isValid() || scrollRect.isEmpty()) { - return; - } - - // scroll internal image - if (lines > 0) { - // check that the memory areas that we are going to move are valid - Q_ASSERT((char *)lastCharPos + bytesToMove < - (char *)(image + (display->lines() * display->columns()))); - Q_ASSERT((lines * display->columns()) < imageSize); - - // scroll internal image down - memmove(firstCharPos, lastCharPos, bytesToMove); - } else { - // check that the memory areas that we are going to move are valid - Q_ASSERT((char *)firstCharPos + bytesToMove < - (char *)(image + (display->lines() * display->columns()))); - - //scroll internal image up - memmove(lastCharPos, firstCharPos, bytesToMove); - } - - // scroll the display vertically to match internal _image - display->scroll(0, display->terminalFont()->fontHeight() * (-lines), scrollRect); + // setting the range or value of a _scrollBar will always trigger + // a repaint, so it should be avoided if it is not necessary + if (this->minimum() == 0 && this->maximum() == (slines - display->lines()) && this->value() == cursor) { + return; } + + disconnect(this, &QScrollBar::valueChanged, this, &TerminalScrollBar::scrollBarPositionChanged); + setRange(0, slines - display->lines()); + setSingleStep(1); + setPageStep(display->lines()); + setValue(cursor); + connect(this, &QScrollBar::valueChanged, this, &TerminalScrollBar::scrollBarPositionChanged); +} + +void TerminalScrollBar::setScrollFullPage(bool fullPage) +{ + _scrollFullPage = fullPage; +} + +bool TerminalScrollBar::scrollFullPage() const +{ + return _scrollFullPage; +} + +void TerminalScrollBar::setHighlightScrolledLines(bool highlight) +{ + _highlightScrolledLines.setEnabled(highlight); + _highlightScrolledLines.setTimer(this); + _highlightScrolledLines.setNeedToClear(true); +} + +bool TerminalScrollBar::alternateScrolling() const +{ + return _alternateScrolling; +} + +void TerminalScrollBar::setAlternateScrolling(bool enable) +{ + _alternateScrolling = enable; +} + +void TerminalScrollBar::scrollBarPositionChanged(int) +{ + const auto display = qobject_cast(this->parent()); + + if (display->screenWindow().isNull()) { + return; + } + + display->screenWindow()->scrollTo(this->value()); + + // if the thumb has been moved to the bottom of the _scrollBar then set + // the display to automatically track new output, + // that is, scroll down automatically + // to how new _lines as they are added + const bool atEndOfOutput = (this->value() == this->maximum()); + display->screenWindow()->setTrackOutput(atEndOfOutput); + + display->updateImage(); +} + +void TerminalScrollBar::highlightScrolledLinesEvent() +{ + const auto display = qobject_cast(this->parent()); + display->update(_highlightScrolledLines.rect()); +} + +void TerminalScrollBar::applyScrollBarPosition(bool propagate) +{ + setHidden(_scrollbarLocation == Enum::ScrollBarHidden); + + if (propagate) { + const auto display = qobject_cast(this->parent()); + display->propagateSize(); + display->update(); + } +} + +// scrolls the image by 'lines', down if lines > 0 or up otherwise. +// +// the terminal emulation keeps track of the scrolling of the character +// image as it receives input, and when the view is updated, it calls scrollImage() +// with the final scroll amount. this improves performance because scrolling the +// display is much cheaper than re-rendering all the text for the +// part of the image which has moved up or down. +// Instead only new lines have to be drawn +void TerminalScrollBar::scrollImage(int lines, const QRect &screenWindowRegion, Character *image, int imageSize) +{ + // return if there is nothing to do + if ((lines == 0) || (image == nullptr)) { + return; + } + + const auto display = qobject_cast(this->parent()); + // 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(), display->lines() - 2)); + + // return if there is nothing to do + if (!region.isValid() || (region.top() + abs(lines)) >= region.bottom() || display->lines() <= region.bottom()) { + return; + } + + // 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. + // + const int scrollBarWidth = this->isHidden() ? 0 : this->width(); + const int SCROLLBAR_CONTENT_GAP = 1; + QRect scrollRect; + if (_scrollbarLocation == Enum::ScrollBarLeft) { + scrollRect.setLeft(scrollBarWidth + SCROLLBAR_CONTENT_GAP + + (_highlightScrolledLines.isEnabled() ? _highlightScrolledLines.HIGHLIGHT_SCROLLED_LINES_WIDTH : 0)); + scrollRect.setRight(display->width()); + } else { + scrollRect.setLeft(_highlightScrolledLines.isEnabled() ? _highlightScrolledLines.HIGHLIGHT_SCROLLED_LINES_WIDTH : 0); + + scrollRect.setRight(display->width() - scrollBarWidth - SCROLLBAR_CONTENT_GAP); + } + void *firstCharPos = &image[region.top() * display->columns()]; + void *lastCharPos = &image[(region.top() + abs(lines)) * display->columns()]; + + const int top = display->contentRect().top() + (region.top() * display->terminalFont()->fontHeight()); + const int linesToMove = region.height() - abs(lines); + const int bytesToMove = linesToMove * display->columns() * sizeof(Character); + + Q_ASSERT(linesToMove > 0); + Q_ASSERT(bytesToMove > 0); + + scrollRect.setTop(lines > 0 ? top : top + abs(lines) * display->terminalFont()->fontHeight()); + scrollRect.setHeight(linesToMove * display->terminalFont()->fontHeight()); + + if (!scrollRect.isValid() || scrollRect.isEmpty()) { + return; + } + + // scroll internal image + if (lines > 0) { + // check that the memory areas that we are going to move are valid + Q_ASSERT((char *)lastCharPos + bytesToMove < (char *)(image + (display->lines() * display->columns()))); + Q_ASSERT((lines * display->columns()) < imageSize); + + // scroll internal image down + memmove(firstCharPos, lastCharPos, bytesToMove); + } else { + // check that the memory areas that we are going to move are valid + Q_ASSERT((char *)firstCharPos + bytesToMove < (char *)(image + (display->lines() * display->columns()))); + + // scroll internal image up + memmove(lastCharPos, firstCharPos, bytesToMove); + } + + // scroll the display vertically to match internal _image + display->scroll(0, display->terminalFont()->fontHeight() * (-lines), scrollRect); +} } // namespace Konsole diff --git a/src/terminalDisplay/TerminalScrollBar.h b/src/terminalDisplay/TerminalScrollBar.h index 8af2ff77e..2d52892ac 100644 --- a/src/terminalDisplay/TerminalScrollBar.h +++ b/src/terminalDisplay/TerminalScrollBar.h @@ -13,88 +13,88 @@ #include // Konsole -#include "ScrollState.h" #include "Enumeration.h" #include "ScreenWindow.h" -#include "konsoleprivate_export.h" +#include "ScrollState.h" #include "extras/HighlightScrolledLines.h" +#include "konsoleprivate_export.h" namespace Konsole { - class TerminalDisplay; +class TerminalDisplay; - class KONSOLEPRIVATE_EXPORT TerminalScrollBar : public QScrollBar +class KONSOLEPRIVATE_EXPORT TerminalScrollBar : public QScrollBar +{ + Q_OBJECT +public: + explicit TerminalScrollBar(QWidget *parent); + + /** + * 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(Enum::ScrollBarPositionEnum position); + + /** + * Sets the current position and range of the display's scroll bar. + * + * @param cursor The position of the scroll bar's thumb. + * @param slines The maximum value of the scroll bar. + */ + void setScroll(int cursor, int slines); + + void setScrollFullPage(bool fullPage); + bool scrollFullPage() const; + void setHighlightScrolledLines(bool highlight); + + /** See setAlternateScrolling() */ + bool alternateScrolling() const; + + /** + * Sets the AlternateScrolling profile property which controls whether + * to emulate up/down key presses for mouse scroll wheel events. + * For more details, check the documentation of that property in the + * Profile header. + * Enabled by default. + */ + void setAlternateScrolling(bool enable); + + // applies changes to scrollbarLocation to the scroll bar and + // if @propagate is true, propagates size information + void applyScrollBarPosition(bool propagate = true); + + // 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 &screenWindowRegion, Character *image, int imageSize); + + Enum::ScrollBarPositionEnum scrollBarPosition() const { - Q_OBJECT - public: - explicit TerminalScrollBar(QWidget *parent); + return _scrollbarLocation; + } - /** - * 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(Enum::ScrollBarPositionEnum position); + /** + * Return the higlight line control + */ + HighlightScrolledLines &highlightScrolledLines() + { + return _highlightScrolledLines; + } - /** - * Sets the current position and range of the display's scroll bar. - * - * @param cursor The position of the scroll bar's thumb. - * @param slines The maximum value of the scroll bar. - */ - void setScroll(int cursor, int slines); +public Q_SLOTS: - void setScrollFullPage(bool fullPage); - bool scrollFullPage() const; - void setHighlightScrolledLines(bool highlight); + void scrollBarPositionChanged(int value); + void highlightScrolledLinesEvent(); - /** See setAlternateScrolling() */ - bool alternateScrolling() const; - - /** - * Sets the AlternateScrolling profile property which controls whether - * to emulate up/down key presses for mouse scroll wheel events. - * For more details, check the documentation of that property in the - * Profile header. - * Enabled by default. - */ - void setAlternateScrolling(bool enable); - - // applies changes to scrollbarLocation to the scroll bar and - // if @propagate is true, propagates size information - void applyScrollBarPosition(bool propagate = true); - - // 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 &screenWindowRegion, Character *image, int imageSize); - - Enum::ScrollBarPositionEnum scrollBarPosition() const - { - return _scrollbarLocation; - } - - /** - * Return the higlight line control - */ - HighlightScrolledLines &highlightScrolledLines() - { - return _highlightScrolledLines; - } - - public Q_SLOTS: - - void scrollBarPositionChanged(int value); - void highlightScrolledLinesEvent(); - - private: - bool _scrollFullPage; - bool _alternateScrolling; - Enum::ScrollBarPositionEnum _scrollbarLocation; - HighlightScrolledLines _highlightScrolledLines; - }; +private: + bool _scrollFullPage; + bool _alternateScrolling; + Enum::ScrollBarPositionEnum _scrollbarLocation; + HighlightScrolledLines _highlightScrolledLines; +}; } // namespace Konsole #endif diff --git a/src/terminalDisplay/extras/AutoScrollHandler.cpp b/src/terminalDisplay/extras/AutoScrollHandler.cpp index 5aa8589df..2f61effbb 100644 --- a/src/terminalDisplay/extras/AutoScrollHandler.cpp +++ b/src/terminalDisplay/extras/AutoScrollHandler.cpp @@ -7,25 +7,25 @@ #include "AutoScrollHandler.h" #include "../TerminalDisplay.h" -#include #include +#include using namespace Konsole; -AutoScrollHandler::AutoScrollHandler(QWidget* parent) +AutoScrollHandler::AutoScrollHandler(QWidget *parent) : QObject(parent) , _timerId(0) { parent->installEventFilter(this); } -void AutoScrollHandler::timerEvent(QTimerEvent* event) +void AutoScrollHandler::timerEvent(QTimerEvent *event) { if (event->timerId() != _timerId) { return; } - auto* terminalDisplay = static_cast(parent()); + auto *terminalDisplay = static_cast(parent()); QMouseEvent mouseEvent(QEvent::MouseMove, widget()->mapFromGlobal(QCursor::pos()), Qt::NoButton, @@ -35,16 +35,16 @@ void AutoScrollHandler::timerEvent(QTimerEvent* event) QApplication::sendEvent(widget(), &mouseEvent); } -bool AutoScrollHandler::eventFilter(QObject* watched, QEvent* event) +bool AutoScrollHandler::eventFilter(QObject *watched, QEvent *event) { Q_ASSERT(watched == parent()); Q_UNUSED(watched) switch (event->type()) { case QEvent::MouseMove: { - auto* mouseEvent = static_cast(event); + auto *mouseEvent = static_cast(event); bool mouseInWidget = widget()->rect().contains(mouseEvent->pos()); - auto* terminalDisplay = static_cast(parent()); + auto *terminalDisplay = static_cast(parent()); if (mouseInWidget) { if (_timerId != 0) { killTimer(_timerId); @@ -60,7 +60,7 @@ bool AutoScrollHandler::eventFilter(QObject* watched, QEvent* event) break; } case QEvent::MouseButtonRelease: { - auto* mouseEvent = static_cast(event); + auto *mouseEvent = static_cast(event); if ((_timerId != 0) && ((mouseEvent->buttons() & ~Qt::LeftButton) != 0U)) { killTimer(_timerId); _timerId = 0; diff --git a/src/terminalDisplay/extras/AutoScrollHandler.h b/src/terminalDisplay/extras/AutoScrollHandler.h index 130ddf710..b6f3e44d1 100644 --- a/src/terminalDisplay/extras/AutoScrollHandler.h +++ b/src/terminalDisplay/extras/AutoScrollHandler.h @@ -12,16 +12,17 @@ namespace Konsole { - class AutoScrollHandler : public QObject { Q_OBJECT public: explicit AutoScrollHandler(QWidget *parent); + protected: void timerEvent(QTimerEvent *event) override; bool eventFilter(QObject *watched, QEvent *event) override; + private: QWidget *widget() const { diff --git a/src/terminalDisplay/extras/CompositeWidgetFocusWatcher.cpp b/src/terminalDisplay/extras/CompositeWidgetFocusWatcher.cpp index f36272034..d033c7ec6 100644 --- a/src/terminalDisplay/extras/CompositeWidgetFocusWatcher.cpp +++ b/src/terminalDisplay/extras/CompositeWidgetFocusWatcher.cpp @@ -20,7 +20,7 @@ CompositeWidgetFocusWatcher::CompositeWidgetFocusWatcher(QWidget *compositeWidge bool CompositeWidgetFocusWatcher::eventFilter(QObject *watched, QEvent *event) { - switch(event->type()) { + switch (event->type()) { case QEvent::Close: case QEvent::DeferredDelete: case QEvent::Destroy: @@ -31,7 +31,7 @@ bool CompositeWidgetFocusWatcher::eventFilter(QObject *watched, QEvent *event) Q_EMIT compositeFocusChanged(true); break; case QEvent::FocusOut: - if(static_cast(event)->reason() != Qt::PopupFocusReason) { + if (static_cast(event)->reason() != Qt::PopupFocusReason) { Q_EMIT compositeFocusChanged(false); } break; @@ -48,7 +48,7 @@ void CompositeWidgetFocusWatcher::registerWidgetAndChildren(QWidget *widget) if (widget->focusPolicy() != Qt::NoFocus) { widget->installEventFilter(this); } - for (auto *child: widget->children()) { + for (auto *child : widget->children()) { auto *childWidget = qobject_cast(child); if (childWidget != nullptr) { registerWidgetAndChildren(childWidget); diff --git a/src/terminalDisplay/extras/HighlightScrolledLines.h b/src/terminalDisplay/extras/HighlightScrolledLines.h index b3efe3d87..f1a2c669d 100644 --- a/src/terminalDisplay/extras/HighlightScrolledLines.h +++ b/src/terminalDisplay/extras/HighlightScrolledLines.h @@ -10,9 +10,9 @@ #define HIGHLIGHTSCROLLEDLINES_HPP // Qt -#include #include #include +#include // Konsole #include "Enumeration.h" @@ -22,12 +22,12 @@ namespace Konsole { class TerminalScrollBar; /** - * Control the highlight the lines that are coming into view. - * A thin blue line on the left of the terminal that highlight - * the new lines in the following situations: - * - scrolling with the mouse - * - using the scroll bar - * - using the keyboard to move up/down + * Control the highlight the lines that are coming into view. + * A thin blue line on the left of the terminal that highlight + * the new lines in the following situations: + * - scrolling with the mouse + * - using the scroll bar + * - using the keyboard to move up/down * - new lines resulting from the output of a command */ class HighlightScrolledLines diff --git a/src/tests/PartManualTest.cpp b/src/tests/PartManualTest.cpp index 38dcae3ce..7562f66e4 100644 --- a/src/tests/PartManualTest.cpp +++ b/src/tests/PartManualTest.cpp @@ -8,20 +8,20 @@ #include "PartManualTest.h" // Qt -#include -#include -#include #include +#include +#include #include +#include // System -#include #include +#include // KDE -#include -#include -#include #include +#include +#include +#include #include // Konsole @@ -45,16 +45,16 @@ void PartManualTest::testShortcutOverride() // Create a main window with a menu and a test // action with a shortcut set to Ctrl+S, which is also used by the terminal auto mainWindow = new KMainWindow(); - QMenu* fileMenu = mainWindow->menuBar()->addMenu(QStringLiteral("File")); - QAction* testAction = fileMenu->addAction(QStringLiteral("Test")); + QMenu *fileMenu = mainWindow->menuBar()->addMenu(QStringLiteral("File")); + QAction *testAction = fileMenu->addAction(QStringLiteral("Test")); testAction->setShortcut(QKeySequence(Konsole::ACCEL | Qt::Key_S)); connect(testAction, &QAction::triggered, this, &Konsole::PartManualTest::shortcutTriggered); // Create terminal part and embed in into the main window - KParts::Part* terminalPart = createPart(); + KParts::Part *terminalPart = createPart(); QVERIFY(terminalPart); mainWindow->setCentralWidget(terminalPart->widget()); - TerminalInterface* terminal = qobject_cast(terminalPart); + TerminalInterface *terminal = qobject_cast(terminalPart); QVERIFY(terminal); terminal->sendInput(QStringLiteral("Press Ctrl+S twice.\n")); mainWindow->show(); @@ -63,10 +63,9 @@ void PartManualTest::testShortcutOverride() _shortcutTriggered = false; _override = false; _overrideCalled = false; - QVERIFY(connect(terminalPart, SIGNAL(overrideShortcut(QKeyEvent*,bool&)), - this, SLOT(overrideShortcut(QKeyEvent*,bool&)))); + QVERIFY(connect(terminalPart, SIGNAL(overrideShortcut(QKeyEvent *, bool &)), this, SLOT(overrideShortcut(QKeyEvent *, bool &)))); - //QTest::keyClick(terminalPart->widget(),Qt::Key_S,Qt::ControlModifier); + // QTest::keyClick(terminalPart->widget(),Qt::Key_S,Qt::ControlModifier); _shortcutEventLoop = new QEventLoop(); _shortcutEventLoop->exec(); @@ -79,7 +78,7 @@ void PartManualTest::testShortcutOverride() _overrideCalled = false; _shortcutTriggered = false; - //QTest::keyClick(terminalPart->widget(),Qt::Key_S,Qt::ControlModifier); + // QTest::keyClick(terminalPart->widget(),Qt::Key_S,Qt::ControlModifier); _shortcutEventLoop->exec(); QVERIFY(_overrideCalled); @@ -90,7 +89,7 @@ void PartManualTest::testShortcutOverride() delete terminalPart; delete mainWindow; } -void PartManualTest::overrideShortcut(QKeyEvent* event, bool& override) +void PartManualTest::overrideShortcut(QKeyEvent *event, bool &override) { QVERIFY(override); if (event->modifiers() == Qt::ControlModifier && event->key() == Qt::Key_S) { @@ -104,17 +103,16 @@ void PartManualTest::shortcutTriggered() _shortcutTriggered = true; } -KParts::Part* PartManualTest::createPart() +KParts::Part *PartManualTest::createPart() { KService::Ptr service = KService::serviceByDesktopName(QStringLiteral("konsolepart")); Q_ASSERT(service); - KPluginFactory* factory = KPluginLoader(service->library()).factory(); + KPluginFactory *factory = KPluginLoader(service->library()).factory(); Q_ASSERT(factory); - auto* terminalPart = factory->create(this); + auto *terminalPart = factory->create(this); return terminalPart; } QTEST_MAIN(PartManualTest) - diff --git a/src/tests/PartManualTest.h b/src/tests/PartManualTest.h index 3a9169f9b..c25d8fa19 100644 --- a/src/tests/PartManualTest.h +++ b/src/tests/PartManualTest.h @@ -9,14 +9,13 @@ #include -#include #include +#include class QKeyEvent; namespace Konsole { - class PartManualTest : public QObject { Q_OBJECT @@ -24,22 +23,21 @@ class PartManualTest : public QObject private Q_SLOTS: void testShortcutOverride(); -// marked as protected so they are not treated as test cases + // marked as protected so they are not treated as test cases protected Q_SLOTS: - void overrideShortcut(QKeyEvent* event, bool& override); + void overrideShortcut(QKeyEvent *event, bool &override); void shortcutTriggered(); private: - KParts::Part* createPart(); + KParts::Part *createPart(); // variables for testShortcutOverride() bool _shortcutTriggered; bool _overrideCalled; bool _override; - QEventLoop* _shortcutEventLoop; + QEventLoop *_shortcutEventLoop; }; } #endif // PARTMANUALTEST_H - diff --git a/src/tests/demo_konsolepart/src/demo_konsolepart.cpp b/src/tests/demo_konsolepart/src/demo_konsolepart.cpp index 2656af4be..828aaf379 100644 --- a/src/tests/demo_konsolepart/src/demo_konsolepart.cpp +++ b/src/tests/demo_konsolepart/src/demo_konsolepart.cpp @@ -7,15 +7,15 @@ #include "demo_konsolepart.h" #include +#include #include #include -#include -#include #include +#include #include -#include #include +#include #include @@ -23,10 +23,10 @@ //#include "../../../WindowSystemInfo.h" demo_konsolepart::demo_konsolepart() - : KMainWindow(), - _mainWindow(nullptr), - _terminalPart(nullptr), - _terminal(nullptr) + : KMainWindow() + , _mainWindow(nullptr) + , _terminalPart(nullptr) + , _terminal(nullptr) { const bool useTranslucency = KWindowSystem::compositingActive(); @@ -36,7 +36,7 @@ demo_konsolepart::demo_konsolepart() // This is used in EditProfileDialog to show the warnings about // transparency issues - needs refactoring as the above // include does not work -// WindowSystemInfo::HAVE_TRANSPARENCY = useTranslucency; + // WindowSystemInfo::HAVE_TRANSPARENCY = useTranslucency; // Create terminal part and embed in into the main window _terminalPart = createPart(); @@ -44,24 +44,22 @@ demo_konsolepart::demo_konsolepart() return; } - QMenu* fileMenu = menuBar()->addMenu(QStringLiteral("File")); - QAction* manageProfilesAction = fileMenu->addAction(QStringLiteral("Manage Profiles...")); + QMenu *fileMenu = menuBar()->addMenu(QStringLiteral("File")); + QAction *manageProfilesAction = fileMenu->addAction(QStringLiteral("Manage Profiles...")); connect(manageProfilesAction, &QAction::triggered, this, &demo_konsolepart::manageProfiles); - QAction* quitAction = fileMenu->addAction(QStringLiteral("Quit")); + QAction *quitAction = fileMenu->addAction(QStringLiteral("Quit")); connect(quitAction, &QAction::triggered, this, &demo_konsolepart::quit); connect(_terminalPart, &KParts::ReadOnlyPart::destroyed, this, &demo_konsolepart::quit); setCentralWidget(_terminalPart->widget()); - _terminal = qobject_cast(_terminalPart); + _terminal = qobject_cast(_terminalPart); // Test if blur is enabled for profile bool blurEnabled; - QMetaObject::invokeMethod(_terminalPart, "isBlurEnabled", - Qt::DirectConnection, - Q_RETURN_ARG(bool, blurEnabled)); - qWarning()<<"blur enabled: "<library()).factory(); + KPluginFactory *factory = KPluginLoader(service->library()).factory(); Q_ASSERT(factory); - auto* terminalPart = factory->create(this); + auto *terminalPart = factory->create(this); return terminalPart; } void demo_konsolepart::manageProfiles() { - QMetaObject::invokeMethod(_terminalPart, "showManageProfilesDialog", - Qt::QueuedConnection, Q_ARG(QWidget*, QApplication::activeWindow())); + QMetaObject::invokeMethod(_terminalPart, "showManageProfilesDialog", Qt::QueuedConnection, Q_ARG(QWidget *, QApplication::activeWindow())); } void demo_konsolepart::quit() diff --git a/src/tests/demo_konsolepart/src/demo_konsolepart.h b/src/tests/demo_konsolepart/src/demo_konsolepart.h index 4bbc93447..658d4f838 100644 --- a/src/tests/demo_konsolepart/src/demo_konsolepart.h +++ b/src/tests/demo_konsolepart/src/demo_konsolepart.h @@ -7,10 +7,10 @@ #ifndef DEMO_KONSOLEPART_H #define DEMO_KONSOLEPART_H -#include #include #include #include +#include class demo_konsolepart : public KMainWindow { @@ -28,12 +28,11 @@ public Q_SLOTS: private: Q_DISABLE_COPY(demo_konsolepart) - KParts::ReadOnlyPart* createPart(); + KParts::ReadOnlyPart *createPart(); KMainWindow *_mainWindow; KParts::ReadOnlyPart *_terminalPart; TerminalInterface *_terminal; - }; #endif diff --git a/src/widgets/DetachableTabBar.cpp b/src/widgets/DetachableTabBar.cpp index 0ea43ded3..22c594fda 100644 --- a/src/widgets/DetachableTabBar.cpp +++ b/src/widgets/DetachableTabBar.cpp @@ -8,22 +8,22 @@ #include "KonsoleSettings.h" #include "widgets/ViewContainer.h" -#include #include #include +#include #include -#include #include +#include -namespace Konsole { - -DetachableTabBar::DetachableTabBar(QWidget *parent) : - QTabBar(parent), - dragType(DragType::NONE), - _originalCursor(cursor()), - tabId(-1) +namespace Konsole +{ +DetachableTabBar::DetachableTabBar(QWidget *parent) + : QTabBar(parent) + , dragType(DragType::NONE) + , _originalCursor(cursor()) + , tabId(-1) { setAcceptDrops(true); setElideMode(Qt::TextElideMode::ElideLeft); @@ -40,7 +40,7 @@ void DetachableTabBar::removeColor(int idx) setTabData(idx, QVariant()); } -void DetachableTabBar::middleMouseButtonClickAt(const QPoint& pos) +void DetachableTabBar::middleMouseButtonClickAt(const QPoint &pos) { tabId = tabAt(pos); @@ -52,7 +52,7 @@ void DetachableTabBar::middleMouseButtonClickAt(const QPoint& pos) void DetachableTabBar::mousePressEvent(QMouseEvent *event) { QTabBar::mousePressEvent(event); - _containers = window()->findChildren(); + _containers = window()->findChildren(); } void DetachableTabBar::mouseMoveEvent(QMouseEvent *event) @@ -71,7 +71,7 @@ void DetachableTabBar::mouseMoveEvent(QMouseEvent *event) setCursor(QCursor(Qt::DragMoveCursor)); } } - } else if (!contentsRect().adjusted(-30,-30,30,30).contains(event->pos())) { + } else if (!contentsRect().adjusted(-30, -30, 30, 30).contains(event->pos())) { // Don't let it detach the last tab. if (count() == 1) { return; @@ -87,23 +87,27 @@ void DetachableTabBar::mouseReleaseEvent(QMouseEvent *event) { QTabBar::mouseReleaseEvent(event); - switch(event->button()) { - case Qt::MiddleButton : if (KonsoleSettings::closeTabOnMiddleMouseButton()) { - middleMouseButtonClickAt(event->pos()); - } + switch (event->button()) { + case Qt::MiddleButton: + if (KonsoleSettings::closeTabOnMiddleMouseButton()) { + middleMouseButtonClickAt(event->pos()); + } - tabId = tabAt(event->pos()); - if (tabId == -1) { - Q_EMIT newTabRequest(); - } - break; - case Qt::LeftButton: _containers = window()->findChildren(); break; - default: break; + tabId = tabAt(event->pos()); + if (tabId == -1) { + Q_EMIT newTabRequest(); + } + break; + case Qt::LeftButton: + _containers = window()->findChildren(); + break; + default: + break; } setCursor(_originalCursor); - if (contentsRect().adjusted(-30,-30,30,30).contains(event->pos())) { + if (contentsRect().adjusted(-30, -30, 30, 30).contains(event->pos())) { return; } @@ -119,7 +123,7 @@ void DetachableTabBar::mouseReleaseEvent(QMouseEvent *event) } } -void DetachableTabBar::dragEnterEvent(QDragEnterEvent* event) +void DetachableTabBar::dragEnterEvent(QDragEnterEvent *event) { const auto dragId = QStringLiteral("konsole/terminal_display"); if (!event->mimeData()->hasFormat(dragId)) { @@ -133,7 +137,7 @@ void DetachableTabBar::dragEnterEvent(QDragEnterEvent* event) event->accept(); } -void DetachableTabBar::dragMoveEvent(QDragMoveEvent* event) +void DetachableTabBar::dragMoveEvent(QDragMoveEvent *event) { int tabIdx = tabAt(event->pos()); if (tabIdx != -1) { @@ -145,7 +149,7 @@ void DetachableTabBar::paintEvent(QPaintEvent *event) { QTabBar::paintEvent(event); if (!event->isAccepted()) { - return; // Reduces repainting + return; // Reduces repainting } QPainter painter(this); @@ -164,7 +168,7 @@ void DetachableTabBar::paintEvent(QPaintEvent *event) painter.setBrush(varColor); QRect tRect = tabRect(tabIndex); - tRect.setTop(painter.fontMetrics().height() + 6); // Color bar top position consider a height the font and fixed spacing of 6px + tRect.setTop(painter.fontMetrics().height() + 6); // Color bar top position consider a height the font and fixed spacing of 6px tRect.setHeight(4); tRect.setLeft(tRect.left() + 6); tRect.setWidth(tRect.width() - 6); diff --git a/src/widgets/DetachableTabBar.h b/src/widgets/DetachableTabBar.h index c6ed6ba4b..edf5c3313 100644 --- a/src/widgets/DetachableTabBar.h +++ b/src/widgets/DetachableTabBar.h @@ -7,18 +7,20 @@ #ifndef DETACHABLETABBAR_H #define DETACHABLETABBAR_H -#include #include +#include class QColor; class QPaintEvent; -namespace Konsole { +namespace Konsole +{ class TabbedViewContainer; -class DetachableTabBar : public QTabBar { +class DetachableTabBar : public QTabBar +{ Q_OBJECT public: - enum class DragType : unsigned char {NONE, OUTSIDE, WINDOW}; + enum class DragType : unsigned char { NONE, OUTSIDE, WINDOW, }; explicit DetachableTabBar(QWidget *parent = nullptr); @@ -29,19 +31,20 @@ Q_SIGNALS: void moveTabToWindow(int tabIndex, QWidget *otherWindow); void closeTab(int index); void newTabRequest(); + protected: - void middleMouseButtonClickAt(const QPoint& pos); + void middleMouseButtonClickAt(const QPoint &pos); void mousePressEvent(QMouseEvent *event) override; - void mouseMoveEvent(QMouseEvent*event) override; + void mouseMoveEvent(QMouseEvent *event) override; void mouseReleaseEvent(QMouseEvent *event) override; void dragEnterEvent(QDragEnterEvent *event) override; - void dragMoveEvent(QDragMoveEvent * event) override; + void dragMoveEvent(QDragMoveEvent *event) override; void paintEvent(QPaintEvent *event) override; private: DragType dragType; QCursor _originalCursor; - QList _containers; + QList _containers; int tabId; }; } diff --git a/src/widgets/EditProfileDialog.cpp b/src/widgets/EditProfileDialog.cpp index 36a011451..1a9bb8429 100644 --- a/src/widgets/EditProfileDialog.cpp +++ b/src/widgets/EditProfileDialog.cpp @@ -12,17 +12,17 @@ #include #include #include -#include #include +#include #include #include +#include #include +#include +#include #include #include #include -#include -#include -#include // KDE #include @@ -34,22 +34,22 @@ #include // Konsole -#include "ui_EditProfileGeneralPage.h" -#include "ui_EditProfileTabsPage.h" +#include "ui_EditProfileAdvancedPage.h" #include "ui_EditProfileAppearancePage.h" -#include "ui_EditProfileScrollingPage.h" +#include "ui_EditProfileGeneralPage.h" #include "ui_EditProfileKeyboardPage.h" #include "ui_EditProfileMousePage.h" -#include "ui_EditProfileAdvancedPage.h" +#include "ui_EditProfileScrollingPage.h" +#include "ui_EditProfileTabsPage.h" #include "colorscheme/ColorSchemeManager.h" #include "keyboardtranslator/KeyboardTranslator.h" #include "KeyBindingEditor.h" -#include "profile/ProfileManager.h" #include "ShellCommand.h" #include "WindowSystemInfo.h" +#include "profile/ProfileManager.h" using namespace Konsole; @@ -88,8 +88,7 @@ EditProfileDialog::EditProfileDialog(QWidget *parent) } }); - connect(_delayedPreviewTimer, &QTimer::timeout, this, - &Konsole::EditProfileDialog::delayedPreviewActivate); + connect(_delayedPreviewTimer, &QTimer::timeout, this, &Konsole::EditProfileDialog::delayedPreviewActivate); // Set a fallback icon for non-plasma desktops as this dialog looks // terrible without all the icons on the left sidebar. On GTK related @@ -118,8 +117,7 @@ EditProfileDialog::EditProfileDialog(QWidget *parent) _tabsUi->setupUi(tabsPageWidget); auto *tabsPageItem = addPage(tabsPageWidget, tabsPageName); tabsPageItem->setHeader(tabsPageName); - tabsPageItem->setIcon(QIcon::fromTheme(QStringLiteral("tab-duplicate"), - defaultIcon)); + tabsPageItem->setIcon(QIcon::fromTheme(QStringLiteral("tab-duplicate"), defaultIcon)); _pages[tabsPageItem] = Page(&EditProfileDialog::setupTabsPage); LabelsAligner tabsAligner(tabsPageWidget); @@ -136,8 +134,7 @@ EditProfileDialog::EditProfileDialog(QWidget *parent) _appearanceUi->setupUi(appearancePageWidget); auto *appearancePageItem = addPage(appearancePageWidget, appearancePageName); appearancePageItem->setHeader(appearancePageName); - appearancePageItem->setIcon(QIcon::fromTheme(QStringLiteral("kcolorchooser"), - defaultIcon)); + appearancePageItem->setIcon(QIcon::fromTheme(QStringLiteral("kcolorchooser"), defaultIcon)); _pages[appearancePageItem] = Page(&EditProfileDialog::setupAppearancePage); LabelsAligner appearanceAligner(appearancePageWidget); @@ -153,8 +150,7 @@ EditProfileDialog::EditProfileDialog(QWidget *parent) _scrollingUi->setupUi(scrollingPageWidget); auto *scrollingPageItem = addPage(scrollingPageWidget, scrollingPageName); scrollingPageItem->setHeader(scrollingPageName); - scrollingPageItem->setIcon(QIcon::fromTheme(QStringLiteral("transform-move-vertical"), - defaultIcon)); + scrollingPageItem->setIcon(QIcon::fromTheme(QStringLiteral("transform-move-vertical"), defaultIcon)); _pages[scrollingPageItem] = Page(&EditProfileDialog::setupScrollingPage); // adjust "history size" label height to match history size widget's first radio button @@ -169,8 +165,7 @@ EditProfileDialog::EditProfileDialog(QWidget *parent) _keyboardUi->setupUi(keyboardPageWidget); auto *keyboardPageItem = addPage(keyboardPageWidget, keyboardPageName); keyboardPageItem->setHeader(keyboardPageTitle); - keyboardPageItem->setIcon(QIcon::fromTheme(QStringLiteral("input-keyboard"), - defaultIcon)); + keyboardPageItem->setIcon(QIcon::fromTheme(QStringLiteral("input-keyboard"), defaultIcon)); _pages[keyboardPageItem] = Page(&EditProfileDialog::setupKeyboardPage); // Mouse page @@ -186,8 +181,7 @@ EditProfileDialog::EditProfileDialog(QWidget *parent) auto *mousePageItem = addPage(mousePageWidget, mousePageName); mousePageItem->setHeader(mousePageName); - mousePageItem->setIcon(QIcon::fromTheme(QStringLiteral("input-mouse"), - defaultIcon)); + mousePageItem->setIcon(QIcon::fromTheme(QStringLiteral("input-mouse"), defaultIcon)); _pages[mousePageItem] = Page(&EditProfileDialog::setupMousePage); // Advanced page @@ -198,8 +192,7 @@ EditProfileDialog::EditProfileDialog(QWidget *parent) _advancedUi->setupUi(advancedPageWidget); auto *advancedPageItem = addPage(advancedPageWidget, advancedPageName); advancedPageItem->setHeader(advancedPageName); - advancedPageItem->setIcon(QIcon::fromTheme(QStringLiteral("configure"), - defaultIcon)); + advancedPageItem->setIcon(QIcon::fromTheme(QStringLiteral("configure"), defaultIcon)); _pages[advancedPageItem] = Page(&EditProfileDialog::setupAdvancedPage); // there are various setupXYZPage() methods to load the items @@ -212,8 +205,7 @@ EditProfileDialog::EditProfileDialog(QWidget *parent) // the _pageNeedsUpdate vector keeps track of the pages that have // not been updated since the last profile change and will need // to be refreshed when the user switches to them - connect(this, &KPageDialog::currentPageChanged, - this, &Konsole::EditProfileDialog::preparePage); + connect(this, &KPageDialog::currentPageChanged, this, &Konsole::EditProfileDialog::preparePage); createTempProfile(); } @@ -292,14 +284,12 @@ bool EditProfileDialog::isProfileNameValid() // check whether the user has enough permissions to save the profile QFileInfo fileInfo(_profile->path()); - if (fileInfo.exists() && !fileInfo.isWritable() - && (!_tempProfile->isPropertySet(Profile::Name) || _tempProfile->name() == _profile->name())) { - setMessageGeneralPage( - xi18nc("@info", - "Insufficient permissions to save settings to: %1." - "Either change the permissions of that file or set a different name to save " - "the settings to a new profile.", - _profile->path())); + if (fileInfo.exists() && !fileInfo.isWritable() && (!_tempProfile->isPropertySet(Profile::Name) || _tempProfile->name() == _profile->name())) { + setMessageGeneralPage(xi18nc("@info", + "Insufficient permissions to save settings to: %1." + "Either change the permissions of that file or set a different name to save " + "the settings to a new profile.", + _profile->path())); return false; } @@ -312,10 +302,8 @@ bool EditProfileDialog::isProfileNameValid() } } - if ((_tempProfile->isPropertySet(Profile::Name) && _tempProfile->name().isEmpty()) - || (_profile->name().isEmpty() && _tempProfile->name().isEmpty())) { - setMessageGeneralPage(i18nc("@info", - "Profile Name was empty; please set a name to be able to save settings.")); + if ((_tempProfile->isPropertySet(Profile::Name) && _tempProfile->name().isEmpty()) || (_profile->name().isEmpty() && _tempProfile->name().isEmpty())) { + setMessageGeneralPage(i18nc("@info", "Profile Name was empty; please set a name to be able to save settings.")); // Revert the name in the dialog _generalUi->profileNameEdit->setText(_profile->name()); selectProfileName(); @@ -323,9 +311,7 @@ bool EditProfileDialog::isProfileNameValid() } if (!_tempProfile->name().isEmpty() && otherExistingProfileNames.contains(_tempProfile->name())) { - setMessageGeneralPage(i18nc("@info", - "A profile with the name \"%1\" already exists.", - _generalUi->profileNameEdit->text())); + setMessageGeneralPage(i18nc("@info", "A profile with the name \"%1\" already exists.", _generalUi->profileNameEdit->text())); // Revert the name in the dialog _generalUi->profileNameEdit->setText(_profile->name()); selectProfileName(); @@ -360,10 +346,7 @@ void EditProfileDialog::updateCaption(const Profile::Ptr &profile) ProfileGroup::Ptr group = profile->asGroup(); if (group && group->profiles().count() > 1) { QString caption = groupProfileNames(group, MAX_GROUP_CAPTION_LENGTH); - setWindowTitle(i18np("Editing profile: %2", - "Editing %1 profiles: %2", - group->profiles().count(), - caption)); + setWindowTitle(i18np("Editing profile: %2", "Editing %1 profiles: %2", group->profiles().count(), caption)); } else { if (_profileState == EditProfileDialog::NewProfile) { setWindowTitle(i18n("Create New Profile")); @@ -388,7 +371,7 @@ void EditProfileDialog::setProfile(const Konsole::Profile::Ptr &profile, EditPro // and force an update of the currently visible page // // the other pages will be updated as necessary - for (Page &page: _pages) { + for (Page &page : _pages) { page.needsUpdate = true; } preparePage(currentPage()); @@ -464,49 +447,36 @@ void EditProfileDialog::setupGeneralPage(const Profile::Ptr &profile) _generalUi->startInSameDirButton->setChecked(profile->startInCurrentSessionDir()); // initial terminal size - const auto colsSuffix = ki18ncp("Suffix of the number of columns (N columns). The leading space is needed to separate it from the number value.", " column", " columns"); - const auto rowsSuffix = ki18ncp("Suffix of the number of rows (N rows). The leading space is needed to separate it from the number value.", " row", " rows"); + const auto colsSuffix = + ki18ncp("Suffix of the number of columns (N columns). The leading space is needed to separate it from the number value.", " column", " columns"); + const auto rowsSuffix = + ki18ncp("Suffix of the number of rows (N rows). The leading space is needed to separate it from the number value.", " row", " rows"); _generalUi->terminalColumnsEntry->setValue(profile->terminalColumns()); _generalUi->terminalRowsEntry->setValue(profile->terminalRows()); _generalUi->terminalColumnsEntry->setSuffix(colsSuffix); _generalUi->terminalRowsEntry->setSuffix(rowsSuffix); // make width of initial terminal size spinboxes equal - const int sizeEntryWidth = qMax(maxSpinBoxWidth(_generalUi->terminalColumnsEntry, colsSuffix), - maxSpinBoxWidth(_generalUi->terminalRowsEntry, rowsSuffix)); + const int sizeEntryWidth = qMax(maxSpinBoxWidth(_generalUi->terminalColumnsEntry, colsSuffix), maxSpinBoxWidth(_generalUi->terminalRowsEntry, rowsSuffix)); _generalUi->terminalColumnsEntry->setFixedWidth(sizeEntryWidth); _generalUi->terminalRowsEntry->setFixedWidth(sizeEntryWidth); - auto *bellModeModel = new QStringListModel({i18n("System Bell"), i18n("System Notifications"), - i18n("Visual Bell"), i18n("Ignore Bell Events")}, - this); + auto *bellModeModel = new QStringListModel({i18n("System Bell"), i18n("System Notifications"), i18n("Visual Bell"), i18n("Ignore Bell Events")}, this); _generalUi->terminalBellCombo->setModel(bellModeModel); _generalUi->terminalBellCombo->setCurrentIndex(profile->property(Profile::BellMode)); // signals and slots - connect(_generalUi->dirSelectButton, &QToolButton::clicked, this, - &Konsole::EditProfileDialog::selectInitialDir); - connect(_generalUi->iconSelectButton, &QPushButton::clicked, this, - &Konsole::EditProfileDialog::selectIcon); - connect(_generalUi->startInSameDirButton, &QCheckBox::toggled, this, - &Konsole::EditProfileDialog::startInSameDir); - connect(_generalUi->profileNameEdit, &QLineEdit::textChanged, this, - &Konsole::EditProfileDialog::profileNameChanged); - connect(_generalUi->initialDirEdit, &QLineEdit::textChanged, this, - &Konsole::EditProfileDialog::initialDirChanged); - connect(_generalUi->commandEdit, &QLineEdit::textChanged, this, - &Konsole::EditProfileDialog::commandChanged); - connect(_generalUi->environmentEditButton, &QPushButton::clicked, this, - &Konsole::EditProfileDialog::showEnvironmentEditor); + connect(_generalUi->dirSelectButton, &QToolButton::clicked, this, &Konsole::EditProfileDialog::selectInitialDir); + connect(_generalUi->iconSelectButton, &QPushButton::clicked, this, &Konsole::EditProfileDialog::selectIcon); + connect(_generalUi->startInSameDirButton, &QCheckBox::toggled, this, &Konsole::EditProfileDialog::startInSameDir); + connect(_generalUi->profileNameEdit, &QLineEdit::textChanged, this, &Konsole::EditProfileDialog::profileNameChanged); + connect(_generalUi->initialDirEdit, &QLineEdit::textChanged, this, &Konsole::EditProfileDialog::initialDirChanged); + connect(_generalUi->commandEdit, &QLineEdit::textChanged, this, &Konsole::EditProfileDialog::commandChanged); + connect(_generalUi->environmentEditButton, &QPushButton::clicked, this, &Konsole::EditProfileDialog::showEnvironmentEditor); - connect(_generalUi->terminalColumnsEntry, - QOverload::of(&QSpinBox::valueChanged), this, - &Konsole::EditProfileDialog::terminalColumnsEntryChanged); - connect(_generalUi->terminalRowsEntry, - QOverload::of(&QSpinBox::valueChanged), this, - &Konsole::EditProfileDialog::terminalRowsEntryChanged); + connect(_generalUi->terminalColumnsEntry, QOverload::of(&QSpinBox::valueChanged), this, &Konsole::EditProfileDialog::terminalColumnsEntryChanged); + connect(_generalUi->terminalRowsEntry, QOverload::of(&QSpinBox::valueChanged), this, &Konsole::EditProfileDialog::terminalRowsEntryChanged); - connect(_generalUi->terminalBellCombo, QOverload::of(&QComboBox::currentIndexChanged), - this, [this](const int index) { + connect(_generalUi->terminalBellCombo, QOverload::of(&QComboBox::currentIndexChanged), this, [this](const int index) { updateTempProfileProperty(Profile::BellMode, index); }); } @@ -522,7 +492,7 @@ void EditProfileDialog::showEnvironmentEditor() // OK/Apply in the parent edit profile dialog, so we make sure // to show the new environment vars if (_tempProfile->isPropertySet(Profile::Environment)) { - currentEnvironment = _tempProfile->environment(); + currentEnvironment = _tempProfile->environment(); } else { currentEnvironment = profile->environment(); } @@ -536,7 +506,7 @@ void EditProfileDialog::showEnvironmentEditor() QStringList newEnvironment; if (ok) { - if(!text.isEmpty()) { + if (!text.isEmpty()) { newEnvironment = text.split(QLatin1Char('\n')); updateTempProfileProperty(Profile::Environment, newEnvironment); } else { @@ -553,12 +523,9 @@ void EditProfileDialog::setupTabsPage(const Profile::Ptr &profile) _tabsUi->renameTabWidget->setRemoteTabTitleText(profile->remoteTabTitleFormat()); _tabsUi->renameTabWidget->setColor(profile->tabColor()); - connect(_tabsUi->renameTabWidget, &Konsole::RenameTabWidget::tabTitleFormatChanged, this, - &Konsole::EditProfileDialog::tabTitleFormatChanged); - connect(_tabsUi->renameTabWidget, &Konsole::RenameTabWidget::remoteTabTitleFormatChanged, this, - &Konsole::EditProfileDialog::remoteTabTitleFormatChanged); - connect(_tabsUi->renameTabWidget, &Konsole::RenameTabWidget::tabColorChanged, this, - &Konsole::EditProfileDialog::tabColorChanged); + connect(_tabsUi->renameTabWidget, &Konsole::RenameTabWidget::tabTitleFormatChanged, this, &Konsole::EditProfileDialog::tabTitleFormatChanged); + connect(_tabsUi->renameTabWidget, &Konsole::RenameTabWidget::remoteTabTitleFormatChanged, this, &Konsole::EditProfileDialog::remoteTabTitleFormatChanged); + connect(_tabsUi->renameTabWidget, &Konsole::RenameTabWidget::tabColorChanged, this, &Konsole::EditProfileDialog::tabColorChanged); // tab monitoring const int silenceSeconds = profile->silenceSeconds(); @@ -568,9 +535,7 @@ void EditProfileDialog::setupTabsPage(const Profile::Ptr &profile) int silenceCheckBoxWidth = maxSpinBoxWidth(_generalUi->terminalColumnsEntry, suffix); _tabsUi->silenceSecondsSpinner->setFixedWidth(silenceCheckBoxWidth); - connect(_tabsUi->silenceSecondsSpinner, - QOverload::of(&QSpinBox::valueChanged), this, - &Konsole::EditProfileDialog::silenceSecondsChanged); + connect(_tabsUi->silenceSecondsSpinner, QOverload::of(&QSpinBox::valueChanged), this, &Konsole::EditProfileDialog::silenceSecondsChanged); } void EditProfileDialog::terminalColumnsEntryChanged(int value) @@ -620,8 +585,7 @@ void EditProfileDialog::silenceSecondsChanged(int seconds) void EditProfileDialog::selectIcon() { - const QString &icon = KIconDialog::getIcon(KIconLoader::Desktop, KIconLoader::Application, - false, 0, false, this); + const QString &icon = KIconDialog::getIcon(KIconLoader::Desktop, KIconLoader::Application, false, 0, false, this); if (!icon.isEmpty()) { _generalUi->iconSelectButton->setIcon(QIcon::fromTheme(icon)); updateTempProfileProperty(Profile::Icon, icon); @@ -655,9 +619,7 @@ void EditProfileDialog::commandChanged(const QString &command) void EditProfileDialog::selectInitialDir() { - const QUrl url = QFileDialog::getExistingDirectoryUrl(this, - i18n("Select Initial Directory"), - QUrl::fromUserInput(_generalUi->initialDirEdit->text())); + const QUrl url = QFileDialog::getExistingDirectoryUrl(this, i18n("Select Initial Directory"), QUrl::fromUserInput(_generalUi->initialDirEdit->text())); if (!url.isEmpty()) { _generalUi->initialDirEdit->setText(url.path()); @@ -699,28 +661,19 @@ void EditProfileDialog::setupAppearancePage(const Profile::Ptr &profile) _appearanceUi->colorSchemeList->installEventFilter(this); _appearanceUi->colorSchemeList->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); - connect(_appearanceUi->colorSchemeList->selectionModel(), - &QItemSelectionModel::selectionChanged, this, - &Konsole::EditProfileDialog::colorSchemeSelected); - connect(_appearanceUi->colorSchemeList, &QListView::entered, this, - &Konsole::EditProfileDialog::previewColorScheme); + connect(_appearanceUi->colorSchemeList->selectionModel(), &QItemSelectionModel::selectionChanged, this, &Konsole::EditProfileDialog::colorSchemeSelected); + connect(_appearanceUi->colorSchemeList, &QListView::entered, this, &Konsole::EditProfileDialog::previewColorScheme); updateColorSchemeButtons(); - connect(_appearanceUi->editColorSchemeButton, &QPushButton::clicked, this, - &Konsole::EditProfileDialog::editColorScheme); - connect(_appearanceUi->removeColorSchemeButton, &QPushButton::clicked, this, - &Konsole::EditProfileDialog::removeColorScheme); - connect(_appearanceUi->newColorSchemeButton, &QPushButton::clicked, this, - &Konsole::EditProfileDialog::newColorScheme); - connect(_appearanceUi->downloadColorSchemeButton, &KNS3::Button::dialogFinished, this, - &Konsole::EditProfileDialog::gotNewColorSchemes); + connect(_appearanceUi->editColorSchemeButton, &QPushButton::clicked, this, &Konsole::EditProfileDialog::editColorScheme); + connect(_appearanceUi->removeColorSchemeButton, &QPushButton::clicked, this, &Konsole::EditProfileDialog::removeColorScheme); + connect(_appearanceUi->newColorSchemeButton, &QPushButton::clicked, this, &Konsole::EditProfileDialog::newColorScheme); + connect(_appearanceUi->downloadColorSchemeButton, &KNS3::Button::dialogFinished, this, &Konsole::EditProfileDialog::gotNewColorSchemes); - connect(_appearanceUi->resetColorSchemeButton, &QPushButton::clicked, this, - &Konsole::EditProfileDialog::resetColorScheme); + connect(_appearanceUi->resetColorSchemeButton, &QPushButton::clicked, this, &Konsole::EditProfileDialog::resetColorScheme); - connect(_appearanceUi->chooseFontButton, &QAbstractButton::clicked, this, - &EditProfileDialog::showFontDialog); + connect(_appearanceUi->chooseFontButton, &QAbstractButton::clicked, this, &EditProfileDialog::showFontDialog); // setup font preview const bool antialias = profile->antiAliasFonts(); @@ -733,20 +686,16 @@ void EditProfileDialog::setupAppearancePage(const Profile::Ptr &profile) // setup font smoothing _appearanceUi->antialiasTextButton->setChecked(antialias); - connect(_appearanceUi->antialiasTextButton, &QCheckBox::toggled, this, - &Konsole::EditProfileDialog::setAntialiasText); + connect(_appearanceUi->antialiasTextButton, &QCheckBox::toggled, this, &Konsole::EditProfileDialog::setAntialiasText); _appearanceUi->boldIntenseButton->setChecked(profile->boldIntense()); - connect(_appearanceUi->boldIntenseButton, &QCheckBox::toggled, this, - &Konsole::EditProfileDialog::setBoldIntense); + connect(_appearanceUi->boldIntenseButton, &QCheckBox::toggled, this, &Konsole::EditProfileDialog::setBoldIntense); _appearanceUi->useFontLineCharactersButton->setChecked(profile->useFontLineCharacters()); - connect(_appearanceUi->useFontLineCharactersButton, &QCheckBox::toggled, this, - &Konsole::EditProfileDialog::useFontLineCharacters); + connect(_appearanceUi->useFontLineCharactersButton, &QCheckBox::toggled, this, &Konsole::EditProfileDialog::useFontLineCharacters); _mouseUi->enableMouseWheelZoomButton->setChecked(profile->mouseWheelZoomEnabled()); - connect(_mouseUi->enableMouseWheelZoomButton, &QCheckBox::toggled, this, - &Konsole::EditProfileDialog::toggleMouseWheelZoom); + connect(_mouseUi->enableMouseWheelZoomButton, &QCheckBox::toggled, this, &Konsole::EditProfileDialog::toggleMouseWheelZoom); // cursor options _appearanceUi->enableBlinkingCursorButton->setChecked(profile->property(Profile::BlinkingCursorEnabled)); @@ -768,43 +717,36 @@ void EditProfileDialog::setupAppearancePage(const Profile::Ptr &profile) const ButtonGroupOptions cursorShapeOptions = { _appearanceUi->cursorShape, // group - Profile::CursorShape, // profileProperty - true, // preview - { // buttons - {_appearanceUi->cursorShapeBlock, Enum::BlockCursor}, - {_appearanceUi->cursorShapeIBeam, Enum::IBeamCursor}, - {_appearanceUi->cursorShapeUnderline, Enum::UnderlineCursor}, + Profile::CursorShape, // profileProperty + true, // preview + { + // buttons + {_appearanceUi->cursorShapeBlock, Enum::BlockCursor}, + {_appearanceUi->cursorShapeIBeam, Enum::IBeamCursor}, + {_appearanceUi->cursorShapeUnderline, Enum::UnderlineCursor}, }, }; setupButtonGroup(cursorShapeOptions, profile); _appearanceUi->marginsSpinner->setValue(profile->terminalMargin()); - connect(_appearanceUi->marginsSpinner, - QOverload::of(&QSpinBox::valueChanged), this, - &Konsole::EditProfileDialog::terminalMarginChanged); + connect(_appearanceUi->marginsSpinner, QOverload::of(&QSpinBox::valueChanged), this, &Konsole::EditProfileDialog::terminalMarginChanged); _appearanceUi->lineSpacingSpinner->setValue(profile->lineSpacing()); - connect(_appearanceUi->lineSpacingSpinner, - QOverload::of(&QSpinBox::valueChanged), this, - &Konsole::EditProfileDialog::lineSpacingChanged); + connect(_appearanceUi->lineSpacingSpinner, QOverload::of(&QSpinBox::valueChanged), this, &Konsole::EditProfileDialog::lineSpacingChanged); _appearanceUi->alignToCenterButton->setChecked(profile->terminalCenter()); - connect(_appearanceUi->alignToCenterButton, &QCheckBox::toggled, this, - &Konsole::EditProfileDialog::setTerminalCenter); + connect(_appearanceUi->alignToCenterButton, &QCheckBox::toggled, this, &Konsole::EditProfileDialog::setTerminalCenter); _appearanceUi->showTerminalSizeHintButton->setChecked(profile->showTerminalSizeHint()); - connect(_appearanceUi->showTerminalSizeHintButton, &QCheckBox::toggled, this, - &Konsole::EditProfileDialog::showTerminalSizeHint); + connect(_appearanceUi->showTerminalSizeHintButton, &QCheckBox::toggled, this, &Konsole::EditProfileDialog::showTerminalSizeHint); _appearanceUi->dimWhenInactiveCheckbox->setChecked(profile->dimWhenInactive()); - connect(_appearanceUi->dimWhenInactiveCheckbox, &QCheckBox::toggled, this, - &Konsole::EditProfileDialog::setDimWhenInactive); + connect(_appearanceUi->dimWhenInactiveCheckbox, &QCheckBox::toggled, this, &Konsole::EditProfileDialog::setDimWhenInactive); _appearanceUi->dimValue->setValue(profile->dimValue()); _appearanceUi->dimValue->setEnabled(profile->dimWhenInactive()); _appearanceUi->dimLabel->setEnabled(profile->dimWhenInactive()); - connect(_appearanceUi->dimValue, &QSlider::valueChanged, - this, &Konsole::EditProfileDialog::setDimValue); + connect(_appearanceUi->dimValue, &QSlider::valueChanged, this, &Konsole::EditProfileDialog::setDimValue); _appearanceUi->invertSelectionColorsCheckbox->setChecked(profile->property(Profile::InvertSelectionColors)); connect(_appearanceUi->invertSelectionColorsCheckbox, &QCheckBox::toggled, this, [this](bool checked) { @@ -812,12 +754,10 @@ void EditProfileDialog::setupAppearancePage(const Profile::Ptr &profile) }); _appearanceUi->displayVerticalLine->setChecked(profile->verticalLine()); - connect(_appearanceUi->displayVerticalLine, &QCheckBox::toggled, - this, &EditProfileDialog::setVerticalLine); + connect(_appearanceUi->displayVerticalLine, &QCheckBox::toggled, this, &EditProfileDialog::setVerticalLine); _appearanceUi->displayVerticalLineAtColumn->setValue(profile->verticalLineAtChar()); - connect(_appearanceUi->displayVerticalLineAtColumn, QOverload::of(&QSpinBox::valueChanged), - this, &EditProfileDialog::setVerticalLineColumn); + connect(_appearanceUi->displayVerticalLineAtColumn, QOverload::of(&QSpinBox::valueChanged), this, &EditProfileDialog::setVerticalLineColumn); } void EditProfileDialog::setAntialiasText(bool enable) @@ -951,7 +891,7 @@ void EditProfileDialog::updateColorSchemeList(const QString &selectedColorScheme QStandardItem *selectedItem = nullptr; - const QList schemeList = ColorSchemeManager::instance()->allColorSchemes(); + const QList schemeList = ColorSchemeManager::instance()->allColorSchemes(); for (const ColorScheme *scheme : schemeList) { QStandardItem *item = new QStandardItem(scheme->description()); @@ -972,8 +912,7 @@ void EditProfileDialog::updateColorSchemeList(const QString &selectedColorScheme if (selectedItem != nullptr) { _appearanceUi->colorSchemeList->updateGeometry(); - _appearanceUi->colorSchemeList->selectionModel()->setCurrentIndex(selectedItem->index(), - QItemSelectionModel::Select); + _appearanceUi->colorSchemeList->selectionModel()->setCurrentIndex(selectedItem->index(), QItemSelectionModel::Select); // update transparency warning label updateTransparencyWarning(); @@ -1018,8 +957,7 @@ void EditProfileDialog::updateKeyBindingsList(const QString &selectKeyBindingsNa model->sort(0); if (selectedItem != nullptr) { - _keyboardUi->keyBindingList->selectionModel()->setCurrentIndex(selectedItem->index(), - QItemSelectionModel::Select); + _keyboardUi->keyBindingList->selectionModel()->setCurrentIndex(selectedItem->index(), QItemSelectionModel::Select); } } @@ -1045,7 +983,7 @@ QSize EditProfileDialog::sizeHint() const // on "tabs" page wider and to add some whitespace on right side // of other pages. The window will not be wider than 2/3 of // the screen width (unless necessary to fit everything) - return QDialog::sizeHint() + QSize(10*ch, 0); + return QDialog::sizeHint() + QSize(10 * ch, 0); } void EditProfileDialog::unpreviewAll() @@ -1114,14 +1052,12 @@ void EditProfileDialog::preview(int property, const QVariant &value) // // TODO - Save the original values for each profile and use to unpreview properties ProfileGroup::Ptr group = original->asGroup(); - if (group && group->profiles().count() > 1 - && original->property(static_cast(property)).isNull()) { + if (group && group->profiles().count() > 1 && original->property(static_cast(property)).isNull()) { return; } if (!_previewedProperties.contains(property)) { - _previewedProperties.insert(property, - original->property(static_cast(property))); + _previewedProperties.insert(property, original->property(static_cast(property))); } // temporary change to color scheme @@ -1195,14 +1131,9 @@ void EditProfileDialog::gotNewColorSchemes(const KNS3::Entry::List &changedEntri ++failures; } if (failures == entry.installedFiles().size()) { - _appearanceUi->colorSchemeMessageWidget->setText( - xi18nc("@info", - "Scheme %1 failed to load.", - entry.name())); + _appearanceUi->colorSchemeMessageWidget->setText(xi18nc("@info", "Scheme %1 failed to load.", entry.name())); _appearanceUi->colorSchemeMessageWidget->animatedShow(); - QTimer::singleShot(8000, - _appearanceUi->colorSchemeMessageWidget, - &KMessageWidget::animatedHide); + QTimer::singleShot(8000, _appearanceUi->colorSchemeMessageWidget, &KMessageWidget::animatedHide); } break; case KNS3::Entry::Deleted: @@ -1229,7 +1160,6 @@ void EditProfileDialog::gotNewColorSchemes(const KNS3::Entry::List &changedEntri void EditProfileDialog::resetColorScheme() { - QModelIndexList selected = _appearanceUi->colorSchemeList->selectionModel()->selectedIndexes(); if (!selected.isEmpty()) { @@ -1263,8 +1193,7 @@ void EditProfileDialog::showColorSchemeEditor(bool isNewScheme) } _colorDialog = new ColorSchemeEditor(this); - connect(_colorDialog, &Konsole::ColorSchemeEditor::colorSchemeSaveRequested, this, - &Konsole::EditProfileDialog::saveColorScheme); + connect(_colorDialog, &Konsole::ColorSchemeEditor::colorSchemeSaveRequested, this, &Konsole::EditProfileDialog::saveColorScheme); _colorDialog->setup(colors, isNewScheme); _colorDialog->show(); @@ -1344,7 +1273,6 @@ void EditProfileDialog::updateColorSchemeButtons() _appearanceUi->removeColorSchemeButton->setEnabled(false); _appearanceUi->resetColorSchemeButton->setEnabled(false); } - } void EditProfileDialog::updateKeyBindingsButtons() @@ -1381,15 +1309,15 @@ void EditProfileDialog::updateTransparencyWarning() if (!needTransparency) { _appearanceUi->transparencyWarningWidget->setHidden(true); } else if (!KWindowSystem::compositingActive()) { - _appearanceUi->transparencyWarningWidget->setText(i18n( - "This color scheme uses a transparent background" - " which does not appear to be supported on your" - " desktop")); + _appearanceUi->transparencyWarningWidget->setText( + i18n("This color scheme uses a transparent background" + " which does not appear to be supported on your" + " desktop")); _appearanceUi->transparencyWarningWidget->setHidden(false); } else if (!WindowSystemInfo::HAVE_TRANSPARENCY) { - _appearanceUi->transparencyWarningWidget->setText(i18n( - "Konsole was started before desktop effects were enabled." - " You need to restart Konsole to see transparent background.")); + _appearanceUi->transparencyWarningWidget->setText( + i18n("Konsole was started before desktop effects were enabled." + " You need to restart Konsole to see transparent background.")); _appearanceUi->transparencyWarningWidget->setHidden(false); } } @@ -1424,11 +1352,11 @@ void EditProfileDialog::updateButtonApply() userModified = true; break; } - // for not-previewed property - // - // for the Profile::KeyBindings property, if it's set in the _tempProfile - // then the user opened the edit key bindings dialog and clicked - // OK, and could have add/removed a key bindings rule + // for not-previewed property + // + // for the Profile::KeyBindings property, if it's set in the _tempProfile + // then the user opened the edit key bindings dialog and clicked + // OK, and could have add/removed a key bindings rule } else if (property == Profile::KeyBindings || (value != _profile->property(property))) { userModified = true; break; @@ -1438,16 +1366,13 @@ void EditProfileDialog::updateButtonApply() _buttonBox->button(QDialogButtonBox::Apply)->setEnabled(userModified); } -void EditProfileDialog::setupKeyboardPage(const Profile::Ptr &/* profile */) +void EditProfileDialog::setupKeyboardPage(const Profile::Ptr & /* profile */) { // setup translator list updateKeyBindingsList(lookupProfile()->keyBindings()); - connect(_keyboardUi->keyBindingList->selectionModel(), - &QItemSelectionModel::selectionChanged, this, - &Konsole::EditProfileDialog::keyBindingSelected); - connect(_keyboardUi->newKeyBindingsButton, &QPushButton::clicked, this, - &Konsole::EditProfileDialog::newKeyBinding); + connect(_keyboardUi->keyBindingList->selectionModel(), &QItemSelectionModel::selectionChanged, this, &Konsole::EditProfileDialog::keyBindingSelected); + connect(_keyboardUi->newKeyBindingsButton, &QPushButton::clicked, this, &Konsole::EditProfileDialog::newKeyBinding); _keyboardUi->editKeyBindingsButton->setIcon(QIcon::fromTheme(QStringLiteral("document-edit"))); _keyboardUi->removeKeyBindingsButton->setIcon(QIcon::fromTheme(QStringLiteral("edit-delete"))); @@ -1460,12 +1385,9 @@ void EditProfileDialog::setupKeyboardPage(const Profile::Ptr &/* profile */) updateKeyBindingsButtons(); - connect(_keyboardUi->editKeyBindingsButton, &QPushButton::clicked, this, - &Konsole::EditProfileDialog::editKeyBinding); - connect(_keyboardUi->removeKeyBindingsButton, &QPushButton::clicked, this, - &Konsole::EditProfileDialog::removeKeyBinding); - connect(_keyboardUi->resetKeyBindingsButton, &QPushButton::clicked, this, - &Konsole::EditProfileDialog::resetKeyBindings); + connect(_keyboardUi->editKeyBindingsButton, &QPushButton::clicked, this, &Konsole::EditProfileDialog::editKeyBinding); + connect(_keyboardUi->removeKeyBindingsButton, &QPushButton::clicked, this, &Konsole::EditProfileDialog::removeKeyBinding); + connect(_keyboardUi->resetKeyBindingsButton, &QPushButton::clicked, this, &Konsole::EditProfileDialog::resetKeyBindings); } void EditProfileDialog::keyBindingSelected() @@ -1474,8 +1396,7 @@ void EditProfileDialog::keyBindingSelected() if (!selected.isEmpty()) { QAbstractItemModel *model = _keyboardUi->keyBindingList->model(); - const auto *translator = model->data(selected.first(), Qt::UserRole + 1) - .value(); + const auto *translator = model->data(selected.first(), Qt::UserRole + 1).value(); if (translator != nullptr) { updateTempProfileProperty(Profile::KeyBindings, translator->name()); } @@ -1516,10 +1437,8 @@ void EditProfileDialog::showKeyBindingEditor(bool isNewTranslator) editor->setup(translator, lookupProfile()->keyBindings(), isNewTranslator); } - connect(editor, &Konsole::KeyBindingEditor::updateKeyBindingsListRequest, - this, &Konsole::EditProfileDialog::updateKeyBindingsList); - connect(editor, &Konsole::KeyBindingEditor::updateTempProfileKeyBindingsRequest, - this, &Konsole::EditProfileDialog::updateTempProfileProperty); + connect(editor, &Konsole::KeyBindingEditor::updateKeyBindingsListRequest, this, &Konsole::EditProfileDialog::updateKeyBindingsList); + connect(editor, &Konsole::KeyBindingEditor::updateTempProfileKeyBindingsRequest, this, &Konsole::EditProfileDialog::updateTempProfileProperty); editor->show(); } @@ -1553,7 +1472,7 @@ void EditProfileDialog::setupButtonGroup(const ButtonGroupOptions &options, cons { auto currentValue = profile->property(options.profileProperty); - for (auto option: options.buttons) { + for (auto option : options.buttons) { options.group->setId(option.button, option.value); } @@ -1563,8 +1482,7 @@ void EditProfileDialog::setupButtonGroup(const ButtonGroupOptions &options, cons activeButton = options.buttons[0].button; } activeButton->setChecked(true); - connect(options.group, QOverload::of(&QButtonGroup::idClicked), - this, [this, options](int value) { + connect(options.group, QOverload::of(&QButtonGroup::idClicked), this, [this, options](int value) { if (options.preview) { preview(options.profileProperty, value); } @@ -1576,13 +1494,14 @@ void EditProfileDialog::setupScrollingPage(const Profile::Ptr &profile) { // setup scrollbar radio const ButtonGroupOptions scrollBarPositionOptions = { - _scrollingUi->scrollBarPosition, // group - Profile::ScrollBarPosition, // profileProperty - false, // preview - { // buttons - {_scrollingUi->scrollBarRightButton, Enum::ScrollBarRight}, - {_scrollingUi->scrollBarLeftButton, Enum::ScrollBarLeft}, - {_scrollingUi->scrollBarHiddenButton, Enum::ScrollBarHidden}, + _scrollingUi->scrollBarPosition, // group + Profile::ScrollBarPosition, // profileProperty + false, // preview + { + // buttons + {_scrollingUi->scrollBarRightButton, Enum::ScrollBarRight}, + {_scrollingUi->scrollBarLeftButton, Enum::ScrollBarLeft}, + {_scrollingUi->scrollBarHiddenButton, Enum::ScrollBarHidden}, }, }; setupButtonGroup(scrollBarPositionOptions, profile); @@ -1590,8 +1509,7 @@ void EditProfileDialog::setupScrollingPage(const Profile::Ptr &profile) // setup scrollback type radio auto scrollBackType = profile->property(Profile::HistoryMode); _scrollingUi->historySizeWidget->setMode(Enum::HistoryModeEnum(scrollBackType)); - connect(_scrollingUi->historySizeWidget, &Konsole::HistorySizeWidget::historyModeChanged, this, - &Konsole::EditProfileDialog::historyModeChanged); + connect(_scrollingUi->historySizeWidget, &Konsole::HistorySizeWidget::historyModeChanged, this, &Konsole::EditProfileDialog::historyModeChanged); // setup scrollback line count spinner const int historySize = profile->historySize(); @@ -1607,14 +1525,13 @@ void EditProfileDialog::setupScrollingPage(const Profile::Ptr &profile) connect(_scrollingUi->scrollFullPage, &QPushButton::clicked, this, &EditProfileDialog::scrollFullPage); _scrollingUi->highlightScrolledLinesButton->setChecked(profile->property(Profile::HighlightScrolledLines)); - connect(_scrollingUi->highlightScrolledLinesButton, &QPushButton::clicked, this, &EditProfileDialog::toggleHighlightScrolledLines); + connect(_scrollingUi->highlightScrolledLinesButton, &QPushButton::clicked, this, &EditProfileDialog::toggleHighlightScrolledLines); _scrollingUi->reflowLinesButton->setChecked(profile->property(Profile::ReflowLines)); - connect(_scrollingUi->reflowLinesButton, &QPushButton::clicked, this, &EditProfileDialog::toggleReflowLines); + connect(_scrollingUi->reflowLinesButton, &QPushButton::clicked, this, &EditProfileDialog::toggleReflowLines); // signals and slots - connect(_scrollingUi->historySizeWidget, &Konsole::HistorySizeWidget::historySizeChanged, this, - &Konsole::EditProfileDialog::historySizeChanged); + connect(_scrollingUi->historySizeWidget, &Konsole::HistorySizeWidget::historySizeChanged, this, &Konsole::EditProfileDialog::historySizeChanged); } void EditProfileDialog::historySizeChanged(int lineCount) @@ -1687,11 +1604,12 @@ void EditProfileDialog::setupMousePage(const Profile::Ptr &profile) connect(_mouseUi->wordCharacterEdit, &QLineEdit::textChanged, this, &Konsole::EditProfileDialog::wordCharactersChanged); const ButtonGroupOptions tripleClickModeOptions = { - _mouseUi->tripleClickMode, // group - Profile::TripleClickMode, // profileProperty - false, // preview - { // buttons - {_mouseUi->tripleClickSelectsTheWholeLine, Enum::SelectWholeLine}, + _mouseUi->tripleClickMode, // group + Profile::TripleClickMode, // profileProperty + false, // preview + { + // buttons + {_mouseUi->tripleClickSelectsTheWholeLine, Enum::SelectWholeLine}, {_mouseUi->tripleClickSelectsFromMousePosition, Enum::SelectForwardsFromCursor}, }, }; @@ -1703,23 +1621,19 @@ void EditProfileDialog::setupMousePage(const Profile::Ptr &profile) connect(_mouseUi->enableMouseWheelZoomButton, &QCheckBox::toggled, this, &Konsole::EditProfileDialog::toggleMouseWheelZoom); _mouseUi->allowLinkEscapeSequenceButton->setChecked(profile->allowEscapedLinks()); - connect(_mouseUi->allowLinkEscapeSequenceButton, &QPushButton::clicked, - this, &Konsole::EditProfileDialog::toggleAllowLinkEscapeSequence); + connect(_mouseUi->allowLinkEscapeSequenceButton, &QPushButton::clicked, this, &Konsole::EditProfileDialog::toggleAllowLinkEscapeSequence); _mouseUi->linkEscapeSequenceTexts->setEnabled(profile->allowEscapedLinks()); _mouseUi->linkEscapeSequenceTexts->setText(profile->escapedLinksSchema().join(QLatin1Char(';'))); - connect(_mouseUi->linkEscapeSequenceTexts, &QLineEdit::textChanged, - this, &Konsole::EditProfileDialog::linkEscapeSequenceTextsChanged); + connect(_mouseUi->linkEscapeSequenceTexts, &QLineEdit::textChanged, this, &Konsole::EditProfileDialog::linkEscapeSequenceTextsChanged); setTextEditorCombo(profile); } void EditProfileDialog::setTextEditorCombo(const Profile::Ptr &profile) { - std::array editorsList = { Enum::Kate, Enum::KWrite, - Enum::KDevelop, Enum::QtCreator, - Enum::Gedit, Enum::gVim, - Enum::CustomTextEditor }; + std::array editorsList = + {Enum::Kate, Enum::KWrite, Enum::KDevelop, Enum::QtCreator, Enum::Gedit, Enum::gVim, Enum::CustomTextEditor}; auto *editorCombo = _mouseUi->textEditorCombo; @@ -1730,7 +1644,7 @@ void EditProfileDialog::setTextEditorCombo(const Profile::Ptr &profile) QString exec; QString displayName; QIcon icon; - switch(editor) { + switch (editor) { case Enum::Kate: exec = QStringLiteral("kate"); displayName = QStringLiteral("Kate"); @@ -1772,8 +1686,7 @@ void EditProfileDialog::setTextEditorCombo(const Profile::Ptr &profile) editorCombo->addItem(icon, displayName); // For "CustomTextEditor" we don't check if the binary exists - const bool isAvailable = editor == Enum::CustomTextEditor - || !QStandardPaths::findExecutable(exec).isEmpty(); + const bool isAvailable = editor == Enum::CustomTextEditor || !QStandardPaths::findExecutable(exec).isEmpty(); // Make un-available editors look disabled in the combobox model->item(static_cast(editor))->setEnabled(isAvailable); } @@ -1781,26 +1694,25 @@ void EditProfileDialog::setTextEditorCombo(const Profile::Ptr &profile) const auto currentEditor = profile->property(Profile::TextEditorCmd); editorCombo->setCurrentIndex(currentEditor); - connect(editorCombo, QOverload::of(&QComboBox::currentIndexChanged), - this, [this](const int index) { + connect(editorCombo, QOverload::of(&QComboBox::currentIndexChanged), this, [this](const int index) { updateTempProfileProperty(Profile::TextEditorCmd, index); _mouseUi->textEditorCustomBtn->setEnabled(index == Enum::CustomTextEditor); }); _mouseUi->textEditorCustomBtn->setEnabled(currentEditor == Enum::CustomTextEditor); - connect(_mouseUi->textEditorCustomBtn, &QAbstractButton::clicked, - this, [this, profile]() { + connect(_mouseUi->textEditorCustomBtn, &QAbstractButton::clicked, this, [this, profile]() { auto *dlg = new QInputDialog(static_cast(this)); - dlg->setLabelText(i18n("The format is e.g. 'editorExec PATH:LINE:COLUMN'\n\n" - "PATH will be replaced by the path to the text file\n" - "LINE will be replaced by the line number\n" - "COLUMN (optional) will be replaced by the column number\n" - "Note: you will need to replace 'PATH:LINE:COLUMN' by the actual\n" - "syntax the editor you want to use supports; e.g.:\n" - "gedit +LINE:COLUMN PATH\n\n" - "If PATH or LINE aren't present in the command, this setting\n" - "will be ignored and the file will be opened by the default text\n" - "editor.")); + dlg->setLabelText( + i18n("The format is e.g. 'editorExec PATH:LINE:COLUMN'\n\n" + "PATH will be replaced by the path to the text file\n" + "LINE will be replaced by the line number\n" + "COLUMN (optional) will be replaced by the column number\n" + "Note: you will need to replace 'PATH:LINE:COLUMN' by the actual\n" + "syntax the editor you want to use supports; e.g.:\n" + "gedit +LINE:COLUMN PATH\n\n" + "If PATH or LINE aren't present in the command, this setting\n" + "will be ignored and the file will be opened by the default text\n" + "editor.")); const QString cmd = profile->customTextEditorCmd(); dlg->setTextValue(cmd); dlg->setAttribute(Qt::WA_DeleteOnClose); @@ -1834,10 +1746,10 @@ void EditProfileDialog::setupAdvancedPage(const Profile::Ptr &profile) // Setup the URL hints modifier checkboxes { auto modifiers = profile->property(Profile::UrlHintsModifiers); - _advancedUi->urlHintsModifierShift->setChecked((modifiers &Qt::ShiftModifier) != 0U); - _advancedUi->urlHintsModifierCtrl->setChecked((modifiers &Qt::ControlModifier) != 0U); - _advancedUi->urlHintsModifierAlt->setChecked((modifiers &Qt::AltModifier) != 0U); - _advancedUi->urlHintsModifierMeta->setChecked((modifiers &Qt::MetaModifier) != 0U); + _advancedUi->urlHintsModifierShift->setChecked((modifiers & Qt::ShiftModifier) != 0U); + _advancedUi->urlHintsModifierCtrl->setChecked((modifiers & Qt::ControlModifier) != 0U); + _advancedUi->urlHintsModifierAlt->setChecked((modifiers & Qt::AltModifier) != 0U); + _advancedUi->urlHintsModifierMeta->setChecked((modifiers & Qt::MetaModifier) != 0U); connect(_advancedUi->urlHintsModifierShift, &QCheckBox::toggled, this, &EditProfileDialog::updateUrlHintsModifier); connect(_advancedUi->urlHintsModifierCtrl, &QCheckBox::toggled, this, &EditProfileDialog::updateUrlHintsModifier); connect(_advancedUi->urlHintsModifierAlt, &QCheckBox::toggled, this, &EditProfileDialog::updateUrlHintsModifier); @@ -1850,9 +1762,11 @@ void EditProfileDialog::setupAdvancedPage(const Profile::Ptr &profile) _advancedUi->selectEncodingButton->setMenu(codecAction->menu()); connect(codecAction, #if KCONFIGWIDGETS_VERSION >= QT_VERSION_CHECK(5, 78, 0) - QOverload::of(&KCodecAction::codecTriggered), this, + QOverload::of(&KCodecAction::codecTriggered), + this, #else - QOverload::of(&KCodecAction::triggered), this, + QOverload::of(&KCodecAction::triggered), + this, #endif &Konsole::EditProfileDialog::setDefaultCodec); @@ -1867,29 +1781,27 @@ int EditProfileDialog::maxSpinBoxWidth(const KPluralHandlingSpinBox *spinBox, co static const int cursorWidth = 2; const QFontMetrics fm(spinBox->fontMetrics()); - const QString plural = suffix.subs(2).toString(); - const QString singular = suffix.subs(1).toString(); - const QString min = QString::number(spinBox->minimum()); - const QString max = QString::number(spinBox->maximum()); - const int pluralWidth = fm.boundingRect(plural).width(); + const QString plural = suffix.subs(2).toString(); + const QString singular = suffix.subs(1).toString(); + const QString min = QString::number(spinBox->minimum()); + const QString max = QString::number(spinBox->maximum()); + const int pluralWidth = fm.boundingRect(plural).width(); const int singularWidth = fm.boundingRect(singular).width(); - const int minWidth = fm.boundingRect(min).width(); - const int maxWidth = fm.boundingRect(max).width(); - const int width = qMax(pluralWidth, singularWidth) + qMax(minWidth, maxWidth) + cursorWidth; + const int minWidth = fm.boundingRect(min).width(); + const int maxWidth = fm.boundingRect(max).width(); + const int width = qMax(pluralWidth, singularWidth) + qMax(minWidth, maxWidth) + cursorWidth; // Based on QAbstractSpinBox::initStyleOption() from Qt QStyleOptionSpinBox opt; opt.initFrom(spinBox); - opt.activeSubControls = QStyle::SC_None; - opt.buttonSymbols = spinBox->buttonSymbols(); + opt.activeSubControls = QStyle::SC_None; + opt.buttonSymbols = spinBox->buttonSymbols(); // Assume all spinboxes have buttons - opt.subControls = QStyle::SC_SpinBoxFrame | QStyle::SC_SpinBoxEditField - | QStyle::SC_SpinBoxUp | QStyle::SC_SpinBoxDown; - opt.frame = spinBox->hasFrame(); + opt.subControls = QStyle::SC_SpinBoxFrame | QStyle::SC_SpinBoxEditField | QStyle::SC_SpinBoxUp | QStyle::SC_SpinBoxDown; + opt.frame = spinBox->hasFrame(); const QSize hint(width, spinBox->sizeHint().height()); - const QSize spinBoxSize = style()->sizeFromContents(QStyle::CT_SpinBox, &opt, hint, spinBox) - .expandedTo(QApplication::globalStrut()); + const QSize spinBoxSize = style()->sizeFromContents(QStyle::CT_SpinBox, &opt, hint, spinBox).expandedTo(QApplication::globalStrut()); return spinBoxSize.width(); } diff --git a/src/widgets/EditProfileDialog.h b/src/widgets/EditProfileDialog.h index 7e6fadd67..85b677e30 100644 --- a/src/widgets/EditProfileDialog.h +++ b/src/widgets/EditProfileDialog.h @@ -9,8 +9,8 @@ #define EDITPROFILEDIALOG_H // KDE -#include #include +#include // Konsole #include "colorscheme/ColorScheme.h" @@ -21,24 +21,26 @@ #include "profile/ProfileGroup.h" #include "Enumeration.h" -#include "keyboardtranslator/KeyboardTranslatorManager.h" #include "FontDialog.h" #include "LabelsAligner.h" +#include "keyboardtranslator/KeyboardTranslatorManager.h" class KPluralHandlingSpinBox; class KLocalizedString; class QItemSelectionModel; -namespace Ui { - class EditProfileGeneralPage; - class EditProfileTabsPage; - class EditProfileAppearancePage; - class EditProfileScrollingPage; - class EditProfileKeyboardPage; - class EditProfileMousePage; - class EditProfileAdvancedPage; +namespace Ui +{ +class EditProfileGeneralPage; +class EditProfileTabsPage; +class EditProfileAppearancePage; +class EditProfileScrollingPage; +class EditProfileKeyboardPage; +class EditProfileMousePage; +class EditProfileAdvancedPage; } -namespace Konsole { +namespace Konsole +{ /** * A dialog which allows the user to edit a profile. * After the dialog is created, it can be initialized with the settings @@ -52,7 +54,7 @@ namespace Konsole { * the persistent argument set to false. These changes are then * un-done when the dialog is closed. */ -class KONSOLEPRIVATE_EXPORT EditProfileDialog: public KPageDialog +class KONSOLEPRIVATE_EXPORT EditProfileDialog : public KPageDialog { Q_OBJECT @@ -219,16 +221,7 @@ private Q_SLOTS: private: Q_DISABLE_COPY(EditProfileDialog) - enum PageID { - GeneralPage = 0, - TabsPage, - AppearancePage, - ScrollingPage, - KeyboardPage, - MousePage, - AdvancedPage, - PagesCount - }; + enum PageID { GeneralPage = 0, TabsPage, AppearancePage, ScrollingPage, KeyboardPage, MousePage, AdvancedPage, PagesCount, }; // initialize various pages of the dialog void setupGeneralPage(const Profile::Ptr &profile); @@ -309,20 +302,21 @@ private: // otherwise returns true. bool isProfileNameValid(); - Ui::EditProfileGeneralPage *_generalUi; - Ui::EditProfileTabsPage *_tabsUi; - Ui::EditProfileAppearancePage *_appearanceUi; - Ui::EditProfileScrollingPage *_scrollingUi; - Ui::EditProfileKeyboardPage *_keyboardUi; - Ui::EditProfileMousePage *_mouseUi; - Ui::EditProfileAdvancedPage *_advancedUi; + Ui::EditProfileGeneralPage *_generalUi; + Ui::EditProfileTabsPage *_tabsUi; + Ui::EditProfileAppearancePage *_appearanceUi; + Ui::EditProfileScrollingPage *_scrollingUi; + Ui::EditProfileKeyboardPage *_keyboardUi; + Ui::EditProfileMousePage *_mouseUi; + Ui::EditProfileAdvancedPage *_advancedUi; using PageSetupMethod = void (EditProfileDialog::*)(const Profile::Ptr &); struct Page { Page(PageSetupMethod page = nullptr, bool update = false) : setupPage(page) , needsUpdate(update) - {} + { + } PageSetupMethod setupPage; bool needsUpdate; diff --git a/src/widgets/HistorySizeWidget.cpp b/src/widgets/HistorySizeWidget.cpp index b7de19ec5..58d82e785 100644 --- a/src/widgets/HistorySizeWidget.cpp +++ b/src/widgets/HistorySizeWidget.cpp @@ -9,8 +9,8 @@ #include "widgets/HistorySizeWidget.h" // Qt -#include #include +#include #include #include @@ -20,33 +20,30 @@ using namespace Konsole; -HistorySizeWidget::HistorySizeWidget(QWidget *parent) : - QWidget(parent), - _ui(nullptr) +HistorySizeWidget::HistorySizeWidget(QWidget *parent) + : QWidget(parent) + , _ui(nullptr) { _ui = new Ui::HistorySizeWidget(); _ui->setupUi(this); // focus and select the spinner automatically when appropriate _ui->fixedSizeHistoryButton->setFocusProxy(_ui->historyLineSpinner); - connect(_ui->fixedSizeHistoryButton, &QRadioButton::clicked, - _ui->historyLineSpinner, - &KPluralHandlingSpinBox::selectAll); + connect(_ui->fixedSizeHistoryButton, &QRadioButton::clicked, _ui->historyLineSpinner, &KPluralHandlingSpinBox::selectAll); auto modeGroup = new QButtonGroup(this); modeGroup->addButton(_ui->noHistoryButton); modeGroup->addButton(_ui->fixedSizeHistoryButton); modeGroup->addButton(_ui->unlimitedHistoryButton); - connect(modeGroup, - static_cast(&QButtonGroup::buttonClicked), - this, &Konsole::HistorySizeWidget::buttonClicked); + connect(modeGroup, static_cast(&QButtonGroup::buttonClicked), this, &Konsole::HistorySizeWidget::buttonClicked); _ui->historyLineSpinner->setSuffix(ki18ncp("@label:textbox Unit of scrollback", " line", " lines")); setLineCount(HistorySizeWidget::DefaultLineCount); connect(_ui->historyLineSpinner, static_cast(&KPluralHandlingSpinBox::valueChanged), - this, &Konsole::HistorySizeWidget::historySizeChanged); + this, + &Konsole::HistorySizeWidget::historySizeChanged); auto warningButtonSizePolicy = _ui->fixedSizeHistoryWarningButton->sizePolicy(); warningButtonSizePolicy.setRetainSizeWhenHidden(true); @@ -56,19 +53,24 @@ HistorySizeWidget::HistorySizeWidget(QWidget *parent) : connect(_ui->fixedSizeHistoryButton, &QAbstractButton::toggled, _ui->historyLineSpinner, &QWidget::setEnabled); connect(_ui->fixedSizeHistoryButton, &QAbstractButton::toggled, _ui->fixedSizeHistoryWarningButton, &QWidget::setVisible); connect(_ui->fixedSizeHistoryWarningButton, &QToolButton::clicked, this, [this](bool) { - const QString message = i18nc("@info:whatsthis", "When using this option, the scrollback data will be saved to RAM. If you choose a huge value, your system may run out of free RAM and cause serious issues with your system."); - const QPoint pos = QPoint(_ui->fixedSizeHistoryWrapper->width() / 2, _ui->fixedSizeHistoryWrapper->height()); - QWhatsThis::showText(_ui->fixedSizeHistoryWrapper->mapToGlobal(pos), message, _ui->fixedSizeHistoryWrapper); - }); + const QString message = i18nc("@info:whatsthis", + "When using this option, the scrollback data will be saved to RAM. If you choose a huge value, your system may run out " + "of free RAM and cause serious issues with your system."); + const QPoint pos = QPoint(_ui->fixedSizeHistoryWrapper->width() / 2, _ui->fixedSizeHistoryWrapper->height()); + QWhatsThis::showText(_ui->fixedSizeHistoryWrapper->mapToGlobal(pos), message, _ui->fixedSizeHistoryWrapper); + }); _ui->unlimitedHistoryWarningButton->setSizePolicy(warningButtonSizePolicy); _ui->unlimitedHistoryWarningButton->hide(); connect(_ui->unlimitedHistoryButton, &QAbstractButton::toggled, _ui->unlimitedHistoryWarningButton, &QWidget::setVisible); connect(_ui->unlimitedHistoryWarningButton, &QToolButton::clicked, this, [this](bool) { - const auto message = xi18nc("@info:tooltip", "When using this option, the scrollback data will be written unencrypted to temporary files. Those temporary files will be deleted automatically when Konsole is closed in a normal manner.Use Settings → Configure Konsole → File Location to select the location of the temporary files."); - const QPoint pos = QPoint(_ui->unlimitedHistoryWrapper->width() / 2, _ui->unlimitedHistoryWrapper->height()); - QWhatsThis::showText(_ui->unlimitedHistoryWrapper->mapToGlobal(pos), message, _ui->unlimitedHistoryWrapper); - }); + const auto message = xi18nc("@info:tooltip", + "When using this option, the scrollback data will be written unencrypted to temporary files. Those temporary files will be " + "deleted automatically when Konsole is closed in a normal manner.Use Settings → Configure Konsole → File " + "Location to select the location of the temporary files."); + const QPoint pos = QPoint(_ui->unlimitedHistoryWrapper->width() / 2, _ui->unlimitedHistoryWrapper->height()); + QWhatsThis::showText(_ui->unlimitedHistoryWrapper->mapToGlobal(pos), message, _ui->unlimitedHistoryWrapper); + }); // Make radio buttons height equal // fixedSizeHistoryWrapper contains radio + spinbox + toolbutton, so it diff --git a/src/widgets/HistorySizeWidget.h b/src/widgets/HistorySizeWidget.h index 2c4d04f1c..df1feb719 100644 --- a/src/widgets/HistorySizeWidget.h +++ b/src/widgets/HistorySizeWidget.h @@ -16,11 +16,13 @@ class QAbstractButton; -namespace Ui { +namespace Ui +{ class HistorySizeWidget; } -namespace Konsole { +namespace Konsole +{ /** * A widget for controlling history related options */ diff --git a/src/widgets/IncrementalSearchBar.cpp b/src/widgets/IncrementalSearchBar.cpp index ab35cd7c5..4037ce355 100644 --- a/src/widgets/IncrementalSearchBar.cpp +++ b/src/widgets/IncrementalSearchBar.cpp @@ -8,32 +8,32 @@ #include "widgets/IncrementalSearchBar.h" // Qt +#include #include #include +#include #include #include -#include -#include // KDE -#include -#include -#include #include "KonsoleSettings.h" +#include +#include +#include using namespace Konsole; -IncrementalSearchBar::IncrementalSearchBar(QWidget *parent) : - QWidget(parent), - _searchEdit(nullptr), - _caseSensitive(nullptr), - _regExpression(nullptr), - _highlightMatches(nullptr), - _reverseSearch(nullptr), - _findNextButton(nullptr), - _findPreviousButton(nullptr), - _searchFromButton(nullptr), - _searchTimer(nullptr) +IncrementalSearchBar::IncrementalSearchBar(QWidget *parent) + : QWidget(parent) + , _searchEdit(nullptr) + , _caseSensitive(nullptr) + , _regExpression(nullptr) + , _highlightMatches(nullptr) + , _reverseSearch(nullptr) + , _findNextButton(nullptr) + , _findPreviousButton(nullptr) + , _searchFromButton(nullptr) + , _searchTimer(nullptr) { setPalette(qApp->palette()); setAutoFillBackground(true); @@ -65,39 +65,32 @@ IncrementalSearchBar::IncrementalSearchBar(QWidget *parent) : _searchTimer = new QTimer(this); _searchTimer->setInterval(250); _searchTimer->setSingleShot(true); - connect(_searchTimer, &QTimer::timeout, this, - &Konsole::IncrementalSearchBar::notifySearchChanged); - connect(_searchEdit, &QLineEdit::textChanged, _searchTimer, - static_cast(&QTimer::start)); + connect(_searchTimer, &QTimer::timeout, this, &Konsole::IncrementalSearchBar::notifySearchChanged); + connect(_searchEdit, &QLineEdit::textChanged, _searchTimer, static_cast(&QTimer::start)); _findNextButton = new QToolButton(this); _findNextButton->setObjectName(QStringLiteral("find-next-button")); _findNextButton->setText(i18nc("@action:button Go to the next phrase", "Next")); _findNextButton->setToolButtonStyle(Qt::ToolButtonIconOnly); _findNextButton->setAutoRaise(true); - _findNextButton->setToolTip(i18nc("@info:tooltip", - "Find the next match for the current search phrase")); + _findNextButton->setToolTip(i18nc("@info:tooltip", "Find the next match for the current search phrase")); _findNextButton->installEventFilter(this); - connect(_findNextButton, &QToolButton::clicked, this, - &Konsole::IncrementalSearchBar::findNextClicked); + connect(_findNextButton, &QToolButton::clicked, this, &Konsole::IncrementalSearchBar::findNextClicked); _findPreviousButton = new QToolButton(this); _findPreviousButton->setAutoRaise(true); _findPreviousButton->setObjectName(QStringLiteral("find-previous-button")); _findPreviousButton->setText(i18nc("@action:button Go to the previous phrase", "Previous")); _findPreviousButton->setToolButtonStyle(Qt::ToolButtonIconOnly); - _findPreviousButton->setToolTip(i18nc("@info:tooltip", - "Find the previous match for the current search phrase")); + _findPreviousButton->setToolTip(i18nc("@info:tooltip", "Find the previous match for the current search phrase")); _findPreviousButton->installEventFilter(this); - connect(_findPreviousButton, &QToolButton::clicked, this, - &Konsole::IncrementalSearchBar::findPreviousClicked); + connect(_findPreviousButton, &QToolButton::clicked, this, &Konsole::IncrementalSearchBar::findPreviousClicked); _searchFromButton = new QToolButton(this); _searchFromButton->setAutoRaise(true); _searchFromButton->setObjectName(QStringLiteral("search-from-button")); _searchFromButton->installEventFilter(this); - connect(_searchFromButton, &QToolButton::clicked, this, - &Konsole::IncrementalSearchBar::searchFromClicked); + connect(_searchFromButton, &QToolButton::clicked, this, &Konsole::IncrementalSearchBar::searchFromClicked); auto optionsButton = new QToolButton(this); optionsButton->setObjectName(QStringLiteral("find-options-button")); @@ -124,27 +117,21 @@ IncrementalSearchBar::IncrementalSearchBar(QWidget *parent) : _caseSensitive = optionsMenu->addAction(i18nc("@item:inmenu", "Case sensitive")); _caseSensitive->setCheckable(true); _caseSensitive->setToolTip(i18nc("@info:tooltip", "Sets whether the search is case sensitive")); - connect(_caseSensitive, &QAction::toggled, this, - &Konsole::IncrementalSearchBar::matchCaseToggled); + connect(_caseSensitive, &QAction::toggled, this, &Konsole::IncrementalSearchBar::matchCaseToggled); _regExpression = optionsMenu->addAction(i18nc("@item:inmenu", "Match regular expression")); _regExpression->setCheckable(true); - connect(_regExpression, &QAction::toggled, this, - &Konsole::IncrementalSearchBar::matchRegExpToggled); + connect(_regExpression, &QAction::toggled, this, &Konsole::IncrementalSearchBar::matchRegExpToggled); _highlightMatches = optionsMenu->addAction(i18nc("@item:inmenu", "Highlight all matches")); _highlightMatches->setCheckable(true); - _highlightMatches->setToolTip(i18nc("@info:tooltip", - "Sets whether matching text should be highlighted")); - connect(_highlightMatches, &QAction::toggled, this, - &Konsole::IncrementalSearchBar::highlightMatchesToggled); + _highlightMatches->setToolTip(i18nc("@info:tooltip", "Sets whether matching text should be highlighted")); + connect(_highlightMatches, &QAction::toggled, this, &Konsole::IncrementalSearchBar::highlightMatchesToggled); _reverseSearch = optionsMenu->addAction(i18nc("@item:inmenu", "Search backwards")); _reverseSearch->setCheckable(true); - _reverseSearch->setToolTip(i18nc("@info:tooltip", - "Sets whether search should start from the bottom")); - connect(_reverseSearch, &QAction::toggled, this, - &Konsole::IncrementalSearchBar::updateButtonsAccordingToReverseSearchSetting); + _reverseSearch->setToolTip(i18nc("@info:tooltip", "Sets whether search should start from the bottom")); + connect(_reverseSearch, &QAction::toggled, this, &Konsole::IncrementalSearchBar::updateButtonsAccordingToReverseSearchSetting); updateButtonsAccordingToReverseSearchSetting(); setOptions(); @@ -172,14 +159,12 @@ void IncrementalSearchBar::updateButtonsAccordingToReverseSearchSetting() { Q_ASSERT(_reverseSearch); if (_reverseSearch->isChecked()) { - _searchFromButton->setToolTip(i18nc("@info:tooltip", - "Search for the current search phrase from the bottom")); + _searchFromButton->setToolTip(i18nc("@info:tooltip", "Search for the current search phrase from the bottom")); _searchFromButton->setIcon(QIcon::fromTheme(QStringLiteral("go-bottom"))); _findNextButton->setIcon(QIcon::fromTheme(QStringLiteral("go-up"))); _findPreviousButton->setIcon(QIcon::fromTheme(QStringLiteral("go-down"))); } else { - _searchFromButton->setToolTip(i18nc("@info:tooltip", - "Search for the current search phrase from the top")); + _searchFromButton->setToolTip(i18nc("@info:tooltip", "Search for the current search phrase from the top")); _searchFromButton->setIcon(QIcon::fromTheme(QStringLiteral("go-top"))); _findNextButton->setIcon(QIcon::fromTheme(QStringLiteral("go-down"))); _findPreviousButton->setIcon(QIcon::fromTheme(QStringLiteral("go-up"))); @@ -219,7 +204,7 @@ bool IncrementalSearchBar::eventFilter(QObject *watched, QEvent *event) return true; } } else if ((toolButton = qobject_cast(watched)) != nullptr) { - if(event->type() == QEvent::KeyPress && !toolButton->isDown()) { + if (event->type() == QEvent::KeyPress && !toolButton->isDown()) { toolButton->setDown(true); toolButton->pressed(); } else if (toolButton->isDown()) { @@ -236,12 +221,9 @@ bool IncrementalSearchBar::eventFilter(QObject *watched, QEvent *event) void IncrementalSearchBar::keyPressEvent(QKeyEvent *event) { - static auto movementKeysToPassAlong = QSet{ - Qt::Key_PageUp, Qt::Key_PageDown, Qt::Key_Up, Qt::Key_Down - }; + static auto movementKeysToPassAlong = QSet{Qt::Key_PageUp, Qt::Key_PageDown, Qt::Key_Up, Qt::Key_Down}; - if (movementKeysToPassAlong.contains(event->key()) - && (event->modifiers() == Qt::ShiftModifier)) { + if (movementKeysToPassAlong.contains(event->key()) && (event->modifiers() == Qt::ShiftModifier)) { Q_EMIT unhandledMovementKeyPressed(event); } @@ -262,15 +244,13 @@ void IncrementalSearchBar::setVisible(bool visible) void IncrementalSearchBar::setFoundMatch(bool match) { if (_searchEdit->text().isEmpty()) { - clearLineEdit(); - return; + clearLineEdit(); + return; } - const auto backgroundBrush = KStatefulBrush(KColorScheme::View, - match ? KColorScheme::PositiveBackground : KColorScheme::NegativeBackground); + const auto backgroundBrush = KStatefulBrush(KColorScheme::View, match ? KColorScheme::PositiveBackground : KColorScheme::NegativeBackground); - const auto matchStyleSheet = QStringLiteral("QLineEdit{ background-color:%1 }") - .arg(backgroundBrush.brush(_searchEdit->palette()).color().name()); + const auto matchStyleSheet = QStringLiteral("QLineEdit{ background-color:%1 }").arg(backgroundBrush.brush(_searchEdit->palette()).color().name()); _searchEdit->setStyleSheet(matchStyleSheet); } diff --git a/src/widgets/IncrementalSearchBar.h b/src/widgets/IncrementalSearchBar.h index 4e0b86ec3..592a44e57 100644 --- a/src/widgets/IncrementalSearchBar.h +++ b/src/widgets/IncrementalSearchBar.h @@ -8,15 +8,16 @@ #define INCREMENTALSEARCHBAR_H // Qt -#include #include +#include class QAction; class QTimer; class QLineEdit; class QToolButton; -namespace Konsole { +namespace Konsole +{ /** * A widget which allows users to search incrementally through a document for a * a text string or regular expression. @@ -54,7 +55,7 @@ public: /** Searches use regular expressions */ RegExp = 2, /** Search from the bottom and up **/ - ReverseSearch = 3 + ReverseSearch = 3, }; /** diff --git a/src/widgets/KonsolePrintManager.cpp b/src/widgets/KonsolePrintManager.cpp index b2031da37..ee8a7579e 100644 --- a/src/widgets/KonsolePrintManager.cpp +++ b/src/widgets/KonsolePrintManager.cpp @@ -13,14 +13,14 @@ #include "PrintOptions.h" // Qt -#include #include -#include -#include -#include #include +#include #include #include +#include +#include +#include // KDE #include @@ -48,10 +48,7 @@ void KonsolePrintManager::printRequest(pPrintContent pContent, QWidget *parent) dialog->setOptionTabs({options}); dialog->setWindowTitle(i18n("Print Shell")); - QObject::connect(dialog, - QOverload<>::of(&QPrintDialog::accepted), - options, - &Konsole::PrintOptions::saveSettings); + QObject::connect(dialog, QOverload<>::of(&QPrintDialog::accepted), options, &Konsole::PrintOptions::saveSettings); if (dialog->exec() != QDialog::Accepted) { return; } @@ -63,16 +60,14 @@ void KonsolePrintManager::printRequest(pPrintContent pContent, QWidget *parent) if (configGroup.readEntry("ScaleOutput", true)) { QRect page_rect = printer.pageLayout().paintRectPixels(printer.resolution()); - double scale = qMin(page_rect.width() / static_cast(parent->width()), - page_rect.height() / static_cast(parent->height())); + double scale = qMin(page_rect.width() / static_cast(parent->width()), page_rect.height() / static_cast(parent->height())); painter.scale(scale, scale); } - + pContent(painter, configGroup.readEntry("PrinterFriendly", true)); } -void KonsolePrintManager::printContent(QPainter &painter, bool friendly, QPoint columnsLines, - pVTFontGet vtFontGet, pVTFontSet vtFontSet) +void KonsolePrintManager::printContent(QPainter &painter, bool friendly, QPoint columnsLines, pVTFontGet vtFontGet, pVTFontSet vtFontSet) { // Reinitialize the font with the printers paint device so the font // measurement calculations will be done correctly diff --git a/src/widgets/KonsolePrintManager.h b/src/widgets/KonsolePrintManager.h index ad0c7b478..4c03a0e63 100644 --- a/src/widgets/KonsolePrintManager.h +++ b/src/widgets/KonsolePrintManager.h @@ -20,30 +20,27 @@ class QPainter; namespace Konsole { - class KonsolePrintManager - { - public: - typedef std::function pPrintContent; - typedef std::function pVTFontGet; - typedef std::function pVTFontSet; - typedef std::function pDrawBackground; - typedef std::function pDrawContents; - typedef std::function pColorGet; +class KonsolePrintManager +{ +public: + typedef std::function pPrintContent; + typedef std::function pVTFontGet; + typedef std::function pVTFontSet; + typedef std::function pDrawBackground; + typedef std::function pDrawContents; + typedef std::function pColorGet; - KonsolePrintManager(pDrawBackground drawBackground, pDrawContents drawContents, pColorGet colorGet); - ~KonsolePrintManager() = default; + KonsolePrintManager(pDrawBackground drawBackground, pDrawContents drawContents, pColorGet colorGet); + ~KonsolePrintManager() = default; - void printRequest(pPrintContent pContent, QWidget *parent); - void printContent(QPainter &painter, bool friendly, QPoint columnsLines, pVTFontGet vtFontGet, pVTFontSet vtFontSet); + void printRequest(pPrintContent pContent, QWidget *parent); + void printContent(QPainter &painter, bool friendly, QPoint columnsLines, pVTFontGet vtFontGet, pVTFontSet vtFontSet); - private: - pDrawBackground _drawBackground; - pDrawContents _drawContents; - pColorGet _backgroundColor; - }; +private: + pDrawBackground _drawBackground; + pDrawContents _drawContents; + pColorGet _backgroundColor; +}; } #endif diff --git a/src/widgets/RenameTabWidget.cpp b/src/widgets/RenameTabWidget.cpp index 79cff83af..5d325f8c1 100644 --- a/src/widgets/RenameTabWidget.cpp +++ b/src/widgets/RenameTabWidget.cpp @@ -18,9 +18,9 @@ using Konsole::RenameTabWidget; -RenameTabWidget::RenameTabWidget(QWidget *parent) : - QWidget(parent), - _ui(nullptr) +RenameTabWidget::RenameTabWidget(QWidget *parent) + : QWidget(parent) + , _ui(nullptr) { _ui = new Ui::RenameTabWidget(); _ui->setupUi(this); @@ -36,20 +36,15 @@ RenameTabWidget::RenameTabWidget(QWidget *parent) : _ui->tabColorCombo->setColors(listColors); _ui->tabColorCombo->setItemText(1, i18nc("@label:listbox No color selected", "None")); - connect(_ui->tabTitleEdit, &QLineEdit::textChanged, this, - &Konsole::RenameTabWidget::tabTitleFormatChanged); - connect(_ui->remoteTabTitleEdit, &QLineEdit::textChanged, this, - &Konsole::RenameTabWidget::remoteTabTitleFormatChanged); - connect(_ui->tabColorCombo, &KColorCombo::activated, this, - &Konsole::RenameTabWidget::tabColorChanged); + connect(_ui->tabTitleEdit, &QLineEdit::textChanged, this, &Konsole::RenameTabWidget::tabTitleFormatChanged); + connect(_ui->remoteTabTitleEdit, &QLineEdit::textChanged, this, &Konsole::RenameTabWidget::remoteTabTitleFormatChanged); + connect(_ui->tabColorCombo, &KColorCombo::activated, this, &Konsole::RenameTabWidget::tabColorChanged); _ui->tabTitleFormatButton->setContext(Session::LocalTabTitle); - connect(_ui->tabTitleFormatButton, &Konsole::TabTitleFormatButton::dynamicElementSelected, this, - &Konsole::RenameTabWidget::insertTabTitleText); + connect(_ui->tabTitleFormatButton, &Konsole::TabTitleFormatButton::dynamicElementSelected, this, &Konsole::RenameTabWidget::insertTabTitleText); _ui->remoteTabTitleFormatButton->setContext(Session::RemoteTabTitle); - connect(_ui->remoteTabTitleFormatButton, &Konsole::TabTitleFormatButton::dynamicElementSelected, - this, &Konsole::RenameTabWidget::insertRemoteTabTitleText); + connect(_ui->remoteTabTitleFormatButton, &Konsole::TabTitleFormatButton::dynamicElementSelected, this, &Konsole::RenameTabWidget::insertRemoteTabTitleText); } RenameTabWidget::~RenameTabWidget() diff --git a/src/widgets/RenameTabWidget.h b/src/widgets/RenameTabWidget.h index 0ca8749c5..4d7138f2f 100644 --- a/src/widgets/RenameTabWidget.h +++ b/src/widgets/RenameTabWidget.h @@ -12,11 +12,13 @@ class QColor; -namespace Ui { +namespace Ui +{ class RenameTabWidget; } -namespace Konsole { +namespace Konsole +{ class RenameTabWidget : public QWidget { Q_OBJECT diff --git a/src/widgets/TabTitleFormatButton.cpp b/src/widgets/TabTitleFormatButton.cpp index f33b839c5..73480652e 100644 --- a/src/widgets/TabTitleFormatButton.cpp +++ b/src/widgets/TabTitleFormatButton.cpp @@ -17,33 +17,29 @@ using namespace Konsole; const TabTitleFormatButton::Element TabTitleFormatButton::_localElements[] = { - { QStringLiteral("%n"), I18N_NOOP("Program Name: %n") }, - { QStringLiteral("%d"), I18N_NOOP("Current Directory (Short): %d") }, - { QStringLiteral("%D"), I18N_NOOP("Current Directory (Long): %D") }, - { QStringLiteral("%w"), I18N_NOOP("Window Title Set by Shell: %w") }, - { QStringLiteral("%#"), I18N_NOOP("Session Number: %#") }, - { QStringLiteral("%u"), I18N_NOOP("User Name: %u") }, - { QStringLiteral("%h"), I18N_NOOP("Local Host: %h") }, - { QStringLiteral("%B"), I18N_NOOP("User's Bourne prompt sigil: %B") } // ($, or # for superuser) + {QStringLiteral("%n"), I18N_NOOP("Program Name: %n")}, + {QStringLiteral("%d"), I18N_NOOP("Current Directory (Short): %d")}, + {QStringLiteral("%D"), I18N_NOOP("Current Directory (Long): %D")}, + {QStringLiteral("%w"), I18N_NOOP("Window Title Set by Shell: %w")}, + {QStringLiteral("%#"), I18N_NOOP("Session Number: %#")}, + {QStringLiteral("%u"), I18N_NOOP("User Name: %u")}, + {QStringLiteral("%h"), I18N_NOOP("Local Host: %h")}, + {QStringLiteral("%B"), I18N_NOOP("User's Bourne prompt sigil: %B")} // ($, or # for superuser) }; -const int TabTitleFormatButton::_localElementCount - = sizeof(_localElements) / sizeof(TabTitleFormatButton::Element); +const int TabTitleFormatButton::_localElementCount = sizeof(_localElements) / sizeof(TabTitleFormatButton::Element); -const TabTitleFormatButton::Element TabTitleFormatButton::_remoteElements[] = { - { QStringLiteral("%u"), I18N_NOOP("User Name: %u") }, - { QStringLiteral("%U"), I18N_NOOP("User Name@ (if given): %U") }, - { QStringLiteral("%h"), I18N_NOOP("Remote Host (Short): %h") }, - { QStringLiteral("%H"), I18N_NOOP("Remote Host (Long): %H") }, - { QStringLiteral("%c"), I18N_NOOP("Command and arguments: %c") }, - { QStringLiteral("%w"), I18N_NOOP("Window Title Set by Shell: %w") }, - { QStringLiteral("%#"), I18N_NOOP("Session Number: %#") } -}; -const int TabTitleFormatButton::_remoteElementCount - = sizeof(_remoteElements) / sizeof(TabTitleFormatButton::Element); +const TabTitleFormatButton::Element TabTitleFormatButton::_remoteElements[] = {{QStringLiteral("%u"), I18N_NOOP("User Name: %u")}, + {QStringLiteral("%U"), I18N_NOOP("User Name@ (if given): %U")}, + {QStringLiteral("%h"), I18N_NOOP("Remote Host (Short): %h")}, + {QStringLiteral("%H"), I18N_NOOP("Remote Host (Long): %H")}, + {QStringLiteral("%c"), I18N_NOOP("Command and arguments: %c")}, + {QStringLiteral("%w"), I18N_NOOP("Window Title Set by Shell: %w")}, + {QStringLiteral("%#"), I18N_NOOP("Session Number: %#")}}; +const int TabTitleFormatButton::_remoteElementCount = sizeof(_remoteElements) / sizeof(TabTitleFormatButton::Element); -TabTitleFormatButton::TabTitleFormatButton(QWidget *parent) : - QPushButton(parent), - _context(Session::LocalTabTitle) +TabTitleFormatButton::TabTitleFormatButton(QWidget *parent) + : QPushButton(parent) + , _context(Session::LocalTabTitle) { setText(i18n("Insert")); setMenu(new QMenu()); diff --git a/src/widgets/TabTitleFormatButton.h b/src/widgets/TabTitleFormatButton.h index 8be6cbc5a..e9989c136 100644 --- a/src/widgets/TabTitleFormatButton.h +++ b/src/widgets/TabTitleFormatButton.h @@ -8,13 +8,14 @@ #define TABTITLEFORMATBUTTON_H // Qt -#include #include +#include // Konsole #include "session/Session.h" -namespace Konsole { +namespace Konsole +{ class TabTitleFormatButton : public QPushButton { Q_OBJECT diff --git a/src/widgets/TerminalDisplayAccessible.cpp b/src/widgets/TerminalDisplayAccessible.cpp index 8ebbfb05c..af1943569 100644 --- a/src/widgets/TerminalDisplayAccessible.cpp +++ b/src/widgets/TerminalDisplayAccessible.cpp @@ -12,8 +12,8 @@ using namespace Konsole; -TerminalDisplayAccessible::TerminalDisplayAccessible(TerminalDisplay *display) : - QAccessibleWidget(display, QAccessible::Terminal, display->sessionController()->userTitle()) +TerminalDisplayAccessible::TerminalDisplayAccessible(TerminalDisplay *display) + : QAccessibleWidget(display, QAccessible::Terminal, display->sessionController()->userTitle()) { } @@ -40,8 +40,7 @@ int TerminalDisplayAccessible::cursorPosition() const return offset + display()->screenWindow()->screen()->getCursorX(); } -void TerminalDisplayAccessible::selection(int selectionIndex, int *startOffset, - int *endOffset) const +void TerminalDisplayAccessible::selection(int selectionIndex, int *startOffset, int *endOffset) const { *startOffset = 0; *endOffset = 0; @@ -93,10 +92,8 @@ void TerminalDisplayAccessible::addSelection(int startOffset, int endOffset) if (display()->screenWindow() == nullptr) { return; } - display()->screenWindow()->setSelectionStart(columnForOffset(startOffset), - lineForOffset(startOffset), false); - display()->screenWindow()->setSelectionEnd(columnForOffset(endOffset), - lineForOffset(endOffset)); + display()->screenWindow()->setSelectionStart(columnForOffset(startOffset), lineForOffset(startOffset), false); + display()->screenWindow()->setSelectionEnd(columnForOffset(endOffset), lineForOffset(endOffset)); } QString TerminalDisplayAccessible::attributes(int offset, int *startOffset, int *endOffset) const @@ -145,8 +142,7 @@ void TerminalDisplayAccessible::setCursorPosition(int position) return; } - display()->screenWindow()->screen()->setCursorYX(lineForOffset(position), - columnForOffset(position)); + display()->screenWindow()->screen()->setCursorYX(lineForOffset(position), columnForOffset(position)); } void *TerminalDisplayAccessible::interface_cast(QAccessible::InterfaceType type) diff --git a/src/widgets/TerminalDisplayAccessible.h b/src/widgets/TerminalDisplayAccessible.h index 9b6e7778a..a5f7d0ba2 100644 --- a/src/widgets/TerminalDisplayAccessible.h +++ b/src/widgets/TerminalDisplayAccessible.h @@ -12,11 +12,12 @@ #include #include -#include "terminalDisplay/TerminalDisplay.h" -#include "ScreenWindow.h" #include "Screen.h" +#include "ScreenWindow.h" +#include "terminalDisplay/TerminalDisplay.h" -namespace Konsole { +namespace Konsole +{ /** * Class implementing the QAccessibleInterface for the terminal display. * This exposes information about the display to assistive technology using the QAccessible framework. diff --git a/src/widgets/TerminalHeaderBar.cpp b/src/widgets/TerminalHeaderBar.cpp index 6e27210aa..fff121c95 100644 --- a/src/widgets/TerminalHeaderBar.cpp +++ b/src/widgets/TerminalHeaderBar.cpp @@ -6,28 +6,28 @@ #include "TerminalHeaderBar.h" -#include "terminalDisplay/TerminalDisplay.h" -#include "session/SessionController.h" -#include "ViewProperties.h" #include "KonsoleSettings.h" +#include "ViewProperties.h" +#include "session/SessionController.h" +#include "terminalDisplay/TerminalDisplay.h" #include "widgets/ViewSplitter.h" #include -#include -#include -#include #include +#include +#include +#include +#include #include -#include #include #include #include #include -#include -#include - -namespace Konsole { +#include +#include +namespace Konsole +{ TerminalHeaderBar::TerminalHeaderBar(QWidget *parent) : QWidget(parent) { @@ -45,9 +45,9 @@ TerminalHeaderBar::TerminalHeaderBar(QWidget *parent) // Status icons - QLabel ** statusIcons[] = {&m_statusIconReadOnly, &m_statusIconCopyInput, &m_statusIconSilence, &m_statusIconActivity, &m_statusIconBell}; + QLabel **statusIcons[] = {&m_statusIconReadOnly, &m_statusIconCopyInput, &m_statusIconSilence, &m_statusIconActivity, &m_statusIconBell}; - for (auto **statusIcon: statusIcons) { + for (auto **statusIcon : statusIcons) { *statusIcon = new QLabel(this); (*statusIcon)->setAlignment(Qt::AlignCenter); (*statusIcon)->setFixedSize(20, 20); @@ -56,11 +56,11 @@ TerminalHeaderBar::TerminalHeaderBar(QWidget *parent) m_boxLayout->addWidget(*statusIcon); } - m_statusIconReadOnly->setPixmap(QIcon::fromTheme(QStringLiteral("object-locked")).pixmap(QSize(16,16))); - m_statusIconCopyInput->setPixmap(QIcon::fromTheme(QStringLiteral("irc-voice")).pixmap(QSize(16,16))); - m_statusIconSilence->setPixmap(QIcon::fromTheme(QStringLiteral("system-suspend")).pixmap(QSize(16,16))); - m_statusIconActivity->setPixmap(QIcon::fromTheme(QStringLiteral("dialog-information")).pixmap(QSize(16,16))); - m_statusIconBell->setPixmap(QIcon::fromTheme(QStringLiteral("notifications")).pixmap(QSize(16,16))); + m_statusIconReadOnly->setPixmap(QIcon::fromTheme(QStringLiteral("object-locked")).pixmap(QSize(16, 16))); + m_statusIconCopyInput->setPixmap(QIcon::fromTheme(QStringLiteral("irc-voice")).pixmap(QSize(16, 16))); + m_statusIconSilence->setPixmap(QIcon::fromTheme(QStringLiteral("system-suspend")).pixmap(QSize(16, 16))); + m_statusIconActivity->setPixmap(QIcon::fromTheme(QStringLiteral("dialog-information")).pixmap(QSize(16, 16))); + m_statusIconBell->setPixmap(QIcon::fromTheme(QStringLiteral("notifications")).pixmap(QSize(16, 16))); // Title @@ -79,8 +79,7 @@ TerminalHeaderBar::TerminalHeaderBar(QWidget *parent) m_toggleExpandedMode->setCheckable(true); m_toggleExpandedMode->setToolTip(i18nc("@info:tooltip", "Maximize terminal")); - connect(m_toggleExpandedMode, &QToolButton::clicked, - this, &TerminalHeaderBar::requestToggleExpansion); + connect(m_toggleExpandedMode, &QToolButton::clicked, this, &TerminalHeaderBar::requestToggleExpansion); m_boxLayout->addWidget(m_toggleExpandedMode); @@ -91,8 +90,7 @@ TerminalHeaderBar::TerminalHeaderBar(QWidget *parent) m_moveToNewTab->setAutoRaise(true); m_moveToNewTab->setToolTip(i18nc("@info:tooltip", "Move terminal to new tab")); - connect(m_moveToNewTab, &QToolButton::clicked, - this, &TerminalHeaderBar::requestMoveToNewTab); + connect(m_moveToNewTab, &QToolButton::clicked, this, &TerminalHeaderBar::requestMoveToNewTab); m_boxLayout->addWidget(m_moveToNewTab); @@ -124,25 +122,22 @@ void TerminalHeaderBar::mouseDoubleClickEvent(QMouseEvent *ev) // Hack until I can detangle the creation of the TerminalViews void TerminalHeaderBar::finishHeaderSetup(ViewProperties *properties) { - auto controller = dynamic_cast(properties); - connect(properties, &Konsole::ViewProperties::titleChanged, this, [this, properties]{ + auto controller = dynamic_cast(properties); + connect(properties, &Konsole::ViewProperties::titleChanged, this, [this, properties] { m_terminalTitle->setText(properties->title()); }); m_terminalTitle->setText(properties->title()); connect(properties, &Konsole::ViewProperties::iconChanged, this, [this, properties] { - m_terminalIcon->setPixmap(properties->icon().pixmap(QSize(22,22))); + m_terminalIcon->setPixmap(properties->icon().pixmap(QSize(22, 22))); }); - m_terminalIcon->setPixmap(properties->icon().pixmap(QSize(22,22))); + m_terminalIcon->setPixmap(properties->icon().pixmap(QSize(22, 22))); - connect(properties, &Konsole::ViewProperties::notificationChanged, this, - &Konsole::TerminalHeaderBar::updateNotification); + connect(properties, &Konsole::ViewProperties::notificationChanged, this, &Konsole::TerminalHeaderBar::updateNotification); - connect(properties, &Konsole::ViewProperties::readOnlyChanged, this, - &Konsole::TerminalHeaderBar::updateSpecialState); + connect(properties, &Konsole::ViewProperties::readOnlyChanged, this, &Konsole::TerminalHeaderBar::updateSpecialState); - connect(properties, &Konsole::ViewProperties::copyInputChanged, this, - &Konsole::TerminalHeaderBar::updateSpecialState); + connect(properties, &Konsole::ViewProperties::copyInputChanged, this, &Konsole::TerminalHeaderBar::updateSpecialState); connect(m_closeBtn, &QToolButton::clicked, controller, &SessionController::closeSession); } @@ -157,7 +152,7 @@ void TerminalHeaderBar::updateNotification(ViewProperties *item, Session::Notifi { Q_UNUSED(item) - switch(notification) { + switch (notification) { case Session::Notification::Silence: m_statusIconSilence->setVisible(enabled); break; @@ -174,7 +169,7 @@ void TerminalHeaderBar::updateNotification(ViewProperties *item, Session::Notifi void TerminalHeaderBar::updateSpecialState(ViewProperties *item) { - auto controller = dynamic_cast(item); + auto controller = dynamic_cast(item); if (controller != nullptr) { m_statusIconReadOnly->setVisible(controller->isReadOnly()); @@ -204,9 +199,9 @@ void TerminalHeaderBar::paintEvent(QPaintEvent *paintEvent) const auto globalPos = parentWidget()->mapToGlobal(pos()); auto *widget = qApp->widgetAt(globalPos.x() + 10, globalPos.y() - 10); - const bool isTabbar = qobject_cast(widget) != nullptr; - const bool isTerminalWidget = qobject_cast(widget) != nullptr; - const bool isSplitter = (qobject_cast(widget) != nullptr) || (qobject_cast(widget) != nullptr); + const bool isTabbar = qobject_cast(widget) != nullptr; + const bool isTerminalWidget = qobject_cast(widget) != nullptr; + const bool isSplitter = (qobject_cast(widget) != nullptr) || (qobject_cast(widget) != nullptr); if ((widget != nullptr) && !isTabbar && !isTerminalWidget && !isSplitter) { QStyleOptionTabBarBase optTabBase; QStylePainter p(this); @@ -220,7 +215,7 @@ void TerminalHeaderBar::paintEvent(QPaintEvent *paintEvent) if (!m_terminalIsFocused) { auto p = qApp->palette(); auto shadowColor = p.color(QPalette::ColorRole::Shadow); - shadowColor.setAlphaF( qreal(0.2) * shadowColor.alphaF() ); // same as breeze. + shadowColor.setAlphaF(qreal(0.2) * shadowColor.alphaF()); // same as breeze. QPainter painter(this); painter.setPen(Qt::NoPen); @@ -229,7 +224,7 @@ void TerminalHeaderBar::paintEvent(QPaintEvent *paintEvent) } } -void TerminalHeaderBar::mouseMoveEvent(QMouseEvent* ev) +void TerminalHeaderBar::mouseMoveEvent(QMouseEvent *ev) { if (m_toggleExpandedMode->isChecked()) { return; @@ -246,12 +241,12 @@ void TerminalHeaderBar::mouseMoveEvent(QMouseEvent* ev) } } -void TerminalHeaderBar::mousePressEvent(QMouseEvent* ev) +void TerminalHeaderBar::mousePressEvent(QMouseEvent *ev) { m_startDrag = ev->pos(); } -void TerminalHeaderBar::mouseReleaseEvent(QMouseEvent* ev) +void TerminalHeaderBar::mouseReleaseEvent(QMouseEvent *ev) { Q_UNUSED(ev) } @@ -266,12 +261,12 @@ QSplitter *TerminalHeaderBar::getTopLevelSplitter() { QWidget *p = parentWidget(); // This is expected. - if (qobject_cast(p) != nullptr) { + if (qobject_cast(p) != nullptr) { p = p->parentWidget(); } // this is also expected. - auto *innerSplitter = qobject_cast(p); + auto *innerSplitter = qobject_cast(p); if (innerSplitter == nullptr) { return nullptr; } @@ -283,16 +278,14 @@ void TerminalHeaderBar::applyVisibilitySettings() { auto *settings = KonsoleSettings::self(); auto toVisibility = settings->splitViewVisibility(); - switch (toVisibility) - { + switch (toVisibility) { case KonsoleSettings::AlwaysShowSplitHeader: setVisible(true); - break; + break; case KonsoleSettings::ShowSplitHeaderWhenNeeded: { - const bool visible = !(getTopLevelSplitter()->findChildren().count() == 1); + const bool visible = !(getTopLevelSplitter()->findChildren().count() == 1); setVisible(visible); - } - break; + } break; case KonsoleSettings::AlwaysHideSplitHeader: setVisible(false); default: diff --git a/src/widgets/TerminalHeaderBar.h b/src/widgets/TerminalHeaderBar.h index 05739bfc9..561a271cb 100644 --- a/src/widgets/TerminalHeaderBar.h +++ b/src/widgets/TerminalHeaderBar.h @@ -7,20 +7,22 @@ #ifndef TERMINAL_HEADER_BAR_H #define TERMINAL_HEADER_BAR_H -#include -#include #include "session/Session.h" +#include +#include class QLabel; class QToolButton; class QBoxLayout; class QSplitter; -namespace Konsole { - class TerminalDisplay; - class ViewProperties; +namespace Konsole +{ +class TerminalDisplay; +class ViewProperties; -class TerminalHeaderBar : public QWidget { +class TerminalHeaderBar : public QWidget +{ Q_OBJECT public: // TODO: Verify if the terminalDisplay is needed, or some other thing like SessionController. @@ -39,7 +41,7 @@ public Q_SLOTS: void updateSpecialState(ViewProperties *item); protected: - void paintEvent(QPaintEvent* paintEvent) override; + void paintEvent(QPaintEvent *paintEvent) override; void mousePressEvent(QMouseEvent *ev) override; void mouseReleaseEvent(QMouseEvent *ev) override; void mouseMoveEvent(QMouseEvent *ev) override; diff --git a/src/widgets/ViewContainer.cpp b/src/widgets/ViewContainer.cpp index 291de84a4..37667a235 100644 --- a/src/widgets/ViewContainer.cpp +++ b/src/widgets/ViewContainer.cpp @@ -9,41 +9,40 @@ #include "config-konsole.h" // Qt -#include -#include #include #include +#include +#include // KDE +#include #include #include #include -#include // Konsole -#include "widgets/IncrementalSearchBar.h" +#include "DetachableTabBar.h" +#include "KonsoleSettings.h" #include "ViewProperties.h" #include "profile/ProfileList.h" -#include "KonsoleSettings.h" #include "session/SessionController.h" #include "session/SessionManager.h" -#include "DetachableTabBar.h" #include "terminalDisplay/TerminalDisplay.h" +#include "widgets/IncrementalSearchBar.h" #include "widgets/ViewSplitter.h" // TODO Perhaps move everything which is Konsole-specific into different files using namespace Konsole; - -TabbedViewContainer::TabbedViewContainer(ViewManager *connectedViewManager, QWidget *parent) : - QTabWidget(parent), - _connectedViewManager(connectedViewManager), - _newTabButton(new QToolButton(this)), - _closeTabButton(new QToolButton(this)), - _contextMenuTabIndex(-1), - _navigationVisibility(ViewManager::NavigationVisibility::NavigationNotSet), - _newTabBehavior(PutNewTabAtTheEnd) +TabbedViewContainer::TabbedViewContainer(ViewManager *connectedViewManager, QWidget *parent) + : QTabWidget(parent) + , _connectedViewManager(connectedViewManager) + , _newTabButton(new QToolButton(this)) + , _closeTabButton(new QToolButton(this)) + , _contextMenuTabIndex(-1) + , _navigationVisibility(ViewManager::NavigationVisibility::NavigationNotSet) + , _newTabBehavior(PutNewTabAtTheEnd) { setAcceptDrops(true); @@ -61,21 +60,19 @@ TabbedViewContainer::TabbedViewContainer(ViewManager *connectedViewManager, QWid _closeTabButton->setIcon(QIcon::fromTheme(QStringLiteral("tab-close"))); _closeTabButton->setAutoRaise(true); _closeTabButton->setToolTip(i18nc("@info:tooltip", "Close this tab")); - connect(_closeTabButton, &QToolButton::clicked, this, [this]{ - closeCurrentTab(); + connect(_closeTabButton, &QToolButton::clicked, this, [this] { + closeCurrentTab(); }); - connect(tabBar(), &QTabBar::tabBarDoubleClicked, this, - &Konsole::TabbedViewContainer::tabDoubleClicked); - connect(tabBar(), &QTabBar::customContextMenuRequested, this, - &Konsole::TabbedViewContainer::openTabContextMenu); + connect(tabBar(), &QTabBar::tabBarDoubleClicked, this, &Konsole::TabbedViewContainer::tabDoubleClicked); + connect(tabBar(), &QTabBar::customContextMenuRequested, this, &Konsole::TabbedViewContainer::openTabContextMenu); connect(tabBarWidget, &DetachableTabBar::detachTab, this, [this](int idx) { Q_EMIT detachTab(idx); }); - connect(tabBarWidget, &DetachableTabBar::closeTab, - this, &TabbedViewContainer::closeTerminalTab); - connect(tabBarWidget, &DetachableTabBar::newTabRequest, - this, [this]{ Q_EMIT newViewRequest(); }); + connect(tabBarWidget, &DetachableTabBar::closeTab, this, &TabbedViewContainer::closeTerminalTab); + connect(tabBarWidget, &DetachableTabBar::newTabRequest, this, [this] { + Q_EMIT newViewRequest(); + }); connect(this, &TabbedViewContainer::currentChanged, this, &TabbedViewContainer::currentTabChanged); connect(this, &TabbedViewContainer::setColor, tabBarWidget, &DetachableTabBar::setColor); @@ -95,25 +92,20 @@ TabbedViewContainer::TabbedViewContainer(ViewManager *connectedViewManager, QWid connect(tabBar(), &QTabBar::tabCloseRequested, this, &TabbedViewContainer::closeTerminalTab); - auto detachAction = _contextPopupMenu->addAction( - QIcon::fromTheme(QStringLiteral("tab-detach")), - i18nc("@action:inmenu", "&Detach Tab"), this, - [this] { Q_EMIT detachTab(_contextMenuTabIndex); } - ); + auto detachAction = _contextPopupMenu->addAction(QIcon::fromTheme(QStringLiteral("tab-detach")), i18nc("@action:inmenu", "&Detach Tab"), this, [this] { + Q_EMIT detachTab(_contextMenuTabIndex); + }); detachAction->setObjectName(QStringLiteral("tab-detach")); - auto editAction = _contextPopupMenu->addAction( - QIcon::fromTheme(QStringLiteral("edit-rename")), - i18nc("@action:inmenu", "&Configure or Rename Tab..."), this, - [this]{ renameTab(_contextMenuTabIndex); } - ); + auto editAction = + _contextPopupMenu->addAction(QIcon::fromTheme(QStringLiteral("edit-rename")), i18nc("@action:inmenu", "&Configure or Rename Tab..."), this, [this] { + renameTab(_contextMenuTabIndex); + }); editAction->setObjectName(QStringLiteral("edit-rename")); - auto closeAction = _contextPopupMenu->addAction( - QIcon::fromTheme(QStringLiteral("tab-close")), - i18nc("@action:inmenu", "Close Tab"), this, - [this] { closeTerminalTab(_contextMenuTabIndex); } - ); + auto closeAction = _contextPopupMenu->addAction(QIcon::fromTheme(QStringLiteral("tab-close")), i18nc("@action:inmenu", "Close Tab"), this, [this] { + closeTerminalTab(_contextMenuTabIndex); + }); closeAction->setObjectName(QStringLiteral("tab-close")); auto profileMenu = new QMenu(this); @@ -128,7 +120,7 @@ TabbedViewContainer::TabbedViewContainer(ViewManager *connectedViewManager, QWid TabbedViewContainer::~TabbedViewContainer() { - for(int i = 0, end = count(); i < end; i++) { + for (int i = 0, end = count(); i < end; i++) { auto view = widget(i); disconnect(view, &QWidget::destroyed, this, &Konsole::TabbedViewContainer::viewDestroyed); } @@ -141,13 +133,13 @@ ViewSplitter *TabbedViewContainer::activeViewSplitter() ViewSplitter *TabbedViewContainer::viewSplitterAt(int index) { - return qobject_cast(widget(index)); + return qobject_cast(widget(index)); } int TabbedViewContainer::currentTabViewCount() { if (auto *splitter = activeViewSplitter()) { - return splitter->findChildren().count(); + return splitter->findChildren().count(); } return 1; @@ -156,11 +148,11 @@ int TabbedViewContainer::currentTabViewCount() void TabbedViewContainer::moveTabToWindow(int index, QWidget *window) { auto splitter = viewSplitterAt(index); - auto manager = window->findChild(); + auto manager = window->findChild(); - QHash sessionsMap = _connectedViewManager->forgetAll(splitter); + QHash sessionsMap = _connectedViewManager->forgetAll(splitter); - const QList displays = splitter->findChildren(); + const QList displays = splitter->findChildren(); for (TerminalDisplay *terminal : displays) { manager->attachView(terminal, sessionsMap[terminal]); } @@ -194,7 +186,7 @@ void TabbedViewContainer::konsoleConfigChanged() } } - setTabPosition((QTabWidget::TabPosition) KonsoleSettings::tabBarPosition()); + setTabPosition((QTabWidget::TabPosition)KonsoleSettings::tabBarPosition()); setCornerWidget(KonsoleSettings::newTabButton() ? _newTabButton : nullptr, Qt::TopLeftCorner); _newTabButton->setVisible(KonsoleSettings::newTabButton()); @@ -214,7 +206,7 @@ void TabbedViewContainer::konsoleConfigChanged() } } -void TabbedViewContainer::setCss(const QString& styleSheet) +void TabbedViewContainer::setCss(const QString &styleSheet) { static const QString defaultCss = QStringLiteral("QTabWidget::tab-bar, QTabWidget::pane { margin: 0; }\n"); setStyleSheet(defaultCss + styleSheet); @@ -242,7 +234,7 @@ void TabbedViewContainer::moveActiveView(MoveDirection direction) return; } const int currentIndex = indexOf(currentWidget()); - int newIndex = direction == MoveViewLeft ? qMax(currentIndex - 1, 0) : qMin(currentIndex + 1, count() - 1); + int newIndex = direction == MoveViewLeft ? qMax(currentIndex - 1, 0) : qMin(currentIndex + 1, count() - 1); auto swappedWidget = viewSplitterAt(newIndex); auto swappedTitle = tabBar()->tabText(newIndex); @@ -262,11 +254,12 @@ void TabbedViewContainer::moveActiveView(MoveDirection direction) setCurrentIndex(newIndex); } -void TabbedViewContainer::terminalDisplayDropped(TerminalDisplay *terminalDisplay) { +void TabbedViewContainer::terminalDisplayDropped(TerminalDisplay *terminalDisplay) +{ if (terminalDisplay->sessionController()->parent() != connectedViewManager()) { // Terminal from another window - recreate SessionController for current ViewManager disconnectTerminalDisplay(terminalDisplay); - Session* terminalSession = terminalDisplay->sessionController()->session(); + Session *terminalSession = terminalDisplay->sessionController()->session(); terminalDisplay->sessionController()->deleteLater(); connectedViewManager()->attachView(terminalDisplay, terminalSession); connectTerminalDisplay(terminalDisplay); @@ -305,24 +298,24 @@ QSize TabbedViewContainer::sizeHint() const // // L/R = left/right widget - return {qMax(terminalSize.width(), tabBarSize.width()), - tabBarSize.height() + terminalSize.height()}; + return {qMax(terminalSize.width(), tabBarSize.width()), tabBarSize.height() + terminalSize.height()}; } -void TabbedViewContainer::addSplitter(ViewSplitter *viewSplitter, int index) { +void TabbedViewContainer::addSplitter(ViewSplitter *viewSplitter, int index) +{ index = insertTab(index, viewSplitter, QString()); connect(viewSplitter, &ViewSplitter::destroyed, this, &TabbedViewContainer::viewDestroyed); disconnect(viewSplitter, &ViewSplitter::terminalDisplayDropped, nullptr, nullptr); connect(viewSplitter, &ViewSplitter::terminalDisplayDropped, this, &TabbedViewContainer::terminalDisplayDropped); - const auto terminalDisplays = viewSplitter->findChildren(); + const auto terminalDisplays = viewSplitter->findChildren(); for (TerminalDisplay *terminal : terminalDisplays) { connectTerminalDisplay(terminal); } if (terminalDisplays.count() > 0) { - updateTitle(qobject_cast(terminalDisplays.at(0)->sessionController())); - updateColor(qobject_cast(terminalDisplays.at(0)->sessionController())); + updateTitle(qobject_cast(terminalDisplays.at(0)->sessionController())); + updateColor(qobject_cast(terminalDisplays.at(0)->sessionController())); } setCurrentIndex(index); } @@ -345,7 +338,7 @@ void TabbedViewContainer::addView(TerminalDisplay *view) void TabbedViewContainer::splitView(TerminalDisplay *view, Qt::Orientation orientation) { - auto viewSplitter = qobject_cast(currentWidget()); + auto viewSplitter = qobject_cast(currentWidget()); viewSplitter->addTerminalDisplay(view, orientation); connectTerminalDisplay(view); } @@ -353,29 +346,21 @@ void TabbedViewContainer::splitView(TerminalDisplay *view, Qt::Orientation orien void TabbedViewContainer::connectTerminalDisplay(TerminalDisplay *display) { auto item = display->sessionController(); - connect(item, &Konsole::SessionController::viewFocused, this, - &Konsole::TabbedViewContainer::currentSessionControllerChanged); + connect(item, &Konsole::SessionController::viewFocused, this, &Konsole::TabbedViewContainer::currentSessionControllerChanged); - connect(item, &Konsole::ViewProperties::titleChanged, this, - &Konsole::TabbedViewContainer::updateTitle); + connect(item, &Konsole::ViewProperties::titleChanged, this, &Konsole::TabbedViewContainer::updateTitle); - connect(item, &Konsole::ViewProperties::colorChanged, this, - &Konsole::TabbedViewContainer::updateColor); + connect(item, &Konsole::ViewProperties::colorChanged, this, &Konsole::TabbedViewContainer::updateColor); - connect(item, &Konsole::ViewProperties::iconChanged, this, - &Konsole::TabbedViewContainer::updateIcon); + connect(item, &Konsole::ViewProperties::iconChanged, this, &Konsole::TabbedViewContainer::updateIcon); - connect(item, &Konsole::ViewProperties::activity, this, - &Konsole::TabbedViewContainer::updateActivity); + connect(item, &Konsole::ViewProperties::activity, this, &Konsole::TabbedViewContainer::updateActivity); - connect(item, &Konsole::ViewProperties::notificationChanged, this, - &Konsole::TabbedViewContainer::updateNotification); + connect(item, &Konsole::ViewProperties::notificationChanged, this, &Konsole::TabbedViewContainer::updateNotification); - connect(item, &Konsole::ViewProperties::readOnlyChanged, this, - &Konsole::TabbedViewContainer::updateSpecialState); + connect(item, &Konsole::ViewProperties::readOnlyChanged, this, &Konsole::TabbedViewContainer::updateSpecialState); - connect(item, &Konsole::ViewProperties::copyInputChanged, this, - &Konsole::TabbedViewContainer::updateSpecialState); + connect(item, &Konsole::ViewProperties::copyInputChanged, this, &Konsole::TabbedViewContainer::updateSpecialState); } void TabbedViewContainer::disconnectTerminalDisplay(TerminalDisplay *display) @@ -386,7 +371,7 @@ void TabbedViewContainer::disconnectTerminalDisplay(TerminalDisplay *display) void TabbedViewContainer::viewDestroyed(QObject *view) { - QWidget *widget = qobject_cast(view); + QWidget *widget = qobject_cast(view); Q_ASSERT(widget); const int idx = indexOf(widget); @@ -423,7 +408,7 @@ void TabbedViewContainer::activatePreviousView() setCurrentIndex(index == 0 ? count() - 1 : index - 1); } -void TabbedViewContainer::keyReleaseEvent(QKeyEvent* event) +void TabbedViewContainer::keyReleaseEvent(QKeyEvent *event) { if (event->modifiers() == Qt::NoModifier) { _connectedViewManager->updateTerminalDisplayHistory(); @@ -450,10 +435,7 @@ void TabbedViewContainer::renameTab(int index) { if (index != -1) { setCurrentIndex(index); - viewSplitterAt(index) - -> activeTerminalDisplay() - -> sessionController() - -> rename(); + viewSplitterAt(index)->activeTerminalDisplay()->sessionController()->rename(); } } @@ -468,9 +450,9 @@ void TabbedViewContainer::openTabContextMenu(const QPoint &point) return; } - //TODO: add a countChanged signal so we can remove this for. + // TODO: add a countChanged signal so we can remove this for. // Detaching in mac causes crashes. - for(auto action : _contextPopupMenu->actions()) { + for (auto action : _contextPopupMenu->actions()) { if (action->objectName() == QStringLiteral("tab-detach")) { action->setEnabled(count() > 1); } @@ -482,7 +464,7 @@ void TabbedViewContainer::openTabContextMenu(const QPoint &point) void TabbedViewContainer::currentTabChanged(int index) { if (index != -1) { - auto splitview = qobject_cast(widget(index)); + auto splitview = qobject_cast(widget(index)); auto view = splitview->activeTerminalDisplay(); setTabActivity(index, false); _tabIconState[splitview].notification = Session::NoNotification; @@ -522,8 +504,8 @@ void TabbedViewContainer::setTabActivity(int index, bool activity) void TabbedViewContainer::updateTitle(ViewProperties *item) { - auto controller = qobject_cast(item); - auto topLevelSplitter = qobject_cast(controller->view()->parentWidget())->getToplevelSplitter(); + auto controller = qobject_cast(item); + auto topLevelSplitter = qobject_cast(controller->view()->parentWidget())->getToplevelSplitter(); if (controller->view() != topLevelSplitter->activeTerminalDisplay()) { return; } @@ -540,7 +522,7 @@ void TabbedViewContainer::updateTitle(ViewProperties *item) void TabbedViewContainer::updateColor(ViewProperties *item) { auto controller = qobject_cast(item); - auto topLevelSplitter = qobject_cast(controller->view()->parentWidget())->getToplevelSplitter(); + auto topLevelSplitter = qobject_cast(controller->view()->parentWidget())->getToplevelSplitter(); const int index = indexOf(topLevelSplitter); Q_EMIT setColor(index, item->color()); @@ -549,7 +531,7 @@ void TabbedViewContainer::updateColor(ViewProperties *item) void TabbedViewContainer::updateIcon(ViewProperties *item) { auto controller = qobject_cast(item); - auto topLevelSplitter = qobject_cast(controller->view()->parentWidget())->getToplevelSplitter(); + auto topLevelSplitter = qobject_cast(controller->view()->parentWidget())->getToplevelSplitter(); const int index = indexOf(topLevelSplitter); const auto &state = _tabIconState[topLevelSplitter]; @@ -566,15 +548,14 @@ void TabbedViewContainer::updateIcon(ViewProperties *item) QIcon icon = item->icon(); if (state.notification != Session::NoNotification) { - switch(state.notification) { + switch (state.notification) { case Session::Bell: { auto session = controller->session(); auto profilePtr = SessionManager::instance()->sessionProfile(session); if (profilePtr->property(Profile::BellMode) != Enum::NoBell) { icon = QIcon::fromTheme(QLatin1String("notifications")); } - } - break; + } break; case Session::Activity: icon = QIcon::fromTheme(QLatin1String("dialog-information")); break; @@ -597,8 +578,8 @@ void TabbedViewContainer::updateIcon(ViewProperties *item) void TabbedViewContainer::updateActivity(ViewProperties *item) { - auto controller = qobject_cast(item); - auto topLevelSplitter = qobject_cast(controller->view()->parentWidget())->getToplevelSplitter(); + auto controller = qobject_cast(item); + auto topLevelSplitter = qobject_cast(controller->view()->parentWidget())->getToplevelSplitter(); const int index = indexOf(topLevelSplitter); if (index != currentIndex()) { @@ -608,8 +589,8 @@ void TabbedViewContainer::updateActivity(ViewProperties *item) void TabbedViewContainer::updateNotification(ViewProperties *item, Session::Notification notification, bool enabled) { - auto controller = qobject_cast(item); - auto topLevelSplitter = qobject_cast(controller->view()->parentWidget())->getToplevelSplitter(); + auto controller = qobject_cast(item); + auto topLevelSplitter = qobject_cast(controller->view()->parentWidget())->getToplevelSplitter(); const int index = indexOf(topLevelSplitter); auto &state = _tabIconState[topLevelSplitter]; @@ -624,13 +605,13 @@ void TabbedViewContainer::updateNotification(ViewProperties *item, Session::Noti void TabbedViewContainer::updateSpecialState(ViewProperties *item) { - auto controller = qobject_cast(item); - auto topLevelSplitter = qobject_cast(controller->view()->parentWidget())->getToplevelSplitter(); + auto controller = qobject_cast(item); + auto topLevelSplitter = qobject_cast(controller->view()->parentWidget())->getToplevelSplitter(); auto &state = _tabIconState[topLevelSplitter]; state.readOnly = true; state.broadcast = true; - const auto displays = topLevelSplitter->findChildren(); + const auto displays = topLevelSplitter->findChildren(); for (const auto display : displays) { if (!display->sessionController()->isReadOnly()) { state.readOnly = false; @@ -644,7 +625,7 @@ void TabbedViewContainer::updateSpecialState(ViewProperties *item) void TabbedViewContainer::currentSessionControllerChanged(SessionController *controller) { - auto topLevelSplitter = qobject_cast(controller->view()->parentWidget())->getToplevelSplitter(); + auto topLevelSplitter = qobject_cast(controller->view()->parentWidget())->getToplevelSplitter(); const int index = indexOf(topLevelSplitter); if (index == currentIndex()) { @@ -653,16 +634,17 @@ void TabbedViewContainer::currentSessionControllerChanged(SessionController *con state.notification = Session::NoNotification; } - updateTitle(qobject_cast(controller)); - updateColor(qobject_cast(controller)); - updateActivity(qobject_cast(controller)); - updateSpecialState(qobject_cast(controller)); + updateTitle(qobject_cast(controller)); + updateColor(qobject_cast(controller)); + updateActivity(qobject_cast(controller)); + updateSpecialState(qobject_cast(controller)); } -void TabbedViewContainer::closeTerminalTab(int idx) { +void TabbedViewContainer::closeTerminalTab(int idx) +{ Q_EMIT removeColor(idx); - //TODO: This for should probably go to the ViewSplitter - for (auto terminal : viewSplitterAt(idx)->findChildren()) { + // TODO: This for should probably go to the ViewSplitter + for (auto terminal : viewSplitterAt(idx)->findChildren()) { terminal->sessionController()->closeSession(); } } @@ -672,7 +654,8 @@ ViewManager *TabbedViewContainer::connectedViewManager() return _connectedViewManager; } -void TabbedViewContainer::setNavigationVisibility(ViewManager::NavigationVisibility navigationVisibility) { +void TabbedViewContainer::setNavigationVisibility(ViewManager::NavigationVisibility navigationVisibility) +{ if (navigationVisibility == ViewManager::NavigationNotSet) { return; } @@ -687,7 +670,7 @@ void TabbedViewContainer::setNavigationVisibility(ViewManager::NavigationVisibil void TabbedViewContainer::toggleMaximizeCurrentTerminal() { - if (auto *terminal = qobject_cast(sender())) { + if (auto *terminal = qobject_cast(sender())) { terminal->setFocus(Qt::FocusReason::OtherFocusReason); } @@ -699,12 +682,12 @@ void TabbedViewContainer::moveTabLeft() if (currentIndex() == 0) { return; } - tabBar()->moveTab(currentIndex(), currentIndex() -1); + tabBar()->moveTab(currentIndex(), currentIndex() - 1); } void TabbedViewContainer::moveTabRight() { - if (currentIndex() == count() -1) { + if (currentIndex() == count() - 1) { return; } tabBar()->moveTab(currentIndex(), currentIndex() + 1); @@ -715,7 +698,8 @@ void TabbedViewContainer::setNavigationBehavior(int behavior) _newTabBehavior = static_cast(behavior); } -void TabbedViewContainer::moveToNewTab(TerminalDisplay* display) { +void TabbedViewContainer::moveToNewTab(TerminalDisplay *display) +{ // Ensure that the current terminal is not maximized so that the other views will be shown properly activeViewSplitter()->handleMinimizeMaximize(false); addView(display); diff --git a/src/widgets/ViewContainer.h b/src/widgets/ViewContainer.h index 8e0a0986a..4e36fb6fc 100644 --- a/src/widgets/ViewContainer.h +++ b/src/widgets/ViewContainer.h @@ -20,7 +20,8 @@ class QPoint; class QToolButton; class QMenu; -namespace Konsole { +namespace Konsole +{ class ViewProperties; class ViewManager; class TabbedViewContainer; @@ -86,8 +87,8 @@ public: /** Changes the active view to the last view */ void activateLastView(); - void setCss(const QString& styleSheet = QString()); - void setCssFromFile(const QUrl& url); + void setCss(const QString &styleSheet = QString()); + void setCssFromFile(const QUrl &url); ViewSplitter *activeViewSplitter(); /** @@ -99,7 +100,7 @@ public: /** Moves the view to the left. */ MoveViewLeft, /** Moves the view to the right. */ - MoveViewRight + MoveViewRight, }; /** @@ -153,13 +154,13 @@ public: /** Put newly created tab at the end. */ PutNewTabAtTheEnd = 0, /** Put newly created tab right after current tab. */ - PutNewTabAfterCurrentTab = 1 + PutNewTabAfterCurrentTab = 1, }; void setNavigationBehavior(int behavior); - void terminalDisplayDropped(TerminalDisplay* terminalDisplay); + void terminalDisplayDropped(TerminalDisplay *terminalDisplay); - void moveToNewTab(TerminalDisplay* display); + void moveToNewTab(TerminalDisplay *display); QSize sizeHint() const override; @@ -218,13 +219,19 @@ private: void forgetView(); struct TabIconState { - TabIconState(): readOnly(false), broadcast(false), notification(Session::NoNotification) {} + TabIconState() + : readOnly(false) + , broadcast(false) + , notification(Session::NoNotification) + { + } bool readOnly; bool broadcast; Session::Notification notification; - bool isAnyStateActive() const { + bool isAnyStateActive() const + { return readOnly || broadcast || (notification != Session::NoNotification); } }; @@ -239,6 +246,5 @@ private: NewTabBehavior _newTabBehavior; }; - } -#endif //VIEWCONTAINER_H +#endif // VIEWCONTAINER_H diff --git a/src/widgets/ViewSplitter.cpp b/src/widgets/ViewSplitter.cpp index 3ba536968..d33787624 100644 --- a/src/widgets/ViewSplitter.cpp +++ b/src/widgets/ViewSplitter.cpp @@ -9,43 +9,49 @@ #include "KonsoleSettings.h" // Qt +#include #include #include #include -#include #include // C++ #include // Konsole -#include "widgets/ViewContainer.h" #include "terminalDisplay/TerminalDisplay.h" +#include "widgets/ViewContainer.h" -using Konsole::ViewSplitter; using Konsole::TerminalDisplay; +using Konsole::ViewSplitter; bool ViewSplitter::m_drawTopLevelHandler; Qt::Orientation ViewSplitter::m_topLevelHandlerDrawnOrientation; -//TODO: Connect the TerminalDisplay destroyed signal here. +// TODO: Connect the TerminalDisplay destroyed signal here. -namespace { - int calculateHandleWidth(int settingsEnum) { - switch (settingsEnum) { - case Konsole::KonsoleSettings::SplitDragHandleLarge: return 10; - case Konsole::KonsoleSettings::SplitDragHandleMedium: return 5; - case Konsole::KonsoleSettings::SplitDragHandleSmall: return 1; - default: return 1; - } +namespace +{ +int calculateHandleWidth(int settingsEnum) +{ + switch (settingsEnum) { + case Konsole::KonsoleSettings::SplitDragHandleLarge: + return 10; + case Konsole::KonsoleSettings::SplitDragHandleMedium: + return 5; + case Konsole::KonsoleSettings::SplitDragHandleSmall: + return 1; + default: + return 1; } } +} -ViewSplitter::ViewSplitter(QWidget *parent) : - QSplitter(parent) +ViewSplitter::ViewSplitter(QWidget *parent) + : QSplitter(parent) { setAcceptDrops(true); - connect(KonsoleSettings::self(), &KonsoleSettings::configChanged, this, [this]{ + connect(KonsoleSettings::self(), &KonsoleSettings::configChanged, this, [this] { setHandleWidth(calculateHandleWidth(KonsoleSettings::self()->splitDragHandleSize())); }); } @@ -56,7 +62,7 @@ void ViewSplitter::adjustActiveTerminalDisplaySize(int percentage) auto focusedTerminalDisplay = activeTerminalDisplay(); Q_ASSERT(focusedTerminalDisplay); - auto parentSplitter = qobject_cast(focusedTerminalDisplay->parent()); + auto parentSplitter = qobject_cast(focusedTerminalDisplay->parent()); const int containerIndex = parentSplitter->indexOf(activeTerminalDisplay()); Q_ASSERT(containerIndex != -1); @@ -66,7 +72,7 @@ void ViewSplitter::adjustActiveTerminalDisplaySize(int percentage) const auto newSize = static_cast(oldSize * (1.0 + percentage / 100.0)); const int perContainerDelta = (count() == 1) ? 0 : ((newSize - oldSize) / (count() - 1)) * (-1); - for (int& size : containerSizes) { + for (int &size : containerSizes) { size += perContainerDelta; } containerSizes[containerIndex] = newSize; @@ -99,8 +105,7 @@ void ViewSplitter::updateSizes() void ViewSplitter::addTerminalDisplay(TerminalDisplay *terminalDisplay, Qt::Orientation containerOrientation, AddBehavior behavior) { ViewSplitter *splitter = activeSplitter(); - const int currentIndex = splitter->activeTerminalDisplay() == nullptr ? splitter->count() - : splitter->indexOf(splitter->activeTerminalDisplay()); + const int currentIndex = splitter->activeTerminalDisplay() == nullptr ? splitter->count() : splitter->indexOf(splitter->activeTerminalDisplay()); if (splitter->count() < 2) { splitter->insertWidget(behavior == AddBehavior::AddBefore ? currentIndex : currentIndex + 1, terminalDisplay); @@ -153,8 +158,8 @@ void ViewSplitter::childEvent(QChildEvent *event) } } - auto terminals = getToplevelSplitter()->findChildren(); - for(auto terminal : terminals) { + auto terminals = getToplevelSplitter()->findChildren(); + for (auto terminal : terminals) { terminal->headerBar()->applyVisibilitySettings(); } } @@ -162,7 +167,7 @@ void ViewSplitter::childEvent(QChildEvent *event) void ViewSplitter::handleFocusDirection(Qt::Orientation orientation, int direction) { auto terminalDisplay = activeTerminalDisplay(); - auto parentSplitter = qobject_cast(terminalDisplay->parentWidget()); + auto parentSplitter = qobject_cast(terminalDisplay->parentWidget()); auto topSplitter = parentSplitter->getToplevelSplitter(); // Find the theme's splitter width + extra space to find valid terminal @@ -173,25 +178,25 @@ void ViewSplitter::handleFocusDirection(Qt::Orientation orientation, int directi const auto startMapped = parentSplitter->mapTo(topSplitter, start); const int newX = orientation != Qt::Horizontal ? startMapped.x() + handleWidth - : direction == 1 ? startMapped.x() + terminalDisplay->width() + handleWidth - : startMapped.x() - handleWidth; + : direction == 1 ? startMapped.x() + terminalDisplay->width() + handleWidth + : startMapped.x() - handleWidth; const int newY = orientation != Qt::Vertical ? startMapped.y() + handleWidth - : direction == 1 ? startMapped.y() + terminalDisplay->height() + handleWidth - : startMapped.y() - handleWidth; + : direction == 1 ? startMapped.y() + terminalDisplay->height() + handleWidth + : startMapped.y() - handleWidth; const auto newPoint = QPoint(newX, newY); auto child = topSplitter->childAt(newPoint); TerminalDisplay *focusTerminal = nullptr; - if (auto* terminal = qobject_cast(child)) { + if (auto *terminal = qobject_cast(child)) { focusTerminal = terminal; - } else if (qobject_cast(child) != nullptr) { - auto targetSplitter = qobject_cast(child->parent()); - focusTerminal = qobject_cast(targetSplitter->widget(0)); - } else if (qobject_cast(child) != nullptr) { - while(child != nullptr && focusTerminal == nullptr) { - focusTerminal = qobject_cast(child->parentWidget()); + } else if (qobject_cast(child) != nullptr) { + auto targetSplitter = qobject_cast(child->parent()); + focusTerminal = qobject_cast(targetSplitter->widget(0)); + } else if (qobject_cast(child) != nullptr) { + while (child != nullptr && focusTerminal == nullptr) { + focusTerminal = qobject_cast(child->parentWidget()); child = child->parentWidget(); } } @@ -223,16 +228,15 @@ void ViewSplitter::focusRight() TerminalDisplay *ViewSplitter::activeTerminalDisplay() const { auto focusedWidget = focusWidget(); - auto focusedTerminalDisplay = qobject_cast(focusedWidget); + auto focusedTerminalDisplay = qobject_cast(focusedWidget); // TD's child can be focused - try to find parent. while (focusedTerminalDisplay == nullptr && focusedWidget != nullptr && focusedWidget != this) { focusedWidget = focusedWidget->parentWidget(); - focusedTerminalDisplay = qobject_cast(focusedWidget); + focusedTerminalDisplay = qobject_cast(focusedWidget); } - return focusedTerminalDisplay != nullptr ? focusedTerminalDisplay - : findChild(); + return focusedTerminalDisplay != nullptr ? focusedTerminalDisplay : findChild(); } void ViewSplitter::toggleMaximizeCurrentTerminal() @@ -241,26 +245,29 @@ void ViewSplitter::toggleMaximizeCurrentTerminal() handleMinimizeMaximize(m_terminalMaximized); } -namespace { - void restoreAll(QList&& terminalDisplays, QList&& splitters) { - for (auto splitter : splitters) { - splitter->setVisible(true); - } - for (auto terminalDisplay : terminalDisplays) { - terminalDisplay->setVisible(true); - } +namespace +{ +void restoreAll(QList &&terminalDisplays, QList &&splitters) +{ + for (auto splitter : splitters) { + splitter->setVisible(true); + } + for (auto terminalDisplay : terminalDisplays) { + terminalDisplay->setVisible(true); } } +} -bool ViewSplitter::hideRecurse(TerminalDisplay *currentTerminalDisplay) { +bool ViewSplitter::hideRecurse(TerminalDisplay *currentTerminalDisplay) +{ bool allHidden = true; - for(int i = 0, end = count(); i < end; i++) { - if (auto *maybeSplitter = qobject_cast(widget(i))) { + for (int i = 0, end = count(); i < end; i++) { + if (auto *maybeSplitter = qobject_cast(widget(i))) { allHidden = maybeSplitter->hideRecurse(currentTerminalDisplay) && allHidden; continue; } - if (auto maybeTerminalDisplay = qobject_cast(widget(i))) { + if (auto maybeTerminalDisplay = qobject_cast(widget(i))) { if (maybeTerminalDisplay == currentTerminalDisplay) { allHidden = false; } else { @@ -283,35 +290,35 @@ void ViewSplitter::handleMinimizeMaximize(bool maximize) if (maximize) { for (int i = 0, end = topLevelSplitter->count(); i < end; i++) { auto widgetAt = topLevelSplitter->widget(i); - if (auto *maybeSplitter = qobject_cast(widgetAt)) { + if (auto *maybeSplitter = qobject_cast(widgetAt)) { maybeSplitter->hideRecurse(currentTerminalDisplay); } - if (auto maybeTerminalDisplay = qobject_cast(widgetAt)) { + if (auto maybeTerminalDisplay = qobject_cast(widgetAt)) { if (maybeTerminalDisplay != currentTerminalDisplay) { maybeTerminalDisplay->setVisible(false); } } } } else { - restoreAll(topLevelSplitter->findChildren(), - topLevelSplitter->findChildren()); + restoreAll(topLevelSplitter->findChildren(), topLevelSplitter->findChildren()); } } ViewSplitter *ViewSplitter::getToplevelSplitter() { ViewSplitter *current = this; - while(qobject_cast(current->parentWidget()) != nullptr) { - current = qobject_cast(current->parentWidget()); + while (qobject_cast(current->parentWidget()) != nullptr) { + current = qobject_cast(current->parentWidget()); } return current; } -namespace { - TerminalDisplay *currentDragTarget = nullptr; +namespace +{ +TerminalDisplay *currentDragTarget = nullptr; } -void Konsole::ViewSplitter::dragEnterEvent(QDragEnterEvent* ev) +void Konsole::ViewSplitter::dragEnterEvent(QDragEnterEvent *ev) { const auto dragId = QStringLiteral("konsole/terminal_display"); if (ev->mimeData()->hasFormat(dragId)) { @@ -327,10 +334,10 @@ void Konsole::ViewSplitter::dragEnterEvent(QDragEnterEvent* ev) } } -void Konsole::ViewSplitter::dragMoveEvent(QDragMoveEvent* ev) +void Konsole::ViewSplitter::dragMoveEvent(QDragMoveEvent *ev) { auto currentWidget = childAt(ev->pos()); - if (auto terminal = qobject_cast(currentWidget)) { + if (auto terminal = qobject_cast(currentWidget)) { if ((currentDragTarget != nullptr) && currentDragTarget != terminal) { currentDragTarget->hideDragTarget(); } @@ -343,7 +350,7 @@ void Konsole::ViewSplitter::dragMoveEvent(QDragMoveEvent* ev) } } -void Konsole::ViewSplitter::dragLeaveEvent(QDragLeaveEvent* event) +void Konsole::ViewSplitter::dragLeaveEvent(QDragLeaveEvent *event) { Q_UNUSED(event) if (currentDragTarget != nullptr) { @@ -352,7 +359,7 @@ void Konsole::ViewSplitter::dragLeaveEvent(QDragLeaveEvent* event) } } -void Konsole::ViewSplitter::dropEvent(QDropEvent* ev) +void Konsole::ViewSplitter::dropEvent(QDropEvent *ev) { if (ev->mimeData()->hasFormat(QStringLiteral("konsole/terminal_display"))) { if (getToplevelSplitter()->terminalMaximized()) { @@ -360,18 +367,16 @@ void Konsole::ViewSplitter::dropEvent(QDropEvent* ev) } if (currentDragTarget != nullptr) { currentDragTarget->hideDragTarget(); - auto source = qobject_cast(ev->source()); + auto source = qobject_cast(ev->source()); source->setVisible(false); source->setParent(nullptr); currentDragTarget->setFocus(Qt::OtherFocusReason); const auto droppedEdge = currentDragTarget->droppedEdge(); - AddBehavior behavior = droppedEdge == Qt::LeftEdge || droppedEdge == Qt::TopEdge - ? AddBehavior::AddBefore : AddBehavior::AddAfter; + AddBehavior behavior = droppedEdge == Qt::LeftEdge || droppedEdge == Qt::TopEdge ? AddBehavior::AddBefore : AddBehavior::AddAfter; - Qt::Orientation orientation = droppedEdge == Qt::LeftEdge || droppedEdge == Qt::RightEdge - ? Qt::Horizontal : Qt::Vertical; + Qt::Orientation orientation = droppedEdge == Qt::LeftEdge || droppedEdge == Qt::RightEdge ? Qt::Horizontal : Qt::Vertical; // topLevel is the splitter that's connected with the ViewManager // that in turn can call the SessionController. @@ -389,9 +394,9 @@ void Konsole::ViewSplitter::showEvent(QShowEvent *) setFocusProxy(activeSplitter()->activeTerminalDisplay()); } -QPoint Konsole::ViewSplitter::mapToTopLevel(const QPoint& p) +QPoint Konsole::ViewSplitter::mapToTopLevel(const QPoint &p) { - auto parentSplitter = qobject_cast(parent()); + auto parentSplitter = qobject_cast(parent()); if (parentSplitter) { auto next_pos = mapToParent(p); return parentSplitter->mapToTopLevel(next_pos); @@ -399,61 +404,58 @@ QPoint Konsole::ViewSplitter::mapToTopLevel(const QPoint& p) return p; } -QPoint Konsole::ViewSplitter::mapFromTopLevel(const QPoint& p) +QPoint Konsole::ViewSplitter::mapFromTopLevel(const QPoint &p) { - - auto parentSplitter = qobject_cast(parent()); + auto parentSplitter = qobject_cast(parent()); if (parentSplitter) { return mapFromParent(parentSplitter->mapFromTopLevel(p)); } return p; } -Konsole::ViewSplitterHandle::ViewSplitterHandle(Qt::Orientation orientation, QSplitter* parent) +Konsole::ViewSplitterHandle::ViewSplitterHandle(Qt::Orientation orientation, QSplitter *parent) : QSplitterHandle(orientation, parent) { } -QSplitterHandle* ViewSplitter::createHandle() +QSplitterHandle *ViewSplitter::createHandle() { return new ViewSplitterHandle(orientation(), this); } -namespace { - QList allSplitterSizes; +namespace +{ +QList allSplitterSizes; - int search_closest(const QList& sorted_array, int x) { - if (sorted_array.isEmpty()) { - return -1; - } - - auto iter_geq = std::lower_bound( - sorted_array.begin(), - sorted_array.end(), - x - ); - - if (iter_geq == sorted_array.begin()) { - return sorted_array[0]; - } - - int a = *(iter_geq - 1); - int b = *(iter_geq); - - if (abs(x - a) < abs(x - b)) { - return a; - } - - return b; +int search_closest(const QList &sorted_array, int x) +{ + if (sorted_array.isEmpty()) { + return -1; } + + auto iter_geq = std::lower_bound(sorted_array.begin(), sorted_array.end(), x); + + if (iter_geq == sorted_array.begin()) { + return sorted_array[0]; + } + + int a = *(iter_geq - 1); + int b = *(iter_geq); + + if (abs(x - a) < abs(x - b)) { + return a; + } + + return b; +} } void Konsole::ViewSplitterHandle::mousePressEvent(QMouseEvent *ev) { - auto parentSplitter = qobject_cast(parentWidget()); + auto parentSplitter = qobject_cast(parentWidget()); auto topLevelSplitter = parentSplitter->getToplevelSplitter(); - QList splitters = topLevelSplitter->findChildren(); + QList splitters = topLevelSplitter->findChildren(); splitters.append(topLevelSplitter); for (auto splitter : splitters) { @@ -464,16 +466,11 @@ void Konsole::ViewSplitterHandle::mousePressEvent(QMouseEvent *ev) int delta = 0; for (auto point : splitter->sizes()) { delta += point; - QPoint thisPoint = orientation() == Qt::Horizontal - ? QPoint(delta, 0) - : QPoint(0, delta); - + QPoint thisPoint = orientation() == Qt::Horizontal ? QPoint(delta, 0) : QPoint(0, delta); QPoint splitterPos = splitter->mapToTopLevel(thisPoint); - const int ourPos = orientation() == Qt::Horizontal - ? splitterPos.x() - : splitterPos.y(); + const int ourPos = orientation() == Qt::Horizontal ? splitterPos.x() : splitterPos.y(); allSplitterSizes.push_back(ourPos); } @@ -501,15 +498,15 @@ void Konsole::ViewSplitterHandle::mouseReleaseEvent(QMouseEvent *ev) void Konsole::ViewSplitterHandle::mouseMoveEvent(QMouseEvent *ev) { - ViewSplitter *parentSplitter = qobject_cast(parentWidget()); + ViewSplitter *parentSplitter = qobject_cast(parentWidget()); QPoint thisPoint = parentSplitter->mapToTopLevel(mapToParent(ev->pos())); const int thisValue = orientation() == Qt::Horizontal ? thisPoint.x() : thisPoint.y(); - const int nearest = search_closest(allSplitterSizes, thisValue ); + const int nearest = search_closest(allSplitterSizes, thisValue); const int threshould = qAbs(nearest - thisValue); if (threshould <= 20) { - auto *thisSplitter = qobject_cast(splitter()); + auto *thisSplitter = qobject_cast(splitter()); QPoint localPoint = thisSplitter->mapFromTopLevel(orientation() == Qt::Horizontal ? QPoint(nearest, 0) : QPoint(0, nearest)); moveSplitter(orientation() == Qt::Horizontal ? localPoint.x() : localPoint.y()); return; diff --git a/src/widgets/ViewSplitter.h b/src/widgets/ViewSplitter.h index cb4645ea2..8927f47d9 100644 --- a/src/widgets/ViewSplitter.h +++ b/src/widgets/ViewSplitter.h @@ -19,13 +19,16 @@ class QDragEnterEvent; class QDropEvent; class QDragLeaveEvent; -namespace Konsole { +namespace Konsole +{ class TerminalDisplay; -class ViewSplitterHandle : public QSplitterHandle { +class ViewSplitterHandle : public QSplitterHandle +{ Q_OBJECT public: ViewSplitterHandle(Qt::Orientation orientation, QSplitter *parent); + protected: void mousePressEvent(QMouseEvent *ev) override; void mouseReleaseEvent(QMouseEvent *ev) override; @@ -51,7 +54,7 @@ class KONSOLEPRIVATE_EXPORT ViewSplitter : public QSplitter public: explicit ViewSplitter(QWidget *parent = nullptr); - enum class AddBehavior {AddBefore, AddAfter}; + enum class AddBehavior { AddBefore, AddAfter, }; /** * Locates the child ViewSplitter widget which currently has the focus * and inserts the container into it. @@ -69,7 +72,7 @@ public: * @param behavior Specifies whether to add new terminal after current * tab or at end. */ - void addTerminalDisplay(TerminalDisplay* terminalDisplay, Qt::Orientation containerOrientation, AddBehavior behavior = AddBehavior::AddAfter); + void addTerminalDisplay(TerminalDisplay *terminalDisplay, Qt::Orientation containerOrientation, AddBehavior behavior = AddBehavior::AddAfter); /** Returns the child ViewSplitter widget which currently has the focus */ ViewSplitter *activeSplitter(); @@ -114,17 +117,21 @@ public: void handleFocusDirection(Qt::Orientation orientation, int direction); - void childEvent(QChildEvent* event) override; - bool terminalMaximized() const { return m_terminalMaximized; } + void childEvent(QChildEvent *event) override; + bool terminalMaximized() const + { + return m_terminalMaximized; + } QSplitterHandle *createHandle() override; - QPoint mapToTopLevel(const QPoint& p); - QPoint mapFromTopLevel(const QPoint& p); + QPoint mapToTopLevel(const QPoint &p); + QPoint mapFromTopLevel(const QPoint &p); + protected: void dragEnterEvent(QDragEnterEvent *ev) override; void dragMoveEvent(QDragMoveEvent *ev) override; - void dragLeaveEvent(QDragLeaveEvent * event) override; + void dragLeaveEvent(QDragLeaveEvent *event) override; void dropEvent(QDropEvent *ev) override; void showEvent(QShowEvent *) override; @@ -149,4 +156,4 @@ private: static Qt::Orientation m_topLevelHandlerDrawnOrientation; }; } -#endif //VIEWSPLITTER_H +#endif // VIEWSPLITTER_H diff --git a/tests/bugs/spam-stderr.c b/tests/bugs/spam-stderr.c index de4c68802..f64fe20c9 100644 --- a/tests/bugs/spam-stderr.c +++ b/tests/bugs/spam-stderr.c @@ -4,13 +4,9 @@ #include -int -main() +int main() { - for (int i = 0; i < 100000000; i++) - { - fprintf (stderr, "foo %d\n", i); + for (int i = 0; i < 100000000; i++) { + fprintf(stderr, "foo %d\n", i); } } - - diff --git a/tests/features/signaltests.c b/tests/features/signaltests.c index c4568e05d..a29492165 100644 --- a/tests/features/signaltests.c +++ b/tests/features/signaltests.c @@ -1,76 +1,77 @@ /* - Author: Kasper Laudrup + Author: Kasper Laudrup This code is in the public domain. From patch from bko 214908 */ -#include #include +#include #include int signals[] = {SIGSTOP, SIGCONT, SIGHUP, SIGINT, SIGTERM, SIGKILL, SIGUSR1, SIGUSR2}; -print_signal_name(int signal) { - char* signame; - switch(signal) { - case SIGSTOP: - signame = "SIGSTOP"; - break; - case SIGCONT: - signame = "SIGCONT"; - break; - case SIGHUP: - signame = "SIGHUP"; - break; - case SIGINT: - signame = "SIGINT"; - break; - case SIGTERM: - signame = "SIGTERM"; - break; - case SIGKILL: - signame = "SIGKILL"; - break; - case SIGUSR1: - signame = "SIGUSR1"; - break; - case SIGUSR2: - signame = "SIGUSR1"; - break; - default: - signame = "UNKNOWN"; - break; - } - printf("Caught signal: %s\n", signame); +print_signal_name(int signal) +{ + char *signame; + switch (signal) { + case SIGSTOP: + signame = "SIGSTOP"; + break; + case SIGCONT: + signame = "SIGCONT"; + break; + case SIGHUP: + signame = "SIGHUP"; + break; + case SIGINT: + signame = "SIGINT"; + break; + case SIGTERM: + signame = "SIGTERM"; + break; + case SIGKILL: + signame = "SIGKILL"; + break; + case SIGUSR1: + signame = "SIGUSR1"; + break; + case SIGUSR2: + signame = "SIGUSR1"; + break; + default: + signame = "UNKNOWN"; + break; + } + printf("Caught signal: %s\n", signame); } -void handler(int signal) { +void handler(int signal) +{ } int main(int argc, char *argv[]) { - sigset_t waitset; - struct sigaction sigact; - int signal, result, i; - int signals_size = sizeof(signals) / sizeof(int); + sigset_t waitset; + struct sigaction sigact; + int signal, result, i; + int signals_size = sizeof(signals) / sizeof(int); - sigemptyset(&sigact.sa_mask); - sigemptyset(&waitset); - sigact.sa_flags = 0; - sigact.sa_handler = handler; - for (i=0; i. This code is in the public domain. - + */ #include @@ -31,25 +31,28 @@ struct termios save; struct termios curr; -#define HERE fprintf(stderr,"%s(%d): here.\n",__FILE__,__LINE__) +#define HERE fprintf(stderr, "%s(%d): here.\n", __FILE__, __LINE__) main() -{ int cc; - FILE* sysin = fopen("ttt","r"); - tcgetattr(0, &save); - tcgetattr(0, &curr); - cfmakeraw(&curr); - tcsetattr(0, TCSANOW, &curr); - cc = fgetc(sysin); - while( cc > 0 ) - { int tmp; - while (cc > 0) - { - fputc(cc,stdout); cc = fgetc(sysin); - if (cc == 0x1b) break; +{ + int cc; + FILE *sysin = fopen("ttt", "r"); + tcgetattr(0, &save); + tcgetattr(0, &curr); + cfmakeraw(&curr); + tcsetattr(0, TCSANOW, &curr); + cc = fgetc(sysin); + while (cc > 0) { + int tmp; + while (cc > 0) { + fputc(cc, stdout); + cc = fgetc(sysin); + if (cc == 0x1b) + break; + } + tmp = fgetc(stdin); + if (tmp == 3) + break; } - tmp = fgetc(stdin); - if (tmp == 3) break; - } - tcsetattr(0, TCSANOW, &save); + tcsetattr(0, TCSANOW, &save); } diff --git a/tests/legacy/quote.c b/tests/legacy/quote.c index b711a6c64..566d51fcd 100644 --- a/tests/legacy/quote.c +++ b/tests/legacy/quote.c @@ -13,44 +13,51 @@ int empty = 1; void pchr(int c, int indent) { - if (skip) - { - skip = (c != '\n'); - return; - } - switch(c) - { + if (skip) { + skip = (c != '\n'); + return; + } + switch (c) { case '\n': - if (!empty) - printf("\\n\"\n%*s\"",indent,""); - empty = 1; - break; - case '#' : - skip = 1; - break; - case '"' : case '\\': - printf("\\"); - // fallthrough + if (!empty) + printf("\\n\"\n%*s\"", indent, ""); + empty = 1; + break; + case '#': + skip = 1; + break; + case '"': + case '\\': + printf("\\"); + // fallthrough default: - printf("%c",c); - empty = 0; - break; - } + printf("%c", c); + empty = 0; + break; + } } #define INDENT 2 -int main(int argc, char* argv[]) -{ int cc; FILE *sysin; - if (argc < 2) { fprintf(stderr,"usage: %s filename\n",argv[0]); return 1; } - sysin = fopen(argv[1],"r"); - if (!sysin) { fprintf(stderr,"cannot open %s\n",argv[1]); perror("reason: "); return 1; } - printf("%*s/* generated by '%s %s' */\n\n",INDENT,"",argv[0],argv[1]); - printf("%*s\"",INDENT,""); - while( (cc = fgetc(sysin)) > 0) - { - pchr(cc,INDENT); - } - printf("\"\n"); - fclose(sysin); +int main(int argc, char *argv[]) +{ + int cc; + FILE *sysin; + if (argc < 2) { + fprintf(stderr, "usage: %s filename\n", argv[0]); + return 1; + } + sysin = fopen(argv[1], "r"); + if (!sysin) { + fprintf(stderr, "cannot open %s\n", argv[1]); + perror("reason: "); + return 1; + } + printf("%*s/* generated by '%s %s' */\n\n", INDENT, "", argv[0], argv[1]); + printf("%*s\"", INDENT, ""); + while ((cc = fgetc(sysin)) > 0) { + pchr(cc, INDENT); + } + printf("\"\n"); + fclose(sysin); } diff --git a/tests/misc/ripple.c b/tests/misc/ripple.c index 8d45f0722..675d188f0 100644 --- a/tests/misc/ripple.c +++ b/tests/misc/ripple.c @@ -7,24 +7,28 @@ This is in the public domain as far as can be determined. */ char *crlf = "\015\012"; -char *p = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]\ +char *p = + " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]\ ^_`abcdefghijklmnopqrstuvwxyz{|}~ !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGH\ IJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ !\"#$%&'()*+,-./012\ 3456789:;<=>?@ABCD"; -main(argc,argv) int argc; char *argv[]; { +main(argc, argv) int argc; +char *argv[]; +{ int i, j, w = 80, l = 1000; - if (argc > 1) /* User-specified width */ - w = atoi(argv[1]); - if (argc > 2) /* User-specified number of lines */ - l = atoi(argv[2]); - if (w < 1 || l < 1 || w > 132) /* Quit upon conversion error */ - exit(1); + if (argc > 1) /* User-specified width */ + w = atoi(argv[1]); + if (argc > 2) /* User-specified number of lines */ + l = atoi(argv[2]); + if (w < 1 || l < 1 || w > 132) /* Quit upon conversion error */ + exit(1); - for (j = i = 0; i < l; i++) { /* Ripple loop */ - write(1, p+j, w); + for (j = i = 0; i < l; i++) { /* Ripple loop */ + write(1, p + j, w); write(1, crlf, 2); - if (++j > 94) j = 0; + if (++j > 94) + j = 0; } } diff --git a/tools/uni2characterwidth/properties.h b/tools/uni2characterwidth/properties.h index cf688424d..c63ea0aba 100644 --- a/tools/uni2characterwidth/properties.h +++ b/tools/uni2characterwidth/properties.h @@ -13,44 +13,44 @@ #define CATEGORY_PROPERTY_GROUP(val, sym, intVal) #endif -CATEGORY_PROPERTY_VALUE(Lu, UppercaseLetter, 1<<0) // an uppercase letter -CATEGORY_PROPERTY_VALUE(Ll, LowercaseLetter, 1<<1) // a lowercase letter -CATEGORY_PROPERTY_VALUE(Lt, TitlecaseLetter, 1<<2) // a digraphic character, with first part uppercase -CATEGORY_PROPERTY_GROUP(LC, CasedLetter, 1<<0|1<<1|1<<2) -CATEGORY_PROPERTY_VALUE(Lm, ModifierLetter, 1<<3) // a modifier letter -CATEGORY_PROPERTY_VALUE(Lo, OtherLetter, 1<<4) // other letters, including syllables and ideographs -CATEGORY_PROPERTY_GROUP(L, Letter, 1<<0|1<<1|1<<2|1<<3|1<<4) -CATEGORY_PROPERTY_VALUE(Mn, NonspacingMark, 1<<5) // a nonspacing combining mark (zero advance width) -CATEGORY_PROPERTY_VALUE(Mc, SpacingMark, 1<<6) // a spacing combining mark (positive advance width) -CATEGORY_PROPERTY_VALUE(Me, EnclosingMark, 1<<7) // an enclosing combining mark -CATEGORY_PROPERTY_GROUP(M, Mark, 1<<5|1<<6|1<<7) -CATEGORY_PROPERTY_VALUE(Nd, DecimalNumber, 1<<8) // a decimal digit -CATEGORY_PROPERTY_VALUE(Nl, LetterNumber, 1<<9) // a letterlike numeric character -CATEGORY_PROPERTY_VALUE(No, OtherNumber, 1<<10) // a numeric character of other type -CATEGORY_PROPERTY_GROUP(N, Number, 1<<8|1<<9|1<<10) -CATEGORY_PROPERTY_VALUE(Pc, ConnectorPunctuation, 1<<11) // a connecting punctuation mark, like a tie -CATEGORY_PROPERTY_VALUE(Pd, DashPunctuation, 1<<12) // a dash or hyphen punctuation mark -CATEGORY_PROPERTY_VALUE(Ps, OpenPunctuation, 1<<13) // an opening punctuation mark (of a pair) -CATEGORY_PROPERTY_VALUE(Pe, ClosePunctuation, 1<<14) // a closing punctuation mark (of a pair) -CATEGORY_PROPERTY_VALUE(Pi, InitialPunctuation, 1<<15) // an initial quotation mark -CATEGORY_PROPERTY_VALUE(Pf, FinalPunctuation, 1<<16) // a final quotation mark -CATEGORY_PROPERTY_VALUE(Po, OtherPunctuation, 1<<17) // a punctuation mark of other type -CATEGORY_PROPERTY_GROUP(P, Punctuation, 1<<11|1<<12|1<<13|1<<14|1<<15|1<<16|1<<17) -CATEGORY_PROPERTY_VALUE(Sm, MathSymbol, 1<<18) // a symbol of mathematical use -CATEGORY_PROPERTY_VALUE(Sc, CurrencySymbol, 1<<19) // a currency sign -CATEGORY_PROPERTY_VALUE(Sk, ModifierSymbol, 1<<20) // a non-letterlike modifier symbol -CATEGORY_PROPERTY_VALUE(So, OtherSymbol, 1<<21) // a symbol of other type -CATEGORY_PROPERTY_GROUP(S, Symbol, 1<<18|1<<19|1<<20|1<<21) -CATEGORY_PROPERTY_VALUE(Zs, SpaceSeparator, 1<<22) // a space character (of various non-zero widths) -CATEGORY_PROPERTY_VALUE(Zl, LineSeparator, 1<<23) // U+2028 LINE SEPARATOR only -CATEGORY_PROPERTY_VALUE(Zp, ParagraphSeparator, 1<<24) // U+2029 PARAGRAPH SEPARATOR only -CATEGORY_PROPERTY_GROUP(Z, Separator, 1<<22|1<<23|1<<24) -CATEGORY_PROPERTY_VALUE(Cc, Control, 1<<25) // a C0 or C1 control code -CATEGORY_PROPERTY_VALUE(Cf, Format, 1<<26) // a format control character -CATEGORY_PROPERTY_VALUE(Cs, Surrogate, 1<<27) // a surrogate code point -CATEGORY_PROPERTY_VALUE(Co, PrivateUse, 1<<28) // a private-use character -CATEGORY_PROPERTY_VALUE(Cn, Unassigned, 1<<29) // a reserved unassigned code point or a noncharacter -CATEGORY_PROPERTY_GROUP(C, Other, 1<<25|1<<26|1<<27|1<<28|1<<29) +CATEGORY_PROPERTY_VALUE(Lu, UppercaseLetter, 1 << 0) // an uppercase letter +CATEGORY_PROPERTY_VALUE(Ll, LowercaseLetter, 1 << 1) // a lowercase letter +CATEGORY_PROPERTY_VALUE(Lt, TitlecaseLetter, 1 << 2) // a digraphic character, with first part uppercase +CATEGORY_PROPERTY_GROUP(LC, CasedLetter, 1 << 0 | 1 << 1 | 1 << 2) +CATEGORY_PROPERTY_VALUE(Lm, ModifierLetter, 1 << 3) // a modifier letter +CATEGORY_PROPERTY_VALUE(Lo, OtherLetter, 1 << 4) // other letters, including syllables and ideographs +CATEGORY_PROPERTY_GROUP(L, Letter, 1 << 0 | 1 << 1 | 1 << 2 | 1 << 3 | 1 << 4) +CATEGORY_PROPERTY_VALUE(Mn, NonspacingMark, 1 << 5) // a nonspacing combining mark (zero advance width) +CATEGORY_PROPERTY_VALUE(Mc, SpacingMark, 1 << 6) // a spacing combining mark (positive advance width) +CATEGORY_PROPERTY_VALUE(Me, EnclosingMark, 1 << 7) // an enclosing combining mark +CATEGORY_PROPERTY_GROUP(M, Mark, 1 << 5 | 1 << 6 | 1 << 7) +CATEGORY_PROPERTY_VALUE(Nd, DecimalNumber, 1 << 8) // a decimal digit +CATEGORY_PROPERTY_VALUE(Nl, LetterNumber, 1 << 9) // a letterlike numeric character +CATEGORY_PROPERTY_VALUE(No, OtherNumber, 1 << 10) // a numeric character of other type +CATEGORY_PROPERTY_GROUP(N, Number, 1 << 8 | 1 << 9 | 1 << 10) +CATEGORY_PROPERTY_VALUE(Pc, ConnectorPunctuation, 1 << 11) // a connecting punctuation mark, like a tie +CATEGORY_PROPERTY_VALUE(Pd, DashPunctuation, 1 << 12) // a dash or hyphen punctuation mark +CATEGORY_PROPERTY_VALUE(Ps, OpenPunctuation, 1 << 13) // an opening punctuation mark (of a pair) +CATEGORY_PROPERTY_VALUE(Pe, ClosePunctuation, 1 << 14) // a closing punctuation mark (of a pair) +CATEGORY_PROPERTY_VALUE(Pi, InitialPunctuation, 1 << 15) // an initial quotation mark +CATEGORY_PROPERTY_VALUE(Pf, FinalPunctuation, 1 << 16) // a final quotation mark +CATEGORY_PROPERTY_VALUE(Po, OtherPunctuation, 1 << 17) // a punctuation mark of other type +CATEGORY_PROPERTY_GROUP(P, Punctuation, 1 << 11 | 1 << 12 | 1 << 13 | 1 << 14 | 1 << 15 | 1 << 16 | 1 << 17) +CATEGORY_PROPERTY_VALUE(Sm, MathSymbol, 1 << 18) // a symbol of mathematical use +CATEGORY_PROPERTY_VALUE(Sc, CurrencySymbol, 1 << 19) // a currency sign +CATEGORY_PROPERTY_VALUE(Sk, ModifierSymbol, 1 << 20) // a non-letterlike modifier symbol +CATEGORY_PROPERTY_VALUE(So, OtherSymbol, 1 << 21) // a symbol of other type +CATEGORY_PROPERTY_GROUP(S, Symbol, 1 << 18 | 1 << 19 | 1 << 20 | 1 << 21) +CATEGORY_PROPERTY_VALUE(Zs, SpaceSeparator, 1 << 22) // a space character (of various non-zero widths) +CATEGORY_PROPERTY_VALUE(Zl, LineSeparator, 1 << 23) // U+2028 LINE SEPARATOR only +CATEGORY_PROPERTY_VALUE(Zp, ParagraphSeparator, 1 << 24) // U+2029 PARAGRAPH SEPARATOR only +CATEGORY_PROPERTY_GROUP(Z, Separator, 1 << 22 | 1 << 23 | 1 << 24) +CATEGORY_PROPERTY_VALUE(Cc, Control, 1 << 25) // a C0 or C1 control code +CATEGORY_PROPERTY_VALUE(Cf, Format, 1 << 26) // a format control character +CATEGORY_PROPERTY_VALUE(Cs, Surrogate, 1 << 27) // a surrogate code point +CATEGORY_PROPERTY_VALUE(Co, PrivateUse, 1 << 28) // a private-use character +CATEGORY_PROPERTY_VALUE(Cn, Unassigned, 1 << 29) // a reserved unassigned code point or a noncharacter +CATEGORY_PROPERTY_GROUP(C, Other, 1 << 25 | 1 << 26 | 1 << 27 | 1 << 28 | 1 << 29) #undef CATEGORY_PROPERTY_VALUE #undef CATEGORY_PROPERTY_GROUP @@ -61,12 +61,12 @@ CATEGORY_PROPERTY_GROUP(C, Other, 1<<25|1<<26|1<<27|1<<28|1<<2 #define EAST_ASIAN_WIDTH_PROPERTY_VALUE(val, sym, intVal) #endif -EAST_ASIAN_WIDTH_PROPERTY_VALUE(A, Ambiguous, 1<<0) -EAST_ASIAN_WIDTH_PROPERTY_VALUE(F, Fullwidth, 1<<1) -EAST_ASIAN_WIDTH_PROPERTY_VALUE(H, Halfwidth, 1<<2) -EAST_ASIAN_WIDTH_PROPERTY_VALUE(N, Neutral, 1<<3) -EAST_ASIAN_WIDTH_PROPERTY_VALUE(Na, Narrow, 1<<4) -EAST_ASIAN_WIDTH_PROPERTY_VALUE(W, Wide, 1<<5) +EAST_ASIAN_WIDTH_PROPERTY_VALUE(A, Ambiguous, 1 << 0) +EAST_ASIAN_WIDTH_PROPERTY_VALUE(F, Fullwidth, 1 << 1) +EAST_ASIAN_WIDTH_PROPERTY_VALUE(H, Halfwidth, 1 << 2) +EAST_ASIAN_WIDTH_PROPERTY_VALUE(N, Neutral, 1 << 3) +EAST_ASIAN_WIDTH_PROPERTY_VALUE(Na, Narrow, 1 << 4) +EAST_ASIAN_WIDTH_PROPERTY_VALUE(W, Wide, 1 << 5) #undef EAST_ASIAN_WIDTH_PROPERTY_VALUE @@ -76,11 +76,11 @@ EAST_ASIAN_WIDTH_PROPERTY_VALUE(W, Wide, 1<<5) #define EMOJI_PROPERTY_VALUE(val, sym, intVal) #endif -EMOJI_PROPERTY_VALUE(, None, 0) -EMOJI_PROPERTY_VALUE(Emoji, Emoji, 1<<0) -EMOJI_PROPERTY_VALUE(Emoji_Presentation, EmojiPresentation, 1<<1) -EMOJI_PROPERTY_VALUE(Emoji_Modifier, EmojiModifier, 1<<2) -EMOJI_PROPERTY_VALUE(Emoji_Modifier_Base, EmojiModifier_Base, 1<<3) -EMOJI_PROPERTY_VALUE(Emoji_Component, EmojiComponent, 1<<4) +EMOJI_PROPERTY_VALUE(, None, 0) +EMOJI_PROPERTY_VALUE(Emoji, Emoji, 1 << 0) +EMOJI_PROPERTY_VALUE(Emoji_Presentation, EmojiPresentation, 1 << 1) +EMOJI_PROPERTY_VALUE(Emoji_Modifier, EmojiModifier, 1 << 2) +EMOJI_PROPERTY_VALUE(Emoji_Modifier_Base, EmojiModifier_Base, 1 << 3) +EMOJI_PROPERTY_VALUE(Emoji_Component, EmojiComponent, 1 << 4) #undef EMOJI_PROPERTY_VALUE diff --git a/tools/uni2characterwidth/template.cpp b/tools/uni2characterwidth/template.cpp index 95f32af76..c9eab0ff7 100644 --- a/tools/uni2characterwidth/template.cpp +++ b/tools/uni2characterwidth/template.cpp @@ -6,16 +6,17 @@ SPDX-License-Identifier: GPL-2.0-or-later */ +#include "template.h" #include #include #include -#include "template.h" -static const QString unescape(const QStringRef &str) { +static const QString unescape(const QStringRef &str) +{ QString result; result.reserve(str.length()); - for(int i = 0; i < str.length(); ++i) { - if(i < str.length() - 1 && str[i] == QLatin1Char('\\')) + for (int i = 0; i < str.length(); ++i) { + if (i < str.length() - 1 && str[i] == QLatin1Char('\\')) result += str[++i]; else result += str[i]; @@ -26,24 +27,26 @@ static const QString unescape(const QStringRef &str) { // // Template::Element // -const QString Template::Element::findFmt(Var::DataType type) const { +const QString Template::Element::findFmt(Var::DataType type) const +{ const Template::Element *element; - for(element = this; element != nullptr; element = element->parent) { - if(!element->fmt.isEmpty() && isValidFmt(element->fmt, type)) { + for (element = this; element != nullptr; element = element->parent) { + if (!element->fmt.isEmpty() && isValidFmt(element->fmt, type)) { return element->fmt; } } return defaultFmt(type); } -QString Template::Element::path() const { +QString Template::Element::path() const +{ QStringList namesList; const Template::Element *element; - for(element = this; element != nullptr; element = element->parent) { - if(!element->hasName() && element->parent != nullptr) { + for (element = this; element != nullptr; element = element->parent) { + if (!element->hasName() && element->parent != nullptr) { QString anonName = QStringLiteral("[anon]"); - for(int i = 0; i < element->parent->children.size(); ++i) { - if(&element->parent->children[i] == element) { + for (int i = 0; i < element->parent->children.size(); ++i) { + if (&element->parent->children[i] == element) { anonName = QStringLiteral("[%1]").arg(i); break; } @@ -56,19 +59,27 @@ QString Template::Element::path() const { return namesList.join(QLatin1Char('.')); } -const QString Template::Element::defaultFmt(Var::DataType type) { - switch(type) { - case Var::DataType::Number: return QStringLiteral("%d"); - case Var::DataType::String: return QStringLiteral("%s"); - default: Q_UNREACHABLE(); +const QString Template::Element::defaultFmt(Var::DataType type) +{ + switch (type) { + case Var::DataType::Number: + return QStringLiteral("%d"); + case Var::DataType::String: + return QStringLiteral("%s"); + default: + Q_UNREACHABLE(); } } -bool Template::Element::isValidFmt(const QString &fmt, Var::DataType type) { - switch(type) { - case Var::DataType::String: return fmt.endsWith(QLatin1Char('s')); - case Var::DataType::Number: return true; // regexp in parser takes care of it - default: return false; +bool Template::Element::isValidFmt(const QString &fmt, Var::DataType type) +{ + switch (type) { + case Var::DataType::String: + return fmt.endsWith(QLatin1Char('s')); + case Var::DataType::Number: + return true; // regexp in parser takes care of it + default: + return false; } } @@ -76,69 +87,76 @@ bool Template::Element::isValidFmt(const QString &fmt, Var::DataType type) { // Template // -Template::Template(const QString &text): _text(text) { - _root.name = QStringLiteral("[root]"); - _root.outer = QStringRef(&_text); - _root.inner = QStringRef(&_text); - _root.parent = nullptr; - _root.line = 1; - _root.column = 1; +Template::Template(const QString &text) + : _text(text) +{ + _root.name = QStringLiteral("[root]"); + _root.outer = QStringRef(&_text); + _root.inner = QStringRef(&_text); + _root.parent = nullptr; + _root.line = 1; + _root.column = 1; } -void Template::parse() { +void Template::parse() +{ _root.children.clear(); _root.outer = QStringRef(&_text); _root.inner = QStringRef(&_text); parseRecursively(_root); -// dbgDumpTree(_root); + // dbgDumpTree(_root); } -QString Template::generate(const Var &data) { +QString Template::generate(const Var &data) +{ QString result; result.reserve(_text.size()); generateRecursively(result, _root, data); return result; } -static inline void warn(const Template::Element &element, const QString &id, const QString &msg) { +static inline void warn(const Template::Element &element, const QString &id, const QString &msg) +{ const QString path = id.isEmpty() ? element.path() : Template::Element(&element, id).path(); qWarning() << QStringLiteral("Warning: %1:%2: %3: %4").arg(element.line).arg(element.column).arg(path, msg); } -static inline void warn(const Template::Element &element, const QString &msg) { +static inline void warn(const Template::Element &element, const QString &msg) +{ warn(element, QString(), msg); } -void Template::executeCommand(Element &element, const Template::Element &childStub, const QStringList &argv) { +void Template::executeCommand(Element &element, const Template::Element &childStub, const QStringList &argv) +{ // Insert content N times - if(argv[0] == QStringLiteral("repeat")) { + if (argv[0] == QStringLiteral("repeat")) { bool ok; unsigned count = argv.value(1).toInt(&ok); - if(!ok || count < 1) { + if (!ok || count < 1) { warn(element, QStringLiteral("!") + argv[0], QStringLiteral("invalid repeat count (%1), assuming 0.").arg(argv[1])); return; } element.children.append(childStub); Template::Element &cmdElement = element.children.last(); - if(!cmdElement.inner.isEmpty()) { + if (!cmdElement.inner.isEmpty()) { // Parse children parseRecursively(cmdElement); // Remember how many children was there before replication int originalChildrenCount = cmdElement.children.size(); // Replicate children - for(unsigned i = 1; i < count; ++i) { - for(int chId = 0; chId < originalChildrenCount; ++chId) { + for (unsigned i = 1; i < count; ++i) { + for (int chId = 0; chId < originalChildrenCount; ++chId) { cmdElement.children.append(cmdElement.children[chId]); } } } - // Set printf-like format (with leading %) applied for strings and numbers - // inside the group - } else if(argv[0] == QStringLiteral("fmt")) { + // Set printf-like format (with leading %) applied for strings and numbers + // inside the group + } else if (argv[0] == QStringLiteral("fmt")) { static const QRegularExpression FMT_RE(QStringLiteral(R":(^%[-0 +#]?(?:[1-9][0-9]*)?\.?[0-9]*[diouxXs]$):")); const auto match = FMT_RE.match(argv.value(1)); QString fmt = QStringLiteral(""); - if(!match.hasMatch()) + if (!match.hasMatch()) warn(element, QStringLiteral("!") + argv[0], QStringLiteral("invalid format (%1), assuming default").arg(argv[1])); else fmt = match.captured(); @@ -150,7 +168,8 @@ void Template::executeCommand(Element &element, const Template::Element &childSt } } -void Template::parseRecursively(Element &element) { +void Template::parseRecursively(Element &element) +{ static const QRegularExpression RE(QStringLiteral(R":((?'comment'«\*(([^:]*):)?.*?(?(-2):\g{-1})\*»)|):" R":(«(?:(?'name'[-_a-zA-Z0-9]*)|(?:!(?'cmd'[-_a-zA-Z0-9]+(?: +(?:[^\\:]+|(?:\\.)+)+)?)))):" R":((?::(?:~[ \t]*\n)?(?'inner'(?:[^«]*?|(?R))*))?(?:\n[ \t]*~)?»):"), @@ -158,21 +177,21 @@ void Template::parseRecursively(Element &element) { static const QRegularExpression CMD_SPLIT_RE(QStringLiteral(R":((?:"((?:(?:\\.)*|[^"]*)*)"|(?:[^\\ "]+|(?:\\.)+)+)):"), QRegularExpression::DotMatchesEverythingOption | QRegularExpression::MultilineOption); static const QRegularExpression UNESCAPE_RE(QStringLiteral(R":(\\(.)):"), - QRegularExpression::DotMatchesEverythingOption | QRegularExpression::MultilineOption); - static const QString nameGroupName = QStringLiteral("name"); - static const QString innerGroupName = QStringLiteral("inner"); - static const QString cmdGroupName = QStringLiteral("cmd"); - static const QString commentGroupName = QStringLiteral("comment"); + QRegularExpression::DotMatchesEverythingOption | QRegularExpression::MultilineOption); + static const QString nameGroupName = QStringLiteral("name"); + static const QString innerGroupName = QStringLiteral("inner"); + static const QString cmdGroupName = QStringLiteral("cmd"); + static const QString commentGroupName = QStringLiteral("comment"); - int posOffset = element.outer.position(); - uint posLine = element.line; + int posOffset = element.outer.position(); + uint posLine = element.line; uint posColumn = element.column; auto matchIter = RE.globalMatch(element.inner); - while(matchIter.hasNext()) { - auto match = matchIter.next(); - auto cmd = match.captured(cmdGroupName); - auto comment = match.captured(commentGroupName); + while (matchIter.hasNext()) { + auto match = matchIter.next(); + auto cmd = match.captured(cmdGroupName); + auto comment = match.captured(commentGroupName); const auto localOuterRef = match.capturedRef(0); const auto localInnerRef = match.capturedRef(innerGroupName); @@ -180,8 +199,8 @@ void Template::parseRecursively(Element &element) { auto outerRef = QStringRef(&_text, localOuterRef.position(), localOuterRef.length()); auto innerRef = QStringRef(&_text, localInnerRef.position(), localInnerRef.length()); - while(posOffset < outerRef.position() && posOffset < _text.size()) { - if(_text[posOffset++] == QLatin1Char('\n')) { + while (posOffset < outerRef.position() && posOffset < _text.size()) { + if (_text[posOffset++] == QLatin1Char('\n')) { ++posLine; posColumn = 1; } else { @@ -189,86 +208,87 @@ void Template::parseRecursively(Element &element) { } } - if(!cmd.isEmpty()) { + if (!cmd.isEmpty()) { QStringList cmdArgv; auto cmdArgIter = CMD_SPLIT_RE.globalMatch(cmd); - while(cmdArgIter.hasNext()) { + while (cmdArgIter.hasNext()) { auto cmdArg = cmdArgIter.next(); cmdArgv += cmdArg.captured(cmdArg.captured(1).isEmpty() ? 0 : 1); cmdArgv.last().replace(UNESCAPE_RE, QStringLiteral("\1")); } Template::Element childStub = Template::Element(&element); - childStub.outer = outerRef; - childStub.name = QLatin1Char('!') + cmd; - childStub.inner = innerRef; - childStub.line = posLine; - childStub.column = posColumn; + childStub.outer = outerRef; + childStub.name = QLatin1Char('!') + cmd; + childStub.inner = innerRef; + childStub.line = posLine; + childStub.column = posColumn; executeCommand(element, childStub, cmdArgv); } else if (!comment.isEmpty()) { element.children.append(Element(&element)); Template::Element &child = element.children.last(); - child.outer = outerRef; - child.name = QString(); - child.inner = QStringRef(); - child.line = posLine; - child.column = posColumn; - child.isComment = true; + child.outer = outerRef; + child.name = QString(); + child.inner = QStringRef(); + child.line = posLine; + child.column = posColumn; + child.isComment = true; } else { element.children.append(Element(&element)); Template::Element &child = element.children.last(); - child.outer = outerRef; - child.name = match.captured(nameGroupName); - child.inner = innerRef; - child.line = posLine; - child.column = posColumn; - if(!child.inner.isEmpty()) + child.outer = outerRef; + child.name = match.captured(nameGroupName); + child.inner = innerRef; + child.line = posLine; + child.column = posColumn; + if (!child.inner.isEmpty()) parseRecursively(child); } } } -int Template::generateRecursively(QString &result, const Template::Element &element, const Var &data, int consumed) { +int Template::generateRecursively(QString &result, const Template::Element &element, const Var &data, int consumed) +{ int consumedDataItems = consumed; - if(!element.children.isEmpty()) { + if (!element.children.isEmpty()) { int totalDataItems; - switch(data.dataType()) { - case Var::DataType::Number: - case Var::DataType::String: - case Var::DataType::Map: - totalDataItems = 1; - break; - case Var::DataType::Vector: - totalDataItems = data.vec.size(); - break; - case Var::DataType::Invalid: - default: - Q_UNREACHABLE(); + switch (data.dataType()) { + case Var::DataType::Number: + case Var::DataType::String: + case Var::DataType::Map: + totalDataItems = 1; + break; + case Var::DataType::Vector: + totalDataItems = data.vec.size(); + break; + case Var::DataType::Invalid: + default: + Q_UNREACHABLE(); } - while(consumedDataItems < totalDataItems) { + while (consumedDataItems < totalDataItems) { int prevChildEndPosition = element.inner.position(); - for(const auto &child: element.children) { + for (const auto &child : element.children) { const int characterCountBetweenChildren = child.outer.position() - prevChildEndPosition; - if(characterCountBetweenChildren > 0) { + if (characterCountBetweenChildren > 0) { // Add text between previous child (or inner beginning) and this child. result += unescape(_text.midRef(prevChildEndPosition, characterCountBetweenChildren)); - } else if(characterCountBetweenChildren < 0) { + } else if (characterCountBetweenChildren < 0) { // Repeated item; they overlap and end1 > start2 result += unescape(element.inner.mid(prevChildEndPosition - element.inner.position())); result += unescape(element.inner.left(child.outer.position() - element.inner.position())); } - switch(data.dataType()) { + switch (data.dataType()) { case Var::DataType::Number: case Var::DataType::String: generateRecursively(result, child, data); consumedDataItems = 1; // Deepest child always consumes number/string break; case Var::DataType::Vector: - if(!data.vec.isEmpty()) { - if(!child.hasName() && !child.isCommand() && consumedDataItems < data.vec.size()) { + if (!data.vec.isEmpty()) { + if (!child.hasName() && !child.isCommand() && consumedDataItems < data.vec.size()) { consumedDataItems += generateRecursively(result, child, data[consumedDataItems]); } else { consumedDataItems += generateRecursively(result, child, data.vec.mid(consumedDataItems)); @@ -278,9 +298,9 @@ int Template::generateRecursively(QString &result, const Template::Element &elem } break; case Var::DataType::Map: - if(!child.hasName()) { + if (!child.hasName()) { consumedDataItems = generateRecursively(result, child, data); - } else if(data.map.contains(child.name)) { + } else if (data.map.contains(child.name)) { generateRecursively(result, child, data.map[child.name]); // Always consume, repeating doesn't change anything consumedDataItems = 1; @@ -296,57 +316,56 @@ int Template::generateRecursively(QString &result, const Template::Element &elem result += unescape(element.inner.mid(prevChildEndPosition - element.inner.position(), -1)); - if(element.isCommand()) { + if (element.isCommand()) { break; } const bool isLast = consumedDataItems >= totalDataItems; - if(!isLast) { + if (!isLast) { // Collapse empty lines between elements int nlNum = 0; - for(int i = 0; i < element.inner.size() / 2; ++i) { - if(element.inner.at(i) == QLatin1Char('\n') && - element.inner.at(i) == element.inner.at(element.inner.size() - i - 1)) + for (int i = 0; i < element.inner.size() / 2; ++i) { + if (element.inner.at(i) == QLatin1Char('\n') && element.inner.at(i) == element.inner.at(element.inner.size() - i - 1)) nlNum++; else break; } - if(nlNum > 0) + if (nlNum > 0) result.chop(nlNum); } } } else if (!element.isComment) { // Handle leaf element - switch(data.dataType()) { - case Var::DataType::Number: { + switch (data.dataType()) { + case Var::DataType::Number: { + const QString fmt = element.findFmt(Var::DataType::Number); + result += QString::asprintf(qUtf8Printable(fmt), data.num); + break; + } + case Var::DataType::String: { + const QString fmt = element.findFmt(Var::DataType::String); + result += QString::asprintf(qUtf8Printable(fmt), qUtf8Printable(data.str)); + break; + } + case Var::DataType::Vector: + if (data.vec.isEmpty()) { + warn(element, QStringLiteral("got empty list.")); + } else if (data.vec.at(0).dataType() == Var::DataType::Number) { const QString fmt = element.findFmt(Var::DataType::Number); result += QString::asprintf(qUtf8Printable(fmt), data.num); - break; - } - case Var::DataType::String: { + } else if (data.vec.at(0).dataType() == Var::DataType::String) { const QString fmt = element.findFmt(Var::DataType::String); result += QString::asprintf(qUtf8Printable(fmt), qUtf8Printable(data.str)); - break; + } else { + warn(element, + QStringLiteral("the list entry data type (%1) is not supported in childrenless elements.").arg(data.vec.at(0).dataTypeAsString())); } - case Var::DataType::Vector: - if(data.vec.isEmpty()) { - warn(element, QStringLiteral("got empty list.")); - } else if(data.vec.at(0).dataType() == Var::DataType::Number) { - const QString fmt = element.findFmt(Var::DataType::Number); - result += QString::asprintf(qUtf8Printable(fmt), data.num); - } else if(data.vec.at(0).dataType() == Var::DataType::String) { - const QString fmt = element.findFmt(Var::DataType::String); - result += QString::asprintf(qUtf8Printable(fmt), qUtf8Printable(data.str)); - } else { - warn(element, QStringLiteral("the list entry data type (%1) is not supported in childrenless elements."). - arg(data.vec.at(0).dataTypeAsString())); - } - break; - case Var::DataType::Map: - warn(element, QStringLiteral("map type is not supported in childrenless elements.")); - break; - case Var::DataType::Invalid: - break; + break; + case Var::DataType::Map: + warn(element, QStringLiteral("map type is not supported in childrenless elements.")); + break; + case Var::DataType::Invalid: + break; } consumedDataItems = 1; } diff --git a/tools/uni2characterwidth/template.h b/tools/uni2characterwidth/template.h index fdc9f7647..846d36b84 100644 --- a/tools/uni2characterwidth/template.h +++ b/tools/uni2characterwidth/template.h @@ -14,12 +14,13 @@ #include // QVariant doesn't offer modification in place. Var does. -class Var { +class Var +{ public: - using Number = qint64; - using String = QString; - using Map = QMap; - using Vector = QVector; + using Number = qint64; + using String = QString; + using Map = QMap; + using Vector = QVector; enum class DataType { Invalid, @@ -29,81 +30,145 @@ public: Map, }; - const QString dataTypeAsString() const { - switch(dataType()) { - case DataType::Invalid: return QStringLiteral("Invalid"); - case DataType::Number: return QStringLiteral("Number"); - case DataType::String: return QStringLiteral("String"); - case DataType::Vector: return QStringLiteral("Vector"); - case DataType::Map: return QStringLiteral("Map"); - default: return QStringLiteral("Unknown?"); + const QString dataTypeAsString() const + { + switch (dataType()) { + case DataType::Invalid: + return QStringLiteral("Invalid"); + case DataType::Number: + return QStringLiteral("Number"); + case DataType::String: + return QStringLiteral("String"); + case DataType::Vector: + return QStringLiteral("Vector"); + case DataType::Map: + return QStringLiteral("Map"); + default: + return QStringLiteral("Unknown?"); } } - Var(): num(0), _dataType(DataType::Invalid) {} - Var(const Var &other) { *this = other; } + Var() + : num(0) + , _dataType(DataType::Invalid) + { + } + Var(const Var &other) + { + *this = other; + } - Var(const Number &newNum): _dataType(DataType::Number) { new(&num) auto(newNum); } - Var(const String &newStr): _dataType(DataType::String) { new(&str) auto(newStr); } - Var(const Vector &newVec): _dataType(DataType::Vector) { new(&vec) auto(newVec); } - Var(const Map &newMap): _dataType(DataType::Map) { new(&map) auto(newMap); } + Var(const Number &newNum) + : _dataType(DataType::Number) + { + new (&num) auto(newNum); + } + Var(const String &newStr) + : _dataType(DataType::String) + { + new (&str) auto(newStr); + } + Var(const Vector &newVec) + : _dataType(DataType::Vector) + { + new (&vec) auto(newVec); + } + Var(const Map &newMap) + : _dataType(DataType::Map) + { + new (&map) auto(newMap); + } // Allow initialization without type name - Var(const char * newStr): _dataType(DataType::String) { new(&str) String(QString::fromUtf8(newStr)); } - Var(std::initializer_list newVec): _dataType(DataType::Vector) { new(&vec) Vector(newVec); } + Var(const char *newStr) + : _dataType(DataType::String) + { + new (&str) String(QString::fromUtf8(newStr)); + } + Var(std::initializer_list newVec) + : _dataType(DataType::Vector) + { + new (&vec) Vector(newVec); + } - ~Var() { - switch(dataType()) { - case DataType::String: str.~String(); break; - case DataType::Vector: vec.~Vector(); break; - case DataType::Map: map.~Map(); break; - default: break; + ~Var() + { + switch (dataType()) { + case DataType::String: + str.~String(); + break; + case DataType::Vector: + vec.~Vector(); + break; + case DataType::Map: + map.~Map(); + break; + default: + break; } } - Var & operator=(const Var &other) { + Var &operator=(const Var &other) + { _dataType = other.dataType(); - switch(other.dataType()) { - case DataType::Number: new(&num) auto(other.num); break; - case DataType::String: new(&str) auto(other.str); break; - case DataType::Vector: new(&vec) auto(other.vec); break; - case DataType::Map: new(&map) auto(other.map); break; - default: break; + switch (other.dataType()) { + case DataType::Number: + new (&num) auto(other.num); + break; + case DataType::String: + new (&str) auto(other.str); + break; + case DataType::Vector: + new (&vec) auto(other.vec); + break; + case DataType::Map: + new (&map) auto(other.map); + break; + default: + break; } return *this; } - Var & operator[](unsigned index) { + Var &operator[](unsigned index) + { Q_ASSERT(_dataType == DataType::Vector); return vec.data()[index]; } - const Var & operator[](unsigned index) const { + const Var &operator[](unsigned index) const + { Q_ASSERT(_dataType == DataType::Vector); return vec.constData()[index]; } - Var & operator[](const String &key) { + Var &operator[](const String &key) + { Q_ASSERT(_dataType == DataType::Map); return map[key]; } - const Var & operator[](const String &key) const { + const Var &operator[](const String &key) const + { Q_ASSERT(_dataType == DataType::Map); return *map.find(key); } - DataType dataType() const { return _dataType; } + DataType dataType() const + { + return _dataType; + } union { - Number num; - String str; - Vector vec; - Map map; + Number num; + String str; + Vector vec; + Map map; }; private: DataType _dataType; }; -class Template { +class Template +{ public: Template(const QString &text); void parse(); @@ -111,34 +176,43 @@ public: struct Element { Element(const Element *parent = nullptr, const QString &name = QString()) - : outer() - , inner() - , name(name) - , fmt() - , line(0) - , column(0) - , isComment(false) - , children() - , parent(parent) {} + : outer() + , inner() + , name(name) + , fmt() + , line(0) + , column(0) + , isComment(false) + , children() + , parent(parent) + { + } Element(const Element &other) - : outer(other.outer) - , inner(other.inner) - , name(other.name) - , fmt(other.fmt) - , line(other.line) - , column(other.column) - , isComment(other.isComment) - , parent(other.parent) { - for(const auto &child: other.children) { + : outer(other.outer) + , inner(other.inner) + , name(other.name) + , fmt(other.fmt) + , line(other.line) + , column(other.column) + , isComment(other.isComment) + , parent(other.parent) + { + for (const auto &child : other.children) { children.append(child); } } const QString findFmt(Var::DataType type) const; QString path() const; - bool isCommand() const { return name.startsWith(QLatin1Char('!')); } - bool hasName() const { return !isCommand() && !name.isEmpty(); } + bool isCommand() const + { + return name.startsWith(QLatin1Char('!')); + } + bool hasName() const + { + return !isCommand() && !name.isEmpty(); + } static const QString defaultFmt(Var::DataType type); static bool isValidFmt(const QString &fmt, Var::DataType type); @@ -153,8 +227,8 @@ public: QList children; const Element *parent; }; -private: +private: void executeCommand(Element &element, const Element &childStub, const QStringList &argv); void parseRecursively(Element &element); int generateRecursively(QString &result, const Element &element, const Var &data, int consumed = 0); diff --git a/tools/uni2characterwidth/uni2characterwidth.cpp b/tools/uni2characterwidth/uni2characterwidth.cpp index e785041aa..54749f6b1 100644 --- a/tools/uni2characterwidth/uni2characterwidth.cpp +++ b/tools/uni2characterwidth/uni2characterwidth.cpp @@ -6,6 +6,7 @@ SPDX-License-Identifier: GPL-2.0-or-later */ +#include "template.h" #include #include #include @@ -17,29 +18,32 @@ #include #include #include -#include "template.h" #include - - static constexpr unsigned int CODE_POINTS_NUM = 0x110000; static constexpr unsigned int LAST_CODE_POINT = CODE_POINTS_NUM - 1; struct UcdEntry { - struct { uint first; uint last; } cp; + struct { + uint first; + uint last; + } cp; QStringList fields; }; -class UcdParserBase { +class UcdParserBase +{ public: - ~UcdParserBase() { + ~UcdParserBase() + { _source->close(); } - bool hasNext() { + bool hasNext() + { bool hadNext = _hasNext; - if(!_nextFetched) { + if (!_nextFetched) { _hasNext = fetchNext(); _nextFetched = true; } @@ -48,19 +52,20 @@ public: protected: UcdParserBase(QIODevice *source, UcdEntry *entry) - : _source(source) - , _nextFetched(false) - , _hasNext(true) - , _lineNo(0) - , _entry(entry) + : _source(source) + , _nextFetched(false) + , _hasNext(true) + , _lineNo(0) + , _entry(entry) { Q_ASSERT(_source); Q_ASSERT(_entry); } - bool fetchNext() { + bool fetchNext() + { Q_ASSERT(_source->isOpen()); - if(!_source->isOpen()) + if (!_source->isOpen()) return false; static const QRegularExpression ENTRY_RE = QRegularExpression(QStringLiteral( @@ -70,58 +75,56 @@ protected: // "udRangeInd" (UnicodeData.txt only) - if present, the line is either first or last line of a range R"#([ \t]*(?[^#;\n]*?(?:, (?First|Last)>)?)[ \t]*(?:;|(?:\#.*)?$))|)#" // Match 2..n: "field" - n-th field - R"#((?:\G(?<=;)[ \t]*(?[^#;\n]*?)[ \t]*(?:;|(?:#.*)?$)))#") - ); + R"#((?:\G(?<=;)[ \t]*(?[^#;\n]*?)[ \t]*(?:;|(?:#.*)?$)))#")); static const QRegularExpression UD_RANGE_IND_RE(QStringLiteral(", (First|Last)")); static const QRegularExpression COMMENT_RE(QStringLiteral("^[ \t]*(#.*)?$")); QString line; bool ok; _entry->fields.clear(); - while(!_source->atEnd()) { + while (!_source->atEnd()) { line = QString::fromUtf8(_source->readLine()); _lineNo++; auto mit = ENTRY_RE.globalMatch(line); - if(!mit.hasNext()) { + if (!mit.hasNext()) { // Do not complain about comments and empty lines - if(!COMMENT_RE.match(line).hasMatch()) + if (!COMMENT_RE.match(line).hasMatch()) qDebug() << QStringLiteral("Line %1: does not match - skipping").arg(_lineNo); continue; } auto match = mit.next(); _entry->cp.first = match.captured(QStringLiteral("cp1")).toUInt(&ok, 16); - if(!ok) { + if (!ok) { qDebug() << QStringLiteral("Line %d Invalid cp1 - skipping").arg(_lineNo); continue; } _entry->cp.last = match.captured(QStringLiteral("cp2")).toUInt(&ok, 16); - if(!ok) { + if (!ok) { _entry->cp.last = _entry->cp.first; } QString field0 = match.captured(QStringLiteral("field0")); - if(field0.isNull()) { + if (field0.isNull()) { qDebug() << QStringLiteral("Line %d: Missing field0 - skipping").arg(_lineNo); continue; } - if(!match.captured(QStringLiteral("udRangeInd")).isNull()) { - if(match.captured(QStringLiteral("udRangeInd")) == QStringLiteral("First")) { + if (!match.captured(QStringLiteral("udRangeInd")).isNull()) { + if (match.captured(QStringLiteral("udRangeInd")) == QStringLiteral("First")) { // Fetch next valid line, as it pairs with the current one to form a range QRegularExpressionMatch nlMatch; int firstLineNo = _lineNo; - while(!_source->atEnd() && !nlMatch.hasMatch()) { + while (!_source->atEnd() && !nlMatch.hasMatch()) { line = QString::fromUtf8(_source->readLine()); _lineNo++; nlMatch = ENTRY_RE.match(line); - if(!nlMatch.hasMatch()) { + if (!nlMatch.hasMatch()) { qDebug() << QStringLiteral("Line %d: does not match - skipping").arg(_lineNo); } } - if(nlMatch.hasMatch()) { + if (nlMatch.hasMatch()) { _entry->cp.last = nlMatch.captured(QStringLiteral("cp1")).toUInt(&ok, 16); - if(!ok) { - qDebug() << QStringLiteral("Line %1-%2: Missing or invalid second cp1 (\"Last\" entry) - skipping") - .arg(firstLineNo).arg(_lineNo); + if (!ok) { + qDebug() << QStringLiteral("Line %1-%2: Missing or invalid second cp1 (\"Last\" entry) - skipping").arg(firstLineNo).arg(_lineNo); continue; } } @@ -130,7 +133,7 @@ protected: } _entry->fields.append(field0); - while(mit.hasNext()) { + while (mit.hasNext()) { _entry->fields.append(mit.next().captured(QStringLiteral("field"))); } @@ -148,15 +151,20 @@ private: UcdEntry *_entry; }; -template -class UcdParser: public UcdParserBase { +template +class UcdParser : public UcdParserBase +{ public: static_assert(std::is_base_of::value, "'EntryType' has to be derived from UcdParser::Entry"); - UcdParser(QIODevice *source): UcdParserBase(source, &_typedEntry) {} + UcdParser(QIODevice *source) + : UcdParserBase(source, &_typedEntry) + { + } - inline const EntryType & next() { - if(!_nextFetched) + inline const EntryType &next() + { + if (!_nextFetched) fetchNext(); _nextFetched = false; return _typedEntry; @@ -166,7 +174,8 @@ private: EntryType _typedEntry; }; -class KIODevice: public QIODevice { +class KIODevice : public QIODevice +{ public: enum Error { NoError, @@ -178,24 +187,27 @@ public: }; KIODevice(const QUrl &url) - : _url(url) - , _job(nullptr) - , _error(NoError) {} + : _url(url) + , _job(nullptr) + , _error(NoError) + { + } - ~KIODevice() { + ~KIODevice() + { close(); } - bool open() { - if(_job) + bool open() + { + if (_job) return false; _job = KIO::storedGet(_url); - QObject::connect(_job, &KIO::StoredTransferJob::result, - _job, [&](KJob *) { - if(_job->isErrorPage()) + QObject::connect(_job, &KIO::StoredTransferJob::result, _job, [&](KJob *) { + if (_job->isErrorPage()) _eventLoop.exit(KIO::ERR_DOES_NOT_EXIST); - else if(_job->error() != KJob::NoError) + else if (_job->error() != KJob::NoError) _eventLoop.exit(_job->error()); else _data = _job->data(); @@ -204,19 +216,29 @@ public: }); _eventLoop.exec(); - switch(_job->error()) { + switch (_job->error()) { case KJob::NoError: _error = NoError; setErrorString(QStringLiteral("")); QIODevice::open(QIODevice::ReadOnly | QIODevice::Unbuffered); break; - case KJob::KilledJobError: _error = TimeoutError; break; - case KIO::ERR_UNKNOWN_HOST: _error = UnknownHostError; break; - case KIO::ERR_DOES_NOT_EXIST: _error = NotFoundError; break; - case KIO::ERR_MALFORMED_URL: _error = MalformedUrlError; break; - default: _error = UnknownError; break; + case KJob::KilledJobError: + _error = TimeoutError; + break; + case KIO::ERR_UNKNOWN_HOST: + _error = UnknownHostError; + break; + case KIO::ERR_DOES_NOT_EXIST: + _error = NotFoundError; + break; + case KIO::ERR_MALFORMED_URL: + _error = MalformedUrlError; + break; + default: + _error = UnknownError; + break; } - if(_error != NoError) { + if (_error != NoError) { setErrorString(QStringLiteral("KIO: ") + _job->errorString()); delete _job; _job = nullptr; @@ -224,12 +246,14 @@ public: } return _error == NoError; } - bool open(OpenMode mode) override { + bool open(OpenMode mode) override + { Q_ASSERT(mode == QIODevice::ReadOnly); return open(); } - void close() override { - if(_job) { + void close() override + { + if (_job) { delete _job; _job = nullptr; _error = NoError; @@ -239,23 +263,34 @@ public: } } - qint64 size() const override { + qint64 size() const override + { return _data.size(); } - int error() const { return _error; } - void unsetError() { _error = NoError; } + int error() const + { + return _error; + } + void unsetError() + { + _error = NoError; + } protected: - qint64 writeData(const char *, qint64) override { return -1; } - qint64 readData(char *data, qint64 maxSize) override { + qint64 writeData(const char *, qint64) override + { + return -1; + } + qint64 readData(char *data, qint64 maxSize) override + { Q_UNUSED(maxSize); Q_ASSERT(_job); Q_ASSERT(_job->error() == NoError); Q_ASSERT(data != nullptr); - if(maxSize == 0 || pos() >= _data.length()) { + if (maxSize == 0 || pos() >= _data.length()) { return 0; - } else if(pos() < _data.length()) { + } else if (pos() < _data.length()) { qint64 bytesToCopy = qMin(maxSize, _data.length() - pos()); memcpy(data, _data.data() + pos(), bytesToCopy); return bytesToCopy; @@ -272,30 +307,44 @@ private: QByteArray _data; }; - - struct CategoryProperty { - enum Flag: uint32_t { + enum Flag : uint32_t { Invalid = 0, - #define CATEGORY_PROPERTY_VALUE(val, sym, intVal) sym = intVal, - #include "properties.h" +#define CATEGORY_PROPERTY_VALUE(val, sym, intVal) sym = intVal, +#include "properties.h" }; - enum Group: uint32_t { - #define CATEGORY_PROPERTY_GROUP(val, sym, intVal) sym = intVal, - #include "properties.h" + enum Group : uint32_t { +#define CATEGORY_PROPERTY_GROUP(val, sym, intVal) sym = intVal, +#include "properties.h" }; - CategoryProperty(uint32_t value = Unassigned): _value(value) {} - CategoryProperty(const QString &string): _value(fromString(string)) {} - operator uint32_t &() { return _value; } - operator const uint32_t &() const { return _value; } - bool isValid() const { return _value != Invalid; } + CategoryProperty(uint32_t value = Unassigned) + : _value(value) + { + } + CategoryProperty(const QString &string) + : _value(fromString(string)) + { + } + operator uint32_t &() + { + return _value; + } + operator const uint32_t &() const + { + return _value; + } + bool isValid() const + { + return _value != Invalid; + } private: - static uint32_t fromString(const QString &string) { + static uint32_t fromString(const QString &string) + { static const QMap map = { - #define CATEGORY_PROPERTY_VALUE(val, sym, intVal) { QStringLiteral(#val), sym }, - #include "properties.h" +#define CATEGORY_PROPERTY_VALUE(val, sym, intVal) {QStringLiteral(#val), sym}, +#include "properties.h" }; return map.contains(string) ? map[string] : uint8_t(Invalid); } @@ -303,23 +352,39 @@ private: }; struct EastAsianWidthProperty { - enum Value: uint8_t { + enum Value : uint8_t { Invalid = 0x80, - #define EAST_ASIAN_WIDTH_PROPERTY_VALUE(val, sym, intVal) sym = intVal, - #include "properties.h" +#define EAST_ASIAN_WIDTH_PROPERTY_VALUE(val, sym, intVal) sym = intVal, +#include "properties.h" }; - EastAsianWidthProperty(uint8_t value = Neutral): _value(value) {} - EastAsianWidthProperty(const QString &string): _value(fromString(string)) {} - operator uint8_t &() { return _value; } - operator const uint8_t &() const { return _value; } - bool isValid() const { return _value != Invalid; } + EastAsianWidthProperty(uint8_t value = Neutral) + : _value(value) + { + } + EastAsianWidthProperty(const QString &string) + : _value(fromString(string)) + { + } + operator uint8_t &() + { + return _value; + } + operator const uint8_t &() const + { + return _value; + } + bool isValid() const + { + return _value != Invalid; + } private: - static uint8_t fromString(const QString &string) { + static uint8_t fromString(const QString &string) + { static const QMap map = { - #define EAST_ASIAN_WIDTH_PROPERTY_VALUE(val, sym, intVal) { QStringLiteral(#val), Value::sym }, - #include "properties.h" +#define EAST_ASIAN_WIDTH_PROPERTY_VALUE(val, sym, intVal) {QStringLiteral(#val), Value::sym}, +#include "properties.h" }; return map.contains(string) ? map[string] : Invalid; } @@ -327,71 +392,113 @@ private: }; struct EmojiProperty { - enum Flag: uint8_t { + enum Flag : uint8_t { Invalid = 0x80, - #define EMOJI_PROPERTY_VALUE(val, sym, intVal) sym = intVal, - #include "properties.h" +#define EMOJI_PROPERTY_VALUE(val, sym, intVal) sym = intVal, +#include "properties.h" }; - EmojiProperty(uint8_t value = None): _value(value) {} - EmojiProperty(const QString &string): _value(fromString(string)) {} - operator uint8_t &() { return _value; } - operator const uint8_t &() const { return _value; } - bool isValid() const { return !(_value & Invalid); } + EmojiProperty(uint8_t value = None) + : _value(value) + { + } + EmojiProperty(const QString &string) + : _value(fromString(string)) + { + } + operator uint8_t &() + { + return _value; + } + operator const uint8_t &() const + { + return _value; + } + bool isValid() const + { + return !(_value & Invalid); + } private: - static uint8_t fromString(const QString &string) { + static uint8_t fromString(const QString &string) + { static const QMap map = { - #define EMOJI_PROPERTY_VALUE(val, sym, intVal) { QStringLiteral(#val), sym }, - #include "properties.h" +#define EMOJI_PROPERTY_VALUE(val, sym, intVal) {QStringLiteral(#val), sym}, +#include "properties.h" }; return map.contains(string) ? map[string] : uint8_t(Invalid); } uint8_t _value; }; - - struct CharacterWidth { - enum Width: int8_t { - Invalid = SCHAR_MIN, - _VALID_START = -3, - Ambiguous = -2, - NonPrintable = -1, + enum Width : int8_t { + Invalid = SCHAR_MIN, + _VALID_START = -3, + Ambiguous = -2, + NonPrintable = -1, // 0 // 1 - Unassigned = 1, + Unassigned = 1, // 2 - _VALID_END = 3, + _VALID_END = 3, }; - CharacterWidth(const CharacterWidth &other): _width(other._width) {} - CharacterWidth(int8_t width = Invalid): _width(width) {} - CharacterWidth & operator =(const CharacterWidth &other) { _width = other._width; return *this; } - int operator =(const int8_t width) { _width = width; return _width; } - int width() const { return _width; } - operator int() const { return width(); } + CharacterWidth(const CharacterWidth &other) + : _width(other._width) + { + } + CharacterWidth(int8_t width = Invalid) + : _width(width) + { + } + CharacterWidth &operator=(const CharacterWidth &other) + { + _width = other._width; + return *this; + } + int operator=(const int8_t width) + { + _width = width; + return _width; + } + int width() const + { + return _width; + } + operator int() const + { + return width(); + } - const QString toString() const { - switch(_width) { - case Ambiguous: return QStringLiteral("Ambiguous"); - case NonPrintable: return QStringLiteral("NonPrintable"); - case 0: return QStringLiteral("0"); - case 1: return QStringLiteral("1"); - case 2: return QStringLiteral("2"); + const QString toString() const + { + switch (_width) { + case Ambiguous: + return QStringLiteral("Ambiguous"); + case NonPrintable: + return QStringLiteral("NonPrintable"); + case 0: + return QStringLiteral("0"); + case 1: + return QStringLiteral("1"); + case 2: + return QStringLiteral("2"); default: - case Invalid: return QStringLiteral("Invalid"); + case Invalid: + return QStringLiteral("Invalid"); } } - bool isValid() const { return (_width > _VALID_START && _width < _VALID_END); }; + bool isValid() const + { + return (_width > _VALID_START && _width < _VALID_END); + }; private: int8_t _width; }; - - struct CharacterProperties { CategoryProperty category; EastAsianWidthProperty eastAsianWidth; @@ -401,35 +508,43 @@ struct CharacterProperties { uint8_t widthFromPropsRule; }; - - -struct UnicodeDataEntry: public UcdEntry { +struct UnicodeDataEntry : public UcdEntry { enum FieldId { - NameId = 0, - CategoryId = 1, + NameId = 0, + CategoryId = 1, }; - CategoryProperty category() const { return CategoryProperty(this->fields.value(CategoryId)); } + CategoryProperty category() const + { + return CategoryProperty(this->fields.value(CategoryId)); + } }; -struct EastAsianWidthEntry: public UcdEntry { +struct EastAsianWidthEntry : public UcdEntry { enum FieldId { WidthId = 0, }; - EastAsianWidthProperty eastAsianWidth() const { return EastAsianWidthProperty(this->fields.value(WidthId)); } + EastAsianWidthProperty eastAsianWidth() const + { + return EastAsianWidthProperty(this->fields.value(WidthId)); + } }; -struct EmojiDataEntry: public UcdEntry { +struct EmojiDataEntry : public UcdEntry { enum FieldId { EmojiId = 0, }; - EmojiProperty emoji() const { return EmojiProperty(this->fields.value(EmojiId)); } + EmojiProperty emoji() const + { + return EmojiProperty(this->fields.value(EmojiId)); + } }; -struct GenericWidthEntry: public UcdEntry { +struct GenericWidthEntry : public UcdEntry { enum FieldId { WidthId = 0, }; - CharacterWidth width() const { + CharacterWidth width() const + { bool ok; CharacterWidth w = this->fields.value(WidthId).toInt(&ok, 10); return (ok && w.isValid()) ? w : CharacterWidth::Invalid; @@ -437,20 +552,24 @@ struct GenericWidthEntry: public UcdEntry { }; struct WidthsRange { - struct { uint first; uint last; } cp; + struct { + uint first; + uint last; + } cp; CharacterWidth width; }; -QVector rangesFromWidths(const QVector &widths, QPair ucsRange = {0, CODE_POINTS_NUM}) { +QVector rangesFromWidths(const QVector &widths, QPair ucsRange = {0, CODE_POINTS_NUM}) +{ QVector ranges; - if(ucsRange.second >= CODE_POINTS_NUM) + if (ucsRange.second >= CODE_POINTS_NUM) ucsRange.second = widths.size() - 1; uint first = ucsRange.first; - for(uint cp = first + 1; cp <= uint(ucsRange.second); ++cp) { - if(widths[first] != widths[cp]) { - ranges.append({{first, cp-1}, widths[cp-1]}); + for (uint cp = first + 1; cp <= uint(ucsRange.second); ++cp) { + if (widths[first] != widths[cp]) { + ranges.append({{first, cp - 1}, widths[cp - 1]}); first = cp; } } @@ -479,25 +598,26 @@ QVector rangesFromWidths(const QVector &widths, QPa // First range is always without change. Last range (A) can be dropped // (it always contains everything). Search should be done in order: D, C, B (A). // For simplicity the function returns all ranges, including first and last. -QMap>> mergedRangesFromWidths(const QVector &widths, const QVector widthsSortOrder, - QPair ucsRange = {0, CODE_POINTS_NUM}) { - if(ucsRange.second >= CODE_POINTS_NUM) +QMap>> +mergedRangesFromWidths(const QVector &widths, const QVector widthsSortOrder, QPair ucsRange = {0, CODE_POINTS_NUM}) +{ + if (ucsRange.second >= CODE_POINTS_NUM) ucsRange.second = widths.size() - 1; QVector ranges = rangesFromWidths(widths, ucsRange); QMap>> mergedRanges; - int cmwi; // Currently Merged Width Index - int sri = -1; // Start Range Index (for current width) - int cri; // Current Range Index + int cmwi; // Currently Merged Width Index + int sri = -1; // Start Range Index (for current width) + int cri; // Current Range Index // First width ranges are without change. Last one has one range spanning everything, so we can skip this - for(cmwi = 1; cmwi < widthsSortOrder.size() - 1; ++cmwi) { - const CharacterWidth &cmw = widthsSortOrder[cmwi]; // Currently Merged Width - for(cri = 0; cri < ranges.size(); ++cri) { - WidthsRange &cr = ranges[cri]; // Current Range - if(cr.width == cmw) { + for (cmwi = 1; cmwi < widthsSortOrder.size() - 1; ++cmwi) { + const CharacterWidth &cmw = widthsSortOrder[cmwi]; // Currently Merged Width + for (cri = 0; cri < ranges.size(); ++cri) { + WidthsRange &cr = ranges[cri]; // Current Range + if (cr.width == cmw) { // Range is suitable for merge - if(sri < 0) { + if (sri < 0) { // First one, just remember it sri = cri; } else { @@ -507,9 +627,9 @@ QMap>> mergedRangesFromWidths(const QV } } else { // Current range has another width - can we continue merging? - if(sri >= 0) { + if (sri >= 0) { const int crwi = widthsSortOrder.indexOf(cr.width); // Current Range Width Index - if(!(crwi < cmwi && crwi >= 0)) { + if (!(crwi < cmwi && crwi >= 0)) { // current range is not above currently merged width - stop merging sri = -1; } @@ -518,8 +638,8 @@ QMap>> mergedRangesFromWidths(const QV } } - for(const auto &range: qAsConst(ranges)) { - if(range.width.isValid() && range.width != widthsSortOrder.last()) + for (const auto &range : qAsConst(ranges)) { + if (range.width.isValid() && range.width != widthsSortOrder.last()) mergedRanges[range.width].append({range.cp.first, range.cp.last}); } mergedRanges[widthsSortOrder.last()].append({ucsRange.first, ucsRange.second}); @@ -527,24 +647,23 @@ QMap>> mergedRangesFromWidths(const QV return mergedRanges; } -namespace generators { +namespace generators +{ +using GeneratorFunc = bool (*)(QTextStream &, const QVector &, const QVector &, const QMap &); -using GeneratorFunc = bool (*)(QTextStream &, const QVector &, - const QVector &, const QMap &); - -bool code(QTextStream &out, const QVector &props, const QVector &widths, - const QMap &args) { +bool code(QTextStream &out, const QVector &props, const QVector &widths, const QMap &args) +{ static constexpr int DIRECT_LUT_SIZE = 256; Q_UNUSED(props); QTextStream eout(stderr, QIODevice::WriteOnly); - if(args.value(QStringLiteral("param")).isEmpty()) { + if (args.value(QStringLiteral("param")).isEmpty()) { eout << QStringLiteral("Template file not specified.") << Qt::endl << Qt::endl; return false; } QFile templateFile(args.value(QStringLiteral("param"))); - if(!templateFile.open(QIODevice::ReadOnly)) { + if (!templateFile.open(QIODevice::ReadOnly)) { eout << QStringLiteral("Could not open file ") << templateFile.fileName() << ": " << templateFile.errorString(); exit(1); } @@ -553,62 +672,61 @@ bool code(QTextStream &out, const QVector &props, const QVe templateFile.close(); Var::Map data = { - {QStringLiteral("gen-file-warning"), QStringLiteral("THIS IS A GENERATED FILE. DO NOT EDIT.")}, - {QStringLiteral("cmdline"), args.value(QStringLiteral("cmdline"))}, - {QStringLiteral("direct-lut"), Var::Vector(DIRECT_LUT_SIZE)}, - {QStringLiteral("direct-lut-size"), DIRECT_LUT_SIZE}, - {QStringLiteral("ranges-luts"), Var::Vector()}, - {QStringLiteral("ranges-lut-list"), Var::Vector()}, + {QStringLiteral("gen-file-warning"), QStringLiteral("THIS IS A GENERATED FILE. DO NOT EDIT.")}, + {QStringLiteral("cmdline"), args.value(QStringLiteral("cmdline"))}, + {QStringLiteral("direct-lut"), Var::Vector(DIRECT_LUT_SIZE)}, + {QStringLiteral("direct-lut-size"), DIRECT_LUT_SIZE}, + {QStringLiteral("ranges-luts"), Var::Vector()}, + {QStringLiteral("ranges-lut-list"), Var::Vector()}, {QStringLiteral("ranges-lut-list-size"), 0}, }; // Fill direct-lut with widths of 0x00-0xFF - for(unsigned i = 0; i < DIRECT_LUT_SIZE; ++i) { + for (unsigned i = 0; i < DIRECT_LUT_SIZE; ++i) { Q_ASSERT(widths[i].isValid()); data[QStringLiteral("direct-lut")].vec[i] = int(widths[i]); } static const QVector widthsSortOrder = {CharacterWidth::NonPrintable, 2, CharacterWidth::Ambiguous, 0, 1}; - const QMap>> mergedRanges - = mergedRangesFromWidths(widths, widthsSortOrder, {DIRECT_LUT_SIZE, CODE_POINTS_NUM}); + const QMap>> mergedRanges = mergedRangesFromWidths(widths, widthsSortOrder, {DIRECT_LUT_SIZE, CODE_POINTS_NUM}); // Find last non-empty ranges lut int lastWidthId = 0; - for(int wi = widthsSortOrder.size() - 1; wi > 0; --wi) { - if(mergedRanges.contains(widthsSortOrder[wi])) { + for (int wi = widthsSortOrder.size() - 1; wi > 0; --wi) { + if (mergedRanges.contains(widthsSortOrder[wi])) { lastWidthId = wi; break; } } // Create ranges-luts for all widths except last non-empty one and empty ones - for(int wi = 0; lastWidthId != 0 && wi < lastWidthId; ++wi) { + for (int wi = 0; lastWidthId != 0 && wi < lastWidthId; ++wi) { const CharacterWidth width = widthsSortOrder[wi]; auto currentMergedRangesIt = mergedRanges.find(width); - if(currentMergedRangesIt == mergedRanges.end() || currentMergedRangesIt.value().isEmpty()) + if (currentMergedRangesIt == mergedRanges.end() || currentMergedRangesIt.value().isEmpty()) continue; const int size = mergedRanges[width].size(); const QString name = QString(QStringLiteral("LUT_%1")).arg(width.toString().toUpper()); - data[QStringLiteral("ranges-luts")].vec.append(Var::Map { - {QStringLiteral("name"), name}, - {QStringLiteral("ranges"), Var::Vector()}, - {QStringLiteral("size"), size}, + data[QStringLiteral("ranges-luts")].vec.append(Var::Map{ + {QStringLiteral("name"), name}, + {QStringLiteral("ranges"), Var::Vector()}, + {QStringLiteral("size"), size}, }); - data[QStringLiteral("ranges-lut-list")].vec.append(Var::Map { - {QStringLiteral("width"), int(width)}, - {QStringLiteral("name"), name}, - {QStringLiteral("size"), size}, + data[QStringLiteral("ranges-lut-list")].vec.append(Var::Map{ + {QStringLiteral("width"), int(width)}, + {QStringLiteral("name"), name}, + {QStringLiteral("size"), size}, }); auto ¤tLut = data[QStringLiteral("ranges-luts")].vec.last()[QStringLiteral("ranges")].vec; - for(const auto &range: *currentMergedRangesIt) { + for (const auto &range : *currentMergedRangesIt) { Q_ASSERT(range.first <= LAST_CODE_POINT); Q_ASSERT(range.second <= LAST_CODE_POINT); - currentLut.append(Var(Var::Map {{QStringLiteral("first"), range.first}, {QStringLiteral("last"), range.second}})); + currentLut.append(Var(Var::Map{{QStringLiteral("first"), range.first}, {QStringLiteral("last"), range.second}})); } } - data[QStringLiteral("ranges-lut-list")].vec.append(Var::Map { - {QStringLiteral("width"), widthsSortOrder[lastWidthId].width()}, - {QStringLiteral("name"), QStringLiteral("nullptr")}, - {QStringLiteral("size"), 1}, + data[QStringLiteral("ranges-lut-list")].vec.append(Var::Map{ + {QStringLiteral("width"), widthsSortOrder[lastWidthId].width()}, + {QStringLiteral("name"), QStringLiteral("nullptr")}, + {QStringLiteral("size"), 1}, }); data[QStringLiteral("ranges-lut-list-size")] = mergedRanges.size(); @@ -619,26 +737,26 @@ bool code(QTextStream &out, const QVector &props, const QVe return true; } -bool list(QTextStream &out, const QVector &props, const QVector &widths, - const QMap &args) { +bool list(QTextStream &out, const QVector &props, const QVector &widths, const QMap &args) +{ Q_UNUSED(props); out << QStringLiteral("# generated with: ") << args.value(QStringLiteral("cmdline")) << QStringLiteral("\n"); - for(uint cp = 1; cp <= LAST_CODE_POINT; ++cp) { + for (uint cp = 1; cp <= LAST_CODE_POINT; ++cp) { out << QString::asprintf("%06X ; %2d\n", cp, int(widths[cp])); } return true; } -bool ranges(QTextStream &out, const QVector &props, const QVector &widths, - const QMap &args) { +bool ranges(QTextStream &out, const QVector &props, const QVector &widths, const QMap &args) +{ Q_UNUSED(props); const auto ranges = rangesFromWidths(widths); out << QStringLiteral("# generated with: ") << args.value(QStringLiteral("cmdline")) << QStringLiteral("\n"); - for(const WidthsRange &range: ranges) { - if(range.cp.first != range.cp.last) + for (const WidthsRange &range : ranges) { + if (range.cp.first != range.cp.last) out << QString::asprintf("%06X..%06X ; %2d\n", range.cp.first, range.cp.last, int(range.width)); else out << QString::asprintf("%06X ; %2d\n", range.cp.first, int(range.width)); @@ -647,19 +765,19 @@ bool ranges(QTextStream &out, const QVector &props, const Q return true; } -bool compactRanges(QTextStream &out, const QVector &props, const QVector &widths, - const QMap &args) { +bool compactRanges(QTextStream &out, const QVector &props, const QVector &widths, const QMap &args) +{ Q_UNUSED(props); static const QVector widthsSortOrder = {CharacterWidth::NonPrintable, 2, CharacterWidth::Ambiguous, 0, 1}; const auto mergedRanges = mergedRangesFromWidths(widths, widthsSortOrder); out << QStringLiteral("# generated with: ") << args.value(QStringLiteral("cmdline")) << QStringLiteral("\n"); - for(const int width: qAsConst(widthsSortOrder)) { + for (const int width : qAsConst(widthsSortOrder)) { const auto currentMergedRangesIt = mergedRanges.find(width); - if(currentMergedRangesIt == mergedRanges.end() || currentMergedRangesIt.value().isEmpty()) + if (currentMergedRangesIt == mergedRanges.end() || currentMergedRangesIt.value().isEmpty()) continue; - for(const auto &range: currentMergedRangesIt.value()) { - if(range.first != range.second) + for (const auto &range : currentMergedRangesIt.value()) { + if (range.first != range.second) out << QString::asprintf("%06X..%06X ; %2d\n", range.first, range.second, int(width)); else out << QString::asprintf("%06X ; %2d\n", range.first, int(width)); @@ -669,40 +787,45 @@ bool compactRanges(QTextStream &out, const QVector &props, return true; } -bool details(QTextStream &out, const QVector &props, const QVector &widths, - const QMap &args) { +bool details(QTextStream &out, const QVector &props, const QVector &widths, const QMap &args) +{ out.setFieldAlignment(QTextStream::AlignLeft); out << QStringLiteral("# generated with: ") << args.value(QStringLiteral("cmdline")) << QStringLiteral("\n"); - out << QString::asprintf("#%-5s ; %-4s ; %-8s ; %-3s ; %-2s ; %-4s ; %-4s\n", - "CP", "Wdth", "Cat", "EAW", "EM", "CstW", "Rule"); + out << QString::asprintf("#%-5s ; %-4s ; %-8s ; %-3s ; %-2s ; %-4s ; %-4s\n", "CP", "Wdth", "Cat", "EAW", "EM", "CstW", "Rule"); QMap widthStats; - for(uint cp = 0; cp <= LAST_CODE_POINT; ++cp) { - out << QString::asprintf("%06X ; %4d ; %08X ; %02X ; %02X ; %4d ; %d\n", cp, - int8_t(widths[cp]), uint32_t(props[cp].category), uint8_t(props[cp].eastAsianWidth), - uint8_t(props[cp].emoji), int8_t(props[cp].customWidth), props[cp].widthFromPropsRule); - if(!widthStats.contains(widths[cp])) + for (uint cp = 0; cp <= LAST_CODE_POINT; ++cp) { + out << QString::asprintf("%06X ; %4d ; %08X ; %02X ; %02X ; %4d ; %d\n", + cp, + int8_t(widths[cp]), + uint32_t(props[cp].category), + uint8_t(props[cp].eastAsianWidth), + uint8_t(props[cp].emoji), + int8_t(props[cp].customWidth), + props[cp].widthFromPropsRule); + if (!widthStats.contains(widths[cp])) widthStats.insert(widths[cp], 0); widthStats[widths[cp]]++; } QMap rangesStats; const auto ranges = rangesFromWidths(widths); - for(const auto &range: ranges) { - if(!rangesStats.contains(range.width)) + for (const auto &range : ranges) { + if (!rangesStats.contains(range.width)) rangesStats.insert(range.width, 0); rangesStats[range.width]++; } out << QStringLiteral("# STATS") << Qt::endl; out << QStringLiteral("#") << Qt::endl; out << QStringLiteral("# Characters count for each width:") << Qt::endl; - for(auto wi = widthStats.constBegin(); wi != widthStats.constEnd(); ++wi) { + for (auto wi = widthStats.constBegin(); wi != widthStats.constEnd(); ++wi) { out << QString::asprintf("# %2d: %7d\n", int(wi.key()), widthStats[wi.key()]); } out << QStringLiteral("#") << Qt::endl; out << QStringLiteral("# Ranges count for each width:") << Qt::endl; int howmany = 0; - for(auto wi = rangesStats.constBegin(); wi != rangesStats.constEnd(); ++wi) { - if(howmany >= 20) break; + for (auto wi = rangesStats.constBegin(); wi != rangesStats.constEnd(); ++wi) { + if (howmany >= 20) + break; howmany++; out << QString::asprintf("# %2d: %7d\n", int(wi.key()), rangesStats[wi.key()]); } @@ -711,46 +834,48 @@ bool details(QTextStream &out, const QVector &props, const } } // namespace generators - - -template -static void processInputFiles(QVector &props, const QStringList &files, const QString &fileTypeName, - void (*cb)(CharacterProperties &prop, const EntryType &entry)) { +template +static void processInputFiles(QVector &props, + const QStringList &files, + const QString &fileTypeName, + void (*cb)(CharacterProperties &prop, const EntryType &entry)) +{ static const QRegularExpression PROTOCOL_RE(QStringLiteral(R"#(^[a-z]+://)#")); - for(const QString &fileName: files) { + for (const QString &fileName : files) { qInfo().noquote() << QStringLiteral("Parsing as %1: %2").arg(fileTypeName).arg(fileName); QSharedPointer source = nullptr; - if(PROTOCOL_RE.match(fileName).hasMatch()) { + if (PROTOCOL_RE.match(fileName).hasMatch()) { source.reset(new KIODevice(QUrl(fileName))); } else { source.reset(new QFile(fileName)); } - if(!source->open(QIODevice::ReadOnly)) { + if (!source->open(QIODevice::ReadOnly)) { qCritical() << QStringLiteral("Could not open %1: %2").arg(fileName).arg(source->errorString()); exit(1); } UcdParser p(source.data()); - while(p.hasNext()) { + while (p.hasNext()) { const auto &e = p.next(); - for(uint cp = e.cp.first; cp <= e.cp.last; ++cp) { + for (uint cp = e.cp.first; cp <= e.cp.last; ++cp) { cb(props[cp], e); } } } } -static const QString escapeCmdline(const QStringList &args) { +static const QString escapeCmdline(const QStringList &args) +{ static QString cmdline = QString(); - if(!cmdline.isEmpty()) + if (!cmdline.isEmpty()) return cmdline; QTextStream stream(&cmdline, QIODevice::WriteOnly); // basename for command name stream << QFileInfo(args[0]).baseName(); - for(auto it = args.begin() + 1; it != args.end(); ++it) { - if(!it->startsWith(QLatin1Char('-'))) + for (auto it = args.begin() + 1; it != args.end(); ++it) { + if (!it->startsWith(QLatin1Char('-'))) stream << QStringLiteral(" \"") << QString(*it).replace(QRegularExpression(QStringLiteral(R"(["`$\\])")), QStringLiteral(R"(\\\1)")) << '"'; else stream << ' ' << *it; @@ -760,8 +885,8 @@ static const QString escapeCmdline(const QStringList &args) { } enum ConvertOptions { - AmbiguousWidthOpt = 0, - EmojiOpt = 1, + AmbiguousWidthOpt = 0, + EmojiOpt = 1, }; // Character width assignment @@ -783,155 +908,153 @@ enum ConvertOptions { // (decomposed Hangul, emoji with modifiers, etc) with different widths, // but interactive terminal programs (at least vim, zsh, everything based // on glibc's wcwidth) would see their width as it is implemented now. -static inline CharacterWidth widthFromProps(const CharacterProperties &props, uint cp, const QMap &convertOpts) { +static inline CharacterWidth widthFromProps(const CharacterProperties &props, uint cp, const QMap &convertOpts) +{ CharacterWidth cw; auto &widthFromPropsRule = const_cast(props.widthFromPropsRule); - if(props.customWidth.isValid()) { + if (props.customWidth.isValid()) { widthFromPropsRule = 1; cw = props.customWidth; - } else if((CategoryProperty::Control | CategoryProperty::Surrogate) & props.category) { + } else if ((CategoryProperty::Control | CategoryProperty::Surrogate) & props.category) { widthFromPropsRule = 2; cw = CharacterWidth::NonPrintable; - } else if(convertOpts[EmojiOpt] & props.emoji && !(EmojiProperty::EmojiComponent & props.emoji)) { + } else if (convertOpts[EmojiOpt] & props.emoji && !(EmojiProperty::EmojiComponent & props.emoji)) { widthFromPropsRule = 3; cw = 2; - } else if((CategoryProperty::NonspacingMark | CategoryProperty::EnclosingMark | CategoryProperty::Format) & props.category) { + } else if ((CategoryProperty::NonspacingMark | CategoryProperty::EnclosingMark | CategoryProperty::Format) & props.category) { widthFromPropsRule = 4; cw = 0; - } else if((EastAsianWidthProperty::Wide | EastAsianWidthProperty::Fullwidth) & props.eastAsianWidth) { + } else if ((EastAsianWidthProperty::Wide | EastAsianWidthProperty::Fullwidth) & props.eastAsianWidth) { widthFromPropsRule = 5; cw = 2; - } else if((EastAsianWidthProperty::Halfwidth | EastAsianWidthProperty::Neutral | EastAsianWidthProperty::Narrow) & props.eastAsianWidth) { + } else if ((EastAsianWidthProperty::Halfwidth | EastAsianWidthProperty::Neutral | EastAsianWidthProperty::Narrow) & props.eastAsianWidth) { widthFromPropsRule = 6; cw = 1; - } else if((CategoryProperty::Unassigned | CategoryProperty::PrivateUse) & props.category) { + } else if ((CategoryProperty::Unassigned | CategoryProperty::PrivateUse) & props.category) { widthFromPropsRule = 7; cw = CharacterWidth::Unassigned; - } else if((EastAsianWidthProperty::Ambiguous) & props.eastAsianWidth) { + } else if ((EastAsianWidthProperty::Ambiguous)&props.eastAsianWidth) { widthFromPropsRule = 8; cw = convertOpts[AmbiguousWidthOpt]; - } else if(!props.category.isValid()) { + } else if (!props.category.isValid()) { widthFromPropsRule = 9; - qWarning() << QStringLiteral("Code point U+%1 has invalid category - this should not happen. Assuming \"unassigned\"") - .arg(cp, 4, 16, QLatin1Char('0')); + qWarning() << QStringLiteral("Code point U+%1 has invalid category - this should not happen. Assuming \"unassigned\"").arg(cp, 4, 16, QLatin1Char('0')); cw = CharacterWidth::Unassigned; } else { widthFromPropsRule = 10; - qWarning() << QStringLiteral("Code point U+%1 not classified - this should not happen. Assuming non-printable character") - .arg(cp, 4, 16, QLatin1Char('0')); + qWarning() + << QStringLiteral("Code point U+%1 not classified - this should not happen. Assuming non-printable character").arg(cp, 4, 16, QLatin1Char('0')); cw = CharacterWidth::NonPrintable; } return cw; } -int main(int argc, char *argv[]) { +int main(int argc, char *argv[]) +{ static const QMap GENERATOR_FUNCS_MAP = { - {QStringLiteral("code"), generators::code}, - {QStringLiteral("compact-ranges"), generators::compactRanges}, - {QStringLiteral("ranges"), generators::ranges}, - {QStringLiteral("list"), generators::list}, - {QStringLiteral("details"), generators::details}, - {QStringLiteral("dummy"), [](QTextStream &, const QVector &, const QVector &, - const QMap &)->bool {return true;}}, + {QStringLiteral("code"), generators::code}, + {QStringLiteral("compact-ranges"), generators::compactRanges}, + {QStringLiteral("ranges"), generators::ranges}, + {QStringLiteral("list"), generators::list}, + {QStringLiteral("details"), generators::details}, + {QStringLiteral("dummy"), + [](QTextStream &, const QVector &, const QVector &, const QMap &) -> bool { + return true; + }}, }; qSetMessagePattern(QStringLiteral("%{message}")); QCoreApplication app(argc, argv); QCommandLineParser parser; - parser.setApplicationDescription( - QStringLiteral("\nUCD files to characters widths converter.\n") - ); + parser.setApplicationDescription(QStringLiteral("\nUCD files to characters widths converter.\n")); parser.addHelpOption(); parser.addOptions({ - {{QStringLiteral("U"), QStringLiteral("unicode-data")}, - QStringLiteral("Path or URL to UnicodeData.txt."), - QStringLiteral("URL|file")}, - {{QStringLiteral("A"), QStringLiteral("east-asian-width")}, - QStringLiteral("Path or URL to EastAsianWidth.txt."), - QStringLiteral("URL|file")}, - {{QStringLiteral("E"), QStringLiteral("emoji-data")}, - QStringLiteral("Path or URL to emoji-data.txt."), - QStringLiteral("URL|file")}, + {{QStringLiteral("U"), QStringLiteral("unicode-data")}, QStringLiteral("Path or URL to UnicodeData.txt."), QStringLiteral("URL|file")}, + {{QStringLiteral("A"), QStringLiteral("east-asian-width")}, QStringLiteral("Path or URL to EastAsianWidth.txt."), QStringLiteral("URL|file")}, + {{QStringLiteral("E"), QStringLiteral("emoji-data")}, QStringLiteral("Path or URL to emoji-data.txt."), QStringLiteral("URL|file")}, {{QStringLiteral("W"), QStringLiteral("generic-width")}, - QStringLiteral("Path or URL to generic file with width data. Accepts output from compact-ranges, ranges, list and details generator."), - QStringLiteral("URL|file")}, + QStringLiteral("Path or URL to generic file with width data. Accepts output from compact-ranges, ranges, list and details generator."), + QStringLiteral("URL|file")}, {QStringLiteral("ambiguous-width"), - QStringLiteral("Ambiguous characters width."), - QStringLiteral("separate|1|2"), QString(QStringLiteral("%1")).arg(CharacterWidth::Ambiguous)}, + QStringLiteral("Ambiguous characters width."), + QStringLiteral("separate|1|2"), + QString(QStringLiteral("%1")).arg(CharacterWidth::Ambiguous)}, {QStringLiteral("emoji"), - QStringLiteral("Which emoji emoji subset is treated as emoji."), - QStringLiteral("all|presentation"), QStringLiteral("presentation")}, + QStringLiteral("Which emoji emoji subset is treated as emoji."), + QStringLiteral("all|presentation"), + QStringLiteral("presentation")}, {{QStringLiteral("g"), QStringLiteral("generator")}, - QStringLiteral("Output generator (use \"-\" to list available generators). The code generator requires path to a template file."), - QStringLiteral("generator[:template]"), QStringLiteral("details")}, + QStringLiteral("Output generator (use \"-\" to list available generators). The code generator requires path to a template file."), + QStringLiteral("generator[:template]"), + QStringLiteral("details")}, }); parser.addPositionalArgument(QStringLiteral("output"), QStringLiteral("Output file (leave empty for stdout).")); parser.process(app); - const QStringList unicodeDataFiles = parser.values(QStringLiteral("unicode-data")); - const QStringList eastAsianWidthFiles = parser.values(QStringLiteral("east-asian-width")); - const QStringList emojiDataFiles = parser.values(QStringLiteral("emoji-data")); - const QStringList genericWidthFiles = parser.values(QStringLiteral("generic-width")); - const QString ambiguousWidthStr = parser.value(QStringLiteral("ambiguous-width")); - const QString emojiStr = parser.value(QStringLiteral("emoji")); - const QString generator = parser.value(QStringLiteral("generator")); - const QString outputFileName = parser.positionalArguments().value(0); + const QStringList unicodeDataFiles = parser.values(QStringLiteral("unicode-data")); + const QStringList eastAsianWidthFiles = parser.values(QStringLiteral("east-asian-width")); + const QStringList emojiDataFiles = parser.values(QStringLiteral("emoji-data")); + const QStringList genericWidthFiles = parser.values(QStringLiteral("generic-width")); + const QString ambiguousWidthStr = parser.value(QStringLiteral("ambiguous-width")); + const QString emojiStr = parser.value(QStringLiteral("emoji")); + const QString generator = parser.value(QStringLiteral("generator")); + const QString outputFileName = parser.positionalArguments().value(0); QTextStream eout(stderr, QIODevice::WriteOnly); - if(unicodeDataFiles.isEmpty() && eastAsianWidthFiles.isEmpty() && emojiDataFiles.isEmpty() && genericWidthFiles.isEmpty()) { + if (unicodeDataFiles.isEmpty() && eastAsianWidthFiles.isEmpty() && emojiDataFiles.isEmpty() && genericWidthFiles.isEmpty()) { eout << QStringLiteral("Input files not specified.") << Qt::endl << Qt::endl; parser.showHelp(1); } static QMap convertOpts = { {AmbiguousWidthOpt, CharacterWidth::Ambiguous}, - {EmojiOpt, EmojiProperty::EmojiPresentation}, + {EmojiOpt, EmojiProperty::EmojiPresentation}, }; - if(emojiStr == QStringLiteral("presentation")) + if (emojiStr == QStringLiteral("presentation")) convertOpts[EmojiOpt] = EmojiProperty::EmojiPresentation; - else if(emojiStr == QStringLiteral("all")) + else if (emojiStr == QStringLiteral("all")) convertOpts[EmojiOpt] = EmojiProperty::Emoji; else { convertOpts[EmojiOpt] = EmojiProperty::EmojiPresentation; qWarning() << QStringLiteral("invalid emoji option value: %1. Assuming \"presentation\".").arg(emojiStr); } - if(ambiguousWidthStr == QStringLiteral("separate")) + if (ambiguousWidthStr == QStringLiteral("separate")) convertOpts[AmbiguousWidthOpt] = CharacterWidth::Ambiguous; - else if(ambiguousWidthStr == QStringLiteral("1")) + else if (ambiguousWidthStr == QStringLiteral("1")) convertOpts[AmbiguousWidthOpt] = 1; - else if(ambiguousWidthStr == QStringLiteral("2")) + else if (ambiguousWidthStr == QStringLiteral("2")) convertOpts[AmbiguousWidthOpt] = 2; else { convertOpts[AmbiguousWidthOpt] = CharacterWidth::Ambiguous; qWarning() << QStringLiteral("Invalid ambiguous-width option value: %1. Assuming \"separate\".").arg(emojiStr); } - const int sepPos = generator.indexOf(QLatin1Char(':')); - const auto generatorName = generator.left(sepPos); - const auto generatorParam = sepPos >= 0 ? generator.mid(sepPos + 1) : QString(); + const int sepPos = generator.indexOf(QLatin1Char(':')); + const auto generatorName = generator.left(sepPos); + const auto generatorParam = sepPos >= 0 ? generator.mid(sepPos + 1) : QString(); - if(!GENERATOR_FUNCS_MAP.contains(generatorName)) { + if (!GENERATOR_FUNCS_MAP.contains(generatorName)) { int status = 0; - if(generatorName != QStringLiteral("-")) { + if (generatorName != QStringLiteral("-")) { status = 1; eout << QStringLiteral("Invalid output generator. Available generators:") << Qt::endl; } - for(auto it = GENERATOR_FUNCS_MAP.constBegin(); it != GENERATOR_FUNCS_MAP.constEnd(); ++it) { + for (auto it = GENERATOR_FUNCS_MAP.constBegin(); it != GENERATOR_FUNCS_MAP.constEnd(); ++it) { eout << it.key() << Qt::endl; } exit(status); @@ -939,9 +1062,9 @@ int main(int argc, char *argv[]) { auto generatorFunc = GENERATOR_FUNCS_MAP[generatorName]; QFile outFile; - if(!outputFileName.isEmpty()) { + if (!outputFileName.isEmpty()) { outFile.setFileName(outputFileName); - if(!outFile.open(QIODevice::WriteOnly)) { + if (!outFile.open(QIODevice::WriteOnly)) { eout << QStringLiteral("Could not open file ") << outputFileName << QStringLiteral(": ") << outFile.errorString() << Qt::endl; exit(1); } @@ -952,26 +1075,35 @@ int main(int argc, char *argv[]) { QVector props(CODE_POINTS_NUM); - processInputFiles( - props, unicodeDataFiles, QStringLiteral("UnicodeData.txt"), - [](CharacterProperties &prop, const UnicodeDataEntry &entry) { prop.category = entry.category(); }); + processInputFiles(props, + unicodeDataFiles, + QStringLiteral("UnicodeData.txt"), + [](CharacterProperties &prop, const UnicodeDataEntry &entry) { + prop.category = entry.category(); + }); - processInputFiles( - props, eastAsianWidthFiles, QStringLiteral("EastAsianWidth.txt"), - [](CharacterProperties &prop, const EastAsianWidthEntry &entry) { prop.eastAsianWidth = entry.eastAsianWidth(); }); + processInputFiles(props, + eastAsianWidthFiles, + QStringLiteral("EastAsianWidth.txt"), + [](CharacterProperties &prop, const EastAsianWidthEntry &entry) { + prop.eastAsianWidth = entry.eastAsianWidth(); + }); - processInputFiles( - props, emojiDataFiles, QStringLiteral("emoji-data.txt"), - [](CharacterProperties &prop, const EmojiDataEntry &entry) { prop.emoji |= entry.emoji(); }); + processInputFiles(props, emojiDataFiles, QStringLiteral("emoji-data.txt"), [](CharacterProperties &prop, const EmojiDataEntry &entry) { + prop.emoji |= entry.emoji(); + }); - processInputFiles( - props, genericWidthFiles, QStringLiteral("generic width data"), - [](CharacterProperties &prop, const GenericWidthEntry &entry) { prop.customWidth = entry.width(); }); + processInputFiles(props, + genericWidthFiles, + QStringLiteral("generic width data"), + [](CharacterProperties &prop, const GenericWidthEntry &entry) { + prop.customWidth = entry.width(); + }); qInfo() << "Generating character width data"; QVector widths(CODE_POINTS_NUM); widths[0] = 0; // NULL character always has width 0 - for(uint cp = 1; cp <= LAST_CODE_POINT; ++cp) { + for (uint cp = 1; cp <= LAST_CODE_POINT; ++cp) { widths[cp] = widthFromProps(props[cp], cp, convertOpts); } @@ -982,7 +1114,7 @@ int main(int argc, char *argv[]) { }; qInfo() << "Generating output"; - if(!generatorFunc(out, props, widths, generatorArgs)) { + if (!generatorFunc(out, props, widths, generatorArgs)) { parser.showHelp(1); }