basefilefind.cpp 12.8 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) 2010 Nokia Corporation and/or its subsidiary(-ies).
con's avatar
con committed
6
**
7
** Contact: Nokia Corporation (qt-info@nokia.com)
con's avatar
con committed
8
**
9
** Commercial Usage
10
**
11
12
13
14
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
15
**
16
** GNU Lesser General Public License Usage
17
**
18
19
20
21
22
23
** 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.
24
**
25
** If you are unsure which license is appropriate for your use, please
hjk's avatar
hjk committed
26
** contact the sales department at http://qt.nokia.com/contact.
con's avatar
con committed
27
**
28
**************************************************************************/
hjk's avatar
hjk committed
29

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

32
#include <coreplugin/icore.h>
33
#include <coreplugin/progressmanager/progressmanager.h>
34
#include <coreplugin/progressmanager/futureprogress.h>
con's avatar
con committed
35
#include <coreplugin/editormanager/editormanager.h>
36
#include <coreplugin/filemanager.h>
con's avatar
con committed
37
#include <find/textfindconstants.h>
38
#include <find/searchresultwindow.h>
con's avatar
con committed
39
40
#include <texteditor/itexteditor.h>
#include <texteditor/basetexteditor.h>
41
#include <utils/stylehelper.h>
con's avatar
con committed
42

43
#include <QtCore/QDebug>
con's avatar
con committed
44
#include <QtCore/QDirIterator>
45
#include <QtCore/QSettings>
46
#include <QtGui/QFileDialog>
47
#include <QtGui/QCheckBox>
48
49
#include <QtGui/QComboBox>
#include <QtGui/QLabel>
con's avatar
con committed
50
#include <QtGui/QPushButton>
51
#include <QtGui/QTextBlock>
con's avatar
con committed
52

53
using namespace Utils;
con's avatar
con committed
54
55
56
using namespace Find;
using namespace TextEditor;

57
58
BaseFileFind::BaseFileFind(SearchResultWindow *resultWindow)
  : m_resultWindow(resultWindow),
con's avatar
con committed
59
60
    m_isSearching(false),
    m_resultLabel(0),
61
    m_filterCombo(0)
con's avatar
con committed
62
63
64
65
66
67
68
69
70
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()));
}

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

QStringList BaseFileFind::fileNameFilters() const
{
    QStringList filters;
    if (m_filterCombo && !m_filterCombo->currentText().isEmpty()) {
77
        const QStringList parts = m_filterCombo->currentText().split(QLatin1Char(','));
con's avatar
con committed
78
        foreach (const QString &part, parts) {
79
            const QString filter = part.trimmed();
con's avatar
con committed
80
81
82
83
84
85
86
87
            if (!filter.isEmpty()) {
                filters << filter;
            }
        }
    }
    return filters;
}

88
void BaseFileFind::findAll(const QString &txt, Find::FindFlags findFlags)
con's avatar
con committed
89
90
91
{
    m_isSearching = true;
    emit changed();
con's avatar
con committed
92
    if (m_filterCombo)
93
        updateComboEntries(m_filterCombo, true);
94
    m_watcher.setFuture(QFuture<FileSearchResultList>());
95
96
    SearchResult *result = m_resultWindow->startNewSearch();
    connect(result, SIGNAL(activated(Find::SearchResultItem)), this, SLOT(openEditor(Find::SearchResultItem)));
con's avatar
con committed
97
    m_resultWindow->popup(true);
98
    if (findFlags & Find::FindRegularExpression) {
99
100
101
102
103
104
        m_watcher.setFuture(Utils::findInFilesRegExp(txt, files(),
            textDocumentFlagsForFindFlags(findFlags), ITextEditor::openedTextEditorsContents()));
    } else {
        m_watcher.setFuture(Utils::findInFiles(txt, files(),
            textDocumentFlagsForFindFlags(findFlags), ITextEditor::openedTextEditorsContents()));
    }
105
    Core::FutureProgress *progress =
106
        Core::ICore::instance()->progressManager()->addTask(m_watcher.future(),
con's avatar
con committed
107
                                                                        "Search",
108
                                                                        Constants::TASK_SEARCH);
con's avatar
con committed
109
110
111
112
    progress->setWidget(createProgressWidget());
    connect(progress, SIGNAL(clicked()), m_resultWindow, SLOT(popup()));
}

