basefilefind.cpp 17.1 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>
53
#include <QLabel>
con's avatar
con committed
54

55 56 57
using namespace Utils;
using namespace Core;

58 59
namespace TextEditor {
namespace Internal {
60

Orgad Shaneh's avatar
Orgad Shaneh committed
61 62 63 64 65 66 67
class CountingLabel : public QLabel
{
public:
    CountingLabel();
    void updateCount(int count);
};

68 69
class BaseFileFindPrivate
{
70
public:
71 72
    QMap<QFutureWatcher<FileSearchResultList> *, QPointer<SearchResult> > m_watchers;
    QPointer<IFindSupport> m_currentFindSupport;
73

74
    QLabel *m_resultLabel = 0;
75 76 77
    QStringListModel m_filterStrings;
    QString m_filterSetting;
    QPointer<QComboBox> m_filterCombo;
78
    QPointer<FileFindExtension> m_extension;
79
};
80

81 82
} // namespace Internal

83
using namespace Internal;
84 85

BaseFileFind::BaseFileFind() : d(new BaseFileFindPrivate)
con's avatar
con committed
86 87 88
{
}

89 90
BaseFileFind::~BaseFileFind()
{
91
    delete d;
92 93
}

con's avatar
con committed
94 95
bool BaseFileFind::isEnabled() const
{
96
    return true;
con's avatar
con committed
97 98
}

dt's avatar
dt committed
99 100
void BaseFileFind::cancel()
{
101 102
    SearchResult *search = qobject_cast<SearchResult *>(sender());
    QTC_ASSERT(search, return);
103
    QFutureWatcher<FileSearchResultList> *watcher = d->m_watchers.key(search);
104 105
    QTC_ASSERT(watcher, return);
    watcher->cancel();
dt's avatar
dt committed
106 107
}

108 109 110 111
void BaseFileFind::setPaused(bool paused)
{
    SearchResult *search = qobject_cast<SearchResult *>(sender());
    QTC_ASSERT(search, return);
112
    QFutureWatcher<FileSearchResultList> *watcher = d->m_watchers.key(search);
113 114 115 116 117
    QTC_ASSERT(watcher, return);
    if (!paused || watcher->isRunning()) // guard against pausing when the search is finished
        watcher->setPaused(paused);
}

con's avatar
con committed
118 119 120
QStringList BaseFileFind::fileNameFilters() const
{
    QStringList filters;
121 122
    if (d->m_filterCombo && !d->m_filterCombo->currentText().isEmpty()) {
        const QStringList parts = d->m_filterCombo->currentText().split(QLatin1Char(','));
con's avatar
con committed
123
        foreach (const QString &part, parts) {
124
            const QString filter = part.trimmed();
125
            if (!filter.isEmpty())
con's avatar
con committed
126 127 128 129 130 131
                filters << filter;
        }
    }
    return filters;
}

132 133 134 135 136
FileFindExtension *BaseFileFind::extension() const
{
    return d->m_extension.data();
}

137
void BaseFileFind::runNewSearch(const QString &txt, FindFlags findFlags,
138
                                    SearchResultWindow::SearchMode searchMode)
con's avatar
con committed
139
{
140 141 142
    d->m_currentFindSupport = 0;
    if (d->m_filterCombo)
        updateComboEntries(d->m_filterCombo, true);
143 144 145
    QString tooltip = toolTip();
    if (d->m_extension)
        tooltip = tooltip.arg(d->m_extension->toolTip());
146
    SearchResult *search = SearchResultWindow::instance()->startNewSearch(label(),
147
                           tooltip.arg(IFindFilter::descriptionForFindFlags(findFlags)),
148
                           txt, searchMode, SearchResultWindow::PreserveCaseEnabled,
149
                           QString::fromLatin1("TextEditor"));
150
    search->setTextToReplace(txt);
151 152 153 154 155 156
    search->setSearchAgainSupported(true);
    FileFindParameters parameters;
    parameters.text = txt;
    parameters.flags = findFlags;
    parameters.nameFilters = fileNameFilters();
    parameters.additionalParameters = additionalParameters();
157 158
    if (d->m_extension)
        parameters.extensionParameters = d->m_extension->parameters();
159
    search->setUserData(qVariantFromValue(parameters));
160 161 162 163 164 165 166 167 168
    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);
169

170 171 172
    runSearch(search);
}

