Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qmimeglobpattern.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:critical reason:data-parser
4
6
7#include <QStringList>
8#include <QDebug>
9
11
12using namespace Qt::StringLiterals;
13
14/*!
15 \internal
16 \class QMimeGlobMatchResult
17 \inmodule QtCore
18 \brief The QMimeGlobMatchResult class accumulates results from glob matching.
19
20 Handles glob weights, and preferring longer matches over shorter matches.
21*/
22
23void QMimeGlobMatchResult::addMatch(const QString &mimeType, int weight, const QString &pattern,
24 qsizetype knownSuffixLength)
25{
26 if (m_allMatchingMimeTypes.contains(mimeType))
27 return;
28 // Is this a lower-weight pattern than the last match? Skip this match then.
29 if (weight < m_weight) {
30 m_allMatchingMimeTypes.append(mimeType);
31 return;
32 }
33 bool replace = weight > m_weight;
34 if (!replace) {
35 // Compare the length of the match
36 if (pattern.size() < m_matchingPatternLength)
37 return; // too short, ignore
38 else if (pattern.size() > m_matchingPatternLength) {
39 // longer: clear any previous match (like *.bz2, when pattern is *.tar.bz2)
40 replace = true;
41 }
42 }
43 if (replace) {
44 m_matchingMimeTypes.clear();
45 // remember the new "longer" length
46 m_matchingPatternLength = pattern.size();
47 m_weight = weight;
48 }
49 if (!m_matchingMimeTypes.contains(mimeType)) {
50 m_matchingMimeTypes.append(mimeType);
51 if (replace)
52 m_allMatchingMimeTypes.prepend(mimeType); // highest-weight first
53 else
54 m_allMatchingMimeTypes.append(mimeType);
55 m_knownSuffixLength = knownSuffixLength;
56 }
57}
58
59template <typename Pattern>
60QMimeGlobPattern::PatternType QMimeGlobPattern::patternTypeOf(Pattern pattern)
61{
62 const qsizetype patternLength = pattern.size();
63 if (!patternLength)
64 return OtherPattern;
65
66 const qsizetype starCount = pattern.count(u'*');
67 const bool hasSquareBracket = pattern.indexOf(u'[') != -1;
68 const bool hasQuestionMark = pattern.indexOf(u'?') != -1;
69
70 if (!hasSquareBracket && !hasQuestionMark) {
71 if (starCount == 1) {
72 // Patterns like "*~", "*.extension"
73 if (pattern.at(0) == u'*')
74 return SuffixPattern;
75 // Patterns like "README*" (well this is currently the only one like that...)
76 if (pattern.at(patternLength - 1) == u'*')
77 return PrefixPattern;
78 } else if (starCount == 0) {
79 // Names without any wildcards like "README"
80 return LiteralPattern;
81 }
82 }
83
84 if (pattern == "[0-9][0-9][0-9].vdr"_L1)
85 return VdrPattern;
86
87 if (pattern == "*.anim[1-9j]"_L1)
88 return AnimPattern;
89
90 return OtherPattern;
91}
92
93QMimeGlobPattern::PatternType QMimeGlobPattern::detectPatternType(QStringView pattern)
94{
95 return patternTypeOf(pattern);
96}
97
98QMimeGlobPattern::PatternType QMimeGlobPattern::detectPatternType(QLatin1StringView pattern)
99{
100 return patternTypeOf(pattern);
101}
102
103
104/*!
105 \internal
106 \class QMimeGlobPattern
107 \inmodule QtCore
108 \brief The QMimeGlobPattern class contains the glob pattern for file names for MIME type matching.
109
110 \sa QMimeType, QMimeDatabase, QMimeMagicRuleMatcher, QMimeMagicRule
111*/
112
113template <typename Pattern>
114bool QMimeGlobPattern::matchWithoutRegularExpression(PatternType patternType, Pattern pattern,
115 QStringView fileName, Qt::CaseSensitivity cs)
116{
117 const qsizetype patternLength = pattern.size();
118 if (!patternLength)
119 return false;
120 const qsizetype fileNameLength = fileName.size();
121
122 switch (patternType) {
123 case SuffixPattern: {
124 if (fileNameLength + 1 < patternLength)
125 return false;
126 // pattern is *.txt, skip the *
127 return fileName.endsWith(pattern.sliced(1), cs);
128 }
129 case PrefixPattern: {
130 if (fileNameLength + 1 < patternLength)
131 return false;
132 // pattern ends with *, stop just before
133 return fileName.startsWith(pattern.chopped(1), cs);
134 }
135 case LiteralPattern:
136 return pattern.compare(fileName, cs) == 0;
137 case VdrPattern: // "[0-9][0-9][0-9].vdr" case
138 return fileNameLength == 7
139 && fileName.at(0).isDigit() && fileName.at(1).isDigit() && fileName.at(2).isDigit()
140 && fileName.mid(3, 4).compare(".vdr"_L1, cs) == 0;
141 case AnimPattern: { // "*.anim[1-9j]" case
142 if (fileNameLength < 6)
143 return false;
144 QChar lastChar = fileName.at(fileNameLength - 1);
145 if (cs == Qt::CaseInsensitive)
146 lastChar = lastChar.toLower();
147 const bool lastCharOK = (lastChar.isDigit() && lastChar != u'0')
148 || lastChar == u'j';
149 return lastCharOK && fileName.mid(fileNameLength - 6, 5).compare(".anim"_L1, cs) == 0;
150 }
151 case OtherPattern:
152 break;
153 }
154 return false;
155}
156template bool QMimeGlobPattern::matchWithoutRegularExpression<QLatin1StringView>(
157 PatternType, QLatin1StringView, QStringView, Qt::CaseSensitivity);
158
159bool QMimeGlobPattern::matchFileName(const QString &fileName) const
160{
161 // "Applications MUST match globs case-insensitively, except when the case-sensitive
162 // attribute is set to true."
163
164#if QT_CONFIG(regularexpression)
165 // Other fallback patterns: slow but correct method
166 if (m_regExp)
167 return m_regExp->match(fileName).hasMatch();
168#endif
169 return matchWithoutRegularExpression(m_patternType, QStringView(m_pattern), fileName,
170 m_caseSensitivity);
171}
172
173static bool isSimplePattern(QStringView pattern)
174{
175 // starts with "*.", has no other '*'
176 return pattern.lastIndexOf(u'*') == 0
177 && pattern.size() > 1
178 && pattern.at(1) == u'.' // (other dots are OK, like *.tar.bz2)
179 // and contains no other special character
180 && !pattern.contains(u'?')
181 && !pattern.contains(u'[')
182 ;
183}
184
185static bool isFastPattern(QStringView pattern)
186{
187 // starts with "*.", has no other '*' and no other '.'
188 return pattern.lastIndexOf(u'*') == 0
189 && pattern.lastIndexOf(u'.') == 1
190 // and contains no other special character
191 && !pattern.contains(u'?')
192 && !pattern.contains(u'[')
193 ;
194}
195
197{
198 const QString &pattern = glob.pattern();
199 Q_ASSERT(!pattern.isEmpty());
200
201 // Store each patterns into either m_fastPatternDict (*.txt, *.html
202 // etc. with default weight 50) or for the rest, like core.*, *.tar.bz2, *~,
203 // into highWeightPatternOffset (>50) or lowWeightPatternOffset (<=50).
204
205 if (glob.weight() == 50 && isFastPattern(pattern) && !glob.isCaseSensitive()) {
206 // The bulk of the patterns is *.foo with weight 50 --> those go into the fast patterns hash.
207 const QString extension = pattern.mid(2).toLower();
208 QStringList &patterns = m_fastPatterns[extension]; // find or create
209 if (!patterns.contains(glob.mimeType()))
210 patterns.append(glob.mimeType());
211 } else {
212 if (glob.weight() > 50) {
213 if (!m_highWeightGlobs.hasPattern(glob.mimeType(), glob.pattern()))
214 m_highWeightGlobs.append(glob);
215 } else {
216 if (!m_lowWeightGlobs.hasPattern(glob.mimeType(), glob.pattern()))
217 m_lowWeightGlobs.append(glob);
218 }
219 }
220}
221
222void QMimeAllGlobPatterns::removeMimeType(const QString &mimeType)
223{
224 for (auto &x : m_fastPatterns)
225 x.removeAll(mimeType);
226 m_highWeightGlobs.removeMimeType(mimeType);
227 m_lowWeightGlobs.removeMimeType(mimeType);
228}
229
230void QMimeGlobPatternList::match(QMimeGlobMatchResult &result, const QString &fileName,
231 const AddMatchFilterFunc &filterFunc) const
232{
233 for (const QMimeGlobPattern &glob : *this) {
234 if (glob.matchFileName(fileName) && filterFunc(glob.mimeType())) {
235 const QString pattern = glob.pattern();
236 const qsizetype suffixLen = isSimplePattern(pattern) ? pattern.size() - strlen("*.") : 0;
237 result.addMatch(glob.mimeType(), glob.weight(), pattern, suffixLen);
238 }
239 }
240}
241
242void QMimeAllGlobPatterns::matchingGlobs(const QString &fileName, QMimeGlobMatchResult &result,
243 const AddMatchFilterFunc &filterFunc) const
244{
245 // First try the high weight matches (>50), if any.
246 m_highWeightGlobs.match(result, fileName, filterFunc);
247
248 // Now use the "fast patterns" dict, for simple *.foo patterns with weight 50
249 // (which is most of them, so this optimization is definitely worth it)
250 const qsizetype lastDot = fileName.lastIndexOf(u'.');
251 if (lastDot != -1) { // if no '.', skip the extension lookup
252 const qsizetype ext_len = fileName.size() - lastDot - 1;
253 const QString simpleExtension = fileName.right(ext_len).toLower();
254 // (toLower because fast patterns are always case-insensitive and saved as lowercase)
255
256 const QStringList matchingMimeTypes = m_fastPatterns.value(simpleExtension);
257 const QString simplePattern = "*."_L1 + simpleExtension;
258 for (const QString &mime : matchingMimeTypes) {
259 if (filterFunc(mime))
260 result.addMatch(mime, 50, simplePattern, simpleExtension.size());
261 }
262 // Can't return yet; *.tar.bz2 has to win over *.bz2, so we need the
263 // low-weight mimetypes anyway, at least those with weight 50.
264 }
265
266 // Finally, try the low weight matches (<=50)
267 m_lowWeightGlobs.match(result, fileName, filterFunc);
268}
269
271{
272 m_fastPatterns.clear();
273 m_highWeightGlobs.clear();
274 m_lowWeightGlobs.clear();
275}
276
277QT_END_NAMESPACE
Result of the globs parsing, as data structures ready for efficient MIME type matching.
void addGlob(const QMimeGlobPattern &glob)
void matchingGlobs(const QString &fileName, QMimeGlobMatchResult &result, const AddMatchFilterFunc &filterFunc) const
void removeMimeType(const QString &mimeType)
QMimeGlobPatternList m_highWeightGlobs
QMimeGlobPatternList m_lowWeightGlobs
void match(QMimeGlobMatchResult &result, const QString &fileName, const AddMatchFilterFunc &filterFunc) const
The QMimeGlobPattern class contains the glob pattern for file names for MIME type matching.
unsigned weight() const
bool matchFileName(const QString &fileName) const
Combined button and popup list for selecting options.
static bool isSimplePattern(QStringView pattern)
static bool isFastPattern(QStringView pattern)