SessionController.cpp 72.3 KB
Newer Older
1
/*
2
    Copyright 2006-2008 by Robert Knight <robertknight@gmail.com>
3
    Copyright 2009 by Thomas Dreibholz <dreibh@iem.uni-due.de>
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

    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
22
#include "session/SessionController.h"
23

24
#include "ProfileManager.h"
25
#include "konsoledebug.h"
26

27
// Qt
28
#include <QApplication>
29
#include <QAction>
patrick pereira's avatar
patrick pereira committed
30
#include <QList>
31
#include <QMenu>
32
#include <QKeyEvent>
33
34
#include <QPrinter>
#include <QPrintDialog>
35
#include <QFileDialog>
36
#include <QPainter>
37
#include <QStandardPaths>
38
39
#include <QUrl>
#include <QIcon>
40

41
// KDE
42
43
#include <KActionMenu>
#include <KActionCollection>
44
#include <KLocalizedString>
45
#include <KMessageBox>
46
#include <KRun>
47
#include <KShell>
Jekyll Wu's avatar
Jekyll Wu committed
48
#include <KToolInvocation>
Robert Knight's avatar
   
Robert Knight committed
49
#include <KToggleAction>
50
#include <KSelectAction>
51
#include <KXmlGuiWindow>
52
#include <KXMLGUIFactory>
53
#include <KXMLGUIBuilder>
Jekyll Wu's avatar
Jekyll Wu committed
54
55
#include <KUriFilter>
#include <KStringHandler>
Alex Richardson's avatar
Alex Richardson committed
56
#include <KSharedConfig>
57
#include <KConfigGroup>
58
#include <KCodecAction>
59
#include <KNotification>
60

61
// Konsole
62
#include "EditProfileDialog.h"
63
#include "CopyInputDialog.h"
64
#include "Emulation.h"
65
#include "Filter.h"
66
#include "History.h"
67
#include "HistorySizeDialog.h"
68
#include "widgets/IncrementalSearchBar.h"
69
#include "RenameTabDialog.h"
70
#include "ScreenWindow.h"
71
#include "session/Session.h"
72
#include "ProfileList.h"
73
#include "widgets/TerminalDisplay.h"
74
#include "session/SessionManager.h"
75
#include "Enumeration.h"
76
#include "PrintOptions.h"
77
78
#include "SaveHistoryTask.h"
#include "SearchHistoryTask.h"
79
#include "session/SessionGroup.h"
80

81
// For Unix signal names
Kurt Hindenburg's avatar
Kurt Hindenburg committed
82
#include <csignal>
83

84
using namespace Konsole;
85

86
QSet<SessionController*> SessionController::_allControllers;
87
int SessionController::_lastControllerId;
Robert Knight's avatar
   
Robert Knight committed
88

89
SessionController::SessionController(Session* session, TerminalDisplay* view, QObject* parent)
Robert Knight's avatar
   
Robert Knight committed
90
    : ViewProperties(parent)
91
92
93
    , KXMLGUIClient()
    , _session(session)
    , _view(view)
Kurt Hindenburg's avatar
Kurt Hindenburg committed
94
    , _copyToGroup(nullptr)
95
    , _profileList(nullptr)
96
97
    , _sessionIcon(QIcon())
    , _sessionIconName(QString())
Kurt Hindenburg's avatar
Kurt Hindenburg committed
98
99
100
101
102
103
104
    , _searchFilter(nullptr)
    , _urlFilter(nullptr)
    , _fileFilter(nullptr)
    , _copyInputToAllTabsAction(nullptr)
    , _findAction(nullptr)
    , _findNextAction(nullptr)
    , _findPreviousAction(nullptr)
105
    , _interactionTimer(nullptr)
Harald Hvaal's avatar
Harald Hvaal committed
106
107
    , _searchStartLine(0)
    , _prevSearchResultLine(0)
Kurt Hindenburg's avatar
Kurt Hindenburg committed
108
109
110
    , _codecAction(nullptr)
    , _switchProfileMenu(nullptr)
    , _webSearchMenu(nullptr)
111
112
    , _listenForScreenWindowUpdates(false)
    , _preventClose(false)
113
    , _selectedText(QString())
Kurt Hindenburg's avatar
Kurt Hindenburg committed
114
    , _showMenuAction(nullptr)
115
    , _bookmarkValidProgramsToClear(QStringList())
116
    , _isSearchBarEnabled(false)
117
    , _editProfileDialog(nullptr)
118
    , _searchBar(view->searchBar())
119
    , _monitorProcessFinish(false)
120
{
Kurt Hindenburg's avatar
Kurt Hindenburg committed
121
122
    Q_ASSERT(session);
    Q_ASSERT(view);
123

124
125
    _sessionDisplayConnection = new SessionDisplayConnection(session, view, this);

126
    // handle user interface related to session (menus etc.)
127
    if (isKonsolePart()) {
128
        setComponentName(QStringLiteral("konsole"), i18n("Konsole"));
129
        setXMLFile(QStringLiteral("partui.rc"));
130
131
        setupCommonActions();
    } else {
132
        setXMLFile(QStringLiteral("sessionui.rc"));
133
134
135
        setupCommonActions();
        setupExtraActions();
    }
136

137
    actionCollection()->addAssociatedWidget(view);
138
139
140

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

144
    setIdentifier(++_lastControllerId);
145
    sessionAttributeChanged();
146

147
148
    connect(_sessionDisplayConnection->view(), &TerminalDisplay::compositeFocusChanged, this, &SessionController::viewFocusChangeHandler);
    _sessionDisplayConnection->view()->setSessionController(this);
Robert Knight's avatar
   
Robert Knight committed
149

150
    // install filter on the view to highlight URLs and files
151
    updateFilterList(SessionManager::instance()->sessionProfile(_sessionDisplayConnection->session()));
152

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

156
    // listen for session resize requests
157
    connect(_sessionDisplayConnection->session(), &Konsole::Session::resizeRequest, this, &Konsole::SessionController::sessionResizeRequest);
158

159
    // listen for popup menu requests
160
    connect(_sessionDisplayConnection->view(), &Konsole::TerminalDisplay::configureRequest, this, &Konsole::SessionController::showDisplayContextMenu);
161

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

Robert Knight's avatar
   
Robert Knight committed
165
    // listen to activity / silence notifications from session
166
    connect(_sessionDisplayConnection->session(), &Konsole::Session::notificationsChanged, this, &Konsole::SessionController::sessionNotificationsChanged);
167
    // listen to title and icon changes
168
169
    connect(_sessionDisplayConnection->session(), &Konsole::Session::sessionAttributeChanged, this, &Konsole::SessionController::sessionAttributeChanged);
    connect(_sessionDisplayConnection->session(), &Konsole::Session::readOnlyChanged, this, &Konsole::SessionController::sessionReadOnlyChanged);
170

171
172
    connect(this, &Konsole::SessionController::tabRenamedByUser, _sessionDisplayConnection->session(), &Konsole::Session::tabTitleSetByUser);
    connect(this, &Konsole::SessionController::tabColoredByUser, _sessionDisplayConnection->session(), &Konsole::Session::tabColorSetByUser);
173

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

176
    // listen for color changes
177
178
    connect(_sessionDisplayConnection->session(), &Konsole::Session::changeBackgroundColorRequest, _sessionDisplayConnection->view(), &Konsole::TerminalDisplay::setBackgroundColor);
    connect(_sessionDisplayConnection->session(), &Konsole::Session::changeForegroundColorRequest, _sessionDisplayConnection->view(), &Konsole::TerminalDisplay::setForegroundColor);
179

180
    // update the title when the session starts
181
    connect(_sessionDisplayConnection->session(), &Konsole::Session::started, this, &Konsole::SessionController::snapshot);
182

183
    // listen for output changes to set activity flag
184
    connect(_sessionDisplayConnection->session()->emulation(), &Konsole::Emulation::outputChanged, this, &Konsole::SessionController::fireActivity);
185
186

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

Robert Knight's avatar
   
Robert Knight committed
190
    // listen for flow control status changes
191
192
    connect(_sessionDisplayConnection->session(), &Konsole::Session::flowControlEnabledChanged, _sessionDisplayConnection->view(), &Konsole::TerminalDisplay::setFlowControlWarningEnabled);
    _sessionDisplayConnection->view()->setFlowControlWarningEnabled(_sessionDisplayConnection->session()->flowControlEnabled());
Robert Knight's avatar
   
Robert Knight committed
193

194
195
    // take a snapshot of the session state every so often when
    // user activity occurs
196
197
198
    //
    // the timer is owned by the session so that it will be destroyed along
    // with the session
199
    _interactionTimer = new QTimer(_sessionDisplayConnection->session());
200
    _interactionTimer->setSingleShot(true);
201
    _interactionTimer->setInterval(500);
202
    connect(_interactionTimer, &QTimer::timeout, this, &Konsole::SessionController::snapshot);
203
    connect(_sessionDisplayConnection->view(), &Konsole::TerminalDisplay::compositeFocusChanged,
204
            this, [this](bool focused) { if (focused) { interactionHandler(); }});
205
    connect(_sessionDisplayConnection->view(), &Konsole::TerminalDisplay::keyPressedSignal,
206
            this, &Konsole::SessionController::interactionHandler);
207

208
    // take a snapshot of the session state periodically in the background
209
    auto backgroundTimer = new QTimer(_sessionDisplayConnection->session());
210
211
    backgroundTimer->setSingleShot(false);
    backgroundTimer->setInterval(2000);
212
    connect(backgroundTimer, &QTimer::timeout, this, &Konsole::SessionController::snapshot);
213
214
    backgroundTimer->start();

215
    // xterm '10;?' request
216
    connect(_sessionDisplayConnection->session(), &Konsole::Session::getForegroundColor,
217
            this, &Konsole::SessionController::sendForegroundColor);
218
    // xterm '11;?' request
219
    connect(_sessionDisplayConnection->session(), &Konsole::Session::getBackgroundColor,
220
221
            this, &Konsole::SessionController::sendBackgroundColor);

222
    _allControllers.insert(this);
223
224
225

    // A list of programs that accept Ctrl+C to clear command line used
    // before outputting bookmark.
226
227
228
229
230
231
232
233
    _bookmarkValidProgramsToClear = QStringList({
        QStringLiteral("bash"),
        QStringLiteral("fish"),
        QStringLiteral("sh"),
        QStringLiteral("tcsh"),
        QStringLiteral("zsh")
    });

234
235
    setupSearchBar();
    _searchBar->setVisible(_isSearchBarEnabled);
236
237
238
}

SessionController::~SessionController()
239
{
Kurt Hindenburg's avatar
Kurt Hindenburg committed
240
    _allControllers.remove(this);
241
242

    if (!_editProfileDialog.isNull()) {
Tomaz  Canabrava's avatar
Tomaz Canabrava committed
243
        _editProfileDialog->deleteLater();
244
    }
245
    if(factory() != nullptr) {
246
247
        factory()->removeClient(this);
    }
248
}
249
void SessionController::trackOutput(QKeyEvent* event)
250
{
251
    Q_ASSERT(_sessionDisplayConnection->view()->screenWindow());
252

253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
    // 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;


271
272
    // Only jump to the bottom if the user actually typed something in,
    // not if the user e. g. just pressed a modifier.
273
    if (event->text().isEmpty() && ((event->modifiers() != 0u) || shouldNotTriggerScroll)) {
274
        return;
275
    }
276

277
    _sessionDisplayConnection->view()->screenWindow()->setTrackOutput(true);
278
}
279
280
281
282
283
284
285
286
287
288
289
290

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
291
        disconnect(_sessionDisplayConnection->session(), &Konsole::Session::bellRequest, nullptr, nullptr);
292
        // second, connect the newly focused view to listen for the session's bell signal
293
        connect(_sessionDisplayConnection->session(), &Konsole::Session::bellRequest, _sessionDisplayConnection->view(), &Konsole::TerminalDisplay::bell);
294
295
296
297
298
299
300
301
302

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

303
304
305
306
307
void SessionController::interactionHandler()
{
    _interactionTimer->start();
}

308
309
void SessionController::snapshot()
{
310
    Q_ASSERT(!_sessionDisplayConnection->session().isNull());
311

312
    QString title = _sessionDisplayConnection->session()->getDynamicTitle();
Robert Knight's avatar
   
Robert Knight committed
313
    title         = title.simplified();
314

315
    // Visualize that the session is broadcasting to others
316
    if ((_copyToGroup != nullptr) && _copyToGroup->sessions().count() > 1) {
317
        title.append(QLatin1Char('*'));
318
    }
Jekyll Wu's avatar
Jekyll Wu committed
319
320
321

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

325
    QColor color = _sessionDisplayConnection->session()->color();
326
327
328
329
    // use the fallback color if needed
    if (!color.isValid()) {
        color = QColor(QColor::Invalid);
    }
330

331
    // apply new title
332
    _sessionDisplayConnection->session()->setTitle(Session::DisplayedTitleRole, title);
Jekyll Wu's avatar
Jekyll Wu committed
333

334
    // apply new color
335
    _sessionDisplayConnection->session()->setColor(color);
336

337
338
    // check if foreground process ended and notify if this option was requested
    if (_monitorProcessFinish) {
339
        bool isForegroundProcessActive = _sessionDisplayConnection->session()->isForegroundProcessActive();
340
        if (!_previousForegroundProcessName.isNull() && !isForegroundProcessActive) {
341
342
            KNotification::event(_sessionDisplayConnection->session()->hasFocus() ? QStringLiteral("ProcessFinished") : QStringLiteral("ProcessFinishedHidden"),
                                 i18n("The process '%1' has finished running in session '%2'", _previousForegroundProcessName, _sessionDisplayConnection->session()->nameTitle()),
343
344
345
346
                                 QPixmap(),
                                 QApplication::activeWindow(),
                                 KNotification::CloseWhenWidgetActivated);
        }
347
        _previousForegroundProcessName = isForegroundProcessActive ? _sessionDisplayConnection->session()->foregroundProcessName() : QString();
348
349
    }

Jekyll Wu's avatar
Jekyll Wu committed
350
351
    // do not forget icon
    updateSessionIcon();
352
353
}

354
355
QString SessionController::currentDir() const
{
356
    return _sessionDisplayConnection->session()->currentWorkingDirectory();
357
358
}

Kurt Hindenburg's avatar
Kurt Hindenburg committed
359
QUrl SessionController::url() const
360
{
361
    return _sessionDisplayConnection->session()->getUrl();
362
363
}

364
365
void SessionController::rename()
{
366
    renameSession();
367
368
}

Kurt Hindenburg's avatar
Kurt Hindenburg committed
369
void SessionController::openUrl(const QUrl& url)
370
{
371
    // Clear shell's command line
372
373
374
    if (!_sessionDisplayConnection->session()->isForegroundProcessActive()
            && _bookmarkValidProgramsToClear.contains(_sessionDisplayConnection->session()->foregroundProcessName())) {
        _sessionDisplayConnection->session()->sendTextToTerminal(QChar(0x03), QLatin1Char('\n')); // Ctrl+C
375
376
    }

377
    // handle local paths
Kurt Hindenburg's avatar
Kurt Hindenburg committed
378
    if (url.isLocalFile()) {
379
        QString path = url.toLocalFile();
380
        _sessionDisplayConnection->session()->sendTextToTerminal(QStringLiteral("cd ") + KShell::quoteArg(path), QLatin1Char('\r'));
Kurt Hindenburg's avatar
Kurt Hindenburg committed
381
382
    } else if (url.scheme().isEmpty()) {
        // QUrl couldn't parse what the user entered into the URL field
383
        // so just dump it to the shell
384
385
        // If you change this, change it also in autotests/BookMarkTest.cpp
        QString command = QUrl::fromPercentEncoding(url.toEncoded());
Kurt Hindenburg's avatar
Kurt Hindenburg committed
386
        if (!command.isEmpty()) {
387
            _sessionDisplayConnection->session()->sendTextToTerminal(command, QLatin1Char('\r'));
Kurt Hindenburg's avatar
Kurt Hindenburg committed
388
        }
389
390
    } else if (url.scheme() == QLatin1String("ssh")) {
        QString sshCommand = QStringLiteral("ssh ");
391
392

        if (url.port() > -1) {
393
            sshCommand += QStringLiteral("-p %1 ").arg(url.port());
394
        }
Kurt Hindenburg's avatar
Kurt Hindenburg committed
395
        if (!url.userName().isEmpty()) {
396
            sshCommand += (url.userName() + QLatin1Char('@'));
397
        }
Kurt Hindenburg's avatar
Kurt Hindenburg committed
398
        if (!url.host().isEmpty()) {
399
400
            sshCommand += url.host();
        }
401
        _sessionDisplayConnection->session()->sendTextToTerminal(sshCommand, QLatin1Char('\r'));
402

403
404
    } else if (url.scheme() == QLatin1String("telnet")) {
        QString telnetCommand = QStringLiteral("telnet ");
405

Kurt Hindenburg's avatar
Kurt Hindenburg committed
406
        if (!url.userName().isEmpty()) {
407
            telnetCommand += QStringLiteral("-l %1 ").arg(url.userName());
408
        }
Kurt Hindenburg's avatar
Kurt Hindenburg committed
409
        if (!url.host().isEmpty()) {
410
            telnetCommand += (url.host() + QLatin1Char(' '));
411
412
        }
        if (url.port() > -1) {
413
            telnetCommand += QString::number(url.port());
414
415
        }

416
        _sessionDisplayConnection->session()->sendTextToTerminal(telnetCommand, QLatin1Char('\r'));
417

Kurt Hindenburg's avatar
Kurt Hindenburg committed
418
    } else {
419
        //TODO Implement handling for other Url types
420

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

425
        qCDebug(KonsoleDebug) << "Unable to open bookmark at url" << url << ", I do not know"
Kurt Hindenburg's avatar
Kurt Hindenburg committed
426
                   << " how to handle the protocol " << url.scheme();
427
428
429
    }
}

Kurt Hindenburg's avatar
Kurt Hindenburg committed
430
void SessionController::setupPrimaryScreenSpecificActions(bool use)
431
{
432
    KActionCollection* collection = actionCollection();
433
434
435
436
    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"));
437
438
439
440

    // these actions are meaningful only when primary screen is used.
    clearAction->setEnabled(use);
    resetAction->setEnabled(use);
441
    selectAllAction->setEnabled(use);
442
    selectLineAction->setEnabled(use);
443
444
}

Jekyll Wu's avatar
Jekyll Wu committed
445
void SessionController::selectionChanged(const QString& selectedText)
446
{
Jekyll Wu's avatar
Jekyll Wu committed
447
448
449
    _selectedText = selectedText;
    updateCopyAction(selectedText);
}
450

Jekyll Wu's avatar
Jekyll Wu committed
451
452
void SessionController::updateCopyAction(const QString& selectedText)
{
453
    QAction* copyAction = actionCollection()->action(QStringLiteral("edit_copy"));
454
    QAction* copyContextMenu = actionCollection()->action(QStringLiteral("edit_copy_contextmenu"));
Jekyll Wu's avatar
Jekyll Wu committed
455
456
    // copy action is meaningful only when some text is selected.
    copyAction->setEnabled(!selectedText.isEmpty());
457
    copyContextMenu->setVisible(!selectedText.isEmpty());
Jekyll Wu's avatar
Jekyll Wu committed
458
459
460
461
462
463
464
465
}

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

Kurt Hindenburg's avatar
Kurt Hindenburg committed
466
    if (_selectedText.isEmpty()) {
467
        return;
Kurt Hindenburg's avatar
Kurt Hindenburg committed
468
    }
Jekyll Wu's avatar
Jekyll Wu committed
469
470

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

Kurt Hindenburg's avatar
Kurt Hindenburg committed
473
    if (searchText.isEmpty()) {
Jekyll Wu's avatar
Jekyll Wu committed
474
        return;
Kurt Hindenburg's avatar
Kurt Hindenburg committed
475
    }
Jekyll Wu's avatar
Jekyll Wu committed
476

477
478
479
480
481
482
    // 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
483
484
485
486
487
488
489
490
    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
491
            QAction* action = nullptr;
Jekyll Wu's avatar
Jekyll Wu committed
492

493
            for (const QString &searchProvider : searchProviders) {
494
                action = new QAction(searchProvider, _webSearchMenu);
Michal Humpula's avatar
Michal Humpula committed
495
                action->setIcon(QIcon::fromTheme(filterData.iconNameForPreferredSearchProvider(searchProvider)));
Jekyll Wu's avatar
Jekyll Wu committed
496
                action->setData(filterData.queryForPreferredSearchProvider(searchProvider));
497
                connect(action, &QAction::triggered, this, &Konsole::SessionController::handleWebShortcutAction);
Jekyll Wu's avatar
Jekyll Wu committed
498
499
500
501
502
                _webSearchMenu->addAction(action);
            }

            _webSearchMenu->addSeparator();

503
            action = new QAction(i18n("Configure Web Shortcuts..."), _webSearchMenu);
Michal Humpula's avatar
Michal Humpula committed
504
            action->setIcon(QIcon::fromTheme(QStringLiteral("configure")));
505
            connect(action, &QAction::triggered, this, &Konsole::SessionController::configureWebShortcuts);
Jekyll Wu's avatar
Jekyll Wu committed
506
507
508
509
510
511
512
513
514
            _webSearchMenu->addAction(action);

            _webSearchMenu->setVisible(true);
        }
    }
}

void SessionController::handleWebShortcutAction()
{
Kurt Hindenburg's avatar
Kurt Hindenburg committed
515
    auto * action = qobject_cast<QAction*>(sender());
Kurt Hindenburg's avatar
Kurt Hindenburg committed
516
    if (action == nullptr) {
Jekyll Wu's avatar
Jekyll Wu committed
517
        return;
Kurt Hindenburg's avatar
Kurt Hindenburg committed
518
    }
Jekyll Wu's avatar
Jekyll Wu committed
519
520
521

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

522
    if (KUriFilter::self()->filterUri(filterData, { QStringLiteral("kurisearchfilter") })) {
Kurt Hindenburg's avatar
Kurt Hindenburg committed
523
        const QUrl& url = filterData.uri();
524
        new KRun(url, QApplication::activeWindow());
Jekyll Wu's avatar
Jekyll Wu committed
525
526
527
528
529
    }
}

void SessionController::configureWebShortcuts()
{
530
    KToolInvocation::kdeinitExec(QStringLiteral("kcmshell5"), { QStringLiteral("webshortcuts") });
531
532
}

533
534
void SessionController::sendSignal(QAction* action)
{
Kurt Hindenburg's avatar
Kurt Hindenburg committed
535
    const auto signal = action->data().toInt();
536
    _sessionDisplayConnection->session()->sendSignal(signal);
537
538
}

539
540
void SessionController::sendForegroundColor()
{
541
542
    const QColor c = _sessionDisplayConnection->view()->getForegroundColor();
    _sessionDisplayConnection->session()->reportForegroundColor(c);
543
544
}

545
546
void SessionController::sendBackgroundColor()
{
547
548
    const QColor c = _sessionDisplayConnection->view()->getBackgroundColor();
    _sessionDisplayConnection->session()->reportBackgroundColor(c);
549
550
}

Kurt Hindenburg's avatar
Kurt Hindenburg committed
551
552
void SessionController::toggleReadOnly()
{
Kurt Hindenburg's avatar
Kurt Hindenburg committed
553
    auto *action = qobject_cast<QAction*>(sender());
Kurt Hindenburg's avatar
Kurt Hindenburg committed
554
555
    if (action != nullptr) {
        bool readonly = !isReadOnly();
556
        _sessionDisplayConnection->session()->setReadOnly(readonly);
Kurt Hindenburg's avatar
Kurt Hindenburg committed
557
558
559
    }
}

560
561
void SessionController::removeSearchFilter()
{
Kurt Hindenburg's avatar
Kurt Hindenburg committed
562
    if (_searchFilter == nullptr) {
563
        return;
Kurt Hindenburg's avatar
Kurt Hindenburg committed
564
    }
565

566
    _sessionDisplayConnection->view()->filterChain()->removeFilter(_searchFilter);
567
    delete _searchFilter;
Kurt Hindenburg's avatar
Kurt Hindenburg committed
568
    _searchFilter = nullptr;
569
570
}

571
void SessionController::setupSearchBar()
572
{
Tomaz  Canabrava's avatar
Tomaz Canabrava committed
573
574
575
576
577
578
579
580
    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);
581
582
}

583
584
void SessionController::setShowMenuAction(QAction* action)
{
585
    _showMenuAction = action;
586
587
}

588
void SessionController::setupCommonActions()
589
{
590
    KActionCollection* collection = actionCollection();
591

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

Michal Humpula's avatar
Michal Humpula committed
596
    action->setIcon(QIcon::fromTheme(QStringLiteral("tab-close")));
597
    collection->setDefaultShortcut(action, Konsole::ACCEL + Qt::SHIFT + Qt::Key_W);
598
599

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

604
    // Copy and Paste
605
    action = KStandardAction::copy(this, &SessionController::copy, collection);
606
#ifdef Q_OS_MACOS
607
608
609
610
611
612
    // 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
613
614
    // disabled at first, since nothing has been selected now
    action->setEnabled(false);
615

616
617
618
619
620
621
622
623
    // 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);

624
    action = KStandardAction::paste(this, &SessionController::paste, collection);
Alex Richardson's avatar
Alex Richardson committed
625
    QList<QKeySequence> pasteShortcut;
626
#ifdef Q_OS_MACOS
627
628
629
630
    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
631
    pasteShortcut.append(QKeySequence(Qt::SHIFT + Qt::Key_Insert));
632
#endif
633
    collection->setDefaultShortcuts(action, pasteShortcut);
634

635
    action = collection->addAction(QStringLiteral("paste-selection"), this, &SessionController::pasteFromX11Selection);
636
    action->setText(i18n("Paste Selection"));
637
#ifdef Q_OS_MACOS
638
639
640
641
    collection->setDefaultShortcut(action, Qt::META + Qt::SHIFT + Qt::Key_V);
#else
    collection->setDefaultShortcut(action, Konsole::ACCEL + Qt::SHIFT + Qt::Key_Insert);
#endif
642

643
    _webSearchMenu = new KActionMenu(i18n("Web Search"), this);
Michal Humpula's avatar
Michal Humpula committed
644
    _webSearchMenu->setIcon(QIcon::fromTheme(QStringLiteral("preferences-web-browser-shortcuts")));
Jekyll Wu's avatar
Jekyll Wu committed
645
    _webSearchMenu->setVisible(false);
646
    collection->addAction(QStringLiteral("web-search"), _webSearchMenu);
Jekyll Wu's avatar
Jekyll Wu committed
647
648


649
    action = collection->addAction(QStringLiteral("select-all"), this, &SessionController::selectAll);
650
    action->setText(i18n("&Select All"));
Michal Humpula's avatar
Michal Humpula committed
651
    action->setIcon(QIcon::fromTheme(QStringLiteral("edit-select-all")));
652

653
    action = collection->addAction(QStringLiteral("select-line"), this, &SessionController::selectLine);
654
655
    action->setText(i18n("Select &Line"));

656
    action = KStandardAction::saveAs(this, &SessionController::saveHistory, collection);
657
    action->setText(i18n("Save Output &As..."));
658
#ifdef Q_OS_MACOS
659
660
    action->setShortcut(QKeySequence(Qt::META + Qt::Key_S));
#endif
661

662
    action = KStandardAction::print(this, &SessionController::print_screen, collection);
663
    action->setText(i18n("&Print Screen..."));
664
    collection->setDefaultShortcut(action, Konsole::ACCEL + Qt::SHIFT + Qt::Key_P);
665

666
    action = collection->addAction(QStringLiteral("adjust-history"), this, &SessionController::showHistoryOptions);
667
    action->setText(i18n("Adjust Scrollback..."));
Michal Humpula's avatar
Michal Humpula committed
668
    action->setIcon(QIcon::fromTheme(QStringLiteral("configure")));
669

670
    action = collection->addAction(QStringLiteral("clear-history"), this, &SessionController::clearHistory);
671
    action->setText(i18n("Clear Scrollback"));
Michal Humpula's avatar
Michal Humpula committed
672
    action->setIcon(QIcon::fromTheme(QStringLiteral("edit-clear-history")));
673

674
    action = collection->addAction(QStringLiteral("clear-history-and-reset"), this, &SessionController::clearHistoryAndReset);
675
    action->setText(i18n("Clear Scrollback and Reset"));
Michal Humpula's avatar
Michal Humpula committed
676
    action->setIcon(QIcon::fromTheme(QStringLiteral("edit-clear-history")));
677
    collection->setDefaultShortcut(action, Konsole::ACCEL + Qt::SHIFT + Qt::Key_K);
678
679

    // Profile Options
680
    action = collection->addAction(QStringLiteral("edit-current-profile"), this, &SessionController::editCurrentProfile);
681
    action->setText(i18n("Edit Current Profile..."));
Michal Humpula's avatar
Michal Humpula committed
682
    action->setIcon(QIcon::fromTheme(QStringLiteral("document-properties")));
683

684
    _switchProfileMenu = new KActionMenu(i18n("Switch Profile"), this);
685
    collection->addAction(QStringLiteral("switch-profile"), _switchProfileMenu);
686
    connect(_switchProfileMenu->menu(), &QMenu::aboutToShow, this, &Konsole::SessionController::prepareSwitchProfileMenu);
687

688
    // History
689
    _findAction = KStandardAction::find(this, &SessionController::searchBarEvent, collection);
690

691
    _findNextAction = KStandardAction::findNext(this, &SessionController::findNextInHistory, collection);
692
693
    _findNextAction->setEnabled(false);

694
    _findPreviousAction = KStandardAction::findPrev(this, &SessionController::findPreviousInHistory, collection);
695
    _findPreviousAction->setEnabled(false);
696

697
698
699
700
701
702
703
704
705
706
#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

707
708
    // Character Encoding
    _codecAction = new KCodecAction(i18n("Set &Encoding"), this);
Michal Humpula's avatar
Michal Humpula committed
709
    _codecAction->setIcon(QIcon::fromTheme(QStringLiteral("character-set")));
710
    collection->addAction(QStringLiteral("set-encoding"), _codecAction);
711
712
    _codecAction->setCurrentCodec(QString::fromUtf8(_sessionDisplayConnection->session()->codec()));
    connect(_sessionDisplayConnection->session(), &Konsole::Session::sessionCodecChanged, this, &Konsole::SessionController::updateCodecAction);
713
714
715
    connect(_codecAction,
            QOverload<QTextCodec*>::of(&KCodecAction::triggered), this,
            &Konsole::SessionController::changeCodec);
716
717

    // Read-only
718
    action = collection->addAction(QStringLiteral("view-readonly"), this, &SessionController::toggleReadOnly);
719
720
721
    action->setText(i18nc("@item:inmenu A read only (locked) session", "Read-only"));
    action->setCheckable(true);
    updateReadOnlyActionStates();
722
723
724
725
726
727
}

void SessionController::setupExtraActions()
{
    KActionCollection* collection = actionCollection();

728
    // Rename Session
729
    QAction* action = collection->addAction(QStringLiteral("rename-session"), this, &SessionController::renameSession);
730
    action->setText(i18n("&Current Tab Settings..."));
Michal Humpula's avatar
Michal Humpula committed
731
    action->setIcon(QIcon::fromTheme(QStringLiteral("edit-rename")));
732
    collection->setDefaultShortcut(action, Konsole::ACCEL + Qt::ALT + Qt::Key_S);
733

734
    // Copy input to ==> all tabs
Kurt Hindenburg's avatar
Kurt Hindenburg committed
735
    auto* copyInputToAllTabsAction = collection->add<KToggleAction>(QStringLiteral("copy-input-to-all-tabs"));
736
737
738
739
740
741
    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
Kurt Hindenburg's avatar
Kurt Hindenburg committed
742
    auto* copyInputToSelectedTabsAction = collection->add<KToggleAction>(QStringLiteral("copy-input-to-selected-tabs"));
743
    copyInputToSelectedTabsAction->setText(i18n("&Select Tabs..."));
744
    collection->setDefaultShortcut(copyInputToSelectedTabsAction, Konsole::ACCEL + Qt::SHIFT + Qt::Key_Period);
745
746
747
    copyInputToSelectedTabsAction->setData(CopyInputToSelectedTabsMode);

    // Copy input to ==> none
Kurt Hindenburg's avatar
Kurt Hindenburg committed
748
    auto* copyInputToNoneAction = collection->add<KToggleAction>(QStringLiteral("copy-input-to-none"));
749
    copyInputToNoneAction->setText(i18nc("@action:inmenu Do not select any tabs", "&None"));