basefilefind.cpp 16.2 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 "basefilefind_p.h"
28
#include "textdocument.h"
con's avatar
con committed
29

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

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

56 57 58
using namespace Utils;
using namespace Core;

59 60
namespace TextEditor {
namespace Internal {
61 62 63

class BaseFileFindPrivate
{
64 65 66
public:
    BaseFileFindPrivate() : m_resultLabel(0), m_filterCombo(0) {}

67 68
    QMap<QFutureWatcher<FileSearchResultList> *, QPointer<SearchResult> > m_watchers;
    QPointer<IFindSupport> m_currentFindSupport;
69 70 71 72 73 74

    QLabel *m_resultLabel;
    QStringListModel m_filterStrings;
    QString m_filterSetting;
    QPointer<QComboBox> m_filterCombo;
};
75

76 77
} // namespace Internal

78
using namespace Internal;
79 80

BaseFileFind::BaseFileFind() : d(new BaseFileFindPrivate)
con's avatar
con committed
81 82 83
{
}

84 85
BaseFileFind::~BaseFileFind()
{
86
    delete d;
87 88
}

con's avatar
con committed
89 90
bool BaseFileFind::isEnabled() const
{
91
    return true;
con's avatar
con committed
92 93
}

dt's avatar
dt committed
94 95
void BaseFileFind::cancel()
{
96 97
    SearchResult *search = qobject_cast<SearchResult *>(sender());
    QTC_ASSERT(search, return);
98
    QFutureWatcher<FileSearchResultList> *watcher = d->m_watchers.key(search);
99 100
    QTC_ASSERT(watcher, return);
    watcher->cancel();
dt's avatar
dt committed
101 102
}

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

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

127
void BaseFileFind::runNewSearch(const QString &txt, FindFlags findFlags,
128
                                    SearchResultWindow::SearchMode searchMode)
con's avatar
con committed
129
{
130 131 132
    d->m_currentFindSupport = 0;
    if (d->m_filterCombo)
        updateComboEntries(d->m_filterCombo, true);
133 134 135
    SearchResult *search = SearchResultWindow::instance()->startNewSearch(label(),
                           toolTip().arg(IFindFilter::descriptionForFindFlags(findFlags)),
                           txt, searchMode, SearchResultWindow::PreserveCaseEnabled,
136
                           QString::fromLatin1("TextEditor"));
137
    search->setTextToReplace(txt);
138 139 140 141 142 143 144
    search->setSearchAgainSupported(true);
    FileFindParameters parameters;
    parameters.text = txt;
    parameters.flags = findFlags;
    parameters.nameFilters = fileNameFilters();
    parameters.additionalParameters = additionalParameters();
    search->setUserData(qVariantFromValue(parameters));
145 146 147 148 149 150 151 152 153
    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);
154

155 156 157
    runSearch(search);
}

158
void BaseFileFind::runSearch(SearchResult *search)
159 160
{
    FileFindParameters parameters = search->userData().value<FileFindParameters>();
161
    CountingLabel *label = new CountingLabel;
162
    connect(search, &SearchResult::countChanged, label, &CountingLabel::updateCount);
163
    CountingLabel *statusLabel = new CountingLabel;
164
    connect(search, &SearchResult::countChanged, statusLabel, &CountingLabel::updateCount);
165
    SearchResultWindow::instance()->popup(IOutputPane::Flags(IOutputPane::ModeSwitch|IOutputPane::WithFocus));
166
    QFutureWatcher<FileSearchResultList> *watcher = new QFutureWatcher<FileSearchResultList>();
167
    d->m_watchers.insert(watcher, search);
168
    watcher->setPendingResultsLimit(1);
169 170
    connect(watcher, &QFutureWatcherBase::resultReadyAt, this, &BaseFileFind::displayResult);
    connect(watcher, &QFutureWatcherBase::finished, this, &BaseFileFind::searchFinished);
171
    if (parameters.flags & FindRegularExpression) {
172 173 174
        watcher->setFuture(Utils::findInFilesRegExp(parameters.text,
            files(parameters.nameFilters, parameters.additionalParameters),
            textDocumentFlagsForFindFlags(parameters.flags),
175
            TextDocument::openedTextDocumentContents()));
176
    } else {
177 178 179
        watcher->setFuture(Utils::findInFiles(parameters.text,
            files(parameters.nameFilters, parameters.additionalParameters),
            textDocumentFlagsForFindFlags(parameters.flags),
180
            TextDocument::openedTextDocumentContents()));
181
    }
182
    FutureProgress *progress =
183
        ProgressManager::addTask(watcher->future(), tr("Searching"), Constants::TASK_SEARCH);
184
    progress->setWidget(label);
185
    progress->setStatusBarWidget(statusLabel);
186
    connect(progress, &FutureProgress::clicked, search, &SearchResult::popup);
con's avatar
con committed
187 188
}

