b842696ff0b97618acadb2b4327762d4a286f0dc
[WebKit-https.git] / Source / WebCore / editing / EditingStyle.cpp
1 /*
2  * Copyright (C) 2007, 2008, 2009, 2013 Apple Computer, Inc.
3  * Copyright (C) 2010, 2011 Google Inc. All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
15  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
16  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
17  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
18  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
19  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
20  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 #include "config.h"
28 #include "EditingStyle.h"
29
30 #include "ApplyStyleCommand.h"
31 #include "CSSComputedStyleDeclaration.h"
32 #include "CSSParser.h"
33 #include "CSSRuleList.h"
34 #include "CSSStyleRule.h"
35 #include "CSSValueList.h"
36 #include "CSSValuePool.h"
37 #include "Editor.h"
38 #include "Frame.h"
39 #include "HTMLFontElement.h"
40 #include "HTMLInterchange.h"
41 #include "HTMLNames.h"
42 #include "Node.h"
43 #include "NodeTraversal.h"
44 #include "QualifiedName.h"
45 #include "RenderStyle.h"
46 #include "StyleFontSizeFunctions.h"
47 #include "StylePropertySet.h"
48 #include "StyleResolver.h"
49 #include "StyleRule.h"
50 #include "StyledElement.h"
51 #include "VisibleUnits.h"
52 #include "htmlediting.h"
53
54 namespace WebCore {
55
56 // Editing style properties must be preserved during editing operation.
57 // e.g. when a user inserts a new paragraph, all properties listed here must be copied to the new paragraph.
58 static const CSSPropertyID editingProperties[] = {
59     CSSPropertyColor,
60     CSSPropertyFontFamily,
61     CSSPropertyFontSize,
62     CSSPropertyFontStyle,
63     CSSPropertyFontVariant,
64     CSSPropertyFontWeight,
65     CSSPropertyLetterSpacing,
66     CSSPropertyLineHeight,
67     CSSPropertyOrphans,
68     CSSPropertyTextAlign,
69     CSSPropertyTextIndent,
70     CSSPropertyTextTransform,
71     CSSPropertyWhiteSpace,
72     CSSPropertyWidows,
73     CSSPropertyWordSpacing,
74     CSSPropertyWebkitTextDecorationsInEffect,
75     CSSPropertyWebkitTextFillColor,
76 #if ENABLE(IOS_TEXT_AUTOSIZING)
77     CSSPropertyWebkitTextSizeAdjust,
78 #endif
79     CSSPropertyWebkitTextStrokeColor,
80     CSSPropertyWebkitTextStrokeWidth,
81
82     // Non-inheritable properties
83     CSSPropertyBackgroundColor,
84     CSSPropertyTextDecoration,
85 };
86
87 const unsigned numAllEditingProperties = WTF_ARRAY_LENGTH(editingProperties);
88 const unsigned numInheritableEditingProperties = numAllEditingProperties - 2;
89
90 enum EditingPropertiesToInclude { OnlyInheritableEditingProperties, AllEditingProperties };
91 template <class StyleDeclarationType>
92 static PassRefPtr<MutableStylePropertySet> copyEditingProperties(StyleDeclarationType* style, EditingPropertiesToInclude type)
93 {
94     if (type == AllEditingProperties)
95         return style->copyPropertiesInSet(editingProperties, numAllEditingProperties);
96     return style->copyPropertiesInSet(editingProperties, numInheritableEditingProperties);
97 }
98
99 static inline bool isEditingProperty(int id)
100 {
101     for (size_t i = 0; i < WTF_ARRAY_LENGTH(editingProperties); ++i) {
102         if (editingProperties[i] == id)
103             return true;
104     }
105     return false;
106 }
107
108 static PassRefPtr<MutableStylePropertySet> copyPropertiesFromComputedStyle(ComputedStyleExtractor& computedStyle, EditingStyle::PropertiesToInclude propertiesToInclude)
109 {
110     switch (propertiesToInclude) {
111     case EditingStyle::AllProperties:
112         return computedStyle.copyProperties();
113     case EditingStyle::OnlyEditingInheritableProperties:
114         return copyEditingProperties(&computedStyle, OnlyInheritableEditingProperties);
115     case EditingStyle::EditingPropertiesInEffect:
116         return copyEditingProperties(&computedStyle, AllEditingProperties);
117     }
118     ASSERT_NOT_REACHED();
119     return 0;
120 }
121
122 static PassRefPtr<MutableStylePropertySet> copyPropertiesFromComputedStyle(Node* node, EditingStyle::PropertiesToInclude propertiesToInclude)
123 {
124     ComputedStyleExtractor computedStyle(node);
125     return copyPropertiesFromComputedStyle(computedStyle, propertiesToInclude);
126 }
127
128 static PassRefPtr<CSSValue> extractPropertyValue(const StylePropertySet* style, CSSPropertyID propertyID)
129 {
130     return style ? style->getPropertyCSSValue(propertyID) : PassRefPtr<CSSValue>();
131 }
132
133 static PassRefPtr<CSSValue> extractPropertyValue(ComputedStyleExtractor* computedStyle, CSSPropertyID propertyID)
134 {
135     return computedStyle->propertyValue(propertyID);
136 }
137
138 template<typename T>
139 int identifierForStyleProperty(T* style, CSSPropertyID propertyID)
140 {
141     RefPtr<CSSValue> value = extractPropertyValue(style, propertyID);
142     if (!value || !value->isPrimitiveValue())
143         return 0;
144     return toCSSPrimitiveValue(value.get())->getValueID();
145 }
146
147 template<typename T> PassRefPtr<MutableStylePropertySet> getPropertiesNotIn(StylePropertySet* styleWithRedundantProperties, T* baseStyle);
148 enum LegacyFontSizeMode { AlwaysUseLegacyFontSize, UseLegacyFontSizeOnlyIfPixelValuesMatch };
149 static int legacyFontSizeFromCSSValue(Document*, CSSPrimitiveValue*, bool shouldUseFixedFontDefaultSize, LegacyFontSizeMode);
150 static bool isTransparentColorValue(CSSValue*);
151 static bool hasTransparentBackgroundColor(StylePropertySet*);
152 static PassRefPtr<CSSValue> backgroundColorInEffect(Node*);
153
154 class HTMLElementEquivalent {
155     WTF_MAKE_FAST_ALLOCATED;
156 public:
157     static PassOwnPtr<HTMLElementEquivalent> create(CSSPropertyID propertyID, CSSValueID primitiveValue, const QualifiedName& tagName)
158     {
159         return adoptPtr(new HTMLElementEquivalent(propertyID, primitiveValue, tagName));
160     }
161
162     virtual ~HTMLElementEquivalent() { }
163     virtual bool matches(const Element* element) const { return !m_tagName || element->hasTagName(*m_tagName); }
164     virtual bool hasAttribute() const { return false; }
165     virtual bool propertyExistsInStyle(const StylePropertySet* style) const { return style->getPropertyCSSValue(m_propertyID); }
166     virtual bool valueIsPresentInStyle(Element*, StylePropertySet*) const;
167     virtual void addToStyle(Element*, EditingStyle*) const;
168
169 protected:
170     HTMLElementEquivalent(CSSPropertyID);
171     HTMLElementEquivalent(CSSPropertyID, const QualifiedName& tagName);
172     HTMLElementEquivalent(CSSPropertyID, CSSValueID primitiveValue, const QualifiedName& tagName);
173     const CSSPropertyID m_propertyID;
174     const RefPtr<CSSPrimitiveValue> m_primitiveValue;
175     const QualifiedName* m_tagName; // We can store a pointer because HTML tag names are const global.
176 };
177
178 HTMLElementEquivalent::HTMLElementEquivalent(CSSPropertyID id)
179     : m_propertyID(id)
180     , m_tagName(0)
181 {
182 }
183
184 HTMLElementEquivalent::HTMLElementEquivalent(CSSPropertyID id, const QualifiedName& tagName)
185     : m_propertyID(id)
186     , m_tagName(&tagName)
187 {
188 }
189
190 HTMLElementEquivalent::HTMLElementEquivalent(CSSPropertyID id, CSSValueID primitiveValue, const QualifiedName& tagName)
191     : m_propertyID(id)
192     , m_primitiveValue(CSSPrimitiveValue::createIdentifier(primitiveValue))
193     , m_tagName(&tagName)
194 {
195     ASSERT(primitiveValue != CSSValueInvalid);
196 }
197
198 bool HTMLElementEquivalent::valueIsPresentInStyle(Element* element, StylePropertySet* style) const
199 {
200     RefPtr<CSSValue> value = style->getPropertyCSSValue(m_propertyID);
201     return matches(element) && value && value->isPrimitiveValue() && toCSSPrimitiveValue(value.get())->getValueID() == m_primitiveValue->getValueID();
202 }
203
204 void HTMLElementEquivalent::addToStyle(Element*, EditingStyle* style) const
205 {
206     style->setProperty(m_propertyID, m_primitiveValue->cssText());
207 }
208
209 class HTMLTextDecorationEquivalent : public HTMLElementEquivalent {
210 public:
211     static PassOwnPtr<HTMLElementEquivalent> create(CSSValueID primitiveValue, const QualifiedName& tagName)
212     {
213         return adoptPtr(new HTMLTextDecorationEquivalent(primitiveValue, tagName));
214     }
215     virtual bool propertyExistsInStyle(const StylePropertySet*) const;
216     virtual bool valueIsPresentInStyle(Element*, StylePropertySet*) const;
217
218 private:
219     HTMLTextDecorationEquivalent(CSSValueID primitiveValue, const QualifiedName& tagName);
220 };
221
222 HTMLTextDecorationEquivalent::HTMLTextDecorationEquivalent(CSSValueID primitiveValue, const QualifiedName& tagName)
223     : HTMLElementEquivalent(CSSPropertyTextDecoration, primitiveValue, tagName)
224     // m_propertyID is used in HTMLElementEquivalent::addToStyle
225 {
226 }
227
228 bool HTMLTextDecorationEquivalent::propertyExistsInStyle(const StylePropertySet* style) const
229 {
230     return style->getPropertyCSSValue(CSSPropertyWebkitTextDecorationsInEffect) || style->getPropertyCSSValue(CSSPropertyTextDecoration);
231 }
232
233 bool HTMLTextDecorationEquivalent::valueIsPresentInStyle(Element* element, StylePropertySet* style) const
234 {
235     RefPtr<CSSValue> styleValue = style->getPropertyCSSValue(CSSPropertyWebkitTextDecorationsInEffect);
236     if (!styleValue)
237         styleValue = style->getPropertyCSSValue(CSSPropertyTextDecoration);
238     return matches(element) && styleValue && styleValue->isValueList() && toCSSValueList(styleValue.get())->hasValue(m_primitiveValue.get());
239 }
240
241 class HTMLAttributeEquivalent : public HTMLElementEquivalent {
242 public:
243     static PassOwnPtr<HTMLAttributeEquivalent> create(CSSPropertyID propertyID, const QualifiedName& tagName, const QualifiedName& attrName)
244     {
245         return adoptPtr(new HTMLAttributeEquivalent(propertyID, tagName, attrName));
246     }
247     static PassOwnPtr<HTMLAttributeEquivalent> create(CSSPropertyID propertyID, const QualifiedName& attrName)
248     {
249         return adoptPtr(new HTMLAttributeEquivalent(propertyID, attrName));
250     }
251
252     bool matches(const Element* elem) const { return HTMLElementEquivalent::matches(elem) && elem->hasAttribute(m_attrName); }
253     virtual bool hasAttribute() const { return true; }
254     virtual bool valueIsPresentInStyle(Element*, StylePropertySet*) const;
255     virtual void addToStyle(Element*, EditingStyle*) const;
256     virtual PassRefPtr<CSSValue> attributeValueAsCSSValue(Element*) const;
257     inline const QualifiedName& attributeName() const { return m_attrName; }
258
259 protected:
260     HTMLAttributeEquivalent(CSSPropertyID, const QualifiedName& tagName, const QualifiedName& attrName);
261     HTMLAttributeEquivalent(CSSPropertyID, const QualifiedName& attrName);
262     const QualifiedName& m_attrName; // We can store a reference because HTML attribute names are const global.
263 };
264
265 HTMLAttributeEquivalent::HTMLAttributeEquivalent(CSSPropertyID id, const QualifiedName& tagName, const QualifiedName& attrName)
266     : HTMLElementEquivalent(id, tagName)
267     , m_attrName(attrName)
268 {
269 }
270
271 HTMLAttributeEquivalent::HTMLAttributeEquivalent(CSSPropertyID id, const QualifiedName& attrName)
272     : HTMLElementEquivalent(id)
273     , m_attrName(attrName)
274 {
275 }
276
277 bool HTMLAttributeEquivalent::valueIsPresentInStyle(Element* element, StylePropertySet* style) const
278 {
279     RefPtr<CSSValue> value = attributeValueAsCSSValue(element);
280     RefPtr<CSSValue> styleValue = style->getPropertyCSSValue(m_propertyID);
281     
282     return compareCSSValuePtr(value, styleValue);
283 }
284
285 void HTMLAttributeEquivalent::addToStyle(Element* element, EditingStyle* style) const
286 {
287     if (RefPtr<CSSValue> value = attributeValueAsCSSValue(element))
288         style->setProperty(m_propertyID, value->cssText());
289 }
290
291 PassRefPtr<CSSValue> HTMLAttributeEquivalent::attributeValueAsCSSValue(Element* element) const
292 {
293     ASSERT(element);
294     if (!element->hasAttribute(m_attrName))
295         return 0;
296     
297     RefPtr<MutableStylePropertySet> dummyStyle;
298     dummyStyle = MutableStylePropertySet::create();
299     dummyStyle->setProperty(m_propertyID, element->getAttribute(m_attrName));
300     return dummyStyle->getPropertyCSSValue(m_propertyID);
301 }
302
303 class HTMLFontSizeEquivalent : public HTMLAttributeEquivalent {
304 public:
305     static PassOwnPtr<HTMLFontSizeEquivalent> create()
306     {
307         return adoptPtr(new HTMLFontSizeEquivalent());
308     }
309     virtual PassRefPtr<CSSValue> attributeValueAsCSSValue(Element*) const;
310
311 private:
312     HTMLFontSizeEquivalent();
313 };
314
315 HTMLFontSizeEquivalent::HTMLFontSizeEquivalent()
316     : HTMLAttributeEquivalent(CSSPropertyFontSize, HTMLNames::fontTag, HTMLNames::sizeAttr)
317 {
318 }
319
320 PassRefPtr<CSSValue> HTMLFontSizeEquivalent::attributeValueAsCSSValue(Element* element) const
321 {
322     ASSERT(element);
323     if (!element->hasAttribute(m_attrName))
324         return 0;
325     CSSValueID size;
326     if (!HTMLFontElement::cssValueFromFontSizeNumber(element->getAttribute(m_attrName), size))
327         return 0;
328     return CSSPrimitiveValue::createIdentifier(size);
329 }
330
331 float EditingStyle::NoFontDelta = 0.0f;
332
333 EditingStyle::EditingStyle()
334     : m_shouldUseFixedDefaultFontSize(false)
335     , m_fontSizeDelta(NoFontDelta)
336 {
337 }
338
339 EditingStyle::EditingStyle(Node* node, PropertiesToInclude propertiesToInclude)
340     : m_shouldUseFixedDefaultFontSize(false)
341     , m_fontSizeDelta(NoFontDelta)
342 {
343     init(node, propertiesToInclude);
344 }
345
346 EditingStyle::EditingStyle(const Position& position, PropertiesToInclude propertiesToInclude)
347     : m_shouldUseFixedDefaultFontSize(false)
348     , m_fontSizeDelta(NoFontDelta)
349 {
350     init(position.deprecatedNode(), propertiesToInclude);
351 }
352
353 EditingStyle::EditingStyle(const StylePropertySet* style)
354     : m_shouldUseFixedDefaultFontSize(false)
355     , m_fontSizeDelta(NoFontDelta)
356 {
357     if (style)
358         m_mutableStyle = style->mutableCopy();
359     extractFontSizeDelta();
360 }
361
362 EditingStyle::EditingStyle(CSSPropertyID propertyID, const String& value)
363     : m_mutableStyle(0)
364     , m_shouldUseFixedDefaultFontSize(false)
365     , m_fontSizeDelta(NoFontDelta)
366 {
367     setProperty(propertyID, value);
368 }
369
370 EditingStyle::~EditingStyle()
371 {
372 }
373
374 static RGBA32 cssValueToRGBA(CSSValue* colorValue)
375 {
376     if (!colorValue || !colorValue->isPrimitiveValue())
377         return Color::transparent;
378     
379     CSSPrimitiveValue* primitiveColor = toCSSPrimitiveValue(colorValue);
380     if (primitiveColor->isRGBColor())
381         return primitiveColor->getRGBA32Value();
382     
383     RGBA32 rgba = 0;
384     CSSParser::parseColor(rgba, colorValue->cssText());
385     return rgba;
386 }
387
388 template<typename T>
389 static inline RGBA32 textColorFromStyle(T* style)
390 {
391     return cssValueToRGBA(extractPropertyValue(style, CSSPropertyColor).get());
392 }
393
394 template<typename T>
395 static inline RGBA32 backgroundColorFromStyle(T* style)
396 {
397     return cssValueToRGBA(extractPropertyValue(style, CSSPropertyBackgroundColor).get());
398 }
399
400 static inline RGBA32 rgbaBackgroundColorInEffect(Node* node)
401 {
402     return cssValueToRGBA(backgroundColorInEffect(node).get());
403 }
404
405 static int textAlignResolvingStartAndEnd(int textAlign, int direction)
406 {
407     switch (textAlign) {
408     case CSSValueCenter:
409     case CSSValueWebkitCenter:
410         return CSSValueCenter;
411     case CSSValueJustify:
412         return CSSValueJustify;
413     case CSSValueLeft:
414     case CSSValueWebkitLeft:
415         return CSSValueLeft;
416     case CSSValueRight:
417     case CSSValueWebkitRight:
418         return CSSValueRight;
419     case CSSValueStart:
420         return direction != CSSValueRtl ? CSSValueLeft : CSSValueRight;
421     case CSSValueEnd:
422         return direction == CSSValueRtl ? CSSValueRight : CSSValueLeft;
423     }
424     return CSSValueInvalid;
425 }
426
427 template<typename T>
428 static int textAlignResolvingStartAndEnd(T* style)
429 {
430     return textAlignResolvingStartAndEnd(identifierForStyleProperty(style, CSSPropertyTextAlign), identifierForStyleProperty(style, CSSPropertyDirection));
431 }
432
433 void EditingStyle::init(Node* node, PropertiesToInclude propertiesToInclude)
434 {
435     if (isTabSpanTextNode(node))
436         node = tabSpanNode(node)->parentNode();
437     else if (isTabSpanNode(node))
438         node = node->parentNode();
439
440     ComputedStyleExtractor computedStyleAtPosition(node);
441     // FIXME: It's strange to not set background-color and text-decoration when propertiesToInclude is EditingPropertiesInEffect.
442     // However editing/selection/contains-boundaries.html fails without this ternary.
443     m_mutableStyle = copyPropertiesFromComputedStyle(computedStyleAtPosition,
444         propertiesToInclude == EditingPropertiesInEffect ? OnlyEditingInheritableProperties : propertiesToInclude);
445
446     if (propertiesToInclude == EditingPropertiesInEffect) {
447         if (RefPtr<CSSValue> value = backgroundColorInEffect(node))
448             m_mutableStyle->setProperty(CSSPropertyBackgroundColor, value->cssText());
449         if (RefPtr<CSSValue> value = computedStyleAtPosition.propertyValue(CSSPropertyWebkitTextDecorationsInEffect))
450             m_mutableStyle->setProperty(CSSPropertyTextDecoration, value->cssText());
451     }
452
453     if (node && node->computedStyle()) {
454         RenderStyle* renderStyle = node->computedStyle();
455         removeTextFillAndStrokeColorsIfNeeded(renderStyle);
456         if (renderStyle->fontDescription().keywordSize())
457             m_mutableStyle->setProperty(CSSPropertyFontSize, computedStyleAtPosition.getFontSizeCSSValuePreferringKeyword()->cssText());
458     }
459
460     m_shouldUseFixedDefaultFontSize = computedStyleAtPosition.useFixedFontDefaultSize();
461     extractFontSizeDelta();
462 }
463
464 void EditingStyle::removeTextFillAndStrokeColorsIfNeeded(RenderStyle* renderStyle)
465 {
466     // If a node's text fill color is invalid, then its children use 
467     // their font-color as their text fill color (they don't
468     // inherit it).  Likewise for stroke color.
469     if (!renderStyle->textFillColor().isValid())
470         m_mutableStyle->removeProperty(CSSPropertyWebkitTextFillColor);
471     if (!renderStyle->textStrokeColor().isValid())
472         m_mutableStyle->removeProperty(CSSPropertyWebkitTextStrokeColor);
473 }
474
475 void EditingStyle::setProperty(CSSPropertyID propertyID, const String& value, bool important)
476 {
477     if (!m_mutableStyle)
478         m_mutableStyle = MutableStylePropertySet::create();
479
480     m_mutableStyle->setProperty(propertyID, value, important);
481 }
482
483 void EditingStyle::extractFontSizeDelta()
484 {
485     if (!m_mutableStyle)
486         return;
487
488     if (m_mutableStyle->getPropertyCSSValue(CSSPropertyFontSize)) {
489         // Explicit font size overrides any delta.
490         m_mutableStyle->removeProperty(CSSPropertyWebkitFontSizeDelta);
491         return;
492     }
493
494     // Get the adjustment amount out of the style.
495     RefPtr<CSSValue> value = m_mutableStyle->getPropertyCSSValue(CSSPropertyWebkitFontSizeDelta);
496     if (!value || !value->isPrimitiveValue())
497         return;
498
499     CSSPrimitiveValue* primitiveValue = toCSSPrimitiveValue(value.get());
500
501     // Only PX handled now. If we handle more types in the future, perhaps
502     // a switch statement here would be more appropriate.
503     if (!primitiveValue->isPx())
504         return;
505
506     m_fontSizeDelta = primitiveValue->getFloatValue();
507     m_mutableStyle->removeProperty(CSSPropertyWebkitFontSizeDelta);
508 }
509
510 bool EditingStyle::isEmpty() const
511 {
512     return (!m_mutableStyle || m_mutableStyle->isEmpty()) && m_fontSizeDelta == NoFontDelta;
513 }
514
515 bool EditingStyle::textDirection(WritingDirection& writingDirection) const
516 {
517     if (!m_mutableStyle)
518         return false;
519
520     RefPtr<CSSValue> unicodeBidi = m_mutableStyle->getPropertyCSSValue(CSSPropertyUnicodeBidi);
521     if (!unicodeBidi || !unicodeBidi->isPrimitiveValue())
522         return false;
523
524     CSSValueID unicodeBidiValue = toCSSPrimitiveValue(unicodeBidi.get())->getValueID();
525     if (unicodeBidiValue == CSSValueEmbed) {
526         RefPtr<CSSValue> direction = m_mutableStyle->getPropertyCSSValue(CSSPropertyDirection);
527         if (!direction || !direction->isPrimitiveValue())
528             return false;
529
530         writingDirection = toCSSPrimitiveValue(direction.get())->getValueID() == CSSValueLtr ? LeftToRightWritingDirection : RightToLeftWritingDirection;
531
532         return true;
533     }
534
535     if (unicodeBidiValue == CSSValueNormal) {
536         writingDirection = NaturalWritingDirection;
537         return true;
538     }
539
540     return false;
541 }
542
543 void EditingStyle::setStyle(PassRefPtr<MutableStylePropertySet> style)
544 {
545     m_mutableStyle = style;
546     // FIXME: We should be able to figure out whether or not font is fixed width for mutable style.
547     // We need to check font-family is monospace as in FontDescription but we don't want to duplicate code here.
548     m_shouldUseFixedDefaultFontSize = false;
549     extractFontSizeDelta();
550 }
551
552 void EditingStyle::overrideWithStyle(const StylePropertySet* style)
553 {
554     return mergeStyle(style, OverrideValues);
555 }
556
557 void EditingStyle::clear()
558 {
559     m_mutableStyle.clear();
560     m_shouldUseFixedDefaultFontSize = false;
561     m_fontSizeDelta = NoFontDelta;
562 }
563
564 PassRefPtr<EditingStyle> EditingStyle::copy() const
565 {
566     RefPtr<EditingStyle> copy = EditingStyle::create();
567     if (m_mutableStyle)
568         copy->m_mutableStyle = m_mutableStyle->mutableCopy();
569     copy->m_shouldUseFixedDefaultFontSize = m_shouldUseFixedDefaultFontSize;
570     copy->m_fontSizeDelta = m_fontSizeDelta;
571     return copy;
572 }
573
574 PassRefPtr<EditingStyle> EditingStyle::extractAndRemoveBlockProperties()
575 {
576     RefPtr<EditingStyle> blockProperties = EditingStyle::create();
577     if (!m_mutableStyle)
578         return blockProperties;
579
580     blockProperties->m_mutableStyle = m_mutableStyle->copyBlockProperties();
581     m_mutableStyle->removeBlockProperties();
582
583     return blockProperties;
584 }
585
586 PassRefPtr<EditingStyle> EditingStyle::extractAndRemoveTextDirection()
587 {
588     RefPtr<EditingStyle> textDirection = EditingStyle::create();
589     textDirection->m_mutableStyle = MutableStylePropertySet::create();
590     textDirection->m_mutableStyle->setProperty(CSSPropertyUnicodeBidi, CSSValueEmbed, m_mutableStyle->propertyIsImportant(CSSPropertyUnicodeBidi));
591     textDirection->m_mutableStyle->setProperty(CSSPropertyDirection, m_mutableStyle->getPropertyValue(CSSPropertyDirection),
592         m_mutableStyle->propertyIsImportant(CSSPropertyDirection));
593
594     m_mutableStyle->removeProperty(CSSPropertyUnicodeBidi);
595     m_mutableStyle->removeProperty(CSSPropertyDirection);
596
597     return textDirection;
598 }
599
600 void EditingStyle::removeBlockProperties()
601 {
602     if (!m_mutableStyle)
603         return;
604
605     m_mutableStyle->removeBlockProperties();
606 }
607
608 void EditingStyle::removeStyleAddedByNode(Node* node)
609 {
610     if (!node || !node->parentNode())
611         return;
612     RefPtr<MutableStylePropertySet> parentStyle = copyPropertiesFromComputedStyle(node->parentNode(), EditingPropertiesInEffect);
613     RefPtr<MutableStylePropertySet> nodeStyle = copyPropertiesFromComputedStyle(node, EditingPropertiesInEffect);
614     nodeStyle->removeEquivalentProperties(parentStyle.get());
615     m_mutableStyle->removeEquivalentProperties(nodeStyle.get());
616 }
617
618 void EditingStyle::removeStyleConflictingWithStyleOfNode(Node* node)
619 {
620     if (!node || !node->parentNode() || !m_mutableStyle)
621         return;
622
623     RefPtr<MutableStylePropertySet> parentStyle = copyPropertiesFromComputedStyle(node->parentNode(), EditingPropertiesInEffect);
624     RefPtr<MutableStylePropertySet> nodeStyle = copyPropertiesFromComputedStyle(node, EditingPropertiesInEffect);
625     nodeStyle->removeEquivalentProperties(parentStyle.get());
626
627     unsigned propertyCount = nodeStyle->propertyCount();
628     for (unsigned i = 0; i < propertyCount; ++i)
629         m_mutableStyle->removeProperty(nodeStyle->propertyAt(i).id());
630 }
631
632 void EditingStyle::collapseTextDecorationProperties()
633 {
634     if (!m_mutableStyle)
635         return;
636
637     RefPtr<CSSValue> textDecorationsInEffect = m_mutableStyle->getPropertyCSSValue(CSSPropertyWebkitTextDecorationsInEffect);
638     if (!textDecorationsInEffect)
639         return;
640
641     if (textDecorationsInEffect->isValueList())
642         m_mutableStyle->setProperty(CSSPropertyTextDecoration, textDecorationsInEffect->cssText(), m_mutableStyle->propertyIsImportant(CSSPropertyTextDecoration));
643     else
644         m_mutableStyle->removeProperty(CSSPropertyTextDecoration);
645     m_mutableStyle->removeProperty(CSSPropertyWebkitTextDecorationsInEffect);
646 }
647
648 // CSS properties that create a visual difference only when applied to text.
649 static const CSSPropertyID textOnlyProperties[] = {
650     CSSPropertyTextDecoration,
651     CSSPropertyWebkitTextDecorationsInEffect,
652     CSSPropertyFontStyle,
653     CSSPropertyFontWeight,
654     CSSPropertyColor,
655 };
656
657 TriState EditingStyle::triStateOfStyle(EditingStyle* style) const
658 {
659     if (!style || !style->m_mutableStyle)
660         return FalseTriState;
661     return triStateOfStyle(style->m_mutableStyle.get(), DoNotIgnoreTextOnlyProperties);
662 }
663
664 template<typename T>
665 TriState EditingStyle::triStateOfStyle(T* styleToCompare, ShouldIgnoreTextOnlyProperties shouldIgnoreTextOnlyProperties) const
666 {
667     RefPtr<MutableStylePropertySet> difference = getPropertiesNotIn(m_mutableStyle.get(), styleToCompare);
668
669     if (shouldIgnoreTextOnlyProperties == IgnoreTextOnlyProperties)
670         difference->removePropertiesInSet(textOnlyProperties, WTF_ARRAY_LENGTH(textOnlyProperties));
671
672     if (difference->isEmpty())
673         return TrueTriState;
674     if (difference->propertyCount() == m_mutableStyle->propertyCount())
675         return FalseTriState;
676
677     return MixedTriState;
678 }
679
680 TriState EditingStyle::triStateOfStyle(const VisibleSelection& selection) const
681 {
682     if (!selection.isCaretOrRange())
683         return FalseTriState;
684
685     if (selection.isCaret())
686         return triStateOfStyle(EditingStyle::styleAtSelectionStart(selection).get());
687
688     TriState state = FalseTriState;
689     bool nodeIsStart = true;
690     for (Node* node = selection.start().deprecatedNode(); node; node = NodeTraversal::next(node)) {
691         if (node->renderer() && node->rendererIsEditable()) {
692             ComputedStyleExtractor computedStyle(node);
693             TriState nodeState = triStateOfStyle(&computedStyle, node->isTextNode() ? EditingStyle::DoNotIgnoreTextOnlyProperties : EditingStyle::IgnoreTextOnlyProperties);
694             if (nodeIsStart) {
695                 state = nodeState;
696                 nodeIsStart = false;
697             } else if (state != nodeState && node->isTextNode()) {
698                 state = MixedTriState;
699                 break;
700             }
701         }
702
703         if (node == selection.end().deprecatedNode())
704             break;
705     }
706
707     return state;
708 }
709
710 bool EditingStyle::conflictsWithInlineStyleOfElement(StyledElement* element, EditingStyle* extractedStyle, Vector<CSSPropertyID>* conflictingProperties) const
711 {
712     ASSERT(element);
713     ASSERT(!conflictingProperties || conflictingProperties->isEmpty());
714
715     const StylePropertySet* inlineStyle = element->inlineStyle();
716     if (!m_mutableStyle || !inlineStyle)
717         return false;
718
719     unsigned propertyCount = m_mutableStyle->propertyCount();
720     for (unsigned i = 0; i < propertyCount; ++i) {
721         CSSPropertyID propertyID = m_mutableStyle->propertyAt(i).id();
722
723         // We don't override whitespace property of a tab span because that would collapse the tab into a space.
724         if (propertyID == CSSPropertyWhiteSpace && isTabSpanNode(element))
725             continue;
726
727         if (propertyID == CSSPropertyWebkitTextDecorationsInEffect && inlineStyle->getPropertyCSSValue(CSSPropertyTextDecoration)) {
728             if (!conflictingProperties)
729                 return true;
730             conflictingProperties->append(CSSPropertyTextDecoration);
731             if (extractedStyle)
732                 extractedStyle->setProperty(CSSPropertyTextDecoration, inlineStyle->getPropertyValue(CSSPropertyTextDecoration), inlineStyle->propertyIsImportant(CSSPropertyTextDecoration));
733             continue;
734         }
735
736         if (!inlineStyle->getPropertyCSSValue(propertyID))
737             continue;
738
739         if (propertyID == CSSPropertyUnicodeBidi && inlineStyle->getPropertyCSSValue(CSSPropertyDirection)) {
740             if (!conflictingProperties)
741                 return true;
742             conflictingProperties->append(CSSPropertyDirection);
743             if (extractedStyle)
744                 extractedStyle->setProperty(propertyID, inlineStyle->getPropertyValue(propertyID), inlineStyle->propertyIsImportant(propertyID));
745         }
746
747         if (!conflictingProperties)
748             return true;
749
750         conflictingProperties->append(propertyID);
751
752         if (extractedStyle)
753             extractedStyle->setProperty(propertyID, inlineStyle->getPropertyValue(propertyID), inlineStyle->propertyIsImportant(propertyID));
754     }
755
756     return conflictingProperties && !conflictingProperties->isEmpty();
757 }
758
759 static const Vector<OwnPtr<HTMLElementEquivalent>>& htmlElementEquivalents()
760 {
761     DEFINE_STATIC_LOCAL(Vector<OwnPtr<HTMLElementEquivalent>>, HTMLElementEquivalents, ());
762
763     if (!HTMLElementEquivalents.size()) {
764         HTMLElementEquivalents.append(HTMLElementEquivalent::create(CSSPropertyFontWeight, CSSValueBold, HTMLNames::bTag));
765         HTMLElementEquivalents.append(HTMLElementEquivalent::create(CSSPropertyFontWeight, CSSValueBold, HTMLNames::strongTag));
766         HTMLElementEquivalents.append(HTMLElementEquivalent::create(CSSPropertyVerticalAlign, CSSValueSub, HTMLNames::subTag));
767         HTMLElementEquivalents.append(HTMLElementEquivalent::create(CSSPropertyVerticalAlign, CSSValueSuper, HTMLNames::supTag));
768         HTMLElementEquivalents.append(HTMLElementEquivalent::create(CSSPropertyFontStyle, CSSValueItalic, HTMLNames::iTag));
769         HTMLElementEquivalents.append(HTMLElementEquivalent::create(CSSPropertyFontStyle, CSSValueItalic, HTMLNames::emTag));
770
771         HTMLElementEquivalents.append(HTMLTextDecorationEquivalent::create(CSSValueUnderline, HTMLNames::uTag));
772         HTMLElementEquivalents.append(HTMLTextDecorationEquivalent::create(CSSValueLineThrough, HTMLNames::sTag));
773         HTMLElementEquivalents.append(HTMLTextDecorationEquivalent::create(CSSValueLineThrough, HTMLNames::strikeTag));
774     }
775
776     return HTMLElementEquivalents;
777 }
778
779
780 bool EditingStyle::conflictsWithImplicitStyleOfElement(HTMLElement* element, EditingStyle* extractedStyle, ShouldExtractMatchingStyle shouldExtractMatchingStyle) const
781 {
782     if (!m_mutableStyle)
783         return false;
784
785     const Vector<OwnPtr<HTMLElementEquivalent>>& HTMLElementEquivalents = htmlElementEquivalents();
786     for (size_t i = 0; i < HTMLElementEquivalents.size(); ++i) {
787         const HTMLElementEquivalent* equivalent = HTMLElementEquivalents[i].get();
788         if (equivalent->matches(element) && equivalent->propertyExistsInStyle(m_mutableStyle.get())
789             && (shouldExtractMatchingStyle == ExtractMatchingStyle || !equivalent->valueIsPresentInStyle(element, m_mutableStyle.get()))) {
790             if (extractedStyle)
791                 equivalent->addToStyle(element, extractedStyle);
792             return true;
793         }
794     }
795     return false;
796 }
797
798 static const Vector<OwnPtr<HTMLAttributeEquivalent>>& htmlAttributeEquivalents()
799 {
800     DEFINE_STATIC_LOCAL(Vector<OwnPtr<HTMLAttributeEquivalent>>, HTMLAttributeEquivalents, ());
801
802     if (!HTMLAttributeEquivalents.size()) {
803         // elementIsStyledSpanOrHTMLEquivalent depends on the fact each HTMLAttriuteEquivalent matches exactly one attribute
804         // of exactly one element except dirAttr.
805         HTMLAttributeEquivalents.append(HTMLAttributeEquivalent::create(CSSPropertyColor, HTMLNames::fontTag, HTMLNames::colorAttr));
806         HTMLAttributeEquivalents.append(HTMLAttributeEquivalent::create(CSSPropertyFontFamily, HTMLNames::fontTag, HTMLNames::faceAttr));
807         HTMLAttributeEquivalents.append(HTMLFontSizeEquivalent::create());
808
809         HTMLAttributeEquivalents.append(HTMLAttributeEquivalent::create(CSSPropertyDirection, HTMLNames::dirAttr));
810         HTMLAttributeEquivalents.append(HTMLAttributeEquivalent::create(CSSPropertyUnicodeBidi, HTMLNames::dirAttr));
811     }
812
813     return HTMLAttributeEquivalents;
814 }
815
816 bool EditingStyle::conflictsWithImplicitStyleOfAttributes(HTMLElement* element) const
817 {
818     ASSERT(element);
819     if (!m_mutableStyle)
820         return false;
821
822     const Vector<OwnPtr<HTMLAttributeEquivalent>>& HTMLAttributeEquivalents = htmlAttributeEquivalents();
823     for (size_t i = 0; i < HTMLAttributeEquivalents.size(); ++i) {
824         if (HTMLAttributeEquivalents[i]->matches(element) && HTMLAttributeEquivalents[i]->propertyExistsInStyle(m_mutableStyle.get())
825             && !HTMLAttributeEquivalents[i]->valueIsPresentInStyle(element, m_mutableStyle.get()))
826             return true;
827     }
828
829     return false;
830 }
831
832 bool EditingStyle::extractConflictingImplicitStyleOfAttributes(HTMLElement* element, ShouldPreserveWritingDirection shouldPreserveWritingDirection,
833     EditingStyle* extractedStyle, Vector<QualifiedName>& conflictingAttributes, ShouldExtractMatchingStyle shouldExtractMatchingStyle) const
834 {
835     ASSERT(element);
836     // HTMLAttributeEquivalent::addToStyle doesn't support unicode-bidi and direction properties
837     ASSERT(!extractedStyle || shouldPreserveWritingDirection == PreserveWritingDirection);
838     if (!m_mutableStyle)
839         return false;
840
841     const Vector<OwnPtr<HTMLAttributeEquivalent>>& HTMLAttributeEquivalents = htmlAttributeEquivalents();
842     bool removed = false;
843     for (size_t i = 0; i < HTMLAttributeEquivalents.size(); ++i) {
844         const HTMLAttributeEquivalent* equivalent = HTMLAttributeEquivalents[i].get();
845
846         // unicode-bidi and direction are pushed down separately so don't push down with other styles.
847         if (shouldPreserveWritingDirection == PreserveWritingDirection && equivalent->attributeName() == HTMLNames::dirAttr)
848             continue;
849
850         if (!equivalent->matches(element) || !equivalent->propertyExistsInStyle(m_mutableStyle.get())
851             || (shouldExtractMatchingStyle == DoNotExtractMatchingStyle && equivalent->valueIsPresentInStyle(element, m_mutableStyle.get())))
852             continue;
853
854         if (extractedStyle)
855             equivalent->addToStyle(element, extractedStyle);
856         conflictingAttributes.append(equivalent->attributeName());
857         removed = true;
858     }
859
860     return removed;
861 }
862
863 bool EditingStyle::styleIsPresentInComputedStyleOfNode(Node* node) const
864 {
865     if (!m_mutableStyle)
866         return true;
867     ComputedStyleExtractor computedStyle(node);
868     return getPropertiesNotIn(m_mutableStyle.get(), &computedStyle)->isEmpty();
869 }
870
871 bool EditingStyle::elementIsStyledSpanOrHTMLEquivalent(const HTMLElement* element)
872 {
873     bool elementIsSpanOrElementEquivalent = false;
874     if (element->hasTagName(HTMLNames::spanTag))
875         elementIsSpanOrElementEquivalent = true;
876     else {
877         const Vector<OwnPtr<HTMLElementEquivalent>>& HTMLElementEquivalents = htmlElementEquivalents();
878         size_t i;
879         for (i = 0; i < HTMLElementEquivalents.size(); ++i) {
880             if (HTMLElementEquivalents[i]->matches(element)) {
881                 elementIsSpanOrElementEquivalent = true;
882                 break;
883             }
884         }
885     }
886
887     if (!element->hasAttributes())
888         return elementIsSpanOrElementEquivalent; // span, b, etc... without any attributes
889
890     unsigned matchedAttributes = 0;
891     const Vector<OwnPtr<HTMLAttributeEquivalent>>& HTMLAttributeEquivalents = htmlAttributeEquivalents();
892     for (size_t i = 0; i < HTMLAttributeEquivalents.size(); ++i) {
893         if (HTMLAttributeEquivalents[i]->matches(element) && HTMLAttributeEquivalents[i]->attributeName() != HTMLNames::dirAttr)
894             matchedAttributes++;
895     }
896
897     if (!elementIsSpanOrElementEquivalent && !matchedAttributes)
898         return false; // element is not a span, a html element equivalent, or font element.
899     
900     if (element->getAttribute(HTMLNames::classAttr) == AppleStyleSpanClass)
901         matchedAttributes++;
902
903     if (element->hasAttribute(HTMLNames::styleAttr)) {
904         if (const StylePropertySet* style = element->inlineStyle()) {
905             unsigned propertyCount = style->propertyCount();
906             for (unsigned i = 0; i < propertyCount; ++i) {
907                 if (!isEditingProperty(style->propertyAt(i).id()))
908                     return false;
909             }
910         }
911         matchedAttributes++;
912     }
913
914     // font with color attribute, span with style attribute, etc...
915     ASSERT(matchedAttributes <= element->attributeCount());
916     return matchedAttributes >= element->attributeCount();
917 }
918
919 void EditingStyle::prepareToApplyAt(const Position& position, ShouldPreserveWritingDirection shouldPreserveWritingDirection)
920 {
921     if (!m_mutableStyle)
922         return;
923
924     // ReplaceSelectionCommand::handleStyleSpans() requires that this function only removes the editing style.
925     // If this function was modified in the future to delete all redundant properties, then add a boolean value to indicate
926     // which one of editingStyleAtPosition or computedStyle is called.
927     RefPtr<EditingStyle> editingStyleAtPosition = EditingStyle::create(position, EditingPropertiesInEffect);
928     StylePropertySet* styleAtPosition = editingStyleAtPosition->m_mutableStyle.get();
929
930     RefPtr<CSSValue> unicodeBidi;
931     RefPtr<CSSValue> direction;
932     if (shouldPreserveWritingDirection == PreserveWritingDirection) {
933         unicodeBidi = m_mutableStyle->getPropertyCSSValue(CSSPropertyUnicodeBidi);
934         direction = m_mutableStyle->getPropertyCSSValue(CSSPropertyDirection);
935     }
936
937     m_mutableStyle->removeEquivalentProperties(styleAtPosition);
938
939     if (textAlignResolvingStartAndEnd(m_mutableStyle.get()) == textAlignResolvingStartAndEnd(styleAtPosition))
940         m_mutableStyle->removeProperty(CSSPropertyTextAlign);
941
942     if (textColorFromStyle(m_mutableStyle.get()) == textColorFromStyle(styleAtPosition))
943         m_mutableStyle->removeProperty(CSSPropertyColor);
944
945     if (hasTransparentBackgroundColor(m_mutableStyle.get())
946         || cssValueToRGBA(m_mutableStyle->getPropertyCSSValue(CSSPropertyBackgroundColor).get()) == rgbaBackgroundColorInEffect(position.containerNode()))
947         m_mutableStyle->removeProperty(CSSPropertyBackgroundColor);
948
949     if (unicodeBidi && unicodeBidi->isPrimitiveValue()) {
950         m_mutableStyle->setProperty(CSSPropertyUnicodeBidi, static_cast<CSSValueID>(toCSSPrimitiveValue(unicodeBidi.get())->getValueID()));
951         if (direction && direction->isPrimitiveValue())
952             m_mutableStyle->setProperty(CSSPropertyDirection, static_cast<CSSValueID>(toCSSPrimitiveValue(direction.get())->getValueID()));
953     }
954 }
955
956 void EditingStyle::mergeTypingStyle(Document& document)
957 {
958     RefPtr<EditingStyle> typingStyle = document.frame()->selection().typingStyle();
959     if (!typingStyle || typingStyle == this)
960         return;
961
962     mergeStyle(typingStyle->style(), OverrideValues);
963 }
964
965 void EditingStyle::mergeInlineStyleOfElement(StyledElement* element, CSSPropertyOverrideMode mode, PropertiesToInclude propertiesToInclude)
966 {
967     ASSERT(element);
968     if (!element->inlineStyle())
969         return;
970
971     switch (propertiesToInclude) {
972     case AllProperties:
973         mergeStyle(element->inlineStyle(), mode);
974         return;
975     case OnlyEditingInheritableProperties:
976         mergeStyle(copyEditingProperties(element->inlineStyle(), OnlyInheritableEditingProperties).get(), mode);
977         return;
978     case EditingPropertiesInEffect:
979         mergeStyle(copyEditingProperties(element->inlineStyle(), AllEditingProperties).get(), mode);
980         return;
981     }
982 }
983
984 static inline bool elementMatchesAndPropertyIsNotInInlineStyleDecl(const HTMLElementEquivalent* equivalent, const StyledElement* element,
985     EditingStyle::CSSPropertyOverrideMode mode, StylePropertySet* style)
986 {
987     return equivalent->matches(element) && (!element->inlineStyle() || !equivalent->propertyExistsInStyle(element->inlineStyle()))
988         && (mode == EditingStyle::OverrideValues || !equivalent->propertyExistsInStyle(style));
989 }
990
991 static PassRefPtr<MutableStylePropertySet> extractEditingProperties(const StylePropertySet* style, EditingStyle::PropertiesToInclude propertiesToInclude)
992 {
993     if (!style)
994         return 0;
995
996     switch (propertiesToInclude) {
997     case EditingStyle::AllProperties:
998     case EditingStyle::EditingPropertiesInEffect:
999         return copyEditingProperties(style, AllEditingProperties);
1000     case EditingStyle::OnlyEditingInheritableProperties:
1001         return copyEditingProperties(style, OnlyInheritableEditingProperties);
1002     }
1003
1004     ASSERT_NOT_REACHED();
1005     return 0;
1006 }
1007
1008 void EditingStyle::mergeInlineAndImplicitStyleOfElement(StyledElement* element, CSSPropertyOverrideMode mode, PropertiesToInclude propertiesToInclude)
1009 {
1010     RefPtr<EditingStyle> styleFromRules = EditingStyle::create();
1011     styleFromRules->mergeStyleFromRulesForSerialization(element);
1012
1013     if (element->inlineStyle())
1014         styleFromRules->m_mutableStyle->mergeAndOverrideOnConflict(*element->inlineStyle());
1015
1016     styleFromRules->m_mutableStyle = extractEditingProperties(styleFromRules->m_mutableStyle.get(), propertiesToInclude);
1017     mergeStyle(styleFromRules->m_mutableStyle.get(), mode);
1018
1019     const Vector<OwnPtr<HTMLElementEquivalent>>& elementEquivalents = htmlElementEquivalents();
1020     for (size_t i = 0; i < elementEquivalents.size(); ++i) {
1021         if (elementMatchesAndPropertyIsNotInInlineStyleDecl(elementEquivalents[i].get(), element, mode, m_mutableStyle.get()))
1022             elementEquivalents[i]->addToStyle(element, this);
1023     }
1024
1025     const Vector<OwnPtr<HTMLAttributeEquivalent>>& attributeEquivalents = htmlAttributeEquivalents();
1026     for (size_t i = 0; i < attributeEquivalents.size(); ++i) {
1027         if (attributeEquivalents[i]->attributeName() == HTMLNames::dirAttr)
1028             continue; // We don't want to include directionality
1029         if (elementMatchesAndPropertyIsNotInInlineStyleDecl(attributeEquivalents[i].get(), element, mode, m_mutableStyle.get()))
1030             attributeEquivalents[i]->addToStyle(element, this);
1031     }
1032 }
1033
1034 PassRefPtr<EditingStyle> EditingStyle::wrappingStyleForSerialization(Node* context, bool shouldAnnotate)
1035 {
1036     RefPtr<EditingStyle> wrappingStyle;
1037     if (shouldAnnotate) {
1038         wrappingStyle = EditingStyle::create(context, EditingStyle::EditingPropertiesInEffect);
1039
1040         // Styles that Mail blockquotes contribute should only be placed on the Mail blockquote,
1041         // to help us differentiate those styles from ones that the user has applied.
1042         // This helps us get the color of content pasted into blockquotes right.
1043         wrappingStyle->removeStyleAddedByNode(enclosingNodeOfType(firstPositionInOrBeforeNode(context), isMailBlockquote, CanCrossEditingBoundary));
1044
1045         // Call collapseTextDecorationProperties first or otherwise it'll copy the value over from in-effect to text-decorations.
1046         wrappingStyle->collapseTextDecorationProperties();
1047         
1048         return wrappingStyle.release();
1049     }
1050
1051     wrappingStyle = EditingStyle::create();
1052
1053     // When not annotating for interchange, we only preserve inline style declarations.
1054     for (Node* node = context; node && !node->isDocumentNode(); node = node->parentNode()) {
1055         if (node->isStyledElement() && !isMailBlockquote(node)) {
1056             wrappingStyle->mergeInlineAndImplicitStyleOfElement(toStyledElement(node), EditingStyle::DoNotOverrideValues,
1057                 EditingStyle::EditingPropertiesInEffect);
1058         }
1059     }
1060
1061     return wrappingStyle.release();
1062 }
1063
1064
1065 static void mergeTextDecorationValues(CSSValueList* mergedValue, const CSSValueList* valueToMerge)
1066 {
1067     RefPtr<CSSPrimitiveValue> underline = cssValuePool().createIdentifierValue(CSSValueUnderline);
1068     RefPtr<CSSPrimitiveValue> lineThrough = cssValuePool().createIdentifierValue(CSSValueLineThrough);
1069
1070     if (valueToMerge->hasValue(underline.get()) && !mergedValue->hasValue(underline.get()))
1071         mergedValue->append(underline.get());
1072
1073     if (valueToMerge->hasValue(lineThrough.get()) && !mergedValue->hasValue(lineThrough.get()))
1074         mergedValue->append(lineThrough.get());
1075 }
1076
1077 void EditingStyle::mergeStyle(const StylePropertySet* style, CSSPropertyOverrideMode mode)
1078 {
1079     if (!style)
1080         return;
1081
1082     if (!m_mutableStyle) {
1083         m_mutableStyle = style->mutableCopy();
1084         return;
1085     }
1086
1087     unsigned propertyCount = style->propertyCount();
1088     for (unsigned i = 0; i < propertyCount; ++i) {
1089         StylePropertySet::PropertyReference property = style->propertyAt(i);
1090         RefPtr<CSSValue> value = m_mutableStyle->getPropertyCSSValue(property.id());
1091
1092         // text decorations never override values
1093         if ((property.id() == CSSPropertyTextDecoration || property.id() == CSSPropertyWebkitTextDecorationsInEffect) && property.value()->isValueList() && value) {
1094             if (value->isValueList()) {
1095                 mergeTextDecorationValues(toCSSValueList(value.get()), toCSSValueList(property.value()));
1096                 continue;
1097             }
1098             value = 0; // text-decoration: none is equivalent to not having the property
1099         }
1100
1101         if (mode == OverrideValues || (mode == DoNotOverrideValues && !value))
1102             m_mutableStyle->setProperty(property.id(), property.value()->cssText(), property.isImportant());
1103     }
1104
1105     int oldFontSizeDelta = m_fontSizeDelta;
1106     extractFontSizeDelta();
1107     m_fontSizeDelta += oldFontSizeDelta;
1108 }
1109
1110 static PassRefPtr<MutableStylePropertySet> styleFromMatchedRulesForElement(Element* element, unsigned rulesToInclude)
1111 {
1112     RefPtr<MutableStylePropertySet> style = MutableStylePropertySet::create();
1113     Vector<RefPtr<StyleRuleBase>> matchedRules = element->document().ensureStyleResolver().styleRulesForElement(element, rulesToInclude);
1114     for (unsigned i = 0; i < matchedRules.size(); ++i) {
1115         if (matchedRules[i]->isStyleRule())
1116             style->mergeAndOverrideOnConflict(static_pointer_cast<StyleRule>(matchedRules[i])->properties());
1117     }
1118     
1119     return style.release();
1120 }
1121
1122 void EditingStyle::mergeStyleFromRules(StyledElement* element)
1123 {
1124     RefPtr<MutableStylePropertySet> styleFromMatchedRules = styleFromMatchedRulesForElement(element,
1125         StyleResolver::AuthorCSSRules | StyleResolver::CrossOriginCSSRules);
1126     // Styles from the inline style declaration, held in the variable "style", take precedence 
1127     // over those from matched rules.
1128     if (m_mutableStyle)
1129         styleFromMatchedRules->mergeAndOverrideOnConflict(*m_mutableStyle);
1130
1131     clear();
1132     m_mutableStyle = styleFromMatchedRules;
1133 }
1134
1135 void EditingStyle::mergeStyleFromRulesForSerialization(StyledElement* element)
1136 {
1137     mergeStyleFromRules(element);
1138
1139     // The property value, if it's a percentage, may not reflect the actual computed value.  
1140     // For example: style="height: 1%; overflow: visible;" in quirksmode
1141     // FIXME: There are others like this, see <rdar://problem/5195123> Slashdot copy/paste fidelity problem
1142     RefPtr<MutableStylePropertySet> fromComputedStyle = MutableStylePropertySet::create();
1143     ComputedStyleExtractor computedStyle(element);
1144
1145     {
1146         unsigned propertyCount = m_mutableStyle->propertyCount();
1147         for (unsigned i = 0; i < propertyCount; ++i) {
1148             StylePropertySet::PropertyReference property = m_mutableStyle->propertyAt(i);
1149             CSSValue* value = property.value();
1150             if (!value->isPrimitiveValue())
1151                 continue;
1152             if (toCSSPrimitiveValue(value)->isPercentage()) {
1153                 if (RefPtr<CSSValue> computedPropertyValue = computedStyle.propertyValue(property.id()))
1154                     fromComputedStyle->addParsedProperty(CSSProperty(property.id(), computedPropertyValue.release()));
1155             }
1156         }
1157     }
1158     m_mutableStyle->mergeAndOverrideOnConflict(*fromComputedStyle);
1159 }
1160
1161 static void removePropertiesInStyle(MutableStylePropertySet* styleToRemovePropertiesFrom, StylePropertySet* style)
1162 {
1163     unsigned propertyCount = style->propertyCount();
1164     Vector<CSSPropertyID> propertiesToRemove(propertyCount);
1165     for (unsigned i = 0; i < propertyCount; ++i)
1166         propertiesToRemove[i] = style->propertyAt(i).id();
1167
1168     styleToRemovePropertiesFrom->removePropertiesInSet(propertiesToRemove.data(), propertiesToRemove.size());
1169 }
1170
1171 void EditingStyle::removeStyleFromRulesAndContext(StyledElement* element, Node* context)
1172 {
1173     ASSERT(element);
1174     if (!m_mutableStyle)
1175         return;
1176
1177     // 1. Remove style from matched rules because style remain without repeating it in inline style declaration
1178     RefPtr<MutableStylePropertySet> styleFromMatchedRules = styleFromMatchedRulesForElement(element, StyleResolver::AllButEmptyCSSRules);
1179     if (styleFromMatchedRules && !styleFromMatchedRules->isEmpty())
1180         m_mutableStyle = getPropertiesNotIn(m_mutableStyle.get(), styleFromMatchedRules.get());
1181
1182     // 2. Remove style present in context and not overriden by matched rules.
1183     RefPtr<EditingStyle> computedStyle = EditingStyle::create(context, EditingPropertiesInEffect);
1184     if (computedStyle->m_mutableStyle) {
1185         if (!computedStyle->m_mutableStyle->getPropertyCSSValue(CSSPropertyBackgroundColor))
1186             computedStyle->m_mutableStyle->setProperty(CSSPropertyBackgroundColor, CSSValueTransparent);
1187
1188         removePropertiesInStyle(computedStyle->m_mutableStyle.get(), styleFromMatchedRules.get());
1189         m_mutableStyle = getPropertiesNotIn(m_mutableStyle.get(), computedStyle->m_mutableStyle.get());
1190     }
1191
1192     // 3. If this element is a span and has display: inline or float: none, remove them unless they are overriden by rules.
1193     // These rules are added by serialization code to wrap text nodes.
1194     if (isStyleSpanOrSpanWithOnlyStyleAttribute(element)) {
1195         if (!styleFromMatchedRules->getPropertyCSSValue(CSSPropertyDisplay) && identifierForStyleProperty(m_mutableStyle.get(), CSSPropertyDisplay) == CSSValueInline)
1196             m_mutableStyle->removeProperty(CSSPropertyDisplay);
1197         if (!styleFromMatchedRules->getPropertyCSSValue(CSSPropertyFloat) && identifierForStyleProperty(m_mutableStyle.get(), CSSPropertyFloat) == CSSValueNone)
1198             m_mutableStyle->removeProperty(CSSPropertyFloat);
1199     }
1200 }
1201
1202 void EditingStyle::removePropertiesInElementDefaultStyle(Element* element)
1203 {
1204     if (!m_mutableStyle || m_mutableStyle->isEmpty())
1205         return;
1206
1207     RefPtr<StylePropertySet> defaultStyle = styleFromMatchedRulesForElement(element, StyleResolver::UAAndUserCSSRules);
1208
1209     removePropertiesInStyle(m_mutableStyle.get(), defaultStyle.get());
1210 }
1211
1212 void EditingStyle::forceInline()
1213 {
1214     if (!m_mutableStyle)
1215         m_mutableStyle = MutableStylePropertySet::create();
1216     const bool propertyIsImportant = true;
1217     m_mutableStyle->setProperty(CSSPropertyDisplay, CSSValueInline, propertyIsImportant);
1218 }
1219
1220 int EditingStyle::legacyFontSize(Document* document) const
1221 {
1222     RefPtr<CSSValue> cssValue = m_mutableStyle->getPropertyCSSValue(CSSPropertyFontSize);
1223     if (!cssValue || !cssValue->isPrimitiveValue())
1224         return 0;
1225     return legacyFontSizeFromCSSValue(document, toCSSPrimitiveValue(cssValue.get()),
1226         m_shouldUseFixedDefaultFontSize, AlwaysUseLegacyFontSize);
1227 }
1228
1229 PassRefPtr<EditingStyle> EditingStyle::styleAtSelectionStart(const VisibleSelection& selection, bool shouldUseBackgroundColorInEffect)
1230 {
1231     if (selection.isNone())
1232         return 0;
1233
1234     Position position = adjustedSelectionStartForStyleComputation(selection);
1235
1236     // If the pos is at the end of a text node, then this node is not fully selected. 
1237     // Move it to the next deep equivalent position to avoid removing the style from this node. 
1238     // e.g. if pos was at Position("hello", 5) in <b>hello<div>world</div></b>, we want Position("world", 0) instead. 
1239     // We only do this for range because caret at Position("hello", 5) in <b>hello</b>world should give you font-weight: bold. 
1240     Node* positionNode = position.containerNode(); 
1241     if (selection.isRange() && positionNode && positionNode->isTextNode() && position.computeOffsetInContainerNode() == positionNode->maxCharacterOffset()) 
1242         position = nextVisuallyDistinctCandidate(position); 
1243
1244     Element* element = position.element();
1245     if (!element)
1246         return 0;
1247
1248     RefPtr<EditingStyle> style = EditingStyle::create(element, EditingStyle::AllProperties);
1249     style->mergeTypingStyle(element->document());
1250
1251     // If background color is transparent, traverse parent nodes until we hit a different value or document root
1252     // Also, if the selection is a range, ignore the background color at the start of selection,
1253     // and find the background color of the common ancestor.
1254     if (shouldUseBackgroundColorInEffect && (selection.isRange() || hasTransparentBackgroundColor(style->m_mutableStyle.get()))) {
1255         RefPtr<Range> range(selection.toNormalizedRange());
1256         if (PassRefPtr<CSSValue> value = backgroundColorInEffect(range->commonAncestorContainer(IGNORE_EXCEPTION)))
1257             style->setProperty(CSSPropertyBackgroundColor, value->cssText());
1258     }
1259
1260     return style;
1261 }
1262
1263 WritingDirection EditingStyle::textDirectionForSelection(const VisibleSelection& selection, EditingStyle* typingStyle, bool& hasNestedOrMultipleEmbeddings)
1264 {
1265     hasNestedOrMultipleEmbeddings = true;
1266
1267     if (selection.isNone())
1268         return NaturalWritingDirection;
1269
1270     Position position = selection.start().downstream();
1271
1272     Node* node = position.deprecatedNode();
1273     if (!node)
1274         return NaturalWritingDirection;
1275
1276     Position end;
1277     if (selection.isRange()) {
1278         end = selection.end().upstream();
1279
1280         Node* pastLast = Range::create(*end.document(), position.parentAnchoredEquivalent(), end.parentAnchoredEquivalent())->pastLastNode();
1281         for (Node* n = node; n && n != pastLast; n = NodeTraversal::next(n)) {
1282             if (!n->isStyledElement())
1283                 continue;
1284
1285             RefPtr<CSSValue> unicodeBidi = ComputedStyleExtractor(n).propertyValue(CSSPropertyUnicodeBidi);
1286             if (!unicodeBidi || !unicodeBidi->isPrimitiveValue())
1287                 continue;
1288
1289             CSSValueID unicodeBidiValue = toCSSPrimitiveValue(unicodeBidi.get())->getValueID();
1290             if (unicodeBidiValue == CSSValueEmbed || unicodeBidiValue == CSSValueBidiOverride)
1291                 return NaturalWritingDirection;
1292         }
1293     }
1294
1295     if (selection.isCaret()) {
1296         WritingDirection direction;
1297         if (typingStyle && typingStyle->textDirection(direction)) {
1298             hasNestedOrMultipleEmbeddings = false;
1299             return direction;
1300         }
1301         node = selection.visibleStart().deepEquivalent().deprecatedNode();
1302     }
1303
1304     // The selection is either a caret with no typing attributes or a range in which no embedding is added, so just use the start position
1305     // to decide.
1306     Node* block = enclosingBlock(node);
1307     WritingDirection foundDirection = NaturalWritingDirection;
1308
1309     for (; node != block; node = node->parentNode()) {
1310         if (!node->isStyledElement())
1311             continue;
1312
1313         ComputedStyleExtractor computedStyle(node);
1314         RefPtr<CSSValue> unicodeBidi = computedStyle.propertyValue(CSSPropertyUnicodeBidi);
1315         if (!unicodeBidi || !unicodeBidi->isPrimitiveValue())
1316             continue;
1317
1318         CSSValueID unicodeBidiValue = toCSSPrimitiveValue(unicodeBidi.get())->getValueID();
1319         if (unicodeBidiValue == CSSValueNormal)
1320             continue;
1321
1322         if (unicodeBidiValue == CSSValueBidiOverride)
1323             return NaturalWritingDirection;
1324
1325         ASSERT(unicodeBidiValue == CSSValueEmbed);
1326         RefPtr<CSSValue> direction = computedStyle.propertyValue(CSSPropertyDirection);
1327         if (!direction || !direction->isPrimitiveValue())
1328             continue;
1329
1330         CSSValueID directionValue = toCSSPrimitiveValue(direction.get())->getValueID();
1331         if (directionValue != CSSValueLtr && directionValue != CSSValueRtl)
1332             continue;
1333
1334         if (foundDirection != NaturalWritingDirection)
1335             return NaturalWritingDirection;
1336
1337         // In the range case, make sure that the embedding element persists until the end of the range.
1338         if (selection.isRange() && !end.deprecatedNode()->isDescendantOf(node))
1339             return NaturalWritingDirection;
1340         
1341         foundDirection = directionValue == CSSValueLtr ? LeftToRightWritingDirection : RightToLeftWritingDirection;
1342     }
1343     hasNestedOrMultipleEmbeddings = false;
1344     return foundDirection;
1345 }
1346
1347 static void reconcileTextDecorationProperties(MutableStylePropertySet* style)
1348 {    
1349     RefPtr<CSSValue> textDecorationsInEffect = style->getPropertyCSSValue(CSSPropertyWebkitTextDecorationsInEffect);
1350     RefPtr<CSSValue> textDecoration = style->getPropertyCSSValue(CSSPropertyTextDecoration);
1351     // We shouldn't have both text-decoration and -webkit-text-decorations-in-effect because that wouldn't make sense.
1352     ASSERT(!textDecorationsInEffect || !textDecoration);
1353     if (textDecorationsInEffect) {
1354         style->setProperty(CSSPropertyTextDecoration, textDecorationsInEffect->cssText());
1355         style->removeProperty(CSSPropertyWebkitTextDecorationsInEffect);
1356         textDecoration = textDecorationsInEffect;
1357     }
1358
1359     // If text-decoration is set to "none", remove the property because we don't want to add redundant "text-decoration: none".
1360     if (textDecoration && !textDecoration->isValueList())
1361         style->removeProperty(CSSPropertyTextDecoration);
1362 }
1363
1364 StyleChange::StyleChange(EditingStyle* style, const Position& position)
1365     : m_applyBold(false)
1366     , m_applyItalic(false)
1367     , m_applyUnderline(false)
1368     , m_applyLineThrough(false)
1369     , m_applySubscript(false)
1370     , m_applySuperscript(false)
1371 {
1372     Document* document = position.anchorNode() ? &position.anchorNode()->document() : 0;
1373     if (!style || !style->style() || !document || !document->frame())
1374         return;
1375
1376     Node* node = position.containerNode();
1377     if (!node)
1378         return;
1379
1380     ComputedStyleExtractor computedStyle(node);
1381
1382     // FIXME: take care of background-color in effect
1383     RefPtr<MutableStylePropertySet> mutableStyle = getPropertiesNotIn(style->style(), &computedStyle);
1384
1385     reconcileTextDecorationProperties(mutableStyle.get());
1386     if (!document->frame()->editor().shouldStyleWithCSS())
1387         extractTextStyles(document, mutableStyle.get(), computedStyle.useFixedFontDefaultSize());
1388
1389     // Changing the whitespace style in a tab span would collapse the tab into a space.
1390     if (isTabSpanTextNode(position.deprecatedNode()) || isTabSpanNode((position.deprecatedNode())))
1391         mutableStyle->removeProperty(CSSPropertyWhiteSpace);
1392
1393     // If unicode-bidi is present in mutableStyle and direction is not, then add direction to mutableStyle.
1394     // FIXME: Shouldn't this be done in getPropertiesNotIn?
1395     if (mutableStyle->getPropertyCSSValue(CSSPropertyUnicodeBidi) && !style->style()->getPropertyCSSValue(CSSPropertyDirection))
1396         mutableStyle->setProperty(CSSPropertyDirection, style->style()->getPropertyValue(CSSPropertyDirection));
1397
1398     // Save the result for later
1399     m_cssStyle = mutableStyle->asText().stripWhiteSpace();
1400 }
1401
1402 static void setTextDecorationProperty(MutableStylePropertySet* style, const CSSValueList* newTextDecoration, CSSPropertyID propertyID)
1403 {
1404     if (newTextDecoration->length())
1405         style->setProperty(propertyID, newTextDecoration->cssText(), style->propertyIsImportant(propertyID));
1406     else {
1407         // text-decoration: none is redundant since it does not remove any text decorations.
1408         style->removeProperty(propertyID);
1409     }
1410 }
1411
1412 void StyleChange::extractTextStyles(Document* document, MutableStylePropertySet* style, bool shouldUseFixedFontDefaultSize)
1413 {
1414     ASSERT(style);
1415
1416     if (identifierForStyleProperty(style, CSSPropertyFontWeight) == CSSValueBold) {
1417         style->removeProperty(CSSPropertyFontWeight);
1418         m_applyBold = true;
1419     }
1420
1421     int fontStyle = identifierForStyleProperty(style, CSSPropertyFontStyle);
1422     if (fontStyle == CSSValueItalic || fontStyle == CSSValueOblique) {
1423         style->removeProperty(CSSPropertyFontStyle);
1424         m_applyItalic = true;
1425     }
1426
1427     // Assuming reconcileTextDecorationProperties has been called, there should not be -webkit-text-decorations-in-effect
1428     // Furthermore, text-decoration: none has been trimmed so that text-decoration property is always a CSSValueList.
1429     RefPtr<CSSValue> textDecoration = style->getPropertyCSSValue(CSSPropertyTextDecoration);
1430     if (textDecoration && textDecoration->isValueList()) {
1431         RefPtr<CSSPrimitiveValue> underline = cssValuePool().createIdentifierValue(CSSValueUnderline);
1432         RefPtr<CSSPrimitiveValue> lineThrough = cssValuePool().createIdentifierValue(CSSValueLineThrough);
1433
1434         RefPtr<CSSValueList> newTextDecoration = toCSSValueList(textDecoration.get())->copy();
1435         if (newTextDecoration->removeAll(underline.get()))
1436             m_applyUnderline = true;
1437         if (newTextDecoration->removeAll(lineThrough.get()))
1438             m_applyLineThrough = true;
1439
1440         // If trimTextDecorations, delete underline and line-through
1441         setTextDecorationProperty(style, newTextDecoration.get(), CSSPropertyTextDecoration);
1442     }
1443
1444     int verticalAlign = identifierForStyleProperty(style, CSSPropertyVerticalAlign);
1445     switch (verticalAlign) {
1446     case CSSValueSub:
1447         style->removeProperty(CSSPropertyVerticalAlign);
1448         m_applySubscript = true;
1449         break;
1450     case CSSValueSuper:
1451         style->removeProperty(CSSPropertyVerticalAlign);
1452         m_applySuperscript = true;
1453         break;
1454     }
1455
1456     if (style->getPropertyCSSValue(CSSPropertyColor)) {
1457         m_applyFontColor = Color(textColorFromStyle(style)).serialized();
1458         style->removeProperty(CSSPropertyColor);
1459     }
1460
1461     m_applyFontFace = style->getPropertyValue(CSSPropertyFontFamily);
1462     // Remove single quotes for Outlook 2007 compatibility. See https://bugs.webkit.org/show_bug.cgi?id=79448
1463     m_applyFontFace.replaceWithLiteral('\'', "");
1464     style->removeProperty(CSSPropertyFontFamily);
1465
1466     if (RefPtr<CSSValue> fontSize = style->getPropertyCSSValue(CSSPropertyFontSize)) {
1467         if (!fontSize->isPrimitiveValue())
1468             style->removeProperty(CSSPropertyFontSize); // Can't make sense of the number. Put no font size.
1469         else if (int legacyFontSize = legacyFontSizeFromCSSValue(document, toCSSPrimitiveValue(fontSize.get()),
1470                 shouldUseFixedFontDefaultSize, UseLegacyFontSizeOnlyIfPixelValuesMatch)) {
1471             m_applyFontSize = String::number(legacyFontSize);
1472             style->removeProperty(CSSPropertyFontSize);
1473         }
1474     }
1475 }
1476
1477 static void diffTextDecorations(MutableStylePropertySet* style, CSSPropertyID propertID, CSSValue* refTextDecoration)
1478 {
1479     RefPtr<CSSValue> textDecoration = style->getPropertyCSSValue(propertID);
1480     if (!textDecoration || !textDecoration->isValueList() || !refTextDecoration || !refTextDecoration->isValueList())
1481         return;
1482
1483     RefPtr<CSSValueList> newTextDecoration = toCSSValueList(textDecoration.get())->copy();
1484     CSSValueList* valuesInRefTextDecoration = toCSSValueList(refTextDecoration);
1485
1486     for (size_t i = 0; i < valuesInRefTextDecoration->length(); i++)
1487         newTextDecoration->removeAll(valuesInRefTextDecoration->item(i));
1488
1489     setTextDecorationProperty(style, newTextDecoration.get(), propertID);
1490 }
1491
1492 static bool fontWeightIsBold(CSSValue* fontWeight)
1493 {
1494     if (!fontWeight)
1495         return false;
1496     if (!fontWeight->isPrimitiveValue())
1497         return false;
1498
1499     // Because b tag can only bold text, there are only two states in plain html: bold and not bold.
1500     // Collapse all other values to either one of these two states for editing purposes.
1501     switch (toCSSPrimitiveValue(fontWeight)->getValueID()) {
1502         case CSSValue100:
1503         case CSSValue200:
1504         case CSSValue300:
1505         case CSSValue400:
1506         case CSSValue500:
1507         case CSSValueNormal:
1508             return false;
1509         case CSSValueBold:
1510         case CSSValue600:
1511         case CSSValue700:
1512         case CSSValue800:
1513         case CSSValue900:
1514             return true;
1515         default:
1516             break;
1517     }
1518
1519     ASSERT_NOT_REACHED(); // For CSSValueBolder and CSSValueLighter
1520     return false;
1521 }
1522
1523 template<typename T>
1524 static bool fontWeightIsBold(T* style)
1525 {
1526     return fontWeightIsBold(extractPropertyValue(style, CSSPropertyFontWeight).get());
1527 }
1528
1529 template<typename T>
1530 static PassRefPtr<MutableStylePropertySet> extractPropertiesNotIn(StylePropertySet* styleWithRedundantProperties, T* baseStyle)
1531 {
1532     ASSERT(styleWithRedundantProperties);
1533     RefPtr<MutableStylePropertySet> result = styleWithRedundantProperties->mutableCopy();
1534
1535     result->removeEquivalentProperties(baseStyle);
1536
1537     RefPtr<CSSValue> baseTextDecorationsInEffect = extractPropertyValue(baseStyle, CSSPropertyWebkitTextDecorationsInEffect);
1538     diffTextDecorations(result.get(), CSSPropertyTextDecoration, baseTextDecorationsInEffect.get());
1539     diffTextDecorations(result.get(), CSSPropertyWebkitTextDecorationsInEffect, baseTextDecorationsInEffect.get());
1540
1541     if (extractPropertyValue(baseStyle, CSSPropertyFontWeight) && fontWeightIsBold(result.get()) == fontWeightIsBold(baseStyle))
1542         result->removeProperty(CSSPropertyFontWeight);
1543
1544     if (extractPropertyValue(baseStyle, CSSPropertyColor) && textColorFromStyle(result.get()) == textColorFromStyle(baseStyle))
1545         result->removeProperty(CSSPropertyColor);
1546
1547     if (extractPropertyValue(baseStyle, CSSPropertyTextAlign)
1548         && textAlignResolvingStartAndEnd(result.get()) == textAlignResolvingStartAndEnd(baseStyle))
1549         result->removeProperty(CSSPropertyTextAlign);
1550
1551     if (extractPropertyValue(baseStyle, CSSPropertyBackgroundColor) && backgroundColorFromStyle(result.get()) == backgroundColorFromStyle(baseStyle))
1552         result->removeProperty(CSSPropertyBackgroundColor);
1553
1554     return result.release();
1555 }
1556
1557 template<typename T>
1558 PassRefPtr<MutableStylePropertySet> getPropertiesNotIn(StylePropertySet* styleWithRedundantProperties, T* baseStyle)
1559 {
1560     return extractPropertiesNotIn(styleWithRedundantProperties, baseStyle);
1561 }
1562
1563 static bool isCSSValueLength(CSSPrimitiveValue* value)
1564 {
1565     return value->isFontIndependentLength();
1566 }
1567
1568 int legacyFontSizeFromCSSValue(Document* document, CSSPrimitiveValue* value, bool shouldUseFixedFontDefaultSize, LegacyFontSizeMode mode)
1569 {
1570     ASSERT(document); // FIXME: This method should take a Document&
1571
1572     if (isCSSValueLength(value)) {
1573         int pixelFontSize = value->getIntValue(CSSPrimitiveValue::CSS_PX);
1574         int legacyFontSize = Style::legacyFontSizeForPixelSize(pixelFontSize, shouldUseFixedFontDefaultSize, *document);
1575         // Use legacy font size only if pixel value matches exactly to that of legacy font size.
1576         int cssPrimitiveEquivalent = legacyFontSize - 1 + CSSValueXSmall;
1577         if (mode == AlwaysUseLegacyFontSize || Style::fontSizeForKeyword(cssPrimitiveEquivalent, shouldUseFixedFontDefaultSize, *document) == pixelFontSize)
1578             return legacyFontSize;
1579
1580         return 0;
1581     }
1582
1583     if (CSSValueXSmall <= value->getValueID() && value->getValueID() <= CSSValueWebkitXxxLarge)
1584         return value->getValueID() - CSSValueXSmall + 1;
1585
1586     return 0;
1587 }
1588
1589 bool isTransparentColorValue(CSSValue* cssValue)
1590 {
1591     if (!cssValue)
1592         return true;
1593     if (!cssValue->isPrimitiveValue())
1594         return false;
1595     CSSPrimitiveValue* value = toCSSPrimitiveValue(cssValue);    
1596     if (value->isRGBColor())
1597         return !alphaChannel(value->getRGBA32Value());    
1598     return value->getValueID() == CSSValueTransparent;
1599 }
1600
1601 bool hasTransparentBackgroundColor(StylePropertySet* style)
1602 {
1603     RefPtr<CSSValue> cssValue = style->getPropertyCSSValue(CSSPropertyBackgroundColor);
1604     return isTransparentColorValue(cssValue.get());
1605 }
1606
1607 PassRefPtr<CSSValue> backgroundColorInEffect(Node* node)
1608 {
1609     for (Node* ancestor = node; ancestor; ancestor = ancestor->parentNode()) {
1610         if (RefPtr<CSSValue> value = ComputedStyleExtractor(ancestor).propertyValue(CSSPropertyBackgroundColor)) {
1611             if (!isTransparentColorValue(value.get()))
1612                 return value.release();
1613         }
1614     }
1615     return 0;
1616 }
1617
1618 }