Title: [276191] trunk/Source
Revision
276191
Author
[email protected]
Date
2021-04-16 19:32:54 -0700 (Fri, 16 Apr 2021)

Log Message

Deploy Ref/RefPtr in Editor
https://bugs.webkit.org/show_bug.cgi?id=224708

Reviewed by Wenson Hsieh.

Source/WebCore:

Deployed smart pointers in WebCore::Editor.

Also deployed ScriptDisallowedScope around the code which accesses the render tree.

* dom/Position.cpp:
(WebCore::Position::containerOrParentElement const): Added.
* dom/Position.h:
* editing/Editor.cpp:
(WebCore::Editor::selectionForCommand):
(WebCore::Editor::pasteAsPlainText):
(WebCore::Editor::pasteAsFragment):
(WebCore::Editor::shouldInsertFragment):
(WebCore::Editor::replaceSelectionWithFragment):
(WebCore::Editor::respondToChangedContents):
(WebCore::Editor::hasBidiSelection const):
(WebCore::Editor::selectionUnorderedListState const):
(WebCore::Editor::selectionOrderedListState const):
(WebCore::Editor::findEventTargetFrom const):
(WebCore::Editor::findEventTargetFromSelection const):
(WebCore::notifyTextFromControls):
(WebCore::Editor::willApplyEditing const):
(WebCore::Editor::appliedEditing):
(WebCore::Editor::insertTextWithoutSendingTextEvent):
(WebCore::Editor::performCutOrCopy):
(WebCore::Editor::simplifyMarkup): Replaced the manual tree traversal by treeOrder(~).
(WebCore::Editor::copyImage):
(WebCore::Editor::setBaseWritingDirection):
(WebCore::Editor::baseWritingDirectionForSelectionStart const):
(WebCore::Editor::setComposition):
(WebCore::Editor::advanceToNextMisspelling):
(WebCore::Editor::markMisspellingsAfterTypingToWord): Use containerOrParentElement.
(WebCore::Editor::isSpellCheckingEnabledFor const):
(WebCore::Editor::markAllMisspellingsAndBadGrammarInRanges):
(WebCore::Editor::markAndReplaceFor):
(WebCore::scanForTelephoneNumbers):
(WebCore::Editor::scanSelectionForTelephoneNumbers): Restrucuted the code with makeScopeExit
to exit early instead of nesting if's.
(WebCore::findFirstMarkable):
(WebCore::Editor::selectionStartHasMarkerFor const):
(WebCore::Editor::resolveTextCheckingTypeMask):
(WebCore::Editor::stringForCandidateRequest const):
(WebCore::Editor::fontAttributesAtSelectionStart):
(WebCore::Editor::promisedAttachmentInfo):
(WebCore::Editor::styleForSelectionStart):
(WebCore::Editor::fontForSelection):
* editing/Editor.h:
* page/DragController.cpp:
(WebCore::DragController::dispatchTextInputEventFor):

Source/WebKit:

* WebProcess/WebPage/WebPage.cpp:
(WebKit::WebPage::editorState const):
* WebProcess/WebPage/ios/WebPageIOS.mm:
(WebKit::WebPage::requestAutocorrectionData):
* WebProcess/WebPage/mac/WebPageMac.mm:
(WebKit::WebPage::fontAtSelection):

Source/WebKitLegacy/mac:

* WebView/WebFrame.mm:
(-[WebFrame fontForSelection:]):
* WebView/WebHTMLView.mm:
(-[WebHTMLView _updateFontPanel]):
* WebView/WebView.mm:
(-[WebView updateTextTouchBar]):

Modified Paths

Diff

Modified: trunk/Source/WebCore/ChangeLog (276190 => 276191)


--- trunk/Source/WebCore/ChangeLog	2021-04-17 02:06:15 UTC (rev 276190)
+++ trunk/Source/WebCore/ChangeLog	2021-04-17 02:32:54 UTC (rev 276191)
@@ -1,3 +1,59 @@
+2021-04-16  Ryosuke Niwa  <[email protected]>
+
+        Deploy Ref/RefPtr in Editor
+        https://bugs.webkit.org/show_bug.cgi?id=224708
+
+        Reviewed by Wenson Hsieh.
+
+        Deployed smart pointers in WebCore::Editor.
+
+        Also deployed ScriptDisallowedScope around the code which accesses the render tree.
+
+        * dom/Position.cpp:
+        (WebCore::Position::containerOrParentElement const): Added.
+        * dom/Position.h:
+        * editing/Editor.cpp:
+        (WebCore::Editor::selectionForCommand):
+        (WebCore::Editor::pasteAsPlainText):
+        (WebCore::Editor::pasteAsFragment):
+        (WebCore::Editor::shouldInsertFragment):
+        (WebCore::Editor::replaceSelectionWithFragment):
+        (WebCore::Editor::respondToChangedContents):
+        (WebCore::Editor::hasBidiSelection const):
+        (WebCore::Editor::selectionUnorderedListState const):
+        (WebCore::Editor::selectionOrderedListState const):
+        (WebCore::Editor::findEventTargetFrom const):
+        (WebCore::Editor::findEventTargetFromSelection const):
+        (WebCore::notifyTextFromControls):
+        (WebCore::Editor::willApplyEditing const):
+        (WebCore::Editor::appliedEditing):
+        (WebCore::Editor::insertTextWithoutSendingTextEvent):
+        (WebCore::Editor::performCutOrCopy):
+        (WebCore::Editor::simplifyMarkup): Replaced the manual tree traversal by treeOrder(~). 
+        (WebCore::Editor::copyImage):
+        (WebCore::Editor::setBaseWritingDirection):
+        (WebCore::Editor::baseWritingDirectionForSelectionStart const):
+        (WebCore::Editor::setComposition):
+        (WebCore::Editor::advanceToNextMisspelling):
+        (WebCore::Editor::markMisspellingsAfterTypingToWord): Use containerOrParentElement.
+        (WebCore::Editor::isSpellCheckingEnabledFor const):
+        (WebCore::Editor::markAllMisspellingsAndBadGrammarInRanges):
+        (WebCore::Editor::markAndReplaceFor):
+        (WebCore::scanForTelephoneNumbers):
+        (WebCore::Editor::scanSelectionForTelephoneNumbers): Restrucuted the code with makeScopeExit
+        to exit early instead of nesting if's. 
+        (WebCore::findFirstMarkable):
+        (WebCore::Editor::selectionStartHasMarkerFor const):
+        (WebCore::Editor::resolveTextCheckingTypeMask):
+        (WebCore::Editor::stringForCandidateRequest const):
+        (WebCore::Editor::fontAttributesAtSelectionStart):
+        (WebCore::Editor::promisedAttachmentInfo):
+        (WebCore::Editor::styleForSelectionStart):
+        (WebCore::Editor::fontForSelection):
+        * editing/Editor.h:
+        * page/DragController.cpp:
+        (WebCore::DragController::dispatchTextInputEventFor):
+
 2021-04-16  Darin Adler  <[email protected]>
 
         font-size with viewport units in calc() doesn't change when viewport resizes

