Add variant of phone number parsing that use DocumentMarker in the current selection
authorbeidson@apple.com <beidson@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Mon, 31 Mar 2014 21:53:42 +0000 (21:53 +0000)
committerbeidson@apple.com <beidson@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Mon, 31 Mar 2014 21:53:42 +0000 (21:53 +0000)
<rdar://problem/16379566> and https://bugs.webkit.org/show_bug.cgi?id=130917

Reviewed by Darin Adler.

* dom/DocumentMarker.h:
(WebCore::DocumentMarker::AllMarkers::AllMarkers): Add a new TelephoneNumber document marker type.

* editing/Editor.cpp:
(WebCore::Editor::respondToChangedSelection):
(WebCore::Editor::scanSelectionForTelephoneNumbers): TextIterate over the selected range looking for numbers.
(WebCore::Editor::scanRangeForTelephoneNumbers): Scan the given range for a telephone number,
  adding the DocumentMarker to any that are found.
(WebCore::Editor::clearDataDetectedTelephoneNumbers):
* editing/Editor.h:

* html/parser/HTMLTreeBuilder.cpp:
(WebCore::HTMLTreeBuilder::processCharacterBufferForInBody): Only linkify on iOS.

* rendering/InlineTextBox.cpp:
(WebCore::InlineTextBox::paintTelephoneNumberMarker): Placeholder UI while the feature is developed.
(WebCore::InlineTextBox::paintDocumentMarkers):
* rendering/InlineTextBox.h:

* testing/Internals.cpp:
(WebCore::markerTypesFrom):

git-svn-id: https://svn.webkit.org/repository/webkit/trunk@166532 268f45cc-cd09-0410-ab3c-d52691b4dbfc

Source/WebCore/ChangeLog
Source/WebCore/dom/DocumentMarker.h
Source/WebCore/editing/Editor.cpp
Source/WebCore/editing/Editor.h
Source/WebCore/html/parser/HTMLTreeBuilder.cpp
Source/WebCore/rendering/InlineTextBox.cpp
Source/WebCore/rendering/InlineTextBox.h
Source/WebCore/testing/Internals.cpp

index 99899d2..2e3f026 100644 (file)
@@ -1,3 +1,32 @@
+2014-03-31  Brady Eidson  <beidson@apple.com>
+
+        Add variant of phone number parsing that use DocumentMarker in the current selection
+        <rdar://problem/16379566> and https://bugs.webkit.org/show_bug.cgi?id=130917
+
+        Reviewed by Darin Adler.
+
+        * dom/DocumentMarker.h:
+        (WebCore::DocumentMarker::AllMarkers::AllMarkers): Add a new TelephoneNumber document marker type.
+
+        * editing/Editor.cpp:
+        (WebCore::Editor::respondToChangedSelection):
+        (WebCore::Editor::scanSelectionForTelephoneNumbers): TextIterate over the selected range looking for numbers.
+        (WebCore::Editor::scanRangeForTelephoneNumbers): Scan the given range for a telephone number,
+          adding the DocumentMarker to any that are found.
+        (WebCore::Editor::clearDataDetectedTelephoneNumbers):
+        * editing/Editor.h:
+
+        * html/parser/HTMLTreeBuilder.cpp:
+        (WebCore::HTMLTreeBuilder::processCharacterBufferForInBody): Only linkify on iOS.
+
+        * rendering/InlineTextBox.cpp:
+        (WebCore::InlineTextBox::paintTelephoneNumberMarker): Placeholder UI while the feature is developed.
+        (WebCore::InlineTextBox::paintDocumentMarkers):
+        * rendering/InlineTextBox.h:
+
+        * testing/Internals.cpp:
+        (WebCore::markerTypesFrom):
+
 2014-03-31  Simon Fraser  <simon.fraser@apple.com>
 
         [iOS WK2] Hook up scroll events for accelerated overflow:scroll
index 480edbf..e9287ab 100644 (file)
@@ -71,10 +71,13 @@ public:
         // This marker indicates that the range of text spanned by the marker is entered by voice dictation,
         // and it has alternative text.
         DictationAlternatives = 1 << 9,
+#if ENABLE(TELEPHONE_NUMBER_DETECTION)
+        TelephoneNumber = 1 << 10
+#endif
 #if PLATFORM(IOS)
