mimedatabase.cpp 38.4 KB
Newer Older
1
/**************************************************************************
con's avatar
con committed
2 3 4
**
** This file is part of Qt Creator
**
hjk's avatar
hjk committed
5
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
con's avatar
con committed
6
**
7
** Contact: Nokia Corporation (qt-info@nokia.com)
con's avatar
con committed
8
**
9
** Commercial Usage
10
**
11 12 13 14
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
15
**
16
** GNU Lesser General Public License Usage
17
**
18 19 20 21 22 23
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24
**
25
** If you are unsure which license is appropriate for your use, please
hjk's avatar
hjk committed
26
** contact the sales department at http://qt.nokia.com/contact.
con's avatar
con committed
27
**
28
**************************************************************************/
hjk's avatar
hjk committed
29

con's avatar
con committed
30 31
#include "mimedatabase.h"

hjk's avatar
hjk committed
32 33 34 35 36
#include <utils/qtcassert.h>

#include <QtCore/QByteArray>
#include <QtCore/QCoreApplication>
#include <QtCore/QDebug>
con's avatar
con committed
37
#include <QtCore/QFile>
hjk's avatar
hjk committed
38 39
#include <QtCore/QFileInfo>
#include <QtCore/QLocale>
con's avatar
con committed
40 41 42 43 44
#include <QtCore/QMap>
#include <QtCore/QMultiHash>
#include <QtCore/QRegExp>
#include <QtCore/QSharedData>
#include <QtCore/QSharedPointer>
hjk's avatar
hjk committed
45
#include <QtCore/QStringList>
con's avatar
con committed
46
#include <QtCore/QTextStream>
47
#include <QtCore/QMutexLocker>
hjk's avatar
hjk committed
48

con's avatar
con committed
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
#include <QtXml/QXmlStreamReader>

enum { debugMimeDB = 0 };

// XML tags in mime files
static const char *mimeInfoTagC = "mime-info";
static const char *mimeTypeTagC = "mime-type";
static const char *mimeTypeAttributeC = "type";
static const char *subClassTagC = "sub-class-of";
static const char *commentTagC = "comment";
static const char *globTagC = "glob";
static const char *aliasTagC = "alias";
static const char *patternAttributeC = "pattern";
static const char *localeAttributeC = "xml:lang";

static const char *magicTagC = "magic";
static const char *priorityAttributeC = "priority";
static const char *matchTagC = "match";
static const char *matchValueAttributeC = "value";
static const char *matchTypeAttributeC = "type";
static const char *matchStringTypeValueC = "string";
static const char *matchOffsetAttributeC = "offset";

// Types
static const char *textTypeC = "text/plain";
static const char *binaryTypeC = "application/octet-stream";

// UTF16 byte order marks
static const char bigEndianByteOrderMarkC[] = "\xFE\xFF";
static const char littleEndianByteOrderMarkC[] = "\xFF\xFE";

// Fallback priorities, must be low.
enum { BinaryMatchPriority = 1, TextMatchPriority = 2};

/* Parse sth like (<mime-info> being optional):
 *\code
?xml version="1.0" encoding="UTF-8"?>
<mime-info xmlns="http://www.freedesktop.org/standards/shared-mime-info">
  <!-- Mime types must match the desktop file associations -->
  <mime-type type="application/vnd.nokia.qt.qmakeprofile">
89
    <comment xml:lang="en">Qt qmake Profile</comment>
con's avatar
con committed
90 91 92 93 94 95 96
    <glob pattern="*.pro"/>
  </mime-type>
</mime-info>
 *\endcode
*/

namespace Core {
97 98 99

typedef QSharedPointer<MagicRuleMatcher> MagicRuleMatcherPtr;

con's avatar
con committed
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
namespace Internal {

// FileMatchContext: Passed on to the mimetypes from the database
// when looking for a file match. It exists to enable reading the file
// contents "on demand" (as opposed to each mime type trying to open
// and read while checking).

class FileMatchContext {
    Q_DISABLE_COPY(FileMatchContext);
public:
    // Max data to be read from a file
    enum { MaxData = 2048 };

    explicit FileMatchContext(const QFileInfo &fi);

    inline QString fileName() const { return m_fileName; }
    // Return (cached) first MaxData bytes of file
    QByteArray data();

private:
    enum State {
        // File cannot be read/does not exist
        NoDataAvailable,
        // Not read yet
        DataNotRead,
        // Available
        DataRead };
    const QFileInfo m_fileInfo;
    const QString m_fileName;
    State m_state;
    QByteArray m_data;
};

FileMatchContext::FileMatchContext(const QFileInfo &fi) :
    m_fileInfo(fi),
    m_fileName(fi.fileName()),
    m_state(fi.isFile() && fi.isReadable() && fi.size() > 0 ? DataNotRead : NoDataAvailable)
{
}

QByteArray FileMatchContext::data()
{
    // Do we need to read?
    if (m_state == DataNotRead) {
        const QString fullName = m_fileInfo.absoluteFilePath();
        QFile file(fullName);
        if (file.open(QIODevice::ReadOnly)) {
            m_data = file.read(MaxData);
            m_state = DataRead;
        } else {
            qWarning("%s failed to open %s: %s\n", Q_FUNC_INFO, fullName.toUtf8().constData(), file.errorString().toUtf8().constData());
            m_state = NoDataAvailable;
        }
    }
    return m_data;
}

// The binary fallback matcher for "application/octet-stream".
class BinaryMatcher : public IMagicMatcher {
    Q_DISABLE_COPY(BinaryMatcher);
public:
    BinaryMatcher() {}
    virtual bool matches(const QByteArray & /*data*/) const { return true; }
    virtual int priority() const  { return BinaryMatchPriority; }
};

// A heuristic text file matcher: If the data do not contain any character
// below tab (9), detect as text.
class HeuristicTextMagicMatcher : public IMagicMatcher {
    Q_DISABLE_COPY(HeuristicTextMagicMatcher);
public:
    HeuristicTextMagicMatcher() {}
    virtual bool matches(const QByteArray &data) const;
    virtual int priority() const  { return TextMatchPriority; }

