Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / core / css / MediaList.cpp
1 /*
2  * (C) 1999-2003 Lars Knoll (knoll@kde.org)
3  * Copyright (C) 2004, 2006, 2010, 2012 Apple Inc. All rights reserved.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public License
16  * along with this library; see the file COPYING.LIB.  If not, write to
17  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18  * Boston, MA 02110-1301, USA.
19  */
20 #include "config.h"
21 #include "core/css/MediaList.h"
22
23 #include "bindings/core/v8/ExceptionState.h"
24 #include "core/MediaFeatureNames.h"
25 #include "core/css/parser/BisonCSSParser.h"
26 #include "core/css/CSSStyleSheet.h"
27 #include "core/css/MediaQuery.h"
28 #include "core/css/MediaQueryExp.h"
29 #include "core/css/parser/MediaQueryParser.h"
30 #include "core/dom/Document.h"
31 #include "core/frame/LocalDOMWindow.h"
32 #include "core/inspector/ConsoleMessage.h"
33 #include "wtf/text/StringBuilder.h"
34
35 namespace blink {
36
37 /* MediaList is used to store 3 types of media related entities which mean the same:
38  *
39  * Media Queries, Media Types and Media Descriptors.
40  *
41  * Media queries, as described in the Media Queries Level 3 specification, build on
42  * the mechanism outlined in HTML4. The syntax of media queries fit into the media
43  * type syntax reserved in HTML4. The media attribute of HTML4 also exists in XHTML
44  * and generic XML. The same syntax can also be used inside the @media and @import
45  * rules of CSS.
46  *
47  * However, the parsing rules for media queries are incompatible with those of HTML4
48  * and are consistent with those of media queries used in CSS.
49  *
50  * HTML5 (at the moment of writing still work in progress) references the Media Queries
51  * specification directly and thus updates the rules for HTML.
52  *
53  * CSS 2.1 Spec (http://www.w3.org/TR/CSS21/media.html)
54  * CSS 3 Media Queries Spec (http://www.w3.org/TR/css3-mediaqueries/)
55  */
56
57 MediaQuerySet::MediaQuerySet()
58 {
59 }
60
61 MediaQuerySet::MediaQuerySet(const MediaQuerySet& o)
62     : m_queries(o.m_queries.size())
63 {
64     for (unsigned i = 0; i < m_queries.size(); ++i)
65         m_queries[i] = o.m_queries[i]->copy();
66 }
67
68 DEFINE_EMPTY_DESTRUCTOR_WILL_BE_REMOVED(MediaQuerySet)
69
70 PassRefPtrWillBeRawPtr<MediaQuerySet> MediaQuerySet::create(const String& mediaString)
71 {
72     if (mediaString.isEmpty())
73         return MediaQuerySet::create();
74
75     if (RuntimeEnabledFeatures::mediaQueryParserEnabled())
76         return MediaQueryParser::parseMediaQuerySet(mediaString);
77
78     BisonCSSParser parser(strictCSSParserContext());
79     return parser.parseMediaQueryList(mediaString);
80 }
81
82 PassRefPtrWillBeRawPtr<MediaQuerySet> MediaQuerySet::createOffMainThread(const String& mediaString)
83 {
84     if (mediaString.isEmpty())
85         return MediaQuerySet::create();
86
87     return MediaQueryParser::parseMediaQuerySet(mediaString);
88 }
89
90 bool MediaQuerySet::set(const String& mediaString)
91 {
92     RefPtrWillBeRawPtr<MediaQuerySet> result = create(mediaString);
93     m_queries.swap(result->m_queries);
94     return true;
95 }
96
97 bool MediaQuerySet::add(const String& queryString)
98 {
99     // To "parse a media query" for a given string means to follow "the parse
100     // a media query list" steps and return "null" if more than one media query
101     // is returned, or else the returned media query.
102     RefPtrWillBeRawPtr<MediaQuerySet> result = create(queryString);
103
104     // Only continue if exactly one media query is found, as described above.
105     if (result->m_queries.size() != 1)
106         return true;
107
108     OwnPtrWillBeRawPtr<MediaQuery> newQuery = result->m_queries[0].release();
109     ASSERT(newQuery);
110
111     // If comparing with any of the media queries in the collection of media
112     // queries returns true terminate these steps.
113     for (size_t i = 0; i < m_queries.size(); ++i) {
114         MediaQuery* query = m_queries[i].get();
115         if (*query == *newQuery)
116             return true;
117     }
118
119     m_queries.append(newQuery.release());
120     return true;
121 }
122
123 bool MediaQuerySet::remove(const String& queryStringToRemove)
124 {
125     // To "parse a media query" for a given string means to follow "the parse
126     // a media query list" steps and return "null" if more than one media query
127     // is returned, or else the returned media query.
128     RefPtrWillBeRawPtr<MediaQuerySet> result = create(queryStringToRemove);
129
130     // Only continue if exactly one media query is found, as described above.
131     if (result->m_queries.size() != 1)
132         return true;
133
134     OwnPtrWillBeRawPtr<MediaQuery> newQuery = result->m_queries[0].release();
135     ASSERT(newQuery);
136
137     // Remove any media query from the collection of media queries for which
138     // comparing with the media query returns true.
139     bool found = false;
140     for (size_t i = 0; i < m_queries.size(); ++i) {
141         MediaQuery* query = m_queries[i].get();
142         if (*query == *newQuery) {
143             m_queries.remove(i);
144             --i;
145             found = true;
146         }
147     }
148
149     return found;
150 }
151
152 void MediaQuerySet::addMediaQuery(PassOwnPtrWillBeRawPtr<MediaQuery> mediaQuery)
153 {
154     m_queries.append(mediaQuery);
155 }
156
157 String MediaQuerySet::mediaText() const
158 {
159     StringBuilder text;
160
161     bool first = true;
162     for (size_t i = 0; i < m_queries.size(); ++i) {
163         if (!first)
164             text.appendLiteral(", ");
165         else
166             first = false;
167         text.append(m_queries[i]->cssText());
168     }
169     return text.toString();
170 }
171
172 void MediaQuerySet::trace(Visitor* visitor)
173 {
174     // We don't support tracing of vectors of OwnPtrs (ie. OwnPtr<Vector<OwnPtr<MediaQuery> > >).
175     // Since this is a transitional object we are just ifdef'ing it out when oilpan is not enabled.
176 #if ENABLE(OILPAN)
177     visitor->trace(m_queries);
178 #endif
179 }
180
181 MediaList::MediaList(MediaQuerySet* mediaQueries, CSSStyleSheet* parentSheet)
182     : m_mediaQueries(mediaQueries)
183     , m_parentStyleSheet(parentSheet)
184     , m_parentRule(nullptr)
185 {
186     ScriptWrappable::init(this);
187 }
188
189 MediaList::MediaList(MediaQuerySet* mediaQueries, CSSRule* parentRule)
190     : m_mediaQueries(mediaQueries)
191     , m_parentStyleSheet(nullptr)
192     , m_parentRule(parentRule)
193 {
194     ScriptWrappable::init(this);
195 }
196
197 MediaList::~MediaList()
198 {
199 }
200
201 void MediaList::setMediaText(const String& value)
202 {
203     CSSStyleSheet::RuleMutationScope mutationScope(m_parentRule);
204
205     m_mediaQueries->set(value);
206
207     if (m_parentStyleSheet)
208         m_parentStyleSheet->didMutate();
209 }
210
211 String MediaList::item(unsigned index) const
212 {
213     const WillBeHeapVector<OwnPtrWillBeMember<MediaQuery> >& queries = m_mediaQueries->queryVector();
214     if (index < queries.size())
215         return queries[index]->cssText();
216     return String();
217 }
218
219 void MediaList::deleteMedium(const String& medium, ExceptionState& exceptionState)
220 {
221     CSSStyleSheet::RuleMutationScope mutationScope(m_parentRule);
222
223     bool success = m_mediaQueries->remove(medium);
224     if (!success) {
225         exceptionState.throwDOMException(NotFoundError, "Failed to delete '" + medium + "'.");
226         return;
227     }
228     if (m_parentStyleSheet)
229         m_parentStyleSheet->didMutate();
230 }
231
232 void MediaList::appendMedium(const String& medium, ExceptionState& exceptionState)
233 {
234     CSSStyleSheet::RuleMutationScope mutationScope(m_parentRule);
235
236     bool success = m_mediaQueries->add(medium);
237     if (!success) {
238         exceptionState.throwDOMException(InvalidCharacterError, "The value provided ('" + medium + "') is not a valid medium.");
239         return;
240     }
241
242     if (m_parentStyleSheet)
243         m_parentStyleSheet->didMutate();
244 }
245
246 void MediaList::reattach(MediaQuerySet* mediaQueries)
247 {
248     ASSERT(mediaQueries);
249     m_mediaQueries = mediaQueries;
250 }
251
252 void MediaList::trace(Visitor* visitor)
253 {
254     visitor->trace(m_mediaQueries);
255     visitor->trace(m_parentStyleSheet);
256     visitor->trace(m_parentRule);
257 }
258
259 static void addResolutionWarningMessageToConsole(Document* document, const String& serializedExpression, CSSPrimitiveValue::UnitType type)
260 {
261     ASSERT(document);
262
263     DEFINE_STATIC_LOCAL(String, mediaQueryMessage, ("Consider using 'dppx' units, as in CSS '%replacementUnits%' means dots-per-CSS-%lengthUnit%, not dots-per-physical-%lengthUnit%, so does not correspond to the actual '%replacementUnits%' of a screen. In media query expression: "));
264     DEFINE_STATIC_LOCAL(String, mediaValueDPI, ("dpi"));
265     DEFINE_STATIC_LOCAL(String, mediaValueDPCM, ("dpcm"));
266     DEFINE_STATIC_LOCAL(String, lengthUnitInch, ("inch"));
267     DEFINE_STATIC_LOCAL(String, lengthUnitCentimeter, ("centimeter"));
268
269     StringBuilder message;
270     if (CSSPrimitiveValue::isDotsPerInch(type))
271         message.append(String(mediaQueryMessage).replace("%replacementUnits%", mediaValueDPI).replace("%lengthUnit%", lengthUnitInch));
272     else if (CSSPrimitiveValue::isDotsPerCentimeter(type))
273         message.append(String(mediaQueryMessage).replace("%replacementUnits%", mediaValueDPCM).replace("%lengthUnit%", lengthUnitCentimeter));
274     else
275         ASSERT_NOT_REACHED();
276
277     message.append(serializedExpression);
278
279     document->addConsoleMessage(ConsoleMessage::create(CSSMessageSource, DebugMessageLevel, message.toString()));
280 }
281
282 static inline bool isResolutionMediaFeature(const String& mediaFeature)
283 {
284     return mediaFeature == MediaFeatureNames::resolutionMediaFeature
285         || mediaFeature == MediaFeatureNames::maxResolutionMediaFeature
286         || mediaFeature == MediaFeatureNames::minResolutionMediaFeature;
287 }
288
289 void reportMediaQueryWarningIfNeeded(Document* document, const MediaQuerySet* mediaQuerySet)
290 {
291     if (!mediaQuerySet || !document)
292         return;
293
294     const WillBeHeapVector<OwnPtrWillBeMember<MediaQuery> >& mediaQueries = mediaQuerySet->queryVector();
295     const size_t queryCount = mediaQueries.size();
296
297     if (!queryCount)
298         return;
299
300     CSSPrimitiveValue::UnitType suspiciousType = CSSPrimitiveValue::CSS_UNKNOWN;
301     bool dotsPerPixelUsed = false;
302     for (size_t i = 0; i < queryCount; ++i) {
303         const MediaQuery* query = mediaQueries[i].get();
304         if (equalIgnoringCase(query->mediaType(), "print"))
305             continue;
306
307         const ExpressionHeapVector& expressions = query->expressions();
308         for (size_t j = 0; j < expressions.size(); ++j) {
309             const MediaQueryExp* expression = expressions.at(j).get();
310             if (isResolutionMediaFeature(expression->mediaFeature())) {
311                 MediaQueryExpValue expValue = expression->expValue();
312                 if (expValue.isValue) {
313                     if (CSSPrimitiveValue::isDotsPerPixel(expValue.unit))
314                         dotsPerPixelUsed = true;
315                     else if (CSSPrimitiveValue::isDotsPerInch(expValue.unit) || CSSPrimitiveValue::isDotsPerCentimeter(expValue.unit))
316                         suspiciousType = expValue.unit;
317                 }
318             }
319         }
320     }
321
322     if (suspiciousType && !dotsPerPixelUsed)
323         addResolutionWarningMessageToConsole(document, mediaQuerySet->mediaText(), suspiciousType);
324 }
325
326 }