Filter.cpp 22 KB
Newer Older
1
/*
2
    Copyright 2007-2008 by Robert Knight <robertknight@gmail.com>
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

    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.
*/

20
21
22
// Own
#include "Filter.h"

23
#include "konsoledebug.h"
24
25
#include "KonsoleSettings.h"

Tomaz  Canabrava's avatar
Tomaz Canabrava committed
26
#include <algorithm>
27

28
// Qt
29
30
#include <QAction>
#include <QApplication>
31
32
33
34
35
36
#include <QClipboard>
#include <QDir>
#include <QMimeDatabase>
#include <QString>
#include <QTextStream>
#include <QUrl>
37
#include <QMenu>
38
39
40
41
42
#include <QMouseEvent>
#include <QToolTip>
#include <QBuffer>
#include <QToolTip>
#include <QTimer>
43
44

// KDE
45
#include <KLocalizedString>
46
#include <KRun>
47
48
49
#include <KFileItem>
#include <KFileItemListProperties>
#include <KFileItemActions>
50
#include <KIO/PreviewJob>
51
52

// Konsole
53
#include "session/Session.h"
54
#include "TerminalCharacterDecoder.h"
55
#include "ProfileManager.h"
56
#include "session/SessionManager.h"
57

58
59
using namespace Konsole;

60
61
FilterChain::~FilterChain()
{
62
    qDeleteAll(_filters);
63
64
}

Kurt Hindenburg's avatar
Kurt Hindenburg committed
65
void FilterChain::addFilter(Filter *filter)
66
{
67
    _filters.append(filter);
68
}
Kurt Hindenburg's avatar
Kurt Hindenburg committed
69
70

void FilterChain::removeFilter(Filter *filter)
71
{
72
    _filters.removeAll(filter);
73
}
Kurt Hindenburg's avatar
Kurt Hindenburg committed
74

75
76
void FilterChain::reset()
{
77
78
    for(auto *filter : _filters) {
        filter->reset();
Kurt Hindenburg's avatar
Kurt Hindenburg committed
79
    }
80
}
Kurt Hindenburg's avatar
Kurt Hindenburg committed
81
82

void FilterChain::setBuffer(const QString *buffer, const QList<int> *linePositions)
83
{
84
85
    for(auto *filter : _filters) {
        filter->setBuffer(buffer, linePositions);
Kurt Hindenburg's avatar
Kurt Hindenburg committed
86
    }
87
}
Kurt Hindenburg's avatar
Kurt Hindenburg committed
88

89
void FilterChain::process()
90
{
91
92
    for( auto *filter : _filters) {
        filter->process();
Kurt Hindenburg's avatar
Kurt Hindenburg committed
93
    }
94
}
Kurt Hindenburg's avatar
Kurt Hindenburg committed
95

96
97
void FilterChain::clear()
{
98
    _filters.clear();
99
}
Kurt Hindenburg's avatar
Kurt Hindenburg committed
100

101
QSharedPointer<Filter::HotSpot> FilterChain::hotSpotAt(int line, int column) const
102
{
103
    for(auto *filter : _filters) {
104
        QSharedPointer<Filter::HotSpot> spot = filter->hotSpotAt(line, column);
Kurt Hindenburg's avatar
Kurt Hindenburg committed
105
        if (spot != nullptr) {
106
           return spot;
107
108
        }
    }
Kurt Hindenburg's avatar
Kurt Hindenburg committed
109
    return nullptr;
110
111
}

112
QList<QSharedPointer<Filter::HotSpot>> FilterChain::hotSpots() const
113
{
114
    QList<QSharedPointer<Filter::HotSpot>> list;
115
116
    for (auto *filter : _filters) {
        list.append(filter->hotSpots());
Tomaz  Canabrava's avatar
Tomaz Canabrava committed
117
   }
118
119
    return list;
}
120

Kurt Hindenburg's avatar
Kurt Hindenburg committed
121
TerminalImageFilterChain::TerminalImageFilterChain() :
Kurt Hindenburg's avatar
Kurt Hindenburg committed
122
123
    _buffer(nullptr),
    _linePositions(nullptr)
