ClangFormat: Change the logic how configuration is picked

Let's use by default the configuration that clang-format picks itself
for the source file. The Qt Creator configuration will now only
override the default one with global or project settings and can be
turned off with the checkbox.

This behavior is clearer than always picking some configuration
which Qt Creator prefers best.

Change-Id: If5ed3d67eb6b4b47a6d0fd5259f7efbb608914d1
Reviewed-by: Marco Bubke <marco.bubke@qt.io>
Reviewed-by: Leena Miettinen <riitta-leena.miettinen@qt.io>
This commit is contained in:
Ivan Donchevskii
2019-03-05 13:12:44 +01:00
parent 2484a5e209
commit bf972bcb01
8 changed files with 143 additions and 73 deletions

View File

@@ -59,6 +59,24 @@ ClangFormatConfigWidget::ClangFormatConfigWidget(ProjectExplorer::Project *proje
{ {
m_ui->setupUi(this); m_ui->setupUi(this);
m_preview = new TextEditor::SnippetEditorWidget(this);
m_ui->horizontalLayout_2->addWidget(m_preview);
if (m_project) {
m_ui->applyButton->show();
hideGlobalCheckboxes();
m_ui->overrideDefault->setChecked(
m_project->namedSettings(Constants::OVERRIDE_FILE_ID).toBool());
} else {
m_ui->applyButton->hide();
showGlobalCheckboxes();
m_ui->overrideDefault->setChecked(ClangFormatSettings::instance().overrideDefaultFile());
}
connect(m_ui->overrideDefault, &QCheckBox::toggled, this, [this](bool checked) {
if (checked)
createStyleFileIfNeeded(!m_project);
initialize();
});
initialize(); initialize();
} }
@@ -81,15 +99,18 @@ void ClangFormatConfigWidget::showGlobalCheckboxes()
m_ui->formatOnSave->show(); m_ui->formatOnSave->show();
} }
static bool projectConfigExists()
{
return Utils::FileName::fromString(Core::ICore::userResourcePath())
.appendPath(currentProjectUniqueId())
.appendPath((Constants::SETTINGS_FILE_NAME))
.exists();
}
void ClangFormatConfigWidget::initialize() void ClangFormatConfigWidget::initialize()
{ {
m_ui->projectHasClangFormat->show(); m_ui->projectHasClangFormat->hide();
m_ui->clangFormatOptionsTable->show();
m_ui->applyButton->show();
hideGlobalCheckboxes();
m_preview = new TextEditor::SnippetEditorWidget(this);
m_ui->horizontalLayout_2->addWidget(m_preview);
m_preview->setPlainText(QLatin1String(CppTools::Constants::DEFAULT_CODE_STYLE_SNIPPETS[0])); m_preview->setPlainText(QLatin1String(CppTools::Constants::DEFAULT_CODE_STYLE_SNIPPETS[0]));
m_preview->textDocument()->setIndenter(new ClangFormatIndenter(m_preview->document())); m_preview->textDocument()->setIndenter(new ClangFormatIndenter(m_preview->document()));
m_preview->textDocument()->setFontSettings(TextEditor::TextEditorSettings::fontSettings()); m_preview->textDocument()->setFontSettings(TextEditor::TextEditorSettings::fontSettings());
@@ -103,21 +124,15 @@ void ClangFormatConfigWidget::initialize()
if (lastItem->spacerItem()) if (lastItem->spacerItem())
m_ui->verticalLayout->removeItem(lastItem); m_ui->verticalLayout->removeItem(lastItem);
if (m_project if (!m_ui->overrideDefault->isChecked()) {
&& !m_project->projectDirectory().appendPath(Constants::SETTINGS_FILE_NAME).exists()) {
m_ui->projectHasClangFormat->setText(tr("No .clang-format file for the project."));
m_ui->clangFormatOptionsTable->hide(); m_ui->clangFormatOptionsTable->hide();
m_ui->applyButton->hide(); m_preview->hide();
m_ui->verticalLayout->addStretch(1); m_ui->verticalLayout->addStretch(1);
connect(m_ui->createFileButton, &QPushButton::clicked, this, [this]() {
createStyleFileIfNeeded(false);
initialize();
});
return; return;
} }
m_ui->createFileButton->hide(); m_ui->clangFormatOptionsTable->show();
m_preview->show();
Utils::FileName fileName; Utils::FileName fileName;
if (m_project) { if (m_project) {
@@ -126,19 +141,13 @@ void ClangFormatConfigWidget::initialize()
fileName = m_project->projectFilePath().appendPath("snippet.cpp"); fileName = m_project->projectFilePath().appendPath("snippet.cpp");
} else { } else {
const Project *currentProject = SessionManager::startupProject(); const Project *currentProject = SessionManager::startupProject();
if (!currentProject if (!currentProject || !projectConfigExists()) {
|| !currentProject->projectDirectory()
.appendPath(Constants::SETTINGS_FILE_NAME)
.exists()) {
m_ui->projectHasClangFormat->hide(); m_ui->projectHasClangFormat->hide();
} else { } else {
m_ui->projectHasClangFormat->setText( m_ui->projectHasClangFormat->setText(
tr("Current project has its own .clang-format file " tr("Current project has its own overridden .clang-format file "
"and can be configured in Projects > Code Style > C++.")); "and can be configured in Projects > Code Style > C++."));
} }
createStyleFileIfNeeded(true);
showGlobalCheckboxes();
m_ui->applyButton->hide();
fileName = Utils::FileName::fromString(Core::ICore::userResourcePath()) fileName = Utils::FileName::fromString(Core::ICore::userResourcePath())
.appendPath("snippet.cpp"); .appendPath("snippet.cpp");
} }
@@ -160,7 +169,7 @@ void ClangFormatConfigWidget::fillTable()
{ {
clang::format::FormatStyle style = m_project ? currentProjectStyle() : currentGlobalStyle(); clang::format::FormatStyle style = m_project ? currentProjectStyle() : currentGlobalStyle();
std::string configText = clang::format::configurationAsText(style); const std::string configText = clang::format::configurationAsText(style);
m_ui->clangFormatOptionsTable->setPlainText(QString::fromStdString(configText)); m_ui->clangFormatOptionsTable->setPlainText(QString::fromStdString(configText));
} }
@@ -168,13 +177,16 @@ ClangFormatConfigWidget::~ClangFormatConfigWidget() = default;
void ClangFormatConfigWidget::apply() void ClangFormatConfigWidget::apply()
{ {
if (!m_project) {
ClangFormatSettings &settings = ClangFormatSettings::instance(); ClangFormatSettings &settings = ClangFormatSettings::instance();
if (!m_project) {
settings.setFormatCodeInsteadOfIndent(m_ui->formatAlways->isChecked()); settings.setFormatCodeInsteadOfIndent(m_ui->formatAlways->isChecked());
settings.setFormatWhileTyping(m_ui->formatWhileTyping->isChecked()); settings.setFormatWhileTyping(m_ui->formatWhileTyping->isChecked());
settings.setFormatOnSave(m_ui->formatOnSave->isChecked()); settings.setFormatOnSave(m_ui->formatOnSave->isChecked());
settings.write(); settings.setOverrideDefaultFile(m_ui->overrideDefault->isChecked());
} else {
m_project->setNamedSettings(Constants::OVERRIDE_FILE_ID, m_ui->overrideDefault->isChecked());
} }
settings.write();
const QString text = m_ui->clangFormatOptionsTable->toPlainText(); const QString text = m_ui->clangFormatOptionsTable->toPlainText();
clang::format::FormatStyle style; clang::format::FormatStyle style;
@@ -184,16 +196,18 @@ void ClangFormatConfigWidget::apply()
QMessageBox::warning(this, QMessageBox::warning(this,
tr("Error in ClangFormat configuration"), tr("Error in ClangFormat configuration"),
QString::fromStdString(error.message())); QString::fromStdString(error.message()));
if (m_ui->overrideDefault->isChecked()) {
fillTable(); fillTable();
updatePreview(); updatePreview();
}
return; return;
} }
QString filePath; QString filePath = Core::ICore::userResourcePath();
if (m_project) if (m_project)
filePath = m_project->projectDirectory().appendPath(Constants::SETTINGS_FILE_NAME).toString(); filePath += "/" + currentProjectUniqueId();
else filePath += "/" + QLatin1String(Constants::SETTINGS_FILE_NAME);
filePath = Core::ICore::userResourcePath() + "/" + Constants::SETTINGS_FILE_NAME;
QFile file(filePath); QFile file(filePath);
if (!file.open(QFile::WriteOnly)) if (!file.open(QFile::WriteOnly))
return; return;
@@ -201,6 +215,7 @@ void ClangFormatConfigWidget::apply()
file.write(text.toUtf8()); file.write(text.toUtf8());
file.close(); file.close();
if (m_ui->overrideDefault->isChecked())
updatePreview(); updatePreview();
} }

