ClangFormat: Rework clangformatconfigwidget

- Move logic work with clang-format file to
additional class to make clangformatconfigwidget
responsible only for work with ui elements.
- Fix functionality: when new BasedOnStyle was
chosen all fields were empty or set in default,
now it fills with the corresponding value.

Change-Id: I2ee42a502e87da761274d293a7f0a38fda98804d
Reviewed-by: Christian Kandeler <christian.kandeler@qt.io>
This commit is contained in:
Artem Sokolovskii
2021-09-28 10:26:34 +02:00
parent ec74c36a8c
commit 8b263b4ae5
7 changed files with 217 additions and 64 deletions

View File

@@ -8,6 +8,7 @@ add_qtc_plugin(ClangFormat
clangformatchecks.ui
clangformatconfigwidget.cpp clangformatconfigwidget.h clangformatconfigwidget.ui
clangformatconstants.h
clangformatfile.cpp clangformatfile.h
clangformatindenter.cpp clangformatindenter.h
clangformatplugin.cpp clangformatplugin.h
clangformatsettings.cpp clangformatsettings.h

View File

@@ -15,6 +15,7 @@ unix:!macos:QMAKE_LFLAGS += -Wl,--exclude-libs,ALL
SOURCES += \
clangformatconfigwidget.cpp \
clangformatfile.cpp \
clangformatindenter.cpp \
clangformatplugin.cpp \
clangformatsettings.cpp \
@@ -22,6 +23,7 @@ SOURCES += \
HEADERS += \
clangformatconfigwidget.h \
clangformatfile.h \
clangformatindenter.h \
clangformatplugin.h \
clangformatsettings.h \

View File

@@ -33,6 +33,8 @@ QtcPlugin {
"clangformatconfigwidget.h",
"clangformatconfigwidget.ui",
"clangformatconstants.h",
"clangformatfile.cpp",
"clangformatfile.h",
"clangformatindenter.cpp",
"clangformatindenter.h",
"clangformatplugin.cpp",

View File

@@ -27,6 +27,7 @@
#include "clangformatconstants.h"
#include "clangformatindenter.h"
#include "clangformatfile.h"
#include "clangformatsettings.h"
#include "clangformatutils.h"
#include "ui_clangformatchecks.h"
@@ -121,6 +122,12 @@ ClangFormatConfigWidget::ClangFormatConfigWidget(ProjectExplorer::Project *proje
{
m_ui->setupUi(this);
Utils::FilePath filePath = Core::ICore::userResourcePath();
if (m_project)
filePath = filePath / "clang-format/" / currentProjectUniqueId();
filePath = filePath / QLatin1String(Constants::SETTINGS_FILE_NAME);
m_config = std::make_unique<ClangFormatFile>(filePath);
initChecksAndPreview();
if (m_project) {
@@ -147,6 +154,8 @@ ClangFormatConfigWidget::ClangFormatConfigWidget(ProjectExplorer::Project *proje
connectChecks();
}
ClangFormatConfigWidget::~ClangFormatConfigWidget() = default;
void ClangFormatConfigWidget::initChecksAndPreview()
{
m_checksScrollArea = new QScrollArea();
@@ -191,7 +200,7 @@ void ClangFormatConfigWidget::connectChecks()
continue;
}
auto button = qobject_cast<QPushButton *>(child);
const auto button = qobject_cast<QPushButton *>(child);
if (button != nullptr)
connect(button, &QPushButton::clicked, this, &ClangFormatConfigWidget::onTableChanged);
}
@@ -202,15 +211,7 @@ void ClangFormatConfigWidget::onTableChanged()
if (m_disableTableUpdate)
return;
const std::string newConfig = tableToString(sender());
if (newConfig.empty())
return;
const std::string oldConfig = m_project ? currentProjectConfigText()
: currentGlobalConfigText();
saveConfig(newConfig);
fillTable();
updatePreview();
saveConfig(oldConfig);
saveChanges(sender());
}
void ClangFormatConfigWidget::hideGlobalCheckboxes()
@@ -379,16 +380,20 @@ void ClangFormatConfigWidget::fillTable()
}
}
std::string ClangFormatConfigWidget::tableToString(QObject *sender)
void ClangFormatConfigWidget::saveChanges(QObject *sender)
{
std::stringstream content;
content << "---";
if (sender->objectName() == "BasedOnStyle") {
auto *basedOnStyle = m_checksWidget->findChild<QComboBox *>("BasedOnStyle");
content << "\nBasedOnStyle: " << basedOnStyle->currentText().toStdString() << '\n';
const auto *basedOnStyle = m_checksWidget->findChild<QComboBox *>("BasedOnStyle");
m_config->setBasedOnStyle(basedOnStyle->currentText());
} else {
QList<ClangFormatFile::Field> fields;
for (QObject *child : m_checksWidget->children()) {
if (child->objectName() == "BasedOnStyle")
continue;
auto *label = qobject_cast<QLabel *>(child);
if (!label)
continue;
@@ -396,7 +401,7 @@ std::string ClangFormatConfigWidget::tableToString(QObject *sender)
QWidget *valueWidget = m_checksWidget->findChild<QWidget *>(label->text().trimmed());
if (!valueWidget) {
// Currently BraceWrapping only.
content << '\n' << label->text().toStdString() << ":";
fields.append({label->text(), ""});
continue;
}
@@ -410,46 +415,34 @@ std::string ClangFormatConfigWidget::tableToString(QObject *sender)
if (plainText->toPlainText().trimmed().isEmpty())
continue;
content << '\n' << label->text().toStdString() << ":";
std::stringstream content;
QStringList list = plainText->toPlainText().split('\n');
for (const QString &line : list)
content << "\n " << line.toStdString();
fields.append({label->text(), QString::fromStdString(content.str())});
} else {
auto *comboBox = qobject_cast<QComboBox *>(valueWidget);
std::string text;
if (comboBox) {
text = comboBox->currentText().toStdString();
QString text;
if (auto *comboBox = qobject_cast<QComboBox *>(valueWidget)) {
text = comboBox->currentText();
} else {
auto *lineEdit = qobject_cast<QLineEdit *>(valueWidget);
QTC_ASSERT(lineEdit, continue;);
text = lineEdit->text().toStdString();
text = lineEdit->text();
}
if (!text.empty() && text != "Default")
content << '\n' << label->text().toStdString() << ": " << text;
if (!text.isEmpty() && text != "Default")
fields.append({label->text(), text});
}
}
content << '\n';
m_config->changeFields(fields);
}
std::string text = content.str();
clang::format::FormatStyle style;
style.Language = clang::format::FormatStyle::LK_Cpp;
const std::error_code error = clang::format::parseConfiguration(text, &style);
if (error.value() != static_cast<int>(clang::format::ParseError::Success)) {
QMessageBox::warning(this,
tr("Error in ClangFormat configuration"),
QString::fromStdString(error.message()));
fillTable();
updatePreview();
return std::string();
}
return text;
fillTable();
updatePreview();
}
ClangFormatConfigWidget::~ClangFormatConfigWidget() = default;
void ClangFormatConfigWidget::apply()
{
ClangFormatSettings &settings = ClangFormatSettings::instance();
@@ -466,28 +459,7 @@ void ClangFormatConfigWidget::apply()
if (!m_checksWidget->isVisible())
return;
const std::string config = tableToString(this);
if (config.empty())
return;
saveConfig(config);
fillTable();
updatePreview();
}
void ClangFormatConfigWidget::saveConfig(const std::string &text) const
{
QString filePath = Core::ICore::userResourcePath().toString();
if (m_project)
filePath += "/clang-format/" + currentProjectUniqueId();
filePath += "/" + QLatin1String(Constants::SETTINGS_FILE_NAME);
QFile file(filePath);
if (!file.open(QFile::WriteOnly))
return;
file.write(text.c_str());
file.close();
saveChanges(this);
}
} // namespace ClangFormat

