1 /**************************************************************************
3 ** This file is part of Qt Creator
5 ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
7 ** Contact: Nokia Corporation (info@qt.nokia.com)
10 ** GNU Lesser General Public License Usage
12 ** This file may be used under the terms of the GNU Lesser General Public
13 ** License version 2.1 as published by the Free Software Foundation and
14 ** appearing in the file LICENSE.LGPL included in the packaging of this file.
15 ** Please review the following information to ensure the GNU Lesser General
16 ** Public License version 2.1 requirements will be met:
17 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
19 ** In addition, as a special exception, Nokia gives you certain additional
20 ** rights. These rights are described in the Nokia Qt LGPL Exception
21 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
25 ** Alternatively, this file may be used in accordance with the terms and
26 ** conditions contained in a signed written agreement between you and Nokia.
28 ** If you have questions regarding the use of this file, please contact
29 ** Nokia at qt-info@nokia.com.
31 **************************************************************************/
33 #include "cppfindreferences.h"
34 #include "cpptoolsconstants.h"
36 #include <texteditor/basetexteditor.h>
37 #include <texteditor/basefilefind.h>
38 #include <find/searchresultwindow.h>
39 #include <extensionsystem/pluginmanager.h>
40 #include <utils/filesearch.h>
41 #include <coreplugin/progressmanager/progressmanager.h>
42 #include <coreplugin/progressmanager/futureprogress.h>
43 #include <coreplugin/editormanager/editormanager.h>
44 #include <coreplugin/icore.h>
46 #include <ASTVisitor.h>
50 #include <TranslationUnit.h>
55 #include <cplusplus/ModelManagerInterface.h>
56 #include <cplusplus/CppDocument.h>
57 #include <cplusplus/Overview.h>
58 #include <cplusplus/FindUsages.h>
60 #include <QtCore/QTime>
61 #include <QtCore/QTimer>
62 #include <QtCore/QtConcurrentRun>
63 #include <QtCore/QtConcurrentMap>
64 #include <QtCore/QDir>
65 #include <QtGui/QApplication>
66 #include <qtconcurrent/runextensions.h>
70 using namespace CppTools::Internal;
71 using namespace CPlusPlus;
73 static QString getSource(const QString &fileName,
74 const CppModelManagerInterface::WorkingCopy &workingCopy)
76 if (workingCopy.contains(fileName)) {
77 return workingCopy.source(fileName);
80 if (! file.open(QFile::ReadOnly))
83 return QTextStream(&file).readAll(); // ### FIXME
89 class ProcessFile: public std::unary_function<QString, QList<Usage> >
91 const CppModelManagerInterface::WorkingCopy workingCopy;
92 const Snapshot snapshot;
93 Document::Ptr symbolDocument;
97 ProcessFile(const CppModelManagerInterface::WorkingCopy &workingCopy,
98 const Snapshot snapshot,
99 Document::Ptr symbolDocument,
101 : workingCopy(workingCopy), snapshot(snapshot), symbolDocument(symbolDocument), symbol(symbol)
104 QList<Usage> operator()(const QString &fileName)
107 const Identifier *symbolId = symbol->identifier();
109 if (Document::Ptr previousDoc = snapshot.document(fileName)) {
110 Control *control = previousDoc->control();
111 if (! control->findIdentifier(symbolId->chars(), symbolId->size()))
112 return usages; // skip this document, it's not using symbolId.
117 const QString unpreprocessedSource = getSource(fileName, workingCopy);
119 if (symbolDocument && fileName == symbolDocument->fileName())
120 doc = symbolDocument;
122 source = snapshot.preprocessedCode(unpreprocessedSource, fileName);
123 doc = snapshot.documentFromSource(source, fileName);
127 Control *control = doc->control();
128 if (control->findIdentifier(symbolId->chars(), symbolId->size()) != 0) {
129 if (doc != symbolDocument)
132 FindUsages process(unpreprocessedSource.toUtf8(), doc, snapshot);
135 usages = process.usages();
142 class UpdateUI: public std::binary_function<QList<Usage> &, QList<Usage>, void>
144 QFutureInterface<Usage> *future;
147 UpdateUI(QFutureInterface<Usage> *future): future(future) {}
149 void operator()(QList<Usage> &, const QList<Usage> &usages)
151 foreach (const Usage &u, usages)
152 future->reportResult(u);
154 future->setProgressValue(future->progressValue() + 1);
158 } // end of anonymous namespace
160 CppFindReferences::CppFindReferences(CppModelManagerInterface *modelManager)
161 : QObject(modelManager),
162 _modelManager(modelManager),
163 _resultWindow(Find::SearchResultWindow::instance())
165 m_watcher.setPendingResultsLimit(1);
166 connect(&m_watcher, SIGNAL(resultsReadyAt(int,int)), this, SLOT(displayResults(int,int)));
167 connect(&m_watcher, SIGNAL(finished()), this, SLOT(searchFinished()));
170 CppFindReferences::~CppFindReferences()
174 QList<int> CppFindReferences::references(Symbol *symbol, const LookupContext &context) const
176 QList<int> references;
178 FindUsages findUsages(context);
180 references = findUsages.references();
185 static void find_helper(QFutureInterface<Usage> &future,
186 const CppModelManagerInterface::WorkingCopy workingCopy,
187 const LookupContext context,
188 CppFindReferences *findRefs,
191 const Identifier *symbolId = symbol->identifier();
192 Q_ASSERT(symbolId != 0);
194 const Snapshot snapshot = context.snapshot();
196 const QString sourceFile = QString::fromUtf8(symbol->fileName(), symbol->fileNameLength());
197 QStringList files(sourceFile);
199 if (symbol->isClass() || symbol->isForwardClassDeclaration() || (symbol->enclosingScope() && ! symbol->isStatic() &&
200 symbol->enclosingScope()->isNamespace())) {
201 foreach (const Document::Ptr &doc, context.snapshot()) {
202 if (doc->fileName() == sourceFile)
205 Control *control = doc->control();
207 if (control->findIdentifier(symbolId->chars(), symbolId->size()))
208 files.append(doc->fileName());
211 DependencyTable dependencyTable = findRefs->updateDependencyTable(snapshot);
212 files += dependencyTable.filesDependingOn(sourceFile);
214 files.removeDuplicates();
216 future.setProgressRange(0, files.size());
218 ProcessFile process(workingCopy, snapshot, context.thisDocument(), symbol);
219 UpdateUI reduce(&future);
221 QtConcurrent::blockingMappedReduced<QList<Usage> > (files, process, reduce);
223 future.setProgressValue(files.size());
226 void CppFindReferences::findUsages(CPlusPlus::Symbol *symbol, const CPlusPlus::LookupContext &context)
228 Find::SearchResult *search = _resultWindow->startNewSearch(Find::SearchResultWindow::SearchOnly);
230 connect(search, SIGNAL(activated(Find::SearchResultItem)),
231 this, SLOT(openEditor(Find::SearchResultItem)));
233 findAll_helper(symbol, context);
236 void CppFindReferences::renameUsages(CPlusPlus::Symbol *symbol, const CPlusPlus::LookupContext &context,
237 const QString &replacement)
239 if (const Identifier *id = symbol->identifier()) {
240 const QString textToReplace = replacement.isEmpty()
241 ? QString::fromUtf8(id->chars(), id->size()) : replacement;
243 Find::SearchResult *search = _resultWindow->startNewSearch(Find::SearchResultWindow::SearchAndReplace);
244 _resultWindow->setTextToReplace(textToReplace);
246 connect(search, SIGNAL(activated(Find::SearchResultItem)),
247 this, SLOT(openEditor(Find::SearchResultItem)));
249 connect(search, SIGNAL(replaceButtonClicked(QString,QList<Find::SearchResultItem>)),
250 SLOT(onReplaceButtonClicked(QString,QList<Find::SearchResultItem>)));
252 findAll_helper(symbol, context);
256 void CppFindReferences::findAll_helper(Symbol *symbol, const LookupContext &context)
258 if (! (symbol && symbol->identifier()))
261 _resultWindow->popup(true);
263 const CppModelManagerInterface::WorkingCopy workingCopy = _modelManager->workingCopy();
265 Core::ProgressManager *progressManager = Core::ICore::instance()->progressManager();
267 QFuture<Usage> result;
269 result = QtConcurrent::run(&find_helper, workingCopy, context, this, symbol);
270 m_watcher.setFuture(result);
272 Core::FutureProgress *progress = progressManager->addTask(result, tr("Searching"),
273 CppTools::Constants::TASK_SEARCH);
275 connect(progress, SIGNAL(clicked()), _resultWindow, SLOT(popup()));
278 void CppFindReferences::onReplaceButtonClicked(const QString &text,
279 const QList<Find::SearchResultItem> &items)
281 Core::EditorManager::instance()->hideEditorInfoBar(QLatin1String("CppEditor.Rename"));
283 const QStringList fileNames = TextEditor::BaseFileFind::replaceAll(text, items);
284 if (!fileNames.isEmpty()) {
285 _modelManager->updateSourceFiles(fileNames);
286 _resultWindow->hide();
290 void CppFindReferences::displayResults(int first, int last)
292 for (int index = first; index != last; ++index) {
293 Usage result = m_watcher.future().resultAt(index);
294 _resultWindow->addResult(result.path,
302 void CppFindReferences::searchFinished()
304 _resultWindow->finishSearch();
308 void CppFindReferences::openEditor(const Find::SearchResultItem &item)
310 if (item.path.size() > 0) {
311 TextEditor::BaseTextEditorWidget::openEditorAt(item.path.first(), item.lineNumber, item.textMarkPos,
313 Core::EditorManager::ModeSwitch);
315 Core::EditorManager::instance()->openEditor(item.text, QString(), Core::EditorManager::ModeSwitch);
322 class FindMacroUsesInFile: public std::unary_function<QString, QList<Usage> >
324 const CppModelManagerInterface::WorkingCopy workingCopy;
325 const Snapshot snapshot;
329 FindMacroUsesInFile(const CppModelManagerInterface::WorkingCopy &workingCopy,
330 const Snapshot snapshot,
332 : workingCopy(workingCopy), snapshot(snapshot), macro(macro)
335 QList<Usage> operator()(const QString &fileName)
339 const Document::Ptr &doc = snapshot.document(fileName);
342 foreach (const Document::MacroUse &use, doc->macroUses()) {
343 const Macro &useMacro = use.macro();
344 if (useMacro.line() == macro.line()
345 && useMacro.fileName() == macro.fileName())
347 if (source.isEmpty())
348 source = getSource(fileName, workingCopy).toLatin1(); // ### FIXME: Encoding?
351 const QString &lineSource = matchingLine(use.begin(), source, &lineStart);
352 usages.append(Usage(fileName, lineSource, use.beginLine(),
353 use.begin() - lineStart, use.length()));
360 // ### FIXME: Pretty close to FindUsages::matchingLine.
361 static QString matchingLine(unsigned position, const QByteArray &source,
362 unsigned *lineStart = 0)
364 const char *beg = source.constData();
365 const char *start = beg + position;
366 for (; start != beg - 1; --start) {
373 const char *end = start + 1;
374 for (; *end; ++end) {
380 *lineStart = start - beg;
382 // ### FIXME: Encoding?
383 const QString matchingLine = QString::fromUtf8(start, end - start);
388 } // end of anonymous namespace
390 static void findMacroUses_helper(QFutureInterface<Usage> &future,
391 const CppModelManagerInterface::WorkingCopy workingCopy,
392 const Snapshot snapshot,
393 CppFindReferences *findRefs,
396 // ensure the dependency table is updated
397 DependencyTable dependencies = findRefs->updateDependencyTable(snapshot);
399 const QString& sourceFile = macro.fileName();
400 QStringList files(sourceFile);
401 files += dependencies.filesDependingOn(sourceFile);
402 files.removeDuplicates();
404 future.setProgressRange(0, files.size());
406 FindMacroUsesInFile process(workingCopy, snapshot, macro);
407 UpdateUI reduce(&future);
408 QtConcurrent::blockingMappedReduced<QList<Usage> > (files, process, reduce);
410 future.setProgressValue(files.size());
413 void CppFindReferences::findMacroUses(const Macro ¯o)
415 Find::SearchResult *search = _resultWindow->startNewSearch(Find::SearchResultWindow::SearchOnly);
417 _resultWindow->popup(true);
419 connect(search, SIGNAL(activated(Find::SearchResultItem)),
420 this, SLOT(openEditor(Find::SearchResultItem)));
422 const Snapshot snapshot = _modelManager->snapshot();
423 const CppModelManagerInterface::WorkingCopy workingCopy = _modelManager->workingCopy();
425 // add the macro definition itself
427 // ### FIXME: Encoding?
428 const QByteArray &source = getSource(macro.fileName(), workingCopy).toLatin1();
429 _resultWindow->addResult(macro.fileName(), macro.line(),
430 source.mid(macro.offset(), macro.length()), 0, macro.length());
433 QFuture<Usage> result;
434 result = QtConcurrent::run(&findMacroUses_helper, workingCopy, snapshot, this, macro);
435 m_watcher.setFuture(result);
437 Core::ProgressManager *progressManager = Core::ICore::instance()->progressManager();
438 Core::FutureProgress *progress = progressManager->addTask(result, tr("Searching"),
439 CppTools::Constants::TASK_SEARCH);
440 connect(progress, SIGNAL(clicked()), _resultWindow, SLOT(popup()));
443 DependencyTable CppFindReferences::updateDependencyTable(CPlusPlus::Snapshot snapshot)
445 DependencyTable oldDeps = dependencyTable();
446 if (oldDeps.isValidFor(snapshot))
449 DependencyTable newDeps;
450 newDeps.build(snapshot);
451 setDependencyTable(newDeps);
455 DependencyTable CppFindReferences::dependencyTable() const
457 QMutexLocker locker(&m_depsLock);
462 void CppFindReferences::setDependencyTable(const CPlusPlus::DependencyTable &newTable)
464 QMutexLocker locker(&m_depsLock);