    static bool isTextFile(const QByteArray &data);
};

bool HeuristicTextMagicMatcher::isTextFile(const QByteArray &data)
{
    const int size = data.size();
    for (int i = 0; i < size; i++) {
        const char c = data.at(i);
        if (c >= 0x01 && c < 0x09) // Sure-fire binary
            return false;
        if (c == 0)             // Check for UTF16
            return data.startsWith(bigEndianByteOrderMarkC) || data.startsWith(littleEndianByteOrderMarkC);
    }
    return true;
}

bool HeuristicTextMagicMatcher::matches(const QByteArray &data) const
{
    const bool rc = isTextFile(data);
    if (debugMimeDB)
        qDebug() << Q_FUNC_INFO << " on " << data.size() << " returns " << rc;
    return rc;
}

} // namespace Internal

// MagicRule
MagicRule::MagicRule(const QByteArray &pattern, int startPos, int endPos) :
    m_pattern(pattern),
    m_startPos(startPos),
    m_endPos(endPos)
{
}

bool MagicRule::matches(const QByteArray &data) const
{
    // Quick check
    const int dataSize = data.size();
    if ((m_startPos + m_pattern.size()) >= dataSize)
        return false;
    // Most common: some string at position 0:
    if (m_startPos == 0 && m_startPos == m_endPos)
        return data.startsWith(m_pattern);
    // Range
    const int index = data.indexOf(m_pattern, m_startPos);
220 221 222 223
    const bool rc = index != -1 && index < m_endPos;
    if (debugMimeDB)
        qDebug() << "Checking " << m_pattern << m_startPos << m_endPos << " returns " << rc;
    return rc;
con's avatar
con committed
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
}

MagicRule *MagicRule::createStringRule(const QString &c, int startPos, int endPos)
{
    return new MagicRule(c.toUtf8(), startPos, endPos);
}

// List matcher
MagicRuleMatcher::MagicRuleMatcher() :
     m_priority(65535)
{
}

void MagicRuleMatcher::add(const MagicRuleSharedPointer &rule)
{
    m_list.push_back(rule);
}

bool MagicRuleMatcher::matches(const QByteArray &data) const
{
    const MagicRuleList::const_iterator cend = m_list.constEnd();
    for (MagicRuleList::const_iterator it = m_list.constBegin(); it != cend; ++it)
        if ( (*it)->matches(data))
            return true;
    return false;
}

int MagicRuleMatcher::priority() const
{
    return m_priority;
}

void MagicRuleMatcher::setPriority(int p)
{
    m_priority = p;
}

// ---------- MimeTypeData
class MimeTypeData : public QSharedData {
public:
    typedef QHash<QString,QString> LocaleHash;
    void clear();
    void debug(QTextStream &str, int indent = 0) const;

    QString type;
    QString comment;

    LocaleHash localeComments;
    QStringList aliases;
    QList<QRegExp> globPatterns;
    QStringList subClassesOf;
    QString preferredSuffix;
    QStringList suffixes;

