CppEditor: FilePathify some of the refactoring operations

... and adjust surrounding code.

Change-Id: I1d36e5a0c6ba14a1d9b8fd59340f1bb2a1e45ad1
Reviewed-by: Christian Kandeler <christian.kandeler@qt.io>
This commit is contained in:
hjk
2022-11-24 17:00:52 +01:00
parent edd0e97ce1
commit e42d24fca9
18 changed files with 221 additions and 233 deletions

View File

@@ -52,6 +52,7 @@
using namespace CppEditor; using namespace CppEditor;
using namespace LanguageClient; using namespace LanguageClient;
using namespace Utils;
namespace ClangCodeModel { namespace ClangCodeModel {
namespace Internal { namespace Internal {
@@ -337,12 +338,11 @@ void ClangModelManagerSupport::findUsages(const CppEditor::CursorInEditor &curso
CppModelManager::findUsages(cursor, CppModelManager::Backend::Builtin); CppModelManager::findUsages(cursor, CppModelManager::Backend::Builtin);
} }
void ClangModelManagerSupport::switchHeaderSource(const Utils::FilePath &filePath, bool inNextSplit) void ClangModelManagerSupport::switchHeaderSource(const FilePath &filePath, bool inNextSplit)
{ {
if (ClangdClient * const client = clientForFile(filePath)) { if (ClangdClient * const client = clientForFile(filePath)) {
// The fast, synchronous approach works most of the time, so let's try that one first. // The fast, synchronous approach works most of the time, so let's try that one first.
const auto otherFile = Utils::FilePath::fromString( const FilePath otherFile = correspondingHeaderOrSource(filePath);
correspondingHeaderOrSource(filePath.toString()));
if (!otherFile.isEmpty()) if (!otherFile.isEmpty())
openEditor(otherFile, inNextSplit); openEditor(otherFile, inNextSplit);
else else

View File

@@ -31,7 +31,9 @@
#include <QMessageBox> #include <QMessageBox>
using namespace ProjectExplorer; using namespace ProjectExplorer;
using namespace CMakeProjectManager::Internal; using namespace Utils;
namespace CMakeProjectManager::Internal {
CMakeManager::CMakeManager() CMakeManager::CMakeManager()
: m_runCMakeAction(new QAction(QIcon(), Tr::tr("Run CMake"), this)) : m_runCMakeAction(new QAction(QIcon(), Tr::tr("Run CMake"), this))
@@ -218,12 +220,12 @@ void CMakeManager::buildFile(Node *node)
CMakeTargetNode *targetNode = dynamic_cast<CMakeTargetNode *>(fileNode->parentProjectNode()); CMakeTargetNode *targetNode = dynamic_cast<CMakeTargetNode *>(fileNode->parentProjectNode());
if (!targetNode) if (!targetNode)
return; return;
Utils::FilePath filePath = fileNode->filePath(); FilePath filePath = fileNode->filePath();
if (filePath.fileName().contains(".h")) { if (filePath.fileName().contains(".h")) {
bool wasHeader = false; bool wasHeader = false;
const QString sourceFile = CppEditor::correspondingHeaderOrSource(filePath.toString(), &wasHeader); const FilePath sourceFile = CppEditor::correspondingHeaderOrSource(filePath, &wasHeader);
if (wasHeader && !sourceFile.isEmpty()) if (wasHeader && !sourceFile.isEmpty())
filePath = Utils::FilePath::fromString(sourceFile); filePath = sourceFile;
} }
Target *target = project->activeTarget(); Target *target = project->activeTarget();
QTC_ASSERT(target, return); QTC_ASSERT(target, return);
@@ -252,3 +254,5 @@ void CMakeManager::buildFileContextMenu()
if (Node *node = ProjectTree::currentNode()) if (Node *node = ProjectTree::currentNode())
buildFile(node); buildFile(node);
} }
} // CMakeProjectManager::Internal

View File

@@ -26,6 +26,7 @@
using namespace Core; using namespace Core;
using namespace TextEditor; using namespace TextEditor;
using namespace Utils;
namespace CppEditor::Internal { namespace CppEditor::Internal {
namespace { namespace {
@@ -54,7 +55,7 @@ private:
tip += evaluator.diagnosis(); tip += evaluator.diagnosis();
setPriority(Priority_Diagnostic); setPriority(Priority_Diagnostic);
} }
const Utils::FilePath filePath = editorWidget->textDocument()->filePath(); const FilePath filePath = editorWidget->textDocument()->filePath();
const QStringList fallback = identifierWordsUnderCursor(tc); const QStringList fallback = identifierWordsUnderCursor(tc);
if (evaluator.identifiedCppElement()) { if (evaluator.identifiedCppElement()) {
const QSharedPointer<CppElement> &cppElement = evaluator.cppElement(); const QSharedPointer<CppElement> &cppElement = evaluator.cppElement();
@@ -187,11 +188,10 @@ void BuiltinModelManagerSupport::findUsages(const CursorInEditor &data) const
} }
} }
void BuiltinModelManagerSupport::switchHeaderSource(const Utils::FilePath &filePath, void BuiltinModelManagerSupport::switchHeaderSource(const FilePath &filePath,
bool inNextSplit) bool inNextSplit)
{ {
const auto otherFile = Utils::FilePath::fromString( const FilePath otherFile = correspondingHeaderOrSource(filePath);
correspondingHeaderOrSource(filePath.toString()));
if (!otherFile.isEmpty()) if (!otherFile.isEmpty())
openEditor(otherFile, inNextSplit); openEditor(otherFile, inNextSplit);
} }

View File

@@ -352,7 +352,7 @@ void CodegenTest::testDefinitionEmptyClass()
QList<InsertionLocation> locList = find.methodDefinition(decl); QList<InsertionLocation> locList = find.methodDefinition(decl);
QVERIFY(locList.size() == 1); QVERIFY(locList.size() == 1);
InsertionLocation loc = locList.first(); InsertionLocation loc = locList.first();
QCOMPARE(loc.fileName(), sourceDocument->filePath().toString()); QCOMPARE(loc.filePath(), sourceDocument->filePath());
QCOMPARE(loc.prefix(), QLatin1String("\n\n")); QCOMPARE(loc.prefix(), QLatin1String("\n\n"));
QCOMPARE(loc.suffix(), QString()); QCOMPARE(loc.suffix(), QString());
QCOMPARE(loc.line(), 3); QCOMPARE(loc.line(), 3);
@@ -410,7 +410,7 @@ void CodegenTest::testDefinitionFirstMember()
QList<InsertionLocation> locList = find.methodDefinition(decl); QList<InsertionLocation> locList = find.methodDefinition(decl);
QVERIFY(locList.size() == 1); QVERIFY(locList.size() == 1);
InsertionLocation loc = locList.first(); InsertionLocation loc = locList.first();
QCOMPARE(loc.fileName(), sourceDocument->filePath().toString()); QCOMPARE(loc.filePath(), sourceDocument->filePath());
QCOMPARE(loc.line(), 4); QCOMPARE(loc.line(), 4);
QCOMPARE(loc.column(), 1); QCOMPARE(loc.column(), 1);
QCOMPARE(loc.suffix(), QLatin1String("\n\n")); QCOMPARE(loc.suffix(), QLatin1String("\n\n"));
@@ -469,7 +469,7 @@ void CodegenTest::testDefinitionLastMember()
QList<InsertionLocation> locList = find.methodDefinition(decl); QList<InsertionLocation> locList = find.methodDefinition(decl);
QVERIFY(locList.size() == 1); QVERIFY(locList.size() == 1);
InsertionLocation loc = locList.first(); InsertionLocation loc = locList.first();
QCOMPARE(loc.fileName(), sourceDocument->filePath().toString()); QCOMPARE(loc.filePath(), sourceDocument->filePath());
QCOMPARE(loc.line(), 7); QCOMPARE(loc.line(), 7);
QCOMPARE(loc.column(), 2); QCOMPARE(loc.column(), 2);
QCOMPARE(loc.prefix(), QLatin1String("\n\n")); QCOMPARE(loc.prefix(), QLatin1String("\n\n"));
@@ -535,7 +535,7 @@ void CodegenTest::testDefinitionMiddleMember()
QList<InsertionLocation> locList = find.methodDefinition(decl); QList<InsertionLocation> locList = find.methodDefinition(decl);
QVERIFY(locList.size() == 1); QVERIFY(locList.size() == 1);
InsertionLocation loc = locList.first(); InsertionLocation loc = locList.first();
QCOMPARE(loc.fileName(), sourceDocument->filePath().toString()); QCOMPARE(loc.filePath(), sourceDocument->filePath());
QCOMPARE(loc.line(), 7); QCOMPARE(loc.line(), 7);
QCOMPARE(loc.column(), 2); QCOMPARE(loc.column(), 2);
QCOMPARE(loc.prefix(), QLatin1String("\n\n")); QCOMPARE(loc.prefix(), QLatin1String("\n\n"));
@@ -595,7 +595,7 @@ void CodegenTest::testDefinitionMiddleMemberSurroundedByUndefined()
QList<InsertionLocation> locList = find.methodDefinition(decl); QList<InsertionLocation> locList = find.methodDefinition(decl);
QVERIFY(locList.size() == 1); QVERIFY(locList.size() == 1);
InsertionLocation loc = locList.first(); InsertionLocation loc = locList.first();
QCOMPARE(loc.fileName(), sourceDocument->filePath().toString()); QCOMPARE(loc.filePath(), sourceDocument->filePath());
QCOMPARE(loc.line(), 4); QCOMPARE(loc.line(), 4);
QCOMPARE(loc.column(), 1); QCOMPARE(loc.column(), 1);
QCOMPARE(loc.prefix(), QString()); QCOMPARE(loc.prefix(), QString());
@@ -656,14 +656,14 @@ void CodegenTest::testDefinitionMemberSpecificFile()
CppRefactoringChanges changes(snapshot); CppRefactoringChanges changes(snapshot);
InsertionPointLocator find(changes); InsertionPointLocator find(changes);
QList<InsertionLocation> locList = QList<InsertionLocation> locList =
find.methodDefinition(decl, true, sourceDocument->filePath().toString()); find.methodDefinition(decl, true, sourceDocument->filePath());
QVERIFY(locList.size() == 1); QVERIFY(locList.size() == 1);
InsertionLocation loc = locList.first(); InsertionLocation loc = locList.first();
QCOMPARE(loc.fileName(), sourceDocument->filePath().toString()); QCOMPARE(loc.filePath(), sourceDocument->filePath());
QCOMPARE(loc.line(), 7); QCOMPARE(loc.line(), 7);
QCOMPARE(loc.column(), 2); QCOMPARE(loc.column(), 2);
QCOMPARE(loc.prefix(), QLatin1String("\n\n")); QCOMPARE(loc.prefix(), QLatin1String("\n\n"));
QCOMPARE(loc.suffix(), QString()); QCOMPARE(loc.suffix(), QString());
} }
} // namespace CppEditor::Internal } // CppEditor::Internal

View File

@@ -768,7 +768,7 @@ static int commonFilePathLength(const QString &s1, const QString &s2)
return length; return length;
} }
static QString correspondingHeaderOrSourceInProject(const QFileInfo &fileInfo, static FilePath correspondingHeaderOrSourceInProject(const QFileInfo &fileInfo,
const QStringList &candidateFileNames, const QStringList &candidateFileNames,
const Project *project, const Project *project,
CacheUsage cacheUsage) CacheUsage cacheUsage)
@@ -789,36 +789,37 @@ static QString correspondingHeaderOrSourceInProject(const QFileInfo &fileInfo,
} }
if (!bestFileName.isEmpty()) { if (!bestFileName.isEmpty()) {
const QFileInfo candidateFi(bestFileName); const QFileInfo candidateFi(bestFileName);
QTC_ASSERT(candidateFi.isFile(), return QString()); QTC_ASSERT(candidateFi.isFile(), return {});
if (cacheUsage == CacheUsage::ReadWrite) { if (cacheUsage == CacheUsage::ReadWrite) {
m_headerSourceMapping[fileInfo.absoluteFilePath()] = candidateFi.absoluteFilePath(); m_headerSourceMapping[fileInfo.absoluteFilePath()] = candidateFi.absoluteFilePath();
m_headerSourceMapping[candidateFi.absoluteFilePath()] = fileInfo.absoluteFilePath(); m_headerSourceMapping[candidateFi.absoluteFilePath()] = fileInfo.absoluteFilePath();
} }
return candidateFi.absoluteFilePath(); return FilePath::fromString(candidateFi.absoluteFilePath());
} }
return QString(); return {};
} }
} // namespace Internal } // namespace Internal
using namespace Internal; using namespace Internal;
QString correspondingHeaderOrSource(const QString &fileName, bool *wasHeader, CacheUsage cacheUsage) FilePath correspondingHeaderOrSource(const FilePath &filePath, bool *wasHeader, CacheUsage cacheUsage)
{ {
const QString fileName = filePath.toString();
const QFileInfo fi(fileName); const QFileInfo fi(fileName);
ProjectFile::Kind kind = ProjectFile::classify(fileName); ProjectFile::Kind kind = ProjectFile::classify(fileName);
const bool isHeader = ProjectFile::isHeader(kind); const bool isHeader = ProjectFile::isHeader(kind);
if (wasHeader) if (wasHeader)
*wasHeader = isHeader; *wasHeader = isHeader;
if (m_headerSourceMapping.contains(fi.absoluteFilePath())) if (m_headerSourceMapping.contains(fi.absoluteFilePath()))
return m_headerSourceMapping.value(fi.absoluteFilePath()); return FilePath::fromString(m_headerSourceMapping.value(fi.absoluteFilePath()));
if (debug) if (debug)
qDebug() << Q_FUNC_INFO << fileName << kind; qDebug() << Q_FUNC_INFO << fileName << kind;
if (kind == ProjectFile::Unsupported) if (kind == ProjectFile::Unsupported)
return QString(); return {};
const QString baseName = fi.completeBaseName(); const QString baseName = fi.completeBaseName();
const QString privateHeaderSuffix = QLatin1String("_p"); const QString privateHeaderSuffix = QLatin1String("_p");
@@ -858,7 +859,7 @@ QString correspondingHeaderOrSource(const QString &fileName, bool *wasHeader, Ca
if (!isHeader || !baseName.endsWith(privateHeaderSuffix)) if (!isHeader || !baseName.endsWith(privateHeaderSuffix))
m_headerSourceMapping[candidateFi.absoluteFilePath()] = fi.absoluteFilePath(); m_headerSourceMapping[candidateFi.absoluteFilePath()] = fi.absoluteFilePath();
} }
return candidateFi.absoluteFilePath(); return FilePath::fromString(candidateFi.absoluteFilePath());
} }
} }
} }
@@ -866,7 +867,7 @@ QString correspondingHeaderOrSource(const QString &fileName, bool *wasHeader, Ca
// Find files in the current project // Find files in the current project
Project *currentProject = ProjectTree::currentProject(); Project *currentProject = ProjectTree::currentProject();
if (currentProject) { if (currentProject) {
const QString path = correspondingHeaderOrSourceInProject(fi, candidateFileNames, const FilePath path = correspondingHeaderOrSourceInProject(fi, candidateFileNames,
currentProject, cacheUsage); currentProject, cacheUsage);
if (!path.isEmpty()) if (!path.isEmpty())
return path; return path;
@@ -880,14 +881,14 @@ QString correspondingHeaderOrSource(const QString &fileName, bool *wasHeader, Ca
if (project == currentProject) if (project == currentProject)
continue; // We have already checked the current project. continue; // We have already checked the current project.
const QString path = correspondingHeaderOrSourceInProject(fi, candidateFileNames, const FilePath path = correspondingHeaderOrSourceInProject(fi, candidateFileNames,
project, cacheUsage); project, cacheUsage);
if (!path.isEmpty()) if (!path.isEmpty())
return path; return path;
} }
} }
return QString(); return {};
} }
} // namespace CppEditor } // namespace CppEditor

