basefilefind.cpp 15.3 KB
Newer Older
1
/**************************************************************************
con's avatar
con committed
2
3
4
**
** This file is part of Qt Creator
**
con's avatar
con committed
5
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
con's avatar
con committed
6
**
hjk's avatar
hjk committed
7
** Contact: Nokia Corporation (info@qt.nokia.com)
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
** If you have questions regarding the use of this file, please contact
Tobias Hunger's avatar
Tobias Hunger committed
29
** Nokia at info@qt.nokia.com.
con's avatar
con committed
30
**
31
**************************************************************************/
hjk's avatar
hjk committed
32

con's avatar
con committed
33
34
#include "basefilefind.h"

35
#include <aggregation/aggregate.h>
36
#include <coreplugin/icore.h>
37
#include <coreplugin/progressmanager/progressmanager.h>
38
#include <coreplugin/progressmanager/futureprogress.h>
con's avatar
con committed
39
#include <coreplugin/editormanager/editormanager.h>
40
#include <coreplugin/editormanager/ieditor.h>
41
#include <coreplugin/filemanager.h>
con's avatar
con committed
42
43
44
#include <find/textfindconstants.h>
#include <texteditor/itexteditor.h>
#include <texteditor/basetexteditor.h>
45
#include <utils/stylehelper.h>
46
#include <utils/fileutils.h>
47
#include <utils/qtcassert.h>
con's avatar
con committed
48

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

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

65
66
67
BaseFileFind::BaseFileFind()
  : m_currentSearch(0),
    m_currentSearchCount(0),
con's avatar
con committed
68
69
    m_isSearching(false),
    m_resultLabel(0),
70
    m_filterCombo(0)
con's avatar
con committed
71
72
73
74
75
76
{
    m_watcher.setPendingResultsLimit(1);
    connect(&m_watcher, SIGNAL(resultReadyAt(int)), this, SLOT(displayResult(int)));
    connect(&m_watcher, SIGNAL(finished()), this, SLOT(searchFinished()));
}

77
78
79
80
BaseFileFind::~BaseFileFind()
{
}

con's avatar
con committed
81
82
83
84
85
bool BaseFileFind::isEnabled() const
{
    return !m_isSearching;
}

dt's avatar
dt committed
86
87
88
89
90
void BaseFileFind::cancel()
{
    m_watcher.cancel();
}

con's avatar
con committed
91
92
93
94
QStringList BaseFileFind::fileNameFilters() const
{
    QStringList filters;
    if (m_filterCombo && !m_filterCombo->currentText().isEmpty()) {
95
        const QStringList parts = m_filterCombo->currentText().split(QLatin1Char(','));
con's avatar
con committed
96
        foreach (const QString &part, parts) {
97
            const QString filter = part.trimmed();
con's avatar
con committed
98
99
100
101
102
103
104
105
            if (!filter.isEmpty()) {
                filters << filter;
            }
        }
    }
    return filters;
}

106
107
void BaseFileFind::runNewSearch(const QString &txt, Find::FindFlags findFlags,
                                    SearchResultWindow::SearchMode searchMode)
con's avatar
con committed
108
109
{
    m_isSearching = true;
110
    m_currentFindSupport = 0;
con's avatar
con committed
111
    emit changed();
con's avatar
con committed
112
    if (m_filterCombo)
113
        updateComboEntries(m_filterCombo, true);
114
    m_watcher.setFuture(QFuture<FileSearchResultList>());
115
116
117
118
119
120
    m_currentSearchCount = 0;
    m_currentSearch = Find::SearchResultWindow::instance()->startNewSearch(searchMode,
                                                     searchMode == SearchResultWindow::SearchAndReplace
                                                     ? QString::fromLatin1("TextEditor")
                                                     : QString());
    m_currentSearch->setTextToReplace(txt);
121
122
123
    m_currentSearch->setInfo(label(),
                             toolTip().arg(Find::IFindFilter::descriptionForFindFlags(findFlags)),
                             txt);
124
125
    QVariantList searchParameters;
    searchParameters << qVariantFromValue(txt) << qVariantFromValue(findFlags);
126
127
    m_currentSearch->setUserData(searchParameters);
    connect(m_currentSearch, SIGNAL(activated(Find::SearchResultItem)), this, SLOT(openEditor(Find::SearchResultItem)));
128
    if (searchMode == SearchResultWindow::SearchAndReplace) {
129
        connect(m_currentSearch, SIGNAL(replaceButtonClicked(QString,QList<Find::SearchResultItem>)),
130
131
                this, SLOT(doReplace(QString,QList<Find::SearchResultItem>)));
    }
132
133
    connect(m_currentSearch, SIGNAL(visibilityChanged(bool)), this, SLOT(hideHighlightAll(bool)));
    Find::SearchResultWindow::instance()->popup(true);
134
    if (findFlags & Find::FindRegularExpression) {
135
136
137
138
139
140
        m_watcher.setFuture(Utils::findInFilesRegExp(txt, files(),
            textDocumentFlagsForFindFlags(findFlags), ITextEditor::openedTextEditorsContents()));
    } else {
        m_watcher.setFuture(Utils::findInFiles(txt, files(),
            textDocumentFlagsForFindFlags(findFlags), ITextEditor::openedTextEditorsContents()));
    }
141
    connect(m_currentSearch, SIGNAL(cancelled()), this, SLOT(cancel()));
142
    Core::FutureProgress *progress =
143
        Core::ICore::instance()->progressManager()->addTask(m_watcher.future(),
Robert Loehning's avatar
Robert Loehning committed
144
                                                                        tr("Search"),
145
                                                                        Constants::TASK_SEARCH);
con's avatar
con committed
146
    progress->setWidget(createProgressWidget());
147
    connect(progress, SIGNAL(clicked()), Find::SearchResultWindow::instance(), SLOT(popup()));
con's avatar
con committed
148
149
}

