SessionController.cpp 73.7 KB
Newer Older
1
/*
2 3
    SPDX-FileCopyrightText: 2006-2008 Robert Knight <robertknight@gmail.com>
    SPDX-FileCopyrightText: 2009 Thomas Dreibholz <dreibh@iem.uni-due.de>
4

5
    SPDX-License-Identifier: GPL-2.0-or-later
6 7 8
*/

// Own
9
#include "SessionController.h"
10

11
#include "profile/ProfileManager.h"
12
#include "konsoledebug.h"
13

14
// Qt
15
#include <QApplication>
16
#include <QAction>
patrick pereira's avatar
patrick pereira committed
17
#include <QList>
18
#include <QMenu>
19
#include <QKeyEvent>
20
#include <QFileDialog>
21
#include <QPainter>
22
#include <QStandardPaths>
23 24
#include <QUrl>
#include <QIcon>
25

26
// KDE
27 28
#include <KActionMenu>
#include <KActionCollection>
29
#include <KLocalizedString>
30
#include <KMessageBox>
31
#include <KShell>
Robert Knight's avatar
 
Robert Knight committed
32
#include <KToggleAction>
33
#include <KSelectAction>
34
#include <KXmlGuiWindow>
35
#include <KXMLGUIFactory>
36
#include <KXMLGUIBuilder>
Jekyll Wu's avatar
Jekyll Wu committed
37 38
#include <KUriFilter>
#include <KStringHandler>
Alex Richardson's avatar
Alex Richardson committed
39
#include <KSharedConfig>
40
#include <KConfigGroup>
41
#include <KCodecAction>
42
#include <KNotification>
43

44
#include <kio_version.h>
Kurt Hindenburg's avatar
Kurt Hindenburg committed
45 46 47 48 49 50
#if KIO_VERSION > QT_VERSION_CHECK(5, 68, 0)
#include <KIO/CommandLauncherJob>
#else
#include <KToolInvocation>
#endif

51 52 53 54 55 56 57
#if KIO_VERSION < QT_VERSION_CHECK(5, 71, 0)
#include <KRun>
#else
#include <KIO/JobUiDelegate>
#include <KIO/OpenUrlJob>
#endif

58
// Konsole
59
#include "CopyInputDialog.h"
60
#include "Emulation.h"
61 62 63 64 65
#include "HistorySizeDialog.h"
#include "RenameTabDialog.h"
#include "SaveHistoryTask.h"
#include "ScreenWindow.h"
#include "SearchHistoryTask.h"
66 67

#include "filterHotSpots/EscapeSequenceUrlFilter.h"
68 69 70 71 72 73
#include "filterHotSpots/FileFilter.h"
#include "filterHotSpots/Filter.h"
#include "filterHotSpots/FilterChain.h"
#include "filterHotSpots/HotSpot.h"
#include "filterHotSpots/RegExpFilter.h"
#include "filterHotSpots/UrlFilter.h"
74
#include "filterHotSpots/ColorFilter.h"
75

76 77
#include "history/HistoryType.h"
#include "history/HistoryTypeFile.h"
78
#include "history/HistoryTypeNone.h"
79
#include "history/compact/CompactHistoryType.h"
80

81
#include "profile/ProfileList.h"
82

83 84
#include "SessionGroup.h"
#include "SessionManager.h"
85

86
#include "widgets/EditProfileDialog.h"
87
#include "widgets/IncrementalSearchBar.h"
88 89

#include "terminalDisplay/TerminalDisplay.h"
90

91
// For Unix signal names
Kurt Hindenburg's avatar
Kurt Hindenburg committed
92
#include <csignal>
93

94
using namespace Konsole;
95

96
QSet<SessionController*> SessionController::_allControllers;
97
int SessionController::_lastControllerId;
Robert Knight's avatar
 
Robert Knight committed
98

99
SessionController::SessionController(Session* session, TerminalDisplay* view, QObject* parent)
Robert Knight's avatar
 
Robert Knight committed
100
    : ViewProperties(parent)
101
    , KXMLGUIClient()
Kurt Hindenburg's avatar
Kurt Hindenburg committed
102
    , _copyToGroup(nullptr)
103
    , _profileList(nullptr)
104 105
    , _sessionIcon(QIcon())
    , _sessionIconName(QString())
