basefilefind.cpp 16.6 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
con's avatar
con committed
2
**
Eike Ziller's avatar
Eike Ziller committed
3 4
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://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
Eike Ziller's avatar
Eike Ziller committed
12 13
** a written agreement between you and The Qt Company.  For licensing terms and
** conditions see http://www.qt.io/terms-conditions.  For further information
Eike Ziller's avatar
Eike Ziller committed
14
** use the contact form at http://www.qt.io/contact-us.
15
**
16
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17
** Alternatively, this file may be used under the terms of the GNU Lesser
Eike Ziller's avatar
Eike Ziller committed
18 19 20 21 22 23
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file.  Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
hjk's avatar
hjk committed
24
**
Eike Ziller's avatar
Eike Ziller committed
25 26
** In addition, as a special exception, The Qt Company gives you certain additional
** rights.  These rights are described in The Qt Company LGPL Exception
con's avatar
con committed
27 28
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
29
****************************************************************************/
hjk's avatar
hjk committed
30

con's avatar
con committed
31
#include "basefilefind.h"
32
#include "basefilefind_p.h"
33
#include "textdocument.h"
con's avatar
con committed
34

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

50 51 52 53
#include <QDebug>
#include <QSettings>
#include <QHash>
#include <QPair>
54 55 56
#include <QStringListModel>
#include <QFutureWatcher>
#include <QPointer>
57
#include <QComboBox>
58
#include <QLabel>
59
#include <QLabel>
con's avatar
con committed
60

61 62 63
using namespace Utils;
using namespace Core;

64 65
namespace TextEditor {
namespace Internal {
66 67 68

class BaseFileFindPrivate
{
69 70 71
public:
    BaseFileFindPrivate() : m_resultLabel(0), m_filterCombo(0) {}

72 73
    QMap<QFutureWatcher<FileSearchResultList> *, QPointer<SearchResult> > m_watchers;
    QPointer<IFindSupport> m_currentFindSupport;
74 75 76 77 78 79

    QLabel *m_resultLabel;
    QStringListModel m_filterStrings;
    QString m_filterSetting;
    QPointer<QComboBox> m_filterCombo;
};
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
void BaseFileFind::runNewSearch(const QString &txt, FindFlags findFlags,
133
                                    SearchResultWindow::SearchMode searchMode)
con's avatar
con committed
134
{
135 136 137
    d->m_currentFindSupport = 0;
    if (d->m_filterCombo)
        updateComboEntries(d->m_filterCombo, true);
138 139 140
    SearchResult *search = SearchResultWindow::instance()->startNewSearch(label(),
                           toolTip().arg(IFindFilter::descriptionForFindFlags(findFlags)),
                           txt, searchMode, SearchResultWindow::PreserveCaseEnabled,
141
                           QString::fromLatin1("TextEditor"));
142
    search->setTextToReplace(txt);
143 144 145 146 147 148 149
    search->setSearchAgainSupported(true);
    FileFindParameters parameters;
    parameters.text = txt;
    parameters.flags = findFlags;
    parameters.nameFilters = fileNameFilters();
    parameters.additionalParameters = additionalParameters();
    search->setUserData(qVariantFromValue(parameters));
150
    connect(search, SIGNAL(activated(Core::SearchResultItem)), this, SLOT(openEditor(Core::SearchResultItem)));
151
    if (searchMode == SearchResultWindow::SearchAndReplace) {
152 153
        connect(search, SIGNAL(replaceButtonClicked(QString,QList<Core::SearchResultItem>,bool)),
                this, SLOT(doReplace(QString,QList<Core::SearchResultItem>,bool)));
154
    }
155
    connect(search, SIGNAL(visibilityChanged(bool)), this, SLOT(hideHighlightAll(bool)));
156
    connect(search, SIGNAL(cancelled()), this, SLOT(cancel()));
157
    connect(search, SIGNAL(paused(bool)), this, SLOT(setPaused(bool)));
158
    connect(search, SIGNAL(searchAgainRequested()), this, SLOT(searchAgain()));
159 160 161
    connect(this, SIGNAL(enabledChanged(bool)), search, SIGNAL(requestEnabledCheck()));
    connect(search, SIGNAL(requestEnabledCheck()), this, SLOT(recheckEnabled()));

162 163 164
    runSearch(search);
}

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

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

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

void BaseFileFind::doReplace(const QString &text,
207
                             const QList<SearchResultItem> &items,
208
                             bool preserveCase)
209
{
210
    QStringList files = replaceAll(text, items, preserveCase);
211
    if (!files.isEmpty()) {
212
        Utils::FadingIndicator::showText(ICore::mainWindow(),
Jarek Kobus's avatar
Jarek Kobus committed
213
            tr("%n occurrences replaced.", nullptr, items.size()),
214
            Utils::FadingIndicator::SmallText);
215
        DocumentManager::notifyFilesChangedInternally(files);
216
        SearchResultWindow::instance()->hide();
217 218 219
    }
}

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

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

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

void BaseFileFind::writeCommonSettings(QSettings *settings)
{
274 275 276
    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
277 278 279 280
}

void BaseFileFind::readCommonSettings(QSettings *settings, const QString &defaultFilter)
{
281
    QStringList filters = settings->value(QLatin1String("filters")).toStringList();
282
    d->m_filterSetting = settings->value(QLatin1String("currentFilter")).toString();
con's avatar
con committed
283 284
    if (filters.isEmpty())
        filters << defaultFilter;
285 286 287 288 289
    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
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
}

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) {
307
        if (onTop)
con's avatar
con committed
308
            combo->insertItem(0, combo->currentText());
309
        else
con's avatar
con committed
310 311 312 313 314
            combo->addItem(combo->currentText());
        combo->setCurrentIndex(combo->findText(combo->currentText()));
    }
}

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

