Reduce use of deprecatedCharacters in WebCore
[WebKit-https.git] / Source / WebCore / inspector / InspectorStyleSheet.cpp
1 /*
2  * Copyright (C) 2010, Google Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1.  Redistributions of source code must retain the above copyright
8  *     notice, this list of conditions and the following disclaimer.
9  * 2.  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  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
15  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
16  * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
17  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
18  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
19  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
20  * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
21  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
22  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
23  */
24
25 #include "config.h"
26
27 #if ENABLE(INSPECTOR)
28
29 #include "InspectorStyleSheet.h"
30
31 #include "CSSImportRule.h"
32 #include "CSSMediaRule.h"
33 #include "CSSParser.h"
34 #include "CSSPropertyNames.h"
35 #include "CSSPropertySourceData.h"
36 #include "CSSRule.h"
37 #include "CSSRuleList.h"
38 #include "CSSStyleRule.h"
39 #include "CSSStyleSheet.h"
40 #include "CSSSupportsRule.h"
41 #include "ContentSecurityPolicy.h"
42 #include "Document.h"
43 #include "Element.h"
44 #include "HTMLHeadElement.h"
45 #include "HTMLNames.h"
46 #include "HTMLParserIdioms.h"
47 #include "HTMLStyleElement.h"
48 #include "InspectorCSSAgent.h"
49 #include "InspectorPageAgent.h"
50 #include "Node.h"
51 #include "SVGElement.h"
52 #include "SVGNames.h"
53 #include "StyleProperties.h"
54 #include "StyleResolver.h"
55 #include "StyleRule.h"
56 #include "StyleRuleImport.h"
57 #include "StyleSheetContents.h"
58 #include "StyleSheetList.h"
59 #include "WebKitCSSKeyframesRule.h"
60 #include <inspector/ContentSearchUtilities.h>
61 #include <inspector/InspectorValues.h>
62 #include <wtf/Vector.h>
63 #include <wtf/text/StringBuilder.h>
64 #include <yarr/RegularExpression.h>
65
66 using Inspector::TypeBuilder::Array;
67 using WebCore::RuleSourceDataList;
68 using WebCore::CSSRuleSourceData;
69
70 class ParsedStyleSheet {
71     WTF_MAKE_FAST_ALLOCATED;
72 public:
73     ParsedStyleSheet();
74
75     const String& text() const { ASSERT(m_hasText); return m_text; }
76     void setText(const String& text);
77     bool hasText() const { return m_hasText; }
78     RuleSourceDataList* sourceData() const { return m_sourceData.get(); }
79     void setSourceData(std::unique_ptr<RuleSourceDataList>);
80     bool hasSourceData() const { return m_sourceData != nullptr; }
81     PassRefPtr<WebCore::CSSRuleSourceData> ruleSourceDataAt(unsigned) const;
82
83 private:
84
85     String m_text;
86     bool m_hasText;
87     std::unique_ptr<RuleSourceDataList> m_sourceData;
88 };
89
90 ParsedStyleSheet::ParsedStyleSheet()
91     : m_hasText(false)
92 {
93 }
94
95 void ParsedStyleSheet::setText(const String& text)
96 {
97     m_hasText = true;
98     m_text = text;
99     setSourceData(nullptr);
100 }
101
102 static void flattenSourceData(RuleSourceDataList* dataList, RuleSourceDataList* target)
103 {
104     for (size_t i = 0; i < dataList->size(); ++i) {
105         RefPtr<CSSRuleSourceData>& data = dataList->at(i);
106         if (data->type == CSSRuleSourceData::STYLE_RULE)
107             target->append(data);
108         else if (data->type == CSSRuleSourceData::MEDIA_RULE)
109             flattenSourceData(&data->childRules, target);
110 #if ENABLE(CSS3_CONDITIONAL_RULES)
111         else if (data->type == CSSRuleSourceData::SUPPORTS_RULE)
112             flattenSourceData(&data->childRules, target);
113 #endif
114     }
115 }
116
117 void ParsedStyleSheet::setSourceData(std::unique_ptr<RuleSourceDataList> sourceData)
118 {
119     if (!sourceData) {
120         m_sourceData.reset();
121         return;
122     }
123
124     m_sourceData = std::make_unique<RuleSourceDataList>();
125
126     // FIXME: This is a temporary solution to retain the original flat sourceData structure
127     // containing only style rules, even though CSSParser now provides the full rule source data tree.
128     // Normally, we should just assign m_sourceData = sourceData;
129     flattenSourceData(sourceData.get(), m_sourceData.get());
130 }
131
132 PassRefPtr<WebCore::CSSRuleSourceData> ParsedStyleSheet::ruleSourceDataAt(unsigned index) const
133 {
134     if (!hasSourceData() || index >= m_sourceData->size())
135         return nullptr;
136
137     return m_sourceData->at(index);
138 }
139
140 using namespace Inspector;
141
142 namespace WebCore {
143
144 enum MediaListSource {
145     MediaListSourceLinkedSheet,
146     MediaListSourceInlineSheet,
147     MediaListSourceMediaRule,
148     MediaListSourceImportRule
149 };
150
151 static PassRefPtr<Inspector::TypeBuilder::CSS::SourceRange> buildSourceRangeObject(const SourceRange& range, Vector<size_t>* lineEndings)
152 {
153     if (!lineEndings)
154         return nullptr;
155     TextPosition start = ContentSearchUtilities::textPositionFromOffset(range.start, *lineEndings);
156     TextPosition end = ContentSearchUtilities::textPositionFromOffset(range.end, *lineEndings);
157
158     RefPtr<Inspector::TypeBuilder::CSS::SourceRange> result = Inspector::TypeBuilder::CSS::SourceRange::create()
159         .setStartLine(start.m_line.zeroBasedInt())
160         .setStartColumn(start.m_column.zeroBasedInt())
161         .setEndLine(end.m_line.zeroBasedInt())
162         .setEndColumn(end.m_column.zeroBasedInt());
163     return result.release();
164 }
165
166 static PassRefPtr<Inspector::TypeBuilder::CSS::CSSMedia> buildMediaObject(const MediaList* media, MediaListSource mediaListSource, const String& sourceURL)
167 {
168     // Make certain compilers happy by initializing |source| up-front.
169     Inspector::TypeBuilder::CSS::CSSMedia::Source::Enum source = Inspector::TypeBuilder::CSS::CSSMedia::Source::InlineSheet;
170     switch (mediaListSource) {
171     case MediaListSourceMediaRule:
172         source = Inspector::TypeBuilder::CSS::CSSMedia::Source::MediaRule;
173         break;
174     case MediaListSourceImportRule:
175         source = Inspector::TypeBuilder::CSS::CSSMedia::Source::ImportRule;
176         break;
177     case MediaListSourceLinkedSheet:
178         source = Inspector::TypeBuilder::CSS::CSSMedia::Source::LinkedSheet;
179         break;
180     case MediaListSourceInlineSheet:
181         source = Inspector::TypeBuilder::CSS::CSSMedia::Source::InlineSheet;
182         break;
183     }
184
185     RefPtr<Inspector::TypeBuilder::CSS::CSSMedia> mediaObject = Inspector::TypeBuilder::CSS::CSSMedia::create()
186         .setText(media->mediaText())
187         .setSource(source);
188
189     if (!sourceURL.isEmpty()) {
190         mediaObject->setSourceURL(sourceURL);
191         mediaObject->setSourceLine(media->queries()->lastLine());
192     }
193     return mediaObject.release();
194 }
195
196 static PassRefPtr<CSSRuleList> asCSSRuleList(CSSStyleSheet* styleSheet)
197 {
198     if (!styleSheet)
199         return nullptr;
200
201     RefPtr<StaticCSSRuleList> list = StaticCSSRuleList::create();
202     Vector<RefPtr<CSSRule>>& listRules = list->rules();
203     for (unsigned i = 0, size = styleSheet->length(); i < size; ++i) {
204         CSSRule* item = styleSheet->item(i);
205         if (item->type() == CSSRule::CHARSET_RULE)
206             continue;
207         listRules.append(item);
208     }
209     return list.release();
210 }
211
212 static PassRefPtr<CSSRuleList> asCSSRuleList(CSSRule* rule)
213 {
214     if (!rule)
215         return nullptr;
216
217     if (rule->type() == CSSRule::MEDIA_RULE)
218         return static_cast<CSSMediaRule*>(rule)->cssRules();
219
220     if (rule->type() == CSSRule::WEBKIT_KEYFRAMES_RULE)
221         return static_cast<WebKitCSSKeyframesRule*>(rule)->cssRules();
222
223 #if ENABLE(CSS3_CONDITIONAL_RULES)
224     if (rule->type() == CSSRule::SUPPORTS_RULE)
225         return static_cast<CSSSupportsRule*>(rule)->cssRules();
226 #endif
227
228     return nullptr;
229 }
230
231 static void fillMediaListChain(CSSRule* rule, Array<Inspector::TypeBuilder::CSS::CSSMedia>* mediaArray)
232 {
233     MediaList* mediaList;
234     CSSRule* parentRule = rule;
235     String sourceURL;
236     while (parentRule) {
237         CSSStyleSheet* parentStyleSheet = nullptr;
238         bool isMediaRule = true;
239         if (parentRule->type() == CSSRule::MEDIA_RULE) {
240             CSSMediaRule* mediaRule = static_cast<CSSMediaRule*>(parentRule);
241             mediaList = mediaRule->media();
242             parentStyleSheet = mediaRule->parentStyleSheet();
243         } else if (parentRule->type() == CSSRule::IMPORT_RULE) {
244             CSSImportRule* importRule = static_cast<CSSImportRule*>(parentRule);
245             mediaList = importRule->media();
246             parentStyleSheet = importRule->parentStyleSheet();
247             isMediaRule = false;
248         } else
249             mediaList = nullptr;
250
251         if (parentStyleSheet) {
252             sourceURL = parentStyleSheet->contents().baseURL();
253             if (sourceURL.isEmpty())
254                 sourceURL = InspectorDOMAgent::documentURLString(parentStyleSheet->ownerDocument());
255         } else
256             sourceURL = "";
257
258         if (mediaList && mediaList->length())
259             mediaArray->addItem(buildMediaObject(mediaList, isMediaRule ? MediaListSourceMediaRule : MediaListSourceImportRule, sourceURL));
260
261         if (parentRule->parentRule())
262             parentRule = parentRule->parentRule();
263         else {
264             CSSStyleSheet* styleSheet = parentRule->parentStyleSheet();
265             while (styleSheet) {
266                 mediaList = styleSheet->media();
267                 if (mediaList && mediaList->length()) {
268                     Document* doc = styleSheet->ownerDocument();
269                     if (doc)
270                         sourceURL = doc->url();
271                     else if (!styleSheet->contents().baseURL().isEmpty())
272                         sourceURL = styleSheet->contents().baseURL();
273                     else
274                         sourceURL = "";
275                     mediaArray->addItem(buildMediaObject(mediaList, styleSheet->ownerNode() ? MediaListSourceLinkedSheet : MediaListSourceInlineSheet, sourceURL));
276                 }
277                 parentRule = styleSheet->ownerRule();
278                 if (parentRule)
279                     break;
280                 styleSheet = styleSheet->parentStyleSheet();
281             }
282         }
283     }
284 }
285
286 static std::unique_ptr<CSSParser> createCSSParser(Document* document)
287 {
288     return std::make_unique<CSSParser>(document ? CSSParserContext(*document) : strictCSSParserContext());
289 }
290
291 PassRefPtr<InspectorStyle> InspectorStyle::create(const InspectorCSSId& styleId, PassRefPtr<CSSStyleDeclaration> style, InspectorStyleSheet* parentStyleSheet)
292 {
293     return adoptRef(new InspectorStyle(styleId, style, parentStyleSheet));
294 }
295
296 InspectorStyle::InspectorStyle(const InspectorCSSId& styleId, PassRefPtr<CSSStyleDeclaration> style, InspectorStyleSheet* parentStyleSheet)
297     : m_styleId(styleId)
298     , m_style(style)
299     , m_parentStyleSheet(parentStyleSheet)
300     , m_formatAcquired(false)
301 {
302     ASSERT(m_style);
303 }
304
305 InspectorStyle::~InspectorStyle()
306 {
307 }
308
309 PassRefPtr<Inspector::TypeBuilder::CSS::CSSStyle> InspectorStyle::buildObjectForStyle() const
310 {
311     RefPtr<Inspector::TypeBuilder::CSS::CSSStyle> result = styleWithProperties();
312     if (!m_styleId.isEmpty())
313         result->setStyleId(m_styleId.asProtocolValue<Inspector::TypeBuilder::CSS::CSSStyleId>());
314
315     result->setWidth(m_style->getPropertyValue("width"));
316     result->setHeight(m_style->getPropertyValue("height"));
317
318     RefPtr<CSSRuleSourceData> sourceData = extractSourceData();
319     if (sourceData)
320         result->setRange(buildSourceRangeObject(sourceData->ruleBodyRange, m_parentStyleSheet->lineEndings().get()));
321
322     return result.release();
323 }
324
325 PassRefPtr<Inspector::TypeBuilder::Array<Inspector::TypeBuilder::CSS::CSSComputedStyleProperty>> InspectorStyle::buildArrayForComputedStyle() const
326 {
327     RefPtr<Inspector::TypeBuilder::Array<Inspector::TypeBuilder::CSS::CSSComputedStyleProperty>> result = Inspector::TypeBuilder::Array<Inspector::TypeBuilder::CSS::CSSComputedStyleProperty>::create();
328     Vector<InspectorStyleProperty> properties;
329     populateAllProperties(&properties);
330
331     for (Vector<InspectorStyleProperty>::iterator it = properties.begin(), itEnd = properties.end(); it != itEnd; ++it) {
332         const CSSPropertySourceData& propertyEntry = it->sourceData;
333         RefPtr<Inspector::TypeBuilder::CSS::CSSComputedStyleProperty> entry = Inspector::TypeBuilder::CSS::CSSComputedStyleProperty::create()
334             .setName(propertyEntry.name)
335             .setValue(propertyEntry.value);
336         result->addItem(entry);
337     }
338
339     return result.release();
340 }
341
342 // This method does the following preprocessing of |propertyText| with |overwrite| == false and |index| past the last active property:
343 // - If the last property (if present) has no closing ";", the ";" is prepended to the current |propertyText| value.
344 // - A heuristic formatting is attempted to retain the style structure.
345 //
346 // The propertyText (if not empty) is checked to be a valid style declaration (containing at least one property). If not,
347 // the method returns false (denoting an error).
348 bool InspectorStyle::setPropertyText(unsigned index, const String& propertyText, bool overwrite, String* oldText, ExceptionCode& ec)
349 {
350     ASSERT(m_parentStyleSheet);
351     DEPRECATED_DEFINE_STATIC_LOCAL(String, bogusPropertyName, (ASCIILiteral("-webkit-boguz-propertee")));
352
353     if (!m_parentStyleSheet->ensureParsedDataReady()) {
354         ec = NOT_FOUND_ERR;
355         return false;
356     }
357
358     if (propertyText.stripWhiteSpace().length()) {
359         RefPtr<MutableStyleProperties> tempMutableStyle = MutableStyleProperties::create();
360         RefPtr<CSSRuleSourceData> sourceData = CSSRuleSourceData::create(CSSRuleSourceData::STYLE_RULE);
361         Document* ownerDocument = m_parentStyleSheet->pageStyleSheet() ? m_parentStyleSheet->pageStyleSheet()->ownerDocument() : nullptr;
362         createCSSParser(ownerDocument)->parseDeclaration(tempMutableStyle.get(), propertyText + " " + bogusPropertyName + ": none", sourceData, &m_style->parentStyleSheet()->contents());
363         Vector<CSSPropertySourceData>& propertyData = sourceData->styleSourceData->propertyData;
364         unsigned propertyCount = propertyData.size();
365
366         // At least one property + the bogus property added just above should be present.
367         if (propertyCount < 2) {
368             ec = SYNTAX_ERR;
369             return false;
370         }
371
372         // Check for a proper propertyText termination (the parser could at least restore to the PROPERTY_NAME state).
373         if (propertyData.at(propertyCount - 1).name != bogusPropertyName) {
374             ec = SYNTAX_ERR;
375             return false;
376         }
377     }
378
379     RefPtr<CSSRuleSourceData> sourceData = extractSourceData();
380     if (!sourceData) {
381         ec = NOT_FOUND_ERR;
382         return false;
383     }
384
385     String text;
386     bool success = styleText(&text);
387     if (!success) {
388         ec = NOT_FOUND_ERR;
389         return false;
390     }
391
392     Vector<InspectorStyleProperty> allProperties;
393     populateAllProperties(&allProperties);
394
395     InspectorStyleTextEditor editor(&allProperties, &m_disabledProperties, text, newLineAndWhitespaceDelimiters());
396     if (overwrite) {
397         if (index >= allProperties.size()) {
398             ec = INDEX_SIZE_ERR;
399             return false;
400         }
401         *oldText = allProperties.at(index).rawText;
402         editor.replaceProperty(index, propertyText);
403     } else
404         editor.insertProperty(index, propertyText, sourceData->ruleBodyRange.length());
405
406     return applyStyleText(editor.styleText());
407 }
408
409 bool InspectorStyle::toggleProperty(unsigned index, bool disable, ExceptionCode& ec)
410 {
411     ASSERT(m_parentStyleSheet);
412     if (!m_parentStyleSheet->ensureParsedDataReady()) {
413         ec = NO_MODIFICATION_ALLOWED_ERR;
414         return false;
415     }
416
417     RefPtr<CSSRuleSourceData> sourceData = extractSourceData();
418     if (!sourceData) {
419         ec = NOT_FOUND_ERR;
420         return false;
421     }
422
423     String text;
424     bool success = styleText(&text);
425     if (!success) {
426         ec = NOT_FOUND_ERR;
427         return false;
428     }
429
430     Vector<InspectorStyleProperty> allProperties;
431     populateAllProperties(&allProperties);
432     if (index >= allProperties.size()) {
433         ec = INDEX_SIZE_ERR;
434         return false;
435     }
436
437     InspectorStyleProperty& property = allProperties.at(index);
438     if (property.disabled == disable)
439         return true; // Idempotent operation.
440
441     InspectorStyleTextEditor editor(&allProperties, &m_disabledProperties, text, newLineAndWhitespaceDelimiters());
442     if (disable)
443         editor.disableProperty(index);
444     else
445         editor.enableProperty(index);
446
447     return applyStyleText(editor.styleText());
448 }
449
450 bool InspectorStyle::getText(String* result) const
451 {
452     // Precondition: m_parentStyleSheet->ensureParsedDataReady() has been called successfully.
453     RefPtr<CSSRuleSourceData> sourceData = extractSourceData();
454     if (!sourceData)
455         return false;
456
457     String styleSheetText;
458     bool success = m_parentStyleSheet->getText(&styleSheetText);
459     if (!success)
460         return false;
461
462     SourceRange& bodyRange = sourceData->ruleBodyRange;
463     *result = styleSheetText.substring(bodyRange.start, bodyRange.end - bodyRange.start);
464     return true;
465 }
466
467 bool InspectorStyle::populateAllProperties(Vector<InspectorStyleProperty>* result) const
468 {
469     HashSet<String> sourcePropertyNames;
470     unsigned disabledIndex = 0;
471     unsigned disabledLength = m_disabledProperties.size();
472     InspectorStyleProperty disabledProperty;
473     if (disabledIndex < disabledLength)
474         disabledProperty = m_disabledProperties.at(disabledIndex);
475
476     RefPtr<CSSRuleSourceData> sourceData = extractSourceData();
477     Vector<CSSPropertySourceData>* sourcePropertyData = sourceData ? &(sourceData->styleSourceData->propertyData) : nullptr;
478     if (sourcePropertyData) {
479         String styleDeclaration;
480         bool isStyleTextKnown = styleText(&styleDeclaration);
481         ASSERT_UNUSED(isStyleTextKnown, isStyleTextKnown);
482         for (Vector<CSSPropertySourceData>::const_iterator it = sourcePropertyData->begin(); it != sourcePropertyData->end(); ++it) {
483             while (disabledIndex < disabledLength && disabledProperty.sourceData.range.start <= it->range.start) {
484                 result->append(disabledProperty);
485                 if (++disabledIndex < disabledLength)
486                     disabledProperty = m_disabledProperties.at(disabledIndex);
487             }
488             InspectorStyleProperty p(*it, true, false);
489             p.setRawTextFromStyleDeclaration(styleDeclaration);
490             result->append(p);
491             sourcePropertyNames.add(it->name.lower());
492         }
493     }
494
495     while (disabledIndex < disabledLength) {
496         disabledProperty = m_disabledProperties.at(disabledIndex++);
497         result->append(disabledProperty);
498     }
499
500     for (int i = 0, size = m_style->length(); i < size; ++i) {
501         String name = m_style->item(i);
502         if (sourcePropertyNames.contains(name.lower()))
503             continue;
504
505         sourcePropertyNames.add(name.lower());
506         result->append(InspectorStyleProperty(CSSPropertySourceData(name, m_style->getPropertyValue(name), !m_style->getPropertyPriority(name).isEmpty(), true, SourceRange()), false, false));
507     }
508
509     return true;
510 }
511
512 PassRefPtr<Inspector::TypeBuilder::CSS::CSSStyle> InspectorStyle::styleWithProperties() const
513 {
514     Vector<InspectorStyleProperty> properties;
515     populateAllProperties(&properties);
516
517     RefPtr<Array<Inspector::TypeBuilder::CSS::CSSProperty>> propertiesObject = Array<Inspector::TypeBuilder::CSS::CSSProperty>::create();
518     RefPtr<Array<Inspector::TypeBuilder::CSS::ShorthandEntry>> shorthandEntries = Array<Inspector::TypeBuilder::CSS::ShorthandEntry>::create();
519     HashMap<String, RefPtr<Inspector::TypeBuilder::CSS::CSSProperty>> propertyNameToPreviousActiveProperty;
520     HashSet<String> foundShorthands;
521     String previousPriority;
522     String previousStatus;
523     std::unique_ptr<Vector<size_t>> lineEndings(m_parentStyleSheet ? m_parentStyleSheet->lineEndings() : nullptr);
524     RefPtr<CSSRuleSourceData> sourceData = extractSourceData();
525     unsigned ruleBodyRangeStart = sourceData ? sourceData->ruleBodyRange.start : 0;
526
527     for (Vector<InspectorStyleProperty>::iterator it = properties.begin(), itEnd = properties.end(); it != itEnd; ++it) {
528         const CSSPropertySourceData& propertyEntry = it->sourceData;
529         const String& name = propertyEntry.name;
530
531         Inspector::TypeBuilder::CSS::CSSProperty::Status::Enum status = it->disabled ? Inspector::TypeBuilder::CSS::CSSProperty::Status::Disabled : Inspector::TypeBuilder::CSS::CSSProperty::Status::Active;
532
533         RefPtr<Inspector::TypeBuilder::CSS::CSSProperty> property = Inspector::TypeBuilder::CSS::CSSProperty::create()
534             .setName(name)
535             .setValue(propertyEntry.value);
536
537         propertiesObject->addItem(property);
538
539         // Default "parsedOk" == true.
540         if (!propertyEntry.parsedOk)
541             property->setParsedOk(false);
542         if (it->hasRawText())
543             property->setText(it->rawText);
544
545         // Default "priority" == "".
546         if (propertyEntry.important)
547             property->setPriority("important");
548         if (!it->disabled) {
549             if (it->hasSource) {
550                 ASSERT(sourceData);
551                 property->setImplicit(false);
552                 // The property range is relative to the style body start.
553                 // Should be converted into an absolute range (relative to the stylesheet start)
554                 // for the proper conversion into line:column.
555                 SourceRange absolutePropertyRange = propertyEntry.range;
556                 absolutePropertyRange.start += ruleBodyRangeStart;
557                 absolutePropertyRange.end += ruleBodyRangeStart;
558                 property->setRange(buildSourceRangeObject(absolutePropertyRange, lineEndings.get()));
559
560                 // Parsed property overrides any property with the same name. Non-parsed property overrides
561                 // previous non-parsed property with the same name (if any).
562                 bool shouldInactivate = false;
563                 CSSPropertyID propertyId = cssPropertyID(name);
564                 // Canonicalize property names to treat non-prefixed and vendor-prefixed property names the same (opacity vs. -webkit-opacity).
565                 String canonicalPropertyName = propertyId ? getPropertyNameString(propertyId) : name;
566                 HashMap<String, RefPtr<Inspector::TypeBuilder::CSS::CSSProperty>>::iterator activeIt = propertyNameToPreviousActiveProperty.find(canonicalPropertyName);
567                 if (activeIt != propertyNameToPreviousActiveProperty.end()) {
568                     if (propertyEntry.parsedOk) {
569                         bool successPriority = activeIt->value->getString(Inspector::TypeBuilder::CSS::CSSProperty::Priority, &previousPriority);
570                         bool successStatus = activeIt->value->getString(Inspector::TypeBuilder::CSS::CSSProperty::Status, &previousStatus);
571                         if (successStatus && previousStatus != "inactive") {
572                             if (propertyEntry.important || !successPriority) // Priority not set == "not important".
573                                 shouldInactivate = true;
574                             else if (status == Inspector::TypeBuilder::CSS::CSSProperty::Status::Active) {
575                                 // Inactivate a non-important property following the same-named important property.
576                                 status = Inspector::TypeBuilder::CSS::CSSProperty::Status::Inactive;
577                             }
578                         }
579                     } else {
580                         bool previousParsedOk;
581                         bool success = activeIt->value->getBoolean(Inspector::TypeBuilder::CSS::CSSProperty::ParsedOk, &previousParsedOk);
582                         if (success && !previousParsedOk)
583                             shouldInactivate = true;
584                     }
585                 } else
586                     propertyNameToPreviousActiveProperty.set(canonicalPropertyName, property);
587
588                 if (shouldInactivate) {
589                     activeIt->value->setStatus(Inspector::TypeBuilder::CSS::CSSProperty::Status::Inactive);
590                     propertyNameToPreviousActiveProperty.set(canonicalPropertyName, property);
591                 }
592             } else {
593                 bool implicit = m_style->isPropertyImplicit(name);
594                 // Default "implicit" == false.
595                 if (implicit)
596                     property->setImplicit(true);
597                 status = Inspector::TypeBuilder::CSS::CSSProperty::Status::Style;
598
599                 String shorthand = m_style->getPropertyShorthand(name);
600                 if (!shorthand.isEmpty()) {
601                     if (!foundShorthands.contains(shorthand)) {
602                         foundShorthands.add(shorthand);
603                         RefPtr<Inspector::TypeBuilder::CSS::ShorthandEntry> entry = Inspector::TypeBuilder::CSS::ShorthandEntry::create()
604                             .setName(shorthand)
605                             .setValue(shorthandValue(shorthand));
606                         shorthandEntries->addItem(entry);
607                     }
608                 }
609             }
610         }
611
612         // Default "status" == "style".
613         if (status != Inspector::TypeBuilder::CSS::CSSProperty::Status::Style)
614             property->setStatus(status);
615     }
616
617     RefPtr<Inspector::TypeBuilder::CSS::CSSStyle> result = Inspector::TypeBuilder::CSS::CSSStyle::create()
618         .setCssProperties(propertiesObject)
619         .setShorthandEntries(shorthandEntries);
620     return result.release();
621 }
622
623 PassRefPtr<CSSRuleSourceData> InspectorStyle::extractSourceData() const
624 {
625     if (!m_parentStyleSheet || !m_parentStyleSheet->ensureParsedDataReady())
626         return nullptr;
627     return m_parentStyleSheet->ruleSourceDataFor(m_style.get());
628 }
629
630 bool InspectorStyle::setText(const String& text, ExceptionCode& ec)
631 {
632     return m_parentStyleSheet->setStyleText(m_style.get(), text, ec);
633 }
634
635 String InspectorStyle::shorthandValue(const String& shorthandProperty) const
636 {
637     String value = m_style->getPropertyValue(shorthandProperty);
638     if (value.isEmpty()) {
639         for (unsigned i = 0; i < m_style->length(); ++i) {
640             String individualProperty = m_style->item(i);
641             if (m_style->getPropertyShorthand(individualProperty) != shorthandProperty)
642                 continue;
643             if (m_style->isPropertyImplicit(individualProperty))
644                 continue;
645             String individualValue = m_style->getPropertyValue(individualProperty);
646             if (individualValue == "initial")
647                 continue;
648             if (value.length())
649                 value.append(" ");
650             value.append(individualValue);
651         }
652     }
653     return value;
654 }
655
656 String InspectorStyle::shorthandPriority(const String& shorthandProperty) const
657 {
658     String priority = m_style->getPropertyPriority(shorthandProperty);
659     if (priority.isEmpty()) {
660         for (unsigned i = 0; i < m_style->length(); ++i) {
661             String individualProperty = m_style->item(i);
662             if (m_style->getPropertyShorthand(individualProperty) != shorthandProperty)
663                 continue;
664             priority = m_style->getPropertyPriority(individualProperty);
665             break;
666         }
667     }
668     return priority;
669 }
670
671 Vector<String> InspectorStyle::longhandProperties(const String& shorthandProperty) const
672 {
673     Vector<String> properties;
674     HashSet<String> foundProperties;
675     for (unsigned i = 0; i < m_style->length(); ++i) {
676         String individualProperty = m_style->item(i);
677         if (foundProperties.contains(individualProperty) || m_style->getPropertyShorthand(individualProperty) != shorthandProperty)
678             continue;
679
680         foundProperties.add(individualProperty);
681         properties.append(individualProperty);
682     }
683     return properties;
684 }
685
686 NewLineAndWhitespace& InspectorStyle::newLineAndWhitespaceDelimiters() const
687 {
688     DEPRECATED_DEFINE_STATIC_LOCAL(String, defaultPrefix, (ASCIILiteral("    ")));
689
690     if (m_formatAcquired)
691         return m_format;
692
693     RefPtr<CSSRuleSourceData> sourceData = extractSourceData();
694     Vector<CSSPropertySourceData>* sourcePropertyData = sourceData ? &(sourceData->styleSourceData->propertyData) : nullptr;
695     int propertyCount;
696     if (!sourcePropertyData || !(propertyCount = sourcePropertyData->size())) {
697         m_format.first = "\n";
698         m_format.second = defaultPrefix;
699         return m_format; // Do not remember the default formatting and attempt to acquire it later.
700     }
701
702     String text;
703     bool success = styleText(&text);
704     ASSERT_UNUSED(success, success);
705
706     m_formatAcquired = true;
707
708     String candidatePrefix = defaultPrefix;
709     StringBuilder formatLineFeed;
710     StringBuilder prefix;
711     int scanStart = 0;
712     int propertyIndex = 0;
713     bool isFullPrefixScanned = false;
714     bool lineFeedTerminated = false;
715     while (propertyIndex < propertyCount) {
716         const WebCore::CSSPropertySourceData& currentProperty = sourcePropertyData->at(propertyIndex++);
717
718         bool processNextProperty = false;
719         int scanEnd = currentProperty.range.start;
720         for (int i = scanStart; i < scanEnd; ++i) {
721             UChar ch = text[i];
722             bool isLineFeed = isHTMLLineBreak(ch);
723             if (isLineFeed) {
724                 if (!lineFeedTerminated)
725                     formatLineFeed.append(ch);
726                 prefix.clear();
727             } else if (isHTMLSpace(ch))
728                 prefix.append(ch);
729             else {
730                 candidatePrefix = prefix.toString();
731                 prefix.clear();
732                 scanStart = currentProperty.range.end;
733                 ++propertyIndex;
734                 processNextProperty = true;
735                 break;
736             }
737             if (!isLineFeed && formatLineFeed.length())
738                 lineFeedTerminated = true;
739         }
740         if (!processNextProperty) {
741             isFullPrefixScanned = true;
742             break;
743         }
744     }
745
746     m_format.first = formatLineFeed.toString();
747     m_format.second = isFullPrefixScanned ? prefix.toString() : candidatePrefix;
748     return m_format;
749 }
750
751 PassRefPtr<InspectorStyleSheet> InspectorStyleSheet::create(InspectorPageAgent* pageAgent, const String& id, PassRefPtr<CSSStyleSheet> pageStyleSheet, Inspector::TypeBuilder::CSS::StyleSheetOrigin::Enum origin, const String& documentURL, Listener* listener)
752 {
753     return adoptRef(new InspectorStyleSheet(pageAgent, id, pageStyleSheet, origin, documentURL, listener));
754 }
755
756 // static
757 String InspectorStyleSheet::styleSheetURL(CSSStyleSheet* pageStyleSheet)
758 {
759     if (pageStyleSheet && !pageStyleSheet->contents().baseURL().isEmpty())
760         return pageStyleSheet->contents().baseURL().string();
761     return emptyString();
762 }
763
764 InspectorStyleSheet::InspectorStyleSheet(InspectorPageAgent* pageAgent, const String& id, PassRefPtr<CSSStyleSheet> pageStyleSheet, Inspector::TypeBuilder::CSS::StyleSheetOrigin::Enum origin, const String& documentURL, Listener* listener)
765     : m_pageAgent(pageAgent)
766     , m_id(id)
767     , m_pageStyleSheet(pageStyleSheet)
768     , m_origin(origin)
769     , m_documentURL(documentURL)
770     , m_isRevalidating(false)
771     , m_listener(listener)
772 {
773     m_parsedStyleSheet = new ParsedStyleSheet();
774 }
775
776 InspectorStyleSheet::~InspectorStyleSheet()
777 {
778     delete m_parsedStyleSheet;
779 }
780
781 String InspectorStyleSheet::finalURL() const
782 {
783     String url = styleSheetURL(m_pageStyleSheet.get());
784     return url.isEmpty() ? m_documentURL : url;
785 }
786
787 void InspectorStyleSheet::reparseStyleSheet(const String& text)
788 {
789     {
790         // Have a separate scope for clearRules() (bug 95324).
791         CSSStyleSheet::RuleMutationScope mutationScope(m_pageStyleSheet.get());
792         m_pageStyleSheet->contents().clearRules();
793     }
794     {
795         CSSStyleSheet::RuleMutationScope mutationScope(m_pageStyleSheet.get());
796         m_pageStyleSheet->contents().parseString(text);
797         m_pageStyleSheet->clearChildRuleCSSOMWrappers();
798         m_inspectorStyles.clear();
799         fireStyleSheetChanged();
800     }
801 }
802
803 bool InspectorStyleSheet::setText(const String& text, ExceptionCode& ec)
804 {
805     if (!checkPageStyleSheet(ec))
806         return false;
807     if (!m_parsedStyleSheet)
808         return false;
809
810     m_parsedStyleSheet->setText(text);
811     m_flatRules.clear();
812
813     return true;
814 }
815
816 String InspectorStyleSheet::ruleSelector(const InspectorCSSId& id, ExceptionCode& ec)
817 {
818     CSSStyleRule* rule = ruleForId(id);
819     if (!rule) {
820         ec = NOT_FOUND_ERR;
821         return "";
822     }
823     return rule->selectorText();
824 }
825
826 bool InspectorStyleSheet::setRuleSelector(const InspectorCSSId& id, const String& selector, ExceptionCode& ec)
827 {
828     if (!checkPageStyleSheet(ec))
829         return false;
830     CSSStyleRule* rule = ruleForId(id);
831     if (!rule) {
832         ec = NOT_FOUND_ERR;
833         return false;
834     }
835     CSSStyleSheet* styleSheet = rule->parentStyleSheet();
836     if (!styleSheet || !ensureParsedDataReady()) {
837         ec = NOT_FOUND_ERR;
838         return false;
839     }
840
841     rule->setSelectorText(selector);
842     RefPtr<CSSRuleSourceData> sourceData = ruleSourceDataFor(rule->style());
843     if (!sourceData) {
844         ec = NOT_FOUND_ERR;
845         return false;
846     }
847
848     String sheetText = m_parsedStyleSheet->text();
849     sheetText.replace(sourceData->ruleHeaderRange.start, sourceData->ruleHeaderRange.length(), selector);
850     m_parsedStyleSheet->setText(sheetText);
851     fireStyleSheetChanged();
852     return true;
853 }
854
855 static bool checkStyleRuleSelector(Document* document, const String& selector)
856 {
857     CSSSelectorList selectorList;
858     createCSSParser(document)->parseSelector(selector, selectorList);
859     return selectorList.isValid();
860 }
861
862 CSSStyleRule* InspectorStyleSheet::addRule(const String& selector, ExceptionCode& ec)
863 {
864     if (!checkPageStyleSheet(ec))
865         return nullptr;
866     if (!checkStyleRuleSelector(m_pageStyleSheet->ownerDocument(), selector)) {
867         ec = SYNTAX_ERR;
868         return nullptr;
869     }
870
871     String text;
872     bool success = getText(&text);
873     if (!success) {
874         ec = NOT_FOUND_ERR;
875         return nullptr;
876     }
877     StringBuilder styleSheetText;
878     styleSheetText.append(text);
879
880     m_pageStyleSheet->addRule(selector, "", ec);
881     if (ec)
882         return nullptr;
883     ASSERT(m_pageStyleSheet->length());
884     unsigned lastRuleIndex = m_pageStyleSheet->length() - 1;
885     CSSRule* rule = m_pageStyleSheet->item(lastRuleIndex);
886     ASSERT(rule);
887
888     CSSStyleRule* styleRule = InspectorCSSAgent::asCSSStyleRule(rule);
889     if (!styleRule) {
890         // What we just added has to be a CSSStyleRule - we cannot handle other types of rules yet.
891         // If it is not a style rule, pretend we never touched the stylesheet.
892         m_pageStyleSheet->deleteRule(lastRuleIndex, ASSERT_NO_EXCEPTION);
893         ec = SYNTAX_ERR;
894         return nullptr;
895     }
896
897     if (!styleSheetText.isEmpty())
898         styleSheetText.append('\n');
899
900     styleSheetText.append(selector);
901     styleSheetText.appendLiteral(" {}");
902     // Using setText() as this operation changes the style sheet rule set.
903     setText(styleSheetText.toString(), ASSERT_NO_EXCEPTION);
904
905     fireStyleSheetChanged();
906
907     return styleRule;
908 }
909
910 bool InspectorStyleSheet::deleteRule(const InspectorCSSId& id, ExceptionCode& ec)
911 {
912     if (!checkPageStyleSheet(ec))
913         return false;
914     RefPtr<CSSStyleRule> rule = ruleForId(id);
915     if (!rule) {
916         ec = NOT_FOUND_ERR;
917         return false;
918     }
919     CSSStyleSheet* styleSheet = rule->parentStyleSheet();
920     if (!styleSheet || !ensureParsedDataReady()) {
921         ec = NOT_FOUND_ERR;
922         return false;
923     }
924
925     RefPtr<CSSRuleSourceData> sourceData = ruleSourceDataFor(rule->style());
926     if (!sourceData) {
927         ec = NOT_FOUND_ERR;
928         return false;
929     }
930
931     styleSheet->deleteRule(id.ordinal(), ec);
932     // |rule| MAY NOT be addressed after this line!
933
934     if (ec)
935         return false;
936
937     String sheetText = m_parsedStyleSheet->text();
938     sheetText.remove(sourceData->ruleHeaderRange.start, sourceData->ruleBodyRange.end - sourceData->ruleHeaderRange.start + 1);
939     setText(sheetText, ASSERT_NO_EXCEPTION);
940     fireStyleSheetChanged();
941     return true;
942 }
943
944 CSSStyleRule* InspectorStyleSheet::ruleForId(const InspectorCSSId& id) const
945 {
946     if (!m_pageStyleSheet)
947         return nullptr;
948
949     ASSERT(!id.isEmpty());
950     ensureFlatRules();
951     return id.ordinal() >= m_flatRules.size() ? nullptr : m_flatRules.at(id.ordinal()).get();
952
953 }
954
955 PassRefPtr<Inspector::TypeBuilder::CSS::CSSStyleSheetBody> InspectorStyleSheet::buildObjectForStyleSheet()
956 {
957     CSSStyleSheet* styleSheet = pageStyleSheet();
958     if (!styleSheet)
959         return nullptr;
960
961     RefPtr<CSSRuleList> cssRuleList = asCSSRuleList(styleSheet);
962
963     RefPtr<Inspector::TypeBuilder::CSS::CSSStyleSheetBody> result = Inspector::TypeBuilder::CSS::CSSStyleSheetBody::create()
964         .setStyleSheetId(id())
965         .setRules(buildArrayForRuleList(cssRuleList.get()));
966
967     String styleSheetText;
968     bool success = getText(&styleSheetText);
969     if (success)
970         result->setText(styleSheetText);
971
972     return result.release();
973 }
974
975 PassRefPtr<Inspector::TypeBuilder::CSS::CSSStyleSheetHeader> InspectorStyleSheet::buildObjectForStyleSheetInfo()
976 {
977     CSSStyleSheet* styleSheet = pageStyleSheet();
978     if (!styleSheet)
979         return nullptr;
980
981     Document* document = styleSheet->ownerDocument();
982     Frame* frame = document ? document->frame() : nullptr;
983     RefPtr<Inspector::TypeBuilder::CSS::CSSStyleSheetHeader> result = Inspector::TypeBuilder::CSS::CSSStyleSheetHeader::create()
984         .setStyleSheetId(id())
985         .setOrigin(m_origin)
986         .setDisabled(styleSheet->disabled())
987         .setSourceURL(finalURL())
988         .setTitle(styleSheet->title())
989         .setFrameId(m_pageAgent->frameId(frame));
990
991     return result.release();
992 }
993
994 static PassRefPtr<Inspector::TypeBuilder::Array<String>> selectorsFromSource(const CSSRuleSourceData* sourceData, const String& sheetText)
995 {
996     DEPRECATED_DEFINE_STATIC_LOCAL(JSC::Yarr::RegularExpression, comment, ("/\\*[^]*?\\*/", TextCaseSensitive, JSC::Yarr::MultilineEnabled));
997     RefPtr<Inspector::TypeBuilder::Array<String>> result = Inspector::TypeBuilder::Array<String>::create();
998     const SelectorRangeList& ranges = sourceData->selectorRanges;
999     for (size_t i = 0, size = ranges.size(); i < size; ++i) {
1000         const SourceRange& range = ranges.at(i);
1001         String selector = sheetText.substring(range.start, range.length());
1002
1003         // We don't want to see any comments in the selector components, only the meaningful parts.
1004         replace(selector, comment, "");
1005         result->addItem(selector.stripWhiteSpace());
1006     }
1007     return result.release();
1008 }
1009
1010 PassRefPtr<Inspector::TypeBuilder::CSS::SelectorList> InspectorStyleSheet::buildObjectForSelectorList(CSSStyleRule* rule)
1011 {
1012     RefPtr<CSSRuleSourceData> sourceData;
1013     if (ensureParsedDataReady())
1014         sourceData = ruleSourceDataFor(rule->style());
1015     RefPtr<Inspector::TypeBuilder::Array<String>> selectors;
1016
1017     // This intentionally does not rely on the source data to avoid catching the trailing comments (before the declaration starting '{').
1018     String selectorText = rule->selectorText();
1019
1020     if (sourceData)
1021         selectors = selectorsFromSource(sourceData.get(), m_parsedStyleSheet->text());
1022     else {
1023         selectors = Inspector::TypeBuilder::Array<String>::create();
1024         const CSSSelectorList& selectorList = rule->styleRule()->selectorList();
1025         for (const CSSSelector* selector = selectorList.first(); selector; selector = CSSSelectorList::next(selector))
1026             selectors->addItem(selector->selectorText());
1027     }
1028     RefPtr<Inspector::TypeBuilder::CSS::SelectorList> result = Inspector::TypeBuilder::CSS::SelectorList::create()
1029         .setSelectors(selectors)
1030         .setText(selectorText)
1031         .release();
1032     if (sourceData)
1033         result->setRange(buildSourceRangeObject(sourceData->ruleHeaderRange, lineEndings().get()));
1034     return result.release();
1035 }
1036
1037 PassRefPtr<Inspector::TypeBuilder::CSS::CSSRule> InspectorStyleSheet::buildObjectForRule(CSSStyleRule* rule)
1038 {
1039     CSSStyleSheet* styleSheet = pageStyleSheet();
1040     if (!styleSheet)
1041         return nullptr;
1042
1043     RefPtr<Inspector::TypeBuilder::CSS::CSSRule> result = Inspector::TypeBuilder::CSS::CSSRule::create()
1044         .setSelectorList(buildObjectForSelectorList(rule))
1045         .setSourceLine(rule->styleRule()->sourceLine())
1046         .setOrigin(m_origin)
1047         .setStyle(buildObjectForStyle(rule->style()));
1048
1049     // "sourceURL" is present only for regular rules, otherwise "origin" should be used in the frontend.
1050     if (m_origin == Inspector::TypeBuilder::CSS::StyleSheetOrigin::Regular)
1051         result->setSourceURL(finalURL());
1052
1053     if (canBind()) {
1054         InspectorCSSId id(ruleId(rule));
1055         if (!id.isEmpty())
1056             result->setRuleId(id.asProtocolValue<Inspector::TypeBuilder::CSS::CSSRuleId>());
1057     }
1058
1059     RefPtr<Array<Inspector::TypeBuilder::CSS::CSSMedia>> mediaArray = Array<Inspector::TypeBuilder::CSS::CSSMedia>::create();
1060
1061     fillMediaListChain(rule, mediaArray.get());
1062     if (mediaArray->length())
1063         result->setMedia(mediaArray.release());
1064
1065     return result.release();
1066 }
1067
1068 PassRefPtr<Inspector::TypeBuilder::CSS::CSSStyle> InspectorStyleSheet::buildObjectForStyle(CSSStyleDeclaration* style)
1069 {
1070     RefPtr<CSSRuleSourceData> sourceData;
1071     if (ensureParsedDataReady())
1072         sourceData = ruleSourceDataFor(style);
1073
1074     InspectorCSSId id = ruleOrStyleId(style);
1075     if (id.isEmpty()) {
1076         RefPtr<Inspector::TypeBuilder::CSS::CSSStyle> bogusStyle = Inspector::TypeBuilder::CSS::CSSStyle::create()
1077             .setCssProperties(Array<Inspector::TypeBuilder::CSS::CSSProperty>::create())
1078             .setShorthandEntries(Array<Inspector::TypeBuilder::CSS::ShorthandEntry>::create());
1079         return bogusStyle.release();
1080     }
1081     RefPtr<InspectorStyle> inspectorStyle = inspectorStyleForId(id);
1082     RefPtr<Inspector::TypeBuilder::CSS::CSSStyle> result = inspectorStyle->buildObjectForStyle();
1083
1084     // Style text cannot be retrieved without stylesheet, so set cssText here.
1085     if (sourceData) {
1086         String sheetText;
1087         bool success = getText(&sheetText);
1088         if (success) {
1089             const SourceRange& bodyRange = sourceData->ruleBodyRange;
1090             result->setCssText(sheetText.substring(bodyRange.start, bodyRange.end - bodyRange.start));
1091         }
1092     }
1093
1094     return result.release();
1095 }
1096
1097 bool InspectorStyleSheet::setStyleText(const InspectorCSSId& id, const String& text, String* oldText, ExceptionCode& ec)
1098 {
1099     RefPtr<InspectorStyle> inspectorStyle = inspectorStyleForId(id);
1100     if (!inspectorStyle) {
1101         ec = NOT_FOUND_ERR;
1102         return false;
1103     }
1104
1105     if (oldText && !inspectorStyle->getText(oldText))
1106         return false;
1107
1108     bool success = inspectorStyle->setText(text, ec);
1109     if (success)
1110         fireStyleSheetChanged();
1111     return success;
1112 }
1113
1114 bool InspectorStyleSheet::setPropertyText(const InspectorCSSId& id, unsigned propertyIndex, const String& text, bool overwrite, String* oldText, ExceptionCode& ec)
1115 {
1116     RefPtr<InspectorStyle> inspectorStyle = inspectorStyleForId(id);
1117     if (!inspectorStyle) {
1118         ec = NOT_FOUND_ERR;
1119         return false;
1120     }
1121
1122     bool success = inspectorStyle->setPropertyText(propertyIndex, text, overwrite, oldText, ec);
1123     if (success)
1124         fireStyleSheetChanged();
1125     return success;
1126 }
1127
1128 bool InspectorStyleSheet::toggleProperty(const InspectorCSSId& id, unsigned propertyIndex, bool disable, ExceptionCode& ec)
1129 {
1130     RefPtr<InspectorStyle> inspectorStyle = inspectorStyleForId(id);
1131     if (!inspectorStyle) {
1132         ec = NOT_FOUND_ERR;
1133         return false;
1134     }
1135
1136     bool success = inspectorStyle->toggleProperty(propertyIndex, disable, ec);
1137     if (success) {
1138         if (disable)
1139             rememberInspectorStyle(inspectorStyle);
1140         else if (!inspectorStyle->hasDisabledProperties())
1141             forgetInspectorStyle(inspectorStyle->cssStyle());
1142         fireStyleSheetChanged();
1143     }
1144     return success;
1145 }
1146
1147 bool InspectorStyleSheet::getText(String* result) const
1148 {
1149     if (!ensureText())
1150         return false;
1151     *result = m_parsedStyleSheet->text();
1152     return true;
1153 }
1154
1155 CSSStyleDeclaration* InspectorStyleSheet::styleForId(const InspectorCSSId& id) const
1156 {
1157     CSSStyleRule* rule = ruleForId(id);
1158     if (!rule)
1159         return nullptr;
1160
1161     return rule->style();
1162 }
1163
1164 void InspectorStyleSheet::fireStyleSheetChanged()
1165 {
1166     if (m_listener)
1167         m_listener->styleSheetChanged(this);
1168 }
1169
1170 PassRefPtr<InspectorStyle> InspectorStyleSheet::inspectorStyleForId(const InspectorCSSId& id)
1171 {
1172     CSSStyleDeclaration* style = styleForId(id);
1173     if (!style)
1174         return nullptr;
1175
1176     InspectorStyleMap::iterator it = m_inspectorStyles.find(style);
1177     if (it == m_inspectorStyles.end()) {
1178         RefPtr<InspectorStyle> inspectorStyle = InspectorStyle::create(id, style, this);
1179         return inspectorStyle.release();
1180     }
1181     return it->value;
1182 }
1183
1184 void InspectorStyleSheet::rememberInspectorStyle(RefPtr<InspectorStyle> inspectorStyle)
1185 {
1186     m_inspectorStyles.set(inspectorStyle->cssStyle(), inspectorStyle);
1187 }
1188
1189 void InspectorStyleSheet::forgetInspectorStyle(CSSStyleDeclaration* style)
1190 {
1191     m_inspectorStyles.remove(style);
1192 }
1193
1194 InspectorCSSId InspectorStyleSheet::ruleOrStyleId(CSSStyleDeclaration* style) const
1195 {
1196     unsigned index = ruleIndexByStyle(style);
1197     if (index != UINT_MAX)
1198         return InspectorCSSId(id(), index);
1199     return InspectorCSSId();
1200 }
1201
1202 Document* InspectorStyleSheet::ownerDocument() const
1203 {
1204     return m_pageStyleSheet->ownerDocument();
1205 }
1206
1207 RefPtr<CSSRuleSourceData> InspectorStyleSheet::ruleSourceDataFor(CSSStyleDeclaration* style) const
1208 {
1209     return m_parsedStyleSheet->ruleSourceDataAt(ruleIndexByStyle(style));
1210 }
1211
1212 std::unique_ptr<Vector<size_t>> InspectorStyleSheet::lineEndings() const
1213 {
1214     if (!m_parsedStyleSheet->hasText())
1215         return nullptr;
1216     return ContentSearchUtilities::lineEndings(m_parsedStyleSheet->text());
1217 }
1218
1219 unsigned InspectorStyleSheet::ruleIndexByStyle(CSSStyleDeclaration* pageStyle) const
1220 {
1221     ensureFlatRules();
1222     unsigned index = 0;
1223     for (unsigned i = 0, size = m_flatRules.size(); i < size; ++i) {
1224         if (m_flatRules.at(i)->style() == pageStyle)
1225             return index;
1226
1227         ++index;
1228     }
1229     return UINT_MAX;
1230 }
1231
1232 bool InspectorStyleSheet::checkPageStyleSheet(ExceptionCode& ec) const
1233 {
1234     if (!m_pageStyleSheet) {
1235         ec = NOT_SUPPORTED_ERR;
1236         return false;
1237     }
1238     return true;
1239 }
1240
1241 bool InspectorStyleSheet::ensureParsedDataReady()
1242 {
1243     return ensureText() && ensureSourceData();
1244 }
1245
1246 bool InspectorStyleSheet::ensureText() const
1247 {
1248     if (!m_parsedStyleSheet)
1249         return false;
1250     if (m_parsedStyleSheet->hasText())
1251         return true;
1252
1253     String text;
1254     bool success = originalStyleSheetText(&text);
1255     if (success)
1256         m_parsedStyleSheet->setText(text);
1257     // No need to clear m_flatRules here - it's empty.
1258
1259     return success;
1260 }
1261
1262 bool InspectorStyleSheet::ensureSourceData()
1263 {
1264     if (m_parsedStyleSheet->hasSourceData())
1265         return true;
1266
1267     if (!m_parsedStyleSheet->hasText())
1268         return false;
1269
1270     RefPtr<StyleSheetContents> newStyleSheet = StyleSheetContents::create();
1271     auto ruleSourceDataResult = std::make_unique<RuleSourceDataList>();
1272     createCSSParser(m_pageStyleSheet->ownerDocument())->parseSheet(newStyleSheet.get(), m_parsedStyleSheet->text(), 0, ruleSourceDataResult.get());
1273     m_parsedStyleSheet->setSourceData(std::move(ruleSourceDataResult));
1274     return m_parsedStyleSheet->hasSourceData();
1275 }
1276
1277 void InspectorStyleSheet::ensureFlatRules() const
1278 {
1279     // We are fine with redoing this for empty stylesheets as this will run fast.
1280     if (m_flatRules.isEmpty())
1281         collectFlatRules(asCSSRuleList(pageStyleSheet()), &m_flatRules);
1282 }
1283
1284 bool InspectorStyleSheet::setStyleText(CSSStyleDeclaration* style, const String& text, ExceptionCode& ec)
1285 {
1286     if (!m_pageStyleSheet)
1287         return false;
1288     if (!ensureParsedDataReady())
1289         return false;
1290
1291     String patchedStyleSheetText;
1292     bool success = styleSheetTextWithChangedStyle(style, text, &patchedStyleSheetText);
1293     if (!success)
1294         return false;
1295
1296     InspectorCSSId id = ruleOrStyleId(style);
1297     if (id.isEmpty())
1298         return false;
1299
1300     style->setCssText(text, ec);
1301     if (!ec)
1302         m_parsedStyleSheet->setText(patchedStyleSheetText);
1303
1304     return !ec;
1305 }
1306
1307 bool InspectorStyleSheet::styleSheetTextWithChangedStyle(CSSStyleDeclaration* style, const String& newStyleText, String* result)
1308 {
1309     if (!style)
1310         return false;
1311
1312     if (!ensureParsedDataReady())
1313         return false;
1314
1315     RefPtr<CSSRuleSourceData> sourceData = ruleSourceDataFor(style);
1316     unsigned bodyStart = sourceData->ruleBodyRange.start;
1317     unsigned bodyEnd = sourceData->ruleBodyRange.end;
1318     ASSERT(bodyStart <= bodyEnd);
1319
1320     String text = m_parsedStyleSheet->text();
1321     ASSERT_WITH_SECURITY_IMPLICATION(bodyEnd <= text.length()); // bodyEnd is exclusive
1322
1323     text.replace(bodyStart, bodyEnd - bodyStart, newStyleText);
1324     *result = text;
1325     return true;
1326 }
1327
1328 InspectorCSSId InspectorStyleSheet::ruleId(CSSStyleRule* rule) const
1329 {
1330     return ruleOrStyleId(rule->style());
1331 }
1332
1333 void InspectorStyleSheet::revalidateStyle(CSSStyleDeclaration* pageStyle)
1334 {
1335     if (m_isRevalidating)
1336         return;
1337
1338     m_isRevalidating = true;
1339     ensureFlatRules();
1340     for (unsigned i = 0, size = m_flatRules.size(); i < size; ++i) {
1341         CSSStyleRule* parsedRule = m_flatRules.at(i).get();
1342         if (parsedRule->style() == pageStyle) {
1343             if (parsedRule->styleRule()->properties().asText() != pageStyle->cssText()) {
1344                 // Clear the disabled properties for the invalid style here.
1345                 m_inspectorStyles.remove(pageStyle);
1346
1347                 ExceptionCode ec = 0;
1348                 setStyleText(pageStyle, pageStyle->cssText(), ec);
1349             }
1350             break;
1351         }
1352     }
1353     m_isRevalidating = false;
1354 }
1355
1356 bool InspectorStyleSheet::originalStyleSheetText(String* result) const
1357 {
1358     bool success = inlineStyleSheetText(result);
1359     if (!success)
1360         success = resourceStyleSheetText(result);
1361     return success;
1362 }
1363
1364 bool InspectorStyleSheet::resourceStyleSheetText(String* result) const
1365 {
1366     if (m_origin == Inspector::TypeBuilder::CSS::StyleSheetOrigin::User || m_origin == Inspector::TypeBuilder::CSS::StyleSheetOrigin::UserAgent)
1367         return false;
1368
1369     if (!m_pageStyleSheet || !ownerDocument() || !ownerDocument()->frame())
1370         return false;
1371
1372     String error;
1373     bool base64Encoded;
1374     InspectorPageAgent::resourceContent(&error, ownerDocument()->frame(), URL(ParsedURLString, m_pageStyleSheet->href()), result, &base64Encoded);
1375     return error.isEmpty() && !base64Encoded;
1376 }
1377
1378 bool InspectorStyleSheet::inlineStyleSheetText(String* result) const
1379 {
1380     if (!m_pageStyleSheet)
1381         return false;
1382
1383     Node* ownerNode = m_pageStyleSheet->ownerNode();
1384     if (!ownerNode || !ownerNode->isElementNode())
1385         return false;
1386     Element* ownerElement = toElement(ownerNode);
1387
1388     if (!isHTMLStyleElement(ownerElement) && !ownerElement->hasTagName(SVGNames::styleTag))
1389         return false;
1390     *result = ownerElement->textContent();
1391     return true;
1392 }
1393
1394 PassRefPtr<Inspector::TypeBuilder::Array<Inspector::TypeBuilder::CSS::CSSRule>> InspectorStyleSheet::buildArrayForRuleList(CSSRuleList* ruleList)
1395 {
1396     RefPtr<Inspector::TypeBuilder::Array<Inspector::TypeBuilder::CSS::CSSRule>> result = Inspector::TypeBuilder::Array<Inspector::TypeBuilder::CSS::CSSRule>::create();
1397     if (!ruleList)
1398         return result.release();
1399
1400     RefPtr<CSSRuleList> refRuleList = ruleList;
1401     CSSStyleRuleVector rules;
1402     collectFlatRules(refRuleList, &rules);
1403
1404     for (unsigned i = 0, size = rules.size(); i < size; ++i)
1405         result->addItem(buildObjectForRule(rules.at(i).get()));
1406
1407     return result.release();
1408 }
1409
1410 void InspectorStyleSheet::collectFlatRules(PassRefPtr<CSSRuleList> ruleList, CSSStyleRuleVector* result)
1411 {
1412     if (!ruleList)
1413         return;
1414
1415     for (unsigned i = 0, size = ruleList->length(); i < size; ++i) {
1416         CSSRule* rule = ruleList->item(i);
1417         CSSStyleRule* styleRule = InspectorCSSAgent::asCSSStyleRule(rule);
1418         if (styleRule)
1419             result->append(styleRule);
1420         else {
1421             RefPtr<CSSRuleList> childRuleList = asCSSRuleList(rule);
1422             if (childRuleList)
1423                 collectFlatRules(childRuleList, result);
1424         }
1425     }
1426 }
1427
1428 PassRefPtr<InspectorStyleSheetForInlineStyle> InspectorStyleSheetForInlineStyle::create(InspectorPageAgent* pageAgent, const String& id, PassRefPtr<Element> element, Inspector::TypeBuilder::CSS::StyleSheetOrigin::Enum origin, Listener* listener)
1429 {
1430     return adoptRef(new InspectorStyleSheetForInlineStyle(pageAgent, id, element, origin, listener));
1431 }
1432
1433 InspectorStyleSheetForInlineStyle::InspectorStyleSheetForInlineStyle(InspectorPageAgent* pageAgent, const String& id, PassRefPtr<Element> element, Inspector::TypeBuilder::CSS::StyleSheetOrigin::Enum origin, Listener* listener)
1434     : InspectorStyleSheet(pageAgent, id, nullptr, origin, "", listener)
1435     , m_element(element)
1436     , m_ruleSourceData(nullptr)
1437     , m_isStyleTextValid(false)
1438 {
1439     ASSERT(m_element);
1440     m_inspectorStyle = InspectorStyle::create(InspectorCSSId(id, 0), inlineStyle(), this);
1441     m_styleText = m_element->isStyledElement() ? m_element->getAttribute("style").string() : String();
1442 }
1443
1444 void InspectorStyleSheetForInlineStyle::didModifyElementAttribute()
1445 {
1446     m_isStyleTextValid = false;
1447     if (m_element->isStyledElement() && m_element->style() != m_inspectorStyle->cssStyle())
1448         m_inspectorStyle = InspectorStyle::create(InspectorCSSId(id(), 0), inlineStyle(), this);
1449     m_ruleSourceData.clear();
1450 }
1451
1452 bool InspectorStyleSheetForInlineStyle::getText(String* result) const
1453 {
1454     if (!m_isStyleTextValid) {
1455         m_styleText = elementStyleText();
1456         m_isStyleTextValid = true;
1457     }
1458     *result = m_styleText;
1459     return true;
1460 }
1461
1462 bool InspectorStyleSheetForInlineStyle::setStyleText(CSSStyleDeclaration* style, const String& text, ExceptionCode& ec)
1463 {
1464     ASSERT_UNUSED(style, style == inlineStyle());
1465
1466     {
1467         InspectorCSSAgent::InlineStyleOverrideScope overrideScope(&m_element->document());
1468         m_element->setAttribute("style", text, ec);
1469     }
1470
1471     m_styleText = text;
1472     m_isStyleTextValid = true;
1473     m_ruleSourceData.clear();
1474     return !ec;
1475 }
1476
1477 std::unique_ptr<Vector<size_t>> InspectorStyleSheetForInlineStyle::lineEndings() const
1478 {
1479     return ContentSearchUtilities::lineEndings(elementStyleText());
1480 }
1481
1482 Document* InspectorStyleSheetForInlineStyle::ownerDocument() const
1483 {
1484     return &m_element->document();
1485 }
1486
1487 bool InspectorStyleSheetForInlineStyle::ensureParsedDataReady()
1488 {
1489     // The "style" property value can get changed indirectly, e.g. via element.style.borderWidth = "2px".
1490     const String& currentStyleText = elementStyleText();
1491     if (m_styleText != currentStyleText) {
1492         m_ruleSourceData.clear();
1493         m_styleText = currentStyleText;
1494         m_isStyleTextValid = true;
1495     }
1496
1497     if (m_ruleSourceData)
1498         return true;
1499
1500     m_ruleSourceData = CSSRuleSourceData::create(CSSRuleSourceData::STYLE_RULE);
1501     bool success = getStyleAttributeRanges(m_ruleSourceData.get());
1502     if (!success)
1503         return false;
1504
1505     return true;
1506 }
1507
1508 PassRefPtr<InspectorStyle> InspectorStyleSheetForInlineStyle::inspectorStyleForId(const InspectorCSSId& id)
1509 {
1510     ASSERT_UNUSED(id, !id.ordinal());
1511     return m_inspectorStyle;
1512 }
1513
1514 CSSStyleDeclaration* InspectorStyleSheetForInlineStyle::inlineStyle() const
1515 {
1516     return m_element->style();
1517 }
1518
1519 const String& InspectorStyleSheetForInlineStyle::elementStyleText() const
1520 {
1521     return m_element->getAttribute("style").string();
1522 }
1523
1524 bool InspectorStyleSheetForInlineStyle::getStyleAttributeRanges(CSSRuleSourceData* result) const
1525 {
1526     if (!m_element->isStyledElement())
1527         return false;
1528
1529     if (m_styleText.isEmpty()) {
1530         result->ruleBodyRange.start = 0;
1531         result->ruleBodyRange.end = 0;
1532         return true;
1533     }
1534
1535     RefPtr<MutableStyleProperties> tempDeclaration = MutableStyleProperties::create();
1536     createCSSParser(&m_element->document())->parseDeclaration(tempDeclaration.get(), m_styleText, result, &m_element->document().elementSheet().contents());
1537     return true;
1538 }
1539
1540 } // namespace WebCore
1541
1542 #endif // ENABLE(INSPECTOR)