summaryrefslogtreecommitdiff
path: root/src/plugins/qmldesigner/components/componentcore/designericons.cpp
blob: 2af0709c3aea1c6eae71214ca0f3c161e39ee070 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
// Copyright (C) 2022 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0+ OR GPL-3.0 WITH Qt-GPL-exception-1.0

#include "designericons.h"

#include <invalidargumentexception.h>

#include <QCache>
#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QMetaEnum>
#include <QRegularExpression>

using namespace QmlDesigner;
namespace { // Blank namespace

template <typename EType>
struct DesignerIconEnums
{
    typedef EType EnumType;
    static QString toString(const EnumType &enumValue);
    static EnumType value(const QString &keyStr, bool *ok = nullptr);

    static const QMetaEnum metaEnum;
    static const QString keyName;
};

template <typename EType>
struct DesignerEnumConfidentType
{
    typedef EType EnumType;
};

template <>
struct DesignerEnumConfidentType<QIcon::Mode>
{
    typedef DesignerIcons::Mode EnumType;
};

template <>
struct DesignerEnumConfidentType<QIcon::State>
{
    typedef DesignerIcons::State EnumType;
};

template <typename T>
QString getEnumName() {
    QMetaEnum metaEnum = QMetaEnum::fromType<T>();
    QString enumName = QString::fromLatin1(metaEnum.enumName());
    if (enumName.size() && enumName.at(0).isUpper())
        enumName.replace(0, 1, enumName.at(0).toLower());
    return enumName;
};

template <>
QString getEnumName<Theme::Icon>() {
    return QLatin1String("iconName");
};

template <typename EType>
const QMetaEnum DesignerIconEnums<EType>::metaEnum =
        QMetaEnum::fromType<typename DesignerEnumConfidentType<EType>::EnumType>();

template <typename EType>
const QString DesignerIconEnums<EType>::keyName =
        getEnumName<typename DesignerEnumConfidentType<EType>::EnumType>();

template <typename EType>
QString DesignerIconEnums<EType>::toString(const EType &enumValue)
{
    return QString::fromLatin1(metaEnum.valueToKey(enumValue));
}

template <typename EType>
EType DesignerIconEnums<EType>::value(const QString &keyStr, bool *ok)
{
    return static_cast<EType>(metaEnum.keyToValue(keyStr.toLatin1(), ok));
}

QJsonObject mergeJsons(const QJsonObject &prior, const QJsonObject &joiner)
{
    QJsonObject object = prior;
    const QStringList joinerKeys = joiner.keys();
    for (const QString &joinerKey : joinerKeys) {
        if (!object.contains(joinerKey)) {
            object.insert(joinerKey, joiner.value(joinerKey));
        } else {
            QJsonValue ov = object.value(joinerKey);
            QJsonValue jv = joiner.value(joinerKey);
            if (ov.isObject() && jv.isObject()) {
                QJsonObject mg = mergeJsons(ov.toObject(), jv.toObject());
                object.insert(joinerKey, mg);
            }
        }
    }
    return object;
}

inline QString toJsonSize(const QSize &size)
{
    return QString::fromLatin1("%1x%2").arg(size.width()).arg(size.height());
}

template <typename EnumType>
void pushSimpleEnumValue(QJsonObject &object, const EnumType &enumVal)
{
    const QString &enumKey = DesignerIconEnums<EnumType>::keyName;
    QString enumValue = DesignerIconEnums<EnumType>::toString(enumVal);
    object.insert(enumKey, enumValue);
}

template <typename T>
T jsonSafeValue(const QJsonObject &jsonObject, const QString &symbolName,
                       std::function<bool (const T&)> validityCheck = [](const T&) -> bool {return true;})
{
    if (!jsonObject.contains(symbolName))
        throw InvalidArgumentException(__LINE__, __FUNCTION__, __FILE__, symbolName.toLatin1());

    QVariant symbolVar = jsonObject.value(symbolName);
    T extractedVal = symbolVar.value<T>();
    if (!validityCheck(extractedVal))
        throw InvalidArgumentException(__LINE__, __FUNCTION__, __FILE__, symbolName.toLatin1());

    return extractedVal;
}

QSize jsonSafeSize(const QJsonObject &jsonObject, const QString &symbolName)
{
    QString extractedVal = jsonSafeValue<QString>(jsonObject, symbolName);
    QStringList dims = extractedVal.split("x");
    if (dims.size() == 2) {
        bool wOk;
        bool hOk;
        int cWidth = dims.first().toInt(&wOk);
        int cHeight = dims.last().toInt(&hOk);
        if (wOk && hOk)
            return {cWidth, cHeight};
    }
    throw InvalidArgumentException(__LINE__, __FUNCTION__, __FILE__, symbolName.toLatin1());
    return {};
}

template <typename T>
T jsonSafeMetaEnum(const QJsonObject &jsonObject, const QString &symbolName = DesignerIconEnums<T>::keyName)
{
    QString extractedVal = jsonSafeValue<QString>(jsonObject, symbolName);
    bool ok;
    T enumIndex = static_cast<T> (DesignerIconEnums<T>::value(extractedVal, &ok));
    if (ok)
        return enumIndex;

    throw InvalidArgumentException(__LINE__, __FUNCTION__, __FILE__, symbolName.toLatin1());
    return {};
}

template <typename T>
struct JsonMap
{};

template <>
struct JsonMap<IconFontHelper>
{
    static IconFontHelper value(const QJsonObject &jsonObject, const QJsonObject &telescopingMap)
    {
        QJsonObject fontHelperJson = mergeJsons(jsonObject, telescopingMap);
        return IconFontHelper::fromJson(fontHelperJson);
    }

