Merge remote-tracking branch 'origin/4.9'

Conflicts:
	qtcreator.pri

Change-Id: I278bc79cb64705471b360d0b8d06a8db17db7904
This commit is contained in:
Eike Ziller
2019-02-08 12:48:19 +01:00
126 changed files with 1409 additions and 1214 deletions

72
dist/changes-4.8.2.md vendored Normal file
View File

@@ -0,0 +1,72 @@
Qt Creator version 4.8.2 contains bug fixes.
The most important changes are listed in this document. For a complete
list of changes, see the Git log for the Qt Creator sources that
you can check out from the public Git repository. For example:
git clone git://code.qt.io/qt-creator/qt-creator.git
git log --cherry-pick --pretty=oneline origin/v4.8.1..v4.8.2
Editing
* Fixed highlighting of search results of regular expression search
(QTCREATORBUG-21887)
Autotools Projects
* Fixed that includes, defines and flags of `SUBDIRS` were ignored
(QTCREATORBUG-21618)
C++ Support
* Fixed crash when expanding macros (QTCREATORBUG-21642)
QML Support
* Fixed auto-insertion of single quotes
Debugging
* GDB
* Fixed detaching from process (QTCREATORBUG-21908)
* LLDB
* Fixed stopping at some breakpoints with newer LLDB (QTCREATORBUG-21615)
* Fixed `Attach to Process` and `Run in Terminal` with newer LLDB
* CDB
* Fixed display of `QDateTime` (QTCREATORBUG-21864)
Qt Quick Designer
* Added support for more JavaScript functions in `.ui.qml` files
Test Integration
* Fixed handling of empty tests
Platform Specific
macOS
* Fixed crash when file change dialog is triggered while another modal dialog
is open
* Fixed running of user applications that need access to camera, microphone or
other restricted services on macOS 10.14 (QTCREATORBUG-21887)
Android
* Fixed upload of GDB server on some devices (QTCREATORBUG-21317)
Credits for these changes go to:
André Pönitz
Christian Kandeler
Christian Stenger
David Schulz
Eike Ziller
Ivan Donchevskii
Leena Miettinen
Liang Qi
Oliver Wolff
Raoul Hecky
Robert Löhning
Thomas Hartmann
Vikas Pachdha

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

View File

@@ -51,49 +51,32 @@
\section1 Generic Highlighting \section1 Generic Highlighting
Generic highlighting is based on highlight definition files that are Generic highlighting is provided by
provided by the \l{https://api.kde.org/frameworks/syntax-highlighting/html/index.html}
\l{http://kate-editor.org/2005/03/24/writing-a-syntax-highlighting-file/} {KSyntaxHighlighting}, which is the syntax highlighting engine for Kate
{Kate Editor}. You can download highlight definition files for use with \QC. syntax definitions. \QC comes with most of the commonly used syntax files,
For more information about the definition files, see and you can download additional files. For more information about the
\l{http://kde-files.org/index.php?xcontentmode=680}{KDE-Files.org}. definition files, see
\l{https://docs.kde.org/stable5/en/applications/katepart/highlight.html}
{Working with Syntax Highlighting}.
If you have a Unix installation that comes with the Kate Editor, you might If the editor cannot find the highlight definition for a file that you open
already have the definition files installed. Typically, the files are for editing, it prompts you to update the highlight definition files. Select
located in a read-only directory, and therefore, you cannot manage them. \QC \uicontrol {Update Definitions} to update the files.
can try to locate them and use them as fallback files, when the primary
location does not contain the definition for the current file type. You can
also specify the directory that contains preinstalled highlight
definition files as the primary location.
When you open a file for editing and the editor cannot find the highlight To suppress the message for a particular file pattern, select
definition for it, an alert appears. To suppress the alerts, you can specify \uicontrol Tools > \uicontrol Options > \uicontrol {Text Editor}
patterns for ignoring files. > \uicontrol {Generic Highlighter} and add the pattern to the
\uicontrol {Ignored file patterns} field.
To download highlight definition files: \image qtcreator-syntax-highlighter.png "Generic Highlighter options"
\list 1 If you have written your own syntax definition files, you
\li Select \uicontrol Tools > \uicontrol Options > can provide an additional definition search path in the
\uicontrol {Text Editor} > \uicontrol {Generic Highlighter}. \uicontrol {User Highlight Definition Files} field.
\image qtcreator-generic-highlighter.png "Generic Highlighter options"
\li In the \uicontrol Location field, specify the path to the primary To manually update the highlight definition files, select
location for highlight definition files. \uicontrol {Update Definitions}.
\li Click \uicontrol {Download Definitions} to open a list of highlight
definition files available for download.
\image qtcreator-manage-definitions.png "Download Definitions dialog"
\li Select highlight definition files in the list and click
\uicontrol {Download Selected Definitions}.
\li Select the \uicontrol {Use fallback location} check box to specify
the secondary location where the editor will look for highlight
definition files.
\li Click \uicontrol Autodetect to allow \QC to look for highlight
definition files on your system, or click \uicontrol Browse to
locate them in the file system yourself.
\li In the \uicontrol {Ignored file patterns} field, specify file
patterns to suppress alerts if the highlight definitions for the
specified files are not found.
\li Click \uicontrol OK to save your changes.
\endlist
\section1 Highlighting and Folding Blocks \section1 Highlighting and Folding Blocks

View File

@@ -17,7 +17,7 @@ Module {
property string qtcreator_compat_version: ide_compat_version_major + '.' property string qtcreator_compat_version: ide_compat_version_major + '.'
+ ide_compat_version_minor + '.' + ide_compat_version_release + ide_compat_version_minor + '.' + ide_compat_version_release
property string qtcreator_copyright_year: '2018' property string qtcreator_copyright_year: '2019'
property string qtcreator_copyright_string: "(C) " + qtcreator_copyright_year + " The Qt Company Ltd" property string qtcreator_copyright_string: "(C) " + qtcreator_copyright_year + " The Qt Company Ltd"
property string ide_display_name: 'Qt Creator' property string ide_display_name: 'Qt Creator'

View File

@@ -5,7 +5,7 @@ QTCREATOR_VERSION = 4.9.82
QTCREATOR_COMPAT_VERSION = 4.9.82 QTCREATOR_COMPAT_VERSION = 4.9.82
VERSION = $$QTCREATOR_VERSION VERSION = $$QTCREATOR_VERSION
QTCREATOR_DISPLAY_VERSION = 4.10.0-beta1 QTCREATOR_DISPLAY_VERSION = 4.10.0-beta1
QTCREATOR_COPYRIGHT_YEAR = 2018 QTCREATOR_COPYRIGHT_YEAR = 2019
BINARY_ARTIFACTS_BRANCH = master BINARY_ARTIFACTS_BRANCH = master
isEmpty(IDE_DISPLAY_NAME): IDE_DISPLAY_NAME = Qt Creator isEmpty(IDE_DISPLAY_NAME): IDE_DISPLAY_NAME = Qt Creator

View File

@@ -150,4 +150,7 @@ win32 {
bindist_installer.commands ~= s,/,\\\\,g bindist_installer.commands ~= s,/,\\\\,g
} }
deployqt.CONFIG += recursive
deployqt.recurse = src
QMAKE_EXTRA_TARGETS += deployqt bindist bindist_installer bindist_debug QMAKE_EXTRA_TARGETS += deployqt bindist bindist_installer bindist_debug

View File

@@ -274,3 +274,5 @@
<string>A user application wants to access the photo library.</string> <string>A user application wants to access the photo library.</string>
<key>NSRemindersUsageDescription</key> <key>NSRemindersUsageDescription</key>
<string>A user application wants to access the reminders.</string> <string>A user application wants to access the reminders.</string>
</dict>
</plist>

View File

@@ -52,3 +52,5 @@ DISTFILES += qtcreator.rc \
QMAKE_SUBSTITUTES += $$PWD/app_version.h.in QMAKE_SUBSTITUTES += $$PWD/app_version.h.in
CONFIG += no_batch CONFIG += no_batch
QMAKE_EXTRA_TARGETS += deployqt # dummy

View File

@@ -78,7 +78,7 @@ Definition Repository::definitionForName(const QString& defName) const
return d->m_defs.value(defName); return d->m_defs.value(defName);
} }
static Definition bestCandidate(QVector<Definition>& candidates) static Definition bestCandidate(QVector<Definition> &&candidates)
{ {
if (candidates.isEmpty()) if (candidates.isEmpty())
return Definition(); return Definition();
@@ -91,6 +91,11 @@ static Definition bestCandidate(QVector<Definition>& candidates)
} }
Definition Repository::definitionForFileName(const QString& fileName) const Definition Repository::definitionForFileName(const QString& fileName) const
{
return bestCandidate(definitionsForFileName(fileName));
}
QVector<Definition> Repository::definitionsForFileName(const QString &fileName) const
{ {
QFileInfo fi(fileName); QFileInfo fi(fileName);
const auto name = fi.fileName(); const auto name = fi.fileName();
@@ -106,10 +111,15 @@ Definition Repository::definitionForFileName(const QString& fileName) const
} }
} }
return bestCandidate(candidates); return candidates;
} }
Definition Repository::definitionForMimeType(const QString& mimeType) const Definition Repository::definitionForMimeType(const QString& mimeType) const
{
return bestCandidate(definitionsForMimeType(mimeType));
}
QVector<Definition> Repository::definitionsForMimeType(const QString &mimeType) const
{ {
QVector<Definition> candidates; QVector<Definition> candidates;
for (auto it = d->m_defs.constBegin(); it != d->m_defs.constEnd(); ++it) { for (auto it = d->m_defs.constBegin(); it != d->m_defs.constEnd(); ++it) {
@@ -121,8 +131,7 @@ Definition Repository::definitionForMimeType(const QString& mimeType) const
} }
} }
} }
return candidates;
return bestCandidate(candidates);
} }
QVector<Definition> Repository::definitions() const QVector<Definition> Repository::definitions() const

View File