150
151
152
153
154
void BaseFileFind::findAll(const QString &txt, Find::FindFlags findFlags)
{
    runNewSearch(txt, findFlags, SearchResultWindow::SearchOnly);
}

155
void BaseFileFind::replaceAll(const QString &txt, Find::FindFlags findFlags)
156
{
157
    runNewSearch(txt, findFlags, SearchResultWindow::SearchAndReplace);
158
159
160
161
162
163
164
165
166
}

void BaseFileFind::doReplace(const QString &text,
                               const QList<Find::SearchResultItem> &items)
{
    QStringList files = replaceAll(text, items);
    Core::FileManager *fileManager = Core::ICore::instance()->fileManager();
    if (!files.isEmpty()) {
        fileManager->notifyFilesChangedInternally(files);
167
        Find::SearchResultWindow::instance()->hide();
168
169
170
    }
}

con's avatar
con committed
171
void BaseFileFind::displayResult(int index) {
172
    Utils::FileSearchResultList results = m_watcher.future().resultAt(index);
173
    QList<Find::SearchResultItem> items;
174
175
    foreach (const Utils::FileSearchResult &result, results) {
        Find::SearchResultItem item;
176
        item.path = QStringList() << QDir::toNativeSeparators(result.fileName);
177
        item.lineNumber = result.lineNumber;
178
179
180
181
        item.text = result.matchingLine;
        item.textMarkLength = result.matchLength;
        item.textMarkPos = result.matchStart;
        item.useTextEditorFont = true;
182
183
184
        item.userData = result.regexpCapturedTexts;
        items << item;
    }
185
186
    m_currentSearch->addResults(items, Find::SearchResult::AddOrdered);
    m_currentSearchCount += items.count();
con's avatar
con committed
187
    if (m_resultLabel)
188
        m_resultLabel->setText(tr("%1 found").arg(m_currentSearchCount));
con's avatar
con committed
189
190
191
192
}

void BaseFileFind::searchFinished()
{
193
194
    m_currentSearch->finishSearch();
    m_currentSearch = 0;
con's avatar
con committed
195
196
197
198
199
200
201
202
    m_isSearching = false;
    m_resultLabel = 0;
    emit changed();
}

QWidget *BaseFileFind::createProgressWidget()
{
    m_resultLabel = new QLabel;
203
    m_resultLabel->setAlignment(Qt::AlignCenter);
con's avatar
con committed
204
205
206
207
208
209
    // ### TODO this setup should be done by style
    QFont f = m_resultLabel->font();
    f.setBold(true);
    f.setPointSizeF(StyleHelper::sidebarFontSize());
    m_resultLabel->setFont(f);
    m_resultLabel->setPalette(StyleHelper::sidebarFontPalette(m_resultLabel->palette()));
210
    m_resultLabel->setText(tr("%1 found").arg(m_currentSearchCount));
con's avatar
con committed
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
    return m_resultLabel;
}

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)
{
    settings->setValue("filters", m_filterStrings.stringList());
    if (m_filterCombo)
        settings->setValue("currentFilter", m_filterCombo->currentText());
}

void BaseFileFind::readCommonSettings(QSettings *settings, const QString &defaultFilter)
{
    QStringList filters = settings->value("filters").toStringList();
    m_filterSetting = settings->value("currentFilter").toString();
    if (filters.isEmpty())
        filters << defaultFilter;
    if (m_filterSetting.isEmpty())
        m_filterSetting = filters.first();
    m_filterStrings.setStringList(filters);
con's avatar
con committed
246
247
    if (m_filterCombo)
        syncComboWithSettings(m_filterCombo, m_filterSetting);
con's avatar
con committed
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
}

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