Modified: trunk/Source/WebCore/dom/Position.cpp (276190 => 276191)


--- trunk/Source/WebCore/dom/Position.cpp	2021-04-17 02:06:15 UTC (rev 276190)
+++ trunk/Source/WebCore/dom/Position.cpp	2021-04-17 02:32:54 UTC (rev 276191)
@@ -197,6 +197,16 @@
     return nullptr;
 }
 
+Element* Position::containerOrParentElement() const
+{
+    auto* container = containerNode();
+    if (!container)
+        return nullptr;
+    if (is<Element>(container))
+        return downcast<Element>(container);
+    return container->parentElement();
+}
+
 int Position::computeOffsetInContainerNode() const
 {
     if (!m_anchorNode)

Modified: trunk/Source/WebCore/dom/Position.h (276190 => 276191)


--- trunk/Source/WebCore/dom/Position.h	2021-04-17 02:06:15 UTC (rev 276190)
+++ trunk/Source/WebCore/dom/Position.h	2021-04-17 02:32:54 UTC (rev 276191)
@@ -83,6 +83,7 @@
     // will return img->parentNode() and img->computeNodeIndex() from these functions.
     WEBCORE_EXPORT Node* containerNode() const; // null for a before/after position anchored to a node with no parent
     Text* containerText() const;
+    Element* containerOrParentElement() const;
 
     int computeOffsetInContainerNode() const;  // O(n) for before/after-anchored positions, O(1) for parent-anchored positions
     WEBCORE_EXPORT Position parentAnchoredEquivalent() const; // Convenience method for DOM positions that also fixes up some positions for editing

Modified: trunk/Source/WebCore/editing/Editor.cpp (276190 => 276191)


--- trunk/Source/WebCore/editing/Editor.cpp	2021-04-17 02:06:15 UTC (rev 276190)
+++ trunk/Source/WebCore/editing/Editor.cpp	2021-04-17 02:32:54 UTC (rev 276191)
@@ -96,6 +96,7 @@
 #include "ReplaceRangeWithTextCommand.h"
 #include "ReplaceSelectionCommand.h"
 #include "RuntimeEnabledFeatures.h"
+#include "ScriptDisallowedScope.h"
 #include "SerializedAttachmentData.h"
 #include "Settings.h"
 #include "ShadowRoot.h"
@@ -120,6 +121,7 @@
 #include "markup.h"
 #include <pal/FileSizeFormatter.h>
 #include <pal/text/KillRing.h>
+#include <wtf/Scope.h>
 #include <wtf/SetForScope.h>
 #include <wtf/unicode/CharacterNames.h>
 
@@ -273,11 +275,10 @@
         return selection;
     // If the target is a text control, and the current selection is outside of its shadow tree,
     // then use the saved selection for that text control.
-    if (is<Element>(event->target()) && downcast<Element>(*event->target()).isTextField()) {
-        auto& target = downcast<HTMLTextFormControlElement>(*event->target());
+    if (auto target = makeRefPtr(event->target()); is<HTMLTextFormControlElement>(target) && downcast<Element>(*target).isTextField()) {
         auto start = selection.start();
-        if (start.isNull() || &target != enclosingTextFormControl(start)) {
-            if (auto range = target.selection())
+        if (start.isNull() || target != enclosingTextFormControl(start)) {
+            if (auto range = downcast<HTMLTextFormControlElement>(*target).selection())
                 return { *range, Affinity::Downstream, selection.isDirectional() };
         }
     }
@@ -608,7 +609,7 @@
 
 void Editor::pasteAsPlainText(const String& pastingText, bool smartReplace)
 {
-    Element* target = findEventTargetFromSelection();
+    auto target = findEventTargetFromSelection();
     if (!target)
         return;
     target->dispatchEvent(TextEvent::createForPlainTextPaste(document().windowProxy(), pastingText, smartReplace));
@@ -616,7 +617,7 @@
 
 void Editor::pasteAsFragment(Ref<DocumentFragment>&& pastingFragment, bool smartReplace, bool matchStyle, MailBlockquoteHandling respectsMailBlockquote)
 {
-    Element* target = findEventTargetFromSelection();
+    auto target = findEventTargetFromSelection();
     if (!target)
         return;
     target->dispatchEvent(TextEvent::createForFragmentPaste(document().windowProxy(), WTFMove(pastingFragment), smartReplace, matchStyle, respectsMailBlockquote));
@@ -660,7 +661,7 @@
     if (!client())
         return false;
     
-    auto* child = fragment.firstChild();
+    auto child = makeRefPtr(fragment.firstChild());
     if (is<CharacterData>(child) && fragment.lastChild() == child)
         return client()->shouldInsertText(downcast<CharacterData>(*child).data(), replacingDOMRange, givenAction);
 
@@ -716,7 +717,7 @@
     if (!isContinuousSpellCheckingEnabled())
         return;
 
-    Node* nodeToCheck = selection.rootEditableElement();
+    auto nodeToCheck = makeRefPtr(selection.rootEditableElement());
     if (!nodeToCheck)
         return;
 
@@ -771,9 +772,9 @@
 void Editor::respondToChangedContents(const VisibleSelection& endingSelection)
 {
     if (AXObjectCache::accessibilityEnabled()) {
-        Node* node = endingSelection.start().deprecatedNode();
+        auto node = makeRefPtr(endingSelection.start().deprecatedNode());
         if (AXObjectCache* cache = document().existingAXObjectCache())
-            cache->postNotification(node, AXObjectCache::AXValueChanged, PostTarget::ObservableParent);
+            cache->postNotification(node.get(), AXObjectCache::AXValueChanged, PostTarget::ObservableParent);
     }
 
     updateMarkersForWordsAffectedByEditing(true);
@@ -787,11 +788,11 @@
     if (m_document.selection().isNone())
         return false;
 
-    Node* startNode;
+    RefPtr<Node> startNode;
     if (m_document.selection().isRange()) {
         startNode = m_document.selection().selection().start().downstream().deprecatedNode();
-        Node* endNode = m_document.selection().selection().end().upstream().deprecatedNode();
-        if (enclosingBlock(startNode) != enclosingBlock(endNode))
+        auto endNode = makeRefPtr(m_document.selection().selection().end().upstream().deprecatedNode());
+        if (enclosingBlock(startNode.get()) != enclosingBlock(endNode.get()))
             return false;
     } else
         startNode = m_document.selection().selection().visibleStart().deepEquivalent().deprecatedNode();
@@ -799,6 +800,8 @@
     if (!startNode)
         return false;
 
+    ScriptDisallowedScope::InMainThread scriptDisallowedScope;
+
     auto renderer = startNode->renderer();
     while (renderer && !is<RenderBlockFlow>(*renderer))
         renderer = renderer->parent();
@@ -818,8 +821,8 @@
         if (enclosingElementWithTag(m_document.selection().selection().start(), ulTag))
             return TriState::True;
     } else if (m_document.selection().isRange()) {
-        auto* startNode = enclosingElementWithTag(m_document.selection().selection().start(), ulTag);
-        auto* endNode = enclosingElementWithTag(m_document.selection().selection().end(), ulTag);
+        auto startNode = makeRefPtr(enclosingElementWithTag(m_document.selection().selection().start(), ulTag));
+        auto endNode = makeRefPtr(enclosingElementWithTag(m_document.selection().selection().end(), ulTag));
         if (startNode && endNode && startNode == endNode)
             return TriState::True;
     }
@@ -833,8 +836,8 @@
         if (enclosingElementWithTag(m_document.selection().selection().start(), olTag))
             return TriState::True;
     } else if (m_document.selection().isRange()) {
-        auto* startNode = enclosingElementWithTag(m_document.selection().selection().start(), olTag);
-        auto* endNode = enclosingElementWithTag(m_document.selection().selection().end(), olTag);
+        auto startNode = makeRefPtr(enclosingElementWithTag(m_document.selection().selection().start(), olTag));
+        auto endNode = makeRefPtr(enclosingElementWithTag(m_document.selection().selection().end(), olTag));
         if (startNode && endNode && startNode == endNode)
             return TriState::True;
     }
@@ -921,9 +924,9 @@
     m_lastEditCommand = nullptr;
 }
 
-Element* Editor::findEventTargetFrom(const VisibleSelection& selection) const
+RefPtr<Element> Editor::findEventTargetFrom(const VisibleSelection& selection) const
 {
-    Element* target = selection.start().element();
+    auto target = makeRefPtr(selection.start().element());
     if (!target)
         target = document().bodyOrFrameset();
     if (!target)
@@ -932,7 +935,7 @@
     return target;
 }
 
-Element* Editor::findEventTargetFromSelection() const
+RefPtr<Element> Editor::findEventTargetFromSelection() const
 {
     return findEventTargetFrom(m_document.selection().selection());
 }
@@ -1068,8 +1071,8 @@
 
 static void notifyTextFromControls(Element* startRoot, Element* endRoot)
 {
-    HTMLTextFormControlElement* startingTextControl = enclosingTextFormControl(firstPositionInOrBeforeNode(startRoot));
-    HTMLTextFormControlElement* endingTextControl = enclosingTextFormControl(firstPositionInOrBeforeNode(endRoot));
+    auto startingTextControl =  makeRefPtr(enclosingTextFormControl(firstPositionInOrBeforeNode(startRoot)));
+    auto endingTextControl = makeRefPtr(enclosingTextFormControl(firstPositionInOrBeforeNode(endRoot)));
     if (startingTextControl)
         startingTextControl->didEditInnerTextValue();
     if (endingTextControl && startingTextControl != endingTextControl)
@@ -1099,7 +1102,7 @@
     if (!command.shouldDispatchInputEvents())
         return true;
 
-    auto* composition = command.composition();
+    auto composition = makeRefPtr(command.composition());
     if (!composition)
         return true;
 
@@ -1117,10 +1120,10 @@
     document().updateLayout();
 
     ASSERT(command.composition());
-    auto& composition = *command.composition();
+    auto composition = makeRef(*command.composition());
     VisibleSelection newSelection(command.endingSelection());
 
-    notifyTextFromControls(composition.startingRootEditableElement(), composition.endingRootEditableElement());
+    notifyTextFromControls(composition->startingRootEditableElement(), composition->endingRootEditableElement());
 
     if (command.isTopLevelCommand()) {
         // Don't clear the typing style with this selection change. We do those things elsewhere if necessary.
@@ -1132,7 +1135,7 @@
     }
 
     if (command.shouldDispatchInputEvents())
-        dispatchInputEvents(composition.startingRootEditableElement(), composition.endingRootEditableElement(), command.inputEventTypeName(), command.inputEventData(), command.inputEventDataTransfer());
+        dispatchInputEvents(composition->startingRootEditableElement(), composition->endingRootEditableElement(), command.inputEventTypeName(), command.inputEventData(), command.inputEventDataTransfer());
 
     if (command.isTopLevelCommand()) {
         updateEditorUINowIfScheduled();
@@ -1290,7 +1293,7 @@
     // that is contained in the event target.
     selection = selectionForCommand(triggeringEvent);
     if (selection.isContentEditable()) {
-        if (Node* selectionStart = selection.start().deprecatedNode()) {
+        if (auto selectionStart = makeRefPtr(selection.start().deprecatedNode())) {
             Ref<Document> document(selectionStart->document());
 
             // Insert the text
@@ -1419,7 +1422,7 @@
     if (enclosingTextFormControl(m_document.selection().selection().start()) || (selection && HTMLElement::isInsideImageOverlay(*selection)))
         Pasteboard::createForCopyAndPaste(PagePasteboardContext::create(m_document.pageID()))->writePlainText(selectedTextForDataTransfer(), canSmartCopyOrDelete() ? Pasteboard::CanSmartReplace : Pasteboard::CannotSmartReplace);
     else {
-        HTMLImageElement* imageElement = nullptr;
+        RefPtr<HTMLImageElement> imageElement;
         if (action == CopyAction)
             imageElement = imageElementFromImageDocument(document());
 
@@ -1545,18 +1548,15 @@
 {
     if (!startNode)
         return;
+
+    RefPtr<Node> pastEndNode;
     if (endNode) {
-        if (&startNode->document() != &endNode->document())
+        if (!is_lt(treeOrder(*startNode, *endNode)))
             return;
-        // check if start node is before endNode
-        Node* node = startNode;
-        while (node && node != endNode)
-            node = NodeTraversal::next(*node);
-        if (!node)
-            return;
+        pastEndNode = NodeTraversal::next(*endNode);
     }
     
-    SimplifyMarkupCommand::create(document(), startNode, endNode ? NodeTraversal::next(*endNode) : nullptr)->apply();
+    SimplifyMarkupCommand::create(document(), startNode, pastEndNode.get())->apply();
 }
 
 void Editor::copyURL(const URL& url, const String& title)
@@ -1594,7 +1594,7 @@
 
 void Editor::copyImage(const HitTestResult& result)
 {
-    Element* element = result.innerNonSharedElement();
+    auto element = makeRefPtr(result.innerNonSharedElement());
     if (!element)
         return;
 
@@ -1876,8 +1876,8 @@
         && baseWritingDirectionForSelectionStart() == direction)
         return;
 #endif
-        
-    Element* focusedElement = document().focusedElement();
+
+    auto focusedElement = makeRefPtr(document().focusedElement());
     if (focusedElement && focusedElement->isTextField()) {
         if (direction == WritingDirection::Natural)
             return;
@@ -1904,10 +1904,12 @@
     auto result = WritingDirection::LeftToRight;
 
     Position pos = m_document.selection().selection().visibleStart().deepEquivalent();
-    Node* node = pos.deprecatedNode();
+    auto node = makeRefPtr(pos.deprecatedNode());
     if (!node)
         return result;
 
+    ScriptDisallowedScope::InMainThread scriptDisallowedScope;
+
     auto renderer = node->renderer();
     if (!renderer)
         return result;
@@ -2075,7 +2077,7 @@
     client()->startDelayingAndCoalescingContentChangeNotifications();
 #endif
 
-    Element* target = document().focusedElement();
+    auto target = makeRefPtr(document().focusedElement());
     if (target) {
         // Dispatch an appropriate composition event to the focused node.
         // We check the composition status and choose an appropriate composition event since this
@@ -2125,13 +2127,13 @@
         // Find out what node has the composition now.
         Position base = m_document.selection().selection().base().downstream();
         Position extent = m_document.selection().selection().extent();
-        Node* baseNode = base.deprecatedNode();
+        auto baseNode = makeRefPtr(base.deprecatedNode());
         unsigned baseOffset = base.deprecatedEditingOffset();
-        Node* extentNode = extent.deprecatedNode();
+        auto extentNode = makeRefPtr(extent.deprecatedNode());
         unsigned extentOffset = extent.deprecatedEditingOffset();
 
         if (is<Text>(baseNode) && baseNode == extentNode && baseOffset + text.length() == extentOffset) {
-            m_compositionNode = downcast<Text>(baseNode);
+            m_compositionNode = static_pointer_cast<Text>(baseNode);
             m_compositionStart = baseOffset;
             m_compositionEnd = extentOffset;
             m_customCompositionUnderlines = underlines;
@@ -2239,7 +2241,7 @@
     }
 
     // topNode defines the whole range we want to operate on 
-    auto* topNode = highestEditableRoot(position);
+    auto topNode = makeRefPtr(highestEditableRoot(position));
     if (topNode)
         spellingSearchRange.end = makeBoundaryPointAfterNodeContents(*topNode);
 
@@ -2551,8 +2553,7 @@
             if (nextPosition.isNull() || nextPosition == spellCheckingEnd)
                 break;
 
-            auto* container = nextPosition.deepEquivalent().upstream().containerNode();
-            if (auto* containerElement = is<Element>(container) ? downcast<Element>(container) : container->parentElement()) {
+            if (auto containerElement = makeRefPtr(nextPosition.deepEquivalent().upstream().containerOrParentElement())) {
                 if (!containerElement->isSpellCheckingEnabled())
                     break;
             }
@@ -2661,11 +2662,11 @@
 {
     if (!node)
         return false;
-    Element* element = is<Element>(*node) ? downcast<Element>(node) : node->parentElement();
+    auto element = makeRefPtr(is<Element>(*node) ? downcast<Element>(node) : node->parentElement());
     if (!element)
         return false;
     if (element->isInUserAgentShadowTree()) {
-        if (HTMLTextFormControlElement* textControl = enclosingTextFormControl(firstPositionInOrBeforeNode(element)))
+        if (auto textControl = makeRefPtr(enclosingTextFormControl(firstPositionInOrBeforeNode(element.get()))))
             return textControl->isSpellCheckingEnabled();
     }
     return element->isSpellCheckingEnabled();
@@ -2704,11 +2705,11 @@
         return;
 
     // If we're not in an editable node, bail.
-    Node& editableNode = spellingRange->startContainer();
-    if (!editableNode.hasEditableStyle())
+    auto editableNode = makeRef(spellingRange->startContainer());
+    if (!editableNode->hasEditableStyle())
         return;
 
-    if (!isSpellCheckingEnabledFor(&editableNode))
+    if (!isSpellCheckingEnabledFor(editableNode.ptr()))
         return;
 
     auto& rangeToCheck = shouldMarkGrammar ? *grammarRange : *spellingRange;
@@ -2900,8 +2901,8 @@
                 correctSpellcheckingPreservingTextCheckingParagraph(paragraph, rangeToReplace, replacement, { resultLocation, resultLength });
 
                 if (AXObjectCache* cache = document().existingAXObjectCache()) {
-                    if (Element* root = m_document.selection().selection().rootEditableElement())
-                        cache->postNotification(root, AXObjectCache::AXAutocorrectionOccured);
+                    if (auto root = makeRefPtr(m_document.selection().selection().rootEditableElement()))
+                        cache->postNotification(root.get(), AXObjectCache::AXAutocorrectionOccured);
                 }
 
                 // Skip all other results for the replaced text.
@@ -3670,8 +3671,7 @@
 static Vector<SimpleRange> scanForTelephoneNumbers(const SimpleRange& range)
 {
     // Don't scan for phone numbers inside editable regions.
-    auto& startNode = range.startContainer();
-    if (startNode.hasEditableStyle())
+    if (auto startNode = makeRef(range.startContainer()); startNode->hasEditableStyle())
         return { };
     auto text = plainText(range);
     Vector<SimpleRange> result;
@@ -3706,27 +3706,34 @@
         return;
 
     m_detectedTelephoneNumberRanges.clear();
+    
+    auto notifyController = makeScopeExit([&] {
+        if (auto* page = m_document.page())
+            page->servicesOverlayController().selectedTelephoneNumberRangesChanged();
+    });
 
-    auto& selection = m_document.selection();
-    if (selection.isRange()) {
-        if (auto selectedRange = selection.selection().firstRange()) {
-            // Extend the range a few characters in each direction to detect incompletely selected phone numbers.
-            constexpr unsigned charactersToExtend = 15;
-            if (auto extendedRange = extendSelection(*selectedRange, charactersToExtend)) {
-                for (auto& range : scanForTelephoneNumbers(*extendedRange)) {
-                    // FIXME: Why do we do this unconditionally instead of when only when it overlaps the selection?
-                    addMarker(range, DocumentMarker::TelephoneNumber);
+    auto selection = m_document.selection().selection();
+    if (!selection.isRange())
+        return;
 
-                    // Only consider ranges with a detected telephone number if they overlap with the selection.
-                    if (intersects<ComposedTree>(range, *selectedRange))
-                        m_detectedTelephoneNumberRanges.append(range);
-                }
-            }
-        }
+    auto selectedRange = selection.firstRange();
+    if (!selectedRange)
+        return;
+
+    // Extend the range a few characters in each direction to detect incompletely selected phone numbers.
+    constexpr unsigned charactersToExtend = 15;
+    auto extendedRange = extendSelection(*selectedRange, charactersToExtend);
+    if (!extendedRange)
+        return;
+
+    for (auto& range : scanForTelephoneNumbers(*extendedRange)) {
+        // FIXME: Why do we do this unconditionally instead of when only when it overlaps the selection?
+        addMarker(range, DocumentMarker::TelephoneNumber);
+
+        // Only consider ranges with a detected telephone number if they overlap with the selection.
+        if (intersects<ComposedTree>(range, *selectedRange))
+            m_detectedTelephoneNumberRanges.append(range);
     }
-
-    if (auto* page = m_document.page())
-        page->servicesOverlayController().selectedTelephoneNumberRangesChanged();
 }
 
 #endif // ENABLE(TELEPHONE_NUMBER_DETECTION) && !PLATFORM(IOS_FAMILY)
@@ -3812,14 +3819,18 @@
 #endif
 }
 
-static Node* findFirstMarkable(Node* node)
+static RefPtr<Node> findFirstMarkable(Node* startingNode)
 {
+    auto node = makeRefPtr(startingNode);
     while (node) {
-        if (!node->renderer())
-            return nullptr;
-        if (node->renderer()->isTextOrLineBreak())
-            return node;
-        if (is<Element>(*node) && downcast<Element>(*node).isTextField())
+        {
+            ScriptDisallowedScope::InMainThread scriptDisallowedScope;
+            if (!node->renderer())
+                return nullptr;
+            if (node->renderer()->isTextOrLineBreak())
+                return node;
+        }
+        if (is<HTMLTextFormControlElement>(*node) && downcast<Element>(*node).isTextField())
             node = downcast<HTMLTextFormControlElement>(*node).visiblePositionForIndex(1).deepEquivalent().deprecatedNode();
         else if (node->firstChild())
             node = node->firstChild();
@@ -3832,7 +3843,7 @@
 
 bool Editor::selectionStartHasMarkerFor(DocumentMarker::MarkerType markerType, int from, int length) const
 {
-    Node* node = findFirstMarkable(m_document.selection().selection().start().deprecatedNode());
+    auto node = findFirstMarkable(m_document.selection().selection().start().deprecatedNode());
     if (!node)
         return false;
 
@@ -3851,7 +3862,7 @@
 {
 #if USE(AUTOMATIC_TEXT_REPLACEMENT) && !PLATFORM(IOS_FAMILY)
     bool _onlyAllowsTextReplacement_ = false;
-    if (auto* host = rootEditableElement.shadowHost())
+    if (auto host = makeRefPtr(rootEditableElement.shadowHost()))
         _onlyAllowsTextReplacement_ = is<HTMLInputElement>(host) && downcast<HTMLInputElement>(*host).isSpellcheckDisabledExceptTextReplacement();
     if (onlyAllowsTextReplacement)
         textCheckingOptions = textCheckingOptions & TextCheckingType::Replacement;
@@ -3911,9 +3922,7 @@
 String Editor::stringForCandidateRequest() const
 {
     auto& selection = m_document.selection().selection();
-    auto range = selection.isCaret()
-        ? wordRangeFromPosition(selection.start())
-        : selection.toNormalizedRange();
+    auto range = selection.isCaret() ? wordRangeFromPosition(selection.start()) : selection.toNormalizedRange();
     if (!range)
         return { };
     if (!candidateWouldReplaceText(selection))
@@ -3989,17 +3998,21 @@
     return textLists;
 }
 
-FontAttributes Editor::fontAttributesAtSelectionStart() const
+FontAttributes Editor::fontAttributesAtSelectionStart()
 {
-    FontAttributes attributes;
-    Node* nodeToRemove = nullptr;
-    auto* style = styleForSelectionStart(m_document.frame(), nodeToRemove);
-    if (!style) {
+    RefPtr<Node> nodeToRemove;
+    auto nodeRemovalScope = WTF::makeScopeExit([&nodeToRemove]() {
         if (nodeToRemove)
             nodeToRemove->remove();
-        return attributes;
-    }
+    });
 
+    auto* style = styleForSelectionStart(nodeToRemove);
+    if (!style)
+        return { };
+
+    ScriptDisallowedScope::InMainThread scriptDisallowedScope;
+
+    FontAttributes attributes;
     platformFontAttributesAtSelectionStart(attributes, *style);
 
     // FIXME: for now, always report the colors after applying -apple-color-filter. In future not all clients
@@ -4081,9 +4094,6 @@
             attributes.hasUnderline = true;
     }
 
-    if (nodeToRemove)
-        nodeToRemove->remove();
-
     return attributes;
 }
 
@@ -4110,7 +4120,7 @@
     getPasteboardTypesAndDataForAttachment(element, additionalTypes, additionalData);
 #endif
 
-    if (auto* file = attachment->file())
+    if (auto file = makeRefPtr(attachment->file()))
         return { file->url(), platformContentTypeForBlobType(file->type()), file->name(), { }, WTFMove(additionalTypes), WTFMove(additionalData) };
 
     return { { }, { }, { }, attachment->uniqueIdentifier(), WTFMove(additionalTypes), WTFMove(additionalData) };
@@ -4253,53 +4263,58 @@
 }
 
 // FIXME: This figures out the current style by inserting a <span>!
-const RenderStyle* Editor::styleForSelectionStart(Frame* frame, Node*& nodeToRemove)
+const RenderStyle* Editor::styleForSelectionStart(RefPtr<Node>& nodeToRemove)
 {
     nodeToRemove = nullptr;
 
-    if (frame->selection().isNone())
+    if (document().selection().isNone())
         return nullptr;
 
-    Position position = adjustedSelectionStartForStyleComputation(frame->selection().selection());
+    Position position = adjustedSelectionStartForStyleComputation(document().selection().selection());
     if (!position.isCandidate() || position.isNull())
         return nullptr;
 
-    RefPtr<EditingStyle> typingStyle = frame->selection().typingStyle();
+    auto typingStyle = makeRefPtr(document().selection().typingStyle());
     if (!typingStyle || !typingStyle->style())
         return &position.deprecatedNode()->renderer()->style();
 
-    auto styleElement = HTMLSpanElement::create(*frame->document());
+    auto styleElement = HTMLSpanElement::create(document());
 
     String styleText = typingStyle->style()->asText() + " display: inline";
     styleElement->setAttribute(HTMLNames::styleAttr, styleText);
 
-    styleElement->appendChild(frame->document()->createEditingTextNode(emptyString()));
+    styleElement->appendChild(document().createEditingTextNode(emptyString()));
 
     auto positionNode = position.deprecatedNode();
-    if (!positionNode || !positionNode->parentNode() || positionNode->parentNode()->appendChild(styleElement).hasException())
+    ASSERT(positionNode);
+    auto parent = makeRefPtr(positionNode->parentNode());
+    if (!parent || parent->appendChild(styleElement.get()).hasException())
         return nullptr;
 
     nodeToRemove = styleElement.ptr();
-    
-    frame->document()->updateStyleIfNeeded();
+
+    document().updateStyleIfNeeded();
     return styleElement->renderer() ? &styleElement->renderer()->style() : nullptr;
 }
 
-const Font* Editor::fontForSelection(bool& hasMultipleFonts) const
+RefPtr<Font> Editor::fontForSelection(bool& hasMultipleFonts)
 {
     hasMultipleFonts = false;
 
     if (!m_document.selection().isRange()) {
-        Node* nodeToRemove;
-        auto* style = styleForSelectionStart(m_document.frame(), nodeToRemove); // sets nodeToRemove
-
-        const Font* font = nullptr;
-        if (style) {
-            font = &style->fontCascade().primaryFont();
-            if (nodeToRemove)
-                nodeToRemove->remove();
+        RefPtr<Node> nodeToRemove;
+        RefPtr<Font> font;
+        {
+            auto* style = styleForSelectionStart(nodeToRemove);
+            if (!style)
+                return nullptr;
+            ScriptDisallowedScope::InMainThread scriptDisallowedScope;
+            font = const_cast<Font*>(&style->fontCascade().primaryFont());
         }
 
+        if (nodeToRemove)
+            nodeToRemove->remove();
+
         return font;
     }
 
@@ -4313,7 +4328,9 @@
         return nullptr;
     range->start = *adjustedStart;
 
-    const Font* font = nullptr;
+    ScriptDisallowedScope::InMainThread scriptDisallowedScope;
+
+    RefPtr<Font> font;
     for (auto& node : intersectingNodes(*range)) {
         auto renderer = node.renderer();
         if (!renderer)
@@ -4320,7 +4337,7 @@
             continue;
         auto& primaryFont = renderer->style().fontCascade().primaryFont();
         if (!font)
-            font = &primaryFont;
+            font = const_cast<Font*>(&primaryFont);
         else if (font != &primaryFont) {
             hasMultipleFonts = true;
             break;

Modified: trunk/Source/WebCore/editing/Editor.h (276190 => 276191)


--- trunk/Source/WebCore/editing/Editor.h	2021-04-17 02:06:15 UTC (rev 276190)
+++ trunk/Source/WebCore/editing/Editor.h	2021-04-17 02:32:54 UTC (rev 276191)
@@ -442,7 +442,7 @@
     void clearMisspellingsAndBadGrammar(const VisibleSelection&);
     void markMisspellingsAndBadGrammar(const VisibleSelection&);
 
-    Element* findEventTargetFrom(const VisibleSelection& selection) const;
+    RefPtr<Element> findEventTargetFrom(const VisibleSelection&) const;
 
     WEBCORE_EXPORT String selectedText() const;
     String selectedTextForDataTransfer() const;
@@ -516,9 +516,9 @@
 
     RefPtr<DocumentFragment> webContentFromPasteboard(Pasteboard&, const SimpleRange& context, bool allowPlainText, bool& chosePlainText);
 
-    WEBCORE_EXPORT const Font* fontForSelection(bool& hasMultipleFonts) const;
-    WEBCORE_EXPORT static const RenderStyle* styleForSelectionStart(Frame* , Node *&nodeToRemove);
-    WEBCORE_EXPORT FontAttributes fontAttributesAtSelectionStart() const;
+    WEBCORE_EXPORT RefPtr<Font> fontForSelection(bool& hasMultipleFonts);
+    WEBCORE_EXPORT const RenderStyle* styleForSelectionStart(RefPtr<Node>& nodeToRemove);
+    WEBCORE_EXPORT FontAttributes fontAttributesAtSelectionStart();
 
 #if PLATFORM(COCOA)
     WEBCORE_EXPORT String stringSelectionForPasteboard();
@@ -605,7 +605,7 @@
 
     void editorUIUpdateTimerFired();
 
-    Element* findEventTargetFromSelection() const;
+    RefPtr<Element> findEventTargetFromSelection() const;
 
     bool unifiedTextCheckerEnabled() const;
 

Modified: trunk/Source/WebCore/page/DragController.cpp (276190 => 276191)


--- trunk/Source/WebCore/page/DragController.cpp	2021-04-17 02:06:15 UTC (rev 276190)
+++ trunk/Source/WebCore/page/DragController.cpp	2021-04-17 02:32:54 UTC (rev 276191)
@@ -526,7 +526,7 @@
 {
     ASSERT(m_page.dragCaretController().hasCaret());
     String text = m_page.dragCaretController().isContentRichlyEditable() ? emptyString() : dragData.asPlainText();
-    Element* target = innerFrame->editor().findEventTargetFrom(m_page.dragCaretController().caretPosition());
+    auto target = innerFrame->editor().findEventTargetFrom(m_page.dragCaretController().caretPosition());
     // FIXME: What guarantees target is not null?
     auto event = TextEvent::createForDrop(&innerFrame->windowProxy(), text);
     target->dispatchEvent(event);

Modified: trunk/Source/WebKit/ChangeLog (276190 => 276191)


--- trunk/Source/WebKit/ChangeLog	2021-04-17 02:06:15 UTC (rev 276190)
+++ trunk/Source/WebKit/ChangeLog	2021-04-17 02:32:54 UTC (rev 276191)
@@ -1,3 +1,17 @@
+2021-04-16  Ryosuke Niwa  <[email protected]>
+
+        Deploy Ref/RefPtr in Editor
+        https://bugs.webkit.org/show_bug.cgi?id=224708
+
+        Reviewed by Wenson Hsieh.
+
+        * WebProcess/WebPage/WebPage.cpp:
+        (WebKit::WebPage::editorState const):
+        * WebProcess/WebPage/ios/WebPageIOS.mm:
+        (WebKit::WebPage::requestAutocorrectionData):
+        * WebProcess/WebPage/mac/WebPageMac.mm:
+        (WebKit::WebPage::fontAtSelection):
+
 2021-04-16  Chris Dumez  <[email protected]>
 
         RemoteAudioDestinationProxy should not launch / relaunch the GPUProcess unless it is actually rendering

Modified: trunk/Source/WebKit/WebProcess/WebPage/WebPage.cpp (276190 => 276191)


--- trunk/Source/WebKit/WebProcess/WebPage/WebPage.cpp	2021-04-17 02:06:15 UTC (rev 276190)
+++ trunk/Source/WebKit/WebProcess/WebPage/WebPage.cpp	2021-04-17 02:32:54 UTC (rev 276191)
@@ -1193,7 +1193,7 @@
     }
 
     const VisibleSelection& selection = frame->selection().selection();
-    const Editor& editor = frame->editor();
+    auto& editor = frame->editor();
 
     result.transactionID = m_lastEditorStateTransactionID.increment();
     result.selectionIsNone = selection.isNone();

Modified: trunk/Source/WebKit/WebProcess/WebPage/ios/WebPageIOS.mm (276190 => 276191)


--- trunk/Source/WebKit/WebProcess/WebPage/ios/WebPageIOS.mm	2021-04-17 02:06:15 UTC (rev 276190)
+++ trunk/Source/WebKit/WebProcess/WebPage/ios/WebPageIOS.mm	2021-04-17 02:32:54 UTC (rev 276191)
@@ -2348,7 +2348,7 @@
 
     bool multipleFonts = false;
     CTFontRef font = nil;
-    if (auto* coreFont = frame.editor().fontForSelection(multipleFonts))
+    if (auto coreFont = frame.editor().fontForSelection(multipleFonts))
         font = coreFont->getCTFont();
 
     reply({ WTFMove(rootViewSelectionRects) , (__bridge UIFont *)font });

Modified: trunk/Source/WebKit/WebProcess/WebPage/mac/WebPageMac.mm (276190 => 276191)


--- trunk/Source/WebKit/WebProcess/WebPage/mac/WebPageMac.mm	2021-04-17 02:06:15 UTC (rev 276190)
+++ trunk/Source/WebKit/WebProcess/WebPage/mac/WebPageMac.mm	2021-04-17 02:32:54 UTC (rev 276191)
@@ -384,7 +384,7 @@
         return;
     }
 
-    auto* font = frame.editor().fontForSelection(selectionHasMultipleFonts);
+    auto font = frame.editor().fontForSelection(selectionHasMultipleFonts);
     if (!font) {
         completionHandler({ }, 0, false);
         return;

Modified: trunk/Source/WebKitLegacy/mac/ChangeLog (276190 => 276191)


--- trunk/Source/WebKitLegacy/mac/ChangeLog	2021-04-17 02:06:15 UTC (rev 276190)
+++ trunk/Source/WebKitLegacy/mac/ChangeLog	2021-04-17 02:32:54 UTC (rev 276191)
@@ -1,3 +1,17 @@
+2021-04-16  Ryosuke Niwa  <[email protected]>
+
+        Deploy Ref/RefPtr in Editor
+        https://bugs.webkit.org/show_bug.cgi?id=224708
+
+        Reviewed by Wenson Hsieh.
+
+        * WebView/WebFrame.mm:
+        (-[WebFrame fontForSelection:]):
+        * WebView/WebHTMLView.mm:
+        (-[WebHTMLView _updateFontPanel]):
+        * WebView/WebView.mm:
+        (-[WebView updateTextTouchBar]):
+
 2021-04-16  Wenson Hsieh  <[email protected]>
 
         [macOS] Refactor some webpage translation code

Modified: trunk/Source/WebKitLegacy/mac/WebView/WebFrame.mm (276190 => 276191)


--- trunk/Source/WebKitLegacy/mac/WebView/WebFrame.mm	2021-04-17 02:06:15 UTC (rev 276190)
+++ trunk/Source/WebKitLegacy/mac/WebView/WebFrame.mm	2021-04-17 02:32:54 UTC (rev 276191)
@@ -1825,9 +1825,8 @@
     bool multipleFonts = false;
     CTFontRef font = nil;
     if (_private->coreFrame) {
-        const WebCore::Font* fd = _private->coreFrame->editor().fontForSelection(multipleFonts);
-        if (fd)
-            font = fd->getCTFont();
+        if (auto coreFont = _private->coreFrame->editor().fontForSelection(multipleFonts))
+            font = coreFont->getCTFont();
     }
     
     if (hasMultipleFonts)

Modified: trunk/Source/WebKitLegacy/mac/WebView/WebHTMLView.mm (276190 => 276191)


--- trunk/Source/WebKitLegacy/mac/WebView/WebHTMLView.mm	2021-04-17 02:06:15 UTC (rev 276190)
+++ trunk/Source/WebKitLegacy/mac/WebView/WebHTMLView.mm	2021-04-17 02:32:54 UTC (rev 276191)
@@ -5741,8 +5741,8 @@
     NSFont *font = nil;
     RetainPtr<NSDictionary> attributes;
     if (auto* coreFrame = core([self _frame])) {
-        if (const WebCore::Font* fd = coreFrame->editor().fontForSelection(multipleFonts))
-            font = (NSFont *)fd->platformData().registeredFont();
+        if (auto coreFont = coreFrame->editor().fontForSelection(multipleFonts))
+            font = (NSFont *)coreFont->platformData().registeredFont();
         attributes = coreFrame->editor().fontAttributesAtSelectionStart().createDictionary();
     }
 

Modified: trunk/Source/WebKitLegacy/mac/WebView/WebView.mm (276190 => 276191)


--- trunk/Source/WebKitLegacy/mac/WebView/WebView.mm	2021-04-17 02:06:15 UTC (rev 276190)
+++ trunk/Source/WebKitLegacy/mac/WebView/WebView.mm	2021-04-17 02:32:54 UTC (rev 276191)
@@ -9477,8 +9477,8 @@
     if (webHTMLView._canEditRichly) {
         const VisibleSelection& selection = coreFrame->selection().selection();
         if (!selection.isNone()) {
-            Node* nodeToRemove;
-            if (auto* style = Editor::styleForSelectionStart(coreFrame, nodeToRemove)) {
+            RefPtr<Node> nodeToRemove;
+            if (auto* style = coreFrame->editor().styleForSelectionStart(nodeToRemove)) {
                 [_private->_textTouchBarItemController setTextIsBold:isFontWeightBold(style->fontCascade().weight())];
                 [_private->_textTouchBarItemController setTextIsItalic:isItalic(style->fontCascade().italic())];
 
@@ -9495,7 +9495,7 @@
 
                 [_private->_textTouchBarItemController setCurrentTextAlignment:nsTextAlignmentFromRenderStyle(style)];
 
-                HTMLElement* enclosingListElement = enclosingList(selection.start().deprecatedNode());
+                auto enclosingListElement = makeRefPtr(enclosingList(selection.start().deprecatedNode()));
                 if (enclosingListElement) {
                     if (is<HTMLUListElement>(*enclosingListElement))
                         [[_private->_textTouchBarItemController webTextListTouchBarViewController] setCurrentListType:WebListType::Unordered];
_______________________________________________
webkit-changes mailing list
[email protected]
https://lists.webkit.org/mailman/listinfo/webkit-changes

Reply via email to