    typedef QSharedPointer<IMagicMatcher> IMagicMatcherSharedPointer;
    typedef QList<IMagicMatcherSharedPointer> IMagicMatcherList;
    IMagicMatcherList magicMatchers;
};

void MimeTypeData::clear()
{
    type.clear();
    comment.clear();
    aliases.clear();
    globPatterns.clear();
    subClassesOf.clear();
    preferredSuffix.clear();
    suffixes.clear();
    magicMatchers.clear();
}

void MimeTypeData::debug(QTextStream &str, int indent) const
{
    const QString indentS = QString(indent, QLatin1Char(' '));
    const QString comma = QString(1, QLatin1Char(','));
    str << indentS << "Type: " << type;
    if (!aliases.empty())
        str << " Aliases: " << aliases.join(comma);
    str << ", magic: " << magicMatchers.size() << '\n';
    str << indentS << "Comment: " << comment << '\n';
    if (!subClassesOf.empty())
        str << indentS << "SubClassesOf: " << subClassesOf.join(comma) << '\n';
    if (!globPatterns.empty()) {
        str << indentS << "Glob: ";
hjk's avatar
hjk committed
308
        foreach (const QRegExp &r, globPatterns)
con's avatar
con committed
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
            str << r.pattern() << ' ';
        str << '\n';
        if (!suffixes.empty()) {
            str <<  indentS << "Suffixes: " << suffixes.join(comma)
                << " preferred: " << preferredSuffix << '\n';
        }
    }
    str << '\n';
}

// ---------------- MimeType
MimeType::MimeType() :
    m_d(new MimeTypeData)
{
}

MimeType::MimeType(const MimeType &rhs) :
    m_d(rhs.m_d)
{
}

MimeType &MimeType::operator=(const MimeType &rhs)
{
    if (this != &rhs)
        m_d = rhs.m_d;
    return *this;
}

MimeType::MimeType(const MimeTypeData &d) :
    m_d(new MimeTypeData(d))
{
}

MimeType::~MimeType()
{
}

void MimeType::clear()
{
    m_d->clear();
}

bool MimeType::isNull() const
{
    return m_d->type.isEmpty();
}

MimeType::operator bool() const
{
    return !isNull();
}

bool MimeType::isTopLevel() const
{
    return m_d->subClassesOf.empty();
}

QString MimeType::type() const
{
    return m_d->type;
}

void MimeType::setType(const QString &type)
{
    m_d->type = type;
}

QString MimeType::comment() const
{
    return m_d->comment;
}

void MimeType::setComment(const QString &comment)
{
    m_d->comment = comment;
}

// Return "en", "de", etc. derived from "en_US", de_DE".
static inline QString systemLanguage()
{
    QString name = QLocale::system().name();
    const int underScorePos = name.indexOf(QLatin1Char('_'));
    if (underScorePos != -1)
        name.truncate(underScorePos);
    return name;
}

QString MimeType::localeComment(const QString &localeArg) const
{
    const QString locale = localeArg.isEmpty() ? systemLanguage() : localeArg;
    const MimeTypeData::LocaleHash::const_iterator it = m_d->localeComments.constFind(locale);
    if (it == m_d->localeComments.constEnd())
        return m_d->comment;
    return it.value();
}

void MimeType::setLocaleComment(const QString &locale, const QString &comment)
{
     m_d->localeComments[locale] = comment;
}

QStringList MimeType::aliases() const
{
    return m_d->aliases;
}

void MimeType::setAliases(const QStringList &a)
{
     m_d->aliases = a;
}

QList<QRegExp> MimeType::globPatterns() const
{
    return m_d->globPatterns;
}

void MimeType::setGlobPatterns(const QList<QRegExp> &g)
{
    m_d->globPatterns = g;
}

QStringList MimeType::subClassesOf() const
{
    return m_d->subClassesOf;
}

void MimeType::setSubClassesOf(const QStringList &s)
{
    m_d->subClassesOf = s;
}

QString MimeType::preferredSuffix() const
{
    return m_d->preferredSuffix;
}

bool MimeType::setPreferredSuffix(const QString &s)
{
    if (!m_d->suffixes.contains(s)) {
        qWarning("%s: Attempt to set preferred suffix to '%s', which is not in the list of suffixes: %s.",
                 m_d->type.toUtf8().constData(),
                 s.toUtf8().constData(),
                 m_d->suffixes.join(QLatin1String(",")).toUtf8().constData());
        return false;
    }
    m_d->preferredSuffix = s;
    return true;
}

458
QString MimeType::formatFilterString(const QString &description, const QList<QRegExp> &globs)
con's avatar
con 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 486 487 488 489 490 491 492 493
{
    QString rc;
    if (globs.empty())  // Binary files
        return rc;
    {
        QTextStream str(&rc);
        str << description;
        if (!globs.empty()) {
            str << " (";
            const int size = globs.size();
            for (int i = 0; i < size; i++) {
                if (i)
                    str << ' ';
                str << globs.at(i).pattern();
            }
            str << ')';
        }
    }
    return rc;
}

QString MimeType::filterString() const
{
    // @todo: Use localeComment() once creator is shipped with translations
    return formatFilterString(comment(), m_d->globPatterns);
}

bool MimeType::matchesType(const QString &type) const
{
    return m_d->type == type || m_d->aliases.contains(type);
}

unsigned MimeType::matchesFile(const QFileInfo &file) const
{
    Internal::FileMatchContext context(file);
494 495 496
    if (const unsigned suffixPriority = matchesFileBySuffix(context))
        return suffixPriority;
    return matchesFileByContent(context);
con's avatar
con committed
497 498
}

499
unsigned MimeType::matchesFileBySuffix(Internal::FileMatchContext &c) const
con's avatar
con committed
500 501
{
    // check globs
502
    foreach (const QRegExp &pattern, m_d->globPatterns) {
503
        if (pattern.exactMatch(c.fileName()))
con's avatar
con committed
504
            return GlobMatchPriority;
505
    }
506 507
    return 0;
}
508

509 510
unsigned MimeType::matchesFileByContent(Internal::FileMatchContext &c) const
{
con's avatar
con committed
511
    // Nope, try magic matchers on context data
512
    if (m_d->magicMatchers.isEmpty())
con's avatar
con committed
513
        return 0;
514

con's avatar
con committed
515 516
    const QByteArray data = c.data();
    if (!data.isEmpty()) {
517
        foreach (const MimeTypeData::IMagicMatcherSharedPointer &matcher, m_d->magicMatchers) {
518 519 520
            if (matcher->matches(data))
                return matcher->priority();
        }
con's avatar
con committed
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
    }
    return 0;
}

QStringList MimeType::suffixes() const
{
    return m_d->suffixes;
}

void MimeType::setSuffixes(const QStringList &s)
{
    m_d->suffixes = s;
}

void MimeType::addMagicMatcher(const QSharedPointer<IMagicMatcher> &matcher)
{
    m_d->magicMatchers.push_back(matcher);
}

QDebug operator<<(QDebug d, const MimeType &mt)
{
    QString s;
    {
        QTextStream str(&s);
        mt.m_d->debug(str);
    }
    d << s;
    return d;
}

namespace Internal {

//  MimeDatabase helpers: Generic parser for a sequence of <mime-type>.
//  Calls abstract handler function process for MimeType it finds.
class BaseMimeTypeParser {
    Q_DISABLE_COPY(BaseMimeTypeParser);
public:
    BaseMimeTypeParser();
    virtual ~BaseMimeTypeParser() {}

