SessionController.cpp 73.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 "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 <KShell>
Robert Knight's avatar
   
Robert Knight committed
45
#include <KToggleAction>
46
#include <KSelectAction>
47
#include <KXmlGuiWindow>
48
#include <KXMLGUIFactory>
49
#include <KXMLGUIBuilder>
Jekyll Wu's avatar
Jekyll Wu committed
50
51
#include <KUriFilter>
#include <KStringHandler>
Alex Richardson's avatar
Alex Richardson committed
52
#include <KSharedConfig>
53
#include <KConfigGroup>
54
#include <KCodecAction>
55
#include <KNotification>
56

57
#include <kio_version.h>
Kurt Hindenburg's avatar
Kurt Hindenburg committed
58
59
60
61
62
63
#if KIO_VERSION > QT_VERSION_CHECK(5, 68, 0)
#include <KIO/CommandLauncherJob>
#else
#include <KToolInvocation>
#endif

64
65
66
67
68
69
70
#if KIO_VERSION < QT_VERSION_CHECK(5, 71, 0)
#include <KRun>
#else
#include <KIO/JobUiDelegate>
#include <KIO/OpenUrlJob>
#endif

71
// Konsole
72
#include "CopyInputDialog.h"
73
#include "Emulation.h"
74
75
76
77
78
#include "HistorySizeDialog.h"
#include "RenameTabDialog.h"
#include "SaveHistoryTask.h"
#include "ScreenWindow.h"
#include "SearchHistoryTask.h"
79
80

#include "filterHotSpots/EscapeSequenceUrlFilter.h"
81
82
83
84
85
86
#include "filterHotSpots/FileFilter.h"
#include "filterHotSpots/Filter.h"
#include "filterHotSpots/FilterChain.h"
#include "filterHotSpots/HotSpot.h"
#include "filterHotSpots/RegExpFilter.h"
#include "filterHotSpots/UrlFilter.h"
87

88
89
#include "history/HistoryType.h"
#include "history/HistoryTypeFile.h"
90
#include "history/HistoryTypeNone.h"
91
#include "history/compact/CompactHistoryType.h"
92

93
#include "profile/ProfileList.h"
94

95
96
#include "SessionGroup.h"
#include "SessionManager.h"
97

98
#include "widgets/EditProfileDialog.h"
99
#include "widgets/IncrementalSearchBar.h"
100
101

#include "terminalDisplay/TerminalDisplay.h"
102

103
// For Unix signal names
Kurt Hindenburg's avatar
Kurt Hindenburg committed
104
#include <csignal>
105

106
using namespace Konsole;
107

108
QSet<SessionController*> SessionController::_allControllers;
109
int SessionController::_lastControllerId;
Robert Knight's avatar
   
Robert Knight committed
110

111
SessionController::SessionController(Session* session, TerminalDisplay* view, QObject* parent)
Robert Knight's avatar
   
Robert Knight committed
112
    : ViewProperties(parent)
113
    , KXMLGUIClient()
Kurt Hindenburg's avatar
Kurt Hindenburg committed
114
    , _copyToGroup(nullptr)
115
    , _profileList(nullptr)
116
117
    , _sessionIcon(QIcon())
    , _sessionIconName(QString())
Kurt Hindenburg's avatar
Kurt Hindenburg committed
118
119
120
121
122
123
124
    , _searchFilter(nullptr)
    , _urlFilter(nullptr)
    , _fileFilter(nullptr)
    , _copyInputToAllTabsAction(nullptr)
    , _findAction(nullptr)
    , _findNextAction(nullptr)
    , _findPreviousAction(nullptr)
125
    , _interactionTimer(nullptr)
Harald Hvaal's avatar
Harald Hvaal committed
126
127
    , _searchStartLine(0)
    , _prevSearchResultLine(0)
Kurt Hindenburg's avatar
Kurt Hindenburg committed
128
129
130
    , _codecAction(nullptr)
    , _switchProfileMenu(nullptr)
    , _webSearchMenu(nullptr)
