mimedatabase.cpp 68.5 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
con's avatar
con committed
2
**
3
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
hjk's avatar
hjk committed
4
** Contact: http://www.qt-project.org/legal
con's avatar
con committed
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
con's avatar
con committed
7
**
hjk's avatar
hjk committed
8 9 10 11 12 13 14
** 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 Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
15
**
16
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17 18 19 20 21 22 23 24 25
** 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.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
con's avatar
con committed
26 27
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
28
****************************************************************************/
hjk's avatar
hjk committed
29

con's avatar
con committed
30
#include "mimedatabase.h"
31
#include "coreconstants.h"
32
#include "icore.h"
con's avatar
con committed
33

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

36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
#include <QByteArray>
#include <QCoreApplication>
#include <QDebug>
#include <QFile>
#include <QDir>
#include <QFileInfo>
#include <QLocale>
#include <QHash>
#include <QMultiHash>
#include <QRegExp>
#include <QSharedData>
#include <QSharedPointer>
#include <QStringList>
#include <QTextStream>
#include <QXmlStreamReader>
#include <QXmlStreamWriter>
con's avatar
con committed
52

Christian Kandeler's avatar
Christian Kandeler committed
53
#include <algorithm>
54
#include <functional>
Christian Kandeler's avatar
Christian Kandeler committed
55

con's avatar
con committed
56 57 58
enum { debugMimeDB = 0 };

// XML tags in mime files
59 60 61 62 63 64 65 66 67 68
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 weightAttributeC[] = "weight";
static const char localeAttributeC[] = "xml:lang";
con's avatar
con committed
69

70 71 72 73 74 75 76 77
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 matchByteTypeValueC[] = "byte";
static const char matchOffsetAttributeC[] = "offset";
con's avatar
con committed
78 79

// Types
80 81
static const char textTypeC[] = "text/plain";
static const char binaryTypeC[] = "application/octet-stream";
con's avatar
con committed
82 83 84 85 86 87

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

// Fallback priorities, must be low.
88 89 90 91
enum {
    BinaryMatchPriority = Core::MimeGlobPattern::MinWeight + 1,
    TextMatchPriority
};
con's avatar
con committed
92

93 94 95
/*!
    \class Core::IMagicMatcher

96 97
    \brief The IMagicMatcher class is an interface for a MIME type magic
    matcher that examines file contents to determine the MIME type of a file.
98 99 100 101

    \sa Core::MimeType, Core::MimeDatabase, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern
    \sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher
    \sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser
con's avatar
con committed
102 103 104
*/