    bool parse(QIODevice *dev, const QString &fileName, QString *errorMessage);

private:
    // Overwrite to process the sequence of parsed data
    virtual bool process(const MimeType &t, QString *errorMessage) = 0;

    void addGlobPattern(const QString &pattern, MimeTypeData *d) const;

    enum ParseStage { ParseBeginning,
                  ParseMimeInfo,
                  ParseMimeType,
                  ParseComment,
                  ParseGlobPattern,
                  ParseSubClass,
                  ParseAlias,
                  ParseMagic,
                  ParseMagicMatchRule,
                  ParseOtherMimeTypeSubTag,
                  ParseError };

    static ParseStage nextStage(ParseStage currentStage, const QStringRef &startElement);

    const QRegExp m_suffixPattern;
};

BaseMimeTypeParser:: BaseMimeTypeParser() :
    // RE to match a suffix glob pattern: "*.ext" (and not sth like "Makefile" or
    // "*.log[1-9]"
589
    m_suffixPattern(QLatin1String("^\\*\\.[\\w+]+$"))
con's avatar
con committed
590
{
hjk's avatar
hjk committed
591
    QTC_ASSERT(m_suffixPattern.isValid(), /**/);
con's avatar
con committed
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 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
}

void BaseMimeTypeParser::addGlobPattern(const QString &pattern, MimeTypeData *d) const
{
    if (pattern.isEmpty())
        return;
    // Collect patterns as a QRegExp list and filter out the plain
    // suffix ones for our suffix list. Use first one as preferred
    const QRegExp wildCard(pattern, Qt::CaseSensitive, QRegExp::Wildcard);
    if (!wildCard.isValid()) {
        qWarning("%s: Invalid wildcard '%s'.",
                 Q_FUNC_INFO, pattern.toUtf8().constData());
        return;
    }

    d->globPatterns.push_back(wildCard);
    if (m_suffixPattern.exactMatch(pattern)) {
        const QString suffix = pattern.right(pattern.size() - 2);
        d->suffixes.push_back(suffix);
        if (d->preferredSuffix.isEmpty())
            d->preferredSuffix = suffix;
    }
}

BaseMimeTypeParser::ParseStage BaseMimeTypeParser::nextStage(ParseStage currentStage, const QStringRef &startElement)
{
    switch (currentStage) {
    case ParseBeginning:
        if (startElement == QLatin1String(mimeInfoTagC))
            return ParseMimeInfo;
        if (startElement == QLatin1String(mimeTypeTagC))
            return ParseMimeType;
        return ParseError;
    case ParseMimeInfo:
        return startElement == QLatin1String(mimeTypeTagC) ? ParseMimeType : ParseError;
    case ParseMimeType:
    case ParseComment:
    case ParseGlobPattern:
    case ParseSubClass:
    case ParseAlias:
    case ParseOtherMimeTypeSubTag:
    case ParseMagicMatchRule:
        if (startElement == QLatin1String(mimeTypeTagC)) // Sequence of <mime-type>
            return ParseMimeType;
        if (startElement == QLatin1String(commentTagC ))
            return ParseComment;
        if (startElement == QLatin1String(globTagC))
            return ParseGlobPattern;
        if (startElement == QLatin1String(subClassTagC))
            return ParseSubClass;
        if (startElement == QLatin1String(aliasTagC))
            return ParseAlias;
        if (startElement == QLatin1String(magicTagC))
            return ParseMagic;
        return ParseOtherMimeTypeSubTag;
    case ParseMagic:
        if (startElement == QLatin1String(matchTagC))
            return ParseMagicMatchRule;
        break;
    case ParseError:
        break;
    }
    return ParseError;
}

// Parse int number from an (attribute) string)
static bool parseNumber(const QString &n, int *target, QString *errorMessage)
{
    bool ok;
    *target = n.toInt(&ok);
    if (!ok) {
663
        *errorMessage = QString::fromLatin1("Not a number '%1'.").arg(n);
con's avatar
con committed
664 665 666 667 668 669 670 671 672
        return false;
    }
    return true;
}

// Evaluate a magic match rule like
//  <match value="must be converted with BinHex" type="string" offset="11"/>
//  <match value="0x9501" type="big16" offset="0:64"/>
static bool addMagicMatchRule(const QXmlStreamAttributes &atts,
673
                              const MagicRuleMatcherPtr  &ruleMatcher,
con's avatar
con committed
674 675 676 677 678 679 680 681 682
                              QString *errorMessage)
{
    const QString type = atts.value(QLatin1String(matchTypeAttributeC)).toString();
    if (type != QLatin1String(matchStringTypeValueC)) {
        qWarning("%s: match type %s is not supported.", Q_FUNC_INFO, type.toUtf8().constData());
        return true;
    }
    const QString value = atts.value(QLatin1String(matchValueAttributeC)).toString();
    if (value.isEmpty()) {
683
        *errorMessage = QString::fromLatin1("Empty match value detected.");
con's avatar
con committed
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
        return false;
    }
    // Parse for offset as "1" or "1:10"
    int startPos, endPos;
    const QString offsetS = atts.value(QLatin1String(matchOffsetAttributeC)).toString();
    const int colonIndex = offsetS.indexOf(QLatin1Char(':'));
    const QString startPosS = colonIndex == -1 ? offsetS : offsetS.mid(0, colonIndex);
    const QString endPosS   = colonIndex == -1 ? offsetS : offsetS.mid(colonIndex + 1);
    if (!parseNumber(startPosS, &startPos, errorMessage) || !parseNumber(endPosS, &endPos, errorMessage))
        return false;
    if (debugMimeDB)
        qDebug() << Q_FUNC_INFO << value << startPos << endPos;
    ruleMatcher->add(QSharedPointer<MagicRule>(MagicRule::createStringRule(value, startPos, endPos)));
    return true;
}

bool BaseMimeTypeParser::parse(QIODevice *dev, const QString &fileName, QString *errorMessage)
{
    MimeTypeData data;
703
    MagicRuleMatcherPtr ruleMatcher;
con's avatar
con committed
704 705 706 707 708 709 710 711 712 713
    QXmlStreamReader reader(dev);
    ParseStage ps = ParseBeginning;
    while (!reader.atEnd()) {
        switch (reader.readNext()) {
        case QXmlStreamReader::StartElement:
            ps = nextStage(ps, reader.name());
            switch (ps) {
            case ParseMimeType: { // start parsing a type
                const QString type = reader.attributes().value(QLatin1String(mimeTypeAttributeC)).toString();
                if (type.isEmpty()) {
714
                    reader.raiseError(QString::fromLatin1("Missing 'type'-attribute"));
con's avatar
con committed
715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731
                } else {
                    data.type = type;
                }
            }
                break;
            case ParseGlobPattern:
                addGlobPattern(reader.attributes().value(QLatin1String(patternAttributeC)).toString(), &data);
                break;
            case ParseSubClass: {
                const QString inheritsFrom = reader.attributes().value(QLatin1String(mimeTypeAttributeC)).toString();
                if (!inheritsFrom.isEmpty())
                    data.subClassesOf.push_back(inheritsFrom);
            }
                break;
            case ParseComment: {
                // comments have locale attributes. We want the default, English one
                QString locale = reader.attributes().value(QLatin1String(localeAttributeC)).toString();
732
                const QString comment = QCoreApplication::translate("MimeType", reader.readElementText().toAscii());
con's avatar
con committed
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
                if (locale.isEmpty()) {
                    data.comment = comment;
                } else {
                    data.localeComments.insert(locale, comment);
                }
            }
                break;
            case ParseAlias: {
                const QString alias = reader.attributes().value(QLatin1String(mimeTypeAttributeC)).toString();
                if (!alias.isEmpty())
                    data.aliases.push_back(alias);
            }
                break;
            case ParseMagic: {
                int priority = 0;
                const QString priorityS = reader.attributes().value(QLatin1String(priorityAttributeC)).toString();
                if (!priorityS.isEmpty()) {
                    if (!parseNumber(priorityS, &priority, errorMessage))
                        return false;

                }
754
                ruleMatcher = MagicRuleMatcherPtr(new MagicRuleMatcher);
con's avatar
con committed
755 756 757 758
                ruleMatcher->setPriority(priority);
            }
                break;
            case ParseMagicMatchRule:
759
                QTC_ASSERT(!ruleMatcher.isNull(), return false)
con's avatar
con committed
760 761 762 763
                if (!addMagicMatchRule(reader.attributes(), ruleMatcher, errorMessage))
                    return false;
                break;
            case ParseError:
764
                reader.raiseError(QString::fromLatin1("Unexpected element <%1>").arg(reader.name().toString()));
con's avatar
con committed
765 766 767 768 769 770 771 772 773 774 775 776 777
                break;
            default:
                break;
            } // switch nextStage
            break;
        // continue switch QXmlStreamReader::Token...
        case QXmlStreamReader::EndElement: // Finished element
            if (reader.name() == QLatin1String(mimeTypeTagC)) {
                if (!process(MimeType(data), errorMessage))
                    return false;
                data.clear();
            } else {
                // Finished a match sequence
778 779 780 781
                if (reader.name() == QLatin1String(magicTagC)) {
                    QTC_ASSERT(!ruleMatcher.isNull(), return false)
                    data.magicMatchers.push_back(ruleMatcher);
                    ruleMatcher = MagicRuleMatcherPtr();
con's avatar
con committed
782 783 784 785 786 787 788 789 790 791
                }
            }
            break;

        default:
            break;
        } // switch reader.readNext()
    }

    if (reader.hasError()) {
792
        *errorMessage = QString::fromLatin1("An error has been encountered at line %1 of %2: %3:").arg(reader.lineNumber()).arg(fileName, reader.errorString());
con's avatar
con committed
793 794 795 796 797 798 799 800 801 802 803
        return false;
    }
    return true;
}

} // namespace Internal

// MimeMapEntry: Entry of a type map, consisting of type and level.

enum { Dangling = 32767 };

hjk's avatar
hjk committed
804 805
struct MimeMapEntry
{
con's avatar
con committed
806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
    explicit MimeMapEntry(const MimeType &t = MimeType(), int aLevel = Dangling);
    MimeType type;
    int level; // hierachy level
};

MimeMapEntry::MimeMapEntry(const MimeType &t, int aLevel) :
    type(t),
    level(aLevel)
{
}

/* MimeDatabasePrivate: Requirements for storage:
 * - Must be robust in case of incomplete hierachies, dangling entries
 * - Plugins will not load and register their mime types in order
 *   of inheritance.
 * - Multiple inheritance (several subClassesOf) can occur
 * - Provide quick lookup by name
 * - Provide quick lookup by file type.
Tobias Hunger's avatar
Tobias Hunger committed
824
 * This basically rules out some pointer-based tree, so the structure chosen
con's avatar
con committed
825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
 * is:
 * - An alias map <QString->QString> for mapping aliases to types
 * - A Map <QString-MimeMapEntry> for the types (MimeMapEntry being a pair of
 *   MimeType and (hierarchy) level.
 * - A map  <QString->QString> representing parent->child relations (enabling
 *   recursing over children)
 * Using strings avoids dangling pointers.
 * The hierarchy level is used for mapping by file types. When findByFile()
 * is first called after addMimeType() it recurses over the hierarchy and sets
 * the hierarchy level of the entries accordingly (0 toplevel, 1 first
 * order...). It then does several passes over the type map, checking the
 * globs for maxLevel, maxLevel-1....until it finds a match (idea being to
 * to check the most specific types first). Starting a recursion from the
 * leaves is not suitable since it will hit parent nodes several times. */

hjk's avatar
hjk committed
840 841
class MimeDatabasePrivate
{
con's avatar
con committed
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 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906
    Q_DISABLE_COPY(MimeDatabasePrivate)
public:
    MimeDatabasePrivate();