131
132
    , _listenForScreenWindowUpdates(false)
    , _preventClose(false)
133
    , _selectedText(QString())
Kurt Hindenburg's avatar
Kurt Hindenburg committed
134
    , _showMenuAction(nullptr)
135
    , _bookmarkValidProgramsToClear(QStringList())
136
    , _isSearchBarEnabled(false)
137
    , _editProfileDialog(nullptr)
138
    , _searchBar(view->searchBar())
139
    , _monitorProcessFinish(false)
140
    , _escapedUrlFilter(nullptr)
141
{
Kurt Hindenburg's avatar
Kurt Hindenburg committed
142
143
    Q_ASSERT(session);
    Q_ASSERT(view);
144

145
146
    _sessionDisplayConnection = new SessionDisplayConnection(session, view, this);

147
    // handle user interface related to session (menus etc.)
148
    if (isKonsolePart()) {
149
        setComponentName(QStringLiteral("konsole"), i18n("Konsole"));
150
        setXMLFile(QStringLiteral("partui.rc"));
151
152
        setupCommonActions();
    } else {
153
        setXMLFile(QStringLiteral("sessionui.rc"));
154
155
156
        setupCommonActions();
        setupExtraActions();
    }
157

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

160
    actionCollection()->addAssociatedWidget(view);
161
162
163

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

167
    setIdentifier(++_lastControllerId);
168
    sessionAttributeChanged();
169

170
171
    connect(_sessionDisplayConnection->view(), &TerminalDisplay::compositeFocusChanged, this, &SessionController::viewFocusChangeHandler);
    _sessionDisplayConnection->view()->setSessionController(this);
Robert Knight's avatar
   
Robert Knight committed
172

173
    // install filter on the view to highlight URLs and files
174
    updateFilterList(SessionManager::instance()->sessionProfile(_sessionDisplayConnection->session()));
175

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

179
    // listen for session resize requests
180
    connect(_sessionDisplayConnection->session(), &Konsole::Session::resizeRequest, this, &Konsole::SessionController::sessionResizeRequest);
181

182
    // listen for popup menu requests
183
    connect(_sessionDisplayConnection->view(), &Konsole::TerminalDisplay::configureRequest, this, &Konsole::SessionController::showDisplayContextMenu);
184

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

Robert Knight's avatar
   
Robert Knight committed
188
    // listen to activity / silence notifications from session
189
    connect(_sessionDisplayConnection->session(), &Konsole::Session::notificationsChanged, this, &Konsole::SessionController::sessionNotificationsChanged);
190
    // listen to title and icon changes
191
192
    connect(_sessionDisplayConnection->session(), &Konsole::Session::sessionAttributeChanged, this, &Konsole::SessionController::sessionAttributeChanged);
    connect(_sessionDisplayConnection->session(), &Konsole::Session::readOnlyChanged, this, &Konsole::SessionController::sessionReadOnlyChanged);
193

194
195
    connect(this, &Konsole::SessionController::tabRenamedByUser, _sessionDisplayConnection->session(), &Konsole::Session::tabTitleSetByUser);
    connect(this, &Konsole::SessionController::tabColoredByUser, _sessionDisplayConnection->session(), &Konsole::Session::tabColorSetByUser);
196

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

199
    // listen for color changes
200
201
    connect(_sessionDisplayConnection->session(), &Konsole::Session::changeBackgroundColorRequest, _sessionDisplayConnection->view(), &Konsole::TerminalDisplay::setBackgroundColor);
    connect(_sessionDisplayConnection->session(), &Konsole::Session::changeForegroundColorRequest, _sessionDisplayConnection->view(), &Konsole::TerminalDisplay::setForegroundColor);
202

203
    // update the title when the session starts
204
    connect(_sessionDisplayConnection->session(), &Konsole::Session::started, this, &Konsole::SessionController::snapshot);
205

206
    // listen for output changes to set activity flag
207
    connect(_sessionDisplayConnection->session()->emulation(), &Konsole::Emulation::outputChanged, this, &Konsole::SessionController::fireActivity);
208
209

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

Robert Knight's avatar
   
Robert Knight committed
213
    // listen for flow control status changes
214
215
    connect(_sessionDisplayConnection->session(), &Konsole::Session::flowControlEnabledChanged, _sessionDisplayConnection->view(), &Konsole::TerminalDisplay::setFlowControlWarningEnabled);
    _sessionDisplayConnection->view()->setFlowControlWarningEnabled(_sessionDisplayConnection->session()->flowControlEnabled());
Robert Knight's avatar
   
Robert Knight committed
216

217
218
    // take a snapshot of the session state every so often when
    // user activity occurs
219
220
221
    //
    // the timer is owned by the session so that it will be destroyed along
    // with the session
222
    _interactionTimer = new QTimer(_sessionDisplayConnection->session());
223
    _interactionTimer->setSingleShot(true);
224
    _interactionTimer->setInterval(500);
225
    connect(_interactionTimer, &QTimer::timeout, this, &Konsole::SessionController::snapshot);
226
    connect(_sessionDisplayConnection->view(), &Konsole::TerminalDisplay::compositeFocusChanged,
227
            this, [this](bool focused) { if (focused) { interactionHandler(); }});
228
    connect(_sessionDisplayConnection->view(), &Konsole::TerminalDisplay::keyPressedSignal,
229
            this, &Konsole::SessionController::interactionHandler);
230

231
    // take a snapshot of the session state periodically in the background
232
    auto backgroundTimer = new QTimer(_sessionDisplayConnection->session());
233
234
    backgroundTimer->setSingleShot(false);
    backgroundTimer->setInterval(2000);
235
    connect(backgroundTimer, &QTimer::timeout, this, &Konsole::SessionController::snapshot);
236
237
    backgroundTimer->start();

238
    // xterm '10;?' request
239
    connect(_sessionDisplayConnection->session(), &Konsole::Session::getForegroundColor,
240
            this, &Konsole::SessionController::sendForegroundColor);
241
    // xterm '11;?' request
242
    connect(_sessionDisplayConnection->session(), &Konsole::Session::getBackgroundColor,
243
244
            this, &Konsole::SessionController::sendBackgroundColor);

245
    _allControllers.insert(this);
246
247
248

    // A list of programs that accept Ctrl+C to clear command line used
    // before outputting bookmark.
249
250
251
252
253
254
255
256
    _bookmarkValidProgramsToClear = QStringList({
        QStringLiteral("bash"),
        QStringLiteral("fish"),
        QStringLiteral("sh"),
        QStringLiteral("tcsh"),
        QStringLiteral("zsh")
    });

257
258
    setupSearchBar();
    _searchBar->setVisible(_isSearchBarEnabled);
259
260
261
}