124
125
126
{
}

127
TerminalImageFilterChain::~TerminalImageFilterChain() = default;
128

Kurt Hindenburg's avatar
Kurt Hindenburg committed
129
130
void TerminalImageFilterChain::setImage(const Character * const image, int lines, int columns,
                                        const QVector<LineProperty> &lineProperties)
131
{
132
    if (_filters.empty()) {
133
        return;
Kurt Hindenburg's avatar
Kurt Hindenburg committed
134
    }
135

136
137
138
    // reset all filters and hotspots
    reset();

139
    PlainTextDecoder decoder;
140
141
    decoder.setLeadingWhitespace(true);
    decoder.setTrailingWhitespace(true);
142

143
    // setup new shared buffers for the filters to process on
144
145
    _buffer.reset(new QString());
    _linePositions.reset(new QList<int>());
146

147
    setBuffer(_buffer.get(), _linePositions.get());
148

149
    QTextStream lineStream(_buffer.get());
150
151
    decoder.begin(&lineStream);

Kurt Hindenburg's avatar
Kurt Hindenburg committed
152
    for (int i = 0; i < lines; i++) {
153
        _linePositions->append(_buffer->length());
Kurt Hindenburg's avatar
Kurt Hindenburg committed
154
        decoder.decodeLine(image + i * columns, columns, LINE_DEFAULT);
155
156
157
158
159
160

        // pretend that each line ends with a newline character.
        // this prevents a link that occurs at the end of one line
        // being treated as part of a link that occurs at the start of the next line
        //
        // the downside is that links which are spread over more than one line are not
Kurt Hindenburg's avatar
Kurt Hindenburg committed
161
        // highlighted.
162
163
164
165
        //
        // TODO - Use the "line wrapped" attribute associated with lines in a
        // terminal image to avoid adding this imaginary character for wrapped
        // lines
Kurt Hindenburg's avatar
Kurt Hindenburg committed
166
        if ((lineProperties.value(i, LINE_DEFAULT) & LINE_WRAPPED) == 0) {
167
            lineStream << QLatin1Char('\n');
Kurt Hindenburg's avatar
Kurt Hindenburg committed
168
        }
169
    }
170
    decoder.end();
171
172
}

Kurt Hindenburg's avatar
Kurt Hindenburg committed
173
Filter::Filter() :
Kurt Hindenburg's avatar
Kurt Hindenburg committed
174
175
    _linePositions(nullptr),
    _buffer(nullptr)
176
177
178
{
}

179
180
Filter::~Filter()
{
David Hallas's avatar
David Hallas committed
181
    reset();
182
}
Kurt Hindenburg's avatar
Kurt Hindenburg committed
183

184
185
186
187
void Filter::reset()
{
    _hotspots.clear();
    _hotspotList.clear();
188
189
}

Kurt Hindenburg's avatar
Kurt Hindenburg committed
190
void Filter::setBuffer(const QString *buffer, const QList<int> *linePositions)
191
192
193
{
    _buffer = buffer;
    _linePositions = linePositions;
194
195
}

196
std::pair<int, int> Filter::getLineColumn(int position)
197
{
Kurt Hindenburg's avatar
Kurt Hindenburg committed
198
199
    Q_ASSERT(_linePositions);
    Q_ASSERT(_buffer);
200

Kurt Hindenburg's avatar
Kurt Hindenburg committed
201
    for (int i = 0; i < _linePositions->count(); i++) {
202
203
204
        const int nextLine = i == _linePositions->count() - 1
            ? _buffer->length() + 1
            : _linePositions->value(i + 1);
205

Kurt Hindenburg's avatar
Kurt Hindenburg committed
206
        if (_linePositions->value(i) <= position && position < nextLine) {
207
208
            return std::make_pair(i,  Character::stringWidth(buffer()->mid(_linePositions->value(i),
                                                     position - _linePositions->value(i))));
209
210
        }
    }
211
    return std::make_pair(-1, -1);
212
}
213

