summaryrefslogtreecommitdiff
path: root/src/libs/utils/qrcparser.cpp
blob: 2dfb9a19c2bd1b52494951d92d54ace988098c49 (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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** 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
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/

#include "qrcparser.h"

#include <utils/qtcassert.h>

#include <QCoreApplication>
#include <QDir>
#include <QDomDocument>
#include <QFile>
#include <QFileInfo>
#include <QLocale>
#include <QLoggingCategory>
#include <QMultiHash>
#include <QMutex>
#include <QMutexLocker>
#include <QSet>
#include <QStringList>

Q_LOGGING_CATEGORY(qrcParserLog, "qtc.qrcParser", QtWarningMsg)

namespace Utils {

namespace Internal {

class QrcParserPrivate
{
    Q_DECLARE_TR_FUNCTIONS(QmlJS::QrcParser)
public:
    typedef QMap<QString,QStringList> SMap;
    QrcParserPrivate(QrcParser *q);
    bool parseFile(const QString &path, const QString &contents);
    QString firstFileAtPath(const QString &path, const QLocale &locale) const;
    void collectFilesAtPath(const QString &path, QStringList *res, const QLocale *locale = nullptr) const;
    bool hasDirAtPath(const QString &path, const QLocale *locale = nullptr) const;
    void collectFilesInPath(const QString &path, QMap<QString,QStringList> *res, bool addDirs = false,
                            const QLocale *locale = nullptr) const;
    void collectResourceFilesForSourceFile(const QString &sourceFile, QStringList *res,
                                           const QLocale *locale = nullptr) const;

    QStringList errorMessages() const;
    QStringList languages() const;
private:
    static QString fixPrefix(const QString &prefix);
    const QStringList allUiLanguages(const QLocale *locale) const;

    SMap m_resources;
    SMap m_files;
    QStringList m_languages;
    QStringList m_errorMessages;
};

class QrcCachePrivate
{
    Q_DECLARE_TR_FUNCTIONS(QmlJS::QrcCachePrivate)
public:
    QrcCachePrivate(QrcCache *q);
    QrcParser::Ptr addPath(const QString &path, const QString &contents);
    void removePath(const QString &path);
    QrcParser::Ptr updatePath(const QString &path, const QString &contents);
    QrcParser::Ptr parsedPath(const QString &path);
    void clear();
private:
    QHash<QString, QPair<QrcParser::Ptr,int> > m_cache;
    QMutex m_mutex;
};
} // namespace Internal

/*!
    \class Utils::QrcParser
    \inmodule QtCreator
    \brief The QrcParser class parses one or more QRC files and keeps their
    content cached.

    A \l{The Qt Resource System}{Qt resource collection (QRC)} contains files
    read from the file system but organized in a possibly different way.
    To easily describe that with a simple structure, we use a map from QRC paths
    to the paths in the filesystem.
    By using a map, we can easily find all QRC paths that start with a given
    prefix, and thus loop on a QRC directory.

    QRC files also support languages, which are mapped to a prefix of the QRC
    path. For example, the French /image/bla.png (lang=fr) will have the path
    \c {fr/image/bla.png}. The empty language represents the default resource.
    Languages are looked up using the locale uiLanguages() property

    For a single QRC, a given path maps to a single file, but when one has
    multiple (platform-specific and mutually exclusive) QRC files, multiple
    files match, so QStringList are used.

    Especially, the \c collect* functions are thought of as low level interface.
 */

/*!
    \typedef QrcParser::Ptr
    Represents pointers.
 */

/*!
    \typedef QrcParser::ConstPtr
    Represents constant pointers.
*/

/*!
    Normalizes the \a path to a file in a QRC resource by dropping the \c qrc:/
    or \c : and any extra slashes in the beginning.
 */
QString QrcParser::normalizedQrcFilePath(const QString &path) {
    QString normPath = path;
    int endPrefix = 0;
    if (path.startsWith(QLatin1String("qrc:/")))
        endPrefix = 4;
    else if (path.startsWith(QLatin1String(":/")))
        endPrefix = 1;
    if (endPrefix < path.size() && path.at(endPrefix) == QLatin1Char('/'))
        while (endPrefix + 1 < path.size() && path.at(endPrefix+1) == QLatin1Char('/'))
            ++endPrefix;
    normPath = path.right(path.size()-endPrefix);
    if (!normPath.startsWith(QLatin1Char('/')))
        normPath.insert(0, QLatin1Char('/'));
    return normPath;
}

/*!
    Returns the path to a directory normalized to \a path in a QRC resource by
    dropping the \c qrc:/ or \c : and any extra slashes at the beginning, and
    by ensuring that the path ends with a slash
 */
QString QrcParser::normalizedQrcDirectoryPath(const QString &path) {
    QString normPath = normalizedQrcFilePath(path);
    if (!normPath.endsWith(QLatin1Char('/')))
        normPath.append(QLatin1Char('/'));
    return normPath;
}

/*!
    Returns the QRC directory path for \a file.
*/
QString QrcParser::qrcDirectoryPathForQrcFilePath(const QString &file)
{
    return file.left(file.lastIndexOf(QLatin1Char('/')));
}

QrcParser::QrcParser()
{
    d = new Internal::QrcParserPrivate(this);
}

/*!
    Destructs the QRC parser.
*/
QrcParser::~QrcParser()
{
    delete d;
}

/*!
    Returns the \a contents of the file at \a path.
*/
bool QrcParser::parseFile(const QString &path, const QString &contents)
{
    return d->parseFile(path, contents);
}

/*!
    Returns the file system path of the first (active) file at the given QRC
    \a path and \a locale.
 */
QString QrcParser::firstFileAtPath(const QString &path, const QLocale &locale) const
{
    return d->firstFileAtPath(path, locale);
}

/*!
    Adds the file system paths for the given QRC \a path to \a res.

    If \a locale is null, all possible files are added. Otherwise, just
    the first one that matches the locale is added.
 */
void QrcParser::collectFilesAtPath(const QString &path, QStringList *res, const QLocale *locale) const
{
    d->collectFilesAtPath(path, res, locale);
}

/*!
    Returns \c true if \a path is a non-empty directory and matches \a locale.

 */
bool QrcParser::hasDirAtPath(const QString &path, const QLocale *locale) const
{
    return d->hasDirAtPath(path, locale);
}

/*!
    Adds the directory contents of the given QRC \a path to \a res if \a addDirs
    is set to \c true.

    Adds the QRC filename to file system path associations contained in the
    given \a path to \a res. If addDirs() is \c true, directories are also
    added.

    If \a locale is null, all possible files are added. Otherwise, just the
    first file with a matching the locale is added.
 */
void QrcParser::collectFilesInPath(const QString &path, QMap<QString,QStringList> *res, bool addDirs,
                                   const QLocale *locale) const
{
    d->collectFilesInPath(path, res, addDirs, locale);
}

/*!
    Adds the resource files from the QRC file \a sourceFile to \a res.

    If \a locale is null, all possible files are added. Otherwise, just
    the first file with a matching the locale is added.
 */
void QrcParser::collectResourceFilesForSourceFile(const QString &sourceFile, QStringList *res,
                                                  const QLocale *locale) const
{
    d->collectResourceFilesForSourceFile(sourceFile, res, locale);
}

/*!
    Returns the errors found while parsing.
 */
QStringList QrcParser::errorMessages() const
{
    return d->errorMessages();
}

/*!
    Returns all languages used in this QRC.
 */
QStringList QrcParser::languages() const
{
    return d->languages();
}

/*!
    Indicates whether the QRC contents are valid.

    Returns an error if the QRC is empty.
 */
bool QrcParser::isValid() const
{
    return errorMessages().isEmpty();
}

/*!
    Returns the \a contents of the QRC file at \a path.
*/
QrcParser::Ptr QrcParser::parseQrcFile(const QString &path, const QString &contents)
{
    Ptr res(new QrcParser);
    if (!path.isEmpty())
        res->parseFile(path, contents);
    return res;
}

// ----------------

/*!
    \class Utils::QrcCache
    \inmodule QtCreator
    \brief The QrcCache class caches the contents of parsed QRC files.

    \sa Utils::QrcParser
*/

QrcCache::QrcCache()
{
    d = new Internal::QrcCachePrivate(this);
}

/*!
    \internal
*/
QrcCache::~QrcCache()
{
    delete d;
}

/*!
    Returns the \a contents of a file at \a path.
*/
QrcParser::ConstPtr QrcCache::addPath(const QString &path, const QString &contents)
{
    return d->addPath(path, contents);
}

/*!
    Removes \a path from the cache.
*/
void QrcCache::removePath(const QString &path)
{
    d->removePath(path);
}

/*!
    Returns updates to the \a contents of a file at \a path.
*/
QrcParser::ConstPtr QrcCache::updatePath(const QString &path, const QString &contents)
{
    return d->updatePath(path, contents);
}

/*!
    Returns the parsed \a path.
*/
QrcParser::ConstPtr QrcCache::parsedPath(const QString &path)
{
    return d->parsedPath(path);
}

/*!
    Clears the contents of the cache.
*/
void QrcCache::clear()
{
    d->clear();
}

// --------------------

namespace Internal {

QrcParserPrivate::QrcParserPrivate(QrcParser *)
{ }

bool QrcParserPrivate::parseFile(const QString &path, const QString &contents)
{
    QDomDocument doc;
    QDir baseDir(QFileInfo(path).path());

    if (contents.isEmpty()) {
        // Regular file
        QFile file(path);
        if (!file.open(QIODevice::ReadOnly)) {
            m_errorMessages.append(file.errorString());
            return false;
        }

        QString error_msg;
        int error_line, error_col;
        if (!doc.setContent(&file, &error_msg, &error_line, &error_col)) {
            m_errorMessages.append(tr("XML error on line %1, col %2: %3")
                                   .arg(error_line).arg(error_col).arg(error_msg));
            return false;
        }
    } else {
        // Virtual file from qmake evaluator
        QString error_msg;
        int error_line, error_col;
        if (!doc.setContent(contents, &error_msg, &error_line, &error_col)) {
            m_errorMessages.append(tr("XML error on line %1, col %2: %3")
                                   .arg(error_line).arg(error_col).arg(error_msg));
            return false;
        }
    }

    QDomElement root = doc.firstChildElement(QLatin1String("RCC"));
    if (root.isNull()) {
        m_errorMessages.append(tr("The <RCC> root element is missing."));
        return false;
    }

    QDomElement relt = root.firstChildElement(QLatin1String("qresource"));
    for (; !relt.isNull(); relt = relt.nextSiblingElement(QLatin1String("qresource"))) {

        QString prefix = fixPrefix(relt.attribute(QLatin1String("prefix")));
        const QString language = relt.attribute(QLatin1String("lang"));
        if (!m_languages.contains(language))
            m_languages.append(language);

        QDomElement felt = relt.firstChildElement(QLatin1String("file"));
        for (; !felt.isNull(); felt = felt.nextSiblingElement(QLatin1String("file"))) {
            const QString fileName = felt.text();
            const QString alias = felt.attribute(QLatin1String("alias"));
            QString filePath = baseDir.absoluteFilePath(fileName);
            QString accessPath;
            if (!alias.isEmpty())
                accessPath = language + prefix + alias;
            else
                accessPath = language + prefix + fileName;
            QStringList &resources = m_resources[accessPath];
            if (!resources.contains(filePath))
                resources.append(filePath);
            QStringList &files = m_files[filePath];
            if (!files.contains(accessPath))
                files.append(accessPath);
        }
    }
    return true;
}

// path is assumed to be a normalized absolute path
QString QrcParserPrivate::firstFileAtPath(const QString &path, const QLocale &locale) const
{
    QTC_CHECK(path.startsWith(QLatin1Char('/')));
    for (const QString &language : allUiLanguages(&locale)) {
        if (m_languages.contains(language)) {
            SMap::const_iterator res = m_resources.find(language + path);
            if (res != m_resources.end())
                return res.value().at(0);
        }
    }
    return QString();
}

void QrcParserPrivate::collectFilesAtPath(const QString &path, QStringList *files,
                                          const QLocale *locale) const
{
    QTC_CHECK(path.startsWith(QLatin1Char('/')));
    for (const QString &language : allUiLanguages(locale)) {
        if (m_languages.contains(language)) {
            SMap::const_iterator res = m_resources.find(language + path);
            if (res != m_resources.end())
                (*files) << res.value();
        }
    }
}

// path is expected to be normalized and start and end with a slash
bool QrcParserPrivate::hasDirAtPath(const QString &path, const QLocale *locale) const
{
    QTC_CHECK(path.startsWith(QLatin1Char('/')));
    QTC_CHECK(path.endsWith(QLatin1Char('/')));
    for (const QString &language : allUiLanguages(locale)) {
        if (m_languages.contains(language)) {
            QString key = language + path;
            SMap::const_iterator res = m_resources.lowerBound(key);
            if (res != m_resources.end() && res.key().startsWith(key))
                return true;
        }
    }
    return false;
}

void QrcParserPrivate::collectFilesInPath(const QString &path, QMap<QString,QStringList> *contents,
                                          bool addDirs, const QLocale *locale) const
{
    QTC_CHECK(path.startsWith(QLatin1Char('/')));
    QTC_CHECK(path.endsWith(QLatin1Char('/')));
    SMap::const_iterator end = m_resources.end();
    for (const QString &language : allUiLanguages(locale)) {
        QString key = language + path;
        SMap::const_iterator res = m_resources.lowerBound(key);
        while (res != end && res.key().startsWith(key)) {
            const QString &actualKey = res.key();
            int endDir = actualKey.indexOf(QLatin1Char('/'), key.size());
            if (endDir == -1) {
                QString fileName = res.key().right(res.key().size()-key.size());
                QStringList &els = (*contents)[fileName];
                for (const QString &val : res.value())
                    if (!els.contains(val))
                        els << val;
                ++res;
            } else {
                QString dirName = res.key().mid(key.size(), endDir - key.size() + 1);
                if (addDirs)
                    contents->insert(dirName, QStringList());
                QString key2 = key + dirName;
                do {
                    ++res;
                } while (res != end && res.key().startsWith(key2));
            }
        }
    }
}

void QrcParserPrivate::collectResourceFilesForSourceFile(const QString &sourceFile,
                                                         QStringList *results,
                                                         const QLocale *locale) const
{
    // TODO: use FileName from fileutils for file paths

    const QStringList langs = allUiLanguages(locale);
    SMap::const_iterator file = m_files.find(sourceFile);
    if (file == m_files.end())
        return;
    for (const QString &resource : file.value()) {
        for (const QString &language : langs) {
            if (resource.startsWith(language) && !results->contains(resource))
                results->append(resource);
        }
    }
}

QStringList QrcParserPrivate::errorMessages() const
{
    return m_errorMessages;
}

QStringList QrcParserPrivate::languages() const
{
    return m_languages;
}

QString QrcParserPrivate::fixPrefix(const QString &prefix)
{
    const QChar slash = QLatin1Char('/');
    QString result = QString(slash);
    for (int i = 0; i < prefix.size(); ++i) {
        const QChar c = prefix.at(i);
        if (c == slash && result.at(result.size() - 1) == slash)
            continue;
        result.append(c);
    }

    if (!result.endsWith(slash))
        result.append(slash);

    return result;
}

const QStringList QrcParserPrivate::allUiLanguages(const QLocale *locale) const
{
    if (!locale)
        return languages();
    QStringList langs = locale->uiLanguages();
    foreach (const QString &language, langs) { // qt4 support
        if (language.contains(QLatin1Char('_')) || language.contains(QLatin1Char('-'))) {
            QStringList splits = QString(language).replace(QLatin1Char('_'), QLatin1Char('-'))
                    .split(QLatin1Char('-'));
            if (splits.size() > 1 && !langs.contains(splits.at(0)))
                langs.append(splits.at(0));
        }
    }
    if (!langs.contains(QString()))
        langs.append(QString());
    return langs;
}

// ----------------

QrcCachePrivate::QrcCachePrivate(QrcCache *)
{ }

QrcParser::Ptr QrcCachePrivate::addPath(const QString &path, const QString &contents)
{
    QPair<QrcParser::Ptr,int> currentValue;
    {
        QMutexLocker l(&m_mutex);
        currentValue = m_cache.value(path, {QrcParser::Ptr(nullptr), 0});
        currentValue.second += 1;
        if (currentValue.second > 1) {
            m_cache.insert(path, currentValue);
            return currentValue.first;
        }
    }
    QrcParser::Ptr newParser = QrcParser::parseQrcFile(path, contents);
    if (!newParser->isValid())
        qCWarning(qrcParserLog) << "adding invalid qrc " << path << " to the cache:" << newParser->errorMessages();
    {
        QMutexLocker l(&m_mutex);
        QPair<QrcParser::Ptr,int> currentValue = m_cache.value(path, {QrcParser::Ptr(nullptr), 0});
        if (currentValue.first.isNull())
            currentValue.first = newParser;
        currentValue.second += 1;
        m_cache.insert(path, currentValue);
        return currentValue.first;
    }
}

void QrcCachePrivate::removePath(const QString &path)
{
    QPair<QrcParser::Ptr,int> currentValue;
    {
        QMutexLocker l(&m_mutex);
        currentValue = m_cache.value(path, {QrcParser::Ptr(nullptr), 0});
        if (currentValue.second == 1) {
            m_cache.remove(path);
        } else if (currentValue.second > 1) {
            currentValue.second -= 1;
            m_cache.insert(path, currentValue);
        } else {
            QTC_CHECK(!m_cache.contains(path));
        }
    }
}

QrcParser::Ptr QrcCachePrivate::updatePath(const QString &path, const QString &contents)
{
    QrcParser::Ptr newParser = QrcParser::parseQrcFile(path, contents);
    {
        QMutexLocker l(&m_mutex);
        QPair<QrcParser::Ptr,int> currentValue = m_cache.value(path, {QrcParser::Ptr(nullptr), 0});
        currentValue.first = newParser;
        if (currentValue.second == 0)
            currentValue.second = 1; // add qrc files that are not in the resources of a project
        m_cache.insert(path, currentValue);
        return currentValue.first;
    }
}

QrcParser::Ptr QrcCachePrivate::parsedPath(const QString &path)
{
    QMutexLocker l(&m_mutex);
    QPair<QrcParser::Ptr,int> currentValue = m_cache.value(path, {QrcParser::Ptr(nullptr), 0});
    return currentValue.first;
}

void QrcCachePrivate::clear()
{
    QMutexLocker l(&m_mutex);
    m_cache.clear();
}

} // namespace Internal
} // namespace QmlJS