173
void BaseFileFind::runSearch(SearchResult *search)
174 175
{
    FileFindParameters parameters = search->userData().value<FileFindParameters>();
176
    CountingLabel *label = new CountingLabel;
177
    connect(search, &SearchResult::countChanged, label, &CountingLabel::updateCount);
178
    CountingLabel *statusLabel = new CountingLabel;
179
    connect(search, &SearchResult::countChanged, statusLabel, &CountingLabel::updateCount);
180
    SearchResultWindow::instance()->popup(IOutputPane::Flags(IOutputPane::ModeSwitch|IOutputPane::WithFocus));
181
    QFutureWatcher<FileSearchResultList> *watcher = new QFutureWatcher<FileSearchResultList>();
182
    d->m_watchers.insert(watcher, search);
183
    watcher->setPendingResultsLimit(1);
184 185
    connect(watcher, &QFutureWatcherBase::resultReadyAt, this, &BaseFileFind::displayResult);
    connect(watcher, &QFutureWatcherBase::finished, this, &BaseFileFind::searchFinished);
Orgad Shaneh's avatar
Orgad Shaneh committed
186
    watcher->setFuture(executeSearch(parameters));
187
    FutureProgress *progress =
188
        ProgressManager::addTask(watcher->future(), tr("Searching"), Constants::TASK_SEARCH);
189
    progress->setWidget(label);
190
    progress->setStatusBarWidget(statusLabel);
191
    connect(progress, &FutureProgress::clicked, search, &SearchResult::popup);
con's avatar
con committed
192 193
}

194
void BaseFileFind::findAll(const QString &txt, FindFlags findFlags)
195 196 197 198
{
    runNewSearch(txt, findFlags, SearchResultWindow::SearchOnly);
}

199
void BaseFileFind::replaceAll(const QString &txt, FindFlags findFlags)
200
{
201
    runNewSearch(txt, findFlags, SearchResultWindow::SearchAndReplace);
202 203
}

204 205 206 207 208 209
void BaseFileFind::setFindExtension(FileFindExtension *extension)
{
    QTC_ASSERT(!d->m_extension, return);
    d->m_extension = extension;
}

210
void BaseFileFind::doReplace(const QString &text,
211
                             const QList<SearchResultItem> &items,
212
                             bool preserveCase)
213
{
214
    QStringList files = replaceAll(text, items, preserveCase);
215
    if (!files.isEmpty()) {
216
        Utils::FadingIndicator::showText(ICore::mainWindow(),
217
            tr("%n occurrences replaced.", 0, items.size()),
218
            Utils::FadingIndicator::SmallText);
219
        DocumentManager::notifyFilesChangedInternally(files);
220
        SearchResultWindow::instance()->hide();
221 222 223
    }
}

con's avatar
con committed
224
void BaseFileFind::displayResult(int index) {
225 226
    QFutureWatcher<FileSearchResultList> *watcher =
            static_cast<QFutureWatcher<FileSearchResultList> *>(sender());
227
    SearchResult *search = d->m_watchers.value(watcher);
228 229 230
    if (!search) {
        // search was removed from search history while the search is running
        watcher->cancel();
231 232
        return;
    }
233 234 235 236
    FileSearchResultList results = watcher->resultAt(index);
    QList<SearchResultItem> items;
    foreach (const FileSearchResult &result, results) {
        SearchResultItem item;
237
        item.path = QStringList() << QDir::toNativeSeparators(result.fileName);
238
        item.lineNumber = result.lineNumber;
239 240 241 242
        item.text = result.matchingLine;
        item.textMarkLength = result.matchLength;
        item.textMarkPos = result.matchStart;
        item.useTextEditorFont = true;
243 244 245
        item.userData = result.regexpCapturedTexts;
        items << item;
    }
246
    search->addResults(items, SearchResult::AddOrdered);
con's avatar
con committed
247 248 249 250
}