    static QJsonObject json(const IconFontHelper &iconFontHelper)
    {
        QJsonObject object;
        pushSimpleEnumValue(object, iconFontHelper.themeIcon());
        pushSimpleEnumValue(object, iconFontHelper.themeColor());
        object.insert("size", toJsonSize(iconFontHelper.size()));
        return object;
    }
};

template <typename Key, typename Value>
struct JsonMap<QMap<Key, Value>>
{
    typedef QMap<Key, Value> MapType;
    static MapType value(const QJsonObject &mapObject, const QJsonObject &telescopingMap)
    {
        typedef typename MapType::key_type KeyType;
        typedef typename MapType::mapped_type ValueType;

        QMap<KeyType, ValueType> output;
        QJsonObject curObject = mergeJsons(mapObject, telescopingMap);
        const QStringList keyList = curObject.keys();
        QStringList validKeys;
        QString keyTypeStr = DesignerIconEnums<KeyType>::keyName;
        QJsonObject nextTelescopingMap = telescopingMap;

        for (const QString &jsonKey : keyList) {
            bool keyAvailable = false;
            DesignerIconEnums<KeyType>::value(jsonKey, &keyAvailable);
            if (keyAvailable)
                validKeys.append(jsonKey);
            else
                nextTelescopingMap.insert(jsonKey, curObject.value(jsonKey));
        }

        for (const QString &jsonKey : validKeys) {
            bool keyAvailable = false;
            const KeyType key = DesignerIconEnums<KeyType>::value(jsonKey, &keyAvailable);
            QJsonValue jsonValue = curObject.value(jsonKey);

            nextTelescopingMap.insert(keyTypeStr, jsonKey);
            if (!jsonValue.isObject()) {
                qWarning() << Q_FUNC_INFO << __LINE__ << "Value of the" << jsonKey << "should be a json object.";
                continue;
            }
            output.insert(key, JsonMap<ValueType>::value(jsonValue.toObject(), nextTelescopingMap));
        }

        return output;
    }

    static QJsonObject json(const QMap<Key, Value> &map)
    {
        QJsonObject output;
        for (auto it = map.cbegin(), end = map.cend(); it != end; ++it)
            output[DesignerIconEnums<Key>::toString(it.key())] = JsonMap<Value>::json(it.value());

        return output;
    }
};

} // End of blank namespace

class QmlDesigner::DesignerIconsPrivate
{
public:
    DesignerIconsPrivate(const QString &fontName)
        : mFontName(fontName) {}

    QString mFontName;
    DesignerIcons::IconsMap icons;
    static QCache<QString, DesignerIcons::IconsMap> cache;
};

QCache<QString, DesignerIcons::IconsMap> DesignerIconsPrivate::cache(100);

IconFontHelper::IconFontHelper(Theme::Icon themeIcon, Theme::Color color, const QSize &size, QIcon::Mode mode, QIcon::State state)
    : Super(Theme::getIconUnicode(themeIcon),
            Theme::getColor(color),
            size,
            mode, state)
    , mThemeIcon(themeIcon)
    , mThemeColor(color)
{}

IconFontHelper IconFontHelper::fromJson(const QJsonObject &jsonObject)
{
    try {
        Theme::Icon iconName = jsonSafeMetaEnum<Theme::Icon>(jsonObject);
        Theme::Color iconColor = jsonSafeMetaEnum<Theme::Color>(jsonObject);
        QSize iconSize = jsonSafeSize(jsonObject, "size");
        QIcon::Mode iconMode = jsonSafeMetaEnum<QIcon::Mode>(jsonObject);
        QIcon::State iconState = jsonSafeMetaEnum<QIcon::State>(jsonObject);
        return IconFontHelper(iconName, iconColor, iconSize, iconMode, iconState);
    } catch (const Exception &exception) {
        exception.showException("Faild to load IconFontHelper");
        return {};
    }
}

