libhtmlpp 1.0.0
Loading...
Searching...
No Matches
htmlcss.cpp
Go to the documentation of this file.
1/*******************************************************************************
2Copyright (c) 2021, Jan Koester jan.koester@gmx.net
3All rights reserved.
4
5Redistribution and use in source and binary forms, with or without
6modification, are permitted provided that the following conditions are met:
7 * Redistributions of source code must retain the above copyright
8 notice, this list of conditions and the following disclaimer.
9 * Redistributions in binary form must reproduce the above copyright
10 notice, this list of conditions and the following disclaimer in the
11 documentation and/or other materials provided with the distribution.
12 * Neither the name of the <organization> nor the
13 names of its contributors may be used to endorse or promote products
14 derived from this software without specific prior written permission.
15
16THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
17ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
20DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26*******************************************************************************/
27
28#include "htmlcss.h"
29
30#include <algorithm>
31#include <vector>
32
33namespace {
34
35 std::string lowerCopy(const std::string &s) {
36 std::string t = s;
37 std::transform(t.begin(), t.end(), t.begin(),
38 [](unsigned char c) { return std::tolower(c); });
39 return t;
40 }
41
42 // Strips a trailing "!important" (case-insensitive, any whitespace
43 // before the "!") from a CSS declaration value -- see the identical
44 // helper in css.cpp for why this matters; duplicated here (rather than
45 // exposed from css.cpp) since it's a small, self-contained detail of
46 // normalizing a single value string, not selector/cascade logic.
47 void stripImportant(std::string &value) {
48 size_t bang = value.rfind('!');
49 if (bang == std::string::npos) return;
50
51 size_t start = value.find_first_not_of(" \t\n\r", bang + 1);
52 size_t end = value.find_last_not_of(" \t\n\r");
53 if (start == std::string::npos || end == std::string::npos || start > end) return;
54
55 std::string tail = value.substr(start, end - start + 1);
56 std::transform(tail.begin(), tail.end(), tail.begin(),
57 [](unsigned char c) { return std::tolower(c); });
58 if (tail != "important") return;
59
60 size_t valEnd = bang;
61 while (valEnd > 0 && std::isspace(static_cast<unsigned char>(value[valEnd - 1]))) --valEnd;
62 value.resize(valEnd);
63 }
64
65}
66
68{
69 // Children discovered while walking a frame's sibling chain are
70 // collected here and pushed in reverse at the end, so <style> blocks
71 // end up appended to `sheet` in true document order (matters once two
72 // rules for the same property fall back to "later one wins").
73 std::vector<Element*> searchStack;
74 searchStack.push_back(&root);
75
76 while (!searchStack.empty()) {
77 Element *cur = searchStack.back();
78 searchStack.pop_back();
79
80 std::vector<Element*> childFrames;
81
82 while (cur) {
83 int type = cur->getType();
84 if (type == HtmlEl || type == SvgEL || type == TextAreaEL) {
85 HtmlElement *hel = static_cast<HtmlElement*>(cur);
86 if (lowerCopy(hel->getTagname()) == "style") {
87 std::string cssText;
88 Element *child = hel->firstChild();
89 while (child) {
90 if (child->getType() == TextEl) {
91 cssText += static_cast<TextElement*>(child)->getText();
92 }
93 child = child->nextElement();
94 }
95 if (!cssText.empty()) {
96 CSSStyleSheet partial;
97 partial.parse(cssText);
98 for (const auto &rule : partial.getRules()) {
99 sheet.addRule(rule);
100 }
101 }
102 } else {
103 Element *child = hel->firstChild();
104 if (child) childFrames.push_back(child);
105 }
106 }
107 cur = cur->nextElement();
108 }
109
110 for (auto it = childFrames.rbegin(); it != childFrames.rend(); ++it) {
111 searchStack.push_back(*it);
112 }
113 }
114}
115
117 const CSSStyleSheet &sheet,
118 std::set<std::string> &seenMediaBlocks,
119 const std::vector<AncestorFrame> *ancestors)
120{
121 CSSRuleResult result;
122
123 CSSDeclaration inlineDecl = CSSStyleSheet::parseInlineStyle(target.getAtributte("style"));
124 for (const auto &prop : inlineDecl.getProperties()) {
125 std::string value = prop.getValue();
126 stripImportant(value);
127 result.properties[prop.getName()] = value;
128 }
129
130 std::string tag = lowerCopy(target.getTagname());
131 std::string cssClass = target.getAtributte("class");
132 std::string id = target.getAtributte("id");
133
134 std::map<std::string,std::string> targetAttributes;
135 for (const HtmlElement::Attributes *attr = target.firstAttribute(); attr; attr = attr->nextAttribute()) {
136 targetAttributes[attr->getKey()] = attr->getValue();
137 }
138
139 sheet.collectApproximateMatches(tag, cssClass, id, result.properties, result.mediaRules,
140 seenMediaBlocks, ancestors, &targetAttributes);
141 return result;
142}
const std::vector< CSSProperty > & getProperties() const
Definition css.cpp:639
void parse(const std::string &input)
Definition css.cpp:797
const std::vector< CSSRule > & getRules() const
Definition css.cpp:924
void collectApproximateMatches(const std::string &tag, const std::string &cssClass, const std::string &id, std::map< std::string, std::string > &props, std::string &mediaRules, std::set< std::string > &seenMediaBlocks, const std::vector< AncestorFrame > *ancestors=nullptr, const std::map< std::string, std::string > *targetAttributes=nullptr) const
Runs every rule in this sheet through approximateSelectorMatch against the element identified by tag/...
Definition css.cpp:1117
void addRule(const CSSRule &rule)
Definition css.cpp:903
Abstract base class for all nodes in the HTML tree.
Definition html.h:76
virtual int getType() const =0
Definition html.cpp:802
Element * nextElement() const
Definition html.cpp:1552
const Attributes * firstAttribute() const
Definition html.cpp:2705
const std::string getAtributte(const std::string &name) const
Definition html.cpp:2757
Element * firstChild() const
Definition html.cpp:2689
const std::string getTagname() const
Definition html.cpp:811
Leaf node representing plain text content of an HTML document.
Definition html.h:214
std::string lowerCopy(const std::string &s)
Definition htmlcss.cpp:35
void stripImportant(std::string &value)
Definition htmlcss.cpp:47
@ TextEl
Definition html.h:65
@ HtmlEl
Definition html.h:66
@ TextAreaEL
Definition html.h:70
@ SvgEL
Definition html.h:69
void collectStyleBlocks(CSSStyleSheet &sheet, Element &root)
Finds every <style> element anywhere in the subtree rooted at root (document order) and appends each ...
Definition htmlcss.cpp:67
CSSRuleResult getCSSRules(HtmlElement &target, const CSSStyleSheet &sheet, std::set< std::string > &seenMediaBlocks, const std::vector< AncestorFrame > *ancestors=nullptr)
Returns every CSS rule that applies to target: its own inline style="..." attribute,...
Definition htmlcss.cpp:116
Result of getCSSRules: the fully cascaded property set (name -> value, "!important" stripped) and the...
Definition htmlcss.h:58
std::map< std::string, std::string > properties
Definition htmlcss.h:59
std::string mediaRules
Definition htmlcss.h:60