    bool addMimeTypes(const QString &fileName, QString *errorMessage);
    bool addMimeTypes(QIODevice *device, QString *errorMessage);
    bool addMimeType(MimeType mt);

    // Returns a mime type or Null one if none found
    MimeType findByType(const QString &type) const;
    // Returns a mime type or Null one if none found
    MimeType findByFile(const QFileInfo &f) const;

    bool setPreferredSuffix(const QString &typeOrAlias, const QString &suffix);

    // Return all known suffixes
    QStringList suffixes() const;
    QStringList filterStrings() const;

    void debug(QTextStream &str) const;

private:
    typedef QHash<QString, MimeMapEntry> TypeMimeTypeMap;
    typedef QHash<QString, QString> AliasMap;
    typedef QMultiHash<QString, QString> ParentChildrenMap;

    bool addMimeTypes(QIODevice *device, const QString &fileName, QString *errorMessage);
    inline const QString &resolveAlias(const QString &name) const;
    MimeType findByFile(const QFileInfo &f, unsigned *priority) const;
    void determineLevels();
    void raiseLevelRecursion(MimeMapEntry &e, int level);

    TypeMimeTypeMap m_typeMimeTypeMap;
    AliasMap m_aliasMap;
    ParentChildrenMap m_parentChildrenMap;
    int m_maxLevel;
};

MimeDatabasePrivate::MimeDatabasePrivate() :
    m_maxLevel(-1)
{
}

namespace Internal {
    // Parser that builds MimeDB hierarchy by adding to MimeDatabasePrivate
    class MimeTypeParser : public BaseMimeTypeParser {
    public:
        explicit MimeTypeParser(MimeDatabasePrivate &db) : m_db(db) {}
    private:
        virtual bool process(const MimeType &t, QString *) { m_db.addMimeType(t); return true; }

