basefilefind.cpp 18.8 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
    QPointer<IFindSupport> m_currentFindSupport;
115

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

125 126
} // namespace Internal

127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
static void syncComboWithSettings(QComboBox *combo, const QString &setting)
{
    if (!combo)
        return;
    int index = combo->findText(setting);
    if (index < 0)
        combo->setEditText(setting);
    else
        combo->setCurrentIndex(index);
}

static void updateComboEntries(QComboBox *combo, bool onTop)
{
    int index = combo->findText(combo->currentText());
    if (index < 0) {
        if (onTop)
            combo->insertItem(0, combo->currentText());
        else
            combo->addItem(combo->currentText());
        combo->setCurrentIndex(combo->findText(combo->currentText()));
    }
}

150
using namespace Internal;
151

152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
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);
}

175
BaseFileFind::BaseFileFind() : d(new BaseFileFindPrivate)
con's avatar
con committed
176
{
177 178
    d->m_internalSearchEngine = new InternalEngine;
    addSearchEngine(d->m_internalSearchEngine);
con's avatar
con committed
179 180
}

181 182
BaseFileFind::~BaseFileFind()
{
183
    delete d;
184 185
}

con's avatar
con committed
186 187
bool BaseFileFind::isEnabled() const
{
188
    return true;
con's avatar
con committed
189 190 191 192 193
}

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

205
SearchEngine *BaseFileFind::currentSearchEngine() const
206
{
207 208 209 210 211 212 213 214 215 216 217 218
    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)
{
219 220
    if (d->m_currentSearchEngineIndex == index)
        return;
221
    d->m_currentSearchEngineIndex = index;
222
    emit currentSearchEngineChanged();
223 224
}

Eike Ziller's avatar
Eike Ziller committed
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
static void displayResult(QFutureWatcher<FileSearchResultList> *watcher,
                          SearchResult *search, int index)
{
    FileSearchResultList results = watcher->resultAt(index);
    QList<SearchResultItem> items;
    foreach (const FileSearchResult &result, results) {
        SearchResultItem item;
        item.path = QStringList() << QDir::toNativeSeparators(result.fileName);
        item.mainRange.begin.line = result.lineNumber;
        item.mainRange.begin.column = result.matchStart;
        item.mainRange.end = item.mainRange.begin;
        item.mainRange.end.column += result.matchLength;
        item.text = result.matchingLine;
        item.useTextEditorFont = true;
        item.userData = result.regexpCapturedTexts;
        items << item;
    }
    search->addResults(items, SearchResult::AddOrdered);
}

245
void BaseFileFind::runNewSearch(const QString &txt, FindFlags findFlags,
246
                                    SearchResultWindow::SearchMode searchMode)
con's avatar
con committed
247
{
248 249 250
    d->m_currentFindSupport = 0;
    if (d->m_filterCombo)
        updateComboEntries(d->m_filterCombo, true);
251
    QString tooltip = toolTip();
252 253 254 255 256 257

    SearchResult *search = SearchResultWindow::instance()->startNewSearch(
                label(),
                tooltip.arg(IFindFilter::descriptionForFindFlags(findFlags)),
                txt, searchMode, SearchResultWindow::PreserveCaseEnabled,
                QString::fromLatin1("TextEditor"));
258
    search->setTextToReplace(txt);
259 260 261 262 263 264
    search->setSearchAgainSupported(true);
    FileFindParameters parameters;
    parameters.text = txt;
    parameters.flags = findFlags;
    parameters.nameFilters = fileNameFilters();
    parameters.additionalParameters = additionalParameters();
265 266
    parameters.searchEngineParameters = currentSearchEngine()->parameters();
    parameters.searchEngineIndex = d->m_currentSearchEngineIndex;
267
    search->setUserData(qVariantFromValue(parameters));
268 269 270 271 272 273 274
    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::searchAgainRequested, this, &BaseFileFind::searchAgain);
    connect(this, &BaseFileFind::enabledChanged, search, &SearchResult::requestEnabledCheck);
    connect(search, &SearchResult::requestEnabledCheck, this, &BaseFileFind::recheckEnabled);
275

276 277 278
    runSearch(search);
}