View File

@@ -44,6 +44,7 @@ namespace Ui {
class ClangFormatConfigWidget;
class ClangFormatChecksWidget;
}
class ClangFormatFile;
class ClangFormatConfigWidget : public TextEditor::CodeStyleEditorWidget
{
@@ -66,18 +67,17 @@ private:
void connectChecks();
void fillTable();
std::string tableToString(QObject *sender);
void saveChanges(QObject *sender);
void hideGlobalCheckboxes();
void showGlobalCheckboxes();
void saveConfig(const std::string &text) const;
void updatePreview();
ProjectExplorer::Project *m_project;
QWidget *m_checksWidget;
QScrollArea *m_checksScrollArea;
TextEditor::SnippetEditorWidget *m_preview;
std::unique_ptr<ClangFormatFile> m_config;
std::unique_ptr<Ui::ClangFormatChecksWidget> m_checks;
std::unique_ptr<Ui::ClangFormatConfigWidget> m_ui;
bool m_disableTableUpdate = false;

View File

@@ -0,0 +1,116 @@
/****************************************************************************
**
** Copyright (C) 2021 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#include "clangformatfile.h"
#include <sstream>
using namespace ClangFormat;
ClangFormatFile::ClangFormatFile(Utils::FilePath filePath)
: m_filePath(filePath)
{
if (!m_filePath.exists()) {
resetStyleToLLVM();
return;
}
const std::error_code error
= clang::format::parseConfiguration(m_filePath.fileContents().toStdString(), &m_style);
if (error.value() != static_cast<int>(clang::format::ParseError::Success)) {
resetStyleToLLVM();
}
}
clang::format::FormatStyle ClangFormatFile::format() {
return m_style;
}
Utils::FilePath ClangFormatFile::filePath()
{
return m_filePath;
}
void ClangFormatFile::setStyle(clang::format::FormatStyle style)
{
m_style = style;
saveNewFormat();
}
void ClangFormatFile::resetStyleToLLVM()
{
m_style = clang::format::getLLVMStyle();
saveNewFormat();
}
void ClangFormatFile::setBasedOnStyle(QString styleName)
{
changeField({"BasedOnStyle", styleName});
saveNewFormat();
}
QString ClangFormatFile::setStyle(QString style)
{
m_style.Language = clang::format::FormatStyle::LK_Cpp;
const std::error_code error = clang::format::parseConfiguration(style.toStdString(), &m_style);
if (error.value() != static_cast<int>(clang::format::ParseError::Success)) {
return QString::fromStdString(error.message());
}
saveNewFormat(style.toUtf8());
return "";
}
QString ClangFormatFile::changeField(Field field)
{
return changeFields({field});
}
QString ClangFormatFile::changeFields(QList<Field> fields)
{
std::stringstream content;
content << "---" << "\n";
for (const auto &field : fields) {
content << field.first.toStdString() << ": " << field.second.toStdString() << "\n";
}
return setStyle(QString::fromStdString(content.str()));
}
void ClangFormatFile::saveNewFormat()
{
std::string style = clang::format::configurationAsText(m_style);
// workaround: configurationAsText() add comment "# " before BasedOnStyle line
const int pos = style.find("# BasedOnStyle");
if (pos < style.size())
style.erase(pos, 2);
m_filePath.writeFileContents(QByteArray::fromStdString(style));
}
void ClangFormatFile::saveNewFormat(QByteArray style)
{
m_filePath.writeFileContents(style);
}

View File

@@ -0,0 +1,60 @@
/****************************************************************************
**
** Copyright (C) 2021 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#pragma once
#include "utils/filepath.h"
#include <clang/Format/Format.h>
namespace ClangFormat {
class ClangFormatFile
{
public:
explicit ClangFormatFile(Utils::FilePath file);
clang::format::FormatStyle format();
Utils::FilePath filePath();
void resetStyleToLLVM();
void setBasedOnStyle(QString styleName);
void setStyle(clang::format::FormatStyle style);
QString setStyle(QString style);
void clearBasedOnStyle();
using Field = std::pair<QString, QString>;
QString changeFields(QList<Field> fields);
QString changeField(Field field);
private:
void saveNewFormat();
void saveNewFormat(QByteArray style);
private:
Utils::FilePath m_filePath;
clang::format::FormatStyle m_style;
};
} // namespace ClangFormat