namespace Core {
105 106 107

typedef QSharedPointer<MagicRuleMatcher> MagicRuleMatcherPtr;

con's avatar
con committed
108 109
namespace Internal {

110 111 112
/*!
    \class Core::Internal::FileMatchContext

113 114
    \brief The FileMatchContext class is the context passed on to the MIME
    types when looking for a file match.
115

Leena Miettinen's avatar
Leena Miettinen committed
116 117
    This class exists to enable reading the file contents \e {on demand},
    as opposed to each mime type trying to open and read while checking.
118 119 120 121 122

    \sa Core::MimeType, Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern
    \sa Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher
    \sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser
*/
con's avatar
con committed
123

hjk's avatar
hjk committed
124 125
class FileMatchContext
{
126
    Q_DISABLE_COPY(FileMatchContext)
hjk's avatar
hjk committed
127

con's avatar
con committed
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
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;
}

176 177
/*!
    \class Core::Internal::BinaryMatcher
178 179
    \brief The BinaryMatcher class is the binary fallback matcher for the MIME
    type \c{application/octet-stream}.
180 181 182 183 184 185

    \sa Core::MimeType, Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern
    \sa Core::Internal::FileMatchContext, Core::Internal::HeuristicTextMagicMatcher
    \sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser
*/

hjk's avatar
hjk committed
186 187
class BinaryMatcher : public IMagicMatcher
{
con's avatar
con committed
188 189 190 191 192 193
public:
    BinaryMatcher() {}
    virtual bool matches(const QByteArray & /*data*/) const { return true; }
    virtual int priority() const  { return BinaryMatchPriority; }
};

194 195
/*!
    \class Core::Internal::HeuristicTextMagicMatcher
196 197
    \brief The HeuristicTextMagicMatcher class implements a heuristic text file
    matcher for MIME types.
198

Leena Miettinen's avatar
Leena Miettinen committed
199 200
    If the data does not contain any character below tab (9), it is detected as
    text. Additionally, UTF16 byte order markers are checked.
201 202 203 204 205 206

    \sa Core::MimeType, Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern
    \sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher
    \sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser
*/

hjk's avatar
hjk committed
207 208
class HeuristicTextMagicMatcher : public IMagicMatcher
{
con's avatar
con committed
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
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

240 241
/*!
    \class Core::MagicRule
242 243
    \brief The MagicRule class is a base class for standard Magic matching rules
    based on contents
244 245 246
    and offset specification.

    Stores the offset and provides conversion helpers.
Leena Miettinen's avatar
Leena Miettinen committed
247 248
    Base class for implementations for \c string and \c byte.
    Others, such as \c little16 and \c big16, can be created when needed.
249 250 251 252 253 254

    \sa Core::MimeType, Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern
    \sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher
    \sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser
 */

255 256
const QChar MagicRule::kColon(QLatin1Char(':'));

257
MagicRule::MagicRule(int startPos, int endPos) : m_startPos(startPos), m_endPos(endPos)
con's avatar
con committed
258 259 260
{
}

261 262 263 264 265 266 267 268 269 270 271 272 273 274
MagicRule::~MagicRule()
{
}

int MagicRule::startPos() const
{
    return m_startPos;
}

int MagicRule::endPos() const
{
    return m_endPos;
}

275 276 277 278 279 280 281 282 283 284 285 286
QString MagicRule::toOffset(const QPair<int, int> &startEnd)
{
    return QString(QLatin1String("%1:%2")).arg(startEnd.first).arg(startEnd.second);
}

QPair<int, int> MagicRule::fromOffset(const QString &offset)
{
    const QStringList &startEnd = offset.split(kColon);
    Q_ASSERT(startEnd.size() == 2);
    return qMakePair(startEnd.at(0).toInt(), startEnd.at(1).toInt());
}

287 288
/*!
    \class Core::MagicStringRule
289
    \brief The MagicStringRule class provides rules for matching strings.
290 291 292 293 294 295

    \sa Core::MimeType, Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicByteRule, Core::GlobPattern
    \sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher
    \sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser
 */

296
const QString MagicStringRule::kMatchType(QLatin1String("string"));
297

298 299 300 301 302 303 304 305 306
MagicStringRule::MagicStringRule(const QString &s, int startPos, int endPos) :
    MagicRule(startPos, endPos), m_pattern(s.toUtf8())
{
}

MagicStringRule::~MagicStringRule()
{
}

307 308 309 310 311 312 313
QString MagicStringRule::matchType() const
{
    return kMatchType;
}

QString MagicStringRule::matchValue() const
{
314
    return QLatin1String(m_pattern);
315 316
}

317
bool MagicStringRule::matches(const QByteArray &data) const
con's avatar
con committed
318 319
{
    // Quick check
320
    if ((startPos() + m_pattern.size()) > data.size())
con's avatar
con committed
321 322
        return false;
    // Most common: some string at position 0:
323
    if (startPos() == 0 && startPos() == endPos())
con's avatar
con committed
324 325
        return data.startsWith(m_pattern);
    // Range
326 327
    const int index = data.indexOf(m_pattern, startPos());
    const bool rc = index != -1 && index <= endPos();
328
    if (debugMimeDB)
329
        qDebug() << "Checking " << m_pattern << startPos() << endPos() << " returns " << rc;
330
    return rc;
con's avatar
con committed
331 332
}

333 334
/*!
    \class Core::MagicByteRule
335 336
    \brief The MagicByteRule class provides rules for matching a sequence of
    binary data.
337 338 339 340 341 342 343 344 345 346 347

    Format:
    \code
    \0x7f\0x45\0x4c\0x46
    \endcode

    \sa Core::MimeType, Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern
    \sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher
    \sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser
 */

348 349
const QString MagicByteRule::kMatchType(QLatin1String("byte"));

350
MagicByteRule::MagicByteRule(const QString &s, int startPos, int endPos) :
351 352 353 354 355 356 357 358 359 360 361 362 363
    MagicRule(startPos, endPos), m_bytesSize(0)
{
    if (validateByteSequence(s, &m_bytes))
        m_bytesSize = m_bytes.size();
    else
        m_bytes.clear();
}

MagicByteRule::~MagicByteRule()
{
}

bool MagicByteRule::validateByteSequence(const QString &sequence, QList<int> *bytes)
con's avatar
con committed
364
{
365
    // Expect an hex format value like this: \0x7f\0x45\0x4c\0x46
366 367
    const QStringList &byteSequence = sequence.split(QLatin1Char('\\'), QString::SkipEmptyParts);
    foreach (const QString &byte, byteSequence) {
368 369 370
        bool ok;
        const int hex = byte.toInt(&ok, 16);
        if (ok) {
371 372
            if (bytes)
                bytes->push_back(hex);
373
        } else {
374
            return false;
375 376
        }
    }
377
    return true;
378 379
}

380
QString MagicByteRule::matchType() const
381
{
382 383 384 385 386 387 388 389 390
    return kMatchType;
}

QString MagicByteRule::matchValue() const
{
    QString value;
    foreach (int byte, m_bytes)
        value.append(QString(QLatin1String("\\0x%1")).arg(byte, 0, 16));
    return value;
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
}

bool MagicByteRule::matches(const QByteArray &data) const
{
    if (m_bytesSize == 0)
        return false;

    const int dataSize = data.size();
    for (int start = startPos(); start <= endPos(); ++start) {
        if ((start + m_bytesSize) > dataSize)
            return false;

        int matchAt = 0;
        while (matchAt < m_bytesSize) {
            if (data.at(start + matchAt) != m_bytes.at(matchAt))
                break;
            ++matchAt;
        }
        if (matchAt == m_bytesSize)
            return true;
    }

    return false;
con's avatar
con committed
414 415
}

416 417 418
/*!
    \class Core::MagicRuleMatcher

419 420
    \brief The MagicRuleMatcher class implements a Magic matcher that checks the
    number of rules based on the boolean operator OR.
421

Leena Miettinen's avatar
Leena Miettinen committed
422
    This class is used for rules parsed from XML files.
423 424 425 426 427 428

    \sa Core::MimeType, Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern
    \sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher
    \sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser
*/

con's avatar
con committed
429 430 431 432 433 434 435
MagicRuleMatcher::MagicRuleMatcher() :
     m_priority(65535)
{
}

void MagicRuleMatcher::add(const MagicRuleSharedPointer &rule)
{
436 437 438 439 440 441 442 443 444 445 446
    m_list.append(rule);
}

void MagicRuleMatcher::add(const MagicRuleList &ruleList)
{
    m_list.append(ruleList);
}

MagicRuleMatcher::MagicRuleList MagicRuleMatcher::magicRules() const
{
    return m_list;
con's avatar
con committed
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
}

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;
}

468 469 470 471 472 473 474 475 476 477 478 479 480 481
IMagicMatcher::IMagicMatcherList MagicRuleMatcher::createMatchers(
    const QHash<int, MagicRuleList> &rulesByPriority)
{
    IMagicMatcher::IMagicMatcherList matchers;
    QHash<int, MagicRuleList>::const_iterator ruleIt = rulesByPriority.begin();
    for (; ruleIt != rulesByPriority.end(); ++ruleIt) {
        MagicRuleMatcher *magicRuleMatcher = new MagicRuleMatcher();
        magicRuleMatcher->setPriority(ruleIt.key());
        magicRuleMatcher->add(ruleIt.value());
        matchers.append(IMagicMatcher::IMagicMatcherSharedPointer(magicRuleMatcher));
    }
    return matchers;
}

482 483
/*!
    \class Core::GlobPattern
484 485
    \brief The GlobPattern class provides a glob pattern for file names for
    MIME type matching.
486 487 488 489 490 491

    \sa Core::MimeType, Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule
    \sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher
    \sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser
*/

492 493
MimeGlobPattern::MimeGlobPattern(const QString &pattern, unsigned weight) :
    m_pattern(pattern), m_weight(weight)
494
{
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
    bool hasQuestionMark = pattern.contains(QLatin1Char('?'));
    bool hasStar = pattern.contains(QLatin1Char('*'));

    if (!hasQuestionMark && hasStar && pattern.lastIndexOf(QLatin1Char('*')) == 0) {
        m_type = Suffix;
    } else if (!hasQuestionMark && !hasStar) {
        m_type = Exact;
    } else {
        // This hopefully never happens as it is expensive.
        m_type = Glob;
        m_regexp.setPattern(pattern);
        m_regexp.setPatternSyntax(QRegExp::Wildcard);
        if (!m_regexp.isValid())
            qWarning("%s: Invalid wildcard '%s'.", Q_FUNC_INFO, pattern.toUtf8().constData());
    }
510 511 512 513 514 515
}

MimeGlobPattern::~MimeGlobPattern()
{
}

516
bool MimeGlobPattern::matches(const QString &fileName) const
517
{
518 519 520 521 522
    if (m_type == Exact)
        return fileName == m_pattern;
    if (m_type == Suffix)
        return fileName.endsWith(m_pattern.midRef(1));
    return m_regexp.exactMatch(fileName);
523 524 525
}


526 527 528
/*!
    \class Core::MimeType

529
    \brief The MimeType class contains MIME type data used in \QC.
530

Leena Miettinen's avatar
Leena Miettinen committed
531
    Contains most information from standard MIME type XML database files.
532

Leena Miettinen's avatar
Leena Miettinen committed
533 534
    Currently, magic of types \c string anc \c bytes is supported. In addition,
    C++ classes, derived from \c Core::IMagicMatcher can be added to check
535 536
    on contents.

Leena Miettinen's avatar
Leena Miettinen committed
537 538 539
    The class provides a list of suffixes and a concept of a
    \e {preferred suffix} (derived from glob patterns). This is used for example
    to be able to configure the suffix used for C++ files in \QC.
540

Leena Miettinen's avatar
Leena Miettinen committed
541
    MIME type XML files look like follows:
542 543 544 545
    \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 -->
Orgad Shaneh's avatar
Orgad Shaneh committed
546
      <mime-type type="application/vnd.qt.qmakeprofile">
547 548 549 550 551 552 553 554 555 556 557
        <comment xml:lang="en">Qt qmake Profile</comment>
        <glob pattern="*.pro" weight="50"/>
      </mime-type>
    </mime-info>
    \endcode

    \sa Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern
    \sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher
    \sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser
*/

con's avatar
con committed
558 559 560
class MimeTypeData : public QSharedData {
public:
    typedef QHash<QString,QString> LocaleHash;
561 562 563