Kurt Hindenburg's avatar
Kurt Hindenburg committed
214
const QString *Filter::buffer()
215
216
217
{
    return _buffer;
}
Kurt Hindenburg's avatar
Kurt Hindenburg committed
218

219
220
Filter::HotSpot::~HotSpot() = default;

221
void Filter::addHotSpot(QSharedPointer<HotSpot> spot)
222
223
224
{
    _hotspotList << spot;

Kurt Hindenburg's avatar
Kurt Hindenburg committed
225
    for (int line = spot->startLine(); line <= spot->endLine(); line++) {
Kurt Hindenburg's avatar
Kurt Hindenburg committed
226
227
        _hotspots.insert(line, spot);
    }
228
}
Kurt Hindenburg's avatar
Kurt Hindenburg committed
229

230
QList<QSharedPointer<Filter::HotSpot>> Filter::hotSpots() const
231
232
233
{
    return _hotspotList;
}
Kurt Hindenburg's avatar
Kurt Hindenburg committed
234

235
QSharedPointer<Filter::HotSpot> Filter::hotSpotAt(int line, int column) const
236
{
237
    const auto hotspots = _hotspots.values(line);
238

239
    for (auto &spot : hotspots) {
Kurt Hindenburg's avatar
Kurt Hindenburg committed
240
        if (spot->startLine() == line && spot->startColumn() > column) {
241
            continue;
Kurt Hindenburg's avatar
Kurt Hindenburg committed
242
243
        }
        if (spot->endLine() == line && spot->endColumn() < column) {
244
            continue;
Kurt Hindenburg's avatar
Kurt Hindenburg committed
245
        }
246

247
248
249
        return spot;
    }

Kurt Hindenburg's avatar
Kurt Hindenburg committed
250
    return nullptr;
251
252
}

Kurt Hindenburg's avatar
Kurt Hindenburg committed
253
254
255
256
257
258
Filter::HotSpot::HotSpot(int startLine, int startColumn, int endLine, int endColumn) :
    _startLine(startLine),
    _startColumn(startColumn),
    _endLine(endLine),
    _endColumn(endColumn),
    _type(NotSpecified)
259
260
{
}
Kurt Hindenburg's avatar
Kurt Hindenburg committed
261

Tomaz  Canabrava's avatar
Tomaz Canabrava committed
262
QList<QAction *> Filter::HotSpot::actions()
263
{
Tomaz Canabrava's avatar
Tomaz Canabrava committed
264
    return {};
265
}
Kurt Hindenburg's avatar
Kurt Hindenburg committed
266

267
268
269
270
271
void Filter::HotSpot::setupMenu(QMenu *)
{

}

272
273
274
275
int Filter::HotSpot::startLine() const
{
    return _startLine;
}
Kurt Hindenburg's avatar
Kurt Hindenburg committed
276

277
278
279
280
int Filter::HotSpot::endLine() const
{
    return _endLine;
}
Kurt Hindenburg's avatar
Kurt Hindenburg committed
281

282
283
284
285
int Filter::HotSpot::startColumn() const
{
    return _startColumn;
}
Kurt Hindenburg's avatar
Kurt Hindenburg committed
286

287
288
289
290
int Filter::HotSpot::endColumn() const
{
    return _endColumn;
}
Kurt Hindenburg's avatar
Kurt Hindenburg committed
291

292
293
294
295
Filter::HotSpot::Type Filter::HotSpot::type() const
{
    return _type;
}
Kurt Hindenburg's avatar
Kurt Hindenburg committed
296

297
298
299
300
301
void Filter::HotSpot::setType(Type type)
{
    _type = type;
}

Kurt Hindenburg's avatar
Kurt Hindenburg committed
302
303
RegExpFilter::RegExpFilter() :
    _searchText(QRegularExpression())
304
305
306
{
}

Kurt Hindenburg's avatar
Kurt Hindenburg committed
307
308
309
310
RegExpFilter::HotSpot::HotSpot(int startLine, int startColumn, int endLine, int endColumn,
                               const QStringList &capturedTexts) :
    Filter::HotSpot(startLine, startColumn, endLine, endColumn),
    _capturedTexts(capturedTexts)