Kurt Hindenburg's avatar
Kurt Hindenburg committed
106 107 108
    , _searchFilter(nullptr)
    , _urlFilter(nullptr)
    , _fileFilter(nullptr)
109
    , _colorFilter(nullptr)
Kurt Hindenburg's avatar
Kurt Hindenburg committed
110 111 112 113
    , _copyInputToAllTabsAction(nullptr)
    , _findAction(nullptr)
    , _findNextAction(nullptr)
    , _findPreviousAction(nullptr)
114
    , _interactionTimer(nullptr)
Harald Hvaal's avatar
Harald Hvaal committed
115 116
    , _searchStartLine(0)
    , _prevSearchResultLine(0)
Kurt Hindenburg's avatar
Kurt Hindenburg committed
117 118 119
    , _codecAction(nullptr)
    , _switchProfileMenu(nullptr)
    , _webSearchMenu(nullptr)
120 121
    , _listenForScreenWindowUpdates(false)
    , _preventClose(false)
122
    , _selectedText(QString())
Kurt Hindenburg's avatar
Kurt Hindenburg committed
123
    , _showMenuAction(nullptr)
124
    , _bookmarkValidProgramsToClear(QStringList())
125
    , _isSearchBarEnabled(false)
126
    , _editProfileDialog(nullptr)
127
    , _searchBar(view->searchBar())
128
    , _monitorProcessFinish(false)
129
    , _escapedUrlFilter(nullptr)