void BaseFileFind::searchFinished()
{
251 252
    QFutureWatcher<FileSearchResultList> *watcher =
            static_cast<QFutureWatcher<FileSearchResultList> *>(sender());
253
    SearchResult *search = d->m_watchers.value(watcher);
254
    if (search)
Eike Ziller's avatar
Eike Ziller committed
255
        search->finishSearch(watcher->isCanceled());
256
    d->m_watchers.remove(watcher);
257
    watcher->deleteLater();
con's avatar
con committed
258 259 260 261 262
}

QWidget *BaseFileFind::createPatternWidget()
{
    QString filterToolTip = tr("List of comma separated wildcard filters");
263 264 265 266 267 268 269 270 271 272 273
    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
274 275 276 277
}

void BaseFileFind::writeCommonSettings(QSettings *settings)
{
278 279 280
    settings->setValue(QLatin1String("filters"), d->m_filterStrings.stringList());
    if (d->m_filterCombo)
        settings->setValue(QLatin1String("currentFilter"), d->m_filterCombo->currentText());
281 282
    if (d->m_extension)
        d->m_extension->writeSettings(settings);
con's avatar
con committed
283 284 285 286
}

void BaseFileFind::readCommonSettings(QSettings *settings, const QString &defaultFilter)
{
287
    QStringList filters = settings->value(QLatin1String("filters")).toStringList();
288 289
    const QVariant currentFilter = settings->value(QLatin1String("currentFilter"));
    d->m_filterSetting = currentFilter.toString();
con's avatar
con committed
290 291
    if (filters.isEmpty())
        filters << defaultFilter;
292
    if (!currentFilter.isValid())
293 294 295 296
        d->m_filterSetting = filters.first();
    d->m_filterStrings.setStringList(filters);
    if (d->m_filterCombo)
        syncComboWithSettings(d->m_filterCombo, d->m_filterSetting);
297 298
    if (d->m_extension)
        d->m_extension->readSettings(settings);
con's avatar
con committed
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
}

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) {
316
        if (onTop)
con's avatar
con committed
317
            combo->insertItem(0, combo->currentText());
318
        else
con's avatar
con committed
319 320 321 322 323
            combo->addItem(combo->currentText());
        combo->setCurrentIndex(combo->findText(combo->currentText()));
    }
}

324
void BaseFileFind::openEditor(const SearchResultItem &item)
con's avatar
con committed
325
{
326
    SearchResult *result = qobject_cast<SearchResult *>(sender());
327
    FileFindParameters parameters = result->userData().value<FileFindParameters>();
328
    IEditor *openedEditor = 0;
329 330 331 332 333 334 335 336 337 338 339
    if (d->m_extension)
        openedEditor = d->m_extension->openEditor(item, parameters);
    if (!openedEditor) {
        if (item.path.size() > 0) {
            openedEditor = EditorManager::openEditorAt(QDir::fromNativeSeparators(item.path.first()),
                                                       item.lineNumber,
                                                       item.textMarkPos, Id(),
                                                       EditorManager::DoNotSwitchToDesignMode);
        } else {
            openedEditor = EditorManager::openEditor(QDir::fromNativeSeparators(item.text));
        }
340
    }
341
    if (d->m_currentFindSupport)
342
        d->m_currentFindSupport->clearHighlights();
343
    d->m_currentFindSupport = 0;
344 345 346 347
    if (!openedEditor)
        return;
    // highlight results
    if (IFindSupport *findSupport = Aggregation::query<IFindSupport>(openedEditor->widget())) {
348 349
        d->m_currentFindSupport = findSupport;
        d->m_currentFindSupport->highlightAll(parameters.text, parameters.flags);
350
    }
con's avatar
con committed
351
}
352

353 354
void BaseFileFind::hideHighlightAll(bool visible)
{
355
    if (!visible && d->m_currentFindSupport)
356
        d->m_currentFindSupport->clearHighlights();
357 358
}