QJsonObject IconFontHelper::toJson() const
{
    QJsonObject jsonObject;
    pushSimpleEnumValue(jsonObject, themeIcon());
    pushSimpleEnumValue(jsonObject, themeColor());
    pushSimpleEnumValue(jsonObject, mode());
    pushSimpleEnumValue(jsonObject, state());
    jsonObject.insert("size", toJsonSize(size()));
    return jsonObject;
}

Theme::Icon IconFontHelper::themeIcon() const
{
    return mThemeIcon;
}

Theme::Color IconFontHelper::themeColor() const
{
    return mThemeColor;
}

IconFontHelper::IconFontHelper()
    : IconFontHelper({}, {}, {}, {}, {}) {}

DesignerIcons::DesignerIcons(const QString &fontName, const QString &iconDatabase)
    : d(new DesignerIconsPrivate(fontName))
{
    if (iconDatabase.size())
        loadIconSettings(iconDatabase);
}

DesignerIcons::~DesignerIcons()
{
    delete d;
}

QIcon DesignerIcons::icon(IconId icon, Area area) const
{
    return Utils::StyleHelper::getIconFromIconFont(d->mFontName, helperList(icon, area));
}

void DesignerIcons::loadIconSettings(const QString &fileName)
{
    if (d->cache.contains(fileName)) {
        d->icons = *d->cache.object(fileName);
        return;
    }

    QFile designerIconFile(fileName);

    if (!designerIconFile.open(QFile::ReadOnly)) {
        qWarning() << Q_FUNC_INFO << __LINE__ << "Can not open file:" << fileName << designerIconFile.errorString();
        return;
    }

    if (designerIconFile.size() > 100e3) {
        qWarning() << Q_FUNC_INFO << __LINE__ << "Large File:" << fileName;
        return;
    }

    QJsonParseError parseError;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(designerIconFile.readAll(), &parseError);

    if (parseError.error != QJsonParseError::NoError) {
        qWarning() << Q_FUNC_INFO << __LINE__ << "Json Parse Error - " << parseError.errorString() << "---\t File: " << fileName;
        return;
    }

    if (!jsonDoc.isObject()) {
        qWarning() << Q_FUNC_INFO << __LINE__ << "Invalid Json Array in file: " << fileName;
        return;
    }

    clearAll();
    d->icons = JsonMap<IconsMap>::value(jsonDoc.object(), {});
    d->cache.insert(fileName, new IconsMap(d->icons), 1);
}

void DesignerIcons::exportSettings(const QString &fileName) const
{
    QFile outFile(fileName);
    if (!outFile.open(QFile::WriteOnly)) {
        qWarning() << Q_FUNC_INFO << __LINE__ << "Can not open file for writing:" << fileName;
        return;
    }

    QJsonDocument jsonDocument;
    jsonDocument.setObject(JsonMap<IconsMap>::json(d->icons));

    outFile.write(jsonDocument.toJson());
    outFile.close();
}

void DesignerIcons::clearAll()
{
    d->icons.clear();
}

void DesignerIcons::addIcon(const IconId &iconId, const Area &area, const IconFontHelper &fontHelper)
{
    AreaMap &areaMap = d->icons[iconId];
    IconMap &iconMap = areaMap[area];
    ModeMap &modeMap = iconMap[static_cast<State>(fontHelper.state())];
    modeMap.insert(static_cast<Mode>(fontHelper.mode()), fontHelper);
}

void DesignerIcons::addIcon(IconId iconId,
                            Area area,
                            QIcon::Mode mode,
                            QIcon::State state,
                            Theme::Icon themeIcon,
                            Theme::Color color,
                            const QSize &size)
{
    addIcon(iconId, area, {themeIcon, color, size, mode, state});
}

void DesignerIcons::addIcon(IconId iconId, Area area, Theme::Icon themeIcon, Theme::Color color, const QSize &size)
{
    addIcon(iconId, area, {themeIcon, color, size});
}

QList<Utils::StyleHelper::IconFontHelper> DesignerIcons::helperList(const IconId &iconId,
                                                                    const Area &area) const
{
    QList<Utils::StyleHelper::IconFontHelper> helperList;
    const IconMap &iconMap = d->icons.value(iconId).value(area);
    for (const ModeMap &modMap : iconMap) {
        for (const IconFontHelper &iconFontHelper : modMap)
            helperList.append(iconFontHelper);
    }
    return helperList;
}