-        // FIXME: iOS has its own dictation marks. iOS should use OpenSource's.
-        DictationPhraseWithAlternatives = 1 << 10,
-        DictationResult = 1 << 11,
+        // FIXME: iOS should share the same Dictation marks as everyone else.
+        DictationPhraseWithAlternatives = 1 << 11,
+        DictationResult = 1 << 12,
 #endif
     };
 
@@ -98,9 +101,13 @@ public:
     public:
         AllMarkers()
 #if !PLATFORM(IOS)
+#if !ENABLE(TELEPHONE_NUMBER_DETECTION)
             : MarkerTypes(Spelling | Grammar | TextMatch | Replacement | CorrectionIndicator | RejectedCorrection | Autocorrected | SpellCheckingExemption | DeletedAutocorrection | DictationAlternatives)
 #else
-            : MarkerTypes(Spelling | Grammar | TextMatch | Replacement | CorrectionIndicator | RejectedCorrection | Autocorrected | SpellCheckingExemption | DeletedAutocorrection | DictationAlternatives | DictationPhraseWithAlternatives | DictationResult)
+            : MarkerTypes(Spelling | Grammar | TextMatch | Replacement | CorrectionIndicator | RejectedCorrection | Autocorrected | SpellCheckingExemption | DeletedAutocorrection | DictationAlternatives | TelephoneNumber)
+#endif // !ENABLE(TELEPHONE_NUMBER_DETECTION)
+#else
+            : MarkerTypes(Spelling | Grammar | TextMatch | Replacement | CorrectionIndicator | RejectedCorrection | Autocorrected | SpellCheckingExemption | DeletedAutocorrection | DictationAlternatives | TelephoneNumber | DictationPhraseWithAlternatives | DictationResult)
 #endif // !PLATFORM(IOS)
         {
         }
index 8344a02..371304c 100644 (file)
@@ -66,6 +66,7 @@
 #include "NodeTraversal.h"
 #include "Page.h"
 #include "Pasteboard.h"
+#include "Range.h"
 #include "RemoveFormatCommand.h"
 #include "RenderBlock.h"
 #include "RenderTextControl.h"
@@ -78,6 +79,7 @@
 #include "SpellChecker.h"
 #include "SpellingCorrectionCommand.h"
 #include "StyleProperties.h"
+#include "TelephoneNumberDetector.h"
 #include "Text.h"
 #include "TextCheckerClient.h"
 #include "TextCheckingHelper.h"