SessionController::~SessionController()
262
{
Kurt Hindenburg's avatar
Kurt Hindenburg committed
263
    _allControllers.remove(this);
264
265

    if (!_editProfileDialog.isNull()) {
Tomaz  Canabrava's avatar
Tomaz Canabrava committed
266
        _editProfileDialog->deleteLater();
267
    }
268
    if(factory() != nullptr) {
269
270
        factory()->removeClient(this);
    }
271
}
272
void SessionController::trackOutput(QKeyEvent* event)
273
{
274
    Q_ASSERT(_sessionDisplayConnection->view()->screenWindow());
275

276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
    // 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;


294
295
    // Only jump to the bottom if the user actually typed something in,
    // not if the user e. g. just pressed a modifier.
296
    if (event->text().isEmpty() && ((event->modifiers() != 0u) || shouldNotTriggerScroll)) {
297
        return;
298
    }
299

300
    _sessionDisplayConnection->view()->screenWindow()->setTrackOutput(true);
301
}
302
303
304
305
306
307
308
309
310
311
312
313

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
314
        disconnect(_sessionDisplayConnection->session(), &Konsole::Session::bellRequest, nullptr, nullptr);
315
        // second, connect the newly focused view to listen for the session's bell signal
316
        connect(_sessionDisplayConnection->session(), &Konsole::Session::bellRequest, _sessionDisplayConnection->view(), &Konsole::TerminalDisplay::bell);