@@ -166,6 +166,13 @@ public:
*/ */
Definition definitionForFileName(const QString &fileName) const; Definition definitionForFileName(const QString &fileName) const;
/**
* Returns all Definition%s for the file named @p fileName.
* The match is performed based on the \e extensions and @e mimetype of
* the definition files.
*/
QVector<Definition> definitionsForFileName(const QString &fileName) const;
/** /**
* Returns the best matching Definition to the type named @p mimeType * Returns the best matching Definition to the type named @p mimeType
* *
@@ -176,6 +183,11 @@ public:
*/ */
Definition definitionForMimeType(const QString &mimeType) const; Definition definitionForMimeType(const QString &mimeType) const;
/**
* Returns all Definition%s to the type named @p mimeType
*/
QVector<Definition> definitionsForMimeType(const QString &mimeType) const;
/** /**
* Returns all available Definition%s. * Returns all available Definition%s.
* Definition%ss are ordered by translated section and translated names, * Definition%ss are ordered by translated section and translated names,

View File

@@ -25,7 +25,7 @@
#pragma once #pragma once
#include "filepathview.h" #include "filepath.h"
#include <compilermacro.h> #include <compilermacro.h>
#include <includesearchpath.h> #include <includesearchpath.h>
@@ -35,7 +35,7 @@
namespace ClangBackEnd { namespace ClangBackEnd {
template<typename ProjectInfo, typename OutputContainer = std::vector<std::string>> template<typename ProjectInfo, typename OutputContainer = Utils::SmallStringVector>
class CommandLineBuilder class CommandLineBuilder
{ {
public: public:
@@ -213,7 +213,7 @@ public:
{ {
for (const IncludeSearchPath &path : projectIncludeSearchPaths) { for (const IncludeSearchPath &path : projectIncludeSearchPaths) {
commandLine.emplace_back("-I"); commandLine.emplace_back("-I");
commandLine.emplace_back(path.path); commandLine.emplace_back(NativeFilePath(FilePathView(path.path)));
} }
} }
@@ -228,7 +228,7 @@ public:
for (const IncludeSearchPath &path : systemIncludeSearchPaths) { for (const IncludeSearchPath &path : systemIncludeSearchPaths) {
if (path.type != IncludeSearchPathType::BuiltIn) { if (path.type != IncludeSearchPathType::BuiltIn) {
commandLine.emplace_back(includeOption(path.type)); commandLine.emplace_back(includeOption(path.type));
commandLine.emplace_back(path.path); commandLine.emplace_back(NativeFilePath(FilePathView(path.path)));
} }
} }
} }
@@ -238,7 +238,7 @@ public:
for (const IncludeSearchPath &path : systemIncludeSearchPaths) { for (const IncludeSearchPath &path : systemIncludeSearchPaths) {
if (path.type == IncludeSearchPathType::BuiltIn) { if (path.type == IncludeSearchPathType::BuiltIn) {
commandLine.emplace_back(includeOption(path.type)); commandLine.emplace_back(includeOption(path.type));
commandLine.emplace_back(path.path); commandLine.emplace_back(NativeFilePath(FilePathView(path.path)));
} }
} }
} }
@@ -247,23 +247,24 @@ public:
{ {
if (!outputPath.isEmpty()) { if (!outputPath.isEmpty()) {
commandLine.emplace_back("-o"); commandLine.emplace_back("-o");
commandLine.emplace_back(outputPath); commandLine.emplace_back(NativeFilePath(outputPath));
} }
} }
void addSourcePath(FilePathView sourcePath) void addSourcePath(FilePathView sourcePath)
{ {
if (!sourcePath.isEmpty()) if (!sourcePath.isEmpty())
commandLine.emplace_back(sourcePath); commandLine.emplace_back(NativeFilePath(sourcePath));
} }
void addIncludePchPath(FilePathView includePchPath) void addIncludePchPath(FilePathView includePchPath)
{ {
if (!includePchPath.isEmpty()) { if (!includePchPath.isEmpty()) {
commandLine.emplace_back("-Xclang"); commandLine.emplace_back("-Xclang");
commandLine.emplace_back("-include-pch"); commandLine.emplace_back("-include-pch");
commandLine.emplace_back("-Xclang"); commandLine.emplace_back("-Xclang");
commandLine.emplace_back(includePchPath); commandLine.emplace_back(NativeFilePath(includePchPath));
} }
} }

View File

@@ -28,7 +28,7 @@
#include "clangsupport_global.h" #include "clangsupport_global.h"
#include "filepathview.h" #include "filepathview.h"
#include "filepathview.h" #include "nativefilepath.h"
#include <utils/hostosinfo.h> #include <utils/hostosinfo.h>
#include <utils/smallstringio.h> #include <utils/smallstringio.h>
@@ -37,6 +37,8 @@
namespace ClangBackEnd { namespace ClangBackEnd {
class NativeFilePath;
class FilePath : public Utils::PathString class FilePath : public Utils::PathString
{ {
using size_type = Utils::PathString::size_type; using size_type = Utils::PathString::size_type;

View File

@@ -26,13 +26,15 @@
#pragma once #pragma once
#include "filepathview.h" #include "filepathview.h"
#include "filepathview.h" #include "filepath.h"
#include <utils/hostosinfo.h> #include <utils/hostosinfo.h>
#include <utils/smallstringio.h> #include <utils/smallstringio.h>
namespace ClangBackEnd { namespace ClangBackEnd {
class FilePath;
class NativeFilePath class NativeFilePath
{ {
using size_type = Utils::PathString::size_type; using size_type = Utils::PathString::size_type;
@@ -50,8 +52,13 @@ public:
NativeFilePath(NativeFilePathView filePathView) NativeFilePath(NativeFilePathView filePathView)
: m_path(filePathView.toStringView()), : m_path(filePathView.toStringView()),
m_slashIndex(filePathView.slashIndex()) m_slashIndex(filePathView.slashIndex())
{ {}
}
explicit NativeFilePath(FilePathView filePathView) { *this = fromFilePath(filePathView); }
explicit NativeFilePath(const FilePath &filePath)
: NativeFilePath{FilePathView{filePath}}
{}
template<size_type Size> template<size_type Size>
NativeFilePath(const char(&string)[Size]) noexcept NativeFilePath(const char(&string)[Size]) noexcept

View File

@@ -25,6 +25,8 @@
#include "languagefeatures.h" #include "languagefeatures.h"
#include <cstddef>
namespace LanguageServerProtocol { namespace LanguageServerProtocol {
constexpr const char HoverRequest::methodName[]; constexpr const char HoverRequest::methodName[];
@@ -406,7 +408,7 @@ CodeActionResult::CodeActionResult(const QJsonValue &val)
emplace<ResultArray>(result); emplace<ResultArray>(result);
return; return;
} }
emplace<nullptr_t>(nullptr); emplace<std::nullptr_t>(nullptr);
} }
bool CodeAction::isValid(QStringList *error) const bool CodeAction::isValid(QStringList *error) const

View File

@@ -48,3 +48,5 @@ win32: isEmpty(QTC_SKIP_CDBEXT) {
message("environment variable pointing to your CDB installation.") message("environment variable pointing to your CDB installation.")
} }
} }
QMAKE_EXTRA_TARGETS += deployqt # dummy

View File

@@ -27,6 +27,7 @@
#include "fancylineedit.h" #include "fancylineedit.h"
#include "historycompleter.h" #include "historycompleter.h"
#include "hostosinfo.h" #include "hostosinfo.h"
#include "optional.h"
#include "qtcassert.h" #include "qtcassert.h"
#include "stylehelper.h" #include "stylehelper.h"
#include "utilsicons.h" #include "utilsicons.h"
@@ -175,6 +176,14 @@ FancyLineEdit::~FancyLineEdit()
} }
} }
void FancyLineEdit::setTextKeepingActiveCursor(const QString &text)
{
optional<int> cursor = hasFocus() ? make_optional(cursorPosition()) : nullopt;
setText(text);
if (cursor)
setCursorPosition(*cursor);
}
void FancyLineEdit::setButtonVisible(Side side, bool visible) void FancyLineEdit::setButtonVisible(Side side, bool visible)
{ {
d->m_iconbutton[side]->setVisible(visible); d->m_iconbutton[side]->setVisible(visible);

View File

@@ -82,6 +82,8 @@ public:
explicit FancyLineEdit(QWidget *parent = nullptr); explicit FancyLineEdit(QWidget *parent = nullptr);
~FancyLineEdit() override; ~FancyLineEdit() override;
void setTextKeepingActiveCursor(const QString &text);
QIcon buttonIcon(Side side) const; QIcon buttonIcon(Side side) const;
void setButtonIcon(Side side, const QIcon &icon); void setButtonIcon(Side side, const QIcon &icon);

View File

@@ -26,7 +26,6 @@
#include "pathchooser.h" #include "pathchooser.h"
#include "environment.h" #include "environment.h"
#include "optional.h"
#include "qtcassert.h" #include "qtcassert.h"
#include "macroexpander.h" #include "macroexpander.h"
@@ -348,22 +347,14 @@ QString PathChooser::expandedDirectory(const QString &input, const Environment &
return path; return path;
} }
void setTextKeepingActiveCursor(QLineEdit *edit, const QString &text)
{
optional<int> cursor = edit->hasFocus() ? make_optional(edit->cursorPosition()) : nullopt;
edit->setText(text);
if (cursor)
edit->setCursorPosition(*cursor);
}
void PathChooser::setPath(const QString &path) void PathChooser::setPath(const QString &path)
{ {
setTextKeepingActiveCursor(d->m_lineEdit, QDir::toNativeSeparators(path)); d->m_lineEdit->setTextKeepingActiveCursor(QDir::toNativeSeparators(path));
} }
void PathChooser::setFileName(const FileName &fn) void PathChooser::setFileName(const FileName &fn)
{ {
setTextKeepingActiveCursor(d->m_lineEdit, fn.toUserOutput()); d->m_lineEdit->setTextKeepingActiveCursor(fn.toUserOutput());
} }
void PathChooser::setErrorColor(const QColor &errorColor) void PathChooser::setErrorColor(const QColor &errorColor)

View File

@@ -90,8 +90,7 @@ public:
SmallStringView(const String &string) noexcept SmallStringView(const String &string) noexcept
: m_pointer(string.data()), : m_pointer(string.data()),
m_size(string.size()) m_size(string.size())
{ {}
}
static static
SmallStringView fromUtf8(const char *const characterPointer) SmallStringView fromUtf8(const char *const characterPointer)

View File

@@ -148,6 +148,11 @@ public:
}; };
TreeItem::insertOrderedChild(item, cmp0); TreeItem::insertOrderedChild(item, cmp0);
} }
ChildType *reverseFindAnyChild(const std::function<bool(TreeItem *)> &pred) const
{
return static_cast<ChildType *>(TreeItem::reverseFindAnyChild(pred));
}
}; };
class QTCREATOR_UTILS_EXPORT StaticTreeItem : public TreeItem class QTCREATOR_UTILS_EXPORT StaticTreeItem : public TreeItem

View File

@@ -163,7 +163,7 @@ TestResultItem *TestResultItem::intermediateFor(const TestResultItem *item) cons
QTC_ASSERT(item, return nullptr); QTC_ASSERT(item, return nullptr);
const TestResult *otherResult = item->testResult(); const TestResult *otherResult = item->testResult();
for (int row = childCount() - 1; row >= 0; --row) { for (int row = childCount() - 1; row >= 0; --row) {
TestResultItem *child = static_cast<TestResultItem *>(childAt(row)); TestResultItem *child = childAt(row);
const TestResult *testResult = child->testResult(); const TestResult *testResult = child->testResult();
if (testResult->result() != Result::MessageIntermediate) if (testResult->result() != Result::MessageIntermediate)
continue; continue;
@@ -186,7 +186,7 @@ TestResultItem *TestResultItem::createAndAddIntermediateFor(const TestResultItem
/********************************* TestResultModel *****************************************/ /********************************* TestResultModel *****************************************/
TestResultModel::TestResultModel(QObject *parent) TestResultModel::TestResultModel(QObject *parent)
: Utils::TreeModel<>(parent) : Utils::TreeModel<TestResultItem>(new TestResultItem(TestResultPtr()), parent)
{ {
} }
@@ -194,16 +194,15 @@ void TestResultModel::updateParent(const TestResultItem *item)
{ {
QTC_ASSERT(item, return); QTC_ASSERT(item, return);
QTC_ASSERT(item->testResult(), return); QTC_ASSERT(item->testResult(), return);
Utils::TreeItem *parentItem = item->parent(); TestResultItem *parentItem = item->parent();
if (parentItem == rootItem()) // do not update invisible root item if (parentItem == rootItem()) // do not update invisible root item
return; return;
bool changed = false; bool changed = false;
TestResultItem *parentResultItem = static_cast<TestResultItem *>(parentItem); parentItem->updateResult(changed, item->testResult()->result());
parentResultItem->updateResult(changed, item->testResult()->result());
if (!changed) if (!changed)
return; return;
emit dataChanged(parentItem->index(), parentItem->index()); emit dataChanged(parentItem->index(), parentItem->index());
updateParent(parentResultItem); updateParent(parentItem);
} }
void TestResultModel::addTestResult(const TestResultPtr &testResult, bool autoExpand) void TestResultModel::addTestResult(const TestResultPtr &testResult, bool autoExpand)
@@ -212,7 +211,7 @@ void TestResultModel::addTestResult(const TestResultPtr &testResult, bool autoEx
if (testResult->result() == Result::MessageCurrentTest) { if (testResult->result() == Result::MessageCurrentTest) {
// MessageCurrentTest should always be the last top level item // MessageCurrentTest should always be the last top level item
if (lastRow >= 0) { if (lastRow >= 0) {
TestResultItem *current = static_cast<TestResultItem *>(rootItem()->childAt(lastRow)); TestResultItem *current = rootItem()->childAt(lastRow);
const TestResult *result = current->testResult(); const TestResult *result = current->testResult();
if (result && result->result() == Result::MessageCurrentTest) { if (result && result->result() == Result::MessageCurrentTest) {
current->updateDescription(testResult->description()); current->updateDescription(testResult->description());
@@ -235,14 +234,11 @@ void TestResultModel::addTestResult(const TestResultPtr &testResult, bool autoEx
if (AutotestPlugin::settings()->displayApplication) { if (AutotestPlugin::settings()->displayApplication) {
const QString application = testResult->id(); const QString application = testResult->id();
if (!application.isEmpty()) { if (!application.isEmpty()) {
for (int row = rootItem()->childCount() - 1; row >= 0; --row) { root = rootItem()->findFirstLevelChild([&application](TestResultItem *child) {
TestResultItem *tmp = static_cast<TestResultItem *>(rootItem()->childAt(row)); QTC_ASSERT(child, return false);
auto tmpTestResult = tmp->testResult(); return child->testResult()->id() == application;
if (tmpTestResult->id() == application) { });
root = tmp;
break;
}
}
if (!root) { if (!root) {
TestResult *tmpAppResult = new TestResult(application, application); TestResult *tmpAppResult = new TestResult(application, application);
tmpAppResult->setResult(Result::Application); tmpAppResult->setResult(Result::Application);
@@ -264,7 +260,7 @@ void TestResultModel::addTestResult(const TestResultPtr &testResult, bool autoEx
updateParent(newItem); updateParent(newItem);
} else { } else {
if (lastRow >= 0) { if (lastRow >= 0) {
TestResultItem *current = static_cast<TestResultItem *>(rootItem()->childAt(lastRow)); TestResultItem *current = rootItem()->childAt(lastRow);
const TestResult *result = current->testResult(); const TestResult *result = current->testResult();
if (result && result->result() == Result::MessageCurrentTest) { if (result && result->result() == Result::MessageCurrentTest) {
rootItem()->insertChild(current->index().row(), newItem); rootItem()->insertChild(current->index().row(), newItem);
@@ -278,15 +274,11 @@ void TestResultModel::addTestResult(const TestResultPtr &testResult, bool autoEx
void TestResultModel::removeCurrentTestMessage() void TestResultModel::removeCurrentTestMessage()
{ {
std::vector<Utils::TreeItem *> topLevelItems(rootItem()->begin(), rootItem()->end()); TestResultItem *currentMessageItem = rootItem()->findFirstLevelChild([](TestResultItem *it) {
auto end = topLevelItems.rend(); return (it->testResult()->result() == Result::MessageCurrentTest);
for (auto it = topLevelItems.rbegin(); it != end; ++it) { });
TestResultItem *current = static_cast<TestResultItem *>(*it); if (currentMessageItem)
if (current->testResult()->result() == Result::MessageCurrentTest) { destroyItem(currentMessageItem);
destroyItem(current);
break;
}
}
} }
void TestResultModel::clearTestResults() void TestResultModel::clearTestResults()
@@ -302,7 +294,7 @@ void TestResultModel::clearTestResults()
const TestResult *TestResultModel::testResult(const QModelIndex &idx) const TestResult *TestResultModel::testResult(const QModelIndex &idx)
{ {
if (idx.isValid()) if (idx.isValid())
return static_cast<TestResultItem *>(itemForIndex(idx))->testResult(); return itemForIndex(idx)->testResult();
return nullptr; return nullptr;
} }
@@ -353,7 +345,7 @@ TestResultItem *TestResultModel::findParentItemFor(const TestResultItem *item,
if (root == nullptr && !name.isEmpty()) { if (root == nullptr && !name.isEmpty()) {
for (int row = rootItem()->childCount() - 1; row >= 0; --row) { for (int row = rootItem()->childCount() - 1; row >= 0; --row) {
TestResultItem *tmp = static_cast<TestResultItem *>(rootItem()->childAt(row)); TestResultItem *tmp = rootItem()->childAt(row);
auto tmpTestResult = tmp->testResult(); auto tmpTestResult = tmp->testResult();
if (tmpTestResult->id() == id && tmpTestResult->name() == name) { if (tmpTestResult->id() == id && tmpTestResult->name() == name) {
root = tmp; root = tmp;
@@ -369,7 +361,7 @@ TestResultItem *TestResultModel::findParentItemFor(const TestResultItem *item,
TestResultItem *currentItem = static_cast<TestResultItem *>(it); TestResultItem *currentItem = static_cast<TestResultItem *>(it);
return currentItem->testResult()->isDirectParentOf(result, &needsIntermediate); return currentItem->testResult()->isDirectParentOf(result, &needsIntermediate);
}; };
TestResultItem *parent = static_cast<TestResultItem *>(root->reverseFindAnyChild(predicate)); TestResultItem *parent = root->reverseFindAnyChild(predicate);
if (parent) { if (parent) {
if (needsIntermediate) { if (needsIntermediate) {
// check if the intermediate is present already // check if the intermediate is present already

View File

@@ -37,7 +37,7 @@
namespace Autotest { namespace Autotest {
namespace Internal { namespace Internal {
class TestResultItem : public Utils::TreeItem class TestResultItem : public Utils::TypedTreeItem<TestResultItem, TestResultItem>
{ {
public: public:
explicit TestResultItem(const TestResultPtr &testResult); explicit TestResultItem(const TestResultPtr &testResult);
@@ -53,7 +53,7 @@ private:
TestResultPtr m_testResult; TestResultPtr m_testResult;
}; };
class TestResultModel : public Utils::TreeModel<> class TestResultModel : public Utils::TreeModel<TestResultItem>
{ {
public: public:
explicit TestResultModel(QObject *parent = nullptr); explicit TestResultModel(QObject *parent = nullptr);

View File

@@ -291,11 +291,26 @@ void MakefileParser::parseSubDirs()
foreach (const QString& source, parser.sources()) foreach (const QString& source, parser.sources())
m_sources.append(subDir + slash + source); m_sources.append(subDir + slash + source);
// Append the include paths of the sub directory
m_includePaths.append(parser.includePaths());
// Append the flags of the sub directory
m_cflags.append(parser.cflags());
m_cxxflags.append(parser.cxxflags());
// Append the macros of the sub directory
foreach (const auto& m, parser.macros())
{
if (!m_macros.contains(m))
m_macros.append(m);
}
}
// Duplicates might be possible in combination with several // Duplicates might be possible in combination with several
// "..._SUBDIRS" targets // "..._SUBDIRS" targets
m_makefiles.removeDuplicates(); m_makefiles.removeDuplicates();
m_sources.removeDuplicates(); m_sources.removeDuplicates();
}
if (subDirs.isEmpty()) if (subDirs.isEmpty())
m_success = false; m_success = false;

View File

@@ -63,9 +63,7 @@ enum { backEndStartTimeOutInMs = 10000 };
static QString backendProcessPath() static QString backendProcessPath()
{ {
return Core::ICore::libexecPath() return Core::ICore::libexecPath() + "/clangbackend" + QTC_HOST_EXE_SUFFIX;
+ QStringLiteral("/clangbackend")
+ QStringLiteral(QTC_HOST_EXE_SUFFIX);
} }
namespace ClangCodeModel { namespace ClangCodeModel {
@@ -121,7 +119,7 @@ BackendCommunicator::~BackendCommunicator()
void BackendCommunicator::initializeBackend() void BackendCommunicator::initializeBackend()
{ {
const QString clangBackEndProcessPath = backendProcessPath(); const QString clangBackEndProcessPath = backendProcessPath();
if (!QFileInfo(clangBackEndProcessPath).exists()) { if (!QFileInfo::exists(clangBackEndProcessPath)) {
logExecutableDoesNotExist(); logExecutableDoesNotExist();
return; return;
} }

View File

@@ -133,7 +133,6 @@ void disableDiagnosticInCurrentProjectConfig(const ClangBackEnd::DiagnosticConta
currentConfigId = globalSettings->clangDiagnosticConfigId(); currentConfigId = globalSettings->clangDiagnosticConfigId();
// Get config // Get config
const ClangDiagnosticConfigs originalConfigs = globalSettings->clangCustomDiagnosticConfigs();
ClangDiagnosticConfigsModel configsModel(globalSettings->clangCustomDiagnosticConfigs()); ClangDiagnosticConfigsModel configsModel(globalSettings->clangCustomDiagnosticConfigs());
QTC_ASSERT(configsModel.hasConfigWithId(currentConfigId), return ); QTC_ASSERT(configsModel.hasConfigWithId(currentConfigId), return );
ClangDiagnosticConfig config = configsModel.configWithId(currentConfigId); ClangDiagnosticConfig config = configsModel.configWithId(currentConfigId);

View File

@@ -471,6 +471,13 @@ QList<Diagnostic> ClangTidyClazyTool::read(const QString &filePath,
return readSerializedDiagnostics(filePath, projectRootDir, logFilePath, errorMessage); return readSerializedDiagnostics(filePath, projectRootDir, logFilePath, errorMessage);
} }
void ClangTidyClazyTool::onNewDiagnosticsAvailable(const QList<Diagnostic> &diagnostics)
{
ClangTool::onNewDiagnosticsAvailable(diagnostics);
if (!m_diagnosticFilterModel->filterRegExp().pattern().isEmpty())
m_diagnosticFilterModel->invalidateFilter();
}
} // namespace Internal } // namespace Internal
} // namespace ClangTools } // namespace ClangTools

View File

@@ -58,6 +58,8 @@ public:
const QString &logFilePath, const QString &logFilePath,
QString *errorMessage) const final; QString *errorMessage) const final;
void onNewDiagnosticsAvailable(const QList<Diagnostic> &diagnostics) override;
private: private:
void handleStateUpdate() final; void handleStateUpdate() final;

View File

@@ -62,7 +62,7 @@ public:
const QString &name() const; const QString &name() const;
void onNewDiagnosticsAvailable(const QList<Diagnostic> &diagnostics); virtual void onNewDiagnosticsAvailable(const QList<Diagnostic> &diagnostics);
signals: signals:
void finished(bool success); // For testing. void finished(bool success); // For testing.

View File

@@ -57,6 +57,8 @@ QVariant FilePathItem::data(int column, int role) const
return m_filePath; return m_filePath;
case Qt::DecorationRole: case Qt::DecorationRole:
return Core::FileIconProvider::icon(m_filePath); return Core::FileIconProvider::icon(m_filePath);
case Debugger::DetailedErrorView::FullTextRole:
return m_filePath;
default: default:
return QVariant(); return QVariant();
} }
@@ -68,12 +70,14 @@ QVariant FilePathItem::data(int column, int role) const
class ExplainingStepItem : public Utils::TreeItem class ExplainingStepItem : public Utils::TreeItem
{ {
public: public:
ExplainingStepItem(const ExplainingStep &step); ExplainingStepItem(const ExplainingStep &step, int index);
int index() const { return m_index; }
private: private:
QVariant data(int column, int role) const override; QVariant data(int column, int role) const override;
const ExplainingStep m_step; const ExplainingStep m_step;
const int m_index = 0;
}; };
ClangToolsDiagnosticModel::ClangToolsDiagnosticModel(QObject *parent) ClangToolsDiagnosticModel::ClangToolsDiagnosticModel(QObject *parent)
@@ -295,15 +299,24 @@ static QString createExplainingStepString(const ExplainingStep &explainingStep,
{ {
return createExplainingStepNumberString(number) return createExplainingStepNumberString(number)
+ QLatin1Char(' ') + QLatin1Char(' ')
+ explainingStep.extendedMessage + explainingStep.message
+ QLatin1Char(' ') + QLatin1Char(' ')
+ createLocationString(explainingStep.location); + createLocationString(explainingStep.location);
} }
static QString lineColumnString(const Debugger::DiagnosticLocation &location)
{
return QString("%1:%2").arg(QString::number(location.line), QString::number(location.column));
}
static QString fullText(const Diagnostic &diagnostic) static QString fullText(const Diagnostic &diagnostic)
{ {
// Summary. QString text = diagnostic.location.filePath + QLatin1Char(':');
QString text = diagnostic.category + QLatin1String(": ") + diagnostic.type; text += lineColumnString(diagnostic.location) + QLatin1String(": ");
if (!diagnostic.category.isEmpty())
text += diagnostic.category + QLatin1String(": ");
text += diagnostic.type;
if (diagnostic.type != diagnostic.description) if (diagnostic.type != diagnostic.description)
text += QLatin1String(": ") + diagnostic.description; text += QLatin1String(": ") + diagnostic.description;
text += QLatin1Char('\n'); text += QLatin1Char('\n');
@@ -339,8 +352,8 @@ DiagnosticItem::DiagnosticItem(const Diagnostic &diag,
if (!diag.explainingSteps.isEmpty()) if (!diag.explainingSteps.isEmpty())
m_parentModel->stepsToItemsCache[diag.explainingSteps].push_back(this); m_parentModel->stepsToItemsCache[diag.explainingSteps].push_back(this);
foreach (const ExplainingStep &s, diag.explainingSteps) for (int i = 0; i < diag.explainingSteps.size(); ++i )
appendChild(new ExplainingStepItem(s)); appendChild(new ExplainingStepItem(diag.explainingSteps[i], i));
} }
DiagnosticItem::~DiagnosticItem() DiagnosticItem::~DiagnosticItem()
@@ -380,11 +393,6 @@ static QVariant iconData(const QString &type)
return QVariant(); return QVariant();
} }
static QString lineColumnString(const Debugger::DiagnosticLocation &location)
{
return QString("%1:%2").arg(QString::number(location.line), QString::number(location.column));
}
QVariant DiagnosticItem::data(int column, int role) const QVariant DiagnosticItem::data(int column, int role) const
{ {
if (column == DiagnosticView::FixItColumn) { if (column == DiagnosticView::FixItColumn) {
@@ -481,9 +489,10 @@ bool DiagnosticItem::hasNewFixIts() const
return m_parentModel->stepsToItemsCache[m_diagnostic.explainingSteps].front() == this; return m_parentModel->stepsToItemsCache[m_diagnostic.explainingSteps].front() == this;
} }
ExplainingStepItem::ExplainingStepItem(const ExplainingStep &step) : m_step(step) ExplainingStepItem::ExplainingStepItem(const ExplainingStep &step, int index)
{ : m_step(step)
} , m_index(index)
{}
// We expect something like "note: ..." // We expect something like "note: ..."
static QVariant iconForExplainingStepMessage(const QString &message) static QVariant iconForExplainingStepMessage(const QString &message)
@@ -509,28 +518,37 @@ QVariant ExplainingStepItem::data(int column, int role) const
switch (role) { switch (role) {
case Debugger::DetailedErrorView::LocationRole: case Debugger::DetailedErrorView::LocationRole:
return QVariant::fromValue(m_step.location); return QVariant::fromValue(m_step.location);
case Debugger::DetailedErrorView::FullTextRole: case Debugger::DetailedErrorView::FullTextRole: {
return fullText(static_cast<DiagnosticItem *>(parent())->diagnostic()); return QString("%1:%2: %3")
.arg(m_step.location.filePath, lineColumnString(m_step.location), m_step.message);
}
case ClangToolsDiagnosticModel::TextRole: case ClangToolsDiagnosticModel::TextRole:
return m_step.message; return m_step.message;
case ClangToolsDiagnosticModel::DiagnosticRole: case ClangToolsDiagnosticModel::DiagnosticRole:
return QVariant::fromValue(static_cast<DiagnosticItem *>(parent())->diagnostic()); return QVariant::fromValue(static_cast<DiagnosticItem *>(parent())->diagnostic());
case Qt::DisplayRole: { case Qt::DisplayRole: {
const QString mainFilePath = static_cast<DiagnosticItem *>(parent())->diagnostic().location.filePath;
const QString locationString
= m_step.location.filePath == mainFilePath
? lineColumnString(m_step.location)
: QString("%1:%2").arg(QFileInfo(m_step.location.filePath).fileName(),
lineColumnString(m_step.location));
if (m_step.isFixIt) { if (m_step.isFixIt) {
if (m_step.ranges[0] == m_step.ranges[1]) { if (m_step.ranges[0] == m_step.ranges[1]) {
return QString("%1: Insertion of \"%2\".") return QString("%1: Insertion of \"%2\".")
.arg(lineColumnString(m_step.location), m_step.message); .arg(locationString, m_step.message);
} }
if (m_step.message.isEmpty()) { if (m_step.message.isEmpty()) {
return QString("%1: Removal of %2.") return QString("%1: Removal of %2.")
.arg(lineColumnString(m_step.location), rangeString(m_step.ranges)); .arg(locationString, rangeString(m_step.ranges));
} }
return QString("%1: Replacement of %2 with: \"%3\".") return QString("%1: Replacement of %2 with: \"%3\".")
.arg(lineColumnString(m_step.location), .arg(locationString,
rangeString(m_step.ranges), rangeString(m_step.ranges),
m_step.message); m_step.message);
} }
return QString("%1: %2").arg(lineColumnString(m_step.location), m_step.message); return QString("%1: %2").arg(locationString, m_step.message);
} }
case Qt::ToolTipRole: case Qt::ToolTipRole:
return createExplainingStepToolTipString(m_step); return createExplainingStepToolTipString(m_step);
@@ -546,7 +564,6 @@ QVariant ExplainingStepItem::data(int column, int role) const
return QVariant(); return QVariant();
} }
DiagnosticFilterModel::DiagnosticFilterModel(QObject *parent) DiagnosticFilterModel::DiagnosticFilterModel(QObject *parent)
: QSortFilterProxyModel(parent) : QSortFilterProxyModel(parent)
{ {
@@ -584,14 +601,32 @@ void DiagnosticFilterModel::addSuppressedDiagnostic(
invalidate(); invalidate();
} }
void DiagnosticFilterModel::invalidateFilter()
{
QSortFilterProxyModel::invalidateFilter();
}
bool DiagnosticFilterModel::filterAcceptsRow(int sourceRow, bool DiagnosticFilterModel::filterAcceptsRow(int sourceRow,
const QModelIndex &sourceParent) const const QModelIndex &sourceParent) const
{ {
auto model = static_cast<ClangToolsDiagnosticModel *>(sourceModel()); auto model = static_cast<ClangToolsDiagnosticModel *>(sourceModel());
Utils::TreeItem *item = model->itemForIndex(sourceParent);
// FilePathItem - hide if no diagnostics match
if (!sourceParent.isValid()) {
const QModelIndex filePathIndex = model->index(sourceRow, 0);
const int rowCount = model->rowCount(filePathIndex);
if (rowCount == 0)
return true; // Children not yet added.
for (int row = 0; row < rowCount; ++row) {
if (filterAcceptsRow(row, filePathIndex))
return true;
}
return false;
}
// DiagnosticItem // DiagnosticItem
if (auto filePathItem = dynamic_cast<FilePathItem *>(item)) { Utils::TreeItem *parentItem = model->itemForIndex(sourceParent);
if (auto filePathItem = dynamic_cast<FilePathItem *>(parentItem)) {
auto diagnosticItem = dynamic_cast<DiagnosticItem *>(filePathItem->childAt(sourceRow)); auto diagnosticItem = dynamic_cast<DiagnosticItem *>(filePathItem->childAt(sourceRow));
QTC_ASSERT(diagnosticItem, return false); QTC_ASSERT(diagnosticItem, return false);
@@ -612,7 +647,7 @@ bool DiagnosticFilterModel::filterAcceptsRow(int sourceRow,
return diag.description.contains(filterRegExp()); return diag.description.contains(filterRegExp());
} }
return true; return true; // ExplainingStepItem
} }
bool DiagnosticFilterModel::lessThan(const QModelIndex &l, const QModelIndex &r) const bool DiagnosticFilterModel::lessThan(const QModelIndex &l, const QModelIndex &r) const
@@ -622,22 +657,34 @@ bool DiagnosticFilterModel::lessThan(const QModelIndex &l, const QModelIndex &r)
const bool isComparingDiagnostics = !dynamic_cast<FilePathItem *>(itemLeft); const bool isComparingDiagnostics = !dynamic_cast<FilePathItem *>(itemLeft);
if (sortColumn() == Debugger::DetailedErrorView::DiagnosticColumn && isComparingDiagnostics) { if (sortColumn() == Debugger::DetailedErrorView::DiagnosticColumn && isComparingDiagnostics) {
bool result = false;
if (dynamic_cast<DiagnosticItem *>(itemLeft)) {
using Debugger::DiagnosticLocation; using Debugger::DiagnosticLocation;
const int role = Debugger::DetailedErrorView::LocationRole; const int role = Debugger::DetailedErrorView::LocationRole;
const auto leftLoc = sourceModel()->data(l, role).value<DiagnosticLocation>(); const auto leftLoc = sourceModel()->data(l, role).value<DiagnosticLocation>();
const auto leftText = sourceModel()->data(l, ClangToolsDiagnosticModel::TextRole).toString(); const auto leftText
= sourceModel()->data(l, ClangToolsDiagnosticModel::TextRole).toString();
const auto rightLoc = sourceModel()->data(r, role).value<DiagnosticLocation>(); const auto rightLoc = sourceModel()->data(r, role).value<DiagnosticLocation>();
const auto rightText = sourceModel()->data(r, ClangToolsDiagnosticModel::TextRole).toString(); const auto rightText
= sourceModel()->data(r, ClangToolsDiagnosticModel::TextRole).toString();
const int result = std::tie(leftLoc.line, leftLoc.column, leftText) result = std::tie(leftLoc.line, leftLoc.column, leftText)
< std::tie(rightLoc.line, rightLoc.column, rightText); < std::tie(rightLoc.line, rightLoc.column, rightText);
} else if (auto left = dynamic_cast<ExplainingStepItem *>(itemLeft)) {
const auto right = dynamic_cast<ExplainingStepItem *>(model->itemForIndex(r));
result = left->index() < right->index();
} else {
QTC_CHECK(false && "Unexpected item");
}
if (sortOrder() == Qt::DescendingOrder) if (sortOrder() == Qt::DescendingOrder)
return !result; // Ensure that we always sort location from top to bottom. return !result; // Do not change the order of these item as this might be confusing.
return result; return result;
} }
// FilePathItem
return QSortFilterProxyModel::lessThan(l, r); return QSortFilterProxyModel::lessThan(l, r);
} }

View File

@@ -146,6 +146,8 @@ public:
void addSuppressedDiagnostic(const SuppressedDiagnostic &diag); void addSuppressedDiagnostic(const SuppressedDiagnostic &diag);
ProjectExplorer::Project *project() const { return m_project; } ProjectExplorer::Project *project() const { return m_project; }
void invalidateFilter();
private: private:
bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const override; bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const override;
bool lessThan(const QModelIndex &l, const QModelIndex &r) const override; bool lessThan(const QModelIndex &l, const QModelIndex &r) const override;

View File

@@ -36,6 +36,7 @@
#include <QVBoxLayout> #include <QVBoxLayout>
#include <QLabel> #include <QLabel>
#include <QToolButton> #include <QToolButton>
#include <QComboBox>
static const char C_SUPPRESSED_WARNINGS[] = "SuppressedWarnings"; static const char C_SUPPRESSED_WARNINGS[] = "SuppressedWarnings";
@@ -73,6 +74,12 @@ void InfoBarEntry::setCancelButtonInfo(const QString &_cancelButtonText, CallBac
m_cancelButtonCallBack = callBack; m_cancelButtonCallBack = callBack;
} }
void InfoBarEntry::setComboInfo(const QStringList &list, InfoBarEntry::ComboCallBack callBack)
{
m_comboCallBack = callBack;
m_comboInfo = list;
}
void InfoBarEntry::removeCancelButton() void InfoBarEntry::removeCancelButton()
{ {
m_useCancelButton = false; m_useCancelButton = false;
@@ -242,7 +249,7 @@ void InfoBarDisplay::update()
QLabel *infoWidgetLabel = new QLabel(info.m_infoText); QLabel *infoWidgetLabel = new QLabel(info.m_infoText);
infoWidgetLabel->setWordWrap(true); infoWidgetLabel->setWordWrap(true);
hbox->addWidget(infoWidgetLabel); hbox->addWidget(infoWidgetLabel, 1);
if (info.m_detailsWidgetCreator) { if (info.m_detailsWidgetCreator) {
if (m_isShowingDetailsWidget) { if (m_isShowingDetailsWidget) {
@@ -270,6 +277,16 @@ void InfoBarDisplay::update()
m_isShowingDetailsWidget = false; m_isShowingDetailsWidget = false;
} }
if (!info.m_comboInfo.isEmpty()) {
auto cb = new QComboBox();
cb->addItems(info.m_comboInfo);
connect(cb, &QComboBox::currentTextChanged, [info](const QString &text) {
info.m_comboCallBack(text);
});
hbox->addWidget(cb);
}
if (!info.m_buttonText.isEmpty()) { if (!info.m_buttonText.isEmpty()) {
auto infoWidgetButton = new QToolButton; auto infoWidgetButton = new QToolButton;
infoWidgetButton->setText(info.m_buttonText); infoWidgetButton->setText(info.m_buttonText);

View File

@@ -61,6 +61,8 @@ public:
void setCustomButtonInfo(const QString &_buttonText, CallBack callBack); void setCustomButtonInfo(const QString &_buttonText, CallBack callBack);
void setCancelButtonInfo(CallBack callBack); void setCancelButtonInfo(CallBack callBack);
void setCancelButtonInfo(const QString &_cancelButtonText, CallBack callBack); void setCancelButtonInfo(const QString &_cancelButtonText, CallBack callBack);
using ComboCallBack = std::function<void(const QString &)>;
void setComboInfo(const QStringList &list, ComboCallBack callBack);
void removeCancelButton(); void removeCancelButton();
using DetailsWidgetCreator = std::function<QWidget*()>; using DetailsWidgetCreator = std::function<QWidget*()>;
@@ -76,6 +78,8 @@ private:
GlobalSuppressionMode m_globalSuppression; GlobalSuppressionMode m_globalSuppression;
DetailsWidgetCreator m_detailsWidgetCreator; DetailsWidgetCreator m_detailsWidgetCreator;
bool m_useCancelButton = true; bool m_useCancelButton = true;
ComboCallBack m_comboCallBack;
QStringList m_comboInfo;
friend class InfoBar; friend class InfoBar;
friend class InfoBarDisplay; friend class InfoBarDisplay;
}; };

View File

@@ -33,8 +33,6 @@ namespace Internal {
class CppAutoCompleter : public TextEditor::AutoCompleter class CppAutoCompleter : public TextEditor::AutoCompleter
{ {
public: public:
CppAutoCompleter() {}
bool contextAllowsAutoBrackets(const QTextCursor &cursor, bool contextAllowsAutoBrackets(const QTextCursor &cursor,
const QString &textToInsert = QString()) const override; const QString &textToInsert = QString()) const override;
bool contextAllowsAutoQuotes(const QTextCursor &cursor, bool contextAllowsAutoQuotes(const QTextCursor &cursor,

View File

@@ -85,8 +85,6 @@ QSizePolicy sizePolicyWithStretchFactor(int stretchFactor)
class DepthFinder : public SymbolVisitor { class DepthFinder : public SymbolVisitor {
public: public:
DepthFinder() : m_symbol(0), m_depth(-1), m_foundDepth(-1), m_stop(false) {}
int operator()(const Document::Ptr &document, Symbol *symbol) int operator()(const Document::Ptr &document, Symbol *symbol)
{ {
m_symbol = symbol; m_symbol = symbol;
@@ -94,7 +92,7 @@ public:
return m_foundDepth; return m_foundDepth;
} }
bool preVisit(Symbol *symbol) bool preVisit(Symbol *symbol) override
{ {
if (m_stop) if (m_stop)
return false; return false;
@@ -111,17 +109,17 @@ public:
return false; return false;
} }
void postVisit(Symbol *symbol) void postVisit(Symbol *symbol) override
{ {
if (symbol->asScope()) if (symbol->asScope())
--m_depth; --m_depth;
} }
private: private:
Symbol *m_symbol; Symbol *m_symbol = nullptr;
int m_depth; int m_depth = -1;
int m_foundDepth; int m_foundDepth = -1;
bool m_stop; bool m_stop = false;
}; };
} // anonymous namespace } // anonymous namespace
@@ -169,12 +167,12 @@ FilterableView::FilterableView(QWidget *parent)
QPushButton *clearButton = new QPushButton(QLatin1String("&Clear"), this); QPushButton *clearButton = new QPushButton(QLatin1String("&Clear"), this);
QObject::connect(clearButton, &QAbstractButton::clicked, this, &FilterableView::clearFilter); QObject::connect(clearButton, &QAbstractButton::clicked, this, &FilterableView::clearFilter);
QHBoxLayout *filterBarLayout = new QHBoxLayout(); auto filterBarLayout = new QHBoxLayout();
filterBarLayout->addWidget(label); filterBarLayout->addWidget(label);
filterBarLayout->addWidget(lineEdit); filterBarLayout->addWidget(lineEdit);
filterBarLayout->addWidget(clearButton); filterBarLayout->addWidget(clearButton);
QVBoxLayout *mainLayout = new QVBoxLayout(); auto mainLayout = new QVBoxLayout();
mainLayout->addWidget(view); mainLayout->addWidget(view);
mainLayout->addLayout(filterBarLayout); mainLayout->addLayout(filterBarLayout);
@@ -222,10 +220,10 @@ public:
enum Columns { FileKindColumn, FilePathColumn, ColumnCount }; enum Columns { FileKindColumn, FilePathColumn, ColumnCount };
int rowCount(const QModelIndex &parent = QModelIndex()) const; int rowCount(const QModelIndex &parent = QModelIndex()) const override;
int columnCount(const QModelIndex &parent = QModelIndex()) const; int columnCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
QVariant headerData(int section, Qt::Orientation orientation, int role) const; QVariant headerData(int section, Qt::Orientation orientation, int role) const override;
private: private:
ProjectFiles m_files; ProjectFiles m_files;
@@ -305,10 +303,10 @@ public:
enum Columns { TypeColumn, PathColumn, ColumnCount }; enum Columns { TypeColumn, PathColumn, ColumnCount };
int rowCount(const QModelIndex &parent = QModelIndex()) const; int rowCount(const QModelIndex &parent = QModelIndex()) const override;
int columnCount(const QModelIndex &parent = QModelIndex()) const; int columnCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
QVariant headerData(int section, Qt::Orientation orientation, int role) const; QVariant headerData(int section, Qt::Orientation orientation, int role) const override;
private: private:
ProjectExplorer::HeaderPaths m_paths; ProjectExplorer::HeaderPaths m_paths;
@@ -377,7 +375,7 @@ class KeyValueModel : public QAbstractListModel
{ {
Q_OBJECT Q_OBJECT
public: public:
typedef QList<QPair<QString, QString> > Table; using Table = QList<QPair<QString, QString>>;
KeyValueModel(QObject *parent); KeyValueModel(QObject *parent);
void configure(const Table &table); void configure(const Table &table);
@@ -385,10 +383,10 @@ public:
enum Columns { KeyColumn, ValueColumn, ColumnCount }; enum Columns { KeyColumn, ValueColumn, ColumnCount };
int rowCount(const QModelIndex &parent = QModelIndex()) const; int rowCount(const QModelIndex &parent = QModelIndex()) const override;
int columnCount(const QModelIndex &parent = QModelIndex()) const; int columnCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
QVariant headerData(int section, Qt::Orientation orientation, int role) const; QVariant headerData(int section, Qt::Orientation orientation, int role) const override;
private: private:
Table m_table; Table m_table;
@@ -465,10 +463,10 @@ public:
enum Columns { SymbolCountColumn, SharedColumn, FilePathColumn, ColumnCount }; enum Columns { SymbolCountColumn, SharedColumn, FilePathColumn, ColumnCount };
int rowCount(const QModelIndex &parent = QModelIndex()) const; int rowCount(const QModelIndex &parent = QModelIndex()) const override;
int columnCount(const QModelIndex &parent = QModelIndex()) const; int columnCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
QVariant headerData(int section, Qt::Orientation orientation, int role) const; QVariant headerData(int section, Qt::Orientation orientation, int role) const override;
private: private:
QList<Document::Ptr> m_documents; QList<Document::Ptr> m_documents;
@@ -498,7 +496,7 @@ QModelIndex SnapshotModel::indexForDocument(const QString &filePath)
if (document->fileName() == filePath) if (document->fileName() == filePath)
return index(i, FilePathColumn); return index(i, FilePathColumn);
} }
return QModelIndex(); return {};
} }
int SnapshotModel::rowCount(const QModelIndex &/*parent*/) const int SnapshotModel::rowCount(const QModelIndex &/*parent*/) const
@@ -565,10 +563,10 @@ public:
enum Columns { ResolvedOrNotColumn, LineNumberColumn, FilePathsColumn, ColumnCount }; enum Columns { ResolvedOrNotColumn, LineNumberColumn, FilePathsColumn, ColumnCount };
int rowCount(const QModelIndex &parent = QModelIndex()) const; int rowCount(const QModelIndex &parent = QModelIndex()) const override;
int columnCount(const QModelIndex &parent = QModelIndex()) const; int columnCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
QVariant headerData(int section, Qt::Orientation orientation, int role) const; QVariant headerData(int section, Qt::Orientation orientation, int role) const override;
private: private:
QList<Document::Include> m_includes; QList<Document::Include> m_includes;
@@ -667,10 +665,10 @@ public:
enum Columns { LevelColumn, LineColumnNumberColumn, MessageColumn, ColumnCount }; enum Columns { LevelColumn, LineColumnNumberColumn, MessageColumn, ColumnCount };
int rowCount(const QModelIndex &parent = QModelIndex()) const; int rowCount(const QModelIndex &parent = QModelIndex()) const override;
int columnCount(const QModelIndex &parent = QModelIndex()) const; int columnCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
QVariant headerData(int section, Qt::Orientation orientation, int role) const; QVariant headerData(int section, Qt::Orientation orientation, int role) const override;
private: private:
QList<Document::DiagnosticMessage> m_messages; QList<Document::DiagnosticMessage> m_messages;
@@ -716,8 +714,7 @@ QVariant DiagnosticMessagesModel::data(const QModelIndex &index, int role) const
static const QBrush darkRedBrushQColor(QColor(139, 0, 0)); static const QBrush darkRedBrushQColor(QColor(139, 0, 0));
const Document::DiagnosticMessage message = m_messages.at(index.row()); const Document::DiagnosticMessage message = m_messages.at(index.row());
const Document::DiagnosticMessage::Level level const auto level = static_cast<Document::DiagnosticMessage::Level>(message.level());
= static_cast<Document::DiagnosticMessage::Level>(message.level());
if (role == Qt::DisplayRole) { if (role == Qt::DisplayRole) {
const int column = index.column(); const int column = index.column();
@@ -775,10 +772,10 @@ public:
enum Columns { LineNumberColumn, MacroColumn, ColumnCount }; enum Columns { LineNumberColumn, MacroColumn, ColumnCount };
int rowCount(const QModelIndex &parent = QModelIndex()) const; int rowCount(const QModelIndex &parent = QModelIndex()) const override;
int columnCount(const QModelIndex &parent = QModelIndex()) const; int columnCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
QVariant headerData(int section, Qt::Orientation orientation, int role) const; QVariant headerData(int section, Qt::Orientation orientation, int role) const override;
private: private:
QList<CPlusPlus::Macro> m_macros; QList<CPlusPlus::Macro> m_macros;
@@ -854,12 +851,12 @@ public:
enum Columns { SymbolColumn, LineNumberColumn, ColumnCount }; enum Columns { SymbolColumn, LineNumberColumn, ColumnCount };
QModelIndex index(int row, int column, const QModelIndex &parent) const; QModelIndex index(int row, int column, const QModelIndex &parent) const override;
QModelIndex parent(const QModelIndex &child) const; QModelIndex parent(const QModelIndex &child) const override;
int rowCount(const QModelIndex &parent = QModelIndex()) const; int rowCount(const QModelIndex &parent = QModelIndex()) const override;
int columnCount(const QModelIndex &parent = QModelIndex()) const; int columnCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
QVariant headerData(int section, Qt::Orientation orientation, int role) const; QVariant headerData(int section, Qt::Orientation orientation, int role) const override;
private: private:
Document::Ptr m_document; Document::Ptr m_document;
@@ -886,21 +883,19 @@ void SymbolsModel::clear()
static Symbol *indexToSymbol(const QModelIndex &index) static Symbol *indexToSymbol(const QModelIndex &index)
{ {
if (Symbol *symbol = static_cast<Symbol*>(index.internalPointer())) return static_cast<Symbol*>(index.internalPointer());
return symbol;
return 0;
} }
static Scope *indexToScope(const QModelIndex &index) static Scope *indexToScope(const QModelIndex &index)
{ {
if (Symbol *symbol = indexToSymbol(index)) if (Symbol *symbol = indexToSymbol(index))
return symbol->asScope(); return symbol->asScope();
return 0; return nullptr;
} }
QModelIndex SymbolsModel::index(int row, int column, const QModelIndex &parent) const QModelIndex SymbolsModel::index(int row, int column, const QModelIndex &parent) const
{ {
Scope *scope = 0; Scope *scope = nullptr;
if (parent.isValid()) if (parent.isValid())
scope = indexToScope(parent); scope = indexToScope(parent);
else if (m_document) else if (m_document)
@@ -911,13 +906,13 @@ QModelIndex SymbolsModel::index(int row, int column, const QModelIndex &parent)
return createIndex(row, column, scope->memberAt(row)); return createIndex(row, column, scope->memberAt(row));
} }
return QModelIndex(); return {};
} }
QModelIndex SymbolsModel::parent(const QModelIndex &child) const QModelIndex SymbolsModel::parent(const QModelIndex &child) const
{ {
if (!child.isValid()) if (!child.isValid())
return QModelIndex(); return {};
if (Symbol *symbol = indexToSymbol(child)) { if (Symbol *symbol = indexToSymbol(child)) {
if (Scope *scope = symbol->enclosingScope()) { if (Scope *scope = symbol->enclosingScope()) {
@@ -926,7 +921,7 @@ QModelIndex SymbolsModel::parent(const QModelIndex &child) const
} }
} }
return QModelIndex(); return {};
} }
int SymbolsModel::rowCount(const QModelIndex &parent) const int SymbolsModel::rowCount(const QModelIndex &parent) const
@@ -994,10 +989,10 @@ public:
BytesAndCodePointsColumn, GeneratedColumn, ExpandedColumn, WhiteSpaceColumn, BytesAndCodePointsColumn, GeneratedColumn, ExpandedColumn, WhiteSpaceColumn,
NewlineColumn, ColumnCount }; NewlineColumn, ColumnCount };
int rowCount(const QModelIndex &parent = QModelIndex()) const; int rowCount(const QModelIndex &parent = QModelIndex()) const override;
int columnCount(const QModelIndex &parent = QModelIndex()) const; int columnCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
QVariant headerData(int section, Qt::Orientation orientation, int role) const; QVariant headerData(int section, Qt::Orientation orientation, int role) const override;
private: private:
struct TokenInfo { struct TokenInfo {
@@ -1126,10 +1121,10 @@ public:
enum Columns { PartNameColumn, PartFilePathColumn, ColumnCount }; enum Columns { PartNameColumn, PartFilePathColumn, ColumnCount };
int rowCount(const QModelIndex &parent = QModelIndex()) const; int rowCount(const QModelIndex &parent = QModelIndex()) const override;
int columnCount(const QModelIndex &parent = QModelIndex()) const; int columnCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
QVariant headerData(int section, Qt::Orientation orientation, int role) const; QVariant headerData(int section, Qt::Orientation orientation, int role) const override;
private: private:
QList<ProjectPart::Ptr> m_projectPartsList; QList<ProjectPart::Ptr> m_projectPartsList;
@@ -1161,7 +1156,7 @@ void ProjectPartsModel::configure(const QList<ProjectInfo> &projectInfos,
QModelIndex ProjectPartsModel::indexForCurrentEditorsProjectPart() const QModelIndex ProjectPartsModel::indexForCurrentEditorsProjectPart() const
{ {
if (m_currentEditorsProjectPartIndex == -1) if (m_currentEditorsProjectPartIndex == -1)
return QModelIndex(); return {};
return createIndex(m_currentEditorsProjectPartIndex, PartFilePathColumn); return createIndex(m_currentEditorsProjectPartIndex, PartFilePathColumn);
} }
@@ -1232,10 +1227,10 @@ public:
enum Columns { RevisionColumn, FilePathColumn, ColumnCount }; enum Columns { RevisionColumn, FilePathColumn, ColumnCount };
int rowCount(const QModelIndex &parent = QModelIndex()) const; int rowCount(const QModelIndex &parent = QModelIndex()) const override;
int columnCount(const QModelIndex &parent = QModelIndex()) const; int columnCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
QVariant headerData(int section, Qt::Orientation orientation, int role) const; QVariant headerData(int section, Qt::Orientation orientation, int role) const override;
private: private:
struct WorkingCopyEntry { struct WorkingCopyEntry {
@@ -1275,7 +1270,7 @@ QModelIndex WorkingCopyModel::indexForFile(const QString &filePath)
if (entry.filePath == filePath) if (entry.filePath == filePath)
return index(i, FilePathColumn); return index(i, FilePathColumn);
} }
return QModelIndex(); return {};
} }
int WorkingCopyModel::rowCount(const QModelIndex &/*parent*/) const int WorkingCopyModel::rowCount(const QModelIndex &/*parent*/) const
@@ -1542,11 +1537,11 @@ void CppCodeModelInspectorDialog::refresh()
dumper.dumpSnapshot(globalSnapshot, globalSnapshotTitle, /*isGlobalSnapshot=*/ true); dumper.dumpSnapshot(globalSnapshot, globalSnapshotTitle, /*isGlobalSnapshot=*/ true);
TextEditor::BaseTextEditor *editor = currentEditor(); TextEditor::BaseTextEditor *editor = currentEditor();
CppTools::CppEditorDocumentHandle *cppEditorDocument = 0; CppTools::CppEditorDocumentHandle *cppEditorDocument = nullptr;
if (editor) { if (editor) {
const QString editorFilePath = editor->document()->filePath().toString(); const QString editorFilePath = editor->document()->filePath().toString();
cppEditorDocument = cmmi->cppEditorDocument(editorFilePath); cppEditorDocument = cmmi->cppEditorDocument(editorFilePath);
if (auto *documentProcessor = CppToolsBridge::baseEditorDocumentProcessor(editorFilePath)) { if (auto documentProcessor = CppToolsBridge::baseEditorDocumentProcessor(editorFilePath)) {
const Snapshot editorSnapshot = documentProcessor->snapshot(); const Snapshot editorSnapshot = documentProcessor->snapshot();
m_snapshotInfos->append(SnapshotInfo(editorSnapshot, SnapshotInfo::EditorSnapshot)); m_snapshotInfos->append(SnapshotInfo(editorSnapshot, SnapshotInfo::EditorSnapshot));
const QString editorSnapshotTitle const QString editorSnapshotTitle
@@ -1555,7 +1550,7 @@ void CppCodeModelInspectorDialog::refresh()
dumper.dumpSnapshot(editorSnapshot, editorSnapshotTitle); dumper.dumpSnapshot(editorSnapshot, editorSnapshotTitle);
m_ui->snapshotSelector->addItem(editorSnapshotTitle); m_ui->snapshotSelector->addItem(editorSnapshotTitle);
} }
CppEditorWidget *cppEditorWidget = qobject_cast<CppEditorWidget *>(editor->editorWidget()); auto cppEditorWidget = qobject_cast<CppEditorWidget *>(editor->editorWidget());
if (cppEditorWidget) { if (cppEditorWidget) {
SemanticInfo semanticInfo = cppEditorWidget->semanticInfo(); SemanticInfo semanticInfo = cppEditorWidget->semanticInfo();
Snapshot snapshot; Snapshot snapshot;
@@ -1855,7 +1850,7 @@ void CppCodeModelInspectorDialog::updateProjectPartData(const ProjectPart::Ptr &
bool CppCodeModelInspectorDialog::event(QEvent *e) bool CppCodeModelInspectorDialog::event(QEvent *e)
{ {
if (e->type() == QEvent::ShortcutOverride) { if (e->type() == QEvent::ShortcutOverride) {
QKeyEvent *ke = static_cast<QKeyEvent *>(e); auto ke = static_cast<QKeyEvent *>(e);
if (ke->key() == Qt::Key_Escape && !ke->modifiers()) { if (ke->key() == Qt::Key_Escape && !ke->modifiers()) {
ke->accept(); ke->accept();
close(); close();

View File

@@ -65,8 +65,8 @@ class CppCodeModelInspectorDialog : public QDialog
Q_OBJECT Q_OBJECT
public: public:
explicit CppCodeModelInspectorDialog(QWidget *parent = 0); explicit CppCodeModelInspectorDialog(QWidget *parent = nullptr);
~CppCodeModelInspectorDialog(); ~CppCodeModelInspectorDialog() override;
private: private:
void onRefreshRequested(); void onRefreshRequested();
@@ -90,7 +90,7 @@ private:
void clearProjectPartData(); void clearProjectPartData();
void updateProjectPartData(const CppTools::ProjectPart::Ptr &part); void updateProjectPartData(const CppTools::ProjectPart::Ptr &part);
bool event(QEvent *e); bool event(QEvent *e) override;
private: private:
Ui::CppCodeModelInspectorDialog *m_ui; Ui::CppCodeModelInspectorDialog *m_ui;

View File

@@ -173,7 +173,7 @@ bool handleDoxygenCppStyleContinuation(QTextCursor &cursor)
return false; return false;
QString newLine(QLatin1Char('\n')); QString newLine(QLatin1Char('\n'));
newLine.append(text.left(offset)); // indent correctly newLine.append(text.leftRef(offset)); // indent correctly
newLine.append(commentMarker); newLine.append(commentMarker);
newLine.append(QLatin1Char(' ')); newLine.append(QLatin1Char(' '));

View File

@@ -80,7 +80,10 @@ public:
mm()->registerCppEditorDocument(this); mm()->registerCppEditorDocument(this);
} }
~CppEditorDocumentHandleImpl() { mm()->unregisterCppEditorDocument(m_registrationFilePath); } ~CppEditorDocumentHandleImpl() override
{
mm()->unregisterCppEditorDocument(m_registrationFilePath);
}
QString filePath() const override { return m_cppEditorDocument->filePath().toString(); } QString filePath() const override { return m_cppEditorDocument->filePath().toString(); }
QByteArray contents() const override { return m_cppEditorDocument->contentsText(); } QByteArray contents() const override { return m_cppEditorDocument->contentsText(); }
@@ -100,12 +103,7 @@ private:
}; };
CppEditorDocument::CppEditorDocument() CppEditorDocument::CppEditorDocument()
: m_fileIsBeingReloaded(false) : m_minimizableInfoBars(*infoBar())
, m_isObjCEnabled(false)
, m_cachedContentsRevision(-1)
, m_processorRevision(0)
, m_completionAssistProvider(0)
, m_minimizableInfoBars(*infoBar())
{ {
setId(CppEditor::Constants::CPPEDITOR_ID); setId(CppEditor::Constants::CPPEDITOR_ID);
setSyntaxHighlighter(new CppHighlighter); setSyntaxHighlighter(new CppHighlighter);
@@ -352,7 +350,7 @@ unsigned CppEditorDocument::contentsRevision() const
void CppEditorDocument::releaseResources() void CppEditorDocument::releaseResources()
{ {
if (m_processor) if (m_processor)
disconnect(m_processor.data(), 0, this, 0); disconnect(m_processor.data(), nullptr, this, nullptr);
m_processor.reset(); m_processor.reset();
} }

View File

@@ -115,19 +115,19 @@ private:
void initializeTimer(); void initializeTimer();
private: private:
bool m_fileIsBeingReloaded; bool m_fileIsBeingReloaded = false;
bool m_isObjCEnabled; bool m_isObjCEnabled = false;
// Caching contents // Caching contents
mutable QMutex m_cachedContentsLock; mutable QMutex m_cachedContentsLock;
mutable QByteArray m_cachedContents; mutable QByteArray m_cachedContents;
mutable int m_cachedContentsRevision; mutable int m_cachedContentsRevision = -1;
unsigned m_processorRevision; unsigned m_processorRevision = 0;
QTimer m_processorTimer; QTimer m_processorTimer;
QScopedPointer<CppTools::BaseEditorDocumentProcessor> m_processor; QScopedPointer<CppTools::BaseEditorDocumentProcessor> m_processor;
CppTools::CppCompletionAssistProvider *m_completionAssistProvider; CppTools::CppCompletionAssistProvider *m_completionAssistProvider = nullptr;
// (Un)Registration in CppModelManager // (Un)Registration in CppModelManager
QScopedPointer<CppTools::CppEditorDocumentHandle> m_editorDocumentHandle; QScopedPointer<CppTools::CppEditorDocumentHandle> m_editorDocumentHandle;

View File

@@ -310,7 +310,7 @@ static CppEditorWidget *currentCppEditorWidget()
{ {
if (IEditor *currentEditor = EditorManager::currentEditor()) if (IEditor *currentEditor = EditorManager::currentEditor())
return qobject_cast<CppEditorWidget*>(currentEditor->widget()); return qobject_cast<CppEditorWidget*>(currentEditor->widget());
return 0; return nullptr;
} }
void CppEditorPlugin::switchDeclarationDefinition() void CppEditorPlugin::switchDeclarationDefinition()

View File

@@ -40,7 +40,7 @@ class CppEditorPlugin : public ExtensionSystem::IPlugin
public: public:
CppEditorPlugin(); CppEditorPlugin();
~CppEditorPlugin(); ~CppEditorPlugin() override;
static CppEditorPlugin *instance(); static CppEditorPlugin *instance();

View File

@@ -261,7 +261,7 @@ void CppEditorWidget::finalizeInitialization()
void CppEditorWidget::finalizeInitializationAfterDuplication(TextEditorWidget *other) void CppEditorWidget::finalizeInitializationAfterDuplication(TextEditorWidget *other)
{ {
QTC_ASSERT(other, return); QTC_ASSERT(other, return);
CppEditorWidget *cppEditorWidget = qobject_cast<CppEditorWidget *>(other); auto cppEditorWidget = qobject_cast<CppEditorWidget *>(other);
QTC_ASSERT(cppEditorWidget, return); QTC_ASSERT(cppEditorWidget, return);
if (cppEditorWidget->isSemanticInfoValidExceptLocalUses()) if (cppEditorWidget->isSemanticInfoValidExceptLocalUses())
@@ -278,10 +278,7 @@ void CppEditorWidget::finalizeInitializationAfterDuplication(TextEditorWidget *o
d->m_cppEditorDocument->parseContextModel().areMultipleAvailable()); d->m_cppEditorDocument->parseContextModel().areMultipleAvailable());
} }
CppEditorWidget::~CppEditorWidget() CppEditorWidget::~CppEditorWidget() = default;
{
// non-inline destructor, see section "Forward Declared Pointers" of QScopedPointer.
}
CppEditorDocument *CppEditorWidget::cppEditorDocument() const CppEditorDocument *CppEditorWidget::cppEditorDocument() const
{ {
@@ -357,7 +354,7 @@ static QString getDocumentLine(const QTextDocument &document, int line)
static QString getFileLine(const QString &path, int line) static QString getFileLine(const QString &path, int line)
{ {
const IDocument *document = DocumentModel::documentForFilePath(path); const IDocument *document = DocumentModel::documentForFilePath(path);
const TextDocument *textDocument = qobject_cast<const TextDocument *>(document); const auto textDocument = qobject_cast<const TextDocument *>(document);
if (textDocument) if (textDocument)
return getDocumentLine(*textDocument->document(), line); return getDocumentLine(*textDocument->document(), line);
@@ -543,7 +540,7 @@ ProjectPart *findProjectPartForCurrentProject(const QList<ProjectPart::Ptr> &pro
if (found != projectParts.cend()) if (found != projectParts.cend())
return (*found).data(); return (*found).data();
return 0; return nullptr;
} }
} // namespace } // namespace
@@ -551,7 +548,7 @@ ProjectPart *findProjectPartForCurrentProject(const QList<ProjectPart::Ptr> &pro
ProjectPart *CppEditorWidget::projectPart() const ProjectPart *CppEditorWidget::projectPart() const
{ {
if (!d->m_modelManager) if (!d->m_modelManager)
return 0; return nullptr;
auto projectParts = fetchProjectParts(d->m_modelManager, textDocument()->filePath()); auto projectParts = fetchProjectParts(d->m_modelManager, textDocument()->filePath());
@@ -668,14 +665,13 @@ void CppEditorWidget::switchDeclarationDefinition(bool inNextSplit)
return; return;
// Find function declaration or definition under cursor // Find function declaration or definition under cursor
Function *functionDefinitionSymbol = 0; Function *functionDefinitionSymbol = nullptr;
Symbol *functionDeclarationSymbol = 0; Symbol *functionDeclarationSymbol = nullptr;
ASTPath astPathFinder(d->m_lastSemanticInfo.doc); ASTPath astPathFinder(d->m_lastSemanticInfo.doc);
const QList<AST *> astPath = astPathFinder(textCursor()); const QList<AST *> astPath = astPathFinder(textCursor());
for (int i = 0, size = astPath.size(); i < size; ++i) { for (AST *ast : astPath) {
AST *ast = astPath.at(i);
if (FunctionDefinitionAST *functionDefinitionAST = ast->asFunctionDefinition()) { if (FunctionDefinitionAST *functionDefinitionAST = ast->asFunctionDefinition()) {
if ((functionDefinitionSymbol = functionDefinitionAST->symbol)) if ((functionDefinitionSymbol = functionDefinitionAST->symbol))
break; // Function definition found! break; // Function definition found!
@@ -999,7 +995,7 @@ AssistInterface *CppEditorWidget::createAssistInterface(AssistKind kind, AssistR
} else { } else {
return TextEditorWidget::createAssistInterface(kind, reason); return TextEditorWidget::createAssistInterface(kind, reason);
} }
return 0; return nullptr;
} }
QSharedPointer<FunctionDeclDefLink> CppEditorWidget::declDefLink() const QSharedPointer<FunctionDeclDefLink> CppEditorWidget::declDefLink() const

View File

@@ -96,19 +96,17 @@ static bool findDeclOrDef(const Document::Ptr &doc, int line, int column,
// by CompoundStatement/CtorInitializer // by CompoundStatement/CtorInitializer
// for function declarations, look for SimpleDeclarations with a single Declarator // for function declarations, look for SimpleDeclarations with a single Declarator
// with a FunctionDeclarator postfix // with a FunctionDeclarator postfix
FunctionDefinitionAST *funcDef = 0; *decl = nullptr;
SimpleDeclarationAST *simpleDecl = 0;
*decl = 0;
for (int i = path.size() - 1; i > 0; --i) { for (int i = path.size() - 1; i > 0; --i) {
AST *ast = path.at(i); AST *ast = path.at(i);
if (ast->asCompoundStatement() || ast->asCtorInitializer()) if (ast->asCompoundStatement() || ast->asCtorInitializer())
break; break;
if ((funcDef = ast->asFunctionDefinition()) != 0) { if (FunctionDefinitionAST *funcDef = ast->asFunctionDefinition()) {
*parent = funcDef; *parent = funcDef;
*decl = funcDef->declarator; *decl = funcDef->declarator;
break; break;
} }
if ((simpleDecl = ast->asSimpleDeclaration()) != 0) { if (SimpleDeclarationAST *simpleDecl = ast->asSimpleDeclaration()) {
*parent = simpleDecl; *parent = simpleDecl;
if (!simpleDecl->declarator_list || !simpleDecl->declarator_list->value) if (!simpleDecl->declarator_list || !simpleDecl->declarator_list->value)
break; break;
@@ -142,12 +140,12 @@ static void declDefLinkStartEnd(const CppRefactoringFileConstPtr &file,
static DeclaratorIdAST *getDeclaratorId(DeclaratorAST *declarator) static DeclaratorIdAST *getDeclaratorId(DeclaratorAST *declarator)
{ {
if (!declarator || !declarator->core_declarator) if (!declarator || !declarator->core_declarator)
return 0; return nullptr;
if (DeclaratorIdAST *id = declarator->core_declarator->asDeclaratorId()) if (DeclaratorIdAST *id = declarator->core_declarator->asDeclaratorId())
return id; return id;
if (NestedDeclaratorAST *nested = declarator->core_declarator->asNestedDeclarator()) if (NestedDeclaratorAST *nested = declarator->core_declarator->asNestedDeclarator())
return getDeclaratorId(nested->declarator); return getDeclaratorId(nested->declarator);
return 0; return nullptr;
} }
static QSharedPointer<FunctionDeclDefLink> findLinkHelper(QSharedPointer<FunctionDeclDefLink> link, CppRefactoringChanges changes) static QSharedPointer<FunctionDeclDefLink> findLinkHelper(QSharedPointer<FunctionDeclDefLink> link, CppRefactoringChanges changes)
@@ -156,7 +154,7 @@ static QSharedPointer<FunctionDeclDefLink> findLinkHelper(QSharedPointer<Functio
const Snapshot &snapshot = changes.snapshot(); const Snapshot &snapshot = changes.snapshot();
// find the matching decl/def symbol // find the matching decl/def symbol
Symbol *target = 0; Symbol *target = nullptr;
SymbolFinder finder; SymbolFinder finder;
if (FunctionDefinitionAST *funcDef = link->sourceDeclaration->asFunctionDefinition()) { if (FunctionDefinitionAST *funcDef = link->sourceDeclaration->asFunctionDefinition()) {
QList<Declaration *> nameMatch, argumentCountMatch, typeMatch; QList<Declaration *> nameMatch, argumentCountMatch, typeMatch;
@@ -178,9 +176,9 @@ static QSharedPointer<FunctionDeclDefLink> findLinkHelper(QSharedPointer<Functio
if (!targetFile->isValid()) if (!targetFile->isValid())
return noResult; return noResult;
DeclarationAST *targetParent = 0; DeclarationAST *targetParent = nullptr;
FunctionDeclaratorAST *targetFuncDecl = 0; FunctionDeclaratorAST *targetFuncDecl = nullptr;
DeclaratorAST *targetDeclarator = 0; DeclaratorAST *targetDeclarator = nullptr;
if (!findDeclOrDef(targetFile->cppDocument(), target->line(), target->column(), if (!findDeclOrDef(targetFile->cppDocument(), target->line(), target->column(),
&targetParent, &targetDeclarator, &targetFuncDecl)) &targetParent, &targetDeclarator, &targetFuncDecl))
return noResult; return noResult;
@@ -213,9 +211,9 @@ void FunctionDeclDefLinkFinder::startFindLinkAt(
QTextCursor cursor, const Document::Ptr &doc, const Snapshot &snapshot) QTextCursor cursor, const Document::Ptr &doc, const Snapshot &snapshot)
{ {
// check if cursor is on function decl/def // check if cursor is on function decl/def
DeclarationAST *parent = 0; DeclarationAST *parent = nullptr;
FunctionDeclaratorAST *funcDecl = 0; FunctionDeclaratorAST *funcDecl = nullptr;
DeclaratorAST *declarator = 0; DeclaratorAST *declarator = nullptr;
if (!findDeclOrDef(doc, cursor.blockNumber() + 1, cursor.columnNumber() + 1, if (!findDeclOrDef(doc, cursor.blockNumber() + 1, cursor.columnNumber() + 1,
&parent, &declarator, &funcDecl)) &parent, &declarator, &funcDecl))
return; return;
@@ -455,10 +453,10 @@ static SpecifierAST *findFirstReplaceableSpecifier(TranslationUnit *translationU
if (canReplaceSpecifier(translationUnit, it->value)) if (canReplaceSpecifier(translationUnit, it->value))
return it->value; return it->value;
} }
return 0; return nullptr;
} }
typedef QVarLengthArray<int, 10> IndicesList; using IndicesList = QVarLengthArray<int, 10>;
template <class IndicesListType> template <class IndicesListType>
static int findUniqueTypeMatch(int sourceParamIndex, Function *sourceFunction, Function *newFunction, static int findUniqueTypeMatch(int sourceParamIndex, Function *sourceFunction, Function *newFunction,
@@ -597,8 +595,8 @@ ChangeSet FunctionDeclDefLink::changes(const Snapshot &snapshot, int targetOffse
Control *control = sourceContext.bindings()->control().data(); Control *control = sourceContext.bindings()->control().data();
// get return type start position and declarator info from declaration // get return type start position and declarator info from declaration
DeclaratorAST *declarator = 0; DeclaratorAST *declarator = nullptr;
SpecifierAST *firstReplaceableSpecifier = 0; SpecifierAST *firstReplaceableSpecifier = nullptr;
TranslationUnit *targetTranslationUnit = targetFile->cppDocument()->translationUnit(); TranslationUnit *targetTranslationUnit = targetFile->cppDocument()->translationUnit();
if (SimpleDeclarationAST *simple = targetDeclaration->asSimpleDeclaration()) { if (SimpleDeclarationAST *simple = targetDeclaration->asSimpleDeclaration()) {
declarator = simple->declarator_list->value; declarator = simple->declarator_list->value;
@@ -790,7 +788,7 @@ ChangeSet FunctionDeclDefLink::changes(const Snapshot &snapshot, int targetOffse
if (hasCommentedName(targetFile->cppDocument()->translationUnit(), if (hasCommentedName(targetFile->cppDocument()->translationUnit(),
QString::fromUtf8(targetFile->cppDocument()->utf8Source()), QString::fromUtf8(targetFile->cppDocument()->utf8Source()),
targetFunctionDeclarator, existingParamIndex)) targetFunctionDeclarator, existingParamIndex))
replacementName = 0; replacementName = nullptr;
// track renames // track renames
if (replacementName != targetParam->name() && replacementName) if (replacementName != targetParam->name() && replacementName)
@@ -914,8 +912,8 @@ ChangeSet FunctionDeclDefLink::changes(const Snapshot &snapshot, int targetOffse
changes.insert(targetFile->endOf(targetFunctionDeclarator->rparen_token), cvString); changes.insert(targetFile->endOf(targetFunctionDeclarator->rparen_token), cvString);
// modify/remove existing specifiers // modify/remove existing specifiers
} else { } else {
SimpleSpecifierAST *constSpecifier = 0; SimpleSpecifierAST *constSpecifier = nullptr;
SimpleSpecifierAST *volatileSpecifier = 0; SimpleSpecifierAST *volatileSpecifier = nullptr;
for (SpecifierListAST *it = targetFunctionDeclarator->cv_qualifier_list; it; it = it->next) { for (SpecifierListAST *it = targetFunctionDeclarator->cv_qualifier_list; it; it = it->next) {
if (SimpleSpecifierAST *simple = it->value->asSimpleSpecifier()) { if (SimpleSpecifierAST *simple = it->value->asSimpleSpecifier()) {
unsigned kind = targetFile->tokenAt(simple->specifier_token).kind(); unsigned kind = targetFile->tokenAt(simple->specifier_token).kind();

View File

@@ -45,7 +45,7 @@ class FunctionDeclDefLinkFinder : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
FunctionDeclDefLinkFinder(QObject *parent = 0); FunctionDeclDefLinkFinder(QObject *parent = nullptr);
void startFindLinkAt(QTextCursor cursor, void startFindLinkAt(QTextCursor cursor,
const CPlusPlus::Document::Ptr &doc, const CPlusPlus::Document::Ptr &doc,

View File

@@ -41,7 +41,7 @@ class CppHighlighter : public TextEditor::SyntaxHighlighter
Q_OBJECT Q_OBJECT
public: public:
CppHighlighter(QTextDocument *document = 0); CppHighlighter(QTextDocument *document = nullptr);
void setLanguageFeatures(const CPlusPlus::LanguageFeatures &languageFeatures); void setLanguageFeatures(const CPlusPlus::LanguageFeatures &languageFeatures);
void highlightBlock(const QString &text) override; void highlightBlock(const QString &text) override;

View File

@@ -80,7 +80,7 @@ static Snapshot globalSnapshot()
struct FileAndLine struct FileAndLine
{ {
FileAndLine() {} FileAndLine() = default;
FileAndLine(const QString &f, int l) : file(f), line(l) {} FileAndLine(const QString &f, int l) : file(f), line(l) {}
QString file; QString file;
@@ -122,7 +122,7 @@ class CppIncludeHierarchyItem
{ {
public: public:
enum SubTree { RootItem, InIncludes, InIncludedBy }; enum SubTree { RootItem, InIncludes, InIncludedBy };
CppIncludeHierarchyItem() {} CppIncludeHierarchyItem() = default;
void createChild(const QString &filePath, SubTree subTree, void createChild(const QString &filePath, SubTree subTree,
int line = 0, bool definitelyNoChildren = false) int line = 0, bool definitelyNoChildren = false)
@@ -348,7 +348,7 @@ class CppIncludeHierarchyWidget : public QWidget
public: public:
CppIncludeHierarchyWidget(); CppIncludeHierarchyWidget();
~CppIncludeHierarchyWidget() { delete m_treeView; } ~CppIncludeHierarchyWidget() override { delete m_treeView; }
void perform(); void perform();
@@ -509,9 +509,9 @@ void CppIncludeHierarchyWidget::syncFromEditorManager()
// Use cppDocumentUpdated to catch parsing finished and later file updates. // Use cppDocumentUpdated to catch parsing finished and later file updates.
// The timer limits the amount of hierarchy updates. // The timer limits the amount of hierarchy updates.
connect(document, &CppEditorDocument::cppDocumentUpdated, this, [this]() { connect(document, &CppEditorDocument::cppDocumentUpdated,
m_timer->start(); m_timer, QOverload<>::of(&QTimer::start),
}, Qt::UniqueConnection); Qt::UniqueConnection);
} }
// CppIncludeHierarchyFactory // CppIncludeHierarchyFactory

View File

@@ -38,7 +38,7 @@ class CppIncludeHierarchyItem;
class CppIncludeHierarchyModel : public Utils::TreeModel<CppIncludeHierarchyItem> class CppIncludeHierarchyModel : public Utils::TreeModel<CppIncludeHierarchyItem>
{ {
Q_OBJECT Q_OBJECT
typedef Utils::TreeModel<CppIncludeHierarchyItem> base_type; using base_type = Utils::TreeModel<CppIncludeHierarchyItem>;
public: public:
CppIncludeHierarchyModel(); CppIncludeHierarchyModel();

View File

@@ -92,8 +92,8 @@ public:
ModeImplementationFile = 0x00000008 ModeImplementationFile = 0x00000008
}; };
InsertVirtualMethodsDialog(QWidget *parent = 0); InsertVirtualMethodsDialog(QWidget *parent = nullptr);
~InsertVirtualMethodsDialog(); ~InsertVirtualMethodsDialog() override;
void initGui(); void initGui();
void initData(); void initData();
virtual void saveSettings(); virtual void saveSettings();
@@ -113,20 +113,20 @@ private:
void updateOverrideReplacementsComboBox(); void updateOverrideReplacementsComboBox();
private: private:
QTreeView *m_view; QTreeView *m_view = nullptr;
QLineEdit *m_filter; QLineEdit *m_filter = nullptr;
QCheckBox *m_hideReimplementedFunctions; QCheckBox *m_hideReimplementedFunctions = nullptr;
QComboBox *m_insertMode; QComboBox *m_insertMode = nullptr;
QCheckBox *m_virtualKeyword; QCheckBox *m_virtualKeyword = nullptr;
QCheckBox *m_overrideReplacementCheckBox; QCheckBox *m_overrideReplacementCheckBox = nullptr;
QComboBox *m_overrideReplacementComboBox; QComboBox *m_overrideReplacementComboBox = nullptr;
QToolButton *m_clearUserAddedReplacementsButton; QToolButton *m_clearUserAddedReplacementsButton = nullptr;
QDialogButtonBox *m_buttons; QDialogButtonBox *m_buttons = nullptr;
QList<bool> m_expansionStateNormal; QList<bool> m_expansionStateNormal;
QList<bool> m_expansionStateReimp; QList<bool> m_expansionStateReimp;
QStringList m_availableOverrideReplacements; QStringList m_availableOverrideReplacements;
bool m_hasImplementationFile; bool m_hasImplementationFile = false;
bool m_hasReimplementedFunctions; bool m_hasReimplementedFunctions = false;
protected: protected:
VirtualMethodsSettings *m_settings; VirtualMethodsSettings *m_settings;
@@ -149,15 +149,11 @@ namespace {
class InsertVirtualMethodsItem class InsertVirtualMethodsItem
{ {
public: public:
InsertVirtualMethodsItem(InsertVirtualMethodsItem *parent) : InsertVirtualMethodsItem(InsertVirtualMethodsItem *parent)
row(-1), : m_parent(parent)
m_parent(parent) {}
{
}
virtual ~InsertVirtualMethodsItem() virtual ~InsertVirtualMethodsItem() = default;
{
}
virtual QString description() const = 0; virtual QString description() const = 0;
virtual Qt::ItemFlags flags() const = 0; virtual Qt::ItemFlags flags() const = 0;
@@ -165,10 +161,10 @@ public:
InsertVirtualMethodsItem *parent() { return m_parent; } InsertVirtualMethodsItem *parent() { return m_parent; }
int row; int row = -1;
private: private:
InsertVirtualMethodsItem *m_parent; InsertVirtualMethodsItem *m_parent = nullptr;
}; };
class FunctionItem; class FunctionItem;
@@ -177,11 +173,11 @@ class ClassItem : public InsertVirtualMethodsItem
{ {
public: public:
ClassItem(const QString &className, const Class *clazz); ClassItem(const QString &className, const Class *clazz);
~ClassItem(); ~ClassItem() override;
QString description() const { return name; } QString description() const override { return name; }
Qt::ItemFlags flags() const; Qt::ItemFlags flags() const override;
Qt::CheckState checkState() const; Qt::CheckState checkState() const override;
void removeFunction(int row); void removeFunction(int row);
const Class *klass; const Class *klass;
@@ -193,9 +189,9 @@ class FunctionItem : public InsertVirtualMethodsItem
{ {
public: public:
FunctionItem(const Function *func, const QString &functionName, ClassItem *parent); FunctionItem(const Function *func, const QString &functionName, ClassItem *parent);
QString description() const; QString description() const override;
Qt::ItemFlags flags() const; Qt::ItemFlags flags() const override;
Qt::CheckState checkState() const { return checked ? Qt::Checked : Qt::Unchecked; } Qt::CheckState checkState() const override { return checked ? Qt::Checked : Qt::Unchecked; }
const Function *function = nullptr; const Function *function = nullptr;
InsertionPointLocator::AccessSpec accessSpec = InsertionPointLocator::Invalid; InsertionPointLocator::AccessSpec accessSpec = InsertionPointLocator::Invalid;
@@ -209,7 +205,7 @@ private:
}; };
ClassItem::ClassItem(const QString &className, const Class *clazz) : ClassItem::ClassItem(const QString &className, const Class *clazz) :
InsertVirtualMethodsItem(0), InsertVirtualMethodsItem(nullptr),
klass(clazz), klass(clazz),
name(className) name(className)
{ {
@@ -339,7 +335,7 @@ public:
bool insertOverrideReplacement = false; bool insertOverrideReplacement = false;
private: private:
typedef QLatin1String _; using _ = QLatin1String;
static QString group() { return _("QuickFix/InsertVirtualMethods"); } static QString group() { return _("QuickFix/InsertVirtualMethods"); }
static QString insertVirtualKeywordKey() { return _("insertKeywordVirtual"); } static QString insertVirtualKeywordKey() { return _("insertKeywordVirtual"); }
static QString insertOverrideReplacementKey() { return _("insertOverrideReplacement"); } static QString insertOverrideReplacementKey() { return _("insertOverrideReplacement"); }
@@ -352,13 +348,13 @@ private:
class InsertVirtualMethodsModel : public QAbstractItemModel class InsertVirtualMethodsModel : public QAbstractItemModel
{ {
public: public:
InsertVirtualMethodsModel(QObject *parent = 0) : QAbstractItemModel(parent) InsertVirtualMethodsModel(QObject *parent = nullptr) : QAbstractItemModel(parent)
{ {
const FontSettings &fs = TextEditorSettings::fontSettings(); const FontSettings &fs = TextEditorSettings::fontSettings();
formatReimpFunc = fs.formatFor(C_DISABLED_CODE); formatReimpFunc = fs.formatFor(C_DISABLED_CODE);
} }
~InsertVirtualMethodsModel() ~InsertVirtualMethodsModel() override
{ {
clear(); clear();
} }
@@ -371,26 +367,26 @@ public:
endResetModel(); endResetModel();
} }
QModelIndex index(int row, int column, const QModelIndex &parent) const QModelIndex index(int row, int column, const QModelIndex &parent) const override
{ {
if (column != 0) if (column != 0)
return QModelIndex(); return {};
if (parent.isValid()) { if (parent.isValid()) {
ClassItem *classItem = static_cast<ClassItem *>(parent.internalPointer()); auto classItem = static_cast<ClassItem *>(parent.internalPointer());
return createIndex(row, column, classItem->functions.at(row)); return createIndex(row, column, classItem->functions.at(row));
} }
return createIndex(row, column, classes.at(row)); return createIndex(row, column, classes.at(row));
} }
QModelIndex parent(const QModelIndex &child) const QModelIndex parent(const QModelIndex &child) const override
{ {
if (!child.isValid()) if (!child.isValid())
return QModelIndex(); return {};
InsertVirtualMethodsItem *parent = itemForIndex(child)->parent(); InsertVirtualMethodsItem *parent = itemForIndex(child)->parent();
return parent ? createIndex(parent->row, 0, parent) : QModelIndex(); return parent ? createIndex(parent->row, 0, parent) : QModelIndex();
} }
int rowCount(const QModelIndex &parent) const int rowCount(const QModelIndex &parent) const override
{ {
if (!parent.isValid()) if (!parent.isValid())
return classes.count(); return classes.count();
@@ -400,7 +396,7 @@ public:
return static_cast<ClassItem *>(item)->functions.count(); return static_cast<ClassItem *>(item)->functions.count();
} }
int columnCount(const QModelIndex &) const int columnCount(const QModelIndex &) const override
{ {
return 1; return 1;
} }
@@ -416,13 +412,13 @@ public:
void removeFunction(FunctionItem *funcItem) void removeFunction(FunctionItem *funcItem)
{ {
ClassItem *classItem = static_cast<ClassItem *>(funcItem->parent()); auto classItem = static_cast<ClassItem *>(funcItem->parent());
beginRemoveRows(createIndex(classItem->row, 0, classItem), funcItem->row, funcItem->row); beginRemoveRows(createIndex(classItem->row, 0, classItem), funcItem->row, funcItem->row);
classItem->removeFunction(funcItem->row); classItem->removeFunction(funcItem->row);
endRemoveRows(); endRemoveRows();
} }
QVariant data(const QModelIndex &index, int role) const QVariant data(const QModelIndex &index, int role) const override
{ {
if (!index.isValid()) if (!index.isValid())
return QVariant(); return QVariant();
@@ -446,7 +442,7 @@ public:
break; break;
case InsertVirtualMethodsDialog::Reimplemented: case InsertVirtualMethodsDialog::Reimplemented:
if (item->parent()) { if (item->parent()) {
FunctionItem *function = static_cast<FunctionItem *>(item); auto function = static_cast<FunctionItem *>(item);
return QVariant(function->alreadyFound); return QVariant(function->alreadyFound);
} }
@@ -454,7 +450,7 @@ public:
return QVariant(); return QVariant();
} }
bool setData(const QModelIndex &index, const QVariant &value, int role) bool setData(const QModelIndex &index, const QVariant &value, int role) override
{ {
if (!index.isValid()) if (!index.isValid())
return false; return false;
@@ -464,7 +460,7 @@ public:
case Qt::CheckStateRole: { case Qt::CheckStateRole: {
bool checked = value.toInt() == Qt::Checked; bool checked = value.toInt() == Qt::Checked;
if (item->parent()) { if (item->parent()) {
FunctionItem *funcItem = static_cast<FunctionItem *>(item); auto funcItem = static_cast<FunctionItem *>(item);
while (funcItem->checked != checked) { while (funcItem->checked != checked) {
funcItem->checked = checked; funcItem->checked = checked;
const QModelIndex funcIndex = createIndex(funcItem->row, 0, funcItem); const QModelIndex funcIndex = createIndex(funcItem->row, 0, funcItem);
@@ -475,7 +471,7 @@ public:
funcItem = funcItem->nextOverride; funcItem = funcItem->nextOverride;
} }
} else { } else {
ClassItem *classItem = static_cast<ClassItem *>(item); auto classItem = static_cast<ClassItem *>(item);
foreach (FunctionItem *funcItem, classItem->functions) { foreach (FunctionItem *funcItem, classItem->functions) {
if (funcItem->alreadyFound || funcItem->checked == checked) if (funcItem->alreadyFound || funcItem->checked == checked)
continue; continue;
@@ -489,7 +485,7 @@ public:
return QAbstractItemModel::setData(index, value, role); return QAbstractItemModel::setData(index, value, role);
} }
Qt::ItemFlags flags(const QModelIndex &index) const Qt::ItemFlags flags(const QModelIndex &index) const override
{ {
if (!index.isValid()) if (!index.isValid())
return Qt::NoItemFlags; return Qt::NoItemFlags;
@@ -586,7 +582,7 @@ public:
if (!name || name->asDestructorNameId()) if (!name || name->asDestructorNameId())
continue; continue;
const Function *firstVirtual = 0; const Function *firstVirtual = nullptr;
const bool isVirtual = FunctionUtils::isVirtualFunction( const bool isVirtual = FunctionUtils::isVirtualFunction(
func, interface.context(), &firstVirtual); func, interface.context(), &firstVirtual);
if (!isVirtual) if (!isVirtual)
@@ -594,7 +590,7 @@ public:
if (func->isFinal()) { if (func->isFinal()) {
if (FunctionItem *first = virtualFunctions[firstVirtual]) { if (FunctionItem *first = virtualFunctions[firstVirtual]) {
FunctionItem *next = 0; FunctionItem *next = nullptr;
for (FunctionItem *removed = first; next != first; removed = next) { for (FunctionItem *removed = first; next != first; removed = next) {
next = removed->nextOverride; next = removed->nextOverride;
m_factory->classFunctionModel->removeFunction(removed); m_factory->classFunctionModel->removeFunction(removed);
@@ -643,7 +639,7 @@ public:
itemName += QLatin1String(" : ") + itemReturnTypeString; itemName += QLatin1String(" : ") + itemReturnTypeString;
if (isReimplemented) if (isReimplemented)
itemName += QLatin1String(" (redeclared)"); itemName += QLatin1String(" (redeclared)");
FunctionItem *funcItem = new FunctionItem(func, itemName, itemBase); auto funcItem = new FunctionItem(func, itemName, itemBase);
if (isReimplemented) { if (isReimplemented) {
factory->setHasReimplementedFunctions(true); factory->setHasReimplementedFunctions(true);
funcItem->reimplemented = true; funcItem->reimplemented = true;
@@ -734,7 +730,7 @@ public:
return spec; return spec;
} }
void perform() void perform() override
{ {
if (!m_factory->gather()) if (!m_factory->gather())
return; return;
@@ -897,12 +893,11 @@ class InsertVirtualMethodsFilterModel : public QSortFilterProxyModel
{ {
Q_OBJECT Q_OBJECT
public: public:
InsertVirtualMethodsFilterModel(QObject *parent = 0) InsertVirtualMethodsFilterModel(QObject *parent = nullptr)
: QSortFilterProxyModel(parent) : QSortFilterProxyModel(parent)
, m_hideReimplemented(false)
{} {}
bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const override
{ {
QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent); QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
@@ -941,22 +936,11 @@ public:
} }
private: private:
bool m_hideReimplemented; bool m_hideReimplemented = false;
}; };
InsertVirtualMethodsDialog::InsertVirtualMethodsDialog(QWidget *parent) InsertVirtualMethodsDialog::InsertVirtualMethodsDialog(QWidget *parent)
: QDialog(parent) : QDialog(parent)
, m_view(0)
, m_filter(0)
, m_hideReimplementedFunctions(0)
, m_insertMode(0)
, m_virtualKeyword(0)
, m_overrideReplacementCheckBox(0)
, m_overrideReplacementComboBox(0)
, m_clearUserAddedReplacementsButton(0)
, m_buttons(0)
, m_hasImplementationFile(false)
, m_hasReimplementedFunctions(false)
, m_settings(new VirtualMethodsSettings) , m_settings(new VirtualMethodsSettings)
, classFunctionModel(new InsertVirtualMethodsModel(this)) , classFunctionModel(new InsertVirtualMethodsModel(this))
, classFunctionFilterModel(new InsertVirtualMethodsFilterModel(this)) , classFunctionFilterModel(new InsertVirtualMethodsFilterModel(this))
@@ -976,11 +960,11 @@ void InsertVirtualMethodsDialog::initGui()
return; return;
setWindowTitle(tr("Insert Virtual Functions")); setWindowTitle(tr("Insert Virtual Functions"));
QVBoxLayout *globalVerticalLayout = new QVBoxLayout; auto globalVerticalLayout = new QVBoxLayout;
// View // View
QGroupBox *groupBoxView = new QGroupBox(tr("&Functions to insert:"), this); QGroupBox *groupBoxView = new QGroupBox(tr("&Functions to insert:"), this);
QVBoxLayout *groupBoxViewLayout = new QVBoxLayout(groupBoxView); auto groupBoxViewLayout = new QVBoxLayout(groupBoxView);
m_filter = new QLineEdit(this); m_filter = new QLineEdit(this);
m_filter->setClearButtonEnabled(true); m_filter->setClearButtonEnabled(true);
m_filter->setPlaceholderText(tr("Filter")); m_filter->setPlaceholderText(tr("Filter"));
@@ -995,7 +979,7 @@ void InsertVirtualMethodsDialog::initGui()
// Insertion options // Insertion options
QGroupBox *groupBoxImplementation = new QGroupBox(tr("&Insertion options:"), this); QGroupBox *groupBoxImplementation = new QGroupBox(tr("&Insertion options:"), this);
QVBoxLayout *groupBoxImplementationLayout = new QVBoxLayout(groupBoxImplementation); auto groupBoxImplementationLayout = new QVBoxLayout(groupBoxImplementation);
m_insertMode = new QComboBox(this); m_insertMode = new QComboBox(this);
m_insertMode->addItem(tr("Insert only declarations"), ModeOnlyDeclarations); m_insertMode->addItem(tr("Insert only declarations"), ModeOnlyDeclarations);
m_insertMode->addItem(tr("Insert definitions inside class"), ModeInsideClass); m_insertMode->addItem(tr("Insert definitions inside class"), ModeInsideClass);
@@ -1012,7 +996,7 @@ void InsertVirtualMethodsDialog::initGui()
connect(m_overrideReplacementCheckBox, &QCheckBox::clicked, connect(m_overrideReplacementCheckBox, &QCheckBox::clicked,
m_overrideReplacementComboBox, &QComboBox::setEnabled); m_overrideReplacementComboBox, &QComboBox::setEnabled);
QAction *clearUserAddedReplacements = new QAction(this); auto clearUserAddedReplacements = new QAction(this);
clearUserAddedReplacements->setIcon(Utils::Icons::CLEAN_TOOLBAR.icon()); clearUserAddedReplacements->setIcon(Utils::Icons::CLEAN_TOOLBAR.icon());
clearUserAddedReplacements->setText(tr("Clear Added \"override\" Equivalents")); clearUserAddedReplacements->setText(tr("Clear Added \"override\" Equivalents"));
connect(clearUserAddedReplacements, &QAction::triggered, [this]() { connect(clearUserAddedReplacements, &QAction::triggered, [this]() {
@@ -1023,7 +1007,7 @@ void InsertVirtualMethodsDialog::initGui()
m_clearUserAddedReplacementsButton = new QToolButton(this); m_clearUserAddedReplacementsButton = new QToolButton(this);
m_clearUserAddedReplacementsButton->setDefaultAction(clearUserAddedReplacements); m_clearUserAddedReplacementsButton->setDefaultAction(clearUserAddedReplacements);
QHBoxLayout *overrideWidgetsLayout = new QHBoxLayout(this); auto overrideWidgetsLayout = new QHBoxLayout(this);
overrideWidgetsLayout->setSpacing(0); overrideWidgetsLayout->setSpacing(0);
overrideWidgetsLayout->setMargin(0); overrideWidgetsLayout->setMargin(0);
overrideWidgetsLayout->addWidget(m_overrideReplacementCheckBox); overrideWidgetsLayout->addWidget(m_overrideReplacementCheckBox);
@@ -1145,8 +1129,7 @@ void InsertVirtualMethodsDialog::setHasReimplementedFunctions(bool functions)
void InsertVirtualMethodsDialog::setHideReimplementedFunctions(bool hide) void InsertVirtualMethodsDialog::setHideReimplementedFunctions(bool hide)
{ {
InsertVirtualMethodsFilterModel *model = auto model = qobject_cast<InsertVirtualMethodsFilterModel *>(classFunctionFilterModel);
qobject_cast<InsertVirtualMethodsFilterModel *>(classFunctionFilterModel);
if (m_expansionStateNormal.isEmpty() && m_expansionStateReimp.isEmpty()) { if (m_expansionStateNormal.isEmpty() && m_expansionStateReimp.isEmpty()) {
model->setHideReimplementedFunctions(hide); model->setHideReimplementedFunctions(hide);
@@ -1172,8 +1155,7 @@ void InsertVirtualMethodsDialog::updateOverrideReplacementsComboBox()
void InsertVirtualMethodsDialog::saveExpansionState() void InsertVirtualMethodsDialog::saveExpansionState()
{ {
InsertVirtualMethodsFilterModel *model = auto model = qobject_cast<InsertVirtualMethodsFilterModel *>(classFunctionFilterModel);
qobject_cast<InsertVirtualMethodsFilterModel *>(classFunctionFilterModel);
QList<bool> &state = model->hideReimplemented() ? m_expansionStateReimp QList<bool> &state = model->hideReimplemented() ? m_expansionStateReimp
: m_expansionStateNormal; : m_expansionStateNormal;
@@ -1184,8 +1166,7 @@ void InsertVirtualMethodsDialog::saveExpansionState()
void InsertVirtualMethodsDialog::restoreExpansionState() void InsertVirtualMethodsDialog::restoreExpansionState()
{ {
InsertVirtualMethodsFilterModel *model = auto model = qobject_cast<InsertVirtualMethodsFilterModel *>(classFunctionFilterModel);
qobject_cast<InsertVirtualMethodsFilterModel *>(classFunctionFilterModel);
const QList<bool> &state = model->hideReimplemented() ? m_expansionStateReimp const QList<bool> &state = model->hideReimplemented() ? m_expansionStateReimp
: m_expansionStateNormal; : m_expansionStateNormal;

View File

@@ -36,9 +36,9 @@ class InsertVirtualMethods : public CppQuickFixFactory
{ {
Q_OBJECT Q_OBJECT
public: public:
InsertVirtualMethods(InsertVirtualMethodsDialog *dialog = 0); InsertVirtualMethods(InsertVirtualMethodsDialog *dialog = nullptr);
~InsertVirtualMethods(); ~InsertVirtualMethods() override;
void match(const CppQuickFixInterface &interface, TextEditor::QuickFixOperations &result); void match(const CppQuickFixInterface &interface, TextEditor::QuickFixOperations &result) override;
#ifdef WITH_TESTS #ifdef WITH_TESTS
static InsertVirtualMethods *createTestFactory(); static InsertVirtualMethods *createTestFactory();
#endif #endif

View File

@@ -51,7 +51,7 @@ public:
static Actions createShowInfoBarActions(const ActionCreator &actionCreator); static Actions createShowInfoBarActions(const ActionCreator &actionCreator);
public: public:
explicit MinimizableInfoBars(Core::InfoBar &infoBar, QObject *parent = 0); explicit MinimizableInfoBars(Core::InfoBar &infoBar, QObject *parent = nullptr);
// Expected call order: processHasProjectPart(), processHeaderDiagnostics() // Expected call order: processHasProjectPart(), processHeaderDiagnostics()
void processHasProjectPart(bool hasProjectPart); void processHasProjectPart(bool hasProjectPart);

View File

@@ -38,9 +38,9 @@ class CppPreProcessorDialog : public QDialog
public: public:
explicit CppPreProcessorDialog(const QString &filePath, QWidget *parent); explicit CppPreProcessorDialog(const QString &filePath, QWidget *parent);
~CppPreProcessorDialog(); ~CppPreProcessorDialog() override;
int exec(); int exec() override;
QString extraPreprocessorDirectives() const; QString extraPreprocessorDirectives() const;

View File

@@ -39,5 +39,4 @@ CppQuickFixOperation::CppQuickFixOperation(const CppQuickFixInterface &interface
: QuickFixOperation(priority), CppQuickFixInterface(interface) : QuickFixOperation(priority), CppQuickFixInterface(interface)
{} {}
CppQuickFixOperation::~CppQuickFixOperation() CppQuickFixOperation::~CppQuickFixOperation() = default;
{}

View File

@@ -39,7 +39,7 @@ class CPPEDITOR_EXPORT CppQuickFixOperation
{ {
public: public:
explicit CppQuickFixOperation(const CppQuickFixInterface &interface, int priority = -1); explicit CppQuickFixOperation(const CppQuickFixInterface &interface, int priority = -1);
~CppQuickFixOperation(); ~CppQuickFixOperation() override;
}; };
/*! /*!
@@ -60,7 +60,7 @@ class CPPEDITOR_EXPORT CppQuickFixFactory : public QObject
public: public:
CppQuickFixFactory(); CppQuickFixFactory();
~CppQuickFixFactory(); ~CppQuickFixFactory() override;
using QuickFixOperations = TextEditor::QuickFixOperations; using QuickFixOperations = TextEditor::QuickFixOperations;

View File

@@ -35,7 +35,7 @@
namespace CppTools { namespace CppTools {
class CppRefactoringFile; class CppRefactoringFile;
typedef QSharedPointer<CppRefactoringFile> CppRefactoringFilePtr; using CppRefactoringFilePtr = QSharedPointer<CppRefactoringFile>;
} }
namespace CppEditor { namespace CppEditor {

File diff suppressed because it is too large Load Diff

View File

@@ -65,7 +65,7 @@ class AddIncludeForUndefinedIdentifierOp: public CppQuickFixOperation
public: public:
AddIncludeForUndefinedIdentifierOp(const CppQuickFixInterface &interface, int priority, AddIncludeForUndefinedIdentifierOp(const CppQuickFixInterface &interface, int priority,
const QString &include); const QString &include);
void perform(); void perform() override;
private: private:
QString m_include; QString m_include;
@@ -383,7 +383,7 @@ public:
class ExtractFunction : public CppQuickFixFactory class ExtractFunction : public CppQuickFixFactory
{ {
public: public:
typedef std::function<QString ()> FunctionNameGetter; using FunctionNameGetter = std::function<QString()>;
ExtractFunction(FunctionNameGetter functionNameGetter = FunctionNameGetter()); ExtractFunction(FunctionNameGetter functionNameGetter = FunctionNameGetter());
void match(const CppQuickFixInterface &interface, TextEditor::QuickFixOperations &result) override; void match(const CppQuickFixInterface &interface, TextEditor::QuickFixOperations &result) override;

View File

@@ -59,7 +59,7 @@ enum ItemRole {
QStandardItem *itemForClass(const CppClass &cppClass) QStandardItem *itemForClass(const CppClass &cppClass)
{ {
QStandardItem *item = new QStandardItem; auto item = new QStandardItem;
item->setFlags(item->flags() | Qt::ItemIsDragEnabled); item->setFlags(item->flags() | Qt::ItemIsDragEnabled);
item->setData(cppClass.name, Qt::DisplayRole); item->setData(cppClass.name, Qt::DisplayRole);
if (cppClass.name != cppClass.qualifiedName) if (cppClass.name != cppClass.qualifiedName)
@@ -88,8 +88,7 @@ namespace CppEditor {
namespace Internal { namespace Internal {
// CppTypeHierarchyWidget // CppTypeHierarchyWidget
CppTypeHierarchyWidget::CppTypeHierarchyWidget() : CppTypeHierarchyWidget::CppTypeHierarchyWidget()
QWidget(0)
{ {
m_inspectedClass = new TextEditor::TextEditorLinkLabel(this); m_inspectedClass = new TextEditor::TextEditorLinkLabel(this);
m_inspectedClass->setMargin(5); m_inspectedClass->setMargin(5);
@@ -114,7 +113,7 @@ CppTypeHierarchyWidget::CppTypeHierarchyWidget() :
m_noTypeHierarchyAvailableLabel->setBackgroundRole(QPalette::Base); m_noTypeHierarchyAvailableLabel->setBackgroundRole(QPalette::Base);
m_hierarchyWidget = new QWidget(this); m_hierarchyWidget = new QWidget(this);
QVBoxLayout *layout = new QVBoxLayout; auto layout = new QVBoxLayout;
layout->setMargin(0); layout->setMargin(0);
layout->setSpacing(0); layout->setSpacing(0);
layout->addWidget(m_inspectedClass); layout->addWidget(m_inspectedClass);
@@ -130,18 +129,17 @@ CppTypeHierarchyWidget::CppTypeHierarchyWidget() :
connect(CppEditorPlugin::instance(), &CppEditorPlugin::typeHierarchyRequested, this, &CppTypeHierarchyWidget::perform); connect(CppEditorPlugin::instance(), &CppEditorPlugin::typeHierarchyRequested, this, &CppTypeHierarchyWidget::perform);
} }
CppTypeHierarchyWidget::~CppTypeHierarchyWidget() CppTypeHierarchyWidget::~CppTypeHierarchyWidget() = default;
{}
void CppTypeHierarchyWidget::perform() void CppTypeHierarchyWidget::perform()
{ {
showNoTypeHierarchyLabel(); showNoTypeHierarchyLabel();
CppEditor *editor = qobject_cast<CppEditor *>(Core::EditorManager::currentEditor()); auto editor = qobject_cast<CppEditor *>(Core::EditorManager::currentEditor());
if (!editor) if (!editor)
return; return;
CppEditorWidget *widget = qobject_cast<CppEditorWidget *>(editor->widget()); auto widget = qobject_cast<CppEditorWidget *>(editor->widget());
if (!widget) if (!widget)
return; return;

View File

@@ -61,9 +61,9 @@ class CppTypeHierarchyModel : public QStandardItemModel
public: public:
CppTypeHierarchyModel(QObject *parent); CppTypeHierarchyModel(QObject *parent);
Qt::DropActions supportedDragActions() const; Qt::DropActions supportedDragActions() const override;
QStringList mimeTypes() const; QStringList mimeTypes() const override;
QMimeData *mimeData(const QModelIndexList &indexes) const; QMimeData *mimeData(const QModelIndexList &indexes) const override;
}; };
class CppTypeHierarchyWidget : public QWidget class CppTypeHierarchyWidget : public QWidget
@@ -71,7 +71,7 @@ class CppTypeHierarchyWidget : public QWidget
Q_OBJECT Q_OBJECT
public: public:
CppTypeHierarchyWidget(); CppTypeHierarchyWidget();
virtual ~CppTypeHierarchyWidget(); ~CppTypeHierarchyWidget() override;
void perform(); void perform();

View File

@@ -44,7 +44,7 @@ class CppUseSelectionsUpdater : public QObject
public: public:
explicit CppUseSelectionsUpdater(TextEditor::TextEditorWidget *editorWidget); explicit CppUseSelectionsUpdater(TextEditor::TextEditorWidget *editorWidget);
~CppUseSelectionsUpdater(); ~CppUseSelectionsUpdater() override;
void scheduleUpdate(); void scheduleUpdate();
void abortSchedule(); void abortSchedule();

View File

@@ -204,8 +204,7 @@ QString ResourcePreviewHoverHandler::makeTooltip() const
ret += QString("<img src=\"file:///%1\" /><br/>").arg(m_resPath); ret += QString("<img src=\"file:///%1\" /><br/>").arg(m_resPath);
ret += QString("<a href=\"file:///%1\">%2</a>") ret += QString("<a href=\"file:///%1\">%2</a>")
.arg(m_resPath) .arg(m_resPath, QDir::toNativeSeparators(m_resPath));
.arg(QDir::toNativeSeparators(m_resPath));
return ret; return ret;
} }

View File

@@ -50,7 +50,7 @@ namespace {
CursorInfo::Range toRange(const SemanticInfo::Use &use) CursorInfo::Range toRange(const SemanticInfo::Use &use)
{ {
return CursorInfo::Range(use.line, use.column, use.length); return {use.line, use.column, use.length};
} }
CursorInfo::Range toRange(int tokenIndex, TranslationUnit *translationUnit) CursorInfo::Range toRange(int tokenIndex, TranslationUnit *translationUnit)
@@ -60,10 +60,9 @@ CursorInfo::Range toRange(int tokenIndex, TranslationUnit *translationUnit)
if (column) if (column)
--column; // adjust the column position. --column; // adjust the column position.
return CursorInfo::Range( return {line,
line,
column + 1, column + 1,
translationUnit->tokenAt(static_cast<unsigned>(tokenIndex)).utf16chars()); translationUnit->tokenAt(static_cast<unsigned>(tokenIndex)).utf16chars()};
} }
CursorInfo::Range toRange(const QTextCursor &textCursor, CursorInfo::Range toRange(const QTextCursor &textCursor,
@@ -74,10 +73,9 @@ CursorInfo::Range toRange(const QTextCursor &textCursor,
cursor.setPosition(static_cast<int>(utf16offset)); cursor.setPosition(static_cast<int>(utf16offset));
const QTextBlock textBlock = cursor.block(); const QTextBlock textBlock = cursor.block();
return CursorInfo::Range( return {static_cast<unsigned>(textBlock.blockNumber() + 1),
static_cast<unsigned>(textBlock.blockNumber() + 1),
static_cast<unsigned>(cursor.position() - textBlock.position() + 1), static_cast<unsigned>(cursor.position() - textBlock.position() + 1),
length); length};
} }
CursorInfo::Ranges toRanges(const SemanticUses &uses) CursorInfo::Ranges toRanges(const SemanticUses &uses)
@@ -216,8 +214,8 @@ private:
bool good = false; bool good = false;
foreach (const CppTools::SemanticInfo::Use &use, uses) { foreach (const CppTools::SemanticInfo::Use &use, uses) {
unsigned l = static_cast<unsigned>(m_line); const auto l = static_cast<unsigned>(m_line);
unsigned c = static_cast<unsigned>(m_column); const auto c = static_cast<unsigned>(m_column);
if (l == use.line && c >= use.column && c <= (use.column + use.length)) { if (l == use.line && c >= use.column && c <= (use.column + use.length)) {
good = true; good = true;
break; break;

View File

@@ -51,6 +51,8 @@
#include <QStringListModel> #include <QStringListModel>
#include <QUuid> #include <QUuid>
#include <memory>
namespace CppTools { namespace CppTools {
using namespace Constants; using namespace Constants;
@@ -383,7 +385,7 @@ private:
} }
} }
QVariant data(const QModelIndex &fullIndex, int role = Qt::DisplayRole) const override final QVariant data(const QModelIndex &fullIndex, int role = Qt::DisplayRole) const final
{ {
if (!fullIndex.isValid() || role == Qt::DecorationRole) if (!fullIndex.isValid() || role == Qt::DecorationRole)
return QVariant(); return QVariant();
@@ -447,7 +449,7 @@ private:
QModelIndex indexForTree(const ClazyChecksTree *tree) const { QModelIndex indexForTree(const ClazyChecksTree *tree) const {
if (!tree) if (!tree)
return QModelIndex(); return {};
QModelIndex result; QModelIndex result;
traverse(index(0, 0, QModelIndex()), [&](const QModelIndex &index){ traverse(index(0, 0, QModelIndex()), [&](const QModelIndex &index){
@@ -989,11 +991,11 @@ static void setupTreeView(QTreeView *view, QAbstractItemModel *model, int expand
void ClangDiagnosticConfigsWidget::setupTabs() void ClangDiagnosticConfigsWidget::setupTabs()
{ {
m_clangBaseChecks.reset(new CppTools::Ui::ClangBaseChecks); m_clangBaseChecks = std::make_unique<CppTools::Ui::ClangBaseChecks>();
m_clangBaseChecksWidget = new QWidget(); m_clangBaseChecksWidget = new QWidget();
m_clangBaseChecks->setupUi(m_clangBaseChecksWidget); m_clangBaseChecks->setupUi(m_clangBaseChecksWidget);
m_clazyChecks.reset(new CppTools::Ui::ClazyChecks); m_clazyChecks = std::make_unique<CppTools::Ui::ClazyChecks>();
m_clazyChecksWidget = new QWidget(); m_clazyChecksWidget = new QWidget();
m_clazyChecks->setupUi(m_clazyChecksWidget); m_clazyChecks->setupUi(m_clazyChecksWidget);
m_clazySortFilterProxyModel = new ClazyChecksSortFilterModel(this); m_clazySortFilterProxyModel = new ClazyChecksSortFilterModel(this);
@@ -1030,7 +1032,7 @@ void ClangDiagnosticConfigsWidget::setupTabs()
= codeModelSettings()->enableLowerClazyLevels() ? Qt::Checked : Qt::Unchecked; = codeModelSettings()->enableLowerClazyLevels() ? Qt::Checked : Qt::Unchecked;
m_clazyChecks->enableLowerLevelsCheckBox->setCheckState(checkEnableLowerClazyLevels); m_clazyChecks->enableLowerLevelsCheckBox->setCheckState(checkEnableLowerClazyLevels);
m_tidyChecks.reset(new CppTools::Ui::TidyChecks); m_tidyChecks = std::make_unique<CppTools::Ui::TidyChecks>();
m_tidyChecksWidget = new QWidget(); m_tidyChecksWidget = new QWidget();
m_tidyChecks->setupUi(m_tidyChecksWidget); m_tidyChecks->setupUi(m_tidyChecksWidget);
setupTreeView(m_tidyChecks->checksPrefixesTree, m_tidyTreeModel.get()); setupTreeView(m_tidyChecks->checksPrefixesTree, m_tidyTreeModel.get());

View File

@@ -666,7 +666,7 @@ CodeFormatter::State CodeFormatter::state(int belowTop) const
if (belowTop < m_currentState.size()) if (belowTop < m_currentState.size())
return m_currentState.at(m_currentState.size() - 1 - belowTop); return m_currentState.at(m_currentState.size() - 1 - belowTop);
else else
return State(); return {};
} }
int CodeFormatter::tokenIndex() const int CodeFormatter::tokenIndex() const

View File

@@ -36,7 +36,7 @@
using namespace CppTools; using namespace CppTools;
static Core::Id initialClangDiagnosticConfigId() static Core::Id initialClangDiagnosticConfigId()
{ return Core::Id(Constants::CPP_CLANG_BUILTIN_CONFIG_ID_EVERYTHING_WITH_EXCEPTIONS); } { return {Constants::CPP_CLANG_BUILTIN_CONFIG_ID_EVERYTHING_WITH_EXCEPTIONS}; }
static CppCodeModelSettings::PCHUsage initialPchUsage() static CppCodeModelSettings::PCHUsage initialPchUsage()
{ return CppCodeModelSettings::PchUse_BuildSystem; } { return CppCodeModelSettings::PchUse_BuildSystem; }
@@ -90,7 +90,7 @@ static QString convertToNewClazyChecksFormat(const QString &checks)
if (checks.size() == 6 && checks.startsWith("level")) { if (checks.size() == 6 && checks.startsWith("level")) {
bool ok = false; bool ok = false;
const int level = checks.mid(5).toInt(&ok); const int level = checks.midRef(5).toInt(&ok);
QTC_ASSERT(ok, return QString()); QTC_ASSERT(ok, return QString());
return clazyChecksForLevel(level); return clazyChecksForLevel(level);
} }

View File

@@ -76,7 +76,7 @@ CppCodeStyleSettings CppCodeStylePreferences::currentCodeStyleSettings() const
QVariant v = currentValue(); QVariant v = currentValue();
if (!v.canConvert<CppCodeStyleSettings>()) { if (!v.canConvert<CppCodeStyleSettings>()) {
// warning // warning
return CppCodeStyleSettings(); return {};
} }
return v.value<CppCodeStyleSettings>(); return v.value<CppCodeStyleSettings>();
} }

View File

@@ -67,30 +67,7 @@ using namespace CppTools;
// ------------------ CppCodeStyleSettingsWidget // ------------------ CppCodeStyleSettingsWidget
CppCodeStyleSettings::CppCodeStyleSettings() : CppCodeStyleSettings::CppCodeStyleSettings() = default;
indentBlockBraces(false)
, indentBlockBody(true)
, indentClassBraces(false)
, indentEnumBraces(false)
, indentNamespaceBraces(false)
, indentNamespaceBody(false)
, indentAccessSpecifiers(false)
, indentDeclarationsRelativeToAccessSpecifiers(true)
, indentFunctionBody(true)
, indentFunctionBraces(false)
, indentSwitchLabels(false)
, indentStatementsRelativeToSwitchLabels(true)
, indentBlocksRelativeToSwitchLabels(false)
, indentControlFlowRelativeToSwitchLabels(true)
, bindStarToIdentifier(true)
, bindStarToTypeName(false)
, bindStarToLeftSpecifier(false)
, bindStarToRightSpecifier(false)
, extraPaddingForConditionsIfConfusingAlign(true)
, alignAssignments(false)
, preferGetterNameWithoutGetPrefix(true)
{
}
void CppCodeStyleSettings::toSettings(const QString &category, QSettings *s) const void CppCodeStyleSettings::toSettings(const QString &category, QSettings *s) const
{ {
@@ -203,21 +180,20 @@ bool CppCodeStyleSettings::equals(const CppCodeStyleSettings &rhs) const
Utils::optional<CppCodeStyleSettings> CppCodeStyleSettings::currentProjectCodeStyle() Utils::optional<CppCodeStyleSettings> CppCodeStyleSettings::currentProjectCodeStyle()
{ {
ProjectExplorer::Project *project = ProjectExplorer::ProjectTree::currentProject(); ProjectExplorer::Project *project = ProjectExplorer::ProjectTree::currentProject();
using OptSettings = Utils::optional<CppCodeStyleSettings>;
if (!project) if (!project)
return OptSettings(); return {};
ProjectExplorer::EditorConfiguration *editorConfiguration = project->editorConfiguration(); ProjectExplorer::EditorConfiguration *editorConfiguration = project->editorConfiguration();
QTC_ASSERT(editorConfiguration, return OptSettings()); QTC_ASSERT(editorConfiguration, return {});
TextEditor::ICodeStylePreferences *codeStylePreferences TextEditor::ICodeStylePreferences *codeStylePreferences
= editorConfiguration->codeStyle(Constants::CPP_SETTINGS_ID); = editorConfiguration->codeStyle(Constants::CPP_SETTINGS_ID);
QTC_ASSERT(codeStylePreferences, return OptSettings()); QTC_ASSERT(codeStylePreferences, return {});
auto cppCodeStylePreferences = auto cppCodeStylePreferences =
dynamic_cast<const CppCodeStylePreferences *>(codeStylePreferences); dynamic_cast<const CppCodeStylePreferences *>(codeStylePreferences);
if (!cppCodeStylePreferences) if (!cppCodeStylePreferences)
return OptSettings(); return {};
return cppCodeStylePreferences->currentCodeStyleSettings(); return cppCodeStylePreferences->currentCodeStyleSettings();
} }

View File

@@ -45,26 +45,26 @@ class CPPTOOLS_EXPORT CppCodeStyleSettings
public: public:
CppCodeStyleSettings(); CppCodeStyleSettings();
bool indentBlockBraces; bool indentBlockBraces = false;
bool indentBlockBody; bool indentBlockBody = true;
bool indentClassBraces; bool indentClassBraces = false;
bool indentEnumBraces; bool indentEnumBraces = false;
bool indentNamespaceBraces; bool indentNamespaceBraces = false;
bool indentNamespaceBody; bool indentNamespaceBody = false;
bool indentAccessSpecifiers; bool indentAccessSpecifiers = false;
bool indentDeclarationsRelativeToAccessSpecifiers; bool indentDeclarationsRelativeToAccessSpecifiers = true;
bool indentFunctionBody; bool indentFunctionBody = true;
bool indentFunctionBraces; bool indentFunctionBraces = false;
bool indentSwitchLabels; bool indentSwitchLabels = false;
bool indentStatementsRelativeToSwitchLabels; bool indentStatementsRelativeToSwitchLabels = true;
bool indentBlocksRelativeToSwitchLabels; bool indentBlocksRelativeToSwitchLabels = false;
bool indentControlFlowRelativeToSwitchLabels; bool indentControlFlowRelativeToSwitchLabels = true;
// Formatting of pointer and reference declarations, see Overview::StarBindFlag. // Formatting of pointer and reference declarations, see Overview::StarBindFlag.
bool bindStarToIdentifier; bool bindStarToIdentifier = true;
bool bindStarToTypeName; bool bindStarToTypeName = false;
bool bindStarToLeftSpecifier; bool bindStarToLeftSpecifier = false;
bool bindStarToRightSpecifier; bool bindStarToRightSpecifier = false;
// false: if (a && // false: if (a &&
// b) // b)
@@ -75,15 +75,15 @@ public:
// but always: while (a && // but always: while (a &&
// b) // b)
// foo; // foo;
bool extraPaddingForConditionsIfConfusingAlign; bool extraPaddingForConditionsIfConfusingAlign = true;
// false: a = a + // false: a = a +
// b; // b;
// true: a = a + // true: a = a +
// b // b
bool alignAssignments; bool alignAssignments = false;
bool preferGetterNameWithoutGetPrefix; bool preferGetterNameWithoutGetPrefix = true;
void toSettings(const QString &category, QSettings *s) const; void toSettings(const QString &category, QSettings *s) const;
void fromSettings(const QString &category, const QSettings *s); void fromSettings(const QString &category, const QSettings *s);

View File

@@ -1737,9 +1737,8 @@ void InternalCppCompletionAssistProcessor::addClassMembersToCompletion(Scope *sc
else else
addCompletionItem(member); addCompletionItem(member);
} }
std::set<Class *>::const_iterator citEnd = nestedAnonymouses.end(); for (Class *klass : nestedAnonymouses)
for (std::set<Class *>::const_iterator cit = nestedAnonymouses.begin(); cit != citEnd; ++cit) addClassMembersToCompletion(klass, staticLookup);
addClassMembersToCompletion(*cit, staticLookup);
} }
bool InternalCppCompletionAssistProcessor::completeQtMethod(const QList<LookupItem> &results, bool InternalCppCompletionAssistProcessor::completeQtMethod(const QList<LookupItem> &results,

View File

@@ -47,7 +47,7 @@ ProjectFileCategorizer::ProjectFileCategorizer(const QString &projectPartName,
QString ProjectFileCategorizer::partName(const QString &languageName) const QString ProjectFileCategorizer::partName(const QString &languageName) const
{ {
if (hasMultipleParts()) if (hasMultipleParts())
return QString::fromLatin1("%1 (%2)").arg(m_partName).arg(languageName); return QString::fromLatin1("%1 (%2)").arg(m_partName, languageName);
return m_partName; return m_partName;
} }

View File

@@ -179,7 +179,7 @@ CppCodeStyleSettings CppQtStyleIndenter::codeStyleSettings() const
{ {
if (m_cppCodeStylePreferences) if (m_cppCodeStylePreferences)
return m_cppCodeStylePreferences->currentCodeStyleSettings(); return m_cppCodeStylePreferences->currentCodeStyleSettings();
return CppCodeStyleSettings(); return {};
} }
TextEditor::IndentationForBlock CppQtStyleIndenter::indentationForBlocks( TextEditor::IndentationForBlock CppQtStyleIndenter::indentationForBlocks(

View File

@@ -198,12 +198,12 @@ Utils::ChangeSet::Range CppRefactoringFile::range(unsigned tokenIndex) const
unsigned line, column; unsigned line, column;
cppDocument()->translationUnit()->getPosition(token.utf16charsBegin(), &line, &column); cppDocument()->translationUnit()->getPosition(token.utf16charsBegin(), &line, &column);
const int start = document()->findBlockByNumber(line - 1).position() + column - 1; const int start = document()->findBlockByNumber(line - 1).position() + column - 1;
return Utils::ChangeSet::Range(start, start + token.utf16chars()); return {start, static_cast<int>(start + token.utf16chars())};
} }
Utils::ChangeSet::Range CppRefactoringFile::range(AST *ast) const Utils::ChangeSet::Range CppRefactoringFile::range(AST *ast) const
{ {
return Utils::ChangeSet::Range(startOf(ast), endOf(ast)); return {startOf(ast), endOf(ast)};
} }
int CppRefactoringFile::startOf(unsigned index) const int CppRefactoringFile::startOf(unsigned index) const

View File

@@ -560,7 +560,6 @@ void CppSelectionChanger::fineTuneASTNodePositions(ASTNodePositions &positions)
qDebug() << "Is raw literal."; qDebug() << "Is raw literal.";
// Start from positions that include quotes. // Start from positions that include quotes.
int newPosStart = positions.astPosStart;
int newPosEnd = positions.astPosEnd; int newPosEnd = positions.astPosEnd;
// Decrement last position to skip last quote. // Decrement last position to skip last quote.
@@ -572,7 +571,7 @@ void CppSelectionChanger::fineTuneASTNodePositions(ASTNodePositions &positions)
// Start position will be the end position minus the size of the actual contents of the // Start position will be the end position minus the size of the actual contents of the
// literal. // literal.
newPosStart = newPosEnd - static_cast<int>(firstToken.string->size()); int newPosStart = newPosEnd - static_cast<int>(firstToken.string->size());
// Skip raw literal parentheses. // Skip raw literal parentheses.
if (isRawLiteral) if (isRawLiteral)
@@ -591,13 +590,8 @@ void CppSelectionChanger::fineTuneASTNodePositions(ASTNodePositions &positions)
if (debug) if (debug)
qDebug() << "Selecting inner contents of char literal."; qDebug() << "Selecting inner contents of char literal.";
int newPosStart = positions.astPosStart; positions.astPosEnd = positions.astPosEnd - 1;
int newPosEnd = positions.astPosEnd; positions.astPosStart = positions.astPosEnd - int(firstToken.literal->size());
newPosEnd = newPosEnd - 1;
newPosStart = newPosEnd - static_cast<int>(firstToken.literal->size());
positions.astPosStart = newPosStart;
positions.astPosEnd = newPosEnd;
} }
} }
} else if (ForStatementAST *forStatementAST = ast->asForStatement()) { } else if (ForStatementAST *forStatementAST = ast->asForStatement()) {

View File

@@ -42,12 +42,7 @@
using namespace CppTools; using namespace CppTools;
using namespace CPlusPlus; using namespace CPlusPlus;
DoxygenGenerator::DoxygenGenerator() DoxygenGenerator::DoxygenGenerator() = default;
: m_addLeadingAsterisks(true)
, m_generateBrief(true)
, m_startComment(true)
, m_style(QtStyle)
{}
void DoxygenGenerator::setStyle(DocumentationStyle style) void DoxygenGenerator::setStyle(DocumentationStyle style)
{ {

View File

@@ -85,10 +85,10 @@ private:
void assignCommentOffset(QTextCursor cursor); void assignCommentOffset(QTextCursor cursor);
QString offsetString() const; QString offsetString() const;
bool m_addLeadingAsterisks; bool m_addLeadingAsterisks = true;
bool m_generateBrief; bool m_generateBrief = true;
bool m_startComment; bool m_startComment = true;
DocumentationStyle m_style; DocumentationStyle m_style = QtStyle;
CPlusPlus::Overview m_printer; CPlusPlus::Overview m_printer;
QString m_commentOffset; QString m_commentOffset;
}; };

View File

@@ -248,10 +248,7 @@ private:
} // end of anonymous namespace } // end of anonymous namespace
InsertionLocation::InsertionLocation() InsertionLocation::InsertionLocation() = default;
: m_line(0)
, m_column(0)
{}
InsertionLocation::InsertionLocation(const QString &fileName, InsertionLocation::InsertionLocation(const QString &fileName,
const QString &prefix, const QString &prefix,
@@ -316,11 +313,9 @@ class HighestValue
{ {
Key _key; Key _key;
Value _value; Value _value;
bool _set; bool _set = false;
public: public:
HighestValue() HighestValue() = default;
: _key(), _set(false)
{}
HighestValue(const Key &initialKey, const Value &initialValue) HighestValue(const Key &initialKey, const Value &initialValue)
: _key(initialKey) : _key(initialKey)

View File

@@ -63,8 +63,8 @@ private:
QString m_fileName; QString m_fileName;
QString m_prefix; QString m_prefix;
QString m_suffix; QString m_suffix;
unsigned m_line; unsigned m_line = 0;
unsigned m_column; unsigned m_column = 0;
}; };
class CPPTOOLS_EXPORT InsertionPointLocator class CPPTOOLS_EXPORT InsertionPointLocator

View File

@@ -41,7 +41,7 @@ namespace CppTools {
class SearchSymbols: protected CPlusPlus::SymbolVisitor class SearchSymbols: protected CPlusPlus::SymbolVisitor
{ {
public: public:
typedef SymbolSearcher::SymbolTypes SymbolTypes; using SymbolTypes = SymbolSearcher::SymbolTypes;
static SymbolTypes AllTypes; static SymbolTypes AllTypes;

View File

@@ -248,9 +248,9 @@ QString SymbolsFindFilter::toolTip(FindFlags findFlags) const
if (m_symbolsToSearch & SymbolSearcher::Declarations) if (m_symbolsToSearch & SymbolSearcher::Declarations)
types.append(tr("Declarations")); types.append(tr("Declarations"));
return tr("Scope: %1\nTypes: %2\nFlags: %3") return tr("Scope: %1\nTypes: %2\nFlags: %3")
.arg(searchScope() == SymbolSearcher::SearchGlobal ? tr("All") : tr("Projects")) .arg(searchScope() == SymbolSearcher::SearchGlobal ? tr("All") : tr("Projects"),
.arg(types.join(tr(", "))) types.join(", "),
.arg(IFindFilter::descriptionForFindFlags(findFlags)); IFindFilter::descriptionForFindFlags(findFlags));
} }
// #pragma mark -- SymbolsFindFilterConfigWidget // #pragma mark -- SymbolsFindFilterConfigWidget

View File

@@ -26,6 +26,7 @@
#include "perftracepointdialog.h" #include "perftracepointdialog.h"
#include "ui_perftracepointdialog.h" #include "ui_perftracepointdialog.h"
#include <projectexplorer/devicesupport/devicemanager.h>
#include <projectexplorer/kitinformation.h> #include <projectexplorer/kitinformation.h>
#include <projectexplorer/project.h> #include <projectexplorer/project.h>
#include <projectexplorer/session.h> #include <projectexplorer/session.h>
@@ -46,17 +47,26 @@ PerfTracePointDialog::PerfTracePointDialog() :
{ {
m_ui->setupUi(this); m_ui->setupUi(this);
Project *currentProject = SessionManager::startupProject(); if (Project *currentProject = SessionManager::startupProject()) {
QTC_ASSERT(currentProject, return); if (const Target *target = currentProject->activeTarget()) {
const Target *target = currentProject->activeTarget();
QTC_ASSERT(target, return);
const Kit *kit = target->kit(); const Kit *kit = target->kit();
QTC_ASSERT(kit, return); QTC_ASSERT(kit, return);
m_device = DeviceKitInformation::device(kit); m_device = DeviceKitInformation::device(kit);
if (!m_device) {
m_ui->textEdit->setPlainText(tr("Error: No device available for active target."));
return;
}
}
}
if (!m_device) {
const DeviceManager *deviceManager = DeviceManager::instance();
// There should at least be a desktop device.
m_device = deviceManager->defaultDevice(Constants::DESKTOP_DEVICE_TYPE);
QTC_ASSERT(m_device, return); QTC_ASSERT(m_device, return);
}
QFile file(":/perfprofiler/tracepoints.sh"); QFile file(":/perfprofiler/tracepoints.sh");
if (file.open(QIODevice::ReadOnly)) { if (file.open(QIODevice::ReadOnly)) {

View File

@@ -133,3 +133,5 @@ for(p, SUBDIRS) {
linux-* { linux-* {
SUBDIRS += debugger/ptracepreload.pro SUBDIRS += debugger/ptracepreload.pro
} }
QMAKE_EXTRA_TARGETS += deployqt # dummy

View File

@@ -86,7 +86,7 @@ BuildConfiguration::BuildConfiguration(Target *target, Core::Id id)
Utils::FileName BuildConfiguration::buildDirectory() const Utils::FileName BuildConfiguration::buildDirectory() const
{ {
const QString path = macroExpander()->expand(QDir::cleanPath(environment().expandVariables(m_buildDirectory.toString()))); const QString path = QDir::cleanPath(macroExpander()->expand(environment().expandVariables(m_buildDirectory.toString())));
return Utils::FileName::fromString(QDir::cleanPath(QDir(target()->project()->projectDirectory().toString()).absoluteFilePath(path))); return Utils::FileName::fromString(QDir::cleanPath(QDir(target()->project()->projectDirectory().toString()).absoluteFilePath(path)));
} }

View File

@@ -390,8 +390,11 @@ void ToolChainKitInformation::addToMacroExpander(Kit *kit, Utils::MacroExpander
IOutputParser *ToolChainKitInformation::createOutputParser(const Kit *k) const IOutputParser *ToolChainKitInformation::createOutputParser(const Kit *k) const
{ {
ToolChain *tc = toolChain(k, Constants::CXX_LANGUAGE_ID); for (const Core::Id langId : {Constants::CXX_LANGUAGE_ID, Constants::C_LANGUAGE_ID}) {
return tc ? tc->outputParser() : nullptr; if (const ToolChain * const tc = toolChain(k, langId))
return tc->outputParser();
}
return nullptr;
} }
QSet<Core::Id> ToolChainKitInformation::availableFeatures(const Kit *k) const QSet<Core::Id> ToolChainKitInformation::availableFeatures(const Kit *k) const

View File

@@ -282,7 +282,7 @@ void BaseStringAspect::update()
} }
if (d->m_lineEditDisplay) { if (d->m_lineEditDisplay) {
d->m_lineEditDisplay->setText(displayedString); d->m_lineEditDisplay->setTextKeepingActiveCursor(displayedString);
d->m_lineEditDisplay->setEnabled(enabled); d->m_lineEditDisplay->setEnabled(enabled);
} }

View File

@@ -110,6 +110,7 @@
#include <coreplugin/actionmanager/actionmanager.h> #include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/actionmanager/actioncontainer.h> #include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/actionmanager/command.h> #include <coreplugin/actionmanager/command.h>
#include <coreplugin/editormanager/documentmodel.h>
#include <coreplugin/editormanager/editormanager.h> #include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/findplaceholder.h> #include <coreplugin/findplaceholder.h>
#include <coreplugin/vcsmanager.h> #include <coreplugin/vcsmanager.h>
@@ -360,6 +361,7 @@ public:
void handleRenameFile(); void handleRenameFile();
void handleSetStartupProject(); void handleSetStartupProject();
void setStartupProject(ProjectExplorer::Project *project); void setStartupProject(ProjectExplorer::Project *project);
bool closeAllFilesInProject(const Project *project);
void updateRecentProjectMenu(); void updateRecentProjectMenu();
void clearRecentProjects(); void clearRecentProjects();
@@ -441,6 +443,8 @@ public:
QAction *m_openFileAction; QAction *m_openFileAction;
QAction *m_projectTreeCollapseAllAction; QAction *m_projectTreeCollapseAllAction;
QAction *m_projectTreeExpandAllAction; QAction *m_projectTreeExpandAllAction;
Utils::ParameterAction *m_closeProjectFilesActionFileMenu;
Utils::ParameterAction *m_closeProjectFilesActionContextMenu;
QAction *m_searchOnFileSystem; QAction *m_searchOnFileSystem;
QAction *m_showInGraphicalShell; QAction *m_showInGraphicalShell;
QAction *m_openTerminalHere; QAction *m_openTerminalHere;
@@ -933,6 +937,15 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er
cmd->setDescription(dd->m_unloadAction->text()); cmd->setDescription(dd->m_unloadAction->text());
mfile->addAction(cmd, Core::Constants::G_FILE_PROJECT); mfile->addAction(cmd, Core::Constants::G_FILE_PROJECT);
dd->m_closeProjectFilesActionFileMenu = new Utils::ParameterAction(
tr("Close All Files in Project"), tr("Close All Files in Project \"%1\""),
Utils::ParameterAction::AlwaysEnabled, this);
cmd = ActionManager::registerAction(dd->m_closeProjectFilesActionFileMenu,
"ProjectExplorer.CloseProjectFilesFileMenu");
cmd->setAttribute(Command::CA_UpdateText);
cmd->setDescription(dd->m_closeProjectFilesActionFileMenu->text());
mfile->addAction(cmd, Core::Constants::G_FILE_PROJECT);
ActionContainer *munload = ActionContainer *munload =
ActionManager::createMenu(Constants::M_UNLOADPROJECTS); ActionManager::createMenu(Constants::M_UNLOADPROJECTS);
munload->menu()->setTitle(tr("Close Pro&ject")); munload->menu()->setTitle(tr("Close Pro&ject"));
@@ -1140,6 +1153,15 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er
cmd->setDescription(dd->m_unloadActionContextMenu->text()); cmd->setDescription(dd->m_unloadActionContextMenu->text());
mprojectContextMenu->addAction(cmd, Constants::G_PROJECT_LAST); mprojectContextMenu->addAction(cmd, Constants::G_PROJECT_LAST);
dd->m_closeProjectFilesActionContextMenu = new Utils::ParameterAction(
tr("Close All Files"), tr("Close All Files in Project \"%1\""),
Utils::ParameterAction::EnabledWithParameter, this);
cmd = ActionManager::registerAction(dd->m_closeProjectFilesActionContextMenu,
"ProjectExplorer.CloseAllFilesInProjectContextMenu");
cmd->setAttribute(Command::CA_UpdateText);
cmd->setDescription(dd->m_closeProjectFilesActionContextMenu->text());
mprojectContextMenu->addAction(cmd, Constants::G_PROJECT_LAST);
// file properties action // file properties action
dd->m_filePropertiesAction = new QAction(tr("Properties..."), this); dd->m_filePropertiesAction = new QAction(tr("Properties..."), this);
cmd = ActionManager::registerAction(dd->m_filePropertiesAction, Constants::FILEPROPERTIES, cmd = ActionManager::registerAction(dd->m_filePropertiesAction, Constants::FILEPROPERTIES,
@@ -1442,6 +1464,10 @@ bool ProjectExplorerPlugin::initialize(const QStringList &arguments, QString *er
dd, &ProjectExplorerPluginPrivate::handleRenameFile); dd, &ProjectExplorerPluginPrivate::handleRenameFile);
connect(dd->m_setStartupProjectAction, &QAction::triggered, connect(dd->m_setStartupProjectAction, &QAction::triggered,
dd, &ProjectExplorerPluginPrivate::handleSetStartupProject); dd, &ProjectExplorerPluginPrivate::handleSetStartupProject);
connect(dd->m_closeProjectFilesActionFileMenu, &QAction::triggered,
dd, [] { dd->closeAllFilesInProject(SessionManager::projects().first()); });
connect(dd->m_closeProjectFilesActionContextMenu, &QAction::triggered,
dd, [] { dd->closeAllFilesInProject(ProjectTree::currentProject()); });
connect(dd->m_projectTreeCollapseAllAction, &QAction::triggered, connect(dd->m_projectTreeCollapseAllAction, &QAction::triggered,
ProjectTree::instance(), &ProjectTree::collapseAll); ProjectTree::instance(), &ProjectTree::collapseAll);
connect(dd->m_projectTreeExpandAllAction, &QAction::triggered, connect(dd->m_projectTreeExpandAllAction, &QAction::triggered,
@@ -1674,6 +1700,9 @@ void ProjectExplorerPlugin::unloadProject(Project *project)
if (!DocumentManager::saveModifiedDocumentSilently(document)) if (!DocumentManager::saveModifiedDocumentSilently(document))
return; return;
if (!dd->closeAllFilesInProject(project))
return;
dd->addToRecentProjects(document->filePath().toString(), project->displayName()); dd->addToRecentProjects(document->filePath().toString(), project->displayName());
SessionManager::removeProject(project); SessionManager::removeProject(project);
@@ -1824,6 +1853,26 @@ void ProjectExplorerPluginPrivate::setStartupProject(Project *project)
updateActions(); updateActions();
} }
bool ProjectExplorerPluginPrivate::closeAllFilesInProject(const Project *project)
{
QTC_ASSERT(project, return false);
const Utils::FileNameList filesInProject = project->files(Project::AllFiles);
QList<IDocument *> openFiles = DocumentModel::openedDocuments();
Utils::erase(openFiles, [filesInProject](const IDocument *doc) {
return !filesInProject.contains(doc->filePath());
});
for (const Project * const otherProject : SessionManager::projects()) {
if (otherProject == project)
continue;
const Utils::FileNameList filesInOtherProject
= otherProject->files(Project::AllFiles);
Utils::erase(openFiles, [filesInOtherProject](const IDocument *doc) {
return filesInOtherProject.contains(doc->filePath());
});
}
return EditorManager::closeDocuments(openFiles);
}
void ProjectExplorerPluginPrivate::savePersistentSettings() void ProjectExplorerPluginPrivate::savePersistentSettings()
{ {
if (dd->m_shuttingDown) if (dd->m_shuttingDown)
@@ -2332,6 +2381,8 @@ void ProjectExplorerPluginPrivate::updateActions()
m_unloadAction->setParameter(projectName); m_unloadAction->setParameter(projectName);
m_unloadActionContextMenu->setParameter(projectNameContextMenu); m_unloadActionContextMenu->setParameter(projectNameContextMenu);
m_closeProjectFilesActionFileMenu->setParameter(projectName);
m_closeProjectFilesActionContextMenu->setParameter(projectNameContextMenu);
// mode bar build action // mode bar build action
QAction * const buildAction = ActionManager::command(Constants::BUILD)->action(); QAction * const buildAction = ActionManager::command(Constants::BUILD)->action();
@@ -2390,6 +2441,9 @@ void ProjectExplorerPluginPrivate::updateActions()
m_unloadAction->setVisible(SessionManager::projects().size() <= 1); m_unloadAction->setVisible(SessionManager::projects().size() <= 1);
m_unloadAction->setEnabled(SessionManager::projects().size() == 1); m_unloadAction->setEnabled(SessionManager::projects().size() == 1);
m_unloadActionContextMenu->setEnabled(SessionManager::hasProjects()); m_unloadActionContextMenu->setEnabled(SessionManager::hasProjects());
m_closeProjectFilesActionFileMenu->setVisible(SessionManager::projects().size() <= 1);
m_closeProjectFilesActionFileMenu->setEnabled(SessionManager::projects().size() == 1);
m_closeProjectFilesActionContextMenu->setEnabled(SessionManager::hasProjects());
ActionContainer *aci = ActionContainer *aci =
ActionManager::actionContainer(Constants::M_UNLOADPROJECTS); ActionManager::actionContainer(Constants::M_UNLOADPROJECTS);

View File

@@ -179,12 +179,6 @@ Internal::QbsProject *QbsBuildConfiguration::project() const
return qobject_cast<Internal::QbsProject *>(BuildConfiguration::project()); return qobject_cast<Internal::QbsProject *>(BuildConfiguration::project());
} }
IOutputParser *QbsBuildConfiguration::createOutputParser() const
{
ToolChain *tc = ToolChainKitInformation::toolChain(target()->kit(), ProjectExplorer::Constants::CXX_LANGUAGE_ID);
return tc ? tc->outputParser() : nullptr;
}
bool QbsBuildConfiguration::isEnabled() const bool QbsBuildConfiguration::isEnabled() const
{ {
return !project()->isParsing() && project()->hasParseResult(); return !project()->isParsing() && project()->hasParseResult();

View File

@@ -57,8 +57,6 @@ public:
Internal::QbsProject *project() const override; Internal::QbsProject *project() const override;
ProjectExplorer::IOutputParser *createOutputParser() const;
bool isEnabled() const override; bool isEnabled() const override;
QString disabledReason() const override; QString disabledReason() const override;

View File

@@ -152,12 +152,6 @@ static int devicePixelHeight(const QPixmap &pixmap)
return pixmap.height() / pixmap.devicePixelRatioF(); return pixmap.height() / pixmap.devicePixelRatioF();
} }
static QString iconPath()
{
return Core::ICore::resourcePath()
+ QLatin1String("/qmldesigner/propertyEditorQmlSources/imports/HelperWidgets/images/");
}
void TimelineFrameHandle::paint(QPainter *painter, void TimelineFrameHandle::paint(QPainter *painter,
const QStyleOptionGraphicsItem * /*option*/, const QStyleOptionGraphicsItem * /*option*/,
QWidget * /*widget*/) QWidget * /*widget*/)

View File

@@ -120,7 +120,7 @@ void TimelineMoveTool::mouseReleaseEvent(TimelineMovableAbstractItem *item,
Q_UNUSED(event); Q_UNUSED(event);
if (auto *current = currentItem()) { if (auto *current = currentItem()) {
if (auto *playhead = current->asTimelineFrameHandle()) { if (current->asTimelineFrameHandle()) {
double mousePos = event->pos().x(); double mousePos = event->pos().x();
double start = current->mapFromFrameToScene(scene()->startFrame()); double start = current->mapFromFrameToScene(scene()->startFrame());
double end = current->mapFromFrameToScene(scene()->endFrame()); double end = current->mapFromFrameToScene(scene()->endFrame());
@@ -142,7 +142,7 @@ void TimelineMoveTool::mouseReleaseEvent(TimelineMovableAbstractItem *item,
current->commitPosition(mapToItem(current, current->rect().center())); current->commitPosition(mapToItem(current, current->rect().center()));
if (TimelineKeyframeItem *currentKeyframe = current->asTimelineKeyframeItem()) { if (current->asTimelineKeyframeItem()) {
double frame = std::round( double frame = std::round(
current->mapFromSceneToFrame(current->rect().center().x())); current->mapFromSceneToFrame(current->rect().center().x()));

View File

@@ -53,7 +53,7 @@ public:
: qmlError("(" QT_QML_URL_REGEXP // url : qmlError("(" QT_QML_URL_REGEXP // url
":\\d+" // colon, line ":\\d+" // colon, line
"(?::\\d+)?)" // colon, column (optional) "(?::\\d+)?)" // colon, column (optional)
"[: \t)]") // colon, space, tab or brace "\\b") // word boundary
, qtError("Object::.*in (.*:\\d+)") , qtError("Object::.*in (.*:\\d+)")
, qtAssert(QT_ASSERT_REGEXP) , qtAssert(QT_ASSERT_REGEXP)
, qtAssertX(QT_ASSERT_X_REGEXP) , qtAssertX(QT_ASSERT_X_REGEXP)
@@ -364,6 +364,26 @@ void QtSupportPlugin::testQtOutputFormatter_data()
<< 0 << 19 << "file:///main.qml:20" << 0 << 19 << "file:///main.qml:20"
<< "/main.qml" << 20 << -1; << "/main.qml" << 20 << -1;
QTest::newRow("File link without further text")
<< "file:///home/user/main.cpp:157"
<< 0 << 30 << "file:///home/user/main.cpp:157"
<< "/home/user/main.cpp" << 157 << -1;
QTest::newRow("File link with text before")
<< "Text before: file:///home/user/main.cpp:157"
<< 13 << 43 << "file:///home/user/main.cpp:157"
<< "/home/user/main.cpp" << 157 << -1;
QTest::newRow("File link with text afterwards")
<< "file:///home/user/main.cpp:157: Text afterwards"
<< 0 << 30 << "file:///home/user/main.cpp:157"
<< "/home/user/main.cpp" << 157 << -1;
QTest::newRow("File link with text before and afterwards")
<< "Text before file:///home/user/main.cpp:157 and text afterwards"
<< 12 << 42 << "file:///home/user/main.cpp:157"
<< "/home/user/main.cpp" << 157 << -1;
QTest::newRow("Unix file link with timestamp") QTest::newRow("Unix file link with timestamp")
<< "file:///home/user/main.cpp:157 2018-03-21 10:54:45.706" << "file:///home/user/main.cpp:157 2018-03-21 10:54:45.706"
<< 0 << 30 << "file:///home/user/main.cpp:157" << 0 << 30 << "file:///home/user/main.cpp:157"

View File

@@ -80,17 +80,26 @@ DocumentContentCompletionProcessor::~DocumentContentCompletionProcessor()
m_watcher.cancel(); m_watcher.cancel();
} }
static void createProposal(QFutureInterface<QStringList> &future, const QString text) static void createProposal(QFutureInterface<QStringList> &future, const QString &text,
const QString &wordUnderCursor)
{ {
const QRegularExpression wordRE("([a-zA-Z_][a-zA-Z0-9_]{2,})"); const QRegularExpression wordRE("([a-zA-Z_][a-zA-Z0-9_]{2,})");
QSet<QString> words; QSet<QString> words;
QRegularExpressionMatchIterator it = wordRE.globalMatch(text); QRegularExpressionMatchIterator it = wordRE.globalMatch(text);
int wordUnderCursorFound = 0;
while (it.hasNext()) { while (it.hasNext()) {
if (future.isCanceled()) if (future.isCanceled())
return; return;
QRegularExpressionMatch match = it.next(); QRegularExpressionMatch match = it.next();
const QString &word = match.captured(); const QString &word = match.captured();
if (word == wordUnderCursor) {
// Only add the word under cursor if it
// already appears elsewhere in the text
if (++wordUnderCursorFound < 2)
continue;
}
if (!words.contains(word)) if (!words.contains(word))
words.insert(word); words.insert(word);
} }
@@ -113,16 +122,18 @@ IAssistProposal *DocumentContentCompletionProcessor::perform(const AssistInterfa
} while (chr.isLetterOrNumber() || chr == '_'); } while (chr.isLetterOrNumber() || chr == '_');
++pos; ++pos;
int length = interface->position() - pos;
if (interface->reason() == IdleEditor) { if (interface->reason() == IdleEditor) {
QChar characterUnderCursor = interface->characterAt(interface->position()); QChar characterUnderCursor = interface->characterAt(interface->position());
if (characterUnderCursor.isLetterOrNumber() || interface->position() - pos < 3) if (characterUnderCursor.isLetterOrNumber() || length < 3)
return nullptr; return nullptr;
} }
const QString wordUnderCursor = interface->textAt(pos, length);
const QString text = interface->textDocument()->toPlainText(); const QString text = interface->textDocument()->toPlainText();
m_watcher.setFuture(Utils::runAsync(&createProposal, text)); m_watcher.setFuture(Utils::runAsync(&createProposal, text, wordUnderCursor));
QObject::connect(&m_watcher, &QFutureWatcher<QStringList>::resultReadyAt, QObject::connect(&m_watcher, &QFutureWatcher<QStringList>::resultReadyAt,
&m_watcher, [this, pos](int index){ &m_watcher, [this, pos](int index){
const TextEditor::SnippetAssistCollector snippetCollector( const TextEditor::SnippetAssistCollector snippetCollector(

View File

@@ -32,6 +32,7 @@
#include <coreplugin/icore.h> #include <coreplugin/icore.h>
#include <coreplugin/messagemanager.h> #include <coreplugin/messagemanager.h>
#include <utils/mimetypes/mimedatabase.h>
#include <Format> #include <Format>
#include <Repository> #include <Repository>
@@ -99,16 +100,48 @@ Highlighter::Highlighter()
&categoryForTextStyle); &categoryForTextStyle);
} }
KSyntaxHighlighting::Definition Highlighter::definitionForMimeType(const QString &mimeType) Highlighter::Definition Highlighter::definitionForDocument(const TextDocument *document)
{
const Utils::MimeType mimeType = Utils::mimeTypeForName(document->mimeType());
Definition definition;
if (mimeType.isValid())
definition = Highlighter::definitionForMimeType(mimeType.name());
if (!definition.isValid())
definition = Highlighter::definitionForFileName(document->filePath().fileName());
return definition;
}
Highlighter::Definition Highlighter::definitionForMimeType(const QString &mimeType)
{ {
return highlightRepository()->definitionForMimeType(mimeType); return highlightRepository()->definitionForMimeType(mimeType);
} }
KSyntaxHighlighting::Definition Highlighter::definitionForFileName(const QString &fileName) Highlighter::Definition Highlighter::definitionForFileName(const QString &fileName)
{ {
return highlightRepository()->definitionForFileName(fileName); return highlightRepository()->definitionForFileName(fileName);
} }
Highlighter::Definitions Highlighter::definitionsForDocument(const TextDocument *document)
{
const Utils::MimeType mimeType = Utils::mimeTypeForName(document->mimeType());
Definitions definitions;
if (mimeType.isValid())
definitions = Highlighter::definitionsForMimeType(mimeType.name());
if (definitions.isEmpty())
definitions = Highlighter::definitionsForFileName(document->filePath().fileName());
return definitions;
}
Highlighter::Definitions Highlighter::definitionsForMimeType(const QString &mimeType)
{
return highlightRepository()->definitionsForMimeType(mimeType).toList();
}
Highlighter::Definitions Highlighter::definitionsForFileName(const QString &fileName)
{
return highlightRepository()->definitionsForFileName(fileName).toList();
}
void Highlighter::addCustomHighlighterPath(const Utils::FileName &path) void Highlighter::addCustomHighlighterPath(const Utils::FileName &path)
{ {
highlightRepository()->addCustomSearchPath(path.toString()); highlightRepository()->addCustomSearchPath(path.toString());

View File

@@ -34,14 +34,22 @@
namespace TextEditor { namespace TextEditor {
class FontSettings; class FontSettings;
class TextDocument;
class Highlighter : public SyntaxHighlighter, public KSyntaxHighlighting::AbstractHighlighter class Highlighter : public SyntaxHighlighter, public KSyntaxHighlighting::AbstractHighlighter
{ {
public: public:
using Definition = KSyntaxHighlighting::Definition;
using Definitions = QList<Definition>;
Highlighter(); Highlighter();
static KSyntaxHighlighting::Definition definitionForMimeType(const QString &mimeType); static Definition definitionForDocument(const TextDocument *document);
static KSyntaxHighlighting::Definition definitionForFileName(const QString &fileName); static Definition definitionForMimeType(const QString &mimeType);
static Definition definitionForFileName(const QString &fileName);
static Definitions definitionsForDocument(const TextDocument *document);
static Definitions definitionsForMimeType(const QString &mimeType);
static Definitions definitionsForFileName(const QString &fileName);
static void addCustomHighlighterPath(const Utils::FileName &path); static void addCustomHighlighterPath(const Utils::FileName &path);
static void updateDefinitions(std::function<void()> callback = nullptr); static void updateDefinitions(std::function<void()> callback = nullptr);

View File

@@ -91,11 +91,10 @@ public:
} }
// By default just calls indent with default settings. // By default just calls indent with default settings.
virtual Replacements format(const QTextCursor &cursor, virtual Replacements format(const QTextCursor &/*cursor*/,
const TabSettings &tabSettings, const TabSettings &/*tabSettings*/,
int cursorPositionInEditor = -1) int /*cursorPositionInEditor*/ = -1)
{ {
indent(cursor, QChar::Null, tabSettings, cursorPositionInEditor);
return Replacements(); return Replacements();
} }

View File

@@ -611,6 +611,8 @@ public:
void updateCodeFoldingVisible(); void updateCodeFoldingVisible();
void reconfigure(); void reconfigure();
void updateSyntaxInfoBar(bool showInfo);
void configureGenericHighlighter(const KSyntaxHighlighting::Definition &definition);
public: public:
TextEditorWidget *q; TextEditorWidget *q;
@@ -768,8 +770,6 @@ public:
QScopedPointer<ClipboardAssistProvider> m_clipboardAssistProvider; QScopedPointer<ClipboardAssistProvider> m_clipboardAssistProvider;
bool m_isMissingSyntaxDefinition = false;
QScopedPointer<AutoCompleter> m_autoCompleter; QScopedPointer<AutoCompleter> m_autoCompleter;
CommentDefinition m_commentDefinition; CommentDefinition m_commentDefinition;
@@ -904,33 +904,6 @@ void TextEditorWidgetPrivate::showTextMarksToolTip(const QPoint &pos,
} // namespace Internal } // namespace Internal
/*!
* Test if syntax highlighter is available (or unneeded) for \a widget.
* If not found, show a warning with a link to the relevant settings page.
*/
static void updateEditorInfoBar(TextEditorWidget *widget)
{
Id id(Constants::INFO_SYNTAX_DEFINITION);
InfoBar *infoBar = widget->textDocument()->infoBar();
if (!widget->isMissingSyntaxDefinition()) {
infoBar->removeInfo(id);
} else if (infoBar->canInfoBeAdded(id)) {
InfoBarEntry info(id,
BaseTextEditor::tr("A highlight definition was not found for this file. "
"Would you like to update highlight definition files?"),
InfoBarEntry::GlobalSuppressionEnabled);
info.setCustomButtonInfo(BaseTextEditor::tr("Update Definitions"), [id, widget]() {
widget->textDocument()->infoBar()->removeInfo(id);
Highlighter::updateDefinitions([widget = QPointer<TextEditorWidget>(widget)]() {
if (widget)
widget->configureGenericHighlighter();
});
});
infoBar->addInfo(info);
}
}
QString TextEditorWidget::plainTextFromSelection(const QTextCursor &cursor) const QString TextEditorWidget::plainTextFromSelection(const QTextCursor &cursor) const
{ {
// Copy the selected text as plain text // Copy the selected text as plain text
@@ -3301,6 +3274,49 @@ void TextEditorWidgetPrivate::reconfigure()
q->configureGenericHighlighter(); q->configureGenericHighlighter();
} }
void TextEditorWidgetPrivate::updateSyntaxInfoBar(bool showInfo)
{
Id id(Constants::INFO_SYNTAX_DEFINITION);
InfoBar *infoBar = m_document->infoBar();
if (showInfo) {
InfoBarEntry info(id,
BaseTextEditor::tr(
"A highlight definition was not found for this file. "
"Would you like to update highlight definition files?"),
InfoBarEntry::GlobalSuppressionEnabled);
info.setCustomButtonInfo(BaseTextEditor::tr("Update Definitions"), [&]() {
m_document->infoBar()->removeInfo(id);
Highlighter::updateDefinitions([widget = QPointer<TextEditorWidget>(q)]() {
if (widget)
widget->configureGenericHighlighter();
});
});
infoBar->addInfo(info);
} else {
infoBar->removeInfo(id);
}
}
void TextEditorWidgetPrivate::configureGenericHighlighter(
const KSyntaxHighlighting::Definition &definition)
{
auto highlighter = new Highlighter();
m_document->setSyntaxHighlighter(highlighter);
if (definition.isValid()) {
highlighter->setDefinition(definition);
m_commentDefinition.singleLine = definition.singleLineCommentMarker();
m_commentDefinition.multiLineStart = definition.multiLineCommentMarker().first;
m_commentDefinition.multiLineEnd = definition.multiLineCommentMarker().second;
q->setCodeFoldingSupported(true);
} else {
q->setCodeFoldingSupported(false);
}
m_document->setFontSettings(TextEditorSettings::fontSettings());
}
bool TextEditorWidget::codeFoldingVisible() const bool TextEditorWidget::codeFoldingVisible() const
{ {
return d->m_codeFoldingVisible; return d->m_codeFoldingVisible;
@@ -8498,36 +8514,11 @@ QString TextEditorWidget::textAt(int from, int to) const
void TextEditorWidget::configureGenericHighlighter() void TextEditorWidget::configureGenericHighlighter()
{ {
auto highlighter = new Highlighter(); const Highlighter::Definition definition = Highlighter::definitionForDocument(textDocument());
textDocument()->setSyntaxHighlighter(highlighter); d->configureGenericHighlighter(definition);
d->updateSyntaxInfoBar(!definition.isValid()
setCodeFoldingSupported(false); && !TextEditorSettings::highlighterSettings().isIgnoredFilePattern(
textDocument()->filePath().fileName()));
const QString type = textDocument()->mimeType();
const MimeType mimeType = Utils::mimeTypeForName(type);
const QString fileName = textDocument()->filePath().fileName();
KSyntaxHighlighting::Definition definition;
if (mimeType.isValid())
definition = Highlighter::definitionForMimeType(mimeType.name());
if (!definition.isValid())
definition = Highlighter::definitionForFileName(fileName);
if (definition.isValid()) {
highlighter->setDefinition(definition);
d->m_isMissingSyntaxDefinition = false;
d->m_commentDefinition.singleLine = definition.singleLineCommentMarker();
d->m_commentDefinition.multiLineStart = definition.multiLineCommentMarker().first;
d->m_commentDefinition.multiLineEnd = definition.multiLineCommentMarker().second;
setCodeFoldingSupported(true);
} else {
d->m_isMissingSyntaxDefinition =
!TextEditorSettings::highlighterSettings().isIgnoredFilePattern(fileName);
}
textDocument()->setFontSettings(TextEditorSettings::fontSettings());
updateEditorInfoBar(this);
} }
int TextEditorWidget::blockNumberForVisibleRow(int row) const int TextEditorWidget::blockNumberForVisibleRow(int row) const
@@ -8562,11 +8553,6 @@ HighlightScrollBarController *TextEditorWidget::highlightScrollBarController() c
return d->m_highlightScrollBarController; return d->m_highlightScrollBarController;
} }
bool TextEditorWidget::isMissingSyntaxDefinition() const
{
return d->m_isMissingSyntaxDefinition;
}
// The remnants of PlainTextEditor. // The remnants of PlainTextEditor.
void TextEditorWidget::setupGenericHighlighter() void TextEditorWidget::setupGenericHighlighter()
{ {
@@ -8574,8 +8560,6 @@ void TextEditorWidget::setupGenericHighlighter()
connect(textDocument(), &IDocument::filePathChanged, connect(textDocument(), &IDocument::filePathChanged,
d, &TextEditorWidgetPrivate::reconfigure); d, &TextEditorWidgetPrivate::reconfigure);
updateEditorInfoBar(this);
} }
// //

View File

@@ -332,7 +332,6 @@ public:
// the blocks list must be sorted // the blocks list must be sorted
void setIfdefedOutBlocks(const QList<BlockRange> &blocks); void setIfdefedOutBlocks(const QList<BlockRange> &blocks);
bool isMissingSyntaxDefinition() const;
enum Side { Left, Right }; enum Side { Left, Right };
QAction *insertExtraToolBarWidget(Side side, QWidget *widget); QAction *insertExtraToolBarWidget(Side side, QWidget *widget);

28
src/shared/shared.pro Normal file
View File

@@ -0,0 +1,28 @@
TEMPLATE = subdirs
QBS_DIRS = \
qbscorelib \
qbsqtprofilesetup \
qbsapps \
qbslibexec \
qbsplugins \
qbsstatic
qbscorelib.subdir = qbs/src/lib/corelib
qbsqtprofilesetup.subdir = qbs/src/lib/qtprofilesetup
qbsqtprofilesetup.depends = qbscorelib
qbsapps.subdir = qbs/src/app
qbsapps.depends = qbsqtprofilesetup
qbslibexec.subdir = qbs/src/libexec
qbslibexec.depends = qbscorelib
qbsplugins.subdir = qbs/src/plugins
qbsplugins.depends = qbscorelib
qbsstatic.file = qbs/static.pro
exists(qbs/qbs.pro) {
isEmpty(QBS_INSTALL_DIR):QBS_INSTALL_DIR = $$(QBS_INSTALL_DIR)
isEmpty(QBS_INSTALL_DIR):SUBDIRS += $$QBS_DIRS
}
TR_EXCLUDE = qbs
QMAKE_EXTRA_TARGETS += deployqt # dummy

View File

@@ -1,36 +1,16 @@
include(../qtcreator.pri)
TEMPLATE = subdirs TEMPLATE = subdirs
CONFIG += ordered CONFIG += ordered
QBS_DIRS = \
qbscorelib \
qbsqtprofilesetup \
qbsapps \
qbslibexec \
qbsplugins \
qbsstatic
qbscorelib.subdir = shared/qbs/src/lib/corelib
qbsqtprofilesetup.subdir = shared/qbs/src/lib/qtprofilesetup
qbsqtprofilesetup.depends = qbscorelib
qbsapps.subdir = shared/qbs/src/app
qbsapps.depends = qbsqtprofilesetup
qbslibexec.subdir = shared/qbs/src/libexec
qbslibexec.depends = qbscorelib
qbsplugins.subdir = shared/qbs/src/plugins
qbsstatic.file = shared/qbs/static.pro
exists(shared/qbs/qbs.pro) {
isEmpty(QBS_INSTALL_DIR):QBS_INSTALL_DIR = $$(QBS_INSTALL_DIR)
isEmpty(QBS_INSTALL_DIR):SUBDIRS += $$QBS_DIRS
}
TR_EXCLUDE = shared/qbs
SUBDIRS += \ SUBDIRS += \
shared \
libs \ libs \
app \ app \
plugins \ plugins \
tools \ tools \
share/qtcreator/data.pro \ share/qtcreator/data.pro \
share/3rdparty/data.pro share/3rdparty/data.pro
# delegate deployqt target
deployqt.CONFIG += recursive
deployqt.recurse = shared libs app plugins tools
QMAKE_EXTRA_TARGETS += deployqt

View File

@@ -82,15 +82,6 @@ bool PchCreator::generatePch()
return tool.run(action.get()) != 1; return tool.run(action.get()) != 1;
} }
FilePath PchCreator::generatePchHeaderFilePath() const
{
std::uniform_int_distribution<std::mt19937_64::result_type> distribution;
return FilePathView{Utils::PathString{Utils::SmallString(m_environment.pchBuildDirectory()),
"/",
std::to_string(distribution(randomNumberGenator)),
".h"}};
}
FilePath PchCreator::generatePchFilePath() const FilePath PchCreator::generatePchFilePath() const
{ {
@@ -103,8 +94,7 @@ FilePath PchCreator::generatePchFilePath() const
".pch"}}; ".pch"}};
} }
std::vector<std::string> PchCreator::generateClangCompilerArguments( Utils::SmallStringVector PchCreator::generateClangCompilerArguments(const PchTask &pchTask,
const PchTask &pchTask,
FilePathView sourceFilePath, FilePathView sourceFilePath,
FilePathView pchOutputPath) FilePathView pchOutputPath)
{ {
@@ -121,15 +111,14 @@ void PchCreator::generatePch(PchTask &&pchTask)
{ {
long long lastModified = QDateTime::currentSecsSinceEpoch(); long long lastModified = QDateTime::currentSecsSinceEpoch();
auto content = generatePchIncludeFileContent(pchTask.includes); auto content = generatePchIncludeFileContent(pchTask.includes);
auto pchSourceFilePath = generatePchHeaderFilePath();
auto pchOutputPath = generatePchFilePath(); auto pchOutputPath = generatePchFilePath();
generateFileWithContent(pchSourceFilePath, content);
m_clangTool.addFile( FilePath headerFilePath{m_environment.pchBuildDirectory().toStdString(), "dummy.h"};
pchSourceFilePath.directory(), Utils::SmallStringVector commandLine = generateClangCompilerArguments(pchTask,
pchSourceFilePath.name(), headerFilePath,
"", pchOutputPath);
generateClangCompilerArguments(pchTask, pchSourceFilePath, pchOutputPath));
m_clangTool.addFile(std::move(headerFilePath), std::move(content), std::move(commandLine));
bool success = generatePch(); bool success = generatePch();
@@ -179,17 +168,4 @@ const FilePathCaching &PchCreator::filePathCache()
return m_filePathCache; return m_filePathCache;
} }
std::unique_ptr<QFile> PchCreator::generateFileWithContent(const Utils::SmallString &filePath,
const Utils::SmallString &content)
{
std::unique_ptr<QFile> precompiledIncludeFile(new QFile(QString(filePath)));
precompiledIncludeFile->open(QIODevice::WriteOnly);
precompiledIncludeFile->write(content.data(), qint64(content.size()));
precompiledIncludeFile->close();
return precompiledIncludeFile;
}
} // namespace ClangBackEnd } // namespace ClangBackEnd

View File

@@ -83,13 +83,10 @@ public:
Utils::SmallString generatePchIncludeFileContent(const FilePathIds &includeIds) const; Utils::SmallString generatePchIncludeFileContent(const FilePathIds &includeIds) const;
bool generatePch(); bool generatePch();
FilePath generatePchHeaderFilePath() const;
FilePath generatePchFilePath() const; FilePath generatePchFilePath() const;
static std::vector<std::string> generateClangCompilerArguments(const PchTask &pchTask, static Utils::SmallStringVector generateClangCompilerArguments(const PchTask &pchTask,
FilePathView includePchHeaderPath, FilePathView includePchHeaderPath,
FilePathView pchPath); FilePathView pchPath);
static std::unique_ptr<QFile> generateFileWithContent(const Utils::SmallString &filePath,
const Utils::SmallString &content);
const ClangTool &clangTool() const const ClangTool &clangTool() const
{ {

Some files were not shown because too many files have changed in this diff Show More