customwizardparameters.cpp 36.4 KB
Newer Older
hjk's avatar
hjk 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
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
7
**
hjk's avatar
hjk committed
8
9
10
11
** 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
**
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17
** 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.
hjk's avatar
hjk 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
con's avatar
con committed
27
28
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
29
****************************************************************************/
30
31

#include "customwizardparameters.h"
32
#include "customwizardscriptgenerator.h"
33

34
35
36
#include <coreplugin/icore.h>
#include <cpptools/cpptoolsconstants.h>

Eike Ziller's avatar
Eike Ziller committed
37
#include <utils/mimetypes/mimedatabase.h>
38
39
#include <utils/macroexpander.h>
#include <utils/templateengine.h>
40
41
#include <utils/qtcassert.h>

42
#include <QCoreApplication>
43
44
#include <QDate>
#include <QDebug>
45
#include <QDir>
46
#include <QFile>
47
48
#include <QFileInfo>
#include <QIcon>
49
#include <QJSEngine>
50
51
52
53
#include <QTemporaryFile>
#include <QTime>
#include <QXmlStreamAttribute>
#include <QXmlStreamReader>
54
55
56

enum { debug = 0 };

hjk's avatar
hjk committed
57
58
using namespace Core;

59
60
61
static const char customWizardElementC[] = "wizard";
static const char iconElementC[] = "icon";
static const char descriptionElementC[] = "description";
62
static const char displayNameElementC[] = "displayname";
63
static const char wizardEnabledAttributeC[] = "enabled";
64
65
66
67
68
69
static const char idAttributeC[] = "id";
static const char kindAttributeC[] = "kind";
static const char klassAttributeC[] = "class";
static const char firstPageAttributeC[] = "firstpage";
static const char langAttributeC[] = "xml:lang";
static const char categoryAttributeC[] = "category";
70
static const char displayCategoryElementC[] = "displaycategory";
71
static const char featuresRequiredC[] = "featuresRequired";
72
static const char platformIndependentC[] = "platformIndependent";
73
74
75
static const char fieldPageTitleElementC[] = "fieldpagetitle";
static const char fieldsElementC[] = "fields";
static const char fieldElementC[] = "field";
76
77
78
static const char comboEntriesElementC[] = "comboentries";
static const char comboEntryElementC[] = "comboentry";
static const char comboEntryTextElementC[] = "comboentrytext";
79

80
81
static const char generatorScriptElementC[] = "generatorscript";
static const char generatorScriptBinaryAttributeC[] = "binary";
82
static const char generatorScriptWorkingDirectoryAttributeC[] = "workingdirectory";
83
84
85
86
87
static const char generatorScriptArgumentElementC[] = "argument";
static const char generatorScriptArgumentValueAttributeC[] = "value";
static const char generatorScriptArgumentOmitEmptyAttributeC[] = "omit-empty";
static const char generatorScriptArgumentWriteFileAttributeC[] = "write-file";

88
89
90
91
92
93
94
static const char fieldDescriptionElementC[] = "fielddescription";
static const char fieldNameAttributeC[] = "name";
static const char fieldMandatoryAttributeC[] = "mandatory";
static const char fieldControlElementC[] = "fieldcontrol";

static const char filesElementC[] = "files";
static const char fileElementC[] = "file";
95
96
static const char fileSourceAttributeC[] = "source";
static const char fileTargetAttributeC[] = "target";
97
static const char fileBinaryAttributeC[] = "binary";
98

99
100
101
102
103
static const char rulesElementC[] = "validationrules";
static const char ruleElementC[] = "validationrule";
static const char ruleConditionAttributeC[] = "condition";
static const char ruleMessageElementC[] = "message";

104
105
106
107
108
enum ParseState {
    ParseBeginning,
    ParseWithinWizard,
    ParseWithinFields,
    ParseWithinField,
109
110
111
112
113
    ParseWithinFieldDescription,
    ParseWithinFieldControl,
    ParseWithinComboEntries,
    ParseWithinComboEntry,
    ParseWithinComboEntryText,
114
115
    ParseWithinFiles,
    ParseWithinFile,
116
117
    ParseWithinScript,
    ParseWithinScriptArguments,
118
119
120
    ParseWithinValidationRules,
    ParseWithinValidationRule,
    ParseWithinValidationRuleMessage,
121
122
123
124
125
126
    ParseError
};