317
318
319
320
321
322
323
324
325

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

326
327
328
329
330
void SessionController::interactionHandler()
{
    _interactionTimer->start();
}

331
332
void SessionController::snapshot()
{
333
    Q_ASSERT(!_sessionDisplayConnection->session().isNull());
334

335
    QString title = _sessionDisplayConnection->session()->getDynamicTitle();
Robert Knight's avatar
   
Robert Knight committed
336
    title         = title.simplified();
337

338
    // Visualize that the session is broadcasting to others
339
    if ((_copyToGroup != nullptr) && _copyToGroup->sessions().count() > 1) {
340
        title.append(QLatin1Char('*'));
341
    }
Jekyll Wu's avatar
Jekyll Wu committed
342
343
344

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

348
    QColor color = _sessionDisplayConnection->session()->color();
349
350
351
352
    // use the fallback color if needed
    if (!color.isValid()) {
        color = QColor(QColor::Invalid);
    }
353

354
    // apply new title
355
    _sessionDisplayConnection->session()->setTitle(Session::DisplayedTitleRole, title);
Jekyll Wu's avatar
Jekyll Wu committed
356

357
    // apply new color
358
    _sessionDisplayConnection->session()->setColor(color);
359

360
361
    // check if foreground process ended and notify if this option was requested
    if (_monitorProcessFinish) {
362
        bool isForegroundProcessActive = _sessionDisplayConnection->session()->isForegroundProcessActive();
363
        if (!_previousForegroundProcessName.isNull() && !isForegroundProcessActive) {
364
365
            KNotification::event(_sessionDisplayConnection->session()->hasFocus() ? QStringLiteral("ProcessFinished") : QStringLiteral("ProcessFinishedHidden"),
                                 i18n("The process '%1' has finished running in session '%2'", _previousForegroundProcessName, _sessionDisplayConnection->session()->nameTitle()),
366
367
368
369
                                 QPixmap(),
                                 QApplication::activeWindow(),
                                 KNotification::CloseWhenWidgetActivated);
        }
370
        _previousForegroundProcessName = isForegroundProcessActive ? _sessionDisplayConnection->session()->foregroundProcessName() : QString();
371
372
    }

Jekyll Wu's avatar
Jekyll Wu committed
373
374
    // do not forget icon
    updateSessionIcon();
375
376
}

377
378
QString SessionController::currentDir() const
{
379
    return _sessionDisplayConnection->session()->currentWorkingDirectory();
380
381
}

Kurt Hindenburg's avatar
Kurt Hindenburg committed
382
QUrl SessionController::url() const
383
{
384
    return _sessionDisplayConnection->session()->getUrl();
385
386
}

387
388
void SessionController::rename()
{
389
    renameSession();
390
391
}

