1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
|
// Copyright (C) 2025 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
#include "qmlformatsettingswidget.h"
#include "coreplugin/messagemanager.h"
#include "qmlformatsettings.h"
#include "qmljscodestylesettings.h"
#include "qmljsformatterselectionwidget.h"
#include "qmljstoolstr.h"
#include <utils/commandline.h>
#include <utils/layoutbuilder.h>
#include <utils/qtcprocess.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/projecttree.h>
#include <projectexplorer/project.h>
#include <QAbstractItemView>
#include <QAbstractTableModel>
#include <QColor>
#include <QCheckBox>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QHeaderView>
#include <QLineEdit>
#include <QPushButton>
#include <QSet>
#include <QSpinBox>
#include <QStackedWidget>
#include <QStyledItemDelegate>
#include <QTableView>
#include <chrono>
using namespace std::chrono_literals;
using namespace ProjectExplorer;
namespace QmlJSTools {
class QmlFormatOptionsModel : public QAbstractTableModel
{
Q_OBJECT
public:
enum Column : int {
Name = 0,
Value
};
struct Option {
QString name;
QVariant value;
QString hint;
bool hidden = false;
bool isBool() const {
return hint == QString::fromUtf8(QMetaType::fromType<bool>().name());
}
bool isInt() const {
return hint == QString::fromUtf8(QMetaType::fromType<int>().name());
}
bool isString() const {
return hint == QString::fromUtf8(QMetaType::fromType<QString>().name());
}
bool isStringList() const {
return !isBool() && !isInt() && !isString() && !isNull();
}
bool isNull() const {
return hint.isEmpty();
}
};
explicit QmlFormatOptionsModel(QObject *parent = nullptr);
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
int columnCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override;
Qt::ItemFlags flags(const QModelIndex &index) const override;
void setOptionsFromJson(const QJsonDocument &doc);
QString writeGlobalQmlFormatIniFile() const;
void loadGlobalQmlFormatIniFile();
const QList<Option> &options() const { return m_options; }
signals:
void dataChanged();
private:
QList<Option> m_options;
};
class QmlFormatOptionsDelegate : public QStyledItemDelegate
{
Q_OBJECT
public:
explicit QmlFormatOptionsDelegate(QmlFormatOptionsModel *model, QObject *parent = nullptr);
QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option,
const QModelIndex &index) const override;
void setEditorData(QWidget *editor, const QModelIndex &index) const override;
void setModelData(QWidget *editor, QAbstractItemModel *model,
const QModelIndex &index) const override;
private:
QmlFormatOptionsModel *m_model;
};
QmlFormatOptionsModel::QmlFormatOptionsModel(QObject *parent)
: QAbstractTableModel(parent)
{
}
int QmlFormatOptionsModel::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent)
return m_options.size();
}
int QmlFormatOptionsModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent)
return 2; // Name and Value columns
}
QVariant QmlFormatOptionsModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid() || index.row() >= m_options.size())
return QVariant();
const Option &option = m_options.at(index.row());
if (role == Qt::DisplayRole) {
switch (index.column()) {
case Column::Name:
return option.name;
case Column::Value:
// Hide text for boolean values, show empty string so checkbox is visible
if (option.isBool()) // Boolean type
return QString();
return option.value;
}
} else if (role == Qt::EditRole) {
switch (index.column()) {
case Column::Name:
return option.name;
case Column::Value:
return option.value;
}
} else if (role == Qt::CheckStateRole && index.column() == Column::Value && option.isBool()) {
// For boolean values, provide check state
return option.value.toBool() ? Qt::Checked : Qt::Unchecked;
} else if (role == Qt::ForegroundRole && option.hidden) {
// Show hidden options in gray
return QColor(Qt::gray);
} else if (role == Qt::ToolTipRole && option.hidden) {
return Tr::tr("This option was found in the INI file but is not a standard qmlformat option");
}
return QVariant();
}
QVariant QmlFormatOptionsModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
switch (section) {
case Column::Name:
return Tr::tr("Option");
case Column::Value:
return Tr::tr("Value");
}
}
return QVariant();
}
bool QmlFormatOptionsModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (!index.isValid() || index.row() >= m_options.size())
return false;
if (index.column() == Column::Value) {
if (role == Qt::EditRole) {
m_options[index.row()].value = value;
emit QAbstractTableModel::dataChanged(index, index);
emit dataChanged();
return true;
} else if (role == Qt::CheckStateRole && m_options[index.row()].isBool()) {
// Handle checkbox state changes for boolean values
bool boolValue = (value.toInt() == Qt::Checked);
m_options[index.row()].value = boolValue;
emit QAbstractTableModel::dataChanged(index, index);
emit dataChanged();
return true;
}
}
return false;
}
Qt::ItemFlags QmlFormatOptionsModel::flags(const QModelIndex &index) const
{
if (!index.isValid())
return Qt::NoItemFlags;
Qt::ItemFlags flags = Qt::ItemIsEnabled | Qt::ItemIsSelectable;
if (index.column() == Column::Value) {
flags |= Qt::ItemIsEditable;
// Add checkable flag for boolean values
if (index.row() < m_options.size() && m_options[index.row()].isBool())
flags |= Qt::ItemIsUserCheckable;
}
return flags;
}
void QmlFormatOptionsModel::setOptionsFromJson(const QJsonDocument &doc)
{
beginResetModel();
m_options.clear();
if (!doc.isObject()) {
endResetModel();
return;
}
QJsonObject rootObj = doc.object();
const QJsonArray optionsArray = rootObj["options"].toArray();
for (const QJsonValue &optionValue : optionsArray) {
if (!optionValue.isObject())
continue;
QJsonObject optionObj = optionValue.toObject();
Option option;
option.name = optionObj["name"].toString();
option.value = optionObj["value"].toVariant();
option.hint = optionObj["hint"].toString();
m_options.append(option);
}
endResetModel();
}
QString QmlFormatOptionsModel::writeGlobalQmlFormatIniFile() const
{
QSettings settings(
QmlFormatSettings::instance().globalQmlFormatIniFile().toFSPathString(),
QSettings::IniFormat);
settings.clear();
for (const Option &option : m_options)
settings.setValue(option.name, option.value);
settings.sync();
QFile file(QmlFormatSettings::instance().globalQmlFormatIniFile().toFSPathString());
QTC_CHECK(file.open(QIODevice::ReadOnly));
return QString::fromUtf8(file.readAll());
}
void QmlFormatOptionsModel::loadGlobalQmlFormatIniFile()
{
// Parse INI content and update options
beginResetModel();
QSettings settings(
QmlFormatSettings::instance().globalQmlFormatIniFile().toFSPathString(),
QSettings::IniFormat);
// Update existing options with INI values
QSet<QString> foundOptions;
for (Option &option : m_options) {
if (settings.contains(option.name)) {
option.value = settings.value(option.name);
foundOptions.insert(option.name);
}
}
// Add missing options as hidden
for (const QString &key : settings.allKeys()) {
if (!foundOptions.contains(key)) {
Option hiddenOption;
hiddenOption.name = key;
hiddenOption.value = settings.value(key);
hiddenOption.hint = QString(); // Unknown type for hidden options
hiddenOption.hidden = true;
m_options.append(hiddenOption);
}
}
std::sort(m_options.begin(), m_options.end(), [](const Option &a, const Option &b){
return a.name < b.name;
});
endResetModel();
}
QmlFormatOptionsDelegate::QmlFormatOptionsDelegate(QmlFormatOptionsModel *model, QObject *parent)
: QStyledItemDelegate(parent), m_model(model)
{
}
QWidget *QmlFormatOptionsDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
Q_UNUSED(option)
if (index.column() != 1) // Only create editors for the value column
return nullptr;
const auto &options = m_model->options();
if (index.row() >= options.size())
return nullptr;
const QmlFormatOptionsModel::Option &opt = options.at(index.row());
if (opt.isInt()) {
QSpinBox *spinBox = new QSpinBox(parent);
spinBox->setRange(std::numeric_limits<int>::min(), std::numeric_limits<int>::max());
return spinBox;
}
if (opt.isString()) {
return new QLineEdit(parent);
}
if (opt.isStringList()) {
QComboBox *comboBox = new QComboBox(parent);
comboBox->addItems(opt.hint.split(','));
return comboBox;
}
return nullptr;
}
void QmlFormatOptionsDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
const auto &options = m_model->options();
if (index.row() >= options.size())
return;
const QmlFormatOptionsModel::Option &opt = options.at(index.row());
if (opt.isInt()) {
QSpinBox *spinBox = qobject_cast<QSpinBox*>(editor);
if (spinBox)
spinBox->setValue(opt.value.toInt());
}
if (opt.isString()) {
QLineEdit *lineEdit = qobject_cast<QLineEdit*>(editor);
if (lineEdit)
lineEdit->setText(opt.value.toString());
}
if (opt.isStringList()) {
QComboBox *comboBox = qobject_cast<QComboBox*>(editor);
if (comboBox)
comboBox->setCurrentText(opt.value.toString());
}
// No action needed for booleans, native checkbox handles this
}
void QmlFormatOptionsDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
const QModelIndex &index) const
{
const auto &options = m_model->options();
if (index.row() >= options.size())
return;
const QmlFormatOptionsModel::Option &opt = options.at(index.row());
QVariant value;
if (opt.isInt()) {
QSpinBox *spinBox = qobject_cast<QSpinBox*>(editor);
if (spinBox)
value = spinBox->value();
}
if (opt.isString()) {
QLineEdit *lineEdit = qobject_cast<QLineEdit*>(editor);
if (lineEdit)
value = lineEdit->text();
}
if (opt.isStringList()) {
QComboBox *comboBox = qobject_cast<QComboBox*>(editor);
if (comboBox)
value = comboBox->currentText();
}
// No action needed for boolean, native checkbox handles this through Qt::CheckStateRole
if (value.isValid())
model->setData(index, value, Qt::EditRole);
}
class QmlFormatSettingsWidget : public QmlCodeStyleWidgetBase
{
public:
QmlFormatSettingsWidget(QWidget *parent, FormatterSelectionWidget *selection);
void setCodeStyleSettings(const QmlJSCodeStyleSettings &s) override;
void setPreferences(QmlJSCodeStylePreferences *preferences) override;
void slotCurrentPreferencesChanged(TextEditor::ICodeStylePreferences* preferences) override;
private:
void slotSettingsChanged();
void initOptions();
void resetOptions();
void generateFallbackJson();
QTableView *m_optionsTableView;
QmlFormatOptionsModel *m_optionsModel;
QmlFormatOptionsDelegate *m_optionsDelegate;
QPushButton *m_deployIniButton;
QPushButton *m_tableResetButton;
FormatterSelectionWidget *m_formatterSelectionWidget = nullptr;
QmlJSCodeStylePreferences *m_preferences = nullptr;
QJsonDocument m_fallbackJson;
};
QmlFormatSettingsWidget::QmlFormatSettingsWidget(
QWidget *parent, FormatterSelectionWidget *selection)
: QmlCodeStyleWidgetBase(parent)
, m_optionsTableView(new QTableView())
, m_optionsModel(new QmlFormatOptionsModel(this))
, m_optionsDelegate(new QmlFormatOptionsDelegate(m_optionsModel, this))
, m_deployIniButton(new QPushButton(Tr::tr("Deploy INI file to current project")))
, m_tableResetButton(new QPushButton(Tr::tr("Reset to Defaults")))
, m_formatterSelectionWidget(selection)
{
generateFallbackJson();
m_optionsTableView->setModel(m_optionsModel);
m_optionsTableView->setItemDelegate(m_optionsDelegate);
m_optionsTableView->horizontalHeader()->setStretchLastSection(false);
m_optionsTableView->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
m_optionsTableView->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch);
m_optionsTableView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
m_optionsTableView->setSelectionBehavior(QAbstractItemView::SelectRows);
QSizePolicy sp(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
sp.setHorizontalStretch(1);
m_optionsTableView->setSizePolicy(sp);
using namespace Layouting;
// clang-format off
Column {
Group {
title(Tr::tr("Global qmlformat Configuration")),
Column {
m_optionsTableView,
Row {
st,
m_deployIniButton,
m_tableResetButton,
},
Label {
wordWrap(true),
text("<i>" + Tr::tr("Global formatting options are ignored by projects having their own deployed .qmlformat.ini files.") + "</i>"),
},
},
},
noMargin
}.attachTo(this);
// clang-format on
initOptions();
connect(
m_optionsModel,
&QmlFormatOptionsModel::dataChanged,
this,
&QmlFormatSettingsWidget::slotSettingsChanged);
connect(
m_tableResetButton,
&QPushButton::clicked,
this,
&QmlFormatSettingsWidget::resetOptions);
connect(
m_deployIniButton,
&QPushButton::clicked,
this,
[this] {
if (Project * const p = ProjectTree::currentProject()) {
p->projectDirectory().pathAppended(".qmlformat.ini")
.writeFileContents(m_optionsModel->writeGlobalQmlFormatIniFile().toUtf8());
}
});
m_deployIniButton->setEnabled(ProjectTree::currentProject());
connect(ProjectTree::instance(), &ProjectTree::currentProjectChanged, this, [this] {
m_deployIniButton->setEnabled(ProjectTree::currentProject());
});
}
void QmlFormatSettingsWidget::setCodeStyleSettings(const QmlJSCodeStyleSettings &s)
{
QSignalBlocker blocker(this);
QmlFormatSettings::instance().globalQmlFormatIniFile().writeFileContents(s.qmlformatIniContent.toUtf8());
m_optionsModel->loadGlobalQmlFormatIniFile();
}
void QmlFormatSettingsWidget::setPreferences(QmlJSCodeStylePreferences *preferences)
{
if (m_preferences == preferences)
return;
slotCurrentPreferencesChanged(preferences);
if (m_preferences) {
disconnect(m_preferences, &QmlJSCodeStylePreferences::currentValueChanged, this, nullptr);
disconnect(m_preferences, &QmlJSCodeStylePreferences::currentPreferencesChanged,
this, &QmlFormatSettingsWidget::slotCurrentPreferencesChanged);
}
m_preferences = preferences;
if (m_preferences) {
setCodeStyleSettings(m_preferences->currentCodeStyleSettings());
connect(m_preferences, &QmlJSCodeStylePreferences::currentValueChanged, this, [this] {
this->setCodeStyleSettings(m_preferences->currentCodeStyleSettings());
});
connect(m_preferences, &QmlJSCodeStylePreferences::currentPreferencesChanged,
this, &QmlFormatSettingsWidget::slotCurrentPreferencesChanged);
}
}
void QmlFormatSettingsWidget::slotCurrentPreferencesChanged(
TextEditor::ICodeStylePreferences *preferences)
{
auto *current = dynamic_cast<QmlJSCodeStylePreferences *>(
preferences ? preferences->currentPreferences() : nullptr);
const bool enableWidgets = current && !current->isReadOnly() && m_formatterSelectionWidget
&& m_formatterSelectionWidget->selection().value()
== QmlCodeStyleWidgetBase::QmlFormat;
setEnabled(enableWidgets);
}
void QmlFormatSettingsWidget::slotSettingsChanged()
{
QmlJSCodeStyleSettings settings = m_preferences ? m_preferences->currentCodeStyleSettings()
: QmlJSCodeStyleSettings::currentGlobalCodeStyle();
settings.qmlformatIniContent = m_optionsModel->writeGlobalQmlFormatIniFile();
emit settingsChanged(settings);
}
void QmlFormatSettingsWidget::initOptions()
{
using namespace Core;
const Utils::FilePath &qmlFormatPath = QmlFormatSettings::instance().latestQmlFormatPath();
if (qmlFormatPath.isEmpty()) {
MessageManager::writeSilently(Tr::tr("QmlFormat not found. Using fallback output options."));
m_optionsModel->setOptionsFromJson(m_fallbackJson);
return;
}
const Utils::CommandLine commandLine(qmlFormatPath);
const Utils::FilePath executable = commandLine.executable();
Utils::Process process;
process.setCommand({executable, {"--output-options"}});
process.setUtf8StdOutCodec();
process.start();
if (!process.waitForFinished(5s)) {
MessageManager::writeFlashing(Tr::tr("Cannot call %1 or some other error occurred. Using fallback output options.")
.arg(executable.toUserOutput()));
m_optionsModel->setOptionsFromJson(m_fallbackJson);
return;
}
const QString errorText = process.readAllStandardError();
if (!errorText.isEmpty()) {
MessageManager::writeFlashing(Tr::tr("%1: %2. Using fallback output options.").arg(executable.toUserOutput(),
errorText));
m_optionsModel->setOptionsFromJson(m_fallbackJson);
return;
}
QJsonDocument doc = QJsonDocument::fromJson(process.readAllStandardOutput().toUtf8());
if (doc.isNull() || !doc.isObject() || !doc.object().contains("options")) {
MessageManager::writeFlashing(Tr::tr("Invalid JSON response from qmlformat. Using fallback output options."));
m_optionsModel->setOptionsFromJson(m_fallbackJson);
return;
}
m_optionsModel->setOptionsFromJson(doc);
}
void QmlFormatSettingsWidget::resetOptions()
{
initOptions();
slotSettingsChanged();
}
void QmlFormatSettingsWidget::generateFallbackJson()
{
QJsonObject root;
QJsonArray optionsArray;
{
QJsonObject obj;
obj["name"] = "NewlineType";
obj["value"] = "native";
obj["hint"] = "native,macos,unix,windows";
optionsArray.append(obj);
}
{
QJsonObject obj;
obj["name"] = "MaxColumnWidth";
obj["value"] = -1;
obj["hint"] = QMetaType::fromType<int>().name();
optionsArray.append(obj);
}
{
QJsonObject obj;
obj["name"] = "UseTabs";
obj["value"] = false;
obj["hint"] = QMetaType::fromType<bool>().name();
optionsArray.append(obj);
}
{
QJsonObject obj;
obj["name"] = "NormalizeOrder";
obj["value"] = false;
obj["hint"] = QMetaType::fromType<bool>().name();
optionsArray.append(obj);
}
{
QJsonObject obj;
obj["name"] = "ObjectsSpacing";
obj["value"] = false;
obj["hint"] = QMetaType::fromType<bool>().name();
optionsArray.append(obj);
}
{
QJsonObject obj;
obj["name"] = "FunctionsSpacing";
obj["value"] = false;
obj["hint"] = QMetaType::fromType<bool>().name();
optionsArray.append(obj);
}
{
QJsonObject obj;
obj["name"] = "IndentWidth";
obj["value"] = 4;
obj["hint"] = QMetaType::fromType<int>().name();
optionsArray.append(obj);
}
{
QJsonObject obj;
obj["name"] = "SemicolonRule";
obj["value"] = "always";
obj["hint"] = "always,essential";
optionsArray.append(obj);
}
root[QStringLiteral("options")] = optionsArray;
m_fallbackJson = QJsonDocument(root);
}
QmlCodeStyleWidgetBase *createQmlFormatSettingsWidget(QWidget *parent, FormatterSelectionWidget *selection)
{
return new QmlFormatSettingsWidget(parent, selection);
}
} // namespace QmlJSTools
#include "qmlformatsettingswidget.moc"
|