namespace ProjectExplorer {
namespace Internal {

127
128
129
const char customWizardFileOpenEditorAttributeC[] = "openeditor";
const char customWizardFileOpenProjectAttributeC[] = "openproject";

130
131
132
133
134
135
136
137
138
139
140
141
142
CustomWizardField::CustomWizardField() :
    mandatory(false)
{
}

void CustomWizardField::clear()
{
    mandatory = false;
    name.clear();
    description.clear();
    controlAttributes.clear();
}

143
144
145
146
147
148
149
150
151
152
153
// Attribute map keys for combo entries
QString CustomWizardField::comboEntryValueKey(int i)
{
    return QLatin1String("comboValue") + QString::number(i);
}

QString CustomWizardField::comboEntryTextKey(int i)
{
    return QLatin1String("comboText") + QString::number(i);
}

154
CustomWizardFile::CustomWizardFile() :
155
        openEditor(false), openProject(false), binary(false)
156
157
158
{
}

159
160
/*!
    \class ProjectExplorer::CustomWizardValidationRule
161
162
    \brief The CustomWizardValidationRule class provides a custom wizard
    validation rule based on JavaScript-expressions over
163
164
165
166
167
168
169
170
171
172
173
    the field placeholders.

    Placeholder replacement is performed on the condition and it is evaluated
    using JavaScript. So, for example '"%ProjectName%" != "untitled" would block
    default names. On failure, the message is displayed in a red warning label
    in the wizard page. Placeholder replacement is also performed on the message
    prior to displaying.

    \sa ProjectExplorer::CustomWizard, ProjectExplorer::CustomWizardFieldPage
*/

174
175
176
177
178
179
180
bool CustomWizardValidationRule::validateRules(const QList<CustomWizardValidationRule> &rules,
                                               const QMap<QString, QString> &replacementMap,
                                               QString *errorMessage)
{
    errorMessage->clear();
    if (rules.isEmpty())
        return true;
181
    QJSEngine engine;
182
    foreach (const CustomWizardValidationRule &rule, rules)
183
184
185
186
187
188
189
190
    if (!rule.validate(engine, replacementMap)) {
        *errorMessage = rule.message;
        CustomWizardContext::replaceFields(replacementMap, errorMessage);
        return false;
    }
    return true;
}

191
bool CustomWizardValidationRule::validate(QJSEngine &engine, const QMap<QString, QString> &replacementMap) const
192
193
194
195
196
197
{
    // Apply parameters and evaluate using JavaScript
    QString cond = condition;
    CustomWizardContext::replaceFields(replacementMap, &cond);
    bool valid = false;
    QString errorMessage;
198
    if (!Utils::TemplateEngine::evaluateBooleanJavaScriptExpression(engine, cond, &valid, &errorMessage)) {
199
200
201
202
203
204
205
        qWarning("Error in custom wizard validation expression '%s': %s",
                 qPrintable(cond), qPrintable(errorMessage));
        return false;
    }
    return valid;
}

206
207
208
209
210
211
212
213
214
215
CustomWizardParameters::CustomWizardParameters() :
        firstPageId(-1)
{
}

void CustomWizardParameters::clear()
{
    directory.clear();
    files.clear();
    fields.clear();
216
    filesGeneratorScript.clear();
217
    filesGeneratorScriptArguments.clear();
218
    firstPageId = -1;
219
    rules.clear();
220
221
222
223
224
225
226
}

// Resolve icon file path relative to config file directory.
static inline QIcon wizardIcon(const QString &configFileFullPath,
                               const QString &xmlIconFileName)
{
    const QFileInfo fi(xmlIconFileName);
jkobus's avatar
jkobus committed
227
    if (fi.isFile() && fi.isAbsolute())
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
        return QIcon(fi.absoluteFilePath());
    if (!fi.isRelative())
        return QIcon();
    // Expand by config path
    const QFileInfo absFi(QFileInfo(configFileFullPath).absolutePath() +
                          QLatin1Char('/') + xmlIconFileName);
    if (absFi.isFile())
        return QIcon(absFi.absoluteFilePath());
    return QIcon();
}

// Forward a reader over element text
static inline bool skipOverElementText(QXmlStreamReader &reader)
{
    QXmlStreamReader::TokenType next = QXmlStreamReader::EndElement;
    do {
        next = reader.readNext();
    } while (next == QXmlStreamReader::Characters || next == QXmlStreamReader::EntityReference
             || next == QXmlStreamReader::ProcessingInstruction || next == QXmlStreamReader::Comment);
    return next == QXmlStreamReader::EndElement;
}

// Helper for reading text element depending on a language.
// Assign the element text to the string passed on if the language matches,
// that is, the element has no language attribute or there is an exact match.
// If there is no match, skip over the element text.
254
static inline bool assignLanguageElementText(QXmlStreamReader &reader,
255
256
257
                                             const QString &desiredLanguage,
                                             QString *target)
{
258
    const QStringRef elementLanguage = reader.attributes().value(QLatin1String(langAttributeC));
259
260
261
    if (elementLanguage.isEmpty()) {
        // Try to find a translation for our built-in Wizards
        *target = QCoreApplication::translate("ProjectExplorer::CustomWizard", reader.readElementText().toLatin1().constData());
262
263
264
        return true;
    }
    if (elementLanguage == desiredLanguage) {
265
        *target = reader.readElementText();
266
        return true;
267
    }
268
269
270
    // Language mismatch: forward to end element.
    skipOverElementText(reader);
    return false;
271
272
273
274
275
276
}

// Read level sub-elements of "wizard"
static bool parseCustomProjectElement(QXmlStreamReader &reader,
                                      const QString &configFileFullPath,
                                      const QString &language,
Tobias Hunger's avatar
Tobias Hunger committed
277
                                      CustomWizardParameters *p)
278
279
280
281
282
283
284
285
286
{
    const QStringRef elementName = reader.name();
    if (elementName == QLatin1String(iconElementC)) {
        const QString path = reader.readElementText();
        const QIcon icon = wizardIcon(configFileFullPath, path);
        if (icon.availableSizes().isEmpty()) {
            qWarning("Invalid icon path '%s' encountered in custom project template %s.",
                     qPrintable(path), qPrintable(configFileFullPath));
        } else {
Tobias Hunger's avatar
Tobias Hunger committed
287
                p->icon = icon;
288
289
290
291
        }
        return true;
    }
    if (elementName == QLatin1String(descriptionElementC)) {
Tobias Hunger's avatar
Tobias Hunger committed
292
        assignLanguageElementText(reader, language, &p->description);
293
294
295
        return true;
    }
    if (elementName == QLatin1String(displayNameElementC)) {
Tobias Hunger's avatar
Tobias Hunger committed
296
        assignLanguageElementText(reader, language, &p->displayName);
297
298
299
        return true;
    }
    if (elementName == QLatin1String(displayCategoryElementC)) {
Tobias Hunger's avatar
Tobias Hunger committed
300
        assignLanguageElementText(reader, language, &p->displayCategory);
301
302
303
304
305
306
307
308
309
        return true;
    }
    if (elementName == QLatin1String(fieldPageTitleElementC)) {
        assignLanguageElementText(reader, language, &p->fieldPageTitle);
        return true;
    }
    return false;
}

310
static inline QMap<QString, QString> attributesToStringMap(const QXmlStreamAttributes &attributes)
311
{
312
    QMap<QString, QString> rc;
313
    foreach (const QXmlStreamAttribute &attribute, attributes)
314
315
        rc.insert(attribute.name().toString(), attribute.value().toString());
    return rc;
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
}

// Switch parser state depending on opening element name.
static ParseState nextOpeningState(ParseState in, const QStringRef &name)
{
    switch (in) {
    case ParseBeginning:
        if (name == QLatin1String(customWizardElementC))
            return ParseWithinWizard;
        break;
    case ParseWithinWizard:
        if (name == QLatin1String(fieldsElementC))
            return ParseWithinFields;
        if (name == QLatin1String(filesElementC))
            return ParseWithinFiles;
331
332
        if (name == QLatin1String(generatorScriptElementC))
            return ParseWithinScript;
333
334
        if (name == QLatin1String(rulesElementC))
            return ParseWithinValidationRules;
335
336
337
338
339
        break;
    case ParseWithinFields:
        if (name == QLatin1String(fieldElementC))
            return ParseWithinField;
        break;
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
    case ParseWithinField:
        if (name == QLatin1String(fieldDescriptionElementC))
            return ParseWithinFieldDescription;
        if (name == QLatin1String(fieldControlElementC))
            return ParseWithinFieldControl;
        break;
    case ParseWithinFieldControl:
        if (name == QLatin1String(comboEntriesElementC))
            return ParseWithinComboEntries;
        break;
    case ParseWithinComboEntries:
        if (name == QLatin1String(comboEntryElementC))
            return ParseWithinComboEntry;
        break;
    case ParseWithinComboEntry:
        if (name == QLatin1String(comboEntryTextElementC))
            return ParseWithinComboEntryText;
        break;
358
359
360
361
    case ParseWithinFiles:
        if (name == QLatin1String(fileElementC))
            return ParseWithinFile;
        break;
362
363
364
365
    case ParseWithinScript:
        if (name == QLatin1String(generatorScriptArgumentElementC))
            return ParseWithinScriptArguments;
        break;
366
367
368
369
370
371
372
373
    case ParseWithinValidationRules:
        if (name == QLatin1String(ruleElementC))
            return ParseWithinValidationRule;
        break;
    case ParseWithinValidationRule:
        if (name == QLatin1String(ruleMessageElementC))
            return ParseWithinValidationRuleMessage;
        break;
374
375
    case ParseWithinFieldDescription: // No subelements
    case ParseWithinComboEntryText:
376
377
    case ParseWithinFile:
    case ParseError:
378
    case ParseWithinScriptArguments:
379
    case ParseWithinValidationRuleMessage:
380
381
382
        break;
    }
    return ParseError;
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

// Switch parser state depending on closing element name.
static ParseState nextClosingState(ParseState in, const QStringRef &name)
{
    switch (in) {
    case ParseBeginning:
        break;
    case ParseWithinWizard:
        if (name == QLatin1String(customWizardElementC))
            return ParseBeginning;
        break;
    case ParseWithinFields:
        if (name == QLatin1String(fieldsElementC))
            return ParseWithinWizard;
        break;
    case ParseWithinField:
        if (name == QLatin1String(fieldElementC))
            return ParseWithinFields;
        break;
    case ParseWithinFiles:
        if (name == QLatin1String(filesElementC))
            return ParseWithinWizard;
        break;
    case ParseWithinFile:
        if (name == QLatin1String(fileElementC))
            return ParseWithinFiles;
        break;
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
    case ParseWithinFieldDescription:
        if (name == QLatin1String(fieldDescriptionElementC))
            return ParseWithinField;
        break;
    case ParseWithinFieldControl:
        if (name == QLatin1String(fieldControlElementC))
            return ParseWithinField;
        break;
    case ParseWithinComboEntries:
        if (name == QLatin1String(comboEntriesElementC))
            return ParseWithinFieldControl;
        break;
    case ParseWithinComboEntry:
        if (name == QLatin1String(comboEntryElementC))
            return ParseWithinComboEntries;
        break;
    case ParseWithinComboEntryText:
        if (name == QLatin1String(comboEntryTextElementC))
            return ParseWithinComboEntry;
        break;
431
432
433
434
435
436
437
438
    case ParseWithinScript:
        if (name == QLatin1String(generatorScriptElementC))
            return ParseWithinWizard;
        break;
    case ParseWithinScriptArguments:
        if (name == QLatin1String(generatorScriptArgumentElementC))
            return ParseWithinScript;
        break;
439
440
441
442
443
444
    case ParseWithinValidationRuleMessage:
        return ParseWithinValidationRule;
    case ParseWithinValidationRule:
        return ParseWithinValidationRules;
    case ParseWithinValidationRules:
        return ParseWithinWizard;
445
446
447
448
    case ParseError:
        break;
    }
    return ParseError;
449
}
450
451

// Parse kind attribute
Tobias Hunger's avatar
Tobias Hunger committed
452
static inline IWizardFactory::WizardKind kindAttribute(const QXmlStreamReader &r)
453
454
{
    const QStringRef value = r.attributes().value(QLatin1String(kindAttributeC));
455
456
    if (value == QLatin1String("file") || value == QLatin1String("class"))
        return IWizardFactory::FileWizard;
Tobias Hunger's avatar
Tobias Hunger committed
457
    return IWizardFactory::ProjectWizard;
458
459
}

460
static inline QSet<Id> readRequiredFeatures(const QXmlStreamReader &reader)
461
462
463
{
    QString value = reader.attributes().value(QLatin1String(featuresRequiredC)).toString();
    QStringList stringList = value.split(QLatin1Char(','), QString::SkipEmptyParts);
464
    QSet<Id> features;
465
    foreach (const QString &string, stringList)
466
        features |= Id::fromString(string);
467
468
469
    return features;
}

Tobias Hunger's avatar
Tobias Hunger committed
470
static inline IWizardFactory::WizardFlags wizardFlags(const QXmlStreamReader &reader)
471
{
Tobias Hunger's avatar
Tobias Hunger committed
472
    IWizardFactory::WizardFlags flags;
473
    const QStringRef value = reader.attributes().value(QLatin1String(platformIndependentC));
474
475

    if (!value.isEmpty() && value == QLatin1String("true"))
Tobias Hunger's avatar
Tobias Hunger committed
476
        flags |= IWizardFactory::PlatformIndependent;
477
478
479
480

    return flags;
}

481
482
483
484
485
486
487
488
static inline QString msgError(const QXmlStreamReader &reader,
                               const QString &fileName,
                               const QString &what)
{
    return QString::fromLatin1("Error in %1 at line %2, column %3: %4").
            arg(fileName).arg(reader.lineNumber()).arg(reader.columnNumber()).arg(what);
}

489
490
static inline bool booleanAttributeValue(const QXmlStreamReader &r, const char *nameC,
                                         bool defaultValue)
491
{
492
493
494
495
    const QStringRef attributeValue = r.attributes().value(QLatin1String(nameC));
    if (attributeValue.isEmpty())
        return defaultValue;
    return attributeValue == QLatin1String("true");
496
497
498
499
}

static inline int integerAttributeValue(const QXmlStreamReader &r, const char *name, int defaultValue)
{
500
    const QStringRef sValue = r.attributes().value(QLatin1String(name));
501
502
503
    if (sValue.isEmpty())
        return defaultValue;
    bool ok;
504
    const int value = sValue.toString().toInt(&ok);
505
506
    if (!ok) {
        qWarning("Invalid integer value specification '%s' for attribute '%s'.",
507
                 qPrintable(sValue.toString()), name);
508
509
510
511
512
513
514
515
516
517
518
        return defaultValue;
    }
    return value;
}

static inline QString attributeValue(const QXmlStreamReader &r, const char *name)
{
    return r.attributes().value(QLatin1String(name)).toString();
}

// Return locale language attribute "de_UTF8" -> "de", empty string for "C"
con's avatar
con committed
519
static inline QString languageSetting()
520
{
hjk's avatar
hjk committed
521
    QString name = ICore::userInterfaceLanguage();
522
523
524
525
526
527
528
529
    const int underScorePos = name.indexOf(QLatin1Char('_'));
    if (underScorePos != -1)
        name.truncate(underScorePos);
    if (name.compare(QLatin1String("C"), Qt::CaseInsensitive) == 0)
        name.clear();
    return name;
}

530
531
/*!
    \class ProjectExplorer::Internal::GeneratorScriptArgument
532
533
    \brief The GeneratorScriptArgument class provides an argument to a custom
    wizard generator script.
534
535
536
537
538
539
540

    Contains placeholders to be replaced by field values or file names
    as in \c '--class-name=%ClassName%' or \c '--description=%Description%'.

    \sa ProjectExplorer::CustomWizard
*/

541
542
543
544
545
GeneratorScriptArgument::GeneratorScriptArgument(const QString &v) :
    value(v), flags(0)
{
}

546
// Main parsing routine
547
CustomWizardParameters::ParseResult
Tobias Hunger's avatar
Tobias Hunger committed
548
549
CustomWizardParameters::parse(QIODevice &device, const QString &configFileFullPath,
                              QString *errorMessage)
550
{
551
    int comboEntryCount = 0;
552
553
554
555
    QXmlStreamReader reader(&device);
    QXmlStreamReader::TokenType token = QXmlStreamReader::EndDocument;
    ParseState state = ParseBeginning;
    clear();
Tobias Hunger's avatar
Tobias Hunger committed
556
    kind = IWizardFactory::ProjectWizard;
con's avatar
con committed
557
    const QString language = languageSetting();
558
559
560
561
562
563
    CustomWizardField field;
    do {
        token = reader.readNext();
        switch (token) {
        case QXmlStreamReader::Invalid:
            *errorMessage = msgError(reader, configFileFullPath, reader.errorString());
564
            return ParseFailed;
565
566
567
        case QXmlStreamReader::StartElement:
            do {
                // Read out subelements applicable to current state
Tobias Hunger's avatar
Tobias Hunger committed
568
                if (state == ParseWithinWizard && parseCustomProjectElement(reader, configFileFullPath, language, this))
569
570
571
572
573
574
575
576
                    break;
                // switch to next state
                state = nextOpeningState(state, reader.name());
                // Read attributes post state-switching
                switch (state) {
                case ParseError:
                    *errorMessage = msgError(reader, configFileFullPath,
                                             QString::fromLatin1("Unexpected start element %1").arg(reader.name().toString()));
577
                    return ParseFailed;
578
                case ParseWithinWizard:
579
580
                    if (!booleanAttributeValue(reader, wizardEnabledAttributeC, true))
                        return ParseDisabled;
581
582
583
584
585
                    {
                        const QString idString = attributeValue(reader, idAttributeC);
                        if (!idString.isEmpty())
                            id = Core::Id::fromString(idString);
                    }
Tobias Hunger's avatar
Tobias Hunger committed
586
587
588
589
                    category = attributeValue(reader, categoryAttributeC);
                    kind = kindAttribute(reader);
                    requiredFeatures = readRequiredFeatures(reader);
                    flags = wizardFlags(reader);
590
591
592
593
594
                    klass = attributeValue(reader, klassAttributeC);
                    firstPageId = integerAttributeValue(reader, firstPageAttributeC, -1);
                    break;
                case ParseWithinField: // field attribute
                    field.name = attributeValue(reader, fieldNameAttributeC);
595
                    field.mandatory = booleanAttributeValue(reader, fieldMandatoryAttributeC, false);
596
                    break;
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
                case ParseWithinFieldDescription:
                    assignLanguageElementText(reader, language, &field.description);
                    state = ParseWithinField; // The above reads away the end tag, set state.
                    break;
                case ParseWithinFieldControl: // Copy widget control attributes
                    field.controlAttributes = attributesToStringMap(reader.attributes());
                    break;
                case ParseWithinComboEntries:
                    break;
                case ParseWithinComboEntry: // Combo entry with 'value' attribute
                    field.controlAttributes.insert(CustomWizardField::comboEntryValueKey(comboEntryCount),
                                                   attributeValue(reader, "value"));
                    break;
                case ParseWithinComboEntryText: {

                        // This reads away the end tag, set state here.
                        QString text;
                        if (assignLanguageElementText(reader, language, &text))
                            field.controlAttributes.insert(CustomWizardField::comboEntryTextKey(comboEntryCount),
                                                           text);
                        state = ParseWithinComboEntry;
                }
                     break;
620
621
                case ParseWithinFiles:
                    break;
622
623
                case ParseWithinFile: { // file attribute
                        CustomWizardFile file;
624
625
626
627
                        file.source = attributeValue(reader, fileSourceAttributeC);
                        file.target = attributeValue(reader, fileTargetAttributeC);
                        file.openEditor = booleanAttributeValue(reader, customWizardFileOpenEditorAttributeC, false);
                        file.openProject = booleanAttributeValue(reader, customWizardFileOpenProjectAttributeC, false);
628
                        file.binary = booleanAttributeValue(reader, fileBinaryAttributeC, false);
629
630
                        if (file.target.isEmpty())
                            file.target = file.source;
631
                        if (file.source.isEmpty())
632
                            qWarning("Skipping empty file name in custom project.");
633
                        else
634
635
636
                            files.push_back(file);
                    }
                    break;
637
638
639
640
641
642
                case ParseWithinScript:
                    filesGeneratorScript = fixGeneratorScript(configFileFullPath, attributeValue(reader, generatorScriptBinaryAttributeC));
                    if (filesGeneratorScript.isEmpty()) {
                        *errorMessage = QString::fromLatin1("No binary specified for generator script.");
                        return ParseFailed;
                    }
643
                    filesGeneratorScriptWorkingDirectory = attributeValue(reader, generatorScriptWorkingDirectoryAttributeC);
644
645
646
647
648
649
650
651
652
653
654
655
656
657
                    break;
                case ParseWithinScriptArguments: {
                    GeneratorScriptArgument argument(attributeValue(reader, generatorScriptArgumentValueAttributeC));
                    if (argument.value.isEmpty()) {
                        *errorMessage = QString::fromLatin1("No value specified for generator script argument.");
                        return ParseFailed;
                    }
                    if (booleanAttributeValue(reader, generatorScriptArgumentOmitEmptyAttributeC, false))
                        argument.flags |= GeneratorScriptArgument::OmitEmpty;
                    if (booleanAttributeValue(reader, generatorScriptArgumentWriteFileAttributeC, false))
                        argument.flags |= GeneratorScriptArgument::WriteFile;
                    filesGeneratorScriptArguments.push_back(argument);
                }
                    break;
658
659
660
661
662
663
664
                case ParseWithinValidationRule: {
                    CustomWizardValidationRule rule;
                    rule.condition = reader.attributes().value(QLatin1String(ruleConditionAttributeC)).toString();
                    rules.push_back(rule);
                }
                    break;
                case ParseWithinValidationRuleMessage:
665
                    QTC_ASSERT(!rules.isEmpty(), return ParseFailed);
666
667
668
669
                    // This reads away the end tag, set state here.
                    assignLanguageElementText(reader, language, &(rules.back().message));
                    state = ParseWithinValidationRule;
                    break;
670
671
672
673
674
675
676
                default:
                    break;
                }
            } while (false);
            break;
        case QXmlStreamReader::EndElement:
            state = nextClosingState(state, reader.name());
677
678
            switch (state) {
            case ParseError:
679
680
                *errorMessage = msgError(reader, configFileFullPath,
                                         QString::fromLatin1("Unexpected end element %1").arg(reader.name().toString()));
681
                return ParseFailed;
682
            case ParseWithinFields:  // Leaving a field element
683
684
                fields.push_back(field);
                field.clear();
685
                comboEntryCount = 0;
686
687
688
689
690
691
                break;
            case ParseWithinComboEntries:
                comboEntryCount++;
                break;
            default:
                break;
692
693
694
695
696
697
            }
            break;
        default:
            break;
        }
    } while (token != QXmlStreamReader::EndDocument);
698
    return ParseOk;
699
700
}

701
CustomWizardParameters::ParseResult
Tobias Hunger's avatar
Tobias Hunger committed
702
CustomWizardParameters::parse(const QString &configFileFullPath, QString *errorMessage)
703
704
705
706
{
    QFile configFile(configFileFullPath);
    if (!configFile.open(QIODevice::ReadOnly|QIODevice::Text)) {
        *errorMessage = QString::fromLatin1("Cannot open %1: %2").arg(configFileFullPath, configFile.errorString());
707
        return ParseFailed;
708
    }
Tobias Hunger's avatar
Tobias Hunger committed
709
    return parse(configFile, configFileFullPath, errorMessage);
710
711
}

712
713
// ------------ CustomWizardContext

714
715
static inline QString passThrough(const QString &in) { return in; }

716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
static inline QString headerGuard(const QString &in)
{
    QString result;
    foreach (const QChar c, in) {
        if (c.isLetterOrNumber())
            result.append(c.toUpper());
        else
            result.append(QLatin1Char('_'));
    }
    return result;
}

static inline QString structName(const QString &in)
{
    bool capNeeded = true;
    QString result;
    foreach (const QChar c, in) {
        if (c.isLetterOrNumber()) {
            if (capNeeded) {
                result.append(c.toUpper());
                capNeeded = false;
            } else {
                result.append(c);
            }
        } else {
            result.append(QLatin1Char('_'));
            capNeeded = true;
        }
    }
    return result;
}

748
749
750
751
752
753
// Do field replacements applying modifiers and string transformation
// for the value
template <class ValueStringTransformation>
bool replaceFieldHelper(ValueStringTransformation transform,
                        const CustomWizardContext::FieldReplacementMap &fm,
                        QString *s)
754
{
755
    bool nonEmptyReplacements = false;
756
757
758
759
760
761
762
763
764
765
766
767
768
769
    if (debug) {
        qDebug().nospace() << "CustomWizardContext::replaceFields with " <<
                fm << *s;
    }
    const QChar delimiter = QLatin1Char('%');
    const QChar modifierDelimiter = QLatin1Char(':');
    int pos = 0;
    while (pos < s->size()) {
        pos = s->indexOf(delimiter, pos);
        if (pos < 0)
            break;
        int nextPos = s->indexOf(delimiter, pos + 1);
        if (nextPos == -1)
            break;
770
        if (nextPos == pos + 1) {
771
772
773
            pos = nextPos; // Replace '%%' with '%'
            s->remove(pos, 1);
            pos = pos + 1;
774
775
776
777
            continue;
        }
        // Evaluate field specification for modifiers
        // "%field:l%"
778
        QString fieldSpec = s->mid(pos + 1, nextPos - pos - 1);
779
780
781
782
783
784
        const int fieldSpecSize = fieldSpec.size();
        char modifier = '\0';
        if (fieldSpecSize >= 3 && fieldSpec.at(fieldSpecSize - 2) == modifierDelimiter) {
            modifier = fieldSpec.at(fieldSpecSize - 1).toLatin1();
            fieldSpec.truncate(fieldSpecSize - 2);
        }
785
        const CustomWizardContext::FieldReplacementMap::const_iterator it = fm.constFind(fieldSpec);
786
787
788
789
790
791
792
793
794
795
796
797
798
        if (it == fm.constEnd()) {
            pos = nextPos; // Not found, skip
            continue;
        }
        // Assign
        QString replacement = it.value();
        switch (modifier) {
        case 'l':
            replacement = it.value().toLower();
            break;
        case 'u':
            replacement = it.value().toUpper();
            break;
799
800
801
802
803
804
805
        case 'h': // Create a header guard.
            replacement = headerGuard(it.value());
            break;
        case 's': // Create a struct or class name.
            replacement = structName(it.value());
            break;
        case 'c': // Capitalize first letter.
806
807
            replacement = it.value();
            if (!replacement.isEmpty())
808
                replacement[0] = replacement.at(0).toTitleCase();
809
810
811
812
            break;
        default:
            break;
        }
813
814
815
        if (!replacement.isEmpty())
            nonEmptyReplacements = true;
        // Apply transformation to empty values as well.
816
        s->replace(pos, nextPos - pos + 1, transform(replacement));
817
        nonEmptyReplacements = true;
818
819
        pos += replacement.size();
    }
820
821
822
    return nonEmptyReplacements;
}

823
/*!
824
    Replaces field values delimited by '%' with special modifiers:
825
    \list
826
827
828
829
830
831
    \li %Field% -> simple replacement
    \li %Field:l% -> replace with everything changed to lower case
    \li %Field:u% -> replace with everything changed to upper case
    \li %Field:c% -> replace with first character capitalized
    \li  %Field:h% -> replace with something usable as header guard
    \li %Field:s% -> replace with something usable as structure or class name
832
833
834
835
836
    \endlist

    The return value indicates whether non-empty replacements were encountered.
*/

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
868
869
870
bool CustomWizardContext::replaceFields(const FieldReplacementMap &fm, QString *s)
{
    return replaceFieldHelper(passThrough, fm, s);
}

// Transformation to be passed to replaceFieldHelper(). Writes the
// value to a text file and returns the file name to be inserted
// instead of the expanded field in the parsed template,
// used for the arguments of a generator script.
class TemporaryFileTransform {
public:
    typedef CustomWizardContext::TemporaryFilePtr TemporaryFilePtr;
    typedef CustomWizardContext::TemporaryFilePtrList TemporaryFilePtrList;

    explicit TemporaryFileTransform(TemporaryFilePtrList *f);

    QString operator()(const QString &) const;

private:
    TemporaryFilePtrList *m_files;
    QString m_pattern;
};

TemporaryFileTransform::TemporaryFileTransform(TemporaryFilePtrList *f) :
    m_files(f), m_pattern(QDir::tempPath())
{
    if (!m_pattern.endsWith(QLatin1Char('/')))
        m_pattern += QLatin1Char('/');
    m_pattern += QLatin1String("qtcreatorXXXXXX.txt");
}

QString TemporaryFileTransform::operator()(const QString &value) const
{
    TemporaryFilePtr temporaryFile(new QTemporaryFile(m_pattern));
871
    QTC_ASSERT(temporaryFile->open(), return QString());
872
873
874
875
876
877
878
879
880

    temporaryFile->write(value.toLocal8Bit());
    const QString name = temporaryFile->fileName();
    temporaryFile->flush();
    temporaryFile->close();
    m_files->push_back(temporaryFile);
    return name;
}

881
882
/*!
    \class ProjectExplorer::Internal::CustomWizardContext
883
884
    \brief The CustomWizardContext class provides the context for one custom
    wizard run.
885
886
887
888

    Shared between CustomWizard and the CustomWizardPage as it is used
    for the QLineEdit-type fields'
    default texts as well. Contains basic replacement fields
889
    like \c '%CppSourceSuffix%', \c '%CppHeaderSuffix%' (settings-dependent).
890
891
892
893
894
895
896
897
    reset() should be called before each wizard run to refresh them.
    CustomProjectWizard additionally inserts \c '%ProjectName%' from
    the intro page to have it available for default texts.

    \sa ProjectExplorer::CustomWizard
*/

/*!
898
899
    This function is a special replaceFields() overload used for the arguments
    of a generator
900
901
    script.

902
903
904
    Writes the expanded field values out to temporary files specified by
    \a files and inserts file names instead of the expanded fields in the
    string \a s.
905
906
*/

907
908
909
910
bool CustomWizardContext::replaceFields(const FieldReplacementMap &fm, QString *s,
                                        TemporaryFilePtrList *files)
{
    return replaceFieldHelper(TemporaryFileTransform(files), fm, s);
911
912
913
914
}

void CustomWizardContext::reset()
{
915
916
917
    // Basic replacement fields: Suffixes and date/time.
    const QDate currentDate = QDate::currentDate();
    const QTime currentTime = QTime::currentTime();
918
    baseReplacements.clear();
Eike Ziller's avatar
Eike Ziller committed
919
    Utils::MimeDatabase mdb;
920
    baseReplacements.insert(QLatin1String("CppSourceSuffix"),
Eike Ziller's avatar
Eike Ziller committed
921
922
                            mdb.mimeTypeForName(QLatin1String(CppTools::Constants::CPP_SOURCE_MIMETYPE))
                            .preferredSuffix());
923
    baseReplacements.insert(QLatin1String("CppHeaderSuffix"),
Eike Ziller's avatar
Eike Ziller committed
924
925
                            mdb.mimeTypeForName(QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE))
                            .preferredSuffix());
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
    baseReplacements.insert(QLatin1String("CurrentDate"),
                            currentDate.toString(Qt::ISODate));
    baseReplacements.insert(QLatin1String("CurrentTime"),
                            currentTime.toString(Qt::ISODate));
    baseReplacements.insert(QLatin1String("CurrentDate:ISO"),
                            currentDate.toString(Qt::ISODate));
    baseReplacements.insert(QLatin1String("CurrentTime:ISO"),
                            currentTime.toString(Qt::ISODate));
    baseReplacements.insert(QLatin1String("CurrentDate:RFC"),
                            currentDate.toString(Qt::RFC2822Date));
    baseReplacements.insert(QLatin1String("CurrentTime:RFC"),
                            currentTime.toString(Qt::RFC2822Date));
    baseReplacements.insert(QLatin1String("CurrentDate:Locale"),
                            currentDate.toString(Qt::DefaultLocaleShortDate));
    baseReplacements.insert(QLatin1String("CurrentTime:Locale"),
                            currentTime.toString(Qt::DefaultLocaleShortDate));
942
    replacements.clear();
943
    path.clear();
944
    targetPath.clear();
945
946
}

947
948
949
950
951
952
953
954
955
956
957
QString CustomWizardContext::processFile(const FieldReplacementMap &fm, QString in)
{

    if (in.isEmpty())
        return in;

    if (!fm.isEmpty())
        replaceFields(fm, &in);

    QString out;
    QString errorMessage;
958
    if (!Utils::TemplateEngine::preprocessText(in, &out, &errorMessage)) {
959
960
961
962
963
964
965
        qWarning("Error preprocessing custom widget file: %s\nFile:\n%s",
                 qPrintable(errorMessage), qPrintable(in));
        return QString();
    }
    return out;
}

966
967
} // namespace Internal
} // namespace ProjectExplorer