    MimeTypeData();

con's avatar
con committed
564
    void clear();
565 566
    void assignSuffix(const QString &pattern);
    void assignSuffixes(const QStringList &patterns);
con's avatar
con committed
567 568
    void debug(QTextStream &str, int indent = 0) const;

569
    QRegExp suffixPattern;
570

con's avatar
con committed
571 572 573 574 575
    QString type;
    QString comment;

    LocaleHash localeComments;
    QStringList aliases;
576
    QList<MimeGlobPattern> globPatterns;
con's avatar
con committed
577 578 579
    QStringList subClassesOf;
    QString preferredSuffix;
    QStringList suffixes;
580
    IMagicMatcher::IMagicMatcherList magicMatchers;
con's avatar
con committed
581 582
};

583 584 585 586 587
MimeTypeData::MimeTypeData()
    // RE to match a suffix glob pattern: "*.ext" (and not sth like "Makefile" or
    // "*.log[1-9]"
    : suffixPattern(QLatin1String("^\\*\\.[\\w+]+$"))
{
588
    QTC_CHECK(suffixPattern.isValid());
589 590
}

con's avatar
con committed
591 592 593 594 595 596 597 598 599 600 601 602
void MimeTypeData::clear()
{
    type.clear();
    comment.clear();
    aliases.clear();
    globPatterns.clear();
    subClassesOf.clear();
    preferredSuffix.clear();
    suffixes.clear();
    magicMatchers.clear();
}

603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
void MimeTypeData::assignSuffix(const QString &pattern)
{
    if (suffixPattern.exactMatch(pattern)) {
        const QString suffix = pattern.right(pattern.size() - 2);
        suffixes.push_back(suffix);
        if (preferredSuffix.isEmpty())
            preferredSuffix = suffix;
    }
}

void MimeTypeData::assignSuffixes(const QStringList &patterns)
{
    foreach (const QString &pattern, patterns)
        assignSuffix(pattern);
}

con's avatar
con committed
619 620 621 622 623 624 625 626 627 628 629 630 631
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: ";
632
        foreach (const MimeGlobPattern &gp, globPatterns)
633
            str << gp.pattern() << '(' << gp.weight() << ')';
con's avatar
con committed
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 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 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
        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;
}

744
QList<MimeGlobPattern> MimeType::globPatterns() const
con's avatar
con committed
745 746 747 748
{
    return m_d->globPatterns;
}

749
void MimeType::setGlobPatterns(const QList<MimeGlobPattern> &g)
con's avatar
con committed
750 751
{
    m_d->globPatterns = g;
752 753 754 755 756 757 758

    QString oldPrefferedSuffix = m_d->preferredSuffix;
    m_d->suffixes.clear();
    m_d->preferredSuffix.clear();
    m_d->assignSuffixes(MimeDatabase::fromGlobPatterns(g));
    if (m_d->preferredSuffix != oldPrefferedSuffix && m_d->suffixes.contains(oldPrefferedSuffix))
        m_d->preferredSuffix = oldPrefferedSuffix;
con's avatar
con committed
759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
}

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;
}