View File

@@ -54,6 +54,13 @@
</property> </property>
</widget> </widget>
</item> </item>
<item>
<widget class="QCheckBox" name="overrideDefault">
<property name="text">
<string>Override Clang Format configuration file</string>
</property>
</widget>
</item>
<item> <item>
<layout class="QHBoxLayout" name="horizontalLayout_2"> <layout class="QHBoxLayout" name="horizontalLayout_2">
<item> <item>
@@ -63,13 +70,6 @@
</item> </item>
<item> <item>
<layout class="QHBoxLayout" name="horizontalLayout"> <layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QPushButton" name="createFileButton">
<property name="text">
<string>Create Clang Format Configuration File</string>
</property>
</widget>
</item>
<item> <item>
<widget class="QPushButton" name="applyButton"> <widget class="QPushButton" name="applyButton">
<property name="text"> <property name="text">

View File

@@ -34,5 +34,6 @@ static const char SETTINGS_ID[] = "ClangFormat";
static const char FORMAT_CODE_INSTEAD_OF_INDENT_ID[] = "ClangFormat.FormatCodeInsteadOfIndent"; static const char FORMAT_CODE_INSTEAD_OF_INDENT_ID[] = "ClangFormat.FormatCodeInsteadOfIndent";
static const char FORMAT_WHILE_TYPING_ID[] = "ClangFormat.FormatWhileTyping"; static const char FORMAT_WHILE_TYPING_ID[] = "ClangFormat.FormatWhileTyping";
static const char FORMAT_CODE_ON_SAVE_ID[] = "ClangFormat.FormatCodeOnSave"; static const char FORMAT_CODE_ON_SAVE_ID[] = "ClangFormat.FormatCodeOnSave";
static const char OVERRIDE_FILE_ID[] = "ClangFormat.OverrideFile";
} // namespace Constants } // namespace Constants
} // namespace ClangFormat } // namespace ClangFormat