279
void BaseFileFind::runSearch(SearchResult *search)
280 281
{
    FileFindParameters parameters = search->userData().value<FileFindParameters>();
282
    CountingLabel *label = new CountingLabel;
283
    connect(search, &SearchResult::countChanged, label, &CountingLabel::updateCount);
284
    CountingLabel *statusLabel = new CountingLabel;
285
    connect(search, &SearchResult::countChanged, statusLabel, &CountingLabel::updateCount);
286
    SearchResultWindow::instance()->popup(IOutputPane::Flags(IOutputPane::ModeSwitch|IOutputPane::WithFocus));
287 288
    QFutureWatcher<FileSearchResultList> *watcher = new QFutureWatcher<FileSearchResultList>();
    watcher->setPendingResultsLimit(1);
Eike Ziller's avatar
Eike Ziller committed
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
    // search is deleted if it is removed from search panel
    connect(search, &QObject::destroyed, watcher, &QFutureWatcherBase::cancel);
    connect(search, &SearchResult::cancelled, watcher, &QFutureWatcherBase::cancel);
    connect(search, &SearchResult::paused, watcher, [watcher](bool paused) {
        if (!paused || watcher->isRunning()) // guard against pausing when the search is finished
            watcher->setPaused(paused);
    });
    connect(watcher, &QFutureWatcherBase::resultReadyAt, search, [watcher, search](int index) {
        displayResult(watcher, search, index);
    });
    // auto-delete:
    connect(watcher, &QFutureWatcherBase::finished, watcher, &QObject::deleteLater);
    connect(watcher, &QFutureWatcherBase::finished, search, [watcher, search]() {
        search->finishSearch(watcher->isCanceled());
    });
Orgad Shaneh's avatar
Orgad Shaneh committed
304
    watcher->setFuture(executeSearch(parameters));
305
    FutureProgress *progress =
306
        ProgressManager::addTask(watcher->future(), tr("Searching"), Constants::TASK_SEARCH);
307
    progress->setWidget(label);
308
    progress->setStatusBarWidget(statusLabel);
309
    connect(progress, &FutureProgress::clicked, search, &SearchResult::popup);
con's avatar
con committed
310 311
}

312
void BaseFileFind::findAll(const QString &txt, FindFlags findFlags)
313 314 315 316
{
    runNewSearch(txt, findFlags, SearchResultWindow::SearchOnly);
}

317
void BaseFileFind::replaceAll(const QString &txt, FindFlags findFlags)
318
{
319
    runNewSearch(txt, findFlags, SearchResultWindow::SearchAndReplace);
320 321
}

322
void BaseFileFind::addSearchEngine(SearchEngine *searchEngine)
323
{
324
    d->m_searchEngines.push_back(searchEngine);
325 326
    if (d->m_searchEngines.size() == 1) // empty before, make sure we have a current engine
        setCurrentSearchEngine(0);
327 328
}

329
void BaseFileFind::doReplace(const QString &text,
330
                             const QList<SearchResultItem> &items,
331
                             bool preserveCase)
332
{
333
    QStringList files = replaceAll(text, items, preserveCase);
334
    if (!files.isEmpty()) {
335
        Utils::FadingIndicator::showText(ICore::mainWindow(),
336
            tr("%n occurrences replaced.", 0, items.size()),
337
            Utils::FadingIndicator::SmallText);
338
        DocumentManager::notifyFilesChangedInternally(files);
339
        SearchResultWindow::instance()->hide();
340 341 342
    }
}

con's avatar
con committed
343 344 345
QWidget *BaseFileFind::createPatternWidget()
{
    QString filterToolTip = tr("List of comma separated wildcard filters");
346 347 348 349 350 351 352 353 354 355 356
    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
357 358 359 360
}

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

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

    foreach (SearchEngine* searchEngine, d->m_searchEngines)
        searchEngine->readSettings(settings);
    const int currentSearchEngineIndex = settings->value("currentSearchEngineIndex", 0).toInt();
    syncSearchEngineCombo(currentSearchEngineIndex);
con's avatar
con committed
387 388
}

389
void BaseFileFind::openEditor(const SearchResultItem &item)
con's avatar
con committed
390
{
391
    SearchResult *result = qobject_cast<SearchResult *>(sender());
392
    FileFindParameters parameters = result->userData().value<FileFindParameters>();
393 394
    IEditor *openedEditor =
            d->m_searchEngines[parameters.searchEngineIndex]->openEditor(item, parameters);
395 396 397
    if (!openedEditor) {
        if (item.path.size() > 0) {
            openedEditor = EditorManager::openEditorAt(QDir::fromNativeSeparators(item.path.first()),
398 399
                                                       item.mainRange.begin.line,
                                                       item.mainRange.begin.column, Id(),
400 401 402 403
                                                       EditorManager::DoNotSwitchToDesignMode);
        } else {
            openedEditor = EditorManager::openEditor(QDir::fromNativeSeparators(item.text));
        }
404
    }
405
    if (d->m_currentFindSupport)
406
        d->m_currentFindSupport->clearHighlights();
407
    d->m_currentFindSupport = 0;
408 409 410 411
    if (!openedEditor)
        return;
    // highlight results
    if (IFindSupport *findSupport = Aggregation::query<IFindSupport>(openedEditor->widget())) {
412 413
        d->m_currentFindSupport = findSupport;
        d->m_currentFindSupport->highlightAll(parameters.text, parameters.flags);
414
    }
con's avatar
con committed
415
}
416