274
void BaseFileFind::openEditor(const Find::SearchResultItem &item)
con's avatar
con committed
275
{
276
277
    SearchResult *result = qobject_cast<SearchResult *>(sender());
    Core::IEditor *openedEditor = 0;
278
    if (item.path.size() > 0) {
279
280
281
282
283
        openedEditor = TextEditor::BaseTextEditorWidget::openEditorAt(QDir::fromNativeSeparators(item.path.first()),
                                                                      item.lineNumber,
                                                                      item.textMarkPos,
                                                                      QString(),
                                                                      Core::EditorManager::ModeSwitch);
284
    } else {
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
        openedEditor = Core::EditorManager::instance()->openEditor(item.text, QString(),
                                                                   Core::EditorManager::ModeSwitch);
    }
    if (m_currentFindSupport)
        m_currentFindSupport->clearResults();
    m_currentFindSupport = 0;
    if (!openedEditor)
        return;
    // highlight results
    if (IFindSupport *findSupport = Aggregation::query<IFindSupport>(openedEditor->widget())) {
        if (result) {
            QVariantList userData = result->userData().value<QVariantList>();
            QTC_ASSERT(userData.size() != 0, return);
            m_currentFindSupport = findSupport;
            m_currentFindSupport->highlightAll(userData.at(0).toString(), userData.at(1).value<FindFlags>());
        }
301
    }
con's avatar
con committed
302
}
303

304
305
306
307
308
309
void BaseFileFind::hideHighlightAll(bool visible)
{
    if (!visible && m_currentFindSupport)
        m_currentFindSupport->clearResults();
}

con's avatar
con committed
310
// #pragma mark Static methods
311
312
313

static void applyChanges(QTextDocument *doc, const QString &text, const QList<Find::SearchResultItem> &items)
{
314
    QList<QPair<QTextCursor, QString> > changes;
315
316
317
318
319

    foreach (const Find::SearchResultItem &item, items) {
        const int blockNumber = item.lineNumber - 1;
        QTextCursor tc(doc->findBlockByNumber(blockNumber));

320
        const int cursorPosition = tc.position() + item.textMarkPos;
321
322

        int cursorIndex = 0;
323
324
        for (; cursorIndex < changes.size(); ++cursorIndex) {
            const QTextCursor &otherTc = changes.at(cursorIndex).first;
325

326
            if (otherTc.position() == cursorPosition)
327
328
329
                break;
        }

330
        if (cursorIndex != changes.size())
331
332
333
            continue; // skip this change.

        tc.setPosition(cursorPosition);
334
        tc.setPosition(tc.position() + item.textMarkLength,
335
                       QTextCursor::KeepAnchor);
336
337
338
339
340
341
        QString substitutionText;
        if (item.userData.canConvert<QStringList>() && !item.userData.toStringList().isEmpty())
            substitutionText = Utils::expandRegExpReplacement(text, item.userData.toStringList());
        else
            substitutionText = text;
        changes.append(QPair<QTextCursor, QString>(tc, substitutionText));
342
343
    }

344
345
346
347
    for (int i = 0; i < changes.size(); ++i) {
        QPair<QTextCursor, QString> &cursor = changes[i];
        cursor.first.insertText(cursor.second);
    }
348
349
350
351
352
}

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

    QHash<QString, QList<Find::SearchResultItem> > changes;

    foreach (const Find::SearchResultItem &item, items)
359
        changes[QDir::fromNativeSeparators(item.path.first())].append(item);
360
361
362
363
364
365
366
367

    Core::EditorManager *editorManager = Core::EditorManager::instance();

    QHashIterator<QString, QList<Find::SearchResultItem> > it(changes);
    while (it.hasNext()) {
        it.next();

        const QString fileName = it.key();
368
        const QList<Find::SearchResultItem> changeItems = it.value();
369
370

        const QList<Core::IEditor *> editors = editorManager->editorsForFileName(fileName);
371
        TextEditor::BaseTextEditorWidget *textEditor = 0;
372
        foreach (Core::IEditor *editor, editors) {
373
            textEditor = qobject_cast<TextEditor::BaseTextEditorWidget *>(editor->widget());
374
375
376
377
378
379
380
            if (textEditor != 0)
                break;
        }

        if (textEditor != 0) {
            QTextCursor tc = textEditor->textCursor();
            tc.beginEditBlock();
381
            applyChanges(textEditor->document(), text, changeItems);
382
383
            tc.endEditBlock();
        } else {
384
385
            Utils::FileReader reader;
            if (reader.fetch(fileName, Core::ICore::instance()->mainWindow())) {
386
387
388
389
390
391
392
                // Keep track of line ending since QTextDocument is '\n' based.
                bool convertLineEnding = false;
                const QByteArray &data = reader.data();
                const int lf = data.indexOf('\n');
                if (lf > 0 && data.at(lf - 1) == '\r')
                    convertLineEnding = true;

393
                QTextDocument doc;
394
                // ### set the encoding
395
                doc.setPlainText(QString::fromLocal8Bit(data));
396
                applyChanges(&doc, text, changeItems);
397
398
399
400
                QString plainText = doc.toPlainText();

                if (convertLineEnding)
                    plainText.replace(QLatin1Char('\n'), QLatin1String("\r\n"));
401

402
403
404
                Utils::FileSaver saver(fileName);
                if (!saver.hasError()) {
                    QTextStream stream(saver.file());
405
                    // ### set the encoding
406
                    stream << plainText;
407
                    saver.setResult(&stream);
408
                }
409
                saver.finalize(Core::ICore::instance()->mainWindow());
410
411
412
413
414
415
            }
        }
    }

    return changes.keys();
}