113
void BaseFileFind::replaceAll(const QString &txt, Find::FindFlags findFlags)
114
115
116
117
{
    m_isSearching = true;
    emit changed();
    if (m_filterCombo)
118
        updateComboEntries(m_filterCombo, true);
119
    m_watcher.setFuture(QFuture<FileSearchResultList>());
120
121
122
123
124
    SearchResult *result = m_resultWindow->startNewSearch(SearchResultWindow::SearchAndReplace);
    connect(result, SIGNAL(activated(Find::SearchResultItem)), this, SLOT(openEditor(Find::SearchResultItem)));
    connect(result, SIGNAL(replaceButtonClicked(QString,QList<Find::SearchResultItem>)),
            this, SLOT(doReplace(QString,QList<Find::SearchResultItem>)));
    m_resultWindow->popup(true);
125
    if (findFlags & Find::FindRegularExpression) {
126
127
128
129
130
131
        m_watcher.setFuture(Utils::findInFilesRegExp(txt, files(),
            textDocumentFlagsForFindFlags(findFlags), ITextEditor::openedTextEditorsContents()));
    } else {
        m_watcher.setFuture(Utils::findInFiles(txt, files(),
            textDocumentFlagsForFindFlags(findFlags), ITextEditor::openedTextEditorsContents()));
    }
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
    Core::FutureProgress *progress =
        Core::ICore::instance()->progressManager()->addTask(m_watcher.future(),
                                                                        "Search",
                                                                        Constants::TASK_SEARCH);
    progress->setWidget(createProgressWidget());
    connect(progress, SIGNAL(clicked()), m_resultWindow, SLOT(popup()));
}

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
151
void BaseFileFind::displayResult(int index) {
152
153
154
155
156
157
158
159
160
161
162
163
164
    Utils::FileSearchResultList results = m_watcher.future().resultAt(index);
    QList<Find::SearchResultItem> items; // this conversion is stupid...
    foreach (const Utils::FileSearchResult &result, results) {
        Find::SearchResultItem item;
        item.fileName = result.fileName;
        item.lineNumber = result.lineNumber;
        item.lineText = result.matchingLine;
        item.searchTermLength = result.matchLength;
        item.searchTermStart = result.matchStart;
        item.userData = result.regexpCapturedTexts;
        items << item;
    }
    m_resultWindow->addResults(items);
con's avatar
con committed
165
166
167
168
169
170
    if (m_resultLabel)
        m_resultLabel->setText(tr("%1 found").arg(m_resultWindow->numberOfResults()));
}

void BaseFileFind::searchFinished()
{
171
    m_resultWindow->finishSearch();
con's avatar
con committed
172
173
174
175
176
177
178
179
    m_isSearching = false;
    m_resultLabel = 0;
    emit changed();
}

QWidget *BaseFileFind::createProgressWidget()
{
    m_resultLabel = new QLabel;
180
    m_resultLabel->setAlignment(Qt::AlignCenter);
con's avatar
con committed
181
182
183
184
185
186
187
188
189
190
191
192
193
194
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
    // ### 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
223
224
    if (m_filterCombo)
        syncComboWithSettings(m_filterCombo, m_filterSetting);
con's avatar
con committed
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
}

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

251
void BaseFileFind::openEditor(const Find::SearchResultItem &item)
con's avatar
con committed
252
{
253
    TextEditor::BaseTextEditor::openEditorAt(item.fileName, item.lineNumber, item.searchTermStart);
con's avatar
con committed
254
}
255

con's avatar
con committed
256
// #pragma mark Static methods
257
258
259

static void applyChanges(QTextDocument *doc, const QString &text, const QList<Find::SearchResultItem> &items)
{
260
    QList<QPair<QTextCursor, QString> > changes;
261
262
263
264
265
266
267
268

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

        const int cursorPosition = tc.position() + item.searchTermStart;

        int cursorIndex = 0;
269
270
        for (; cursorIndex < changes.size(); ++cursorIndex) {
            const QTextCursor &otherTc = changes.at(cursorIndex).first;
271

272
            if (otherTc.position() == cursorPosition)
273
274
275
                break;
        }

276
        if (cursorIndex != changes.size())
277
278
279
280
281
            continue; // skip this change.

        tc.setPosition(cursorPosition);
        tc.setPosition(tc.position() + item.searchTermLength,
                       QTextCursor::KeepAnchor);
282
283
284
285
286
287
        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));
288
289
    }

290
291
292
293
    for (int i = 0; i < changes.size(); ++i) {
        QPair<QTextCursor, QString> &cursor = changes[i];
        cursor.first.insertText(cursor.second);
    }
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
}

QStringList BaseFileFind::replaceAll(const QString &text,
                               const QList<Find::SearchResultItem> &items)
{
    if (text.isEmpty() || items.isEmpty())
        return QStringList();

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

    foreach (const Find::SearchResultItem &item, items)
        changes[item.fileName].append(item);

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

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

        const QString fileName = it.key();
314
        const QList<Find::SearchResultItem> changeItems = it.value();
315
316
317
318
319
320
321
322
323
324
325
326

        const QList<Core::IEditor *> editors = editorManager->editorsForFileName(fileName);
        TextEditor::BaseTextEditor *textEditor = 0;
        foreach (Core::IEditor *editor, editors) {
            textEditor = qobject_cast<TextEditor::BaseTextEditor *>(editor->widget());
            if (textEditor != 0)
                break;
        }

        if (textEditor != 0) {
            QTextCursor tc = textEditor->textCursor();
            tc.beginEditBlock();
327
            applyChanges(textEditor->document(), text, changeItems);
328
329
330
331
332
333
334
335
336
337
338
339
340
            tc.endEditBlock();
        } else {
            QFile file(fileName);

            if (file.open(QFile::ReadOnly)) {
                QTextStream stream(&file);
                // ### set the encoding
                const QString plainText = stream.readAll();
                file.close();

                QTextDocument doc;
                doc.setPlainText(plainText);

341
                applyChanges(&doc, text, changeItems);
342
343
344
345
346
347
348
349
350
351
352
353
354

                QFile newFile(fileName);
                if (newFile.open(QFile::WriteOnly)) {
                    QTextStream stream(&newFile);
                    // ### set the encoding
                    stream << doc.toPlainText();
                }
            }
        }
    }

    return changes.keys();
}