basefilefind.cpp 13.6 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
    m_isSearching(false),
    m_resultLabel(0),
    m_filterCombo(0),
    m_useRegExp(false),
    m_useRegExpCheckBox(0)
{
    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()) {
79
        const QStringList parts = m_filterCombo->currentText().split(QLatin1Char(','));
con's avatar
con committed
80
        foreach (const QString &part, parts) {
81
            const QString filter = part.trimmed();
con's avatar
con committed
82
83
84
85
86
87
88
89
90
91
92
93
            if (!filter.isEmpty()) {
                filters << filter;
            }
        }
    }
    return filters;
}

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

112
113
114
115
116
void BaseFileFind::replaceAll(const QString &txt, QTextDocument::FindFlags findFlags)
{
    m_isSearching = true;
    emit changed();
    if (m_filterCombo)
117
        updateComboEntries(m_filterCombo, true);
118
    m_watcher.setFuture(QFuture<FileSearchResultList>());
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
    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);
    if (m_useRegExp)
        m_watcher.setFuture(Utils::findInFilesRegExp(txt, files(), findFlags, ITextEditor::openedTextEditorsContents()));
    else
        m_watcher.setFuture(Utils::findInFiles(txt, files(), findFlags, ITextEditor::openedTextEditorsContents()));
    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
147
void BaseFileFind::displayResult(int index) {
148
149
150
151
152
153
154
155
156
157
158
159
160
    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
161
162
163
164
165
166
    if (m_resultLabel)
        m_resultLabel->setText(tr("%1 found").arg(m_resultWindow->numberOfResults()));
}

void BaseFileFind::searchFinished()
{
167
    m_resultWindow->finishSearch();
con's avatar
con committed
168
169
170
171
172
173
174
175
    m_isSearching = false;
    m_resultLabel = 0;
    emit changed();
}

QWidget *BaseFileFind::createProgressWidget()
{
    m_resultLabel = new QLabel;
176
    m_resultLabel->setAlignment(Qt::AlignCenter);
con's avatar
con committed
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
    // ### 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()
{
/*
    QWidget *widget = new QWidget;
    QHBoxLayout *hlayout = new QHBoxLayout(widget);
    hlayout->setMargin(0);
    widget->setLayout(hlayout);
*/
    QString filterToolTip = tr("List of comma separated wildcard filters");
/*
197
    QLabel *label = new QLabel(tr("File &pattern:"));
con's avatar
con committed
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
    label->setToolTip(filterToolTip);
*/
/*
    hlayout->addWidget(label);
*/
    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);
/*
214
    label->setBuddy(m_filterCombo);
con's avatar
con committed
215
216
217
218
219
220
221
    hlayout->addWidget(m_filterCombo);
*/
    return m_filterCombo;
}

QWidget *BaseFileFind::createRegExpWidget()
{
222
    m_useRegExpCheckBox = new QCheckBox(tr("Use regular e&xpressions"));
con's avatar
con committed
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
    m_useRegExpCheckBox->setChecked(m_useRegExp);
    connect(m_useRegExpCheckBox, SIGNAL(toggled(bool)), this, SLOT(syncRegExpSetting(bool)));
    return m_useRegExpCheckBox;
}

void BaseFileFind::writeCommonSettings(QSettings *settings)
{
    settings->setValue("filters", m_filterStrings.stringList());
    if (m_filterCombo)
        settings->setValue("currentFilter", m_filterCombo->currentText());
    settings->setValue("useRegExp", m_useRegExp);
}

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

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

void BaseFileFind::syncRegExpSetting(bool useRegExp)
{
    m_useRegExp = useRegExp;
}

281
void BaseFileFind::openEditor(const Find::SearchResultItem &item)
con's avatar
con committed
282
{
283
    TextEditor::BaseTextEditor::openEditorAt(item.fileName, item.lineNumber, item.searchTermStart);
con's avatar
con committed
284
}
285

con's avatar
con committed
286
// #pragma mark Static methods
287
288
289

static void applyChanges(QTextDocument *doc, const QString &text, const QList<Find::SearchResultItem> &items)
{
290
    QList<QPair<QTextCursor, QString> > changes;
291
292
293
294
295
296
297
298

    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;
299
300
        for (; cursorIndex < changes.size(); ++cursorIndex) {
            const QTextCursor &otherTc = changes.at(cursorIndex).first;
301

302
            if (otherTc.position() == cursorPosition)
303
304
305
                break;
        }

306
        if (cursorIndex != changes.size())
307
308
309
310
311
            continue; // skip this change.

        tc.setPosition(cursorPosition);
        tc.setPosition(tc.position() + item.searchTermLength,
                       QTextCursor::KeepAnchor);
312
313
314
315
316
317
        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));
318
319
    }

320
321
322
323
    for (int i = 0; i < changes.size(); ++i) {
        QPair<QTextCursor, QString> &cursor = changes[i];
        cursor.first.insertText(cursor.second);
    }
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
}

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();
344
        const QList<Find::SearchResultItem> changeItems = it.value();
345
346
347
348
349
350
351
352
353
354
355
356

        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();
357
            applyChanges(textEditor->document(), text, changeItems);
358
359
360
361
362
363
364
365
366
367
368
369
370
            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);

371
                applyChanges(&doc, text, changeItems);
372
373
374
375
376
377
378
379
380
381
382
383
384

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

    return changes.keys();
}