359 360 361
void BaseFileFind::searchAgain()
{
    SearchResult *search = qobject_cast<SearchResult *>(sender());
Eike Ziller's avatar
Eike Ziller committed
362
    search->restart();
363 364 365
    runSearch(search);
}

366 367 368 369 370 371 372 373
void BaseFileFind::recheckEnabled()
{
    SearchResult *search = qobject_cast<SearchResult *>(sender());
    if (!search)
        return;
    search->setSearchAgainEnabled(isEnabled());
}

374
QStringList BaseFileFind::replaceAll(const QString &text,
375
                                     const QList<SearchResultItem> &items,
376
                                     bool preserveCase)
377
{
378
    if (items.isEmpty())
379 380
        return QStringList();

381
    RefactoringChanges refactoring;
382

383 384
    QHash<QString, QList<SearchResultItem> > changes;
    foreach (const SearchResultItem &item, items)
385
        changes[QDir::fromNativeSeparators(item.path.first())].append(item);
386

387
    // Checking for files without write permissions
388
    QHashIterator<QString, QList<SearchResultItem> > it(changes);
389 390 391 392 393 394 395 396 397 398
    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
399
        ReadOnlyFilesDialog roDialog(roFiles.toList(), ICore::mainWindow());
400
        roDialog.setShowFailWarning(true, tr("Aborting replace."));
hjk's avatar
hjk committed
401
        if (roDialog.exec() == ReadOnlyFilesDialog::RO_Cancel)
402 403 404 405
            return QStringList();
    }

    it.toFront();
406 407 408
    while (it.hasNext()) {
        it.next();
        const QString fileName = it.key();
409
        const QList<SearchResultItem> changeItems = it.value();
410

411 412 413
        ChangeSet changeSet;
        RefactoringFilePtr file = refactoring.file(fileName);
        QSet<QPair<int, int> > processed;
414
        foreach (const SearchResultItem &item, changeItems) {
415 416 417 418 419 420
            const QPair<int, int> &p = qMakePair(item.lineNumber, item.textMarkPos);
            if (processed.contains(p))
                continue;
            processed.insert(p);

            QString replacement;
421
            if (item.userData.canConvert<QStringList>() && !item.userData.toStringList().isEmpty()) {
422
                replacement = Utils::expandRegExpReplacement(text, item.userData.toStringList());
423 424 425 426 427
            } else if (preserveCase) {
                const QString originalText = (item.textMarkLength == 0) ? item.text
                                                                        : item.text.mid(item.textMarkPos, item.textMarkLength);
                replacement = Utils::matchCaseReplacement(originalText, text);
            } else {
428
                replacement = text;
429
            }
430 431 432 433 434

            const int start = file->position(item.lineNumber, item.textMarkPos + 1);
            const int end = file->position(item.lineNumber,
                                           item.textMarkPos + item.textMarkLength + 1);
            changeSet.replace(start, end, replacement);
435
        }
436 437
        file->setChangeSet(changeSet);
        file->apply();
438 439 440 441
    }

    return changes.keys();
}
442

443 444 445 446 447
QVariant BaseFileFind::getAdditionalParameters(SearchResult *search)
{
    return search->userData().value<FileFindParameters>().additionalParameters;
}

Orgad Shaneh's avatar
Orgad Shaneh committed
448 449
QFuture<FileSearchResultList> BaseFileFind::executeSearch(const FileFindParameters &parameters)
{
450 451 452
    if (d->m_extension && d->m_extension->isEnabled(parameters))
        return d->m_extension->executeSearch(parameters);

Orgad Shaneh's avatar
Orgad Shaneh committed
453 454 455 456 457 458 459 460 461 462 463 464
    auto func = parameters.flags & FindRegularExpression
            ? Utils::findInFilesRegExp
            : Utils::findInFiles;

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

namespace Internal {

465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
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()));
    updateCount(0);
}

void CountingLabel::updateCount(int count)
{
    setText(tr("%1 found").arg(count));
}
481

Orgad Shaneh's avatar
Orgad Shaneh committed
482
} // namespace Internal
483
} // namespace TextEditor