Kurt Hindenburg's avatar
Kurt Hindenburg committed
392
void SessionController::openUrl(const QUrl& url)
393
{
394
    // Clear shell's command line
395
396
397
    if (!_sessionDisplayConnection->session()->isForegroundProcessActive()
            && _bookmarkValidProgramsToClear.contains(_sessionDisplayConnection->session()->foregroundProcessName())) {
        _sessionDisplayConnection->session()->sendTextToTerminal(QChar(0x03), QLatin1Char('\n')); // Ctrl+C
398
399
    }

400
    // handle local paths
Kurt Hindenburg's avatar
Kurt Hindenburg committed
401
    if (url.isLocalFile()) {
402
        QString path = url.toLocalFile();
403
        _sessionDisplayConnection->session()->sendTextToTerminal(QStringLiteral("cd ") + KShell::quoteArg(path), QLatin1Char('\r'));
Kurt Hindenburg's avatar
Kurt Hindenburg committed
404
405
    } else if (url.scheme().isEmpty()) {
        // QUrl couldn't parse what the user entered into the URL field
406
        // so just dump it to the shell
407
408
        // If you change this, change it also in autotests/BookMarkTest.cpp
        QString command = QUrl::fromPercentEncoding(url.toEncoded());
Kurt Hindenburg's avatar
Kurt Hindenburg committed
409
        if (!command.isEmpty()) {
410
            _sessionDisplayConnection->session()->sendTextToTerminal(command, QLatin1Char('\r'));
Kurt Hindenburg's avatar
Kurt Hindenburg committed
411
        }
412
413
    } else if (url.scheme() == QLatin1String("ssh")) {
        QString sshCommand = QStringLiteral("ssh ");
414
415

        if (url.port() > -1) {
416
            sshCommand += QStringLiteral("-p %1 ").arg(url.port());
417
        }
Kurt Hindenburg's avatar
Kurt Hindenburg committed
418
        if (!url.userName().isEmpty()) {
419
            sshCommand += (url.userName() + QLatin1Char('@'));
420
        }
Kurt Hindenburg's avatar
Kurt Hindenburg committed
421
        if (!url.host().isEmpty()) {
422
423
            sshCommand += url.host();
        }
424
        _sessionDisplayConnection->session()->sendTextToTerminal(sshCommand, QLatin1Char('\r'));
425

426
427
    } else if (url.scheme() == QLatin1String("telnet")) {
        QString telnetCommand = QStringLiteral("telnet ");
428

Kurt Hindenburg's avatar
Kurt Hindenburg committed
429
        if (!url.userName().isEmpty()) {
430
            telnetCommand += QStringLiteral("-l %1 ").arg(url.userName());
431
        }
Kurt Hindenburg's avatar
Kurt Hindenburg committed
432
        if (!url.host().isEmpty()) {
433
            telnetCommand += (url.host() + QLatin1Char(' '));
434
435
        }
        if (url.port() > -1) {
436
            telnetCommand += QString::number(url.port());
437
438
        }

439
        _sessionDisplayConnection->session()->sendTextToTerminal(telnetCommand, QLatin1Char('\r'));
440

Kurt Hindenburg's avatar
Kurt Hindenburg committed
441
    } else {
442
        //TODO Implement handling for other Url types
443

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

448
        qCDebug(KonsoleDebug) << "Unable to open bookmark at url" << url << ", I do not know"
Kurt Hindenburg's avatar
Kurt Hindenburg committed
449
                   << " how to handle the protocol " << url.scheme();
450
451
452
    }
}

Kurt Hindenburg's avatar
Kurt Hindenburg committed
453
void SessionController::setupPrimaryScreenSpecificActions(bool use)
454
{
455
    KActionCollection* collection = actionCollection();
456
457
458
459
    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"));
460
461
462
463

    // these actions are meaningful only when primary screen is used.
    clearAction->setEnabled(use);
    resetAction->setEnabled(use);
464
    selectAllAction->setEnabled(use);
465
    selectLineAction->setEnabled(use);
466
467
}

Jekyll Wu's avatar
Jekyll Wu committed
468
void SessionController::selectionChanged(const QString& selectedText)
469
{
Jekyll Wu's avatar
Jekyll Wu committed
470
471
472
    _selectedText = selectedText;
    updateCopyAction(selectedText);
}
473

Jekyll Wu's avatar
Jekyll Wu committed
474
475
void SessionController::updateCopyAction(const QString& selectedText)
{
476
    QAction* copyAction = actionCollection()->action(QStringLiteral("edit_copy"));
477
    QAction* copyContextMenu = actionCollection()->action(QStringLiteral("edit_copy_contextmenu"));
Jekyll Wu's avatar
Jekyll Wu committed
478
479
    // copy action is meaningful only when some text is selected.
    copyAction->setEnabled(!selectedText.isEmpty());
480
    copyContextMenu->setVisible(!selectedText.isEmpty());
Jekyll Wu's avatar
Jekyll Wu committed
481
482
483
484
485
486
487
488
}

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