130
{
Kurt Hindenburg's avatar
Kurt Hindenburg committed
131 132
    Q_ASSERT(session);
    Q_ASSERT(view);
133

134 135
    _sessionDisplayConnection = new SessionDisplayConnection(session, view, this);

136
    // handle user interface related to session (menus etc.)
137
    if (isKonsolePart()) {
138
        setComponentName(QStringLiteral("konsole"), i18n("Konsole"));
139
        setXMLFile(QStringLiteral("partui.rc"));
140 141
        setupCommonActions();
    } else {
142
        setXMLFile(QStringLiteral("sessionui.rc"));
143 144 145
        setupCommonActions();
        setupExtraActions();
    }
146

147 148
    connect(this, &SessionController::requestPrint, _sessionDisplayConnection->view(), &TerminalDisplay::printScreen);

149
    actionCollection()->addAssociatedWidget(view);
150 151 152

    const QList<QAction *> actionsList = actionCollection()->actions();
    for (QAction *action : actionsList) {
Jekyll Wu's avatar
Jekyll Wu committed
153 154
        action->setShortcutContext(Qt::WidgetWithChildrenShortcut);
    }
155

156
    setIdentifier(++_lastControllerId);
157
    sessionAttributeChanged();
158

159 160
    connect(_sessionDisplayConnection->view(), &TerminalDisplay::compositeFocusChanged, this, &SessionController::viewFocusChangeHandler);
    _sessionDisplayConnection->view()->setSessionController(this);
Robert Knight's avatar
 
Robert Knight committed
161

162
    // install filter on the view to highlight URLs and files
163
    updateFilterList(SessionManager::instance()->sessionProfile(_sessionDisplayConnection->session()));
164

165 166
    // listen for changes in session, we might need to change the enabled filters
    connect(ProfileManager::instance(), &Konsole::ProfileManager::profileChanged, this, &Konsole::SessionController::updateFilterList);
167

168
    // listen for session resize requests
169
    connect(_sessionDisplayConnection->session(), &Konsole::Session::resizeRequest, this, &Konsole::SessionController::sessionResizeRequest);
170

171
    // listen for popup menu requests
172
    connect(_sessionDisplayConnection->view(), &Konsole::TerminalDisplay::configureRequest, this, &Konsole::SessionController::showDisplayContextMenu);
173

174
    // move view to newest output when keystrokes occur
175
    connect(_sessionDisplayConnection->view(), &Konsole::TerminalDisplay::keyPressedSignal, this, &Konsole::SessionController::trackOutput);
176

Robert Knight's avatar
 
Robert Knight committed
177
    // listen to activity / silence notifications from session
178
    connect(_sessionDisplayConnection->session(), &Konsole::Session::notificationsChanged, this, &Konsole::SessionController::sessionNotificationsChanged);
179
    // listen to title and icon changes
180 181
    connect(_sessionDisplayConnection->session(), &Konsole::Session::sessionAttributeChanged, this, &Konsole::SessionController::sessionAttributeChanged);
    connect(_sessionDisplayConnection->session(), &Konsole::Session::readOnlyChanged, this, &Konsole::SessionController::sessionReadOnlyChanged);
182

183 184
    connect(this, &Konsole::SessionController::tabRenamedByUser, _sessionDisplayConnection->session(), &Konsole::Session::tabTitleSetByUser);
    connect(this, &Konsole::SessionController::tabColoredByUser, _sessionDisplayConnection->session(), &Konsole::Session::tabColorSetByUser);
185

186
    connect(_sessionDisplayConnection->session() , &Konsole::Session::currentDirectoryChanged , this , &Konsole::SessionController::currentDirectoryChanged);
187

188
    // listen for color changes
189 190
    connect(_sessionDisplayConnection->session(), &Konsole::Session::changeBackgroundColorRequest, _sessionDisplayConnection->view(), &Konsole::TerminalDisplay::setBackgroundColor);
    connect(_sessionDisplayConnection->session(), &Konsole::Session::changeForegroundColorRequest, _sessionDisplayConnection->view(), &Konsole::TerminalDisplay::setForegroundColor);
191

192
    // update the title when the session starts
193
    connect(_sessionDisplayConnection->session(), &Konsole::Session::started, this, &Konsole::SessionController::snapshot);
194

195
    // listen for output changes to set activity flag
196
    connect(_sessionDisplayConnection->session()->emulation(), &Konsole::Emulation::outputChanged, this, &Konsole::SessionController::fireActivity);
197 198

    // listen for detection of ZModem transfer
199 200
    connect(_sessionDisplayConnection->session(), &Konsole::Session::zmodemDownloadDetected, this, &Konsole::SessionController::zmodemDownload);
    connect(_sessionDisplayConnection->session(), &Konsole::Session::zmodemUploadDetected, this, &Konsole::SessionController::zmodemUpload);
201

Robert Knight's avatar
 
Robert Knight committed
202
    // listen for flow control status changes
203 204
    connect(_sessionDisplayConnection->session(), &Konsole::Session::flowControlEnabledChanged, _sessionDisplayConnection->view(), &Konsole::TerminalDisplay::setFlowControlWarningEnabled);
    _sessionDisplayConnection->view()->setFlowControlWarningEnabled(_sessionDisplayConnection->session()->flowControlEnabled());
Robert Knight's avatar
 
Robert Knight committed
205

206 207
    // take a snapshot of the session state every so often when
    // user activity occurs
208 209 210
    //
    // the timer is owned by the session so that it will be destroyed along
    // with the session
211
    _interactionTimer = new QTimer(_sessionDisplayConnection->session());
212
    _interactionTimer->setSingleShot(true);
213
    _interactionTimer->setInterval(500);
214
    connect(_interactionTimer, &QTimer::timeout, this, &Konsole::SessionController::snapshot);
215
    connect(_sessionDisplayConnection->view(), &Konsole::TerminalDisplay::compositeFocusChanged,
216
            this, [this](bool focused) { if (focused) { interactionHandler(); }});
217
    connect(_sessionDisplayConnection->view(), &Konsole::TerminalDisplay::keyPressedSignal,
218
            this, &Konsole::SessionController::interactionHandler);
219

220
    // take a snapshot of the session state periodically in the background
221
    auto backgroundTimer = new QTimer(_sessionDisplayConnection->session());
222 223
    backgroundTimer->setSingleShot(false);
    backgroundTimer->setInterval(2000);
224
    connect(backgroundTimer, &QTimer::timeout, this, &Konsole::SessionController::snapshot);
225 226
    backgroundTimer->start();

227
    // xterm '10;?' request
228
    connect(_sessionDisplayConnection->session(), &Konsole::Session::getForegroundColor,
229
            this, &Konsole::SessionController::sendForegroundColor);
230
    // xterm '11;?' request
231
    connect(_sessionDisplayConnection->session(), &Konsole::Session::getBackgroundColor,
232 233
            this, &Konsole::SessionController::sendBackgroundColor);

234
    _allControllers.insert(this);
235 236 237

    // A list of programs that accept Ctrl+C to clear command line used
    // before outputting bookmark.
238 239 240 241 242 243 244 245
    _bookmarkValidProgramsToClear = QStringList({
        QStringLiteral("bash"),
        QStringLiteral("fish"),
        QStringLiteral("sh"),
        QStringLiteral("tcsh"),
        QStringLiteral("zsh")
    });

246 247
    setupSearchBar();
    _searchBar->setVisible(_isSearchBarEnabled);
248 249 250
}