789
QString MimeType::formatFilterString(const QString &description, const QList<MimeGlobPattern> &globs)
con's avatar
con committed
790 791 792 793 794 795 796 797 798 799 800 801 802
{
    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 << ' ';
803
                str << globs.at(i).pattern();
con's avatar
con committed
804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824
            }
            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);
825 826
    const unsigned suffixPriority = matchesFileBySuffix(context);
    if (suffixPriority >= MimeGlobPattern::MaxWeight)
827
        return suffixPriority;
828
    return qMax(suffixPriority, matchesFileByContent(context));
con's avatar
con committed
829 830
}

831
unsigned MimeType::matchesFileBySuffix(Internal::FileMatchContext &c) const
con's avatar
con committed
832 833
{
    // check globs
834
    foreach (const MimeGlobPattern &gp, m_d->globPatterns) {
835
        if (gp.matches(c.fileName()))
836
            return gp.weight();
837
    }
838 839
    return 0;
}
840

841 842
unsigned MimeType::matchesFileByContent(Internal::FileMatchContext &c) const
{
con's avatar
con committed
843
    // Nope, try magic matchers on context data
844
    if (m_d->magicMatchers.isEmpty())
845 846 847 848
        return 0;

    return matchesData(c.data());
}
849

850 851 852
unsigned MimeType::matchesData(const QByteArray &data) const
{
    unsigned priority = 0;
con's avatar
con committed
853
    if (!data.isEmpty()) {
854
        foreach (const IMagicMatcher::IMagicMatcherSharedPointer &matcher, m_d->magicMatchers) {
855 856 857
            const unsigned magicPriority = matcher->priority();
            if (magicPriority > priority && matcher->matches(data))
                priority = magicPriority;
858
        }
con's avatar
con committed
859
    }
860
    return priority;
con's avatar
con committed
861 862 863 864 865 866 867
}

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

