SessionController.cpp 72.5 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
66
67
68
69
70
#include "filterHotSpots/FileFilter.h"
#include "filterHotSpots/Filter.h"
#include "filterHotSpots/FilterChain.h"
#include "filterHotSpots/HotSpot.h"
#include "filterHotSpots/RegExpFilter.h"
#include "filterHotSpots/UrlFilter.h"
71
#include "History.h"
72
#include "HistorySizeDialog.h"
73
#include "widgets/IncrementalSearchBar.h"
74
#include "RenameTabDialog.h"
75
#include "ScreenWindow.h"
76
#include "session/Session.h"
77
#include "ProfileList.h"
78
#include "widgets/TerminalDisplay.h"
79
#include "session/SessionManager.h"
80
#include "Enumeration.h"
81
#include "PrintOptions.h"
82
83
#include "SaveHistoryTask.h"
#include "SearchHistoryTask.h"
84
#include "session/SessionGroup.h"
85

86
// For Unix signal names
Kurt Hindenburg's avatar
Kurt Hindenburg committed
87
#include <csignal>
88

89
using namespace Konsole;
90

91
QSet<SessionController*> SessionController::_allControllers;
92
int SessionController::_lastControllerId;
Robert Knight's avatar
   
Robert Knight committed
93

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

129
130
    _sessionDisplayConnection = new SessionDisplayConnection(session, view, this);

131
    // handle user interface related to session (menus etc.)
132
    if (isKonsolePart()) {
133
        setComponentName(QStringLiteral("konsole"), i18n("Konsole"));
134
        setXMLFile(QStringLiteral("partui.rc"));
135
136
        setupCommonActions();
    } else {
137
        setXMLFile(QStringLiteral("sessionui.rc"));
138
139
140
        setupCommonActions();
        setupExtraActions();
    }
141

142
    actionCollection()->addAssociatedWidget(view);
143
144
145

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

149
    setIdentifier(++_lastControllerId);
150
    sessionAttributeChanged();
151

152
153
    connect(_sessionDisplayConnection->view(), &TerminalDisplay::compositeFocusChanged, this, &SessionController::viewFocusChangeHandler);
    _sessionDisplayConnection->view()->setSessionController(this);
Robert Knight's avatar
   
Robert Knight committed
154

155
    // install filter on the view to highlight URLs and files
156
    updateFilterList(SessionManager::instance()->sessionProfile(_sessionDisplayConnection->session()));
157

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

161
    // listen for session resize requests
162
    connect(_sessionDisplayConnection->session(), &Konsole::Session::resizeRequest, this, &Konsole::SessionController::sessionResizeRequest);
163

164
    // listen for popup menu requests
165
    connect(_sessionDisplayConnection->view(), &Konsole::TerminalDisplay::configureRequest, this, &Konsole::SessionController::showDisplayContextMenu);
166

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

Robert Knight's avatar
   
Robert Knight committed
170
    // listen to activity / silence notifications from session
171
    connect(_sessionDisplayConnection->session(), &Konsole::Session::notificationsChanged, this, &Konsole::SessionController::sessionNotificationsChanged);
172
    // listen to title and icon changes
173
174
    connect(_sessionDisplayConnection->session(), &Konsole::Session::sessionAttributeChanged, this, &Konsole::SessionController::sessionAttributeChanged);
    connect(_sessionDisplayConnection->session(), &Konsole::Session::readOnlyChanged, this, &Konsole::SessionController::sessionReadOnlyChanged);
175

176
177
    connect(this, &Konsole::SessionController::tabRenamedByUser, _sessionDisplayConnection->session(), &Konsole::Session::tabTitleSetByUser);
    connect(this, &Konsole::SessionController::tabColoredByUser, _sessionDisplayConnection->session(), &Konsole::Session::tabColorSetByUser);
178

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

181
    // listen for color changes
182
183
    connect(_sessionDisplayConnection->session(), &Konsole::Session::changeBackgroundColorRequest, _sessionDisplayConnection->view(), &Konsole::TerminalDisplay::setBackgroundColor);
    connect(_sessionDisplayConnection->session(), &Konsole::Session::changeForegroundColorRequest, _sessionDisplayConnection->view(), &Konsole::TerminalDisplay::setForegroundColor);
