basefilefind.cpp 15.2 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
con's avatar
con committed
2
**
3
** Copyright (C) 2013 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>
con's avatar
con committed
37
#include <coreplugin/editormanager/editormanager.h>
38
#include <coreplugin/editormanager/ieditor.h>
39
#include <coreplugin/documentmanager.h>
con's avatar
con committed
40
41
42
#include <find/textfindconstants.h>
#include <texteditor/itexteditor.h>
#include <texteditor/basetexteditor.h>
43
#include <texteditor/refactoringchanges.h>
44
#include <utils/stylehelper.h>
45
#include <utils/fileutils.h>
46
#include <utils/qtcassert.h>
con's avatar
con committed
47

48
49
50
51
52
53
54
55
56
57
58
59
#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
60

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

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

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

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

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

90
91
92
93
94
95
96
97
98
99
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
100
101
102
103
QStringList BaseFileFind::fileNameFilters() const
{
    QStringList filters;
    if (m_filterCombo && !m_filterCombo->currentText().isEmpty()) {
104
        const QStringList parts = m_filterCombo->currentText().split(QLatin1Char(','));
con's avatar
con committed
105
        foreach (const QString &part, parts) {
106
            const QString filter = part.trimmed();
107
            if (!filter.isEmpty())
con's avatar
con committed
108
109
110
111
112
113
                filters << filter;
        }
    }
    return filters;
}

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

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

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

179
void BaseFileFind::replaceAll(const QString &txt, Find::FindFlags findFlags)
180
{
181
    runNewSearch(txt, findFlags, SearchResultWindow::SearchAndReplace);
182
183
184
}

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

con's avatar
con committed
195
void BaseFileFind::displayResult(int index) {
196
197
198
199
200
201
    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();
202
203
        return;
    }
204
    Utils::FileSearchResultList results = watcher->resultAt(index);
205
    QList<Find::SearchResultItem> items;
206
207
    foreach (const Utils::FileSearchResult &result, results) {
        Find::SearchResultItem item;
208
        item.path = QStringList() << QDir::toNativeSeparators(result.fileName);
209
        item.lineNumber = result.lineNumber;
210
211
212
213
        item.text = result.matchingLine;
        item.textMarkLength = result.matchLength;
        item.textMarkPos = result.matchStart;
        item.useTextEditorFont = true;
214
215
216
        item.userData = result.regexpCapturedTexts;
        items << item;
    }
217
    search->addResults(items, Find::SearchResult::AddOrdered);
con's avatar
con committed
218
219
220
221
}

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

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)
{
249
    settings->setValue(QLatin1String("filters"), m_filterStrings.stringList());
con's avatar
con committed
250
    if (m_filterCombo)
251
        settings->setValue(QLatin1String("currentFilter"), m_filterCombo->currentText());
con's avatar
con committed
252
253
254
255
}

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

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) {
282
        if (onTop)
con's avatar
con committed
283
            combo->insertItem(0, combo->currentText());
284
        else
con's avatar
con committed
285
286
287
288
289
            combo->addItem(combo->currentText());
        combo->setCurrentIndex(combo->findText(combo->currentText()));
    }
}

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

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

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

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

339
    RefactoringChanges refactoring;
340

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

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

351
352
353
354
355
356
357
358
359
360
        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;
361
            if (item.userData.canConvert<QStringList>() && !item.userData.toStringList().isEmpty()) {
362
                replacement = Utils::expandRegExpReplacement(text, item.userData.toStringList());
363
364
365
366
367
            } else if (preserveCase) {
                const QString originalText = (item.textMarkLength == 0) ? item.text
                                                                        : item.text.mid(item.textMarkPos, item.textMarkLength);
                replacement = Utils::matchCaseReplacement(originalText, text);
            } else {
368
                replacement = text;
369
            }
370
371
372
373
374

            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);
375
        }
376
377
        file->setChangeSet(changeSet);
        file->apply();
378
379
380
381
    }

    return changes.keys();
}
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398

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