jsonfieldpage.cpp 29 KB
Newer Older
1
2
/****************************************************************************
**
Eike Ziller's avatar
Eike Ziller committed
3
4
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
5
6
7
8
9
10
11
**
** 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
Eike Ziller's avatar
Eike Ziller committed
12
13
** a written agreement between you and The Qt Company.  For licensing terms and
** conditions see http://www.qt.io/terms-conditions.  For further information
Eike Ziller's avatar
Eike Ziller committed
14
** use the contact form at http://www.qt.io/contact-us.
15
16
17
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
Eike Ziller's avatar
Eike Ziller committed
18
19
20
21
22
23
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file.  Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24
**
Eike Ziller's avatar
Eike Ziller committed
25
26
** In addition, as a special exception, The Qt Company gives you certain additional
** rights.  These rights are described in The Qt Company LGPL Exception
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "jsonfieldpage.h"

#include "jsonwizard.h"
#include "jsonwizardfactory.h"

#include <utils/algorithm.h>
#include <utils/qtcassert.h>
#include <utils/stringutils.h>
#include <utils/textfieldcheckbox.h>
#include <utils/textfieldcombobox.h>

#include <QCheckBox>
43
#include <QApplication>
44
45
46
47
#include <QDebug>
#include <QFormLayout>
#include <QLabel>
#include <QLineEdit>
48
#include <QRegularExpressionValidator>
49
50
51
52
53
#include <QTextEdit>
#include <QVariant>
#include <QVariantMap>
#include <QVBoxLayout>

54
using namespace Utils;
55

56
57
58
59
60
61
62
63
const char NAME_KEY[] = "name";
const char DISPLAY_NAME_KEY[] = "trDisplayName";
const char MANDATORY_KEY[] = "mandatory";
const char VISIBLE_KEY[] = "visible";
const char ENABLED_KEY[] = "enabled";
const char SPAN_KEY[] = "span";
const char TYPE_KEY[] = "type";
const char DATA_KEY[] = "data";
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

namespace ProjectExplorer {

// --------------------------------------------------------------------
// Helper:
// --------------------------------------------------------------------

static JsonFieldPage::Field *createFieldData(const QString &type)
{
    if (type == QLatin1String("Label"))
        return new JsonFieldPage::LabelField;
    else if (type == QLatin1String("Spacer"))
        return new JsonFieldPage::SpacerField;
    else if (type == QLatin1String("LineEdit"))
        return new JsonFieldPage::LineEditField;
    else if (type == QLatin1String("TextEdit"))
        return new JsonFieldPage::TextEditField;
    else if (type == QLatin1String("PathChooser"))
        return new JsonFieldPage::PathChooserField;
    else if (type == QLatin1String("CheckBox"))
        return new JsonFieldPage::CheckBoxField;
    else if (type == QLatin1String("ComboBox"))
        return new JsonFieldPage::ComboBoxField;
    return 0;
}

90
91
92
93
94
95
96
97
98
99
class LineEditValidator : public QRegularExpressionValidator
{
public:
    LineEditValidator(MacroExpander *expander, const QRegularExpression &pattern, QObject *parent) :
        QRegularExpressionValidator(pattern, parent)
    {
        m_expander.setDisplayName(tr("Line Edit Validator Expander"));
        m_expander.setAccumulating(true);
        m_expander.registerVariable("INPUT", tr("The text edit input to fix up."),
                                    [this]() { return m_currentInput; });
100
        m_expander.registerSubProvider([expander]() -> MacroExpander * { return expander; });
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
    }

    void setFixupExpando(const QString &expando)
    {
        m_fixupExpando = expando;
    }

    QValidator::State validate(QString &input, int &pos) const
    {
        fixup(input);
        return QRegularExpressionValidator::validate(input, pos);
    }

    void fixup(QString &fixup) const
    {
        if (m_fixupExpando.isEmpty())
            return;

        m_currentInput = fixup;
        fixup = m_expander.expand(m_fixupExpando);
    }

private:
    MacroExpander m_expander;
    QString m_fixupExpando;
    mutable QString m_currentInput;
};

129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
// --------------------------------------------------------------------
// JsonFieldPage::FieldData:
// --------------------------------------------------------------------

JsonFieldPage::Field *JsonFieldPage::Field::parse(const QVariant &input, QString *errorMessage)
{
    if (input.type() != QVariant::Map) {
        *errorMessage = QCoreApplication::translate("ProjectExplorer::JsonFieldPage",
                                                    "Field is not an object.");
        return 0;
    }

    QVariantMap tmp = input.toMap();
    const QString name = tmp.value(QLatin1String(NAME_KEY)).toString();
    if (name.isEmpty()) {
        *errorMessage = QCoreApplication::translate("ProjectExplorer::JsonFieldPage",
                                                    "Field has no name.");
        return 0;
    }
    const QString type = tmp.value(QLatin1String(TYPE_KEY)).toString();
    if (type.isEmpty()) {
        *errorMessage = QCoreApplication::translate("ProjectExplorer::JsonFieldPage",
151
                                                    "Field \"%1\" has no type.").arg(name);
152
153
154
155
156
157
        return 0;
    }

    Field *data = createFieldData(type);
    if (!data) {
        *errorMessage = QCoreApplication::translate("ProjectExplorer::JsonFieldPage",
158
                                                    "Field \"%1\" has unsupported type \"%2\".")
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
                .arg(name).arg(type);
        return 0;
    }
    data->name = name;

    data->m_visibleExpression = tmp.value(QLatin1String(VISIBLE_KEY), true);
    data->m_enabledExpression = tmp.value(QLatin1String(ENABLED_KEY), true);
    data->mandatory = tmp.value(QLatin1String(MANDATORY_KEY), true).toBool();
    data->span = tmp.value(QLatin1String(SPAN_KEY), false).toBool();

    data->displayName = JsonWizardFactory::localizedString(tmp.value(QLatin1String(DISPLAY_NAME_KEY)).toString());

    QVariant dataVal = tmp.value(QLatin1String(DATA_KEY));
    if (!data->parseData(dataVal, errorMessage)) {
        *errorMessage = QCoreApplication::translate("ProjectExplorer::JsonFieldPage",
174
                                                    "When parsing Field \"%1\": %2")
175
176
177
178
179
180
181
182
183
184
                .arg(name).arg(*errorMessage);
        delete data;
        return 0;
    }

    return data;
}

void JsonFieldPage::Field::createWidget(JsonFieldPage *page)
{
185
    QWidget *w = widget(displayName, page);
186
187
188
189
190
191
192
193
194
195
196
197
198
    w->setObjectName(name);
    QFormLayout *layout = page->layout();

    if (suppressName())
        layout->addWidget(w);
    else if (span)
        layout->addRow(w);
    else
        layout->addRow(displayName, w);

    setup(page, name);
}

199
void JsonFieldPage::Field::adjustState(MacroExpander *expander)
200
201
202
203
204
{
    setVisible(JsonWizard::boolFromVariant(m_visibleExpression, expander));
    setEnabled(JsonWizard::boolFromVariant(m_enabledExpression, expander));
}

205
void JsonFieldPage::Field::initialize(MacroExpander *expander)
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
{
    adjustState(expander);
    initializeData(expander);
}

// --------------------------------------------------------------------
// JsonFieldPage::LabelFieldData:
// --------------------------------------------------------------------

JsonFieldPage::LabelField::LabelField() :
    m_wordWrap(false)
{ }

bool JsonFieldPage::LabelField::parseData(const QVariant &data, QString *errorMessage)
{
    if (data.type() != QVariant::Map) {
        *errorMessage = QCoreApplication::translate("ProjectExplorer::JsonFieldPage",
                                                    "Label data is not an object.");
        return false;
    }

    QVariantMap tmp = data.toMap();

    m_wordWrap = tmp.value(QLatin1String("wordWrap"), false).toBool();
    m_text = JsonWizardFactory::localizedString(tmp.value(QLatin1String("trText")));

    if (m_text.isEmpty()) {
        *errorMessage = QCoreApplication::translate("ProjectExplorer::JsonFieldPage",
                                                    "No text given for Label.");
        return false;
    }

    return true;
}

241
QWidget *JsonFieldPage::LabelField::widget(const QString &displayName, JsonFieldPage *page)
242
243
{
    Q_UNUSED(displayName);
244
    Q_UNUSED(page);
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
    QTC_ASSERT(!m_widget, return m_widget);

    QLabel *w = new QLabel();
    w->setWordWrap(m_wordWrap);
    w->setText(m_text);

    m_widget = w;
    return m_widget;
}

// --------------------------------------------------------------------
// JsonFieldPage::SpacerFieldData:
// --------------------------------------------------------------------

JsonFieldPage::SpacerField::SpacerField() :
260
    m_factor(1)
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
{ }

bool JsonFieldPage::SpacerField::parseData(const QVariant &data, QString *errorMessage)
{
    if (data.isNull())
        return true;

    if (data.type() != QVariant::Map) {
        *errorMessage = QCoreApplication::translate("ProjectExplorer::JsonFieldPage",
                                                    "Spacer data is not an object.");
        return false;
    }

    QVariantMap tmp = data.toMap();

    bool ok;
277
    m_factor = tmp.value(QLatin1String("factor"), 1).toInt(&ok);
278
279
280

    if (!ok) {
        *errorMessage = QCoreApplication::translate("ProjectExplorer::JsonFieldPage",
281
                                                    "\"factor\" is no integer value.");
282
283
284
285
286
287
        return false;
    }

    return true;
}

288
QWidget *JsonFieldPage::SpacerField::widget(const QString &displayName, JsonFieldPage *page)
289
290
{
    Q_UNUSED(displayName);
291
    Q_UNUSED(page);
292
293
    QTC_ASSERT(!m_widget, return m_widget);

294
295
    int size = qApp->style()->pixelMetric(QStyle::PM_DefaultLayoutSpacing) * m_factor;

296
297
298
299
300
301
302
303
304
305
306
    m_widget = new QWidget();
    m_widget->setMinimumSize(size, size);
    m_widget->setMaximumSize(size, size);
    m_widget->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    return m_widget;
}

// --------------------------------------------------------------------
// JsonFieldPage::LineEditFieldData:
// --------------------------------------------------------------------

307
JsonFieldPage::LineEditField::LineEditField() : m_isModified(false), m_isValidating(false)
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
{ }

bool JsonFieldPage::LineEditField::parseData(const QVariant &data, QString *errorMessage)
{
    if (data.isNull())
        return true;

    if (data.type() != QVariant::Map) {
        *errorMessage = QCoreApplication::translate("ProjectExplorer::JsonFieldPage",
                                                    "LineEdit data is not an object.");
        return false;
    }

    QVariantMap tmp = data.toMap();

    m_defaultText = JsonWizardFactory::localizedString(tmp.value(QLatin1String("trText")).toString());
    m_disabledText = JsonWizardFactory::localizedString(tmp.value(QLatin1String("trDisabledText")).toString());
    m_placeholderText = JsonWizardFactory::localizedString(tmp.value(QLatin1String("trPlaceholder")).toString());
326
327
    QString pattern = tmp.value(QLatin1String("validator")).toString();
    if (!pattern.isEmpty()) {
328
329
        m_validatorRegExp = QRegularExpression(pattern);
        if (!m_validatorRegExp.isValid()) {
330
331
332
            *errorMessage = QCoreApplication::translate("ProjectExplorer::JsonFieldPage",
                                                        "Invalid regular expression \"%1\" in \"validator\".")
                    .arg(pattern);
333
            m_validatorRegExp = QRegularExpression();
334
335
336
            return false;
        }
    }
337
    m_fixupExpando = tmp.value(QLatin1String("fixup")).toString();
338
339
340
341

    return true;
}

342
QWidget *JsonFieldPage::LineEditField::widget(const QString &displayName, JsonFieldPage *page)
343
344
345
346
347
{
    Q_UNUSED(displayName);
    QTC_ASSERT(!m_widget, return m_widget);
    QLineEdit *w = new QLineEdit;

348
349
350
351
352
    if (m_validatorRegExp.isValid()) {
        LineEditValidator *lv = new LineEditValidator(page->expander(), m_validatorRegExp, w);
        lv->setFixupExpando(m_fixupExpando);
        w->setValidator(lv);
    }
353

354
355
356
357
358
359
360
361
    m_widget = w;
    return m_widget;
}

void JsonFieldPage::LineEditField::setup(JsonFieldPage *page, const QString &name)
{
    QLineEdit *w = static_cast<QLineEdit *>(m_widget);
    page->registerFieldWithName(name, w);
362
363
    connect(w, &QLineEdit::textChanged,
            page, [this, page]() -> void { m_isModified = true; emit page->completeChanged(); });
364
365
}

366
bool JsonFieldPage::LineEditField::validate(MacroExpander *expander, QString *message)
367
368
{
    Q_UNUSED(message);
369
370
371
372
373
    if (m_isValidating)
        return true;

    m_isValidating = true;

374
375
    QLineEdit *w = static_cast<QLineEdit *>(m_widget);

376
377
378
379
380
381
382
383
384
385
386
387
388
    if (w->isEnabled()) {
        if (m_isModified) {
            if (!m_currentText.isNull()) {
                w->setText(m_currentText);
                m_currentText.clear();
            }
        } else {
            w->setText(expander->expand(m_defaultText));
            m_isModified = false;
        }
    } else {
        if (!m_disabledText.isNull() && m_currentText.isNull())
            m_currentText = w->text();
389
390
    }

391
392
    m_isValidating = false;

393
394
395
    return !w->text().isEmpty();
}

396
void JsonFieldPage::LineEditField::initializeData(MacroExpander *expander)
397
398
399
400
{
    QTC_ASSERT(m_widget, return);

    QLineEdit *w = static_cast<QLineEdit *>(m_widget);
401
    m_isValidating = true;
402
    w->setText(expander->expand(m_defaultText));
403
    w->setPlaceholderText(m_placeholderText);
404
405
    m_isModified = false;
    m_isValidating = false;
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
}

// --------------------------------------------------------------------
// JsonFieldPage::TextEditFieldData:
// --------------------------------------------------------------------


JsonFieldPage::TextEditField::TextEditField() :
    m_acceptRichText(false)
{ }

bool JsonFieldPage::TextEditField::parseData(const QVariant &data, QString *errorMessage)
{
    if (data.isNull())
        return true;

    if (data.type() != QVariant::Map) {
        *errorMessage = QCoreApplication::translate("ProjectExplorer::JsonFieldPage",
                                                    "TextEdit data is not an object.");
        return false;
    }

    QVariantMap tmp = data.toMap();

    m_defaultText = JsonWizardFactory::localizedString(tmp.value(QLatin1String("trText")).toString());
    m_disabledText = JsonWizardFactory::localizedString(tmp.value(QLatin1String("trDisabledText")).toString());
    m_acceptRichText = tmp.value(QLatin1String("richText"), true).toBool();

    return true;
}

437
QWidget *JsonFieldPage::TextEditField::widget(const QString &displayName, JsonFieldPage *page)
438
439
440
{
    // TODO: Set up modification monitoring...
    Q_UNUSED(displayName);
441
    Q_UNUSED(page);
442
443
444
445
446
447
448
449
450
451
452
453
454
455
    QTC_ASSERT(!m_widget, return m_widget);
    QTextEdit *w = new QTextEdit;
    w->setAcceptRichText(m_acceptRichText);
    m_widget = w;
    return m_widget;
}

void JsonFieldPage::TextEditField::setup(JsonFieldPage *page, const QString &name)
{
    QTextEdit *w = static_cast<QTextEdit *>(m_widget);
    page->registerFieldWithName(name, w, "plainText", SIGNAL(textChanged()));
    connect(w, &QTextEdit::textChanged, page, &QWizardPage::completeChanged);
}

456
bool JsonFieldPage::TextEditField::validate(MacroExpander *expander, QString *message)
457
458
459
460
461
462
463
464
{
    Q_UNUSED(expander);
    Q_UNUSED(message);

    QTextEdit *w = static_cast<QTextEdit *>(m_widget);

    if (!w->isEnabled() && !m_disabledText.isNull() && m_currentText.isNull()) {
        m_currentText = w->toHtml();
465
        w->setPlainText(expander->expand(m_disabledText));
466
467
468
469
470
471
472
473
    } else if (w->isEnabled() && !m_currentText.isNull()) {
        w->setText(m_currentText);
        m_currentText.clear();
    }

    return !w->toPlainText().isEmpty();
}

474
void JsonFieldPage::TextEditField::initializeData(MacroExpander *expander)
475
476
{
    QTextEdit *w = static_cast<QTextEdit *>(m_widget);
477
    w->setPlainText(expander->expand(m_defaultText));
478
479
480
481
482
483
484
}

// --------------------------------------------------------------------
// JsonFieldPage::PathChooserFieldData:
// --------------------------------------------------------------------

JsonFieldPage::PathChooserField::PathChooserField() :
485
    m_kind(PathChooser::ExistingDirectory)
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
{ }

bool JsonFieldPage::PathChooserField::parseData(const QVariant &data, QString *errorMessage)
{
    if (data.isNull())
        return true;

    if (data.type() != QVariant::Map) {
        *errorMessage = QCoreApplication::translate("ProjectExplorer::JsonFieldPage",
                                                    "PathChooser data is not an object.");
        return false;
    }

    QVariantMap tmp = data.toMap();

    m_path = tmp.value(QLatin1String("path")).toString();
    m_basePath = tmp.value(QLatin1String("basePath")).toString();

    QString kindStr = tmp.value(QLatin1String("kind"), QLatin1String("existingDirectory")).toString();
    if (kindStr == QLatin1String("existingDirectory")) {
506
        m_kind = PathChooser::ExistingDirectory;
507
    } else if (kindStr == QLatin1String("directory")) {
508
        m_kind = PathChooser::Directory;
509
    } else if (kindStr == QLatin1String("file")) {
510
        m_kind = PathChooser::File;
511
    } else if (kindStr == QLatin1String("saveFile")) {
512
        m_kind = PathChooser::SaveFile;
513
    } else if (kindStr == QLatin1String("existingCommand")) {
514
        m_kind = PathChooser::ExistingCommand;
515
    } else if (kindStr == QLatin1String("command")) {
516
        m_kind = PathChooser::Command;
517
    } else if (kindStr == QLatin1String("any")) {
518
        m_kind = PathChooser::Any;
519
520
    } else {
        *errorMessage = QCoreApplication::translate("ProjectExplorer::JsonFieldPage",
521
522
523
                                                    "kind \"%1\" is not one of the supported \"existingDirectory\", "
                                                    "\"directory\", \"file\", \"saveFile\", \"existingCommand\", "
                                                    "\"command\", \"any\".")
524
525
526
527
528
529
530
                .arg(kindStr);
        return false;
    }

    return true;
}

531
QWidget *JsonFieldPage::PathChooserField::widget(const QString &displayName, JsonFieldPage *page)
532
533
{
    Q_UNUSED(displayName);
534
    Q_UNUSED(page);
535
    QTC_ASSERT(!m_widget, return m_widget);
536
    m_widget = new PathChooser;
537
538
539
540
541
542
    return m_widget;
}

void JsonFieldPage::PathChooserField::setEnabled(bool e)
{
    QTC_ASSERT(m_widget, return);
543
    PathChooser *w = static_cast<PathChooser *>(m_widget);
544
545
546
547
548
    w->setReadOnly(!e);
}

void JsonFieldPage::PathChooserField::setup(JsonFieldPage *page, const QString &name)
{
549
    PathChooser *w = static_cast<PathChooser *>(m_widget);
550
    page->registerFieldWithName(name, w, "path", SIGNAL(changed(QString)));
551
    connect(w, &PathChooser::changed, page, [page](QString) { page->completeChanged(); });
552
553
}

554
bool JsonFieldPage::PathChooserField::validate(MacroExpander *expander, QString *message)
555
556
557
{
    Q_UNUSED(expander);
    Q_UNUSED(message);
558
    PathChooser *w = static_cast<PathChooser *>(m_widget);
559
560
561
    return w->isValid();
}

562
void JsonFieldPage::PathChooserField::initializeData(MacroExpander *expander)
563
564
{
    QTC_ASSERT(m_widget, return);
565
566
    PathChooser *w = static_cast<PathChooser *>(m_widget);
    w->setBaseDirectory(expander->expand(m_basePath));
567
568
569
    w->setExpectedKind(m_kind);

    if (m_currentPath.isNull())
570
        w->setPath(expander->expand(m_path));
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
    else
        w->setPath(m_currentPath);
}

// --------------------------------------------------------------------
// JsonFieldPage::CheckBoxFieldData:
// --------------------------------------------------------------------

JsonFieldPage::CheckBoxField::CheckBoxField() :
    m_checkedValue(QLatin1String("0")),
    m_uncheckedValue(QLatin1String("1")),
    m_isModified(false)
{ }

bool JsonFieldPage::CheckBoxField::parseData(const QVariant &data, QString *errorMessage)
{
    if (data.isNull())
        return true;

    if (data.type() != QVariant::Map) {
        *errorMessage = QCoreApplication::translate("ProjectExplorer::JsonFieldPage",
                                                    "CheckBox data is not an object.");
        return false;
    }

    QVariantMap tmp = data.toMap();

    m_checkedValue = tmp.value(QLatin1String("checkedValue"), QLatin1String("0")).toString();
    m_uncheckedValue = tmp.value(QLatin1String("uncheckedValue"), QLatin1String("1")).toString();
    if (m_checkedValue == m_uncheckedValue) {
        *errorMessage= QCoreApplication::translate("ProjectExplorer::JsonFieldPage",
                                                   "CheckBox values for checked and unchecked state are identical.");
       return false;
    }
    m_checkedExpression = tmp.value(QLatin1String("checked"), false);

    return true;
}

610
QWidget *JsonFieldPage::CheckBoxField::widget(const QString &displayName, JsonFieldPage *page)
611
{
612
    Q_UNUSED(page);
613
    QTC_ASSERT(!m_widget, return m_widget);
614
    TextFieldCheckBox *w = new TextFieldCheckBox(displayName);
615
616
617
618
619
620
    m_widget = w;
    return m_widget;
}

void JsonFieldPage::CheckBoxField::setup(JsonFieldPage *page, const QString &name)
{
621
622
    TextFieldCheckBox *w = static_cast<TextFieldCheckBox *>(m_widget);
    connect(w, &TextFieldCheckBox::clicked, [this]() { m_isModified = true; });
623
624
625
    page->registerFieldWithName(name, w, "text", SIGNAL(textChanged(QString)));
}

626
bool JsonFieldPage::CheckBoxField::validate(MacroExpander *expander, QString *message)
627
628
629
{
    Q_UNUSED(message);
    if (!m_isModified) {
630
        TextFieldCheckBox *w = static_cast<TextFieldCheckBox *>(m_widget);
631
632
633
634
635
        w->setChecked(JsonWizard::boolFromVariant(m_checkedExpression, expander));
    }
    return true;
}

636
void JsonFieldPage::CheckBoxField::initializeData(MacroExpander *expander)
637
638
639
{
    QTC_ASSERT(m_widget, return);

640
641
642
    TextFieldCheckBox *w = static_cast<TextFieldCheckBox *>(m_widget);
    w->setTrueText(expander->expand(m_checkedValue));
    w->setFalseText(expander->expand(m_uncheckedValue));
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666

    w->setChecked(JsonWizard::boolFromVariant(m_checkedExpression, expander));
}

// --------------------------------------------------------------------
// JsonFieldPage::ComboBoxFieldData:
// --------------------------------------------------------------------

JsonFieldPage::ComboBoxField::ComboBoxField() :
    m_index(-1), m_disabledIndex(-1), m_savedIndex(-1), m_currentIndex(-1)
{ }

QPair<QString, QString> parseComboBoxItem(const QVariant &item, QString *errorMessage)
{
    if (item.type() == QVariant::List) {
        *errorMessage  = QCoreApplication::translate("ProjectExplorer::JsonFieldPage",
                                                     "No lists allowed inside ComboBox items list.");
        return qMakePair(QString(), QString());
    } else if (item.type() == QVariant::Map) {
        QVariantMap tmp = item.toMap();
        QString key = JsonWizardFactory::localizedString(tmp.value(QLatin1String("trKey"), QString()).toString());
        QString value = tmp.value(QLatin1String("value"), QString()).toString();
        if (key.isNull() || key.isEmpty()) {
            *errorMessage  = QCoreApplication::translate("ProjectExplorer::JsonFieldPage",
667
                                                         "No \"key\" found in ComboBox items.");
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
            return qMakePair(QString(), QString());
        }
        if (value.isNull())
            value = key;
        return qMakePair(key, value);
    } else {
        QString keyvalue = item.toString();
        return qMakePair(keyvalue, keyvalue);
    }
}

bool JsonFieldPage::ComboBoxField::parseData(const QVariant &data, QString *errorMessage)
{
    if (data.type() != QVariant::Map) {
        *errorMessage = QCoreApplication::translate("ProjectExplorer::JsonFieldPage",
                                                    "ComboBox data is not an object.");
        return false;
    }

    QVariantMap tmp = data.toMap();

    bool ok;
    m_index = tmp.value(QLatin1String("index"), 0).toInt(&ok);
    if (!ok) {
        *errorMessage = QCoreApplication::translate("ProjectExplorer::JsonFieldPage",
693
                                                    "ComboBox \"index\" is not an integer value.");
694
695
696
697
698
        return false;
    }
    m_disabledIndex = tmp.value(QLatin1String("disabledIndex"), -1).toInt(&ok);
    if (!ok) {
        *errorMessage = QCoreApplication::translate("ProjectExplorer::JsonFieldPage",
699
                                                    "ComboBox \"disabledIndex\" is not an integer value.");
700
701
702
703
704
705
        return false;
    }

    QVariant value = tmp.value(QLatin1String("items"));
    if (value.isNull()) {
        *errorMessage = QCoreApplication::translate("ProjectExplorer::JsonFieldPage",
706
                                                    "ComboBox \"items\" missing.");
707
708
709
710
        return false;
    }
    if (value.type() != QVariant::List) {
        *errorMessage = QCoreApplication::translate("ProjectExplorer::JsonFieldPage",
711
                                                    "ComboBox \"items\" is not a list.");
712
713
714
715
716
717
718
719
720
721
722
723
724
725
        return false;
    }

    foreach (const QVariant &i, value.toList()) {
        QPair<QString, QString> keyValue = parseComboBoxItem(i, errorMessage);
        if (keyValue.first.isNull())
            return false; // an error happened...
        m_itemList.append(keyValue.first);
        m_itemDataList.append(keyValue.second);
    }

    return true;
}

726
QWidget *JsonFieldPage::ComboBoxField::widget(const QString &displayName, JsonFieldPage *page)
727
728
{
    Q_UNUSED(displayName);
729
    Q_UNUSED(page);
730
    QTC_ASSERT(!m_widget, return m_widget);
731
    m_widget = new TextFieldComboBox;
732
733
734
735
736
    return m_widget;
}

void JsonFieldPage::ComboBoxField::setup(JsonFieldPage *page, const QString &name)
{
737
    TextFieldComboBox *w = static_cast<TextFieldComboBox *>(m_widget);
738
    page->registerFieldWithName(name, w, "text", SIGNAL(text4Changed(QString)));
739
    connect(w, &TextFieldComboBox::text4Changed, page, [page](QString) { page->completeChanged(); });
740
741
}

742
bool JsonFieldPage::ComboBoxField::validate(MacroExpander *expander, QString *message)
743
744
745
746
{
    Q_UNUSED(expander);
    Q_UNUSED(message);

747
    TextFieldComboBox *w = static_cast<TextFieldComboBox *>(m_widget);
748
749
750
751
752
753
754
755
756
757
758
    if (!w->isEnabled() && m_disabledIndex >= 0 && m_savedIndex < 0) {
        m_savedIndex = w->currentIndex();
        w->setCurrentIndex(m_disabledIndex);
    } else if (w->isEnabled() && m_savedIndex >= 0) {
        w->setCurrentIndex(m_savedIndex);
        m_savedIndex = -1;
    }

    return true;
}

759
void JsonFieldPage::ComboBoxField::initializeData(MacroExpander *expander)
760
{
761
    TextFieldComboBox *w = static_cast<TextFieldComboBox *>(m_widget);
762
763
    QStringList tmpItems
            = Utils::transform(m_itemList,
764
                               [expander](const QString &i) { return expander->expand(i); });
765
766
    QStringList tmpData
            = Utils::transform(m_itemDataList,
767
                               [expander](const QString &i) { return expander->expand(i); });
768
769
770
771
772
773
774
775
776
777
778
779
780
    w->setItems(tmpItems, tmpData);
    w->setInsertPolicy(QComboBox::NoInsert);

    if (m_currentIndex >= 0)
        w->setCurrentIndex(m_currentIndex);
    else
        w->setCurrentIndex(m_index);
}

// --------------------------------------------------------------------
// JsonFieldPage:
// --------------------------------------------------------------------

781
782
JsonFieldPage::JsonFieldPage(MacroExpander *expander, QWidget *parent) :
    WizardPage(parent),
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
    m_formLayout(new QFormLayout),
    m_errorLabel(new QLabel),
    m_expander(expander)
{
    QTC_CHECK(m_expander);

    QVBoxLayout *vLayout = new QVBoxLayout;
    m_formLayout->setFieldGrowthPolicy(QFormLayout::ExpandingFieldsGrow);
    vLayout->addLayout(m_formLayout);
    m_errorLabel->setVisible(false);
    m_errorLabel->setStyleSheet(QLatin1String("background: red"));
    vLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Ignored, QSizePolicy::MinimumExpanding));
    vLayout->addWidget(m_errorLabel);
    setLayout(vLayout);
}

JsonFieldPage::~JsonFieldPage()
{
    // Do not delete m_expander, it belongs to the wizard!
    qDeleteAll(m_fields);
}

bool JsonFieldPage::setup(const QVariant &data)
{
    QString errorMessage;
    QList<QVariant> fieldList = JsonWizardFactory::objectOrList(data, &errorMessage);
    foreach (const QVariant &field, fieldList) {
        Field *f = JsonFieldPage::Field::parse(field, &errorMessage);
        if (!f)
            continue;
        f->createWidget(this);
        m_fields.append(f);
    }

    return true;
}

bool JsonFieldPage::isComplete() const
{
    QString message;

    bool result = true;
    bool hasErrorMessage = false;
    foreach (Field *f, m_fields) {
        f->adjustState(m_expander);
        if (!f->validate(m_expander, &message)) {
            if (!message.isEmpty()) {
                showError(message);
                hasErrorMessage = true;
            }
            if (f->mandatory)
                result = false;
        }
    }

    if (!hasErrorMessage)
        clearError();

    return result;
}

void JsonFieldPage::initializePage()
{
    foreach (Field *f, m_fields)
        f->initialize(m_expander);
}

void JsonFieldPage::cleanupPage()
{
    foreach (Field *f, m_fields)
        f->cleanup(m_expander);
}

void JsonFieldPage::showError(const QString &m) const
{
    m_errorLabel->setText(m);
    m_errorLabel->setVisible(true);
}

void JsonFieldPage::clearError() const
{
    m_errorLabel->setText(QString());
    m_errorLabel->setVisible(false);
}

868
MacroExpander *JsonFieldPage::expander()
869
870
871
872
873
{
    return m_expander;
}

} // namespace ProjectExplorer