Kurt Hindenburg's avatar
Kurt Hindenburg committed
489
    if (_selectedText.isEmpty()) {
490
        return;
Kurt Hindenburg's avatar
Kurt Hindenburg committed
491
    }
Jekyll Wu's avatar
Jekyll Wu committed
492
493

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

Kurt Hindenburg's avatar
Kurt Hindenburg committed
496
    if (searchText.isEmpty()) {
Jekyll Wu's avatar
Jekyll Wu committed
497
        return;
Kurt Hindenburg's avatar
Kurt Hindenburg committed
498
    }
Jekyll Wu's avatar
Jekyll Wu committed
499

500
501
502
503
504
505
    // 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
506
507
508
509
510
511
512
513
    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
514
            QAction* action = nullptr;
Jekyll Wu's avatar
Jekyll Wu committed
515

516
            for (const QString &searchProvider : searchProviders) {
517
                action = new QAction(searchProvider, _webSearchMenu);
Michal Humpula's avatar
Michal Humpula committed
518
                action->setIcon(QIcon::fromTheme(filterData.iconNameForPreferredSearchProvider(searchProvider)));
Jekyll Wu's avatar
Jekyll Wu committed
519
                action->setData(filterData.queryForPreferredSearchProvider(searchProvider));
520
                connect(action, &QAction::triggered, this, &Konsole::SessionController::handleWebShortcutAction);
Jekyll Wu's avatar
Jekyll Wu committed
521
522
523
524
525
                _webSearchMenu->addAction(action);
            }

            _webSearchMenu->addSeparator();

526
            action = new QAction(i18n("Configure Web Shortcuts..."), _webSearchMenu);
Michal Humpula's avatar
Michal Humpula committed
527
            action->setIcon(QIcon::fromTheme(QStringLiteral("configure")));
528
            connect(action, &QAction::triggered, this, &Konsole::SessionController::configureWebShortcuts);
Jekyll Wu's avatar
Jekyll Wu committed
529
530
531
532
533
534
535
536
537
            _webSearchMenu->addAction(action);

            _webSearchMenu->setVisible(true);
        }
    }
}

void SessionController::handleWebShortcutAction()
{
Kurt Hindenburg's avatar
Kurt Hindenburg committed
538
    auto * action = qobject_cast<QAction*>(sender());
Kurt Hindenburg's avatar
Kurt Hindenburg committed
539
    if (action == nullptr) {
Jekyll Wu's avatar
Jekyll Wu committed
540
        return;
Kurt Hindenburg's avatar
Kurt Hindenburg committed
541
    }
Jekyll Wu's avatar
Jekyll Wu committed
542
543
544

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

545
    if (KUriFilter::self()->filterUri(filterData, { QStringLiteral("kurisearchfilter") })) {
546
547
548
        const QUrl url = filterData.uri();

#if KIO_VERSION < QT_VERSION_CHECK(5, 71, 0)
549
        new KRun(url, QApplication::activeWindow());
550
551
552
553
554
#else
        auto *job = new KIO::OpenUrlJob(url);
        job->setUiDelegate(new KIO::JobUiDelegate(KJobUiDelegate::AutoHandlingEnabled, QApplication::activeWindow()));
        job->start();
#endif
Jekyll Wu's avatar
Jekyll Wu committed
555
556
557
558
559
    }
}

void SessionController::configureWebShortcuts()
{
Kurt Hindenburg's avatar
Kurt Hindenburg committed
560
#if KIO_VERSION > QT_VERSION_CHECK(5, 68, 0)
561
562
    auto job = new KIO::CommandLauncherJob(QStringLiteral("kcmshell5"), { QStringLiteral("webshortcuts") });
    job->start();
Kurt Hindenburg's avatar
Kurt Hindenburg committed
563
564
565
#else
    KToolInvocation::kdeinitExec(QStringLiteral("kcmshell5"), { QStringLiteral("webshortcuts") });
#endif
566
567
}