189
void BaseFileFind::findAll(const QString &txt, FindFlags findFlags)
190 191 192 193
{
    runNewSearch(txt, findFlags, SearchResultWindow::SearchOnly);
}

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

void BaseFileFind::doReplace(const QString &text,
200
                             const QList<SearchResultItem> &items,
201
                             bool preserveCase)
202
{
203
    QStringList files = replaceAll(text, items, preserveCase);
204
    if (!files.isEmpty()) {
205
        Utils::FadingIndicator::showText(ICore::mainWindow(),
206
            tr("%n occurrences replaced.", 0, items.size()),
207
            Utils::FadingIndicator::SmallText);
208
        DocumentManager::notifyFilesChangedInternally(files);
209
        SearchResultWindow::instance()->hide();
210 211 212
    }
}

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

void BaseFileFind::searchFinished()
{
240 241
    QFutureWatcher<FileSearchResultList> *watcher =
            static_cast<QFutureWatcher<FileSearchResultList> *>(sender());
242
    SearchResult *search = d->m_watchers.value(watcher);
243
    if (search)
Eike Ziller's avatar
Eike Ziller committed
244
        search->finishSearch(watcher->isCanceled());
245
    d->m_watchers.remove(watcher);
246
    watcher->deleteLater();
con's avatar
con committed
247 248 249 250 251
}

QWidget *BaseFileFind::createPatternWidget()
{
    QString filterToolTip = tr("List of comma separated wildcard filters");
252 253 254 255 256 257 258 259 260 261 262
    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
263 264 265 266
}

void BaseFileFind::writeCommonSettings(QSettings *settings)
{
267 268 269
    settings->setValue(QLatin1String("filters"), d->m_filterStrings.stringList());
    if (d->m_filterCombo)
        settings->setValue(QLatin1String("currentFilter"), d->m_filterCombo->currentText());
con's avatar
con committed
270 271 272 273
}

void BaseFileFind::readCommonSettings(QSettings *settings, const QString &defaultFilter)
{
274
    QStringList filters = settings->value(QLatin1String("filters")).toStringList();
275
    d->m_filterSetting = settings->value(QLatin1String("currentFilter")).toString();
con's avatar
con committed
276 277
    if (filters.isEmpty())
        filters << defaultFilter;
278 279 280 281 282
    if (d->m_filterSetting.isEmpty())
        d->m_filterSetting = filters.first();
    d->m_filterStrings.setStringList(filters);
    if (d->m_filterCombo)
        syncComboWithSettings(d->m_filterCombo, d->m_filterSetting);
con's avatar
con committed
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
}

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) {
300
        if (onTop)
con's avatar
con committed
301
            combo->insertItem(0, combo->currentText());
302
        else
con's avatar
con committed
303 304 305 306 307
            combo->addItem(combo->currentText());
        combo->setCurrentIndex(combo->findText(combo->currentText()));
    }
}

