basefilefind.cpp 16.4 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
con's avatar
con committed
2
**
3
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
hjk's avatar
hjk committed
4
** Contact: http://www.qt-project.org/legal
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 12
** 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
** a written agreement between you and Digia.  For licensing terms and
Eike Ziller's avatar
Eike Ziller committed
13 14
** conditions see http://www.qt.io/licensing.  For further information
** 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 25 26
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt 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"
con's avatar
con committed
33

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

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

58 59
namespace TextEditor {
namespace Internal {
60 61 62

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

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

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

75 76
} // namespace Internal

77
using namespace Internal;
78
using namespace Utils;
79
using namespace Core;
80 81

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

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

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

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

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

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

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

158 159 160
    runSearch(search);
}

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

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

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

void BaseFileFind::doReplace(const QString &text,
203
                             const QList<Core::SearchResultItem> &items,
204
                             bool preserveCase)
205
{
206
    QStringList files = replaceAll(text, items, preserveCase);
207
    if (!files.isEmpty()) {
208
        DocumentManager::notifyFilesChangedInternally(files);
209
        Core::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
    Utils::FileSearchResultList results = watcher->resultAt(index);
223
    QList<Core::SearchResultItem> items;
224
    foreach (const Utils::FileSearchResult &result, results) {
225
        Core::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, Core::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 Core::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
                                                         item.lineNumber,
Eike Ziller's avatar
Eike Ziller committed
315
                                                         item.textMarkPos);
316
    } else {
317
        openedEditor = EditorManager::openEditor(QDir::fromNativeSeparators(item.text));
318
    }
319
    if (d->m_currentFindSupport)
320
        d->m_currentFindSupport->clearHighlights();
321
    d->m_currentFindSupport = 0;
322 323 324 325 326
    if (!openedEditor)
        return;
    // highlight results
    if (IFindSupport *findSupport = Aggregation::query<IFindSupport>(openedEditor->widget())) {
        if (result) {
327
            FileFindParameters parameters = result->userData().value<FileFindParameters>();
328 329
            d->m_currentFindSupport = findSupport;
            d->m_currentFindSupport->highlightAll(parameters.text, parameters.flags);
330
        }
331
    }
con's avatar
con committed
332
}
333

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

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

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

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

362
    RefactoringChanges refactoring;
363

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

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

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

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

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

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

    return changes.keys();
}
423

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

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

} // namespace TextEditor