SessionController::~SessionController()
251
{
Kurt Hindenburg's avatar
Kurt Hindenburg committed
252
    _allControllers.remove(this);
253 254

    if (!_editProfileDialog.isNull()) {
Tomaz  Canabrava's avatar
Tomaz Canabrava committed
255
        _editProfileDialog->deleteLater();
256
    }
257
    if(factory() != nullptr) {
258 259
        factory()->removeClient(this);
    }
260
}
261
void SessionController::trackOutput(QKeyEvent* event)
262
{
263
    Q_ASSERT(_sessionDisplayConnection->view()->screenWindow());
264

265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
    // Qt has broken something, so we can't rely on just checking if certain
    // keys are passed as modifiers anymore.
    const int key = event->key();
    const bool shouldNotTriggerScroll =
        key == Qt::Key_Super_L      ||
        key == Qt::Key_Super_R      ||
        key == Qt::Key_Hyper_L      ||
        key == Qt::Key_Hyper_R      ||
        key == Qt::Key_Shift        ||
        key == Qt::Key_Control      ||
        key == Qt::Key_Meta         ||
        key == Qt::Key_Alt          ||
        key == Qt::Key_AltGr        ||
        key == Qt::Key_CapsLock     ||
        key == Qt::Key_NumLock      ||
        key == Qt::Key_ScrollLock;


283 284
    // Only jump to the bottom if the user actually typed something in,
    // not if the user e. g. just pressed a modifier.
285
    if (event->text().isEmpty() && ((event->modifiers() != 0u) || shouldNotTriggerScroll)) {
286
        return;
287
    }
288

289
    _sessionDisplayConnection->view()->screenWindow()->setTrackOutput(true);
290
}
291 292 293 294 295 296 297 298 299 300 301 302

void SessionController::viewFocusChangeHandler(bool focused)
{
    if (focused) {
        // 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 viewFocused(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
303
        disconnect(_sessionDisplayConnection->session(), &Konsole::Session::bellRequest, nullptr, nullptr);
304
        // second, connect the newly focused view to listen for the session's bell signal
305
        connect(_sessionDisplayConnection->session(), &Konsole::Session::bellRequest, _sessionDisplayConnection->view(), &Konsole::TerminalDisplay::bell);
306 307 308 309 310 311 312 313 314

        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();
        }
    }
}

315 316 317 318 319
void SessionController::interactionHandler()
{
    _interactionTimer->start();
}

320 321
void SessionController::snapshot()
{
322
    Q_ASSERT(!_sessionDisplayConnection->session().isNull());
323

324
    QString title = _sessionDisplayConnection->session()->getDynamicTitle();
Robert Knight's avatar
 
Robert Knight committed
325
    title         = title.simplified();
326

327
    // Visualize that the session is broadcasting to others
328
    if ((_copyToGroup != nullptr) && _copyToGroup->sessions().count() > 1) {
329
        title.append(QLatin1Char('*'));
330
    }
Jekyll Wu's avatar
Jekyll Wu committed
331 332 333

    // use the fallback title if needed
    if (title.isEmpty()) {
334
        title = _sessionDisplayConnection->session()->title(Session::NameRole);
Jekyll Wu's avatar
Jekyll Wu committed
335
    }
336

337
    QColor color = _sessionDisplayConnection->session()->color();
338 339 340 341
    // use the fallback color if needed
    if (!color.isValid()) {
        color = QColor(QColor::Invalid);
    }
342

343
    // apply new title
344
    _sessionDisplayConnection->session()->setTitle(Session::DisplayedTitleRole, title);
Jekyll Wu's avatar
Jekyll Wu committed
345

346
    // apply new color
347
    _sessionDisplayConnection->session()->setColor(color);
348

349 350
    // check if foreground process ended and notify if this option was requested
    if (_monitorProcessFinish) {
351
        bool isForegroundProcessActive = _sessionDisplayConnection->session()->isForegroundProcessActive();
352
        if (!_previousForegroundProcessName.isNull() && !isForegroundProcessActive) {
353 354
            KNotification::event(_sessionDisplayConnection->session()->hasFocus() ? QStringLiteral("ProcessFinished") : QStringLiteral("ProcessFinishedHidden"),
                                 i18n("The process '%1' has finished running in session '%2'", _previousForegroundProcessName, _sessionDisplayConnection->session()->nameTitle()),
355 356 357 358
                                 QPixmap(),
                                 QApplication::activeWindow(),
                                 KNotification::CloseWhenWidgetActivated);
        }
359
        _previousForegroundProcessName = isForegroundProcessActive ? _sessionDisplayConnection->session()->foregroundProcessName() : QString();
360 361
    }

Jekyll Wu's avatar
Jekyll Wu committed
362 363
    // do not forget icon
    updateSessionIcon();
364 365
}

