jsonwizardfactory.cpp 24.3 KB
Newer Older
Tobias Hunger's avatar
Tobias Hunger committed
1 2
/****************************************************************************
**
Eike Ziller's avatar
Eike Ziller committed
3 4
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
Tobias Hunger's avatar
Tobias Hunger committed
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.
Tobias Hunger's avatar
Tobias Hunger committed
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.
Tobias Hunger's avatar
Tobias Hunger committed
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
Tobias Hunger's avatar
Tobias Hunger committed
27 28 29 30 31 32 33 34 35 36 37 38 39
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "jsonwizardfactory.h"

#include "jsonwizard.h"
#include "jsonwizardgeneratorfactory.h"
#include "jsonwizardpagefactory.h"

#include "../projectexplorerconstants.h"

#include <coreplugin/coreconstants.h>
40
#include <coreplugin/icontext.h>
Tobias Hunger's avatar
Tobias Hunger committed
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
#include <coreplugin/icore.h>
#include <coreplugin/messagemanager.h>

#include <extensionsystem/pluginmanager.h>

#include <utils/algorithm.h>
#include <utils/qtcassert.h>
#include <utils/stringutils.h>
#include <utils/wizard.h>
#include <utils/wizardpage.h>

#include <QDebug>
#include <QDir>
#include <QMap>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>

namespace ProjectExplorer {

static QList<JsonWizardPageFactory *> s_pageFactories;
static QList<JsonWizardGeneratorFactory *> s_generatorFactories;

static const char WIZARD_PATH[] = "templates/wizards";
static const char WIZARD_FILE[] = "wizard.json";

static const char VERSION_KEY[] = "version";
68
static const char ENABLED_EXPRESSION_KEY[] = "enabled";
Tobias Hunger's avatar
Tobias Hunger committed
69 70 71 72 73 74 75

static const char KIND_KEY[] = "kind";
static const char ID_KEY[] = "id";
static const char CATEGORY_KEY[] = "category";
static const char CATEGORY_NAME_KEY[] = "trDisplayCategory";
static const char DISPLAY_NAME_KEY[] = "trDisplayName";
static const char ICON_KEY[] = "icon";
76
static const char IMAGE_KEY[] = "image";
Tobias Hunger's avatar
Tobias Hunger committed
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
static const char DESCRIPTION_KEY[] = "trDescription";
static const char REQUIRED_FEATURES_KEY[] = "featuresRequired";
static const char SUGGESTED_FEATURES_KEY[] = "featuresSuggested";
static const char GENERATOR_KEY[] = "generators";
static const char PAGES_KEY[] = "pages";
static const char TYPE_ID_KEY[] = "typeId";
static const char DATA_KEY[] = "data";
static const char PAGE_SUB_TITLE_KEY[] = "trSubTitle";
static const char PAGE_SHORT_TITLE_KEY[] = "trShortTitle";
static const char PAGE_INDEX_KEY[] = "index";
static const char OPTIONS_KEY[] = "options";
static const char PLATFORM_INDEPENDENT_KEY[] = "platformIndependent";

int JsonWizardFactory::m_verbose = 0;

// Return locale language attribute "de_UTF8" -> "de", empty string for "C"
static QString languageSetting()
{
    QString name = Core::ICore::userInterfaceLanguage();
    const int underScorePos = name.indexOf(QLatin1Char('_'));
    if (underScorePos != -1)
        name.truncate(underScorePos);
    if (name.compare(QLatin1String("C"), Qt::CaseInsensitive) == 0)
        name.clear();
    return name;
}

template<class T>
static QString supportedTypeIds(const QList<T *> &factories)
{
    QStringList tmp;
    foreach (const T*f, factories) {
        foreach (Core::Id i, f->supportedIds())
            tmp.append(i.toString());
    }
    return tmp.join(QLatin1String("', '"));
}

static JsonWizardFactory::Generator parseGenerator(const QVariant &value, QString *errorMessage)
{
    JsonWizardFactory::Generator gen;

    if (value.type() != QVariant::Map) {
        *errorMessage = QCoreApplication::translate("ProjectExplorer::JsonWizardFactory", "Generator is not a object.");
        return gen;
    }

    QVariantMap data = value.toMap();
    QString strVal = data.value(QLatin1String(TYPE_ID_KEY)).toString();
    if (strVal.isEmpty()) {
        *errorMessage = QCoreApplication::translate("ProjectExplorer::JsonWizardFactory", "Generator has no typeId set.");
        return gen;
    }
    Core::Id typeId = Core::Id::fromString(QLatin1String(Constants::GENERATOR_ID_PREFIX) + strVal);
    JsonWizardGeneratorFactory *factory
            = Utils::findOr(s_generatorFactories, 0, [typeId](JsonWizardGeneratorFactory *f) { return f->canCreate(typeId); });
    if (!factory) {
        *errorMessage = QCoreApplication::translate("ProjectExplorer::JsonWizardFactory",
                                                    "TypeId \"%1\" of generator is unknown. Supported typeIds are: \"%2\".")
                .arg(strVal)
                .arg(supportedTypeIds(s_generatorFactories).replace(QLatin1String(Constants::GENERATOR_ID_PREFIX), QLatin1String("")));
        return gen;
    }

    QVariant varVal = data.value(QLatin1String(DATA_KEY));
    if (!factory->validateData(typeId, varVal, errorMessage))
        return gen;

    gen.typeId = typeId;
    gen.data = varVal;

    return gen;
}

static JsonWizardFactory::Page parsePage(const QVariant &value, QString *errorMessage)
{
    JsonWizardFactory::Page p;

    if (value.type() != QVariant::Map) {
Robert Loehning's avatar
Robert Loehning committed
156
        *errorMessage = QCoreApplication::translate("ProjectExplorer::JsonWizardFactory", "Page is not an object.");
Tobias Hunger's avatar
Tobias Hunger committed
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
        return p;
    }

    QVariantMap data = value.toMap();
    QString strVal = data.value(QLatin1String(TYPE_ID_KEY)).toString();
    if (strVal.isEmpty()) {
        *errorMessage = QCoreApplication::translate("ProjectExplorer::JsonWizardFactory", "Page has no typeId set.");
        return p;
    }
    Core::Id typeId = Core::Id::fromString(QLatin1String(Constants::PAGE_ID_PREFIX) + strVal);

    JsonWizardPageFactory *factory
            = Utils::findOr(s_pageFactories, 0, [typeId](JsonWizardPageFactory *f) { return f->canCreate(typeId); });
    if (!factory) {
        *errorMessage = QCoreApplication::translate("ProjectExplorer::JsonWizardFactory",
                                                    "TypeId \"%1\" of page is unknown. Supported typeIds are: \"%2\".")
                .arg(strVal)
                .arg(supportedTypeIds(s_pageFactories).replace(QLatin1String(Constants::PAGE_ID_PREFIX), QLatin1String("")));
        return p;
    }

    QString title = JsonWizardFactory::localizedString(data.value(QLatin1String(DISPLAY_NAME_KEY)));
    QString subTitle = JsonWizardFactory::localizedString(data.value(QLatin1String(PAGE_SUB_TITLE_KEY)));
    QString shortTitle = JsonWizardFactory::localizedString(data.value(QLatin1String(PAGE_SHORT_TITLE_KEY)));

    bool ok;
    int index = data.value(QLatin1String(PAGE_INDEX_KEY), -1).toInt(&ok);
    if (!ok) {
185
        *errorMessage = QCoreApplication::translate("ProjectExplorer::JsonWizardFactory", "Page with typeId \"%1\" has invalid \"index\".")
Tobias Hunger's avatar
Tobias Hunger committed
186 187 188 189
                .arg(typeId.toString());
        return p;
    }

190
    QVariant enabled = data.value(QLatin1String(ENABLED_EXPRESSION_KEY), true);
191 192 193

    QVariant subData = data.value(QLatin1String(DATA_KEY));
    if (!factory->validateData(typeId, subData, errorMessage))
Tobias Hunger's avatar
Tobias Hunger committed
194 195 196 197 198 199 200
        return p;

    p.typeId = typeId;
    p.title = title;
    p.subTitle = subTitle;
    p.shortTitle = shortTitle;
    p.index = index;
201 202
    p.data = subData;
    p.enabled = enabled;
Tobias Hunger's avatar
Tobias Hunger committed
203 204 205 206

    return p;
}

207
QList<Core::IWizardFactory *> JsonWizardFactory::createWizardFactories()
Tobias Hunger's avatar
Tobias Hunger committed
208 209 210 211 212
{
    QString errorMessage;
    QString verboseLog;
    const QString wizardFileName = QLatin1String(WIZARD_FILE);

213
    QList <Core::IWizardFactory *> result;
214
    foreach (const Utils::FileName &path, searchPaths()) {
Tobias Hunger's avatar
Tobias Hunger committed
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
        if (path.isEmpty())
            continue;

        QDir dir(path.toString());
        if (!dir.exists()) {
            if (verbose())
                verboseLog.append(tr("Path \"%1\" does not exist when checking Json wizard search paths.\n")
                                  .arg(path.toUserOutput()));
            continue;
        }

        const QDir::Filters filters = QDir::Dirs|QDir::Readable|QDir::NoDotAndDotDot;
        const QDir::SortFlags sortflags = QDir::Name|QDir::IgnoreCase;
        QList<QFileInfo> dirs = dir.entryInfoList(filters, sortflags);

        while (!dirs.isEmpty()) {
            const QFileInfo dirFi = dirs.takeFirst();
            const QDir current(dirFi.absoluteFilePath());
            if (verbose())
                verboseLog.append(tr("Checking \"%1\" for %2.\n")
                                  .arg(QDir::toNativeSeparators(current.absolutePath()))
                                  .arg(wizardFileName));
            if (current.exists(wizardFileName)) {
                QFile configFile(current.absoluteFilePath(wizardFileName));
                configFile.open(QIODevice::ReadOnly);
                QJsonParseError error;
                QByteArray fileData = configFile.readAll();
                QJsonDocument json = QJsonDocument::fromJson(fileData, &error);
                configFile.close();

                if (error.error != QJsonParseError::NoError) {
                    int line = 1;
                    int column = 1;
                    for (int i = 0; i < error.offset; ++i) {
                        if (fileData.at(i) == '\n') {
                            ++line;
                            column = 1;
                        } else {
                            ++column;
                        }
                    }
                    verboseLog.append(tr("* Failed to parse \"%1\":%2:%3: %4\n")
                                      .arg(configFile.fileName())
                                      .arg(line).arg(column)
                                      .arg(error.errorString()));
                    continue;
                }

                if (!json.isObject()) {
                    verboseLog.append(tr("* Did not find a JSON object in \"%1\".\n")
                                      .arg(configFile.fileName()));
                    continue;
                }

                if (verbose())
                    verboseLog.append(tr("* Configuration found and parsed.\n"));

                QVariantMap data = json.object().toVariantMap();

                int version = data.value(QLatin1String(VERSION_KEY), 0).toInt();
                if (version < 1 || version > 1) {
                    verboseLog.append(tr("* Version %1 not supported.\n").arg(version));
                    continue;
                }

                JsonWizardFactory *factory = createWizardFactory(data, current, &errorMessage);
                if (!factory) {
                    verboseLog.append(tr("* Failed to create: %1\n").arg(errorMessage));
                    continue;
                }

                result << factory;
            } else {
                QList<QFileInfo> subDirs = current.entryInfoList(filters, sortflags);
                if (!subDirs.isEmpty()) {
                    // There is no QList::prepend(QList)...
                    dirs.swap(subDirs);
                    dirs.append(subDirs);
                } else if (verbose()) {
                    verboseLog.append(tr("JsonWizard: \"%1\" not found\n").arg(wizardFileName));
                }
            }
        }
    }

    if (verbose()) { // Print to output pane for Windows.
        qWarning("%s", qPrintable(verboseLog));
        Core::MessageManager::write(verboseLog, Core::MessageManager::ModeSwitch);
    }

    return result;
}

JsonWizardFactory *JsonWizardFactory::createWizardFactory(const QVariantMap &data, const QDir &baseDir,
Tobias Hunger's avatar
Tobias Hunger committed
309
                                                          QString *errorMessage)
Tobias Hunger's avatar
Tobias Hunger committed
310 311 312 313 314 315 316 317 318
{
    JsonWizardFactory *factory = new JsonWizardFactory;
    if (!factory->initialize(data, baseDir, errorMessage)) {
        delete factory;
        factory = 0;
    }
    return factory;
}

319
Utils::FileNameList &JsonWizardFactory::searchPaths()
320
{
321
    static Utils::FileNameList m_searchPaths = Utils::FileNameList()
322 323 324 325 326 327 328
            << Utils::FileName::fromString(Core::ICore::userResourcePath() + QLatin1Char('/') +
                                           QLatin1String(WIZARD_PATH))
            << Utils::FileName::fromString(Core::ICore::resourcePath() + QLatin1Char('/') +
                                           QLatin1String(WIZARD_PATH));
    return m_searchPaths;
}

Tobias Hunger's avatar
Tobias Hunger committed
329 330
void JsonWizardFactory::addWizardPath(const Utils::FileName &path)
{
331
    searchPaths().append(path);
Tobias Hunger's avatar
Tobias Hunger committed
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
}

void JsonWizardFactory::setVerbose(int level)
{
    m_verbose = level;
}

int JsonWizardFactory::verbose()
{
    return m_verbose;
}

void JsonWizardFactory::registerPageFactory(JsonWizardPageFactory *factory)
{
    QTC_ASSERT(!s_pageFactories.contains(factory), return);
    s_pageFactories.append(factory);
}

void JsonWizardFactory::registerGeneratorFactory(JsonWizardGeneratorFactory *factory)
{
    QTC_ASSERT(!s_generatorFactories.contains(factory), return);
    s_generatorFactories.append(factory);
}

JsonWizardFactory::~JsonWizardFactory()
{ }

359
Utils::Wizard *JsonWizardFactory::runWizardImpl(const QString &path, QWidget *parent,
360
                                                Core::Id platform,
361
                                                const QVariantMap &variables)
Tobias Hunger's avatar
Tobias Hunger committed
362
{
363 364 365
    auto wizard = new JsonWizard(parent);
    wizard->setWindowIcon(icon());
    wizard->setWindowTitle(displayName());
Tobias Hunger's avatar
Tobias Hunger committed
366

367
    wizard->setValue(QStringLiteral("WizardDir"), m_wizardDir);
368 369 370
    QSet<Core::Id> tmp = requiredFeatures();
    tmp.subtract(pluginFeatures());
    wizard->setValue(QStringLiteral("RequiredFeatures"), Core::Id::toStringList(tmp));
Tobias Hunger's avatar
Tobias Hunger committed
371
    tmp = m_preferredFeatures;
372 373
    tmp.subtract(pluginFeatures());
    wizard->setValue(QStringLiteral("PreferredFeatures"), Core::Id::toStringList(tmp));
Tobias Hunger's avatar
Tobias Hunger committed
374

375 376
    wizard->setValue(QStringLiteral("Features"), Core::Id::toStringList(availableFeatures(platform)));
    wizard->setValue(QStringLiteral("Plugins"), Core::Id::toStringList(pluginFeatures()));
377

Tobias Hunger's avatar
Tobias Hunger committed
378 379
    // Add data to wizard:
    for (auto i = variables.constBegin(); i != variables.constEnd(); ++i)
380
        wizard->setValue(i.key(), i.value());
Tobias Hunger's avatar
Tobias Hunger committed
381

382
    wizard->setValue(QStringLiteral("InitialPath"), path);
383
    wizard->setValue(QStringLiteral("Platform"), platform.toString());
Tobias Hunger's avatar
Tobias Hunger committed
384 385 386 387 388 389

    QString kindStr = QLatin1String(Core::Constants::WIZARD_KIND_UNKNOWN);
    if (kind() == IWizardFactory::FileWizard)
        kindStr = QLatin1String(Core::Constants::WIZARD_KIND_FILE);
    else if (kind() == IWizardFactory::ProjectWizard)
        kindStr = QLatin1String(Core::Constants::WIZARD_KIND_PROJECT);
390
    wizard->setValue(QStringLiteral("kind"), kindStr);
Tobias Hunger's avatar
Tobias Hunger committed
391

392 393
    wizard->setValue(QStringLiteral("trDescription"), description());
    wizard->setValue(QStringLiteral("trDisplayName"), displayName());
394
    wizard->setValue(QStringLiteral("trDisplayCategory"), displayCategory());
395 396
    wizard->setValue(QStringLiteral("category"), category());
    wizard->setValue(QStringLiteral("id"), id().toString());
397

Tobias Hunger's avatar
Tobias Hunger committed
398
    for (auto i = m_options.constBegin(); i != m_options.constEnd(); ++i)
399
        wizard->setValue(i.key(), i.value());
Tobias Hunger's avatar
Tobias Hunger committed
400

401
    bool havePage = false;
Tobias Hunger's avatar
Tobias Hunger committed
402 403
    foreach (const Page &data, m_pages) {
        QTC_ASSERT(data.isValid(), continue);
404

405
        if (!JsonWizard::boolFromVariant(data.enabled, wizard->expander()))
406 407
            continue;

408
        havePage = true;
Tobias Hunger's avatar
Tobias Hunger committed
409 410 411 412 413
        JsonWizardPageFactory *factory = Utils::findOr(s_pageFactories, 0,
                                                       [&data](JsonWizardPageFactory *f) {
                                                            return f->canCreate(data.typeId);
                                                       });
        QTC_ASSERT(factory, continue);
414
        Utils::WizardPage *page = factory->create(wizard, data.typeId, data.data);
Tobias Hunger's avatar
Tobias Hunger committed
415 416 417 418 419 420 421
        QTC_ASSERT(page, continue);

        page->setTitle(data.title);
        page->setSubTitle(data.subTitle);
        page->setProperty(Utils::SHORT_TITLE_PROPERTY, data.shortTitle);

        if (data.index >= 0) {
422 423
            wizard->setPage(data.index, page);
            if (wizard->page(data.index) != page) // Failed to set page!
Tobias Hunger's avatar
Tobias Hunger committed
424 425
                delete page;
        } else {
426
            wizard->addPage(page);
Tobias Hunger's avatar
Tobias Hunger committed
427 428 429 430 431 432 433 434 435 436 437 438 439
        }
    }

    foreach (const Generator &data, m_generators) {
        QTC_ASSERT(data.isValid(), continue);
        JsonWizardGeneratorFactory *factory = Utils::findOr(s_generatorFactories, 0,
                                                            [&data](JsonWizardGeneratorFactory *f) {
                                                                 return f->canCreate(data.typeId);
                                                            });
        QTC_ASSERT(factory, continue);
        JsonWizardGenerator *gen = factory->create(data.typeId, data.data, path, platform, variables);
        QTC_ASSERT(gen, continue);

440
        wizard->addGenerator(gen);
Tobias Hunger's avatar
Tobias Hunger committed
441 442
    }

443 444 445 446
    if (!havePage) {
        wizard->accept();
        wizard->deleteLater();
        return 0;
447
    }
448 449 450

    wizard->show();
    return wizard;
Tobias Hunger's avatar
Tobias Hunger committed
451 452 453 454 455
}

QList<QVariant> JsonWizardFactory::objectOrList(const QVariant &data, QString *errorMessage)
{
    QList<QVariant> result;
456 457 458
    if (data.isNull())
        *errorMessage = tr("key not found.");
    else if (data.type() == QVariant::Map)
Tobias Hunger's avatar
Tobias Hunger committed
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
        result.append(data);
    else if (data.type() == QVariant::List)
        result = data.toList();
    else
        *errorMessage = tr("Expected an object or a list.");
    return result;
}

QString JsonWizardFactory::localizedString(const QVariant &value)
{
    if (value.isNull())
        return QString();
    if (value.type() == QVariant::Map) {
        QVariantMap tmp = value.toMap();
        const QString locale = languageSetting().toLower();
        QStringList locales;
        locales << locale << QLatin1String("en") << QLatin1String("C") << tmp.keys();
        foreach (const QString &locale, locales) {
            QString result = tmp.value(locale, QString()).toString();
            if (!result.isEmpty())
                return result;
        }
        return QString();
    }
    return QCoreApplication::translate("ProjectExplorer::JsonWizardFactory", value.toByteArray());
}

486
bool JsonWizardFactory::isAvailable(Core::Id platformId) const
487
{
488
    if (!IWizardFactory::isAvailable(platformId)) // check for required features
489 490 491
        return false;

    Utils::MacroExpander expander;
492
    Utils::MacroExpander *e = &expander;
493
    expander.registerVariable("Platform", tr("The platform selected for the wizard."),
494
                              [platformId]() { return platformId.toString(); });
495
    expander.registerVariable("Features", tr("The features available to this wizard."),
496
                              [this, e, platformId]() { return JsonWizard::stringListToArrayString(Core::Id::toStringList(availableFeatures(platformId)), e); });
497
    expander.registerVariable("Plugins", tr("The plugins loaded."),
498
                              [this, e]() { return JsonWizard::stringListToArrayString(Core::Id::toStringList(pluginFeatures()), e); });
499 500 501 502

    return JsonWizard::boolFromVariant(m_enabledExpression, &expander);
}

Tobias Hunger's avatar
Tobias Hunger committed
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
void JsonWizardFactory::destroyAllFactories()
{
    qDeleteAll(s_pageFactories);
    s_pageFactories.clear();
    qDeleteAll(s_generatorFactories);
    s_generatorFactories.clear();
}

bool JsonWizardFactory::initialize(const QVariantMap &data, const QDir &baseDir, QString *errorMessage)
{
    QTC_ASSERT(errorMessage, return false);

    errorMessage->clear();

    m_wizardDir = baseDir.absolutePath();

519 520
    m_enabledExpression = data.value(QLatin1String(ENABLED_EXPRESSION_KEY), true);

Tobias Hunger's avatar
Tobias Hunger committed
521 522 523 524
    QString strVal = data.value(QLatin1String(KIND_KEY)).toString();
    if (strVal != QLatin1String("class")
            && strVal != QLatin1String("file")
            && strVal != QLatin1String("project")) {
525
        *errorMessage = tr("\"kind\" value \"%1\" is not \"class\" (deprecated), \"file\" or \"project\".").arg(strVal);
Tobias Hunger's avatar
Tobias Hunger committed
526 527 528
        return false;
    }
    IWizardFactory::WizardKind kind = IWizardFactory::ProjectWizard;
529
    if (strVal == QLatin1String("file") || strVal == QLatin1String("class"))
Tobias Hunger's avatar
Tobias Hunger committed
530 531 532 533 534 535 536 537
        kind = IWizardFactory::FileWizard;
    setWizardKind(kind);

    strVal = data.value(QLatin1String(ID_KEY)).toString();
    if (strVal.isEmpty()) {
        *errorMessage = tr("No id set.");
        return false;
    }
538
    setId(Core::Id::fromString(strVal));
Tobias Hunger's avatar
Tobias Hunger committed
539 540 541 542 543 544 545 546 547 548 549

    strVal = data.value(QLatin1String(CATEGORY_KEY)).toString();
    if (strVal.isEmpty()) {
        *errorMessage = tr("No category is set.");
        return false;
    }
    setCategory(strVal);

    strVal = data.value(QLatin1String(ICON_KEY)).toString();
    if (!strVal.isEmpty()) {
        strVal = baseDir.absoluteFilePath(strVal);
550
        if (!QFileInfo::exists(strVal)) {
551
            *errorMessage = tr("Icon file \"%1\" not found.").arg(QDir::toNativeSeparators(strVal));
Tobias Hunger's avatar
Tobias Hunger committed
552 553 554 555 556
            return false;
        }
        setIcon(QIcon(strVal));
    }

557 558 559 560 561 562 563 564 565 566
    strVal = data.value(QLatin1String(IMAGE_KEY)).toString();
    if (!strVal.isEmpty()) {
        strVal = baseDir.absoluteFilePath(strVal);
        if (!QFileInfo::exists(strVal)) {
            *errorMessage = tr("Image file \"%1\" not found.").arg(QDir::toNativeSeparators(strVal));
            return false;
        }
        setDescriptionImage(strVal);
    }

567 568 569
    setRequiredFeatures(Core::Id::fromStringList(data.value(QLatin1String(REQUIRED_FEATURES_KEY)).toStringList()));
    m_preferredFeatures = Core::Id::fromStringList(data.value(QLatin1String(SUGGESTED_FEATURES_KEY)).toStringList());
    m_preferredFeatures.unite(requiredFeatures());
Tobias Hunger's avatar
Tobias Hunger committed
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593

    strVal = localizedString(data.value(QLatin1String(DISPLAY_NAME_KEY)));
    if (strVal.isEmpty()) {
        *errorMessage = tr("No displayName set.");
        return false;
    }
    setDisplayName(strVal);

    strVal = localizedString(data.value(QLatin1String(CATEGORY_NAME_KEY)));
    if (strVal.isEmpty()) {
        *errorMessage = tr("No displayCategory set.");
        return false;
    }
    setDisplayCategory(strVal);

    strVal = localizedString(data.value(QLatin1String(DESCRIPTION_KEY)));
    if (strVal.isEmpty()) {
        *errorMessage = tr("No description set.");
        return false;
    }
    setDescription(strVal);

    // Generator:
    QVariantList list = objectOrList(data.value(QLatin1String(GENERATOR_KEY)), errorMessage);
594
    if (!errorMessage->isEmpty()) {
Tobias Hunger's avatar
Tobias Hunger committed
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
        *errorMessage = tr("When parsing \"generators\": %1").arg(*errorMessage);
        return false;
    }

    foreach (const QVariant &v, list) {
        Generator gen = parseGenerator(v, errorMessage);
        if (gen.isValid())
            m_generators.append(gen);
        else
            return false;
    }

    // Pages:
    list = objectOrList(data.value(QLatin1String(PAGES_KEY)), errorMessage);
    if (!errorMessage->isEmpty()) {
        *errorMessage = tr("When parsing \"pages\": %1").arg(*errorMessage);
        return false;
    }

    foreach (const QVariant &v, list) {
        Page p = parsePage(v, errorMessage);
        if (p.isValid())
            m_pages.append(p);
        else
            return false;
    }

    WizardFlags flags = 0;
    if (data.value(QLatin1String(PLATFORM_INDEPENDENT_KEY), false).toBool())
        flags |= PlatformIndependent;
    setFlags(flags);

    // Options:
628
    const QVariant optionValue = data.value(QLatin1String(OPTIONS_KEY));
629
    const QVariantList optionList = optionValue.isNull() ? QVariantList() : objectOrList(optionValue, errorMessage);
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647

    foreach (const QVariant &v, optionList) {
        if (v.type() != QVariant::Map) {
            *errorMessage = tr("List element of \"options\" is not an object.");
            return false;
        }
        QVariantMap data = v.toMap();
        const QString key = data.value(QStringLiteral("key"), QString()).toString();
        const QString value = data.value(QStringLiteral("value"), QString()).toString();
        if (key.isEmpty()) {
            *errorMessage = tr("No \"key\" given for entry in \"options\".");
            return false;
        }
        if (m_options.contains(key)) {
            *errorMessage = tr("When parsing \"options\": Key \"%1\" set more than once.").arg(key);
            return false;
        }
        m_options.insert(key, value);
Tobias Hunger's avatar
Tobias Hunger committed
648 649 650 651 652 653
    }

    return true;
}

} // namespace ProjectExplorer