View File

@@ -683,8 +683,7 @@ void FollowSymbolUnderCursor::findLink(
for (const LookupItem &r : resolvedSymbols) { for (const LookupItem &r : resolvedSymbols) {
if (Symbol *d = r.declaration()) { if (Symbol *d = r.declaration()) {
if (d->asDeclaration() || d->asFunction()) { if (d->asDeclaration() || d->asFunction()) {
const QString fileName = QString::fromUtf8(d->fileName(), d->fileNameLength()); if (data.filePath() == d->filePath()) {
if (data.filePath().toString() == fileName) {
if (line == d->line() && positionInBlock >= d->column()) { if (line == d->line() && positionInBlock >= d->column()) {
// TODO: check the end // TODO: check the end
result = r; // take the symbol under cursor. result = r; // take the symbol under cursor.

View File

@@ -147,10 +147,7 @@ static QSharedPointer<FunctionDeclDefLink> findLinkHelper(QSharedPointer<Functio
return noResult; return noResult;
// parse the target file to get the linked decl/def // parse the target file to get the linked decl/def
const QString targetFileName = QString::fromUtf8( CppRefactoringFileConstPtr targetFile = changes.fileNoEditor(target->filePath());
target->fileName(), target->fileNameLength());
CppRefactoringFileConstPtr targetFile = changes.fileNoEditor(
Utils::FilePath::fromString(targetFileName));
if (!targetFile->isValid()) if (!targetFile->isValid())
return noResult; return noResult;

View File

@@ -14,10 +14,13 @@
#include <QDir> #include <QDir>
#include <QtTest> #include <QtTest>
using namespace Utils;
static inline QString _(const QByteArray &ba) { return QString::fromLatin1(ba, ba.size()); } static inline QString _(const QByteArray &ba) { return QString::fromLatin1(ba, ba.size()); }
static void createTempFile(const QString &fileName) static void createTempFile(const FilePath &filePath)
{ {
QString fileName = filePath.toString();
QFile file(fileName); QFile file(fileName);
QDir(QFileInfo(fileName).absolutePath()).mkpath(_(".")); QDir(QFileInfo(fileName).absolutePath()).mkpath(_("."));
file.open(QFile::WriteOnly); file.open(QFile::WriteOnly);
@@ -40,8 +43,8 @@ void HeaderSourceTest::test()
QVERIFY(temporaryDir.isValid()); QVERIFY(temporaryDir.isValid());
const QDir path = QDir(temporaryDir.path() + QLatin1Char('/') + _(QTest::currentDataTag())); const QDir path = QDir(temporaryDir.path() + QLatin1Char('/') + _(QTest::currentDataTag()));
const QString sourcePath = path.absoluteFilePath(sourceFileName); const FilePath sourcePath = FilePath::fromString(path.absoluteFilePath(sourceFileName));
const QString headerPath = path.absoluteFilePath(headerFileName); const FilePath headerPath = FilePath::fromString(path.absoluteFilePath(headerFileName));
createTempFile(sourcePath); createTempFile(sourcePath);
createTempFile(headerPath); createTempFile(headerPath);

View File

@@ -46,6 +46,7 @@
using namespace CPlusPlus; using namespace CPlusPlus;
using namespace TextEditor; using namespace TextEditor;
using namespace Utils;
namespace CppEditor { namespace CppEditor {
namespace Internal { namespace Internal {
@@ -703,8 +704,8 @@ public:
return; return;
bool isHeaderFile = false; bool isHeaderFile = false;
m_cppFileName = correspondingHeaderOrSource(interface.filePath().toString(), &isHeaderFile); m_cppFilePath = correspondingHeaderOrSource(interface.filePath(), &isHeaderFile);
m_factory->setHasImplementationFile(isHeaderFile && !m_cppFileName.isEmpty()); m_factory->setHasImplementationFile(isHeaderFile && !m_cppFilePath.isEmpty());
m_valid = true; m_valid = true;
} }
@@ -881,8 +882,7 @@ public:
if (!clazz) if (!clazz)
return; return;
CppRefactoringFilePtr implementationFile = refactoring.file( CppRefactoringFilePtr implementationFile = refactoring.file(m_cppFilePath);
Utils::FilePath::fromString(m_cppFileName));
Utils::ChangeSet implementationChangeSet; Utils::ChangeSet implementationChangeSet;
const int insertPos = qMax(0, implementationFile->document()->characterCount() - 1); const int insertPos = qMax(0, implementationFile->document()->characterCount() - 1);
@@ -932,7 +932,7 @@ private:
InsertVirtualMethodsDialog *m_factory = nullptr; InsertVirtualMethodsDialog *m_factory = nullptr;
const ClassSpecifierAST *m_classAST = nullptr; const ClassSpecifierAST *m_classAST = nullptr;
bool m_valid = false; bool m_valid = false;
QString m_cppFileName; FilePath m_cppFilePath;
int m_insertPosDecl = 0; int m_insertPosDecl = 0;
int m_insertPosOutside = 0; int m_insertPosOutside = 0;
unsigned m_functionCount = 0; unsigned m_functionCount = 0;

View File

@@ -1726,17 +1726,17 @@ void CppModelManager::onAboutToLoadSession()
GC(); GC();
} }
QSet<QString> CppModelManager::dependingInternalTargets(const Utils::FilePath &file) const QSet<QString> CppModelManager::dependingInternalTargets(const FilePath &file) const
{ {
QSet<QString> result; QSet<QString> result;
const Snapshot snapshot = this->snapshot(); const Snapshot snapshot = this->snapshot();
QTC_ASSERT(snapshot.contains(file), return result); QTC_ASSERT(snapshot.contains(file), return result);
bool wasHeader; bool wasHeader;
const QString correspondingFile const FilePath correspondingFile
= correspondingHeaderOrSource(file.toString(), &wasHeader, CacheUsage::ReadOnly); = correspondingHeaderOrSource(file, &wasHeader, CacheUsage::ReadOnly);
const Utils::FilePaths dependingFiles = snapshot.filesDependingOn( const FilePaths dependingFiles = snapshot.filesDependingOn(
wasHeader ? file : Utils::FilePath::fromString(correspondingFile)); wasHeader ? file : correspondingFile);
for (const Utils::FilePath &fn : std::as_const(dependingFiles)) { for (const FilePath &fn : std::as_const(dependingFiles)) {
for (const ProjectPart::ConstPtr &part : projectPart(fn)) for (const ProjectPart::ConstPtr &part : projectPart(fn))
result.insert(part->buildSystemTarget); result.insert(part->buildSystemTarget);
} }

View File

@@ -5,19 +5,17 @@
#include "baseeditordocumentprocessor.h" #include "baseeditordocumentprocessor.h"
#include "cppcodestylesettings.h" #include "cppcodestylesettings.h"
#include "cppeditorconstants.h"
#include "cppeditordocument.h" #include "cppeditordocument.h"
#include "cppeditorwidget.h" #include "cppeditorwidget.h"
#include "cppfunctiondecldeflink.h" #include "cppfunctiondecldeflink.h"
#include "cppinsertvirtualmethods.h" #include "cppinsertvirtualmethods.h"
#include "cpplocatorfilter.h"
#include "cpppointerdeclarationformatter.h" #include "cpppointerdeclarationformatter.h"
#include "cppquickfixassistant.h" #include "cppquickfixassistant.h"
#include "cppquickfixprojectsettings.h" #include "cppquickfixprojectsettings.h"
#include "cpprefactoringchanges.h" #include "cpprefactoringchanges.h"
#include "cpptoolsreuse.h" #include "cpptoolsreuse.h"
#include "cppvirtualfunctionassistprovider.h"
#include "includeutils.h" #include "includeutils.h"
#include "indexitem.h"
#include "insertionpointlocator.h" #include "insertionpointlocator.h"
#include "symbolfinder.h" #include "symbolfinder.h"
@@ -103,9 +101,9 @@ const QList<CppQuickFixFactory *> &CppQuickFixFactory::cppQuickFixFactories()
namespace Internal { namespace Internal {
QString inlinePrefix(const QString &targetFile, const std::function<bool()> &extraCondition = {}) QString inlinePrefix(const FilePath &targetFile, const std::function<bool()> &extraCondition = {})
{ {
if (ProjectFile::isHeader(ProjectFile::classify(targetFile)) if (ProjectFile::isHeader(ProjectFile::classify(targetFile.path()))
&& (!extraCondition || extraCondition())) { && (!extraCondition || extraCondition())) {
return "inline "; return "inline ";
} }
@@ -2527,10 +2525,10 @@ class InsertDeclOperation: public CppQuickFixOperation
{ {
public: public:
InsertDeclOperation(const CppQuickFixInterface &interface, InsertDeclOperation(const CppQuickFixInterface &interface,
const QString &targetFileName, const Class *targetSymbol, const FilePath &targetFilePath, const Class *targetSymbol,
InsertionPointLocator::AccessSpec xsSpec, const QString &decl, int priority) InsertionPointLocator::AccessSpec xsSpec, const QString &decl, int priority)
: CppQuickFixOperation(interface, priority) : CppQuickFixOperation(interface, priority)
, m_targetFileName(FilePath::fromString(targetFileName)) , m_targetFilePath(targetFilePath)
, m_targetSymbol(targetSymbol) , m_targetSymbol(targetSymbol)
, m_xsSpec(xsSpec) , m_xsSpec(xsSpec)
, m_decl(decl) , m_decl(decl)
@@ -2546,10 +2544,10 @@ public:
InsertionPointLocator locator(refactoring); InsertionPointLocator locator(refactoring);
const InsertionLocation loc = locator.methodDeclarationInClass( const InsertionLocation loc = locator.methodDeclarationInClass(
m_targetFileName, m_targetSymbol, m_xsSpec); m_targetFilePath, m_targetSymbol, m_xsSpec);
QTC_ASSERT(loc.isValid(), return); QTC_ASSERT(loc.isValid(), return);
CppRefactoringFilePtr targetFile = refactoring.file(m_targetFileName); CppRefactoringFilePtr targetFile = refactoring.file(m_targetFilePath);
int targetPosition1 = targetFile->position(loc.line(), loc.column()); int targetPosition1 = targetFile->position(loc.line(), loc.column());
int targetPosition2 = qMax(0, targetFile->position(loc.line(), 1) - 1); int targetPosition2 = qMax(0, targetFile->position(loc.line(), 1) - 1);
@@ -2564,7 +2562,7 @@ public:
static QString generateDeclaration(const Function *function); static QString generateDeclaration(const Function *function);
private: private:
FilePath m_targetFileName; FilePath m_targetFilePath;
const Class *m_targetSymbol; const Class *m_targetSymbol;
InsertionPointLocator::AccessSpec m_xsSpec; InsertionPointLocator::AccessSpec m_xsSpec;
QString m_decl; QString m_decl;
@@ -2573,22 +2571,22 @@ private:
class DeclOperationFactory class DeclOperationFactory
{ {
public: public:
DeclOperationFactory(const CppQuickFixInterface &interface, const QString &fileName, DeclOperationFactory(const CppQuickFixInterface &interface, const FilePath &filePath,
const Class *matchingClass, const QString &decl) const Class *matchingClass, const QString &decl)
: m_interface(interface) : m_interface(interface)
, m_fileName(fileName) , m_filePath(filePath)
, m_matchingClass(matchingClass) , m_matchingClass(matchingClass)
, m_decl(decl) , m_decl(decl)
{} {}
QuickFixOperation *operator()(InsertionPointLocator::AccessSpec xsSpec, int priority) QuickFixOperation *operator()(InsertionPointLocator::AccessSpec xsSpec, int priority)
{ {
return new InsertDeclOperation(m_interface, m_fileName, m_matchingClass, xsSpec, m_decl, priority); return new InsertDeclOperation(m_interface, m_filePath, m_matchingClass, xsSpec, m_decl, priority);
} }
private: private:
const CppQuickFixInterface &m_interface; const CppQuickFixInterface &m_interface;
const QString &m_fileName; const FilePath &m_filePath;
const Class *m_matchingClass; const Class *m_matchingClass;
const QString &m_decl; const QString &m_decl;
}; };
@@ -2646,8 +2644,7 @@ void InsertDeclFromDef::match(const CppQuickFixInterface &interface, QuickFixOpe
return; return;
} }
} }
QString fileName = QString::fromUtf8(matchingClass->fileName(), const FilePath fileName = matchingClass->filePath();
matchingClass->fileNameLength());
const QString decl = InsertDeclOperation::generateDeclaration(fun); const QString decl = InsertDeclOperation::generateDeclaration(fun);
// Add several possible insertion locations for declaration // Add several possible insertion locations for declaration
@@ -2685,23 +2682,23 @@ public:
// Make sure that either loc is valid or targetFileName is not empty. // Make sure that either loc is valid or targetFileName is not empty.
InsertDefOperation(const CppQuickFixInterface &interface, InsertDefOperation(const CppQuickFixInterface &interface,
Declaration *decl, DeclaratorAST *declAST, const InsertionLocation &loc, Declaration *decl, DeclaratorAST *declAST, const InsertionLocation &loc,
const DefPos defpos, const QString &targetFileName = QString(), const DefPos defpos, const FilePath &targetFileName = {},
bool freeFunction = false) bool freeFunction = false)
: CppQuickFixOperation(interface, 0) : CppQuickFixOperation(interface, 0)
, m_decl(decl) , m_decl(decl)
, m_declAST(declAST) , m_declAST(declAST)
, m_loc(loc) , m_loc(loc)
, m_defpos(defpos) , m_defpos(defpos)
, m_targetFileName(targetFileName) , m_targetFilePath(targetFileName)
{ {
if (m_defpos == DefPosImplementationFile) { if (m_defpos == DefPosImplementationFile) {
const QString declFile = QString::fromUtf8(decl->fileName(), decl->fileNameLength()); const FilePath declFile = decl->filePath();
const QDir dir = QFileInfo(declFile).dir(); const FilePath targetFile = m_loc.isValid() ? m_loc.filePath() : m_targetFilePath;
const FilePath resolved = targetFile.relativePathFrom(declFile.parentDir());
setPriority(2); setPriority(2);
setDescription(QCoreApplication::translate("CppEditor::InsertDefOperation", setDescription(QCoreApplication::translate("CppEditor::InsertDefOperation",
"Add Definition in %1") "Add Definition in %1")
.arg(dir.relativeFilePath(m_loc.isValid() ? m_loc.fileName() .arg(resolved.displayName()));
: m_targetFileName)));
} else if (freeFunction) { } else if (freeFunction) {
setDescription(QCoreApplication::translate("CppEditor::InsertDefOperation", setDescription(QCoreApplication::translate("CppEditor::InsertDefOperation",
"Add Definition Here")); "Add Definition Here"));
@@ -2721,7 +2718,7 @@ public:
DefPos defPos, DefPos defPos,
DeclaratorAST *declAST, DeclaratorAST *declAST,
Declaration *decl, Declaration *decl,
const QString &targetFilePath, const FilePath &targetFilePath,
ChangeSet *changeSet = nullptr, ChangeSet *changeSet = nullptr,
QList<ChangeSet::Range> *indentRanges = nullptr) QList<ChangeSet::Range> *indentRanges = nullptr)
{ {
@@ -2731,8 +2728,7 @@ public:
refactoring, targetFilePath); refactoring, targetFilePath);
QTC_ASSERT(loc.isValid(), return); QTC_ASSERT(loc.isValid(), return);
CppRefactoringFilePtr targetFile = refactoring.file( CppRefactoringFilePtr targetFile = refactoring.file(loc.filePath());
Utils::FilePath::fromString(loc.fileName()));
Overview oo = CppCodeStyleSettings::currentProjectCodeStyleOverview(); Overview oo = CppCodeStyleSettings::currentProjectCodeStyleOverview();
oo.showFunctionSignatures = true; oo.showFunctionSignatures = true;
oo.showReturnTypes = true; oo.showReturnTypes = true;
@@ -2846,14 +2842,14 @@ public:
private: private:
void perform() override void perform() override
{ {
insertDefinition(this, m_loc, m_defpos, m_declAST, m_decl, m_targetFileName); insertDefinition(this, m_loc, m_defpos, m_declAST, m_decl, m_targetFilePath);
} }
Declaration *m_decl; Declaration *m_decl;
DeclaratorAST *m_declAST; DeclaratorAST *m_declAST;
InsertionLocation m_loc; InsertionLocation m_loc;
const DefPos m_defpos; const DefPos m_defpos;
const QString m_targetFileName; const FilePath m_targetFilePath;
}; };
} // anonymous namespace } // anonymous namespace
@@ -2894,14 +2890,13 @@ void InsertDefFromDecl::match(const CppQuickFixInterface &interface, QuickFixOpe
// location, because insertLocationForMethodDefinition() should // location, because insertLocationForMethodDefinition() should
// be used in perform() to get consistent insert positions. // be used in perform() to get consistent insert positions.
for (const InsertionLocation &location : for (const InsertionLocation &location :
locator.methodDefinition(decl, false, QString())) { locator.methodDefinition(decl, false, {})) {
if (!location.isValid()) if (!location.isValid())
continue; continue;
const QString fileName = location.fileName(); const FilePath filePath = location.filePath();
if (ProjectFile::isHeader(ProjectFile::classify(fileName))) { if (ProjectFile::isHeader(ProjectFile::classify(filePath.path()))) {
const QString source const FilePath source = correspondingHeaderOrSource(filePath);
= correspondingHeaderOrSource(fileName);
if (!source.isEmpty()) { if (!source.isEmpty()) {
op = new InsertDefOperation(interface, decl, declAST, op = new InsertDefOperation(interface, decl, declAST,
InsertionLocation(), InsertionLocation(),
@@ -2912,7 +2907,7 @@ void InsertDefFromDecl::match(const CppQuickFixInterface &interface, QuickFixOpe
op = new InsertDefOperation(interface, decl, declAST, op = new InsertDefOperation(interface, decl, declAST,
InsertionLocation(), InsertionLocation(),
DefPosImplementationFile, DefPosImplementationFile,
fileName); filePath);
} }
if (op) if (op)
@@ -2929,7 +2924,7 @@ void InsertDefFromDecl::match(const CppQuickFixInterface &interface, QuickFixOpe
result << new InsertDefOperation(interface, decl, declAST, result << new InsertDefOperation(interface, decl, declAST,
InsertionLocation(), InsertionLocation(),
DefPosOutsideClass, DefPosOutsideClass,
interface.filePath().toString()); interface.filePath());
} }
// Insert Position: Inside Class // Insert Position: Inside Class
@@ -2938,10 +2933,10 @@ void InsertDefFromDecl::match(const CppQuickFixInterface &interface, QuickFixOpe
const CppRefactoringFilePtr file = interface.currentFile(); const CppRefactoringFilePtr file = interface.currentFile();
file->lineAndColumn(file->endOf(simpleDecl), &line, &column); file->lineAndColumn(file->endOf(simpleDecl), &line, &column);
const InsertionLocation loc const InsertionLocation loc
= InsertionLocation(interface.filePath().toString(), QString(), = InsertionLocation(interface.filePath(), QString(),
QString(), line, column); QString(), line, column);
result << new InsertDefOperation(interface, decl, declAST, loc, result << new InsertDefOperation(interface, decl, declAST, loc,
DefPosInsideClass, QString(), DefPosInsideClass, FilePath(),
isFreeFunction); isFreeFunction);
return; return;
@@ -3229,20 +3224,20 @@ private:
CppRefactoringChanges refactoring(snapshot()); CppRefactoringChanges refactoring(snapshot());
const bool isHeaderFile = ProjectFile::isHeader(ProjectFile::classify(filePath().toString())); const bool isHeaderFile = ProjectFile::isHeader(ProjectFile::classify(filePath().toString()));
QString cppFile; // Only set if the class is defined in a header file. FilePath cppFile; // Only set if the class is defined in a header file.
if (isHeaderFile) { if (isHeaderFile) {
InsertionPointLocator locator(refactoring); InsertionPointLocator locator(refactoring);
for (const InsertionLocation &location for (const InsertionLocation &location
: locator.methodDefinition(unimplemented.first(), false, {})) { : locator.methodDefinition(unimplemented.first(), false, {})) {
if (!location.isValid()) if (!location.isValid())
continue; continue;
const QString fileName = location.fileName(); const FilePath filePath = location.filePath();
if (ProjectFile::isHeader(ProjectFile::classify(fileName))) { if (ProjectFile::isHeader(ProjectFile::classify(filePath.path()))) {
const QString source = correspondingHeaderOrSource(fileName); const FilePath source = correspondingHeaderOrSource(filePath);
if (!source.isEmpty()) if (!source.isEmpty())
cppFile = source; cppFile = source;
} else { } else {
cppFile = fileName; cppFile = filePath;
} }
break; break;
} }
@@ -3251,7 +3246,7 @@ private:
MemberFunctionImplSettings settings; MemberFunctionImplSettings settings;
switch (m_mode) { switch (m_mode) {
case InsertDefsFromDecls::Mode::User: { case InsertDefsFromDecls::Mode::User: {
AddImplementationsDialog dlg(unimplemented, Utils::FilePath::fromString(cppFile)); AddImplementationsDialog dlg(unimplemented, cppFile);
if (dlg.exec() == QDialog::Accepted) if (dlg.exec() == QDialog::Accepted)
settings = dlg.settings(); settings = dlg.settings();
break; break;
@@ -3301,19 +3296,19 @@ private:
SimpleDeclarationAST *m_decl = nullptr; SimpleDeclarationAST *m_decl = nullptr;
}; };
QHash<QString, QPair<ChangeSet, QList<ChangeSet::Range>>> changeSets; QHash<FilePath, QPair<ChangeSet, QList<ChangeSet::Range>>> changeSets;
for (const MemberFunctionImplSetting &setting : std::as_const(settings)) { for (const MemberFunctionImplSetting &setting : std::as_const(settings)) {
DeclFinder finder(currentFile().data(), setting.func); DeclFinder finder(currentFile().data(), setting.func);
finder.accept(m_classAST); finder.accept(m_classAST);
QTC_ASSERT(finder.decl(), continue); QTC_ASSERT(finder.decl(), continue);
InsertionLocation loc; InsertionLocation loc;
const QString targetFilePath = setting.defPos == DefPosImplementationFile const FilePath targetFilePath = setting.defPos == DefPosImplementationFile
? cppFile : filePath().toString(); ? cppFile : filePath();
QTC_ASSERT(!targetFilePath.isEmpty(), continue); QTC_ASSERT(!targetFilePath.isEmpty(), continue);
if (setting.defPos == DefPosInsideClass) { if (setting.defPos == DefPosInsideClass) {
int line, column; int line, column;
currentFile()->lineAndColumn(currentFile()->endOf(finder.decl()), &line, &column); currentFile()->lineAndColumn(currentFile()->endOf(finder.decl()), &line, &column);
loc = InsertionLocation(filePath().toString(), QString(), QString(), line, column); loc = InsertionLocation(filePath(), QString(), QString(), line, column);
} }
auto &changeSet = changeSets[targetFilePath]; auto &changeSet = changeSets[targetFilePath];
InsertDefOperation::insertDefinition( InsertDefOperation::insertDefinition(
@@ -3322,8 +3317,7 @@ private:
&changeSet.first, &changeSet.second); &changeSet.first, &changeSet.second);
} }
for (auto it = changeSets.cbegin(); it != changeSets.cend(); ++it) { for (auto it = changeSets.cbegin(); it != changeSets.cend(); ++it) {
const CppRefactoringFilePtr file = refactoring.file( const CppRefactoringFilePtr file = refactoring.file(it.key());
Utils::FilePath::fromString(it.key()));
for (const ChangeSet::Range &r : it.value().second) for (const ChangeSet::Range &r : it.value().second)
file->appendIndentRange(r); file->appendIndentRange(r);
file->setChangeSet(it.value().first); file->setChangeSet(it.value().first);
@@ -3444,19 +3438,19 @@ class GetterSetterRefactoringHelper
{ {
public: public:
GetterSetterRefactoringHelper(CppQuickFixOperation *operation, GetterSetterRefactoringHelper(CppQuickFixOperation *operation,
const QString &fileName, const FilePath &filePath,
Class *clazz) Class *clazz)
: m_operation(operation) : m_operation(operation)
, m_changes(m_operation->snapshot()) , m_changes(m_operation->snapshot())
, m_locator(m_changes) , m_locator(m_changes)
, m_headerFile(m_changes.file(Utils::FilePath::fromString(fileName))) , m_headerFile(m_changes.file(filePath))
, m_sourceFile([&] { , m_sourceFile([&] {
QString cppFileName = correspondingHeaderOrSource(fileName, &m_isHeaderHeaderFile); FilePath cppFilePath = correspondingHeaderOrSource(filePath, &m_isHeaderHeaderFile);
if (!m_isHeaderHeaderFile || !QFile::exists(cppFileName)) { if (!m_isHeaderHeaderFile || !cppFilePath.exists()) {
// there is no "source" file // there is no "source" file
return m_headerFile; return m_headerFile;
} else { } else {
return m_changes.file(Utils::FilePath::fromString(cppFileName)); return m_changes.file(cppFilePath);
} }
}()) }())
, m_class(clazz) , m_class(clazz)
@@ -3649,7 +3643,7 @@ protected:
? NamespaceHandling::CreateMissing ? NamespaceHandling::CreateMissing
: NamespaceHandling::Ignore, : NamespaceHandling::Ignore,
m_changes, m_changes,
m_sourceFile->filePath().toString(), m_sourceFile->filePath(),
insertedNamespaces); insertedNamespaces);
if (m_settings->addUsingNamespaceinCppFile()) { if (m_settings->addUsingNamespaceinCppFile()) {
// check if we have to insert a using namespace ... // check if we have to insert a using namespace ...
@@ -3675,7 +3669,7 @@ protected:
ns.resize(ns.size() - 2); // remove last '::' ns.resize(ns.size() - 2); // remove last '::'
ns += ";\n"; ns += ";\n";
const auto &loc = m_sourceFileInsertionPoint; const auto &loc = m_sourceFileInsertionPoint;
m_sourceFileInsertionPoint = InsertionLocation(loc.fileName(), m_sourceFileInsertionPoint = InsertionLocation(loc.filePath(),
loc.prefix() + ns, loc.prefix() + ns,
loc.suffix(), loc.suffix(),
loc.line(), loc.line(),
@@ -3787,9 +3781,7 @@ public:
void perform() override void perform() override
{ {
GetterSetterRefactoringHelper helper(this, GetterSetterRefactoringHelper helper(this, currentFile()->filePath(), m_data.clazz);
currentFile()->filePath().toString(),
m_data.clazz);
helper.performGeneration(m_data, m_generateFlags); helper.performGeneration(m_data, m_generateFlags);
helper.applyChanges(); helper.applyChanges();
} }
@@ -3976,7 +3968,7 @@ void GetterSetterRefactoringHelper::performGeneration(ExistingGetterSetterData d
false, false,
NamespaceHandling::Ignore, NamespaceHandling::Ignore,
m_changes, m_changes,
m_headerFile->filePath().toString()); m_headerFile->filePath());
const FullySpecifiedType returnType = getReturnTypeAt(m_headerFile, loc); const FullySpecifiedType returnType = getReturnTypeAt(m_headerFile, loc);
const QString clazz = symbolAt(data.clazz, m_headerFile, loc); const QString clazz = symbolAt(data.clazz, m_headerFile, loc);
QString code = overview.prettyType(returnType, clazz + "::" + data.getterName) QString code = overview.prettyType(returnType, clazz + "::" + data.getterName)
@@ -4067,7 +4059,7 @@ void GetterSetterRefactoringHelper::performGeneration(ExistingGetterSetterData d
false, false,
NamespaceHandling::Ignore, NamespaceHandling::Ignore,
m_changes, m_changes,
m_headerFile->filePath().toString()); m_headerFile->filePath());
FullySpecifiedType newParameterType = typeAt(data.declarationSymbol->type(), FullySpecifiedType newParameterType = typeAt(data.declarationSymbol->type(),
data.clazz, data.clazz,
@@ -4141,7 +4133,7 @@ void GetterSetterRefactoringHelper::performGeneration(ExistingGetterSetterData d
false, false,
NamespaceHandling::Ignore, NamespaceHandling::Ignore,
m_changes, m_changes,
m_headerFile->filePath().toString()); m_headerFile->filePath());
const FullySpecifiedType type = typeAt(data.declarationSymbol->type(), const FullySpecifiedType type = typeAt(data.declarationSymbol->type(),
data.clazz, data.clazz,
m_headerFile, m_headerFile,
@@ -4722,7 +4714,7 @@ private:
if (m_candidates.empty()) if (m_candidates.empty())
return; return;
GetterSetterRefactoringHelper helper(this, GetterSetterRefactoringHelper helper(this,
currentFile()->filePath().toString(), currentFile()->filePath(),
m_candidates.front().data.clazz); m_candidates.front().data.clazz);
for (MemberInfo &mi : m_candidates) { for (MemberInfo &mi : m_candidates) {
if (mi.requestedFlags != 0) { if (mi.requestedFlags != 0) {
@@ -4907,7 +4899,7 @@ public:
} }
funcDef.append(QLatin1String("\n}\n\n")); funcDef.append(QLatin1String("\n}\n\n"));
funcDef.replace(QChar::ParagraphSeparator, QLatin1String("\n")); funcDef.replace(QChar::ParagraphSeparator, QLatin1String("\n"));
funcDef.prepend(inlinePrefix(currentFile->filePath().toString())); funcDef.prepend(inlinePrefix(currentFile->filePath()));
funcCall.append(QLatin1Char(';')); funcCall.append(QLatin1Char(';'));
// Get starting indentation from original code. // Get starting indentation from original code.
@@ -5447,7 +5439,6 @@ public:
{ {
FoundDeclaration result; FoundDeclaration result;
Function *func = ast->symbol; Function *func = ast->symbol;
QString declFileName;
if (Class *matchingClass = isMemberFunction(context(), func)) { if (Class *matchingClass = isMemberFunction(context(), func)) {
// Dealing with member functions // Dealing with member functions
const QualifiedNameId *qName = func->name()->asQualifiedNameId(); const QualifiedNameId *qName = func->name()->asQualifiedNameId();
@@ -5460,10 +5451,8 @@ public:
continue; continue;
} }
declFileName = QString::fromUtf8(matchingClass->fileName(), const FilePath declFilePath = matchingClass->filePath();
matchingClass->fileNameLength()); result.file = refactoring.file(declFilePath);
result.file = refactoring.file(Utils::FilePath::fromString(declFileName));
ASTPath astPath(result.file->cppDocument()); ASTPath astPath(result.file->cppDocument());
const QList<AST *> path = astPath(s->line(), s->column()); const QList<AST *> path = astPath(s->line(), s->column());
SimpleDeclarationAST *simpleDecl = nullptr; SimpleDeclarationAST *simpleDecl = nullptr;
@@ -5483,10 +5472,10 @@ public:
} else if (Namespace *matchingNamespace = isNamespaceFunction(context(), func)) { } else if (Namespace *matchingNamespace = isNamespaceFunction(context(), func)) {
// Dealing with free functions and inline member functions. // Dealing with free functions and inline member functions.
bool isHeaderFile; bool isHeaderFile;
declFileName = correspondingHeaderOrSource(filePath().toString(), &isHeaderFile); FilePath declFilePath = correspondingHeaderOrSource(filePath(), &isHeaderFile);
if (!QFile::exists(declFileName)) if (!declFilePath.exists())
return FoundDeclaration(); return FoundDeclaration();
result.file = refactoring.file(Utils::FilePath::fromString(declFileName)); result.file = refactoring.file(declFilePath);
if (!result.file) if (!result.file)
return FoundDeclaration(); return FoundDeclaration();
const LookupContext lc(result.file->cppDocument(), snapshot()); const LookupContext lc(result.file->cppDocument(), snapshot());
@@ -6295,12 +6284,11 @@ public:
}; };
MoveFuncDefRefactoringHelper(CppQuickFixOperation *operation, MoveType type, MoveFuncDefRefactoringHelper(CppQuickFixOperation *operation, MoveType type,
const QString &fromFile, const QString &toFile) const FilePath &fromFile, const FilePath &toFile)
: m_operation(operation), m_type(type), m_changes(m_operation->snapshot()) : m_operation(operation), m_type(type), m_changes(m_operation->snapshot())
{ {
m_fromFile = m_changes.file(Utils::FilePath::fromString(fromFile)); m_fromFile = m_changes.file(fromFile);
m_toFile = (m_type == MoveOutside) ? m_fromFile m_toFile = (m_type == MoveOutside) ? m_fromFile : m_changes.file(toFile);
: m_changes.file(Utils::FilePath::fromString(toFile));
} }
void performMove(FunctionDefinitionAST *funcAST) void performMove(FunctionDefinitionAST *funcAST)
@@ -6308,15 +6296,14 @@ public:
// Determine file, insert position and scope // Determine file, insert position and scope
InsertionLocation l = insertLocationForMethodDefinition( InsertionLocation l = insertLocationForMethodDefinition(
funcAST->symbol, false, NamespaceHandling::Ignore, funcAST->symbol, false, NamespaceHandling::Ignore,
m_changes, m_toFile->filePath().toString()); m_changes, m_toFile->filePath());
const QString prefix = l.prefix(); const QString prefix = l.prefix();
const QString suffix = l.suffix(); const QString suffix = l.suffix();
const int insertPos = m_toFile->position(l.line(), l.column()); const int insertPos = m_toFile->position(l.line(), l.column());
Scope *scopeAtInsertPos = m_toFile->cppDocument()->scopeAt(l.line(), l.column()); Scope *scopeAtInsertPos = m_toFile->cppDocument()->scopeAt(l.line(), l.column());
// construct definition // construct definition
const QString funcDec = inlinePrefix( const QString funcDec = inlinePrefix(m_toFile->filePath(), [this] { return m_type == MoveOutside; })
m_toFile->filePath().toString(), [this] { return m_type == MoveOutside; })
+ definitionSignature(m_operation, funcAST, m_fromFile, m_toFile, + definitionSignature(m_operation, funcAST, m_fromFile, m_toFile,
scopeAtInsertPos); scopeAtInsertPos);
QString funcDef = prefix + funcDec; QString funcDef = prefix + funcDec;
@@ -6372,28 +6359,27 @@ class MoveFuncDefOutsideOp : public CppQuickFixOperation
public: public:
MoveFuncDefOutsideOp(const CppQuickFixInterface &interface, MoveFuncDefOutsideOp(const CppQuickFixInterface &interface,
MoveFuncDefRefactoringHelper::MoveType type, MoveFuncDefRefactoringHelper::MoveType type,
FunctionDefinitionAST *funcDef, const QString &cppFileName) FunctionDefinitionAST *funcDef, const FilePath &cppFilePath)
: CppQuickFixOperation(interface, 0) : CppQuickFixOperation(interface, 0)
, m_funcDef(funcDef) , m_funcDef(funcDef)
, m_type(type) , m_type(type)
, m_cppFileName(cppFileName) , m_cppFilePath(cppFilePath)
, m_headerFileName(QString::fromUtf8(funcDef->symbol->fileName(), , m_headerFilePath(funcDef->symbol->filePath())
funcDef->symbol->fileNameLength()))
{ {
if (m_type == MoveFuncDefRefactoringHelper::MoveOutside) { if (m_type == MoveFuncDefRefactoringHelper::MoveOutside) {
setDescription(QCoreApplication::translate("CppEditor::QuickFix", setDescription(QCoreApplication::translate("CppEditor::QuickFix",
"Move Definition Outside Class")); "Move Definition Outside Class"));
} else { } else {
const QDir dir = QFileInfo(m_headerFileName).dir(); const FilePath resolved = m_cppFilePath.relativePathFrom(m_headerFilePath.parentDir());
setDescription(QCoreApplication::translate("CppEditor::QuickFix", setDescription(QCoreApplication::translate("CppEditor::QuickFix",
"Move Definition to %1") "Move Definition to %1")
.arg(dir.relativeFilePath(m_cppFileName))); .arg(resolved.displayName()));
} }
} }
void perform() override void perform() override
{ {
MoveFuncDefRefactoringHelper helper(this, m_type, m_headerFileName, m_cppFileName); MoveFuncDefRefactoringHelper helper(this, m_type, m_headerFilePath, m_cppFilePath);
helper.performMove(m_funcDef); helper.performMove(m_funcDef);
helper.applyChanges(); helper.applyChanges();
} }
@@ -6401,8 +6387,8 @@ public:
private: private:
FunctionDefinitionAST *m_funcDef; FunctionDefinitionAST *m_funcDef;
MoveFuncDefRefactoringHelper::MoveType m_type; MoveFuncDefRefactoringHelper::MoveType m_type;
const QString m_cppFileName; const FilePath m_cppFilePath;
const QString m_headerFileName; const FilePath m_headerFilePath;
}; };
} // anonymous namespace } // anonymous namespace
@@ -6446,8 +6432,7 @@ void MoveFuncDefOutside::match(const CppQuickFixInterface &interface, QuickFixOp
return; return;
bool isHeaderFile = false; bool isHeaderFile = false;
const QString cppFileName = correspondingHeaderOrSource(interface.filePath().toString(), const FilePath cppFileName = correspondingHeaderOrSource(interface.filePath(), &isHeaderFile);
&isHeaderFile);
if (isHeaderFile && !cppFileName.isEmpty()) { if (isHeaderFile && !cppFileName.isEmpty()) {
const MoveFuncDefRefactoringHelper::MoveType type = moveOutsideMemberDefinition const MoveFuncDefRefactoringHelper::MoveType type = moveOutsideMemberDefinition
@@ -6458,7 +6443,7 @@ void MoveFuncDefOutside::match(const CppQuickFixInterface &interface, QuickFixOp
if (classAST) if (classAST)
result << new MoveFuncDefOutsideOp(interface, MoveFuncDefRefactoringHelper::MoveOutside, result << new MoveFuncDefOutsideOp(interface, MoveFuncDefRefactoringHelper::MoveOutside,
funcAST, QLatin1String("")); funcAST, FilePath());
return; return;
} }
@@ -6470,28 +6455,27 @@ class MoveAllFuncDefOutsideOp : public CppQuickFixOperation
public: public:
MoveAllFuncDefOutsideOp(const CppQuickFixInterface &interface, MoveAllFuncDefOutsideOp(const CppQuickFixInterface &interface,
MoveFuncDefRefactoringHelper::MoveType type, MoveFuncDefRefactoringHelper::MoveType type,
ClassSpecifierAST *classDef, const QString &cppFileName) ClassSpecifierAST *classDef, const FilePath &cppFileName)
: CppQuickFixOperation(interface, 0) : CppQuickFixOperation(interface, 0)
, m_type(type) , m_type(type)
, m_classDef(classDef) , m_classDef(classDef)
, m_cppFileName(cppFileName) , m_cppFilePath(cppFileName)
, m_headerFileName(QString::fromUtf8(classDef->symbol->fileName(), , m_headerFilePath(classDef->symbol->filePath())
classDef->symbol->fileNameLength()))
{ {
if (m_type == MoveFuncDefRefactoringHelper::MoveOutside) { if (m_type == MoveFuncDefRefactoringHelper::MoveOutside) {
setDescription(QCoreApplication::translate("CppEditor::QuickFix", "Move All Function " setDescription(QCoreApplication::translate("CppEditor::QuickFix", "Move All Function "
"Definitions Outside Class")); "Definitions Outside Class"));
} else { } else {
const QDir dir = QFileInfo(m_headerFileName).dir(); const FilePath resolved = m_cppFilePath.relativePathFrom(m_headerFilePath.parentDir());
setDescription(QCoreApplication::translate("CppEditor::QuickFix", setDescription(QCoreApplication::translate("CppEditor::QuickFix",
"Move All Function Definitions to %1") "Move All Function Definitions to %1")
.arg(dir.relativeFilePath(m_cppFileName))); .arg(resolved.displayName()));
} }
} }
void perform() override void perform() override
{ {
MoveFuncDefRefactoringHelper helper(this, m_type, m_headerFileName, m_cppFileName); MoveFuncDefRefactoringHelper helper(this, m_type, m_headerFilePath, m_cppFilePath);
for (DeclarationListAST *it = m_classDef->member_specifier_list; it; it = it->next) { for (DeclarationListAST *it = m_classDef->member_specifier_list; it; it = it->next) {
if (FunctionDefinitionAST *funcAST = it->value->asFunctionDefinition()) { if (FunctionDefinitionAST *funcAST = it->value->asFunctionDefinition()) {
if (funcAST->symbol && !funcAST->symbol->isGenerated()) if (funcAST->symbol && !funcAST->symbol->isGenerated())
@@ -6504,8 +6488,8 @@ public:
private: private:
MoveFuncDefRefactoringHelper::MoveType m_type; MoveFuncDefRefactoringHelper::MoveType m_type;
ClassSpecifierAST *m_classDef; ClassSpecifierAST *m_classDef;
const QString m_cppFileName; const FilePath m_cppFilePath;
const QString m_headerFileName; const FilePath m_headerFilePath;
}; };
} // anonymous namespace } // anonymous namespace
@@ -6530,15 +6514,14 @@ void MoveAllFuncDefOutside::match(const CppQuickFixInterface &interface, QuickFi
return; return;
bool isHeaderFile = false; bool isHeaderFile = false;
const QString cppFileName = correspondingHeaderOrSource(interface.filePath().toString(), const FilePath cppFileName = correspondingHeaderOrSource(interface.filePath(), &isHeaderFile);
&isHeaderFile);
if (isHeaderFile && !cppFileName.isEmpty()) { if (isHeaderFile && !cppFileName.isEmpty()) {
result << new MoveAllFuncDefOutsideOp(interface, result << new MoveAllFuncDefOutsideOp(interface,
MoveFuncDefRefactoringHelper::MoveToCppFile, MoveFuncDefRefactoringHelper::MoveToCppFile,
classAST, cppFileName); classAST, cppFileName);
} }
result << new MoveAllFuncDefOutsideOp(interface, MoveFuncDefRefactoringHelper::MoveOutside, result << new MoveAllFuncDefOutsideOp(interface, MoveFuncDefRefactoringHelper::MoveOutside,
classAST, QLatin1String("")); classAST, FilePath());
} }
namespace { namespace {
@@ -6547,34 +6530,34 @@ class MoveFuncDefToDeclOp : public CppQuickFixOperation
{ {
public: public:
MoveFuncDefToDeclOp(const CppQuickFixInterface &interface, MoveFuncDefToDeclOp(const CppQuickFixInterface &interface,
const QString &fromFileName, const QString &toFileName, const FilePath &fromFilePath, const FilePath &toFilePath,
FunctionDefinitionAST *funcDef, const QString &declText, FunctionDefinitionAST *funcDef, const QString &declText,
const ChangeSet::Range &fromRange, const ChangeSet::Range &fromRange,
const ChangeSet::Range &toRange) const ChangeSet::Range &toRange)
: CppQuickFixOperation(interface, 0) : CppQuickFixOperation(interface, 0)
, m_fromFileName(fromFileName) , m_fromFilePath(fromFilePath)
, m_toFileName(toFileName) , m_toFilePath(toFilePath)
, m_funcAST(funcDef) , m_funcAST(funcDef)
, m_declarationText(declText) , m_declarationText(declText)
, m_fromRange(fromRange) , m_fromRange(fromRange)
, m_toRange(toRange) , m_toRange(toRange)
{ {
if (m_toFileName == m_fromFileName) { if (m_toFilePath == m_fromFilePath) {
setDescription(QCoreApplication::translate("CppEditor::QuickFix", setDescription(QCoreApplication::translate("CppEditor::QuickFix",
"Move Definition to Class")); "Move Definition to Class"));
} else { } else {
const QDir dir = QFileInfo(m_fromFileName).dir(); const FilePath resolved = m_toFilePath.relativePathFrom(m_fromFilePath.parentDir());
setDescription(QCoreApplication::translate("CppEditor::QuickFix", setDescription(QCoreApplication::translate("CppEditor::QuickFix",
"Move Definition to %1") "Move Definition to %1")
.arg(dir.relativeFilePath(m_toFileName))); .arg(resolved.displayName()));
} }
} }
void perform() override void perform() override
{ {
CppRefactoringChanges refactoring(snapshot()); CppRefactoringChanges refactoring(snapshot());
CppRefactoringFilePtr fromFile = refactoring.file(Utils::FilePath::fromString(m_fromFileName)); CppRefactoringFilePtr fromFile = refactoring.file(m_fromFilePath);
CppRefactoringFilePtr toFile = refactoring.file(Utils::FilePath::fromString(m_toFileName)); CppRefactoringFilePtr toFile = refactoring.file(m_toFilePath);
const QString wholeFunctionText = m_declarationText const QString wholeFunctionText = m_declarationText
+ fromFile->textOf(fromFile->endOf(m_funcAST->declarator), + fromFile->textOf(fromFile->endOf(m_funcAST->declarator),
@@ -6583,13 +6566,13 @@ public:
// Replace declaration with function and delete old definition // Replace declaration with function and delete old definition
ChangeSet toTarget; ChangeSet toTarget;
toTarget.replace(m_toRange, wholeFunctionText); toTarget.replace(m_toRange, wholeFunctionText);
if (m_toFileName == m_fromFileName) if (m_toFilePath == m_fromFilePath)
toTarget.remove(m_fromRange); toTarget.remove(m_fromRange);
toFile->setChangeSet(toTarget); toFile->setChangeSet(toTarget);
toFile->appendIndentRange(m_toRange); toFile->appendIndentRange(m_toRange);
toFile->setOpenEditor(true, m_toRange.start); toFile->setOpenEditor(true, m_toRange.start);
toFile->apply(); toFile->apply();
if (m_toFileName != m_fromFileName) { if (m_toFilePath != m_fromFilePath) {
ChangeSet fromTarget; ChangeSet fromTarget;
fromTarget.remove(m_fromRange); fromTarget.remove(m_fromRange);
fromFile->setChangeSet(fromTarget); fromFile->setChangeSet(fromTarget);
@@ -6598,8 +6581,8 @@ public:
} }
private: private:
const QString m_fromFileName; const FilePath m_fromFilePath;
const QString m_toFileName; const FilePath m_toFilePath;
FunctionDefinitionAST *m_funcAST; FunctionDefinitionAST *m_funcAST;
const QString m_declarationText; const QString m_declarationText;
const ChangeSet::Range m_fromRange; const ChangeSet::Range m_fromRange;
@@ -6640,9 +6623,9 @@ void MoveFuncDefToDecl::match(const CppQuickFixInterface &interface, QuickFixOpe
const ChangeSet::Range defRange = defFile->range(completeDefAST); const ChangeSet::Range defRange = defFile->range(completeDefAST);
// Determine declaration (file, range, text); // Determine declaration (file, range, text);
QString declFileName;
ChangeSet::Range declRange; ChangeSet::Range declRange;
QString declText; QString declText;
FilePath declFilePath;
Function *func = funcAST->symbol; Function *func = funcAST->symbol;
if (Class *matchingClass = isMemberFunction(interface.context(), func)) { if (Class *matchingClass = isMemberFunction(interface.context(), func)) {
@@ -6667,10 +6650,8 @@ void MoveFuncDefToDecl::match(const CppQuickFixInterface &interface, QuickFixOpe
continue; continue;
} }
declFileName = QString::fromUtf8(matchingClass->fileName(), declFilePath = matchingClass->filePath();
matchingClass->fileNameLength()); const CppRefactoringFilePtr declFile = refactoring.file(declFilePath);
const CppRefactoringFilePtr declFile = refactoring.file(Utils::FilePath::fromString(declFileName));
ASTPath astPath(declFile->cppDocument()); ASTPath astPath(declFile->cppDocument());
const QList<AST *> path = astPath(s->line(), s->column()); const QList<AST *> path = astPath(s->line(), s->column());
for (int idx = path.size() - 1; idx > 0; --idx) { for (int idx = path.size() - 1; idx > 0; --idx) {
@@ -6691,12 +6672,11 @@ void MoveFuncDefToDecl::match(const CppQuickFixInterface &interface, QuickFixOpe
} else if (Namespace *matchingNamespace = isNamespaceFunction(interface.context(), func)) { } else if (Namespace *matchingNamespace = isNamespaceFunction(interface.context(), func)) {
// Dealing with free functions // Dealing with free functions
bool isHeaderFile = false; bool isHeaderFile = false;
declFileName = correspondingHeaderOrSource(interface.filePath().toString(), &isHeaderFile); declFilePath = correspondingHeaderOrSource(interface.filePath(), &isHeaderFile);
if (isHeaderFile) if (isHeaderFile)
return; return;
const CppRefactoringFilePtr declFile = refactoring.file( const CppRefactoringFilePtr declFile = refactoring.file(declFilePath);
Utils::FilePath::fromString(declFileName));
const LookupContext lc(declFile->cppDocument(), interface.snapshot()); const LookupContext lc(declFile->cppDocument(), interface.snapshot());
const QList<LookupItem> candidates = lc.lookup(func->name(), matchingNamespace); const QList<LookupItem> candidates = lc.lookup(func->name(), matchingNamespace);
for (const LookupItem &candidate : candidates) { for (const LookupItem &candidate : candidates) {
@@ -6716,16 +6696,16 @@ void MoveFuncDefToDecl::match(const CppQuickFixInterface &interface, QuickFixOpe
} }
if (!declText.isEmpty()) { if (!declText.isEmpty()) {
declText.prepend(inlinePrefix(declFileName)); declText.prepend(inlinePrefix(declFilePath));
break; break;
} }
} }
} }
if (!declFileName.isEmpty() && !declText.isEmpty()) if (!declFilePath.isEmpty() && !declText.isEmpty())
result << new MoveFuncDefToDeclOp(interface, result << new MoveFuncDefToDeclOp(interface,
interface.filePath().toString(), interface.filePath(),
declFileName, declFilePath,
funcAST, declText, funcAST, declText,
defRange, declRange); defRange, declRange);
} }
@@ -8941,11 +8921,11 @@ private:
const ClassSpecifierAST *m_classAST; const ClassSpecifierAST *m_classAST;
InsertionPointLocator::AccessSpec m_accessSpec; InsertionPointLocator::AccessSpec m_accessSpec;
GenerateConstructorRefactoringHelper(CppQuickFixOperation *operation, GenerateConstructorRefactoringHelper(CppQuickFixOperation *operation,
const QString &fileName, const FilePath &filePath,
Class *clazz, Class *clazz,
const ClassSpecifierAST *classAST, const ClassSpecifierAST *classAST,
InsertionPointLocator::AccessSpec accessSpec) InsertionPointLocator::AccessSpec accessSpec)
: GetterSetterRefactoringHelper(operation, fileName, clazz) : GetterSetterRefactoringHelper(operation, filePath, clazz)
, m_classAST(classAST) , m_classAST(classAST)
, m_accessSpec(accessSpec) , m_accessSpec(accessSpec)
{} {}
@@ -8979,7 +8959,7 @@ private:
false, false,
NamespaceHandling::Ignore, NamespaceHandling::Ignore,
m_changes, m_changes,
m_headerFile->filePath().toString(), m_headerFile->filePath(),
&insertedNamespaces); &insertedNamespaces);
implFile = m_headerFile; implFile = m_headerFile;
implCode = symbolAt(m_class, m_headerFile, implLoc); implCode = symbolAt(m_class, m_headerFile, implLoc);
@@ -9086,7 +9066,7 @@ private:
} }
}; };
GenerateConstructorRefactoringHelper helper(this, GenerateConstructorRefactoringHelper helper(this,
currentFile()->filePath().toString(), currentFile()->filePath(),
m_classAST->symbol, m_classAST->symbol,
m_classAST, m_classAST,
accessSpec); accessSpec);

View File

@@ -58,8 +58,10 @@ CppCompletionAssistProcessor CPPEDITOR_EXPORT *getCppCompletionAssistProcessor()
enum class CacheUsage { ReadWrite, ReadOnly }; enum class CacheUsage { ReadWrite, ReadOnly };
QString CPPEDITOR_EXPORT correspondingHeaderOrSource(const QString &fileName, bool *wasHeader = nullptr, Utils::FilePath CPPEDITOR_EXPORT correspondingHeaderOrSource(
const Utils::FilePath &filePath, bool *wasHeader = nullptr,
CacheUsage cacheUsage = CacheUsage::ReadWrite); CacheUsage cacheUsage = CacheUsage::ReadWrite);
void CPPEDITOR_EXPORT openEditor(const Utils::FilePath &filePath, bool inNextSplit, void CPPEDITOR_EXPORT openEditor(const Utils::FilePath &filePath, bool inNextSplit,
Utils::Id editorId = {}); Utils::Id editorId = {});
class CppCodeModelSettings; class CppCodeModelSettings;

View File

@@ -3,7 +3,6 @@
#include "insertionpointlocator.h" #include "insertionpointlocator.h"
#include "cppeditorconstants.h"
#include "cppprojectfile.h" #include "cppprojectfile.h"
#include "cpptoolsreuse.h" #include "cpptoolsreuse.h"
#include "symbolfinder.h" #include "symbolfinder.h"
@@ -16,6 +15,7 @@
#include <utils/qtcassert.h> #include <utils/qtcassert.h>
using namespace CPlusPlus; using namespace CPlusPlus;
using namespace Utils;
namespace CppEditor { namespace CppEditor {
namespace { namespace {
@@ -207,11 +207,11 @@ QList<AccessRange> collectAccessRanges(const CPlusPlus::TranslationUnit *tu,
InsertionLocation::InsertionLocation() = default; InsertionLocation::InsertionLocation() = default;
InsertionLocation::InsertionLocation(const QString &fileName, InsertionLocation::InsertionLocation(const FilePath &filePath,
const QString &prefix, const QString &prefix,
const QString &suffix, const QString &suffix,
int line, int column) int line, int column)
: m_fileName(fileName) : m_filePath(filePath)
, m_prefix(prefix) , m_prefix(prefix)
, m_suffix(suffix) , m_suffix(suffix)
, m_line(line) , m_line(line)
@@ -306,7 +306,7 @@ InsertionLocation InsertionPointLocator::methodDeclarationInClass(const Translat
if (needsSuffix) if (needsSuffix)
suffix = QLatin1Char('\n'); suffix = QLatin1Char('\n');
const QString fileName = QString::fromUtf8(tu->fileName(), tu->fileNameLength()); const QString fileName = QString::fromUtf8(tu->fileName(), tu->fileNameLength());
return InsertionLocation(fileName, prefix, suffix, line, column); return InsertionLocation(FilePath::fromString(fileName), prefix, suffix, line, column);
} }
InsertionPointLocator::AccessSpec symbolsAccessSpec(Symbol *symbol) InsertionPointLocator::AccessSpec symbolsAccessSpec(Symbol *symbol)
@@ -360,16 +360,17 @@ InsertionLocation InsertionPointLocator::constructorDeclarationInClass(
// we have a constructor with x arguments but there are only ones with < x arguments // we have a constructor with x arguments but there are only ones with < x arguments
--iter; // select greatest one (in terms of argument count) --iter; // select greatest one (in terms of argument count)
} }
const QString fileName = QString::fromUtf8(tu->fileName(), tu->fileNameLength()); const FilePath filePath =
FilePath::fromString(QString::fromUtf8(tu->fileName(), tu->fileNameLength()));
int line, column; int line, column;
if (iter->first <= constructorArgumentCount) { if (iter->first <= constructorArgumentCount) {
tu->getTokenEndPosition(iter->second.second->lastToken() - 1, &line, &column); tu->getTokenEndPosition(iter->second.second->lastToken() - 1, &line, &column);
return InsertionLocation(fileName, "\n", "", line, column); return InsertionLocation(filePath, "\n", "", line, column);
} }
// before iter // before iter
// end pos of firstToken-1 instead of start pos of firstToken to skip leading commend // end pos of firstToken-1 instead of start pos of firstToken to skip leading commend
tu->getTokenEndPosition(iter->second.first->firstToken() - 1, &line, &column); tu->getTokenEndPosition(iter->second.first->firstToken() - 1, &line, &column);
return InsertionLocation(fileName, "\n", "", line, column); return InsertionLocation(filePath, "\n", "", line, column);
} }
namespace { namespace {
@@ -529,7 +530,7 @@ static Declaration *isNonVirtualFunctionDeclaration(Symbol *s)
static InsertionLocation nextToSurroundingDefinitions(Symbol *declaration, static InsertionLocation nextToSurroundingDefinitions(Symbol *declaration,
const CppRefactoringChanges &changes, const CppRefactoringChanges &changes,
const QString& destinationFile) const FilePath &destinationFile)
{ {
InsertionLocation noResult; InsertionLocation noResult;
Class *klass = declaration->enclosingClass(); Class *klass = declaration->enclosingClass();
@@ -560,8 +561,7 @@ static InsertionLocation nextToSurroundingDefinitions(Symbol *declaration,
if ((definitionFunction = symbolFinder.findMatchingDefinition(surroundingFunctionDecl, if ((definitionFunction = symbolFinder.findMatchingDefinition(surroundingFunctionDecl,
changes.snapshot()))) changes.snapshot())))
{ {
if (destinationFile.isEmpty() || destinationFile == QString::fromUtf8( if (destinationFile.isEmpty() || destinationFile == definitionFunction->filePath()) {
definitionFunction->fileName(), definitionFunction->fileNameLength())) {
prefix = QLatin1String("\n\n"); prefix = QLatin1String("\n\n");
break; break;
} }
@@ -578,8 +578,7 @@ static InsertionLocation nextToSurroundingDefinitions(Symbol *declaration,
if ((definitionFunction = symbolFinder.findMatchingDefinition(surroundingFunctionDecl, if ((definitionFunction = symbolFinder.findMatchingDefinition(surroundingFunctionDecl,
changes.snapshot()))) changes.snapshot())))
{ {
if (destinationFile.isEmpty() || destinationFile == QString::fromUtf8( if (destinationFile.isEmpty() || destinationFile == definitionFunction->filePath()) {
definitionFunction->fileName(), definitionFunction->fileNameLength())) {
suffix = QLatin1String("\n\n"); suffix = QLatin1String("\n\n");
break; break;
} }
@@ -622,11 +621,11 @@ static InsertionLocation nextToSurroundingDefinitions(Symbol *declaration,
} }
} }
return InsertionLocation(QString::fromUtf8(definitionFunction->fileName()), prefix, suffix, line, column); return InsertionLocation(definitionFunction->filePath(), prefix, suffix, line, column);
} }
const QList<InsertionLocation> InsertionPointLocator::methodDefinition( const QList<InsertionLocation> InsertionPointLocator::methodDefinition(
Symbol *declaration, bool useSymbolFinder, const QString &destinationFile) const Symbol *declaration, bool useSymbolFinder, const FilePath &destinationFile) const
{ {
QList<InsertionLocation> result; QList<InsertionLocation> result;
if (!declaration) if (!declaration)
@@ -646,17 +645,15 @@ const QList<InsertionLocation> InsertionPointLocator::methodDefinition(
return result; return result;
} }
const QString declFileName = QString::fromUtf8(declaration->fileName(), const FilePath declFilePath = declaration->filePath();
declaration->fileNameLength()); FilePath target = declFilePath;
QString target = declFileName; if (!ProjectFile::isSource(ProjectFile::classify(declFilePath.path()))) {
if (!ProjectFile::isSource(ProjectFile::classify(declFileName))) { FilePath candidate = correspondingHeaderOrSource(declFilePath);
QString candidate = correspondingHeaderOrSource(declFileName);
if (!candidate.isEmpty()) if (!candidate.isEmpty())
target = candidate; target = candidate;
} }
CppRefactoringFilePtr targetFile = m_refactoringChanges.file( CppRefactoringFilePtr targetFile = m_refactoringChanges.file(target);
Utils::FilePath::fromString(target));
Document::Ptr doc = targetFile->cppDocument(); Document::Ptr doc = targetFile->cppDocument();
if (doc.isNull()) if (doc.isNull())
return result; return result;
@@ -759,12 +756,12 @@ InsertionLocation insertLocationForMethodDefinition(Symbol *symbol,
const bool useSymbolFinder, const bool useSymbolFinder,
NamespaceHandling namespaceHandling, NamespaceHandling namespaceHandling,
const CppRefactoringChanges &refactoring, const CppRefactoringChanges &refactoring,
const QString &fileName, const FilePath &filePath,
QStringList *insertedNamespaces) QStringList *insertedNamespaces)
{ {
QTC_ASSERT(symbol, return InsertionLocation()); QTC_ASSERT(symbol, return InsertionLocation());
CppRefactoringFilePtr file = refactoring.file(Utils::FilePath::fromString(fileName)); CppRefactoringFilePtr file = refactoring.file(filePath);
QStringList requiredNamespaces; QStringList requiredNamespaces;
if (namespaceHandling == NamespaceHandling::CreateMissing) { if (namespaceHandling == NamespaceHandling::CreateMissing) {
requiredNamespaces = getNamespaceNames(symbol); requiredNamespaces = getNamespaceNames(symbol);
@@ -775,8 +772,8 @@ InsertionLocation insertLocationForMethodDefinition(Symbol *symbol,
// (or provide enough context). // (or provide enough context).
const InsertionPointLocator locator(refactoring); const InsertionPointLocator locator(refactoring);
const QList<InsertionLocation> list const QList<InsertionLocation> list
= locator.methodDefinition(symbol, useSymbolFinder, fileName); = locator.methodDefinition(symbol, useSymbolFinder, filePath);
const bool isHeader = ProjectFile::isHeader(ProjectFile::classify(fileName)); const bool isHeader = ProjectFile::isHeader(ProjectFile::classify(filePath.path()));
const bool hasIncludeGuard = isHeader const bool hasIncludeGuard = isHeader
&& !file->cppDocument()->includeGuardMacroName().isEmpty(); && !file->cppDocument()->includeGuardMacroName().isEmpty();
int lastLine; int lastLine;
@@ -787,7 +784,7 @@ InsertionLocation insertLocationForMethodDefinition(Symbol *symbol,
int i = 0; int i = 0;
for ( ; i < list.count(); ++i) { for ( ; i < list.count(); ++i) {
InsertionLocation location = list.at(i); InsertionLocation location = list.at(i);
if (!location.isValid() || location.fileName() != fileName) if (!location.isValid() || location.filePath() != filePath)
continue; continue;
if (hasIncludeGuard && location.line() == lastLine) if (hasIncludeGuard && location.line() == lastLine)
continue; continue;
@@ -805,11 +802,11 @@ InsertionLocation insertLocationForMethodDefinition(Symbol *symbol,
// if class member try to get position right after class // if class member try to get position right after class
int line = 0, column = 0; int line = 0, column = 0;
if (Class *clazz = symbol->enclosingClass()) { if (Class *clazz = symbol->enclosingClass()) {
if (symbol->fileName() == fileName.toUtf8()) { if (symbol->filePath() == filePath) {
file->cppDocument()->translationUnit()->getPosition(clazz->endOffset(), &line, &column); file->cppDocument()->translationUnit()->getPosition(clazz->endOffset(), &line, &column);
if (line != 0) { if (line != 0) {
++column; // Skipping the ";" ++column; // Skipping the ";"
return InsertionLocation(fileName, QLatin1String("\n\n"), QLatin1String(""), return InsertionLocation(filePath, QLatin1String("\n\n"), QLatin1String(""),
line, column); line, column);
} }
} }
@@ -834,7 +831,7 @@ InsertionLocation insertLocationForMethodDefinition(Symbol *symbol,
//TODO watch for moc-includes //TODO watch for moc-includes
file->lineAndColumn(pos, &line, &column); file->lineAndColumn(pos, &line, &column);
return InsertionLocation(fileName, prefix, suffix, line, column); return InsertionLocation(filePath, prefix, suffix, line, column);
} }
} // namespace CppEditor; } // namespace CppEditor;

View File

@@ -6,6 +6,8 @@
#include "cppeditor_global.h" #include "cppeditor_global.h"
#include "cpprefactoringchanges.h" #include "cpprefactoringchanges.h"
#include <utils/filepath.h>
namespace CPlusPlus { namespace CPlusPlus {
class Namespace; class Namespace;
class NamespaceAST; class NamespaceAST;
@@ -18,11 +20,11 @@ class CPPEDITOR_EXPORT InsertionLocation
{ {
public: public:
InsertionLocation(); InsertionLocation();
InsertionLocation(const QString &fileName, const QString &prefix, InsertionLocation(const Utils::FilePath &filePath, const QString &prefix,
const QString &suffix, int line, int column); const QString &suffix, int line, int column);
QString fileName() const const Utils::FilePath &filePath() const
{ return m_fileName; } { return m_filePath; }
/// \returns The prefix to insert before any other text. /// \returns The prefix to insert before any other text.
QString prefix() const QString prefix() const
@@ -41,10 +43,10 @@ public:
{ return m_column; } { return m_column; }
bool isValid() const bool isValid() const
{ return !m_fileName.isEmpty() && m_line > 0 && m_column > 0; } { return !m_filePath.isEmpty() && m_line > 0 && m_column > 0; }
private: private:
QString m_fileName; Utils::FilePath m_filePath;
QString m_prefix; QString m_prefix;
QString m_suffix; QString m_suffix;
int m_line = 0; int m_line = 0;
@@ -99,10 +101,9 @@ public:
AccessSpec xsSpec, AccessSpec xsSpec,
int constructorArgumentCount) const; int constructorArgumentCount) const;
const QList<InsertionLocation> methodDefinition( const QList<InsertionLocation> methodDefinition(CPlusPlus::Symbol *declaration,
CPlusPlus::Symbol *declaration,
bool useSymbolFinder = true, bool useSymbolFinder = true,
const QString &destinationFile = QString()) const; const Utils::FilePath &destinationFile = {}) const;
private: private:
CppRefactoringChanges m_refactoringChanges; CppRefactoringChanges m_refactoringChanges;
@@ -115,7 +116,7 @@ insertLocationForMethodDefinition(CPlusPlus::Symbol *symbol,
const bool useSymbolFinder, const bool useSymbolFinder,
NamespaceHandling namespaceHandling, NamespaceHandling namespaceHandling,
const CppRefactoringChanges &refactoring, const CppRefactoringChanges &refactoring,
const QString &fileName, const Utils::FilePath &fileName,
QStringList *insertedNamespaces = nullptr); QStringList *insertedNamespaces = nullptr);
} // namespace CppEditor } // namespace CppEditor

View File

@@ -543,11 +543,11 @@ bool QtCreatorIntegration::navigateToSlot(const QString &objectName,
{FilePath::fromString(QString::fromUtf8(funImpl->fileName())), funImpl->line() + 2}); {FilePath::fromString(QString::fromUtf8(funImpl->fileName())), funImpl->line() + 2});
return true; return true;
} }
const QString implFilePath = CppEditor::correspondingHeaderOrSource(declFilePath.toString()); const FilePath implFilePath = CppEditor::correspondingHeaderOrSource(declFilePath);
const CppEditor::InsertionLocation location = CppEditor::insertLocationForMethodDefinition const CppEditor::InsertionLocation location = CppEditor::insertLocationForMethodDefinition
(fun, false, CppEditor::NamespaceHandling::CreateMissing, refactoring, implFilePath); (fun, false, CppEditor::NamespaceHandling::CreateMissing, refactoring, implFilePath);
if (BaseTextEditor *editor = editorAt(FilePath::fromString(location.fileName()), if (BaseTextEditor *editor = editorAt(location.filePath(),
location.line(), location.column())) { location.line(), location.column())) {
Overview o; Overview o;
const QString className = o.prettyName(cl->name()); const QString className = o.prettyName(cl->name());
@@ -555,7 +555,7 @@ bool QtCreatorIntegration::navigateToSlot(const QString &objectName,
+ functionNameWithParameterNames + "\n{\n" + QString(indentation, ' ') + "\n}\n" + functionNameWithParameterNames + "\n{\n" + QString(indentation, ' ') + "\n}\n"
+ location.suffix(); + location.suffix();
editor->insert(definition); editor->insert(definition);
Core::EditorManager::openEditorAt({FilePath::fromString(location.fileName()), Core::EditorManager::openEditorAt({location.filePath(),
int(location.line() + location.prefix().count('\n') + 2), int(location.line() + location.prefix().count('\n') + 2),
indentation}); indentation});
return true; return true;

View File

@@ -8,6 +8,7 @@
#include <cplusplus/Overview.h> #include <cplusplus/Overview.h>
#include <cplusplus/LookupContext.h> #include <cplusplus/LookupContext.h>
using namespace Utils;
namespace ModelEditor { namespace ModelEditor {
namespace Internal { namespace Internal {
@@ -16,7 +17,7 @@ ClassViewController::ClassViewController(QObject *parent)
{ {
} }
QSet<QString> ClassViewController::findClassDeclarations(const QString &fileName, int line, int column) QSet<QString> ClassViewController::findClassDeclarations(const FilePath &filePath, int line, int column)
{ {
QSet<QString> classNames; QSet<QString> classNames;
@@ -24,15 +25,15 @@ QSet<QString> ClassViewController::findClassDeclarations(const QString &fileName
CPlusPlus::Snapshot snapshot = cppModelManager->snapshot(); CPlusPlus::Snapshot snapshot = cppModelManager->snapshot();
// scan original file // scan original file
CPlusPlus::Document::Ptr document = snapshot.document(Utils::FilePath::fromString(fileName)); CPlusPlus::Document::Ptr document = snapshot.document(filePath);
if (!document.isNull()) if (!document.isNull())
appendClassDeclarationsFromDocument(document, line, column, &classNames); appendClassDeclarationsFromDocument(document, line, column, &classNames);
if (line <= 0) { if (line <= 0) {
QString otherFileName = CppEditor::correspondingHeaderOrSource(fileName); const FilePath otherFilePath = CppEditor::correspondingHeaderOrSource(filePath);
// scan other file // scan other file
document = snapshot.document(Utils::FilePath::fromString(otherFileName)); document = snapshot.document(otherFilePath);
if (!document.isNull()) if (!document.isNull())
appendClassDeclarationsFromDocument(document, -1, -1, &classNames); appendClassDeclarationsFromDocument(document, -1, -1, &classNames);
} }

View File

@@ -19,7 +19,7 @@ public:
explicit ClassViewController(QObject *parent = nullptr); explicit ClassViewController(QObject *parent = nullptr);
~ClassViewController() = default; ~ClassViewController() = default;
QSet<QString> findClassDeclarations(const QString &fileName, int line = -1, int column = -1); QSet<QString> findClassDeclarations(const Utils::FilePath &filePath, int line = -1, int column = -1);
private: private:
void appendClassDeclarationsFromDocument(CPlusPlus::Document::Ptr document, int line, int column, void appendClassDeclarationsFromDocument(CPlusPlus::Document::Ptr document, int line, int column,

View File

@@ -28,6 +28,8 @@
#include <QMenu> #include <QMenu>
#include <QQueue> #include <QQueue>
using namespace Utils;
namespace ModelEditor { namespace ModelEditor {
namespace Internal { namespace Internal {
@@ -135,7 +137,8 @@ void PxNodeController::addFileSystemEntry(const QString &filePath, int line, int
menu->addAction(new MenuAction(tr("Add Component %1").arg(elementName), elementName, menu->addAction(new MenuAction(tr("Add Component %1").arg(elementName), elementName,
MenuAction::TYPE_ADD_COMPONENT, menu)); MenuAction::TYPE_ADD_COMPONENT, menu));
const QStringList classNames = Utils::toList( const QStringList classNames = Utils::toList(
d->classViewController->findClassDeclarations(filePath, line, column)); d->classViewController->findClassDeclarations(
FilePath::fromString(filePath), line, column));
if (!classNames.empty()) { if (!classNames.empty()) {
menu->addSeparator(); menu->addSeparator();
int index = 0; int index = 0;