366 367
QString SessionController::currentDir() const
{
368
    return _sessionDisplayConnection->session()->currentWorkingDirectory();
369 370
}

Kurt Hindenburg's avatar
Kurt Hindenburg committed
371
QUrl SessionController::url() const
372
{
373
    return _sessionDisplayConnection->session()->getUrl();
374 375
}

376 377
void SessionController::rename()
{
378
    renameSession();
379 380
}

Kurt Hindenburg's avatar
Kurt Hindenburg committed
381
void SessionController::openUrl(const QUrl& url)
382
{
383
    // Clear shell's command line
384 385 386
    if (!_sessionDisplayConnection->session()->isForegroundProcessActive()
            && _bookmarkValidProgramsToClear.contains(_sessionDisplayConnection->session()->foregroundProcessName())) {
        _sessionDisplayConnection->session()->sendTextToTerminal(QChar(0x03), QLatin1Char('\n')); // Ctrl+C
387 388
    }

389
    // handle local paths
Kurt Hindenburg's avatar
Kurt Hindenburg committed
390
    if (url.isLocalFile()) {
391
        QString path = url.toLocalFile();
392
        _sessionDisplayConnection->session()->sendTextToTerminal(QStringLiteral("cd ") + KShell::quoteArg(path), QLatin1Char('\r'));
Kurt Hindenburg's avatar
Kurt Hindenburg committed
393 394
    } else if (url.scheme().isEmpty()) {
        // QUrl couldn't parse what the user entered into the URL field
395
        // so just dump it to the shell
396 397
        // If you change this, change it also in autotests/BookMarkTest.cpp
        QString command = QUrl::fromPercentEncoding(url.toEncoded());
Kurt Hindenburg's avatar
Kurt Hindenburg committed
398
        if (!command.isEmpty()) {
399
            _sessionDisplayConnection->session()->sendTextToTerminal(command, QLatin1Char('\r'));
Kurt Hindenburg's avatar
Kurt Hindenburg committed
400
        }
401 402
    } else if (url.scheme() == QLatin1String("ssh")) {
        QString sshCommand = QStringLiteral("ssh ");
403 404

        if (url.port() > -1) {
405
            sshCommand += QStringLiteral("-p %1 ").arg(url.port());
406
        }
Kurt Hindenburg's avatar
Kurt Hindenburg committed
407
        if (!url.userName().isEmpty()) {
408
            sshCommand += (url.userName() + QLatin1Char('@'));
409
        }
Kurt Hindenburg's avatar
Kurt Hindenburg committed
410
        if (!url.host().isEmpty()) {
411 412
            sshCommand += url.host();
        }
413
        _sessionDisplayConnection->session()->sendTextToTerminal(sshCommand, QLatin1Char('\r'));
414

415 416
    } else if (url.scheme() == QLatin1String("telnet")) {
        QString telnetCommand = QStringLiteral("telnet ");
417

Kurt Hindenburg's avatar
Kurt Hindenburg committed
418
        if (!url.userName().isEmpty()) {
419
            telnetCommand += QStringLiteral("-l %1 ").arg(url.userName());
420
        }
Kurt Hindenburg's avatar
Kurt Hindenburg committed
421
        if (!url.host().isEmpty()) {
422
            telnetCommand += (url.host() + QLatin1Char(' '));
423 424
        }
        if (url.port() > -1) {
425
            telnetCommand += QString::number(url.port());
426 427
        }

428
        _sessionDisplayConnection->session()->sendTextToTerminal(telnetCommand, QLatin1Char('\r'));
429

Kurt Hindenburg's avatar
Kurt Hindenburg committed
430
    } else {
431
        //TODO Implement handling for other Url types
432

433
        KMessageBox::sorry(_sessionDisplayConnection->view()->window(),
434
                           i18n("Konsole does not know how to open the bookmark: ") +
Kurt Hindenburg's avatar
Kurt Hindenburg committed
435
                           url.toDisplayString());
436

437
        qCDebug(KonsoleDebug) << "Unable to open bookmark at url" << url << ", I do not know"
Kurt Hindenburg's avatar
Kurt Hindenburg committed
438
                   << " how to handle the protocol " << url.scheme();
439 440 441
    }
}