@@ -3314,6 +3316,11 @@ void Editor::respondToChangedSelection(const VisibleSelection&, FrameSelection::
 
     if (client())
         client()->respondToChangedSelection(&m_frame);
+
+#if ENABLE(TELEPHONE_NUMBER_DETECTION) && !PLATFORM(IOS)
+    scanSelectionForTelephoneNumbers();
+#endif
+
     setStartNewKillRingSequence(true);
 
     if (m_editorUIUpdateTimer.isActive())
@@ -3326,6 +3333,70 @@ void Editor::respondToChangedSelection(const VisibleSelection&, FrameSelection::
     m_editorUIUpdateTimer.startOneShot(0);
 }
 
+#if ENABLE(TELEPHONE_NUMBER_DETECTION) && !PLATFORM(IOS)
+void Editor::scanSelectionForTelephoneNumbers()
+{
+    if (!TelephoneNumberDetector::isSupported())
+        return;
+
+    if (!m_frame.document())
+        return;
+
+    clearDataDetectedTelephoneNumbers();
+
+    RefPtr<Range> selectedRange = m_frame.selection().toNormalizedRange();
+    if (!selectedRange || selectedRange->startOffset() == selectedRange->endOffset())
+        return;
+
+    // FIXME: This won't work if a phone number spans multiple chunks of text from the perspective of the TextIterator
+    // (By a style change, image, line break, etc.)
+    // On idea to handle this would be a model like text search that uses a rotating window.
+    for (TextIterator textChunk(selectedRange.get()); !textChunk.atEnd(); textChunk.advance()) {
+        // TextIterator is supposed to never returns a Range that spans multiple Nodes.
+        ASSERT(textChunk.range()->startContainer() == textChunk.range()->endContainer());
+
+        scanRangeForTelephoneNumbers(*textChunk.range(), textChunk.text());
+    }
+}
+
+void Editor::scanRangeForTelephoneNumbers(Range& range, const StringView& stringView)
+{
+    // relativeStartPosition and relativeEndPosition are the endpoints of the phone number range,
+    // relative to the scannerPosition
+    unsigned length = stringView.length();
+    unsigned scannerPosition = 0;
+    int relativeStartPosition = 0;
+    int relativeEndPosition = 0;
+
+    auto characters = stringView.upconvertedCharacters();
+
+    while (scannerPosition < length && TelephoneNumberDetector::find(&characters[scannerPosition], length - scannerPosition, &relativeStartPosition, &relativeEndPosition)) {
+        // The convention in the Data Detectors framework is that the end position is the first character NOT in the phone number
+        // (that is, the length of the range is relativeEndPosition - relativeStartPosition). So substract 1 to get the same
+        // convention as the old WebCore phone number parser (so that the rest of the code is still valid if we want to go back
+        // to the old parser).
+        --relativeEndPosition;
+
+        ASSERT(scannerPosition + relativeEndPosition < length);
+
+        // It doesn't make sense to add the document marker to a match that's not in a text node.
+        if (!range.startContainer()->isTextNode())
+            continue;
+
+        range.ownerDocument().markers().addMarkerToNode(range.startContainer(), range.startOffset() + scannerPosition + relativeStartPosition, relativeEndPosition - relativeStartPosition + 1, DocumentMarker::TelephoneNumber);
+
+        scannerPosition += relativeEndPosition + 1;
+    }
+}
+
+void Editor::clearDataDetectedTelephoneNumbers()
+{
+    m_frame.document()->markers().removeMarkers(DocumentMarker::TelephoneNumber);
+
+    // FIXME: Do other UI cleanup here once we have other UI.
+}
+#endif // ENABLE(TELEPHONE_NUMBER_DETECTION) && !PLATFORM(IOS)
+
 void Editor::updateEditorUINowIfScheduled()
 {
     if (!m_editorUIUpdateTimer.isActive())
index 4c9ee07..922fcec 100644 (file)
@@ -473,6 +473,12 @@ private:
 
     bool unifiedTextCheckerEnabled() const;
 
+#if ENABLE(TELEPHONE_NUMBER_DETECTION) && !PLATFORM(IOS)
+    void scanSelectionForTelephoneNumbers();
+    void scanRangeForTelephoneNumbers(Range&, const StringView&);
+    void clearDataDetectedTelephoneNumbers();
+#endif
+
 #if PLATFORM(COCOA)
     PassRefPtr<SharedBuffer> selectionInWebArchiveFormat();
     PassRefPtr<Range> adjustedSelectionRange();
index 0e4ebfb..40144f8 100644 (file)
@@ -2305,7 +2305,7 @@ void HTMLTreeBuilder::processCharacter(AtomicHTMLToken* token)
 }
 
 // FIXME: Extract the following iOS-specific code into a separate file.
-#if ENABLE(TELEPHONE_NUMBER_DETECTION)
+#if ENABLE(TELEPHONE_NUMBER_DETECTION) && PLATFORM(IOS)
 // From the string 4089961010, creates a link of the form <a href="tel:4089961010">4089961010</a> and inserts it.
 void HTMLTreeBuilder::insertPhoneNumberLink(const String& string)
 {
@@ -2389,7 +2389,7 @@ static inline bool shouldParseTelephoneNumbersInNode(const ContainerNode& node)
     } while (currentNode);
     return true;
 }