184

185
    // update the title when the session starts
186
    connect(_sessionDisplayConnection->session(), &Konsole::Session::started, this, &Konsole::SessionController::snapshot);
187

188
    // listen for output changes to set activity flag
189
    connect(_sessionDisplayConnection->session()->emulation(), &Konsole::Emulation::outputChanged, this, &Konsole::SessionController::fireActivity);
190
191

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

Robert Knight's avatar
   
Robert Knight committed
195
    // listen for flow control status changes
196
197
    connect(_sessionDisplayConnection->session(), &Konsole::Session::flowControlEnabledChanged, _sessionDisplayConnection->view(), &Konsole::TerminalDisplay::setFlowControlWarningEnabled);
    _sessionDisplayConnection->view()->setFlowControlWarningEnabled(_sessionDisplayConnection->session()->flowControlEnabled());
Robert Knight's avatar
   
Robert Knight committed
198

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

213
    // take a snapshot of the session state periodically in the background
214
    auto backgroundTimer = new QTimer(_sessionDisplayConnection->session());
215
216
    backgroundTimer->setSingleShot(false);
    backgroundTimer->setInterval(2000);
217
    connect(backgroundTimer, &QTimer::timeout, this, &Konsole::SessionController::snapshot);
218
219
    backgroundTimer->start();

220
    // xterm '10;?' request
221
    connect(_sessionDisplayConnection->session(), &Konsole::Session::getForegroundColor,
222
            this, &Konsole::SessionController::sendForegroundColor);
223
    // xterm '11;?' request
224
    connect(_sessionDisplayConnection->session(), &Konsole::Session::getBackgroundColor,
225
226
            this, &Konsole::SessionController::sendBackgroundColor);

227
    _allControllers.insert(this);
228
229
230

    // A list of programs that accept Ctrl+C to clear command line used
    // before outputting bookmark.
231
232
233
234
235
236
237
238
    _bookmarkValidProgramsToClear = QStringList({
        QStringLiteral("bash"),
        QStringLiteral("fish"),
        QStringLiteral("sh"),
        QStringLiteral("tcsh"),
        QStringLiteral("zsh")
    });

239
240
    setupSearchBar();
    _searchBar->setVisible(_isSearchBarEnabled);
241
242
243
}

SessionController::~SessionController()
244
{
Kurt Hindenburg's avatar
Kurt Hindenburg committed
245
    _allControllers.remove(this);
246
247

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

258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
    // 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;


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

282
    _sessionDisplayConnection->view()->screenWindow()->setTrackOutput(true);
283
}
284
285
286
287
288
289
290
291
292
293
294
295

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

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

308
309
310
311
312
void SessionController::interactionHandler()
{
    _interactionTimer->start();
}

313
314
void SessionController::snapshot()
{
315
    Q_ASSERT(!_sessionDisplayConnection->session().isNull());
316

317
    QString title = _sessionDisplayConnection->session()->getDynamicTitle();
Robert Knight's avatar
   
Robert Knight committed
318
    title         = title.simplified();
319

320
    // Visualize that the session is broadcasting to others
321
    if ((_copyToGroup != nullptr) && _copyToGroup->sessions().count() > 1) {
322
        title.append(QLatin1Char('*'));
323
    }
Jekyll Wu's avatar
Jekyll Wu committed
324
325
326

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

330
    QColor color = _sessionDisplayConnection->session()->color();
331
332
333
334
    // use the fallback color if needed
    if (!color.isValid()) {
        color = QColor(QColor::Invalid);
    }
335

336
    // apply new title
337
    _sessionDisplayConnection->session()->setTitle(Session::DisplayedTitleRole, title);
Jekyll Wu's avatar
Jekyll Wu committed
338

339
    // apply new color
340
    _sessionDisplayConnection->session()->setColor(color);
341

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

Jekyll Wu's avatar
Jekyll Wu committed
355
356
    // do not forget icon
    updateSessionIcon();
357
358
}

359
360
QString SessionController::currentDir() const
{
361
    return _sessionDisplayConnection->session()->currentWorkingDirectory();
362
363
}