342 343
void BaseFileFind::hideHighlightAll(bool visible)
{
344
    if (!visible && d->m_currentFindSupport)
345
        d->m_currentFindSupport->clearHighlights();
346 347
}

348 349 350
void BaseFileFind::searchAgain()
{
    SearchResult *search = qobject_cast<SearchResult *>(sender());
Eike Ziller's avatar
Eike Ziller committed
351
    search->restart();
352 353 354
    runSearch(search);
}

355 356 357 358 359 360 361 362
void BaseFileFind::recheckEnabled()
{
    SearchResult *search = qobject_cast<SearchResult *>(sender());
    if (!search)
        return;
    search->setSearchAgainEnabled(isEnabled());
}

363
QStringList BaseFileFind::replaceAll(const QString &text,
364
                                     const QList<SearchResultItem> &items,
365
                                     bool preserveCase)
366
{
367
    if (items.isEmpty())
368 369
        return QStringList();

370
    RefactoringChanges refactoring;
371

372 373
    QHash<QString, QList<SearchResultItem> > changes;
    foreach (const SearchResultItem &item, items)
374
        changes[QDir::fromNativeSeparators(item.path.first())].append(item);
375

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

    it.toFront();
395 396 397
    while (it.hasNext()) {
        it.next();
        const QString fileName = it.key();
398
        const QList<SearchResultItem> changeItems = it.value();
399

400 401 402
        ChangeSet changeSet;
        RefactoringFilePtr file = refactoring.file(fileName);
        QSet<QPair<int, int> > processed;
403
        foreach (const SearchResultItem &item, changeItems) {
404 405 406 407 408 409
            const QPair<int, int> &p = qMakePair(item.lineNumber, item.textMarkPos);
            if (processed.contains(p))
                continue;
            processed.insert(p);

            QString replacement;
410
            if (item.userData.canConvert<QStringList>() && !item.userData.toStringList().isEmpty()) {
411
                replacement = Utils::expandRegExpReplacement(text, item.userData.toStringList());
412 413 414 415 416
            } else if (preserveCase) {
                const QString originalText = (item.textMarkLength == 0) ? item.text
                                                                        : item.text.mid(item.textMarkPos, item.textMarkLength);
                replacement = Utils::matchCaseReplacement(originalText, text);
            } else {
417
                replacement = text;
418
            }
419 420 421 422 423

            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);
424
        }
425 426
        file->setChangeSet(changeSet);
        file->apply();
427 428 429 430
    }

    return changes.keys();
}
431

432 433 434 435 436
QVariant BaseFileFind::getAdditionalParameters(SearchResult *search)
{
    return search->userData().value<FileFindParameters>().additionalParameters;
}

437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
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));
}
453 454

} // namespace TextEditor