View File

@@ -57,7 +57,7 @@ bool ClangFormatIndenter::formatWhileTyping() const
Utils::optional<TabSettings> ClangFormatIndenter::tabSettings() const Utils::optional<TabSettings> ClangFormatIndenter::tabSettings() const
{ {
FormatStyle style = currentProjectStyle(); FormatStyle style = styleForFile();
TabSettings tabSettings; TabSettings tabSettings;
switch (style.UseTab) { switch (style.UseTab) {

View File

@@ -46,6 +46,8 @@ ClangFormatSettings::ClangFormatSettings()
.toBool(); .toBool();
m_formatOnSave = settings->value(QLatin1String(Constants::FORMAT_CODE_ON_SAVE_ID), false) m_formatOnSave = settings->value(QLatin1String(Constants::FORMAT_CODE_ON_SAVE_ID), false)
.toBool(); .toBool();
m_overrideDefaultFile = settings->value(QLatin1String(Constants::OVERRIDE_FILE_ID), false)
.toBool();
settings->endGroup(); settings->endGroup();
} }
@@ -57,6 +59,7 @@ void ClangFormatSettings::write() const
m_formatCodeInsteadOfIndent); m_formatCodeInsteadOfIndent);
settings->setValue(QLatin1String(Constants::FORMAT_WHILE_TYPING_ID), m_formatWhileTyping); settings->setValue(QLatin1String(Constants::FORMAT_WHILE_TYPING_ID), m_formatWhileTyping);
settings->setValue(QLatin1String(Constants::FORMAT_CODE_ON_SAVE_ID), m_formatOnSave); settings->setValue(QLatin1String(Constants::FORMAT_CODE_ON_SAVE_ID), m_formatOnSave);
settings->setValue(QLatin1String(Constants::OVERRIDE_FILE_ID), m_overrideDefaultFile);
settings->endGroup(); settings->endGroup();
} }
@@ -90,4 +93,14 @@ bool ClangFormatSettings::formatOnSave() const
return m_formatOnSave; return m_formatOnSave;
} }
void ClangFormatSettings::setOverrideDefaultFile(bool enable)
{
m_overrideDefaultFile = enable;
}
bool ClangFormatSettings::overrideDefaultFile() const
{
return m_overrideDefaultFile;
}
} // namespace ClangFormat } // namespace ClangFormat