311
312
313
{
    setType(Marker);
}
314

Kurt Hindenburg's avatar
Kurt Hindenburg committed
315
void RegExpFilter::HotSpot::activate(QObject *)
316
317
318
319
320
321
322
323
{
}

QStringList RegExpFilter::HotSpot::capturedTexts() const
{
    return _capturedTexts;
}

324
void RegExpFilter::setRegExp(const QRegularExpression &regExp)
325
{
326
    _searchText = regExp;
327
    _searchText.optimize();
328
}
Kurt Hindenburg's avatar
Kurt Hindenburg committed
329

330
QRegularExpression RegExpFilter::regExp() const
331
332
333
{
    return _searchText;
}
Kurt Hindenburg's avatar
Kurt Hindenburg committed
334

335
336
void RegExpFilter::process()
{
Kurt Hindenburg's avatar
Kurt Hindenburg committed
337
    const QString *text = buffer();
338

Kurt Hindenburg's avatar
Kurt Hindenburg committed
339
    Q_ASSERT(text);
340

341
    if (!_searchText.isValid() || _searchText.pattern().isEmpty()) {
342
        return;
343
    }
344

345
346
347
    QRegularExpressionMatchIterator iterator(_searchText.globalMatch(*text));
    while (iterator.hasNext()) {
        QRegularExpressionMatch match(iterator.next());
Tomaz  Canabrava's avatar
Tomaz Canabrava committed
348
349
350
351
352
353
354
355
356
        std::pair<int, int> start = getLineColumn(match.capturedStart());
        std::pair<int, int> end = getLineColumn(match.capturedEnd());

        QSharedPointer<Filter::HotSpot> spot(
            newHotSpot(start.first, start.second,
                       end.first, end.second,
                       match.capturedTexts()
            )
        );
357

358
        if (spot == nullptr) {
359
            continue;
360
        }
361
362

        addHotSpot(spot);
Kurt Hindenburg's avatar
Kurt Hindenburg committed
363
    }
364
365
}

366
QSharedPointer<Filter::HotSpot> RegExpFilter::newHotSpot(int startLine, int startColumn, int endLine,
Kurt Hindenburg's avatar
Kurt Hindenburg committed
367
                                                int endColumn, const QStringList &capturedTexts)
368
{
369
370
    return QSharedPointer<Filter::HotSpot>(new RegExpFilter::HotSpot(startLine, startColumn,
                                     endLine, endColumn, capturedTexts));
371
}
Kurt Hindenburg's avatar
Kurt Hindenburg committed
372

373
QSharedPointer<Filter::HotSpot> UrlFilter::newHotSpot(int startLine, int startColumn, int endLine,
Kurt Hindenburg's avatar
Kurt Hindenburg committed
374
                                             int endColumn, const QStringList &capturedTexts)
375
{
376
377
    return QSharedPointer<Filter::HotSpot>(new UrlFilter::HotSpot(startLine, startColumn,
                                  endLine, endColumn, capturedTexts));
378
}
Kurt Hindenburg's avatar
Kurt Hindenburg committed
379

380
UrlFilter::HotSpot::HotSpot(int startLine, int startColumn, int endLine, int endColumn,
Kurt Hindenburg's avatar
Kurt Hindenburg committed
381
                            const QStringList &capturedTexts) :
382
    RegExpFilter::HotSpot(startLine, startColumn, endLine, endColumn, capturedTexts)
383
{
384
385
386
387
388
389
390
391
392
393
    switch(urlType()) {
    case Email:
        setType(EMailAddress);
        break;

    case StandardUrl:
    case Unknown:
    default:
        setType(Link);
    }
394
}
Kurt Hindenburg's avatar
Kurt Hindenburg committed
395

396
UrlFilter::HotSpot::UrlType UrlFilter::HotSpot::urlType() const
397
{
398
    const QString url = capturedTexts().at(0);
399
400
401
402
403
404
405
406
407

    // Don't use a ternary here, it gets completely unreadable
    if (FullUrlRegExp.match(url).hasMatch()) {
        return StandardUrl;
    } else if (EmailAddressRegExp.match(url).hasMatch()) {
        return Email;
    } else {
        return Unknown;
    }
408
409
}

