basefilefind.cpp 16.3 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/texteditor.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 60
using namespace Utils;
using namespace Core;

61 62
namespace TextEditor {
namespace Internal {
63 64 65

class BaseFileFindPrivate
{
66 67 68
public:
    BaseFileFindPrivate() : m_resultLabel(0), m_filterCombo(0) {}

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

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

78 79
} // namespace Internal

80
using namespace Internal;
81 82

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

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

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

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

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

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

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

159 160 161
    runSearch(search);
}

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

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

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

void BaseFileFind::doReplace(const QString &text,
204
                             const QList<SearchResultItem> &items,
205
                             bool preserveCase)
206
{
207
    QStringList files = replaceAll(text, items, preserveCase);
208
    if (!files.isEmpty()) {
209
        DocumentManager::notifyFilesChangedInternally(files);
210
        SearchResultWindow::instance()->hide();
211 212 213
    }
}

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

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

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

void BaseFileFind::writeCommonSettings(QSettings *settings)
{
268 269 270
    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
271 272 273 274
}

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

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

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

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

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

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

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

364
    RefactoringChanges refactoring;
365

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

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

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

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

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

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

    return changes.keys();
}
425

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

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

} // namespace TextEditor