diff --git a/desktop/konsoleui.rc b/desktop/konsoleui.rc index 1dd4f696..32f1321e 100644 --- a/desktop/konsoleui.rc +++ b/desktop/konsoleui.rc @@ -1,47 +1,48 @@ - + File Edit View Split View + Settings Help diff --git a/src/Application.cpp b/src/Application.cpp index ec2da4cc..8732d105 100644 --- a/src/Application.cpp +++ b/src/Application.cpp @@ -1,605 +1,605 @@ /* Copyright 2006-2008 by Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ // Own #include "Application.h" // Qt #include #include #include #include #include #include // KDE #include #include #include // Konsole #include "SessionManager.h" #include "ProfileManager.h" #include "MainWindow.h" #include "Session.h" #include "ShellCommand.h" #include "KonsoleSettings.h" #include "ViewManager.h" #include "SessionController.h" #include "WindowSystemInfo.h" +#include "ViewContainer.h" +#include "TerminalDisplay.h" using namespace Konsole; Application::Application(QSharedPointer parser, const QStringList &customCommand) : _backgroundInstance(nullptr), m_parser(parser), m_customCommand(customCommand) { } void Application::populateCommandLineParser(QCommandLineParser *parser) { auto options = QVector { { { QStringLiteral("profile") }, i18nc("@info:shell", "Name of profile to use for new Konsole instance"), QStringLiteral("name") }, { { 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") } }; foreach(const auto& option, options) { parser->addOption(option); } 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. // -T is technically meant to set a title, that is not really meaningful // for Konsole as we have multiple user-facing options controlling // 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")); titleOption.setHidden(true); parser->addOption(titleOption); } QStringList Application::getCustomCommand(QStringList &args) { int i = args.indexOf(QStringLiteral("-e")); QStringList customCommand; if ((0 < i) && (i < (args.size() - 1))) { // -e was specified with at least one extra argument // if -e was specified without arguments, QCommandLineParser will deal // with that args.removeAt(i); while (args.size() > i) { customCommand << args.takeAt(i); } } return customCommand; } Application::~Application() { SessionManager::instance()->closeAllSessions(); ProfileManager::instance()->saveSettings(); } MainWindow *Application::newMainWindow() { WindowSystemInfo::HAVE_TRANSPARENCY = !m_parser->isSet(QStringLiteral("notransparency")); auto window = new MainWindow(); connect(window, &Konsole::MainWindow::newWindowRequest, this, &Konsole::Application::createWindow); - connect(window, &Konsole::MainWindow::viewDetached, this, &Konsole::Application::detachView); + connect(window, &Konsole::MainWindow::terminalsDetached, this, &Konsole::Application::detachTerminals); return window; } void Application::createWindow(const Profile::Ptr &profile, const QString &directory) { MainWindow *window = newMainWindow(); - ViewManager *viewManager = window->viewManager(); - window->createSession(viewManager->activeContainer(), profile, directory); + window->createSession(profile, directory); finalizeNewMainWindow(window); } -void Application::detachView(Session *session) +void Application::detachTerminals(ViewSplitter *splitter,const QHash& sessionsMap) { MainWindow *currentWindow = qobject_cast(sender()); MainWindow *window = newMainWindow(); ViewManager *manager = window->viewManager(); - manager->createView(manager->activeContainer(), session); + foreach(TerminalDisplay* terminal, splitter->findChildren()) { + manager->attachView(terminal, sessionsMap[terminal]); + } + manager->activeContainer()->addSplitter(splitter); - // Since user is dragging and dropping, move dnd window to where - // the user has the cursor (correct multiple monitor setups). - window->move(QCursor::pos()); - window->resize(currentWindow->geometry().width(), currentWindow->geometry().height()); window->show(); + window->resize(currentWindow->width(), currentWindow->height()); + window->move(QCursor::pos()); } int Application::newInstance() { // handle session management // returns from processWindowArgs(args, createdNewMainWindow) // if a new window was created bool createdNewMainWindow = false; // check for arguments to print help or other information to the // terminal, quit if such an argument was found if (processHelpArgs()) { return 0; } // create a new window or use an existing one MainWindow *window = processWindowArgs(createdNewMainWindow); if (m_parser->isSet(QStringLiteral("tabs-from-file"))) { // create new session(s) as described in file if (!processTabsFromFileArgs(window)) { return 0; } } // select profile to use Profile::Ptr baseProfile = processProfileSelectArgs(); // process various command-line options which cause a property of the // selected profile to be changed Profile::Ptr newProfile = processProfileChangeArgs(baseProfile); // create new session - ViewManager *viewManager = window->viewManager(); - Session *session = window->createSession(viewManager->activeContainer(), newProfile, QString()); + Session *session = window->createSession(newProfile, QString()); if (m_parser->isSet(QStringLiteral("noclose"))) { session->setAutoClose(false); } // 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); } else { // Qt constrains top-level windows which have not been manually // resized (via QWidget::resize()) to a maximum of 2/3rds of the // screen size. // // This means that the terminal display might not get the width/ // height it asks for. To work around this, the widget must be // manually resized to its sizeHint(). // // This problem only affects the first time the application is run. // run. After that KMainWindow will have manually resized the // window to its saved size at this point (so the Qt::WA_Resized // attribute will be set) // If not restoring size from last time or only adding new tab, // resize window to chosen profile size (see Bug:345403) if (createdNewMainWindow) { finalizeNewMainWindow(window); } else { window->show(); } } return 1; } /* Documentation for tab file: * * ;; is the token separator * # at the beginning of line results in line being ignored. * supported tokens: title, command, profile and workdir * * Note that the title is static and the tab will close when the * command is complete (do not use --noclose). You can start new tabs. * * Example below will create 6 tabs as listed and a 7th default tab title: This is the title;; command: ssh localhost title: This is the title;; command: ssh localhost;; profile: Shell title: Top this!;; command: top title: mc this!;; command: mc;; workdir: /tmp #this line is comment command: ssh localhost profile: Shell */ bool Application::processTabsFromFileArgs(MainWindow *window) { // Open tab configuration file 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(); return false; } unsigned int sessions = 0; while (!tabsFile.atEnd()) { QString lineString(QString::fromUtf8(tabsFile.readLine()).trimmed()); if ((lineString.isEmpty()) || (lineString[0] == QLatin1Char('#'))) { continue; } QHash lineTokens; QStringList lineParts = lineString.split(QStringLiteral(";;"), QString::SkipEmptyParts); for (int i = 0; i < lineParts.size(); ++i) { QString key = lineParts.at(i).section(QLatin1Char(':'), 0, 0).trimmed().toLower(); QString value = lineParts.at(i).section(QLatin1Char(':'), 1, -1).trimmed(); lineTokens[key] = value; } // should contain at least one of 'command' and 'profile' if (lineTokens.contains(QStringLiteral("command")) || lineTokens.contains(QStringLiteral("profile"))) { createTabFromArgs(window, lineTokens); sessions++; } else { qWarning() << "Each line should contain at least one of 'command' and 'profile'."; } } tabsFile.close(); if (sessions < 1) { qWarning() << "No valid lines found in " << tabsFileName.toLocal8Bit().data(); return false; } return true; } void Application::createTabFromArgs(MainWindow *window, const QHash &tokens) { const QString &title = tokens[QStringLiteral("title")]; const QString &command = tokens[QStringLiteral("command")]; const QString &profile = tokens[QStringLiteral("profile")]; const QString &workdir = tokens[QStringLiteral("workdir")]; Profile::Ptr baseProfile; if (!profile.isEmpty()) { baseProfile = ProfileManager::instance()->loadProfile(profile); } if (!baseProfile) { // fallback to default profile baseProfile = ProfileManager::instance()->defaultProfile(); } Profile::Ptr newProfile = Profile::Ptr(new Profile(baseProfile)); newProfile->setHidden(true); // FIXME: the method of determining whether to use newProfile does not // scale well when we support more fields in the future bool shouldUseNewProfile = false; if (!command.isEmpty()) { newProfile->setProperty(Profile::Command, command); newProfile->setProperty(Profile::Arguments, command.split(QLatin1Char(' '))); shouldUseNewProfile = true; } if (!title.isEmpty()) { newProfile->setProperty(Profile::LocalTabTitleFormat, title); newProfile->setProperty(Profile::RemoteTabTitleFormat, title); shouldUseNewProfile = true; } if (m_parser->isSet(QStringLiteral("workdir"))) { newProfile->setProperty(Profile::Directory, m_parser->value(QStringLiteral("workdir"))); shouldUseNewProfile = true; } if (!workdir.isEmpty()) { newProfile->setProperty(Profile::Directory, workdir); shouldUseNewProfile = true; } // Create the new session Profile::Ptr theProfile = shouldUseNewProfile ? newProfile : baseProfile; - ViewManager *viewManager = window->viewManager(); - Session *session = window->createSession(viewManager->activeContainer(), theProfile, QString()); + Session *session = window->createSession(theProfile, QString()); if (m_parser->isSet(QStringLiteral("noclose"))) { session->setAutoClose(false); } if (!window->testAttribute(Qt::WA_Resized)) { window->resize(window->sizeHint()); } // FIXME: this ugly hack here is to make the session start running, so that // its tab title is displayed as expected. // // This is another side effect of the commit fixing BKO 176902. window->show(); window->hide(); } // Creates a new Konsole window. // If --new-tab is given, use existing window. MainWindow *Application::processWindowArgs(bool &createdNewMainWindow) { MainWindow *window = nullptr; if (m_parser->isSet(QStringLiteral("new-tab"))) { QListIterator iter(QApplication::topLevelWidgets()); iter.toBack(); while (iter.hasPrevious()) { window = qobject_cast(iter.previous()); if (window != nullptr) { break; } } } if (window == nullptr) { createdNewMainWindow = true; window = newMainWindow(); // override default menubar visibility if (m_parser->isSet(QStringLiteral("show-menubar"))) { window->setMenuBarInitialVisibility(true); } if (m_parser->isSet(QStringLiteral("hide-menubar"))) { window->setMenuBarInitialVisibility(false); } if (m_parser->isSet(QStringLiteral("fullscreen"))) { window->viewFullScreen(true); } if (m_parser->isSet(QStringLiteral("show-tabbar"))) { window->viewManager()->setNavigationVisibility(ViewManager::AlwaysShowNavigation); } else if (m_parser->isSet(QStringLiteral("hide-tabbar"))) { window->viewManager()->setNavigationVisibility(ViewManager::AlwaysHideNavigation); } } return window; } // Loads a profile. // If --profile is given, loads profile . // If --fallback-profile is given, loads profile FALLBACK/. // Else loads the default profile. 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"))); if (profile) { return profile; } } else if (m_parser->isSet(QStringLiteral("fallback-profile"))) { Profile::Ptr profile = ProfileManager::instance()->loadProfile(QStringLiteral("FALLBACK/")); if (profile) { return profile; } } return defaultProfile; } bool Application::processHelpArgs() { if (m_parser->isSet(QStringLiteral("list-profiles"))) { listAvailableProfiles(); return true; } else if (m_parser->isSet(QStringLiteral("list-profile-properties"))) { listProfilePropertyInfo(); return true; } return false; } void Application::listAvailableProfiles() { QStringList paths = ProfileManager::instance()->availableProfilePaths(); foreach (const QString &path, paths) { QFileInfo info(path); printf("%s\n", info.completeBaseName().toLocal8Bit().constData()); } } void Application::listProfilePropertyInfo() { Profile::Ptr tempProfile = ProfileManager::instance()->defaultProfile(); const QStringList names = tempProfile->propertiesInfoList(); foreach (const QString &name, names) { printf("%s\n", name.toLocal8Bit().constData()); } } Profile::Ptr Application::processProfileChangeArgs(Profile::Ptr baseProfile) { bool shouldUseNewProfile = false; Profile::Ptr newProfile = Profile::Ptr(new Profile(baseProfile)); newProfile->setHidden(true); // change the initial working directory if (m_parser->isSet(QStringLiteral("workdir"))) { newProfile->setProperty(Profile::Directory, m_parser->value(QStringLiteral("workdir"))); shouldUseNewProfile = true; } // temporary changes to profile options specified on the command line const QStringList profileProperties = m_parser->values(QStringLiteral("p")); foreach (const QString &value, profileProperties) { ProfileCommandParser parser; QHashIterator iter(parser.parse(value)); while (iter.hasNext()) { iter.next(); newProfile->setProperty(iter.key(), iter.value()); } shouldUseNewProfile = true; } // run a custom command if (!m_customCommand.isEmpty()) { // Example: konsole -e man ls QString commandExec = m_customCommand[0]; QStringList commandArguments(m_customCommand); if ((m_customCommand.size() == 1) && (QStandardPaths::findExecutable(commandExec).isEmpty())) { // Example: konsole -e "man ls" ShellCommand shellCommand(commandExec); commandExec = shellCommand.command(); commandArguments = shellCommand.arguments(); } if (commandExec.startsWith(QLatin1String("./"))) { commandExec = QDir::currentPath() + commandExec.mid(1); } newProfile->setProperty(Profile::Command, commandExec); newProfile->setProperty(Profile::Arguments, commandArguments); shouldUseNewProfile = true; } if (shouldUseNewProfile) { return newProfile; } else { return baseProfile; } } void Application::startBackgroundMode(MainWindow *window) { if (_backgroundInstance != nullptr) { return; } 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)); connect(action, &QAction::triggered, this, &Application::toggleBackgroundInstance); _backgroundInstance = window; } void Application::toggleBackgroundInstance() { Q_ASSERT(_backgroundInstance); if (!_backgroundInstance->isVisible()) { _backgroundInstance->show(); // ensure that the active terminal display has the focus. Without // this, an odd problem occurred where the focus widget would change // each time the background instance was shown _backgroundInstance->setFocus(); } else { _backgroundInstance->hide(); } } void Application::slotActivateRequested(QStringList args, const QString & /*workingDir*/) { // QCommandLineParser expects the first argument to be the executable name // In the current version it just strips it away args.prepend(qApp->applicationFilePath()); m_customCommand = getCustomCommand(args); // We can't re-use QCommandLineParser instances, it preserves earlier parsed values auto parser = new QCommandLineParser; populateCommandLineParser(parser); parser->parse(args); m_parser.reset(parser); newInstance(); } void Application::finalizeNewMainWindow(MainWindow *window) { if (!KonsoleSettings::saveGeometryOnExit()) { window->resize(window->sizeHint()); } window->show(); } diff --git a/src/Application.h b/src/Application.h index c702ca5a..98d44dd2 100644 --- a/src/Application.h +++ b/src/Application.h @@ -1,97 +1,98 @@ /* Copyright 2007-2008 by Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef APPLICATION_H #define APPLICATION_H // Qt #include // Konsole #include "Profile.h" +#include "ViewSplitter.h" namespace Konsole { class MainWindow; class Session; /** * The Konsole Application. * * The application consists of one or more main windows and a set of * factories to create new sessions and views. * * To create a new main window with a default terminal session, call * the newInstance(). Empty main windows can be created using newMainWindow(). * * The factory used to create new terminal sessions can be retrieved using * the sessionManager() accessor. */ class Application : public QObject { Q_OBJECT public: /** Constructs a new Konsole application. */ explicit Application(QSharedPointer parser, const QStringList &customCommand); static void populateCommandLineParser(QCommandLineParser *parser); static QStringList getCustomCommand(QStringList &args); ~Application() Q_DECL_OVERRIDE; /** Creates a new main window and opens a default terminal session */ int newInstance(); /** * Creates a new, empty main window and connects to its newSessionRequest() * and newWindowRequest() signals to trigger creation of new sessions or * windows when then they are emitted. */ MainWindow *newMainWindow(); private Q_SLOTS: void createWindow(const Profile::Ptr &profile, const QString &directory); - void detachView(Session *session); + void detachTerminals(ViewSplitter *splitter, const QHash& sessionsMap); void toggleBackgroundInstance(); public Q_SLOTS: void slotActivateRequested(QStringList args, const QString &workingDir); private: Q_DISABLE_COPY(Application) void listAvailableProfiles(); void listProfilePropertyInfo(); void startBackgroundMode(MainWindow *window); bool processHelpArgs(); MainWindow *processWindowArgs(bool &createdNewMainWindow); Profile::Ptr processProfileSelectArgs(); Profile::Ptr processProfileChangeArgs(Profile::Ptr baseProfile); bool processTabsFromFileArgs(MainWindow *window); void createTabFromArgs(MainWindow *window, const QHash &); void finalizeNewMainWindow(MainWindow *window); MainWindow *_backgroundInstance; QSharedPointer m_parser; QStringList m_customCommand; }; } #endif // APPLICATION_H diff --git a/src/DetachableTabBar.cpp b/src/DetachableTabBar.cpp index bdbc07b8..92e00855 100644 --- a/src/DetachableTabBar.cpp +++ b/src/DetachableTabBar.cpp @@ -1,139 +1,115 @@ /* Copyright 2018 by Tomaz Canabrava This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "DetachableTabBar.h" #include "KonsoleSettings.h" #include "ViewContainer.h" #include #include namespace Konsole { DetachableTabBar::DetachableTabBar(QWidget *parent) : QTabBar(parent), dragType(DragType::NONE), _originalCursor(cursor()), tabId(-1) {} -bool DetachableTabBar::droppedContainerIsNotThis(const QPoint& currentPos) const -{ - for(const auto dropWidget : _containers) { - if (dropWidget->rect().contains(dropWidget->mapFromGlobal(currentPos))) { - if (dropWidget != parent()) { - return true; - } - } - } - return false; -} - void DetachableTabBar::middleMouseButtonClickAt(const QPoint& pos) { tabId = tabAt(pos); if (tabId != -1) { emit closeTab(tabId); } } void DetachableTabBar::mousePressEvent(QMouseEvent *event) { QTabBar::mousePressEvent(event); _containers = window()->findChildren(); } void DetachableTabBar::mouseMoveEvent(QMouseEvent *event) { QTabBar::mouseMoveEvent(event); auto widgetAtPos = qApp->topLevelAt(event->globalPos()); if (widgetAtPos != nullptr) { if (window() == widgetAtPos->window()) { - if (droppedContainerIsNotThis(event->globalPos())) { - if (dragType != DragType::WINDOW) { - dragType = DragType::WINDOW; - setCursor(QCursor(Qt::DragMoveCursor)); - } - } else { - if (dragType != DragType::NONE) { - dragType = DragType::NONE; - setCursor(_originalCursor); - } + if (dragType != DragType::NONE) { + dragType = DragType::NONE; + setCursor(_originalCursor); } } else { if (dragType != DragType::WINDOW) { dragType = DragType::WINDOW; setCursor(QCursor(Qt::DragMoveCursor)); } } } else if (!contentsRect().adjusted(-30,-30,30,30).contains(event->pos())) { // Don't let it detach the last tab. if (count() == 1) { return; } if (dragType != DragType::OUTSIDE) { dragType = DragType::OUTSIDE; setCursor(QCursor(Qt::DragCopyCursor)); } } } void DetachableTabBar::mouseReleaseEvent(QMouseEvent *event) { QTabBar::mouseReleaseEvent(event); switch(event->button()) { case Qt::MiddleButton : if (KonsoleSettings::closeTabOnMiddleMouseButton()) { middleMouseButtonClickAt(event->pos()); } tabId = tabAt(event->pos()); if (tabId == -1) { emit newTabRequest(); } break; case Qt::LeftButton: _containers = window()->findChildren(); break; default: break; } setCursor(_originalCursor); if (contentsRect().adjusted(-30,-30,30,30).contains(event->pos())) { return; } auto widgetAtPos = qApp->topLevelAt(event->globalPos()); if (widgetAtPos == nullptr) { if (count() != 1) { emit detachTab(currentIndex()); } } else if (window() != widgetAtPos->window()) { - // splits have a tendency to break, forbid to detach if split and it's the last tab. if (_containers.size() == 1 || count() > 1) { emit moveTabToWindow(currentIndex(), widgetAtPos); } - } else if (droppedContainerIsNotThis(event->globalPos())){ - if (count() != 1) { - emit moveTabToWindow(currentIndex(), widgetAtPos); - } } } } diff --git a/src/DetachableTabBar.h b/src/DetachableTabBar.h index 77288786..a8ff7abc 100644 --- a/src/DetachableTabBar.h +++ b/src/DetachableTabBar.h @@ -1,54 +1,53 @@ /* Copyright 2018 by Tomaz Canabrava This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef DETACHABLETABBAR_H #define DETACHABLETABBAR_H #include #include namespace Konsole { class TabbedViewContainer; class DetachableTabBar : public QTabBar { Q_OBJECT public: enum class DragType : unsigned char {NONE, OUTSIDE, WINDOW}; explicit DetachableTabBar(QWidget *parent = nullptr); Q_SIGNALS: void detachTab(int index); void moveTabToWindow(int tabIndex, QWidget *otherWindow); void closeTab(int index); void newTabRequest(); protected: void middleMouseButtonClickAt(const QPoint& pos); void mousePressEvent(QMouseEvent *event) override; void mouseMoveEvent(QMouseEvent*event) override; void mouseReleaseEvent(QMouseEvent *event) override; - bool droppedContainerIsNotThis(const QPoint& currentPos) const; private: DragType dragType; QCursor _originalCursor; QList _containers; int tabId; }; } #endif diff --git a/src/MainWindow.cpp b/src/MainWindow.cpp index 485a7357..4d1d3ae0 100644 --- a/src/MainWindow.cpp +++ b/src/MainWindow.cpp @@ -1,893 +1,893 @@ /* Copyright 2006-2008 by Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ // Own #include "MainWindow.h" // Qt #include #include // KDE #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // Konsole #include "BookmarkHandler.h" #include "SessionController.h" #include "ProfileList.h" #include "Session.h" #include "ViewContainer.h" #include "ViewManager.h" #include "SessionManager.h" #include "ProfileManager.h" #include "KonsoleSettings.h" #include "WindowSystemInfo.h" #include "TerminalDisplay.h" #include "settings/FileLocationSettings.h" #include "settings/GeneralSettings.h" #include "settings/ProfileSettings.h" #include "settings/TabBarSettings.h" using namespace Konsole; MainWindow::MainWindow() : KXmlGuiWindow(), _viewManager(nullptr), _bookmarkHandler(nullptr), _toggleMenuBarAction(nullptr), _newTabMenuAction(nullptr), _pluggedController(nullptr), _menuBarInitialVisibility(true), _menuBarInitialVisibilityApplied(false) { if (!KonsoleSettings::saveGeometryOnExit()) { // If we are not using the global Konsole save geometry on exit, // remove all Height and Width from [MainWindow] from konsolerc // Each screen resolution will have entries (Width 1280=619) KSharedConfigPtr konsoleConfig = KSharedConfig::openConfig(QStringLiteral("konsolerc")); KConfigGroup group = konsoleConfig->group("MainWindow"); QMap configEntries = group.entryMap(); QMapIterator i(configEntries); while (i.hasNext()) { i.next(); if (i.key().startsWith(QLatin1String("Width")) || i.key().startsWith(QLatin1String("Height"))) { group.deleteEntry(i.key()); } } } updateUseTransparency(); // create actions for menus setupActions(); // create view manager _viewManager = new ViewManager(this, actionCollection()); connect(_viewManager, &Konsole::ViewManager::empty, this, &Konsole::MainWindow::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::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::viewDetached, this, - &Konsole::MainWindow::viewDetached); + connect(_viewManager, &Konsole::ViewManager::terminalsDetached, this, + &Konsole::MainWindow::terminalsDetached); setCentralWidget(_viewManager->widget()); // disable automatically generated accelerators in top-level // menu items - to avoid conflicting with Alt+[Letter] shortcuts // in terminal applications KAcceleratorManager::setNoAccel(menuBar()); // create menus createGUI(); // remember the original menu accelerators for later use rememberMenuAccelerators(); // replace standard shortcuts which cannot be used in a terminal // emulator (as they are reserved for use by terminal applications) correctStandardShortcuts(); setProfileList(new ProfileList(false, this)); // this must come at the end applyKonsoleSettings(); connect(KonsoleSettings::self(), &Konsole::KonsoleSettings::configChanged, this, &Konsole::MainWindow::applyKonsoleSettings); } void MainWindow::updateUseTransparency() { if (!WindowSystemInfo::HAVE_TRANSPARENCY) { return; } bool useTranslucency = KWindowSystem::compositingActive(); setAttribute(Qt::WA_TranslucentBackground, useTranslucency); setAttribute(Qt::WA_NoSystemBackground, false); WindowSystemInfo::HAVE_TRANSPARENCY = useTranslucency; } void MainWindow::rememberMenuAccelerators() { foreach (QAction *menuItem, menuBar()->actions()) { QString itemText = menuItem->text(); menuItem->setData(itemText); } } // remove accelerators for standard menu items (eg. &File, &View, &Edit) // etc. which are defined in kdelibs/kdeui/xmlgui/ui_standards.rc, again, // to avoid conflicting with Alt+[Letter] terminal shortcuts // // TODO - Modify XMLGUI so that it allows the text for standard actions // defined in ui_standards.rc to be re-defined in the local application // XMLGUI file (konsoleui.rc in this case) - the text for standard items // can then be redefined there to exclude the standard accelerators void MainWindow::removeMenuAccelerators() { foreach (QAction *menuItem, menuBar()->actions()) { menuItem->setText(menuItem->text().replace(QLatin1Char('&'), QString())); } } void MainWindow::restoreMenuAccelerators() { foreach (QAction *menuItem, menuBar()->actions()) { QString itemText = menuItem->data().toString(); menuItem->setText(itemText); } } void MainWindow::correctStandardShortcuts() { // replace F1 shortcut for help contents QAction *helpAction = actionCollection()->action(QStringLiteral("help_contents")); if (helpAction != nullptr) { actionCollection()->setDefaultShortcut(helpAction, QKeySequence()); } // replace Ctrl+B shortcut for bookmarks only if user hasn't already // changed the shortcut; however, if the user changed it to Ctrl+B // this will still get changed to Ctrl+Shift+B QAction *bookmarkAction = actionCollection()->action(QStringLiteral("add_bookmark")); if ((bookmarkAction != nullptr) && bookmarkAction->shortcut() == QKeySequence(Konsole::ACCEL + Qt::Key_B)) { actionCollection()->setDefaultShortcut(bookmarkAction, Konsole::ACCEL + Qt::SHIFT + Qt::Key_B); } } ViewManager *MainWindow::viewManager() const { return _viewManager; } 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); if (auto view = controller->view()) { view->removeEventFilter(this); } // KXmlGuiFactory::removeClient() will try to access actions associated // with the controller internally, which may not be valid after the controller // itself is no longer valid (after the associated session and or view have // been destroyed) if (controller->isValid()) { guiFactory()->removeClient(controller); } + + if (_pluggedController == controller) { + _pluggedController = nullptr; + } } void MainWindow::activeViewChanged(SessionController *controller) { if (!SessionManager::instance()->sessionProfile(controller->session())) { return; } // 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); if (!_pluggedController.isNull()) { disconnectController(_pluggedController); } Q_ASSERT(controller); _pluggedController = controller; _pluggedController->view()->installEventFilter(this); 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); controller->setShowMenuAction(_toggleMenuBarAction); guiFactory()->addClient(controller); // update session title to match newly activated session activeViewTitleChanged(controller); // Update window icon to newly activated session's icon updateWindowIcon(); } void MainWindow::activeViewTitleChanged(ViewProperties *properties) { Q_UNUSED(properties); updateWindowCaption(); } void MainWindow::updateWindowCaption() { if (_pluggedController.isNull()) { return; } const QString &title = _pluggedController->title(); const QString &userTitle = _pluggedController->userTitle(); // use tab title as caption by default QString caption = title; // use window title as caption when this setting is enabled // if the userTitle is empty, use a blank space (using an empty string // removes the dash — before the application name; leaving the dash // looks better) if (KonsoleSettings::showWindowTitleOnTitleBar()) { !userTitle.isEmpty() ? caption = userTitle : caption = QStringLiteral(" "); } setCaption(caption); } void MainWindow::updateWindowIcon() { if ((!_pluggedController.isNull()) && !_pluggedController->icon().isNull()) { setWindowIcon(_pluggedController->icon()); } } void MainWindow::setupActions() { KActionCollection *collection = actionCollection(); // File Menu _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); - connect(_newTabMenuAction, &KActionMenu::triggered, - this, [this] { newTab(_viewManager->activeContainer());}); + connect(_newTabMenuAction, &KActionMenu::triggered, this, &MainWindow::newTab); collection->addAction(QStringLiteral("new-tab"), _newTabMenuAction); collection->setShortcutsConfigurable(_newTabMenuAction, true); 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()); menuAction->setAutoRepeat(false); connect(menuAction, &QAction::triggered, this, &Konsole::MainWindow::cloneTab); menuAction = collection->addAction(QStringLiteral("new-window")); menuAction->setIcon(QIcon::fromTheme(QStringLiteral("window-new"))); menuAction->setText(i18nc("@action:inmenu", "New &Window")); collection->setDefaultShortcut(menuAction, Konsole::ACCEL + Qt::SHIFT + Qt::Key_N); menuAction->setAutoRepeat(false); connect(menuAction, &QAction::triggered, this, &Konsole::MainWindow::newWindow); menuAction = collection->addAction(QStringLiteral("close-window")); menuAction->setIcon(QIcon::fromTheme(QStringLiteral("window-close"))); menuAction->setText(i18nc("@action:inmenu", "Close Window")); collection->setDefaultShortcut(menuAction, Konsole::ACCEL + Qt::SHIFT + Qt::Key_Q); connect(menuAction, &QAction::triggered, this, &Konsole::MainWindow::close); // Bookmark Menu 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); // Settings Menu _toggleMenuBarAction = KStandardAction::showMenubar(menuBar(), SLOT(setVisible(bool)), collection); collection->setDefaultShortcut(_toggleMenuBarAction, Konsole::ACCEL + Qt::SHIFT + Qt::Key_M); // Full Screen menuAction = KStandardAction::fullScreen(this, SLOT(viewFullScreen(bool)), this, collection); collection->setDefaultShortcut(menuAction, Qt::Key_F11); KStandardAction::configureNotifications(this, SLOT(configureNotifications()), collection); KStandardAction::keyBindings(this, SLOT(showShortcutsDialog()), collection); KStandardAction::preferences(this, SLOT(showSettingsDialog()), collection); menuAction = collection->addAction(QStringLiteral("manage-profiles")); menuAction->setText(i18nc("@action:inmenu", "Manage Profiles...")); menuAction->setIcon(QIcon::fromTheme(QStringLiteral("configure"))); connect(menuAction, &QAction::triggered, this, &Konsole::MainWindow::showManageProfilesDialog); // Set up an shortcut-only action for activating menu bar. menuAction = collection->addAction(QStringLiteral("activate-menu")); menuAction->setText(i18nc("@item", "Activate Menu")); collection->setDefaultShortcut(menuAction, Konsole::ACCEL + Qt::SHIFT + Qt::Key_F10); connect(menuAction, &QAction::triggered, this, &Konsole::MainWindow::activateMenuBar); } void MainWindow::viewFullScreen(bool fullScreen) { if (fullScreen) { setWindowState(windowState() | Qt::WindowFullScreen); } else { setWindowState(windowState() & ~Qt::WindowFullScreen); } } BookmarkHandler *MainWindow::bookmarkHandler() const { return _bookmarkHandler; } void MainWindow::setProfileList(ProfileList *list) { profileListChanged(list->actions()); - connect(list, &Konsole::ProfileList::profileSelected, this, - [this](const Profile::Ptr &profile) { newFromProfile(_viewManager->activeContainer(), profile);}); - - connect(list, &Konsole::ProfileList::actionsChanged, this, - &Konsole::MainWindow::profileListChanged); + connect(list, &Konsole::ProfileList::profileSelected, this, &MainWindow::newFromProfile); + connect(list, &Konsole::ProfileList::actionsChanged, this, &Konsole::MainWindow::profileListChanged); } void MainWindow::profileListChanged(const QList &sessionActions) { // If only 1 profile is to be shown in the menu, only display // it if it is the non-default profile. if (sessionActions.size() > 2) { // Update the 'New Tab' KActionMenu if (_newTabMenuAction->menu() != nullptr) { _newTabMenuAction->menu()->clear(); } else { _newTabMenuAction->setMenu(new QMenu()); } foreach (QAction *sessionAction, sessionActions) { _newTabMenuAction->menu()->addAction(sessionAction); // NOTE: defaultProfile seems to not work here, sigh. Profile::Ptr profile = ProfileManager::instance()->defaultProfile(); if (profile && profile->name() == sessionAction->text().remove(QLatin1Char('&'))) { QIcon icon(KIconLoader::global()->loadIcon(profile->icon(), KIconLoader::Small, 0, KIconLoader::DefaultState, QStringList(QStringLiteral("emblem-favorite")))); sessionAction->setIcon(icon); _newTabMenuAction->menu()->setDefaultAction(sessionAction); QFont actionFont = sessionAction->font(); actionFont.setBold(true); sessionAction->setFont(actionFont); } } } else { if (_newTabMenuAction->menu() != nullptr) { _newTabMenuAction->menu()->clear(); } else { _newTabMenuAction->setMenu(new QMenu()); } Profile::Ptr profile = ProfileManager::instance()->defaultProfile(); // NOTE: Compare names w/o any '&' if (sessionActions.size() == 2 && sessionActions[1]->text().remove(QLatin1Char('&')) != profile->name()) { _newTabMenuAction->menu()->addAction(sessionActions[1]); } else { _newTabMenuAction->menu()->deleteLater(); } } } QString MainWindow::activeSessionDir() const { if (!_pluggedController.isNull()) { if (Session *session = _pluggedController->session()) { // For new tabs to get the correct working directory, // force the updating of the currentWorkingDirectory. session->getDynamicTitle(); } return _pluggedController->currentDir(); } else { return QString(); } } void MainWindow::openUrls(const QList &urls) { Profile::Ptr defaultProfile = ProfileManager::instance()->defaultProfile(); for (const auto &url : urls) { if (url.isLocalFile()) { - createSession(_viewManager->activeContainer(), defaultProfile, url.path()); + createSession(defaultProfile, url.path()); } else if (url.scheme() == QLatin1String("ssh")) { - createSSHSession(_viewManager->activeContainer(), defaultProfile, url); + createSSHSession(defaultProfile, url); } } } -void MainWindow::newTab(TabbedViewContainer *tabWidget) +void MainWindow::newTab() { Profile::Ptr defaultProfile = ProfileManager::instance()->defaultProfile(); - createSession(tabWidget, defaultProfile, activeSessionDir()); + createSession(defaultProfile, activeSessionDir()); } void MainWindow::cloneTab() { Q_ASSERT(_pluggedController); Session *session = _pluggedController->session(); Profile::Ptr profile = SessionManager::instance()->sessionProfile(session); if (profile) { - createSession(_viewManager->activeContainer(), profile, activeSessionDir()); + createSession(profile, activeSessionDir()); } else { // something must be wrong: every session should be associated with profile Q_ASSERT(false); - newTab(_viewManager->activeContainer()); + newTab(); } } -Session *MainWindow::createSession(TabbedViewContainer *tabWidget, Profile::Ptr profile, const QString &directory) +Session *MainWindow::createSession(Profile::Ptr profile, const QString &directory) { if (!profile) { profile = ProfileManager::instance()->defaultProfile(); } Session *session = SessionManager::instance()->createSession(profile); if (!directory.isEmpty() && profile->startInCurrentSessionDir()) { session->setInitialWorkingDirectory(directory); } session->addEnvironmentEntry(QStringLiteral("KONSOLE_DBUS_WINDOW=/Windows/%1").arg(_viewManager->managerId())); // create view before starting the session process so that the session // doesn't suffer a change in terminal size right after the session // starts. Some applications such as GNU Screen and Midnight Commander // don't like this happening - _viewManager->createView(tabWidget, session); - + auto newView = _viewManager->createView(session); + _viewManager->activeContainer()->addView(newView); return session; } -Session *MainWindow::createSSHSession(TabbedViewContainer *tabWidget, Profile::Ptr profile, const QUrl &url) +Session *MainWindow::createSSHSession(Profile::Ptr profile, const QUrl &url) { if (!profile) { profile = ProfileManager::instance()->defaultProfile(); } Session *session = SessionManager::instance()->createSession(profile); QString sshCommand = QStringLiteral("ssh "); if (url.port() > -1) { sshCommand += QStringLiteral("-p %1 ").arg(url.port()); } if (!url.userName().isEmpty()) { sshCommand += (url.userName() + QLatin1Char('@')); } if (!url.host().isEmpty()) { sshCommand += url.host(); } session->sendTextToTerminal(sshCommand, QLatin1Char('\r')); // create view before starting the session process so that the session // doesn't suffer a change in terminal size right after the session // starts. some applications such as GNU Screen and Midnight Commander // don't like this happening - _viewManager->createView(tabWidget, session); - + auto newView = _viewManager->createView(session); + _viewManager->activeContainer()->addView(newView); return session; } void MainWindow::setFocus() { _viewManager->activeView()->setFocus(); } void MainWindow::newWindow() { Profile::Ptr defaultProfile = ProfileManager::instance()->defaultProfile(); emit newWindowRequest(defaultProfile, activeSessionDir()); } bool MainWindow::queryClose() { // Do not ask for confirmation during log out and power off // TODO: rework the dealing of this case to make it has its own confirmation // dialog. if (qApp->isSavingSession()) { return true; } // Check what processes are running, excluding the shell QStringList processesRunning; const auto uniqueSessions = QSet::fromList(_viewManager->sessions()); foreach (Session *session, uniqueSessions) { if ((session == nullptr) || !session->isForegroundProcessActive()) { continue; } const QString defaultProc = session->program().split(QLatin1Char('/')).last(); const QString currentProc = session->foregroundProcessName().split(QLatin1Char('/')).last(); if (currentProc.isEmpty()) { continue; } if (defaultProc != currentProc) { processesRunning.append(currentProc); } } // Get number of open tabs const int openTabs = _viewManager->viewProperties().count(); // If no processes running (except the shell) and no extra tabs, just close if (processesRunning.count() == 0 && openTabs < 2) { return true; } // NOTE: Some, if not all, of the below KWindowSystem calls are only // implemented under x11 (KDE4.8 kdelibs/kdeui/windowmanagement). // make sure the window is shown on current desktop and is not minimized KWindowSystem::setOnDesktop(winId(), KWindowSystem::currentDesktop()); if (isMinimized()) { KWindowSystem::unminimizeWindow(winId(), true); } int result; if (!processesRunning.isEmpty()) { result = KMessageBox::warningYesNoCancelList(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")), KGuiItem(i18nc("@action:button", "Close Current &Tab"), QStringLiteral("tab-close")), KStandardGuiItem::cancel(), QStringLiteral("CloseAllTabs")); } else { result = KMessageBox::warningYesNoCancel(this, i18nc("@info", "There are %1 open tabs in this window. " "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")), KStandardGuiItem::cancel(), QStringLiteral("CloseAllEmptyTabs")); } switch (result) { case KMessageBox::Yes: return true; case KMessageBox::No: if ((!_pluggedController.isNull()) && (!_pluggedController->session().isNull())) { disconnectController(_pluggedController); _pluggedController->session()->closeInNormalWay(); } return false; case KMessageBox::Cancel: return false; } return true; } void MainWindow::saveProperties(KConfigGroup &group) { _viewManager->saveSessions(group); } void MainWindow::readProperties(const KConfigGroup &group) { _viewManager->restoreSessions(group); } void MainWindow::saveGlobalProperties(KConfig *config) { SessionManager::instance()->saveSessions(config); } void MainWindow::readGlobalProperties(KConfig *config) { SessionManager::instance()->restoreSessions(config); } void MainWindow::syncActiveShortcuts(KActionCollection *dest, const KActionCollection *source) { foreach (QAction *qAction, source->actions()) { if (QAction *destQAction = dest->action(qAction->objectName())) { destQAction->setShortcut(qAction->shortcut()); } } } void MainWindow::showShortcutsDialog() { KShortcutsDialog dialog(KShortcutsEditor::AllActions, KShortcutsEditor::LetterShortcutsDisallowed, this); // add actions from this window and the current session controller foreach (KXMLGUIClient *client, guiFactory()->clients()) { dialog.addCollection(client->actionCollection()); } if (dialog.configure()) { // sync shortcuts for non-session actions (defined in "konsoleui.rc") in other main windows foreach (QWidget *mainWindowWidget, QApplication::topLevelWidgets()) { auto *mainWindow = qobject_cast(mainWindowWidget); if ((mainWindow != nullptr) && mainWindow != this) { syncActiveShortcuts(mainWindow->actionCollection(), actionCollection()); } } // sync shortcuts for session actions (defined in "sessionui.rc") in other session controllers. // Controllers which are currently plugged in (ie. their actions are part of the current menu) // must be updated immediately via syncActiveShortcuts(). Other controllers will be updated // when they are plugged into a main window. foreach (SessionController *controller, SessionController::allControllers()) { controller->reloadXML(); if ((controller->factory() != nullptr) && controller != _pluggedController) { syncActiveShortcuts(controller->actionCollection(), _pluggedController->actionCollection()); } } } } -void MainWindow::newFromProfile(TabbedViewContainer *tabWidget, const Profile::Ptr &profile) +void MainWindow::newFromProfile(const Profile::Ptr &profile) { - createSession(tabWidget, profile, activeSessionDir()); + createSession(profile, activeSessionDir()); } void MainWindow::showManageProfilesDialog() { showSettingsDialog(true); } void MainWindow::showSettingsDialog(const bool showProfilePage) { if (KConfigDialog::showDialog(QStringLiteral("settings"))) { return; } KConfigDialog *settingsDialog = new KConfigDialog(this, QStringLiteral("settings"), KonsoleSettings::self()); settingsDialog->setFaceType(KPageDialog::Tabbed); auto generalSettings = new GeneralSettings(settingsDialog); settingsDialog->addPage(generalSettings, i18nc("@title Preferences page name", "General"), QStringLiteral("utilities-terminal")); auto profileSettings = new ProfileSettings(settingsDialog); KPageWidgetItem *profilePage = settingsDialog->addPage(profileSettings, i18nc("@title Preferences page name", "Profiles"), QStringLiteral("configure")); auto tabBarSettings = new TabBarSettings(settingsDialog); settingsDialog->addPage(tabBarSettings, i18nc("@title Preferences page name", "TabBar"), QStringLiteral("system-run")); auto fileLocationSettings = new FileLocationSettings(settingsDialog); settingsDialog->addPage(fileLocationSettings, i18nc("@title Preferences page name", "File Location"), QStringLiteral("configure")); if (showProfilePage) { settingsDialog->setCurrentPage(profilePage); } settingsDialog->show(); } void MainWindow::applyKonsoleSettings() { setMenuBarInitialVisibility(KonsoleSettings::showMenuBarByDefault()); setRemoveWindowTitleBarAndFrame(KonsoleSettings::removeWindowTitleBarAndFrame()); if (KonsoleSettings::allowMenuAccelerators()) { restoreMenuAccelerators(); } else { removeMenuAccelerators(); } _viewManager->setNavigationBehavior(KonsoleSettings::newTabBehavior()); setAutoSaveSettings(QStringLiteral("MainWindow"), KonsoleSettings::saveGeometryOnExit()); updateWindowCaption(); } void MainWindow::activateMenuBar() { const QList menuActions = menuBar()->actions(); if (menuActions.isEmpty()) { return; } // Show menubar if it is hidden at the moment if (menuBar()->isHidden()) { menuBar()->setVisible(true); _toggleMenuBarAction->setChecked(true); } // First menu action should be 'File' QAction *menuAction = menuActions.first(); // TODO: Handle when menubar is top level (MacOS) menuBar()->setActiveAction(menuAction); } void MainWindow::configureNotifications() { KNotifyConfigWidget::configure(this); } void MainWindow::setBlur(bool blur) { if (_pluggedController.isNull()) { return; } if (!_pluggedController->isKonsolePart()) { KWindowEffects::enableBlurBehind(winId(), blur); } } void MainWindow::setMenuBarInitialVisibility(bool visible) { _menuBarInitialVisibility = visible; } void MainWindow::setRemoveWindowTitleBarAndFrame(bool frameless) { // This is used to check if the window is in "opening" state // And avoid the visibility change when we change the window flag bool oldVisibility = isVisible(); if (frameless) { setWindowFlags(Qt::FramelessWindowHint); } else { setWindowFlags(Qt::Widget); } if (oldVisibility && !isVisible()) { setVisible(true); } } void MainWindow::showEvent(QShowEvent *event) { // Make sure the 'initial' visibility is applied only once. if (!_menuBarInitialVisibilityApplied) { // the initial visibility of menubar should be applied at this last // moment. Otherwise, the initial visibility will be determined by // what KMainWindow has automatically stored in konsolerc, but not by // what users has explicitly configured . menuBar()->setVisible(_menuBarInitialVisibility); _toggleMenuBarAction->setChecked(_menuBarInitialVisibility); _menuBarInitialVisibilityApplied = true; if (!KonsoleSettings::saveGeometryOnExit()) { resize(sizeHint()); } } // Call parent method KXmlGuiWindow::showEvent(event); } void MainWindow::triggerAction(const QString &name) const { if (auto action = actionCollection()->action(name)) { if (action->isEnabled()) { action->trigger(); } } } bool MainWindow::eventFilter(QObject *obj, QEvent *event) { - if (obj == _pluggedController->view()) { + if (!_pluggedController.isNull() && obj == _pluggedController->view()) { switch(event->type()) { - case QEvent::MouseButtonPress: - case QEvent::MouseButtonDblClick: + 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: ; + case Qt::ForwardButton: + triggerAction(QStringLiteral("next-view")); + break; + case Qt::BackButton: + triggerAction(QStringLiteral("previous-view")); + break; + default: ; } - default: ; + default: ; } } return KXmlGuiWindow::eventFilter(obj, event); } bool MainWindow::focusNextPrevChild(bool) { // In stand-alone konsole, always disable implicit focus switching // through 'Tab' and 'Shift+Tab' // // Kpart is another different story return false; } diff --git a/src/MainWindow.h b/src/MainWindow.h index 4592ff97..291e466b 100644 --- a/src/MainWindow.h +++ b/src/MainWindow.h @@ -1,207 +1,206 @@ /* Copyright 2006-2008 by Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef MAINWINDOW_H #define MAINWINDOW_H // Qt #include #include // KDE #include // Konsole #include "Profile.h" +#include "ViewSplitter.h" class QAction; class KActionMenu; class KToggleAction; namespace Konsole { class IncrementalSearchBar; class ViewManager; class ViewProperties; class Session; class SessionController; class ProfileList; class BookmarkHandler; class TabbedViewContainer; /** * The main window. This contains the menus and an area which contains the terminal displays. * * The main window does not create the views or the container widgets which hold the views. * This is done by the ViewManager class. When a MainWindow is instantiated, it creates * a new ViewManager. The ViewManager can then be used to create new terminal displays * inside the window. * * Do not construct new main windows directly, use Application's newMainWindow() method. */ class MainWindow : public KXmlGuiWindow { Q_OBJECT public: /** * Constructs a new main window. Do not create new main windows directly, use Application's * newMainWindow() method instead. */ MainWindow(); /** * Returns the view manager associated with this window. The view manager can be used to * create new views on particular session objects inside this window. */ ViewManager *viewManager() const; /** * Create a new session. * - * @param tabWidget where the new widget should be added. * @param profile The profile to use to create the new session. * @param directory Initial working directory for the new session or empty * if the default working directory associated with the profile should be used. */ - Session *createSession(TabbedViewContainer *tabWidget, Profile::Ptr profile, const QString &directory); + Session *createSession(Profile::Ptr profile, const QString &directory); /** * create a new SSH session. * - * @param tabWidget where the new widget should be added. * @param profile The profile to use to create the new session. * @param url the URL representing the new SSH connection */ - Session *createSSHSession(TabbedViewContainer *tabWidget, Profile::Ptr profile, const QUrl &url); + Session *createSSHSession(Profile::Ptr profile, const QUrl &url); /** * Helper method to make this window get input focus */ void setFocus(); /** * Set the initial visibility of the menubar. */ void setMenuBarInitialVisibility(bool visible); /** * @brief Set the frameless state * * @param frameless If true, no titlebar or frame is displayed. */ void setRemoveWindowTitleBarAndFrame(bool frameless); Q_SIGNALS: /** * Emitted by the main window to request the creation of a * new session in a new window. * * @param profile The profile to use to create the * first session in the new window. * @param directory Initial working directory for the new window or empty * if the default working directory associated with the profile should * be used. */ void newWindowRequest(const Profile::Ptr &profile, const QString &directory); /** * Emitted when a view for one session is detached from this window */ - void viewDetached(Session *session); + void terminalsDetached(ViewSplitter *splitter, QHash sessionsMap); protected: // Reimplemented for internal reasons. void showEvent(QShowEvent *event) Q_DECL_OVERRIDE; bool eventFilter(QObject *obj, QEvent *event) Q_DECL_OVERRIDE; // reimplemented from KMainWindow bool queryClose() Q_DECL_OVERRIDE; void saveProperties(KConfigGroup &group) Q_DECL_OVERRIDE; void readProperties(const KConfigGroup &group) Q_DECL_OVERRIDE; void saveGlobalProperties(KConfig *config) Q_DECL_OVERRIDE; void readGlobalProperties(KConfig *config) Q_DECL_OVERRIDE; // reimplemented from QWidget bool focusNextPrevChild(bool next) Q_DECL_OVERRIDE; private Q_SLOTS: - void newTab(TabbedViewContainer *tabWidget); + void newTab(); void cloneTab(); void newWindow(); void showManageProfilesDialog(); void activateMenuBar(); void showSettingsDialog(const bool showProfilePage = false); void showShortcutsDialog(); - void newFromProfile(TabbedViewContainer *tabWidget, const Profile::Ptr &profile); + void newFromProfile(const Profile::Ptr &profile); void activeViewChanged(SessionController *controller); void disconnectController(SessionController *controller); void activeViewTitleChanged(ViewProperties *); void profileListChanged(const QList &sessionActions); void configureNotifications(); void setBlur(bool blur); void updateWindowIcon(); void updateWindowCaption(); void openUrls(const QList &urls); // Sets the list of profiles to be displayed under the "New Tab" action void setProfileList(ProfileList *list); void applyKonsoleSettings(); void updateUseTransparency(); public Q_SLOTS: void viewFullScreen(bool fullScreen); private: void correctStandardShortcuts(); void rememberMenuAccelerators(); void removeMenuAccelerators(); void restoreMenuAccelerators(); void setupActions(); QString activeSessionDir() const; void triggerAction(const QString &name) const; /** * Returns the bookmark handler associated with this window. */ BookmarkHandler *bookmarkHandler() const; // sets the active shortcuts of actions in 'dest' to the shortcuts of actions // with the same name in 'source' (see QAction::ActiveShortcut) static void syncActiveShortcuts(KActionCollection *dest, const KActionCollection *source); private: ViewManager *_viewManager; BookmarkHandler *_bookmarkHandler; KToggleAction *_toggleMenuBarAction; KActionMenu *_newTabMenuAction; QPointer _pluggedController; bool _menuBarInitialVisibility; bool _menuBarInitialVisibilityApplied; }; } #endif // MAINWINDOW_H diff --git a/src/Part.cpp b/src/Part.cpp index 045f6569..d2ff5132 100644 --- a/src/Part.cpp +++ b/src/Part.cpp @@ -1,390 +1,391 @@ /* Copyright 2007-2008 by Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ // Own #include "Part.h" // Qt #include #include #include #include // KDE #include #include #include #include #include // Konsole #include "EditProfileDialog.h" #include "Emulation.h" #include "Session.h" #include "SessionController.h" #include "SessionManager.h" #include "ProfileManager.h" #include "TerminalDisplay.h" #include "ViewManager.h" #include "ViewContainer.h" #include "KonsoleSettings.h" #include "settings/PartInfo.h" #include "settings/ProfileSettings.h" using namespace Konsole; K_PLUGIN_FACTORY_WITH_JSON(KonsolePartFactory, "konsolepart.json", registerPlugin();) 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::empty, this, &Konsole::Part::terminalExited); connect(_viewManager, &Konsole::ViewManager::newViewRequest, this, &Konsole::Part::newTab); _viewManager->widget()->setParent(parentWidget); setWidget(_viewManager->widget()); actionCollection()->addAssociatedWidget(_viewManager->widget()); foreach (QAction *action, actionCollection()->actions()) { action->setShortcutContext(Qt::WidgetWithChildrenShortcut); } // Enable translucency support. _viewManager->widget()->setAttribute(Qt::WA_TranslucentBackground, true); // create basic session createSession(); } Part::~Part() { ProfileManager::instance()->saveSettings(); delete _viewManager; } bool Part::openFile() { return false; } void Part::terminalExited() { deleteLater(); } void Part::newTab() { createSession(); } Session *Part::activeSession() const { if (_viewManager->activeViewController() != nullptr) { Q_ASSERT(_viewManager->activeViewController()->session()); return _viewManager->activeViewController()->session(); } else { return nullptr; } } void Part::startProgram(const QString &program, const QStringList &arguments) { Q_ASSERT(activeSession()); // do nothing if the session has already started running if (activeSession()->isRunning()) { return; } if (!program.isEmpty() && !arguments.isEmpty()) { activeSession()->setProgram(program); activeSession()->setArguments(arguments); } activeSession()->run(); } void Part::openTeletype(int ptyMasterFd) { Q_ASSERT(activeSession()); activeSession()->openTeletype(ptyMasterFd); } void Part::showShellInDir(const QString &dir) { Q_ASSERT(activeSession()); // do nothing if the session has already started running if (activeSession()->isRunning()) { return; } // All other checking is done in setInitialWorkingDirectory() if (!dir.isEmpty()) { activeSession()->setInitialWorkingDirectory(dir); } activeSession()->run(); } void Part::sendInput(const QString &text) { Q_ASSERT(activeSession()); activeSession()->sendTextToTerminal(text); } int Part::terminalProcessId() { Q_ASSERT(activeSession()); return activeSession()->processId(); } int Part::foregroundProcessId() { Q_ASSERT(activeSession()); if (activeSession()->isForegroundProcessActive()) { return activeSession()->foregroundProcessId(); } else { return -1; } } QString Part::foregroundProcessName() { Q_ASSERT(activeSession()); if (activeSession()->isForegroundProcessActive()) { return activeSession()->foregroundProcessName(); } else { return QString(); } } QString Part::currentWorkingDirectory() const { Q_ASSERT(activeSession()); return activeSession()->currentWorkingDirectory(); } void Part::createSession(const QString &profileName, const QString &directory) { Profile::Ptr profile = ProfileManager::instance()->defaultProfile(); if (!profileName.isEmpty()) { profile = ProfileManager::instance()->loadProfile(profileName); } Q_ASSERT(profile); Session *session = SessionManager::instance()->createSession(profile); // override the default directory specified in the profile if (!directory.isEmpty() && profile->startInCurrentSessionDir()) { session->setInitialWorkingDirectory(directory); } - _viewManager->createView(_viewManager->activeContainer(), session); + auto newView = _viewManager->createView(session); + _viewManager->activeContainer()->addView(newView); } void Part::activeViewChanged(SessionController *controller) { Q_ASSERT(controller); Q_ASSERT(controller->view()); // 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); } // insert new controller insertChildClient(controller); connect(controller, &Konsole::SessionController::titleChanged, this, &Konsole::Part::activeViewTitleChanged); activeViewTitleChanged(controller); connect(controller, &Konsole::SessionController::currentDirectoryChanged, this, &Konsole::Part::currentDirectoryChanged); const char *displaySignal = SIGNAL(overrideShortcutCheck(QKeyEvent*,bool&)); const char *partSlot = SLOT(overrideTerminalShortcut(QKeyEvent*,bool&)); disconnect(controller->view(), displaySignal, this, partSlot); connect(controller->view(), displaySignal, this, partSlot); _pluggedController = controller; } 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)) { override = false; return; } // override all shortcuts in the embedded terminal by default override = true; emit overrideShortcut(event, override); } void Part::activeViewTitleChanged(ViewProperties *properties) { emit setWindowCaption(properties->title()); } void Part::showManageProfilesDialog(QWidget *parent) { // Make sure this string is unique among all users of this part if (KConfigDialog::showDialog(QStringLiteral("konsolepartmanageprofiles"))) { return; } 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")); auto partInfoSettings = new PartInfoSettings(settingsDialog); settingsDialog->addPage(partInfoSettings, i18nc("@title Preferences page name", "Part Info"), QStringLiteral("dialog-information")); settingsDialog->show(); } void Part::showEditCurrentProfileDialog(QWidget *parent) { Q_ASSERT(activeSession()); auto dialog = new EditProfileDialog(parent); dialog->setAttribute(Qt::WA_DeleteOnClose); dialog->setProfile(SessionManager::instance()->sessionProfile(activeSession())); dialog->show(); } void Part::changeSessionSettings(const QString &text) { Q_ASSERT(activeSession()); // send a profile change command, the escape code format // is the same as the normal X-Term commands used to change the window title or icon, // but with a magic value of '50' for the parameter which specifies what to change QString command = QStringLiteral("\033]50;%1\a").arg(text); sendInput(command); } // Konqueror integration bool Part::openUrl(const QUrl &url) { if (KParts::ReadOnlyPart::url() == url) { emit completed(); return true; } setUrl(url); emit setWindowCaption(url.toDisplayString(QUrl::PreferLocalFile)); ////qDebug() << "Set Window Caption to " << url.pathOrUrl(); emit started(nullptr); if (url.isLocalFile()) { showShellInDir(url.path()); } else { showShellInDir(QDir::homePath()); } emit completed(); return true; } void Part::setMonitorSilenceEnabled(bool enabled) { Q_ASSERT(activeSession()); if (enabled) { activeSession()->setMonitorSilence(true); connect(activeSession(), &Konsole::Session::stateChanged, this, &Konsole::Part::sessionStateChanged, Qt::UniqueConnection); } else { activeSession()->setMonitorSilence(false); disconnect(activeSession(), &Konsole::Session::stateChanged, this, &Konsole::Part::sessionStateChanged); } } void Part::setMonitorActivityEnabled(bool enabled) { Q_ASSERT(activeSession()); if (enabled) { activeSession()->setMonitorActivity(true); connect(activeSession(), &Konsole::Session::stateChanged, this, &Konsole::Part::sessionStateChanged, Qt::UniqueConnection); } else { activeSession()->setMonitorActivity(false); disconnect(activeSession(), &Konsole::Session::stateChanged, this, &Konsole::Part::sessionStateChanged); } } bool Part::isBlurEnabled() { return ViewManager::profileHasBlurEnabled(SessionManager::instance()->sessionProfile(activeSession())); } void Part::sessionStateChanged(int state) { if (state == NOTIFYSILENCE) { emit silenceDetected(); } else if (state == NOTIFYACTIVITY) { emit activityDetected(); } } #include "Part.moc" diff --git a/src/SessionController.cpp b/src/SessionController.cpp index 97192d31..fa062d8a 100644 --- a/src/SessionController.cpp +++ b/src/SessionController.cpp @@ -1,1803 +1,1795 @@ /* Copyright 2006-2008 by Robert Knight Copyright 2009 by Thomas Dreibholz This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ // Own #include "SessionController.h" #include "ProfileManager.h" #include "konsoledebug.h" // Qt #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 // Konsole #include "EditProfileDialog.h" #include "CopyInputDialog.h" #include "Emulation.h" #include "Filter.h" #include "History.h" #include "HistorySizeDialog.h" #include "IncrementalSearchBar.h" #include "RenameTabDialog.h" #include "ScreenWindow.h" #include "Session.h" #include "ProfileList.h" #include "TerminalDisplay.h" #include "SessionManager.h" #include "Enumeration.h" #include "PrintOptions.h" #include "SaveHistoryTask.h" #include "SearchHistoryTask.h" // For Unix signal names #include using namespace Konsole; // TODO - Replace the icon choices below when suitable icons for silence and // activity are available Q_GLOBAL_STATIC_WITH_ARGS(QIcon, _activityIcon, (QIcon::fromTheme(QLatin1String("dialog-information")))) Q_GLOBAL_STATIC_WITH_ARGS(QIcon, _silenceIcon, (QIcon::fromTheme(QLatin1String("dialog-information")))) Q_GLOBAL_STATIC_WITH_ARGS(QIcon, _bellIcon, (QIcon::fromTheme(QLatin1String("preferences-desktop-notification-bell")))) Q_GLOBAL_STATIC_WITH_ARGS(QIcon, _broadcastIcon, (QIcon::fromTheme(QLatin1String("emblem-important")))) QSet SessionController::_allControllers; int SessionController::_lastControllerId; SessionController::SessionController(Session* session , TerminalDisplay* view, QObject* parent) : ViewProperties(parent) , KXMLGUIClient() , _session(session) , _view(view) , _copyToGroup(nullptr) , _sessionIcon(QIcon()) , _sessionIconName(QString()) , _previousState(-1) , _searchFilter(nullptr) , _urlFilter(nullptr) , _fileFilter(nullptr) , _copyInputToAllTabsAction(nullptr) , _findAction(nullptr) , _findNextAction(nullptr) , _findPreviousAction(nullptr) , _interactionTimer(nullptr) , _searchStartLine(0) , _prevSearchResultLine(0) , _codecAction(nullptr) , _switchProfileMenu(nullptr) , _webSearchMenu(nullptr) , _listenForScreenWindowUpdates(false) , _preventClose(false) , _keepIconUntilInteraction(false) , _selectedText(QString()) , _showMenuAction(nullptr) , _bookmarkValidProgramsToClear(QStringList()) , _isSearchBarEnabled(false) , _editProfileDialog(nullptr) , _searchBar(view->searchBar()) { Q_ASSERT(session); Q_ASSERT(view); // handle user interface related to session (menus etc.) if (isKonsolePart()) { setComponentName(QStringLiteral("konsole"), i18n("Konsole")); setXMLFile(QStringLiteral("partui.rc")); setupCommonActions(); } else { setXMLFile(QStringLiteral("sessionui.rc")); setupCommonActions(); setupExtraActions(); } actionCollection()->addAssociatedWidget(view); foreach(QAction * action, actionCollection()->actions()) { action->setShortcutContext(Qt::WidgetWithChildrenShortcut); } setIdentifier(++_lastControllerId); sessionAttributeChanged(); view->installEventFilter(this); view->setSessionController(this); // install filter on the view to highlight URLs and files updateFilterList(SessionManager::instance()->sessionProfile(_session)); // listen for changes in session, we might need to change the enabled filters connect(ProfileManager::instance(), &Konsole::ProfileManager::profileChanged, this, &Konsole::SessionController::updateFilterList); // listen for session resize requests connect(_session.data(), &Konsole::Session::resizeRequest, this, &Konsole::SessionController::sessionResizeRequest); // listen for popup menu requests connect(_view.data(), &Konsole::TerminalDisplay::configureRequest, this, &Konsole::SessionController::showDisplayContextMenu); // move view to newest output when keystrokes occur connect(_view.data(), &Konsole::TerminalDisplay::keyPressedSignal, this, &Konsole::SessionController::trackOutput); // listen to activity / silence notifications from session connect(_session.data(), &Konsole::Session::stateChanged, this, &Konsole::SessionController::sessionStateChanged); // listen to title and icon changes connect(_session.data(), &Konsole::Session::sessionAttributeChanged, this, &Konsole::SessionController::sessionAttributeChanged); connect(_session.data(), &Konsole::Session::readOnlyChanged, this, &Konsole::SessionController::sessionReadOnlyChanged); connect(this, &Konsole::SessionController::tabRenamedByUser, _session, &Konsole::Session::tabTitleSetByUser); connect(_session.data() , &Konsole::Session::currentDirectoryChanged , this , &Konsole::SessionController::currentDirectoryChanged); // listen for color changes connect(_session.data(), &Konsole::Session::changeBackgroundColorRequest, _view.data(), &Konsole::TerminalDisplay::setBackgroundColor); connect(_session.data(), &Konsole::Session::changeForegroundColorRequest, _view.data(), &Konsole::TerminalDisplay::setForegroundColor); // update the title when the session starts connect(_session.data(), &Konsole::Session::started, this, &Konsole::SessionController::snapshot); // listen for output changes to set activity flag connect(_session->emulation(), &Konsole::Emulation::outputChanged, this, &Konsole::SessionController::fireActivity); // listen for detection of ZModem transfer connect(_session.data(), &Konsole::Session::zmodemDownloadDetected, this, &Konsole::SessionController::zmodemDownload); connect(_session.data(), &Konsole::Session::zmodemUploadDetected, this, &Konsole::SessionController::zmodemUpload); // listen for flow control status changes connect(_session.data(), &Konsole::Session::flowControlEnabledChanged, _view.data(), &Konsole::TerminalDisplay::setFlowControlWarningEnabled); _view->setFlowControlWarningEnabled(_session->flowControlEnabled()); // take a snapshot of the session state every so often when // user activity occurs // // the timer is owned by the session so that it will be destroyed along // with the session _interactionTimer = new QTimer(_session); _interactionTimer->setSingleShot(true); _interactionTimer->setInterval(500); connect(_interactionTimer, &QTimer::timeout, this, &Konsole::SessionController::snapshot); connect(_view.data(), &Konsole::TerminalDisplay::focusGained, this, &Konsole::SessionController::interactionHandler); connect(_view.data(), &Konsole::TerminalDisplay::keyPressedSignal, this, &Konsole::SessionController::interactionHandler); // take a snapshot of the session state periodically in the background auto backgroundTimer = new QTimer(_session); backgroundTimer->setSingleShot(false); backgroundTimer->setInterval(2000); connect(backgroundTimer, &QTimer::timeout, this, &Konsole::SessionController::snapshot); backgroundTimer->start(); // xterm '11;?' request connect(_session.data(), &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 << QStringLiteral("bash") << QStringLiteral("fish") << QStringLiteral("sh"); _bookmarkValidProgramsToClear << QStringLiteral("tcsh") << QStringLiteral("zsh"); setupSearchBar(); _searchBar->setVisible(_isSearchBarEnabled); _profileList = ProfileManager::instance()->getProfileList(); connect(_profileList, &ProfileList::actionsChanged, this, &Konsole::SessionController::prepareSwitchProfileMenu); prepareSwitchProfileMenu(); } SessionController::~SessionController() { - if (!_view.isNull()) { - _view->setScreenWindow(nullptr); - } - _allControllers.remove(this); if (!_editProfileDialog.isNull()) { delete _editProfileDialog.data(); } } void SessionController::trackOutput(QKeyEvent* event) { Q_ASSERT(_view->screenWindow()); // Only jump to the bottom if the user actually typed something in, // not if the user e. g. just pressed a modifier. if (event->text().isEmpty() && (event->modifiers() != 0u)) { return; } _view->screenWindow()->setTrackOutput(true); } void SessionController::interactionHandler() { // This flag is used to make sure those special icons indicating interest // events (activity/silence/bell?) remain in the tab until user interaction // happens. Otherwise, those special icons will quickly be replaced by // normal icon when ::snapshot() is triggered _keepIconUntilInteraction = false; _interactionTimer->start(); } void SessionController::snapshot() { Q_ASSERT(!_session.isNull()); QString title = _session->getDynamicTitle(); title = title.simplified(); // Visualize that the session is broadcasting to others if ((_copyToGroup != nullptr) && _copyToGroup->sessions().count() > 1) { title.append(QLatin1Char('*')); } // use the fallback title if needed if (title.isEmpty()) { title = _session->title(Session::NameRole); } // apply new title _session->setTitle(Session::DisplayedTitleRole, title); // do not forget icon updateSessionIcon(); } QString SessionController::currentDir() const { return _session->currentWorkingDirectory(); } QUrl SessionController::url() const { return _session->getUrl(); } void SessionController::rename() { renameSession(); } void SessionController::openUrl(const QUrl& url) { // Clear shell's command line if (!_session->isForegroundProcessActive() && _bookmarkValidProgramsToClear.contains(_session->foregroundProcessName())) { _session->sendTextToTerminal(QChar(0x03), QLatin1Char('\n')); // Ctrl+C } // handle local paths if (url.isLocalFile()) { QString path = url.toLocalFile(); _session->sendTextToTerminal(QStringLiteral("cd ") + KShell::quoteArg(path), QLatin1Char('\r')); } else if (url.scheme().isEmpty()) { // QUrl couldn't parse what the user entered into the URL field // so just dump it to the shell QString command = url.toDisplayString(); if (!command.isEmpty()) { _session->sendTextToTerminal(command, QLatin1Char('\r')); } } else if (url.scheme() == QLatin1String("ssh")) { QString sshCommand = QStringLiteral("ssh "); if (url.port() > -1) { sshCommand += QStringLiteral("-p %1 ").arg(url.port()); } if (!url.userName().isEmpty()) { sshCommand += (url.userName() + QLatin1Char('@')); } if (!url.host().isEmpty()) { sshCommand += url.host(); } _session->sendTextToTerminal(sshCommand, QLatin1Char('\r')); } else if (url.scheme() == QLatin1String("telnet")) { QString telnetCommand = QStringLiteral("telnet "); if (!url.userName().isEmpty()) { telnetCommand += QStringLiteral("-l %1 ").arg(url.userName()); } if (!url.host().isEmpty()) { telnetCommand += (url.host() + QLatin1Char(' ')); } if (url.port() > -1) { telnetCommand += QString::number(url.port()); } _session->sendTextToTerminal(telnetCommand, QLatin1Char('\r')); } else { //TODO Implement handling for other Url types 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(); } } 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")); // these actions are meaningful only when primary screen is used. clearAction->setEnabled(use); resetAction->setEnabled(use); selectAllAction->setEnabled(use); selectLineAction->setEnabled(use); } void SessionController::selectionChanged(const QString& selectedText) { _selectedText = selectedText; updateCopyAction(selectedText); } void SessionController::updateCopyAction(const QString& selectedText) { QAction* copyAction = actionCollection()->action(QStringLiteral("edit_copy")); // copy action is meaningful only when some text is selected. copyAction->setEnabled(!selectedText.isEmpty()); } void SessionController::updateWebSearchMenu() { // reset _webSearchMenu->setVisible(false); _webSearchMenu->menu()->clear(); if (_selectedText.isEmpty()) { return; } QString searchText = _selectedText; searchText = searchText.replace(QLatin1Char('\n'), QLatin1Char(' ')).replace(QLatin1Char('\r'), QLatin1Char(' ')).simplified(); if (searchText.isEmpty()) { return; } KUriFilterData filterData(searchText); filterData.setSearchFilteringOptions(KUriFilterData::RetrievePreferredSearchProvidersOnly); 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))); QAction* action = nullptr; foreach(const QString& searchProvider, searchProviders) { action = new QAction(searchProvider, _webSearchMenu); action->setIcon(QIcon::fromTheme(filterData.iconNameForPreferredSearchProvider(searchProvider))); action->setData(filterData.queryForPreferredSearchProvider(searchProvider)); connect(action, &QAction::triggered, this, &Konsole::SessionController::handleWebShortcutAction); _webSearchMenu->addAction(action); } _webSearchMenu->addSeparator(); action = new QAction(i18n("Configure Web Shortcuts..."), _webSearchMenu); action->setIcon(QIcon::fromTheme(QStringLiteral("configure"))); connect(action, &QAction::triggered, this, &Konsole::SessionController::configureWebShortcuts); _webSearchMenu->addAction(action); _webSearchMenu->setVisible(true); } } } void SessionController::handleWebShortcutAction() { auto * action = qobject_cast(sender()); if (action == nullptr) { return; } KUriFilterData filterData(action->data().toString()); if (KUriFilter::self()->filterUri(filterData, QStringList() << QStringLiteral("kurisearchfilter"))) { const QUrl& url = filterData.uri(); new KRun(url, QApplication::activeWindow()); } } void SessionController::configureWebShortcuts() { KToolInvocation::kdeinitExec(QStringLiteral("kcmshell5"), QStringList() << QStringLiteral("webshortcuts")); } void SessionController::sendSignal(QAction* action) { const auto signal = action->data().value(); _session->sendSignal(signal); } void SessionController::sendBackgroundColor() { const QColor c = _view->getBackgroundColor(); _session->reportBackgroundColor(c); } void SessionController::toggleReadOnly() { auto *action = qobject_cast(sender()); if (action != nullptr) { bool readonly = !isReadOnly(); _session->setReadOnly(readonly); } } bool SessionController::eventFilter(QObject* watched , QEvent* event) { if (event->type() == QEvent::FocusIn && watched == _view) { // notify the world that the view associated with this session has been focused // used by the view manager to update the title of the MainWindow widget containing the view emit focused(this); // when the view is focused, set bell events from the associated session to be delivered // by the focused view // first, disconnect any other views which are listening for bell signals from the session disconnect(_session.data(), &Konsole::Session::bellRequest, nullptr, nullptr); // second, connect the newly focused view to listen for the session's bell signal connect(_session.data(), &Konsole::Session::bellRequest, _view.data(), &Konsole::TerminalDisplay::bell); disconnect(_profileList, &Konsole::ProfileList::profileSelected, nullptr, nullptr); connect(_profileList, &Konsole::ProfileList::profileSelected, this, &Konsole::SessionController::switchProfile); if ((_copyInputToAllTabsAction != nullptr) && _copyInputToAllTabsAction->isChecked()) { // A session with "Copy To All Tabs" has come into focus: // Ensure that newly created sessions are included in _copyToGroup! copyInputToAllTabs(); } } return Konsole::ViewProperties::eventFilter(watched, event); } void SessionController::removeSearchFilter() { if (_searchFilter == nullptr) { return; } _view->filterChain()->removeFilter(_searchFilter); delete _searchFilter; _searchFilter = nullptr; } void SessionController::setupSearchBar() { connect(_searchBar.data(), &Konsole::IncrementalSearchBar::unhandledMovementKeyPressed, this, &Konsole::SessionController::movementKeyFromSearchBarReceived); connect(_searchBar.data(), &Konsole::IncrementalSearchBar::closeClicked, this, &Konsole::SessionController::searchClosed); connect(_searchBar.data(), &Konsole::IncrementalSearchBar::searchFromClicked, this, &Konsole::SessionController::searchFrom); connect(_searchBar.data(), &Konsole::IncrementalSearchBar::findNextClicked, this, &Konsole::SessionController::findNextInHistory); connect(_searchBar.data(), &Konsole::IncrementalSearchBar::findPreviousClicked, this, &Konsole::SessionController::findPreviousInHistory); connect(_searchBar.data(), &Konsole::IncrementalSearchBar::highlightMatchesToggled , this , &Konsole::SessionController::highlightMatches); connect(_searchBar.data(), &Konsole::IncrementalSearchBar::matchCaseToggled, this, &Konsole::SessionController::changeSearchMatch); connect(_searchBar.data(), &Konsole::IncrementalSearchBar::matchRegExpToggled, this, &Konsole::SessionController::changeSearchMatch); } void SessionController::setShowMenuAction(QAction* action) { _showMenuAction = action; } void SessionController::setupCommonActions() { KActionCollection* collection = actionCollection(); // Close Session QAction* action = collection->addAction(QStringLiteral("close-session"), this, SLOT(closeSession())); - if (isKonsolePart()) { - action->setText(i18n("&Close Session")); - } else { - action->setText(i18n("&Close Tab")); - } + action->setText(i18n("&Close Session")); action->setIcon(QIcon::fromTheme(QStringLiteral("tab-close"))); collection->setDefaultShortcut(action, Konsole::ACCEL + Qt::SHIFT + Qt::Key_W); // Open Browser action = collection->addAction(QStringLiteral("open-browser"), this, SLOT(openBrowser())); action->setText(i18n("Open File Manager")); action->setIcon(QIcon::fromTheme(QStringLiteral("system-file-manager"))); // Copy and Paste action = KStandardAction::copy(this, SLOT(copy()), collection); #ifdef Q_OS_MACOS // Don't use the Konsole::ACCEL const here, we really want the Command key (Qt::META) // TODO: check what happens if we leave it to Qt to assign the default? collection->setDefaultShortcut(action, Qt::META + Qt::Key_C); #else collection->setDefaultShortcut(action, Konsole::ACCEL + Qt::SHIFT + Qt::Key_C); #endif // disabled at first, since nothing has been selected now action->setEnabled(false); action = KStandardAction::paste(this, SLOT(paste()), collection); QList pasteShortcut; #ifdef Q_OS_MACOS pasteShortcut.append(QKeySequence(Qt::META + Qt::Key_V)); // No Insert key on Mac keyboards #else pasteShortcut.append(QKeySequence(Konsole::ACCEL + Qt::SHIFT + Qt::Key_V)); pasteShortcut.append(QKeySequence(Qt::SHIFT + Qt::Key_Insert)); #endif collection->setDefaultShortcuts(action, pasteShortcut); action = collection->addAction(QStringLiteral("paste-selection"), this, SLOT(pasteFromX11Selection())); action->setText(i18n("Paste Selection")); #ifdef Q_OS_MACOS collection->setDefaultShortcut(action, Qt::META + Qt::SHIFT + Qt::Key_V); #else collection->setDefaultShortcut(action, Konsole::ACCEL + Qt::SHIFT + Qt::Key_Insert); #endif _webSearchMenu = new KActionMenu(i18n("Web Search"), this); _webSearchMenu->setIcon(QIcon::fromTheme(QStringLiteral("preferences-web-browser-shortcuts"))); _webSearchMenu->setVisible(false); collection->addAction(QStringLiteral("web-search"), _webSearchMenu); action = collection->addAction(QStringLiteral("select-all"), this, SLOT(selectAll())); action->setText(i18n("&Select All")); action->setIcon(QIcon::fromTheme(QStringLiteral("edit-select-all"))); action = collection->addAction(QStringLiteral("select-line"), this, SLOT(selectLine())); action->setText(i18n("Select &Line")); action = KStandardAction::saveAs(this, SLOT(saveHistory()), collection); action->setText(i18n("Save Output &As...")); #ifdef Q_OS_MACOS action->setShortcut(QKeySequence(Qt::META + Qt::Key_S)); #endif action = KStandardAction::print(this, SLOT(print_screen()), collection); action->setText(i18n("&Print Screen...")); collection->setDefaultShortcut(action, Konsole::ACCEL + Qt::SHIFT + Qt::Key_P); action = collection->addAction(QStringLiteral("adjust-history"), this, SLOT(showHistoryOptions())); action->setText(i18n("Adjust Scrollback...")); action->setIcon(QIcon::fromTheme(QStringLiteral("configure"))); action = collection->addAction(QStringLiteral("clear-history"), this, SLOT(clearHistory())); action->setText(i18n("Clear Scrollback")); action->setIcon(QIcon::fromTheme(QStringLiteral("edit-clear-history"))); action = collection->addAction(QStringLiteral("clear-history-and-reset"), this, SLOT(clearHistoryAndReset())); action->setText(i18n("Clear Scrollback and Reset")); action->setIcon(QIcon::fromTheme(QStringLiteral("edit-clear-history"))); collection->setDefaultShortcut(action, Konsole::ACCEL + Qt::SHIFT + Qt::Key_K); // Profile Options action = collection->addAction(QStringLiteral("edit-current-profile"), this, SLOT(editCurrentProfile())); action->setText(i18n("Edit Current Profile...")); action->setIcon(QIcon::fromTheme(QStringLiteral("document-properties"))); _switchProfileMenu = new KActionMenu(i18n("Switch Profile"), this); collection->addAction(QStringLiteral("switch-profile"), _switchProfileMenu); // History _findAction = KStandardAction::find(this, SLOT(searchBarEvent()), collection); _findNextAction = KStandardAction::findNext(this, SLOT(findNextInHistory()), collection); _findNextAction->setEnabled(false); _findPreviousAction = KStandardAction::findPrev(this, SLOT(findPreviousInHistory()), collection); _findPreviousAction->setEnabled(false); #ifdef Q_OS_MACOS collection->setDefaultShortcut(_findAction, Qt::META + Qt::Key_F); collection->setDefaultShortcut(_findNextAction, Qt::META + Qt::Key_G); collection->setDefaultShortcut(_findPreviousAction, Qt::META + Qt::SHIFT + Qt::Key_G); #else collection->setDefaultShortcut(_findAction, Konsole::ACCEL + Qt::SHIFT + Qt::Key_F); collection->setDefaultShortcut(_findNextAction, Qt::Key_F3); collection->setDefaultShortcut(_findPreviousAction, Qt::SHIFT + Qt::Key_F3); #endif // Character Encoding _codecAction = new KCodecAction(i18n("Set &Encoding"), this); _codecAction->setIcon(QIcon::fromTheme(QStringLiteral("character-set"))); collection->addAction(QStringLiteral("set-encoding"), _codecAction); connect(_codecAction->menu(), &QMenu::aboutToShow, this, &Konsole::SessionController::updateCodecAction); connect(_codecAction, QOverload::of(&KCodecAction::triggered), this, &Konsole::SessionController::changeCodec); // Read-only action = collection->addAction(QStringLiteral("view-readonly"), this, SLOT(toggleReadOnly())); action->setText(i18nc("@item:inmenu A read only (locked) session", "Read-only")); action->setCheckable(true); updateReadOnlyActionStates(); } void SessionController::setupExtraActions() { KActionCollection* collection = actionCollection(); // Rename Session QAction* action = collection->addAction(QStringLiteral("rename-session"), this, SLOT(renameSession())); action->setText(i18n("&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")); 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")); 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")); copyInputToNoneAction->setText(i18nc("@action:inmenu Do not select any tabs", "&None")); collection->setDefaultShortcut(copyInputToNoneAction, Konsole::ACCEL + Qt::SHIFT + Qt::Key_Slash); copyInputToNoneAction->setData(CopyInputToNoneMode); copyInputToNoneAction->setChecked(true); // the default state // The "Copy Input To" submenu // The above three choices are represented as combo boxes 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); action = collection->addAction(QStringLiteral("zmodem-upload"), this, SLOT(zmodemUpload())); action->setText(i18n("&ZModem Upload...")); action->setIcon(QIcon::fromTheme(QStringLiteral("document-open"))); collection->setDefaultShortcut(action, Konsole::ACCEL + Qt::ALT + Qt::Key_U); // Monitor 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); toggleAction = new KToggleAction(i18n("Monitor for &Silence"), this); collection->setDefaultShortcut(toggleAction, Konsole::ACCEL + Qt::SHIFT + Qt::Key_I); action = collection->addAction(QStringLiteral("monitor-silence"), toggleAction); connect(action, &QAction::toggled, this, &Konsole::SessionController::monitorSilence); // Text Size action = collection->addAction(QStringLiteral("enlarge-font"), this, SLOT(increaseFontSize())); action->setText(i18n("Enlarge Font")); action->setIcon(QIcon::fromTheme(QStringLiteral("format-font-size-more"))); QList enlargeFontShortcut; enlargeFontShortcut.append(QKeySequence(Konsole::ACCEL + Qt::Key_Plus)); enlargeFontShortcut.append(QKeySequence(Konsole::ACCEL + Qt::Key_Equal)); collection->setDefaultShortcuts(action, enlargeFontShortcut); action = collection->addAction(QStringLiteral("shrink-font"), this, SLOT(decreaseFontSize())); action->setText(i18n("Shrink Font")); action->setIcon(QIcon::fromTheme(QStringLiteral("format-font-size-less"))); collection->setDefaultShortcut(action, Konsole::ACCEL + Qt::Key_Minus); action = collection->addAction(QStringLiteral("reset-font-size"), this, SLOT(resetFontSize())); action->setText(i18n("Reset Font Size")); collection->setDefaultShortcut(action, Konsole::ACCEL + Qt::ALT + Qt::Key_0); // Send signal auto* sendSignalActions = collection->add(QStringLiteral("send-signal")); sendSignalActions->setText(i18n("Send Signal")); connect(sendSignalActions, QOverload::of(&KSelectAction::triggered), this, &Konsole::SessionController::sendSignal); action = collection->addAction(QStringLiteral("sigstop-signal")); 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->setData(SIGCONT); sendSignalActions->addAction(action); action = collection->addAction(QStringLiteral("sighup-signal")); action->setText(i18n("&Hangup") + QStringLiteral(" (HUP)")); action->setData(SIGHUP); sendSignalActions->addAction(action); action = collection->addAction(QStringLiteral("sigint-signal")); action->setText(i18n("&Interrupt Task") + QStringLiteral(" (INT)")); action->setData(SIGINT); sendSignalActions->addAction(action); action = collection->addAction(QStringLiteral("sigterm-signal")); action->setText(i18n("&Terminate Task") + QStringLiteral(" (TERM)")); action->setData(SIGTERM); sendSignalActions->addAction(action); action = collection->addAction(QStringLiteral("sigkill-signal")); 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->setData(SIGUSR1); sendSignalActions->addAction(action); action = collection->addAction(QStringLiteral("sigusr2-signal")); action->setText(i18n("User Signal &2") + QStringLiteral(" (USR2)")); action->setData(SIGUSR2); sendSignalActions->addAction(action); } void SessionController::switchProfile(const Profile::Ptr &profile) { if (isReadOnly()) { return; } SessionManager::instance()->setSessionProfile(_session, profile); updateFilterList(profile); } void SessionController::prepareSwitchProfileMenu() { _switchProfileMenu->menu()->clear(); _switchProfileMenu->menu()->addActions(_profileList->actions()); } void SessionController::updateCodecAction() { _codecAction->setCurrentCodec(QString::fromUtf8(_session->codec())); } void SessionController::changeCodec(QTextCodec* codec) { _session->setCodec(codec); } EditProfileDialog* SessionController::profileDialogPointer() { return _editProfileDialog.data(); } void SessionController::editCurrentProfile() { // Searching for Edit profile dialog opened with the same profile const QList allSessionsControllers = _allControllers.values(); foreach (SessionController* session, allSessionsControllers) { if ((session->profileDialogPointer() != nullptr) && session->profileDialogPointer()->isVisible() && session->profileDialogPointer()->lookupProfile() == SessionManager::instance()->sessionProfile(_session)) { session->profileDialogPointer()->close(); } } // NOTE bug311270: For to prevent the crash, the profile must be reset. if (!_editProfileDialog.isNull()) { // exists but not visible delete _editProfileDialog.data(); } _editProfileDialog = new EditProfileDialog(QApplication::activeWindow()); _editProfileDialog.data()->setProfile(SessionManager::instance()->sessionProfile(_session)); _editProfileDialog.data()->show(); } void SessionController::renameSession() { const QString &sessionLocalTabTitleFormat = _session->tabTitleFormat(Session::LocalTabTitle); const QString &sessionRemoteTabTitleFormat = _session->tabTitleFormat(Session::RemoteTabTitle); QScopedPointer dialog(new RenameTabDialog(QApplication::activeWindow())); dialog->setTabTitleText(sessionLocalTabTitleFormat); dialog->setRemoteTabTitleText(sessionRemoteTabTitleFormat); if (_session->isRemote()) { dialog->focusRemoteTabTitleText(); } else { dialog->focusTabTitleText(); } QPointer guard(_session); int result = dialog->exec(); if (guard.isNull()) { return; } if (result != 0) { const QString &tabTitle = dialog->tabTitleText(); const QString &remoteTabTitle = dialog->remoteTabTitleText(); if (tabTitle != sessionLocalTabTitleFormat) { _session->setTabTitleFormat(Session::LocalTabTitle, tabTitle); emit tabRenamedByUser(true); // trigger an update of the tab text snapshot(); } if(remoteTabTitle != sessionRemoteTabTitleFormat) { _session->setTabTitleFormat(Session::RemoteTabTitle, remoteTabTitle); emit tabRenamedByUser(true); snapshot(); } } } bool SessionController::confirmClose() const { if (_session->isForegroundProcessActive()) { QString title = _session->foregroundProcessName(); // hard coded for now. In future make it possible for the user to specify which programs // are ignored when considering whether to display a confirmation QStringList ignoreList; ignoreList << QString::fromUtf8(qgetenv("SHELL")).section(QLatin1Char('/'), -1); if (ignoreList.contains(title)) { return true; } QString question; if (title.isEmpty()) { 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); } int result = KMessageBox::warningYesNo(_view->window(), question, i18n("Confirm Close")); return result == KMessageBox::Yes; } return true; } bool SessionController::confirmForceClose() const { if (_session->isRunning()) { QString title = _session->program(); // hard coded for now. In future make it possible for the user to specify which programs // are ignored when considering whether to display a confirmation QStringList ignoreList; ignoreList << QString::fromUtf8(qgetenv("SHELL")).section(QLatin1Char('/'), -1); if (ignoreList.contains(title)) { return true; } 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?"); } else { 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")); return result == KMessageBox::Yes; } return true; } void SessionController::closeSession() { if (_preventClose) { return; } if (confirmClose()) { if (_session->closeInNormalWay()) { return; } else if (confirmForceClose()) { if (_session->closeInForceWay()) { return; } else { qCDebug(KonsoleDebug) << "Konsole failed to close a session in any way."; } } } } // Trying to open a remote Url may produce unexpected results. // Therefore, if a remote url, open the user's home path. // TODO consider: 1) disable menu upon remote session // 2) transform url to get the desired result (ssh -> sftp, etc) void SessionController::openBrowser() { const QUrl currentUrl = url(); if (currentUrl.isLocalFile()) { new KRun(currentUrl, QApplication::activeWindow(), true); } else { new KRun(QUrl::fromLocalFile(QDir::homePath()), QApplication::activeWindow(), true); } } void SessionController::copy() { _view->copyToClipboard(); } void SessionController::paste() { _view->pasteFromClipboard(); } void SessionController::pasteFromX11Selection() { _view->pasteFromX11Selection(); } void SessionController::selectAll() { _view->selectAll(); } void SessionController::selectLine() { _view->selectCurrentLine(); } 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); if (window != nullptr) { return(window); } object = object->parent(); } return(nullptr); } static bool hasTerminalDisplayInSameWindow(const Session* session, const KXmlGuiWindow* window) { // Iterate all TerminalDisplays of this Session ... foreach(const TerminalDisplay* terminalDisplay, session->views()) { // ... and check whether a TerminalDisplay has the same // window as given in the parameter if (window == findWindow(terminalDisplay)) { return(true); } } return(false); } void SessionController::copyInputActionsTriggered(QAction* action) { const auto mode = action->data().value(); switch (mode) { case CopyInputToAllTabsMode: copyInputToAllTabs(); break; case CopyInputToSelectedTabsMode: copyInputToSelectedTabs(); break; case CopyInputToNoneMode: copyInputToNone(); break; default: Q_ASSERT(false); } } void SessionController::copyInputToAllTabs() { if (_copyToGroup == nullptr) { _copyToGroup = new SessionGroup(this); } // Find our window ... const KXmlGuiWindow* myWindow = findWindow(_view); QSet group = QSet::fromList(SessionManager::instance()->sessions()); for (auto session : group) { // First, ensure that the session is removed // (necessary to avoid duplicates on addSession()!) _copyToGroup->removeSession(session); // Add current session if it is displayed our window if (hasTerminalDisplayInSameWindow(session, myWindow)) { _copyToGroup->addSession(session); } } _copyToGroup->setMasterStatus(_session, true); _copyToGroup->setMasterMode(SessionGroup::CopyInputToAll); snapshot(); } void SessionController::copyInputToSelectedTabs() { if (_copyToGroup == nullptr) { _copyToGroup = new SessionGroup(this); _copyToGroup->addSession(_session); _copyToGroup->setMasterStatus(_session, true); _copyToGroup->setMasterMode(SessionGroup::CopyInputToAll); } QPointer dialog = new CopyInputDialog(_view); dialog->setMasterSession(_session); QSet currentGroup = QSet::fromList(_copyToGroup->sessions()); currentGroup.remove(_session); dialog->setChosenSessions(currentGroup); QPointer guard(_session); int result = dialog->exec(); if (guard.isNull()) { return; } if (result == QDialog::Accepted) { QSet newGroup = dialog->chosenSessions(); newGroup.remove(_session); QSet completeGroup = newGroup | currentGroup; foreach(Session * session, completeGroup) { if (newGroup.contains(session) && !currentGroup.contains(session)) { _copyToGroup->addSession(session); } else if (!newGroup.contains(session) && currentGroup.contains(session)) { _copyToGroup->removeSession(session); } } _copyToGroup->setMasterStatus(_session, true); _copyToGroup->setMasterMode(SessionGroup::CopyInputToAll); snapshot(); } } void SessionController::copyInputToNone() { if (_copyToGroup == nullptr) { // No 'Copy To' is active return; } QSet group = QSet::fromList(SessionManager::instance()->sessions()); for (auto iterator : group) { Session* session = iterator; if (session != _session) { _copyToGroup->removeSession(iterator); } } delete _copyToGroup; _copyToGroup = nullptr; snapshot(); } void SessionController::searchClosed() { _isSearchBarEnabled = false; searchHistory(false); } void SessionController::updateFilterList(Profile::Ptr profile) { if (profile != SessionManager::instance()->sessionProfile(_session)) { return; } bool underlineFiles = profile->underlineFilesEnabled(); if (!underlineFiles && (_fileFilter != nullptr)) { _view->filterChain()->removeFilter(_fileFilter); delete _fileFilter; _fileFilter = nullptr; } else if (underlineFiles && (_fileFilter == nullptr)) { _fileFilter = new FileFilter(_session); _view->filterChain()->addFilter(_fileFilter); } bool underlineLinks = profile->underlineLinksEnabled(); if (!underlineLinks && (_urlFilter != nullptr)) { _view->filterChain()->removeFilter(_urlFilter); delete _urlFilter; _urlFilter = nullptr; } else if (underlineLinks && (_urlFilter == nullptr)) { _urlFilter = new UrlFilter(); _view->filterChain()->addFilter(_urlFilter); } } void SessionController::setSearchStartToWindowCurrentLine() { setSearchStartTo(-1); } void SessionController::setSearchStartTo(int line) { _searchStartLine = line; _prevSearchResultLine = line; } void SessionController::listenForScreenWindowUpdates() { if (_listenForScreenWindowUpdates) { return; } 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.data(), QOverload<>::of(&Konsole::TerminalDisplay::update)); _listenForScreenWindowUpdates = true; } void SessionController::updateSearchFilter() { if ((_searchFilter != nullptr) && (!_searchBar.isNull())) { _view->processFilters(); } } void SessionController::searchBarEvent() { QString selectedText = _view->screenWindow()->selectedText(Screen::PreserveLineBreaks | Screen::TrimLeadingWhitespace | Screen::TrimTrailingWhitespace); if (!selectedText.isEmpty()) { _searchBar->setSearchText(selectedText); } if (_searchBar->isVisible()) { _searchBar->focusLineEdit(); } else { searchHistory(true); _isSearchBarEnabled = true; } } void SessionController::enableSearchBar(bool showSearchBar) { if (_searchBar.isNull()) { return; } if (showSearchBar && !_searchBar->isVisible()) { setSearchStartToWindowCurrentLine(); } _searchBar->setVisible(showSearchBar); if (showSearchBar) { connect(_searchBar.data(), &Konsole::IncrementalSearchBar::searchChanged, this, &Konsole::SessionController::searchTextChanged); connect(_searchBar.data(), &Konsole::IncrementalSearchBar::searchReturnPressed, this, &Konsole::SessionController::findPreviousInHistory); connect(_searchBar.data(), &Konsole::IncrementalSearchBar::searchShiftPlusReturnPressed, this, &Konsole::SessionController::findNextInHistory); } else { disconnect(_searchBar.data(), &Konsole::IncrementalSearchBar::searchChanged, this, &Konsole::SessionController::searchTextChanged); disconnect(_searchBar.data(), &Konsole::IncrementalSearchBar::searchReturnPressed, this, &Konsole::SessionController::findPreviousInHistory); disconnect(_searchBar.data(), &Konsole::IncrementalSearchBar::searchShiftPlusReturnPressed, this, &Konsole::SessionController::findNextInHistory); if ((!_view.isNull()) && (_view->screenWindow() != nullptr)) { _view->screenWindow()->setCurrentResultLine(-1); } } } bool SessionController::reverseSearchChecked() const { Q_ASSERT(_searchBar); QBitArray options = _searchBar->optionsChecked(); return options.at(IncrementalSearchBar::ReverseSearch); } QRegularExpression SessionController::regexpFromSearchBarOptions() const { QBitArray options = _searchBar->optionsChecked(); QString text(_searchBar->searchText()); QRegularExpression regExp; if (options.at(IncrementalSearchBar::RegExp)) { regExp.setPattern(text); } else { regExp.setPattern(QRegularExpression::escape(text)); } if (!options.at(IncrementalSearchBar::MatchCase)) { regExp.setPatternOptions(QRegularExpression::CaseInsensitiveOption); } return regExp; } // searchHistory() may be called either as a result of clicking a menu item or // as a result of changing the search bar widget void SessionController::searchHistory(bool showSearchBar) { enableSearchBar(showSearchBar); if (!_searchBar.isNull()) { if (showSearchBar) { removeSearchFilter(); listenForScreenWindowUpdates(); _searchFilter = new RegExpFilter(); _searchFilter->setRegExp(regexpFromSearchBarOptions()); _view->filterChain()->addFilter(_searchFilter); _view->processFilters(); setFindNextPrevEnabled(true); } else { setFindNextPrevEnabled(false); removeSearchFilter(); _view->setFocus(Qt::ActiveWindowFocusReason); } } } void SessionController::setFindNextPrevEnabled(bool enabled) { _findNextAction->setEnabled(enabled); _findPreviousAction->setEnabled(enabled); } void SessionController::searchTextChanged(const QString& text) { Q_ASSERT(_view->screenWindow()); if (_searchText == text) { return; } _searchText = text; if (text.isEmpty()) { _view->screenWindow()->clearSelection(); _view->screenWindow()->scrollTo(_searchStartLine); } // update search. this is called even when the text is // empty to clear the view's filters beginSearch(text , reverseSearchChecked() ? Enum::BackwardsSearch : Enum::ForwardsSearch); } void SessionController::searchCompleted(bool success) { _prevSearchResultLine = _view->screenWindow()->currentResultLine(); if (!_searchBar.isNull()) { _searchBar->setFoundMatch(success); } } void SessionController::beginSearch(const QString& text, Enum::SearchDirection direction) { Q_ASSERT(_searchBar); Q_ASSERT(_searchFilter); QRegularExpression regExp = regexpFromSearchBarOptions(); _searchFilter->setRegExp(regExp); if (_searchStartLine < 0 || _searchStartLine > _view->screenWindow()->lineCount()) { if (direction == Enum::ForwardsSearch) { setSearchStartTo(_view->screenWindow()->currentLine()); } else { setSearchStartTo(_view->screenWindow()->currentLine() + _view->screenWindow()->windowLines()); } } if (!regExp.pattern().isEmpty()) { _view->screenWindow()->setCurrentResultLine(-1); auto task = new SearchHistoryTask(this); connect(task, &Konsole::SearchHistoryTask::completed, this, &Konsole::SessionController::searchCompleted); task->setRegExp(regExp); task->setSearchDirection(direction); task->setAutoDelete(true); task->setStartLine(_searchStartLine); task->addScreenWindow(_session , _view->screenWindow()); task->execute(); } else if (text.isEmpty()) { searchCompleted(false); } _view->processFilters(); } void SessionController::highlightMatches(bool highlight) { if (highlight) { _view->filterChain()->addFilter(_searchFilter); _view->processFilters(); } else { _view->filterChain()->removeFilter(_searchFilter); } _view->update(); } void SessionController::searchFrom() { Q_ASSERT(_searchBar); Q_ASSERT(_searchFilter); if (reverseSearchChecked()) { setSearchStartTo(_view->screenWindow()->lineCount()); } else { setSearchStartTo(0); } beginSearch(_searchBar->searchText(), reverseSearchChecked() ? Enum::BackwardsSearch : Enum::ForwardsSearch); } void SessionController::findNextInHistory() { Q_ASSERT(_searchBar); Q_ASSERT(_searchFilter); setSearchStartTo(_prevSearchResultLine); beginSearch(_searchBar->searchText(), reverseSearchChecked() ? Enum::BackwardsSearch : Enum::ForwardsSearch); } void SessionController::findPreviousInHistory() { Q_ASSERT(_searchBar); Q_ASSERT(_searchFilter); setSearchStartTo(_prevSearchResultLine); beginSearch(_searchBar->searchText(), reverseSearchChecked() ? Enum::ForwardsSearch : Enum::BackwardsSearch); } void SessionController::changeSearchMatch() { Q_ASSERT(_searchBar); Q_ASSERT(_searchFilter); // reset Selection for new case match _view->screenWindow()->clearSelection(); beginSearch(_searchBar->searchText(), reverseSearchChecked() ? Enum::BackwardsSearch : Enum::ForwardsSearch); } void SessionController::showHistoryOptions() { QScopedPointer dialog(new HistorySizeDialog(QApplication::activeWindow())); const HistoryType& currentHistory = _session->historyType(); if (currentHistory.isEnabled()) { if (currentHistory.isUnlimited()) { dialog->setMode(Enum::UnlimitedHistory); } else { dialog->setMode(Enum::FixedSizeHistory); dialog->setLineCount(currentHistory.maximumLineCount()); } } else { dialog->setMode(Enum::NoHistory); } QPointer guard(_session); int result = dialog->exec(); if (guard.isNull()) { return; } if (result != 0) { scrollBackOptionsChanged(dialog->mode(), dialog->lineCount()); } } void SessionController::sessionResizeRequest(const QSize& size) { ////qDebug() << "View resize requested to " << size; _view->setSize(size.width(), size.height()); } void SessionController::scrollBackOptionsChanged(int mode, int lines) { switch (mode) { case Enum::NoHistory: _session->setHistoryType(HistoryTypeNone()); break; case Enum::FixedSizeHistory: _session->setHistoryType(CompactHistoryType(lines)); break; case Enum::UnlimitedHistory: _session->setHistoryType(HistoryTypeFile()); break; } } void SessionController::print_screen() { QPrinter printer; QPointer dialog = new QPrintDialog(&printer, _view); auto options = new PrintOptions(); dialog->setOptionTabs(QList() << options); dialog->setWindowTitle(i18n("Print Shell")); connect(dialog.data(), QOverload<>::of(&QPrintDialog::accepted), options, &Konsole::PrintOptions::saveSettings); if (dialog->exec() != QDialog::Accepted) { return; } QPainter painter; painter.begin(&printer); KConfigGroup configGroup(KSharedConfig::openConfig(), "PrintOptions"); if (configGroup.readEntry("ScaleOutput", true)) { double scale = qMin(printer.pageRect().width() / static_cast(_view->width()), printer.pageRect().height() / static_cast(_view->height())); painter.scale(scale, scale); } _view->printContent(painter, configGroup.readEntry("PrinterFriendly", true)); } void SessionController::saveHistory() { SessionTask* task = new SaveHistoryTask(this); task->setAutoDelete(true); task->addSession(_session); task->execute(); } void SessionController::clearHistory() { _session->clearHistory(); _view->updateImage(); // To reset view scrollbar _view->repaint(); } void SessionController::clearHistoryAndReset() { Profile::Ptr profile = SessionManager::instance()->sessionProfile(_session); QByteArray name = profile->defaultEncoding().toUtf8(); Emulation* emulation = _session->emulation(); emulation->reset(); _session->refresh(); _session->setCodec(QTextCodec::codecForName(name)); clearHistory(); } void SessionController::increaseFontSize() { _view->increaseFontSize(); } void SessionController::decreaseFontSize() { _view->decreaseFontSize(); } void SessionController::resetFontSize() { _view->resetFontSize(); } void SessionController::monitorActivity(bool monitor) { _session->setMonitorActivity(monitor); } void SessionController::monitorSilence(bool monitor) { _session->setMonitorSilence(monitor); } void SessionController::updateSessionIcon() { // If the default profile icon is being used, don't put it on the tab // Only show the icon if the user specifically chose one if (_session->iconName() == QStringLiteral("utilities-terminal")) { _sessionIconName = QString(); } else { _sessionIconName = _session->iconName(); } _sessionIcon = QIcon::fromTheme(_sessionIconName); // Visualize that the session is broadcasting to others if ((_copyToGroup != nullptr) && _copyToGroup->sessions().count() > 1) { // Master Mode: set different icon, to warn the user to be careful setIcon(*_broadcastIcon); } else { if (!_keepIconUntilInteraction) { // Not in Master Mode: use normal icon setIcon(_sessionIcon); } } } void SessionController::updateReadOnlyActionStates() { bool readonly = isReadOnly(); QAction *readonlyAction = actionCollection()->action(QStringLiteral("view-readonly")); Q_ASSERT(readonlyAction != nullptr); readonlyAction->setIcon(QIcon::fromTheme(readonly ? QStringLiteral("object-locked") : QStringLiteral("object-unlocked"))); readonlyAction->setChecked(readonly); auto updateActionState = [this, readonly](const QString &name) { QAction *action = actionCollection()->action(name); if (action != nullptr) { action->setEnabled(!readonly); } }; updateActionState(QStringLiteral("edit_paste")); updateActionState(QStringLiteral("clear-history")); updateActionState(QStringLiteral("clear-history-and-reset")); updateActionState(QStringLiteral("edit-current-profile")); updateActionState(QStringLiteral("switch-profile")); updateActionState(QStringLiteral("adjust-history")); updateActionState(QStringLiteral("send-signal")); updateActionState(QStringLiteral("zmodem-upload")); _codecAction->setEnabled(!readonly); // Without the timer, when detaching a tab while the message widget is visible, // the size of the terminal becomes really small... QTimer::singleShot(0, this, [this, readonly]() { _view->updateReadOnlyState(readonly); }); } bool SessionController::isReadOnly() const { if (!_session.isNull()) { return _session->isReadOnly(); } else { return false; } } void SessionController::sessionAttributeChanged() { if (_sessionIconName != _session->iconName()) { updateSessionIcon(); } QString title = _session->title(Session::DisplayedTitleRole); // special handling for the "%w" marker which is replaced with the // window title set by the shell title.replace(QLatin1String("%w"), _session->userTitle()); // special handling for the "%#" marker which is replaced with the // number of the shell title.replace(QLatin1String("%#"), QString::number(_session->sessionId())); if (title.isEmpty()) { title = _session->title(Session::NameRole); } setTitle(title); emit rawTitleChanged(); } void SessionController::sessionReadOnlyChanged() { // Trigger icon update sessionAttributeChanged(); updateReadOnlyActionStates(); // Update all views foreach (TerminalDisplay* view, session()->views()) { if (view != _view.data()) { view->updateReadOnlyState(isReadOnly()); } } } 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. if (factory() == nullptr) { if (clientBuilder() == nullptr) { setClientBuilder(new KXMLGUIBuilder(_view)); } auto factory = new KXMLGUIFactory(clientBuilder(), this); factory->addClient(this); ////qDebug() << "Created xmlgui factory" << factory; } QPointer popup = qobject_cast(factory()->container(QStringLiteral("session-popup-menu"), this)); if (!popup.isNull()) { updateReadOnlyActionStates(); // prepend content-specific actions such as "Open Link", "Copy Email Address" etc. QList contentActions = _view->filterActions(position); auto contentSeparator = new QAction(popup); contentSeparator->setSeparator(true); contentActions << contentSeparator; popup->insertActions(popup->actions().value(0, nullptr), contentActions); // always update this submenu before showing the context menu, // because the available search services might have changed // since the context menu is shown last time updateWebSearchMenu(); _preventClose = true; if (_showMenuAction != nullptr) { if ( _showMenuAction->isChecked() ) { popup->removeAction( _showMenuAction); } else { popup->insertAction(_switchProfileMenu, _showMenuAction); } } QAction* chosen = popup->exec(_view->mapToGlobal(position)); // check for validity of the pointer to the popup menu if (!popup.isNull()) { // Remove content-specific actions // // If the close action was chosen, the popup menu will be partially // destroyed at this point, and the rest will be destroyed later by // 'chosen->trigger()' foreach(QAction * action, contentActions) { popup->removeAction(action); } delete contentSeparator; } _preventClose = false; if ((chosen != nullptr) && chosen->objectName() == QLatin1String("close-session")) { chosen->trigger(); } } else { qCDebug(KonsoleDebug) << "Unable to display popup menu for session" << _session->title(Session::NameRole) << ", no GUI factory available to build the popup."; } } void SessionController::movementKeyFromSearchBarReceived(QKeyEvent *event) { QCoreApplication::sendEvent(_view, event); setSearchStartToWindowCurrentLine(); } void SessionController::sessionStateChanged(int state) { if (state == _previousState) { return; } if (state == NOTIFYACTIVITY) { setIcon(*_activityIcon); _keepIconUntilInteraction = true; } else if (state == NOTIFYSILENCE) { setIcon(*_silenceIcon); _keepIconUntilInteraction = true; } else if (state == NOTIFYBELL) { setIcon(*_bellIcon); _keepIconUntilInteraction = true; } else if (state == NOTIFYNORMAL) { updateSessionIcon(); } _previousState = state; } void SessionController::zmodemDownload() { QString zmodem = QStandardPaths::findExecutable(QStringLiteral("rz")); if (zmodem.isEmpty()) { zmodem = QStandardPaths::findExecutable(QStringLiteral("lrz")); } if (!zmodem.isEmpty()) { const QString path = QFileDialog::getExistingDirectory(_view, i18n("Save ZModem Download to..."), QDir::homePath(), QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); if (!path.isEmpty()) { _session->startZModem(zmodem, path, QStringList()); return; } } else { KMessageBox::error(_view, i18n("

A ZModem file transfer attempt has been detected, " "but no suitable ZModem software was found on this system.

" "

You may wish to install the 'rzsz' or 'lrzsz' package.

")); } _session->cancelZModem(); } void SessionController::zmodemUpload() { if (_session->isZModemBusy()) { KMessageBox::sorry(_view, i18n("

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

")); return; } _session->setZModemBusy(true); QString zmodem = QStandardPaths::findExecutable(QStringLiteral("sz")); if (zmodem.isEmpty()) { zmodem = QStandardPaths::findExecutable(QStringLiteral("lsz")); } if (zmodem.isEmpty()) { KMessageBox::sorry(_view, i18n("

No suitable ZModem software was found on this system.

" "

You may wish to install the 'rzsz' or 'lrzsz' package.

")); return; } QStringList files = QFileDialog::getOpenFileNames(_view, i18n("Select Files for ZModem Upload"), QDir::homePath()); if (!files.isEmpty()) { _session->startZModem(zmodem, QString(), files); } } bool SessionController::isKonsolePart() const { // Check to see if we are being called from Konsole or a KPart return !(qApp->applicationName() == QLatin1String("konsole")); } QString SessionController::userTitle() const { if (!_session.isNull()) { return _session->userTitle(); } else { return QString(); } } diff --git a/src/Shortcut_p.h b/src/Shortcut_p.h index cc16ab16..55456cc5 100644 --- a/src/Shortcut_p.h +++ b/src/Shortcut_p.h @@ -1,40 +1,44 @@ /* This file is part of Konsole, an X terminal. Copyright 2015 by René J.V. Bertin This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef SHORTCUT_H #define SHORTCUT_H #include namespace Konsole { /** * Platform-specific main shortcut "opcode": */ enum Modifier { #ifdef Q_OS_MACOS - ACCEL = Qt::META + ACCEL = Qt::META, + LEFT = Qt::Key_BracketLeft, + RIGHT = Qt::Key_BracketRight #else - ACCEL = Qt::CTRL + ACCEL = Qt::CTRL, + LEFT = Qt::Key_Left, + RIGHT = Qt::Key_Right #endif }; } #endif //SHORTCUT_H diff --git a/src/ViewContainer.cpp b/src/ViewContainer.cpp index eb934c89..d0f5c0d5 100644 --- a/src/ViewContainer.cpp +++ b/src/ViewContainer.cpp @@ -1,550 +1,576 @@ /* This file is part of the Konsole Terminal. Copyright 2006-2008 Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ // Own #include "ViewContainer.h" #include // Qt #include #include #include #include #include #include #include // KDE #include #include #include #include // Konsole #include "IncrementalSearchBar.h" #include "ViewProperties.h" #include "ProfileList.h" #include "ViewManager.h" #include "KonsoleSettings.h" #include "SessionController.h" #include "DetachableTabBar.h" #include "TerminalDisplay.h" +#include "ViewSplitter.h" +#include "MainWindow.h" +#include "Session.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()), _closeTabButton(new QToolButton()), _contextMenuTabIndex(-1), - _navigationVisibility(ViewManager::NavigationVisibility::NavigationNotSet), - _tabHistoryIndex(-1) + _navigationVisibility(ViewManager::NavigationVisibility::NavigationNotSet) { setAcceptDrops(true); auto tabBarWidget = new DetachableTabBar(); setTabBar(tabBarWidget); setDocumentMode(true); setMovable(true); connect(tabBarWidget, &DetachableTabBar::moveTabToWindow, this, &TabbedViewContainer::moveTabToWindow); tabBar()->setContextMenuPolicy(Qt::CustomContextMenu); _newTabButton->setIcon(QIcon::fromTheme(QStringLiteral("tab-new"))); _newTabButton->setAutoRaise(true); - connect(_newTabButton, &QToolButton::clicked, this, [this]{ - emit newViewRequest(this); - }); + connect(_newTabButton, &QToolButton::clicked, this, &TabbedViewContainer::newViewRequest); _closeTabButton->setIcon(QIcon::fromTheme(QStringLiteral("tab-close"))); _closeTabButton->setAutoRaise(true); connect(_closeTabButton, &QToolButton::clicked, this, [this]{ closeCurrentTab(); }); connect(tabBar(), &QTabBar::tabBarDoubleClicked, this, &Konsole::TabbedViewContainer::tabDoubleClicked); connect(tabBar(), &QTabBar::customContextMenuRequested, this, &Konsole::TabbedViewContainer::openTabContextMenu); +#if defined(ENABLE_DETACHING) connect(tabBarWidget, &DetachableTabBar::detachTab, this, [this](int idx) { - emit detachTab(this, terminalAt(idx)); + emit detachTab(idx); }); +#endif connect(tabBarWidget, &DetachableTabBar::closeTab, this, &TabbedViewContainer::closeTerminalTab); connect(tabBarWidget, &DetachableTabBar::newTabRequest, - this, [this]{ emit newViewRequest(this); }); + this, [this]{ emit newViewRequest(); }); connect(this, &TabbedViewContainer::currentChanged, this, &TabbedViewContainer::currentTabChanged); // The context menu of tab bar _contextPopupMenu = new QMenu(tabBar()); connect(_contextPopupMenu, &QMenu::aboutToHide, this, [this]() { // Remove the read-only action when the popup closes for (auto &action : _contextPopupMenu->actions()) { if (action->objectName() == QStringLiteral("view-readonly")) { _contextPopupMenu->removeAction(action); break; } } }); connect(tabBar(), &QTabBar::tabCloseRequested, this, &TabbedViewContainer::closeTerminalTab); #if defined(ENABLE_DETACHING) auto detachAction = _contextPopupMenu->addAction( QIcon::fromTheme(QStringLiteral("tab-detach")), i18nc("@action:inmenu", "&Detach Tab"), this, - [this] { emit detachTab(this, terminalAt(_contextMenuTabIndex)); } + [this] { emit detachTab(_contextMenuTabIndex); } ); detachAction->setObjectName(QStringLiteral("tab-detach")); #endif auto editAction = _contextPopupMenu->addAction( QIcon::fromTheme(QStringLiteral("edit-rename")), i18nc("@action:inmenu", "&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); } ); closeAction->setObjectName(QStringLiteral("tab-close")); auto profileMenu = new QMenu(); auto profileList = new ProfileList(false, profileMenu); profileList->syncWidgetActions(profileMenu, true); - connect(profileList, &Konsole::ProfileList::profileSelected, this, - [this](const Profile::Ptr &profile) { emit newViewWithProfileRequest(this, profile); }); + connect(profileList, &Konsole::ProfileList::profileSelected, this, &TabbedViewContainer::newViewWithProfileRequest); _newTabButton->setMenu(profileMenu); konsoleConfigChanged(); connect(KonsoleSettings::self(), &KonsoleSettings::configChanged, this, &TabbedViewContainer::konsoleConfigChanged); } TabbedViewContainer::~TabbedViewContainer() { for(int i = 0, end = count(); i < end; i++) { auto view = widget(i); disconnect(view, &QWidget::destroyed, this, &Konsole::TabbedViewContainer::viewDestroyed); } } -TerminalDisplay *TabbedViewContainer::terminalAt(int index) +ViewSplitter *TabbedViewContainer::activeViewSplitter() +{ + return viewSplitterAt(currentIndex()); +} + +ViewSplitter *TabbedViewContainer::viewSplitterAt(int index) { - return qobject_cast(widget(index)); + return qobject_cast(widget(index)); } void TabbedViewContainer::moveTabToWindow(int index, QWidget *window) { - const int id = terminalAt(index)->sessionController()->identifier(); - // This one line here will be removed as soon as I finish my new split handling. - // it's hacky but it works. - const auto widgets = window->findChildren(); - const auto currentPos = QCursor::pos(); - for(const auto dropWidget : widgets) { - if (dropWidget->rect().contains(dropWidget->mapFromGlobal(currentPos))) { - emit dropWidget->moveViewRequest(-1, id); - removeView(terminalAt(index)); - } + auto splitter = viewSplitterAt(index); + auto manager = window->findChild(); + + QHash sessionsMap = _connectedViewManager->forgetAll(splitter); + + foreach(TerminalDisplay* terminal, splitter->findChildren()) { + manager->attachView(terminal, sessionsMap[terminal]); } + auto container = manager->activeContainer(); + container->addSplitter(splitter); + + auto controller = splitter->activeTerminalDisplay()->sessionController(); + container->currentSessionControllerChanged(controller); + + forgetView(splitter); } void TabbedViewContainer::konsoleConfigChanged() { // don't show tabs if we are in KParts mode. // This is a hack, and this needs to be rewritten. // The container should not be part of the KParts, perhaps just the // TerminalDisplay should. // ASAN issue if using sessionController->isKonsolePart(), just // duplicate code for now if (qApp->applicationName() != QLatin1String("konsole")) { tabBar()->setVisible(false); } else { // if we start with --show-tabbar or --hide-tabbar we ignore the preferences. setTabBarAutoHide(KonsoleSettings::tabBarVisibility() == KonsoleSettings::EnumTabBarVisibility::ShowTabBarWhenNeeded); if (KonsoleSettings::tabBarVisibility() == KonsoleSettings::EnumTabBarVisibility::AlwaysShowTabBar) { tabBar()->setVisible(true); } else if (KonsoleSettings::tabBarVisibility() == KonsoleSettings::EnumTabBarVisibility::AlwaysHideTabBar) { tabBar()->setVisible(false); } } setTabPosition((QTabWidget::TabPosition) KonsoleSettings::tabBarPosition()); setCornerWidget(KonsoleSettings::newTabButton() ? _newTabButton : nullptr, Qt::TopLeftCorner); _newTabButton->setVisible(KonsoleSettings::newTabButton()); setCornerWidget(KonsoleSettings::closeTabButton() == 1 ? _closeTabButton : nullptr, Qt::TopRightCorner); _closeTabButton->setVisible(KonsoleSettings::closeTabButton() == 1); tabBar()->setTabsClosable(KonsoleSettings::closeTabButton() == 0); tabBar()->setExpanding(KonsoleSettings::expandTabWidth()); tabBar()->update(); if (KonsoleSettings::tabBarUseUserStyleSheet()) { setCssFromFile(KonsoleSettings::tabBarUserStyleSheetFile()); } else { setCss(); } } void TabbedViewContainer::setCss(const QString& styleSheet) { static const QString defaultCss = QStringLiteral("QTabWidget::tab-bar, QTabWidget::pane { margin: 0; }\n"); setStyleSheet(defaultCss + styleSheet); } void TabbedViewContainer::setCssFromFile(const QUrl &url) { // Let's only deal w/ local files for now if (!url.isLocalFile()) { setStyleSheet(KonsoleSettings::tabBarStyleSheet()); } QFile file(url.toLocalFile()); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { setStyleSheet(KonsoleSettings::tabBarStyleSheet()); } QTextStream in(&file); setCss(in.readAll()); } void TabbedViewContainer::moveActiveView(MoveDirection direction) { if (count() < 2) { // return if only one view return; } const int currentIndex = indexOf(currentWidget()); int newIndex = direction == MoveViewLeft ? qMax(currentIndex - 1, 0) : qMin(currentIndex + 1, count() - 1); - auto swappedWidget = terminalAt(newIndex); - auto currentWidget = terminalAt(currentIndex); - auto swappedContext = swappedWidget->sessionController(); - auto currentContext = currentWidget->sessionController(); + auto swappedWidget = viewSplitterAt(newIndex); + auto swappedTitle = tabBar()->tabText(newIndex); + auto swappedIcon = tabBar()->tabIcon(newIndex); + + auto currentWidget = viewSplitterAt(currentIndex); + auto currentTitle = tabBar()->tabText(currentIndex); + auto currentIcon = tabBar()->tabIcon(currentIndex); if (newIndex < currentIndex) { - insertTab(newIndex, currentWidget, currentContext->icon(), currentContext->title()); - insertTab(currentIndex, swappedWidget, swappedContext->icon(), swappedContext->title()); + insertTab(newIndex, currentWidget, currentIcon, currentTitle); + insertTab(currentIndex, swappedWidget, swappedIcon, swappedTitle); } else { - insertTab(currentIndex, swappedWidget, swappedContext->icon(), swappedContext->title()); - insertTab(newIndex, currentWidget, currentContext->icon(), currentContext->title()); + insertTab(currentIndex, swappedWidget, swappedIcon, swappedTitle); + insertTab(newIndex, currentWidget, currentIcon, currentTitle); } setCurrentIndex(newIndex); } +void TabbedViewContainer::addSplitter(ViewSplitter *viewSplitter, int index) { + if (index == -1) { + index = addTab(viewSplitter, QString()); + } else { + insertTab(index, viewSplitter, QString()); + } + connect(viewSplitter, &ViewSplitter::destroyed, this, &TabbedViewContainer::viewDestroyed); + foreach(TerminalDisplay* terminal, viewSplitter->findChildren()) { + connectTerminalDisplay(terminal); + } + setCurrentIndex(index); +} + void TabbedViewContainer::addView(TerminalDisplay *view, int index) { + auto viewSplitter = new ViewSplitter(); + viewSplitter->addTerminalDisplay(view, Qt::Horizontal); auto item = view->sessionController(); if (index == -1) { - addTab(view, item->icon(), item->title()); + index = addTab(viewSplitter, item->icon(), item->title()); } else { - insertTab(index, view, item->icon(), item->title()); + insertTab(index, viewSplitter, item->icon(), item->title()); } - _tabHistory.append(view); + connectTerminalDisplay(view); + connect(viewSplitter, &ViewSplitter::destroyed, this, &TabbedViewContainer::viewDestroyed); + setCurrentIndex(index); + emit viewAdded(view); +} + +void TabbedViewContainer::splitView(TerminalDisplay *view, Qt::Orientation orientation) +{ + auto viewSplitter = qobject_cast(currentWidget()); + viewSplitter->addTerminalDisplay(view, orientation); + connectTerminalDisplay(view); +} + +void TabbedViewContainer::connectTerminalDisplay(TerminalDisplay *display) +{ + auto item = display->sessionController(); + connect(item, &Konsole::SessionController::focused, this, + &Konsole::TabbedViewContainer::currentSessionControllerChanged); + connect(item, &Konsole::ViewProperties::titleChanged, this, &Konsole::TabbedViewContainer::updateTitle); + connect(item, &Konsole::ViewProperties::iconChanged, this, &Konsole::TabbedViewContainer::updateIcon); + connect(item, &Konsole::ViewProperties::activity, this, &Konsole::TabbedViewContainer::updateActivity); - connect(view, &QWidget::destroyed, this, - &Konsole::TabbedViewContainer::viewDestroyed); - emit viewAdded(view); +} + +void TabbedViewContainer::disconnectTerminalDisplay(TerminalDisplay *display) +{ + auto item = display->sessionController(); + disconnect(item, &Konsole::SessionController::focused, this, + &Konsole::TabbedViewContainer::currentSessionControllerChanged); + + disconnect(item, &Konsole::ViewProperties::titleChanged, this, + &Konsole::TabbedViewContainer::updateTitle); + + disconnect(item, &Konsole::ViewProperties::iconChanged, this, + &Konsole::TabbedViewContainer::updateIcon); + + disconnect(item, &Konsole::ViewProperties::activity, this, + &Konsole::TabbedViewContainer::updateActivity); } void TabbedViewContainer::viewDestroyed(QObject *view) { - auto widget = static_cast(view); + auto widget = static_cast(view); const auto idx = indexOf(widget); removeTab(idx); forgetView(widget); } -void TabbedViewContainer::forgetView(TerminalDisplay *view) +void TabbedViewContainer::forgetView(ViewSplitter *view) { - updateTabHistory(view, true); - emit viewRemoved(view); + Q_UNUSED(view); if (count() == 0) { emit empty(this); } } void TabbedViewContainer::removeView(TerminalDisplay *view) { - const int idx = indexOf(view); - disconnect(view, &QWidget::destroyed, this, &Konsole::TabbedViewContainer::viewDestroyed); - removeTab(idx); - forgetView(view); + /* TODO: This is absolutely the wrong place. + * We are removing a terminal display from a ViewSplitter, + * this should be inside of the view splitter or something. + */ + view->setParent(nullptr); } void TabbedViewContainer::activateNextView() { QWidget *active = currentWidget(); int index = indexOf(active); setCurrentIndex(index == count() - 1 ? 0 : index + 1); } void TabbedViewContainer::activateLastView() { setCurrentIndex(count() - 1); } void TabbedViewContainer::activatePreviousView() { QWidget *active = currentWidget(); int index = indexOf(active); setCurrentIndex(index == 0 ? count() - 1 : index - 1); } -void TabbedViewContainer::activateLastUsedView(bool reverse) -{ - if (_tabHistory.count() <= 1) { - return; - } - - if (_tabHistoryIndex == -1) { - _tabHistoryIndex = reverse ? _tabHistory.count() - 1 : 1; - } else if (reverse) { - if (_tabHistoryIndex == 0) { - _tabHistoryIndex = _tabHistory.count() - 1; - } else { - _tabHistoryIndex--; - } - } else { - if (_tabHistoryIndex >= _tabHistory.count() - 1) { - _tabHistoryIndex = 0; - } else { - _tabHistoryIndex++; - } - } - - int index = indexOf(_tabHistory[_tabHistoryIndex]); - setCurrentIndex(index); -} - -// Jump to last view - this allows toggling between two views -// Using "Last Used Tabs" shortcut will cause "Toggle between two tabs" -// shortcut to be incorrect the first time. -void TabbedViewContainer::toggleLastUsedView() -{ - if (_tabHistory.count() <= 1) { - return; - } - - setCurrentIndex(indexOf(_tabHistory.at(1))); -} - void TabbedViewContainer::keyReleaseEvent(QKeyEvent* event) { - if (_tabHistoryIndex != -1 && event->modifiers() == Qt::NoModifier) { - _tabHistoryIndex = -1; - auto *active = qobject_cast(currentWidget()); - if (active != _tabHistory[0]) { - // Update the tab history now that we have ended the walk-through - updateTabHistory(active); - } - } -} - -void TabbedViewContainer::updateTabHistory(TerminalDisplay* view, bool remove) -{ - if (_tabHistoryIndex != -1 && !remove) { - // Do not reorder the tab history while we are walking through it - return; - } - - for (int i = 0; i < _tabHistory.count(); ++i ) { - if (_tabHistory[i] == view) { - _tabHistory.removeAt(i); - if (!remove) { - _tabHistory.prepend(view); - } - break; - } + if (event->modifiers() == Qt::NoModifier) { + _connectedViewManager->updateTerminalDisplayHistory(); } } void TabbedViewContainer::closeCurrentTab() { if (currentIndex() != -1) { closeTerminalTab(currentIndex()); } } void TabbedViewContainer::tabDoubleClicked(int index) { if (index >= 0) { renameTab(index); } else { - emit newViewRequest(this); + emit newViewRequest(); } } void TabbedViewContainer::renameTab(int index) { if (index != -1) { - terminalAt(index)->sessionController()->rename(); + setCurrentIndex(index); + viewSplitterAt(index) + -> activeTerminalDisplay() + -> sessionController() + -> rename(); } } void TabbedViewContainer::openTabContextMenu(const QPoint &point) { if (point.isNull()) { return; } _contextMenuTabIndex = tabBar()->tabAt(point); if (_contextMenuTabIndex < 0) { return; } //TODO: add a countChanged signal so we can remove this for. // Detaching in mac causes crashes. #if defined(ENABLE_DETACHING) for(auto action : _contextPopupMenu->actions()) { if (action->objectName() == QStringLiteral("tab-detach")) { action->setEnabled(count() > 1); } } #endif + /* This needs to nove away fro the tab or to lock every thing inside of it. + * for now, disable. + * */ + // // Add the read-only action - auto controller = terminalAt(_contextMenuTabIndex)->sessionController(); - auto sessionController = qobject_cast(controller); +#if 0 + auto sessionController = terminalAt(_contextMenuTabIndex)->sessionController(); if (sessionController != nullptr) { auto collection = sessionController->actionCollection(); auto readonlyAction = collection->action(QStringLiteral("view-readonly")); if (readonlyAction != nullptr) { const auto readonlyActions = _contextPopupMenu->actions(); _contextPopupMenu->insertAction(readonlyActions.last(), readonlyAction); } // Disable tab rename for (auto &action : _contextPopupMenu->actions()) { if (action->objectName() == QStringLiteral("edit-rename")) { action->setEnabled(!sessionController->isReadOnly()); break; } } } - +#endif _contextPopupMenu->exec(tabBar()->mapToGlobal(point)); } void TabbedViewContainer::currentTabChanged(int index) { if (index != -1) { - auto *view = terminalAt(index); - view->setFocus(); - updateTabHistory(view); + auto splitview = qobject_cast(widget(index)); + auto view = splitview->activeTerminalDisplay(); emit activeViewChanged(view); setTabActivity(index, false); } else { deleteLater(); } } void TabbedViewContainer::wheelScrolled(int delta) { if (delta < 0) { activateNextView(); } else { activatePreviousView(); } } void TabbedViewContainer::setTabActivity(int index, bool activity) { const QPalette &palette = tabBar()->palette(); KColorScheme colorScheme(palette.currentColorGroup()); const QColor colorSchemeActive = colorScheme.foreground(KColorScheme::ActiveText).color(); const QColor normalColor = palette.text().color(); const QColor activityColor = KColorUtils::mix(normalColor, colorSchemeActive); QColor color = activity ? activityColor : QColor(); if (color != tabBar()->tabTextColor(index)) { tabBar()->setTabTextColor(index, color); } } void TabbedViewContainer::updateActivity(ViewProperties *item) { auto controller = qobject_cast(item); auto index = indexOf(controller->view()); if (index != currentIndex()) { setTabActivity(index, true); } } +void TabbedViewContainer::currentSessionControllerChanged(SessionController *controller) +{ + updateTitle(qobject_cast(controller)); +} + void TabbedViewContainer::updateTitle(ViewProperties *item) { auto controller = qobject_cast(item); + auto topLevelSplitter = qobject_cast(controller->view()->parentWidget())->getToplevelSplitter(); - const int index = indexOf(controller->view()); + const int index = indexOf(topLevelSplitter); QString tabText = item->title(); setTabToolTip(index, tabText); // To avoid having & replaced with _ (shortcut indicator) tabText.replace(QLatin1Char('&'), QLatin1String("&&")); setTabText(index, tabText); } void TabbedViewContainer::updateIcon(ViewProperties *item) { auto controller = qobject_cast(item); const int index = indexOf(controller->view()); setTabIcon(index, item->icon()); } void TabbedViewContainer::closeTerminalTab(int idx) { - terminalAt(idx)->sessionController()->closeSession(); + //TODO: This for should probably go to the ViewSplitter + for (auto terminal : viewSplitterAt(idx)->findChildren()) { + terminal->sessionController()->closeSession(); + } } ViewManager *TabbedViewContainer::connectedViewManager() { return _connectedViewManager; } void TabbedViewContainer::setNavigationVisibility(ViewManager::NavigationVisibility navigationVisibility) { if (navigationVisibility == ViewManager::NavigationNotSet) { return; } setTabBarAutoHide(navigationVisibility == ViewManager::ShowNavigationAsNeeded); if (navigationVisibility == ViewManager::AlwaysShowNavigation) { tabBar()->setVisible(true); } else if (navigationVisibility == ViewManager::AlwaysHideNavigation) { tabBar()->setVisible(false); } } + +void TabbedViewContainer::maximizeCurrentTerminal() +{ + activeViewSplitter()->maximizeCurrentTerminal(); +} + +void TabbedViewContainer::restoreOtherTerminals() +{ + activeViewSplitter()->restoreOtherTerminals(); +} diff --git a/src/ViewContainer.h b/src/ViewContainer.h index cec7b000..420314be 100644 --- a/src/ViewContainer.h +++ b/src/ViewContainer.h @@ -1,216 +1,211 @@ /* This file is part of the Konsole Terminal. Copyright 2006-2008 Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef VIEWCONTAINER_H #define VIEWCONTAINER_H // Qt #include #include #include // Konsole #include "Profile.h" #include "ViewManager.h" // Qt class QPoint; class QToolButton; class QMenu; class QDropEvent; class QDragEnterEvent; namespace Konsole { class IncrementalSearchBar; class ViewProperties; class ViewManager; class TabbedViewContainer; /** * An interface for container widgets which can hold one or more views. * * The container widget typically displays a list of the views which * it has and provides a means of switching between them. * * Subclasses should reimplement the addViewWidget() and removeViewWidget() functions * to actually add or remove view widgets from the container widget, as well * as updating any navigation aids. */ class KONSOLEPRIVATE_EXPORT TabbedViewContainer : public QTabWidget { Q_OBJECT public: /** * Constructs a new view container with the specified parent. * * @param connectedViewManager Connect the new view to this manager * @param parent The parent object of the container */ TabbedViewContainer(ViewManager *connectedViewManager, QWidget *parent); /** * Called when the ViewContainer is destroyed. When reimplementing this in * subclasses, use object->deleteLater() to delete any widgets or other objects * instead of 'delete object'. */ ~TabbedViewContainer() Q_DECL_OVERRIDE; /** Adds a new view to the container widget */ void addView(TerminalDisplay *view, int index = -1); + void addSplitter(ViewSplitter *splitter, int index = -1); + + /** splits the currently focused Splitter */ + void splitView(TerminalDisplay *view, Qt::Orientation orientation); /** Removes a view from the container */ void removeView(TerminalDisplay *view); void setTabActivity(int index, bool activity); void updateTitle(ViewProperties *item); void updateIcon(ViewProperties *item); void updateActivity(ViewProperties *item); /** Changes the active view to the next view */ void activateNextView(); /** Changes the active view to the previous view */ void activatePreviousView(); /** Changes the active view to the last view */ void activateLastView(); - /** Changes the active view to the last used view */ - void activateLastUsedView(bool reverse); - - /** Toggle between last two views */ - void toggleLastUsedView(); - void setCss(const QString& styleSheet = QString()); void setCssFromFile(const QUrl& url); + + ViewSplitter *activeViewSplitter(); /** * This enum describes the directions * in which views can be re-arranged within the container * using the moveActiveView() method. */ enum MoveDirection { /** Moves the view to the left. */ MoveViewLeft, /** Moves the view to the right. */ MoveViewRight }; /** * Moves the active view within the container and * updates the order in which the views are shown * in the container's navigation widget. * * The default implementation does nothing. */ void moveActiveView(MoveDirection direction); /** Sets the menu to be shown when the new view button is clicked. * Only valid if the QuickNewView feature is enabled. * The default implementation does nothing. */ // TODO: Reenable this later. // void setNewViewMenu(QMenu *menu); void renameTab(int index); ViewManager *connectedViewManager(); void currentTabChanged(int index); void closeCurrentTab(); void wheelScrolled(int delta); - + void currentSessionControllerChanged(SessionController *controller); void tabDoubleClicked(int index); void openTabContextMenu(const QPoint &point); void setNavigationVisibility(ViewManager::NavigationVisibility navigationVisibility); void moveTabToWindow(int index, QWidget *window); + void maximizeCurrentTerminal(); + void restoreOtherTerminals(); /* return the widget(int index) casted to TerminalDisplay* * * The only thing that this class holds are TerminalDisplays, so * this is the only thing that should be used to retrieve widgets. */ - TerminalDisplay *terminalAt(int index); + ViewSplitter *viewSplitterAt(int index); + + void connectTerminalDisplay(TerminalDisplay *view); + void disconnectTerminalDisplay(TerminalDisplay *view); + Q_SIGNALS: /** Emitted when the container has no more children */ void empty(TabbedViewContainer *container); /** Emitted when the user requests to open a new view */ - void newViewRequest(TabbedViewContainer *thisContainer); + void newViewRequest(); /** Requests creation of a new view, with the selected profile. */ - void newViewWithProfileRequest(TabbedViewContainer *thisContainer, const Profile::Ptr&); + void newViewWithProfileRequest(const Profile::Ptr&); /** * Emitted when the user requests to move a view from another container * into this container. If 'success' is set to true by a connected slot * then the original view will be removed. * * @param index Index at which to insert the new view in the container * or -1 to append it. This index should be passed to addView() when * the new view has been created. * @param sessionControllerId The identifier of the view. */ void moveViewRequest(int index, int sessionControllerId); /** Emitted when the active view changes */ void activeViewChanged(TerminalDisplay *view); /** Emitted when a view is added to the container. */ void viewAdded(TerminalDisplay *view); /** Emitted when a view is removed from the container. */ void viewRemoved(TerminalDisplay *view); /** detach the specific tab */ - void detachTab(TabbedViewContainer *self, TerminalDisplay *activeView); + void detachTab(int tabIdx); protected: - /** - * Rearranges the order of widgets in the container. - * - * @param fromIndex Current index of the widget to move - * @param toIndex New index for the widget - */ - void moveViewWidget(int fromIndex, int toIndex); - // close tabs and unregister void closeTerminalTab(int idx); void keyReleaseEvent(QKeyEvent *event) Q_DECL_OVERRIDE; private Q_SLOTS: void viewDestroyed(QObject *view); void konsoleConfigChanged(); private: - void forgetView(TerminalDisplay *view); - void updateTabHistory(TerminalDisplay *view, bool remove = false); + void forgetView(ViewSplitter *view); - QList _tabHistory; ViewManager *_connectedViewManager; QMenu *_contextPopupMenu; QToolButton *_newTabButton; QToolButton *_closeTabButton; int _contextMenuTabIndex; ViewManager::NavigationVisibility _navigationVisibility; - int _tabHistoryIndex; }; } #endif //VIEWCONTAINER_H diff --git a/src/ViewManager.cpp b/src/ViewManager.cpp index 2f67bf39..69a3b2f1 100644 --- a/src/ViewManager.cpp +++ b/src/ViewManager.cpp @@ -1,1082 +1,1105 @@ /* Copyright 2006-2008 by Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ // Own #include "ViewManager.h" #include // Qt #include -#include #include // KDE #include #include #include #include // Konsole #include #include "ColorScheme.h" #include "ColorSchemeManager.h" #include "Session.h" #include "TerminalDisplay.h" #include "SessionController.h" #include "SessionManager.h" #include "ProfileManager.h" #include "ViewSplitter.h" #include "Enumeration.h" #include "ViewContainer.h" using namespace Konsole; int ViewManager::lastManagerId = 0; ViewManager::ViewManager(QObject *parent, KActionCollection *collection) : QObject(parent), - _viewSplitter(nullptr), + _viewContainer(nullptr), _pluggedController(nullptr), _sessionMap(QHash()), _actionCollection(collection), _navigationMethod(NoNavigation), _navigationVisibility(NavigationNotSet), _newTabBehavior(PutNewTabAtTheEnd), - _managerId(0) + _managerId(0), + _terminalDisplayHistoryIndex(-1) { - // create main view area - _viewSplitter = new ViewSplitter(nullptr); - KAcceleratorManager::setNoAccel(_viewSplitter); - - // the ViewSplitter class supports both recursive and non-recursive splitting, - // in non-recursive mode, all containers are inserted into the same top-level splitter - // widget, and all the divider lines between the containers have the same orientation - // - // the ViewManager class is not currently able to handle a ViewSplitter in recursive-splitting - // mode - _viewSplitter->setRecursiveSplitting(false); - _viewSplitter->setFocusPolicy(Qt::NoFocus); - + _viewContainer = createContainer(); // setup actions which are related to the views setupActions(); + /* TODO: Reconnect // emit a signal when all of the views held by this view manager are destroyed - connect(_viewSplitter.data(), &Konsole::ViewSplitter::allContainersEmpty, + */ + connect(_viewContainer.data(), &Konsole::TabbedViewContainer::empty, this, &Konsole::ViewManager::empty); - connect(_viewSplitter.data(), &Konsole::ViewSplitter::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); //prepare DBus communication new WindowAdaptor(this); _managerId = ++lastManagerId; QDBusConnection::sessionBus().registerObject(QLatin1String("/Windows/") + QString::number(_managerId), this); - - _viewSplitter->addContainer(createContainer(), Qt::Vertical); } ViewManager::~ViewManager() = default; int ViewManager::managerId() const { return _managerId; } QWidget *ViewManager::activeView() const { - TabbedViewContainer *container = _viewSplitter->activeContainer(); - if (container != nullptr) { - return container->currentWidget(); - } else { - return nullptr; - } + return _viewContainer->currentWidget(); } QWidget *ViewManager::widget() const { - return _viewSplitter; + return _viewContainer; } void ViewManager::setupActions() { Q_ASSERT(_actionCollection); if (_actionCollection == nullptr) { return; } KActionCollection *collection = _actionCollection; - QAction *nextViewAction = new QAction(i18nc("@action Shortcut entry", "Next Tab"), this); - QAction *previousViewAction = new QAction(i18nc("@action Shortcut entry", "Previous Tab"), this); - QAction *lastViewAction = new QAction(i18nc("@action Shortcut entry", - "Switch to Last Tab"), this); - QAction *lastUsedViewAction = new QAction(i18nc("@action Shortcut entry", "Last Used Tabs"), this); - QAction *lastUsedViewReverseAction = new QAction(i18nc("@action Shortcut entry", - "Last Used Tabs (Reverse)"), this); - QAction *toggleTwoViewsAction = new QAction(i18nc("@action Shortcut entry", "Toggle Between Two Tabs"), this); - QAction *nextContainerAction = new QAction(i18nc("@action Shortcut entry", - "Next View Container"), this); - - QAction *moveViewLeftAction = new QAction(i18nc("@action Shortcut entry", "Move Tab Left"), this); - QAction *moveViewRightAction = new QAction(i18nc("@action Shortcut entry", - "Move Tab Right"), this); - - // list of actions that should only be enabled when there are multiple view - // containers open - QList multiViewOnlyActions; - multiViewOnlyActions << nextContainerAction; - - QAction *splitLeftRightAction = new QAction(QIcon::fromTheme(QStringLiteral("view-split-left-right")), - i18nc("@action:inmenu", "Split View Left/Right"), - this); - collection->setDefaultShortcut(splitLeftRightAction, Konsole::ACCEL + Qt::Key_ParenLeft); - collection->addAction(QStringLiteral("split-view-left-right"), splitLeftRightAction); - connect(splitLeftRightAction, &QAction::triggered, this, &Konsole::ViewManager::splitLeftRight); - - QAction *splitTopBottomAction = new QAction(QIcon::fromTheme(QStringLiteral("view-split-top-bottom")), - i18nc("@action:inmenu", - "Split View Top/Bottom"), this); - collection->setDefaultShortcut(splitTopBottomAction, Konsole::ACCEL + Qt::Key_ParenRight); - collection->addAction(QStringLiteral("split-view-top-bottom"), splitTopBottomAction); - connect(splitTopBottomAction, &QAction::triggered, this, &Konsole::ViewManager::splitTopBottom); - - QAction *closeActiveAction = new QAction(i18nc("@action:inmenu Close Active View", "Close Active"), this); - closeActiveAction->setIcon(QIcon::fromTheme(QStringLiteral("view-close"))); - collection->setDefaultShortcut(closeActiveAction, Konsole::ACCEL + Qt::SHIFT + Qt::Key_X); - closeActiveAction->setEnabled(false); - collection->addAction(QStringLiteral("close-active-view"), closeActiveAction); - connect(closeActiveAction, &QAction::triggered, this, - &Konsole::ViewManager::closeActiveContainer); - - multiViewOnlyActions << closeActiveAction; - - QAction *closeOtherAction = new QAction(i18nc("@action:inmenu Close Other Views", - "Close Others"), this); - collection->setDefaultShortcut(closeOtherAction, Konsole::ACCEL + Qt::SHIFT + Qt::Key_O); - closeOtherAction->setEnabled(false); - collection->addAction(QStringLiteral("close-other-views"), closeOtherAction); - connect(closeOtherAction, &QAction::triggered, this, - &Konsole::ViewManager::closeOtherContainers); - - multiViewOnlyActions << closeOtherAction; - - // Expand & Shrink Active View - QAction *expandActiveAction = new QAction(i18nc("@action:inmenu", "Expand View"), this); - collection->setDefaultShortcut(expandActiveAction, - Konsole::ACCEL + Qt::SHIFT + Qt::Key_BracketRight); - expandActiveAction->setEnabled(false); - collection->addAction(QStringLiteral("expand-active-view"), expandActiveAction); - connect(expandActiveAction, &QAction::triggered, this, - &Konsole::ViewManager::expandActiveContainer); - - multiViewOnlyActions << expandActiveAction; - - QAction *shrinkActiveAction = new QAction(i18nc("@action:inmenu", "Shrink View"), this); - collection->setDefaultShortcut(shrinkActiveAction, - Konsole::ACCEL + Qt::SHIFT + Qt::Key_BracketLeft); - shrinkActiveAction->setEnabled(false); - collection->addAction(QStringLiteral("shrink-active-view"), shrinkActiveAction); - connect(shrinkActiveAction, &QAction::triggered, this, - &Konsole::ViewManager::shrinkActiveContainer); - - multiViewOnlyActions << shrinkActiveAction; + // Let's reuse the pointer, no need not to. + auto *action = new QAction(); + action->setIcon(QIcon::fromTheme(QStringLiteral("view-split-left-right"))); + action->setText(i18nc("@action:inmenu", "Split View Left/Right")); + connect(action, &QAction::triggered, this, &ViewManager::splitLeftRight); + collection->addAction(QStringLiteral("split-view-left-right"), action); + collection->setDefaultShortcut(action, Konsole::ACCEL + Qt::Key_ParenLeft); + + action = new QAction(); + action->setIcon(QIcon::fromTheme(QStringLiteral("view-split-top-bottom"))); + action->setText(i18nc("@action:inmenu", "Split View Top/Bottom")); + connect(action, &QAction::triggered, this, &ViewManager::splitTopBottom); + collection->setDefaultShortcut(action, Konsole::ACCEL + Qt::Key_ParenRight); + collection->addAction(QStringLiteral("split-view-top-bottom"), action); + + action = new QAction(); + action->setText(i18nc("@action:inmenu", "Expand View")); + action->setEnabled(false); + connect(action, &QAction::triggered, this, &ViewManager::expandActiveContainer); + collection->setDefaultShortcut(action, Konsole::ACCEL + Qt::SHIFT + Qt::Key_BracketRight); + collection->addAction(QStringLiteral("expand-active-view"), action); + _multiSplitterOnlyActions << action; + + action = new QAction(); + action->setText(i18nc("@action:inmenu", "Shrink View")); + collection->setDefaultShortcut(action, Konsole::ACCEL + Qt::SHIFT + Qt::Key_BracketLeft); + action->setEnabled(false); + collection->addAction(QStringLiteral("shrink-active-view"), action); + connect(action, &QAction::triggered, this, &ViewManager::shrinkActiveContainer); + _multiSplitterOnlyActions << action; // Crashes on Mac. #if defined(ENABLE_DETACHING) - QAction *detachViewAction = collection->addAction(QStringLiteral("detach-view")); - detachViewAction->setEnabled(true); - detachViewAction->setIcon(QIcon::fromTheme(QStringLiteral("tab-detach"))); - detachViewAction->setText(i18nc("@action:inmenu", "D&etach Current Tab")); + action = collection->addAction(QStringLiteral("detach-view")); + action->setEnabled(true); + action->setIcon(QIcon::fromTheme(QStringLiteral("tab-detach"))); + action->setText(i18nc("@action:inmenu", "Detach Current &View")); + + connect(action, &QAction::triggered, this, &ViewManager::detachActiveView); + _multiSplitterOnlyActions << action; + // Ctrl+Shift+D is not used as a shortcut by default because it is too close // to Ctrl+D - which will terminate the session in many cases - collection->setDefaultShortcut(detachViewAction, Konsole::ACCEL + Qt::SHIFT + Qt::Key_H); - - connect(this, &Konsole::ViewManager::splitViewToggle, this, - &Konsole::ViewManager::updateDetachViewState); - connect(detachViewAction, &QAction::triggered, this, &Konsole::ViewManager::detachActiveView); + collection->setDefaultShortcut(action, Konsole::ACCEL + Qt::SHIFT + Qt::Key_H); + + action = collection->addAction(QStringLiteral("detach-tab")); + action->setEnabled(true); + action->setIcon(QIcon::fromTheme(QStringLiteral("tab-detach"))); + action->setText(i18nc("@action:inmenu", "Detach Current &Tab")); + connect(action, &QAction::triggered, this, &ViewManager::detachActiveTab); + _multiTabOnlyActions << action; + // Ctrl+Shift+D is not used as a shortcut by default because it is too close + // to Ctrl+D - which will terminate the session in many cases + collection->setDefaultShortcut(action, Konsole::ACCEL + Qt::SHIFT + Qt::Key_L); #endif - // Next / Previous View , Next Container - collection->addAction(QStringLiteral("next-view"), nextViewAction); - collection->addAction(QStringLiteral("previous-view"), previousViewAction); - collection->addAction(QStringLiteral("last-tab"), lastViewAction); - collection->addAction(QStringLiteral("last-used-tab"), lastUsedViewAction); - collection->addAction(QStringLiteral("last-used-tab-reverse"), lastUsedViewReverseAction); - collection->addAction(QStringLiteral("toggle-two-tabs"), toggleTwoViewsAction); - collection->addAction(QStringLiteral("next-container"), nextContainerAction); - collection->addAction(QStringLiteral("move-view-left"), moveViewLeftAction); - collection->addAction(QStringLiteral("move-view-right"), moveViewRightAction); - - // Switch to tab N shortcuts - const int SWITCH_TO_TAB_COUNT = 19; - for (int i = 0; i < SWITCH_TO_TAB_COUNT; i++) { - QAction *switchToTabAction = new QAction(i18nc("@action Shortcut entry", "Switch to Tab %1", i + 1), this); - - connect(switchToTabAction, &QAction::triggered, this, - [this, i]() { - switchToView(i); - }); - collection->addAction(QStringLiteral("switch-to-tab-%1").arg(i), switchToTabAction); - } - - foreach (QAction *action, multiViewOnlyActions) { - connect(this, &Konsole::ViewManager::splitViewToggle, action, &QAction::setEnabled); - } - // keyboard shortcut only actions + action = new QAction(i18nc("@action Shortcut entry", "Next Tab"), this); const QList nextViewActionKeys{Qt::SHIFT + Qt::Key_Right, Qt::CTRL + Qt::Key_PageDown}; - collection->setDefaultShortcuts(nextViewAction, nextViewActionKeys); - connect(nextViewAction, &QAction::triggered, this, &Konsole::ViewManager::nextView); - _viewSplitter->addAction(nextViewAction); + collection->setDefaultShortcuts(action, nextViewActionKeys); + collection->addAction(QStringLiteral("next-tab"), action); + connect(action, &QAction::triggered, this, &ViewManager::nextView); + _multiTabOnlyActions << action; + // _viewSplitter->addAction(nextViewAction); + action = new QAction(i18nc("@action Shortcut entry", "Previous Tab"), this); const QList previousViewActionKeys{Qt::SHIFT + Qt::Key_Left, Qt::CTRL + Qt::Key_PageUp}; - collection->setDefaultShortcuts(previousViewAction, previousViewActionKeys); - connect(previousViewAction, &QAction::triggered, this, &Konsole::ViewManager::previousView); - _viewSplitter->addAction(previousViewAction); - - collection->setDefaultShortcut(nextContainerAction, Qt::SHIFT + Qt::Key_Tab); - connect(nextContainerAction, &QAction::triggered, this, &Konsole::ViewManager::nextContainer); - _viewSplitter->addAction(nextContainerAction); - -#ifdef Q_OS_MACOS - collection->setDefaultShortcut(moveViewLeftAction, - Konsole::ACCEL + Qt::SHIFT + Qt::Key_BracketLeft); -#else - collection->setDefaultShortcut(moveViewLeftAction, Konsole::ACCEL + Qt::SHIFT + Qt::Key_Left); -#endif - connect(moveViewLeftAction, &QAction::triggered, this, - &Konsole::ViewManager::moveActiveViewLeft); - _viewSplitter->addAction(moveViewLeftAction); - -#ifdef Q_OS_MACOS - collection->setDefaultShortcut(moveViewRightAction, - Konsole::ACCEL + Qt::SHIFT + Qt::Key_BracketRight); -#else - collection->setDefaultShortcut(moveViewRightAction, Konsole::ACCEL + Qt::SHIFT + Qt::Key_Right); -#endif - connect(moveViewRightAction, &QAction::triggered, this, - &Konsole::ViewManager::moveActiveViewRight); - _viewSplitter->addAction(moveViewRightAction); - - connect(lastViewAction, &QAction::triggered, this, &Konsole::ViewManager::lastView); - _viewSplitter->addAction(lastViewAction); + collection->setDefaultShortcuts(action, previousViewActionKeys); + collection->addAction(QStringLiteral("previous-tab"), action); + connect(action, &QAction::triggered, this, &ViewManager::previousView); + _multiTabOnlyActions << action; + // _viewSplitter->addAction(previousViewAction); + + action = new QAction(i18nc("@action Shortcut entry", "Next View Container"), this); + connect(action, &QAction::triggered, this, &ViewManager::focusUp); + collection->addAction(QStringLiteral("next-container"), action); + collection->setDefaultShortcut(action, Qt::SHIFT + Qt::CTRL + Qt::Key_Up); + _viewContainer->addAction(action); + _multiSplitterOnlyActions << action; + + action = new QAction(QStringLiteral("Focus Down")); + collection->setDefaultShortcut(action, Qt::SHIFT + Qt::CTRL + Qt::Key_Down); + connect(action, &QAction::triggered, this, &ViewManager::focusDown); + _multiSplitterOnlyActions << action; + _viewContainer->addAction(action); + + action = new QAction(i18nc("@action Shortcut entry", "Move Tab Left"), this); + collection->setDefaultShortcut(action, Konsole::ACCEL + Qt::SHIFT + Konsole::LEFT); + connect(action, &QAction::triggered, this, &ViewManager::focusLeft); + collection->addAction(QStringLiteral("move-view-left"), action); + _multiSplitterOnlyActions << action; + + action = new QAction(i18nc("@action Shortcut entry", "Move Tab Right"), this); + collection->setDefaultShortcut(action, Konsole::ACCEL + Qt::SHIFT + Konsole::RIGHT); + connect(action, &QAction::triggered, this, &ViewManager::focusRight); + collection->addAction(QStringLiteral("move-view-right"), action); + _multiSplitterOnlyActions << action; + + action = new QAction(i18nc("@action Shortcut entry", "Switch to Last Tab"), this); + connect(action, &QAction::triggered, this, &ViewManager::lastView); + collection->addAction(QStringLiteral("last-tab"), action); + _multiTabOnlyActions << action; + + action = new QAction(i18nc("@action Shortcut entry", "Last Used Tabs"), this); + connect(action, &QAction::triggered, this, &ViewManager::lastUsedView); + collection->setDefaultShortcut(action, Qt::CTRL + Qt::Key_Tab); + collection->addAction(QStringLiteral("last-used-tab"), action); + _multiTabOnlyActions << action; + + action = new QAction(i18nc("@action Shortcut entry", "Toggle Between Two Tabs"), this); + connect(action, &QAction::triggered, this, &Konsole::ViewManager::toggleTwoViews); + collection->addAction(QStringLiteral("toggle-two-tabs"), action); + _multiTabOnlyActions << action; + + action = new QAction(i18nc("@action Shortcut entry", "Last Used Tabs (Reverse)"), this); + collection->addAction(QStringLiteral("last-used-tab-reverse"), action); + collection->setDefaultShortcut(action, Qt::CTRL + Qt::SHIFT + Qt::Key_Tab); + connect(action, &QAction::triggered, this, &ViewManager::lastUsedViewReverse); + _multiTabOnlyActions << action; + + action = new QAction(i18nc("@action Shortcut entry", "Maximize current Terminal"), this); + collection->addAction(QStringLiteral("maximize-current-terminal"), action); + collection->setDefaultShortcut(action, Qt::CTRL + Qt::SHIFT + Qt::Key_E); + connect(action, &QAction::triggered, _viewContainer, &TabbedViewContainer::maximizeCurrentTerminal); + _multiSplitterOnlyActions << action; + _viewContainer->addAction(action); + + action = new QAction(i18nc("@action Shortcut entry", "Restore other terminals"), this); + collection->addAction(QStringLiteral("restore-other-terminals"), action); + collection->setDefaultShortcut(action, Qt::CTRL + Qt::SHIFT + Qt::Key_Minus); + connect(action, &QAction::triggered, _viewContainer, &TabbedViewContainer::restoreOtherTerminals); + _multiSplitterOnlyActions << action; + _viewContainer->addAction(action); + + // _viewSplitter->addAction(lastUsedViewReverseAction); + 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); }); + collection->addAction(QStringLiteral("switch-to-tab-%1").arg(i), action); + } - collection->setDefaultShortcut(lastUsedViewAction, Qt::CTRL + Qt::Key_Tab); - connect(lastUsedViewAction, &QAction::triggered, this, &Konsole::ViewManager::lastUsedView); - _viewSplitter->addAction(lastUsedViewAction); + auto handleMultiTabActionsLambda = [=]{ + const int count = _viewContainer->count(); + foreach(QAction *action, _multiTabOnlyActions) { + action->setEnabled(count > 1); + } + }; + connect(_viewContainer, &TabbedViewContainer::viewAdded, this, handleMultiTabActionsLambda); + connect(_viewContainer, &TabbedViewContainer::viewRemoved, this, handleMultiTabActionsLambda); - collection->setDefaultShortcut(lastUsedViewReverseAction, Qt::CTRL + Qt::SHIFT + Qt::Key_Tab); - connect(lastUsedViewReverseAction, &QAction::triggered, this, &Konsole::ViewManager::lastUsedViewReverse); - _viewSplitter->addAction(lastUsedViewReverseAction); + connect(_viewContainer, &QTabWidget::currentChanged, this, &ViewManager::updateDetachViewState); - connect(toggleTwoViewsAction, &QAction::triggered, this, &Konsole::ViewManager::toggleTwoViews); - _viewSplitter->addAction(toggleTwoViewsAction); + // Initial state + handleMultiTabActionsLambda(); + updateDetachViewState(); } void ViewManager::switchToView(int index) { - _viewSplitter->activeContainer()->setCurrentIndex(index); + _viewContainer->setCurrentIndex(index); +} + +void ViewManager::switchToTerminalDisplay(Konsole::TerminalDisplay* terminalDisplay) +{ + auto splitter = qobject_cast(terminalDisplay->parentWidget()); + auto toplevelSplitter = splitter->getToplevelSplitter(); + + // Focus the TermialDisplay + terminalDisplay->setFocus(); + + if (_viewContainer->currentWidget() != toplevelSplitter) { + // Focus the tab + switchToView(_viewContainer->indexOf(toplevelSplitter)); + } } void ViewManager::updateDetachViewState() { - Q_ASSERT(_actionCollection); - if (_actionCollection == nullptr) { - return; + if (_viewContainer && _viewContainer->activeViewSplitter()) { + const int splitCount = _viewContainer + ->activeViewSplitter() + ->getToplevelSplitter() + ->findChildren() + .count(); + + foreach (QAction *action, _multiSplitterOnlyActions) { + action->setEnabled(splitCount > 1); + } } +} + +void ViewManager::focusUp() +{ + _viewContainer->activeViewSplitter()->focusUp(); +} - const bool splitView = _viewSplitter->containers().count() >= 2; - auto activeContainer = _viewSplitter->activeContainer(); - const bool shouldEnable = splitView - || ((activeContainer != nullptr) - && activeContainer->count() >= 2); +void ViewManager::focusDown() +{ + _viewContainer->activeViewSplitter()->focusDown(); +} - QAction *detachAction = _actionCollection->action(QStringLiteral("detach-view")); +void ViewManager::focusLeft() +{ + _viewContainer->activeViewSplitter()->focusLeft(); +} - if ((detachAction != nullptr) && shouldEnable != detachAction->isEnabled()) { - detachAction->setEnabled(shouldEnable); - } +void ViewManager::focusRight() +{ + _viewContainer->activeViewSplitter()->focusRight(); } void ViewManager::moveActiveViewLeft() { - TabbedViewContainer *container = _viewSplitter->activeContainer(); - Q_ASSERT(container); - container->moveActiveView(TabbedViewContainer::MoveViewLeft); + _viewContainer->moveActiveView(TabbedViewContainer::MoveViewLeft); } void ViewManager::moveActiveViewRight() { - TabbedViewContainer *container = _viewSplitter->activeContainer(); - Q_ASSERT(container); - container->moveActiveView(TabbedViewContainer::MoveViewRight); + _viewContainer->moveActiveView(TabbedViewContainer::MoveViewRight); } void ViewManager::nextContainer() { - _viewSplitter->activateNextContainer(); +// _viewSplitter->activateNextContainer(); } void ViewManager::nextView() { - TabbedViewContainer *container = _viewSplitter->activeContainer(); - Q_ASSERT(container); - container->activateNextView(); + _viewContainer->activateNextView(); } void ViewManager::previousView() { - TabbedViewContainer *container = _viewSplitter->activeContainer(); - Q_ASSERT(container); - container->activatePreviousView(); + _viewContainer->activatePreviousView(); } void ViewManager::lastView() { - TabbedViewContainer *container = _viewSplitter->activeContainer(); - Q_ASSERT(container); - container->activateLastView(); + _viewContainer->activateLastView(); +} + +void ViewManager::activateLastUsedView(bool reverse) +{ + if (_terminalDisplayHistory.count() <= 1) { + return; + } + + if (_terminalDisplayHistoryIndex == -1) { + _terminalDisplayHistoryIndex = reverse ? _terminalDisplayHistory.count() - 1 : 1; + } else if (reverse) { + if (_terminalDisplayHistoryIndex == 0) { + _terminalDisplayHistoryIndex = _terminalDisplayHistory.count() - 1; + } else { + _terminalDisplayHistoryIndex--; + } + } else { + if (_terminalDisplayHistoryIndex >= _terminalDisplayHistory.count() - 1) { + _terminalDisplayHistoryIndex = 0; + } else { + _terminalDisplayHistoryIndex++; + } + } + + switchToTerminalDisplay(_terminalDisplayHistory[_terminalDisplayHistoryIndex]); } void ViewManager::lastUsedView() { - TabbedViewContainer *container = _viewSplitter->activeContainer(); - Q_ASSERT(container); - container->activateLastUsedView(false); + activateLastUsedView(false); } void ViewManager::lastUsedViewReverse() { - TabbedViewContainer *container = _viewSplitter->activeContainer(); - Q_ASSERT(container); - container->activateLastUsedView(true); + activateLastUsedView(true); } void ViewManager::toggleTwoViews() { - TabbedViewContainer *container = _viewSplitter->activeContainer(); - Q_ASSERT(container); - container->toggleLastUsedView(); + if (_terminalDisplayHistory.count() <= 1) { + return; + } + + switchToTerminalDisplay(_terminalDisplayHistory.at(1)); } void ViewManager::detachActiveView() { +#if !defined(ENABLE_DETACHING) + return; +#endif // find the currently active view and remove it from its container - TabbedViewContainer *container = _viewSplitter->activeContainer(); - detachView(container, container->currentWidget()); + 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); + emit terminalsDetached(newSplitter, detachedSessions); + focusAnotherTerminal(activeSplitter->getToplevelSplitter()); + updateDetachViewState(); + } } -void ViewManager::detachView(TabbedViewContainer *container, QWidget *view) +void ViewManager::detachActiveTab() +{ + const int currentIdx = _viewContainer->currentIndex(); + detachTab(currentIdx); +} + +void ViewManager::detachTab(int tabIdx) { #if !defined(ENABLE_DETACHING) return; #endif + ViewSplitter* splitter = _viewContainer->viewSplitterAt(tabIdx); + QHash detachedSessions = forgetAll(_viewContainer->viewSplitterAt(tabIdx)); + emit terminalsDetached(splitter, detachedSessions); +} - auto *viewToDetach = qobject_cast(view); - - if (viewToDetach == nullptr) { - return; - } - - // BR390736 - some instances are sending invalid session to viewDetached() - Session *sessionToDetach = _sessionMap[viewToDetach]; - if (sessionToDetach == nullptr) { - return; +QHash ViewManager::forgetAll(ViewSplitter* splitter) { + splitter->setParent(nullptr); + QHash detachedSessions; + foreach(TerminalDisplay* terminal, splitter->findChildren()) { + Session* session = forgetTerminal(terminal); + detachedSessions[terminal] = session; } - emit viewDetached(sessionToDetach); - - _sessionMap.remove(viewToDetach); - - // remove the view from this window - container->removeView(viewToDetach); - viewToDetach->deleteLater(); + return detachedSessions; +} - // if the container from which the view was removed is now empty then it can be deleted, - // unless it is the only container in the window, in which case it is left empty - // so that there is always an active container - if (_viewSplitter->containers().count() > 1 - && container->count() == 0) { - removeContainer(container); +Session* ViewManager::forgetTerminal(TerminalDisplay* terminal) +{ + removeController(terminal->sessionController()); + auto session = _sessionMap.take(terminal); + if (session != nullptr) { + disconnect(session, &Konsole::Session::finished, this, &Konsole::ViewManager::sessionFinished); } + _viewContainer->disconnectTerminalDisplay(terminal); + updateTerminalDisplayHistory(terminal, true); + return session; } void ViewManager::sessionFinished() { // if this slot is called after the view manager's main widget // has been destroyed, do nothing - if (_viewSplitter.isNull()) { + if (_viewContainer.isNull()) { return; } auto *session = qobject_cast(sender()); Q_ASSERT(session); - // close attached views - QList children = _viewSplitter->findChildren(); + auto view = _sessionMap.key(session); + _sessionMap.remove(view); - foreach (TerminalDisplay *view, children) { - if (_sessionMap[view] == session) { - _sessionMap.remove(view); - view->deleteLater(); - } - } + // Before deleting the view, let's unmaximize if it's maximized. + auto splitter = qobject_cast(view->parentWidget()); + auto toplevelSplitter = splitter->getToplevelSplitter(); + toplevelSplitter->restoreOtherTerminals(); + _viewContainer->removeView(view); + view->deleteLater(); // Only remove the controller from factory() if it's actually controlling // the session from the sender. // This fixes BUG: 348478 - messed up menus after a detached tab is closed if ((!_pluggedController.isNull()) && (_pluggedController->session() == session)) { // This is needed to remove this controller from factory() in // order to prevent BUG: 185466 - disappearing menu popup emit unplugController(_pluggedController); } + + updateTerminalDisplayHistory(view, true); + focusAnotherTerminal(toplevelSplitter); + updateDetachViewState(); +} + +void ViewManager::focusAnotherTerminal(ViewSplitter *toplevelSplitter) +{ + auto tabTterminalDisplays = toplevelSplitter->findChildren(); + if (tabTterminalDisplays.count() > 1) { + // Give focus to the last used terminal in this tab + for (auto *historyItem : _terminalDisplayHistory) { + for (auto *terminalDisplay : tabTterminalDisplays) { + if (terminalDisplay == historyItem) { + terminalDisplay->setFocus(Qt::OtherFocusReason); + return; + } + } + } + } else if (_terminalDisplayHistory.count() >= 1) { + // Give focus to the last used terminal tab + switchToTerminalDisplay(_terminalDisplayHistory[0]); + } } -void ViewManager::viewActivated(QWidget *view) +void ViewManager::viewActivated(TerminalDisplay *view) { Q_ASSERT(view != nullptr); // focus the activated view, this will cause the SessionController // to notify the world that the view has been focused and the appropriate UI // actions will be plugged in. view->setFocus(Qt::OtherFocusReason); } void ViewManager::splitLeftRight() { splitView(Qt::Horizontal); } void ViewManager::splitTopBottom() { splitView(Qt::Vertical); } void ViewManager::splitView(Qt::Orientation orientation) { - TabbedViewContainer *container = createContainer(); + auto viewSplitter = qobject_cast(_viewContainer->currentWidget()); - if (_viewSplitter->activeContainer()->count()) { - // get the currently applied profile and use it to create the new tab. - auto *activeContainer= _viewSplitter->activeContainer(); - auto *currentDisplay = qobject_cast(activeContainer->currentWidget()); - auto profile = SessionManager::instance()->sessionProfile(_sessionMap[currentDisplay]); - - // Create a new session with the selected profile. - auto *session = SessionManager::instance()->createSession(profile); - session->addEnvironmentEntry(QStringLiteral("KONSOLE_DBUS_WINDOW=/Windows/%1").arg(managerId())); - - createView(session, container, 0); - } + // get the currently applied profile and use it to create the new tab. + auto *currentDisplay = viewSplitter->findChild(); + auto profile = SessionManager::instance()->sessionProfile(_sessionMap[currentDisplay]); - _viewSplitter->addContainer(container, orientation); - emit splitViewToggle(_viewSplitter->containers().count() > 0); - - // focus the new container - container->currentWidget()->setFocus(); + // Create a new session with the selected profile. + auto *session = SessionManager::instance()->createSession(profile); + session->addEnvironmentEntry(QStringLiteral("KONSOLE_DBUS_WINDOW=/Windows/%1").arg(managerId())); - // ensure that the active view is focused after the split / unsplit - TabbedViewContainer *activeContainer = _viewSplitter->activeContainer(); - QWidget *activeView = activeContainer != nullptr ? activeContainer->currentWidget() : nullptr; + auto terminalDisplay = createView(session); - if (activeView != nullptr) { - activeView->setFocus(Qt::OtherFocusReason); - } -} + _viewContainer->splitView(terminalDisplay, orientation); -void ViewManager::removeContainer(TabbedViewContainer *container) -{ - // remove session map entries for views in this container - for(int i = 0, end = container->count(); i < end; i++) { - auto view = container->widget(i); - auto *display = qobject_cast(view); - Q_ASSERT(display); - _sessionMap.remove(display); - } - - _viewSplitter->removeContainer(container); - container->deleteLater(); + updateDetachViewState(); - emit splitViewToggle(_viewSplitter->containers().count() > 1); + // focus the new container + terminalDisplay->setFocus(); } void ViewManager::expandActiveContainer() { - _viewSplitter->adjustContainerSize(_viewSplitter->activeContainer(), 10); + _viewContainer->activeViewSplitter()->adjustActiveTerminalDisplaySize(10); } void ViewManager::shrinkActiveContainer() { - _viewSplitter->adjustContainerSize(_viewSplitter->activeContainer(), -10); -} - -void ViewManager::closeActiveContainer() -{ - // only do something if there is more than one container active - if (_viewSplitter->containers().count() > 1) { - TabbedViewContainer *container = _viewSplitter->activeContainer(); - - removeContainer(container); - - // focus next container so that user can continue typing - // without having to manually focus it themselves - nextContainer(); - } -} - -void ViewManager::closeOtherContainers() -{ - TabbedViewContainer *active = _viewSplitter->activeContainer(); - - foreach (TabbedViewContainer *container, _viewSplitter->containers()) { - if (container != active) { - removeContainer(container); - } - } + _viewContainer->activeViewSplitter()->adjustActiveTerminalDisplaySize(-10); } SessionController *ViewManager::createController(Session *session, TerminalDisplay *view) { // 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::focused, 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()) { controllerChanged(controller); } return controller; } +// should this be handed by ViewManager::unplugController signal +void ViewManager::removeController(SessionController* controller) +{ + disconnect(controller, &Konsole::SessionController::focused, this, + &Konsole::ViewManager::controllerChanged); + if (_pluggedController == controller) { + _pluggedController = nullptr; + } + controller->deleteLater(); +} + void ViewManager::controllerChanged(SessionController *controller) { if (controller == _pluggedController) { return; } - _viewSplitter->setFocusProxy(controller->view()); + updateTerminalDisplayHistory(controller->view()); _pluggedController = controller; emit activeViewChanged(controller); } SessionController *ViewManager::activeViewController() const { return _pluggedController; } -void ViewManager::createView(Session *session, TabbedViewContainer *container, int index) +void ViewManager::attachView(TerminalDisplay *terminal, Session *session) +{ + connect(session, &Konsole::Session::finished, this, &Konsole::ViewManager::sessionFinished, + Qt::UniqueConnection); + _sessionMap[terminal] = session; + createController(session, terminal); + updateDetachViewState(); + _terminalDisplayHistory.append(terminal); +} + +TerminalDisplay *ViewManager::createView(Session *session) { // notify this view manager when the session finishes so that its view // can be deleted // // Use Qt::UniqueConnection to avoid duplicate connection connect(session, &Konsole::Session::finished, this, &Konsole::ViewManager::sessionFinished, Qt::UniqueConnection); - TerminalDisplay *display = createTerminalDisplay(session); + const Profile::Ptr profile = SessionManager::instance()->sessionProfile(session); applyProfileToView(display, profile); // set initial size const QSize &preferredSize = session->preferredSize(); display->setSize(preferredSize.width(), preferredSize.height()); createController(session, display); _sessionMap[display] = session; - container->addView(display, index); session->addView(display); + _terminalDisplayHistory.append(display); // tell the session whether it has a light or dark background session->setDarkBackground(colorSchemeForProfile(profile)->hasDarkBackground()); - container->setCurrentWidget(display); display->setFocus(Qt::OtherFocusReason); +// updateDetachViewState(); - updateDetachViewState(); -} - -void ViewManager::createView(TabbedViewContainer *tabWidget, Session *session) -{ - const int index = _newTabBehavior == PutNewTabAfterCurrentTab ? - _viewSplitter->activeContainer()->currentIndex() + 1 : -1; - - createView(session, tabWidget, index); + return display; } TabbedViewContainer *ViewManager::createContainer() { - - auto *container = new TabbedViewContainer(this, _viewSplitter); + auto *container = new TabbedViewContainer(this, nullptr); container->setNavigationVisibility(_navigationVisibility); - //TODO: Fix Detaching. - connect(container, &TabbedViewContainer::detachTab, this, &ViewManager::detachView); + 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, &TabbedViewContainer::newViewRequest, this, &ViewManager::newViewRequest); connect(container, &Konsole::TabbedViewContainer::newViewWithProfileRequest, this, &Konsole::ViewManager::newViewWithProfileRequest); - connect(container, &Konsole::TabbedViewContainer::moveViewRequest, this, - &Konsole::ViewManager::containerMoveViewRequest); connect(container, &Konsole::TabbedViewContainer::viewRemoved, this, &Konsole::ViewManager::viewDestroyed); connect(container, &Konsole::TabbedViewContainer::activeViewChanged, this, &Konsole::ViewManager::viewActivated); return container; } -void ViewManager::containerMoveViewRequest(int index, int id) -{ - auto *container = qobject_cast(sender()); - auto *controller = qobject_cast(ViewProperties::propertiesById(id)); - Q_ASSERT(container); - Q_ASSERT(controller); - - createView(controller->session(), container, index); - controller->session()->refresh(); - container->currentWidget()->setFocus(); -} - void ViewManager::setNavigationMethod(NavigationMethod method) { Q_ASSERT(_actionCollection); if (_actionCollection == nullptr) { return; } KActionCollection *collection = _actionCollection; _navigationMethod = method; // FIXME: The following disables certain actions for the KPart that it // doesn't actually have a use for, to avoid polluting the action/shortcut // namespace of an application using the KPart (otherwise, a shortcut may // be in use twice, and the user gets to see an "ambiguous shortcut over- // load" error dialog). However, this approach sucks - it's the inverse of // what it should be. Rather than disabling actions not used by the KPart, // a method should be devised to only enable those that are used, perhaps // by using a separate action collection. const bool enable = (method != NoNavigation); auto enableAction = [&enable, &collection](const QString& actionName) { auto *action = collection->action(actionName); if (action != nullptr) { action->setEnabled(enable); } }; enableAction(QStringLiteral("next-view")); enableAction(QStringLiteral("previous-view")); enableAction(QStringLiteral("last-tab")); enableAction(QStringLiteral("last-used-tab")); enableAction(QStringLiteral("last-used-tab-reverse")); enableAction(QStringLiteral("split-view-left-right")); enableAction(QStringLiteral("split-view-top-bottom")); enableAction(QStringLiteral("rename-session")); enableAction(QStringLiteral("move-view-left")); enableAction(QStringLiteral("move-view-right")); } ViewManager::NavigationMethod ViewManager::navigationMethod() const { return _navigationMethod; } void ViewManager::containerViewsChanged(TabbedViewContainer *container) { - if ((!_viewSplitter.isNull()) && container == _viewSplitter->activeContainer()) { - emit viewPropertiesChanged(viewProperties()); - } + // TODO: Verify that this is right. + emit viewPropertiesChanged(viewProperties()); } void ViewManager::viewDestroyed(QWidget *view) { // Note: the received QWidget has already been destroyed, so // using dynamic_cast<> or qobject_cast<> does not work here // We only need the pointer address to look it up below auto *display = reinterpret_cast(view); // 1. detach view from session // 2. if the session has no views left, close it Session *session = _sessionMap[ display ]; _sessionMap.remove(display); if (session != nullptr) { if (session->views().count() == 0) { session->close(); } } + //we only update the focus if the splitter is still alive - if (!_viewSplitter.isNull()) { - updateDetachViewState(); - } + updateDetachViewState(); + // The below causes the menus to be messed up // Only happens when using the tab bar close button // if (_pluggedController) // emit unplugController(_pluggedController); } TerminalDisplay *ViewManager::createTerminalDisplay(Session *session) { auto display = new TerminalDisplay(nullptr); display->setRandomSeed(session->sessionId() * 31); return display; } const ColorScheme *ViewManager::colorSchemeForProfile(const Profile::Ptr &profile) { const ColorScheme *colorScheme = ColorSchemeManager::instance()-> findColorScheme(profile->colorScheme()); if (colorScheme == nullptr) { colorScheme = ColorSchemeManager::instance()->defaultColorScheme(); } Q_ASSERT(colorScheme); return colorScheme; } bool ViewManager::profileHasBlurEnabled(const Profile::Ptr &profile) { return colorSchemeForProfile(profile)->blur(); } void ViewManager::applyProfileToView(TerminalDisplay *view, const Profile::Ptr &profile) { Q_ASSERT(profile); view->applyProfile(profile); emit updateWindowIcon(); emit blurSettingChanged(view->colorScheme()->blur()); } void ViewManager::updateViewsForSession(Session *session) { const Profile::Ptr profile = SessionManager::instance()->sessionProfile(session); const QList sessionMapKeys = _sessionMap.keys(session); foreach (TerminalDisplay *view, sessionMapKeys) { applyProfileToView(view, profile); } } void ViewManager::profileChanged(const Profile::Ptr &profile) { // update all views associated with this profile QHashIterator iter(_sessionMap); while (iter.hasNext()) { iter.next(); // if session uses this profile, update the display if (iter.key() != nullptr && iter.value() != nullptr && SessionManager::instance()->sessionProfile(iter.value()) == profile) { applyProfileToView(iter.key(), profile); } } } QList ViewManager::viewProperties() const { QList list; - TabbedViewContainer *container = _viewSplitter->activeContainer(); + TabbedViewContainer *container = _viewContainer; if (container == nullptr) { return {}; } - list.reserve(container->count()); + auto terminalContainers = _viewContainer->findChildren(); + list.reserve(terminalContainers.size()); - for(int i = 0, end = container->count(); i < end; i++) { - auto view = container->terminalAt(i); - ViewProperties *properties = view->sessionController(); - Q_ASSERT(properties); - list << properties; + for(auto terminalDisplay : _viewContainer->findChildren()) { + list.append(terminalDisplay->sessionController()); } return list; } void ViewManager::saveSessions(KConfigGroup &group) { // find all unique session restore IDs QList ids; QSet unique; int tab = 1; - TabbedViewContainer *container = _viewSplitter->activeContainer(); + TabbedViewContainer *container = _viewContainer; // first: sessions in the active container, preserving the order Q_ASSERT(container); if (container == nullptr) { return; } ids.reserve(container->count()); + //TODO: Handle sessions +#if 0 auto *activeview = qobject_cast(container->currentWidget()); for (int i = 0, end = container->count(); i < end; i++) { auto *view = qobject_cast(container->widget(i)); Q_ASSERT(view); Session *session = _sessionMap[view]; ids << SessionManager::instance()->getRestoreId(session); unique.insert(session); if (view == activeview) { group.writeEntry("Active", tab); } tab++; } +#endif // second: all other sessions, in random order // we don't want to have sessions restored that are not connected foreach (Session *session, _sessionMap) { if (!unique.contains(session)) { ids << SessionManager::instance()->getRestoreId(session); unique.insert(session); } } group.writeEntry("Sessions", ids); } TabbedViewContainer *ViewManager::activeContainer() { - return _viewSplitter->activeContainer(); + return _viewContainer; } void ViewManager::restoreSessions(const KConfigGroup &group) { QList ids = group.readEntry("Sessions", QList()); int activeTab = group.readEntry("Active", 0); TerminalDisplay *display = nullptr; int tab = 1; foreach (int id, ids) { Session *session = SessionManager::instance()->idToSession(id); if (session == nullptr) { qWarning() << "Unable to load session with id" << id; // Force a creation of a default session below ids.clear(); break; } - createView(activeContainer(), session); + createView(session); if (!session->isRunning()) { session->run(); } if (tab++ == activeTab) { display = qobject_cast(activeView()); } } if (display != nullptr) { - _viewSplitter->activeContainer()->setCurrentWidget(display); + activeContainer()->setCurrentWidget(display); display->setFocus(Qt::OtherFocusReason); } if (ids.isEmpty()) { // Session file is unusable, start default Profile Profile::Ptr profile = ProfileManager::instance()->defaultProfile(); Session *session = SessionManager::instance()->createSession(profile); - createView(activeContainer(), session); + createView(session); if (!session->isRunning()) { session->run(); } } } int ViewManager::sessionCount() { return _sessionMap.size(); } QStringList ViewManager::sessionList() { QStringList ids; QHash::const_iterator i; for (i = _sessionMap.constBegin(); i != _sessionMap.constEnd(); ++i) { ids.append(QString::number(i.value()->sessionId())); } return ids; } int ViewManager::currentSession() { QHash::const_iterator i; for (i = _sessionMap.constBegin(); i != _sessionMap.constEnd(); ++i) { if (i.key()->isVisible()) { return i.value()->sessionId(); } } return -1; } void ViewManager::setCurrentSession(int sessionId) { QHash::const_iterator i; for (i = _sessionMap.constBegin(); i != _sessionMap.constEnd(); ++i) { if (i.value()->sessionId() == sessionId) { - TabbedViewContainer *container = _viewSplitter->activeContainer(); + TabbedViewContainer *container = activeContainer(); if (container != nullptr) { container->setCurrentWidget(i.key()); } } } } int ViewManager::newSession() { Profile::Ptr profile = ProfileManager::instance()->defaultProfile(); Session *session = SessionManager::instance()->createSession(profile); session->addEnvironmentEntry(QStringLiteral("KONSOLE_DBUS_WINDOW=/Windows/%1").arg(managerId())); - createView(activeContainer(), session); + createView(session); session->run(); return session->sessionId(); } int ViewManager::newSession(const QString &profile) { const QList profilelist = ProfileManager::instance()->allProfiles(); Profile::Ptr profileptr = ProfileManager::instance()->defaultProfile(); for (const auto &i : profilelist) { if (i->name() == profile) { profileptr = i; break; } } Session *session = SessionManager::instance()->createSession(profileptr); session->addEnvironmentEntry(QStringLiteral("KONSOLE_DBUS_WINDOW=/Windows/%1").arg(managerId())); - createView(activeContainer(), session); + createView(session); session->run(); return session->sessionId(); } int ViewManager::newSession(const QString &profile, const QString &directory) { const QList profilelist = ProfileManager::instance()->allProfiles(); Profile::Ptr profileptr = ProfileManager::instance()->defaultProfile(); for (const auto &i : profilelist) { if (i->name() == profile) { profileptr = i; break; } } Session *session = SessionManager::instance()->createSession(profileptr); session->setInitialWorkingDirectory(directory); session->addEnvironmentEntry(QStringLiteral("KONSOLE_DBUS_WINDOW=/Windows/%1").arg(managerId())); - createView(activeContainer(), session); + createView(session); session->run(); return session->sessionId(); } QString ViewManager::defaultProfile() { return ProfileManager::instance()->defaultProfile()->name(); } QStringList ViewManager::profileList() { return ProfileManager::instance()->availableProfileNames(); } void ViewManager::nextSession() { nextView(); } void ViewManager::prevSession() { previousView(); } void ViewManager::moveSessionLeft() { moveActiveViewLeft(); } void ViewManager::moveSessionRight() { moveActiveViewRight(); } void ViewManager::setTabWidthToText(bool setTabWidthToText) { - for(auto container : _viewSplitter->containers()) { - container->tabBar()->setExpanding(!setTabWidthToText); - container->tabBar()->update(); - } + _viewContainer->tabBar()->setExpanding(!setTabWidthToText); + _viewContainer->tabBar()->update(); } void ViewManager::setNavigationVisibility(NavigationVisibility navigationVisibility) { if (_navigationVisibility != navigationVisibility) { _navigationVisibility = navigationVisibility; - for(auto *container : _viewSplitter->containers()) { - container->setNavigationVisibility(navigationVisibility); - } + _viewContainer->setNavigationVisibility(navigationVisibility); } } void ViewManager::setNavigationBehavior(int behavior) { _newTabBehavior = static_cast(behavior); } + +void ViewManager::updateTerminalDisplayHistory(TerminalDisplay* terminalDisplay, bool remove) +{ + if (terminalDisplay == nullptr) { + if (_terminalDisplayHistoryIndex >= 0) { + // This is the case when we finished walking through the history + // (i.e. when Ctrl-Tab has been released) + terminalDisplay = _terminalDisplayHistory[_terminalDisplayHistoryIndex]; + _terminalDisplayHistoryIndex = -1; + } else { + return; + } + } + + if (_terminalDisplayHistoryIndex >= 0 && !remove) { + // Do not reorder the tab history while we are walking through it + return; + } + + for (int i = 0; i < _terminalDisplayHistory.count(); i++) { + if (_terminalDisplayHistory[i] == terminalDisplay) { + _terminalDisplayHistory.removeAt(i); + if (!remove) { + _terminalDisplayHistory.prepend(terminalDisplay); + } + break; + } + } +} diff --git a/src/ViewManager.h b/src/ViewManager.h index 22f6e7b3..acb22b21 100644 --- a/src/ViewManager.h +++ b/src/ViewManager.h @@ -1,432 +1,450 @@ /* Copyright 2006-2008 by Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef VIEWMANAGER_H #define VIEWMANAGER_H // Qt +#include #include #include #include // Konsole #include "Profile.h" class KActionCollection; class KConfigGroup; namespace Konsole { class ColorScheme; class Session; class TerminalDisplay; class TabbedViewContainer; class SessionController; class ViewProperties; class ViewSplitter; class TabbedViewContainer; /** * Manages the terminal display widgets in a Konsole window or part. * - * When a view manager is created, it constructs a splitter widget ( accessed via - * widget() ) to hold one or more view containers. Each view container holds - * one or more terminal displays and a navigation widget ( eg. tabs or a list ) - * to allow the user to navigate between the displays in that container. + * When a view manager is created, it constructs a tab widget ( accessed via + * widget() ) to hold one or more view splitters. Each view splitter holds + * one or more terminal displays and splitters. * * The view manager provides menu actions ( defined in the 'konsoleui.rc' XML file ) * to manipulate the views and view containers - for example, actions to split the view * left/right or top/bottom, detach a view from the current window and navigate between * views and containers. These actions are added to the collection specified in the * ViewManager's constructor. * * The view manager provides facilities to construct display widgets for a terminal * session and also to construct the SessionController which provides the menus and other * user interface elements specific to each display/session pair. * */ class KONSOLEPRIVATE_EXPORT ViewManager : public QObject { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.kde.konsole.Window") public: /** * Constructs a new view manager with the specified @p parent. * View-related actions defined in 'konsoleui.rc' are created * and added to the specified @p collection. */ ViewManager(QObject *parent, KActionCollection *collection); ~ViewManager() Q_DECL_OVERRIDE; /** * Creates a new view to display the output from and deliver input to @p session. * Constructs a new container to hold the views if no container has yet been created. */ void createView(TabbedViewContainer *tabWidget, Session *session); + /* + * Applies the view-specific settings associated with specified @p profile + * to the terminal display @p view. + */ + void applyProfileToView(TerminalDisplay *view, const Profile::Ptr &profile); + /** * Return the main widget for the view manager which * holds all of the views managed by this ViewManager instance. */ QWidget *widget() const; /** * Returns the view manager's active view. */ QWidget *activeView() const; /** * Returns the list of view properties for views in the active container. * Each view widget is associated with a ViewProperties instance which * provides access to basic information about the session being * displayed in the view, such as title, current directory and * associated icon. */ QList viewProperties() const; /** * This enum describes the available types of navigation widget * which newly created containers can provide to allow navigation * between open sessions. */ enum NavigationMethod { /** * Each container has a row of tabs (one per session) which the user * can click on to navigate between open sessions. */ TabbedNavigation, /** The container has no navigation widget. */ NoNavigation }; /** * This enum describes where newly created tab should be placed. */ enum NewTabBehavior { /** Put newly created tab at the end. */ PutNewTabAtTheEnd = 0, /** Put newly created tab right after current tab. */ PutNewTabAfterCurrentTab = 1 }; /** * 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. AlwaysShowNavigation, ShowNavigationAsNeeded, 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 */ void setNavigationVisibility(NavigationVisibility navigationVisibility); /** Returns the current mode for controlling the visibility of the * view container's navigation widget. */ NavigationVisibility navigationVisibility() const; /** * Sets the type of widget provided to navigate between open sessions * in a container. The changes will only apply to newly created containers. * * The default method is TabbedNavigation. To disable navigation widgets, call * setNavigationMethod(ViewManager::NoNavigation) before creating any sessions. */ void setNavigationMethod(NavigationMethod method); /** * Returns the type of navigation widget created in new containers. * See setNavigationMethod() */ NavigationMethod navigationMethod() const; /** * Returns the controller for the active view. activeViewChanged() is * emitted when this changes. */ SessionController *activeViewController() const; /** * Session management */ void saveSessions(KConfigGroup &group); void restoreSessions(const KConfigGroup &group); void setNavigationBehavior(int behavior); int managerId() const; /** Returns a list of sessions in this ViewManager */ QList sessions() { return _sessionMap.values(); } /** * Returns whether the @p profile has the blur setting enabled */ static bool profileHasBlurEnabled(const Profile::Ptr &profile); /** returns the active tab from the view */ TabbedViewContainer *activeContainer(); - - void applyProfileToView(TerminalDisplay *view, const Profile::Ptr &profile); + TerminalDisplay *createView(Session *session); + void attachView(TerminalDisplay *terminal, Session *session); static const ColorScheme *colorSchemeForProfile(const Profile::Ptr &profile); + /** Reorder the terminal display history list */ + void updateTerminalDisplayHistory(TerminalDisplay *terminalDisplay = nullptr, bool remove = false); + QHash forgetAll(ViewSplitter* splitter); + Session* forgetTerminal(TerminalDisplay* terminal); 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 viewDetached(Session *session); + void terminalsDetached(ViewSplitter *splitter, QHash sessionsMap); /** * Emitted when the active view changes. * @param controller The controller associated with the active view */ void activeViewChanged(SessionController *controller); /** * Emitted when the current session needs unplugged from factory(). * @param controller The controller associated with the active view */ void unplugController(SessionController *controller); /** * Emitted when the list of view properties ( as returned by viewProperties() ) changes. * This occurs when views are added to or removed from the active container, or * if the active container is changed. */ void viewPropertiesChanged(const QList &propertiesList); - /** - * Emitted when the number of views containers changes. This is used to disable or - * enable menu items which can only be used when there are one or multiple containers - * visible. - * - * @param multipleViews True if there are multiple view containers open or false if there is - * just a single view. - */ - void splitViewToggle(bool multipleViews); - /** * Emitted when menu bar visibility changes because a profile that requires so is * activated. */ void setMenuBarVisibleRequest(bool); void updateWindowIcon(); void blurSettingChanged(bool); /** Requests creation of a new view with the default profile. */ - void newViewRequest(TabbedViewContainer *tabWidget); + void newViewRequest(); /** Requests creation of a new view, with the selected profile. */ - void newViewWithProfileRequest(TabbedViewContainer *tabWidget, const Profile::Ptr&); + void newViewWithProfileRequest(const Profile::Ptr&); public Q_SLOTS: /** DBus slot that returns the number of sessions in the current view. */ Q_SCRIPTABLE int sessionCount(); /** * DBus slot that returns the unique ids of the sessions in the * current view. The returned list is not sorted. * QList is not printable by qdbus so we use QStringList */ Q_SCRIPTABLE QStringList sessionList(); /** DBus slot that returns the current (active) session window */ Q_SCRIPTABLE int currentSession(); /** DBus slot that sets the current (active) session window */ Q_SCRIPTABLE void setCurrentSession(int sessionId); /** DBus slot that creates a new session in the current view. * @param profile the name of the profile to be used * started. */ Q_SCRIPTABLE int newSession(const QString &profile); /** DBus slot that creates a new session in the current view. * @param profile the name of the profile to be used * @param directory the working directory where the session is * started. */ Q_SCRIPTABLE int newSession(const QString &profile, const QString &directory); // TODO: its semantic is application-wide. Move it to more appropriate place // DBus slot that returns the name of default profile Q_SCRIPTABLE QString defaultProfile(); // TODO: its semantic is application-wide. Move it to more appropriate place // DBus slot that returns a string list of defined (known) profiles Q_SCRIPTABLE QStringList profileList(); /** DBus slot that creates a new session in the current view with the associated * default profile and the default working directory */ Q_SCRIPTABLE int newSession(); /** DBus slot that changes the view port to the next session */ Q_SCRIPTABLE void nextSession(); /** DBus slot that changes the view port to the previous session */ 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. */ 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. */ Q_SCRIPTABLE void moveSessionRight(); /** DBus slot that sets ALL tabs' width to match their text */ Q_SCRIPTABLE void setTabWidthToText(bool); private Q_SLOTS: // called when the "Split View Left/Right" menu item is selected void splitLeftRight(); void splitTopBottom(); - void closeActiveContainer(); - void closeOtherContainers(); void expandActiveContainer(); void shrinkActiveContainer(); // called when the "Detach View" menu item is selected void detachActiveView(); + void detachActiveTab(); void updateDetachViewState(); // called when a session terminates - the view manager will delete any // views associated with the session void sessionFinished(); // called when one view has been destroyed void viewDestroyed(QWidget *view); // 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 ); // called when the active view in a ViewContainer changes, so // that we can plug the appropriate actions into the UI - void viewActivated(QWidget *view); + void viewActivated(TerminalDisplay *view); + + void focusUp(); + void focusDown(); + void focusLeft(); + void focusRight(); // called when "Next View" shortcut is activated void nextView(); // called when "Previous View" shortcut is activated void previousView(); // called when "Switch to last tab" shortcut is activated void lastView(); // called when "Switch to last used tab" shortcut is activated void lastUsedView(); // called when "Switch to last used tab (reverse)" shortcut is activated void lastUsedViewReverse(); // called when "Next View Container" shortcut is activated void nextContainer(); // called when "Toggle Two tabs" shortcut is activated void toggleTwoViews(); // called when the views in a container owned by this view manager // changes void containerViewsChanged(TabbedViewContainer *container); // called when a profile changes void profileChanged(const Profile::Ptr &profile); void updateViewsForSession(Session *session); // moves active view to the left void moveActiveViewLeft(); // moves active view to the right void moveActiveViewRight(); // switches to the view at visual position 'index' // in the current container void switchToView(int index); + // gives focus and switches the terminal display, changing tab if needed + void switchToTerminalDisplay(TerminalDisplay *terminalDisplay); // called when a SessionController gains focus void controllerChanged(SessionController *controller); - // called when a ViewContainer requests a view be - // moved - void containerMoveViewRequest(int index, int sessionControllerId); - - void detachView(TabbedViewContainer *container, QWidget *view); + /* Detaches the tab at index tabIdx */ + void detachTab(int tabIdx); private: Q_DISABLE_COPY(ViewManager) void createView(Session *session, TabbedViewContainer *container, int index); void setupActions(); // 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 splitView(Qt::Orientation orientation); // creates a new container which can hold terminal displays TabbedViewContainer *createContainer(); - // removes a container and emits appropriate signals - void removeContainer(TabbedViewContainer *container); // creates a new terminal display // the 'session' is used so that the terminal display's random seed // can be set to something which depends uniquely on that session TerminalDisplay *createTerminalDisplay(Session *session = nullptr); // creates a new controller for a session/display pair which provides the menu // 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); + + // Activates a different terminal when the TerminalDisplay + // closes or is detached and another one should be focused. + // It will activate the last used terminal within the same splitView + // if possible otherwise it will focus the last used tab + void focusAnotherTerminal(ViewSplitter *toplevelSplitter); + + void activateLastUsedView(bool reverse); private: - QPointer _viewSplitter; + QPointer _viewContainer; QPointer _pluggedController; QHash _sessionMap; KActionCollection *_actionCollection; NavigationMethod _navigationMethod; NavigationVisibility _navigationVisibility; NewTabBehavior _newTabBehavior; int _managerId; static int lastManagerId; + QList _terminalDisplayHistory; + int _terminalDisplayHistoryIndex; + + // List of actions that should only be enabled when there are multiple view + // containers open + QList _multiTabOnlyActions; + QList _multiSplitterOnlyActions; + }; } #endif diff --git a/src/ViewSplitter.cpp b/src/ViewSplitter.cpp index 8d384c41..8e21e7a0 100644 --- a/src/ViewSplitter.cpp +++ b/src/ViewSplitter.cpp @@ -1,279 +1,219 @@ /* This file is part of the Konsole Terminal. Copyright 2006-2008 Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ // Own #include "ViewSplitter.h" // Qt #include +#include +#include // Konsole #include "ViewContainer.h" +#include "TerminalDisplay.h" using Konsole::ViewSplitter; -using Konsole::TabbedViewContainer; +using Konsole::TerminalDisplay; -ViewSplitter::ViewSplitter(QWidget *parent) : - QSplitter(parent), - _containers(QList()), - _recursiveSplitting(true) -{ -} +//TODO: Connect the TerminalDisplay destroyed signal here. -void ViewSplitter::childEmpty(ViewSplitter *splitter) +ViewSplitter::ViewSplitter(QWidget *parent) : + QSplitter(parent) { - delete splitter; - - if (count() == 0) { - emit empty(this); - } } -void ViewSplitter::adjustContainerSize(TabbedViewContainer *container, int percentage) +void ViewSplitter::adjustActiveTerminalDisplaySize(int percentage) { - int containerIndex = indexOf(container); - + const int containerIndex = indexOf(activeTerminalDisplay()); Q_ASSERT(containerIndex != -1); QList containerSizes = sizes(); const int oldSize = containerSizes[containerIndex]; - const auto newSize = static_cast(oldSize * (1.0 + percentage / 100.0)); - + const int newSize = static_cast(oldSize * (1.0 + percentage / 100.0)); const int perContainerDelta = (count() == 1) ? 0 : ((newSize - oldSize) / (count() - 1)) * (-1); - for (int i = 0; i < containerSizes.count(); i++) { - if (i == containerIndex) { - containerSizes[i] = newSize; - } else { - containerSizes[i] = containerSizes[i] + perContainerDelta; - } + for (int& size : containerSizes) { + size += perContainerDelta; } + containerSizes[containerIndex] = newSize; setSizes(containerSizes); } ViewSplitter *ViewSplitter::activeSplitter() { QWidget *widget = focusWidget() != nullptr ? focusWidget() : this; ViewSplitter *splitter = nullptr; while ((splitter == nullptr) && (widget != nullptr)) { splitter = qobject_cast(widget); widget = widget->parentWidget(); } Q_ASSERT(splitter); return splitter; } -void ViewSplitter::registerContainer(TabbedViewContainer *container) -{ - _containers << container; - connect(container, &TabbedViewContainer::empty, this, &ViewSplitter::containerEmpty); -} - -void ViewSplitter::unregisterContainer(TabbedViewContainer *container) -{ - _containers.removeAll(container); - disconnect(container, nullptr, this, nullptr); -} - void ViewSplitter::updateSizes() { - int space; - - if (orientation() == Qt::Horizontal) { - space = width() / count(); - } else { - space = height() / count(); - } - - QList widgetSizes; - const int widgetCount = count(); - widgetSizes.reserve(widgetCount); - for (int i = 0; i < widgetCount; i++) { - widgetSizes << space; - } - - setSizes(widgetSizes); -} - -void ViewSplitter::setRecursiveSplitting(bool recursive) -{ - _recursiveSplitting = recursive; -} - -bool ViewSplitter::recursiveSplitting() const -{ - return _recursiveSplitting; + const int space = (orientation() == Qt::Horizontal ? width() : height()) / count(); + setSizes(QVector(count(), space).toList()); } -void ViewSplitter::removeContainer(TabbedViewContainer *container) -{ - Q_ASSERT(containers().contains(container)); - - unregisterContainer(container); -} - -void ViewSplitter::addContainer(TabbedViewContainer *container, Qt::Orientation containerOrientation) +void ViewSplitter::addTerminalDisplay(TerminalDisplay *terminalDisplay, Qt::Orientation containerOrientation) { ViewSplitter *splitter = activeSplitter(); - - if (splitter->count() < 2 - || containerOrientation == splitter->orientation() - || !_recursiveSplitting) { - splitter->registerContainer(container); - splitter->addWidget(container); - - if (splitter->orientation() != containerOrientation) { - splitter->setOrientation(containerOrientation); + if (splitter->count() < 2) { + splitter->addWidget(terminalDisplay); + splitter->setOrientation(containerOrientation); + } else if (containerOrientation == splitter->orientation()) { + auto activeDisplay = splitter->activeTerminalDisplay(); + if (!activeDisplay) { + splitter->addWidget(terminalDisplay); + } else { + const int currentIndex = splitter->indexOf(activeDisplay); + splitter->insertWidget(currentIndex, terminalDisplay); } - - splitter->updateSizes(); } else { - auto newSplitter = new ViewSplitter(this); - connect(newSplitter, &Konsole::ViewSplitter::empty, splitter, - &Konsole::ViewSplitter::childEmpty); - - TabbedViewContainer *oldContainer = splitter->activeContainer(); - const int oldContainerIndex = splitter->indexOf(oldContainer); + auto newSplitter = new ViewSplitter(); - splitter->unregisterContainer(oldContainer); - - newSplitter->registerContainer(oldContainer); - newSplitter->registerContainer(container); - - newSplitter->addWidget(oldContainer); - newSplitter->addWidget(container); + TerminalDisplay *oldTerminalDisplay = splitter->activeTerminalDisplay(); + const int oldContainerIndex = splitter->indexOf(oldTerminalDisplay); + newSplitter->addWidget(oldTerminalDisplay); + newSplitter->addWidget(terminalDisplay); newSplitter->setOrientation(containerOrientation); newSplitter->updateSizes(); newSplitter->show(); splitter->insertWidget(oldContainerIndex, newSplitter); } + splitter->updateSizes(); } -void ViewSplitter::containerEmpty(TabbedViewContainer * myContainer) +void ViewSplitter::childEvent(QChildEvent *event) { - _containers.removeAll(myContainer); - if (count() == 0) { - emit empty(this); - } - - int children = 0; - foreach (auto container, _containers) { - children += container->count(); - } - - if (children == 0) { - emit allContainersEmpty(); - } - - // This container is no more, try to find another container to focus. - ViewSplitter *currentSplitter = activeSplitter(); - while(qobject_cast(currentSplitter->parent())) { - currentSplitter = qobject_cast(currentSplitter->parent()); - } + QSplitter::childEvent(event); - for(auto tabWidget : currentSplitter->findChildren()) { - if (tabWidget != myContainer && tabWidget->count()) { - tabWidget->setCurrentIndex(0); + if (event->removed()) { + if (count() == 0) { + deleteLater(); + } + if (!findChild()) { + deleteLater(); } } } -void ViewSplitter::activateNextContainer() +void ViewSplitter::handleFocusDirection(Qt::Orientation orientation, int direction) { - TabbedViewContainer *active = activeContainer(); + auto terminalDisplay = activeTerminalDisplay(); + auto parentSplitter = qobject_cast(terminalDisplay->parentWidget()); + auto topSplitter = parentSplitter->getToplevelSplitter(); - int index = _containers.indexOf(active); + const auto handleWidth = parentSplitter->handleWidth() <= 1 ? 4 : parentSplitter->handleWidth(); - if (index == -1) { - return; - } + const auto start = QPoint(terminalDisplay->x(), terminalDisplay->y()); + const auto startMapped = parentSplitter->mapTo(topSplitter, start); - if (index == _containers.count() - 1) { - index = 0; - } else { - index++; - } + const int newX = orientation != Qt::Horizontal ? 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; - setActiveContainer(_containers.at(index)); + const auto newPoint = QPoint(newX, newY); + auto child = topSplitter->childAt(newPoint); + + qDebug() << "Handling focus"; + if (TerminalDisplay* terminal = qobject_cast(child)) { + terminal->setFocus(Qt::OtherFocusReason); + } else if (qobject_cast(child)) { + auto terminal = qobject_cast(child->parent()); + terminal->setFocus(Qt::OtherFocusReason); + } else if (qobject_cast(child)) { + auto targetSplitter = qobject_cast(child->parent()); + auto terminal = qobject_cast(targetSplitter->widget(0)); + terminal->setFocus(Qt::OtherFocusReason); + } } -void ViewSplitter::activatePreviousContainer() +void ViewSplitter::focusUp() { - TabbedViewContainer *active = activeContainer(); + handleFocusDirection(Qt::Vertical, -1); +} - int index = _containers.indexOf(active); +void ViewSplitter::focusDown() +{ + handleFocusDirection(Qt::Vertical, +1); +} - if (index == 0) { - index = _containers.count() - 1; - } else { - index--; - } +void ViewSplitter::focusLeft() +{ + handleFocusDirection(Qt::Horizontal, -1); +} - setActiveContainer(_containers.at(index)); +void ViewSplitter::focusRight() +{ + handleFocusDirection(Qt::Horizontal, +1); } -void ViewSplitter::setActiveContainer(TabbedViewContainer *container) +TerminalDisplay *ViewSplitter::activeTerminalDisplay() const { - QWidget *activeView = container->currentWidget(); + auto focusedWidget = qobject_cast(focusWidget()); + return focusedWidget ? focusedWidget : findChild(); +} - if (activeView != nullptr) { - activeView->setFocus(Qt::OtherFocusReason); - } +void ViewSplitter::maximizeCurrentTerminal() +{ + handleMinimizeMaximize(true); } -TabbedViewContainer *ViewSplitter::activeContainer() const +void ViewSplitter::restoreOtherTerminals() { - if (QWidget *focusW = focusWidget()) { - TabbedViewContainer *focusContainer = nullptr; - - while (focusW != nullptr) { - foreach (TabbedViewContainer *container, _containers) { - if (container == focusW) { - focusContainer = container; - break; - } - } - focusW = focusW->parentWidget(); - } + handleMinimizeMaximize(false); +} - if (focusContainer != nullptr) { - return focusContainer; +void ViewSplitter::handleMinimizeMaximize(bool maximize) +{ + auto viewSplitter = getToplevelSplitter(); + auto terminalDisplays = viewSplitter->findChildren(); + auto currentActiveTerminal = viewSplitter->activeTerminalDisplay(); + auto method = maximize ? &QWidget::hide : &QWidget::show; + for(auto terminal : terminalDisplays) { + if (Q_LIKELY(currentActiveTerminal != terminal)) { + (terminal->*method)(); } } +} - QList splitters = findChildren(); - - if (!splitters.isEmpty()) { - return splitters.last()->activeContainer(); - } else { - if (!_containers.isEmpty()) { - return _containers.last(); - } else { - return nullptr; - } +ViewSplitter *ViewSplitter::getToplevelSplitter() +{ + ViewSplitter *current = this; + while(qobject_cast(current->parentWidget())) { + current = qobject_cast(current->parentWidget()); } + return current; } diff --git a/src/ViewSplitter.h b/src/ViewSplitter.h index 70ca0040..aa248e1e 100644 --- a/src/ViewSplitter.h +++ b/src/ViewSplitter.h @@ -1,185 +1,133 @@ /* This file is part of the Konsole Terminal. Copyright 2006-2008 Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef VIEWSPLITTER_H #define VIEWSPLITTER_H // Qt #include #include +// Konsole +#include "konsoleprivate_export.h" + class QFocusEvent; namespace Konsole { -class TabbedViewContainer; +class TerminalDisplay; /** * A splitter which holds a number of ViewContainer objects and allows * the user to control the size of each view container by dragging a splitter * bar between them. * * Each splitter can also contain child ViewSplitter widgets, allowing * for a hierarchy of view splitters and containers. * * The addContainer() method is used to split the existing view and * insert a new view container. * Containers can only be removed from the hierarchy by deleting them. */ -class ViewSplitter : public QSplitter +class KONSOLEPRIVATE_EXPORT ViewSplitter : public QSplitter { Q_OBJECT public: explicit ViewSplitter(QWidget *parent = nullptr); /** * Locates the child ViewSplitter widget which currently has the focus * and inserts the container into it. * * @param container The container to insert * @param orientation Specifies whether the view should be split * horizontally or vertically. If the orientation * is the same as the ViewSplitter into which the * container is to be inserted, or if the splitter * has fewer than two child widgets then the container * will be added to that splitter. If the orientation * is different, then a new child splitter * will be created, into which the container will * be inserted. */ - void addContainer(TabbedViewContainer *container, Qt::Orientation orientation); + void addTerminalDisplay(TerminalDisplay *terminalDisplay, Qt::Orientation orientation); /** Removes a container from the splitter. The container is not deleted. */ - void removeContainer(TabbedViewContainer *container); + void removeTerminalDisplay(TerminalDisplay *terminalDisplay); /** Returns the child ViewSplitter widget which currently has the focus */ ViewSplitter *activeSplitter(); /** * Returns the container which currently has the focus or 0 if none * of the immediate child containers have the focus. This does not * search through child splitters. activeSplitter() can be used * to search recursively through child splitters for the splitter * which currently has the focus. * * To find the currently active container, use * mySplitter->activeSplitter()->activeContainer() where mySplitter * is the ViewSplitter widget at the top of the hierarchy. */ - TabbedViewContainer *activeContainer() const; + TerminalDisplay *activeTerminalDisplay() const; - /** - * Gives the focus to the active view in the specified container + /** Makes the current TerminalDisplay expanded to 100% of the view */ - void setActiveContainer(TabbedViewContainer *container); + void maximizeCurrentTerminal(); - /** - * Returns a list of the containers held by this splitter + /** Restore the sizes of the terminals. */ - QList containers() const - { - return _containers; - } + void restoreOtherTerminals(); + + void handleMinimizeMaximize(bool maximize); + + /** returns the splitter that has no splitter as a parent. */ + ViewSplitter *getToplevelSplitter(); /** - * Gives the focus to the active view in the next container + * Gives the focus to the active view in the specified container */ - void activateNextContainer(); + void setActiveTerminalDisplay(TerminalDisplay *container); /** * Changes the size of the specified @p container by a given @p percentage. * @p percentage may be positive ( in which case the size of the container * is increased ) or negative ( in which case the size of the container * is decreased ). * * The sizes of the remaining containers are increased or decreased * uniformly to maintain the width of the splitter. */ - void adjustContainerSize(TabbedViewContainer *container, int percentage); + void adjustActiveTerminalDisplaySize(int percentage); - /** - * Gives the focus to the active view in the previous container - */ - void activatePreviousContainer(); + void focusUp(); + void focusDown(); + void focusLeft(); + void focusRight(); - /** - * Specifies whether the view may be split recursively. - * - * If this is false, all containers will be placed into the same - * top-level splitter. Adding a container with an orientation - * which is different to that specified when adding the previous - * containers will change the orientation for all dividers - * between containers. - * - * If this is true, adding a container to the view splitter with - * an orientation different to the orientation of the previous - * area will result in the previously active container being - * replaced with a new splitter containing the active container - * and the newly added container. - */ - void setRecursiveSplitting(bool recursive); - - /** - * Returns whether the view may be split recursively. - * See setRecursiveSplitting() - */ - bool recursiveSplitting() const; - -Q_SIGNALS: - /** Signal emitted when the last child widget is removed from the splitter */ - void empty(ViewSplitter *splitter); - - /** - * Signal emitted when the containers held by this splitter become empty, this - * differs from the empty() signal which is only emitted when all of the containers - * are deleted. This signal is emitted even if there are still container widgets. - * - * TODO: This does not yet work recursively (ie. when splitters inside splitters have empty containers) - */ - void allContainersEmpty(); - -protected: - //virtual void focusEvent(QFocusEvent* event); + void handleFocusDirection(Qt::Orientation orientation, int direction); + void childEvent(QChildEvent* event) override; private: - // Adds container to splitter's internal list and - // connects signals and slots - void registerContainer(TabbedViewContainer *container); - // Removes container from splitter's internal list and - // removes signals and slots - void unregisterContainer(TabbedViewContainer *container); - void updateSizes(); - -private Q_SLOTS: - // Called to indicate that a child ViewContainer is empty - void containerEmpty(TabbedViewContainer *container); - - // Called to indicate that a child ViewSplitter is empty - // (ie. all child widgets have been deleted) - void childEmpty(ViewSplitter *splitter); - -private: - QList _containers; - bool _recursiveSplitting; }; } #endif //VIEWSPLITTER_H