308
void BaseFileFind::openEditor(const SearchResultItem &item)
con's avatar
con committed
309
{
310
    SearchResult *result = qobject_cast<SearchResult *>(sender());
311
    IEditor *openedEditor = 0;
312
    if (item.path.size() > 0) {
313
        openedEditor = EditorManager::openEditorAt(QDir::fromNativeSeparators(item.path.first()),
314 315 316
                                                   item.lineNumber,
                                                   item.textMarkPos, Id(),
                                                   EditorManager::DoNotSwitchToDesignMode);
317
    } else {
318
        openedEditor = EditorManager::openEditor(QDir::fromNativeSeparators(item.text));
319
    }
320
    if (d->m_currentFindSupport)
321
        d->m_currentFindSupport->clearHighlights();
322
    d->m_currentFindSupport = 0;
323 324 325 326 327
    if (!openedEditor)
        return;
    // highlight results
    if (IFindSupport *findSupport = Aggregation::query<IFindSupport>(openedEditor->widget())) {
        if (result) {
328
            FileFindParameters parameters = result->userData().value<FileFindParameters>();
329 330
            d->m_currentFindSupport = findSupport;
            d->m_currentFindSupport->highlightAll(parameters.text, parameters.flags);
331
        }
332
    }
con's avatar
con committed
333
}
334

335 336
void BaseFileFind::hideHighlightAll(bool visible)
{
337
    if (!visible && d->m_currentFindSupport)
338
        d->m_currentFindSupport->clearHighlights();
339 340
}

341 342 343
void BaseFileFind::searchAgain()
{
    SearchResult *search = qobject_cast<SearchResult *>(sender());
Eike Ziller's avatar
Eike Ziller committed
344
    search->restart();
345 346 347
    runSearch(search);
}

348 349 350 351 352 353 354 355
void BaseFileFind::recheckEnabled()
{
    SearchResult *search = qobject_cast<SearchResult *>(sender());
    if (!search)
        return;
    search->setSearchAgainEnabled(isEnabled());
}

356
QStringList BaseFileFind::replaceAll(const QString &text,
357
                                     const QList<SearchResultItem> &items,
358
                                     bool preserveCase)
359
{
360
    if (items.isEmpty())
361 362
        return QStringList();

363
    RefactoringChanges refactoring;
364

365 366
    QHash<QString, QList<SearchResultItem> > changes;
    foreach (const SearchResultItem &item, items)
367
        changes[QDir::fromNativeSeparators(item.path.first())].append(item);
368

369
    // Checking for files without write permissions
370
    QHashIterator<QString, QList<SearchResultItem> > it(changes);
371 372 373 374 375 376 377 378 379 380
    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
381
        ReadOnlyFilesDialog roDialog(roFiles.toList(), ICore::mainWindow());
382
        roDialog.setShowFailWarning(true, tr("Aborting replace."));
hjk's avatar
hjk committed
383
        if (roDialog.exec() == ReadOnlyFilesDialog::RO_Cancel)
384 385 386 387
            return QStringList();
    }

    it.toFront();
388 389 390
    while (it.hasNext()) {
        it.next();
        const QString fileName = it.key();
391
        const QList<SearchResultItem> changeItems = it.value();
392

393 394 395
        ChangeSet changeSet;
        RefactoringFilePtr file = refactoring.file(fileName);
        QSet<QPair<int, int> > processed;
396
        foreach (const SearchResultItem &item, changeItems) {
397 398 399 400 401 402
            const QPair<int, int> &p = qMakePair(item.lineNumber, item.textMarkPos);
            if (processed.contains(p))
                continue;
            processed.insert(p);

            QString replacement;
403
            if (item.userData.canConvert<QStringList>() && !item.userData.toStringList().isEmpty()) {
404
                replacement = Utils::expandRegExpReplacement(text, item.userData.toStringList());
405 406 407 408 409
            } else if (preserveCase) {
                const QString originalText = (item.textMarkLength == 0) ? item.text
                                                                        : item.text.mid(item.textMarkPos, item.textMarkLength);
                replacement = Utils::matchCaseReplacement(originalText, text);
            } else {
410
                replacement = text;
411
            }
412 413 414 415 416

            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);
417
        }
418 419
        file->setChangeSet(changeSet);
        file->apply();
420 421 422 423
    }

    return changes.keys();
}
424

425 426 427 428 429
QVariant BaseFileFind::getAdditionalParameters(SearchResult *search)
{
    return search->userData().value<FileFindParameters>().additionalParameters;
}

430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
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));
}
446 447

} // namespace TextEditor