basefilefind.cpp 19.7 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
con's avatar
con committed
2
**
3 4
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
con's avatar
con committed
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
con's avatar
con committed
7
**
hjk's avatar
hjk committed
8 9 10 11
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
12 13 14
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
15
**
16 17 18 19 20 21 22
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
con's avatar
con committed
23
**
hjk's avatar
hjk committed
24
****************************************************************************/
hjk's avatar
hjk committed
25

con's avatar
con committed
26
#include "basefilefind.h"
27
#include "textdocument.h"
con's avatar
con committed
28

29
#include <aggregation/aggregate.h>
30
#include <coreplugin/icore.h>
31
#include <coreplugin/progressmanager/progressmanager.h>
32
#include <coreplugin/progressmanager/futureprogress.h>
33
#include <coreplugin/dialogs/readonlyfilesdialog.h>
34
#include <coreplugin/documentmanager.h>
35
#include <coreplugin/editormanager/editormanager.h>
36
#include <coreplugin/find/ifindsupport.h>
37
#include <texteditor/texteditor.h>
38
#include <texteditor/refactoringchanges.h>
39
#include <utils/fadingindicator.h>
40
#include <utils/filesearch.h>
41 42
#include <utils/qtcassert.h>
#include <utils/stylehelper.h>
con's avatar
con committed
43

44 45 46 47
#include <QDebug>
#include <QSettings>
#include <QHash>
#include <QPair>
48 49 50
#include <QStringListModel>
#include <QFutureWatcher>
#include <QPointer>
51
#include <QComboBox>
52
#include <QLabel>
con's avatar
con committed
53

54 55 56
using namespace Utils;
using namespace Core;

