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
13
14
** 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
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
15
**
16
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17
18
19
20
21
22
23
24
25
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** 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
26
27
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
28
****************************************************************************/
hjk's avatar
hjk committed
29

con's avatar
con committed
30
#include "basefilefind.h"
31
#include "basefilefind_p.h"
con's avatar
con committed
32

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

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

57
58
namespace TextEditor {
namespace Internal {
59
60
61

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

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

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

74
75
} // namespace Internal

76
using namespace Internal;
77
using namespace Utils;
78
using namespace Core;
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, Core::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
    SearchResult *search = Core::SearchResultWindow::instance()->startNewSearch(label(),
                           toolTip().arg(Core::IFindFilter::descriptionForFindFlags(findFlags)),
135
                           txt, searchMode, QString::fromLatin1("TextEditor"));
136
    search->setTextToReplace(txt);
137
138
139
140
141
142
143
    search->setSearchAgainSupported(true);
    FileFindParameters parameters;
    parameters.text = txt;
    parameters.flags = findFlags;
    parameters.nameFilters = fileNameFilters();
    parameters.additionalParameters = additionalParameters();
    search->setUserData(qVariantFromValue(parameters));
144
    connect(search, SIGNAL(activated(Core::SearchResultItem)), this, SLOT(openEditor(Core::SearchResultItem)));
145
    if (searchMode == SearchResultWindow::SearchAndReplace) {
146
147
        connect(search, SIGNAL(replaceButtonClicked(QString,QList<Core::SearchResultItem>,bool)),
                this, SLOT(doReplace(QString,QList<Core::SearchResultItem>,bool)));
148
    }
149
    connect(search, SIGNAL(visibilityChanged(bool)), this, SLOT(hideHighlightAll(bool)));
150
    connect(search, SIGNAL(cancelled()), this, SLOT(cancel()));
151
    connect(search, SIGNAL(paused(bool)), this, SLOT(setPaused(bool)));
152
    connect(search, SIGNAL(searchAgainRequested()), this, SLOT(searchAgain()));
153
154
155
    connect(this, SIGNAL(enabledChanged(bool)), search, SIGNAL(requestEnabledCheck()));
    connect(search, SIGNAL(requestEnabledCheck()), this, SLOT(recheckEnabled()));

156
157
158
    runSearch(search);
}

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

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

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

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

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

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

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

void BaseFileFind::writeCommonSettings(QSettings *settings)
{
265
266
267
    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
268
269
270
271
}

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

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

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

332
333
void BaseFileFind::hideHighlightAll(bool visible)
{
334
335
    if (!visible && d->m_currentFindSupport)
        d->m_currentFindSupport->clearResults();
336
337
}

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

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

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

360
    RefactoringChanges refactoring;
361

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

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

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

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

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

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

    return changes.keys();
}
421

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

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

} // namespace TextEditor