SessionController.cpp 71.7 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 "profile/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
#include <QFileDialog>
34
#include <QPainter>
35
#include <QStandardPaths>
36
37
#include <QUrl>
#include <QIcon>
38

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

59
// Konsole
60
#include "CopyInputDialog.h"
61
#include "Emulation.h"
62
63
64
65
66
67
#include "Enumeration.h"
#include "HistorySizeDialog.h"
#include "RenameTabDialog.h"
#include "SaveHistoryTask.h"
#include "ScreenWindow.h"
#include "SearchHistoryTask.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
75
#include "history/HistoryType.h"
#include "history/HistoryTypeFile.h"
76
#include "history/HistoryTypeNone.h"
77
#include "history/compact/CompactHistoryType.h"
78
#include "profile/ProfileList.h"
79
80
#include "session/Session.h"
#include "session/SessionGroup.h"
81
#include "session/SessionManager.h"
82
#include "widgets/EditProfileDialog.h"
83
84
#include "widgets/IncrementalSearchBar.h"
#include "widgets/TerminalDisplay.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
143
    connect(this, &SessionController::requestPrint, _sessionDisplayConnection->view(), &TerminalDisplay::printScreen);

144
    actionCollection()->addAssociatedWidget(view);
145
146
147

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

151
    setIdentifier(++_lastControllerId);
152
    sessionAttributeChanged();
153

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

229
    _allControllers.insert(this);
230
231
232

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

241
242
    setupSearchBar();
    _searchBar->setVisible(_isSearchBarEnabled);
243
244
245
}

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

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

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


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

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

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

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

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

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

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

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

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

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

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

341
    // apply new color
342
    _sessionDisplayConnection->session()->setColor(color);
343

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

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

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

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

371
372
void SessionController::rename()
{
373
    renameSession();
374
375
}

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

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

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

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

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

423
        _sessionDisplayConnection->session()->sendTextToTerminal(telnetCommand, QLatin1Char('\r'));
424

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

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

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

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

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

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

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

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

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

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

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

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

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

            _webSearchMenu->addSeparator();

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

            _webSearchMenu->setVisible(true);
        }
    }
}

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

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

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

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

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

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

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

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

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

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

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

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

595
void SessionController::setupCommonActions()
596
{
597
    KActionCollection* collection = actionCollection();
598

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    // Copy input to ==> none
Kurt Hindenburg's avatar
Kurt Hindenburg committed
755
    auto* copyInputToNoneAction = collection->add<KToggleAction>(QStringLiteral("copy-input-to-none"));
756
    copyInputToNoneAction->setText(i18nc("@action:inmenu Do not select any tabs", "&None"));
757
    collection->setDefaultShortcut(copyInputToNoneAction, Konsole::ACCEL + Qt::SHIFT + Qt::Key_Slash);
758
759
760
761
762
    copyInputToNoneAction->setData(CopyInputToNoneMode);
    copyInputToNoneAction->setChecked(true); // the default state

    // The "Copy Input To" submenu
    // The above three choices are represented as combo boxes