57 58
namespace TextEditor {
namespace Internal {
59

60 61 62 63 64 65 66 67 68 69
namespace {
class InternalEngine : public TextEditor::SearchEngine
{
public:
    InternalEngine() : m_widget(new QWidget) {}
    ~InternalEngine() override { delete m_widget;}
    QString title() const override { return tr("Internal"); }
    QString toolTip() const override { return QString(); }
    QWidget *widget() const override { return m_widget; }
    QVariant parameters() const override { return QVariant(); }
Tim Jenssen's avatar
Tim Jenssen committed
70 71
    void readSettings(QSettings * /*settings*/) override {}
    void writeSettings(QSettings * /*settings*/) const override {}
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
    QFuture<Utils::FileSearchResultList> executeSearch(
            const TextEditor::FileFindParameters &parameters,
            BaseFileFind *baseFileFind) override
    {
        auto func = parameters.flags & FindRegularExpression
                ? Utils::findInFilesRegExp
                : Utils::findInFiles;

        return func(parameters.text,
                    baseFileFind->files(parameters.nameFilters, parameters.additionalParameters),
                    textDocumentFlagsForFindFlags(parameters.flags),
                    TextDocument::openedTextDocumentContents());

    }
    Core::IEditor *openEditor(const Core::SearchResultItem &/*item*/,
                              const TextEditor::FileFindParameters &/*parameters*/) override
    {
        return nullptr;
    }

private:
    QWidget *m_widget;
};
95
} // namespace
96

97 98 99 100 101
class SearchEnginePrivate
{
public:
    bool isEnabled = true;
};
102

Orgad Shaneh's avatar
Orgad Shaneh committed
103 104 105 106 107 108 109
class CountingLabel : public QLabel
{
public:
    CountingLabel();
    void updateCount(int count);
};

110 111
class BaseFileFindPrivate
{
112
public:
113
    ~BaseFileFindPrivate() { delete m_internalSearchEngine; }
114 115
    QMap<QFutureWatcher<FileSearchResultList> *, QPointer<SearchResult> > m_watchers;
    QPointer<IFindSupport> m_currentFindSupport;
116

117
    QLabel *m_resultLabel = 0;
118 119 120
    QStringListModel m_filterStrings;
    QString m_filterSetting;
    QPointer<QComboBox> m_filterCombo;
121 122
    QVector<SearchEngine *> m_searchEngines;
    SearchEngine *m_internalSearchEngine;
123
    int m_currentSearchEngineIndex = -1;
124
};
125

126 127
} // namespace Internal

128
using namespace Internal;
129

130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
SearchEngine::SearchEngine()
    : d(new SearchEnginePrivate)
{
}

SearchEngine::~SearchEngine()
{
    delete d;
}

bool SearchEngine::isEnabled() const
{
    return d->isEnabled;
}

void SearchEngine::setEnabled(bool enabled)
{
    if (enabled == d->isEnabled)
        return;
    d->isEnabled = enabled;
    emit enabledChanged(d->isEnabled);
}

153
BaseFileFind::BaseFileFind() : d(new BaseFileFindPrivate)
con's avatar
con committed
154
{
155 156
    d->m_internalSearchEngine = new InternalEngine;
    addSearchEngine(d->m_internalSearchEngine);
con's avatar
con committed
157 158
}

159 160
BaseFileFind::~BaseFileFind()
{
161
    delete d;
162 163
}

con's avatar
con committed
164 165
bool BaseFileFind::isEnabled() const
{
166
    return true;
con's avatar
con committed
167 168
}

dt's avatar
dt committed
169 170
void BaseFileFind::cancel()
{
171 172
    SearchResult *search = qobject_cast<SearchResult *>(sender());
    QTC_ASSERT(search, return);
173
    QFutureWatcher<FileSearchResultList> *watcher = d->m_watchers.key(search);
174 175
    QTC_ASSERT(watcher, return);
    watcher->cancel();
dt's avatar
dt committed
176 177
}

178 179 180 181
void BaseFileFind::setPaused(bool paused)
{
    SearchResult *search = qobject_cast<SearchResult *>(sender());
    QTC_ASSERT(search, return);
182
    QFutureWatcher<FileSearchResultList> *watcher = d->m_watchers.key(search);
183 184 185 186 187
    QTC_ASSERT(watcher, return);
    if (!paused || watcher->isRunning()) // guard against pausing when the search is finished
        watcher->setPaused(paused);
}

con's avatar
con committed
188 189 190
QStringList BaseFileFind::fileNameFilters() const
{
    QStringList filters;
191
    if (d->m_filterCombo && !d->m_filterCombo->currentText().isEmpty()) {
192
        const QStringList parts = d->m_filterCombo->currentText().split(',');
con's avatar
con committed
193
        foreach (const QString &part, parts) {
194
            const QString filter = part.trimmed();
195
            if (!filter.isEmpty())
con's avatar
con committed
196 197 198 199 200 201
                filters << filter;
        }
    }
    return filters;
}

202
SearchEngine *BaseFileFind::currentSearchEngine() const
203
{
204 205 206 207 208 209 210 211 212 213 214 215
    if (d->m_searchEngines.isEmpty() || d->m_currentSearchEngineIndex == -1)
        return nullptr;
    return d->m_searchEngines[d->m_currentSearchEngineIndex];
}

QVector<SearchEngine *> BaseFileFind::searchEngines() const
{
    return d->m_searchEngines;
}

void BaseFileFind::setCurrentSearchEngine(int index)
{
216 217
    if (d->m_currentSearchEngineIndex == index)
        return;
218
    d->m_currentSearchEngineIndex = index;
219
    emit currentSearchEngineChanged();
220 221
}

222
void BaseFileFind::runNewSearch(const QString &txt, FindFlags findFlags,
223
                                    SearchResultWindow::SearchMode searchMode)
con's avatar
con committed
224
{
225 226 227
    d->m_currentFindSupport = 0;
    if (d->m_filterCombo)
        updateComboEntries(d->m_filterCombo, true);
228
    QString tooltip = toolTip();
229 230 231 232 233 234

    SearchResult *search = SearchResultWindow::instance()->startNewSearch(
                label(),
                tooltip.arg(IFindFilter::descriptionForFindFlags(findFlags)),
                txt, searchMode, SearchResultWindow::PreserveCaseEnabled,
                QString::fromLatin1("TextEditor"));
235
    search->setTextToReplace(txt);
236 237 238 239 240 241
    search->setSearchAgainSupported(true);
    FileFindParameters parameters;
    parameters.text = txt;
    parameters.flags = findFlags;
    parameters.nameFilters = fileNameFilters();
    parameters.additionalParameters = additionalParameters();
242 243
    parameters.searchEngineParameters = currentSearchEngine()->parameters();
    parameters.searchEngineIndex = d->m_currentSearchEngineIndex;
244
    search->setUserData(qVariantFromValue(parameters));
245 246 247 248 249 250 251 252 253
    connect(search, &SearchResult::activated, this, &BaseFileFind::openEditor);
    if (searchMode == SearchResultWindow::SearchAndReplace)
        connect(search, &SearchResult::replaceButtonClicked, this, &BaseFileFind::doReplace);
    connect(search, &SearchResult::visibilityChanged, this, &BaseFileFind::hideHighlightAll);
    connect(search, &SearchResult::cancelled, this, &BaseFileFind::cancel);
    connect(search, &SearchResult::paused, this, &BaseFileFind::setPaused);
    connect(search, &SearchResult::searchAgainRequested, this, &BaseFileFind::searchAgain);
    connect(this, &BaseFileFind::enabledChanged, search, &SearchResult::requestEnabledCheck);
    connect(search, &SearchResult::requestEnabledCheck, this, &BaseFileFind::recheckEnabled);
254

255 256 257
    runSearch(search);
}

258
void BaseFileFind::runSearch(SearchResult *search)
259 260
{
    FileFindParameters parameters = search->userData().value<FileFindParameters>();
261
    CountingLabel *label = new CountingLabel;
262
    connect(search, &SearchResult::countChanged, label, &CountingLabel::updateCount);
263
    CountingLabel *statusLabel = new CountingLabel;
264
    connect(search, &SearchResult::countChanged, statusLabel, &CountingLabel::updateCount);
265
    SearchResultWindow::instance()->popup(IOutputPane::Flags(IOutputPane::ModeSwitch|IOutputPane::WithFocus));
266
    QFutureWatcher<FileSearchResultList> *watcher = new QFutureWatcher<FileSearchResultList>();
267
    d->m_watchers.insert(watcher, search);
268
    watcher->setPendingResultsLimit(1);
269 270
    connect(watcher, &QFutureWatcherBase::resultReadyAt, this, &BaseFileFind::displayResult);
    connect(watcher, &QFutureWatcherBase::finished, this, &BaseFileFind::searchFinished);
Orgad Shaneh's avatar
Orgad Shaneh committed
271
    watcher->setFuture(executeSearch(parameters));
272
    FutureProgress *progress =
273
        ProgressManager::addTask(watcher->future(), tr("Searching"), Constants::TASK_SEARCH);
274
    progress->setWidget(label);
275
    progress->setStatusBarWidget(statusLabel);
276
    connect(progress, &FutureProgress::clicked, search, &SearchResult::popup);
con's avatar
con committed
277 278
}

279
void BaseFileFind::findAll(const QString &txt, FindFlags findFlags)
280 281 282 283
{
    runNewSearch(txt, findFlags, SearchResultWindow::SearchOnly);
}

284
void BaseFileFind::replaceAll(const QString &txt, FindFlags findFlags)
285
{
286
    runNewSearch(txt, findFlags, SearchResultWindow::SearchAndReplace);
287 288
}

289
void BaseFileFind::addSearchEngine(SearchEngine *searchEngine)
290
{
291
    d->m_searchEngines.push_back(searchEngine);
292 293
    if (d->m_searchEngines.size() == 1) // empty before, make sure we have a current engine
        setCurrentSearchEngine(0);
294 295
}

296
void BaseFileFind::doReplace(const QString &text,
297
                             const QList<SearchResultItem> &items,
298
                             bool preserveCase)
299
{
300
    QStringList files = replaceAll(text, items, preserveCase);
301
    if (!files.isEmpty()) {
302
        Utils::FadingIndicator::showText(ICore::mainWindow(),
303
            tr("%n occurrences replaced.", 0, items.size()),
304
            Utils::FadingIndicator::SmallText);
305
        DocumentManager::notifyFilesChangedInternally(files);
306
        SearchResultWindow::instance()->hide();
307 308 309
    }
}

con's avatar
con committed
310
void BaseFileFind::displayResult(int index) {
311 312
    QFutureWatcher<FileSearchResultList> *watcher =
            static_cast<QFutureWatcher<FileSearchResultList> *>(sender());
313
    SearchResult *search = d->m_watchers.value(watcher);
314 315 316
    if (!search) {
        // search was removed from search history while the search is running
        watcher->cancel();
317 318
        return;
    }
319 320 321 322
    FileSearchResultList results = watcher->resultAt(index);
    QList<SearchResultItem> items;
    foreach (const FileSearchResult &result, results) {
        SearchResultItem item;
323
        item.path = QStringList() << QDir::toNativeSeparators(result.fileName);
324 325 326 327
        item.mainRange.begin.line = result.lineNumber;
        item.mainRange.begin.column = result.matchStart;
        item.mainRange.end = item.mainRange.begin;
        item.mainRange.end.column += result.matchLength;
328 329
        item.text = result.matchingLine;
        item.useTextEditorFont = true;
330 331 332
        item.userData = result.regexpCapturedTexts;
        items << item;
    }
333
    search->addResults(items, SearchResult::AddOrdered);
con's avatar
con committed
334 335 336 337
}

void BaseFileFind::searchFinished()
{
338 339
    QFutureWatcher<FileSearchResultList> *watcher =
            static_cast<QFutureWatcher<FileSearchResultList> *>(sender());
340
    SearchResult *search = d->m_watchers.value(watcher);
341
    if (search)
Eike Ziller's avatar
Eike Ziller committed
342
        search->finishSearch(watcher->isCanceled());
343
    d->m_watchers.remove(watcher);
344
    watcher->deleteLater();
con's avatar
con committed
345 346 347 348 349
}

QWidget *BaseFileFind::createPatternWidget()
{
    QString filterToolTip = tr("List of comma separated wildcard filters");
350 351 352 353 354 355 356 357 358 359 360
    d->m_filterCombo = new QComboBox;
    d->m_filterCombo->setEditable(true);
    d->m_filterCombo->setModel(&d->m_filterStrings);
    d->m_filterCombo->setMaxCount(10);
    d->m_filterCombo->setMinimumContentsLength(10);
    d->m_filterCombo->setSizeAdjustPolicy(QComboBox::AdjustToMinimumContentsLengthWithIcon);
    d->m_filterCombo->setInsertPolicy(QComboBox::InsertAtBottom);
    d->m_filterCombo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    d->m_filterCombo->setToolTip(filterToolTip);
    syncComboWithSettings(d->m_filterCombo, d->m_filterSetting);
    return d->m_filterCombo;
con's avatar
con committed
361 362 363 364
}

void BaseFileFind::writeCommonSettings(QSettings *settings)
{
365
    settings->setValue("filters", d->m_filterStrings.stringList());
366
    if (d->m_filterCombo)
367 368 369 370 371
        settings->setValue("currentFilter", d->m_filterCombo->currentText());

    foreach (SearchEngine *searchEngine, d->m_searchEngines)
        searchEngine->writeSettings(settings);
    settings->setValue("currentSearchEngineIndex", d->m_currentSearchEngineIndex);
con's avatar
con committed
372 373 374 375
}

void BaseFileFind::readCommonSettings(QSettings *settings, const QString &defaultFilter)
{
376 377
    QStringList filters = settings->value("filters").toStringList();
    const QVariant currentFilter = settings->value("currentFilter");
378
    d->m_filterSetting = currentFilter.toString();
con's avatar
con committed
379 380
    if (filters.isEmpty())
        filters << defaultFilter;
381
    if (!currentFilter.isValid())
382 383 384 385
        d->m_filterSetting = filters.first();
    d->m_filterStrings.setStringList(filters);
    if (d->m_filterCombo)
        syncComboWithSettings(d->m_filterCombo, d->m_filterSetting);
386 387 388 389 390

    foreach (SearchEngine* searchEngine, d->m_searchEngines)
        searchEngine->readSettings(settings);
    const int currentSearchEngineIndex = settings->value("currentSearchEngineIndex", 0).toInt();
    syncSearchEngineCombo(currentSearchEngineIndex);
con's avatar
con committed
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
}

void BaseFileFind::syncComboWithSettings(QComboBox *combo, const QString &setting)
{
    if (!combo)
        return;
    int index = combo->findText(setting);
    if (index < 0)
        combo->setEditText(setting);
    else
        combo->setCurrentIndex(index);
}

void BaseFileFind::updateComboEntries(QComboBox *combo, bool onTop)
{
    int index = combo->findText(combo->currentText());
    if (index < 0) {
408
        if (onTop)
con's avatar
con committed
409
            combo->insertItem(0, combo->currentText());
410
        else
con's avatar
con committed
411 412 413 414 415
            combo->addItem(combo->currentText());
        combo->setCurrentIndex(combo->findText(combo->currentText()));
    }
}

416
void BaseFileFind::openEditor(const SearchResultItem &item)
con's avatar
con committed
417
{
418
    SearchResult *result = qobject_cast<SearchResult *>(sender());
419
    FileFindParameters parameters = result->userData().value<FileFindParameters>();
420 421
    IEditor *openedEditor =
            d->m_searchEngines[parameters.searchEngineIndex]->openEditor(item, parameters);
422 423 424
    if (!openedEditor) {
        if (item.path.size() > 0) {
            openedEditor = EditorManager::openEditorAt(QDir::fromNativeSeparators(item.path.first()),
425 426
                                                       item.mainRange.begin.line,
                                                       item.mainRange.begin.column, Id(),
427 428 429 430
                                                       EditorManager::DoNotSwitchToDesignMode);
        } else {
            openedEditor = EditorManager::openEditor(QDir::fromNativeSeparators(item.text));
        }
431
    }
432
    if (d->m_currentFindSupport)
433
        d->m_currentFindSupport->clearHighlights();
434
    d->m_currentFindSupport = 0;
435 436 437 438
    if (!openedEditor)
        return;
    // highlight results
    if (IFindSupport *findSupport = Aggregation::query<IFindSupport>(openedEditor->widget())) {
439 440
        d->m_currentFindSupport = findSupport;
        d->m_currentFindSupport->highlightAll(parameters.text, parameters.flags);
441
    }
con's avatar
con committed
442
}
443

444 445
void BaseFileFind::hideHighlightAll(bool visible)
{
446
    if (!visible && d->m_currentFindSupport)
447
        d->m_currentFindSupport->clearHighlights();
448 449
}

450 451 452
void BaseFileFind::searchAgain()
{
    SearchResult *search = qobject_cast<SearchResult *>(sender());
Eike Ziller's avatar
Eike Ziller committed
453
    search->restart();
454 455 456
    runSearch(search);
}

457 458 459 460 461 462 463 464
void BaseFileFind::recheckEnabled()
{
    SearchResult *search = qobject_cast<SearchResult *>(sender());
    if (!search)
        return;
    search->setSearchAgainEnabled(isEnabled());
}

465
QStringList BaseFileFind::replaceAll(const QString &text,
466
                                     const QList<SearchResultItem> &items,
467
                                     bool preserveCase)
468
{
469
    if (items.isEmpty())
470 471
        return QStringList();

472
    RefactoringChanges refactoring;
473

474 475
    QHash<QString, QList<SearchResultItem> > changes;
    foreach (const SearchResultItem &item, items)
476
        changes[QDir::fromNativeSeparators(item.path.first())].append(item);
477

478
    // Checking for files without write permissions
479
    QHashIterator<QString, QList<SearchResultItem> > it(changes);
480 481 482 483 484 485 486 487 488 489
    QSet<QString> roFiles;
    while (it.hasNext()) {
        it.next();
        const QFileInfo fileInfo(it.key());
        if (!fileInfo.isWritable())
            roFiles.insert(it.key());
    }

    // Query the user for permissions
    if (!roFiles.isEmpty()) {
hjk's avatar
hjk committed
490
        ReadOnlyFilesDialog roDialog(roFiles.toList(), ICore::mainWindow());
491
        roDialog.setShowFailWarning(true, tr("Aborting replace."));
hjk's avatar
hjk committed
492
        if (roDialog.exec() == ReadOnlyFilesDialog::RO_Cancel)
493 494 495 496
            return QStringList();
    }

    it.toFront();
497 498 499
    while (it.hasNext()) {
        it.next();
        const QString fileName = it.key();
500
        const QList<SearchResultItem> changeItems = it.value();
501

502 503 504
        ChangeSet changeSet;
        RefactoringFilePtr file = refactoring.file(fileName);
        QSet<QPair<int, int> > processed;
505
        foreach (const SearchResultItem &item, changeItems) {
506 507
            const QPair<int, int> &p = qMakePair(item.mainRange.begin.line,
                                                 item.mainRange.begin.column);
508 509 510 511 512
            if (processed.contains(p))
                continue;
            processed.insert(p);

            QString replacement;
513
            if (item.userData.canConvert<QStringList>() && !item.userData.toStringList().isEmpty()) {
514
                replacement = Utils::expandRegExpReplacement(text, item.userData.toStringList());
515
            } else if (preserveCase) {
516 517
                const QString originalText = (item.mainRange.length() == 0) ? item.text
                                                                            : item.mainRange.mid(text);
518 519
                replacement = Utils::matchCaseReplacement(originalText, text);
            } else {
520
                replacement = text;
521
            }
522

523 524 525 526
            const int start = file->position(item.mainRange.begin.line,
                                             item.mainRange.begin.column + 1);
            const int end = file->position(item.mainRange.end.line,
                                           item.mainRange.end.column + 1);
527
            changeSet.replace(start, end, replacement);
528
        }
529 530
        file->setChangeSet(changeSet);
        file->apply();
531 532 533 534
    }

    return changes.keys();
}
535

536 537 538 539 540
QVariant BaseFileFind::getAdditionalParameters(SearchResult *search)
{
    return search->userData().value<FileFindParameters>().additionalParameters;
}

Orgad Shaneh's avatar
Orgad Shaneh committed
541 542
QFuture<FileSearchResultList> BaseFileFind::executeSearch(const FileFindParameters &parameters)
{
543
    return d->m_searchEngines[parameters.searchEngineIndex]->executeSearch(parameters,this);
Orgad Shaneh's avatar
Orgad Shaneh committed
544 545 546 547
}

namespace Internal {

548 549 550 551 552 553 554 555 556
CountingLabel::CountingLabel()
{
    setAlignment(Qt::AlignCenter);
    // ### TODO this setup should be done by style
    QFont f = font();
    f.setBold(true);
    f.setPointSizeF(StyleHelper::sidebarFontSize());
    setFont(f);
    setPalette(StyleHelper::sidebarFontPalette(palette()));
557
    setProperty("_q_custom_style_disabled", QVariant(true));
558 559 560 561 562
    updateCount(0);
}

void CountingLabel::updateCount(int count)
{
Jaroslaw Kobus's avatar
Jaroslaw Kobus committed
563
    setText(BaseFileFind::tr("%n found", nullptr, count));
564
}
565

Orgad Shaneh's avatar
Orgad Shaneh committed
566
} // namespace Internal
567
} // namespace TextEditor