basefilefind.cpp 14.4 KB
Newer Older
1
/**************************************************************************
con's avatar
con committed
2
3
4
**
** This file is part of Qt Creator
**
hjk's avatar
hjk committed
5
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
con's avatar
con committed
6
**
Eike Ziller's avatar
Eike Ziller committed
7
** Contact: http://www.qt-project.org/
con's avatar
con committed
8
**
9
**
10
** GNU Lesser General Public License Usage
11
**
hjk's avatar
hjk committed
12
13
14
15
16
17
** 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.
18
**
con's avatar
con committed
19
** In addition, as a special exception, Nokia gives you certain additional
hjk's avatar
hjk committed
20
** rights. These rights are described in the Nokia Qt LGPL Exception
con's avatar
con committed
21
22
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
23
24
25
26
27
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
con's avatar
con committed
28
**
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>
con's avatar
con committed
38
#include <coreplugin/editormanager/editormanager.h>
39
#include <coreplugin/editormanager/ieditor.h>
40
#include <coreplugin/documentmanager.h>
con's avatar
con committed
41
42
43
#include <find/textfindconstants.h>
#include <texteditor/itexteditor.h>
#include <texteditor/basetexteditor.h>
44
#include <texteditor/refactoringchanges.h>
45
#include <utils/stylehelper.h>
46
#include <utils/fileutils.h>
47
#include <utils/qtcassert.h>
con's avatar
con committed
48

49
50
51
52
53
54
55
56
57
58
59
60
#include <QDebug>
#include <QDirIterator>
#include <QSettings>
#include <QHash>
#include <QPair>
#include <QFileDialog>
#include <QCheckBox>
#include <QComboBox>
#include <QHBoxLayout>
#include <QLabel>
#include <QPushButton>
#include <QTextBlock>
con's avatar
con committed
61

62
using namespace Utils;
con's avatar
con committed
63
64
using namespace Find;
using namespace TextEditor;
65
using namespace TextEditor::Internal;
con's avatar
con committed
66

67
BaseFileFind::BaseFileFind()
68
  : m_resultLabel(0),
69
    m_filterCombo(0)
con's avatar
con committed
70
71
72
{
}

73
74
75
76
BaseFileFind::~BaseFileFind()
{
}

con's avatar
con committed
77
78
bool BaseFileFind::isEnabled() const
{
79
    return true;
con's avatar
con committed
80
81
}

dt's avatar
dt committed
82
83
void BaseFileFind::cancel()
{
84
85
    SearchResult *search = qobject_cast<SearchResult *>(sender());
    QTC_ASSERT(search, return);
Eike Ziller's avatar
Eike Ziller committed
86
    QFutureWatcher<FileSearchResultList> *watcher = m_watchers.key(search);
87
88
    QTC_ASSERT(watcher, return);
    watcher->cancel();
dt's avatar
dt committed
89
90
}

91
92
93
94
95
96
97
98
99
100
void BaseFileFind::setPaused(bool paused)
{
    SearchResult *search = qobject_cast<SearchResult *>(sender());
    QTC_ASSERT(search, return);
    QFutureWatcher<FileSearchResultList> *watcher = m_watchers.key(search);
    QTC_ASSERT(watcher, return);
    if (!paused || watcher->isRunning()) // guard against pausing when the search is finished
        watcher->setPaused(paused);
}

con's avatar
con committed
101
102
103
104
QStringList BaseFileFind::fileNameFilters() const
{
    QStringList filters;
    if (m_filterCombo && !m_filterCombo->currentText().isEmpty()) {
105
        const QStringList parts = m_filterCombo->currentText().split(QLatin1Char(','));
con's avatar
con committed
106
        foreach (const QString &part, parts) {
107
            const QString filter = part.trimmed();
con's avatar
con committed
108
109
110
111
112
113
114
115
            if (!filter.isEmpty()) {
                filters << filter;
            }
        }
    }
    return filters;
}

116
117
void BaseFileFind::runNewSearch(const QString &txt, Find::FindFlags findFlags,
                                    SearchResultWindow::SearchMode searchMode)
con's avatar
con committed
118
{
119
    m_currentFindSupport = 0;
con's avatar
con committed
120
    if (m_filterCombo)
121
        updateComboEntries(m_filterCombo, true);
122
    SearchResult *search = Find::SearchResultWindow::instance()->startNewSearch(label(),
123
124
                           toolTip().arg(Find::IFindFilter::descriptionForFindFlags(findFlags)),
                           txt, searchMode, QString::fromLatin1("TextEditor"));
125
    search->setTextToReplace(txt);
126
127
128
129
130
131
132
    search->setSearchAgainSupported(true);
    FileFindParameters parameters;
    parameters.text = txt;
    parameters.flags = findFlags;
    parameters.nameFilters = fileNameFilters();
    parameters.additionalParameters = additionalParameters();
    search->setUserData(qVariantFromValue(parameters));
133
    connect(search, SIGNAL(activated(Find::SearchResultItem)), this, SLOT(openEditor(Find::SearchResultItem)));
134
    if (searchMode == SearchResultWindow::SearchAndReplace) {
135
        connect(search, SIGNAL(replaceButtonClicked(QString,QList<Find::SearchResultItem>)),
136
137
                this, SLOT(doReplace(QString,QList<Find::SearchResultItem>)));
    }
138
    connect(search, SIGNAL(visibilityChanged(bool)), this, SLOT(hideHighlightAll(bool)));
139
    connect(search, SIGNAL(cancelled()), this, SLOT(cancel()));
140
    connect(search, SIGNAL(paused(bool)), this, SLOT(setPaused(bool)));
141
    connect(search, SIGNAL(searchAgainRequested()), this, SLOT(searchAgain()));
142
    connect(this, SIGNAL(enabledChanged(bool)), search, SLOT(setSearchAgainEnabled(bool)));
143
144
145
146
147
148
    runSearch(search);
}

void BaseFileFind::runSearch(Find::SearchResult *search)
{
    FileFindParameters parameters = search->userData().value<FileFindParameters>();
149
150
    CountingLabel *label = new CountingLabel;
    connect(search, SIGNAL(countChanged(int)), label, SLOT(updateCount(int)));
151
    Find::SearchResultWindow::instance()->popup(Core::IOutputPane::Flags(Core::IOutputPane::ModeSwitch | Core::IOutputPane::WithFocus));
152
153
154
155
156
157
158
159
160
161
    QFutureWatcher<FileSearchResultList> *watcher = new QFutureWatcher<FileSearchResultList>();
    m_watchers.insert(watcher, search);
    watcher->setPendingResultsLimit(1);
    connect(watcher, SIGNAL(resultReadyAt(int)), this, SLOT(displayResult(int)));
    connect(watcher, SIGNAL(finished()), this, SLOT(searchFinished()));
    if (parameters.flags & Find::FindRegularExpression) {
        watcher->setFuture(Utils::findInFilesRegExp(parameters.text,
            files(parameters.nameFilters, parameters.additionalParameters),
            textDocumentFlagsForFindFlags(parameters.flags),
            ITextEditor::openedTextEditorsContents()));
162
    } else {
163
164
165
166
        watcher->setFuture(Utils::findInFiles(parameters.text,
            files(parameters.nameFilters, parameters.additionalParameters),
            textDocumentFlagsForFindFlags(parameters.flags),
            ITextEditor::openedTextEditorsContents()));
167
    }
168
    Core::FutureProgress *progress =
hjk's avatar
hjk committed
169
        Core::ICore::progressManager()->addTask(watcher->future(),
Robert Loehning's avatar
Robert Loehning committed
170
                                                                        tr("Search"),
171
                                                                        QLatin1String(Constants::TASK_SEARCH));
172
    progress->setWidget(label);
173
    connect(progress, SIGNAL(clicked()), search, SLOT(popup()));
con's avatar
con committed
174
175
}

176
177
178
179
180
void BaseFileFind::findAll(const QString &txt, Find::FindFlags findFlags)
{
    runNewSearch(txt, findFlags, SearchResultWindow::SearchOnly);
}

181
void BaseFileFind::replaceAll(const QString &txt, Find::FindFlags findFlags)
182
{
183
    runNewSearch(txt, findFlags, SearchResultWindow::SearchAndReplace);
184
185
186
187
188
189
190
}

void BaseFileFind::doReplace(const QString &text,
                               const QList<Find::SearchResultItem> &items)
{
    QStringList files = replaceAll(text, items);
    if (!files.isEmpty()) {
191
        Core::DocumentManager::notifyFilesChangedInternally(files);
192
        Find::SearchResultWindow::instance()->hide();
193
194
195
    }
}

con's avatar
con committed
196
void BaseFileFind::displayResult(int index) {
197
198
199
200
201
202
    QFutureWatcher<FileSearchResultList> *watcher =
            static_cast<QFutureWatcher<FileSearchResultList> *>(sender());
    SearchResult *search = m_watchers.value(watcher);
    if (!search) {
        // search was removed from search history while the search is running
        watcher->cancel();
203
204
        return;
    }
205
    Utils::FileSearchResultList results = watcher->resultAt(index);
206
    QList<Find::SearchResultItem> items;
207
208
    foreach (const Utils::FileSearchResult &result, results) {
        Find::SearchResultItem item;
209
        item.path = QStringList() << QDir::toNativeSeparators(result.fileName);
210
        item.lineNumber = result.lineNumber;
211
212
213
214
        item.text = result.matchingLine;
        item.textMarkLength = result.matchLength;
        item.textMarkPos = result.matchStart;
        item.useTextEditorFont = true;
215
216
217
        item.userData = result.regexpCapturedTexts;
        items << item;
    }
218
    search->addResults(items, Find::SearchResult::AddOrdered);
con's avatar
con committed
219
220
221
222
}

void BaseFileFind::searchFinished()
{
223
224
225
226
    QFutureWatcher<FileSearchResultList> *watcher =
            static_cast<QFutureWatcher<FileSearchResultList> *>(sender());
    SearchResult *search = m_watchers.value(watcher);
    if (search)
Eike Ziller's avatar
Eike Ziller committed
227
        search->finishSearch(watcher->isCanceled());
228
229
    m_watchers.remove(watcher);
    watcher->deleteLater();
con's avatar
con committed
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
}

QWidget *BaseFileFind::createPatternWidget()
{
    QString filterToolTip = tr("List of comma separated wildcard filters");
    m_filterCombo = new QComboBox;
    m_filterCombo->setEditable(true);
    m_filterCombo->setModel(&m_filterStrings);
    m_filterCombo->setMaxCount(10);
    m_filterCombo->setMinimumContentsLength(10);
    m_filterCombo->setSizeAdjustPolicy(QComboBox::AdjustToMinimumContentsLengthWithIcon);
    m_filterCombo->setInsertPolicy(QComboBox::InsertAtBottom);
    m_filterCombo->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    m_filterCombo->setToolTip(filterToolTip);
    syncComboWithSettings(m_filterCombo, m_filterSetting);
    return m_filterCombo;
}

void BaseFileFind::writeCommonSettings(QSettings *settings)
{
250
    settings->setValue(QLatin1String("filters"), m_filterStrings.stringList());
con's avatar
con committed
251
    if (m_filterCombo)
252
        settings->setValue(QLatin1String("currentFilter"), m_filterCombo->currentText());
con's avatar
con committed
253
254
255
256
}

void BaseFileFind::readCommonSettings(QSettings *settings, const QString &defaultFilter)
{
257
258
    QStringList filters = settings->value(QLatin1String("filters")).toStringList();
    m_filterSetting = settings->value(QLatin1String("currentFilter")).toString();
con's avatar
con committed
259
260
261
262
263
    if (filters.isEmpty())
        filters << defaultFilter;
    if (m_filterSetting.isEmpty())
        m_filterSetting = filters.first();
    m_filterStrings.setStringList(filters);
con's avatar
con committed
264
265
    if (m_filterCombo)
        syncComboWithSettings(m_filterCombo, m_filterSetting);
con's avatar
con committed
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
}

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) {
        if (onTop) {
            combo->insertItem(0, combo->currentText());
        } else {
            combo->addItem(combo->currentText());
        }
        combo->setCurrentIndex(combo->findText(combo->currentText()));
    }
}

292
void BaseFileFind::openEditor(const Find::SearchResultItem &item)
con's avatar
con committed
293
{
294
295
    SearchResult *result = qobject_cast<SearchResult *>(sender());
    Core::IEditor *openedEditor = 0;
296
    if (item.path.size() > 0) {
297
298
299
        openedEditor = TextEditor::BaseTextEditorWidget::openEditorAt(QDir::fromNativeSeparators(item.path.first()),
                                                                      item.lineNumber,
                                                                      item.textMarkPos,
hjk's avatar
hjk committed
300
                                                                      Core::Id(),
301
                                                                      Core::EditorManager::ModeSwitch);
302
    } else {
hjk's avatar
hjk committed
303
304
        openedEditor = Core::EditorManager::openEditor(QDir::fromNativeSeparators(item.text),
                                                        Core::Id(), Core::EditorManager::ModeSwitch);
305
306
307
308
309
310
311
312
313
    }
    if (m_currentFindSupport)
        m_currentFindSupport->clearResults();
    m_currentFindSupport = 0;
    if (!openedEditor)
        return;
    // highlight results
    if (IFindSupport *findSupport = Aggregation::query<IFindSupport>(openedEditor->widget())) {
        if (result) {
314
            FileFindParameters parameters = result->userData().value<FileFindParameters>();
315
            m_currentFindSupport = findSupport;
316
            m_currentFindSupport->highlightAll(parameters.text, parameters.flags);
317
        }
318
    }
con's avatar
con committed
319
}
320

321
322
323
324
325
326
void BaseFileFind::hideHighlightAll(bool visible)
{
    if (!visible && m_currentFindSupport)
        m_currentFindSupport->clearResults();
}

327
328
329
void BaseFileFind::searchAgain()
{
    SearchResult *search = qobject_cast<SearchResult *>(sender());
Eike Ziller's avatar
Eike Ziller committed
330
    search->restart();
331
332
333
    runSearch(search);
}

334
335
336
QStringList BaseFileFind::replaceAll(const QString &text,
                               const QList<Find::SearchResultItem> &items)
{
337
    if (items.isEmpty())
338
339
        return QStringList();

340
    RefactoringChanges refactoring;
341

342
    QHash<QString, QList<Find::SearchResultItem> > changes;
343
    foreach (const Find::SearchResultItem &item, items)
344
        changes[QDir::fromNativeSeparators(item.path.first())].append(item);
345
346
347
348
349

    QHashIterator<QString, QList<Find::SearchResultItem> > it(changes);
    while (it.hasNext()) {
        it.next();
        const QString fileName = it.key();
350
        const QList<Find::SearchResultItem> changeItems = it.value();
351

352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
        ChangeSet changeSet;
        RefactoringFilePtr file = refactoring.file(fileName);
        QSet<QPair<int, int> > processed;
        foreach (const Find::SearchResultItem &item, changeItems) {
            const QPair<int, int> &p = qMakePair(item.lineNumber, item.textMarkPos);
            if (processed.contains(p))
                continue;
            processed.insert(p);

            QString replacement;
            if (item.userData.canConvert<QStringList>() && !item.userData.toStringList().isEmpty())
                replacement = Utils::expandRegExpReplacement(text, item.userData.toStringList());
            else
                replacement = text;

            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);
371
        }
372
373
        file->setChangeSet(changeSet);
        file->apply();
374
375
376
377
    }

    return changes.keys();
}
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394

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));
}