basefilefind.cpp 14.9 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
55
#include <QtGui/QComboBox>
#include <QtGui/QLabel>
56
#include <QtGui/QMainWindow>
con's avatar
con committed
57
#include <QtGui/QPushButton>
58
#include <QtGui/QTextBlock>
con's avatar
con committed
59

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

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

bool BaseFileFind::isEnabled() const
{
    return !m_isSearching;
}

dt's avatar
dt committed
80
81
82
83
84
85
86
87
88
89
bool BaseFileFind::canCancel() const
{
    return m_isSearching;
}

void BaseFileFind::cancel()
{
    m_watcher.cancel();
}

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

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

143
144
145
146
147
void BaseFileFind::findAll(const QString &txt, Find::FindFlags findFlags)
{
    runNewSearch(txt, findFlags, SearchResultWindow::SearchOnly);
}

148
void BaseFileFind::replaceAll(const QString &txt, Find::FindFlags findFlags)
149
{
150
    runNewSearch(txt, findFlags, SearchResultWindow::SearchAndReplace);
151
152
153
154
155
156
157
158
159
160
161
162
163
}

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

con's avatar
con committed
164
void BaseFileFind::displayResult(int index) {
165
    Utils::FileSearchResultList results = m_watcher.future().resultAt(index);
166
    QList<Find::SearchResultItem> items;
167
168
    foreach (const Utils::FileSearchResult &result, results) {
        Find::SearchResultItem item;
169
        item.path = QStringList() << QDir::toNativeSeparators(result.fileName);
170
        item.lineNumber = result.lineNumber;
171
172
173
174
        item.text = result.matchingLine;
        item.textMarkLength = result.matchLength;
        item.textMarkPos = result.matchStart;
        item.useTextEditorFont = true;
175
176
177
        item.userData = result.regexpCapturedTexts;
        items << item;
    }
178
    m_resultWindow->addResults(items, Find::SearchResultWindow::AddOrdered);
con's avatar
con committed
179
180
181
182
183
184
    if (m_resultLabel)
        m_resultLabel->setText(tr("%1 found").arg(m_resultWindow->numberOfResults()));
}

void BaseFileFind::searchFinished()
{
185
    m_resultWindow->finishSearch();
con's avatar
con committed
186
187
188
189
190
191
192
193
    m_isSearching = false;
    m_resultLabel = 0;
    emit changed();
}

QWidget *BaseFileFind::createProgressWidget()
{
    m_resultLabel = new QLabel;
194
    m_resultLabel->setAlignment(Qt::AlignCenter);
con's avatar
con committed
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
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
    // ### 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()));
    m_resultLabel->setText(tr("%1 found").arg(m_resultWindow->numberOfResults()));
    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
237
238
    if (m_filterCombo)
        syncComboWithSettings(m_filterCombo, m_filterSetting);
con's avatar
con committed
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
}

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

265
void BaseFileFind::openEditor(const Find::SearchResultItem &item)
con's avatar
con committed
266
{
267
268
    SearchResult *result = qobject_cast<SearchResult *>(sender());
    Core::IEditor *openedEditor = 0;
269
    if (item.path.size() > 0) {
270
271
272
273
274
        openedEditor = TextEditor::BaseTextEditorWidget::openEditorAt(QDir::fromNativeSeparators(item.path.first()),
                                                                      item.lineNumber,
                                                                      item.textMarkPos,
                                                                      QString(),
                                                                      Core::EditorManager::ModeSwitch);
275
    } else {
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
        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>());
        }
292
    }
con's avatar
con committed
293
}
294

295
296
297
298
299
300
void BaseFileFind::hideHighlightAll(bool visible)
{
    if (!visible && m_currentFindSupport)
        m_currentFindSupport->clearResults();
}

con's avatar
con committed
301
// #pragma mark Static methods
302
303
304

static void applyChanges(QTextDocument *doc, const QString &text, const QList<Find::SearchResultItem> &items)
{
305
    QList<QPair<QTextCursor, QString> > changes;
306
307
308
309
310

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

311
        const int cursorPosition = tc.position() + item.textMarkPos;
312
313

        int cursorIndex = 0;
314
315
        for (; cursorIndex < changes.size(); ++cursorIndex) {
            const QTextCursor &otherTc = changes.at(cursorIndex).first;
316

317
            if (otherTc.position() == cursorPosition)
318
319
320
                break;
        }

321
        if (cursorIndex != changes.size())
322
323
324
            continue; // skip this change.

        tc.setPosition(cursorPosition);
325
        tc.setPosition(tc.position() + item.textMarkLength,
326
                       QTextCursor::KeepAnchor);
327
328
329
330
331
332
        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));
333
334
    }

335
336
337
338
    for (int i = 0; i < changes.size(); ++i) {
        QPair<QTextCursor, QString> &cursor = changes[i];
        cursor.first.insertText(cursor.second);
    }
339
340
341
342
343
}

QStringList BaseFileFind::replaceAll(const QString &text,
                               const QList<Find::SearchResultItem> &items)
{
344
    if (items.isEmpty())
345
346
347
348
349
        return QStringList();

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

    foreach (const Find::SearchResultItem &item, items)
350
        changes[QDir::fromNativeSeparators(item.path.first())].append(item);
351
352
353
354
355
356
357
358

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

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

        const QString fileName = it.key();
359
        const QList<Find::SearchResultItem> changeItems = it.value();
360
361

        const QList<Core::IEditor *> editors = editorManager->editorsForFileName(fileName);
362
        TextEditor::BaseTextEditorWidget *textEditor = 0;
363
        foreach (Core::IEditor *editor, editors) {
364
            textEditor = qobject_cast<TextEditor::BaseTextEditorWidget *>(editor->widget());
365
366
367
368
369
370
371
            if (textEditor != 0)
                break;
        }

        if (textEditor != 0) {
            QTextCursor tc = textEditor->textCursor();
            tc.beginEditBlock();
372
            applyChanges(textEditor->document(), text, changeItems);
373
374
            tc.endEditBlock();
        } else {
375
376
            Utils::FileReader reader;
            if (reader.fetch(fileName, Core::ICore::instance()->mainWindow())) {
377
378
379
380
381
382
383
                // 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;

384
                QTextDocument doc;
385
                // ### set the encoding
386
                doc.setPlainText(QString::fromLocal8Bit(data));
387
                applyChanges(&doc, text, changeItems);
388
389
390
391
                QString plainText = doc.toPlainText();

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

393
394
395
                Utils::FileSaver saver(fileName);
                if (!saver.hasError()) {
                    QTextStream stream(saver.file());
396
                    // ### set the encoding
397
                    stream << plainText;
398
                    saver.setResult(&stream);
399
                }
400
                saver.finalize(Core::ICore::instance()->mainWindow());
401
402
403
404
405
406
            }
        }
    }

    return changes.keys();
}