View File

@@ -25,6 +25,8 @@
#pragma once #pragma once
#include <QString>
namespace ClangFormat { namespace ClangFormat {
class ClangFormatSettings class ClangFormatSettings
@@ -43,10 +45,14 @@ public:
void setFormatOnSave(bool enable); void setFormatOnSave(bool enable);
bool formatOnSave() const; bool formatOnSave() const;
void setOverrideDefaultFile(bool enable);
bool overrideDefaultFile() const;
private: private:
bool m_formatCodeInsteadOfIndent = false; bool m_formatCodeInsteadOfIndent = false;
bool m_formatWhileTyping = false; bool m_formatWhileTyping = false;
bool m_formatOnSave = false; bool m_formatOnSave = false;
bool m_overrideDefaultFile = false;
}; };
} // namespace ClangFormat } // namespace ClangFormat

View File

@@ -26,6 +26,7 @@
#include "clangformatutils.h" #include "clangformatutils.h"
#include "clangformatconstants.h" #include "clangformatconstants.h"
#include "clangformatsettings.h"
#include <coreplugin/icore.h> #include <coreplugin/icore.h>
#include <cpptools/cppcodestylesettings.h> #include <cpptools/cppcodestylesettings.h>
@@ -33,6 +34,8 @@
#include <projectexplorer/project.h> #include <projectexplorer/project.h>
#include <projectexplorer/session.h> #include <projectexplorer/session.h>
#include <QCryptographicHash>
using namespace clang; using namespace clang;
using namespace format; using namespace format;
using namespace llvm; using namespace llvm;
@@ -92,13 +95,26 @@ static void applyCppCodeStyleSettings(clang::format::FormatStyle &style,
: - static_cast<int>(style.IndentWidth); : - static_cast<int>(style.IndentWidth);
} }
static Utils::FileName projectPath() static bool useGlobalOverriddenSettings()
{
return ClangFormatSettings::instance().overrideDefaultFile();
}
QString currentProjectUniqueId()
{ {
const Project *project = SessionManager::startupProject(); const Project *project = SessionManager::startupProject();
if (project) if (!project)
return project->projectDirectory(); return QString();
return Utils::FileName(); return QString::fromUtf8(QCryptographicHash::hash(project->projectFilePath().toString().toUtf8(),
QCryptographicHash::Md5)
.toHex(0));
}
static bool useProjectOverriddenSettings()
{
const Project *project = SessionManager::startupProject();
return project ? project->namedSettings(Constants::OVERRIDE_FILE_ID).toBool() : false;
} }
static Utils::FileName globalPath() static Utils::FileName globalPath()
@@ -106,25 +122,40 @@ static Utils::FileName globalPath()
return Utils::FileName::fromString(Core::ICore::userResourcePath()); return Utils::FileName::fromString(Core::ICore::userResourcePath());
} }
static QString configForFile(Utils::FileName fileName) static Utils::FileName projectPath()
{ {
Utils::FileName topProjectPath = projectPath(); const Project *project = SessionManager::startupProject();
if (topProjectPath.isEmpty()) if (project)
return QString(); return globalPath().appendPath("clang-format").appendPath(currentProjectUniqueId());
QDir projectDir(fileName.parentDir().toString()); return Utils::FileName();
while (!projectDir.exists(Constants::SETTINGS_FILE_NAME)
&& !projectDir.exists(Constants::SETTINGS_FILE_ALT_NAME)) {
if (projectDir.path() == topProjectPath.toString()
|| !Utils::FileName::fromString(projectDir.path()).isChildOf(topProjectPath)
|| !projectDir.cdUp()) {
return QString();
}
} }
if (projectDir.exists(Constants::SETTINGS_FILE_NAME)) static QString configForFile(Utils::FileName fileName, bool checkForSettings)
return projectDir.filePath(Constants::SETTINGS_FILE_NAME); {
return projectDir.filePath(Constants::SETTINGS_FILE_ALT_NAME); QDir overrideDir;
if (!checkForSettings || useProjectOverriddenSettings()) {
overrideDir = projectPath().toString();
if (!overrideDir.isEmpty() && overrideDir.exists(Constants::SETTINGS_FILE_NAME))
return overrideDir.filePath(Constants::SETTINGS_FILE_NAME);
}
if (!checkForSettings || useGlobalOverriddenSettings()) {
overrideDir = globalPath().toString();
if (!overrideDir.isEmpty() && overrideDir.exists(Constants::SETTINGS_FILE_NAME))
return overrideDir.filePath(Constants::SETTINGS_FILE_NAME);
}
QDir parentDir(fileName.parentDir().toString());
while (!parentDir.exists(Constants::SETTINGS_FILE_NAME)
&& !parentDir.exists(Constants::SETTINGS_FILE_ALT_NAME)) {
if (!parentDir.cdUp())
return QString();
}
if (parentDir.exists(Constants::SETTINGS_FILE_NAME))
return parentDir.filePath(Constants::SETTINGS_FILE_NAME);
return parentDir.filePath(Constants::SETTINGS_FILE_ALT_NAME);
} }
static clang::format::FormatStyle constructStyle(bool isGlobal, static clang::format::FormatStyle constructStyle(bool isGlobal,
@@ -169,6 +200,7 @@ void createStyleFileIfNeeded(bool isGlobal)
if (QFile::exists(configFile)) if (QFile::exists(configFile))
return; return;
QDir().mkpath(path.parentDir().toString());
std::fstream newStyleFile(configFile.toStdString(), std::fstream::out); std::fstream newStyleFile(configFile.toStdString(), std::fstream::out);
if (newStyleFile.is_open()) { if (newStyleFile.is_open()) {
newStyleFile << clang::format::configurationAsText(constructStyle(isGlobal)); newStyleFile << clang::format::configurationAsText(constructStyle(isGlobal));
@@ -198,16 +230,11 @@ static QByteArray configBaseStyleName(const QString &configFile)
.trimmed(); .trimmed();
} }
clang::format::FormatStyle styleForFile(Utils::FileName fileName) static clang::format::FormatStyle styleForFile(Utils::FileName fileName, bool checkForSettings)
{ {
bool isGlobal = false; QString configFile = configForFile(fileName, checkForSettings);
QString configFile = configForFile(fileName); if (configFile.isEmpty())
if (configFile.isEmpty()) { return constructStyle(true);
Utils::FileName path = fileName = globalPath();
fileName.appendPath(Constants::SAMPLE_FILE_NAME);
createStyleFileIfNeeded(true);
configFile = path.appendPath(Constants::SETTINGS_FILE_NAME).toString();
}
Expected<FormatStyle> style = format::getStyle("file", Expected<FormatStyle> style = format::getStyle("file",
fileName.toString().toStdString(), fileName.toString().toStdString(),
@@ -219,17 +246,22 @@ clang::format::FormatStyle styleForFile(Utils::FileName fileName)
// do nothing // do nothing
}); });
return constructStyle(isGlobal, configBaseStyleName(configFile)); return constructStyle(true, configBaseStyleName(configFile));
}
clang::format::FormatStyle styleForFile(Utils::FileName fileName)
{
return styleForFile(fileName, true);
} }
clang::format::FormatStyle currentProjectStyle() clang::format::FormatStyle currentProjectStyle()
{ {
return styleForFile(projectPath().appendPath(Constants::SAMPLE_FILE_NAME)); return styleForFile(projectPath().appendPath(Constants::SAMPLE_FILE_NAME), false);
} }
clang::format::FormatStyle currentGlobalStyle() clang::format::FormatStyle currentGlobalStyle()
{ {
return styleForFile(globalPath().appendPath(Constants::SAMPLE_FILE_NAME)); return styleForFile(globalPath().appendPath(Constants::SAMPLE_FILE_NAME), false);
} }
} }

View File

@@ -25,6 +25,7 @@
#pragma once #pragma once
#include <coreplugin/id.h>
#include <utils/fileutils.h> #include <utils/fileutils.h>
#include <clang/Format/Format.h> #include <clang/Format/Format.h>
@@ -37,6 +38,8 @@ namespace ClangFormat {
// Creates the style for the current project or the global style if needed. // Creates the style for the current project or the global style if needed.
void createStyleFileIfNeeded(bool isGlobal); void createStyleFileIfNeeded(bool isGlobal);
QString currentProjectUniqueId();
clang::format::FormatStyle currentProjectStyle(); clang::format::FormatStyle currentProjectStyle();
clang::format::FormatStyle currentGlobalStyle(); clang::format::FormatStyle currentGlobalStyle();