Kurt Hindenburg's avatar
Kurt Hindenburg committed
364
QUrl SessionController::url() const
365
{
366
    return _sessionDisplayConnection->session()->getUrl();
367
368
}

369
370
void SessionController::rename()
{
371
    renameSession();
372
373
}

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

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

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

408
409
    } else if (url.scheme() == QLatin1String("telnet")) {
        QString telnetCommand = QStringLiteral("telnet ");
410

Kurt Hindenburg's avatar
Kurt Hindenburg committed
411
        if (!url.userName().isEmpty()) {
412
            telnetCommand += QStringLiteral("-l %1 ").arg(url.userName());
413
        }
Kurt Hindenburg's avatar
Kurt Hindenburg committed
414
        if (!url.host().isEmpty()) {
415
            telnetCommand += (url.host() + QLatin1Char(' '));
416
417
        }
        if (url.port() > -1) {
418
            telnetCommand += QString::number(url.port());
419
420
        }

421
        _sessionDisplayConnection->session()->sendTextToTerminal(telnetCommand, QLatin1Char('\r'));
422

Kurt Hindenburg's avatar
Kurt Hindenburg committed
423
    } else {
424
        //TODO Implement handling for other Url types
425

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

430
        qCDebug(KonsoleDebug) << "Unable to open bookmark at url" << url << ", I do not know"
Kurt Hindenburg's avatar
Kurt Hindenburg committed
431
                   << " how to handle the protocol " << url.scheme();
432
433
434
    }
}

Kurt Hindenburg's avatar
Kurt Hindenburg committed
435
void SessionController::setupPrimaryScreenSpecificActions(bool use)
436
{
437
    KActionCollection* collection = actionCollection();
438
439
440
441
    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"));
442
443
444
445

    // these actions are meaningful only when primary screen is used.
    clearAction->setEnabled(use);
    resetAction->setEnabled(use);
446
    selectAllAction->setEnabled(use);
447
    selectLineAction->setEnabled(use);
448
449
}

Jekyll Wu's avatar
Jekyll Wu committed
450
void SessionController::selectionChanged(const QString& selectedText)
451
{
Jekyll Wu's avatar
Jekyll Wu committed
452
453
454
    _selectedText = selectedText;
    updateCopyAction(selectedText);
}
455

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

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

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

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

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

482
483
484
485
486
487
    // 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
488
489
490
491
492
493
494
495
    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
496
            QAction* action = nullptr;
Jekyll Wu's avatar
Jekyll Wu committed
497

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

            _webSearchMenu->addSeparator();

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

            _webSearchMenu->setVisible(true);
        }
    }
}

void SessionController::handleWebShortcutAction()
{
Kurt Hindenburg's avatar
Kurt Hindenburg committed
520
    auto * action = qobject_cast<QAction*>(sender());
Kurt Hindenburg's avatar
Kurt Hindenburg committed
521
    if (action == nullptr) {
Jekyll Wu's avatar
Jekyll Wu committed
522
        return;
Kurt Hindenburg's avatar
Kurt Hindenburg committed
523
    }
Jekyll Wu's avatar
Jekyll Wu committed
524
525
526

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

527
    if (KUriFilter::self()->filterUri(filterData, { QStringLiteral("kurisearchfilter") })) {
Kurt Hindenburg's avatar
Kurt Hindenburg committed
528
        const QUrl& url = filterData.uri();
529
        new KRun(url, QApplication::activeWindow());
Jekyll Wu's avatar
Jekyll Wu committed
530
531
532
533
534
    }
}

void SessionController::configureWebShortcuts()
{
535
    KToolInvocation::kdeinitExec(QStringLiteral("kcmshell5"), { QStringLiteral("webshortcuts") });
536
537
}

538
539
void SessionController::sendSignal(QAction* action)
{
Kurt Hindenburg's avatar
Kurt Hindenburg committed
540
    const auto signal = action->data().toInt();
541
    _sessionDisplayConnection->session()->sendSignal(signal);
542
543
}

544
545
void SessionController::sendForegroundColor()
{
546
547
    const QColor c = _sessionDisplayConnection->view()->getForegroundColor();
    _sessionDisplayConnection->session()->reportForegroundColor(c);
548
549
}