Kurt Hindenburg's avatar
Kurt Hindenburg committed
410
void UrlFilter::HotSpot::activate(QObject *object)
411
{
412
    QString url = capturedTexts().at(0);
413

414
415
    const UrlType kind = urlType();

Kurt Hindenburg's avatar
Kurt Hindenburg committed
416
    const QString &actionName = object != nullptr ? object->objectName() : QString();
417

418
    if (actionName == QLatin1String("copy-action")) {
419
420
        QApplication::clipboard()->setText(url);
        return;
421
422
    }

423
    if ((object == nullptr) || actionName == QLatin1String("open-action")) {
Kurt Hindenburg's avatar
Kurt Hindenburg committed
424
        if (kind == StandardUrl) {
425
            // if the URL path does not include the protocol ( eg. "www.kde.org" ) then
426
            // prepend https:// ( eg. "www.kde.org" --> "https://www.kde.org" )
427
            if (!url.contains(QLatin1String("://"))) {
428
                url.prepend(QLatin1String("https://"));
429
            }
Kurt Hindenburg's avatar
Kurt Hindenburg committed
430
        } else if (kind == Email) {
431
            url.prepend(QLatin1String("mailto:"));
432
        }
433

Kurt Hindenburg's avatar
Kurt Hindenburg committed
434
        new KRun(QUrl(url), QApplication::activeWindow());
435
436
    }
}
437

Kurt Hindenburg's avatar
Kurt Hindenburg committed
438
// Note:  Altering these regular expressions can have a major effect on the performance of the filters
439
440
441
442
// used for finding URLs in the text, especially if they are very general and could match very long
// pieces of text.
// Please be careful when altering them.

443
//regexp matches:
Kurt Hindenburg's avatar
Kurt Hindenburg committed
444
// full url:
445
// protocolname:// or www. followed by anything other than whitespaces, <, >, ' or ", and ends before whitespaces, <, >, ', ", ], !, ), :, comma and dot
446
const QRegularExpression UrlFilter::FullUrlRegExp(QStringLiteral("(www\\.(?!\\.)|[a-z][a-z0-9+.-]*://)[^\\s<>'\"]+[^!,\\.\\s<>'\"\\]\\)\\:]"),
447
                                                  QRegularExpression::OptimizeOnFirstUsageOption);
448
449
// email address:
// [word chars, dots or dashes]@[word chars, dots or dashes].[word chars]
450
const QRegularExpression UrlFilter::EmailAddressRegExp(QStringLiteral("\\b(\\w|\\.|-|\\+)+@(\\w|\\.|-)+\\.\\w+\\b"),
451
                                                       QRegularExpression::OptimizeOnFirstUsageOption);
452
453

// matches full url or email address
Kurt Hindenburg's avatar
Kurt Hindenburg committed
454
455
const QRegularExpression UrlFilter::CompleteUrlRegExp(QLatin1Char('(') + FullUrlRegExp.pattern() + QLatin1Char('|')
                                                      + EmailAddressRegExp.pattern() + QLatin1Char(')'),
456
                                                      QRegularExpression::OptimizeOnFirstUsageOption);
457

458
459
UrlFilter::UrlFilter()
{
Kurt Hindenburg's avatar
Kurt Hindenburg committed
460
    setRegExp(CompleteUrlRegExp);
461
}
Kurt Hindenburg's avatar
Kurt Hindenburg committed
462

463
UrlFilter::HotSpot::~HotSpot() = default;
Kurt Hindenburg's avatar
Kurt Hindenburg committed
464