568
569
void SessionController::sendSignal(QAction* action)
{
Kurt Hindenburg's avatar
Kurt Hindenburg committed
570
    const auto signal = action->data().toInt();
571
    _sessionDisplayConnection->session()->sendSignal(signal);
572
573
}

574
void SessionController::sendForegroundColor(uint terminator)
575
{
576
    const QColor c = _sessionDisplayConnection->view()->getForegroundColor();
577
    _sessionDisplayConnection->session()->reportForegroundColor(c, terminator);
578
579
}

580
void Konsole::SessionController::sendBackgroundColor(uint terminator)
581
{
582
    const QColor c = _sessionDisplayConnection->view()->getBackgroundColor();
583
    _sessionDisplayConnection->session()->reportBackgroundColor(c, terminator);
584
585
}

Kurt Hindenburg's avatar
Kurt Hindenburg committed
586
587
void SessionController::toggleReadOnly()
{
Kurt Hindenburg's avatar
Kurt Hindenburg committed
588
    auto *action = qobject_cast<QAction*>(sender());
Kurt Hindenburg's avatar
Kurt Hindenburg committed
589
590
    if (action != nullptr) {
        bool readonly = !isReadOnly();
591
        _sessionDisplayConnection->session()->setReadOnly(readonly);
Kurt Hindenburg's avatar
Kurt Hindenburg committed
592
593
594
    }
}

595
596
void SessionController::removeSearchFilter()
{
Kurt Hindenburg's avatar
Kurt Hindenburg committed
597
    if (_searchFilter == nullptr) {
598
        return;
Kurt Hindenburg's avatar
Kurt Hindenburg committed
599
    }
600

601
    _sessionDisplayConnection->view()->filterChain()->removeFilter(_searchFilter);
602
    delete _searchFilter;
Kurt Hindenburg's avatar
Kurt Hindenburg committed
603
    _searchFilter = nullptr;
604
605
}

606
void SessionController::setupSearchBar()
607
{
Tomaz  Canabrava's avatar
Tomaz Canabrava committed
608
609
610
611
612
613
614
615
    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);
616
617
}

618
619
void SessionController::setShowMenuAction(QAction* action)
{
620
    _showMenuAction = action;
621
622
}