Kurt Hindenburg's avatar
Kurt Hindenburg committed
442
void SessionController::setupPrimaryScreenSpecificActions(bool use)
443
{
444
    KActionCollection* collection = actionCollection();
445 446 447 448
    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"));
449 450 451 452

    // these actions are meaningful only when primary screen is used.
    clearAction->setEnabled(use);
    resetAction->setEnabled(use);
453
    selectAllAction->setEnabled(use);
454
    selectLineAction->setEnabled(use);
455 456
}

Jekyll Wu's avatar
Jekyll Wu committed
457
void SessionController::selectionChanged(const QString& selectedText)
458
{
Jekyll Wu's avatar
Jekyll Wu committed
459 460 461
    _selectedText = selectedText;
    updateCopyAction(selectedText);
}
462

Jekyll Wu's avatar
Jekyll Wu committed
463 464
void SessionController::updateCopyAction(const QString& selectedText)
{
465
    QAction* copyAction = actionCollection()->action(QStringLiteral("edit_copy"));
466
    QAction* copyContextMenu = actionCollection()->action(QStringLiteral("edit_copy_contextmenu"));
Jekyll Wu's avatar
Jekyll Wu committed
467 468
    // copy action is meaningful only when some text is selected.
    copyAction->setEnabled(!selectedText.isEmpty());
469
    copyContextMenu->setVisible(!selectedText.isEmpty());
Jekyll Wu's avatar
Jekyll Wu committed
470 471 472 473 474 475 476 477
}

void SessionController::updateWebSearchMenu()
{
    // reset
    _webSearchMenu->setVisible(false);
    _webSearchMenu->menu()->clear();

Kurt Hindenburg's avatar
Kurt Hindenburg committed
478
    if (_selectedText.isEmpty()) {
479
        return;
Kurt Hindenburg's avatar
Kurt Hindenburg committed
480
    }
Jekyll Wu's avatar
Jekyll Wu committed
481 482

    QString searchText = _selectedText;
483
    searchText = searchText.replace(QLatin1Char('\n'), QLatin1Char(' ')).replace(QLatin1Char('\r'), QLatin1Char(' ')).simplified();
Jekyll Wu's avatar
Jekyll Wu committed
484

Kurt Hindenburg's avatar
Kurt Hindenburg committed
485
    if (searchText.isEmpty()) {
Jekyll Wu's avatar
Jekyll Wu committed
486
        return;
Kurt Hindenburg's avatar
Kurt Hindenburg committed
487
    }
Jekyll Wu's avatar
Jekyll Wu committed
488

489 490 491 492 493 494
    // Is 'Enable Web shortcuts' checked in System Settings?
    KSharedConfigPtr kuriikwsConfig = KSharedConfig::openConfig(QStringLiteral("kuriikwsfilterrc"));
    if (!kuriikwsConfig->group("General").readEntry("EnableWebShortcuts", true)) {
        return;
    }

Jekyll Wu's avatar
Jekyll Wu committed
495 496 497 498 499 500 501 502
    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)));

Kurt Hindenburg's avatar
Kurt Hindenburg committed
503
            QAction* action = nullptr;
Jekyll Wu's avatar
Jekyll Wu committed
504

505
            for (const QString &searchProvider : searchProviders) {
506
                action = new QAction(searchProvider, _webSearchMenu);
Michal Humpula's avatar
Michal Humpula committed
507
                action->setIcon(QIcon::fromTheme(filterData.iconNameForPreferredSearchProvider(searchProvider)));
Jekyll Wu's avatar
Jekyll Wu committed
508
                action->setData(filterData.queryForPreferredSearchProvider(searchProvider));
509
                connect(action, &QAction::triggered, this, &Konsole::SessionController::handleWebShortcutAction);
Jekyll Wu's avatar
Jekyll Wu committed
510 511 512 513 514
                _webSearchMenu->addAction(action);
            }

            _webSearchMenu->addSeparator();