Tomaz  Canabrava's avatar
Tomaz Canabrava committed
465
QList<QAction *> UrlFilter::HotSpot::actions()
466
{
467
468
    auto openAction = new QAction(this);
    auto copyAction = new QAction(this);
469

Jekyll Wu's avatar
Jekyll Wu committed
470
    const UrlType kind = urlType();
Kurt Hindenburg's avatar
Kurt Hindenburg committed
471
    Q_ASSERT(kind == StandardUrl || kind == Email);
472

Kurt Hindenburg's avatar
Kurt Hindenburg committed
473
    if (kind == StandardUrl) {
474
        openAction->setText(i18n("Open Link"));
475
        openAction->setIcon(QIcon::fromTheme(QStringLiteral("internet-services")));
476
        copyAction->setText(i18n("Copy Link Address"));
477
        copyAction->setIcon(QIcon::fromTheme(QStringLiteral("edit-copy-url")));
Kurt Hindenburg's avatar
Kurt Hindenburg committed
478
    } else if (kind == Email) {
479
        openAction->setText(i18n("Send Email To..."));
480
        openAction->setIcon(QIcon::fromTheme(QStringLiteral("mail-send")));
481
        copyAction->setText(i18n("Copy Email Address"));
482
        copyAction->setIcon(QIcon::fromTheme(QStringLiteral("edit-copy-mail")));
483
484
485
486
487
    }

    // object names are set here so that the hotspot performs the
    // correct action when activated() is called with the triggered
    // action passed as a parameter.
488
489
    openAction->setObjectName(QStringLiteral("open-action"));
    copyAction->setObjectName(QStringLiteral("copy-action"));
490

491
492
    QObject::connect(openAction, &QAction::triggered, this, [this, openAction]{ activate(openAction); });
    QObject::connect(copyAction, &QAction::triggered, this, [this, copyAction]{ activate(copyAction); });
493

494
    return {openAction, copyAction};
495
496
}

497
498
499
500
/**
  * File Filter - Construct a filter that works on local file paths using the
  * posix portable filename character set combined with KDE's mimetype filename
  * extension blob patterns.
501
  * https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_267
502
503
  */

504
QSharedPointer<Filter::HotSpot> FileFilter::newHotSpot(int startLine, int startColumn, int endLine,
Kurt Hindenburg's avatar
Kurt Hindenburg committed
505
                                              int endColumn, const QStringList &capturedTexts)
506
{
507
    if (_session.isNull()) {
508
        qCDebug(KonsoleDebug) << "Trying to create new hot spot without session!";
509
510
511
        return nullptr;
    }

512
513
514
515
    QString filename = capturedTexts.first();
    if (filename.startsWith(QLatin1Char('\'')) && filename.endsWith(QLatin1Char('\''))) {
        filename.remove(0, 1);
        filename.chop(1);
Kurt Hindenburg's avatar
Kurt Hindenburg committed
516
    }
517

518
519
520
    // Return nullptr if it's not:
    // <current dir>/filename
    // <current dir>/childDir/filename
521
522
523
524
    auto match = std::find_if(_currentDirContents.cbegin(), _currentDirContents.cend(),
                              [filename](const QString &s) { return filename.startsWith(s); });

    if (match == _currentDirContents.cend()) {
525
526
527
        return nullptr;
    }

528
    return QSharedPointer<Filter::HotSpot>(new FileFilter::HotSpot(startLine, startColumn, endLine, endColumn, capturedTexts, _dirPath + filename));
529
530
531
532
533
}

void FileFilter::process()
{
    const QDir dir(_session->currentWorkingDirectory());
534
535
536
    // Do not re-process.
    if (_dirPath != dir.canonicalPath() + QLatin1Char('/')) {
        _dirPath = dir.canonicalPath() + QLatin1Char('/');
537
#if QT_VERSION >= QT_VERSION_CHECK(5,14,0)
538

539
540
        const auto tmpList = dir.entryList(QDir::Dirs | QDir::Files);
        _currentDirContents = QSet<QString>(std::begin(tmpList), std::end(tmpList));
541

542
#else
543
        _currentDirContents = QSet<QString>::fromList(dir.entryList(QDir::Dirs | QDir::Files));
544
#endif
545
546
    }

547
    RegExpFilter::process();
548
549
}

Kurt Hindenburg's avatar
Kurt Hindenburg committed
550
FileFilter::HotSpot::HotSpot(int startLine, int startColumn, int endLine, int endColumn,
551
                             const QStringList &capturedTexts, const QString &filePath) :
