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
qcssparser.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
5#include "qcssparser_p.h"
6
7#include <QtCore/qmap.h>
8#include <qdebug.h>
9#include <qicon.h>
10#include <qcolor.h>
11#include <qfont.h>
12#include <qfileinfo.h>
13#include <qfontmetrics.h>
14#include <qbrush.h>
15#include <qimagereader.h>
16#include <qtextformat.h>
17
18#include <QtCore/q20algorithm.h>
19
20#ifndef QT_NO_CSSPARSER
21
23
24using namespace Qt::StringLiterals;
25
26QT_IMPL_METATYPE_EXTERN_TAGGED(QCss::BackgroundData, QCss__BackgroundData)
27QT_IMPL_METATYPE_EXTERN_TAGGED(QCss::LengthData, QCss__LengthData)
28QT_IMPL_METATYPE_EXTERN_TAGGED(QCss::BorderData, QCss__BorderData)
29
30#include "qcssscanner.cpp"
31
32using namespace QCss;
33
34template <typename T>
36{
37 const char name[28];
38 T id;
39
40 struct ByName;
41};
42
43template <typename T>
44struct QCssKnownValue<T>::ByName
45{
46 constexpr bool operator()(const QCssKnownValue<T> &lhs, const QCssKnownValue<T> &rhs) const noexcept
47 { return std::string_view{lhs.name} < std::string_view{rhs.name}; }
48};
49#if !defined(Q_CC_GNU_ONLY) || Q_CC_GNU >= 1000
50# define NOT_OLD_GCCs(...) __VA_ARGS__
51#else
52# define NOT_OLD_GCCs(...) /* nothing */
53#endif
54#define CHECK_ARRAY_IS_SORTED(array, type)
55 NOT_OLD_GCCs(
56 static_assert(q20::is_sorted(std::begin(array), std::end(array),
57 QCssKnownValue<type>::ByName{}));
58 ) /* NOT_OLD_GCCs */
59 /* end */
60
61// This array is sorted alphabetically.
62static constexpr QCssKnownValue<Property> properties[] = {
63 { "-qt-background-role", Property::QtBackgroundRole },
64 { "-qt-block-indent", Property::QtBlockIndent },
65 { "-qt-fg-texture-cachekey", Property::QtForegroundTextureCacheKey },
66 { "-qt-foreground", Property::QtForeground },
67 { "-qt-line-height-type", Property::QtLineHeightType },
68 { "-qt-list-indent", Property::QtListIndent },
69 { "-qt-list-number-prefix", Property::QtListNumberPrefix },
70 { "-qt-list-number-suffix", Property::QtListNumberSuffix },
71 { "-qt-paragraph-type", Property::QtParagraphType },
72 { "-qt-stroke-color", Property::QtStrokeColor },
73 { "-qt-stroke-dasharray", Property::QtStrokeDashArray },
74 { "-qt-stroke-dashoffset", Property::QtStrokeDashOffset },
75 { "-qt-stroke-linecap", Property::QtStrokeLineCap },
76 { "-qt-stroke-linejoin", Property::QtStrokeLineJoin },
77 { "-qt-stroke-miterlimit", Property::QtStrokeMiterLimit },
78 { "-qt-stroke-width", Property::QtStrokeWidth },
79 { "-qt-style-features", Property::QtStyleFeatures },
80 { "-qt-table-type", Property::QtTableType },
81 { "-qt-user-state", Property::QtUserState },
82 { "accent-color", Property::QtAccent },
83 { "alternate-background-color", Property::QtAlternateBackground },
84 { "background", Property::Background },
85 { "background-attachment", Property::BackgroundAttachment },
86 { "background-clip", Property::BackgroundClip },
87 { "background-color", Property::BackgroundColor },
88 { "background-image", Property::BackgroundImage },
89 { "background-origin", Property::BackgroundOrigin },
90 { "background-position", Property::BackgroundPosition },
91 { "background-repeat", Property::BackgroundRepeat },
92 { "border", Property::Border },
93 { "border-bottom", Property::BorderBottom },
94 { "border-bottom-color", Property::BorderBottomColor },
95 { "border-bottom-left-radius", Property::BorderBottomLeftRadius },
96 { "border-bottom-right-radius", Property::BorderBottomRightRadius },
97 { "border-bottom-style", Property::BorderBottomStyle },
98 { "border-bottom-width", Property::BorderBottomWidth },
99 { "border-collapse", Property::BorderCollapse },
100 { "border-color", Property::BorderColor },
101 { "border-image", Property::BorderImage },
102 { "border-left", Property::BorderLeft },
103 { "border-left-color", Property::BorderLeftColor },
104 { "border-left-style", Property::BorderLeftStyle },
105 { "border-left-width", Property::BorderLeftWidth },
106 { "border-radius", Property::BorderRadius },
107 { "border-right", Property::BorderRight },
108 { "border-right-color", Property::BorderRightColor },
109 { "border-right-style", Property::BorderRightStyle },
110 { "border-right-width", Property::BorderRightWidth },
111 { "border-style", Property::BorderStyles },
112 { "border-top", Property::BorderTop },
113 { "border-top-color", Property::BorderTopColor },
114 { "border-top-left-radius", Property::BorderTopLeftRadius },
115 { "border-top-right-radius", Property::BorderTopRightRadius },
116 { "border-top-style", Property::BorderTopStyle },
117 { "border-top-width", Property::BorderTopWidth },
118 { "border-width", Property::BorderWidth },
119 { "bottom", Property::Bottom },
120 { "color", Property::Color },
121 { "float", Property::Float },
122 { "font", Property::Font },
123 { "font-family", Property::FontFamily },
124 { "font-kerning", Property::FontKerning },
125 { "font-size", Property::FontSize },
126 { "font-style", Property::FontStyle },
127 { "font-variant", Property::FontVariant },
128 { "font-weight", Property::FontWeight },
129 { "height", Property::Height },
130 { "icon", Property::QtIcon },
131 { "image", Property::QtImage },
132 { "image-position", Property::QtImageAlignment },
133 { "left", Property::Left },
134 { "letter-spacing", Property::LetterSpacing },
135 { "line-height", Property::LineHeight },
136 { "list-style", Property::ListStyle },
137 { "list-style-type", Property::ListStyleType },
138 { "margin", Property::Margin },
139 { "margin-bottom", Property::MarginBottom },
140 { "margin-left", Property::MarginLeft },
141 { "margin-right", Property::MarginRight },
142 { "margin-top", Property::MarginTop },
143 { "max-height", Property::MaximumHeight },
144 { "max-width", Property::MaximumWidth },
145 { "min-height", Property::MinimumHeight },
146 { "min-width", Property::MinimumWidth },
147 { "outline", Property::Outline },
148 { "outline-bottom-left-radius", Property::OutlineBottomLeftRadius },
149 { "outline-bottom-right-radius", Property::OutlineBottomRightRadius },
150 { "outline-color", Property::OutlineColor },
151 { "outline-offset", Property::OutlineOffset },
152 { "outline-radius", Property::OutlineRadius },
153 { "outline-style", Property::OutlineStyle },
154 { "outline-top-left-radius", Property::OutlineTopLeftRadius },
155 { "outline-top-right-radius", Property::OutlineTopRightRadius },
156 { "outline-width", Property::OutlineWidth },
157 { "padding", Property::Padding },
158 { "padding-bottom", Property::PaddingBottom },
159 { "padding-left", Property::PaddingLeft },
160 { "padding-right", Property::PaddingRight },
161 { "padding-top", Property::PaddingTop },
162 { "page-break-after", Property::PageBreakAfter },
163 { "page-break-before", Property::PageBreakBefore },
164 { "placeholder-text-color", Property::QtPlaceHolderText },
165 { "position", Property::Position },
166 { "right", Property::Right },
167 { "selection-background-color", Property::QtSelectionBackground },
168 { "selection-color", Property::QtSelectionForeground },
169 { "spacing", Property::QtSpacing },
170 { "subcontrol-origin", Property::QtOrigin },
171 { "subcontrol-position", Property::QtPosition },
172 { "text-align", Property::TextAlignment },
173 { "text-decoration", Property::TextDecoration },
174 { "text-decoration-color", Property::TextDecorationColor },
175 { "text-indent", Property::TextIndent },
176 { "text-transform", Property::TextTransform },
177 { "text-underline-style", Property::TextUnderlineStyle },
178 { "top", Property::Top },
179 { "vertical-align", Property::VerticalAlignment },
180 { "white-space", Property::Whitespace },
181 { "width", Property::Width },
182 { "word-spacing", Property::WordSpacing }
183};
184CHECK_ARRAY_IS_SORTED(properties, Property)
185
186static constexpr QCssKnownValue<KnownValue> values[] = {
187 { "accent", KnownValue::Accent },
188 { "active", KnownValue::Active },
189 { "alternate-base", KnownValue::AlternateBase },
190 { "always", KnownValue::Always },
191 { "auto", KnownValue::Auto },
192 { "base", KnownValue::Base },
193 { "beveljoin", KnownValue::BevelJoin},
194 { "bold", KnownValue::Bold },
195 { "bottom", KnownValue::Bottom },
196 { "bright-text", KnownValue::BrightText },
197 { "button", KnownValue::Button },
198 { "button-text", KnownValue::ButtonText },
199 { "center", KnownValue::Center },
200 { "circle", KnownValue::Circle },
201 { "dark", KnownValue::Dark },
202 { "dashed", KnownValue::Dashed },
203 { "decimal", KnownValue::Decimal },
204 { "disabled", KnownValue::Disabled },
205 { "disc", KnownValue::Disc },
206 { "dot-dash", KnownValue::DotDash },
207 { "dot-dot-dash", KnownValue::DotDotDash },
208 { "dotted", KnownValue::Dotted },
209 { "double", KnownValue::Double },
210 { "flatcap", KnownValue::FlatCap},
211 { "groove", KnownValue::Groove },
212 { "highlight", KnownValue::Highlight },
213 { "highlighted-text", KnownValue::HighlightedText },
214 { "inset", KnownValue::Inset },
215 { "italic", KnownValue::Italic },
216 { "large", KnownValue::Large },
217 { "left", KnownValue::Left },
218 { "light", KnownValue::Light },
219 { "line-through", KnownValue::LineThrough },
220 { "link", KnownValue::Link },
221 { "link-visited", KnownValue::LinkVisited },
222 { "lower-alpha", KnownValue::LowerAlpha },
223 { "lower-roman", KnownValue::LowerRoman },
224 { "lowercase", KnownValue::Lowercase },
225 { "medium", KnownValue::Medium },
226 { "mid", KnownValue::Mid },
227 { "middle", KnownValue::Middle },
228 { "midlight", KnownValue::Midlight },
229 { "miterjoin", KnownValue::MiterJoin},
230 { "native", KnownValue::Native },
231 { "no-role", KnownValue::NoRole },
232 { "none", KnownValue::None },
233 { "normal", KnownValue::Normal },
234 { "nowrap", KnownValue::NoWrap },
235 { "oblique", KnownValue::Oblique },
236 { "off", KnownValue::Off },
237 { "on", KnownValue::On },
238 { "outset", KnownValue::Outset },
239 { "overline", KnownValue::Overline },
240 { "placeholder-text", KnownValue::PlaceholderText },
241 { "pre", KnownValue::Pre },
242 { "pre-line", KnownValue::PreLine },
243 { "pre-wrap", KnownValue::PreWrap },
244 { "ridge", KnownValue::Ridge },
245 { "right", KnownValue::Right },
246 { "roundcap", KnownValue::RoundCap},
247 { "roundjoin", KnownValue::RoundJoin},
248 { "selected", KnownValue::Selected },
249 { "shadow", KnownValue::Shadow },
250 { "small" , KnownValue::Small },
251 { "small-caps", KnownValue::SmallCaps },
252 { "solid", KnownValue::Solid },
253 { "square", KnownValue::Square },
254 { "squarecap", KnownValue::SquareCap},
255 { "sub", KnownValue::Sub },
256 { "super", KnownValue::Super },
257 { "svgmiterjoin", KnownValue::SvgMiterJoin},
258 { "text", KnownValue::Text },
259 { "tooltip-base", KnownValue::ToolTipBase },
260 { "tooltip-text", KnownValue::ToolTipText },
261 { "top", KnownValue::Top },
262 { "transparent", KnownValue::Transparent },
263 { "underline", KnownValue::Underline },
264 { "upper-alpha", KnownValue::UpperAlpha },
265 { "upper-roman", KnownValue::UpperRoman },
266 { "uppercase", KnownValue::Uppercase },
267 { "wave", KnownValue::Wave },
268 { "window", KnownValue::Window },
269 { "window-text", KnownValue::WindowText },
270 { "x-large", KnownValue::XLarge },
271 { "xx-large", KnownValue::XXLarge }
272};
273CHECK_ARRAY_IS_SORTED(values, KnownValue)
274
275//Map id to strings as they appears in the 'values' array above
276static constexpr uchar indexOfId[] = {
277 0, 46, 54, 47, 55, 56, 63, 38, 29, 83, 84, 28, 48, 7, 76, 52,
278 32, 68, 69, 30, 58, 74, 8, 12, 43, 65, 21, 15, 19, 20, 22, 24,
279 57, 27, 51, 80, 40, 4, 3, 45, 75, 18, 13, 66, 16, 35, 77, 36,
280 78, 64, 79, 37, 67, 23, 59, 42, 6, 60, 70, 82, 10, 31, 41, 14,
281 39, 71, 9, 11, 5, 81, 62, 25, 26, 33, 34, 2, 44, 72, 73, 53,
282 0, 17, 1, 61, 50, 49 };
283
284static_assert(std::size(indexOfId) == std::size(values) + 1); // UnknownValue not in values array but in indexOfId
285
286QString Value::toString() const
287{
288 if (type == KnownIdentifier) {
289 return QLatin1StringView(values[indexOfId[variant.toInt()]].name);
290 } else {
291 return variant.toString();
292 }
293}
294
295static constexpr QCssKnownValue<quint64> pseudos[] = {
296 { "active", PseudoClass_Active },
297 { "adjoins-item", PseudoClass_Item },
298 { "alternate", PseudoClass_Alternate },
299 { "bottom", PseudoClass_Bottom },
300 { "checked", PseudoClass_Checked },
301 { "closable", PseudoClass_Closable },
302 { "closed", PseudoClass_Closed },
303 { "default", PseudoClass_Default },
304 { "disabled", PseudoClass_Disabled },
305 { "edit-focus", PseudoClass_EditFocus },
306 { "editable", PseudoClass_Editable },
307 { "enabled", PseudoClass_Enabled },
308 { "exclusive", PseudoClass_Exclusive },
309 { "first", PseudoClass_First },
310 { "flat", PseudoClass_Flat },
311 { "floatable", PseudoClass_Floatable },
312 { "focus", PseudoClass_Focus },
313 { "has-children", PseudoClass_Children },
314 { "has-siblings", PseudoClass_Sibling },
315 { "horizontal", PseudoClass_Horizontal },
316 { "hover", PseudoClass_Hover },
317 { "indeterminate" , PseudoClass_Indeterminate },
318 { "last", PseudoClass_Last },
319 { "left", PseudoClass_Left },
320 { "maximized", PseudoClass_Maximized },
321 { "middle", PseudoClass_Middle },
322 { "minimized", PseudoClass_Minimized },
323 { "movable", PseudoClass_Movable },
324 { "next-selected", PseudoClass_NextSelected },
325 { "no-frame", PseudoClass_Frameless },
326 { "non-exclusive", PseudoClass_NonExclusive },
327 { "off", PseudoClass_Unchecked },
328 { "on", PseudoClass_Checked },
329 { "only-one", PseudoClass_OnlyOne },
330 { "open", PseudoClass_Open },
331 { "pressed", PseudoClass_Pressed },
332 { "previous-selected", PseudoClass_PreviousSelected },
333 { "read-only", PseudoClass_ReadOnly },
334 { "right", PseudoClass_Right },
335 { "selected", PseudoClass_Selected },
336 { "top", PseudoClass_Top },
337 { "unchecked" , PseudoClass_Unchecked },
338 { "vertical", PseudoClass_Vertical },
339 { "window", PseudoClass_Window }
340};
341CHECK_ARRAY_IS_SORTED(pseudos, quint64)
342
343static constexpr QCssKnownValue<Origin> origins[] = {
344 { "border", Origin::Border },
345 { "content", Origin::Content },
346 { "margin", Origin::Margin }, // not in css
347 { "padding", Origin::Padding }
348};
349CHECK_ARRAY_IS_SORTED(origins, Origin)
350
351static constexpr QCssKnownValue<Repeat> repeats[] = {
352 { "no-repeat", Repeat::None },
353 { "repeat-x", Repeat::X },
354 { "repeat-xy", Repeat::XY },
355 { "repeat-y", Repeat::Y }
356};
357CHECK_ARRAY_IS_SORTED(repeats, Repeat)
358
359static constexpr QCssKnownValue<TileMode> tileModes[] = {
360 { "repeat", TileMode::Repeat },
361 { "round", TileMode::Round },
362 { "stretch", TileMode::Stretch },
363};
364CHECK_ARRAY_IS_SORTED(tileModes, TileMode)
365
366static constexpr QCssKnownValue<PositionMode> positions[] = {
367 { "absolute", PositionMode::Absolute },
368 { "fixed", PositionMode::Fixed },
369 { "relative", PositionMode::Relative },
370 { "static", PositionMode::Static }
371};
372CHECK_ARRAY_IS_SORTED(positions, PositionMode)
373
374static constexpr QCssKnownValue<Attachment> attachments[] = {
375 { "fixed", Attachment::Fixed },
376 { "scroll", Attachment::Scroll }
377};
378CHECK_ARRAY_IS_SORTED(attachments, Attachment)
379
380static constexpr QCssKnownValue<int> styleFeatures[] = {
381 { "background-color", StyleFeature_BackgroundColor },
382 { "background-gradient", StyleFeature_BackgroundGradient },
383 { "none", StyleFeature_None }
384};
385CHECK_ARRAY_IS_SORTED(styleFeatures, int)
386
387template <typename T>
388static bool operator<(const QString &name, const QCssKnownValue<T> &prop)
389{
390 return QString::compare(name, QLatin1StringView(prop.name), Qt::CaseInsensitive) < 0;
391}
392
393template <typename T>
394static bool operator<(const QCssKnownValue<T> &prop, const QString &name)
395{
396 return QString::compare(QLatin1StringView(prop.name), name, Qt::CaseInsensitive) < 0;
397}
398
399#undef CHECK_ARRAY_IS_SORTED
400#undef NOT_OLD_GCCs
401
402template <typename C>
403static auto findKnownValue(const QString &name, const C &arr)
404{
405 const auto *prop = std::lower_bound(std::begin(arr), std::end(arr), name);
406 if ((prop == std::end(arr)) || (name < *prop))
407 return static_cast<decltype(prop->id)>(0);
408 return prop->id;
409}
410
411static inline bool isInheritable(Property propertyId)
412{
413 switch (propertyId) {
414 case Property::Font:
430 return true;
431 default:
432 break;
433 }
434 return false;
435}
436
437///////////////////////////////////////////////////////////////////////////////
438// Value Extractor
439ValueExtractor::ValueExtractor(const QList<Declaration> &decls, const QPalette &pal)
440: declarations(decls), adjustment(0), fontExtracted(false), pal(pal)
441{
442}
443
444LengthData ValueExtractor::lengthValue(const Value& v)
445{
446 const QString str = v.variant.toString();
447 QStringView s(str);
448 LengthData data;
449 data.unit = LengthData::None;
450 if (s.endsWith(u"px", Qt::CaseInsensitive))
451 data.unit = LengthData::Px;
452 else if (s.endsWith(u"ex", Qt::CaseInsensitive))
453 data.unit = LengthData::Ex;
454 else if (s.endsWith(u"em", Qt::CaseInsensitive))
455 data.unit = LengthData::Em;
456
457 if (data.unit != LengthData::None)
458 s.chop(2);
459 else if (v.type == Value::Percentage)
460 data.unit = LengthData::Percent;
461
462 data.number = s.toDouble();
463 return data;
464}
465
466static int lengthValueFromData(const LengthData& data, const QFont& f)
467{
468 const int scale = (data.unit == LengthData::Ex ? QFontMetrics(f).xHeight()
469 : data.unit == LengthData::Em ? QFontMetrics(f).height() : 1);
470 // raised lower limit due to the implementation of qRound()
471 return qRound(qBound(double(INT_MIN) + 0.1, scale * data.number, double(INT_MAX)));
472}
473
474QTextLength ValueExtractor::textLength(const Declaration &decl)
475{
476 const LengthData data = lengthValue(decl.d->values.at(0));
477 if (data.unit == LengthData::Percent)
478 return QTextLength(QTextLength::PercentageLength, data.number);
479
480 return QTextLength(QTextLength::FixedLength, lengthValueFromData(data, f));
481}
482
483int ValueExtractor::lengthValue(const Declaration &decl)
484{
485 if (decl.d->parsed.isValid())
486 return lengthValueFromData(qvariant_cast<LengthData>(decl.d->parsed), f);
487 if (decl.d->values.size() < 1)
488 return 0;
489 LengthData data = lengthValue(decl.d->values.at(0));
490 decl.d->parsed = QVariant::fromValue<LengthData>(data);
491 return lengthValueFromData(data,f);
492}
493
494void ValueExtractor::lengthValues(const Declaration &decl, int *m)
495{
496 if (decl.d->parsed.isValid()) {
497 QList<QVariant> v = decl.d->parsed.toList();
498 Q_ASSERT(v.size() == 4);
499 for (int i = 0; i < 4; i++)
500 m[i] = lengthValueFromData(qvariant_cast<LengthData>(v.at(i)), f);
501 return;
502 }
503
504 LengthData datas[4];
505 int i;
506 for (i = 0; i < qMin(decl.d->values.size(), 4); i++)
507 datas[i] = lengthValue(decl.d->values[i]);
508
509 if (i == 0) {
510 LengthData zero = {0.0, LengthData::None};
511 datas[0] = datas[1] = datas[2] = datas[3] = zero;
512 } else if (i == 1) {
513 datas[3] = datas[2] = datas[1] = datas[0];
514 } else if (i == 2) {
515 datas[2] = datas[0];
516 datas[3] = datas[1];
517 } else if (i == 3) {
518 datas[3] = datas[1];
519 }
520
521 QList<QVariant> v;
522 v.reserve(4);
523 for (i = 0; i < 4; i++) {
524 v += QVariant::fromValue<LengthData>(datas[i]);
525 m[i] = lengthValueFromData(datas[i], f);
526 }
527 decl.d->parsed = std::move(v);
528}
529
530bool ValueExtractor::extractGeometry(int *w, int *h, int *minw, int *minh, int *maxw, int *maxh)
531{
532 extractFont();
533 bool hit = false;
534 for (const Declaration &decl : std::as_const(declarations)) {
535 switch (decl.d->propertyId) {
536 case Property::Width: *w = lengthValue(decl); break;
537 case Property::Height: *h = lengthValue(decl); break;
538 case Property::MinimumWidth: *minw = lengthValue(decl); break;
539 case Property::MinimumHeight: *minh = lengthValue(decl); break;
540 case Property::MaximumWidth: *maxw = lengthValue(decl); break;
541 case Property::MaximumHeight: *maxh = lengthValue(decl); break;
542 default: continue;
543 }
544 hit = true;
545 }
546
547 return hit;
548}
549
550bool ValueExtractor::extractPosition(int *left, int *top, int *right, int *bottom, QCss::Origin *origin,
551 Qt::Alignment *position, QCss::PositionMode *mode, Qt::Alignment *textAlignment)
552{
553 extractFont();
554 bool hit = false;
555 for (const Declaration &decl : std::as_const(declarations)) {
556 switch (decl.d->propertyId) {
557 case Property::Left: *left = lengthValue(decl); break;
558 case Property::Top: *top = lengthValue(decl); break;
559 case Property::Right: *right = lengthValue(decl); break;
560 case Property::Bottom: *bottom = lengthValue(decl); break;
561 case Property::QtOrigin: *origin = decl.originValue(); break;
562 case Property::QtPosition: *position = decl.alignmentValue(); break;
563 case Property::TextAlignment: *textAlignment = decl.alignmentValue(); break;
564 case Property::Position: *mode = decl.positionValue(); break;
565 default: continue;
566 }
567 hit = true;
568 }
569
570 return hit;
571}
572
573bool ValueExtractor::extractBox(int *margins, int *paddings, int *spacing)
574{
575 extractFont();
576 bool hit = false;
577 for (const Declaration &decl : std::as_const(declarations)) {
578 switch (decl.d->propertyId) {
579 case Property::PaddingLeft: paddings[LeftEdge] = lengthValue(decl); break;
580 case Property::PaddingRight: paddings[RightEdge] = lengthValue(decl); break;
581 case Property::PaddingTop: paddings[TopEdge] = lengthValue(decl); break;
582 case Property::PaddingBottom: paddings[BottomEdge] = lengthValue(decl); break;
583 case Property::Padding: lengthValues(decl, paddings); break;
584
585 case Property::MarginLeft: margins[LeftEdge] = lengthValue(decl); break;
586 case Property::MarginRight: margins[RightEdge] = lengthValue(decl); break;
587 case Property::MarginTop: margins[TopEdge] = lengthValue(decl); break;
588 case Property::MarginBottom: margins[BottomEdge] = lengthValue(decl); break;
589 case Property::Margin: lengthValues(decl, margins); break;
590 case Property::QtSpacing: if (spacing) *spacing = lengthValue(decl); break;
591
592 default: continue;
593 }
594 hit = true;
595 }
596
597 return hit;
598}
599
600int ValueExtractor::extractStyleFeatures() const
601{
602 int features = StyleFeature_None;
603 for (const Declaration &decl : declarations) {
604 if (decl.d->propertyId == Property::QtStyleFeatures)
605 features = decl.styleFeaturesValue();
606 }
607 return features;
608}
609
610QSize ValueExtractor::sizeValue(const Declaration &decl)
611{
612 if (decl.d->parsed.isValid()) {
613 QList<QVariant> v = decl.d->parsed.toList();
614 return QSize(lengthValueFromData(qvariant_cast<LengthData>(v.at(0)), f),
615 lengthValueFromData(qvariant_cast<LengthData>(v.at(1)), f));
616 }
617
618 LengthData x[2] = { {0, LengthData::None }, {0, LengthData::None} };
619 if (decl.d->values.size() > 0)
620 x[0] = lengthValue(decl.d->values.at(0));
621 if (decl.d->values.size() > 1)
622 x[1] = lengthValue(decl.d->values.at(1));
623 else
624 x[1] = x[0];
625 QList<QVariant> v;
626 v << QVariant::fromValue<LengthData>(x[0]) << QVariant::fromValue<LengthData>(x[1]);
627 decl.d->parsed = std::move(v);
628 return QSize(lengthValueFromData(x[0], f), lengthValueFromData(x[1], f));
629}
630
631void ValueExtractor::sizeValues(const Declaration &decl, QSize *radii)
632{
633 radii[0] = sizeValue(decl);
634 for (int i = 1; i < 4; i++)
635 radii[i] = radii[0];
636}
637
638bool ValueExtractor::extractBorder(int *borders, QBrush *colors, BorderStyle *styles,
639 QSize *radii)
640{
641 extractFont();
642 bool hit = false;
643 for (const Declaration &decl : std::as_const(declarations)) {
644 switch (decl.d->propertyId) {
645 case Property::BorderLeftWidth: borders[LeftEdge] = lengthValue(decl); break;
646 case Property::BorderRightWidth: borders[RightEdge] = lengthValue(decl); break;
647 case Property::BorderTopWidth: borders[TopEdge] = lengthValue(decl); break;
648 case Property::BorderBottomWidth: borders[BottomEdge] = lengthValue(decl); break;
649 case Property::BorderWidth: lengthValues(decl, borders); break;
650
651 case Property::BorderLeftColor: colors[LeftEdge] = decl.brushValue(pal); break;
652 case Property::BorderRightColor: colors[RightEdge] = decl.brushValue(pal); break;
653 case Property::BorderTopColor: colors[TopEdge] = decl.brushValue(pal); break;
654 case Property::BorderBottomColor: colors[BottomEdge] = decl.brushValue(pal); break;
655 case Property::BorderColor: decl.brushValues(colors, pal); break;
656
657 case Property::BorderTopStyle: styles[TopEdge] = decl.styleValue(); break;
658 case Property::BorderBottomStyle: styles[BottomEdge] = decl.styleValue(); break;
659 case Property::BorderLeftStyle: styles[LeftEdge] = decl.styleValue(); break;
660 case Property::BorderRightStyle: styles[RightEdge] = decl.styleValue(); break;
661 case Property::BorderStyles: decl.styleValues(styles); break;
662
663 case Property::BorderTopLeftRadius: radii[0] = sizeValue(decl); break;
664 case Property::BorderTopRightRadius: radii[1] = sizeValue(decl); break;
665 case Property::BorderBottomLeftRadius: radii[2] = sizeValue(decl); break;
666 case Property::BorderBottomRightRadius: radii[3] = sizeValue(decl); break;
667 case Property::BorderRadius: sizeValues(decl, radii); break;
668
669 case Property::BorderLeft:
670 borderValue(decl, &borders[LeftEdge], &styles[LeftEdge], &colors[LeftEdge]);
671 break;
672 case Property::BorderTop:
673 borderValue(decl, &borders[TopEdge], &styles[TopEdge], &colors[TopEdge]);
674 break;
675 case Property::BorderRight:
676 borderValue(decl, &borders[RightEdge], &styles[RightEdge], &colors[RightEdge]);
677 break;
678 case Property::BorderBottom:
679 borderValue(decl, &borders[BottomEdge], &styles[BottomEdge], &colors[BottomEdge]);
680 break;
681 case Property::Border:
682 borderValue(decl, &borders[LeftEdge], &styles[LeftEdge], &colors[LeftEdge]);
683 borders[TopEdge] = borders[RightEdge] = borders[BottomEdge] = borders[LeftEdge];
684 styles[TopEdge] = styles[RightEdge] = styles[BottomEdge] = styles[LeftEdge];
685 colors[TopEdge] = colors[RightEdge] = colors[BottomEdge] = colors[LeftEdge];
686 break;
687
688 default: continue;
689 }
690 hit = true;
691 }
692
693 return hit;
694}
695
696bool ValueExtractor::extractOutline(int *borders, QBrush *colors, BorderStyle *styles,
697 QSize *radii, int *offsets)
698{
699 extractFont();
700 bool hit = false;
701 for (const Declaration &decl : std::as_const(declarations)) {
702 switch (decl.d->propertyId) {
703 case Property::OutlineWidth: lengthValues(decl, borders); break;
704 case Property::OutlineColor: decl.brushValues(colors, pal); break;
705 case Property::OutlineStyle: decl.styleValues(styles); break;
706
707 case Property::OutlineTopLeftRadius: radii[0] = sizeValue(decl); break;
708 case Property::OutlineTopRightRadius: radii[1] = sizeValue(decl); break;
709 case Property::OutlineBottomLeftRadius: radii[2] = sizeValue(decl); break;
710 case Property::OutlineBottomRightRadius: radii[3] = sizeValue(decl); break;
711 case Property::OutlineRadius: sizeValues(decl, radii); break;
712 case Property::OutlineOffset: lengthValues(decl, offsets); break;
713
714 case Property::Outline:
715 borderValue(decl, &borders[LeftEdge], &styles[LeftEdge], &colors[LeftEdge]);
716 borders[TopEdge] = borders[RightEdge] = borders[BottomEdge] = borders[LeftEdge];
717 styles[TopEdge] = styles[RightEdge] = styles[BottomEdge] = styles[LeftEdge];
718 colors[TopEdge] = colors[RightEdge] = colors[BottomEdge] = colors[LeftEdge];
719 break;
720
721 default: continue;
722 }
723 hit = true;
724 }
725
726 return hit;
727}
728
729static Qt::Alignment parseAlignment(const QCss::Value *values, int count)
730{
731 Qt::Alignment a[2] = { { }, { } };
732 for (int i = 0; i < qMin(2, count); i++) {
733 if (values[i].type != Value::KnownIdentifier)
734 break;
735 switch (values[i].variant.value<KnownValue>()) {
736 case KnownValue::Left: a[i] = Qt::AlignLeft; break;
737 case KnownValue::Right: a[i] = Qt::AlignRight; break;
738 case KnownValue::Top: a[i] = Qt::AlignTop; break;
739 case KnownValue::Bottom: a[i] = Qt::AlignBottom; break;
740 case KnownValue::Center: a[i] = Qt::AlignCenter; break;
741 default: break;
742 }
743 }
744
745 if (a[0] == Qt::AlignCenter && a[1] != 0 && a[1] != Qt::AlignCenter)
746 a[0] = (a[1] == Qt::AlignLeft || a[1] == Qt::AlignRight) ? Qt::AlignVCenter : Qt::AlignHCenter;
747 if ((a[1] == 0 || a[1] == Qt::AlignCenter) && a[0] != Qt::AlignCenter)
748 a[1] = (a[0] == Qt::AlignLeft || a[0] == Qt::AlignRight) ? Qt::AlignVCenter : Qt::AlignHCenter;
749 return a[0] | a[1];
750}
751
753{
755 v.variant.convert(QMetaType::fromType<QColor>());
757 }
758
759 if (v.type == Value::Color)
760 return qvariant_cast<QColor>(v.variant);
761
762 if (v.type == Value::KnownIdentifier && v.variant.value<KnownValue>() == KnownValue::Transparent)
763 return QColor(Qt::transparent);
764
765 if (v.type != Value::Function)
766 return ColorData();
767
768 QStringList lst = v.variant.toStringList();
769 if (lst.size() != 2)
770 return ColorData();
771
772 const QString &identifier = lst.at(0);
773 if ((identifier.compare("palette"_L1, Qt::CaseInsensitive)) == 0) {
774 static_assert((int(KnownValue::LastColorRole) - int(KnownValue::FirstColorRole) + 1) == QPalette::ColorRole::NColorRoles);
775
776 const KnownValue role = findKnownValue(lst.at(1).trimmed(), values);
777 if (role >= KnownValue::FirstColorRole && role <= KnownValue::LastColorRole)
778 return (QPalette::ColorRole)(int(role) - int(KnownValue::FirstColorRole));
779
780 return ColorData();
781 }
782
783 const bool rgb = identifier.startsWith("rgb"_L1);
784 const bool hsv = !rgb && identifier.startsWith("hsv"_L1);
785 const bool hsl = !rgb && !hsv && identifier.startsWith("hsl"_L1);
786
787 if (!rgb && !hsv && !hsl)
788 return ColorData();
789
790 const bool hasAlpha = identifier.size() == 4 && identifier.at(3) == u'a';
791 if (identifier.size() > 3 && !hasAlpha)
792 return ColorData();
793
794 Parser p(lst.at(1));
795 if (!p.testExpr())
796 return ColorData();
797
798 QList<QCss::Value> colorDigits;
799 if (!p.parseExpr(&colorDigits))
800 return ColorData();
801 const int tokenCount = colorDigits.size();
802
803 for (int i = 0; i < qMin(tokenCount, 7); i += 2) {
804 if (colorDigits.at(i).type == Value::Percentage) {
805 const qreal maxRange = (rgb || i != 0) ? 255. : 359.;
806 colorDigits[i].variant = colorDigits.at(i).variant.toReal() * (maxRange / 100.);
807 colorDigits[i].type = Value::Number;
808 } else if (colorDigits.at(i).type != Value::Number) {
809 return ColorData();
810 }
811 }
812
813
814 if (tokenCount < 5)
815 return ColorData();
816
817 if (hasAlpha && tokenCount != 7) {
818 qWarning("QCssParser::parseColorValue: Specified color with alpha value but no alpha given: '%s'", qPrintable(lst.join(u' ')));
819 return ColorData();
820 }
821 if (!hasAlpha && tokenCount != 5) {
822 qWarning("QCssParser::parseColorValue: Specified color without alpha value but alpha given: '%s'", qPrintable(lst.join(u' ')));
823 return ColorData();
824 }
825
826 int v1 = colorDigits.at(0).variant.toInt();
827 int v2 = colorDigits.at(2).variant.toInt();
828 int v3 = colorDigits.at(4).variant.toInt();
829 int alpha = 255;
830 if (tokenCount == 7) {
831 int alphaValue = colorDigits.at(6).variant.toInt();
832 if (alphaValue <= 1)
833 alpha = colorDigits.at(6).variant.toReal() * 255.;
834 else
835 alpha = alphaValue;
836 }
837
838 if (rgb)
839 return QColor::fromRgb(v1, v2, v3, alpha);
840 if (hsv)
841 return QColor::fromHsv(v1, v2, v3, alpha);
842 return QColor::fromHsl(v1, v2, v3, alpha);
843}
844
845static QColor colorFromData(const ColorData& c, const QPalette &pal)
846{
847 if (c.type == ColorData::Color) {
848 return c.color;
849 } else if (c.type == ColorData::Role) {
850 return pal.color(c.role);
851 }
852 return QColor();
853}
854
855static BrushData parseBrushValue(const QCss::Value &v, const QPalette &pal)
856{
858 if (c.type == ColorData::Color) {
859 return QBrush(c.color);
860 } else if (c.type == ColorData::Role) {
861 return c.role;
862 }
863
864 if (v.type != Value::Function)
865 return BrushData();
866
867 QStringList lst = v.variant.toStringList();
868 if (lst.size() != 2)
869 return BrushData();
870
871 QStringList gradFuncs;
872 gradFuncs << "qlineargradient"_L1 << "qradialgradient"_L1 << "qconicalgradient"_L1 << "qgradient"_L1;
873 int gradType = -1;
874
875 if ((gradType = gradFuncs.indexOf(lst.at(0).toLower())) == -1)
876 return BrushData();
877
878 QHash<QString, qreal> vars;
879 QList<QGradientStop> stops;
880
881 int spread = -1;
882 QStringList spreads;
883 spreads << "pad"_L1 << "reflect"_L1 << "repeat"_L1;
884
885 int coordinateMode = -1;
886 QStringList coordinateModes;
887 coordinateModes << "logical"_L1 << "stretchtodevice"_L1 << "objectbounding"_L1 << "object"_L1;
888
889 bool dependsOnThePalette = false;
890 Parser parser(lst.at(1));
891 while (parser.hasNext()) {
892 parser.skipSpace();
893 if (!parser.test(IDENT))
894 return BrushData();
895 QString attr = parser.lexem();
896 parser.skipSpace();
897 if (!parser.test(COLON))
898 return BrushData();
899 parser.skipSpace();
900 if (attr.compare("stop"_L1, Qt::CaseInsensitive) == 0) {
901 QCss::Value stop, color;
902 parser.next();
903 if (!parser.parseTerm(&stop)) return BrushData();
904 parser.skipSpace();
905 parser.next();
906 if (!parser.parseTerm(&color)) return BrushData();
908 if (cd.type == ColorData::Role)
909 dependsOnThePalette = true;
910 stops.append(QGradientStop(stop.variant.toReal(), colorFromData(cd, pal)));
911 } else {
912 parser.next();
913 QCss::Value value;
914 (void)parser.parseTerm(&value);
915 if (attr.compare("spread"_L1, Qt::CaseInsensitive) == 0)
916 spread = spreads.indexOf(value.variant.toString());
917 else if (attr.compare("coordinatemode"_L1, Qt::CaseInsensitive) == 0)
918 coordinateMode = coordinateModes.indexOf(value.variant.toString());
919 else
920 vars[attr] = value.variant.toReal();
921 }
922 parser.skipSpace();
923 (void)parser.test(COMMA);
924 }
925
926 if (gradType == 0) {
927 QLinearGradient lg(vars.value("x1"_L1), vars.value("y1"_L1),
928 vars.value("x2"_L1), vars.value("y2"_L1));
929 lg.setCoordinateMode(coordinateMode < 0 ? QGradient::ObjectBoundingMode : QGradient::CoordinateMode(coordinateMode));
930 lg.setStops(stops);
931 if (spread != -1)
932 lg.setSpread(QGradient::Spread(spread));
933 BrushData bd = QBrush(lg);
934 if (dependsOnThePalette)
936 return bd;
937 }
938
939 if (gradType == 1) {
940 QRadialGradient rg(vars.value("cx"_L1), vars.value("cy"_L1),
941 vars.value("radius"_L1), vars.value("fx"_L1),
942 vars.value("fy"_L1));
943 rg.setCoordinateMode(coordinateMode < 0 ? QGradient::ObjectBoundingMode : QGradient::CoordinateMode(coordinateMode));
944 rg.setStops(stops);
945 if (spread != -1)
946 rg.setSpread(QGradient::Spread(spread));
947 BrushData bd = QBrush(rg);
948 if (dependsOnThePalette)
950 return bd;
951 }
952
953 if (gradType == 2) {
954 QConicalGradient cg(vars.value("cx"_L1), vars.value("cy"_L1), vars.value("angle"_L1));
955 cg.setCoordinateMode(coordinateMode < 0 ? QGradient::ObjectBoundingMode : QGradient::CoordinateMode(coordinateMode));
956 cg.setStops(stops);
957 if (spread != -1)
958 cg.setSpread(QGradient::Spread(spread));
959 BrushData bd = QBrush(cg);
960 if (dependsOnThePalette)
962 return bd;
963 }
964
965 return BrushData();
966}
967
968static QBrush brushFromData(const BrushData& c, const QPalette &pal)
969{
970 if (c.type == BrushData::Role) {
971 return pal.color(c.role);
972 } else {
973 return c.brush;
974 }
975}
976
978{
980 switch (v.variant.value<KnownValue>()) {
981 case KnownValue::None:
982 return BorderStyle::None;
984 return BorderStyle::Dotted;
986 return BorderStyle::Dashed;
988 return BorderStyle::Solid;
990 return BorderStyle::Double;
996 return BorderStyle::Groove;
998 return BorderStyle::Ridge;
1000 return BorderStyle::Inset;
1001 case KnownValue::Outset:
1002 return BorderStyle::Outset;
1003 case KnownValue::Native:
1004 return BorderStyle::Native;
1005 default:
1006 break;
1007 }
1008 }
1009 return BorderStyle::Unknown;
1010}
1011
1012void ValueExtractor::borderValue(const Declaration &decl, int *width, QCss::BorderStyle *style, QBrush *color)
1013{
1014 if (decl.d->parsed.isValid()) {
1015 BorderData data = qvariant_cast<BorderData>(decl.d->parsed);
1016 *width = lengthValueFromData(data.width, f);
1017 *style = data.style;
1018 *color = data.color.type != BrushData::Invalid ? brushFromData(data.color, pal) : QBrush(QColor());
1019 return;
1020 }
1021
1022 *width = 0;
1023 *style = BorderStyle::None;
1024 *color = QColor();
1025
1026 if (decl.d->values.isEmpty())
1027 return;
1028
1029 BorderData data;
1030 data.width.number = 0;
1031 data.width.unit = LengthData::None;
1032 data.style = BorderStyle::None;
1033
1034 int i = 0;
1035 if (decl.d->values.at(i).type == Value::Length || decl.d->values.at(i).type == Value::Number) {
1036 data.width = lengthValue(decl.d->values.at(i));
1037 *width = lengthValueFromData(data.width, f);
1038 if (++i >= decl.d->values.size()) {
1039 decl.d->parsed = QVariant::fromValue<BorderData>(data);
1040 return;
1041 }
1042 }
1043
1044 data.style = parseStyleValue(decl.d->values.at(i));
1045 if (data.style != BorderStyle::Unknown) {
1046 *style = data.style;
1047 if (++i >= decl.d->values.size()) {
1048 decl.d->parsed = QVariant::fromValue<BorderData>(data);
1049 return;
1050 }
1051 } else {
1052 data.style = BorderStyle::None;
1053 }
1054
1055 data.color = parseBrushValue(decl.d->values.at(i), pal);
1056 if (data.color.type != BrushData::Invalid) {
1057 *color = brushFromData(data.color, pal);
1058 if (data.color.type != BrushData::DependsOnThePalette)
1059 decl.d->parsed = QVariant::fromValue<BorderData>(data);
1060 }
1061}
1062
1063static void parseShorthandBackgroundProperty(const QList<QCss::Value> &values, BrushData *brush, QString *image, Repeat *repeat, Qt::Alignment *alignment, const QPalette &pal)
1064{
1065 *brush = BrushData();
1066 *image = QString();
1067 *repeat = Repeat::XY;
1068 *alignment = Qt::AlignTop | Qt::AlignLeft;
1069
1070 for (qsizetype i = 0; i < values.size(); ++i) {
1071 const QCss::Value &v = values.at(i);
1072 if (v.type == Value::Uri) {
1073 *image = v.variant.toString();
1074 continue;
1075 } else if (v.type == Value::KnownIdentifier && v.variant.value<KnownValue>() == KnownValue::None) {
1076 *image = QString();
1077 continue;
1078 } else if (v.type == Value::KnownIdentifier && v.variant.value<KnownValue>() == KnownValue::Transparent) {
1079 *brush = QBrush(Qt::transparent);
1080 }
1081
1082 const Repeat repeatAttempt = findKnownValue(v.variant.toString(), repeats);
1083 if (repeatAttempt != Repeat::Unknown) {
1084 *repeat = repeatAttempt;
1085 continue;
1086 }
1087
1088 if (v.type == Value::KnownIdentifier) {
1089 const int start = i;
1090 int count = 1;
1091 if (i < values.size() - 1
1092 && values.at(i + 1).type == Value::KnownIdentifier) {
1093 ++i;
1094 ++count;
1095 }
1096 Qt::Alignment a = parseAlignment(values.constData() + start, count);
1097 if (int(a) != 0) {
1098 *alignment = a;
1099 continue;
1100 }
1101 i -= count - 1;
1102 }
1103
1104 *brush = parseBrushValue(v, pal);
1105 }
1106}
1107
1108bool ValueExtractor::extractBackground(QBrush *brush, QString *image, Repeat *repeat,
1109 Qt::Alignment *alignment, Origin *origin, Attachment *attachment,
1110 Origin *clip) const
1111{
1112 bool hit = false;
1113 for (const Declaration &decl : declarations) {
1114 if (decl.d->values.isEmpty())
1115 continue;
1116 const QCss::Value &val = decl.d->values.at(0);
1117 switch (decl.d->propertyId) {
1118 case Property::BackgroundColor:
1119 *brush = decl.brushValue();
1120 break;
1121 case Property::BackgroundImage:
1122 if (val.type == Value::Uri)
1123 *image = val.variant.toString();
1124 break;
1125 case Property::BackgroundRepeat:
1126 if (decl.d->parsed.isValid()) {
1127 *repeat = decl.d->parsed.value<Repeat>();
1128 } else {
1129 *repeat = findKnownValue(val.variant.toString(), repeats);
1130 decl.d->parsed = QVariant::fromValue(*repeat);
1131 }
1132 break;
1133 case Property::BackgroundPosition:
1134 *alignment = decl.alignmentValue();
1135 break;
1136 case Property::BackgroundOrigin:
1137 *origin = decl.originValue();
1138 break;
1139 case Property::BackgroundClip:
1140 *clip = decl.originValue();
1141 break;
1142 case Property::Background:
1143 if (decl.d->parsed.isValid()) {
1144 BackgroundData data = qvariant_cast<BackgroundData>(decl.d->parsed);
1145 *brush = brushFromData(data.brush, pal);
1146 *image = data.image;
1147 *repeat = data.repeat;
1148 *alignment = data.alignment;
1149 } else {
1150 BrushData brushData;
1151 parseShorthandBackgroundProperty(decl.d->values, &brushData, image, repeat, alignment, pal);
1152 *brush = brushFromData(brushData, pal);
1153 if (brushData.type != BrushData::DependsOnThePalette) {
1154 BackgroundData data = { brushData, *image, *repeat, *alignment };
1155 decl.d->parsed = QVariant::fromValue<BackgroundData>(data);
1156 }
1157 }
1158 break;
1159 case Property::BackgroundAttachment:
1160 *attachment = decl.attachmentValue();
1161 break;
1162 default: continue;
1163 }
1164 hit = true;
1165 }
1166 return hit;
1167}
1168
1169static bool setFontSizeFromValue(QCss::Value value, QFont *font, int *fontSizeAdjustment)
1170{
1171 if (value.type == Value::KnownIdentifier) {
1172 bool valid = true;
1173 switch (value.variant.value<KnownValue>()) {
1174 case KnownValue::Small: *fontSizeAdjustment = -1; break;
1175 case KnownValue::Medium: *fontSizeAdjustment = 0; break;
1176 case KnownValue::Large: *fontSizeAdjustment = 1; break;
1177 case KnownValue::XLarge: *fontSizeAdjustment = 2; break;
1178 case KnownValue::XXLarge: *fontSizeAdjustment = 3; break;
1179 default: valid = false; break;
1180 }
1181 return valid;
1182 }
1183 if (value.type != Value::Length)
1184 return false;
1185
1186 bool valid = false;
1187 QString s = value.variant.toString();
1188 if (s.endsWith("pt"_L1, Qt::CaseInsensitive)) {
1189 s.chop(2);
1190 value.variant = std::move(s);
1191 if (value.variant.convert(QMetaType::fromType<qreal>())) {
1192 font->setPointSizeF(qBound(qreal(0), value.variant.toReal(), qreal(1 << 24) - 1));
1193 valid = true;
1194 }
1195 } else if (s.endsWith("px"_L1, Qt::CaseInsensitive)) {
1196 s.chop(2);
1197 value.variant = std::move(s);
1198 if (value.variant.convert(QMetaType::fromType<qreal>())) {
1199 font->setPixelSize(qBound(0, value.variant.toInt(), (1 << 24) - 1));
1200 valid = true;
1201 }
1202 }
1203 return valid;
1204}
1205
1206static bool setFontStyleFromValue(const QCss::Value &value, QFont *font)
1207{
1208 if (value.type != Value::KnownIdentifier)
1209 return false ;
1210 switch (value.variant.value<KnownValue>()) {
1211 case KnownValue::Normal: font->setStyle(QFont::StyleNormal); return true;
1212 case KnownValue::Italic: font->setStyle(QFont::StyleItalic); return true;
1213 case KnownValue::Oblique: font->setStyle(QFont::StyleOblique); return true;
1214 default: break;
1215 }
1216 return false;
1217}
1218
1219static bool setFontKerningFromValue(const QCss::Value &value, QFont *font)
1220{
1221 if (value.type != Value::KnownIdentifier)
1222 return false ;
1223 switch (value.variant.value<KnownValue>()) {
1224 case KnownValue::Normal: font->setKerning(true); return true;
1225 case KnownValue::None: font->setKerning(false); return true;
1226 case KnownValue::Auto: return true;
1227 default: break;
1228 }
1229 return false;
1230}
1231
1232static bool setFontWeightFromValue(const QCss::Value &value, QFont *font)
1233{
1234 if (value.type == Value::KnownIdentifier) {
1235 switch (value.variant.value<KnownValue>()) {
1236 case KnownValue::Normal: font->setWeight(QFont::Normal); return true;
1237 case KnownValue::Bold: font->setWeight(QFont::Bold); return true;
1238 default: break;
1239 }
1240 return false;
1241 }
1242 if (value.type != Value::Number)
1243 return false;
1244 // .toInt() would call qRound64() and might overflow the long long there
1245 font->setWeight(QFont::Weight(qRound(qBound(0.0, value.variant.toDouble(), 1001.0))));
1246 return true;
1247}
1248
1249/** \internal
1250 * parse the font family from the values (starting from index \a start)
1251 * and set it the \a font
1252 * The function returns \c true if a family was extracted.
1253 */
1254static bool setFontFamilyFromValues(const QList<QCss::Value> &values, QFont *font, int start = 0)
1255{
1256 QString family;
1257 QStringList families;
1258 bool shouldAddSpace = false;
1259 for (qsizetype i = start; i < values.size(); ++i) {
1260 const QCss::Value &v = values.at(i);
1262 families << family;
1263 family.clear();
1264 shouldAddSpace = false;
1265 continue;
1266 }
1267 const QString str = v.variant.toString();
1268 if (str.isEmpty())
1269 break;
1270 if (shouldAddSpace)
1271 family += u' ';
1272 family += str;
1273 shouldAddSpace = true;
1274 }
1275 if (!family.isEmpty())
1276 families << family;
1277 if (families.isEmpty())
1278 return false;
1279 font->setFamilies(families);
1280 return true;
1281}
1282
1283static void setTextDecorationFromValues(const QList<QCss::Value> &values, QFont *font)
1284{
1285 for (const QCss::Value &value : values) {
1286 if (value.type != Value::KnownIdentifier)
1287 continue;
1288 switch (value.variant.value<KnownValue>()) {
1289 case KnownValue::Underline: font->setUnderline(true); break;
1290 case KnownValue::Overline: font->setOverline(true); break;
1291 case KnownValue::LineThrough: font->setStrikeOut(true); break;
1292 case KnownValue::None:
1293 font->setUnderline(false);
1294 font->setOverline(false);
1295 font->setStrikeOut(false);
1296 break;
1297 default: break;
1298 }
1299 }
1300}
1301
1302static void setLetterSpacingFromValue(const QCss::Value &value, QFont *font)
1303{
1304 QString s = value.variant.toString();
1305 qreal val;
1306 bool ok = false;
1307 if (s.endsWith("em"_L1, Qt::CaseInsensitive)) {
1308 s.chop(2);
1309 val = s.toDouble(&ok);
1310 if (ok)
1311 font->setLetterSpacing(QFont::PercentageSpacing, (val + 1.0) * 100);
1312 } else if (s.endsWith("px"_L1, Qt::CaseInsensitive)) {
1313 s.chop(2);
1314 val = s.toDouble(&ok);
1315 if (ok)
1316 font->setLetterSpacing(QFont::AbsoluteSpacing, val);
1317 }
1318}
1319
1320static void setWordSpacingFromValue(const QCss::Value &value, QFont *font)
1321{
1322 QString s = value.variant.toString();
1323 if (s.endsWith("px"_L1, Qt::CaseInsensitive)) {
1324 s.chop(2);
1325 qreal val;
1326 bool ok = false;
1327 val = s.toDouble(&ok);
1328 if (ok)
1329 font->setWordSpacing(val);
1330 }
1331}
1332
1333static void parseShorthandFontProperty(const QList<QCss::Value> &values, QFont *font, int *fontSizeAdjustment)
1334{
1335 font->setStyle(QFont::StyleNormal);
1336 font->setWeight(QFont::Normal);
1337 *fontSizeAdjustment = -255;
1338
1339 int i = 0;
1340 while (i < values.size()) {
1341 if (setFontStyleFromValue(values.at(i), font)
1342 || setFontWeightFromValue(values.at(i), font))
1343 ++i;
1344 else
1345 break;
1346 }
1347
1348 if (i < values.size()) {
1349 setFontSizeFromValue(values.at(i), font, fontSizeAdjustment);
1350 ++i;
1351 }
1352
1353 if (i < values.size()) {
1354 setFontFamilyFromValues(values, font, i);
1355 }
1356}
1357
1358static void setFontVariantFromValue(const QCss::Value &value, QFont *font)
1359{
1360 if (value.type == Value::KnownIdentifier) {
1361 switch (value.variant.value<KnownValue>()) {
1362 case KnownValue::Normal: font->setCapitalization(QFont::MixedCase); break;
1363 case KnownValue::SmallCaps: font->setCapitalization(QFont::SmallCaps); break;
1364 default: break;
1365 }
1366 }
1367}
1368
1369static void setTextTransformFromValue(const QCss::Value &value, QFont *font)
1370{
1371 if (value.type == Value::KnownIdentifier) {
1372 switch (value.variant.value<KnownValue>()) {
1373 case KnownValue::None: font->setCapitalization(QFont::MixedCase); break;
1374 case KnownValue::Uppercase: font->setCapitalization(QFont::AllUppercase); break;
1375 case KnownValue::Lowercase: font->setCapitalization(QFont::AllLowercase); break;
1376 default: break;
1377 }
1378 }
1379}
1380
1381bool ValueExtractor::extractFont(QFont *font, int *fontSizeAdjustment)
1382{
1383 if (fontExtracted) {
1384 *font = f;
1385 *fontSizeAdjustment = adjustment;
1386 return fontExtracted == 1;
1387 }
1388
1389 bool hit = false;
1390 for (const Declaration &decl : std::as_const(declarations)) {
1391 if (decl.d->values.isEmpty())
1392 continue;
1393 const QCss::Value &val = decl.d->values.at(0);
1394 switch (decl.d->propertyId) {
1395 case Property::FontSize: setFontSizeFromValue(val, font, fontSizeAdjustment); break;
1396 case Property::FontStyle: setFontStyleFromValue(val, font); break;
1397 case Property::FontWeight: setFontWeightFromValue(val, font); break;
1398 case Property::FontFamily: setFontFamilyFromValues(decl.d->values, font); break;
1399 case Property::FontKerning: setFontKerningFromValue(val, font); break;
1400 case Property::TextDecoration: setTextDecorationFromValues(decl.d->values, font); break;
1401 case Property::Font: parseShorthandFontProperty(decl.d->values, font, fontSizeAdjustment); break;
1402 case Property::FontVariant: setFontVariantFromValue(val, font); break;
1403 case Property::TextTransform: setTextTransformFromValue(val, font); break;
1404 case Property::LetterSpacing: setLetterSpacingFromValue(val, font); break;
1405 case Property::WordSpacing: setWordSpacingFromValue(val, font); break;
1406 default: continue;
1407 }
1408 hit = true;
1409 }
1410
1411 f = *font;
1412 adjustment = *fontSizeAdjustment;
1413 fontExtracted = hit ? 1 : 2;
1414 return hit;
1415}
1416
1417bool ValueExtractor::extractPalette(QBrush *foreground,
1418 QBrush *selectedForeground,
1419 QBrush *selectedBackground,
1420 QBrush *alternateBackground,
1421 QBrush *placeHolderTextForeground,
1422 QBrush *accent) const
1423{
1424 bool hit = false;
1425 for (const Declaration &decl : declarations) {
1426 switch (decl.d->propertyId) {
1427 case Property::Color: *foreground = decl.brushValue(pal); break;
1428 case Property::QtSelectionForeground: *selectedForeground = decl.brushValue(pal); break;
1429 case Property::QtSelectionBackground: *selectedBackground = decl.brushValue(pal); break;
1430 case Property::QtAlternateBackground: *alternateBackground = decl.brushValue(pal); break;
1431 case Property::QtPlaceHolderText: *placeHolderTextForeground = decl.brushValue(pal); break;
1432 case Property::QtAccent: *accent = decl.brushValue(pal); break;
1433 default: continue;
1434 }
1435 hit = true;
1436 }
1437 return hit;
1438}
1439
1440void ValueExtractor::extractFont()
1441{
1442 if (fontExtracted)
1443 return;
1444 int dummy = -255;
1445 extractFont(&f, &dummy);
1446}
1447
1448bool ValueExtractor::extractImage(QIcon *icon, Qt::Alignment *a, QSize *size) const
1449{
1450 bool hit = false;
1451 for (const Declaration &decl : declarations) {
1452 switch (decl.d->propertyId) {
1453 case Property::QtImage:
1454 *icon = decl.iconValue();
1455 if (decl.d->values.size() > 0 && decl.d->values.at(0).type == Value::Uri) {
1456 // try to pull just the size from the image...
1457 QImageReader imageReader(decl.d->values.at(0).variant.toString());
1458 if ((*size = imageReader.size()).isNull()) {
1459 // but we'll have to load the whole image if the
1460 // format doesn't support just reading the size
1461 *size = imageReader.read().size();
1462 }
1463 }
1464 break;
1465 case Property::QtImageAlignment: *a = decl.alignmentValue(); break;
1466 default: continue;
1467 }
1468 hit = true;
1469 }
1470 return hit;
1471}
1472
1473bool ValueExtractor::extractIcon(QIcon *icon, QSize *size) const
1474{
1475 // Find last declaration that specifies an icon
1476 const auto declaration = std::find_if(
1477 declarations.rbegin(), declarations.rend(),
1478 [](const Declaration &decl) { return decl.d->propertyId == Property::QtIcon; });
1479 if (declaration == declarations.rend())
1480 return false;
1481
1482 *icon = declaration->iconValue();
1483
1484 // If the value contains a URI, try to get the size of the icon
1485 if (declaration->d->values.isEmpty())
1486 return true;
1487
1488 const auto &propertyValue = declaration->d->values.constFirst();
1489 if (propertyValue.type != Value::Uri)
1490 return true;
1491
1492 // First try to read just the size from the image without loading it
1493 const QString url(propertyValue.variant.toString());
1494 QImageReader imageReader(url);
1495 *size = imageReader.size();
1496 if (!size->isNull())
1497 return true;
1498
1499 // Get the size by loading the image instead
1500 *size = imageReader.read().size();
1501 return true;
1502}
1503
1504///////////////////////////////////////////////////////////////////////////////
1505// Declaration
1506QColor Declaration::colorValue(const QPalette &pal) const
1507{
1508 if (d->values.size() != 1)
1509 return QColor();
1510
1511 if (d->parsed.isValid()) {
1512 switch (d->parsed.typeId()) {
1513 case qMetaTypeId<QColor>():
1514 return qvariant_cast<QColor>(d->parsed);
1515 case qMetaTypeId<int>():
1516 return pal.color((QPalette::ColorRole)(d->parsed.toInt()));
1517 case qMetaTypeId<QList<QVariant>>():
1518 if (d->parsed.toList().size() == 1) {
1519 auto parsedList = d->parsed.toList();
1520 const auto &value = parsedList.at(0);
1521 return qvariant_cast<QColor>(value);
1522 }
1523 break;
1524 }
1525 }
1526
1527 ColorData color = parseColorValue(d->values.at(0));
1528 if (color.type == ColorData::Role) {
1529 d->parsed = QVariant::fromValue<int>(color.role);
1530 return pal.color((QPalette::ColorRole)(color.role));
1531 } else {
1532 d->parsed = QVariant::fromValue<QColor>(color.color);
1533 return color.color;
1534 }
1535}
1536
1537QBrush Declaration::brushValue(const QPalette &pal) const
1538{
1539 if (d->values.size() != 1)
1540 return QBrush();
1541
1542 if (d->parsed.isValid()) {
1543 if (d->parsed.userType() == QMetaType::QBrush)
1544 return qvariant_cast<QBrush>(d->parsed);
1545 if (d->parsed.userType() == QMetaType::Int)
1546 return pal.color((QPalette::ColorRole)(d->parsed.toInt()));
1547 }
1548
1549 BrushData data = parseBrushValue(d->values.at(0), pal);
1550
1551 if (data.type == BrushData::Role) {
1552 d->parsed = QVariant::fromValue<int>(data.role);
1553 return pal.color((QPalette::ColorRole)(data.role));
1554 } else {
1555 if (data.type != BrushData::DependsOnThePalette)
1556 d->parsed = QVariant::fromValue<QBrush>(data.brush);
1557 return data.brush;
1558 }
1559}
1560
1561void Declaration::brushValues(QBrush *c, const QPalette &pal) const
1562{
1563 int needParse = 0x1f; // bits 0..3 say if we should parse the corresponding value.
1564 // the bit 4 say we need to update d->parsed
1565 int i = 0;
1566 if (d->parsed.isValid()) {
1567 needParse = 0;
1568 Q_ASSERT(d->parsed.metaType() == QMetaType::fromType<QList<QVariant>>());
1569 QList<QVariant> v = d->parsed.toList();
1570 for (i = 0; i < qMin(v.size(), 4); i++) {
1571 if (v.at(i).userType() == QMetaType::QBrush) {
1572 c[i] = qvariant_cast<QBrush>(v.at(i));
1573 } else if (v.at(i).userType() == QMetaType::Int) {
1574 c[i] = pal.color((QPalette::ColorRole)(v.at(i).toInt()));
1575 } else {
1576 needParse |= (1<<i);
1577 }
1578 }
1579 }
1580 if (needParse != 0) {
1581 QList<QVariant> v;
1582 for (i = 0; i < qMin(d->values.size(), 4); i++) {
1583 if (!(needParse & (1<<i)))
1584 continue;
1585 BrushData data = parseBrushValue(d->values.at(i), pal);
1586 if (data.type == BrushData::Role) {
1587 v += QVariant::fromValue<int>(data.role);
1588 c[i] = pal.color((QPalette::ColorRole)(data.role));
1589 } else {
1590 if (data.type != BrushData::DependsOnThePalette) {
1591 v += QVariant::fromValue<QBrush>(data.brush);
1592 } else {
1593 v += QVariant();
1594 }
1595 c[i] = data.brush;
1596 }
1597 }
1598 if (needParse & 0x10)
1599 d->parsed = std::move(v);
1600 }
1601 if (i == 0) c[0] = c[1] = c[2] = c[3] = QBrush();
1602 else if (i == 1) c[3] = c[2] = c[1] = c[0];
1603 else if (i == 2) c[2] = c[0], c[3] = c[1];
1604 else if (i == 3) c[3] = c[1];
1605}
1606
1607bool Declaration::realValue(qreal *real, const char *unit) const
1608{
1609 if (d->values.size() != 1)
1610 return false;
1611 const Value &v = d->values.at(0);
1612 if (unit && v.type != Value::Length)
1613 return false;
1614 const QString str = v.variant.toString();
1615 QStringView s(str);
1616 if (unit) {
1617 const QLatin1StringView unitStr(unit);
1618 if (!s.endsWith(unitStr, Qt::CaseInsensitive))
1619 return false;
1620 s.chop(unitStr.size());
1621 }
1622 bool ok = false;
1623 qreal val = s.toDouble(&ok);
1624 if (ok)
1625 *real = val;
1626 return ok;
1627}
1628
1629static bool intValueHelper(const QCss::Value &v, int *i, const char *unit)
1630{
1631 if (unit && v.type != Value::Length)
1632 return false;
1633 const QString str = v.variant.toString();
1634 QStringView s(str);
1635 if (unit) {
1636 const QLatin1StringView unitStr(unit);
1637 if (!s.endsWith(unitStr, Qt::CaseInsensitive))
1638 return false;
1639 s.chop(unitStr.size());
1640 }
1641 bool ok = false;
1642 int val = s.toInt(&ok);
1643 if (ok)
1644 *i = val;
1645 return ok;
1646}
1647
1648bool Declaration::intValue(int *i, const char *unit) const
1649{
1650 if (d->values.size() != 1)
1651 return false;
1652 return intValueHelper(d->values.at(0), i, unit);
1653}
1654
1655QSize Declaration::sizeValue() const
1656{
1657 if (d->parsed.isValid())
1658 return qvariant_cast<QSize>(d->parsed);
1659
1660 int x[2] = { 0, 0 };
1661 const qsizetype count = d->values.size();
1662 for (qsizetype i = 0; i < count; ++i) {
1663 if (i > 1) {
1664 qWarning("QCssParser::sizeValue: Too many values provided");
1665 break;
1666 }
1667 const auto &value = d->values.at(i);
1668 const QString valueString = value.variant.toString();
1669 if (valueString.endsWith(u"pt", Qt::CaseInsensitive)) {
1670 intValueHelper(value, &x[i], "pt");
1671 // according to https://www.w3.org/TR/css3-values/#absolute-lengths
1672 // 1pt = 1/72th of 1 inch, and 1px = 1/96th of 1 inch
1673 x[i] = (x[i] * 72) / 96;
1674 } else {
1675 // by default we use 'px'
1676 intValueHelper(value, &x[i], "px");
1677 }
1678 }
1679 if (count == 1)
1680 x[1] = x[0];
1681 QSize size(x[0], x[1]);
1682 d->parsed = QVariant::fromValue<QSize>(size);
1683 return size;
1684}
1685
1686QRect Declaration::rectValue() const
1687{
1688 if (d->values.size() != 1)
1689 return QRect();
1690
1691 if (d->parsed.isValid())
1692 return qvariant_cast<QRect>(d->parsed);
1693
1694 const QCss::Value &v = d->values.at(0);
1695 if (v.type != Value::Function)
1696 return QRect();
1697 const QStringList func = v.variant.toStringList();
1698 if (func.size() != 2 || func.at(0).compare("rect"_L1) != 0)
1699 return QRect();
1700 const auto args = QStringView{func[1]}.split(u' ', Qt::SkipEmptyParts);
1701 if (args.size() != 4)
1702 return QRect();
1703 QRect rect(args[0].toInt(), args[1].toInt(), args[2].toInt(), args[3].toInt());
1704 d->parsed = QVariant::fromValue<QRect>(rect);
1705 return rect;
1706}
1707
1708void Declaration::colorValues(QColor *c, const QPalette &pal) const
1709{
1710 int i;
1711 if (d->parsed.isValid()) {
1712 QList<QVariant> v = d->parsed.toList();
1713 for (i = 0; i < qMin(d->values.size(), 4); i++) {
1714 if (v.at(i).userType() == QMetaType::QColor) {
1715 c[i] = qvariant_cast<QColor>(v.at(i));
1716 } else {
1717 c[i] = pal.color((QPalette::ColorRole)(v.at(i).toInt()));
1718 }
1719 }
1720 } else {
1721 QList<QVariant> v;
1722 for (i = 0; i < qMin(d->values.size(), 4); i++) {
1723 ColorData color = parseColorValue(d->values.at(i));
1724 if (color.type == ColorData::Role) {
1725 v += QVariant::fromValue<int>(color.role);
1726 c[i] = pal.color((QPalette::ColorRole)(color.role));
1727 } else {
1728 v += QVariant::fromValue<QColor>(color.color);
1729 c[i] = color.color;
1730 }
1731 }
1732 d->parsed = std::move(v);
1733 }
1734
1735 if (i == 0) c[0] = c[1] = c[2] = c[3] = QColor();
1736 else if (i == 1) c[3] = c[2] = c[1] = c[0];
1737 else if (i == 2) c[2] = c[0], c[3] = c[1];
1738 else if (i == 3) c[3] = c[1];
1739}
1740
1741BorderStyle Declaration::styleValue() const
1742{
1743 if (d->values.size() != 1)
1744 return BorderStyle::None;
1745 return parseStyleValue(d->values.at(0));
1746}
1747
1748void Declaration::styleValues(BorderStyle *s) const
1749{
1750 int i;
1751 for (i = 0; i < qMin(d->values.size(), 4); i++)
1752 s[i] = parseStyleValue(d->values.at(i));
1753 if (i == 0) s[0] = s[1] = s[2] = s[3] = BorderStyle::None;
1754 else if (i == 1) s[3] = s[2] = s[1] = s[0];
1755 else if (i == 2) s[2] = s[0], s[3] = s[1];
1756 else if (i == 3) s[3] = s[1];
1757}
1758
1759Repeat Declaration::repeatValue() const
1760{
1761 if (d->parsed.isValid())
1762 return static_cast<Repeat>(d->parsed.toInt());
1763 if (d->values.size() != 1)
1764 return Repeat::Unknown;
1765 Repeat v = findKnownValue(d->values.at(0).variant.toString(), repeats);
1766 d->parsed = QVariant::fromValue(v);
1767 return v;
1768}
1769
1770Origin Declaration::originValue() const
1771{
1772 if (d->parsed.isValid())
1773 return static_cast<Origin>(d->parsed.toInt());
1774 if (d->values.size() != 1)
1775 return Origin::Unknown;
1776 Origin v = findKnownValue(d->values.at(0).variant.toString(), origins);
1777 d->parsed = QVariant::fromValue(v);
1778 return v;
1779}
1780
1781PositionMode Declaration::positionValue() const
1782{
1783 if (d->parsed.isValid())
1784 return static_cast<PositionMode>(d->parsed.toInt());
1785 if (d->values.size() != 1)
1786 return PositionMode::Unknown;
1787 PositionMode v = findKnownValue(d->values.at(0).variant.toString(), positions);
1788 d->parsed = QVariant::fromValue(v);
1789 return v;
1790}
1791
1792Attachment Declaration::attachmentValue() const
1793{
1794 if (d->parsed.isValid())
1795 return static_cast<Attachment>(d->parsed.toInt());
1796 if (d->values.size() != 1)
1797 return Attachment::Unknown;
1798 Attachment v = findKnownValue(d->values.at(0).variant.toString(), attachments);
1799 d->parsed = QVariant::fromValue(v);
1800 return v;
1801}
1802
1803int Declaration::styleFeaturesValue() const
1804{
1805 Q_ASSERT(d->propertyId == Property::QtStyleFeatures);
1806 if (d->parsed.isValid())
1807 return d->parsed.toInt();
1808 int features = StyleFeature_None;
1809 for (const Value &value : std::as_const(d->values)) {
1810 features |= findKnownValue(value.variant.toString(), styleFeatures);
1811 }
1812 d->parsed = features;
1813 return features;
1814}
1815
1816QString Declaration::uriValue() const
1817{
1818 if (d->values.isEmpty() || d->values.at(0).type != Value::Uri)
1819 return QString();
1820 return d->values.at(0).variant.toString();
1821}
1822
1823Qt::Alignment Declaration::alignmentValue() const
1824{
1825 if (d->parsed.isValid())
1826 return Qt::Alignment(d->parsed.toInt());
1827 if (d->values.isEmpty() || d->values.size() > 2)
1828 return Qt::AlignLeft | Qt::AlignTop;
1829
1830 Qt::Alignment v = parseAlignment(d->values.constData(), d->values.size());
1831 d->parsed = int(v);
1832 return v;
1833}
1834
1835void Declaration::borderImageValue(QString *image, int *cuts,
1836 TileMode *h, TileMode *v) const
1837{
1838 const DeclarationData *d = this->d.data(); // make it const and shadow d
1839 *image = uriValue();
1840 for (int i = 0; i < 4; i++)
1841 cuts[i] = -1;
1842 *h = *v = TileMode::Stretch;
1843
1844 if (d->values.size() < 2)
1845 return;
1846
1847 if (d->values.at(1).type == Value::Number) { // cuts!
1848 int i;
1849 for (i = 0; i < qMin(d->values.size()-1, 4); i++) {
1850 const Value& v = d->values.at(i+1);
1851 if (v.type != Value::Number)
1852 break;
1853 cuts[i] = v.variant.toString().toInt();
1854 if (cuts[i] < 0) {
1855 qWarning("Declaration::borderImageValue: Invalid cut value %d at position %d",
1856 cuts[i], i);
1857 cuts[0] = cuts[1] = cuts[2] = cuts[3] = -1;
1858 i = 4;
1859 break;
1860 }
1861 }
1862 if (i == 0) cuts[0] = cuts[1] = cuts[2] = cuts[3] = 0;
1863 else if (i == 1) cuts[3] = cuts[2] = cuts[1] = cuts[0];
1864 else if (i == 2) cuts[2] = cuts[0], cuts[3] = cuts[1];
1865 else if (i == 3) cuts[3] = cuts[1];
1866 }
1867
1868 if (d->values.last().type == Value::Identifier) {
1869 *v = findKnownValue(d->values.last().variant.toString(), tileModes);
1870 }
1871 if (d->values[d->values.size() - 2].type == Value::Identifier) {
1872 *h = findKnownValue(d->values[d->values.size()-2].variant.toString(), tileModes);
1873 } else
1874 *h = *v;
1875}
1876
1877bool Declaration::borderCollapseValue() const
1878{
1879 if (d->values.size() != 1)
1880 return false;
1881 else
1882 return d->values.at(0).toString() == "collapse"_L1;
1883}
1884
1885QList<qreal> Declaration::dashArray() const
1886{
1887 if (d->propertyId != Property::QtStrokeDashArray || d->values.empty())
1888 return QList<qreal>();
1889
1890 bool isValid = true;
1891 QList<qreal> dashes;
1892 for (qsizetype i = 0; i < d->values.size(); i++) {
1893 const Value &v = d->values[i];
1894 // Separators must be at odd indices and Numbers at even indices.
1895 bool isValidSeparator = (i & 1) && v.type == Value::TermOperatorComma;
1896 bool isValidNumber = !(i & 1) && v.type == Value::Number;
1897 if (!isValidNumber && !isValidSeparator) {
1898 isValid = false;
1899 break;
1900 } else if (isValidNumber) {
1901 bool ok;
1902 dashes.append(v.variant.toReal(&ok));
1903 if (!ok) {
1904 isValid = false;
1905 break;
1906 }
1907 }
1908 }
1909
1910 isValid &= !(dashes.size() & 1);
1911 return isValid ? dashes : QList<qreal>();
1912}
1913
1914QIcon Declaration::iconValue() const
1915{
1916 if (d->parsed.isValid())
1917 return qvariant_cast<QIcon>(d->parsed);
1918
1919 QIcon icon;
1920 for (qsizetype i = 0; i < d->values.size();) {
1921 const Value &value = d->values.at(i++);
1922 if (value.type != Value::Uri)
1923 break;
1924 QString uri = value.variant.toString();
1925 QIcon::Mode mode = QIcon::Normal;
1926 QIcon::State state = QIcon::Off;
1927 for (int j = 0; j < 2; j++) {
1928 if (i != d->values.size() && d->values.at(i).type == Value::KnownIdentifier) {
1929 switch (d->values.at(i).variant.value<KnownValue>()) {
1930 case KnownValue::Disabled: mode = QIcon::Disabled; break;
1931 case KnownValue::Active: mode = QIcon::Active; break;
1932 case KnownValue::Selected: mode = QIcon::Selected; break;
1933 case KnownValue::Normal: mode = QIcon::Normal; break;
1934 case KnownValue::On: state = QIcon::On; break;
1935 case KnownValue::Off: state = QIcon::Off; break;
1936 default: break;
1937 }
1938 ++i;
1939 } else {
1940 break;
1941 }
1942 }
1943
1944 // QIcon is soo broken
1945 if (icon.isNull())
1946 icon = QIcon(uri);
1947 else
1948 icon.addPixmap(uri, mode, state);
1949
1950 if (i == d->values.size())
1951 break;
1952
1953 if (d->values.at(i).type == Value::TermOperatorComma)
1954 i++;
1955 }
1956
1957 d->parsed = QVariant::fromValue<QIcon>(icon);
1958 return icon;
1959}
1960
1961///////////////////////////////////////////////////////////////////////////////
1962// Selector
1963int Selector::specificity() const
1964{
1965 int val = 0;
1966 for (const BasicSelector &sel : basicSelectors) {
1967 if (!sel.elementName.isEmpty())
1968 val += 1;
1969
1970 val += (sel.pseudos.size() + sel.attributeSelectors.size()) * 0x10;
1971 val += sel.ids.size() * 0x100;
1972 }
1973 return val;
1974}
1975
1976QString Selector::pseudoElement() const
1977{
1978 const BasicSelector& bs = basicSelectors.last();
1979 if (!bs.pseudos.isEmpty() && bs.pseudos.at(0).type == PseudoClass_Unknown)
1980 return bs.pseudos.at(0).name;
1981 return QString();
1982}
1983
1984quint64 Selector::pseudoClass(quint64 *negated) const
1985{
1986 const BasicSelector& bs = basicSelectors.last();
1987 if (bs.pseudos.isEmpty())
1988 return PseudoClass_Unspecified;
1989 quint64 pc = PseudoClass_Unknown;
1990 for (int i = !pseudoElement().isEmpty(); i < bs.pseudos.size(); i++) {
1991 const Pseudo &pseudo = bs.pseudos.at(i);
1992 if (pseudo.type == PseudoClass_Unknown)
1993 return PseudoClass_Unknown;
1994 if (!pseudo.negated)
1995 pc |= pseudo.type;
1996 else if (negated)
1997 *negated |= pseudo.type;
1998 }
1999 return pc;
2000}
2001
2002///////////////////////////////////////////////////////////////////////////////
2003// StyleSheet
2004void StyleSheet::buildIndexes(Qt::CaseSensitivity nameCaseSensitivity)
2005{
2006 QList<StyleRule> universals;
2007 for (qsizetype i = 0; i < styleRules.size(); ++i) {
2008 const StyleRule &rule = styleRules.at(i);
2009 QList<Selector> universalsSelectors;
2010 for (const Selector &selector : rule.selectors) {
2011
2012 if (selector.basicSelectors.isEmpty())
2013 continue;
2014
2015 if (selector.basicSelectors.at(0).relationToNext == BasicSelector::NoRelation) {
2016 if (selector.basicSelectors.size() != 1)
2017 continue;
2018 } else if (selector.basicSelectors.size() <= 1) {
2019 continue;
2020 }
2021
2022 const BasicSelector &sel = selector.basicSelectors.at(selector.basicSelectors.size() - 1);
2023
2024 if (!sel.ids.isEmpty()) {
2025 StyleRule nr;
2026 nr.selectors += selector;
2027 nr.declarations = rule.declarations;
2028 nr.order = i;
2029 idIndex.insert(sel.ids.at(0), nr);
2030 } else if (!sel.elementName.isEmpty()) {
2031 StyleRule nr;
2032 nr.selectors += selector;
2033 nr.declarations = rule.declarations;
2034 nr.order = i;
2035 QString name = sel.elementName;
2036 if (nameCaseSensitivity == Qt::CaseInsensitive)
2037 name = std::move(name).toLower();
2038 nameIndex.insert(name, nr);
2039 } else {
2040 universalsSelectors += selector;
2041 }
2042 }
2043 if (!universalsSelectors.isEmpty()) {
2044 StyleRule nr;
2045 nr.selectors = universalsSelectors;
2046 nr.declarations = rule.declarations;
2047 nr.order = i;
2048 universals << nr;
2049 }
2050 }
2051 styleRules = universals;
2052}
2053
2054///////////////////////////////////////////////////////////////////////////////
2055// StyleSelector
2056StyleSelector::~StyleSelector()
2057{
2058}
2059
2060bool StyleSelector::nodeNameEquals(NodePtr node, const QString& nodeName) const
2061{
2062 return nodeNames(node).contains(nodeName, nameCaseSensitivity);
2063}
2064
2065QStringList StyleSelector::nodeIds(NodePtr node) const
2066{
2067 return QStringList(attributeValue(node, QCss::AttributeSelector{"id"_L1, {}, AttributeSelector::NoMatch}));
2068}
2069
2070bool StyleSelector::selectorMatches(const Selector &selector, NodePtr node) const
2071{
2072 if (selector.basicSelectors.isEmpty())
2073 return false;
2074
2075 if (selector.basicSelectors.at(0).relationToNext == BasicSelector::NoRelation) {
2076 if (selector.basicSelectors.size() != 1)
2077 return false;
2078 return basicSelectorMatches(selector.basicSelectors.at(0), node);
2079 }
2080 if (selector.basicSelectors.size() <= 1)
2081 return false;
2082
2083 qsizetype i = selector.basicSelectors.size() - 1;
2084 node = duplicateNode(node);
2085 bool match = true;
2086
2087 BasicSelector sel = selector.basicSelectors.at(i);
2088 do {
2089 match = basicSelectorMatches(sel, node);
2090 if (!match) {
2091 if (i == selector.basicSelectors.size() - 1) // first element must always match!
2092 break;
2093 if (sel.relationToNext != BasicSelector::MatchNextSelectorIfAncestor &&
2094 sel.relationToNext != BasicSelector::MatchNextSelectorIfIndirectAdjecent)
2095 break;
2096 }
2097
2098 if (match || (sel.relationToNext != BasicSelector::MatchNextSelectorIfAncestor &&
2099 sel.relationToNext != BasicSelector::MatchNextSelectorIfIndirectAdjecent))
2100 --i;
2101
2102 if (i < 0)
2103 break;
2104
2105 sel = selector.basicSelectors.at(i);
2106 if (sel.relationToNext == BasicSelector::MatchNextSelectorIfAncestor
2107 || sel.relationToNext == BasicSelector::MatchNextSelectorIfParent) {
2108
2109 NodePtr nextParent = parentNode(node);
2110 freeNode(node);
2111 node = nextParent;
2112 } else if (sel.relationToNext == BasicSelector::MatchNextSelectorIfDirectAdjecent
2113 || sel.relationToNext == BasicSelector::MatchNextSelectorIfIndirectAdjecent) {
2114 NodePtr previousSibling = previousSiblingNode(node);
2115 freeNode(node);
2116 node = previousSibling;
2117 }
2118 if (isNullNode(node)) {
2119 match = false;
2120 break;
2121 }
2122 } while (i >= 0 && (match || sel.relationToNext == BasicSelector::MatchNextSelectorIfAncestor
2123 || sel.relationToNext == BasicSelector::MatchNextSelectorIfIndirectAdjecent));
2124
2125 freeNode(node);
2126
2127 return match;
2128}
2129
2130bool StyleSelector::basicSelectorMatches(const BasicSelector &sel, NodePtr node) const
2131{
2132 if (!sel.attributeSelectors.isEmpty()) {
2133 if (!hasAttributes(node))
2134 return false;
2135
2136 for (const QCss::AttributeSelector &a : sel.attributeSelectors) {
2137
2138 const QString attrValue = attributeValue(node, a);
2139 if (attrValue.isNull())
2140 return false;
2141
2142 switch (a.valueMatchCriterium) {
2143 case QCss::AttributeSelector::NoMatch:
2144 break;
2145 case QCss::AttributeSelector::MatchEqual:
2146 if (attrValue != a.value)
2147 return false;
2148 break;
2149 case QCss::AttributeSelector::MatchIncludes: {
2150 const auto lst = QStringView{attrValue}.tokenize(u' ');
2151 bool found = false;
2152 for (auto s : lst) {
2153 if (s == a.value) {
2154 found = true;
2155 break;
2156 }
2157 }
2158 if (!found)
2159 return false;
2160 break;
2161 }
2162 case QCss::AttributeSelector::MatchDashMatch: {
2163 const QString dashPrefix = a.value + u'-';
2164 if (attrValue != a.value && !attrValue.startsWith(dashPrefix))
2165 return false;
2166 break;
2167 }
2168 case QCss::AttributeSelector::MatchBeginsWith:
2169 if (!attrValue.startsWith(a.value))
2170 return false;
2171 break;
2172 case QCss::AttributeSelector::MatchEndsWith:
2173 if (!attrValue.endsWith(a.value))
2174 return false;
2175 break;
2176 case QCss::AttributeSelector::MatchContains:
2177 if (!attrValue.contains(a.value))
2178 return false;
2179 break;
2180 }
2181 }
2182 }
2183
2184 if (!sel.elementName.isEmpty()
2185 && !nodeNameEquals(node, sel.elementName))
2186 return false;
2187
2188 if (!sel.ids.isEmpty()
2189 && sel.ids != nodeIds(node))
2190 return false;
2191
2192 return true;
2193}
2194
2195void StyleSelector::matchRule(NodePtr node, const StyleRule &rule, StyleSheetOrigin origin,
2196 int depth, std::multimap<uint64_t, StyleRule> *weightedRules) const
2197{
2198 for (const Selector &selector : rule.selectors) {
2199 if (selectorMatches(selector, node)) {
2200 if (uint32_t(rule.order) >= 0x100000ULL)
2201 qWarning("StyleSelector: rule order is to large - style sheet"
2202 "must not contain more than 0x100000 entries");
2203 if (uint32_t(selector.specificity()) >= 0x100000ULL)
2204 qWarning("StyleSelector: selector specifity is to large - "
2205 "style sheet must not contain more than 0x100000 selectors "
2206 "per widget type");
2207 const uint64_t weight = rule.order
2208 + selector.specificity() * 0x100000ULL
2209 + (uint(origin) + depth) * 0x10000000000ULL;
2210 StyleRule newRule = rule;
2211 if (rule.selectors.size() > 1)
2212 newRule.selectors = { selector };
2213
2214 //We might have rules with the same weight if they came from a rule with several selectors
2215 weightedRules->emplace(weight, std::move(newRule));
2216 }
2217 }
2218}
2219
2220// Returns style rules that are in ascending order of specificity
2221// Each of the StyleRule returned will contain exactly one Selector
2222QList<StyleRule> StyleSelector::styleRulesForNode(NodePtr node)
2223{
2224 QList<StyleRule> rules;
2225 if (styleSheets.isEmpty())
2226 return rules;
2227
2228 std::multimap<uint64_t, StyleRule> weightedRules; // (spec, rule) that will be sorted below
2229
2230 //prune using indexed stylesheet
2231 for (const StyleSheet &styleSheet : std::as_const(styleSheets)) {
2232 for (const StyleRule &styleRule : styleSheet.styleRules)
2233 matchRule(node, styleRule, styleSheet.origin, styleSheet.depth, &weightedRules);
2234
2235 if (!styleSheet.idIndex.isEmpty()) {
2236 const QStringList ids = nodeIds(node);
2237 for (const QString &key : ids) {
2238 auto it = styleSheet.idIndex.constFind(key);
2239 while (it != styleSheet.idIndex.constEnd() && it.key() == key) {
2240 matchRule(node, it.value(), styleSheet.origin, styleSheet.depth, &weightedRules);
2241 ++it;
2242 }
2243 }
2244 }
2245 if (!styleSheet.nameIndex.isEmpty()) {
2246 const QStringList names = nodeNames(node);
2247 for (QString name : names) {
2248 if (nameCaseSensitivity == Qt::CaseInsensitive)
2249 name = std::move(name).toLower();
2250 auto it = styleSheet.nameIndex.constFind(name);
2251 while (it != styleSheet.nameIndex.constEnd() && it.key() == name) {
2252 matchRule(node, it.value(), styleSheet.origin, styleSheet.depth, &weightedRules);
2253 ++it;
2254 }
2255 }
2256 }
2257 if (!medium.isEmpty()) {
2258 for (const MediaRule &mediaRule : styleSheet.mediaRules) {
2259 if (mediaRule.media.contains(medium, Qt::CaseInsensitive)) {
2260 for (const StyleRule &styleRule : mediaRule.styleRules) {
2261 matchRule(node, styleRule, styleSheet.origin,
2262 styleSheet.depth, &weightedRules);
2263 }
2264 }
2265 }
2266 }
2267 }
2268
2269 rules.reserve(weightedRules.size());
2270 for (const auto &weigthedRule : weightedRules)
2271 rules.push_back(std::move(weigthedRule.second));
2272
2273 return rules;
2274}
2275
2276// for qtexthtmlparser which requires just the declarations with Enabled state
2277// and without pseudo elements
2278QList<Declaration> StyleSelector::declarationsForNode(NodePtr node, const char *extraPseudo)
2279{
2280 QList<Declaration> decls;
2281 const QList<StyleRule> rules = styleRulesForNode(node);
2282 for (const StyleRule &styleRule : rules) {
2283 const Selector &selector = styleRule.selectors.at(0);
2284 const QString pseudoElement = selector.pseudoElement();
2285
2286 if (extraPseudo && pseudoElement == QLatin1StringView(extraPseudo)) {
2287 decls += styleRule.declarations;
2288 continue;
2289 }
2290
2291 if (!pseudoElement.isEmpty()) // skip rules with pseudo elements
2292 continue;
2293 quint64 pseudoClass = selector.pseudoClass();
2294 if (pseudoClass == PseudoClass_Enabled || pseudoClass == PseudoClass_Unspecified)
2295 decls += styleRule.declarations;
2296 }
2297 return decls;
2298}
2299
2300static inline bool isHexDigit(const char c)
2301{
2302 return (c >= '0' && c <= '9')
2303 || (c >= 'a' && c <= 'f')
2304 || (c >= 'A' && c <= 'F')
2305 ;
2306}
2307
2308QString Scanner::preprocess(const QString &input, bool *hasEscapeSequences)
2309{
2310 QString output = input;
2311
2312 if (hasEscapeSequences)
2313 *hasEscapeSequences = false;
2314
2315 int i = 0;
2316 while (i < output.size()) {
2317 if (output.at(i) == u'\\') {
2318
2319 ++i;
2320 // test for unicode hex escape
2321 int hexCount = 0;
2322 const int hexStart = i;
2323 while (i < output.size()
2324 && isHexDigit(output.at(i).toLatin1())
2325 && hexCount < 7) {
2326 ++hexCount;
2327 ++i;
2328 }
2329 if (hexCount == 0) {
2330 if (hasEscapeSequences)
2331 *hasEscapeSequences = true;
2332 continue;
2333 }
2334
2335 hexCount = qMin(hexCount, 6);
2336 bool ok = false;
2337 const char16_t code = QStringView{output}.mid(hexStart, hexCount).toUShort(&ok, 16);
2338 if (ok) {
2339 output.replace(hexStart - 1, hexCount + 1, code);
2340 i = hexStart;
2341 } else {
2342 i = hexStart;
2343 }
2344 } else {
2345 ++i;
2346 }
2347 }
2348 return output;
2349}
2350
2351int QCssScanner_Generated::handleCommentStart()
2352{
2353 while (pos < input.size() - 1) {
2354 if (input.at(pos) == u'*' && input.at(pos + 1) == u'/') {
2355 pos += 2;
2356 break;
2357 }
2358 ++pos;
2359 }
2360 return S;
2361}
2362
2363void Scanner::scan(const QString &preprocessedInput, QList<Symbol> *symbols)
2364{
2365 QCssScanner_Generated scanner(preprocessedInput);
2366 Symbol sym;
2367 int tok = scanner.lex();
2368 while (tok != -1) {
2369 sym.token = static_cast<QCss::TokenType>(tok);
2370 sym.text = scanner.input;
2371 sym.start = scanner.lexemStart;
2372 sym.len = scanner.lexemLength;
2373 symbols->append(sym);
2374 tok = scanner.lex();
2375 }
2376}
2377
2378QString Symbol::lexem() const
2379{
2380 QString result;
2381 if (len > 0)
2382 result.reserve(len);
2383 for (int i = 0; i < len; ++i) {
2384 if (text.at(start + i) == u'\\' && i < len - 1)
2385 ++i;
2386 result += text.at(start + i);
2387 }
2388 return result;
2389}
2390
2391Parser::Parser(const QString &css, bool isFile)
2392{
2393 init(css, isFile);
2394}
2395
2396Parser::Parser()
2397{
2398 index = 0;
2399 errorIndex = -1;
2400 hasEscapeSequences = false;
2401}
2402
2403void Parser::init(const QString &css, bool isFile)
2404{
2405 QString styleSheet = css;
2406 if (isFile) {
2407 QFile file(css);
2408 if (file.open(QFile::ReadOnly)) {
2409 sourcePath = QFileInfo(styleSheet).absolutePath() + u'/';
2410 QTextStream stream(&file);
2411 styleSheet = stream.readAll();
2412 } else {
2413 qWarning() << "QCss::Parser - Failed to load file " << css;
2414 styleSheet.clear();
2415 }
2416 } else {
2417 sourcePath.clear();
2418 }
2419
2420 hasEscapeSequences = false;
2421 symbols.clear();
2422 symbols.reserve(8);
2423 Scanner::scan(Scanner::preprocess(styleSheet, &hasEscapeSequences), &symbols);
2424 index = 0;
2425 errorIndex = -1;
2426}
2427
2428bool Parser::parse(StyleSheet *styleSheet, Qt::CaseSensitivity nameCaseSensitivity)
2429{
2430 if (testTokenAndEndsWith(ATKEYWORD_SYM, "charset"_L1)) {
2431 while (test(S) || test(CDO) || test(CDC)) {}
2432 if (!next(STRING)) return false;
2433 if (!next(SEMICOLON)) return false;
2434 }
2435
2436 while (test(S) || test(CDO) || test(CDC)) {}
2437
2438 while (testImport()) {
2439 ImportRule rule;
2440 if (!parseImport(&rule)) return false;
2441 styleSheet->importRules.append(rule);
2442 while (test(S) || test(CDO) || test(CDC)) {}
2443 }
2444
2445 do {
2446 if (testMedia()) {
2447 MediaRule rule;
2448 if (!parseMedia(&rule)) return false;
2449 styleSheet->mediaRules.append(rule);
2450 } else if (testPage()) {
2451 PageRule rule;
2452 if (!parsePage(&rule)) return false;
2453 styleSheet->pageRules.append(rule);
2454 } else if (testAnimation()) {
2455 AnimationRule rule;
2456 if (!parseAnimation(&rule)) return false;
2457 styleSheet->animationRules.append(rule);
2458 } else if (testRuleset()) {
2459 StyleRule rule;
2460 if (!parseRuleset(&rule)) return false;
2461 styleSheet->styleRules.append(rule);
2462 } else if (test(ATKEYWORD_SYM)) {
2463 if (!until(RBRACE)) return false;
2464 } else if (hasNext()) {
2465 return false;
2466 }
2467 while (test(S) || test(CDO) || test(CDC)) {}
2468 } while (hasNext());
2469 styleSheet->buildIndexes(nameCaseSensitivity);
2470 return true;
2471}
2472
2473Symbol Parser::errorSymbol()
2474{
2475 if (errorIndex == -1) return Symbol();
2476 return symbols.at(errorIndex);
2477}
2478
2479static inline void removeOptionalQuotes(QString *str)
2480{
2481 if (!str->startsWith(u'\'') && !str->startsWith(u'\"'))
2482 return;
2483 str->remove(0, 1);
2484 str->chop(1);
2485}
2486
2487bool Parser::parseImport(ImportRule *importRule)
2488{
2489 skipSpace();
2490
2491 if (test(STRING)) {
2492 importRule->href = lexem();
2493 } else {
2494 if (!testAndParseUri(&importRule->href)) return false;
2495 }
2496 removeOptionalQuotes(&importRule->href);
2497
2498 skipSpace();
2499
2500 if (testMedium()) {
2501 if (!parseMedium(&importRule->media)) return false;
2502
2503 while (test(COMMA)) {
2504 skipSpace();
2505 if (!parseNextMedium(&importRule->media)) return false;
2506 }
2507 }
2508
2509 if (!next(SEMICOLON)) return false;
2510
2511 skipSpace();
2512 return true;
2513}
2514
2515bool Parser::parseMedia(MediaRule *mediaRule)
2516{
2517 do {
2518 skipSpace();
2519 if (!parseNextMedium(&mediaRule->media)) return false;
2520 } while (test(COMMA));
2521
2522 if (!next(LBRACE)) return false;
2523 skipSpace();
2524
2525 while (testRuleset()) {
2526 StyleRule rule;
2527 if (!parseRuleset(&rule)) return false;
2528 mediaRule->styleRules.append(rule);
2529 }
2530
2531 if (!next(RBRACE)) return false;
2532 skipSpace();
2533 return true;
2534}
2535
2536bool Parser::parseMedium(QStringList *media)
2537{
2538 media->append(lexem());
2539 skipSpace();
2540 return true;
2541}
2542
2543bool Parser::parsePage(PageRule *pageRule)
2544{
2545 skipSpace();
2546
2547 if (testPseudoPage())
2548 if (!parsePseudoPage(&pageRule->selector)) return false;
2549
2550 skipSpace();
2551 if (!next(LBRACE)) return false;
2552
2553 do {
2554 skipSpace();
2555 Declaration decl;
2556 if (!parseNextDeclaration(&decl)) return false;
2557 if (!decl.isEmpty())
2558 pageRule->declarations.append(decl);
2559 } while (test(SEMICOLON));
2560
2561 if (!next(RBRACE)) return false;
2562 skipSpace();
2563 return true;
2564}
2565
2566bool Parser::parsePseudoPage(QString *selector)
2567{
2568 if (!next(IDENT)) return false;
2569 *selector = lexem();
2570 return true;
2571}
2572
2573bool Parser::parseNextOperator(Value *value)
2574{
2575 if (!hasNext()) return true;
2576 switch (next()) {
2577 case SLASH: value->type = Value::TermOperatorSlash; skipSpace(); break;
2578 case COMMA: value->type = Value::TermOperatorComma; skipSpace(); break;
2579 default: prev(); break;
2580 }
2581 return true;
2582}
2583
2584bool Parser::parseAnimation(AnimationRule *animationRule)
2585{
2586 skipSpace();
2587 if (!test(IDENT)) return false;
2588
2589 animationRule->animName = lexem();
2590
2591 if (!next(LBRACE)) return false;
2592 skipSpace();
2593
2594 while (test(PERCENTAGE) || test(IDENT)) {
2595 AnimationRule::AnimationRuleSet set;
2596 if (lookup() == PERCENTAGE) {
2597 QString name = lexem();
2598 name.removeLast();
2599 float keyFrame = name.toFloat() / 100;
2600 set.keyFrame = keyFrame;
2601 } else if (lookup() == IDENT) {
2602 QString name;
2603 if (parseElementName(&name)) {
2604 if (name == QStringLiteral("from"))
2605 set.keyFrame = 0;
2606 else if (name == QStringLiteral("to"))
2607 set.keyFrame = 1;
2608 }
2609 }
2610
2611 skipSpace();
2612 if (!next(LBRACE)) return false;
2613 const int declarationStart = index;
2614
2615 do {
2616 skipSpace();
2617 Declaration decl;
2618 const int rewind = index;
2619 if (!parseNextDeclaration(&decl)) {
2620 index = rewind;
2621 const bool foundSemicolon = until(SEMICOLON);
2622 const int semicolonIndex = index;
2623
2624 index = declarationStart;
2625 const bool foundRBrace = until(RBRACE);
2626
2627 if (foundSemicolon && semicolonIndex < index) {
2628 decl = Declaration();
2629 index = semicolonIndex - 1;
2630 } else {
2631 skipSpace();
2632 return foundRBrace;
2633 }
2634 }
2635 if (!decl.isEmpty()) {
2636 if (decl.d->property == "animation-timing-function"_L1)
2637 set.timingFunction = std::move(decl);
2638 else
2639 set.declarations.push_back(std::move(decl));
2640 }
2641 } while (test(SEMICOLON));
2642
2643 if (!next(RBRACE)) return false;
2644 skipSpace();
2645 animationRule->ruleSets.append(set);
2646 }
2647
2648 if (!next(RBRACE)) return false;
2649 skipSpace();
2650
2651 return true;
2652}
2653
2654bool Parser::parseCombinator(BasicSelector::Relation *relation)
2655{
2656 *relation = BasicSelector::NoRelation;
2657 if (lookup() == S) {
2658 *relation = BasicSelector::MatchNextSelectorIfAncestor;
2659 skipSpace();
2660 } else {
2661 prev();
2662 }
2663 if (test(PLUS)) {
2664 *relation = BasicSelector::MatchNextSelectorIfDirectAdjecent;
2665 } else if (test(GREATER)) {
2666 *relation = BasicSelector::MatchNextSelectorIfParent;
2667 } else if (test(TILDE)) {
2668 *relation = BasicSelector::MatchNextSelectorIfIndirectAdjecent;
2669 }
2670 skipSpace();
2671 return true;
2672}
2673
2674bool Parser::parseProperty(Declaration *decl)
2675{
2676 decl->d->property = lexem();
2677 decl->d->propertyId = findKnownValue(decl->d->property, properties);
2678 decl->d->inheritable = isInheritable(decl->d->propertyId);
2679 skipSpace();
2680 return true;
2681}
2682
2683bool Parser::parseRuleset(StyleRule *styleRule)
2684{
2685 Selector sel;
2686 if (!parseSelector(&sel)) return false;
2687 styleRule->selectors.append(sel);
2688
2689 while (test(COMMA)) {
2690 skipSpace();
2691 Selector sel;
2692 if (!parseNextSelector(&sel)) return false;
2693 styleRule->selectors.append(sel);
2694 }
2695
2696 skipSpace();
2697 if (!next(LBRACE)) return false;
2698 const int declarationStart = index;
2699
2700 do {
2701 skipSpace();
2702 Declaration decl;
2703 const int rewind = index;
2704 if (!parseNextDeclaration(&decl)) {
2705 index = rewind;
2706 const bool foundSemicolon = until(SEMICOLON);
2707 const int semicolonIndex = index;
2708
2709 index = declarationStart;
2710 const bool foundRBrace = until(RBRACE);
2711
2712 if (foundSemicolon && semicolonIndex < index) {
2713 decl = Declaration();
2714 index = semicolonIndex - 1;
2715 } else {
2716 skipSpace();
2717 return foundRBrace;
2718 }
2719 }
2720 if (!decl.isEmpty())
2721 styleRule->declarations.append(decl);
2722 } while (test(SEMICOLON));
2723
2724 if (!next(RBRACE)) return false;
2725 skipSpace();
2726 return true;
2727}
2728
2729bool Parser::parseSelector(Selector *sel)
2730{
2731 BasicSelector basicSel;
2732 if (!parseSimpleSelector(&basicSel)) return false;
2733 while (testCombinator()) {
2734 if (!parseCombinator(&basicSel.relationToNext)) return false;
2735
2736 if (!testSimpleSelector()) break;
2737 sel->basicSelectors.append(basicSel);
2738
2739 basicSel = BasicSelector();
2740 if (!parseSimpleSelector(&basicSel)) return false;
2741 }
2742 sel->basicSelectors.append(basicSel);
2743 return true;
2744}
2745
2746bool Parser::parseSimpleSelector(BasicSelector *basicSel)
2747{
2748 int minCount = 0;
2749 if (lookupElementName()) {
2750 if (!parseElementName(&basicSel->elementName)) return false;
2751 } else {
2752 prev();
2753 minCount = 1;
2754 }
2755 bool onceMore;
2756 int count = 0;
2757 do {
2758 onceMore = false;
2759 if (test(HASH)) {
2760 QString theid = lexem();
2761 // chop off leading #
2762 theid.remove(0, 1);
2763 basicSel->ids.append(theid);
2764 onceMore = true;
2765 } else if (testClass()) {
2766 onceMore = true;
2767 AttributeSelector a;
2768 a.name = "class"_L1;
2769 a.valueMatchCriterium = AttributeSelector::MatchIncludes;
2770 if (!parseClass(&a.value)) return false;
2771 basicSel->attributeSelectors.append(a);
2772 } else if (testAttrib()) {
2773 onceMore = true;
2774 AttributeSelector a;
2775 if (!parseAttrib(&a)) return false;
2776 basicSel->attributeSelectors.append(a);
2777 } else if (testPseudo()) {
2778 onceMore = true;
2779 Pseudo ps;
2780 if (!parsePseudo(&ps)) return false;
2781 basicSel->pseudos.append(ps);
2782 }
2783 if (onceMore) ++count;
2784 } while (onceMore);
2785 return count >= minCount;
2786}
2787
2788bool Parser::parseClass(QString *name)
2789{
2790 if (!next(IDENT)) return false;
2791 *name = lexem();
2792 return true;
2793}
2794
2795bool Parser::parseElementName(QString *name)
2796{
2797 switch (lookup()) {
2798 case STAR: name->clear(); break;
2799 case IDENT: *name = lexem(); break;
2800 default: return false;
2801 }
2802 return true;
2803}
2804
2805bool Parser::parseAttrib(AttributeSelector *attr)
2806{
2807 skipSpace();
2808 if (!next(IDENT)) return false;
2809 attr->name = lexem();
2810 skipSpace();
2811
2812 if (test(EQUAL)) {
2813 attr->valueMatchCriterium = AttributeSelector::MatchEqual;
2814 } else if (test(INCLUDES)) {
2815 attr->valueMatchCriterium = AttributeSelector::MatchIncludes;
2816 } else if (test(DASHMATCH)) {
2817 attr->valueMatchCriterium = AttributeSelector::MatchDashMatch;
2818 } else if (test(BEGINSWITH)) {
2819 attr->valueMatchCriterium = AttributeSelector::MatchBeginsWith;
2820 } else if (test(ENDSWITH)) {
2821 attr->valueMatchCriterium = AttributeSelector::MatchEndsWith;
2822 } else if (test(CONTAINS)) {
2823 attr->valueMatchCriterium = AttributeSelector::MatchContains;
2824 } else {
2825 return next(RBRACKET);
2826 }
2827
2828 skipSpace();
2829
2830 if (!test(IDENT) && !test(STRING)) return false;
2831 attr->value = unquotedLexem();
2832
2833 skipSpace();
2834 return next(RBRACKET);
2835}
2836
2837bool Parser::parsePseudo(Pseudo *pseudo)
2838{
2839 (void)test(COLON);
2840 pseudo->negated = test(EXCLAMATION_SYM);
2841 if (test(IDENT)) {
2842 pseudo->name = lexem();
2843 pseudo->type = findKnownValue(pseudo->name, pseudos);
2844 return true;
2845 }
2846 if (!next(FUNCTION)) return false;
2847 pseudo->function = lexem();
2848 // chop off trailing parenthesis
2849 pseudo->function.chop(1);
2850 skipSpace();
2851 if (!test(IDENT)) return false;
2852 pseudo->name = lexem();
2853 skipSpace();
2854 return next(RPAREN);
2855}
2856
2857bool Parser::parseNextDeclaration(Declaration *decl)
2858{
2859 if (!testProperty())
2860 return true; // not an error!
2861 if (!parseProperty(decl)) return false;
2862 if (!next(COLON)) return false;
2863 skipSpace();
2864 if (!parseNextExpr(&decl->d->values)) return false;
2865 if (testPrio())
2866 if (!parsePrio(decl)) return false;
2867 return true;
2868}
2869
2870bool Parser::testPrio()
2871{
2872 const int rewind = index;
2873 if (!test(EXCLAMATION_SYM)) return false;
2874 skipSpace();
2875 if (!test(IDENT)) {
2876 index = rewind;
2877 return false;
2878 }
2879 if (lexem().compare("important"_L1, Qt::CaseInsensitive) != 0) {
2880 index = rewind;
2881 return false;
2882 }
2883 return true;
2884}
2885
2886bool Parser::parsePrio(Declaration *declaration)
2887{
2888 declaration->d->important = true;
2889 skipSpace();
2890 return true;
2891}
2892
2893bool Parser::parseExpr(QList<Value> *values)
2894{
2895 Value val;
2896 if (!parseTerm(&val)) return false;
2897 values->append(val);
2898 bool onceMore;
2899 do {
2900 onceMore = false;
2901 val = Value();
2902 if (!parseNextOperator(&val)) return false;
2903 if (val.type != QCss::Value::Unknown)
2904 values->append(val);
2905 if (testTerm()) {
2906 onceMore = true;
2907 val = Value();
2908 if (!parseTerm(&val)) return false;
2909 values->append(val);
2910 }
2911 } while (onceMore);
2912 return true;
2913}
2914
2915bool Parser::testTerm()
2916{
2917 return test(PLUS) || test(MINUS)
2918 || test(NUMBER)
2919 || test(PERCENTAGE)
2920 || test(LENGTH)
2921 || test(STRING)
2922 || test(IDENT)
2923 || testHexColor()
2924 || testFunction();
2925}
2926
2927bool Parser::parseTerm(Value *value)
2928{
2929 QString str = lexem();
2930 bool haveUnary = false;
2931 if (lookup() == PLUS || lookup() == MINUS) {
2932 haveUnary = true;
2933 if (!hasNext()) return false;
2934 next();
2935 str += lexem();
2936 }
2937
2938 value->variant = str;
2939 value->type = QCss::Value::String;
2940 switch (lookup()) {
2941 case NUMBER:
2942 value->type = Value::Number;
2943 value->variant.convert(QMetaType::fromType<double>());
2944 break;
2945 case PERCENTAGE:
2946 value->type = Value::Percentage;
2947 str.chop(1); // strip off %
2948 value->variant = str;
2949 break;
2950 case LENGTH:
2951 value->type = Value::Length;
2952 break;
2953
2954 case STRING:
2955 if (haveUnary) return false;
2956 value->type = Value::String;
2957 str.chop(1);
2958 str.remove(0, 1);
2959 value->variant = str;
2960 break;
2961 case IDENT: {
2962 if (haveUnary) return false;
2963 value->type = Value::Identifier;
2964 const KnownValue theid = findKnownValue(str, values);
2965 if (theid != KnownValue::Unknown) {
2966 value->type = Value::KnownIdentifier;
2967 value->variant = QVariant::fromValue(theid);
2968 }
2969 break;
2970 }
2971 default: {
2972 if (haveUnary) return false;
2973 prev();
2974 if (testHexColor()) {
2975 QColor col;
2976 if (!parseHexColor(&col)) return false;
2977 value->type = Value::Color;
2978 value->variant = col;
2979 } else if (testFunction()) {
2980 QString name, args;
2981 if (!parseFunction(&name, &args)) return false;
2982 if (name == "url"_L1) {
2983 value->type = Value::Uri;
2984 removeOptionalQuotes(&args);
2985 if (QFileInfo(args).isRelative() && !sourcePath.isEmpty()) {
2986 args.prepend(sourcePath);
2987 }
2988 value->variant = std::move(args);
2989 } else {
2990 value->type = Value::Function;
2991 value->variant = QStringList() << name << args;
2992 }
2993 } else {
2994 return recordError();
2995 }
2996 return true;
2997 }
2998 }
2999 skipSpace();
3000 return true;
3001}
3002
3003bool Parser::parseFunction(QString *name, QString *args)
3004{
3005 *name = lexem();
3006 name->chop(1);
3007 // until(RPAREN) needs FUNCTION token at index-1 to work properly
3008 int start = index;
3009 skipSpace();
3010 std::swap(start, index);
3011 if (!until(RPAREN)) return false;
3012 for (int i = start; i < index - 1; ++i)
3013 args->append(symbols.at(i).lexem());
3014 /*
3015 if (!nextExpr(&arguments)) return false;
3016 if (!next(RPAREN)) return false;
3017 */
3018 skipSpace();
3019 return true;
3020}
3021
3022bool Parser::parseHexColor(QColor *col)
3023{
3024 *col = QColor::fromString(lexem());
3025 if (!col->isValid()) {
3026 qWarning("QCssParser::parseHexColor: Unknown color name '%s'",lexem().toLatin1().constData());
3027 return false;
3028 }
3029 skipSpace();
3030 return true;
3031}
3032
3033bool Parser::testAndParseUri(QString *uri)
3034{
3035 const int rewind = index;
3036 if (!testFunction()) return false;
3037
3038 QString name, args;
3039 if (!parseFunction(&name, &args)) {
3040 index = rewind;
3041 return false;
3042 }
3043 if (name.compare("url"_L1, Qt::CaseInsensitive) != 0) {
3044 index = rewind;
3045 return false;
3046 }
3047 *uri = std::move(args);
3048 removeOptionalQuotes(uri);
3049 return true;
3050}
3051
3052bool Parser::testSimpleSelector()
3053{
3054 return testElementName()
3055 || (test(HASH))
3056 || testClass()
3057 || testAttrib()
3058 || testPseudo();
3059}
3060
3061bool Parser::next(QCss::TokenType t)
3062{
3063 if (hasNext() && next() == t)
3064 return true;
3065 return recordError();
3066}
3067
3068bool Parser::test(QCss::TokenType t)
3069{
3070 if (index >= symbols.size())
3071 return false;
3072 if (symbols.at(index).token == t) {
3073 ++index;
3074 return true;
3075 }
3076 return false;
3077}
3078
3079QString Parser::unquotedLexem() const
3080{
3081 QString s = lexem();
3082 if (lookup() == STRING) {
3083 s.chop(1);
3084 s.remove(0, 1);
3085 }
3086 return s;
3087}
3088
3089QString Parser::lexemUntil(QCss::TokenType t)
3090{
3091 QString lexem;
3092 while (hasNext() && next() != t)
3093 lexem += symbol().lexem();
3094 return lexem;
3095}
3096
3097bool Parser::until(QCss::TokenType target, QCss::TokenType target2)
3098{
3099 int braceCount = 0;
3100 int brackCount = 0;
3101 int parenCount = 0;
3102 if (index) {
3103 switch(symbols.at(index-1).token) {
3104 case LBRACE: ++braceCount; break;
3105 case LBRACKET: ++brackCount; break;
3106 case FUNCTION:
3107 case LPAREN: ++parenCount; break;
3108 default: ;
3109 }
3110 }
3111 while (index < symbols.size()) {
3112 QCss::TokenType t = symbols.at(index++).token;
3113 switch (t) {
3114 case LBRACE: ++braceCount; break;
3115 case RBRACE: --braceCount; break;
3116 case LBRACKET: ++brackCount; break;
3117 case RBRACKET: --brackCount; break;
3118 case FUNCTION:
3119 case LPAREN: ++parenCount; break;
3120 case RPAREN: --parenCount; break;
3121 default: break;
3122 }
3123 if ((t == target || (target2 != NONE && t == target2))
3124 && braceCount <= 0
3125 && brackCount <= 0
3126 && parenCount <= 0)
3127 return true;
3128
3129 if (braceCount < 0 || brackCount < 0 || parenCount < 0) {
3130 --index;
3131 break;
3132 }
3133 }
3134 return false;
3135}
3136
3137bool Parser::testTokenAndEndsWith(QCss::TokenType t, QLatin1StringView str)
3138{
3139 if (!test(t)) return false;
3140 if (!lexem().endsWith(str, Qt::CaseInsensitive)) {
3141 prev();
3142 return false;
3143 }
3144 return true;
3145}
3146
3147QT_END_NAMESPACE
3148#endif // QT_NO_CSSPARSER
\inmodule QtGui
Definition qbrush.h:469
\inmodule QtGui
Definition qbrush.h:417
\inmodule QtGui
Definition qbrush.h:435
@ StyleFeature_BackgroundGradient
@ StyleFeature_BackgroundColor
@ StyleFeature_None
Combined button and popup list for selecting options.
static void setTextDecorationFromValues(const QList< QCss::Value > &values, QFont *font)
static bool operator<(const QString &name, const QCssKnownValue< T > &prop)
static constexpr QCssKnownValue< PositionMode > positions[]
static void removeOptionalQuotes(QString *str)
static constexpr QCssKnownValue< quint64 > pseudos[]
static constexpr QCssKnownValue< Repeat > repeats[]
static bool setFontFamilyFromValues(const QList< QCss::Value > &values, QFont *font, int start=0)
static bool setFontWeightFromValue(const QCss::Value &value, QFont *font)
static int lengthValueFromData(const LengthData &data, const QFont &f)
static void setTextTransformFromValue(const QCss::Value &value, QFont *font)
static bool setFontSizeFromValue(QCss::Value value, QFont *font, int *fontSizeAdjustment)
static constexpr QCssKnownValue< TileMode > tileModes[]
static bool setFontStyleFromValue(const QCss::Value &value, QFont *font)
static constexpr QCssKnownValue< Attachment > attachments[]
static ColorData parseColorValue(QCss::Value v)
static BorderStyle parseStyleValue(const QCss::Value &v)
static constexpr QCssKnownValue< Origin > origins[]
static void setFontVariantFromValue(const QCss::Value &value, QFont *font)
static bool intValueHelper(const QCss::Value &v, int *i, const char *unit)
#define CHECK_ARRAY_IS_SORTED(array, type)
static Qt::Alignment parseAlignment(const QCss::Value *values, int count)
static void setLetterSpacingFromValue(const QCss::Value &value, QFont *font)
static BrushData parseBrushValue(const QCss::Value &v, const QPalette &pal)
static bool isHexDigit(const char c)
static bool isInheritable(Property propertyId)
static constexpr QCssKnownValue< Property > properties[]
static constexpr uchar indexOfId[]
static bool setFontKerningFromValue(const QCss::Value &value, QFont *font)
static void parseShorthandBackgroundProperty(const QList< QCss::Value > &values, BrushData *brush, QString *image, Repeat *repeat, Qt::Alignment *alignment, const QPalette &pal)
static void parseShorthandFontProperty(const QList< QCss::Value > &values, QFont *font, int *fontSizeAdjustment)
static constexpr QCssKnownValue< int > styleFeatures[]
static constexpr QCssKnownValue< KnownValue > values[]
static QBrush brushFromData(const BrushData &c, const QPalette &pal)
static auto findKnownValue(const QString &name, const C &arr)
static void setWordSpacingFromValue(const QCss::Value &value, QFont *font)
static bool operator<(const QCssKnownValue< T > &prop, const QString &name)
static QColor colorFromData(const ColorData &c, const QPalette &pal)
constexpr bool operator()(const QCssKnownValue< T > &lhs, const QCssKnownValue< T > &rhs) const noexcept
const char name[28]
Q_GUI_EXPORT void buildIndexes(Qt::CaseSensitivity nameCaseSensitivity=Qt::CaseSensitive)