868
void MimeType::addMagicMatcher(const IMagicMatcherSharedPointer &matcher)
con's avatar
con committed
869
{
870
    m_d->magicMatchers.push_back(matcher);
con's avatar
con committed
871 872
}

873
const MimeType::IMagicMatcherList &MimeType::magicMatchers() const
con's avatar
con committed
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 907 908 909 910 911
    return m_d->magicMatchers;
}

void MimeType::setMagicMatchers(const IMagicMatcherList &matchers)
{
    m_d->magicMatchers = matchers;
}

namespace {
struct RemovePred : std::unary_function<MimeType::IMagicMatcherSharedPointer, bool>
{
    RemovePred(bool keepRuleBased) : m_keepRuleBase(keepRuleBased) {}
    bool m_keepRuleBase;

    bool operator()(const MimeType::IMagicMatcherSharedPointer &matcher) {
        if ((m_keepRuleBase && !dynamic_cast<MagicRuleMatcher *>(matcher.data()))
                || (!m_keepRuleBase && dynamic_cast<MagicRuleMatcher *>(matcher.data())))
            return true;
        return false;
    }
};
} // Anonymous

MimeType::IMagicMatcherList MimeType::magicRuleMatchers() const
{
    IMagicMatcherList ruleMatchers = m_d->magicMatchers;
    ruleMatchers.erase(std::remove_if(ruleMatchers.begin(), ruleMatchers.end(), RemovePred(true)),
                       ruleMatchers.end());
    return ruleMatchers;
}