550
551
void SessionController::sendBackgroundColor()
{
552
553
    const QColor c = _sessionDisplayConnection->view()->getBackgroundColor();
    _sessionDisplayConnection->session()->reportBackgroundColor(c);
554
555
}

Kurt Hindenburg's avatar
Kurt Hindenburg committed
556
557
void SessionController::toggleReadOnly()
{
Kurt Hindenburg's avatar
Kurt Hindenburg committed
558
    auto *action = qobject_cast<QAction*>(sender());
Kurt Hindenburg's avatar
Kurt Hindenburg committed
559
560
    if (action != nullptr) {
        bool readonly = !isReadOnly();
561
        _sessionDisplayConnection->session()->setReadOnly(readonly);
Kurt Hindenburg's avatar
Kurt Hindenburg committed
562
563
564
    }
}

565
566
void SessionController::removeSearchFilter()
{
Kurt Hindenburg's avatar
Kurt Hindenburg committed
567
    if (_searchFilter == nullptr) {
568
        return;
Kurt Hindenburg's avatar
Kurt Hindenburg committed
569
    }
570

571
    _sessionDisplayConnection->view()->filterChain()->removeFilter(_searchFilter);
572
    delete _searchFilter;
Kurt Hindenburg's avatar
Kurt Hindenburg committed
573
    _searchFilter = nullptr;
574
575
}

576
void SessionController::setupSearchBar()
577
{
Tomaz  Canabrava's avatar
Tomaz Canabrava committed
578
579
580
581
582
583
584
585
    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);
586
587
}

588
589
void SessionController::setShowMenuAction(QAction* action)
{
590
    _showMenuAction = action;
591
592
}

593
void SessionController::setupCommonActions()
594
{
595
    KActionCollection* collection = actionCollection();
596

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

Michal Humpula's avatar
Michal Humpula committed
601
    action->setIcon(QIcon::fromTheme(QStringLiteral("tab-close")));
602
    collection->setDefaultShortcut(action, Konsole::ACCEL + Qt::SHIFT + Qt::Key_W);
603
604

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

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

621
622
623
624
625
626
627
628
    // 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);

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

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

648
    _webSearchMenu = new KActionMenu(i18n("Web Search"), this);
Michal Humpula's avatar
Michal Humpula committed
649
    _webSearchMenu->setIcon(QIcon::fromTheme(QStringLiteral("preferences-web-browser-shortcuts")));
Jekyll Wu's avatar
Jekyll Wu committed
650
    _webSearchMenu->setVisible(false);
651
    collection->addAction(QStringLiteral("web-search"), _webSearchMenu);
Jekyll Wu's avatar
Jekyll Wu committed
652
653


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

658
    action = collection->addAction(QStringLiteral("select-line"), this, &SessionController::selectLine);
659
660
    action->setText(i18n("Select &Line"));

661
    action = KStandardAction::saveAs(this, &SessionController::saveHistory, collection);
662
    action->setText(i18n("Save Output &As..."));
663
#ifdef Q_OS_MACOS
664
665
    action->setShortcut(QKeySequence(Qt::META + Qt::Key_S));
#endif
666

667
    action = KStandardAction::print(this, &SessionController::print_screen, collection);
668
    action->setText(i18n("&Print Screen..."));
669
    collection->setDefaultShortcut(action, Konsole::ACCEL + Qt::SHIFT + Qt::Key_P);
670

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

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

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

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

689
    _switchProfileMenu = new KActionMenu(i18n("Switch Profile"), this);
690
    collection->addAction(QStringLiteral("switch-profile"), _switchProfileMenu);
691
    connect(_switchProfileMenu->menu(), &QMenu::aboutToShow, this, &Konsole::SessionController::prepareSwitchProfileMenu);
692

693
    // History
694
    _findAction = KStandardAction::find(this, &SessionController::searchBarEvent, collection);
695

696
    _findNextAction = KStandardAction::findNext(this, &SessionController::findNextInHistory, collection);
697
698
    _findNextAction->setEnabled(false);

699
    _findPreviousAction = KStandardAction::findPrev(this, &SessionController::findPreviousInHistory, collection);
700
    _findPreviousAction->setEnabled(false);
701

702
703
704
705
706
707
708
709
710
711
#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

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

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

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

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

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

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