basefilefind.cpp 19.6 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
}

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

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

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

QWidget *BaseFileFind::createPatternWidget()
{
    QString filterToolTip = tr("List of comma separated wildcard filters");
348 349 350 351 352 353 354 355 356 357 358
    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
359 360 361 362
}

void BaseFileFind::writeCommonSettings(QSettings *settings)
{
363
    settings->setValue("filters", d->m_filterStrings.stringList());
364
    if (d->m_filterCombo)
365 366 367 368 369
        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
370 371 372 373
}

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

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

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) {
406
        if (onTop)
con's avatar
con committed
407
            combo->insertItem(0, combo->currentText());
408
        else
con's avatar
con committed
409 410 411 412 413
            combo->addItem(combo->currentText());
        combo->setCurrentIndex(combo->findText(combo->currentText()));
    }
}

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

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

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

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

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

470
    RefactoringChanges refactoring;
471

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

476
    // Checking for files without write permissions
477
    QHashIterator<QString, QList<SearchResultItem> > it(changes);
478 479 480 481 482 483 484 485 486 487
    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
488
        ReadOnlyFilesDialog roDialog(roFiles.toList(), ICore::mainWindow());
489
        roDialog.setShowFailWarning(true, tr("Aborting replace."));
hjk's avatar
hjk committed
490
        if (roDialog.exec() == ReadOnlyFilesDialog::RO_Cancel)
491 492 493 494
            return QStringList();
    }

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

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

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

521 522 523 524
            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);
525
            changeSet.replace(start, end, replacement);
526
        }
527 528
        file->setChangeSet(changeSet);
        file->apply();
529 530 531 532
    }

    return changes.keys();
}
533

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

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

namespace Internal {

546 547 548 549 550 551 552 553 554
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()));
555
    setProperty("_q_custom_style_disabled", QVariant(true));
556 557 558 559 560
    updateCount(0);
}

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

Orgad Shaneh's avatar
Orgad Shaneh committed
564
} // namespace Internal
565
} // namespace TextEditor