-#endif
+#endif // ENABLE(TELEPHONE_NUMBER_DETECTION) && PLATFORM(IOS)
 
 void HTMLTreeBuilder::processCharacterBuffer(ExternalCharacterTokenBuffer& buffer)
 {
@@ -2566,7 +2566,7 @@ void HTMLTreeBuilder::processCharacterBufferForInBody(ExternalCharacterTokenBuff
 {
     m_tree.reconstructTheActiveFormattingElements();
     String characters = buffer.takeRemaining();
-#if ENABLE(TELEPHONE_NUMBER_DETECTION)
+#if ENABLE(TELEPHONE_NUMBER_DETECTION) && PLATFORM(IOS)
     if (!isParsingFragment() && m_tree.isTelephoneNumberParsingEnabled() && shouldParseTelephoneNumbersInNode(*m_tree.currentNode()) && TelephoneNumberDetector::isSupported())
         linkifyPhoneNumbers(characters);
     else
index 2a3e13a..566dceb 100644 (file)
@@ -1248,6 +1248,33 @@ void InlineTextBox::paintTextMatchMarker(GraphicsContext* pt, const FloatPoint&
     }
 }
 
+#if ENABLE(TELEPHONE_NUMBER_DETECTION)
+void InlineTextBox::paintTelephoneNumberMarker(GraphicsContext* ctx, const FloatPoint& boxOrigin, DocumentMarker* marker, const RenderStyle& style, const Font& font)
+{
+    // FIXME: This is placeholder UI for development of the feature.
+
+    int startPosition = std::max<int>(marker->startOffset() - m_start, 0);
+    int endPosition = std::min<int>(marker->endOffset() - m_start, m_len);
+
+    if (m_truncation != cNoTruncation)
+        endPosition = std::min<int>(endPosition, m_truncation);
+
+    int deltaY = renderer().style().isFlippedLinesWritingMode() ? selectionBottom() - logicalBottom() : logicalTop() - selectionTop();
+    int selHeight = selectionHeight();
+    FloatPoint startPoint(boxOrigin.x(), boxOrigin.y() - deltaY);
+    TextRun run = constructTextRun(style, font);
+
+    IntRect markerRect = enclosingIntRect(font.selectionRectForText(run, startPoint, selHeight, startPosition, endPosition));
+
+    computeRectForReplacementMarker(marker, style, font);
+
+    Path outline;
+    outline.addRoundedRect(markerRect, FloatSize(4, 4));
+    ctx->setFillColor(Color(150, 150, 150, 255), ColorSpaceDeviceRGB);
+    ctx->fillPath(outline);
+}
+#endif // ENABLE(TELEPHONE_NUMBER_DETECTION)
+
 void InlineTextBox::computeRectForReplacementMarker(DocumentMarker* marker, const RenderStyle& style, const Font& font)
 {
     // Replacement markers are not actually drawn, but their rects need to be computed for hit testing.
@@ -1293,6 +1320,9 @@ void InlineTextBox::paintDocumentMarkers(GraphicsContext* pt, const FloatPoint&
                     continue;
                 break;
             case DocumentMarker::TextMatch:
+#if ENABLE(TELEPHONE_NUMBER_DETECTION)
+            case DocumentMarker::TelephoneNumber:
+#endif
                 if (!background)
                     continue;
                 break;
@@ -1331,6 +1361,11 @@ void InlineTextBox::paintDocumentMarkers(GraphicsContext* pt, const FloatPoint&
             case DocumentMarker::Replacement:
                 computeRectForReplacementMarker(marker, style, font);
                 break;
+#if ENABLE(TELEPHONE_NUMBER_DETECTION)
+            case DocumentMarker::TelephoneNumber:
+                paintTelephoneNumberMarker(pt, boxOrigin, marker, style, font);
+                break;
+#endif
             default:
                 ASSERT_NOT_REACHED();
         }
index 577521a..9359287 100644 (file)
@@ -173,6 +173,11 @@ private:
     void paintSelection(GraphicsContext*, const FloatPoint& boxOrigin, const RenderStyle&, const Font&, Color textColor);
     void paintDocumentMarker(GraphicsContext*, const FloatPoint& boxOrigin, DocumentMarker*, const RenderStyle&, const Font&, bool grammar);
     void paintTextMatchMarker(GraphicsContext*, const FloatPoint& boxOrigin, DocumentMarker*, const RenderStyle&, const Font&);
+
+#if ENABLE(TELEPHONE_NUMBER_DETECTION)
+    void paintTelephoneNumberMarker(GraphicsContext*, const FloatPoint& boxOrigin, DocumentMarker*, const RenderStyle&, const Font&);
+#endif
+
     void computeRectForReplacementMarker(DocumentMarker*, const RenderStyle&, const Font&);
 
     TextRun::ExpansionBehavior expansionBehavior() const
index 3affc7b..cfe8164 100644 (file)
@@ -245,6 +245,10 @@ static bool markerTypesFrom(const String& markerType, DocumentMarker::MarkerType
         result =  DocumentMarker::DeletedAutocorrection;
     else if (equalIgnoringCase(markerType, "DictationAlternatives"))
         result =  DocumentMarker::DictationAlternatives;
+#if ENABLE(TELEPHONE_NUMBER_DETECTION)
+    else if (equalIgnoringCase(markerType, "TelephoneNumber"))
+        result =  DocumentMarker::TelephoneNumber;
+#endif
     else
         return false;