Kurt Hindenburg's avatar
Kurt Hindenburg committed
552
    RegExpFilter::HotSpot(startLine, startColumn, endLine, endColumn, capturedTexts),
553
    _filePath(filePath)
554
555
556
557
{
    setType(Link);
}

Kurt Hindenburg's avatar
Kurt Hindenburg committed
558
void FileFilter::HotSpot::activate(QObject *)
559
{
560
561
562
    new KRun(QUrl::fromLocalFile(_filePath), QApplication::activeWindow());
}

Kurt Hindenburg's avatar
Kurt Hindenburg committed
563
564
FileFilter::FileFilter(Session *session) :
    _session(session)
565
    , _dirPath(QString())
566
    , _currentDirContents()
567
{
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
    Profile::Ptr profile = SessionManager::instance()->sessionProfile(_session);
    QString wordCharacters = profile->wordCharacters();

    /* The wordCharacters can be a potentially broken regexp,
     * so let's fix it manually if it has some troublesome characters.
     */
    // Add a folder delimiter at the beginning.
    if (wordCharacters.contains(QLatin1Char('/'))) {
        wordCharacters.remove(QLatin1Char('/'));
        wordCharacters.prepend(QStringLiteral("\\/"));
    }

    // Add minus at the end.
    if (wordCharacters.contains(QLatin1Char('-'))){
        wordCharacters.remove(QLatin1Char('-'));
        wordCharacters.append(QLatin1Char('-'));
    }

586
587
588
589
590
591
592
593
    static auto re = QRegularExpression(
        /* First part of the regexp means 'strings with spaces and starting with single quotes'
         * Second part means "Strings with double quotes"
         * Last part means "Everything else plus some special chars
         * This is much smaller, and faster, than the previous regexp
         * on the HotSpot creation we verify if this is indeed a file, so there's
         * no problem on testing on random words on the screen.
         */
594
595
596
597
            QLatin1String("'[^']+'")             // Matches everything between single quotes.
            + QStringLiteral(R"RX(|"[^"]+")RX")      // Matches everything inside double quotes
            + QStringLiteral(R"RX(|[\w%1]+)RX").arg(wordCharacters) // matches a contiguous line of alphanumeric characters plus some special ones defined in the profile.
        ,
598
        QRegularExpression::DontCaptureOption);
599
    setRegExp(re);
600
601
}

602
FileFilter::HotSpot::~HotSpot() = default;
603

Tomaz  Canabrava's avatar
Tomaz Canabrava committed
604
QList<QAction *> FileFilter::HotSpot::actions()
605
{
606
    QAction *action = new QAction(i18n("Copy Location"), this);
Tomaz  Canabrava's avatar
Tomaz Canabrava committed
607
    action->setIcon(QIcon::fromTheme(QStringLiteral("edit-copy")));
608
609
610
611
    connect(action, &QAction::triggered, this, [this] {
        QGuiApplication::clipboard()->setText(_filePath);
    });
    return {action};
612
}
613
614
615

void FileFilter::HotSpot::setupMenu(QMenu *menu)
{
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
    // We are reusing the QMenu, but we need to update the actions anyhow.
    // Remove the 'Open with' actions from it, then add the new ones.
    QList<QAction*> toDelete;
    for (auto *action : menu->actions()) {
        if (action->text().toLower().remove(QLatin1Char('&')).contains(i18n("open with"))) {
            toDelete.append(action);
        }
    }
    qDeleteAll(toDelete);

    const KFileItem fileItem(QUrl::fromLocalFile(_filePath));
    const KFileItemList itemList({fileItem});
    const KFileItemListProperties itemProperties(itemList);
    _menuActions.setParent(this);
    _menuActions.setItemListProperties(itemProperties);
    _menuActions.addOpenWithActionsTo(menu);
632
633
634

    // Here we added the actions to the last part of the menu, but we need to move them up.
    // TODO: As soon as addOpenWithActionsTo accepts a index, change this.
635
    // https://bugs.kde.org/show_bug.cgi?id=423765
636
637
638
639
640
641
642
    QAction *firstAction = menu->actions().at(0);
    for (auto *action : menu->actions()) {
        if (action->text().toLower().remove(QLatin1Char('&')).contains(i18n("open with"))) {
            menu->removeAction(action);
            menu->insertAction(firstAction, action);
        }
    }
643
644
645
    QAction *separator = new QAction(this);
    separator->setSeparator(true);
    menu->insertAction(firstAction, separator);
646
}
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671

// Static variables for the HotSpot
qintptr FileFilter::HotSpot::currentThumbnailHotspot = 0;
bool FileFilter::HotSpot::_canGenerateThumbnail = false;
QPointer<KIO::PreviewJob> FileFilter::HotSpot::_previewJob;

void FileFilter::HotSpot::requestThumbnail(Qt::KeyboardModifiers modifiers, const QPoint &pos) {
    _canGenerateThumbnail = true;
    currentThumbnailHotspot = reinterpret_cast<qintptr>(this);
    _eventModifiers = modifiers;
    _eventPos = pos;

    // Defer the real creation of the thumbnail by a few msec.
    QTimer::singleShot(250, this, [this]{
        if (currentThumbnailHotspot != reinterpret_cast<qintptr>(this)) {
            return;
        }

        thumbnailRequested();
    });
}

void FileFilter::HotSpot::stopThumbnailGeneration()
{
    _canGenerateThumbnail = false;
672
    if (_previewJob != nullptr) {
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
        _previewJob->deleteLater();
        QToolTip::hideText();
    }
}

void Konsole::FileFilter::HotSpot::showThumbnail(const KFileItem& item, const QPixmap& preview)
{
    if (!_canGenerateThumbnail) {
        return;
    }
    _thumbnailFinished = true;
    Q_UNUSED(item)
    QByteArray data;
    QBuffer buffer(&data);
    preview.save(&buffer, "PNG", 100);

    const auto tooltipString = QStringLiteral("<img src='data:image/png;base64, %0'>")
        .arg(QString::fromLocal8Bit(data.toBase64()));

    QToolTip::showText(_thumbnailPos, tooltipString, qApp->focusWidget());
}

void FileFilter::HotSpot::thumbnailRequested() {
    if (!_canGenerateThumbnail) {
        return;
    }

    auto *settings = KonsoleSettings::self();

    Qt::KeyboardModifiers modifiers = settings->thumbnailCtrl() ? Qt::ControlModifier : Qt::NoModifier;
    modifiers |= settings->thumbnailAlt() ? Qt::AltModifier : Qt::NoModifier;
    modifiers |= settings->thumbnailShift() ? Qt::ShiftModifier : Qt::NoModifier;

    if (_eventModifiers != modifiers) {
        return;
    }

    _thumbnailPos = QPoint(_eventPos.x() + 100, _eventPos.y() - settings->thumbnailSize() / 2);

    const int size = KonsoleSettings::thumbnailSize();
713
    if (_previewJob != nullptr) {
714
715
716
717
718
719
720
        _previewJob->deleteLater();
    }

    _thumbnailFinished = false;

    // Show a "Loading" if Preview takes a long time.
    QTimer::singleShot(10, this, [this]{
721
        if (_previewJob == nullptr) {
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
            return;
        }
        if (!_thumbnailFinished) {
            QToolTip::showText(_thumbnailPos, i18n("Generating Thumbnail"), qApp->focusWidget());
        }
    });

    _previewJob = new KIO::PreviewJob(KFileItemList({fileItem()}), QSize(size, size));
    connect(_previewJob, &KIO::PreviewJob::gotPreview, this, &FileFilter::HotSpot::showThumbnail);
    connect(_previewJob, &KIO::PreviewJob::failed, this, []{ QToolTip::hideText(); });
    _previewJob->setAutoDelete(true);
    _previewJob->start();
}

KFileItem Konsole::FileFilter::HotSpot::fileItem() const
{
    return KFileItem(QUrl::fromLocalFile(_filePath));
}