ApplyStyleCommand.cpp 62.1 KB
Newer Older
mjs's avatar
mjs committed
1
/*
2
 * Copyright (C) 2005, 2006, 2008, 2009 Apple Inc. All rights reserved.
mjs's avatar
mjs committed
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
 */

mjs's avatar
mjs committed
26
#include "config.h"
darin's avatar
darin committed
27
#include "ApplyStyleCommand.h"
mjs's avatar
mjs committed
28

darin's avatar
darin committed
29
#include "CSSComputedStyleDeclaration.h"
darin@apple.com's avatar
darin@apple.com committed
30
#include "CSSMutableStyleDeclaration.h"
weinig's avatar
weinig committed
31
#include "CSSParser.h"
32
#include "CSSProperty.h"
darin's avatar
darin committed
33
#include "CSSPropertyNames.h"
34
#include "CSSStyleSelector.h"
mitz@apple.com's avatar
mitz@apple.com committed
35
#include "CSSValueKeywords.h"
36
#include "CSSValueList.h"
darin's avatar
darin committed
37
#include "Document.h"
38
#include "EditingStyle.h"
justin.garcia@apple.com's avatar
justin.garcia@apple.com committed
39 40
#include "Editor.h"
#include "Frame.h"
41
#include "HTMLFontElement.h"
darin's avatar
darin committed
42 43
#include "HTMLInterchange.h"
#include "HTMLNames.h"
darin's avatar
darin committed
44
#include "NodeList.h"
darin's avatar
darin committed
45 46
#include "Range.h"
#include "RenderObject.h"
47
#include "RenderText.h"
darin's avatar
darin committed
48
#include "Text.h"
justing's avatar
justing committed
49
#include "TextIterator.h"
weinig's avatar
weinig committed
50
#include "htmlediting.h"
justing's avatar
justing committed
51
#include "visible_units.h"
52
#include <wtf/StdLibExtras.h>
mjs's avatar
mjs committed
53