623
void SessionController::setupCommonActions()
624
{
625
    KActionCollection* collection = actionCollection();
626

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

Michal Humpula's avatar
Michal Humpula committed
631
    action->setIcon(QIcon::fromTheme(QStringLiteral("tab-close")));
632
    collection->setDefaultShortcut(action, Konsole::ACCEL + Qt::SHIFT + Qt::Key_W);
633
634

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

639
    // Copy and Paste
640
    action = KStandardAction::copy(this, &SessionController::copy, collection);
641
#ifdef Q_OS_MACOS
642
643
644
645
646
647
    // 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
648
649
    // disabled at first, since nothing has been selected now
    action->setEnabled(false);
650

651
652
653
654
655
656
657
658
    // 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);

659
    action = KStandardAction::paste(this, &SessionController::paste, collection);
Alex Richardson's avatar
Alex Richardson committed
660
    QList<QKeySequence> pasteShortcut;
661
#ifdef Q_OS_MACOS
662
663
664
665
    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
666
    pasteShortcut.append(QKeySequence(Qt::SHIFT + Qt::Key_Insert));
667
#endif
668
    collection->setDefaultShortcuts(action, pasteShortcut);
669

670
    action = collection->addAction(QStringLiteral("paste-selection"), this, &SessionController::pasteFromX11Selection);
671
    action->setText(i18n("Paste Selection"));
672
#ifdef Q_OS_MACOS
673
674
675
676
    collection->setDefaultShortcut(action, Qt::META + Qt::SHIFT + Qt::Key_V);
#else
    collection->setDefaultShortcut(action, Konsole::ACCEL + Qt::SHIFT + Qt::Key_Insert);
#endif
677

678
    _webSearchMenu = new KActionMenu(i18n("Web Search"), this);
Michal Humpula's avatar
Michal Humpula committed
679
    _webSearchMenu->setIcon(QIcon::fromTheme(QStringLiteral("preferences-web-browser-shortcuts")));
Jekyll Wu's avatar
Jekyll Wu committed
680
    _webSearchMenu->setVisible(false);
681
    collection->addAction(QStringLiteral("web-search"), _webSearchMenu);
Jekyll Wu's avatar
Jekyll Wu committed
682
683


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

688
    action = collection->addAction(QStringLiteral("select-line"), this, &SessionController::selectLine);
689
690
    action->setText(i18n("Select &Line"));

691
    action = KStandardAction::saveAs(this, &SessionController::saveHistory, collection);
692
    action->setText(i18n("Save Output &As..."));
693
#ifdef Q_OS_MACOS
694
695
    action->setShortcut(QKeySequence(Qt::META + Qt::Key_S));
#endif
696

697
    action = KStandardAction::print(this, &SessionController::requestPrint, collection);
698
    action->setText(i18n("&Print Screen..."));
699
    collection->setDefaultShortcut(action, Konsole::ACCEL + Qt::SHIFT + Qt::Key_P);
700

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

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

709
    action = collection->addAction(QStringLiteral("clear-history-and-reset"), this, &SessionController::clearHistoryAndReset);
710
    action->setText(i18n("Clear Scrollback and Reset"));
Michal Humpula's avatar
Michal Humpula committed
711
    action->setIcon(QIcon::fromTheme(QStringLiteral("edit-clear-history")));
712
    collection->setDefaultShortcut(action, Konsole::ACCEL + Qt::SHIFT + Qt::Key_K);
713
714

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

719
    _switchProfileMenu = new KActionMenu(i18n("Switch Profile"), this);
720
    collection->addAction(QStringLiteral("switch-profile"), _switchProfileMenu);
721
    connect(_switchProfileMenu->menu(), &QMenu::aboutToShow, this, &Konsole::SessionController::prepareSwitchProfileMenu);
722

723
    // History
724
    _findAction = KStandardAction::find(this, &SessionController::searchBarEvent, collection);
725

726
    _findNextAction = KStandardAction::findNext(this, &SessionController::findNextInHistory, collection);
727
728
    _findNextAction->setEnabled(false);

729
    _findPreviousAction = KStandardAction::findPrev(this, &SessionController::findPreviousInHistory, collection);
730
    _findPreviousAction->setEnabled(false);
731

732
733
734
735
736
737
738
739
740
741
#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

742
743
    // Character Encoding
    _codecAction = new KCodecAction(i18n("Set &Encoding"), this);
Michal Humpula's avatar
Michal Humpula committed
744
    _codecAction->setIcon(QIcon::fromTheme(QStringLiteral("character-set")));
745
    collection->addAction(QStringLiteral("set-encoding"), _codecAction);
746
747
    _codecAction->setCurrentCodec(QString::fromUtf8(_sessionDisplayConnection->session()->codec()));
    connect(_sessionDisplayConnection->session(), &Konsole::Session::sessionCodecChanged, this, &Konsole::SessionController::updateCodecAction);
748
749
750
    connect(_codecAction,
            QOverload<QTextCodec*>::of(&KCodecAction::triggered), this,
            &Konsole::SessionController::changeCodec);
751
752

    // Read-only
753
    action = collection->addAction(QStringLiteral("view-readonly"), this, &SessionController::toggleReadOnly);
754
755
756
    action->setText(i18nc("@item:inmenu A read only (locked) session", "Read-only"));
    action->setCheckable(true);
    updateReadOnlyActionStates();
757
758
759
760
761
762
}

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

763
    // Rename Session
764
    QAction* action = collection->addAction(QStringLiteral("rename-session"), this, &SessionController::renameSession);
765
    action->setText(i18n("&Configure or Rename Tab..."));
Michal Humpula's avatar
Michal Humpula committed
766
    action->setIcon(QIcon::fromTheme(QStringLiteral("edit-rename")));