void MimeType::setMagicRuleMatchers(const IMagicMatcherList &matchers)
{
    m_d->magicMatchers.erase(std::remove_if(m_d->magicMatchers.begin(), m_d->magicMatchers.end(),
                                            RemovePred(false)),
                             m_d->magicMatchers.end());
    m_d->magicMatchers.append(matchers);
con's avatar
con committed
912 913 914 915 916 917 918 919 920 921 922 923 924 925 926
}

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

namespace Internal {

927 928
/*!
    \class Core::Internal::BaseMimeTypeParser
929 930
    \brief The BaseMimeTypeParser class provides a generic parser for a
    sequence of <mime-type>.
931

Leena Miettinen's avatar
Leena Miettinen committed
932 933
    This class calls the abstract handler function process for the MIME types
    it finds.
934 935 936 937 938 939

    \sa Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern
    \sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher
    \sa Core::Internal::MimeTypeParser
*/

hjk's avatar
hjk committed
940 941
class BaseMimeTypeParser
{
942
    Q_DISABLE_COPY(BaseMimeTypeParser)
hjk's avatar
hjk committed
943

con's avatar
con committed
944
public:
945
    BaseMimeTypeParser() {}
con's avatar
con committed
946 947 948 949 950 951 952 953
    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;

954
    void addGlobPattern(const QString &pattern, const QString &weight, MimeTypeData *d) const;
con's avatar
con committed
955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970

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

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

971
void BaseMimeTypeParser::addGlobPattern(const QString &pattern, const QString &weight, MimeTypeData *d) const
con's avatar
con committed
972 973 974 975 976
{
    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
977
    if (weight.isEmpty())
978
        d->globPatterns.push_back(MimeGlobPattern(pattern));
979
    else
980
        d->globPatterns.push_back(MimeGlobPattern(pattern, weight.toInt()));
981

982
    d->assignSuffix(pattern);
con's avatar
con committed
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
}

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;
1015 1016
        if (startElement == QLatin1String(matchTagC))
            return ParseMagicMatchRule;
con's avatar
con committed
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
        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) {
1034
        *errorMessage = QString::fromLatin1("Not a number \"%1\".").arg(n);
con's avatar
con committed
1035 1036 1037 1038 1039 1040 1041 1042 1043
        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,
1044
                              const MagicRuleMatcherPtr  &ruleMatcher,
con's avatar
con committed
1045 1046
                              QString *errorMessage)
{
1047
    const QStringRef type = atts.value(QLatin1String(matchTypeAttributeC));
1048 1049
    if (type != QLatin1String(matchStringTypeValueC) &&
        type != QLatin1String(matchByteTypeValueC)) {
con's avatar
con committed
1050 1051 1052 1053 1054
        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()) {
1055
        *errorMessage = QString::fromLatin1("Empty match value detected.");
con's avatar
con committed
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
        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;
1068 1069 1070 1071 1072

    if (type == QLatin1String(matchStringTypeValueC))
        ruleMatcher->add(QSharedPointer<MagicRule>(new MagicStringRule(value, startPos, endPos)));
    else
        ruleMatcher->add(QSharedPointer<MagicRule>(new MagicByteRule(value, startPos, endPos)));
con's avatar
con committed
1073 1074 1075 1076 1077 1078
    return true;
}

bool BaseMimeTypeParser::parse(QIODevice *dev, const QString &fileName, QString *errorMessage)
{
    MimeTypeData data;
1079
    MagicRuleMatcherPtr ruleMatcher;
con's avatar
con committed
1080 1081
    QXmlStreamReader reader(dev);
    ParseStage ps = ParseBeginning;
1082
    QXmlStreamAttributes atts;
con's avatar
con committed
1083 1084 1085 1086
    while (!reader.atEnd()) {
        switch (reader.readNext()) {
        case QXmlStreamReader::StartElement:
            ps = nextStage(ps, reader.name());
1087
            atts = reader.attributes();
con's avatar
con committed
1088 1089
            switch (ps) {
            case ParseMimeType: { // start parsing a type
1090
                const QString type = atts.value(QLatin1String(mimeTypeAttributeC)).toString();
1091
                if (type.isEmpty())
1092
                    reader.raiseError(QString::fromLatin1("Missing 'type'-attribute"));
1093
                else
con's avatar
con committed
1094 1095 1096 1097
                    data.type = type;
            }
                break;
            case ParseGlobPattern:
1098 1099
                addGlobPattern(atts.value(QLatin1String(patternAttributeC)).toString(),
                               atts.value(QLatin1String(weightAttributeC)).toString(), &data);
con's avatar
con committed
1100 1101
                break;
            case ParseSubClass: {
1102
                const QString inheritsFrom = atts.value(QLatin1String(mimeTypeAttributeC)).toString();
con's avatar
con committed
1103 1104 1105 1106 1107 1108
                if (!inheritsFrom.isEmpty())
                    data.subClassesOf.push_back(inheritsFrom);
            }
                break;
            case ParseComment: {
                // comments have locale attributes. We want the default, English one
1109
                const QStringRef locale = atts.value(QLatin1String(localeAttributeC));
1110
                const QString comment = QCoreApplication::translate("MimeType", reader.readElementText().toLatin1());
1111
                if (locale.isEmpty())
con's avatar
con committed
1112
                    data.comment = comment;
1113
                else
1114
                    data.localeComments.insert(locale.toString(), comment);
con's avatar
con committed
1115 1116 1117
            }
                break;
            case ParseAlias: {
1118
                const QStringRef alias = atts.value(QLatin1String(mimeTypeAttributeC));
con's avatar
con committed
1119
                if (!alias.isEmpty())
1120
                    data.aliases.push_back(alias.toString());
con's avatar
con committed
1121 1122 1123 1124
            }
                break;
            case ParseMagic: {
                int priority = 0;
1125
                const QStringRef priorityS = atts.value(QLatin1String(priorityAttributeC));
con's avatar
con committed
1126
                if (!priorityS.isEmpty()) {
1127
                    if (!parseNumber(priorityS.toString(), &priority, errorMessage))
con's avatar
con committed
1128 1129 1130
                        return false;

                }
1131
                ruleMatcher = MagicRuleMatcherPtr(new MagicRuleMatcher);
con's avatar
con committed
1132 1133 1134 1135
                ruleMatcher->setPriority(priority);
            }
                break;
            case ParseMagicMatchRule:
1136
                QTC_ASSERT(!ruleMatcher.isNull(), return false);
1137
                if (!addMagicMatchRule(atts, ruleMatcher, errorMessage))
con's avatar
con committed
1138 1139 1140
                    return false;
                break;
            case ParseError:
1141
                reader.raiseError(QString::fromLatin1("Unexpected element <%1>").arg(reader.name().toString()));
con's avatar
con committed
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
                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
1155
                if (reader.name() == QLatin1String(magicTagC)) {
1156
                    QTC_ASSERT(!ruleMatcher.isNull(), return false);
1157 1158
                    data.magicMatchers.push_back(ruleMatcher);
                    ruleMatcher = MagicRuleMatcherPtr();
con's avatar
con committed
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
                }
            }
            break;

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

    if (reader.hasError()) {
1169
        *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
1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
        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
1181 1182
struct MimeMapEntry
{
con's avatar
con committed
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
    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)
{
}

1194 1195
/*!
    \class Core::MimeDatabase
1196 1197
    \brief The MimeDatabase class is a MIME type database to which the plugins
    can add the MIME types they handle.
1198 1199 1200

    The class is protected by a QMutex and can therefore be accessed by threads.

Leena Miettinen's avatar
Leena Miettinen committed
1201
    A good testcase is to run it over \c {/usr/share/mime/<*>/<*>.xml} on Linux.
1202

Leena Miettinen's avatar
Leena Miettinen committed
1203
    When adding a \c{text/plain} to it, the MIME type will receive a magic matcher
1204 1205 1206 1207 1208 1209
    that checks for text files that do not match the globs by heuristics.

    \section1 Design Considerations

    Storage requirements:
    \list
Leena Miettinen's avatar
Leena Miettinen committed
1210 1211 1212 1213 1214
    \li Must be robust in case of incomplete hierarchies and dangling entries.
    \li Plugins will not load and register their MIME types in order of
        inheritance.
    \li Multiple inheritance (several subClassesOf) can occur.
    \li Provide quick lookup by name.
1215
    \li Provide quick lookup by file type.
1216 1217
    \endlist

Leena Miettinen's avatar
Leena Miettinen committed
1218
    This basically rules out a pointer-based tree, so the structure chosen is:
1219
    \list
Leena Miettinen's avatar
Leena Miettinen committed
1220 1221
    \li An alias map \c {QString->QString} for mapping aliases to types.
    \li A map \c {QString->MimeMapEntry} for the types (MimeMapEntry being a pair of
1222
       MimeType and (hierarchy) level.
Leena Miettinen's avatar
Leena Miettinen committed
1223 1224
    \li A map  \c {QString->QString} representing parent to child relations (enabling
       recursing over children).
1225
    \li Using strings avoids dangling pointers.
1226 1227
    \endlist

Leena Miettinen's avatar
Leena Miettinen committed
1228 1229
    The hierarchy level is used for mapping by file types. When \c findByFile()
    is first called after \c addMimeType(), it recurses over the hierarchy and sets
1230 1231
    the hierarchy level of the entries accordingly (0 toplevel, 1 first
    order...). It then does several passes over the type map, checking the
Leena Miettinen's avatar
Leena Miettinen committed
1232
    globs for maxLevel, maxLevel-1....until it finds a match (the idea being
1233 1234 1235 1236 1237 1238 1239
    to check the most specific types first). Starting a recursion from the
    leaves is not suitable since it will hit parent nodes several times.

    \sa Core::MimeType, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern
    \sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher
    \sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser
*/
con's avatar
con committed
1240

hjk's avatar
hjk committed
1241 1242
class MimeDatabasePrivate
{
con's avatar
con committed
1243
    Q_DISABLE_COPY(MimeDatabasePrivate)
hjk's avatar
hjk committed
1244

con's avatar
con committed
1245 1246 1247 1248 1249 1250 1251 1252 1253
public:
    MimeDatabasePrivate();

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

    MimeType findByType(const QString &type) const;
    MimeType findByFile(const QFileInfo &f) const;
1254
    MimeType findByData(const QByteArray &data) const;
con's avatar
con committed
1255

1256
    QStringList filterStrings() const;
con's avatar
con committed
1257 1258

    QStringList suffixes() const;
1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
    bool setPreferredSuffix(const QString &typeOrAlias, const QString &suffix);

    QList<MimeGlobPattern> globPatterns() const;
    void setGlobPatterns(const QString &typeOrAlias, const QList<MimeGlobPattern> &globPatterns);

    QList<QSharedPointer<IMagicMatcher> > magicMatchers() const;
    void setMagicMatchers(const QString &typeOrAlias,
                          const QList<QSharedPointer<IMagicMatcher> > &matchers);

    QList<MimeType> mimeTypes() const;

    void syncUserModifiedMimeTypes();
    static QList<MimeType> readUserModifiedMimeTypes();
    static void writeUserModifiedMimeTypes(const QList<MimeType> &mimeTypes);
    void clearUserModifiedMimeTypes();

    static QList<MimeGlobPattern> toGlobPatterns(const QStringList &patterns,
                                                 int weight = MimeGlobPattern::MaxWeight);
    static QStringList fromGlobPatterns(const QList<MimeGlobPattern> &globPatterns);
con's avatar
con committed
1278 1279 1280 1281 1282 1283 1284

    void debug(QTextStream &str) const;

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