        MimeDatabasePrivate &m_db;
    };
} // namespace Internal

bool MimeDatabasePrivate::addMimeTypes(QIODevice *device, const QString &fileName, QString *errorMessage)
{
    Internal::MimeTypeParser parser(*this);
    return parser.parse(device, fileName, errorMessage);
}

bool MimeDatabasePrivate::addMimeTypes(const QString &fileName, QString *errorMessage)
{
    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly|QIODevice::Text)) {
907
        *errorMessage = QString::fromLatin1("Cannot open %1: %2").arg(fileName, file.errorString());
con's avatar
con committed
908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
        return false;
    }
    return addMimeTypes(&file, fileName, errorMessage);
}

bool MimeDatabasePrivate::addMimeTypes(QIODevice *device, QString *errorMessage)
{
    return addMimeTypes(device, QLatin1String("<stream>"), errorMessage);
}

bool MimeDatabasePrivate::addMimeType(MimeType mt)
{
    if (!mt)
        return false;

    const QString type = mt.type();
    // Hack: Add a magic text matcher to "text/plain" and the fallback matcher to
    // binary types "application/octet-stream"
    if (type == QLatin1String(textTypeC)) {
        mt.addMagicMatcher(QSharedPointer<IMagicMatcher>(new Internal::HeuristicTextMagicMatcher));
    } else {
        if (type == QLatin1String(binaryTypeC))
             mt.addMagicMatcher(QSharedPointer<IMagicMatcher>(new Internal::BinaryMatcher));
    }
    // insert the type.
    m_typeMimeTypeMap.insert(type, MimeMapEntry(mt));
    // Register the children, resolved via alias map. Note that it is still
    // possible that aliases end up in the map if the parent classes are not inserted
    // at this point (thus their aliases not known).
    const QStringList subClassesOf = mt.subClassesOf();
    if (!subClassesOf.empty()) {
        const QStringList::const_iterator socend = subClassesOf.constEnd();
        for (QStringList::const_iterator soit = subClassesOf.constBegin(); soit !=  socend; ++soit)
            m_parentChildrenMap.insert(resolveAlias(*soit), type);
    }
    // register aliasses
    const QStringList aliases = mt.aliases();
    if (!aliases.empty()) {
        const QStringList::const_iterator cend = aliases.constEnd();
        for (QStringList::const_iterator it = aliases.constBegin(); it !=  cend; ++it)
            m_aliasMap.insert(*it, type);
    }
    m_maxLevel = -1; // Mark as dirty
    return true;
}

const QString &MimeDatabasePrivate::resolveAlias(const  QString &name) const
{
    const AliasMap::const_iterator aliasIt = m_aliasMap.constFind(name);
    return aliasIt == m_aliasMap.constEnd() ? name : aliasIt.value();
}