417 418
void BaseFileFind::hideHighlightAll(bool visible)
{
419
    if (!visible && d->m_currentFindSupport)
420
        d->m_currentFindSupport->clearHighlights();
421 422
}

423 424 425
void BaseFileFind::searchAgain()
{
    SearchResult *search = qobject_cast<SearchResult *>(sender());
Eike Ziller's avatar
Eike Ziller committed
426
    search->restart();
427 428 429
    runSearch(search);
}

430 431 432 433 434 435 436 437
void BaseFileFind::recheckEnabled()
{
    SearchResult *search = qobject_cast<SearchResult *>(sender());
    if (!search)
        return;
    search->setSearchAgainEnabled(isEnabled());
}

438
QStringList BaseFileFind::replaceAll(const QString &text,
439
                                     const QList<SearchResultItem> &items,
440
                                     bool preserveCase)
441
{
442
    if (items.isEmpty())
443 444
        return QStringList();

445
    RefactoringChanges refactoring;
446

447 448
    QHash<QString, QList<SearchResultItem> > changes;
    foreach (const SearchResultItem &item, items)
449
        changes[QDir::fromNativeSeparators(item.path.first())].append(item);
450

451
    // Checking for files without write permissions
452
    QHashIterator<QString, QList<SearchResultItem> > it(changes);
453 454 455 456 457 458 459 460 461 462
    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
463
        ReadOnlyFilesDialog roDialog(roFiles.toList(), ICore::mainWindow());
464
        roDialog.setShowFailWarning(true, tr("Aborting replace."));
hjk's avatar
hjk committed
465
        if (roDialog.exec() == ReadOnlyFilesDialog::RO_Cancel)
466 467 468 469
            return QStringList();
    }

    it.toFront();
470 471 472
    while (it.hasNext()) {
        it.next();
        const QString fileName = it.key();
473
        const QList<SearchResultItem> changeItems = it.value();
474

475 476 477
        ChangeSet changeSet;
        RefactoringFilePtr file = refactoring.file(fileName);
        QSet<QPair<int, int> > processed;
478
        foreach (const SearchResultItem &item, changeItems) {
479 480
            const QPair<int, int> &p = qMakePair(item.mainRange.begin.line,
                                                 item.mainRange.begin.column);
481 482 483 484 485
            if (processed.contains(p))
                continue;
            processed.insert(p);

            QString replacement;
486
            if (item.userData.canConvert<QStringList>() && !item.userData.toStringList().isEmpty()) {
487
                replacement = Utils::expandRegExpReplacement(text, item.userData.toStringList());
488
            } else if (preserveCase) {
489 490
                const QString originalText = (item.mainRange.length() == 0) ? item.text
                                                                            : item.mainRange.mid(text);
491 492
                replacement = Utils::matchCaseReplacement(originalText, text);
            } else {
493
                replacement = text;
494
            }
495

496 497 498 499
            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);
500
            changeSet.replace(start, end, replacement);
501
        }
502 503
        file->setChangeSet(changeSet);
        file->apply();
504 505 506 507
    }

    return changes.keys();
}
508

509 510 511 512 513
QVariant BaseFileFind::getAdditionalParameters(SearchResult *search)
{
    return search->userData().value<FileFindParameters>().additionalParameters;
}

Orgad Shaneh's avatar
Orgad Shaneh committed
514 515
QFuture<FileSearchResultList> BaseFileFind::executeSearch(const FileFindParameters &parameters)
{
516
    return d->m_searchEngines[parameters.searchEngineIndex]->executeSearch(parameters, this);
Orgad Shaneh's avatar
Orgad Shaneh committed
517 518 519 520
}

namespace Internal {

521 522 523 524 525 526 527 528 529
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()));
530
    setProperty("_q_custom_style_disabled", QVariant(true));
531 532 533 534 535
    updateCount(0);
}

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

Orgad Shaneh's avatar
Orgad Shaneh committed
539
} // namespace Internal
540
} // namespace TextEditor