515
            action = new QAction(i18n("Configure Web Shortcuts..."), _webSearchMenu);
Michal Humpula's avatar
Michal Humpula committed
516
            action->setIcon(QIcon::fromTheme(QStringLiteral("configure")));
517
            connect(action, &QAction::triggered, this, &Konsole::SessionController::configureWebShortcuts);
Jekyll Wu's avatar
Jekyll Wu committed
518 519 520 521 522 523 524 525 526
            _webSearchMenu->addAction(action);

            _webSearchMenu->setVisible(true);
        }
    }
}

void SessionController::handleWebShortcutAction()
{
Kurt Hindenburg's avatar
Kurt Hindenburg committed
527
    auto * action = qobject_cast<QAction*>(sender());
Kurt Hindenburg's avatar
Kurt Hindenburg committed
528
    if (action == nullptr) {
Jekyll Wu's avatar
Jekyll Wu committed
529
        return;
Kurt Hindenburg's avatar
Kurt Hindenburg committed
530
    }
Jekyll Wu's avatar
Jekyll Wu committed
531 532 533

    KUriFilterData filterData(action->data().toString());

534
    if (KUriFilter::self()->filterUri(filterData, { QStringLiteral("kurisearchfilter") })) {
535 536 537
        const QUrl url = filterData.uri();

#if KIO_VERSION < QT_VERSION_CHECK(5, 71, 0)
538
        new KRun(url, QApplication::activeWindow());
539 540 541 542 543
#else
        auto *job = new KIO::OpenUrlJob(url);
        job->setUiDelegate(new KIO::JobUiDelegate(KJobUiDelegate::AutoHandlingEnabled, QApplication::activeWindow()));
        job->start();
#endif
Jekyll Wu's avatar
Jekyll Wu committed
544 545 546 547 548
    }
}

void SessionController::configureWebShortcuts()
{
Kurt Hindenburg's avatar
Kurt Hindenburg committed
549
#if KIO_VERSION > QT_VERSION_CHECK(5, 68, 0)
550 551
    auto job = new KIO::CommandLauncherJob(QStringLiteral("kcmshell5"), { QStringLiteral("webshortcuts") });
    job->start();
Kurt Hindenburg's avatar
Kurt Hindenburg committed
552 553 554
#else
    KToolInvocation::kdeinitExec(QStringLiteral("kcmshell5"), { QStringLiteral("webshortcuts") });
#endif
555 556
}

557 558
void SessionController::sendSignal(QAction* action)
{
Kurt Hindenburg's avatar
Kurt Hindenburg committed
559
    const auto signal = action->data().toInt();
560
    _sessionDisplayConnection->session()->sendSignal(signal);
561 562
}

563
void SessionController::sendForegroundColor(uint terminator)
564
{
565
    const QColor c = _sessionDisplayConnection->view()->getForegroundColor();
566
    _sessionDisplayConnection->session()->reportForegroundColor(c, terminator);
567 568
}

569
void Konsole::SessionController::sendBackgroundColor(uint terminator)
570
{
571
    const QColor c = _sessionDisplayConnection->view()->getBackgroundColor();
572
    _sessionDisplayConnection->session()->reportBackgroundColor(c, terminator);
573 574
}

Kurt Hindenburg's avatar
Kurt Hindenburg committed
575 576
void SessionController::toggleReadOnly()
{
Kurt Hindenburg's avatar
Kurt Hindenburg committed
577
    auto *action = qobject_cast<QAction*>(sender());
Kurt Hindenburg's avatar
Kurt Hindenburg committed
578 579
    if (action != nullptr) {
        bool readonly = !isReadOnly();
580
        _sessionDisplayConnection->session()->setReadOnly(readonly);
Kurt Hindenburg's avatar
Kurt Hindenburg committed
581 582 583
    }
}

584 585
void SessionController::removeSearchFilter()
{
Kurt Hindenburg's avatar
Kurt Hindenburg committed
586
    if (_searchFilter == nullptr) {
587
        return;
Kurt Hindenburg's avatar
Kurt Hindenburg committed
588
    }
589

590
    _sessionDisplayConnection->view()->filterChain()->removeFilter(_searchFilter);
591
    delete _searchFilter;
Kurt Hindenburg's avatar
Kurt Hindenburg committed
592
    _searchFilter = nullptr;
593 594
}

