summaryrefslogtreecommitdiff
path: root/Source/WebCore/editing/ApplyStyleCommand.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'Source/WebCore/editing/ApplyStyleCommand.cpp')
-rw-r--r--Source/WebCore/editing/ApplyStyleCommand.cpp635
1 files changed, 313 insertions, 322 deletions
diff --git a/Source/WebCore/editing/ApplyStyleCommand.cpp b/Source/WebCore/editing/ApplyStyleCommand.cpp
index 9e1bfe92f..efc1f8839 100644
--- a/Source/WebCore/editing/ApplyStyleCommand.cpp
+++ b/Source/WebCore/editing/ApplyStyleCommand.cpp
@@ -10,10 +10,10 @@
* 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
+ * THIS SOFTWARE IS PROVIDED BY APPLE 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
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE 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
@@ -34,8 +34,10 @@
#include "ElementIterator.h"
#include "Frame.h"
#include "HTMLFontElement.h"
+#include "HTMLIFrameElement.h"
#include "HTMLInterchange.h"
#include "HTMLNames.h"
+#include "HTMLSpanElement.h"
#include "NodeList.h"
#include "NodeTraversal.h"
#include "RenderObject.h"
@@ -43,9 +45,11 @@
#include "StyleProperties.h"
#include "StyleResolver.h"
#include "Text.h"
+#include "TextIterator.h"
#include "TextNodeTraversal.h"
#include "VisibleUnits.h"
#include "htmlediting.h"
+#include <wtf/NeverDestroyed.h>
#include <wtf/StdLibExtras.h>
#include <wtf/text/StringBuilder.h>
@@ -55,22 +59,21 @@ using namespace HTMLNames;
static int toIdentifier(PassRefPtr<CSSValue> value)
{
- return (value && value->isPrimitiveValue()) ? static_pointer_cast<CSSPrimitiveValue>(value)->getValueID() : 0;
+ return (value && value->isPrimitiveValue()) ? static_pointer_cast<CSSPrimitiveValue>(value)->valueID() : 0;
}
static String& styleSpanClassString()
{
- DEFINE_STATIC_LOCAL(String, styleSpanClassString, ((AppleStyleSpanClass)));
+ static NeverDestroyed<String> styleSpanClassString(AppleStyleSpanClass);
return styleSpanClassString;
}
-bool isLegacyAppleStyleSpan(const Node *node)
+bool isLegacyAppleStyleSpan(const Node* node)
{
- if (!node || !node->isHTMLElement())
+ if (!is<HTMLSpanElement>(node))
return false;
- const HTMLElement* elem = toHTMLElement(node);
- return elem->hasLocalName(spanAttr) && elem->getAttribute(classAttr) == styleSpanClassString();
+ return downcast<HTMLSpanElement>(*node).attributeWithoutSynchronization(classAttr) == styleSpanClassString();
}
static bool hasNoAttributeOrOnlyStyleAttribute(const StyledElement* element, ShouldStyleAttributeBeEmpty shouldStyleAttributeBeEmpty)
@@ -79,7 +82,7 @@ static bool hasNoAttributeOrOnlyStyleAttribute(const StyledElement* element, Sho
return true;
unsigned matchedAttributes = 0;
- if (element->getAttribute(classAttr) == styleSpanClassString())
+ if (element->attributeWithoutSynchronization(classAttr) == styleSpanClassString())
matchedAttributes++;
if (element->hasAttribute(styleAttr) && (shouldStyleAttributeBeEmpty == AllowNonEmptyStyleAttribute
|| !element->inlineStyle() || element->inlineStyle()->isEmpty()))
@@ -91,87 +94,77 @@ static bool hasNoAttributeOrOnlyStyleAttribute(const StyledElement* element, Sho
bool isStyleSpanOrSpanWithOnlyStyleAttribute(const Element* element)
{
- if (!element || !element->hasTagName(spanTag))
+ if (!is<HTMLSpanElement>(element))
return false;
- return hasNoAttributeOrOnlyStyleAttribute(toHTMLElement(element), AllowNonEmptyStyleAttribute);
+ return hasNoAttributeOrOnlyStyleAttribute(downcast<HTMLSpanElement>(element), AllowNonEmptyStyleAttribute);
}
static inline bool isSpanWithoutAttributesOrUnstyledStyleSpan(const Element* element)
{
- if (!element || !element->isHTMLElement() || !element->hasTagName(spanTag))
+ if (!is<HTMLSpanElement>(element))
return false;
- return hasNoAttributeOrOnlyStyleAttribute(toHTMLElement(element), StyleAttributeShouldBeEmpty);
+ return hasNoAttributeOrOnlyStyleAttribute(downcast<HTMLSpanElement>(element), StyleAttributeShouldBeEmpty);
}
bool isEmptyFontTag(const Element* element, ShouldStyleAttributeBeEmpty shouldStyleAttributeBeEmpty)
{
- if (!element || !element->hasTagName(fontTag))
+ if (!is<HTMLFontElement>(element))
return false;
- return hasNoAttributeOrOnlyStyleAttribute(toHTMLElement(element), shouldStyleAttributeBeEmpty);
+ return hasNoAttributeOrOnlyStyleAttribute(downcast<HTMLFontElement>(element), shouldStyleAttributeBeEmpty);
}
-static PassRefPtr<Element> createFontElement(Document& document)
+static RefPtr<HTMLElement> createFontElement(Document& document)
{
return createHTMLElement(document, fontTag);
}
-PassRefPtr<HTMLElement> createStyleSpanElement(Document& document)
+RefPtr<HTMLElement> createStyleSpanElement(Document& document)
{
return createHTMLElement(document, spanTag);
}
ApplyStyleCommand::ApplyStyleCommand(Document& document, const EditingStyle* style, EditAction editingAction, EPropertyLevel propertyLevel)
- : CompositeEditCommand(document)
+ : CompositeEditCommand(document, editingAction)
, m_style(style->copy())
- , m_editingAction(editingAction)
, m_propertyLevel(propertyLevel)
, m_start(endingSelection().start().downstream())
, m_end(endingSelection().end().upstream())
, m_useEndingSelection(true)
- , m_styledInlineElement(0)
, m_removeOnly(false)
- , m_isInlineElementToRemoveFunction(0)
{
}
ApplyStyleCommand::ApplyStyleCommand(Document& document, const EditingStyle* style, const Position& start, const Position& end, EditAction editingAction, EPropertyLevel propertyLevel)
- : CompositeEditCommand(document)
+ : CompositeEditCommand(document, editingAction)
, m_style(style->copy())
- , m_editingAction(editingAction)
, m_propertyLevel(propertyLevel)
, m_start(start)
, m_end(end)
, m_useEndingSelection(false)
- , m_styledInlineElement(0)
, m_removeOnly(false)
- , m_isInlineElementToRemoveFunction(0)
{
}
ApplyStyleCommand::ApplyStyleCommand(PassRefPtr<Element> element, bool removeOnly, EditAction editingAction)
- : CompositeEditCommand(element->document())
+ : CompositeEditCommand(element->document(), editingAction)
, m_style(EditingStyle::create())
- , m_editingAction(editingAction)
, m_propertyLevel(PropertyDefault)
, m_start(endingSelection().start().downstream())
, m_end(endingSelection().end().upstream())
, m_useEndingSelection(true)
, m_styledInlineElement(element)
, m_removeOnly(removeOnly)
- , m_isInlineElementToRemoveFunction(0)
{
}
ApplyStyleCommand::ApplyStyleCommand(Document& document, const EditingStyle* style, IsInlineElementToRemoveFunction isInlineElementToRemoveFunction, EditAction editingAction)
- : CompositeEditCommand(document)
+ : CompositeEditCommand(document, editingAction)
, m_style(style->copy())
- , 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)
{
@@ -228,11 +221,6 @@ void ApplyStyleCommand::doApply()
}
}
-EditAction ApplyStyleCommand::editingAction() const
-{
- return m_editingAction;
-}
-
void ApplyStyleCommand::applyBlockStyle(EditingStyle *style)
{
// update document layout once before removing styles
@@ -255,18 +243,10 @@ void ApplyStyleCommand::applyBlockStyle(EditingStyle *style)
if (visibleStart.isNull() || visibleStart.isOrphan() || visibleEnd.isNull() || visibleEnd.isOrphan())
return;
-#if !PLATFORM(IOS)
- // Save and restore the selection endpoints using their indices in the document, since
-#else
// Save and restore the selection endpoints using their indices in the editable root, since
-#endif
// addBlockStyleIfNeeded may moveParagraphs, which can remove these endpoints.
// Calculate start and end indices from the start of the tree that they're in.
-#if !PLATFORM(IOS)
- Node* scope = highestAncestor(visibleStart.deepEquivalent().deprecatedNode());
-#else
- Node* scope = highestEditableRoot(visibleStart.deepEquivalent());
-#endif
+ auto* scope = highestEditableRoot(visibleStart.deepEquivalent());
if (!scope)
return;
@@ -282,18 +262,18 @@ void ApplyStyleCommand::applyBlockStyle(EditingStyle *style)
VisiblePosition beyondEnd(endOfParagraph(visibleEnd).next());
while (paragraphStart.isNotNull() && paragraphStart != beyondEnd) {
StyleChange styleChange(style, paragraphStart.deepEquivalent());
- if (styleChange.cssStyle().length() || m_removeOnly) {
+ if (styleChange.cssStyle() || m_removeOnly) {
RefPtr<Node> block = enclosingBlock(paragraphStart.deepEquivalent().deprecatedNode());
if (!m_removeOnly) {
RefPtr<Node> newBlock = moveParagraphContentsToNewBlockIfNecessary(paragraphStart.deepEquivalent());
if (newBlock)
block = newBlock;
}
- ASSERT(!block || block->isHTMLElement());
- if (block && block->isHTMLElement()) {
- removeCSSStyle(style, toHTMLElement(block.get()));
+ ASSERT(!block || is<HTMLElement>(*block));
+ if (is<HTMLElement>(block.get())) {
+ removeCSSStyle(style, downcast<HTMLElement>(block.get()));
if (!m_removeOnly)
- addBlockStyle(styleChange, toHTMLElement(block.get()));
+ addBlockStyle(styleChange, downcast<HTMLElement>(block.get()));
}
if (nextParagraphStart.isOrphan())
@@ -304,8 +284,8 @@ void ApplyStyleCommand::applyBlockStyle(EditingStyle *style)
nextParagraphStart = endOfParagraph(paragraphStart).next();
}
- startRange = TextIterator::rangeFromLocationAndLength(toContainerNode(scope), startIndex, 0, true);
- endRange = TextIterator::rangeFromLocationAndLength(toContainerNode(scope), endIndex, 0, true);
+ startRange = TextIterator::rangeFromLocationAndLength(scope, startIndex, 0, true);
+ endRange = TextIterator::rangeFromLocationAndLength(scope, endIndex, 0, true);
if (startRange && endRange)
updateStartEnd(startRange->startPosition(), endRange->startPosition());
}
@@ -333,7 +313,7 @@ void ApplyStyleCommand::applyRelativeFontStyleChange(EditingStyle* style)
}
// Join up any adjacent text nodes.
- if (start.deprecatedNode()->isTextNode()) {
+ if (is<Text>(*start.deprecatedNode())) {
joinChildTextNodes(start.deprecatedNode()->parentNode(), start, end);
start = startPosition();
end = endPosition();
@@ -342,7 +322,7 @@ void ApplyStyleCommand::applyRelativeFontStyleChange(EditingStyle* style)
if (start.isNull() || end.isNull())
return;
- if (end.deprecatedNode()->isTextNode() && start.deprecatedNode()->parentNode() != end.deprecatedNode()->parentNode()) {
+ if (is<Text>(*end.deprecatedNode()) && start.deprecatedNode()->parentNode() != end.deprecatedNode()->parentNode()) {
joinChildTextNodes(end.deprecatedNode()->parentNode(), start, end);
start = startPosition();
end = endPosition();
@@ -358,49 +338,69 @@ void ApplyStyleCommand::applyRelativeFontStyleChange(EditingStyle* style)
end = endPosition();
}
+ if (start.isNull() || end.isNull())
+ return;
+
if (isValidCaretPositionInTextNode(end)) {
splitTextAtEnd(start, end);
start = startPosition();
end = endPosition();
}
+ if (start.isNull() || end.isNull())
+ return;
+
// 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;
- if (start.deprecatedNode()->isDescendantOf(end.deprecatedNode()))
- beyondEnd = NodeTraversal::nextSkippingChildren(end.deprecatedNode());
+ Node* beyondEnd;
+ ASSERT(start.deprecatedNode());
+ ASSERT(end.deprecatedNode());
+ if (start.deprecatedNode()->isDescendantOf(*end.deprecatedNode()))
+ beyondEnd = NodeTraversal::nextSkippingChildren(*end.deprecatedNode());
else
- beyondEnd = NodeTraversal::next(end.deprecatedNode());
+ beyondEnd = NodeTraversal::next(*end.deprecatedNode());
start = start.upstream(); // Move upstream to ensure we do not add redundant spans.
Node* startNode = start.deprecatedNode();
- if (startNode->isTextNode() && start.deprecatedEditingOffset() >= caretMaxOffset(startNode)) // Move out of text node if range does not include its characters.
- startNode = NodeTraversal::next(startNode);
+
+ // Make sure we're not already at the end or the next NodeTraversal::next() will traverse past it.
+ if (startNode == beyondEnd)
+ return;
+
+ if (is<Text>(*startNode) && start.deprecatedEditingOffset() >= caretMaxOffset(*startNode)) {
+ // Move out of text node if range does not include its characters.
+ startNode = NodeTraversal::next(*startNode);
+ if (!startNode)
+ return;
+ }
// Store away font size before making any changes to the document.
// This ensures that changes to one node won't effect another.
HashMap<Node*, float> startingFontSizes;
- for (Node *node = startNode; node != beyondEnd; node = NodeTraversal::next(node))
+ for (Node* node = startNode; node != beyondEnd; node = NodeTraversal::next(*node)) {
+ ASSERT(node);
startingFontSizes.set(node, computedFontSize(node));
+ }
// These spans were added by us. If empty after font size changes, they can be removed.
Vector<RefPtr<HTMLElement>> unstyledSpans;
- Node* lastStyledNode = 0;
- for (Node* node = startNode; node != beyondEnd; node = NodeTraversal::next(node)) {
+ Node* lastStyledNode = nullptr;
+ for (Node* node = startNode; node != beyondEnd; node = NodeTraversal::next(*node)) {
+ ASSERT(node);
RefPtr<HTMLElement> element;
- if (node->isHTMLElement()) {
+ if (is<HTMLElement>(*node)) {
// Only work on fully selected nodes.
- if (!nodeFullySelected(node, start, end))
+ if (!nodeFullySelected(downcast<HTMLElement>(*node), start, end))
continue;
- element = toHTMLElement(node);
- } else if (node->isTextNode() && node->renderer() && node->parentNode() != lastStyledNode) {
+ element = &downcast<HTMLElement>(*node);
+ } else if (is<Text>(*node) && node->renderer() && node->parentNode() != lastStyledNode) {
// 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.
- RefPtr<HTMLElement> span = createStyleSpanElement(document());
+ auto span = createStyleSpanElement(document());
surroundNodeRangeWithElement(node, node, span.get());
- element = span.release();
+ element = WTFMove(span);
} else {
// Only handle HTML elements and text nodes.
continue;
@@ -416,27 +416,26 @@ void ApplyStyleCommand::applyRelativeFontStyleChange(EditingStyle* style)
currentFontSize = computedFontSize(node);
}
if (currentFontSize != desiredFontSize) {
- inlineStyle->setProperty(CSSPropertyFontSize, cssValuePool().createValue(desiredFontSize, CSSPrimitiveValue::CSS_PX), false);
+ inlineStyle->setProperty(CSSPropertyFontSize, CSSValuePool::singleton().createValue(desiredFontSize, CSSPrimitiveValue::CSS_PX), false);
setNodeAttribute(element.get(), styleAttr, inlineStyle->asText());
}
if (inlineStyle->isEmpty()) {
removeNodeAttribute(element.get(), styleAttr);
if (isSpanWithoutAttributesOrUnstyledStyleSpan(element.get()))
- unstyledSpans.append(element.release());
+ unstyledSpans.append(WTFMove(element));
}
}
- size_t size = unstyledSpans.size();
- for (size_t i = 0; i < size; ++i)
- removeNodePreservingChildren(unstyledSpans[i].get());
+ for (auto& unstyledSpan : unstyledSpans)
+ removeNodePreservingChildren(unstyledSpan.get());
}
static ContainerNode* dummySpanAncestorForNode(const Node* node)
{
- while (node && (!node->isElementNode() || !isStyleSpanOrSpanWithOnlyStyleAttribute(toElement(node))))
+ while (node && (!is<Element>(*node) || !isStyleSpanOrSpanWithOnlyStyleAttribute(downcast<Element>(node))))
node = node->parentNode();
- return node ? node->parentNode() : 0;
+ return node ? node->parentNode() : nullptr;
}
void ApplyStyleCommand::cleanupUnstyledAppleStyleSpans(ContainerNode* dummySpanAncestor)
@@ -454,20 +453,21 @@ void ApplyStyleCommand::cleanupUnstyledAppleStyleSpans(ContainerNode* dummySpanA
if (isSpanWithoutAttributesOrUnstyledStyleSpan(&child))
toRemove.append(&child);
}
- for (unsigned i = 0; i < toRemove.size(); ++i)
- removeNodePreservingChildren(toRemove[i]);
+
+ for (auto& element : toRemove)
+ removeNodePreservingChildren(element);
}
HTMLElement* ApplyStyleCommand::splitAncestorsWithUnicodeBidi(Node* node, bool before, WritingDirection allowedDirection)
{
// 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)
+ Element* block = enclosingBlock(node);
+ if (!block || block == node)
return 0;
- Node* highestAncestorWithUnicodeBidi = 0;
- Node* nextHighestAncestorWithUnicodeBidi = 0;
+ Node* highestAncestorWithUnicodeBidi = nullptr;
+ Node* nextHighestAncestorWithUnicodeBidi = nullptr;
int highestAncestorUnicodeBidi = 0;
for (Node* n = node->parentNode(); n != block; n = n->parentNode()) {
int unicodeBidi = toIdentifier(ComputedStyleExtractor(n).propertyValue(CSSPropertyUnicodeBidi));
@@ -481,25 +481,25 @@ HTMLElement* ApplyStyleCommand::splitAncestorsWithUnicodeBidi(Node* node, bool b
if (!highestAncestorWithUnicodeBidi)
return 0;
- HTMLElement* unsplitAncestor = 0;
+ HTMLElement* unsplitAncestor = nullptr;
WritingDirection highestAncestorDirection;
if (allowedDirection != NaturalWritingDirection
&& highestAncestorUnicodeBidi != CSSValueBidiOverride
- && highestAncestorWithUnicodeBidi->isHTMLElement()
+ && is<HTMLElement>(*highestAncestorWithUnicodeBidi)
&& EditingStyle::create(highestAncestorWithUnicodeBidi, EditingStyle::AllProperties)->textDirection(highestAncestorDirection)
&& highestAncestorDirection == allowedDirection) {
if (!nextHighestAncestorWithUnicodeBidi)
- return toHTMLElement(highestAncestorWithUnicodeBidi);
+ return downcast<HTMLElement>(highestAncestorWithUnicodeBidi);
- unsplitAncestor = toHTMLElement(highestAncestorWithUnicodeBidi);
+ unsplitAncestor = downcast<HTMLElement>(highestAncestorWithUnicodeBidi);
highestAncestorWithUnicodeBidi = nextHighestAncestorWithUnicodeBidi;
}
// Split every ancestor through highest ancestor with embedding.
RefPtr<Node> currentNode = node;
while (currentNode) {
- RefPtr<Element> parent = toElement(currentNode->parentNode());
+ RefPtr<Element> parent = downcast<Element>(currentNode->parentNode());
if (before ? currentNode->previousSibling() : currentNode->nextSibling())
splitElement(parent, before ? currentNode : currentNode->nextSibling());
if (parent == highestAncestorWithUnicodeBidi)
@@ -511,18 +511,18 @@ HTMLElement* ApplyStyleCommand::splitAncestorsWithUnicodeBidi(Node* node, bool b
void ApplyStyleCommand::removeEmbeddingUpToEnclosingBlock(Node* node, Node* unsplitAncestor)
{
- Node* block = enclosingBlock(node);
- if (!block)
+ Element* block = enclosingBlock(node);
+ if (!block || block == node)
return;
- Node* parent = 0;
- for (Node* n = node->parentNode(); n != block && n != unsplitAncestor; n = parent) {
- parent = n->parentNode();
- if (!n->isStyledElement())
+ Node* parent = nullptr;
+ for (Node* ancestor = node->parentNode(); ancestor != block && ancestor != unsplitAncestor; ancestor = parent) {
+ parent = ancestor->parentNode();
+ if (!is<StyledElement>(*ancestor))
continue;
- StyledElement* element = toStyledElement(n);
- int unicodeBidi = toIdentifier(ComputedStyleExtractor(element).propertyValue(CSSPropertyUnicodeBidi));
+ StyledElement& element = downcast<StyledElement>(*ancestor);
+ int unicodeBidi = toIdentifier(ComputedStyleExtractor(&element).propertyValue(CSSPropertyUnicodeBidi));
if (!unicodeBidi || unicodeBidi == CSSValueNormal)
continue;
@@ -530,17 +530,17 @@ void ApplyStyleCommand::removeEmbeddingUpToEnclosingBlock(Node* node, Node* unsp
// 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)) {
+ if (element.hasAttributeWithoutSynchronization(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);
+ removeNodeAttribute(&element, dirAttr);
} else {
- RefPtr<MutableStyleProperties> inlineStyle = copyStyleOrCreateEmpty(element->inlineStyle());
+ RefPtr<MutableStyleProperties> inlineStyle = copyStyleOrCreateEmpty(element.inlineStyle());
inlineStyle->setProperty(CSSPropertyUnicodeBidi, CSSValueNormal);
inlineStyle->removeProperty(CSSPropertyDirection);
- setNodeAttribute(element, styleAttr, inlineStyle->asText());
- if (isSpanWithoutAttributesOrUnstyledStyleSpan(element))
- removeNodePreservingChildren(element);
+ setNodeAttribute(&element, styleAttr, inlineStyle->asText());
+ if (isSpanWithoutAttributesOrUnstyledStyleSpan(&element))
+ removeNodePreservingChildren(&element);
}
}
}
@@ -557,8 +557,8 @@ static Node* highestEmbeddingAncestor(Node* startNode, Node* enclosingNode)
void ApplyStyleCommand::applyInlineStyle(EditingStyle* style)
{
- RefPtr<ContainerNode> startDummySpanAncestor = 0;
- RefPtr<ContainerNode> endDummySpanAncestor = 0;
+ RefPtr<ContainerNode> startDummySpanAncestor;
+ RefPtr<ContainerNode> endDummySpanAncestor;
// update document layout once before removing styles
// so that we avoid the expense of updating before each and every call
@@ -590,6 +590,9 @@ void ApplyStyleCommand::applyInlineStyle(EditingStyle* style)
startDummySpanAncestor = dummySpanAncestorForNode(start.deprecatedNode());
}
+ if (start.isNull() || end.isNull())
+ return;
+
// split the end node and containing element if the selection ends inside of it
bool splitEnd = isValidCaretPositionInTextNode(end);
if (splitEnd) {
@@ -602,6 +605,9 @@ void ApplyStyleCommand::applyInlineStyle(EditingStyle* style)
endDummySpanAncestor = dummySpanAncestorForNode(end.deprecatedNode());
}
+ if (start.isNull() || end.isNull())
+ return;
+
// 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
@@ -621,11 +627,11 @@ void ApplyStyleCommand::applyInlineStyle(EditingStyle* style)
// Avoid removing the dir attribute and the unicode-bidi and direction properties from the unsplit ancestors.
Position embeddingRemoveStart = removeStart;
- if (startUnsplitAncestor && nodeFullySelected(startUnsplitAncestor, removeStart, end))
+ if (startUnsplitAncestor && nodeFullySelected(*startUnsplitAncestor, removeStart, end))
embeddingRemoveStart = positionInParentAfterNode(startUnsplitAncestor);
Position embeddingRemoveEnd = end;
- if (endUnsplitAncestor && nodeFullySelected(endUnsplitAncestor, removeStart, end))
+ if (endUnsplitAncestor && nodeFullySelected(*endUnsplitAncestor, removeStart, end))
embeddingRemoveEnd = positionInParentBeforeNode(endUnsplitAncestor).downstream();
if (embeddingRemoveEnd != removeStart || embeddingRemoveEnd != end) {
@@ -654,6 +660,9 @@ void ApplyStyleCommand::applyInlineStyle(EditingStyle* style)
end = endPosition();
}
+ if (start.isNull() || end.isNull())
+ return;
+
// 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
@@ -692,42 +701,43 @@ void ApplyStyleCommand::fixRangeAndApplyInlineStyle(EditingStyle* style, const P
{
Node* startNode = start.deprecatedNode();
- if (start.deprecatedEditingOffset() >= caretMaxOffset(start.deprecatedNode())) {
- startNode = NodeTraversal::next(startNode);
+ if (start.deprecatedEditingOffset() >= caretMaxOffset(*startNode)) {
+ startNode = NodeTraversal::next(*startNode);
if (!startNode || comparePositions(end, firstPositionInOrBeforeNode(startNode)) < 0)
return;
}
Node* pastEndNode = end.deprecatedNode();
- if (end.deprecatedEditingOffset() >= caretMaxOffset(end.deprecatedNode()))
- pastEndNode = NodeTraversal::nextSkippingChildren(end.deprecatedNode());
+ if (end.deprecatedEditingOffset() >= caretMaxOffset(*pastEndNode))
+ pastEndNode = NodeTraversal::nextSkippingChildren(*pastEndNode);
// FIXME: Callers should perform this operation on a Range that includes the br
// if they want style applied to the empty line.
+ // FIXME: Should this be using startNode instead of start.deprecatedNode()?
if (start == end && start.deprecatedNode()->hasTagName(brTag))
- pastEndNode = NodeTraversal::next(start.deprecatedNode());
+ pastEndNode = NodeTraversal::next(*start.deprecatedNode());
// 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();
+ auto range = Range::create(startNode->document(), start, end);
+ auto* editableRoot = startNode->rootEditableElement();
if (startNode != editableRoot) {
- while (editableRoot && startNode->parentNode() != editableRoot && isNodeVisiblyContainedWithin(startNode->parentNode(), range.get()))
+ while (editableRoot && startNode->parentNode() != editableRoot && isNodeVisiblyContainedWithin(*startNode->parentNode(), range))
startNode = startNode->parentNode();
}
applyInlineStyleToNodeRange(style, startNode, pastEndNode);
}
-static bool containsNonEditableRegion(Node* node)
+static bool containsNonEditableRegion(Node& node)
{
- if (!node->hasEditableStyle())
+ if (!node.hasEditableStyle())
return true;
Node* sibling = NodeTraversal::nextSkippingChildren(node);
- for (Node* descendent = node->firstChild(); descendent && descendent != sibling; descendent = NodeTraversal::next(descendent)) {
- if (!descendent->hasEditableStyle())
+ for (Node* descendant = node.firstChild(); descendant && descendant != sibling; descendant = NodeTraversal::next(*descendant)) {
+ if (!descendant->hasEditableStyle())
return true;
}
@@ -745,7 +755,7 @@ struct InlineRunToApplyStyle {
bool startAndEndAreStillInDocument()
{
- return start && end && start->inDocument() && end->inDocument();
+ return start && end && start->isConnected() && end->isConnected();
}
RefPtr<Node> start;
@@ -766,35 +776,35 @@ void ApplyStyleCommand::applyInlineStyleToNodeRange(EditingStyle* style, PassRef
Vector<InlineRunToApplyStyle> runs;
RefPtr<Node> node = startNode;
for (RefPtr<Node> next; node && node != pastEndNode; node = next) {
- next = NodeTraversal::next(node.get());
+ next = NodeTraversal::next(*node);
if (!node->renderer() || !node->hasEditableStyle())
continue;
- if (!node->hasRichlyEditableStyle() && node->isHTMLElement()) {
+ if (!node->hasRichlyEditableStyle() && is<HTMLElement>(*node)) {
// 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.get()))
+ if (pastEndNode && pastEndNode->isDescendantOf(*node))
break;
// Add to this element's inline style and skip over its contents.
- HTMLElement* element = toHTMLElement(node.get());
- RefPtr<MutableStyleProperties> inlineStyle = copyStyleOrCreateEmpty(element->inlineStyle());
+ HTMLElement& element = downcast<HTMLElement>(*node);
+ RefPtr<MutableStyleProperties> inlineStyle = copyStyleOrCreateEmpty(element.inlineStyle());
if (MutableStyleProperties* otherStyle = style->style())
inlineStyle->mergeAndOverrideOnConflict(*otherStyle);
- setNodeAttribute(element, styleAttr, inlineStyle->asText());
- next = NodeTraversal::nextSkippingChildren(node.get());
+ setNodeAttribute(&element, styleAttr, inlineStyle->asText());
+ next = NodeTraversal::nextSkippingChildren(*node);
continue;
}
if (isBlock(node.get()))
continue;
- if (node->childNodeCount()) {
- if (node->contains(pastEndNode.get()) || containsNonEditableRegion(node.get()) || !node->parentNode()->hasEditableStyle())
+ if (node->hasChildNodes()) {
+ if (node->contains(pastEndNode.get()) || containsNonEditableRegion(*node) || !node->parentNode()->hasEditableStyle())
continue;
- if (editingIgnoresContent(node.get())) {
- next = NodeTraversal::nextSkippingChildren(node.get());
+ if (editingIgnoresContent(*node)) {
+ next = NodeTraversal::nextSkippingChildren(*node);
continue;
}
}
@@ -802,37 +812,35 @@ void ApplyStyleCommand::applyInlineStyleToNodeRange(EditingStyle* style, PassRef
Node* runStart = node.get();
Node* runEnd = node.get();
Node* sibling = node->nextSibling();
- while (sibling && sibling != pastEndNode && !sibling->contains(pastEndNode.get())
- && (!isBlock(sibling) || sibling->hasTagName(brTag))
- && !containsNonEditableRegion(sibling)) {
+ while (sibling && sibling != pastEndNode && !sibling->contains(pastEndNode.get()) && (!isBlock(sibling) || sibling->hasTagName(brTag)) && !containsNonEditableRegion(*sibling)) {
runEnd = sibling;
sibling = runEnd->nextSibling();
}
- next = NodeTraversal::nextSkippingChildren(runEnd);
+ next = NodeTraversal::nextSkippingChildren(*runEnd);
- Node* pastEndNode = NodeTraversal::nextSkippingChildren(runEnd);
+ Node* pastEndNode = NodeTraversal::nextSkippingChildren(*runEnd);
if (!shouldApplyInlineStyleToRun(style, runStart, pastEndNode))
continue;
runs.append(InlineRunToApplyStyle(runStart, runEnd, pastEndNode));
}
- for (size_t i = 0; i < runs.size(); i++) {
- removeConflictingInlineStyleFromRun(style, runs[i].start, runs[i].end, runs[i].pastEndNode);
- runs[i].positionForStyleComputation = positionToComputeInlineStyleChange(runs[i].start, runs[i].dummyElement);
+ for (auto& run : runs) {
+ removeConflictingInlineStyleFromRun(style, run.start, run.end, run.pastEndNode);
+ if (run.startAndEndAreStillInDocument())
+ run.positionForStyleComputation = positionToComputeInlineStyleChange(run.start, run.dummyElement);
}
document().updateLayoutIgnorePendingStylesheets();
- for (size_t i = 0; i < runs.size(); i++)
- runs[i].change = StyleChange(style, runs[i].positionForStyleComputation);
+ for (auto& run : runs)
+ run.change = StyleChange(style, run.positionForStyleComputation);
- for (size_t i = 0; i < runs.size(); i++) {
- InlineRunToApplyStyle& run = runs[i];
+ for (auto& run : runs) {
if (run.dummyElement)
removeNode(run.dummyElement);
if (run.startAndEndAreStillInDocument())
- applyInlineStyleChange(run.start.release(), run.end.release(), run.change, AddStyledElement);
+ applyInlineStyleChange(WTFMove(run.start), WTFMove(run.end), run.change, AddStyledElement);
}
}
@@ -846,13 +854,13 @@ bool ApplyStyleCommand::shouldApplyInlineStyleToRun(EditingStyle* style, Node* r
{
ASSERT(style && runStart);
- for (Node* node = runStart; node && node != pastEndNode; node = NodeTraversal::next(node)) {
- if (node->childNodeCount())
+ for (Node* node = runStart; node && node != pastEndNode; node = NodeTraversal::next(*node)) {
+ if (node->hasChildNodes())
continue;
// We don't consider m_isInlineElementToRemoveFunction here because we never apply style when m_isInlineElementToRemoveFunction is specified
if (!style->styleIsPresentInComputedStyleOfNode(node))
return true;
- if (m_styledInlineElement && !enclosingNodeWithTag(positionBeforeNode(node), m_styledInlineElement->tagQName()))
+ if (m_styledInlineElement && !enclosingElementWithTag(positionBeforeNode(node), m_styledInlineElement->tagQName()))
return true;
}
return false;
@@ -862,20 +870,21 @@ void ApplyStyleCommand::removeConflictingInlineStyleFromRun(EditingStyle* style,
{
ASSERT(runStart && runEnd);
RefPtr<Node> next = runStart;
- for (RefPtr<Node> node = next; node && node->inDocument() && node != pastEndNode; node = next) {
- if (editingIgnoresContent(node.get())) {
+ for (RefPtr<Node> node = next; node && node->isConnected() && node != pastEndNode; node = next) {
+ if (editingIgnoresContent(*node)) {
ASSERT(!node->contains(pastEndNode.get()));
- next = NodeTraversal::nextSkippingChildren(node.get());
+ next = NodeTraversal::nextSkippingChildren(*node);
} else
- next = NodeTraversal::next(node.get());
- if (!node->isHTMLElement())
+ next = NodeTraversal::next(*node);
+
+ if (!is<HTMLElement>(*node))
continue;
RefPtr<Node> previousSibling = node->previousSibling();
RefPtr<Node> nextSibling = node->nextSibling();
RefPtr<ContainerNode> parent = node->parentNode();
- removeInlineStyleFromElement(style, toHTMLElement(node.get()), RemoveAlways);
- if (!node->inDocument()) {
+ removeInlineStyleFromElement(style, downcast<HTMLElement>(node.get()), RemoveAlways);
+ if (!node->isConnected()) {
// 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();
@@ -889,7 +898,7 @@ bool ApplyStyleCommand::removeInlineStyleFromElement(EditingStyle* style, PassRe
{
ASSERT(element);
- if (!element->parentNode() || !element->parentNode()->isContentEditable(Node::UserSelectAllIsAlwaysNonEditable))
+ if (!element->parentNode() || !isEditableNode(*element->parentNode()))
return false;
if (isStyledInlineElementToRemove(element.get())) {
@@ -905,7 +914,7 @@ bool ApplyStyleCommand::removeInlineStyleFromElement(EditingStyle* style, PassRe
if (removeImplicitlyStyledElement(style, element.get(), mode, extractedStyle))
removed = true;
- if (!element->inDocument())
+ if (!element->isConnected())
return removed;
// If the node was converted to a span, the span may still contain relevant
@@ -922,7 +931,7 @@ void ApplyStyleCommand::replaceWithSpanOrRemoveIfWithoutAttributes(HTMLElement*&
removeNodePreservingChildren(elem);
else {
HTMLElement* newSpanElement = replaceElementWithSpanPreservingChildrenAndAttributes(elem);
- ASSERT(newSpanElement && newSpanElement->inDocument());
+ ASSERT(newSpanElement && newSpanElement->isConnected());
elem = newSpanElement;
}
}
@@ -947,8 +956,8 @@ bool ApplyStyleCommand::removeImplicitlyStyledElement(EditingStyle* style, HTMLE
extractedStyle, attributes, mode == RemoveAlways ? EditingStyle::ExtractMatchingStyle : EditingStyle::DoNotExtractMatchingStyle))
return false;
- for (size_t i = 0; i < attributes.size(); i++)
- removeNodeAttribute(element, attributes[i]);
+ for (auto& attribute : attributes)
+ removeNodeAttribute(element, attribute);
if (isEmptyFontTag(element) || isSpanWithoutAttributesOrUnstyledStyleSpan(element))
removeNodePreservingChildren(element);
@@ -964,17 +973,14 @@ bool ApplyStyleCommand::removeCSSStyle(EditingStyle* style, HTMLElement* element
if (mode == RemoveNone)
return style->conflictsWithInlineStyleOfElement(element);
- Vector<CSSPropertyID> properties;
- if (!style->conflictsWithInlineStyleOfElement(element, extractedStyle, properties))
+ RefPtr<MutableStyleProperties> newInlineStyle;
+ if (!style->conflictsWithInlineStyleOfElement(element, newInlineStyle, extractedStyle))
return false;
- // FIXME: We should use a mass-removal function here but we don't have an undoable one yet.
- for (size_t i = 0; i < properties.size(); i++)
- removeCSSProperty(element, properties[i]);
-
- // No need to serialize <foo style=""> if we just removed the last css property
- if (element->inlineStyle()->isEmpty())
+ if (newInlineStyle->isEmpty())
removeNodeAttribute(element, styleAttr);
+ else
+ setNodeAttribute(element, styleAttr, newInlineStyle->asText());
if (isSpanWithoutAttributesOrUnstyledStyleSpan(element))
removeNodePreservingChildren(element);
@@ -985,17 +991,17 @@ bool ApplyStyleCommand::removeCSSStyle(EditingStyle* style, HTMLElement* element
HTMLElement* ApplyStyleCommand::highestAncestorWithConflictingInlineStyle(EditingStyle* style, Node* node)
{
if (!node)
- return 0;
+ return nullptr;
- HTMLElement* result = 0;
+ HTMLElement* result = nullptr;
Node* unsplittableElement = unsplittableElementForPosition(firstPositionInOrBeforeNode(node));
- for (Node *n = node; n; n = n->parentNode()) {
- if (n->isHTMLElement() && shouldRemoveInlineStyleFromElement(style, toHTMLElement(n)))
- result = toHTMLElement(n);
+ for (Node* ancestor = node; ancestor; ancestor = ancestor->parentNode()) {
+ if (is<HTMLElement>(*ancestor) && shouldRemoveInlineStyleFromElement(style, downcast<HTMLElement>(ancestor)))
+ result = downcast<HTMLElement>(ancestor);
// Should stop at the editable root (cannot cross editing boundary) and
// also stop at the unsplittable element to be consistent with other UAs
- if (n == unsplittableElement)
+ if (ancestor == unsplittableElement)
break;
}
@@ -1008,19 +1014,19 @@ void ApplyStyleCommand::applyInlineStyleToPushDown(Node* node, EditingStyle* sty
node->document().updateStyleIfNeeded();
- if (!style || style->isEmpty() || !node->renderer() || node->hasTagName(iframeTag))
+ if (!style || style->isEmpty() || !node->renderer() || is<HTMLIFrameElement>(*node))
return;
RefPtr<EditingStyle> newInlineStyle = style;
- if (node->isHTMLElement() && toHTMLElement(node)->inlineStyle()) {
+ if (is<HTMLElement>(*node) && downcast<HTMLElement>(node)->inlineStyle()) {
newInlineStyle = style->copy();
- newInlineStyle->mergeInlineStyleOfElement(toHTMLElement(node), EditingStyle::OverrideValues);
+ newInlineStyle->mergeInlineStyleOfElement(downcast<HTMLElement>(node), EditingStyle::OverrideValues);
}
// Since addInlineStyleIfNeeded can't add styles to block-flow render objects, add style attribute instead.
// FIXME: applyInlineStyleToRange should be used here instead.
- if ((node->renderer()->isRenderBlockFlow() || node->childNodeCount()) && node->isHTMLElement()) {
- setNodeAttribute(toHTMLElement(node), styleAttr, newInlineStyle->style()->asText());
+ if ((node->renderer()->isRenderBlockFlow() || node->hasChildNodes()) && is<HTMLElement>(*node)) {
+ setNodeAttribute(downcast<HTMLElement>(node), styleAttr, newInlineStyle->style()->asText());
return;
}
@@ -1051,31 +1057,31 @@ void ApplyStyleCommand::pushDownInlineStyleAroundNode(EditingStyle* style, Node*
getChildNodes(*current.get(), currentChildren);
RefPtr<StyledElement> styledElement;
- if (current->isStyledElement() && isStyledInlineElementToRemove(toElement(current.get()))) {
- styledElement = toStyledElement(current.get());
+ if (is<StyledElement>(*current) && isStyledInlineElementToRemove(downcast<Element>(current.get()))) {
+ styledElement = downcast<StyledElement>(current.get());
elementsToPushDown.append(*styledElement);
}
RefPtr<EditingStyle> styleToPushDown = EditingStyle::create();
- if (current->isHTMLElement())
- removeInlineStyleFromElement(style, toHTMLElement(current.get()), RemoveIfNeeded, styleToPushDown.get());
+ if (is<HTMLElement>(*current))
+ removeInlineStyleFromElement(style, downcast<HTMLElement>(current.get()), RemoveIfNeeded, styleToPushDown.get());
// The inner loop will go through children on each level
// FIXME: we should aggregate inline child elements together so that we don't wrap each child separately.
- for (size_t i = 0; i < currentChildren.size(); ++i) {
- Node& child = currentChildren[i].get();
+ for (Ref<Node>& childRef : currentChildren) {
+ Node& child = childRef;
if (!child.parentNode())
continue;
if (!child.contains(targetNode) && elementsToPushDown.size()) {
- for (size_t i = 0; i < elementsToPushDown.size(); i++) {
- RefPtr<Element> wrapper = elementsToPushDown[i]->cloneElementWithoutChildren();
+ for (auto& element : elementsToPushDown) {
+ RefPtr<Element> wrapper = element->cloneElementWithoutChildren(document());
wrapper->removeAttribute(styleAttr);
surroundNodeRangeWithElement(&child, &child, wrapper);
}
}
// Apply style to all nodes containing targetNode and their siblings but NOT to targetNode
- // But if we've removed styledElement then go ahead and always apply the style.
+ // But if we've removed styledElement then always apply the style.
if (&child != targetNode || styledElement)
applyInlineStyleToPushDown(&child, styleToPushDown.get());
@@ -1087,12 +1093,12 @@ void ApplyStyleCommand::pushDownInlineStyleAroundNode(EditingStyle* style, Node*
}
}
-void ApplyStyleCommand::removeInlineStyle(EditingStyle* style, const Position &start, const Position &end)
+void ApplyStyleCommand::removeInlineStyle(EditingStyle* style, const Position& start, const Position& end)
{
ASSERT(start.isNotNull());
ASSERT(end.isNotNull());
- ASSERT(start.anchorNode()->inDocument());
- ASSERT(end.anchorNode()->inDocument());
+ ASSERT(start.anchorNode()->isConnected());
+ ASSERT(end.anchorNode()->isConnected());
ASSERT(comparePositions(start, end) <= 0);
// FIXME: We should assert that start/end are not in the middle of a text node.
@@ -1100,15 +1106,14 @@ void ApplyStyleCommand::removeInlineStyle(EditingStyle* style, const Position &s
// If the pushDownStart is at the end of a text node, then this node is not fully selected.
// Move it to the next deep quivalent position to avoid removing the style from this node.
// e.g. if pushDownStart was at Position("hello", 5) in <b>hello<div>world</div></b>, we want Position("world", 0) instead.
- Node* pushDownStartContainer = pushDownStart.containerNode();
- if (pushDownStartContainer && pushDownStartContainer->isTextNode()
- && pushDownStart.computeOffsetInContainerNode() == pushDownStartContainer->maxCharacterOffset())
+ auto* pushDownStartContainer = pushDownStart.containerNode();
+ if (is<Text>(pushDownStartContainer) && pushDownStart.computeOffsetInContainerNode() == pushDownStartContainer->maxCharacterOffset())
pushDownStart = nextVisuallyDistinctCandidate(pushDownStart);
// If pushDownEnd is at the start of a text node, then this node is not fully selected.
// Move it to the previous deep equivalent position to avoid removing the style from this node.
Position pushDownEnd = end.upstream();
- Node* pushDownEndContainer = pushDownEnd.containerNode();
- if (pushDownEndContainer && pushDownEndContainer->isTextNode() && !pushDownEnd.computeOffsetInContainerNode())
+ auto* pushDownEndContainer = pushDownEnd.containerNode();
+ if (is<Text>(pushDownEndContainer) && !pushDownEnd.computeOffsetInContainerNode())
pushDownEnd = previousVisuallyDistinctCandidate(pushDownEnd);
pushDownInlineStyleAroundNode(style, pushDownStart.deprecatedNode());
@@ -1125,32 +1130,32 @@ void ApplyStyleCommand::removeInlineStyle(EditingStyle* style, const Position &s
RefPtr<Node> node = start.deprecatedNode();
while (node) {
RefPtr<Node> next;
- if (editingIgnoresContent(node.get())) {
+ if (editingIgnoresContent(*node)) {
ASSERT(node == end.deprecatedNode() || !node->contains(end.deprecatedNode()));
- next = NodeTraversal::nextSkippingChildren(node.get());
+ next = NodeTraversal::nextSkippingChildren(*node);
} else
- next = NodeTraversal::next(node.get());
+ next = NodeTraversal::next(*node);
- if (node->isHTMLElement() && nodeFullySelected(node.get(), start, end)) {
- RefPtr<HTMLElement> elem = toHTMLElement(node.get());
- RefPtr<Node> prev = NodeTraversal::previousPostOrder(elem.get());
- RefPtr<Node> next = NodeTraversal::next(elem.get());
+ if (is<HTMLElement>(*node) && nodeFullySelected(downcast<HTMLElement>(*node), start, end)) {
+ Ref<HTMLElement> element = downcast<HTMLElement>(*node);
+ RefPtr<Node> prev = NodeTraversal::previousPostOrder(element);
+ RefPtr<Node> next = NodeTraversal::next(element);
RefPtr<EditingStyle> styleToPushDown;
RefPtr<Node> childNode;
- if (isStyledInlineElementToRemove(elem.get())) {
+ if (isStyledInlineElementToRemove(element.ptr())) {
styleToPushDown = EditingStyle::create();
- childNode = elem->firstChild();
+ childNode = element->firstChild();
}
- removeInlineStyleFromElement(style, elem.get(), RemoveIfNeeded, styleToPushDown.get());
- if (!elem->inDocument()) {
- if (s.deprecatedNode() == elem) {
+ removeInlineStyleFromElement(style, element.ptr(), RemoveIfNeeded, styleToPushDown.get());
+ if (!element->isConnected()) {
+ if (s.deprecatedNode() == element.ptr()) {
// Since elem must have been fully selected, and it is at the start
// of the selection, it is clear we can set the new s offset to 0.
ASSERT(s.anchorType() == Position::PositionIsBeforeAnchor || s.offsetInContainerNode() <= 0);
s = firstPositionInOrBeforeNode(next.get());
}
- if (e.deprecatedNode() == elem) {
+ if (e.deprecatedNode() == element.ptr()) {
// Since elem must have been fully selected, and it is at the end
// of the selection, it is clear we can set the new e offset to
// the max range offset of prev.
@@ -1172,32 +1177,27 @@ void ApplyStyleCommand::removeInlineStyle(EditingStyle* style, const Position &s
updateStartEnd(s, e);
}
-bool ApplyStyleCommand::nodeFullySelected(Node *node, const Position &start, const Position &end) const
+bool ApplyStyleCommand::nodeFullySelected(Element& element, const Position& start, const Position& end) const
{
- ASSERT(node);
- ASSERT(node->isElementNode());
-
// The tree may have changed and Position::upstream() relies on an up-to-date layout.
- node->document().updateLayoutIgnorePendingStylesheets();
+ element.document().updateLayoutIgnorePendingStylesheets();
- return comparePositions(firstPositionInOrBeforeNode(node), start) >= 0
- && comparePositions(lastPositionInOrAfterNode(node).upstream(), end) <= 0;
+ return comparePositions(firstPositionInOrBeforeNode(&element), start) >= 0
+ && comparePositions(lastPositionInOrAfterNode(&element).upstream(), end) <= 0;
}
-bool ApplyStyleCommand::nodeFullyUnselected(Node *node, const Position &start, const Position &end) const
+bool ApplyStyleCommand::nodeFullyUnselected(Element& element, const Position& start, const Position& end) const
{
- ASSERT(node);
- ASSERT(node->isElementNode());
-
- bool isFullyBeforeStart = comparePositions(lastPositionInOrAfterNode(node).upstream(), start) < 0;
- bool isFullyAfterEnd = comparePositions(firstPositionInOrBeforeNode(node), end) > 0;
+ // The tree may have changed and Position::upstream() relies on an up-to-date layout.
+ element.document().updateLayoutIgnorePendingStylesheets();
- return isFullyBeforeStart || isFullyAfterEnd;
+ return comparePositions(lastPositionInOrAfterNode(&element).upstream(), start) < 0
+ || comparePositions(firstPositionInOrBeforeNode(&element), end) > 0;
}
void ApplyStyleCommand::splitTextAtStart(const Position& start, const Position& end)
{
- ASSERT(start.containerNode()->isTextNode());
+ ASSERT(is<Text>(start.containerNode()));
Position newEnd;
if (end.anchorType() == Position::PositionIsOffsetInAnchor && start.containerNode() == end.containerNode())
@@ -1212,23 +1212,23 @@ void ApplyStyleCommand::splitTextAtStart(const Position& start, const Position&
void ApplyStyleCommand::splitTextAtEnd(const Position& start, const Position& end)
{
- ASSERT(end.containerNode()->isTextNode());
+ ASSERT(is<Text>(end.containerNode()));
bool shouldUpdateStart = start.anchorType() == Position::PositionIsOffsetInAnchor && start.containerNode() == end.containerNode();
- Text* text = toText(end.deprecatedNode());
- splitTextNode(text, end.offsetInContainerNode());
+ Text& text = downcast<Text>(*end.deprecatedNode());
+ splitTextNode(&text, end.offsetInContainerNode());
- Node* prevNode = text->previousSibling();
- if (!prevNode || !prevNode->isTextNode())
+ Node* prevNode = text.previousSibling();
+ if (!is<Text>(prevNode))
return;
- Position newStart = shouldUpdateStart ? Position(toText(prevNode), start.offsetInContainerNode()) : start;
+ Position newStart = shouldUpdateStart ? Position(downcast<Text>(prevNode), start.offsetInContainerNode()) : start;
updateStartEnd(newStart, lastPositionInNode(prevNode));
}
void ApplyStyleCommand::splitTextElementAtStart(const Position& start, const Position& end)
{
- ASSERT(start.containerNode()->isTextNode());
+ ASSERT(is<Text>(start.containerNode()));
Position newEnd;
if (start.containerNode() == end.containerNode())
@@ -1242,7 +1242,7 @@ void ApplyStyleCommand::splitTextElementAtStart(const Position& start, const Pos
void ApplyStyleCommand::splitTextElementAtEnd(const Position& start, const Position& end)
{
- ASSERT(end.containerNode()->isTextNode());
+ ASSERT(is<Text>(end.containerNode()));
bool shouldUpdateStart = start.containerNode() == end.containerNode();
splitTextNodeContainingElement(end.containerText(), end.offsetInContainerNode());
@@ -1251,33 +1251,33 @@ void ApplyStyleCommand::splitTextElementAtEnd(const Position& start, const Posit
if (!parentElement || !parentElement->previousSibling())
return;
Node* firstTextNode = parentElement->previousSibling()->lastChild();
- if (!firstTextNode || !firstTextNode->isTextNode())
+ if (!is<Text>(firstTextNode))
return;
- Position newStart = shouldUpdateStart ? Position(toText(firstTextNode), start.offsetInContainerNode()) : start;
+ Position newStart = shouldUpdateStart ? Position(downcast<Text>(firstTextNode), start.offsetInContainerNode()) : start;
updateStartEnd(newStart, positionAfterNode(firstTextNode));
}
bool ApplyStyleCommand::shouldSplitTextElement(Element* element, EditingStyle* style)
{
- if (!element || !element->isHTMLElement())
+ if (!is<HTMLElement>(element))
return false;
- return shouldRemoveInlineStyleFromElement(style, toHTMLElement(element));
+ return shouldRemoveInlineStyleFromElement(style, &downcast<HTMLElement>(*element));
}
bool ApplyStyleCommand::isValidCaretPositionInTextNode(const Position& position)
{
Node* node = position.containerNode();
- if (position.anchorType() != Position::PositionIsOffsetInAnchor || !node->isTextNode())
+ if (position.anchorType() != Position::PositionIsOffsetInAnchor || !is<Text>(node))
return false;
int offsetInText = position.offsetInContainerNode();
- return offsetInText > caretMinOffset(node) && offsetInText < caretMaxOffset(node);
+ return offsetInText > caretMinOffset(*node) && offsetInText < caretMaxOffset(*node);
}
bool ApplyStyleCommand::mergeStartWithPreviousIfIdentical(const Position& start, const Position& end)
{
- Node* startNode = start.containerNode();
+ auto* startNode = start.containerNode();
int startOffset = start.computeOffsetInContainerNode();
if (startOffset)
return false;
@@ -1289,29 +1289,23 @@ bool ApplyStyleCommand::mergeStartWithPreviousIfIdentical(const Position& start,
return false;
startNode = startNode->parentNode();
- startOffset = 0;
}
- if (!startNode->isElementNode())
+ auto* previousSibling = startNode->previousSibling();
+ if (!previousSibling || !areIdenticalElements(*startNode, *previousSibling))
return false;
- Node* previousSibling = startNode->previousSibling();
-
- if (previousSibling && areIdenticalElements(startNode, previousSibling)) {
- Element* previousElement = toElement(previousSibling);
- Element* element = toElement(startNode);
- Node* startChild = element->firstChild();
- ASSERT(startChild);
- mergeIdenticalElements(previousElement, element);
+ auto& previousElement = downcast<Element>(*previousSibling);
+ auto& element = downcast<Element>(*startNode);
+ auto* startChild = element.firstChild();
+ ASSERT(startChild);
+ mergeIdenticalElements(&previousElement, &element);
- int startOffsetAdjustment = startChild->nodeIndex();
- int endOffsetAdjustment = startNode == end.deprecatedNode() ? startOffsetAdjustment : 0;
- updateStartEnd(Position(startNode, startOffsetAdjustment, Position::PositionIsOffsetInAnchor),
- Position(end.deprecatedNode(), end.deprecatedEditingOffset() + endOffsetAdjustment, Position::PositionIsOffsetInAnchor));
- return true;
- }
-
- return false;
+ int startOffsetAdjustment = startChild->computeNodeIndex();
+ int endOffsetAdjustment = startNode == end.deprecatedNode() ? startOffsetAdjustment : 0;
+ updateStartEnd({ startNode, startOffsetAdjustment, Position::PositionIsOffsetInAnchor},
+ { end.deprecatedNode(), end.deprecatedEditingOffset() + endOffsetAdjustment, Position::PositionIsOffsetInAnchor });
+ return true;
}
bool ApplyStyleCommand::mergeEndWithNextIfIdentical(const Position& start, const Position& end)
@@ -1326,25 +1320,24 @@ bool ApplyStyleCommand::mergeEndWithNextIfIdentical(const Position& start, const
endNode = end.deprecatedNode()->parentNode();
}
- if (!endNode->isElementNode() || endNode->hasTagName(brTag))
+ if (endNode->hasTagName(brTag))
return false;
Node* nextSibling = endNode->nextSibling();
- if (nextSibling && areIdenticalElements(endNode, nextSibling)) {
- Element* nextElement = toElement(nextSibling);
- Element* element = toElement(endNode);
- Node* nextChild = nextElement->firstChild();
+ if (!nextSibling || !areIdenticalElements(*endNode, *nextSibling))
+ return false;
- mergeIdenticalElements(element, nextElement);
+ auto& nextElement = downcast<Element>(*nextSibling);
+ auto& element = downcast<Element>(*endNode);
+ Node* nextChild = nextElement.firstChild();
- bool shouldUpdateStart = start.containerNode() == endNode;
- int endOffset = nextChild ? nextChild->nodeIndex() : nextElement->childNodeCount();
- updateStartEnd(shouldUpdateStart ? Position(nextElement, start.offsetInContainerNode(), Position::PositionIsOffsetInAnchor) : start,
- Position(nextElement, endOffset, Position::PositionIsOffsetInAnchor));
- return true;
- }
+ mergeIdenticalElements(&element, &nextElement);
- return false;
+ bool shouldUpdateStart = start.containerNode() == endNode;
+ int endOffset = nextChild ? nextChild->computeNodeIndex() : nextElement.countChildNodes();
+ updateStartEnd(shouldUpdateStart ? Position(&nextElement, start.offsetInContainerNode(), Position::PositionIsOffsetInAnchor) : start,
+ { &nextElement, endOffset, Position::PositionIsOffsetInAnchor });
+ return true;
}
void ApplyStyleCommand::surroundNodeRangeWithElement(PassRefPtr<Node> passedStartNode, PassRefPtr<Node> endNode, PassRefPtr<Element> elementToInsert)
@@ -1360,7 +1353,7 @@ void ApplyStyleCommand::surroundNodeRangeWithElement(PassRefPtr<Node> passedStar
RefPtr<Node> node = startNode;
while (node) {
RefPtr<Node> next = node->nextSibling();
- if (node->isContentEditable(Node::UserSelectAllIsAlwaysNonEditable)) {
+ if (isEditableNode(*node)) {
removeNode(node);
appendNode(node, element);
}
@@ -1371,15 +1364,15 @@ void ApplyStyleCommand::surroundNodeRangeWithElement(PassRefPtr<Node> passedStar
RefPtr<Node> nextSibling = element->nextSibling();
RefPtr<Node> previousSibling = element->previousSibling();
- if (nextSibling && nextSibling->isElementNode() && nextSibling->hasEditableStyle()
- && areIdenticalElements(element.get(), toElement(nextSibling.get())))
- mergeIdenticalElements(element.get(), toElement(nextSibling.get()));
-
- if (previousSibling && previousSibling->isElementNode() && previousSibling->hasEditableStyle()) {
- Node* mergedElement = previousSibling->nextSibling();
- if (mergedElement->isElementNode() && mergedElement->hasEditableStyle()
- && areIdenticalElements(toElement(previousSibling.get()), toElement(mergedElement)))
- mergeIdenticalElements(toElement(previousSibling.get()), toElement(mergedElement));
+
+ if (nextSibling && nextSibling->hasEditableStyle() && areIdenticalElements(*element, *nextSibling))
+ mergeIdenticalElements(element.get(), downcast<Element>(nextSibling.get()));
+
+ if (is<Element>(previousSibling.get()) && previousSibling->hasEditableStyle()) {
+ auto* mergedElement = previousSibling->nextSibling();
+ ASSERT(mergedElement);
+ if (mergedElement->hasEditableStyle() && areIdenticalElements(*previousSibling, *mergedElement))
+ mergeIdenticalElements(downcast<Element>(previousSibling.get()), downcast<Element>(mergedElement));
}
// FIXME: We should probably call updateStartEnd if the start or end was in the node
@@ -1389,12 +1382,13 @@ void ApplyStyleCommand::surroundNodeRangeWithElement(PassRefPtr<Node> passedStar
void ApplyStyleCommand::addBlockStyle(const StyleChange& styleChange, HTMLElement* block)
{
+ ASSERT(styleChange.cssStyle());
// Do not check for legacy styles here. Those styles, like <B> and <I>, only apply for
// inline content.
if (!block)
return;
- String cssStyle = styleChange.cssStyle();
+ String cssStyle = styleChange.cssStyle()->asText();
StringBuilder cssText;
cssText.append(cssStyle);
if (const StyleProperties* decl = block->inlineStyle()) {
@@ -1407,7 +1401,7 @@ void ApplyStyleCommand::addBlockStyle(const StyleChange& styleChange, HTMLElemen
void ApplyStyleCommand::addInlineStyleIfNeeded(EditingStyle* style, PassRefPtr<Node> passedStart, PassRefPtr<Node> passedEnd, EAddStyledElement addStyledElement)
{
- if (!passedStart || !passedEnd || !passedStart->inDocument() || !passedEnd->inDocument())
+ if (!passedStart || !passedEnd || !passedStart->isConnected() || !passedEnd->isConnected())
return;
RefPtr<Node> start = passedStart;
@@ -1423,7 +1417,7 @@ void ApplyStyleCommand::addInlineStyleIfNeeded(EditingStyle* style, PassRefPtr<N
Position ApplyStyleCommand::positionToComputeInlineStyleChange(PassRefPtr<Node> startNode, RefPtr<Node>& dummyElement)
{
// It's okay to obtain the style at the startNode because we've removed all relevant styles from the current run.
- if (!startNode->isElementNode()) {
+ if (!is<Element>(*startNode)) {
dummyElement = createStyleSpanElement(document());
insertNodeAt(dummyElement, positionBeforeNode(startNode.get()));
return firstPositionInOrBeforeNode(dummyElement.get());
@@ -1436,22 +1430,25 @@ void ApplyStyleCommand::applyInlineStyleChange(PassRefPtr<Node> passedStart, Pas
{
RefPtr<Node> startNode = passedStart;
RefPtr<Node> endNode = passedEnd;
- ASSERT(startNode->inDocument());
- ASSERT(endNode->inDocument());
+ ASSERT(startNode->isConnected());
+ ASSERT(endNode->isConnected());
// Find appropriate font and span elements top-down.
- HTMLElement* fontContainer = 0;
- HTMLElement* styleContainer = 0;
- for (Node* container = startNode.get(); container && startNode == endNode; container = container->firstChild()) {
- if (container->isHTMLElement() && container->hasTagName(fontTag))
- fontContainer = toHTMLElement(container);
- bool styleContainerIsNotSpan = !styleContainer || !styleContainer->hasTagName(spanTag);
- if (container->isHTMLElement() && (container->hasTagName(spanTag) || (styleContainerIsNotSpan && container->childNodeCount())))
- styleContainer = toHTMLElement(container);
- if (!container->firstChild())
+ HTMLFontElement* fontContainer = nullptr;
+ HTMLElement* styleContainer = nullptr;
+ while (startNode == endNode) {
+ if (is<HTMLElement>(*startNode)) {
+ auto& container = downcast<HTMLElement>(*startNode);
+ if (is<HTMLFontElement>(container))
+ fontContainer = &downcast<HTMLFontElement>(container);
+ if (is<HTMLSpanElement>(container) || (!is<HTMLSpanElement>(styleContainer) && container.hasChildNodes()))
+ styleContainer = &container;
+ }
+ auto* startNodeFirstChild = startNode->firstChild();
+ if (!startNodeFirstChild)
break;
- startNode = container->firstChild();
- endNode = container->lastChild();
+ endNode = startNode->lastChild();
+ startNode = startNodeFirstChild;
}
// Font tags need to go outside of CSS so that CSS font sizes override leagcy font sizes.
@@ -1464,33 +1461,29 @@ void ApplyStyleCommand::applyInlineStyleChange(PassRefPtr<Node> passedStart, Pas
if (styleChange.applyFontSize())
setNodeAttribute(fontContainer, sizeAttr, styleChange.fontSize());
} else {
- RefPtr<Element> fontElement = createFontElement(document());
+ auto fontElement = createFontElement(document());
if (styleChange.applyFontColor())
- fontElement->setAttribute(colorAttr, styleChange.fontColor());
+ fontElement->setAttributeWithoutSynchronization(colorAttr, styleChange.fontColor());
if (styleChange.applyFontFace())
- fontElement->setAttribute(faceAttr, styleChange.fontFace());
+ fontElement->setAttributeWithoutSynchronization(faceAttr, styleChange.fontFace());
if (styleChange.applyFontSize())
- fontElement->setAttribute(sizeAttr, styleChange.fontSize());
+ fontElement->setAttributeWithoutSynchronization(sizeAttr, styleChange.fontSize());
surroundNodeRangeWithElement(startNode, endNode, fontElement.get());
}
}
- if (styleChange.cssStyle().length()) {
+ if (auto styleToMerge = styleChange.cssStyle()) {
if (styleContainer) {
- if (const StyleProperties* existingStyle = styleContainer->inlineStyle()) {
- String existingText = existingStyle->asText();
- StringBuilder cssText;
- cssText.append(existingText);
- if (!existingText.isEmpty())
- cssText.append(' ');
- cssText.append(styleChange.cssStyle());
- setNodeAttribute(styleContainer, styleAttr, cssText.toString());
+ if (auto existingStyle = styleContainer->inlineStyle()) {
+ auto inlineStyle = EditingStyle::create(existingStyle);
+ inlineStyle->overrideWithStyle(styleToMerge);
+ setNodeAttribute(styleContainer, styleAttr, inlineStyle->style()->asText());
} else
- setNodeAttribute(styleContainer, styleAttr, styleChange.cssStyle());
+ setNodeAttribute(styleContainer, styleAttr, styleToMerge->asText());
} else {
- RefPtr<Element> styleElement = createStyleSpanElement(document());
- styleElement->setAttribute(styleAttr, styleChange.cssStyle());
- surroundNodeRangeWithElement(startNode, endNode, styleElement.release());
+ auto styleElement = createStyleSpanElement(document());
+ styleElement->setAttribute(styleAttr, styleToMerge->asText());
+ surroundNodeRangeWithElement(startNode, endNode, WTFMove(styleElement));
}
}
@@ -1512,7 +1505,7 @@ void ApplyStyleCommand::applyInlineStyleChange(PassRefPtr<Node> passedStart, Pas
surroundNodeRangeWithElement(startNode, endNode, createHTMLElement(document(), supTag));
if (m_styledInlineElement && addStyledElement == AddStyledElement)
- surroundNodeRangeWithElement(startNode, endNode, m_styledInlineElement->cloneElementWithoutChildren());
+ surroundNodeRangeWithElement(startNode, endNode, m_styledInlineElement->cloneElementWithoutChildren(document()));
}
float ApplyStyleCommand::computedFontSize(Node* node)
@@ -1520,9 +1513,8 @@ float ApplyStyleCommand::computedFontSize(Node* node)
if (!node)
return 0;
- RefPtr<CSSValue> value = ComputedStyleExtractor(node).propertyValue(CSSPropertyFontSize);
- ASSERT(value && value->isPrimitiveValue());
- return toCSSPrimitiveValue(value.get())->getFloatValue(CSSPrimitiveValue::CSS_PX);
+ auto value = ComputedStyleExtractor(node).propertyValue(CSSPropertyFontSize);
+ return downcast<CSSPrimitiveValue>(*value).floatValue(CSSPrimitiveValue::CSS_PX);
}
void ApplyStyleCommand::joinChildTextNodes(Node* node, const Position& start, const Position& end)
@@ -1534,21 +1526,20 @@ void ApplyStyleCommand::joinChildTextNodes(Node* node, const Position& start, co
Position newEnd = end;
Vector<RefPtr<Text>> textNodes;
- for (Text* textNode = TextNodeTraversal::firstChild(node); textNode; textNode = TextNodeTraversal::nextSibling(textNode))
+ for (Text* textNode = TextNodeTraversal::firstChild(*node); textNode; textNode = TextNodeTraversal::nextSibling(*textNode))
textNodes.append(textNode);
- for (size_t i = 0; i < textNodes.size(); ++i) {
- Text* childText = textNodes[i].get();
+ for (auto& childText : textNodes) {
Node* next = childText->nextSibling();
- if (!next || !next->isTextNode())
+ if (!is<Text>(next))
continue;
- Text* nextText = toText(next);
+ Text& nextText = downcast<Text>(*next);
if (start.anchorType() == Position::PositionIsOffsetInAnchor && next == start.containerNode())
- newStart = Position(childText, childText->length() + start.offsetInContainerNode());
+ newStart = Position(childText.get(), childText->length() + start.offsetInContainerNode());
if (end.anchorType() == Position::PositionIsOffsetInAnchor && next == end.containerNode())
- newEnd = Position(childText, childText->length() + end.offsetInContainerNode());
- String textToMove = nextText->data();
+ newEnd = Position(childText.get(), childText->length() + end.offsetInContainerNode());
+ String textToMove = nextText.data();
insertTextIntoNode(childText, childText->length(), textToMove);
removeNode(next);
// don't move child node pointer. it may want to merge with more text nodes.