darin's avatar
darin committed
54 55 56
namespace WebCore {

using namespace HTMLNames;
mjs's avatar
mjs committed
57

eric@webkit.org's avatar
eric@webkit.org committed
58
static String& styleSpanClassString()
mjs's avatar
mjs committed
59
{
60
    DEFINE_STATIC_LOCAL(String, styleSpanClassString, ((AppleStyleSpanClass)));
mjs's avatar
mjs committed
61 62 63
    return styleSpanClassString;
}

darin's avatar
darin committed
64
bool isStyleSpan(const Node *node)
mjs's avatar
mjs committed
65 66 67 68
{
    if (!node || !node->isHTMLElement())
        return false;

eric@webkit.org's avatar
eric@webkit.org committed
69
    const HTMLElement* elem = static_cast<const HTMLElement*>(node);
70
    return elem->hasLocalName(spanAttr) && elem->getAttribute(classAttr) == styleSpanClassString();
mjs's avatar
mjs committed
71 72
}

eric@webkit.org's avatar
eric@webkit.org committed
73
static bool isUnstyledStyleSpan(const Node* node)
mjs's avatar
mjs committed
74
{
75
    if (!node || !node->isHTMLElement() || !node->hasTagName(spanTag))
mjs's avatar
mjs committed
76 77
        return false;

eric@webkit.org's avatar
eric@webkit.org committed
78 79
    const HTMLElement* elem = static_cast<const HTMLElement*>(node);
    CSSMutableStyleDeclaration* inlineStyleDecl = elem->inlineStyleDecl();
80
    return (!inlineStyleDecl || inlineStyleDecl->isEmpty()) && elem->getAttribute(classAttr) == styleSpanClassString();
mjs's avatar
mjs committed
81 82
}

eric@webkit.org's avatar
eric@webkit.org committed
83 84 85 86 87 88
static bool isSpanWithoutAttributesOrUnstyleStyleSpan(const Node* node)
{
    if (!node || !node->isHTMLElement() || !node->hasTagName(spanTag))
        return false;

    const HTMLElement* elem = static_cast<const HTMLElement*>(node);
89
    NamedNodeMap* attributes = elem->attributes(true); // readonly
90
    if (attributes->isEmpty())
eric@webkit.org's avatar
eric@webkit.org committed
91 92 93 94 95
        return true;

    return isUnstyledStyleSpan(node);
}

darin's avatar
darin committed
96
static bool isEmptyFontTag(const Node *node)
mjs's avatar
mjs committed
97
{
98
    if (!node || !node->hasTagName(fontTag))
mjs's avatar
mjs committed
99 100
        return false;

darin's avatar
darin committed
101
    const Element *elem = static_cast<const Element *>(node);
102
    NamedNodeMap *map = elem->attributes(true); // true for read-only
103 104 105
    if (!map)
        return true;
    return map->isEmpty() || (map->length() == 1 && elem->getAttribute(classAttr) == styleSpanClassString());
mjs's avatar
mjs committed
106 107
}

darin's avatar
darin committed
108
static PassRefPtr<Element> createFontElement(Document* document)
mjs's avatar
mjs committed
109
{
eric@webkit.org's avatar
eric@webkit.org committed
110
    RefPtr<Element> fontNode = createHTMLElement(document, fontTag);
111
    fontNode->setAttribute(classAttr, styleSpanClassString());
darin's avatar
darin committed
112
    return fontNode.release();
mjs's avatar
mjs committed
113 114
}

darin's avatar
darin committed
115
PassRefPtr<HTMLElement> createStyleSpanElement(Document* document)
mjs's avatar
mjs committed
116
{
eric@webkit.org's avatar
eric@webkit.org committed
117
    RefPtr<HTMLElement> styleElement = createHTMLElement(document, spanTag);
118
    styleElement->setAttribute(classAttr, styleSpanClassString());
119
    return styleElement.release();
mjs's avatar
mjs committed
120
}
121

122
ApplyStyleCommand::ApplyStyleCommand(Document* document, const EditingStyle* style, EditAction editingAction, EPropertyLevel propertyLevel)
justing's avatar
justing committed
123
    : CompositeEditCommand(document)
124
    , m_style(style->copy())
justing's avatar
justing committed
125 126 127 128 129
    , m_editingAction(editingAction)
    , m_propertyLevel(propertyLevel)
    , m_start(endingSelection().start().downstream())
    , m_end(endingSelection().end().upstream())
    , m_useEndingSelection(true)
justing's avatar
justing committed
130 131
    , m_styledInlineElement(0)
    , m_removeOnly(false)
132
    , m_isInlineElementToRemoveFunction(0)
justing's avatar
justing committed
133
{
harrison's avatar
harrison committed
134 135
}

136
ApplyStyleCommand::ApplyStyleCommand(Document* document, const EditingStyle* style, const Position& start, const Position& end, EditAction editingAction, EPropertyLevel propertyLevel)
justing's avatar
justing committed
137
    : CompositeEditCommand(document)
138
    , m_style(style->copy())
justing's avatar
justing committed
139 140 141 142 143
    , m_editingAction(editingAction)
    , m_propertyLevel(propertyLevel)
    , m_start(start)
    , m_end(end)
    , m_useEndingSelection(false)
justing's avatar
justing committed
144 145
    , m_styledInlineElement(0)
    , m_removeOnly(false)
146
    , m_isInlineElementToRemoveFunction(0)
justing's avatar
justing committed
147 148 149
{
}

150
ApplyStyleCommand::ApplyStyleCommand(PassRefPtr<Element> element, bool removeOnly, EditAction editingAction)
darin's avatar
darin committed
151
    : CompositeEditCommand(element->document())
152
    , m_style(EditingStyle::create())
justing's avatar
justing committed
153 154 155 156 157
    , m_editingAction(editingAction)
    , m_propertyLevel(PropertyDefault)
    , m_start(endingSelection().start().downstream())
    , m_end(endingSelection().end().upstream())
    , m_useEndingSelection(true)
justing's avatar
justing committed
158
    , m_styledInlineElement(element)
justing's avatar
justing committed
159
    , m_removeOnly(removeOnly)
160 161 162 163
    , m_isInlineElementToRemoveFunction(0)
{
}

164
ApplyStyleCommand::ApplyStyleCommand(Document* document, const EditingStyle* style, IsInlineElementToRemoveFunction isInlineElementToRemoveFunction, EditAction editingAction)
165
    : CompositeEditCommand(document)
166
    , m_style(style->copy())
167 168 169 170 171 172 173 174
    , m_editingAction(editingAction)
    , m_propertyLevel(PropertyDefault)
    , m_start(endingSelection().start().downstream())
    , m_end(endingSelection().end().upstream())
    , m_useEndingSelection(true)
    , m_styledInlineElement(0)
    , m_removeOnly(true)
    , m_isInlineElementToRemoveFunction(isInlineElementToRemoveFunction)
harrison's avatar
harrison committed
175
{
mjs's avatar
mjs committed
176 177
}

darin's avatar
darin committed
178
void ApplyStyleCommand::updateStartEnd(const Position& newStart, const Position& newEnd)
harrison's avatar
harrison committed
179
{
180
    ASSERT(comparePositions(newEnd, newStart) >= 0);
harrison's avatar
harrison committed
181 182 183 184

    if (!m_useEndingSelection && (newStart != m_start || newEnd != m_end))
        m_useEndingSelection = true;

185
    setEndingSelection(VisibleSelection(newStart, newEnd, VP_DEFAULT_AFFINITY));
harrison's avatar
harrison committed
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
    m_start = newStart;
    m_end = newEnd;
}

Position ApplyStyleCommand::startPosition()
{
    if (m_useEndingSelection)
        return endingSelection().start();
    
    return m_start;
}

Position ApplyStyleCommand::endPosition()
{
    if (m_useEndingSelection)
        return endingSelection().end();
    
    return m_end;
}

mjs's avatar
mjs committed
206 207 208
void ApplyStyleCommand::doApply()
{
    switch (m_propertyLevel) {
209 210 211 212
    case PropertyDefault: {
        // Apply the block-centric properties of the style.
        RefPtr<EditingStyle> blockStyle = m_style->extractAndRemoveBlockProperties();
        if (!blockStyle->isEmpty())
213
            applyBlockStyle(blockStyle.get());
214 215
        // Apply any remaining styles to the inline elements.
        if (!m_style->isEmpty() || m_styledInlineElement || m_isInlineElementToRemoveFunction) {
216
            applyRelativeFontStyleChange(m_style.get());
217
            applyInlineStyle(m_style.get());
mjs's avatar
mjs committed
218
        }
219 220 221 222
        break;
    }
    case ForceBlockProperties:
        // Force all properties to be applied as block styles.
223
        applyBlockStyle(m_style.get());
224
        break;
mjs's avatar
mjs committed
225 226 227 228 229 230 231 232
    }
}

EditAction ApplyStyleCommand::editingAction() const
{
    return m_editingAction;
}

233
void ApplyStyleCommand::applyBlockStyle(EditingStyle *style)
mjs's avatar
mjs committed
234 235 236 237
{
    // update document layout once before removing styles
    // so that we avoid the expense of updating before each and every call
    // to check a computed style
darin's avatar
darin committed
238
    updateLayout();
mjs's avatar
mjs committed
239 240

    // get positions we want to use for applying style
harrison's avatar
harrison committed
241 242
    Position start = startPosition();
    Position end = endPosition();
243
    if (comparePositions(end, start) < 0) {
harrison's avatar
harrison committed
244 245 246 247
        Position swap = start;
        start = end;
        end = swap;
    }
248

justing's avatar
justing committed
249 250
    VisiblePosition visibleStart(start);
    VisiblePosition visibleEnd(end);
251 252 253

    if (visibleStart.isNull() || visibleStart.isOrphan() || visibleEnd.isNull() || visibleEnd.isOrphan())
        return;
254

justing's avatar
justing committed
255 256
    // Save and restore the selection endpoints using their indices in the document, since
    // addBlockStyleIfNeeded may moveParagraphs, which can remove these endpoints.
justing's avatar
justing committed
257
    // Calculate start and end indices from the start of the tree that they're in.
258
    Node* scope = highestAncestor(visibleStart.deepEquivalent().deprecatedNode());
259 260
    RefPtr<Range> startRange = Range::create(document(), firstPositionInNode(scope), visibleStart.deepEquivalent().parentAnchoredEquivalent());
    RefPtr<Range> endRange = Range::create(document(), firstPositionInNode(scope), visibleEnd.deepEquivalent().parentAnchoredEquivalent());
justing's avatar
justing committed
261 262
    int startIndex = TextIterator::rangeLength(startRange.get(), true);
    int endIndex = TextIterator::rangeLength(endRange.get(), true);
263

justing's avatar
justing committed
264 265 266 267
    VisiblePosition paragraphStart(startOfParagraph(visibleStart));
    VisiblePosition nextParagraphStart(endOfParagraph(paragraphStart).next());
    VisiblePosition beyondEnd(endOfParagraph(visibleEnd).next());
    while (paragraphStart.isNotNull() && paragraphStart != beyondEnd) {
268
        StyleChange styleChange(style, paragraphStart.deepEquivalent());
269
        if (styleChange.cssStyle().length() || m_removeOnly) {
270
            RefPtr<Node> block = enclosingBlock(paragraphStart.deepEquivalent().deprecatedNode());
271 272 273 274 275
            if (!m_removeOnly) {
                RefPtr<Node> newBlock = moveParagraphContentsToNewBlockIfNecessary(paragraphStart.deepEquivalent());
                if (newBlock)
                    block = newBlock;
            }
justing's avatar
justing committed
276 277
            ASSERT(block->isHTMLElement());
            if (block->isHTMLElement()) {
278
                removeCSSStyle(style, toHTMLElement(block.get()));
justing's avatar
justing committed
279
                if (!m_removeOnly)
280
                    addBlockStyle(styleChange, toHTMLElement(block.get()));
justing's avatar
justing committed
281
            }
282 283 284

            if (nextParagraphStart.isOrphan())
                nextParagraphStart = endOfParagraph(paragraphStart).next();
justing's avatar
justing committed
285
        }
286

justing's avatar
justing committed
287 288
        paragraphStart = nextParagraphStart;
        nextParagraphStart = endOfParagraph(paragraphStart).next();
mjs's avatar
mjs committed
289
    }
justing's avatar
justing committed
290
    
adele's avatar
adele committed
291 292 293 294
    startRange = TextIterator::rangeFromLocationAndLength(static_cast<Element*>(scope), startIndex, 0, true);
    endRange = TextIterator::rangeFromLocationAndLength(static_cast<Element*>(scope), endIndex, 0, true);
    if (startRange && endRange)
        updateStartEnd(startRange->startPosition(), endRange->startPosition());
mjs's avatar
mjs committed
295 296
}

297
void ApplyStyleCommand::applyRelativeFontStyleChange(EditingStyle* style)
mjs's avatar
mjs committed
298
{
299
    static const float MinimumFontSize = 0.1f;
mjs's avatar
mjs committed
300

301
    if (!style || !style->hasFontSizeDelta())
mjs's avatar
mjs committed
302
        return;
303

harrison's avatar
harrison committed
304 305
    Position start = startPosition();
    Position end = endPosition();
306
    if (comparePositions(end, start) < 0) {
mjs's avatar
mjs committed
307 308 309 310
        Position swap = start;
        start = end;
        end = swap;
    }
311

mjs's avatar
mjs committed
312
    // Join up any adjacent text nodes.
313 314
    if (start.deprecatedNode()->isTextNode()) {
        joinChildTextNodes(start.deprecatedNode()->parentNode(), start, end);
harrison's avatar
harrison committed
315 316
        start = startPosition();
        end = endPosition();
mjs's avatar
mjs committed
317
    }
318 319
    if (end.deprecatedNode()->isTextNode() && start.deprecatedNode()->parentNode() != end.deprecatedNode()->parentNode()) {
        joinChildTextNodes(end.deprecatedNode()->parentNode(), start, end);
harrison's avatar
harrison committed
320 321
        start = startPosition();
        end = endPosition();
mjs's avatar
mjs committed
322 323 324
    }

    // Split the start text nodes if needed to apply style.
325 326
    if (isValidCaretPositionInTextNode(start)) {
        splitTextAtStart(start, end);
harrison's avatar
harrison committed
327 328
        start = startPosition();
        end = endPosition();
mjs's avatar
mjs committed
329
    }
330 331 332

    if (isValidCaretPositionInTextNode(end)) {
        splitTextAtEnd(start, end);
harrison's avatar
harrison committed
333 334
        start = startPosition();
        end = endPosition();
mjs's avatar
mjs committed
335 336
    }

337 338 339 340
    // Calculate loop end point.
    // If the end node is before the start node (can only happen if the end node is
    // an ancestor of the start node), we gather nodes up to the next sibling of the end node
    Node *beyondEnd;
341 342
    if (start.deprecatedNode()->isDescendantOf(end.deprecatedNode()))
        beyondEnd = end.deprecatedNode()->traverseNextSibling();
343
    else
344
        beyondEnd = end.deprecatedNode()->traverseNextNode();
345
    
mjs's avatar
mjs committed
346
    start = start.upstream(); // Move upstream to ensure we do not add redundant spans.
347
    Node* startNode = start.deprecatedNode();
eric@webkit.org's avatar
eric@webkit.org committed
348
    if (startNode->isTextNode() && start.deprecatedEditingOffset() >= caretMaxOffset(startNode)) // Move out of text node if range does not include its characters.
mjs's avatar
mjs committed
349 350 351 352
        startNode = startNode->traverseNextNode();

    // Store away font size before making any changes to the document.
    // This ensures that changes to one node won't effect another.
darin's avatar
darin committed
353 354
    HashMap<Node*, float> startingFontSizes;
    for (Node *node = startNode; node != beyondEnd; node = node->traverseNextNode())
darin's avatar
darin committed
355
        startingFontSizes.set(node, computedFontSize(node));
mjs's avatar
mjs committed
356 357

    // These spans were added by us. If empty after font size changes, they can be removed.
358
    Vector<RefPtr<HTMLElement> > unstyledSpans;
mjs's avatar
mjs committed
359
    
360 361 362
    Node* lastStyledNode = 0;
    for (Node* node = startNode; node != beyondEnd; node = node->traverseNextNode()) {
        RefPtr<HTMLElement> element;
mjs's avatar
mjs committed
363 364 365 366
        if (node->isHTMLElement()) {
            // Only work on fully selected nodes.
            if (!nodeFullySelected(node, start, end))
                continue;
367
            element = toHTMLElement(node);
mjs's avatar
mjs committed
368
        } else if (node->isTextNode() && node->renderer() && node->parentNode() != lastStyledNode) {
mjs's avatar
mjs committed
369 370
            // Last styled node was not parent node of this text node, but we wish to style this
            // text node. To make this possible, add a style span to surround this text node.
darin's avatar
darin committed
371
            RefPtr<HTMLElement> span = createStyleSpanElement(document());
darin's avatar
darin committed
372
            surroundNodeRangeWithElement(node, node, span.get());
373
            element = span.release();
harrison's avatar
harrison committed
374
        }  else {
mjs's avatar
mjs committed
375 376 377 378
            // Only handle HTML elements and text nodes.
            continue;
        }
        lastStyledNode = node;
379 380

        CSSMutableStyleDeclaration* inlineStyleDecl = element->getInlineStyleDecl();
mjs's avatar
mjs committed
381
        float currentFontSize = computedFontSize(node);
382
        float desiredFontSize = max(MinimumFontSize, startingFontSizes.get(node) + style->fontSizeDelta());
383
        RefPtr<CSSValue> value = inlineStyleDecl->getPropertyCSSValue(CSSPropertyFontSize);
darin's avatar
darin committed
384
        if (value) {
385
            inlineStyleDecl->removeProperty(CSSPropertyFontSize, true);
mjs's avatar
mjs committed
386 387 388
            currentFontSize = computedFontSize(node);
        }
        if (currentFontSize != desiredFontSize) {
389
            inlineStyleDecl->setProperty(CSSPropertyFontSize, String::number(desiredFontSize) + "px", false, false);
390
            setNodeAttribute(element.get(), styleAttr, inlineStyleDecl->cssText());
mjs's avatar
mjs committed
391
        }
392
        if (inlineStyleDecl->isEmpty()) {
393
            removeNodeAttribute(element.get(), styleAttr);
eric@webkit.org's avatar
eric@webkit.org committed
394
            // FIXME: should this be isSpanWithoutAttributesOrUnstyleStyleSpan?  Need a test.
395 396
            if (isUnstyledStyleSpan(element.get()))
                unstyledSpans.append(element.release());
mjs's avatar
mjs committed
397 398 399
        }
    }

400 401 402
    size_t size = unstyledSpans.size();
    for (size_t i = 0; i < size; ++i)
        removeNodePreservingChildren(unstyledSpans[i].get());
mjs's avatar
mjs committed
403 404
}

harrison's avatar
harrison committed
405 406 407
static Node* dummySpanAncestorForNode(const Node* node)
{
    while (node && !isStyleSpan(node))
408
        node = node->parentNode();
harrison's avatar
harrison committed
409
    
410
    return node ? node->parentNode() : 0;
harrison's avatar
harrison committed
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
}

void ApplyStyleCommand::cleanupUnstyledAppleStyleSpans(Node* dummySpanAncestor)
{
    if (!dummySpanAncestor)
        return;

    // Dummy spans are created when text node is split, so that style information
    // can be propagated, which can result in more splitting. If a dummy span gets
    // cloned/split, the new node is always a sibling of it. Therefore, we scan
    // all the children of the dummy's parent
    Node* next;
    for (Node* node = dummySpanAncestor->firstChild(); node; node = next) {
        next = node->nextSibling();
        if (isUnstyledStyleSpan(node))
            removeNodePreservingChildren(node);
        node = next;
    }
}

431
HTMLElement* ApplyStyleCommand::splitAncestorsWithUnicodeBidi(Node* node, bool before, WritingDirection allowedDirection)
mitz@apple.com's avatar
mitz@apple.com committed
432 433 434 435 436 437 438 439 440
{
    // We are allowed to leave the highest ancestor with unicode-bidi unsplit if it is unicode-bidi: embed and direction: allowedDirection.
    // In that case, we return the unsplit ancestor. Otherwise, we return 0.
    Node* block = enclosingBlock(node);
    if (!block)
        return 0;

    Node* highestAncestorWithUnicodeBidi = 0;
    Node* nextHighestAncestorWithUnicodeBidi = 0;
441
    int highestAncestorUnicodeBidi = 0;
442
    for (Node* n = node->parentNode(); n != block; n = n->parentNode()) {
443 444 445 446 447
        int unicodeBidi = getIdentifierValue(computedStyle(n).get(), CSSPropertyUnicodeBidi);
        if (unicodeBidi && unicodeBidi != CSSValueNormal) {
            highestAncestorUnicodeBidi = unicodeBidi;
            nextHighestAncestorWithUnicodeBidi = highestAncestorWithUnicodeBidi;
            highestAncestorWithUnicodeBidi = n;
mitz@apple.com's avatar
mitz@apple.com committed
448 449 450 451 452 453 454 455
        }
    }

    if (!highestAncestorWithUnicodeBidi)
        return 0;

    HTMLElement* unsplitAncestor = 0;

456 457 458 459 460 461
    WritingDirection highestAncestorDirection;
    if (allowedDirection != NaturalWritingDirection
        && highestAncestorUnicodeBidi != CSSValueBidiOverride
        && highestAncestorWithUnicodeBidi->isHTMLElement()
        && EditingStyle::create(highestAncestorWithUnicodeBidi, EditingStyle::AllProperties)->textDirection(highestAncestorDirection)
        && highestAncestorDirection == allowedDirection) {
462
        if (!nextHighestAncestorWithUnicodeBidi)
463
            return toHTMLElement(highestAncestorWithUnicodeBidi);
mitz@apple.com's avatar
mitz@apple.com committed
464

465
        unsplitAncestor = toHTMLElement(highestAncestorWithUnicodeBidi);
466
        highestAncestorWithUnicodeBidi = nextHighestAncestorWithUnicodeBidi;
mitz@apple.com's avatar
mitz@apple.com committed
467 468 469 470 471
    }

    // Split every ancestor through highest ancestor with embedding.
    Node* n = node;
    while (true) {
472
        Element* parent = static_cast<Element*>(n->parentNode());
mitz@apple.com's avatar
mitz@apple.com committed
473 474 475 476
        if (before ? n->previousSibling() : n->nextSibling())
            splitElement(parent, before ? n : n->nextSibling());
        if (parent == highestAncestorWithUnicodeBidi)
            break;
477
        n = n->parentNode();
mitz@apple.com's avatar
mitz@apple.com committed
478 479 480 481 482 483 484 485 486 487
    }
    return unsplitAncestor;
}

void ApplyStyleCommand::removeEmbeddingUpToEnclosingBlock(Node* node, Node* unsplitAncestor)
{
    Node* block = enclosingBlock(node);
    if (!block)
        return;

488
    Node* parent = 0;
489 490
    for (Node* n = node->parentNode(); n != block && n != unsplitAncestor; n = parent) {
        parent = n->parentNode();
491
        if (!n->isStyledElement())
mitz@apple.com's avatar
mitz@apple.com committed
492 493 494
            continue;

        StyledElement* element = static_cast<StyledElement*>(n);
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
        int unicodeBidi = getIdentifierValue(computedStyle(element).get(), CSSPropertyUnicodeBidi);
        if (!unicodeBidi || unicodeBidi == CSSValueNormal)
            continue;

        // FIXME: This code should really consider the mapped attribute 'dir', the inline style declaration,
        // and all matching style rules in order to determine how to best set the unicode-bidi property to 'normal'.
        // For now, it assumes that if the 'dir' attribute is present, then removing it will suffice, and
        // otherwise it sets the property in the inline style declaration.
        if (element->hasAttribute(dirAttr)) {
            // FIXME: If this is a BDO element, we should probably just remove it if it has no
            // other attributes, like we (should) do with B and I elements.
            removeNodeAttribute(element, dirAttr);
        } else {
            RefPtr<CSSMutableStyleDeclaration> inlineStyle = element->getInlineStyleDecl()->copy();
            inlineStyle->setProperty(CSSPropertyUnicodeBidi, CSSValueNormal);
            inlineStyle->removeProperty(CSSPropertyDirection);
            setNodeAttribute(element, styleAttr, inlineStyle->cssText());
            // FIXME: should this be isSpanWithoutAttributesOrUnstyleStyleSpan?  Need a test.
            if (isUnstyledStyleSpan(element))
                removeNodePreservingChildren(element);
mitz@apple.com's avatar
mitz@apple.com committed
515 516 517 518
        }
    }
}

519 520
static Node* highestEmbeddingAncestor(Node* startNode, Node* enclosingNode)
{
521
    for (Node* n = startNode; n && n != enclosingNode; n = n->parentNode()) {
522 523 524 525 526 527 528
        if (n->isHTMLElement() && getIdentifierValue(computedStyle(n).get(), CSSPropertyUnicodeBidi) == CSSValueEmbed)
            return n;
    }

    return 0;
}

529
void ApplyStyleCommand::applyInlineStyle(EditingStyle* style)
mjs's avatar
mjs committed
530
{
harrison's avatar
harrison committed
531 532
    Node* startDummySpanAncestor = 0;
    Node* endDummySpanAncestor = 0;
533 534 535

    style->collapseTextDecorationProperties();

justing's avatar
justing committed
536 537 538
    // update document layout once before removing styles
    // so that we avoid the expense of updating before each and every call
    // to check a computed style
darin's avatar
darin committed
539
    updateLayout();
harrison's avatar
harrison committed
540

mjs's avatar
mjs committed
541
    // adjust to the positions we want to use for applying style
harrison's avatar
harrison committed
542 543
    Position start = startPosition();
    Position end = endPosition();
544
    if (comparePositions(end, start) < 0) {
mjs's avatar
mjs committed
545 546 547 548 549 550
        Position swap = start;
        start = end;
        end = swap;
    }

    // split the start node and containing element if the selection starts inside of it
551
    bool splitStart = isValidCaretPositionInTextNode(start);
mjs's avatar
mjs committed
552
    if (splitStart) {
553
        if (shouldSplitTextElement(start.deprecatedNode()->parentElement(), style))
554 555 556
            splitTextElementAtStart(start, end);
        else
            splitTextAtStart(start, end);
harrison's avatar
harrison committed
557 558
        start = startPosition();
        end = endPosition();
559
        startDummySpanAncestor = dummySpanAncestorForNode(start.deprecatedNode());
mjs's avatar
mjs committed
560 561 562
    }

    // split the end node and containing element if the selection ends inside of it
563
    bool splitEnd = isValidCaretPositionInTextNode(end);
justing's avatar
justing committed
564
    if (splitEnd) {
565
        if (shouldSplitTextElement(end.deprecatedNode()->parentElement(), style))
566 567 568
            splitTextElementAtEnd(start, end);
        else
            splitTextAtEnd(start, end);
harrison's avatar
harrison committed
569 570
        start = startPosition();
        end = endPosition();
571
        endDummySpanAncestor = dummySpanAncestorForNode(end.deprecatedNode());
justing's avatar
justing committed
572
    }
mjs's avatar
mjs committed
573

574 575 576 577 578 579
    // Remove style from the selection.
    // Use the upstream position of the start for removing style.
    // This will ensure we remove all traces of the relevant styles from the selection
    // and prevent us from adding redundant ones, as described in:
    // <rdar://problem/3724344> Bolding and unbolding creates extraneous tags
    Position removeStart = start.upstream();
580 581
    WritingDirection textDirection = NaturalWritingDirection;
    bool hasTextDirection = style->textDirection(textDirection);
582 583
    RefPtr<EditingStyle> styleWithoutEmbedding;
    RefPtr<EditingStyle> embeddingStyle;
584
    if (hasTextDirection) {
585
        // Leave alone an ancestor that provides the desired single level embedding, if there is one.
586 587 588 589
        HTMLElement* startUnsplitAncestor = splitAncestorsWithUnicodeBidi(start.deprecatedNode(), true, textDirection);
        HTMLElement* endUnsplitAncestor = splitAncestorsWithUnicodeBidi(end.deprecatedNode(), false, textDirection);
        removeEmbeddingUpToEnclosingBlock(start.deprecatedNode(), startUnsplitAncestor);
        removeEmbeddingUpToEnclosingBlock(end.deprecatedNode(), endUnsplitAncestor);
mitz@apple.com's avatar
mitz@apple.com committed
590 591

        // Avoid removing the dir attribute and the unicode-bidi and direction properties from the unsplit ancestors.
592
        Position embeddingRemoveStart = removeStart;
mitz@apple.com's avatar
mitz@apple.com committed
593
        if (startUnsplitAncestor && nodeFullySelected(startUnsplitAncestor, removeStart, end))
594
            embeddingRemoveStart = positionInParentAfterNode(startUnsplitAncestor);
595 596

        Position embeddingRemoveEnd = end;
mitz@apple.com's avatar
mitz@apple.com committed
597
        if (endUnsplitAncestor && nodeFullySelected(endUnsplitAncestor, removeStart, end))
598
            embeddingRemoveEnd = positionInParentBeforeNode(endUnsplitAncestor).downstream();
mitz@apple.com's avatar
mitz@apple.com committed
599

600 601
        if (embeddingRemoveEnd != removeStart || embeddingRemoveEnd != end) {
            styleWithoutEmbedding = style->copy();
602 603 604
            embeddingStyle = styleWithoutEmbedding->extractAndRemoveTextDirection();

            if (comparePositions(embeddingRemoveStart, embeddingRemoveEnd) <= 0)
605
                removeInlineStyle(embeddingStyle.get(), embeddingRemoveStart, embeddingRemoveEnd);
606 607
        }
    }
mitz@apple.com's avatar
mitz@apple.com committed
608

609
    removeInlineStyle(styleWithoutEmbedding ? styleWithoutEmbedding.get() : style, removeStart, end);
harrison's avatar
harrison committed
610 611
    start = startPosition();
    end = endPosition();
612 613
    if (start.isNull() || start.isOrphan() || end.isNull() || end.isOrphan())
        return;
mjs's avatar
mjs committed
614

615 616 617
    if (splitStart && mergeStartWithPreviousIfIdentical(start, end)) {
        start = startPosition();
        end = endPosition();
mjs's avatar
mjs committed
618 619 620 621
    }

    if (splitEnd) {
        mergeEndWithNextIfIdentical(start, end);
harrison's avatar
harrison committed
622 623
        start = startPosition();
        end = endPosition();
mjs's avatar
mjs committed
624 625 626 627 628
    }

    // update document layout once before running the rest of the function
    // so that we avoid the expense of updating before each and every call
    // to check a computed style
darin's avatar
darin committed
629
    updateLayout();
mitz@apple.com's avatar
mitz@apple.com committed
630

631 632
    RefPtr<EditingStyle> styleToApply = style;
    if (hasTextDirection) {
mitz@apple.com's avatar
mitz@apple.com committed
633
        // Avoid applying the unicode-bidi and direction properties beneath ancestors that already have them.
634 635
        Node* embeddingStartNode = highestEmbeddingAncestor(start.deprecatedNode(), enclosingBlock(start.deprecatedNode()));
        Node* embeddingEndNode = highestEmbeddingAncestor(end.deprecatedNode(), enclosingBlock(end.deprecatedNode()));
mitz@apple.com's avatar
mitz@apple.com committed
636

637 638 639 640
        if (embeddingStartNode || embeddingEndNode) {
            Position embeddingApplyStart = embeddingStartNode ? positionInParentAfterNode(embeddingStartNode) : start;
            Position embeddingApplyEnd = embeddingEndNode ? positionInParentBeforeNode(embeddingEndNode) : end;
            ASSERT(embeddingApplyStart.isNotNull() && embeddingApplyEnd.isNotNull());
mitz@apple.com's avatar
mitz@apple.com committed
641

642 643 644
            if (!embeddingStyle) {
                styleWithoutEmbedding = style->copy();
                embeddingStyle = styleWithoutEmbedding->extractAndRemoveTextDirection();
645
            }
646
            fixRangeAndApplyInlineStyle(embeddingStyle.get(), embeddingApplyStart, embeddingApplyEnd);
647

648
            styleToApply = styleWithoutEmbedding;
mitz@apple.com's avatar
mitz@apple.com committed
649
        }
650
    }
mitz@apple.com's avatar
mitz@apple.com committed
651

652
    fixRangeAndApplyInlineStyle(styleToApply.get(), start, end);
mitz@apple.com's avatar
mitz@apple.com committed
653 654 655 656 657 658 659

    // Remove dummy style spans created by splitting text elements.
    cleanupUnstyledAppleStyleSpans(startDummySpanAncestor);
    if (endDummySpanAncestor != startDummySpanAncestor)
        cleanupUnstyledAppleStyleSpans(endDummySpanAncestor);
}

660
void ApplyStyleCommand::fixRangeAndApplyInlineStyle(EditingStyle* style, const Position& start, const Position& end)
mitz@apple.com's avatar
mitz@apple.com committed
661
{
662
    Node* startNode = start.deprecatedNode();
adele's avatar
adele committed
663

664
    if (start.deprecatedEditingOffset() >= caretMaxOffset(start.deprecatedNode())) {
665
        startNode = startNode->traverseNextNode();
666
        if (!startNode || comparePositions(end, firstPositionInOrBeforeNode(startNode)) < 0)
667
            return;
justing's avatar
justing committed
668
    }
mitz@apple.com's avatar
mitz@apple.com committed
669

670 671 672
    Node* pastEndNode = end.deprecatedNode();
    if (end.deprecatedEditingOffset() >= caretMaxOffset(end.deprecatedNode()))
        pastEndNode = end.deprecatedNode()->traverseNextSibling();
673 674 675

    // FIXME: Callers should perform this operation on a Range that includes the br
    // if they want style applied to the empty line.
676 677
    if (start == end && start.deprecatedNode()->hasTagName(brTag))
        pastEndNode = start.deprecatedNode()->traverseNextNode();
678

679 680 681 682 683
    // Start from the highest fully selected ancestor so that we can modify the fully selected node.
    // e.g. When applying font-size: large on <font color="blue">hello</font>, we need to include the font element in our run
    // to generate <font color="blue" size="4">hello</font> instead of <font color="blue"><font size="4">hello</font></font>
    RefPtr<Range> range = Range::create(startNode->document(), start, end);
    Element* editableRoot = startNode->rootEditableElement();
684 685 686 687
    if (startNode != editableRoot) {
        while (editableRoot && startNode->parentNode() != editableRoot && isNodeVisiblyContainedWithin(startNode->parentNode(), range.get()))
            startNode = startNode->parentNode();
    }
688

689 690 691
    applyInlineStyleToNodeRange(style, startNode, pastEndNode);
}

692 693
static bool containsNonEditableRegion(Node* node)
{
694
    if (!node->rendererIsEditable())
695 696 697 698
        return true;

    Node* sibling = node->traverseNextSibling();
    for (Node* descendent = node->firstChild(); descendent && descendent != sibling; descendent = descendent->traverseNextNode()) {
699
        if (!descendent->rendererIsEditable())
700 701 702 703 704 705
            return true;
    }

    return false;
}

706
void ApplyStyleCommand::applyInlineStyleToNodeRange(EditingStyle* style, Node* node, Node* pastEndNode)
707
{
708 709 710
    if (m_removeOnly)
        return;

711
    for (RefPtr<Node> next; node && node != pastEndNode; node = next.get()) {
712
        next = node->traverseNextNode();
713

714
        if (!node->renderer() || !node->rendererIsEditable())
715 716
            continue;
        
717
        if (!node->rendererIsRichlyEditable() && node->isHTMLElement()) {
718 719 720 721 722 723
            // This is a plaintext-only region. Only proceed if it's fully selected.
            // pastEndNode is the node after the last fully selected node, so if it's inside node then
            // node isn't fully selected.
            if (pastEndNode && pastEndNode->isDescendantOf(node))
                break;
            // Add to this element's inline style and skip over its contents.
724
            HTMLElement* element = toHTMLElement(node);
725
            RefPtr<CSSMutableStyleDeclaration> inlineStyle = element->getInlineStyleDecl()->copy();
726
            inlineStyle->merge(style->style());
727
            setNodeAttribute(element, styleAttr, inlineStyle->cssText());
728
            next = node->traverseNextSibling();
729 730 731 732 733 734 735
            continue;
        }
        
        if (isBlock(node))
            continue;
        
        if (node->childNodeCount()) {
736
            if (node->contains(pastEndNode) || containsNonEditableRegion(node) || !node->parentNode()->rendererIsEditable())
737 738
                continue;
            if (editingIgnoresContent(node)) {
739
                next = node->traverseNextSibling();
740 741
                continue;
            }
742 743
        }

744 745
        RefPtr<Node> runStart = node;
        RefPtr<Node> runEnd = node;
746 747 748
        Node* sibling = node->nextSibling();
        while (sibling && sibling != pastEndNode && !sibling->contains(pastEndNode)
               && (!isBlock(sibling) || sibling->hasTagName(brTag))
749
               && !containsNonEditableRegion(sibling)) {
750 751
            runEnd = sibling;
            sibling = runEnd->nextSibling();
mjs's avatar
mjs committed
752
        }
753
        next = runEnd->traverseNextSibling();
754

755
        if (!removeStyleFromRunBeforeApplyingStyle(style, runStart, runEnd))
756
            continue;
757
        addInlineStyleIfNeeded(style, runStart.get(), runEnd.get(), AddStyledElement);
mjs's avatar
mjs committed
758 759 760
    }
}

761 762 763 764 765 766
bool ApplyStyleCommand::isStyledInlineElementToRemove(Element* element) const
{
    return (m_styledInlineElement && element->hasTagName(m_styledInlineElement->tagQName()))
        || (m_isInlineElementToRemoveFunction && m_isInlineElementToRemoveFunction(element));
}

767
bool ApplyStyleCommand::removeStyleFromRunBeforeApplyingStyle(EditingStyle* style, RefPtr<Node>& runStart, RefPtr<Node>& runEnd)
768
{
769
    ASSERT(runStart && runEnd && runStart->parentNode() == runEnd->parentNode());
770
    RefPtr<Node> pastEndNode = runEnd->traverseNextSibling();
771
    bool needToApplyStyle = false;
772
    for (Node* node = runStart.get(); node && node != pastEndNode.get(); node = node->traverseNextNode()) {
773 774
        if (node->childNodeCount())
            continue;
775
        // We don't consider m_isInlineElementToRemoveFunction here because we never apply style when m_isInlineElementToRemoveFunction is specified
776
        if (!style->styleIsPresentInComputedStyleOfNode(node)
777 778 779 780 781 782 783 784
            || (m_styledInlineElement && !enclosingNodeWithTag(positionBeforeNode(node), m_styledInlineElement->tagQName()))) {
            needToApplyStyle = true;
            break;
        }
    }
    if (!needToApplyStyle)
        return false;

785 786
    RefPtr<Node> next = runStart;
    for (RefPtr<Node> node = next; node && node->inDocument() && node != pastEndNode; node = next) {
787 788 789
        next = node->traverseNextNode();
        if (!node->isHTMLElement())
            continue;
790 791 792 793

        RefPtr<Node> previousSibling = node->previousSibling();
        RefPtr<Node> nextSibling = node->nextSibling();
        RefPtr<ContainerNode> parent = node->parentNode();
794
        removeInlineStyleFromElement(style, toHTMLElement(node.get()), RemoveAlways);
795 796 797 798 799 800 801 802 803 804 805 806
        if (!node->inDocument()) {
            // FIXME: We might need to update the start and the end of current selection here but need a test.
            if (runStart == node)
                runStart = previousSibling ? previousSibling->nextSibling() : parent->firstChild();
            if (runEnd == node)
                runEnd = nextSibling ? nextSibling->previousSibling() : parent->lastChild();
        }
    }

    return true;
}

807
bool ApplyStyleCommand::removeInlineStyleFromElement(EditingStyle* style, PassRefPtr<HTMLElement> element, InlineStyleRemovalMode mode, EditingStyle* extractedStyle)
808 809 810
{
    ASSERT(element);

811
    if (!element->parentNode() || !element->parentNode()->rendererIsEditable())
812 813
        return false;

814
    if (isStyledInlineElementToRemove(element.get())) {
815 816 817
        if (mode == RemoveNone)
            return true;
        ASSERT(extractedStyle);
818
        extractedStyle->mergeInlineStyleOfElement(element.get());
819
        removeNodePreservingChildren(element);
820
        return true;
821 822
    }

823
    bool removed = false;
824
    if (removeImplicitlyStyledElement(style, element.get(), mode, extractedStyle))
825 826 827 828 829 830 831
        removed = true;

    if (!element->inDocument())
        return removed;

    // If the node was converted to a span, the span may still contain relevant
    // styles which must be removed (e.g. <b style='font-weight: bold'>)
832
    if (removeCSSStyle(style, element.get(), mode, extractedStyle))
833 834 835