595
void SessionController::setupSearchBar()
596
{
Tomaz  Canabrava's avatar
Tomaz Canabrava committed
597 598 599 600 601 602 603 604
    connect(_searchBar, &Konsole::IncrementalSearchBar::unhandledMovementKeyPressed, this, &Konsole::SessionController::movementKeyFromSearchBarReceived);
    connect(_searchBar, &Konsole::IncrementalSearchBar::closeClicked, this, &Konsole::SessionController::searchClosed);
    connect(_searchBar, &Konsole::IncrementalSearchBar::searchFromClicked, this, &Konsole::SessionController::searchFrom);
    connect(_searchBar, &Konsole::IncrementalSearchBar::findNextClicked, this, &Konsole::SessionController::findNextInHistory);
    connect(_searchBar, &Konsole::IncrementalSearchBar::findPreviousClicked, this, &Konsole::SessionController::findPreviousInHistory);
    connect(_searchBar, &Konsole::IncrementalSearchBar::highlightMatchesToggled , this , &Konsole::SessionController::highlightMatches);
    connect(_searchBar, &Konsole::IncrementalSearchBar::matchCaseToggled, this, &Konsole::SessionController::changeSearchMatch);
    connect(_searchBar, &Konsole::IncrementalSearchBar::matchRegExpToggled, this, &Konsole::SessionController::changeSearchMatch);
605 606
}

607 608
void SessionController::setShowMenuAction(QAction* action)
{
609
    _showMenuAction = action;
610 611
}

612
void SessionController::setupCommonActions()
613
{
614
    KActionCollection* collection = actionCollection();
615

616
    // Close Session
617
    QAction* action = collection->addAction(QStringLiteral("close-session"), this, &SessionController::closeSession);
Tomaz  Canabrava's avatar
Tomaz Canabrava committed
618
    action->setText(i18n("&Close Session"));
619

Michal Humpula's avatar
Michal Humpula committed
620
    action->setIcon(QIcon::fromTheme(QStringLiteral("tab-close")));
621
    collection->setDefaultShortcut(action, Konsole::ACCEL + Qt::SHIFT + Qt::Key_W);
622 623

    // Open Browser
624
    action = collection->addAction(QStringLiteral("open-browser"), this, &SessionController::openBrowser);
625
    action->setText(i18n("Open File Manager"));
Michal Humpula's avatar
Michal Humpula committed
626
    action->setIcon(QIcon::fromTheme(QStringLiteral("system-file-manager")));
627

628
    // Copy and Paste
629
    action = KStandardAction::copy(this, &SessionController::copy, collection);
630
#ifdef Q_OS_MACOS
631 632 633 634 635 636
    // 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
637 638
    // disabled at first, since nothing has been selected now
    action->setEnabled(false);
639

640 641 642 643 644 645 646 647
    // We need a different QAction on the context menu because one will be disabled when there's no selection,
    // other will be hidden.
    action = collection->addAction(QStringLiteral("edit_copy_contextmenu"));
    action->setText(i18n("Copy"));
    action->setIcon(QIcon::fromTheme(QStringLiteral("edit-copy")));
    action->setVisible(false);
    connect(action, &QAction::triggered, this, &SessionController::copy);

648
    action = KStandardAction::paste(this, &SessionController::paste, collection);
Alex Richardson's avatar
Alex Richardson committed
649
    QList<QKeySequence> pasteShortcut;
650
#ifdef Q_OS_MACOS
651 652 653 654
    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));
Alex Richardson's avatar
Alex Richardson committed
655
    pasteShortcut.append(QKeySequence(Qt::SHIFT + Qt::Key_Insert));
656
#endif
657
    collection->setDefaultShortcuts(action, pasteShortcut);
658

659
    action = collection->addAction(QStringLiteral("paste-selection"), this, &SessionController::pasteFromX11Selection);
660
    action->setText(i18n("Paste Selection"));
661
#ifdef Q_OS_MACOS
662 663 664 665
    collection->setDefaultShortcut(action, Qt::META + Qt::SHIFT + Qt::Key_V);
#else
    collection->setDefaultShortcut(action, Konsole::ACCEL + Qt::SHIFT + Qt::Key_Insert);
#endif
666

667
    _webSearchMenu = new KActionMenu(i18n("Web Search"), this);
Michal Humpula's avatar
Michal Humpula committed
668
    _webSearchMenu