void MimeDatabasePrivate::raiseLevelRecursion(MimeMapEntry &e, int level)
{
    if (e.level == Dangling || e.level < level)
        e.level = level;
    if (m_maxLevel < level)
        m_maxLevel = level;
    // At all events recurse over children since nodes might have been
    // added.
    const QStringList childTypes = m_parentChildrenMap.values(e.type.type());
    if (childTypes.empty())
        return;
    // look them up in the type->mime type map
    const int nextLevel = level + 1;
    const TypeMimeTypeMap::iterator tm_end = m_typeMimeTypeMap.end();
    const QStringList::const_iterator cend = childTypes.constEnd();
    for (QStringList::const_iterator it = childTypes.constBegin(); it !=  cend; ++it) {
        const TypeMimeTypeMap::iterator tm_it = m_typeMimeTypeMap.find(resolveAlias(*it));
        if (tm_it == tm_end) {
            qWarning("%s: Inconsistent mime hierarchy detected, child %s of %s cannot be found.",
                     Q_FUNC_INFO, it->toUtf8().constData(), e.type.type().toUtf8().constData());
        } else {
            raiseLevelRecursion(*tm_it, nextLevel);
        }
    }
}

void MimeDatabasePrivate::determineLevels()
{
    // Loop over toplevels and recurse down their hierarchies.
    // Determine top levels by subtracting the children from the parent
    // set. Note that a toplevel at this point might have 'subclassesOf'
    // set to some class that is not in the DB, so, checking for an empty
    // 'subclassesOf' set is not sufficient to find the toplevels.
    // First, take the parent->child entries  whose parent exists and build
    // sets of parents/children
    QSet<QString> parentSet, childrenSet;
    const ParentChildrenMap::const_iterator pcend = m_parentChildrenMap.constEnd();
    for (ParentChildrenMap::const_iterator it =  m_parentChildrenMap.constBegin(); it !=  pcend; ++it)
        if (m_typeMimeTypeMap.contains(it.key())) {
            parentSet.insert(it.key());
            childrenSet.insert(it.value());
        }
    const QSet<QString> topLevels = parentSet.subtract(childrenSet);
    if (debugMimeDB)
        qDebug() << Q_FUNC_INFO << "top levels" << topLevels;
    const TypeMimeTypeMap::iterator tm_end = m_typeMimeTypeMap.end();
    const QSet<QString>::const_iterator tl_cend = topLevels.constEnd();
    for (QSet<QString>::const_iterator tl_it =  topLevels.constBegin(); tl_it !=  tl_cend; ++tl_it) {
        const TypeMimeTypeMap::iterator tm_it = m_typeMimeTypeMap.find(resolveAlias(*tl_it));
        if (tm_it == tm_end) {
            qWarning("%s: Inconsistent mime hierarchy detected, top level element %s cannot be found.",
                     Q_FUNC_INFO, tl_it->toUtf8().constData());
        } else {
            raiseLevelRecursion(tm_it.value(), 0);
        }
    }
}

bool MimeDatabasePrivate::setPreferredSuffix(const QString &typeOrAlias, const QString &suffix)
{
    TypeMimeTypeMap::iterator tit =  m_typeMimeTypeMap.find(resolveAlias(typeOrAlias));
    if (tit != m_typeMimeTypeMap.end())
        return tit.value().type.setPreferredSuffix(suffix);
    return false;
}

// Returns a mime type or Null one if none found
MimeType MimeDatabasePrivate::findByType(const QString &typeOrAlias) const
{
    const TypeMimeTypeMap::const_iterator tit =  m_typeMimeTypeMap.constFind(resolveAlias(typeOrAlias));
    if (tit != m_typeMimeTypeMap.constEnd())
        return tit.value().type;
    return MimeType();
}

// Debugging wrapper around findByFile()
MimeType MimeDatabasePrivate::findByFile(const QFileInfo &f) const
{
    unsigned priority = 0;
    if (debugMimeDB)
1040
        qDebug() << '>' << Q_FUNC_INFO << f.absoluteFilePath();
con's avatar
con committed
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
    const MimeType rc = findByFile(f, &priority);
    if (debugMimeDB) {
        if (rc) {
            qDebug() << "<MimeDatabase::findByFile: match prio=" << priority << rc.type();
        } else {
            qDebug() << "<MimeDatabase::findByFile: no match";
        }
    }
    return rc;
}

// Returns a mime type or Null one if none found
MimeType MimeDatabasePrivate::findByFile(const QFileInfo &f, unsigned *priorityPtr) const
{
    // Is the hierarchy set up in case we find several matches?
    if (m_maxLevel < 0) {
        MimeDatabasePrivate *db = const_cast<MimeDatabasePrivate *>(this);
        db->determineLevels();
    }
    // Starting from max level (most specific): Try to find a match of
    // best (max) priority. Return if a glob match triggers.
    *priorityPtr = 0;
    Internal::FileMatchContext context(f);
1064
    // Pass 1) Try to match on suffix
con's avatar
con committed
1065
    const TypeMimeTypeMap::const_iterator cend = m_typeMimeTypeMap.constEnd();
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
    for (int level = m_maxLevel; level >= 0; level--)
        for (TypeMimeTypeMap::const_iterator it = m_typeMimeTypeMap.constBegin(); it != cend; ++it)
            if (it.value().level == level)
                if (const unsigned suffixPriority = it.value().type.matchesFileBySuffix(context)) {
                    *priorityPtr = suffixPriority;
                    return it.value().type;
                }
    // Pass 2) Match on content
    MimeType rc;
    if (!f.isReadable())
        return rc;
    unsigned maxPriority = 0;
con's avatar
con committed
1078 1079 1080
    for (int level = m_maxLevel; level >= 0; level--)
        for (TypeMimeTypeMap::const_iterator it = m_typeMimeTypeMap.constBegin(); it != cend; ++it)
            if (it.value().level == level) {
1081 1082 1083 1084 1085
                const unsigned priority = it.value().type.matchesFileByContent(context);
                if (priority && priority > maxPriority) {
                    rc = it.value().type;
                    maxPriority = priority;
                }
con's avatar
con committed
1086
            }
1087
    *priorityPtr = maxPriority;
con's avatar
con committed
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
    return rc;
}

// Return all known suffixes
QStringList MimeDatabasePrivate::suffixes() const
{
    QStringList rc;
    const TypeMimeTypeMap::const_iterator cend = m_typeMimeTypeMap.constEnd();
    for (TypeMimeTypeMap::const_iterator it = m_typeMimeTypeMap.constBegin(); it != cend; ++it)
        rc += it.value().type.suffixes();
    return rc;
}

QStringList MimeDatabasePrivate::filterStrings() const
{
    QStringList rc;
    const TypeMimeTypeMap::const_iterator cend = m_typeMimeTypeMap.constEnd();
1105 1106 1107 1108 1109
    for (TypeMimeTypeMap::const_iterator it = m_typeMimeTypeMap.constBegin(); it != cend; ++it) {
        const QString filterString = it.value().type.filterString();
        if (!filterString.isEmpty())
            rc += filterString;
    }
con's avatar
con committed
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
    return rc;
}

void MimeDatabasePrivate::debug(QTextStream &str) const
{
    str << ">MimeDatabase\n";
    const TypeMimeTypeMap::const_iterator cend = m_typeMimeTypeMap.constEnd();
    for (TypeMimeTypeMap::const_iterator it = m_typeMimeTypeMap.constBegin(); it != cend; ++it) {
        str << "Entry level " << it.value().level << '\n';
        it.value().type.m_d->debug(str);
    }
    str << "<MimeDatabase\n";
}

// --------------- MimeDatabase
MimeDatabase::MimeDatabase() :
    m_d(new MimeDatabasePrivate)
{
}

MimeDatabase::~MimeDatabase()
{
    delete m_d;
}

MimeType MimeDatabase::findByType(const QString &typeOrAlias) const
{
1137 1138 1139 1140
    m_mutex.lock();
    const MimeType rc = m_d->findByType(typeOrAlias);
    m_mutex.unlock();
    return rc;
con's avatar
con committed
1141 1142
}

1143
MimeType MimeDatabase::findByFileUnlocked(const QFileInfo &f) const
con's avatar
con committed
1144 1145 1146 1147
{
    return m_d->findByFile(f);
}

1148 1149 1150 1151 1152 1153 1154 1155
MimeType MimeDatabase::findByFile(const QFileInfo &f) const
{
    m_mutex.lock();
    const MimeType rc = findByFileUnlocked(f);
    m_mutex.unlock();
    return rc;
}

con's avatar
con committed
1156 1157
bool MimeDatabase::addMimeType(const  MimeType &mt)
{
1158 1159 1160 1161
    m_mutex.lock();
    const bool rc = m_d->addMimeType(mt);
    m_mutex.unlock();
    return rc;
con's avatar
con committed
1162 1163 1164 1165
}

bool MimeDatabase::addMimeTypes(const QString &fileName, QString *errorMessage)
{
1166 1167 1168 1169
    m_mutex.lock();
    const bool rc = m_d->addMimeTypes(fileName, errorMessage);
    m_mutex.unlock();
    return rc;
con's avatar
con committed
1170 1171 1172 1173
}

bool MimeDatabase::addMimeTypes(QIODevice *device, QString *errorMessage)
{
1174 1175 1176 1177
    m_mutex.lock();
    const bool rc = m_d->addMimeTypes(device, errorMessage);
    m_mutex.unlock();
    return rc;
con's avatar
con committed
1178 1179 1180 1181
}

QStringList MimeDatabase::suffixes() const
{
1182 1183 1184 1185
    m_mutex.lock();
    const QStringList rc = m_d->suffixes();
    m_mutex.unlock();
    return rc;
con's avatar
con committed
1186 1187 1188 1189
}

QStringList MimeDatabase::filterStrings() const
{
1190 1191 1192 1193
    m_mutex.lock();
    const  QStringList rc = m_d->filterStrings();
    m_mutex.unlock();
    return rc;
con's avatar
con committed
1194 1195 1196 1197 1198
}

QString MimeDatabase::preferredSuffixByType(const QString &type) const
{
    if (const MimeType mt = findByType(type))
1199
        return mt.preferredSuffix(); // already does Mutex locking
con's avatar
con committed
1200 1201 1202 1203 1204 1205
    return QString();
}

QString MimeDatabase::preferredSuffixByFile(const QFileInfo &f) const
{
    if (const MimeType mt = findByFile(f))
1206
        return mt.preferredSuffix(); // already does Mutex locking
con's avatar
con committed
1207 1208 1209 1210 1211
    return QString();
}

bool MimeDatabase::setPreferredSuffix(const QString &typeOrAlias, const QString &suffix)
{
1212 1213 1214 1215
    m_mutex.lock();
    const bool rc = m_d->setPreferredSuffix(typeOrAlias, suffix);
    m_mutex.unlock();
    return rc;
con's avatar
con committed
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
}

QDebug operator<<(QDebug d, const MimeDatabase &mt)
{
    QString s;
    {
        QTextStream str(&s);
        mt.m_d->debug(str);
    }
    d << s;
    return d;
}

} // namespace Core