9f99b4be5ce896a15b8e34f70f8904bee907e5e7
[WebKit-https.git] / Source / WebKit / WebProcess / WebPage / ios / WebPageIOS.mm
1 /*
2  * Copyright (C) 2012-2018 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #import "config.h"
27 #import "WebPage.h"
28
29 #if PLATFORM(IOS_FAMILY)
30
31 #import "AccessibilityIOS.h"
32 #import "AssistedNodeInformation.h"
33 #import "DataReference.h"
34 #import "DrawingArea.h"
35 #import "EditingRange.h"
36 #import "EditorState.h"
37 #import "GestureTypes.h"
38 #import "InteractionInformationAtPosition.h"
39 #import "Logging.h"
40 #import "NativeWebKeyboardEvent.h"
41 #import "PluginView.h"
42 #import "PrintInfo.h"
43 #import "RemoteLayerTreeDrawingArea.h"
44 #import "SandboxUtilities.h"
45 #import "UIKitSPI.h"
46 #import "UserData.h"
47 #import "VisibleContentRectUpdateInfo.h"
48 #import "WKAccessibilityWebPageObjectIOS.h"
49 #import "WebChromeClient.h"
50 #import "WebCoreArgumentCoders.h"
51 #import "WebFrame.h"
52 #import "WebImage.h"
53 #import "WebPageProxyMessages.h"
54 #import "WebPreviewLoaderClient.h"
55 #import "WebProcess.h"
56 #import <CoreText/CTFont.h>
57 #import <WebCore/Autofill.h>
58 #import <WebCore/AutofillElements.h>
59 #import <WebCore/Chrome.h>
60 #import <WebCore/DataDetection.h>
61 #import <WebCore/DiagnosticLoggingClient.h>
62 #import <WebCore/DiagnosticLoggingKeys.h>
63 #import <WebCore/DragController.h>
64 #import <WebCore/Editing.h>
65 #import <WebCore/Editor.h>
66 #import <WebCore/Element.h>
67 #import <WebCore/ElementAncestorIterator.h>
68 #import <WebCore/EventHandler.h>
69 #import <WebCore/File.h>
70 #import <WebCore/FloatQuad.h>
71 #import <WebCore/FocusController.h>
72 #import <WebCore/Frame.h>
73 #import <WebCore/FrameLoaderClient.h>
74 #import <WebCore/FrameView.h>
75 #import <WebCore/GeometryUtilities.h>
76 #import <WebCore/HTMLAreaElement.h>
77 #import <WebCore/HTMLAttachmentElement.h>
78 #import <WebCore/HTMLBodyElement.h>
79 #import <WebCore/HTMLElement.h>
80 #import <WebCore/HTMLElementTypeHelpers.h>
81 #import <WebCore/HTMLFormElement.h>
82 #import <WebCore/HTMLImageElement.h>
83 #import <WebCore/HTMLInputElement.h>
84 #import <WebCore/HTMLOptGroupElement.h>
85 #import <WebCore/HTMLOptionElement.h>
86 #import <WebCore/HTMLParserIdioms.h>
87 #import <WebCore/HTMLSelectElement.h>
88 #import <WebCore/HTMLTextAreaElement.h>
89 #import <WebCore/HTMLTextFormControlElement.h>
90 #import <WebCore/HistoryItem.h>
91 #import <WebCore/HitTestResult.h>
92 #import <WebCore/InputMode.h>
93 #import <WebCore/KeyboardEvent.h>
94 #import <WebCore/LibWebRTCProvider.h>
95 #import <WebCore/MediaSessionManagerIOS.h>
96 #import <WebCore/Node.h>
97 #import <WebCore/NodeList.h>
98 #import <WebCore/NotImplemented.h>
99 #import <WebCore/Page.h>
100 #import <WebCore/Pasteboard.h>
101 #import <WebCore/PlatformKeyboardEvent.h>
102 #import <WebCore/PlatformMouseEvent.h>
103 #import <WebCore/RenderBlock.h>
104 #import <WebCore/RenderImage.h>
105 #import <WebCore/RenderThemeIOS.h>
106 #import <WebCore/RenderView.h>
107 #import <WebCore/RuntimeApplicationChecks.h>
108 #import <WebCore/Settings.h>
109 #import <WebCore/SharedBuffer.h>
110 #import <WebCore/StyleProperties.h>
111 #import <WebCore/TextIndicator.h>
112 #import <WebCore/TextIterator.h>
113 #import <WebCore/VisibleUnits.h>
114 #import <WebCore/WKContentObservation.h>
115 #import <WebCore/WebEvent.h>
116 #import <wtf/MathExtras.h>
117 #import <wtf/MemoryPressureHandler.h>
118 #import <wtf/SetForScope.h>
119 #import <wtf/SoftLinking.h>
120 #import <wtf/cocoa/Entitlements.h>
121 #import <wtf/text/TextStream.h>
122
123 #if ENABLE(MEDIA_STREAM)
124 #import "CelestialSPI.h"
125 SOFT_LINK_PRIVATE_FRAMEWORK_OPTIONAL(Celestial)
126 SOFT_LINK_CLASS_OPTIONAL(Celestial, AVSystemController)
127 SOFT_LINK_CONSTANT_MAY_FAIL(Celestial, AVSystemController_PIDToInheritApplicationStateFrom, NSString *)
128 #endif
129
130 namespace WebKit {
131 using namespace WebCore;
132
133 const int blockSelectionStartWidth = 100;
134 const int blockSelectionStartHeight = 100;
135
136 void WebPage::platformInitialize()
137 {
138     platformInitializeAccessibility();
139 }
140
141 void WebPage::platformDetach()
142 {
143     [m_mockAccessibilityElement setWebPage:nullptr];
144 }
145     
146 void WebPage::platformInitializeAccessibility()
147 {
148     m_mockAccessibilityElement = adoptNS([[WKAccessibilityWebPageObject alloc] init]);
149     [m_mockAccessibilityElement setWebPage:this];
150     
151     NSData *remoteToken = newAccessibilityRemoteToken([NSUUID UUID]);
152     IPC::DataReference dataToken = IPC::DataReference(reinterpret_cast<const uint8_t*>([remoteToken bytes]), [remoteToken length]);
153     send(Messages::WebPageProxy::RegisterWebProcessAccessibilityToken(dataToken));
154 }
155
156 static void computeEditableRootHasContentAndPlainText(const VisibleSelection& selection, EditorState::PostLayoutData& data)
157 {
158     data.hasContent = false;
159     data.hasPlainText = false;
160     if (!selection.isContentEditable())
161         return;
162
163     if (data.selectedTextLength || data.characterAfterSelection || data.characterBeforeSelection || data.twoCharacterBeforeSelection) {
164         // If any of these variables have been previously set, the editable root must have plain text content, so we can bail from the remainder of the check.
165         data.hasContent = true;
166         data.hasPlainText = true;
167         return;
168     }
169
170     auto* root = selection.rootEditableElement();
171     if (!root)
172         return;
173
174     auto startInEditableRoot = firstPositionInNode(root);
175     data.hasContent = root->hasChildNodes() && !isEndOfEditableOrNonEditableContent(startInEditableRoot);
176     data.hasPlainText = data.hasContent && hasAnyPlainText(Range::create(root->document(), VisiblePosition { startInEditableRoot }, VisiblePosition { lastPositionInNode(root) }));
177 }
178
179 void WebPage::platformEditorState(Frame& frame, EditorState& result, IncludePostLayoutDataHint shouldIncludePostLayoutData) const
180 {
181     if (frame.editor().hasComposition()) {
182         RefPtr<Range> compositionRange = frame.editor().compositionRange();
183         Vector<WebCore::SelectionRect> compositionRects;
184         if (compositionRange) {
185             compositionRange->collectSelectionRects(compositionRects);
186             if (compositionRects.size())
187                 result.firstMarkedRect = compositionRects[0].rect();
188             if (compositionRects.size() > 1)
189                 result.lastMarkedRect = compositionRects.last().rect();
190             else
191                 result.lastMarkedRect = result.firstMarkedRect;
192             result.markedText = plainTextReplacingNoBreakSpace(compositionRange.get());
193         }
194     }
195
196     // We only set the remaining EditorState entries if layout is done as a performance optimization
197     // to avoid the need to force a synchronous layout here to compute these entries. If we
198     // have a composition or are using a hardware keyboard then we send the full editor state
199     // immediately so that the UIProcess can update UI, including the position of the caret.
200     bool needsLayout = !frame.view() || frame.view()->needsLayout();
201     bool requiresPostLayoutData = frame.editor().hasComposition();
202 #if !PLATFORM(IOSMAC)
203     requiresPostLayoutData |= [UIKeyboard isInHardwareKeyboardMode];
204 #endif
205     if (shouldIncludePostLayoutData == IncludePostLayoutDataHint::No && needsLayout && !requiresPostLayoutData) {
206         result.isMissingPostLayoutData = true;
207         return;
208     }
209
210     auto& postLayoutData = result.postLayoutData();
211     FrameView* view = frame.view();
212     const VisibleSelection& selection = frame.selection().selection();
213     postLayoutData.isStableStateUpdate = m_isInStableState;
214     bool startNodeIsInsideFixedPosition = false;
215     bool endNodeIsInsideFixedPosition = false;
216     if (selection.isCaret()) {
217         postLayoutData.caretRectAtStart = view->contentsToRootView(frame.selection().absoluteCaretBounds(&startNodeIsInsideFixedPosition));
218         endNodeIsInsideFixedPosition = startNodeIsInsideFixedPosition;
219         postLayoutData.caretRectAtEnd = postLayoutData.caretRectAtStart;
220         // FIXME: The following check should take into account writing direction.
221         postLayoutData.isReplaceAllowed = result.isContentEditable && atBoundaryOfGranularity(selection.start(), WordGranularity, DirectionForward);
222         postLayoutData.wordAtSelection = plainTextReplacingNoBreakSpace(wordRangeFromPosition(selection.start()).get());
223         if (selection.isContentEditable())
224             charactersAroundPosition(selection.start(), postLayoutData.characterAfterSelection, postLayoutData.characterBeforeSelection, postLayoutData.twoCharacterBeforeSelection);
225     } else if (selection.isRange()) {
226         postLayoutData.caretRectAtStart = view->contentsToRootView(VisiblePosition(selection.start()).absoluteCaretBounds(&startNodeIsInsideFixedPosition));
227         postLayoutData.caretRectAtEnd = view->contentsToRootView(VisiblePosition(selection.end()).absoluteCaretBounds(&endNodeIsInsideFixedPosition));
228         RefPtr<Range> selectedRange = selection.toNormalizedRange();
229         String selectedText;
230         if (selectedRange) {
231             selectedRange->collectSelectionRects(postLayoutData.selectionRects);
232             convertSelectionRectsToRootView(view, postLayoutData.selectionRects);
233             selectedText = plainTextReplacingNoBreakSpace(selectedRange.get(), TextIteratorDefaultBehavior, true);
234             postLayoutData.selectedTextLength = selectedText.length();
235             const int maxSelectedTextLength = 200;
236             if (selectedText.length() <= maxSelectedTextLength)
237                 postLayoutData.wordAtSelection = selectedText;
238         }
239         // FIXME: We should disallow replace when the string contains only CJ characters.
240         postLayoutData.isReplaceAllowed = result.isContentEditable && !result.isInPasswordField && !selectedText.isAllSpecialCharacters<isHTMLSpace>();
241     }
242     postLayoutData.insideFixedPosition = startNodeIsInsideFixedPosition || endNodeIsInsideFixedPosition;
243     if (!selection.isNone()) {
244         if (m_assistedNode && m_assistedNode->renderer()) {
245             postLayoutData.selectionClipRect = view->contentsToRootView(m_assistedNode->renderer()->absoluteBoundingBoxRect());
246             postLayoutData.caretColor = m_assistedNode->renderer()->style().caretColor();
247             postLayoutData.elementIsTransparent = m_assistedNode->renderer()->isTransparentRespectingParentFrames();
248         }
249         computeEditableRootHasContentAndPlainText(selection, postLayoutData);
250     }
251 }
252
253 FloatSize WebPage::screenSize() const
254 {
255     return m_screenSize;
256 }
257
258 FloatSize WebPage::availableScreenSize() const
259 {
260     return m_availableScreenSize;
261 }
262
263 FloatSize WebPage::overrideScreenSize() const
264 {
265     return m_overrideScreenSize;
266 }
267
268 void WebPage::didReceiveMobileDocType(bool isMobileDoctype)
269 {
270     resetViewportDefaultConfiguration(m_mainFrame.get(), isMobileDoctype);
271 }
272
273 void WebPage::savePageState(HistoryItem& historyItem)
274 {
275     historyItem.setScaleIsInitial(!m_userHasChangedPageScaleFactor);
276     historyItem.setMinimumLayoutSizeInScrollViewCoordinates(m_viewportConfiguration.minimumLayoutSize());
277     historyItem.setContentSize(m_viewportConfiguration.contentsSize());
278 }
279
280 static double scaleAfterViewportWidthChange(double currentScale, bool userHasChangedPageScaleFactor, const ViewportConfiguration& viewportConfiguration, float unobscuredWidthInScrollViewCoordinates, const IntSize& newContentSize, const IntSize& oldContentSize, float visibleHorizontalFraction)
281 {
282     double scale;
283     if (!userHasChangedPageScaleFactor)
284         scale = viewportConfiguration.initialScale();
285     else
286         scale = std::max(std::min(currentScale, viewportConfiguration.maximumScale()), viewportConfiguration.minimumScale());
287
288     LOG(VisibleRects, "scaleAfterViewportWidthChange getting scale %.2f", scale);
289
290     if (userHasChangedPageScaleFactor) {
291         // When the content size changes, we keep the same relative horizontal content width in view, otherwise we would
292         // end up zoomed too far in landscape->portrait, and too close in portrait->landscape.
293         double widthToKeepInView = visibleHorizontalFraction * newContentSize.width();
294         double newScale = unobscuredWidthInScrollViewCoordinates / widthToKeepInView;
295         scale = std::max(std::min(newScale, viewportConfiguration.maximumScale()), viewportConfiguration.minimumScale());
296     }
297     return scale;
298 }
299
300 static FloatPoint relativeCenterAfterContentSizeChange(const FloatRect& originalContentRect, IntSize oldContentSize, IntSize newContentSize)
301 {
302     // If the content size has changed, keep the same relative position.
303     FloatPoint oldContentCenter = originalContentRect.center();
304     float relativeHorizontalPosition = oldContentCenter.x() / oldContentSize.width();
305     float relativeVerticalPosition =  oldContentCenter.y() / oldContentSize.height();
306     return FloatPoint(relativeHorizontalPosition * newContentSize.width(), relativeVerticalPosition * newContentSize.height());
307 }
308
309 static inline FloatRect adjustExposedRectForNewScale(const FloatRect& exposedRect, double exposedRectScale, double newScale)
310 {
311     if (exposedRectScale == newScale)
312         return exposedRect;
313
314     float horizontalChange = exposedRect.width() * exposedRectScale / newScale - exposedRect.width();
315     float verticalChange = exposedRect.height() * exposedRectScale / newScale - exposedRect.height();
316
317     auto adjustedRect = exposedRect;
318     adjustedRect.inflate({ horizontalChange / 2, verticalChange / 2 });
319     return adjustedRect;
320 }
321
322 void WebPage::restorePageState(const HistoryItem& historyItem)
323 {
324     // When a HistoryItem is cleared, its scale factor and scroll point are set to zero. We should not try to restore the other
325     // parameters in those conditions.
326     if (!historyItem.pageScaleFactor()) {
327         send(Messages::WebPageProxy::CouldNotRestorePageState());
328         return;
329     }
330
331     // We can restore the exposed rect and scale, but we cannot touch the scroll position since the obscured insets
332     // may be changing in the UIProcess. The UIProcess can update the position from the information we send and will then
333     // scroll to the correct position through a regular VisibleContentRectUpdate.
334
335     m_userHasChangedPageScaleFactor = !historyItem.scaleIsInitial();
336
337     FrameView& frameView = *m_page->mainFrame().view();
338
339     FloatSize currentMinimumLayoutSizeInScrollViewCoordinates = m_viewportConfiguration.minimumLayoutSize();
340     if (historyItem.minimumLayoutSizeInScrollViewCoordinates() == currentMinimumLayoutSizeInScrollViewCoordinates) {
341         float boundedScale = std::min<float>(m_viewportConfiguration.maximumScale(), std::max<float>(m_viewportConfiguration.minimumScale(), historyItem.pageScaleFactor()));
342         scalePage(boundedScale, IntPoint());
343
344         Optional<FloatPoint> scrollPosition;
345         if (historyItem.shouldRestoreScrollPosition()) {
346             m_drawingArea->setExposedContentRect(historyItem.exposedContentRect());
347             scrollPosition = FloatPoint(historyItem.scrollPosition());
348         }
349         send(Messages::WebPageProxy::RestorePageState(scrollPosition, frameView.scrollOrigin(), historyItem.obscuredInsets(), boundedScale));
350     } else {
351         IntSize oldContentSize = historyItem.contentSize();
352         IntSize newContentSize = frameView.contentsSize();
353         double visibleHorizontalFraction = static_cast<float>(historyItem.unobscuredContentRect().width()) / oldContentSize.width();
354
355         double newScale = scaleAfterViewportWidthChange(historyItem.pageScaleFactor(), !historyItem.scaleIsInitial(), m_viewportConfiguration, currentMinimumLayoutSizeInScrollViewCoordinates.width(), newContentSize, oldContentSize, visibleHorizontalFraction);
356
357         Optional<FloatPoint> newCenter;
358         if (historyItem.shouldRestoreScrollPosition()) {
359             if (!oldContentSize.isEmpty() && !newContentSize.isEmpty() && newContentSize != oldContentSize)
360                 newCenter = relativeCenterAfterContentSizeChange(historyItem.unobscuredContentRect(), oldContentSize, newContentSize);
361             else
362                 newCenter = FloatRect(historyItem.unobscuredContentRect()).center();
363         }
364
365         scalePage(newScale, IntPoint());
366         send(Messages::WebPageProxy::RestorePageCenterAndScale(newCenter, newScale));
367     }
368 }
369
370 double WebPage::minimumPageScaleFactor() const
371 {
372     if (!m_viewportConfiguration.allowsUserScaling())
373         return m_page->pageScaleFactor();
374     return m_viewportConfiguration.minimumScale();
375 }
376
377 double WebPage::maximumPageScaleFactor() const
378 {
379     if (!m_viewportConfiguration.allowsUserScaling())
380         return m_page->pageScaleFactor();
381     return m_viewportConfiguration.maximumScale();
382 }
383
384 double WebPage::maximumPageScaleFactorIgnoringAlwaysScalable() const
385 {
386     if (!m_viewportConfiguration.allowsUserScalingIgnoringAlwaysScalable())
387         return m_page->pageScaleFactor();
388     return m_viewportConfiguration.maximumScaleIgnoringAlwaysScalable();
389 }
390
391 bool WebPage::allowsUserScaling() const
392 {
393     return m_viewportConfiguration.allowsUserScaling();
394 }
395
396 bool WebPage::handleEditingKeyboardEvent(KeyboardEvent* event)
397 {
398     auto* platformEvent = event->underlyingPlatformEvent();
399     if (!platformEvent)
400         return false;
401
402     // FIXME: Interpret the event immediately upon receiving it in UI process, without sending to WebProcess first.
403     bool eventWasHandled = false;
404     bool sendResult = WebProcess::singleton().parentProcessConnection()->sendSync(Messages::WebPageProxy::InterpretKeyEvent(editorState(), platformEvent->type() == PlatformKeyboardEvent::Char),
405         Messages::WebPageProxy::InterpretKeyEvent::Reply(eventWasHandled), m_pageID);
406     return sendResult && eventWasHandled;
407 }
408
409 bool WebPage::parentProcessHasServiceWorkerEntitlement() const
410 {
411     static bool hasEntitlement = WTF::hasEntitlement(WebProcess::singleton().parentProcessConnection()->xpcConnection(), "com.apple.developer.WebKit.ServiceWorkers");
412     return hasEntitlement;
413 }
414
415 void WebPage::sendComplexTextInputToPlugin(uint64_t, const String&)
416 {
417     notImplemented();
418 }
419
420 bool WebPage::performNonEditingBehaviorForSelector(const String&, WebCore::KeyboardEvent*)
421 {
422     notImplemented();
423     return false;
424 }
425
426 bool WebPage::performDefaultBehaviorForKeyEvent(const WebKeyboardEvent&)
427 {
428     notImplemented();
429     return false;
430 }
431
432 void WebPage::getSelectionContext(CallbackID callbackID)
433 {
434     Frame& frame = m_page->focusController().focusedOrMainFrame();
435     if (!frame.selection().isRange()) {
436         send(Messages::WebPageProxy::SelectionContextCallback(String(), String(), String(), callbackID));
437         return;
438     }
439     const int selectionExtendedContextLength = 350;
440     
441     String selectedText = plainTextReplacingNoBreakSpace(frame.selection().selection().toNormalizedRange().get());
442     String textBefore = plainTextReplacingNoBreakSpace(rangeExpandedByCharactersInDirectionAtWordBoundary(frame.selection().selection().start(), selectionExtendedContextLength, DirectionBackward).get(), TextIteratorDefaultBehavior, true);
443     String textAfter = plainTextReplacingNoBreakSpace(rangeExpandedByCharactersInDirectionAtWordBoundary(frame.selection().selection().end(), selectionExtendedContextLength, DirectionForward).get(), TextIteratorDefaultBehavior, true);
444
445     send(Messages::WebPageProxy::SelectionContextCallback(selectedText, textBefore, textAfter, callbackID));
446 }
447
448 NSObject *WebPage::accessibilityObjectForMainFramePlugin()
449 {
450     if (!m_page)
451         return nil;
452     
453     if (auto* pluginView = pluginViewForFrame(&m_page->mainFrame()))
454         return pluginView->accessibilityObject();
455     
456     return nil;
457 }
458     
459 void WebPage::registerUIProcessAccessibilityTokens(const IPC::DataReference& elementToken, const IPC::DataReference&)
460 {
461     NSData *elementTokenData = [NSData dataWithBytes:elementToken.data() length:elementToken.size()];
462     [m_mockAccessibilityElement setRemoteTokenData:elementTokenData];
463 }
464
465 void WebPage::readSelectionFromPasteboard(const String&, bool&)
466 {
467     notImplemented();
468 }
469
470 void WebPage::getStringSelectionForPasteboard(String&)
471 {
472     notImplemented();
473 }
474
475 void WebPage::getDataSelectionForPasteboard(const String, SharedMemory::Handle&, uint64_t&)
476 {
477     notImplemented();
478 }
479
480 WKAccessibilityWebPageObject* WebPage::accessibilityRemoteObject()
481 {
482     notImplemented();
483     return 0;
484 }
485
486 bool WebPage::platformCanHandleRequest(const WebCore::ResourceRequest&)
487 {
488     notImplemented();
489     return false;
490 }
491
492 void WebPage::shouldDelayWindowOrderingEvent(const WebKit::WebMouseEvent&, bool&)
493 {
494     notImplemented();
495 }
496
497 void WebPage::acceptsFirstMouse(int, const WebKit::WebMouseEvent&, bool&)
498 {
499     notImplemented();
500 }
501
502 void WebPage::computePagesForPrintingPDFDocument(uint64_t, const PrintInfo&, Vector<IntRect>&)
503 {
504     notImplemented();
505 }
506
507 void WebPage::drawPagesToPDFFromPDFDocument(CGContextRef, PDFDocument *, const PrintInfo&, uint32_t, uint32_t)
508 {
509     notImplemented();
510 }
511
512 void WebPage::advanceToNextMisspelling(bool)
513 {
514     notImplemented();
515 }
516
517 IntRect WebPage::rectForElementAtInteractionLocation()
518 {
519     HitTestResult result = m_page->mainFrame().eventHandler().hitTestResultAtPoint(m_lastInteractionLocation, HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::AllowChildFrameContent);
520     Node* hitNode = result.innerNode();
521     if (!hitNode || !hitNode->renderer())
522         return IntRect();
523     return result.innerNodeFrame()->view()->contentsToRootView(hitNode->renderer()->absoluteBoundingBoxRect(true));
524 }
525
526 void WebPage::updateSelectionAppearance()
527 {
528     Frame& frame = m_page->focusController().focusedOrMainFrame();
529     if (!frame.editor().ignoreSelectionChanges() && (frame.editor().hasComposition() || !frame.selection().selection().isNone()))
530         didChangeSelection();
531 }
532
533 void WebPage::handleSyntheticClick(Node* nodeRespondingToClick, const WebCore::FloatPoint& location)
534 {
535     IntPoint roundedAdjustedPoint = roundedIntPoint(location);
536     Frame& mainframe = m_page->mainFrame();
537
538     LOG_WITH_STREAM(ContentObservation, stream << "handleSyntheticClick: node(" << nodeRespondingToClick << ") " << location);
539     WKStartObservingContentChanges();
540     WKStartObservingDOMTimerScheduling();
541
542     mainframe.eventHandler().mouseMoved(PlatformMouseEvent(roundedAdjustedPoint, roundedAdjustedPoint, NoButton, PlatformEvent::MouseMoved, 0, false, false, false, false, WallTime::now(), WebCore::ForceAtClick, WebCore::NoTap));
543     mainframe.document()->updateStyleIfNeeded();
544
545     WKStopObservingDOMTimerScheduling();
546     WKStopObservingContentChanges();
547
548     m_pendingSyntheticClickNode = nullptr;
549     m_pendingSyntheticClickLocation = FloatPoint();
550
551     if (m_isClosed)
552         return;
553
554     switch (WKObservedContentChange()) {
555     case WKContentVisibilityChange:
556         // The move event caused new contents to appear. Don't send the click event.
557         LOG(ContentObservation, "handleSyntheticClick: Observed meaningful visible change -> hover.");
558         return;
559     case WKContentIndeterminateChange:
560         // Wait for callback to completePendingSyntheticClickForContentChangeObserver() to decide whether to send the click event.
561         m_pendingSyntheticClickNode = nodeRespondingToClick;
562         m_pendingSyntheticClickLocation = location;
563         LOG(ContentObservation, "handleSyntheticClick: Observed some change, but can't decide it yet -> wait.");
564         return;
565     case WKContentNoChange:
566         LOG(ContentObservation, "handleSyntheticClick: No change was observed -> click.");
567         completeSyntheticClick(nodeRespondingToClick, location, WebCore::OneFingerTap);
568         return;
569     }
570     ASSERT_NOT_REACHED();
571 }
572
573 void WebPage::completePendingSyntheticClickForContentChangeObserver()
574 {
575     LOG_WITH_STREAM(ContentObservation, stream << "completePendingSyntheticClickForContentChangeObserver: pending target node(" << m_pendingSyntheticClickNode << ")");
576     if (!m_pendingSyntheticClickNode)
577         return;
578     // Only dispatch the click if the document didn't get changed by any timers started by the move event.
579     if (WKObservedContentChange() == WKContentNoChange) {
580         LOG(ContentObservation, "No chage was observed -> click.");
581         completeSyntheticClick(m_pendingSyntheticClickNode.get(), m_pendingSyntheticClickLocation, WebCore::OneFingerTap);
582     } else
583         LOG(ContentObservation, "Observed meaningful visible change -> hover.");
584
585     m_pendingSyntheticClickNode = nullptr;
586     m_pendingSyntheticClickLocation = FloatPoint();
587 }
588
589 void WebPage::completeSyntheticClick(Node* nodeRespondingToClick, const WebCore::FloatPoint& location, SyntheticClickType syntheticClickType)
590 {
591     IntPoint roundedAdjustedPoint = roundedIntPoint(location);
592     Frame& mainframe = m_page->mainFrame();
593
594     RefPtr<Frame> oldFocusedFrame = m_page->focusController().focusedFrame();
595     RefPtr<Element> oldFocusedElement = oldFocusedFrame ? oldFocusedFrame->document()->focusedElement() : nullptr;
596
597     SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
598
599     bool tapWasHandled = false;
600     m_lastInteractionLocation = roundedAdjustedPoint;
601
602     tapWasHandled |= mainframe.eventHandler().handleMousePressEvent(PlatformMouseEvent(roundedAdjustedPoint, roundedAdjustedPoint, LeftButton, PlatformEvent::MousePressed, 1, false, false, false, false, WallTime::now(), WebCore::ForceAtClick, syntheticClickType));
603     if (m_isClosed)
604         return;
605
606     tapWasHandled |= mainframe.eventHandler().handleMouseReleaseEvent(PlatformMouseEvent(roundedAdjustedPoint, roundedAdjustedPoint, LeftButton, PlatformEvent::MouseReleased, 1, false, false, false, false, WallTime::now(), WebCore::ForceAtClick, syntheticClickType));
607     if (m_isClosed)
608         return;
609
610     RefPtr<Frame> newFocusedFrame = m_page->focusController().focusedFrame();
611     RefPtr<Element> newFocusedElement = newFocusedFrame ? newFocusedFrame->document()->focusedElement() : nullptr;
612
613     // If the focus has not changed, we need to notify the client anyway, since it might be
614     // necessary to start assisting the node.
615     // If the node has been focused by JavaScript without user interaction, the
616     // keyboard is not on screen.
617     if (newFocusedElement && newFocusedElement == oldFocusedElement)
618         elementDidRefocus(newFocusedElement.get());
619
620     if (!tapWasHandled || !nodeRespondingToClick || !nodeRespondingToClick->isElementNode())
621         send(Messages::WebPageProxy::DidNotHandleTapAsClick(roundedIntPoint(location)));
622     
623     send(Messages::WebPageProxy::DidCompleteSyntheticClick());
624 }
625
626 void WebPage::handleTap(const IntPoint& point, uint64_t lastLayerTreeTransactionId)
627 {
628     FloatPoint adjustedPoint;
629     Node* nodeRespondingToClick = m_page->mainFrame().nodeRespondingToClickEvents(point, adjustedPoint);
630     Frame* frameRespondingToClick = nodeRespondingToClick ? nodeRespondingToClick->document().frame() : nullptr;
631     IntPoint adjustedIntPoint = roundedIntPoint(adjustedPoint);
632
633     if (!frameRespondingToClick || lastLayerTreeTransactionId < WebFrame::fromCoreFrame(*frameRespondingToClick)->firstLayerTreeTransactionIDAfterDidCommitLoad())
634         send(Messages::WebPageProxy::DidNotHandleTapAsClick(adjustedIntPoint));
635 #if ENABLE(DATA_DETECTION)
636     else if (is<Element>(*nodeRespondingToClick) && DataDetection::shouldCancelDefaultAction(downcast<Element>(*nodeRespondingToClick))) {
637         InteractionInformationRequest request(adjustedIntPoint);
638         requestPositionInformation(request);
639         send(Messages::WebPageProxy::DidNotHandleTapAsClick(adjustedIntPoint));
640     }
641 #endif
642     else
643         handleSyntheticClick(nodeRespondingToClick, adjustedPoint);
644 }
645
646 void WebPage::requestAssistedNodeInformation(WebKit::CallbackID callbackID)
647 {
648     AssistedNodeInformation info;
649     if (m_assistedNode)
650         getAssistedNodeInformation(info);
651
652     send(Messages::WebPageProxy::AssistedNodeInformationCallback(info, callbackID));
653 }
654
655 #if ENABLE(DATA_INTERACTION)
656 void WebPage::requestStartDataInteraction(const IntPoint& clientPosition, const IntPoint& globalPosition)
657 {
658     bool didStart = m_page->mainFrame().eventHandler().tryToBeginDataInteractionAtPoint(clientPosition, globalPosition);
659     send(Messages::WebPageProxy::DidHandleStartDataInteractionRequest(didStart));
660 }
661
662 void WebPage::requestAdditionalItemsForDragSession(const IntPoint& clientPosition, const IntPoint& globalPosition)
663 {
664     // To augment the platform drag session with additional items, end the current drag session and begin a new drag session with the new drag item.
665     // This process is opaque to the UI process, which still maintains the old drag item in its drag session. Similarly, this persistent drag session
666     // is opaque to the web process, which only sees that the current drag has ended, and that a new one is beginning.
667     PlatformMouseEvent event(clientPosition, globalPosition, LeftButton, PlatformEvent::MouseMoved, 0, false, false, false, false, WallTime::now(), 0, NoTap);
668     m_page->dragController().dragEnded();
669     m_page->mainFrame().eventHandler().dragSourceEndedAt(event, DragOperationNone, MayExtendDragSession::Yes);
670
671     bool didHandleDrag = m_page->mainFrame().eventHandler().tryToBeginDataInteractionAtPoint(clientPosition, globalPosition);
672     send(Messages::WebPageProxy::DidHandleAdditionalDragItemsRequest(didHandleDrag));
673 }
674
675 void WebPage::didConcludeEditDataInteraction()
676 {
677     Optional<TextIndicatorData> textIndicatorData;
678
679     static auto defaultEditDataInteractionTextIndicatorOptions = TextIndicatorOptionIncludeSnapshotOfAllVisibleContentWithoutSelection | TextIndicatorOptionExpandClipBeyondVisibleRect | TextIndicatorOptionPaintAllContent | TextIndicatorOptionIncludeMarginIfRangeMatchesSelection | TextIndicatorOptionPaintBackgrounds | TextIndicatorOptionComputeEstimatedBackgroundColor| TextIndicatorOptionUseSelectionRectForSizing | TextIndicatorOptionIncludeSnapshotWithSelectionHighlight;
680     auto& frame = m_page->focusController().focusedOrMainFrame();
681     if (auto range = frame.selection().selection().toNormalizedRange()) {
682         if (auto textIndicator = TextIndicator::createWithRange(*range, defaultEditDataInteractionTextIndicatorOptions, TextIndicatorPresentationTransition::None, FloatSize()))
683             textIndicatorData = textIndicator->data();
684     }
685
686     send(Messages::WebPageProxy::DidConcludeEditDataInteraction(textIndicatorData));
687 }
688 #endif
689
690 void WebPage::sendTapHighlightForNodeIfNecessary(uint64_t requestID, Node* node)
691 {
692 #if ENABLE(TOUCH_EVENTS)
693     if (!node)
694         return;
695
696     if (m_page->isEditable() && node == m_page->mainFrame().document()->body())
697         return;
698
699     if (is<Element>(*node)) {
700         ASSERT(m_page);
701         m_page->mainFrame().loader().client().prefetchDNS(downcast<Element>(*node).absoluteLinkURL().host().toString());
702     }
703
704     if (is<HTMLAreaElement>(node)) {
705         node = downcast<HTMLAreaElement>(node)->imageElement();
706         if (!node)
707             return;
708     }
709
710     Vector<FloatQuad> quads;
711     if (RenderObject *renderer = node->renderer()) {
712         renderer->absoluteQuads(quads);
713         Color highlightColor = renderer->style().tapHighlightColor();
714         if (!node->document().frame()->isMainFrame()) {
715             FrameView* view = node->document().frame()->view();
716             for (size_t i = 0; i < quads.size(); ++i) {
717                 FloatQuad& currentQuad = quads[i];
718                 currentQuad.setP1(view->contentsToRootView(roundedIntPoint(currentQuad.p1())));
719                 currentQuad.setP2(view->contentsToRootView(roundedIntPoint(currentQuad.p2())));
720                 currentQuad.setP3(view->contentsToRootView(roundedIntPoint(currentQuad.p3())));
721                 currentQuad.setP4(view->contentsToRootView(roundedIntPoint(currentQuad.p4())));
722             }
723         }
724
725         RoundedRect::Radii borderRadii;
726         if (is<RenderBox>(*renderer))
727             borderRadii = downcast<RenderBox>(*renderer).borderRadii();
728
729         send(Messages::WebPageProxy::DidGetTapHighlightGeometries(requestID, highlightColor, quads, roundedIntSize(borderRadii.topLeft()), roundedIntSize(borderRadii.topRight()), roundedIntSize(borderRadii.bottomLeft()), roundedIntSize(borderRadii.bottomRight())));
730     }
731 #else
732     UNUSED_PARAM(requestID);
733     UNUSED_PARAM(node);
734 #endif
735 }
736
737 void WebPage::handleTwoFingerTapAtPoint(const WebCore::IntPoint& point, uint64_t requestID)
738 {
739     FloatPoint adjustedPoint;
740     Node* nodeRespondingToClick = m_page->mainFrame().nodeRespondingToClickEvents(point, adjustedPoint);
741     if (!nodeRespondingToClick || !nodeRespondingToClick->renderer()) {
742         send(Messages::WebPageProxy::DidNotHandleTapAsClick(roundedIntPoint(adjustedPoint)));
743         return;
744     }
745     sendTapHighlightForNodeIfNecessary(requestID, nodeRespondingToClick);
746 #if ENABLE(DATA_DETECTION)
747     if (is<Element>(*nodeRespondingToClick) && DataDetection::shouldCancelDefaultAction(downcast<Element>(*nodeRespondingToClick))) {
748         InteractionInformationRequest request(roundedIntPoint(adjustedPoint));
749         requestPositionInformation(request);
750         send(Messages::WebPageProxy::DidNotHandleTapAsClick(roundedIntPoint(adjustedPoint)));
751     } else
752 #endif
753         completeSyntheticClick(nodeRespondingToClick, adjustedPoint, WebCore::TwoFingerTap);
754 }
755
756 void WebPage::handleStylusSingleTapAtPoint(const WebCore::IntPoint& point, uint64_t requestID)
757 {
758     SetForScope<bool> userIsInteractingChange { m_userIsInteracting, true };
759
760     auto& frame = m_page->focusController().focusedOrMainFrame();
761
762     auto pointInDocument = frame.view()->rootViewToContents(point);
763     HitTestResult hitTest = frame.eventHandler().hitTestResultAtPoint(pointInDocument, HitTestRequest::ReadOnly | HitTestRequest::Active);
764
765     Node* node = hitTest.innerNonSharedNode();
766     if (!node)
767         return;
768     auto renderer = node->renderer();
769     if (!renderer)
770         return;
771
772     if (renderer->isReplaced())
773         return;
774
775     VisiblePosition position = renderer->positionForPoint(hitTest.localPoint(), nullptr);
776     if (position.isNull())
777         position = firstPositionInOrBeforeNode(node);
778
779     if (position.isNull())
780         return;
781
782     auto range = Range::create(*frame.document(), position, position);
783     frame.selection().setSelectedRange(range.ptr(), position.affinity(), WebCore::FrameSelection::ShouldCloseTyping::Yes, UserTriggered);
784     auto image = frame.editor().insertEditableImage();
785     frame.document()->setFocusedElement(image.get());
786 }
787
788 void WebPage::potentialTapAtPosition(uint64_t requestID, const WebCore::FloatPoint& position)
789 {
790     m_potentialTapNode = m_page->mainFrame().nodeRespondingToClickEvents(position, m_potentialTapLocation, m_potentialTapSecurityOrigin.get());
791     sendTapHighlightForNodeIfNecessary(requestID, m_potentialTapNode.get());
792 #if ENABLE(TOUCH_EVENTS)
793     if (m_potentialTapNode && !m_potentialTapNode->allowsDoubleTapGesture())
794         send(Messages::WebPageProxy::DisableDoubleTapGesturesDuringTapIfNecessary(requestID));
795 #endif
796 }
797
798 void WebPage::commitPotentialTap(uint64_t lastLayerTreeTransactionId)
799 {
800     if (!m_potentialTapNode || (!m_potentialTapNode->renderer() && !is<HTMLAreaElement>(m_potentialTapNode.get()))) {
801         commitPotentialTapFailed();
802         return;
803     }
804
805     FloatPoint adjustedPoint;
806     Node* nodeRespondingToClick = m_page->mainFrame().nodeRespondingToClickEvents(m_potentialTapLocation, adjustedPoint, m_potentialTapSecurityOrigin.get());
807     Frame* frameRespondingToClick = nodeRespondingToClick ? nodeRespondingToClick->document().frame() : nullptr;
808
809     if (!frameRespondingToClick || lastLayerTreeTransactionId < WebFrame::fromCoreFrame(*frameRespondingToClick)->firstLayerTreeTransactionIDAfterDidCommitLoad()) {
810         commitPotentialTapFailed();
811         return;
812     }
813
814     if (m_potentialTapNode == nodeRespondingToClick) {
815 #if ENABLE(DATA_DETECTION)
816         if (is<Element>(*nodeRespondingToClick) && DataDetection::shouldCancelDefaultAction(downcast<Element>(*nodeRespondingToClick))) {
817             InteractionInformationRequest request(roundedIntPoint(m_potentialTapLocation));
818             requestPositionInformation(request);
819             commitPotentialTapFailed();
820         } else
821 #endif
822             handleSyntheticClick(nodeRespondingToClick, adjustedPoint);
823     } else
824         commitPotentialTapFailed();
825
826     m_potentialTapNode = nullptr;
827     m_potentialTapLocation = FloatPoint();
828     m_potentialTapSecurityOrigin = nullptr;
829 }
830
831 void WebPage::commitPotentialTapFailed()
832 {
833     send(Messages::WebPageProxy::CommitPotentialTapFailed());
834     send(Messages::WebPageProxy::DidNotHandleTapAsClick(roundedIntPoint(m_potentialTapLocation)));
835 }
836
837 void WebPage::cancelPotentialTap()
838 {
839     cancelPotentialTapInFrame(*m_mainFrame);
840 }
841
842 void WebPage::cancelPotentialTapInFrame(WebFrame& frame)
843 {
844     if (m_potentialTapNode) {
845         Frame* potentialTapFrame = m_potentialTapNode->document().frame();
846         if (potentialTapFrame && !potentialTapFrame->tree().isDescendantOf(frame.coreFrame()))
847             return;
848     }
849
850     m_potentialTapNode = nullptr;
851     m_potentialTapLocation = FloatPoint();
852     m_potentialTapSecurityOrigin = nullptr;
853 }
854
855 void WebPage::tapHighlightAtPosition(uint64_t requestID, const FloatPoint& position)
856 {
857     Frame& mainframe = m_page->mainFrame();
858     FloatPoint adjustedPoint;
859     sendTapHighlightForNodeIfNecessary(requestID, mainframe.nodeRespondingToClickEvents(position, adjustedPoint));
860 }
861
862 void WebPage::inspectorNodeSearchMovedToPosition(const FloatPoint& position)
863 {
864     IntPoint adjustedPoint = roundedIntPoint(position);
865     Frame& mainframe = m_page->mainFrame();
866
867     mainframe.eventHandler().mouseMoved(PlatformMouseEvent(adjustedPoint, adjustedPoint, NoButton, PlatformEvent::MouseMoved, 0, false, false, false, false, { }, 0, WebCore::NoTap));
868     mainframe.document()->updateStyleIfNeeded();
869 }
870
871 void WebPage::inspectorNodeSearchEndedAtPosition(const FloatPoint& position)
872 {
873     if (Node* node = m_page->mainFrame().deepestNodeAtLocation(position))
874         node->inspect();
875 }
876
877 void WebPage::blurAssistedNode()
878 {
879     if (is<Element>(m_assistedNode.get()))
880         downcast<Element>(*m_assistedNode).blur();
881 }
882
883 void WebPage::setAssistedNodeValue(const String& value)
884 {
885     // FIXME: should also handle the case of HTMLSelectElement.
886     if (is<HTMLInputElement>(m_assistedNode.get()))
887         downcast<HTMLInputElement>(*m_assistedNode).setValue(value, DispatchInputAndChangeEvent);
888 }
889
890 void WebPage::setAssistedNodeValueAsNumber(double value)
891 {
892     if (is<HTMLInputElement>(m_assistedNode.get()))
893         downcast<HTMLInputElement>(*m_assistedNode).setValueAsNumber(value, DispatchInputAndChangeEvent);
894 }
895
896 void WebPage::setAssistedNodeSelectedIndex(uint32_t index, bool allowMultipleSelection)
897 {
898     if (is<HTMLSelectElement>(m_assistedNode.get()))
899         downcast<HTMLSelectElement>(*m_assistedNode).optionSelectedByUser(index, true, allowMultipleSelection);
900 }
901
902 void WebPage::showInspectorHighlight(const WebCore::Highlight& highlight)
903 {
904     send(Messages::WebPageProxy::ShowInspectorHighlight(highlight));
905 }
906
907 void WebPage::hideInspectorHighlight()
908 {
909     send(Messages::WebPageProxy::HideInspectorHighlight());
910 }
911
912 void WebPage::showInspectorIndication()
913 {
914     send(Messages::WebPageProxy::ShowInspectorIndication());
915 }
916
917 void WebPage::hideInspectorIndication()
918 {
919     send(Messages::WebPageProxy::HideInspectorIndication());
920 }
921
922 void WebPage::enableInspectorNodeSearch()
923 {
924     send(Messages::WebPageProxy::EnableInspectorNodeSearch());
925 }
926
927 void WebPage::disableInspectorNodeSearch()
928 {
929     send(Messages::WebPageProxy::DisableInspectorNodeSearch());
930 }
931
932 void WebPage::setForceAlwaysUserScalable(bool userScalable)
933 {
934     m_forceAlwaysUserScalable = userScalable;
935     m_viewportConfiguration.setForceAlwaysUserScalable(userScalable);
936 }
937
938 static FloatQuad innerFrameQuad(const Frame& frame, const Node& assistedNode)
939 {
940     frame.document()->updateLayoutIgnorePendingStylesheets();
941     RenderElement* renderer = nullptr;
942     if (assistedNode.hasTagName(HTMLNames::textareaTag) || assistedNode.hasTagName(HTMLNames::inputTag) || assistedNode.hasTagName(HTMLNames::selectTag))
943         renderer = downcast<RenderElement>(assistedNode.renderer());
944     else if (Element* rootEditableElement = assistedNode.rootEditableElement())
945         renderer = rootEditableElement->renderer();
946     
947     if (!renderer)
948         return FloatQuad();
949
950     auto& style = renderer->style();
951     IntRect boundingBox = renderer->absoluteBoundingBoxRect(true /* use transforms*/);
952
953     boundingBox.move(style.borderLeftWidth(), style.borderTopWidth());
954     boundingBox.setWidth(boundingBox.width() - style.borderLeftWidth() - style.borderRightWidth());
955     boundingBox.setHeight(boundingBox.height() - style.borderBottomWidth() - style.borderTopWidth());
956
957     return FloatQuad(boundingBox);
958 }
959
960 static IntPoint constrainPoint(const IntPoint& point, const Frame& frame, const Node& assistedNode)
961 {
962     ASSERT(&assistedNode.document() == frame.document());
963     const int DEFAULT_CONSTRAIN_INSET = 2;
964     IntRect innerFrame = innerFrameQuad(frame, assistedNode).enclosingBoundingBox();
965     IntPoint constrainedPoint = point;
966
967     int minX = innerFrame.x() + DEFAULT_CONSTRAIN_INSET;
968     int maxX = innerFrame.maxX() - DEFAULT_CONSTRAIN_INSET;
969     int minY = innerFrame.y() + DEFAULT_CONSTRAIN_INSET;
970     int maxY = innerFrame.maxY() - DEFAULT_CONSTRAIN_INSET;
971
972     if (point.x() < minX)
973         constrainedPoint.setX(minX);
974     else if (point.x() > maxX)
975         constrainedPoint.setX(maxX);
976
977     if (point.y() < minY)
978         constrainedPoint.setY(minY);
979     else if (point.y() >= maxY)
980         constrainedPoint.setY(maxY);
981                     
982     return constrainedPoint;
983 }
984
985 static IntRect selectionBoxForRange(WebCore::Range* range)
986 {
987     if (!range)
988         return IntRect();
989     
990     IntRect boundingRect;
991     Vector<SelectionRect> selectionRects;
992     range->collectSelectionRects(selectionRects);
993     unsigned size = selectionRects.size();
994     
995     for (unsigned i = 0; i < size; ++i) {
996         const IntRect &coreRect = selectionRects[i].rect();
997         if (!i)
998             boundingRect = coreRect;
999         else
1000             boundingRect.unite(coreRect);
1001     }
1002     return boundingRect;
1003 }
1004
1005 static bool canShrinkToTextSelection(Node* node)
1006 {
1007     if (node && !is<Element>(*node))
1008         node = node->parentElement();
1009     
1010     auto* renderer = (node) ? node->renderer() : nullptr;
1011     return renderer && renderer->childrenInline() && (is<RenderBlock>(*renderer) && !downcast<RenderBlock>(*renderer).inlineContinuation()) && !renderer->isTable();
1012 }
1013
1014 static bool hasCustomLineHeight(Node& node)
1015 {
1016     auto* renderer = node.renderer();
1017     return renderer && renderer->style().lineHeight().isSpecified();
1018 }
1019     
1020 RefPtr<Range> WebPage::rangeForWebSelectionAtPosition(const IntPoint& point, const VisiblePosition& position, SelectionFlags& flags)
1021 {
1022     HitTestResult result = m_page->mainFrame().eventHandler().hitTestResultAtPoint((point), HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::DisallowUserAgentShadowContent | HitTestRequest::AllowChildFrameContent);
1023
1024     Node* currentNode = result.innerNode();
1025     if (!currentNode)
1026         return nullptr;
1027     RefPtr<Range> range;
1028     FloatRect boundingRectInScrollViewCoordinates;
1029
1030     if (!currentNode->isTextNode() && !canShrinkToTextSelection(currentNode) && hasCustomLineHeight(*currentNode)) {
1031         auto* renderer = currentNode->renderer();
1032         if (is<RenderBlockFlow>(renderer)) {
1033             auto* renderText = downcast<RenderBlockFlow>(*renderer).findClosestTextAtAbsolutePoint(point);
1034             if (renderText && renderText->textNode())
1035                 currentNode = renderText->textNode();
1036         }
1037     }
1038
1039     if (currentNode->isTextNode()) {
1040         range = enclosingTextUnitOfGranularity(position, ParagraphGranularity, DirectionForward);
1041         if (!range || range->collapsed())
1042             range = Range::create(currentNode->document(), position, position);
1043         else {
1044             m_blockRectForTextSelection = selectionBoxForRange(range.get());
1045             range = wordRangeFromPosition(position);
1046         }
1047
1048         return range;
1049     }
1050
1051     if (!currentNode->isElementNode())
1052         currentNode = currentNode->parentElement();
1053
1054     Node* bestChoice = currentNode;
1055     while (currentNode) {
1056         if (currentNode->renderer()) {
1057             boundingRectInScrollViewCoordinates = currentNode->renderer()->absoluteBoundingBoxRect(true);
1058             boundingRectInScrollViewCoordinates.scale(m_page->pageScaleFactor());
1059             if (boundingRectInScrollViewCoordinates.width() > m_blockSelectionDesiredSize.width() && boundingRectInScrollViewCoordinates.height() > m_blockSelectionDesiredSize.height())
1060                 break;
1061             bestChoice = currentNode;
1062         }
1063         currentNode = currentNode->parentElement();
1064     }
1065
1066     if (!bestChoice)
1067         return nullptr;
1068
1069     RenderObject* renderer = bestChoice->renderer();
1070     if (!renderer || renderer->style().userSelect() == UserSelect::None)
1071         return nullptr;
1072
1073     if (renderer->childrenInline() && (is<RenderBlock>(*renderer) && !downcast<RenderBlock>(*renderer).inlineContinuation()) && !renderer->isTable()) {
1074         range = enclosingTextUnitOfGranularity(position, WordGranularity, DirectionBackward);
1075         if (range && !range->collapsed())
1076             return range;
1077     }
1078
1079     // If all we could find is a block whose height is very close to the height
1080     // of the visible area, don't use it.
1081     const float adjustmentFactor = .97;
1082     boundingRectInScrollViewCoordinates = renderer->absoluteBoundingBoxRect(true);
1083
1084     if (boundingRectInScrollViewCoordinates.height() > m_page->mainFrame().view()->exposedContentRect().height() * adjustmentFactor)
1085         return nullptr;
1086
1087     range = Range::create(bestChoice->document());
1088     range->selectNodeContents(*bestChoice);
1089     return range->collapsed() ? nullptr : range;
1090 }
1091
1092 void WebPage::selectWithGesture(const IntPoint& point, uint32_t granularity, uint32_t gestureType, uint32_t gestureState, bool isInteractingWithAssistedNode, CallbackID callbackID)
1093 {
1094     auto& frame = m_page->focusController().focusedOrMainFrame();
1095     VisiblePosition position = visiblePositionInFocusedNodeForPoint(frame, point, isInteractingWithAssistedNode);
1096
1097     if (position.isNull()) {
1098         send(Messages::WebPageProxy::GestureCallback(point, gestureType, gestureState, 0, callbackID));
1099         return;
1100     }
1101     RefPtr<Range> range;
1102     SelectionFlags flags = None;
1103     GestureRecognizerState wkGestureState = static_cast<GestureRecognizerState>(gestureState);
1104     switch (static_cast<GestureType>(gestureType)) {
1105     case GestureType::PhraseBoundary:
1106     {
1107         if (!frame.editor().hasComposition())
1108             break;
1109         RefPtr<Range> markedRange = frame.editor().compositionRange();
1110         if (position < markedRange->startPosition())
1111             position = markedRange->startPosition();
1112         if (position > markedRange->endPosition())
1113             position = markedRange->endPosition();
1114         if (wkGestureState != GestureRecognizerState::Began)
1115             flags = distanceBetweenPositions(markedRange->startPosition(), frame.selection().selection().start()) != distanceBetweenPositions(markedRange->startPosition(), position) ? PhraseBoundaryChanged : None;
1116         else
1117             flags = PhraseBoundaryChanged;
1118         range = Range::create(*frame.document(), position, position);
1119     }
1120         break;
1121
1122     case GestureType::OneFingerTap:
1123     {
1124         VisiblePosition result;
1125         // move the position at the end of the word
1126         if (atBoundaryOfGranularity(position, LineGranularity, DirectionForward)) {
1127             // Don't cross line boundaries.
1128             result = position;
1129         } else if (withinTextUnitOfGranularity(position, WordGranularity, DirectionForward)) {
1130             // The position lies within a word.
1131             RefPtr<Range> wordRange = enclosingTextUnitOfGranularity(position, WordGranularity, DirectionForward);
1132             if (wordRange) {
1133                 result = wordRange->startPosition();
1134                 if (distanceBetweenPositions(position, result) > 1)
1135                     result = wordRange->endPosition();
1136             }
1137         } else if (atBoundaryOfGranularity(position, WordGranularity, DirectionBackward)) {
1138             // The position is at the end of a word.
1139             result = position;
1140         } else {
1141             // The position is not within a word.
1142             // Go to the next boundary.
1143             result = positionOfNextBoundaryOfGranularity(position, WordGranularity, DirectionForward);
1144
1145             // If there is no such boundary we go to the end of the element.
1146             if (result.isNull())
1147                 result = endOfEditableContent(position);
1148         }
1149         if (result.isNotNull())
1150             range = Range::create(*frame.document(), result, result);
1151     }
1152         break;
1153
1154     case GestureType::Loupe:
1155         if (position.rootEditableElement())
1156             range = Range::create(*frame.document(), position, position);
1157         else
1158 #if !PLATFORM(IOSMAC)
1159             range = wordRangeFromPosition(position);
1160 #else
1161             switch (wkGestureState) {
1162             case GestureRecognizerState::Began:
1163                 m_startingGestureRange = Range::create(*frame.document(), position, position);
1164                 break;
1165             case GestureRecognizerState::Changed:
1166                 if (m_startingGestureRange) {
1167                     if (m_startingGestureRange->startPosition() < position)
1168                         range = Range::create(*frame.document(), m_startingGestureRange->startPosition(), position);
1169                     else
1170                         range = Range::create(*frame.document(), position, m_startingGestureRange->startPosition());
1171                 }
1172                 break;
1173             case GestureRecognizerState::Ended:
1174             case GestureRecognizerState::Cancelled:
1175                 m_startingGestureRange = nullptr;
1176                 break;
1177             case GestureRecognizerState::Failed:
1178             case GestureRecognizerState::Possible:
1179                 ASSERT_NOT_REACHED();
1180                 break;
1181             }
1182 #endif
1183         break;
1184
1185     case GestureType::TapAndAHalf:
1186         switch (wkGestureState) {
1187         case GestureRecognizerState::Began:
1188             range = wordRangeFromPosition(position);
1189             m_currentWordRange = range ? RefPtr<Range>(Range::create(*frame.document(), range->startPosition(), range->endPosition())) : nullptr;
1190             break;
1191         case GestureRecognizerState::Changed:
1192             if (!m_currentWordRange)
1193                 break;
1194             range = Range::create(*frame.document(), m_currentWordRange->startPosition(), m_currentWordRange->endPosition());
1195             if (position < range->startPosition())
1196                 range->setStart(position.deepEquivalent());
1197             if (position > range->endPosition())
1198                 range->setEnd(position.deepEquivalent());
1199             break;
1200         case GestureRecognizerState::Ended:
1201         case GestureRecognizerState::Cancelled:
1202             m_currentWordRange = nullptr;
1203             break;
1204         case GestureRecognizerState::Failed:
1205         case GestureRecognizerState::Possible:
1206             ASSERT_NOT_REACHED();
1207         }
1208         break;
1209
1210     case GestureType::OneFingerDoubleTap:
1211         if (atBoundaryOfGranularity(position, LineGranularity, DirectionForward)) {
1212             // Double-tap at end of line only places insertion point there.
1213             // This helps to get the callout for pasting at ends of lines,
1214             // paragraphs, and documents.
1215             range = Range::create(*frame.document(), position, position);
1216          } else
1217             range = wordRangeFromPosition(position);
1218         break;
1219
1220     case GestureType::TwoFingerSingleTap:
1221         // Single tap with two fingers selects the entire paragraph.
1222         range = enclosingTextUnitOfGranularity(position, ParagraphGranularity, DirectionForward);
1223         break;
1224
1225     case GestureType::OneFingerTripleTap:
1226         if (atBoundaryOfGranularity(position, LineGranularity, DirectionForward)) {
1227             // Triple-tap at end of line only places insertion point there.
1228             // This helps to get the callout for pasting at ends of lines,
1229             // paragraphs, and documents.
1230             range = Range::create(*frame.document(), position, position);
1231         } else
1232             range = enclosingTextUnitOfGranularity(position, ParagraphGranularity, DirectionForward);
1233         break;
1234
1235     case GestureType::MakeWebSelection:
1236         if (wkGestureState == GestureRecognizerState::Began) {
1237             m_blockSelectionDesiredSize.setWidth(blockSelectionStartWidth);
1238             m_blockSelectionDesiredSize.setHeight(blockSelectionStartHeight);
1239             m_currentBlockSelection = nullptr;
1240         }
1241         range = rangeForWebSelectionAtPosition(point, position, flags);
1242         break;
1243
1244     default:
1245         break;
1246     }
1247     if (range)
1248         frame.selection().setSelectedRange(range.get(), position.affinity(), WebCore::FrameSelection::ShouldCloseTyping::Yes, UserTriggered);
1249
1250     send(Messages::WebPageProxy::GestureCallback(point, gestureType, gestureState, static_cast<uint32_t>(flags), callbackID));
1251 }
1252
1253 static RefPtr<Range> rangeForPointInRootViewCoordinates(Frame& frame, const IntPoint& pointInRootViewCoordinates, bool baseIsStart)
1254 {
1255     VisibleSelection existingSelection = frame.selection().selection();
1256     VisiblePosition selectionStart = existingSelection.visibleStart();
1257     VisiblePosition selectionEnd = existingSelection.visibleEnd();
1258
1259     auto pointInDocument = frame.view()->rootViewToContents(pointInRootViewCoordinates);
1260
1261     if (baseIsStart) {
1262         int startY = selectionStart.absoluteCaretBounds().center().y();
1263         if (pointInDocument.y() < startY)
1264             pointInDocument.setY(startY);
1265     } else {
1266         int endY = selectionEnd.absoluteCaretBounds().center().y();
1267         if (pointInDocument.y() > endY)
1268             pointInDocument.setY(endY);
1269     }
1270     
1271     VisiblePosition result;
1272     RefPtr<Range> range;
1273     
1274     HitTestResult hitTest = frame.eventHandler().hitTestResultAtPoint(pointInDocument, HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::AllowChildFrameContent);
1275     if (hitTest.targetNode())
1276         result = frame.eventHandler().selectionExtentRespectingEditingBoundary(frame.selection().selection(), hitTest.localPoint(), hitTest.targetNode()).deepEquivalent();
1277     else
1278         result = frame.visiblePositionForPoint(pointInDocument).deepEquivalent();
1279     
1280     if (baseIsStart) {
1281         if (comparePositions(result, selectionStart) <= 0)
1282             result = selectionStart.next();
1283         else if (&selectionStart.deepEquivalent().anchorNode()->treeScope() != &hitTest.targetNode()->treeScope())
1284             result = VisibleSelection::adjustPositionForEnd(result.deepEquivalent(), selectionStart.deepEquivalent().containerNode());
1285         
1286         if (result.isNotNull())
1287             range = Range::create(*frame.document(), selectionStart, result);
1288     } else {
1289         if (comparePositions(selectionEnd, result) <= 0)
1290             result = selectionEnd.previous();
1291         else if (&hitTest.targetNode()->treeScope() != &selectionEnd.deepEquivalent().anchorNode()->treeScope())
1292             result = VisibleSelection::adjustPositionForStart(result.deepEquivalent(), selectionEnd.deepEquivalent().containerNode());
1293         
1294         if (result.isNotNull())
1295             range = Range::create(*frame.document(), result.deepEquivalent(), selectionEnd);
1296     }
1297     
1298     return range;
1299 }
1300
1301 static RefPtr<Range> rangeAtWordBoundaryForPosition(Frame* frame, const VisiblePosition& position, bool baseIsStart, SelectionDirection direction)
1302 {
1303     SelectionDirection sameDirection = baseIsStart ? DirectionForward : DirectionBackward;
1304     SelectionDirection oppositeDirection = baseIsStart ? DirectionBackward : DirectionForward;
1305     VisiblePosition base = baseIsStart ? frame->selection().selection().visibleStart() : frame->selection().selection().visibleEnd();
1306     VisiblePosition extent = baseIsStart ? frame->selection().selection().visibleEnd() : frame->selection().selection().visibleStart();
1307     VisiblePosition initialExtent = position;
1308
1309     if (atBoundaryOfGranularity(extent, WordGranularity, sameDirection)) {
1310         // This is a word boundary. Leave selection where it is.
1311         return nullptr;
1312     }
1313
1314     if (atBoundaryOfGranularity(extent, WordGranularity, oppositeDirection)) {
1315         // This is a word boundary in the wrong direction. Nudge the selection to a character before proceeding.
1316         extent = baseIsStart ? extent.previous() : extent.next();
1317     }
1318
1319     // Extend to the boundary of the word.
1320
1321     VisiblePosition wordBoundary = positionOfNextBoundaryOfGranularity(extent, WordGranularity, sameDirection);
1322     if (wordBoundary.isNotNull()
1323         && atBoundaryOfGranularity(wordBoundary, WordGranularity, sameDirection)
1324         && initialExtent != wordBoundary) {
1325         extent = wordBoundary;
1326         return (base < extent) ? Range::create(*frame->document(), base, extent) : Range::create(*frame->document(), extent, base);
1327     }
1328     // Conversely, if the initial extent equals the current word boundary, then
1329     // run the rest of this function to see if the selection should extend
1330     // the other direction to the other word.
1331
1332     // If this is where the extent was initially, then iterate in the other direction in the document until we hit the next word.
1333     while (extent.isNotNull()
1334         && !atBoundaryOfGranularity(extent, WordGranularity, sameDirection)
1335         && extent != base
1336         && !atBoundaryOfGranularity(extent, LineGranularity, sameDirection)
1337         && !atBoundaryOfGranularity(extent, LineGranularity, oppositeDirection)) {
1338         extent = baseIsStart ? extent.next() : extent.previous();
1339     }
1340
1341     // Don't let the smart extension make the extent equal the base.
1342     // Expand out to word boundary.
1343     if (extent.isNull() || extent == base)
1344         extent = wordBoundary;
1345     if (extent.isNull())
1346         return nullptr;
1347
1348     return (base < extent) ? Range::create(*frame->document(), base, extent) : Range::create(*frame->document(), extent, base);
1349 }
1350
1351 void WebPage::clearSelection(){
1352     m_startingGestureRange = nullptr;
1353     m_currentBlockSelection = nullptr;
1354     m_page->focusController().focusedOrMainFrame().selection().clear();
1355 }
1356
1357 void WebPage::updateSelectionWithTouches(const IntPoint& point, uint32_t touches, bool baseIsStart, CallbackID callbackID)
1358 {
1359     Frame& frame = m_page->focusController().focusedOrMainFrame();
1360     IntPoint pointInDocument = frame.view()->rootViewToContents(point);
1361     VisiblePosition position = frame.visiblePositionForPoint(pointInDocument);
1362     if (position.isNull()) {
1363         send(Messages::WebPageProxy::TouchesCallback(point, touches, 0, callbackID));
1364         return;
1365     }
1366
1367     RefPtr<Range> range;
1368     VisiblePosition result;
1369     SelectionFlags flags = None;
1370
1371     switch (static_cast<SelectionTouch>(touches)) {
1372     case SelectionTouch::Started:
1373     case SelectionTouch::EndedNotMoving:
1374         break;
1375     
1376     case SelectionTouch::Ended:
1377         if (frame.selection().selection().isContentEditable()) {
1378             result = closestWordBoundaryForPosition(position);
1379             if (result.isNotNull())
1380                 range = Range::create(*frame.document(), result, result);
1381         } else
1382             range = rangeForPointInRootViewCoordinates(frame, point, baseIsStart);
1383         break;
1384
1385     case SelectionTouch::EndedMovingForward:
1386         range = rangeAtWordBoundaryForPosition(&frame, position, baseIsStart, DirectionForward);
1387         break;
1388         
1389     case SelectionTouch::EndedMovingBackward:
1390         range = rangeAtWordBoundaryForPosition(&frame, position, baseIsStart, DirectionBackward);
1391         break;
1392
1393     case SelectionTouch::Moved:
1394         range = rangeForPointInRootViewCoordinates(frame, point, baseIsStart);
1395         break;
1396     }
1397     if (range)
1398         frame.selection().setSelectedRange(range.get(), position.affinity(), WebCore::FrameSelection::ShouldCloseTyping::Yes, UserTriggered);
1399
1400     send(Messages::WebPageProxy::TouchesCallback(point, touches, flags, callbackID));
1401 }
1402
1403 void WebPage::selectWithTwoTouches(const WebCore::IntPoint& from, const WebCore::IntPoint& to, uint32_t gestureType, uint32_t gestureState, CallbackID callbackID)
1404 {
1405     Frame& frame = m_page->focusController().focusedOrMainFrame();
1406     VisiblePosition fromPosition = frame.visiblePositionForPoint(frame.view()->rootViewToContents(from));
1407     VisiblePosition toPosition = frame.visiblePositionForPoint(frame.view()->rootViewToContents(to));
1408     RefPtr<Range> range;
1409     if (fromPosition.isNotNull() && toPosition.isNotNull()) {
1410         if (fromPosition < toPosition)
1411             range = Range::create(*frame.document(), fromPosition, toPosition);
1412         else
1413             range = Range::create(*frame.document(), toPosition, fromPosition);
1414         frame.selection().setSelectedRange(range.get(), fromPosition.affinity(), WebCore::FrameSelection::ShouldCloseTyping::Yes, UserTriggered);
1415     }
1416
1417     // We can use the same callback for the gestures with one point.
1418     send(Messages::WebPageProxy::GestureCallback(from, gestureType, gestureState, 0, callbackID));
1419 }
1420
1421 void WebPage::extendSelection(uint32_t granularity)
1422 {
1423     Frame& frame = m_page->focusController().focusedOrMainFrame();
1424     // For the moment we handle only WordGranularity.
1425     if (granularity != WordGranularity || !frame.selection().isCaret())
1426         return;
1427
1428     VisiblePosition position = frame.selection().selection().start();
1429     frame.selection().setSelectedRange(wordRangeFromPosition(position).get(), position.affinity(), WebCore::FrameSelection::ShouldCloseTyping::Yes, UserTriggered);
1430 }
1431
1432 void WebPage::selectWordBackward()
1433 {
1434     Frame& frame = m_page->focusController().focusedOrMainFrame();
1435     if (!frame.selection().isCaret())
1436         return;
1437
1438     VisiblePosition position = frame.selection().selection().start();
1439     VisiblePosition startPosition = positionOfNextBoundaryOfGranularity(position, WordGranularity, DirectionBackward);
1440     if (startPosition.isNotNull() && startPosition != position)
1441         frame.selection().setSelectedRange(Range::create(*frame.document(), startPosition, position).ptr(), position.affinity(), WebCore::FrameSelection::ShouldCloseTyping::Yes, UserTriggered);
1442 }
1443
1444 void WebPage::moveSelectionByOffset(int32_t offset, CallbackID callbackID)
1445 {
1446     Frame& frame = m_page->focusController().focusedOrMainFrame();
1447     
1448     VisiblePosition startPosition = frame.selection().selection().end();
1449     if (startPosition.isNull())
1450         return;
1451     SelectionDirection direction = offset < 0 ? DirectionBackward : DirectionForward;
1452     VisiblePosition position = startPosition;
1453     for (int i = 0; i < abs(offset); ++i) {
1454         position = positionOfNextBoundaryOfGranularity(position, CharacterGranularity, direction);
1455         if (position.isNull())
1456             break;
1457     }
1458     if (position.isNotNull() && startPosition != position)
1459         frame.selection().setSelectedRange(Range::create(*frame.document(), position, position).ptr(), position.affinity(), WebCore::FrameSelection::ShouldCloseTyping::Yes, UserTriggered);
1460     send(Messages::WebPageProxy::VoidCallback(callbackID));
1461 }
1462     
1463 void WebPage::startAutoscrollAtPosition(const WebCore::FloatPoint& positionInWindow)
1464 {
1465     if (m_assistedNode && m_assistedNode->renderer())
1466         m_page->mainFrame().eventHandler().startSelectionAutoscroll(m_assistedNode->renderer(), positionInWindow);
1467     else {
1468         Frame& frame = m_page->focusController().focusedOrMainFrame();
1469         VisibleSelection selection = frame.selection().selection();
1470         if (selection.isRange()) {
1471             RefPtr<Range> range = frame.selection().toNormalizedRange();
1472             Node& node = range->startContainer();
1473             auto* renderer = node.renderer();
1474             if (renderer)
1475                 m_page->mainFrame().eventHandler().startSelectionAutoscroll(renderer, positionInWindow);
1476         }
1477     }
1478 }
1479     
1480 void WebPage::cancelAutoscroll()
1481 {
1482     m_page->mainFrame().eventHandler().cancelSelectionAutoscroll();
1483 }
1484
1485 void WebPage::getRectsForGranularityWithSelectionOffset(uint32_t granularity, int32_t offset, CallbackID callbackID)
1486 {
1487     Frame& frame = m_page->focusController().focusedOrMainFrame();
1488     VisibleSelection selection = m_storedSelectionForAccessibility.isNone() ? frame.selection().selection() : m_storedSelectionForAccessibility;
1489     VisiblePosition selectionStart = selection.visibleStart();
1490
1491     if (selectionStart.isNull()) {
1492         send(Messages::WebPageProxy::SelectionRectsCallback({ }, callbackID));
1493         return;
1494     }
1495
1496     auto position = visiblePositionForPositionWithOffset(selectionStart, offset);
1497     SelectionDirection direction = offset < 0 ? DirectionBackward : DirectionForward;
1498
1499     auto range = enclosingTextUnitOfGranularity(position, static_cast<WebCore::TextGranularity>(granularity), direction);
1500     if (!range || range->collapsed()) {
1501         send(Messages::WebPageProxy::SelectionRectsCallback({ }, callbackID));
1502         return;
1503     }
1504
1505     Vector<WebCore::SelectionRect> selectionRects;
1506     range->collectSelectionRectsWithoutUnionInteriorLines(selectionRects);
1507     convertSelectionRectsToRootView(frame.view(), selectionRects);
1508     send(Messages::WebPageProxy::SelectionRectsCallback(selectionRects, callbackID));
1509 }
1510
1511 void WebPage::storeSelectionForAccessibility(bool shouldStore)
1512 {
1513     if (!shouldStore)
1514         m_storedSelectionForAccessibility = VisibleSelection();
1515     else {
1516         Frame& frame = m_page->focusController().focusedOrMainFrame();
1517         m_storedSelectionForAccessibility = frame.selection().selection();
1518     }
1519 }
1520
1521 static RefPtr<Range> rangeNearPositionMatchesText(const VisiblePosition& position, RefPtr<Range> originalRange, const String& matchText, RefPtr<Range> selectionRange)
1522 {
1523     auto range = Range::create(selectionRange->ownerDocument(), selectionRange->startPosition(), position.deepEquivalent().parentAnchoredEquivalent());
1524     unsigned targetOffset = TextIterator::rangeLength(range.ptr(), true);
1525     return findClosestPlainText(*selectionRange.get(), matchText, { }, targetOffset);
1526 }
1527
1528 void WebPage::getRectsAtSelectionOffsetWithText(int32_t offset, const String& text, CallbackID callbackID)
1529 {
1530     Frame& frame = m_page->focusController().focusedOrMainFrame();
1531     uint32_t length = text.length();
1532     VisibleSelection selection = m_storedSelectionForAccessibility.isNone() ? frame.selection().selection() : m_storedSelectionForAccessibility;
1533     VisiblePosition selectionStart = selection.visibleStart();
1534     VisiblePosition selectionEnd = selection.visibleEnd();
1535
1536     if (selectionStart.isNull() || selectionEnd.isNull()) {
1537         send(Messages::WebPageProxy::SelectionRectsCallback({ }, callbackID));
1538         return;
1539     }
1540
1541     auto startPosition = visiblePositionForPositionWithOffset(selectionStart, offset);
1542     auto endPosition = visiblePositionForPositionWithOffset(startPosition, length);
1543     auto range = Range::create(*frame.document(), startPosition, endPosition);
1544
1545     if (range->collapsed()) {
1546         send(Messages::WebPageProxy::SelectionRectsCallback({ }, callbackID));
1547         return;
1548     }
1549
1550     String rangeText = plainTextReplacingNoBreakSpace(range.ptr(), TextIteratorDefaultBehavior, true);
1551     if (rangeText != text) {
1552         auto selectionRange = selection.toNormalizedRange();
1553         // Try to search for a range which is the closest to the position within the selection range that matches the passed in text.
1554         if (auto wordRange = rangeNearPositionMatchesText(startPosition, range.ptr(), text, selectionRange)) {
1555             if (!wordRange->collapsed())
1556                 range = *wordRange;
1557         }
1558     }
1559
1560     Vector<WebCore::SelectionRect> selectionRects;
1561     range->collectSelectionRectsWithoutUnionInteriorLines(selectionRects);
1562     convertSelectionRectsToRootView(frame.view(), selectionRects);
1563     send(Messages::WebPageProxy::SelectionRectsCallback(selectionRects, callbackID));
1564 }
1565
1566 VisiblePosition WebPage::visiblePositionInFocusedNodeForPoint(const Frame& frame, const IntPoint& point, bool isInteractingWithAssistedNode)
1567 {
1568     IntPoint adjustedPoint(frame.view()->rootViewToContents(point));
1569     IntPoint constrainedPoint = m_assistedNode && isInteractingWithAssistedNode ? constrainPoint(adjustedPoint, frame, *m_assistedNode) : adjustedPoint;
1570     return frame.visiblePositionForPoint(constrainedPoint);
1571 }
1572
1573 void WebPage::selectPositionAtPoint(const WebCore::IntPoint& point, bool isInteractingWithAssistedNode, CallbackID callbackID)
1574 {
1575     auto& frame = m_page->focusController().focusedOrMainFrame();
1576     VisiblePosition position = visiblePositionInFocusedNodeForPoint(frame, point, isInteractingWithAssistedNode);
1577     
1578     if (position.isNotNull())
1579         frame.selection().setSelectedRange(Range::create(*frame.document(), position, position).ptr(), position.affinity(), WebCore::FrameSelection::ShouldCloseTyping::Yes, UserTriggered);
1580     send(Messages::WebPageProxy::VoidCallback(callbackID));
1581 }
1582
1583 void WebPage::selectPositionAtBoundaryWithDirection(const WebCore::IntPoint& point, uint32_t granularity, uint32_t direction, bool isInteractingWithAssistedNode, CallbackID callbackID)
1584 {
1585     auto& frame = m_page->focusController().focusedOrMainFrame();
1586     VisiblePosition position = visiblePositionInFocusedNodeForPoint(frame, point, isInteractingWithAssistedNode);
1587
1588     if (position.isNotNull()) {
1589         position = positionOfNextBoundaryOfGranularity(position, static_cast<WebCore::TextGranularity>(granularity), static_cast<SelectionDirection>(direction));
1590         if (position.isNotNull())
1591             frame.selection().setSelectedRange(Range::create(*frame.document(), position, position).ptr(), UPSTREAM, WebCore::FrameSelection::ShouldCloseTyping::Yes, UserTriggered);
1592     }
1593     send(Messages::WebPageProxy::VoidCallback(callbackID));
1594 }
1595
1596 void WebPage::moveSelectionAtBoundaryWithDirection(uint32_t granularity, uint32_t direction, CallbackID callbackID)
1597 {
1598     Frame& frame = m_page->focusController().focusedOrMainFrame();
1599     
1600     if (!frame.selection().selection().isNone()) {
1601         bool isForward = (direction == DirectionForward || direction == DirectionRight);
1602         VisiblePosition position = (isForward) ? frame.selection().selection().visibleEnd() : frame.selection().selection().visibleStart();
1603         position = positionOfNextBoundaryOfGranularity(position, static_cast<WebCore::TextGranularity>(granularity), static_cast<SelectionDirection>(direction));
1604         if (position.isNotNull())
1605             frame.selection().setSelectedRange(Range::create(*frame.document(), position, position).ptr(), isForward? UPSTREAM : DOWNSTREAM, WebCore::FrameSelection::ShouldCloseTyping::Yes, UserTriggered);
1606     }
1607     send(Messages::WebPageProxy::VoidCallback(callbackID));
1608 }
1609
1610 RefPtr<Range> WebPage::rangeForGranularityAtPoint(Frame& frame, const WebCore::IntPoint& point, uint32_t granularity, bool isInteractingWithAssistedNode)
1611 {
1612     VisiblePosition position = visiblePositionInFocusedNodeForPoint(frame, point, isInteractingWithAssistedNode);
1613
1614     RefPtr<Range> range;
1615     switch (static_cast<WebCore::TextGranularity>(granularity)) {
1616     case WordGranularity:
1617         range = wordRangeFromPosition(position);
1618         break;
1619     case SentenceGranularity:
1620         range = enclosingTextUnitOfGranularity(position, SentenceGranularity, DirectionForward);
1621         break;
1622     case ParagraphGranularity:
1623         range = enclosingTextUnitOfGranularity(position, ParagraphGranularity, DirectionForward);
1624         break;
1625     case DocumentGranularity:
1626         frame.selection().selectAll();
1627         break;
1628     default:
1629         break;
1630     }
1631     return range;
1632 }
1633
1634 static inline bool rectIsTooBigForSelection(const IntRect& blockRect, const Frame& frame)
1635 {
1636     const float factor = 0.97;
1637     return blockRect.height() > frame.view()->unobscuredContentRect().height() * factor;
1638 }
1639
1640 void WebPage::selectTextWithGranularityAtPoint(const WebCore::IntPoint& point, uint32_t granularity, bool isInteractingWithAssistedNode, CallbackID callbackID)
1641 {
1642     auto& frame = m_page->focusController().focusedOrMainFrame();
1643     RefPtr<Range> range = rangeForGranularityAtPoint(frame, point, granularity, isInteractingWithAssistedNode);
1644     if (!isInteractingWithAssistedNode) {
1645         m_blockSelectionDesiredSize.setWidth(blockSelectionStartWidth);
1646         m_blockSelectionDesiredSize.setHeight(blockSelectionStartHeight);
1647         m_currentBlockSelection = nullptr;
1648         auto* renderer = range ? range->startContainer().renderer() : nullptr;
1649         if (renderer && renderer->style().preserveNewline())
1650             m_blockRectForTextSelection = renderer->absoluteBoundingBoxRect(true);
1651         else {
1652             auto paragraphRange = enclosingTextUnitOfGranularity(visiblePositionInFocusedNodeForPoint(frame, point, isInteractingWithAssistedNode), ParagraphGranularity, DirectionForward);
1653             if (paragraphRange && !paragraphRange->collapsed())
1654                 m_blockRectForTextSelection = selectionBoxForRange(paragraphRange.get());
1655         }
1656         
1657         if (rectIsTooBigForSelection(m_blockRectForTextSelection, frame))
1658             m_blockRectForTextSelection.setHeight(0);
1659     }
1660
1661     if (range)
1662         frame.selection().setSelectedRange(range.get(), UPSTREAM, WebCore::FrameSelection::ShouldCloseTyping::Yes, UserTriggered);
1663     m_initialSelection = range;
1664     send(Messages::WebPageProxy::VoidCallback(callbackID));
1665 }
1666
1667 void WebPage::beginSelectionInDirection(uint32_t direction, CallbackID callbackID)
1668 {
1669     m_selectionAnchor = (static_cast<SelectionDirection>(direction) == DirectionLeft) ? Start : End;
1670     send(Messages::WebPageProxy::UnsignedCallback(m_selectionAnchor == Start, callbackID));
1671 }
1672
1673 void WebPage::updateSelectionWithExtentPointAndBoundary(const WebCore::IntPoint& point, uint32_t granularity, bool isInteractingWithAssistedNode, CallbackID callbackID)
1674 {
1675     auto& frame = m_page->focusController().focusedOrMainFrame();
1676     VisiblePosition position = visiblePositionInFocusedNodeForPoint(frame, point, isInteractingWithAssistedNode);
1677     RefPtr<Range> newRange = rangeForGranularityAtPoint(frame, point, granularity, isInteractingWithAssistedNode);
1678     
1679     if (position.isNull() || !m_initialSelection || !newRange) {
1680         send(Messages::WebPageProxy::UnsignedCallback(false, callbackID));
1681         return;
1682     }
1683     
1684     RefPtr<Range> range;
1685     VisiblePosition selectionStart = m_initialSelection->startPosition();
1686     VisiblePosition selectionEnd = m_initialSelection->endPosition();
1687
1688     if (position > m_initialSelection->endPosition())
1689         selectionEnd = newRange->endPosition();
1690     else if (position < m_initialSelection->startPosition())
1691         selectionStart = newRange->startPosition();
1692     
1693     if (selectionStart.isNotNull() && selectionEnd.isNotNull())
1694         range = Range::create(*frame.document(), selectionStart, selectionEnd);
1695     
1696     if (range)
1697         frame.selection().setSelectedRange(range.get(), UPSTREAM, WebCore::FrameSelection::ShouldCloseTyping::Yes, UserTriggered);
1698     
1699     send(Messages::WebPageProxy::UnsignedCallback(selectionStart == m_initialSelection->startPosition(), callbackID));
1700 }
1701
1702 void WebPage::updateSelectionWithExtentPoint(const WebCore::IntPoint& point, bool isInteractingWithAssistedNode, CallbackID callbackID)
1703 {
1704     auto& frame = m_page->focusController().focusedOrMainFrame();
1705     VisiblePosition position = visiblePositionInFocusedNodeForPoint(frame, point, isInteractingWithAssistedNode);
1706
1707     if (position.isNull()) {
1708         send(Messages::WebPageProxy::UnsignedCallback(false, callbackID));
1709         return;
1710     }
1711
1712     RefPtr<Range> range;
1713     VisiblePosition selectionStart;
1714     VisiblePosition selectionEnd;
1715     
1716     if (m_selectionAnchor == Start) {
1717         selectionStart = frame.selection().selection().visibleStart();
1718         selectionEnd = position;
1719
1720         if (position <= selectionStart) {
1721             selectionStart = selectionStart.previous();
1722             selectionEnd = frame.selection().selection().visibleEnd();
1723             m_selectionAnchor = End;
1724         }
1725     } else {
1726         selectionStart = position;
1727         selectionEnd = frame.selection().selection().visibleEnd();
1728         
1729         if (position >= selectionEnd) {
1730             selectionStart = frame.selection().selection().visibleStart();
1731             selectionEnd = selectionEnd.next();
1732             m_selectionAnchor = Start;
1733         }
1734     }
1735     
1736     if (selectionStart.isNotNull() && selectionEnd.isNotNull())
1737         range = Range::create(*frame.document(), selectionStart, selectionEnd);
1738
1739     if (range)
1740         frame.selection().setSelectedRange(range.get(), UPSTREAM, WebCore::FrameSelection::ShouldCloseTyping::Yes, UserTriggered);
1741
1742     send(Messages::WebPageProxy::UnsignedCallback(m_selectionAnchor == Start, callbackID));
1743 }
1744
1745 void WebPage::convertSelectionRectsToRootView(FrameView* view, Vector<SelectionRect>& selectionRects)
1746 {
1747     for (size_t i = 0; i < selectionRects.size(); ++i) {
1748         SelectionRect& currentRect = selectionRects[i];
1749         currentRect.setRect(view->contentsToRootView(currentRect.rect()));
1750     }
1751 }
1752
1753 void WebPage::requestDictationContext(CallbackID callbackID)
1754 {
1755     Frame& frame = m_page->focusController().focusedOrMainFrame();
1756     VisiblePosition startPosition = frame.selection().selection().start();
1757     VisiblePosition endPosition = frame.selection().selection().end();
1758     const unsigned dictationContextWordCount = 5;
1759
1760     String selectedText;
1761     if (frame.selection().isRange())
1762         selectedText = plainTextReplacingNoBreakSpace(frame.selection().selection().toNormalizedRange().get());
1763
1764     String contextBefore;
1765     if (startPosition != startOfEditableContent(startPosition)) {
1766         VisiblePosition currentPosition = startPosition;
1767         VisiblePosition lastPosition = startPosition;
1768         for (unsigned i = 0; i < dictationContextWordCount; ++i) {
1769             currentPosition = startOfWord(positionOfNextBoundaryOfGranularity(lastPosition, WordGranularity, DirectionBackward));
1770             if (currentPosition.isNull())
1771                 break;
1772             lastPosition = currentPosition;
1773         }
1774         if (lastPosition.isNotNull() && lastPosition != startPosition)
1775             contextBefore = plainTextReplacingNoBreakSpace(Range::create(*frame.document(), lastPosition, startPosition).ptr());
1776     }
1777
1778     String contextAfter;
1779     if (endPosition != endOfEditableContent(endPosition)) {
1780         VisiblePosition currentPosition = endPosition;
1781         VisiblePosition lastPosition = endPosition;
1782         for (unsigned i = 0; i < dictationContextWordCount; ++i) {
1783             currentPosition = endOfWord(positionOfNextBoundaryOfGranularity(lastPosition, WordGranularity, DirectionForward));
1784             if (currentPosition.isNull())
1785                 break;
1786             lastPosition = currentPosition;
1787         }
1788         if (lastPosition.isNotNull() && lastPosition != endPosition)
1789             contextAfter = plainTextReplacingNoBreakSpace(Range::create(*frame.document(), endPosition, lastPosition).ptr());
1790     }
1791
1792     send(Messages::WebPageProxy::SelectionContextCallback(selectedText, contextBefore, contextAfter, callbackID));
1793 }
1794
1795 void WebPage::replaceSelectedText(const String& oldText, const String& newText)
1796 {
1797     Frame& frame = m_page->focusController().focusedOrMainFrame();
1798     RefPtr<Range> wordRange = frame.selection().isCaret() ? wordRangeFromPosition(frame.selection().selection().start()) : frame.selection().toNormalizedRange();
1799     if (plainTextReplacingNoBreakSpace(wordRange.get()) != oldText)
1800         return;
1801     
1802     frame.editor().setIgnoreSelectionChanges(true);
1803     frame.selection().setSelectedRange(wordRange.get(), UPSTREAM, WebCore::FrameSelection::ShouldCloseTyping::Yes);
1804     frame.editor().insertText(newText, 0);
1805     frame.editor().setIgnoreSelectionChanges(false);
1806 }
1807
1808 void WebPage::replaceDictatedText(const String& oldText, const String& newText)
1809 {
1810     Frame& frame = m_page->focusController().focusedOrMainFrame();
1811     if (frame.selection().isNone())
1812         return;
1813     
1814     if (frame.selection().isRange()) {
1815         frame.editor().deleteSelectionWithSmartDelete(false);
1816         return;
1817     }
1818     VisiblePosition position = frame.selection().selection().start();
1819     for (size_t i = 0; i < oldText.length(); ++i)
1820         position = position.previous();
1821     if (position.isNull())
1822         position = startOfDocument(static_cast<Node*>(frame.document()->documentElement()));
1823     RefPtr<Range> range = Range::create(*frame.document(), position, frame.selection().selection().start());
1824
1825     if (plainTextReplacingNoBreakSpace(range.get()) != oldText)
1826         return;
1827
1828     // We don't want to notify the client that the selection has changed until we are done inserting the new text.
1829     frame.editor().setIgnoreSelectionChanges(true);
1830     frame.selection().setSelectedRange(range.get(), UPSTREAM, WebCore::FrameSelection::ShouldCloseTyping::Yes);
1831     frame.editor().insertText(newText, 0);
1832     frame.editor().setIgnoreSelectionChanges(false);
1833 }
1834
1835 void WebPage::requestAutocorrectionData(const String& textForAutocorrection, CallbackID callbackID)
1836 {
1837     Frame& frame = m_page->focusController().focusedOrMainFrame();
1838     if (!frame.selection().isCaret()) {
1839         send(Messages::WebPageProxy::AutocorrectionDataCallback(Vector<FloatRect>(), String(), 0, 0, callbackID));
1840         return;
1841     }
1842
1843     VisiblePosition position = frame.selection().selection().start();
1844     RefPtr<Range> range = wordRangeFromPosition(position);
1845     if (!range) {
1846         send(Messages::WebPageProxy::AutocorrectionDataCallback(Vector<FloatRect>(), String(), 0, 0, callbackID));
1847         return;
1848     }
1849
1850     String textForRange = plainTextReplacingNoBreakSpace(range.get());
1851     const unsigned maxSearchAttempts = 5;
1852     for (size_t i = 0;  i < maxSearchAttempts && textForRange != textForAutocorrection; ++i)
1853     {
1854         position = range->startPosition().previous();
1855         if (position.isNull() || position == range->startPosition())
1856             break;
1857         range = Range::create(*frame.document(), wordRangeFromPosition(position)->startPosition(), range->endPosition());
1858         textForRange = plainTextReplacingNoBreakSpace(range.get());
1859     }
1860
1861     Vector<SelectionRect> selectionRects;
1862     if (textForRange == textForAutocorrection)
1863         range->collectSelectionRects(selectionRects);
1864
1865     Vector<FloatRect> rectsForText;
1866     rectsForText.grow(selectionRects.size());
1867
1868     convertSelectionRectsToRootView(frame.view(), selectionRects);
1869     for (size_t i = 0; i < selectionRects.size(); i++)
1870         rectsForText[i] = selectionRects[i].rect();
1871
1872     bool multipleFonts = false;
1873     CTFontRef font = nil;
1874     if (auto* coreFont = frame.editor().fontForSelection(multipleFonts))
1875         font = coreFont->getCTFont();
1876
1877     CGFloat fontSize = CTFontGetSize(font);
1878     uint64_t fontTraits = CTFontGetSymbolicTraits(font);
1879     RetainPtr<NSString> fontName = adoptNS((NSString *)CTFontCopyFamilyName(font));
1880     send(Messages::WebPageProxy::AutocorrectionDataCallback(rectsForText, fontName.get(), fontSize, fontTraits, callbackID));
1881 }
1882
1883 void WebPage::applyAutocorrection(const String& correction, const String& originalText, CallbackID callbackID)
1884 {
1885     bool correctionApplied;
1886     syncApplyAutocorrection(correction, originalText, correctionApplied);
1887     send(Messages::WebPageProxy::StringCallback(correctionApplied ? correction : String(), callbackID));
1888 }
1889
1890 Seconds WebPage::eventThrottlingDelay() const
1891 {
1892     auto behaviorOverride = m_page->eventThrottlingBehaviorOverride();
1893     if (behaviorOverride) {
1894         switch (behaviorOverride.value()) {
1895         case EventThrottlingBehavior::Responsive:
1896             return 0_s;
1897         case EventThrottlingBehavior::Unresponsive:
1898             return 1_s;
1899         }
1900     }
1901
1902     if (m_isInStableState || m_estimatedLatency <= Seconds(1.0 / 60))
1903         return 0_s;
1904
1905     return std::min(m_estimatedLatency * 2, 1_s);
1906 }
1907
1908 void WebPage::syncApplyAutocorrection(const String& correction, const String& originalText, bool& correctionApplied)
1909 {
1910     correctionApplied = false;
1911
1912     Frame& frame = m_page->focusController().focusedOrMainFrame();
1913     if (!frame.selection().isCaretOrRange())
1914         return;
1915
1916     RefPtr<Range> range;
1917     String textForRange;
1918
1919     if (frame.selection().isCaret()) {
1920         VisiblePosition position = frame.selection().selection().start();
1921         range = wordRangeFromPosition(position);
1922         textForRange = plainTextReplacingNoBreakSpace(range.get());
1923         if (textForRange != originalText) {
1924             // Search for the original text before the selection caret.
1925             for (size_t i = 0; i < originalText.length(); ++i)
1926                 position = position.previous();
1927             if (position.isNull())
1928                 position = startOfDocument(static_cast<Node*>(frame.document()->documentElement()));
1929             range = Range::create(*frame.document(), position, frame.selection().selection().start());
1930             if (range)
1931                 textForRange = (range) ? plainTextReplacingNoBreakSpace(range.get()) : emptyString();
1932             unsigned loopCount = 0;
1933             const unsigned maxPositionsAttempts = 10;
1934             while (textForRange.length() && textForRange.length() > originalText.length() && loopCount < maxPositionsAttempts) {
1935                 position = position.next();
1936                 if (position.isNotNull() && position >= frame.selection().selection().start())
1937                     range = nullptr;
1938                 else
1939                     range = Range::create(*frame.document(), position, frame.selection().selection().start());
1940                 textForRange = (range) ? plainTextReplacingNoBreakSpace(range.get()) : emptyString();
1941                 loopCount++;
1942             }
1943         }
1944     } else {
1945         // Range selection.
1946         range = frame.selection().toNormalizedRange();
1947         if (!range) {
1948             correctionApplied = false;
1949             return;
1950         }
1951         textForRange = plainTextReplacingNoBreakSpace(range.get());
1952     }
1953
1954     if (textForRange != originalText) {
1955         correctionApplied = false;
1956         return;
1957     }
1958     
1959     // Correctly determine affinity, using logic currently only present in VisiblePosition
1960     EAffinity affinity = DOWNSTREAM;
1961     if (range && range->collapsed())
1962         affinity = VisiblePosition(range->startPosition(), UPSTREAM).affinity();
1963     
1964     frame.selection().setSelectedRange(range.get(), affinity, WebCore::FrameSelection::ShouldCloseTyping::Yes);
1965     if (correction.length())
1966         frame.editor().insertText(correction, 0, originalText.isEmpty() ? TextEventInputKeyboard : TextEventInputAutocompletion);
1967     else
1968         frame.editor().deleteWithDirection(DirectionBackward, CharacterGranularity, false, true);
1969     correctionApplied = true;
1970 }
1971
1972 static void computeAutocorrectionContext(Frame& frame, String& contextBefore, String& markedText, String& selectedText, String& contextAfter, uint64_t& location, uint64_t& length)
1973 {
1974     RefPtr<Range> range;
1975     VisiblePosition startPosition = frame.selection().selection().start();
1976     VisiblePosition endPosition = frame.selection().selection().end();
1977     location = NSNotFound;
1978     length = 0;
1979     const unsigned minContextWordCount = 3;
1980     const unsigned minContextLenght = 12;
1981     const unsigned maxContextLength = 30;
1982
1983     if (frame.selection().isRange())
1984         selectedText = plainTextReplacingNoBreakSpace(frame.selection().selection().toNormalizedRange().get());
1985
1986     if (auto compositionRange = frame.editor().compositionRange()) {
1987         range = Range::create(*frame.document(), compositionRange->startPosition(), startPosition);
1988         String markedTextBefore;
1989         if (range)
1990             markedTextBefore = plainTextReplacingNoBreakSpace(range.get());
1991         range = Range::create(*frame.document(), endPosition, compositionRange->endPosition());
1992         String markedTextAfter;
1993         if (range)
1994             markedTextAfter = plainTextReplacingNoBreakSpace(range.get());
1995         markedText = markedTextBefore + selectedText + markedTextAfter;
1996         if (!markedText.isEmpty()) {
1997             location = markedTextBefore.length();
1998             length = selectedText.length();
1999         }
2000     } else {
2001         if (startPosition != startOfEditableContent(startPosition)) {
2002             VisiblePosition currentPosition = startPosition;
2003             VisiblePosition previousPosition;
2004             unsigned totalContextLength = 0;
2005             for (unsigned i = 0; i < minContextWordCount; ++i) {
2006                 if (contextBefore.length() >= minContextLenght)
2007                     break;
2008                 previousPosition = startOfWord(positionOfNextBoundaryOfGranularity(currentPosition, WordGranularity, DirectionBackward));
2009                 if (previousPosition.isNull())
2010                     break;
2011                 String currentWord = plainTextReplacingNoBreakSpace(Range::create(*frame.document(), previousPosition, currentPosition).ptr());
2012                 totalContextLength += currentWord.length();
2013                 if (totalContextLength >= maxContextLength)
2014                     break;
2015                 currentPosition = previousPosition;
2016             }
2017             if (currentPosition.isNotNull() && currentPosition != startPosition) {
2018                 contextBefore = plainTextReplacingNoBreakSpace(Range::create(*frame.document(), currentPosition, startPosition).ptr());
2019                 if (atBoundaryOfGranularity(currentPosition, ParagraphGranularity, DirectionBackward))
2020                     contextBefore = makeString("\n "_s, contextBefore);
2021             }
2022         }
2023
2024         if (endPosition != endOfEditableContent(endPosition)) {
2025             VisiblePosition nextPosition;
2026             if (!atBoundaryOfGranularity(endPosition, WordGranularity, DirectionForward) && withinTextUnitOfGranularity(endPosition, WordGranularity, DirectionForward))
2027                 nextPosition = positionOfNextBoundaryOfGranularity(endPosition, WordGranularity, DirectionForward);
2028             if (nextPosition.isNotNull())
2029                 contextAfter = plainTextReplacingNoBreakSpace(Range::create(*frame.document(), endPosition, nextPosition).ptr());
2030         }
2031     }
2032 }
2033
2034 void WebPage::requestAutocorrectionContext(CallbackID callbackID)
2035 {
2036     String contextBefore;
2037     String contextAfter;
2038     String selectedText;
2039     String markedText;
2040     uint64_t location;
2041     uint64_t length;
2042
2043     computeAutocorrectionContext(m_page->focusController().focusedOrMainFrame(), contextBefore, markedText, selectedText, contextAfter, location, length);
2044
2045     send(Messages::WebPageProxy::AutocorrectionContextCallback(contextBefore, markedText, selectedText, contextAfter, location, length, callbackID));
2046 }
2047
2048 void WebPage::getAutocorrectionContext(String& contextBefore, String& markedText, String& selectedText, String& contextAfter, uint64_t& location, uint64_t& length)
2049 {
2050     computeAutocorrectionContext(m_page->focusController().focusedOrMainFrame(), contextBefore, markedText, selectedText, contextAfter, location, length);
2051 }
2052
2053 static HTMLAnchorElement* containingLinkElement(Element* element)
2054 {
2055     for (auto& currentElement : elementLineage(element)) {
2056         if (currentElement.isLink() && is<HTMLAnchorElement>(currentElement))
2057             return downcast<HTMLAnchorElement>(&currentElement);
2058     }
2059     return nullptr;
2060 }
2061
2062 static inline bool isAssistableElement(Element& node)
2063 {
2064     if (is<HTMLSelectElement>(node))
2065         return true;
2066     if (is<HTMLTextAreaElement>(node))
2067         return true;
2068     if (is<HTMLImageElement>(node) && downcast<HTMLImageElement>(node).hasEditableImageAttribute())
2069         return true;
2070     if (is<HTMLInputElement>(node)) {
2071         HTMLInputElement& inputElement = downcast<HTMLInputElement>(node);
2072         // FIXME: This laundry list of types is not a good way to factor this. Need a suitable function on HTMLInputElement itself.
2073 #if ENABLE(INPUT_TYPE_COLOR)
2074         if (inputElement.isColorControl())
2075             return true;
2076 #endif
2077         return inputElement.isTextField() || inputElement.isDateField() || inputElement.isDateTimeLocalField() || inputElement.isMonthField() || inputElement.isTimeField();
2078     }
2079     return node.isContentEditable();
2080 }
2081
2082 void WebPage::getPositionInformation(const InteractionInformationRequest& request, InteractionInformationAtPosition& info)
2083 {
2084     info.request = request;
2085
2086     FloatPoint adjustedPoint;
2087     Node* hitNode = m_page->mainFrame().nodeRespondingToClickEvents(request.point, adjustedPoint);
2088
2089     info.nodeAtPositionIsAssistedNode = (hitNode == m_assistedNode);
2090     if (m_assistedNode) {
2091         const Frame& frame = m_page->focusController().focusedOrMainFrame();
2092         if (frame.editor().hasComposition()) {
2093             const uint32_t kHitAreaWidth = 66;
2094             const uint32_t kHitAreaHeight = 66;
2095             FrameView& view = *frame.view();
2096             IntPoint adjustedPoint(view.rootViewToContents(request.point));
2097             IntPoint constrainedPoint = m_assistedNode ? constrainPoint(adjustedPoint, frame, *m_assistedNode) : adjustedPoint;
2098             VisiblePosition position = frame.visiblePositionForPoint(constrainedPoint);
2099
2100             RefPtr<Range> compositionRange = frame.editor().compositionRange();
2101             if (position < compositionRange->startPosition())
2102                 position = compositionRange->startPosition();
2103             else if (position > compositionRange->endPosition())
2104                 position = compositionRange->endPosition();
2105             IntRect caretRect = view.contentsToRootView(position.absoluteCaretBounds());
2106             float deltaX = abs(caretRect.x() + (caretRect.width() / 2) - request.point.x());
2107             float deltaYFromTheTop = abs(caretRect.y() - request.point.y());
2108             float deltaYFromTheBottom = abs(caretRect.y() + caretRect.height() - request.point.y());
2109
2110             info.isNearMarkedText = !(deltaX > kHitAreaWidth || deltaYFromTheTop > kHitAreaHeight || deltaYFromTheBottom > kHitAreaHeight);
2111         }
2112     }
2113     bool elementIsLinkOrImage = false;
2114     if (hitNode) {
2115         Element* element = is<Element>(*hitNode) ? downcast<Element>(hitNode) : nullptr;
2116         if (element) {
2117             info.isElement = true;
2118             info.idAttribute = element->getIdAttribute();
2119             Element* linkElement = nullptr;
2120             if (element->renderer() && element->renderer()->isRenderImage()) {
2121                 elementIsLinkOrImage = true;
2122                 linkElement = containingLinkElement(element);
2123             } else if (element->isLink()) {
2124                 linkElement = element;
2125                 elementIsLinkOrImage = true;
2126             }
2127
2128             if (elementIsLinkOrImage) {
2129                 if (linkElement) {
2130                     info.isLink = true;
2131
2132                     if (request.includeSnapshot) {
2133                         // Ensure that the image contains at most 600K pixels, so that it is not too big.
2134                         if (RefPtr<WebImage> snapshot = snapshotNode(*element, SnapshotOptionsShareable, 600 * 1024))
2135                             info.image = &snapshot->bitmap();
2136                     }
2137
2138                     if (request.includeLinkIndicator) {
2139                         RefPtr<Range> linkRange = rangeOfContents(*linkElement);
2140                         if (linkRange) {
2141                             float deviceScaleFactor = corePage()->deviceScaleFactor();
2142                             const float marginInPoints = 4;
2143
2144                             RefPtr<TextIndicator> textIndicator = TextIndicator::createWithRange(*linkRange, TextIndicatorOptionTightlyFitContent | TextIndicatorOptionRespectTextColor | TextIndicatorOptionPaintBackgrounds | TextIndicatorOptionUseBoundingRectAndPaintAllContentForComplexRanges |
2145                                 TextIndicatorOptionIncludeMarginIfRangeMatchesSelection, TextIndicatorPresentationTransition::None, FloatSize(marginInPoints * deviceScaleFactor, marginInPoints * deviceScaleFactor));
2146
2147                             if (textIndicator)
2148                                 info.linkIndicator = textIndicator->data();
2149                         }
2150                     }
2151
2152 #if ENABLE(DATA_DETECTION)
2153                     info.isDataDetectorLink = DataDetection::isDataDetectorLink(*element);
2154                     if (info.isDataDetectorLink) {
2155                         const int dataDetectionExtendedContextLength = 350;
2156                         info.dataDetectorIdentifier = DataDetection::dataDetectorIdentifier(*element);
2157                         info.dataDetectorResults = element->document().frame()->dataDetectionResults();
2158                         if (DataDetection::requiresExtendedContext(*element)) {
2159                             RefPtr<Range> linkRange = Range::create(element->document());
2160                             linkRange->selectNodeContents(*element);
2161                             info.textBefore = plainTextReplacingNoBreakSpace(rangeExpandedByCharactersInDirectionAtWordBoundary(linkRange->startPosition(), dataDetectionExtendedContextLength, DirectionBackward).get(), TextIteratorDefaultBehavior, true);
2162                             info.textAfter = plainTextReplacingNoBreakSpace(rangeExpandedByCharactersInDirectionAtWordBoundary(linkRange->endPosition(), dataDetectionExtendedContextLength, DirectionForward).get(), TextIteratorDefaultBehavior, true);
2163                         }
2164                     }
2165 #endif
2166                 }
2167                 if (element->renderer() && element->renderer()->isRenderImage()) {
2168                     info.isImage = true;
2169                     auto& renderImage = downcast<RenderImage>(*(element->renderer()));
2170                     if (renderImage.cachedImage() && !renderImage.cachedImage()->errorOccurred()) {
2171                         if (Image* image = renderImage.cachedImage()->imageForRenderer(&renderImage)) {
2172                             if (image->width() > 1 && image->height() > 1) {
2173                                 info.imageURL = element->document().completeURL(renderImage.cachedImage()->url());
2174                                 info.isAnimatedImage = image->isAnimated();
2175
2176                                 if (request.includeSnapshot) {
2177                                     FloatSize screenSizeInPixels = screenSize();
2178                                     screenSizeInPixels.scale(corePage()->deviceScaleFactor());
2179                                     FloatSize scaledSize = largestRectWithAspectRatioInsideRect(image->size().width() / image->size().height(), FloatRect(0, 0, screenSizeInPixels.width(), screenSizeInPixels.height())).size();
2180                                     FloatSize bitmapSize = scaledSize.width() < image->size().width() ? scaledSize : image->size();
2181                                     // FIXME: Only select ExtendedColor on images known to need wide gamut
2182                                     ShareableBitmap::Configuration bitmapConfiguration;
2183                                     bitmapConfiguration.colorSpace.cgColorSpace = screenColorSpace(m_page->mainFrame().view());
2184                                     if (RefPtr<ShareableBitmap> sharedBitmap = ShareableBitmap::createShareable(IntSize(bitmapSize), bitmapConfiguration)) {
2185                                         auto graphicsContext = sharedBitmap->createGraphicsContext();
2186                                         graphicsContext->drawImage(*image, FloatRect(0, 0, bitmapSize.width(), bitmapSize.height()));
2187                                         info.image = sharedBitmap;
2188                                     }
2189                                 }
2190                             }
2191                         }
2192                     }
2193                 }
2194             }
2195             if (linkElement)
2196                 info.url = linkElement->document().completeURL(stripLeadingAndTrailingHTMLSpaces(linkElement->getAttribute(HTMLNames::hrefAttr)));
2197             info.title = element->attributeWithoutSynchronization(HTMLNames::titleAttr).string();
2198             if (linkElement && info.title.isEmpty())
2199                 info.title = element->innerText();
2200             if (element->renderer())
2201                 info.touchCalloutEnabled = element->renderer()->style().touchCalloutEnabled();
2202
2203             if (RenderElement* renderer = element->renderer()) {
2204                 if (renderer->isRenderImage())
2205                     info.bounds = downcast<RenderImage>(*renderer).absoluteContentQuad().enclosingBoundingBox();
2206                 else
2207                     info.bounds = renderer->absoluteBoundingBoxRect();
2208
2209                 if (!renderer->document().frame()->isMainFrame()) {
2210                     FrameView *view = renderer->document().frame()->view();
2211                     info.bounds = view->contentsToRootView(info.bounds);
2212                 }
2213             }
2214         }
2215     }
2216
2217     if (!elementIsLinkOrImage) {
2218         HitTestResult result = m_page->mainFrame().eventHandler().hitTestResultAtPoint(request.point, HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::DisallowUserAgentShadowContent | HitTestRequest::AllowChildFrameContent);
2219         hitNode = result.innerNode();
2220         // Hit test could return HTMLHtmlElement that has no renderer, if the body is smaller than the document.
2221         if (hitNode && hitNode->renderer()) {
2222             RenderObject* renderer = hitNode->renderer();
2223             m_page->focusController().setFocusedFrame(result.innerNodeFrame());
2224             info.bounds = renderer->absoluteBoundingBoxRect(true);
2225             // We don't want to select blocks that are larger than 97% of the visible area of the document.
2226             if (is<HTMLAttachmentElement>(*hitNode)) {
2227                 info.isAttachment = true;
2228                 const HTMLAttachmentElement& attachment = downcast<HTMLAttachmentElement>(*hitNode);
2229                 info.title = attachment.attachmentTitle();
2230                 if (attachment.file())
2231                     info.url = URL::fileURLWithFileSystemPath(downcast<HTMLAttachmentElement>(*hitNode).file()->path());
2232             } else {
2233                 info.isSelectable = renderer->style().userSelect() != UserSelect::None;
2234                 if (info.isSelectable && !hitNode->isTextNode())
2235                     info.isSelectable = !isAssistableElement(*downcast<Element>(hitNode)) && !rectIsTooBigForSelection(info.bounds, *result.innerNodeFrame());
2236             }
2237 #if PLATFORM(IOSMAC)
2238             bool isInsideFixedPosition;
2239             VisiblePosition caretPosition(renderer->positionForPoint(request.point, nullptr));
2240             info.caretRect = caretPosition.absoluteCaretBounds(&isInsideFixedPosition);
2241 #endif
2242         }
2243     }
2244
2245     // Prevent the callout bar from showing when tapping on the datalist button.
2246 #if ENABLE(DATALIST_ELEMENT)
2247     if (is<HTMLInputElement>(*hitNode)) {
2248         const HTMLInputElement& input = downcast<HTMLInputElement>(*hitNode);
2249         if (input.list()) {
2250             HitTestResult result = m_page->mainFrame().eventHandler().hitTestResultAtPoint(request.point, HitTestRequest::ReadOnly | HitTestRequest::Active);
2251             if (result.innerNode() == input.dataListButtonElement())
2252                 info.preventTextInteraction = true;
2253         }
2254     }
2255 #endif
2256
2257 #if ENABLE(DATA_INTERACTION)
2258     info.hasSelectionAtPosition = m_page->hasSelectionAtPosition(adjustedPoint);
2259 #endif
2260     info.adjustedPointForNodeRespondingToClickEvents = adjustedPoint;
2261 }
2262
2263 void WebPage::requestPositionInformation(const InteractionInformationRequest& request)
2264 {
2265     InteractionInformationAtPosition info;
2266
2267     getPositionInformation(request, info);
2268     send(Messages::WebPageProxy::DidReceivePositionInformation(info));
2269 }
2270
2271 void WebPage::startInteractionWithElementAtPosition(const WebCore::IntPoint& point)
2272 {
2273     FloatPoint adjustedPoint;
2274     m_interactionNode = m_page->mainFrame().nodeRespondingToClickEvents(point, adjustedPoint);
2275 }
2276
2277 void WebPage::stopInteraction()
2278 {
2279     m_interactionNode = nullptr;
2280 }
2281
2282 void WebPage::performActionOnElement(uint32_t action)
2283 {
2284     if (!is<HTMLElement>(m_interactionNode.get()))
2285         return;
2286
2287     HTMLElement& element = downcast<HTMLElement>(*m_interactionNode);
2288     if (!element.renderer())
2289         return;
2290
2291     if (static_cast<SheetAction>(action) == SheetAction::Copy) {
2292         if (is<RenderImage>(*element.renderer())) {
2293             URL url;
2294             String title;
2295             if (auto* linkElement = containingLinkElement(&element)) {
2296                 url = linkElement->href();
2297                 title = linkElement->attributeWithoutSynchronization(HTMLNames::titleAttr);
2298                 if (!title.length())
2299                     title = linkElement->textContent();
2300                 title = stripLeadingAndTrailingHTMLSpaces(title);
2301             }
2302             m_interactionNode->document().frame()->editor().writeImageToPasteboard(*Pasteboard::createForCopyAndPaste(), element, url, title);
2303         } else if (element.isLink()) {
2304             m_interactionNode->document().frame()->editor().copyURL(element.document().completeURL(stripLeadingAndTrailingHTMLSpaces(element.attributeWithoutSynchronization(HTMLNames::hrefAttr))), element.textContent());
2305         }
2306     } else if (static_cast<SheetAction>(action) == SheetAction::SaveImage) {
2307         if (!is<RenderImage>(*element.renderer()))
2308             return;
2309         CachedImage* cachedImage = downcast<RenderImage>(*element.renderer()).cachedImage();
2310         if (!cachedImage)
2311             return;
2312         RefPtr<SharedBuffer> buffer = cachedImage->resourceBuffer();
2313         if (!buffer)
2314             return;
2315         uint64_t bufferSize = buffer->size();
2316         RefPtr<SharedMemory> sharedMemoryBuffer = SharedMemory::allocate(bufferSize);
2317         memcpy(sharedMemoryBuffer->data(), buffer->data(), bufferSize);
2318         SharedMemory::Handle handle;
2319         sharedMemoryBuffer->createHandle(handle, SharedMemory::Protection::ReadOnly);
2320         send(Messages::WebPageProxy::SaveImageToLibrary(handle, bufferSize));
2321     }
2322 }
2323
2324 static inline Element* nextAssistableElement(Node* startNode, Page& page, bool isForward)
2325 {
2326     if (!is<Element>(startNode))
2327         return nullptr;
2328
2329     Element* nextElement = downcast<Element>(startNode);
2330     do {
2331         nextElement = isForward
2332             ? page.focusController().nextFocusableElement(*nextElement)
2333             : page.focusController().previousFocusableElement(*nextElement);
2334     } while (nextElement && !isAssistableElement(*nextElement));
2335
2336     return nextElement;
2337 }
2338
2339 void WebPage::focusNextAssistedNode(bool isForward, CallbackID callbackID)
2340 {
2341     Element* nextElement = nextAssistableElement(m_assistedNode.get(), *m_page, isForward);
2342     m_userIsInteracting = true;
2343     if (nextElement)
2344         nextElement->focus();
2345     m_userIsInteracting = false;
2346     send(Messages::WebPageProxy::VoidCallback(callbackID));
2347 }
2348
2349 static IntRect elementRectInRootViewCoordinates(const Node& node, const Frame& frame)
2350 {
2351     auto* view = frame.view();
2352     if (!view)
2353         return { };
2354
2355     auto* renderer = node.renderer();
2356     if (!renderer)
2357         return { };
2358
2359     return view->contentsToRootView(renderer->absoluteBoundingBoxRect());
2360 }
2361
2362 void WebPage::getAssistedNodeInformation(AssistedNodeInformation& information)
2363 {
2364     layoutIfNeeded();
2365
2366     information.elementInteractionLocation = m_lastInteractionLocation;
2367
2368     if (RenderObject* renderer = m_assistedNode->renderer()) {
2369         Frame& elementFrame = m_page->focusController().focusedOrMainFrame();
2370         information.elementRect = elementRectInRootViewCoordinates(*m_assistedNode, elementFrame);
2371         information.nodeFontSize = renderer->style().fontDescription().computedSize();
2372         information.elementIsTransparent = renderer->isTransparentRespectingParentFrames();
2373
2374         bool inFixed = false;
2375         renderer->localToContainerPoint(FloatPoint(), nullptr, UseTransforms, &inFixed);
2376         information.insideFixedPosition = inFixed;
2377         information.isRTL = renderer->style().direction() == TextDirection::RTL;
2378
2379         FrameView* frameView = elementFrame.view();
2380         if (inFixed && elementFrame.isMainFrame() && !frameView->frame().settings().visualViewportEnabled()) {
2381             IntRect currentFixedPositionRect = frameView->customFixedPositionLayoutRect();
2382             frameView->setCustomFixedPositionLayoutRect(frameView->renderView()->documentRect());
2383             information.elementRect = frameView->contentsToRootView(renderer->absoluteBoundingBoxRect());
2384             frameView->setCustomFixedPositionLayoutRect(currentFixedPositionRect);
2385             
2386             if (!information.elementRect.contains(m_lastInteractionLocation))
2387                 information.elementInteractionLocation = information.elementRect.location();
2388         } else {
2389             // Don't use the selection rect if interaction was outside the element rect.
2390             if (!information.elementRect.contains(m_lastInteractionLocation))
2391                 information.elementInteractionLocation = { };
2392         }
2393     } else
2394         information.elementRect = IntRect();
2395
2396     information.minimumScaleFactor = minimumPageScaleFactor();
2397     information.maximumScaleFactor = maximumPageScaleFactor();
2398     information.maximumScaleFactorIgnoringAlwaysScalable = maximumPageScaleFactorIgnoringAlwaysScalable();
2399     information.allowsUserScaling = m_viewportConfiguration.allowsUserScaling();
2400     information.allowsUserScalingIgnoringAlwaysScalable = m_viewportConfiguration.allowsUserScalingIgnoringAlwaysScalable();
2401     if (auto* nextElement = nextAssistableElement(m_assistedNode.get(), *m_page, true)) {
2402         if (auto* frame = nextElement->document().frame())
2403             information.nextNodeRect = elementRectInRootViewCoordinates(*nextElement, *frame);
2404         information.hasNextNode = true;
2405     }
2406     if (auto* previousElement = nextAssistableElement(m_assistedNode.get(), *m_page, false)) {
2407         if (auto* frame = previousElement->document().frame())
2408             information.previousNodeRect = elementRectInRootViewCoordinates(*previousElement, *frame);
2409         information.hasPreviousNode = true;
2410     }
2411     information.assistedNodeIdentifier = m_currentAssistedNodeIdentifier;
2412
2413     if (is<LabelableElement>(*m_assistedNode)) {
2414         auto labels = downcast<LabelableElement>(*m_assistedNode).labels();
2415         Vector<Ref<Element>> associatedLabels;
2416         for (unsigned index = 0; index < labels->length(); ++index) {
2417             if (is<Element>(labels->item(index)) && labels->item(index)->renderer())
2418                 associatedLabels.append(downcast<Element>(*labels->item(index)));
2419         }
2420         for (auto& labelElement : associatedLabels) {
2421             auto text = labelElement->innerText();
2422             if (!text.isEmpty()) {
2423                 information.label = WTFMove(text);
2424                 break;
2425             }
2426         }
2427     }
2428
2429     if (is<Element>(m_assistedNode.get())) {
2430         auto& element = downcast<Element>(*m_assistedNode);
2431         information.title = element.title();
2432         information.ariaLabel = element.attributeWithoutSynchronization(HTMLNames::aria_labelAttr);
2433     }
2434
2435     if (is<HTMLSelectElement>(*m_assistedNode)) {
2436         HTMLSelectElement& element = downcast<HTMLSelectElement>(*m_assistedNode);
2437         information.elementType = InputType::Select;
2438         const Vector<HTMLElement*>& items = element.listItems();
2439         size_t count = items.size();
2440         int parentGroupID = 0;
2441         // The parent group ID indicates the group the option belongs to and is 0 for group elements.
2442         // If there are option elements in between groups, they are given it's own group identifier.
2443         // If a select does not have groups, all the option elements have group ID 0.
2444         for (size_t i = 0; i < count; ++i) {
2445             HTMLElement* item = items[i];
2446             if (is<HTMLOptionElement>(*item)) {
2447                 HTMLOptionElement& option = downcast<HTMLOptionElement>(*item);
2448                 information.selectOptions.append(OptionItem(option.text(), false, parentGroupID, option.selected(), option.hasAttributeWithoutSynchronization(WebCore::HTMLNames::disabledAttr)));
2449             } else if (is<HTMLOptGroupElement>(*item)) {
2450                 HTMLOptGroupElement& group = downcast<HTMLOptGroupElement>(*item);
2451                 parentGroupID++;
2452                 information.selectOptions.append(OptionItem(group.groupLabelText(), true, 0, false, group.hasAttributeWithoutSynchronization(WebCore::HTMLNames::disabledAttr)));
2453             }
2454         }
2455         information.selectedIndex = element.selectedIndex();
2456         information.isMultiSelect = element.multiple();
2457     } else if (is<HTMLTextAreaElement>(*m_assistedNode)) {
2458         HTMLTextAreaElement& element = downcast<HTMLTextAreaElement>(*m_assistedNode);
2459         information.autocapitalizeType = element.autocapitalizeType();
2460         information.isAutocorrect = element.shouldAutocorrect();
2461         information.elementType = InputType::TextArea;
2462         information.isReadOnly = element.isReadOnly();
2463         information.value = element.value();
2464         information.autofillFieldName = WebCore::toAutofillFieldName(element.autofillData().fieldName);
2465         information.placeholder = element.attributeWithoutSynchronization(HTMLNames::placeholderAttr);
2466         information.inputMode = element.canonicalInputMode();
2467     } else if (is<HTMLInputElement>(*m_assistedNode)) {
2468         HTMLInputElement& element = downcast<HTMLInputElement>(*m_assistedNode);
2469         HTMLFormElement* form = element.form();
2470         if (form)
2471             information.formAction = form->getURLAttribute(WebCore::HTMLNames::actionAttr);
2472         if (auto autofillElements = WebCore::AutofillElements::computeAutofillElements(element)) {
2473             information.acceptsAutofilledLoginCredentials = true;
2474             information.isAutofillableUsernameField = autofillElements->username() == m_assistedNode;
2475         }
2476         information.representingPageURL = element.document().urlForBindings();
2477         information.autocapitalizeType = element.autocapitalizeType();
2478         information.isAutocorrect = element.shouldAutocorrect();
2479         information.placeholder = element.attributeWithoutSynchronization(HTMLNames::placeholderAttr);
2480         if (element.isPasswordField())
2481             information.elementType = InputType::Password;
2482         else if (element.isSearchField())
2483             information.elementType = InputType::Search;
2484         else if (element.isEmailField())
2485             information.elementType = InputType::Email;
2486         else if (element.isTelephoneField())
2487             information.elementType = InputType::Phone;
2488         else if (element.isNumberField())
2489             information.elementType = element.getAttribute("pattern") == "\\d*" || element.getAttribute("pattern") == "[0-9]*" ? InputType::NumberPad : InputType::Number;
2490         else if (element.isDateTimeLocalField())
2491             information.elementType = InputType::DateTimeLocal;
2492         else if (element.isDateField())
2493             information.elementType = InputType::Date;
2494         else if (element.isDateTimeField())
2495             information.elementType = InputType::DateTime;
2496         else if (element.isTimeField())
2497             information.elementType = InputType::Time;
2498         else if (element.isWeekField())
2499             information.elementType = InputType::Week;
2500         else if (element.isMonthField())
2501             information.elementType = InputType::Month;
2502         else if (element.isURLField())
2503             information.elementType = InputType::URL;
2504         else if (element.isText()) {
2505             const AtomicString& pattern = element.attributeWithoutSynchronization(HTMLNames::patternAttr);
2506             if (pattern == "\\d*" || pattern == "[0-9]*")
2507                 information.elementType = InputType::NumberPad;
2508             else {
2509                 information.elementType = InputType::Text;
2510                 if (!information.formAction.isEmpty()
2511                     && (element.getNameAttribute().contains("search") || element.getIdAttribute().contains("search") || element.attributeWithoutSynchronization(HTMLNames::titleAttr).contains("search")))
2512                     information.elementType = InputType::Search;
2513             }
2514         }
2515 #if ENABLE(INPUT_TYPE_COLOR)
2516         else if (element.isColorControl()) {
2517             information.elementType = InputType::Color;
2518 #if ENABLE(DATALIST_ELEMENT)
2519             information.suggestedColors = element.suggestedColors();
2520 #endif
2521         }
2522 #endif
2523
2524 #if ENABLE(DATALIST_ELEMENT)
2525         information.hasSuggestions = !!element.list();
2526 #endif
2527         information.inputMode = element.canonicalInputMode();
2528         information.isReadOnly = element.isReadOnly();
2529         information.value = element.value();
2530         information.valueAsNumber = element.valueAsNumber();
2531         information.autofillFieldName = WebCore::toAutofillFieldName(element.autofillData().fieldName);
2532     } else if (is<HTMLImageElement>(*m_assistedNode) && downcast<HTMLImageElement>(*m_assistedNode).hasEditableImageAttribute()) {
2533         information.elementType = InputType::Drawing;
2534         information.embeddedViewID = downcast<HTMLImageElement>(*m_assistedNode).editableImageViewID();
2535     } else if (m_assistedNode->hasEditableStyle()) {
2536         information.elementType = InputType::ContentEditable;
2537         if (is<HTMLElement>(*m_assistedNode)) {
2538             auto& assistedElement = downcast<HTMLElement>(*m_assistedNode);
2539             information.isAutocorrect = assistedElement.shouldAutocorrect();
2540             information.autocapitalizeType = assistedElement.autocapitalizeType();
2541             information.inputMode = assistedElement.canonicalInputMode();
2542         } else {
2543             information.isAutocorrect = true;
2544             information.autocapitalizeType = AutocapitalizeTypeDefault;
2545         }
2546         information.isReadOnly = false;
2547     }
2548 }
2549
2550 void WebPage::autofillLoginCredentials(const String& username, const String& password)
2551 {
2552     if (is<HTMLInputElement>(m_assistedNode.get())) {
2553         if (auto autofillElements = AutofillElements::computeAutofillElements(downcast<HTMLInputElement>(*m_assistedNode)))
2554             autofillElements->autofill(username, password);
2555     }
2556 }
2557
2558 // WebCore stores the page scale factor as float instead of double. When we get a scale from WebCore,
2559 // we need to ignore differences that are within a small rounding error on floats.
2560 static inline bool areEssentiallyEqualAsFloat(float a, float b)
2561 {
2562     return WTF::areEssentiallyEqual(a, b);
2563 }
2564
2565 void WebPage::setViewportConfigurationViewLayoutSize(const FloatSize& size, double scaleFactor, double minimumEffectiveDeviceWidth)
2566 {
2567     LOG_WITH_STREAM(VisibleRects, stream << "WebPage " << m_pageID << " setViewportConfigurationViewLayoutSize " << size << " scaleFactor " << scaleFactor << " minimumEffectiveDeviceWidth " << minimumEffectiveDeviceWidth);
2568
2569     ZoomToInitialScale shouldZoomToInitialScale = ZoomToInitialScale::No;
2570     if (m_viewportConfiguration.layoutSizeScaleFactor() != scaleFactor && areEssentiallyEqualAsFloat(m_viewportConfiguration.initialScale(), pageScaleFactor()))
2571         shouldZoomToInitialScale = ZoomToInitialScale::Yes;
2572
2573     if (m_viewportConfiguration.setViewLayoutSize(size, scaleFactor, minimumEffectiveDeviceWidth))
2574         viewportConfigurationChanged(shouldZoomToInitialScale);
2575 }
2576
2577 void WebPage::setMaximumUnobscuredSize(const FloatSize& maximumUnobscuredSize)
2578 {
2579     m_maximumUnobscuredSize = maximumUnobscuredSize;
2580     updateViewportSizeForCSSViewportUnits();
2581 }
2582
2583 void WebPage::setDeviceOrientation(int32_t deviceOrientation)
2584 {
2585     if (deviceOrientation == m_deviceOrientation)
2586         return;
2587     m_deviceOrientation = deviceOrientation;
2588     m_page->mainFrame().orientationChanged();
2589 }
2590
2591 void WebPage::setOverrideViewportArguments(const Optional<WebCore::ViewportArguments>& arguments)
2592 {
2593     if (auto* document = m_page->mainFrame().document())
2594         document->setOverrideViewportArguments(arguments);
2595 }
2596
2597 void WebPage::resetTextAutosizing()
2598 {
2599     for (Frame* frame = &m_page->mainFrame(); frame; frame = frame->tree().traverseNext()) {
2600         Document* document = frame->document();
2601         if (!document || !document->renderView())
2602             continue;
2603         document->renderView()->resetTextAutosizing();
2604     }
2605 }
2606
2607 void WebPage::dynamicViewportSizeUpdate(const FloatSize& viewLayoutSize, const WebCore::FloatSize& maximumUnobscuredSize, const FloatRect& targetExposedContentRect, const FloatRect& targetUnobscuredRect, const WebCore::FloatRect& targetUnobscuredRectInScrollViewCoordinates, const WebCore::FloatBoxExtent& targetUnobscuredSafeAreaInsets, double targetScale, int32_t deviceOrientation, DynamicViewportSizeUpdateID dynamicViewportSizeUpdateID)
2608 {
2609     SetForScope<bool> dynamicSizeUpdateGuard(m_inDynamicSizeUpdate, true);
2610     // FIXME: this does not handle the cases where the content would change the content size or scroll position from JavaScript.
2611     // To handle those cases, we would need to redo this computation on every change until the next visible content rect update.
2612     LOG_WITH_STREAM(VisibleRects, stream << "\nWebPage::dynamicViewportSizeUpdate - viewLayoutSize " << viewLayoutSize << " targetUnobscuredRect " << targetUnobscuredRect << " targetExposedContentRect " << targetExposedContentRect << " targetScale " << targetScale);
2613
2614     FrameView& frameView = *m_page->mainFrame().view();
2615     IntSize oldContentSize = frameView.contentsSize();
2616     float oldPageScaleFactor = m_page->pageScaleFactor();
2617
2618     m_dynamicSizeUpdateHistory.add(std::make_pair(oldContentSize, oldPageScaleFactor), frameView.scrollPosition());
2619
2620     RefPtr<Node> oldNodeAtCenter;
2621     double visibleHorizontalFraction = 1;
2622     float relativeHorizontalPositionInNodeAtCenter = 0;
2623     float relativeVerticalPositionInNodeAtCenter = 0;
2624     {
2625         visibleHorizontalFraction = frameView.unobscuredContentSize().width() / oldContentSize.width();
2626         IntPoint unobscuredContentRectCenter = frameView.unobscuredContentRect().center();
2627
2628         HitTestResult hitTestResult = HitTestResult(unobscuredContentRectCenter);
2629
2630         if (RenderView* mainFrameRenderView = frameView.renderView())
2631             mainFrameRenderView->hitTest(HitTestRequest(), hitTestResult);
2632
2633         if (Node* node = hitTestResult.innerNode()) {
2634             if (RenderObject* renderer = node->renderer()) {
2635                 FrameView& containingView = *node->document().frame()->view();
2636                 FloatRect boundingBox = containingView.contentsToRootView(renderer->absoluteBoundingBoxRect(true));
2637                 relativeHorizontalPositionInNodeAtCenter = (unobscuredContentRectCenter.x() - boundingBox.x()) / boundingBox.width();
2638                 relativeVerticalPositionInNodeAtCenter = (unobscuredContentRectCenter.y() - boundingBox.y()) / boundingBox.height();
2639                 oldNodeAtCenter = node;
2640             }
2641         }
2642     }
2643
2644     LOG_WITH_STREAM(VisibleRects, stream << "WebPage::dynamicViewportSizeUpdate setting view layout size to " << viewLayoutSize);
2645     m_viewportConfiguration.setViewLayoutSize(viewLayoutSize);
2646     IntSize newLayoutSize = m_viewportConfiguration.layoutSize();
2647
2648     if (setFixedLayoutSize(newLayoutSize))
2649         resetTextAutosizing();
2650
2651     setMaximumUnobscuredSize(maximumUnobscuredSize);
2652     m_page->setUnobscuredSafeAreaInsets(targetUnobscuredSafeAreaInsets);
2653
2654     frameView.updateLayoutAndStyleIfNeededRecursive();
2655
2656     IntSize newContentSize = frameView.contentsSize();
2657
2658     double scale = scaleAfterViewportWidthChange(targetScale, m_userHasChangedPageScaleFactor, m_viewportConfiguration, targetUnobscuredRectInScrollViewCoordinates.width(), newContentSize, oldContentSize, visibleHorizontalFraction);
2659     FloatRect newUnobscuredContentRect = targetUnobscuredRect;
2660     FloatRect newExposedContentRect = targetExposedContentRect;
2661
2662     bool scaleChanged = !areEssentiallyEqualAsFloat(scale, targetScale);
2663     if (scaleChanged) {
2664         // The target scale the UI is using cannot be reached by the content. We need to compute new targets based
2665         // on the viewport constraint and report everything back to the UIProcess.
2666
2667         // 1) Compute a new unobscured rect centered around the original one.
2668         double scaleDifference = targetScale / scale;
2669         double newUnobscuredRectWidth = targetUnobscuredRect.width() * scaleDifference;
2670         double newUnobscuredRectHeight = targetUnobscuredRect.height() * scaleDifference;
2671         double newUnobscuredRectX = targetUnobscuredRect.x() - (newUnobscuredRectWidth - targetUnobscuredRect.width()) / 2;
2672         double newUnobscuredRectY = targetUnobscuredRect.y() - (newUnobscuredRectHeight - targetUnobscuredRect.height()) / 2;
2673         newUnobscuredContentRect = FloatRect(newUnobscuredRectX, newUnobscuredRectY, newUnobscuredRectWidth, newUnobscuredRectHeight);
2674
2675         // 2) Extend our new unobscuredRect by the obscured margins to get a new exposed rect.
2676         double obscuredTopMargin = (targetUnobscuredRect.y() - targetExposedContentRect.y()) * scaleDifference;
2677         double obscuredLeftMargin = (targetUnobscuredRect.x() - targetExposedContentRect.x()) * scaleDifference;
2678         double obscuredBottomMargin = (targetExposedContentRect.maxY() - targetUnobscuredRect.maxY()) * scaleDifference;
2679         double obscuredRightMargin = (targetExposedContentRect.maxX() - targetUnobscuredRect.maxX()) * scaleDifference;
2680         newExposedContentRect = FloatRect(newUnobscuredRectX - obscuredLeftMargin,
2681                                           newUnobscuredRectY - obscuredTopMargin,
2682                                           newUnobscuredRectWidth + obscuredLeftMargin + obscuredRightMargin,
2683                                           newUnobscuredRectHeight + obscuredTopMargin + obscuredBottomMargin);
2684     }
2685
2686     if (oldContentSize != newContentSize || scaleChanged) {
2687         // Snap the new unobscured rect back into the content rect.
2688         newUnobscuredContentRect.setWidth(std::min(static_cast<float>(newContentSize.width()), newUnobscuredContentRect.width()));
2689         newUnobscuredContentRect.setHeight(std::min(static_cast<float>(newContentSize.height()), newUnobscuredContentRect.height()));
2690
2691         bool positionWasRestoredFromSizeUpdateHistory = false;
2692         const auto& previousPosition = m_dynamicSizeUpdateHistory.find(std::pair<IntSize, float>(newContentSize, scale));
2693         if (previousPosition != m_dynamicSizeUpdateHistory.end()) {
2694             IntPoint restoredPosition = previousPosition->value;
2695             FloatPoint deltaPosition(restoredPosition.x() - newUnobscuredContentRect.x(), restoredPosition.y() - newUnobscuredContentRect.y());
2696             newUnobscuredContentRect.moveBy(deltaPosition);
2697             newExposedContentRect.moveBy(deltaPosition);
2698             positionWasRestoredFromSizeUpdateHistory = true;
2699         } else if (oldContentSize != newContentSize) {
2700             FloatPoint newRelativeContentCenter;
2701
2702             if (RenderObject* renderer = oldNodeAtCenter ? oldNodeAtCenter->renderer() : nullptr) {
2703                 FrameView& containingView = *oldNodeAtCenter->document().frame()->view();
2704                 FloatRect newBoundingBox = containingView.contentsToRootView(renderer->absoluteBoundingBoxRect(true));
2705                 newRelativeContentCenter = FloatPoint(newBoundingBox.x() + relativeHorizontalPositionInNodeAtCenter * newBoundingBox.width(), newBoundingBox.y() + relativeVerticalPositionInNodeAtCenter * newBoundingBox.height());
2706             } else
2707                 newRelativeContentCenter = relativeCenterAfterContentSizeChange(targetUnobscuredRect, oldContentSize, newContentSize);
2708
2709             FloatPoint newUnobscuredContentRectCenter = newUnobscuredContentRect.center();
2710             FloatPoint positionDelta(newRelativeContentCenter.x() - newUnobscuredContentRectCenter.x(), newRelativeContentCenter.y() - newUnobscuredContentRectCenter.y());
2711             newUnobscuredContentRect.moveBy(positionDelta);
2712             newExposedContentRect.moveBy(positionDelta);
2713         }
2714
2715         // Make the top/bottom edges "sticky" within 1 pixel.
2716         if (!positionWasRestoredFromSizeUpdateHistory) {
2717             if (targetUnobscuredRect.maxY() > oldContentSize.height() - 1) {
2718                 float bottomVerticalPosition = newContentSize.height() - newUnobscuredContentRect.height();
2719                 newUnobscuredContentRect.setY(bottomVerticalPosition);
2720                 newExposedContentRect.setY(bottomVerticalPosition);
2721             }
2722             if (targetUnobscuredRect.y() < 1) {
2723                 newUnobscuredContentRect.setY(0);
2724                 newExposedContentRect.setY(0);
2725             }
2726
2727             bool likelyResponsiveDesignViewport = newLayoutSize.width() == viewLayoutSize.width() && areEssentiallyEqualAsFloat(scale, 1);
2728             bool contentBleedsOutsideLayoutWidth = newContentSize.width() > newLayoutSize.width();
2729             bool originalScrollPositionWasOnTheLeftEdge = targetUnobscuredRect.x() <= 0;
2730             if (likelyResponsiveDesignViewport && contentBleedsOutsideLayoutWidth && originalScrollPositionWasOnTheLeftEdge) {
2731                 // This is a special heuristics for "responsive" design with odd layout. It is quite common for responsive design
2732                 // to have content "bleeding" outside of the minimal layout width, usually from an image or table larger than expected.
2733                 // In those cases, the design usually does not adapt to the new width and remain at the newLayoutSize except for the
2734                 // large boxes.
2735                 // It is worth revisiting this special case as web developers get better with responsive design.
2736                 newExposedContentRect.setX(0);
2737                 newUnobscuredContentRect.setX(0);
2738             }
2739         }
2740
2741         float horizontalAdjustment = 0;
2742         if (newUnobscuredContentRect.maxX() > newContentSize.width())
2743             horizontalAdjustment -= newUnobscuredContentRect.maxX() - newContentSize.width();
2744         float verticalAdjustment = 0;
2745         if (newUnobscuredContentRect.maxY() > newContentSize.height())
2746             verticalAdjustment -= newUnobscuredContentRect.maxY() - newContentSize.height();
2747         if (newUnobscuredContentRect.x() < 0)
2748             horizontalAdjustment += - newUnobscuredContentRect.x();
2749         if (newUnobscuredContentRect.y() < 0)
2750             verticalAdjustment += - newUnobscuredContentRect.y();
2751
2752         FloatPoint adjustmentDelta(horizontalAdjustment, verticalAdjustment);
2753         newUnobscuredContentRect.moveBy(adjustmentDelta);
2754         newExposedContentRect.moveBy(adjustmentDelta);
2755     }
2756
2757     frameView.setScrollVelocity(0, 0, 0, MonotonicTime::now());
2758
2759     IntPoint roundedUnobscuredContentRectPosition = roundedIntPoint(newUnobscuredContentRect.location());
2760     frameView.setUnobscuredContentSize(newUnobscuredContentRect.size());
2761     m_drawingArea->setExposedContentRect(newExposedContentRect);
2762
2763     scalePage(scale, roundedUnobscuredContentRectPosition);
2764
2765     frameView.updateLayoutAndStyleIfNeededRecursive();
2766
2767     auto& settings = frameView.frame().settings();
2768     if (settings.visualViewportEnabled()) {
2769         LayoutRect documentRect = IntRect(frameView.scrollOrigin(), frameView.contentsSize());
2770         auto layoutViewportSize = FrameView::expandedLayoutViewportSize(frameView.baseLayoutViewportSize(), LayoutSize(documentRect.size()), settings.layoutViewportHeightExpansionFactor());
2771         LayoutRect layoutViewportRect = FrameView::computeUpdatedLayoutViewportRect(frameView.layoutViewportRect(), documentRect, LayoutSize(newUnobscuredContentRect.size()), LayoutRect(newUnobscuredContentRect), layoutViewportSize, frameView.minStableLayoutViewportOrigin(), frameView.maxStableLayoutViewportOrigin(), FrameView::LayoutViewportConstraint::ConstrainedToDocumentRect);
2772         frameView.setLayoutViewportOverrideRect(layoutViewportRect);
2773     } else {
2774         IntRect fixedPositionLayoutRect = enclosingIntRect(frameView.viewportConstrainedObjectsRect());
2775         frameView.setCustomFixedPositionLayoutRect(fixedPositionLayoutRect);
2776     }
2777
2778     frameView.setCustomSizeForResizeEvent(expandedIntSize(targetUnobscuredRectInScrollViewCoordinates.size()));
2779     setDeviceOrientation(deviceOrientation);
2780     frameView.setScrollOffset(roundedUnobscuredContentRectPosition);
2781
2782     m_drawingArea->scheduleCompositingLayerFlush();
2783
2784     m_pendingDynamicViewportSizeUpdateID = dynamicViewportSizeUpdateID;
2785 }
2786
2787 void WebPage::resetViewportDefaultConfiguration(WebFrame* frame, bool hasMobileDocType)
2788 {
2789     LOG_WITH_STREAM(VisibleRects, stream << "WebPage " << m_pageID << " resetViewportDefaultConfiguration");
2790     if (m_useTestingViewportConfiguration) {
2791         m_viewportConfiguration.setDefaultConfiguration(ViewportConfiguration::testingParameters());
2792         return;
2793     }
2794
2795     auto parametersForStandardFrame = [&] {
2796         if (m_page->settings().shouldIgnoreMetaViewport())
2797             return ViewportConfiguration::nativeWebpageParameters();
2798
2799         return ViewportConfiguration::webpageParameters();
2800     };
2801
2802     if (!frame) {
2803         m_viewportConfiguration.setDefaultConfiguration(parametersForStandardFrame());
2804         return;
2805     }
2806
2807     if (hasMobileDocType) {
2808         m_viewportConfiguration.setDefaultConfiguration(ViewportConfiguration::xhtmlMobileParameters());
2809         return;
2810     }
2811
2812     Document* document = frame->coreFrame()->document();
2813     if (document->isImageDocument())
2814         m_viewportConfiguration.setDefaultConfiguration(ViewportConfiguration::imageDocumentParameters());
2815     else if (document->isTextDocument())
2816         m_viewportConfiguration.setDefaultConfiguration(ViewportConfiguration::textDocumentParameters());
2817     else
2818         m_viewportConfiguration.setDefaultConfiguration(parametersForStandardFrame());
2819 }
2820
2821 void WebPage::viewportConfigurationChanged(ZoomToInitialScale zoomToInitialScale)
2822 {
2823     if (setFixedLayoutSize(m_viewportConfiguration.layoutSize()))
2824         resetTextAutosizing();
2825
2826     double initialScale = m_viewportConfiguration.initialScale();
2827     double scale;
2828     if (m_userHasChangedPageScaleFactor && zoomToInitialScale == ZoomToInitialScale::No)
2829         scale = std::max(std::min(pageScaleFactor(), m_viewportConfiguration.maximumScale()), m_viewportConfiguration.minimumScale());
2830     else
2831         scale = initialScale;
2832
2833     LOG_WITH_STREAM(VisibleRects, stream << "WebPage " << m_pageID << " viewportConfigurationChanged - setting zoomedOutPageScaleFactor to " << m_viewportConfiguration.minimumScale() << " and scale to " << scale);
2834
2835     m_page->setZoomedOutPageScaleFactor(m_viewportConfiguration.minimumScale());
2836
2837     updateViewportSizeForCSSViewportUnits();
2838
2839     FrameView& frameView = *mainFrameView();
2840     IntPoint scrollPosition = frameView.scrollPosition();
2841     if (!m_hasReceivedVisibleContentRectsAfterDidCommitLoad) {
2842         FloatSize minimumLayoutSizeInScrollViewCoordinates = m_viewportConfiguration.viewLayoutSize();
2843         minimumLayoutSizeInScrollViewCoordinates.scale(1 / scale);
2844         IntSize minimumLayoutSizeInDocumentCoordinates = roundedIntSize(minimumLayoutSizeInScrollViewCoordinates);
2845         frameView.setUnobscuredContentSize(minimumLayoutSizeInDocumentCoordinates);
2846         frameView.setScrollVelocity(0, 0, 0, MonotonicTime::now());
2847
2848         // FIXME: We could send down the obscured margins to find a better exposed rect and unobscured rect.
2849         // It is not a big deal at the moment because the tile coverage will always extend past the obscured bottom inset.
2850         m_drawingArea->setExposedContentRect(FloatRect(scrollPosition, minimumLayoutSizeInDocumentCoordinates));
2851     }
2852     scalePage(scale, scrollPosition);
2853     
2854     if (!m_hasReceivedVisibleContentRectsAfterDidCommitLoad) {
2855         // This takes scale into account, so do after the scale change.
2856         frameView.setCustomFixedPositionLayoutRect(enclosingIntRect(frameView.viewportConstrainedObjectsRect()));
2857
2858         frameView.setCustomSizeForResizeEvent(expandedIntSize(m_viewportConfiguration.minimumLayoutSize()));
2859     }
2860 }
2861
2862 void WebPage::updateViewportSizeForCSSViewportUnits()
2863 {
2864     FloatSize largestUnobscuredSize = m_maximumUnobscuredSize;
2865     if (largestUnobscuredSize.isEmpty())
2866         largestUnobscuredSize = m_viewportConfiguration.viewLayoutSize();
2867
2868     FrameView& frameView = *mainFrameView();
2869     largestUnobscuredSize.scale(1 / m_viewportConfiguration.initialScaleIgnoringContentSize());
2870     frameView.setViewportSizeForCSSViewportUnits(roundedIntSize(largestUnobscuredSize));
2871 }
2872
2873 void WebPage::applicationWillResignActive()
2874 {
2875     [[NSNotificationCenter defaultCenter] postNotificationName:WebUIApplicationWillResignActiveNotification object:nil];
2876     if (m_page)
2877         m_page->applicationWillResignActive();
2878 }
2879
2880 void WebPage::applicationDidEnterBackground(bool isSuspendedUnderLock)
2881 {
2882     [[NSNotificationCenter defaultCenter] postNotificationName:WebUIApplicationDidEnterBackgroundNotification object:nil userInfo:@{@"isSuspendedUnderLock": [NSNumber numberWithBool:isSuspendedUnderLock]}];
2883
2884     m_isSuspendedUnderLock = isSuspendedUnderLock;
2885     freezeLayerTree(LayerTreeFreezeReason::BackgroundApplication);
2886
2887     if (m_page)
2888         m_page->applicationDidEnterBackground();
2889 }
2890
2891 void WebPage::applicationDidFinishSnapshottingAfterEnteringBackground()
2892 {
2893     markLayersVolatile();
2894 }
2895
2896 void WebPage::applicationWillEnterForeground(bool isSuspendedUnderLock)
2897 {
2898     m_isSuspendedUnderLock = false;
2899     cancelMarkLayersVolatile();
2900     unfreezeLayerTree(LayerTreeFreezeReason::BackgroundApplication);
2901
2902     [[NSNotificationCenter defaultCenter] postNotificationName:WebUIApplicationWillEnterForegroundNotification object:nil userInfo:@{@"isSuspendedUnderLock": @(isSuspendedUnderLock)}];
2903
2904     if (m_page)
2905         m_page->applicationWillEnterForeground();
2906 }
2907
2908 void WebPage::applicationDidBecomeActive()
2909 {
2910     [[NSNotificationCenter defaultCenter] postNotificationName:WebUIApplicationDidBecomeActiveNotification object:nil];
2911     if (m_page)
2912         m_page->applicationDidBecomeActive();
2913 }
2914
2915 static inline void adjustVelocityDataForBoundedScale(double& horizontalVelocity, double& verticalVelocity, double& scaleChangeRate, double exposedRectScale, double minimumScale, double maximumScale)
2916 {
2917     if (scaleChangeRate) {
2918         horizontalVelocity = 0;
2919         verticalVelocity = 0;
2920     }
2921
2922     if (exposedRectScale >= maximumScale || exposedRectScale <= minimumScale)
2923         scaleChangeRate = 0;
2924 }
2925
2926 Optional<float> WebPage::scaleFromUIProcess(const VisibleContentRectUpdateInfo& visibleContentRectUpdateInfo) const
2927 {
2928     auto transactionIDForLastScaleFromUIProcess = visibleContentRectUpdateInfo.lastLayerTreeTransactionID();
2929     if (m_lastTransactionIDWithScaleChange > transactionIDForLastScaleFromUIProcess)
2930         return WTF::nullopt;
2931
2932     float scaleFromUIProcess = visibleContentRectUpdateInfo.scale();
2933     float currentScale = m_page->pageScaleFactor();
2934
2935     double scaleNoiseThreshold = 0.005;
2936     if (!m_isInStableState && fabs(scaleFromUIProcess - currentScale) < scaleNoiseThreshold) {
2937         // Tiny changes of scale during interactive zoom cause content to jump by one pixel, creating
2938         // visual noise. We filter those useless updates.
2939         scaleFromUIProcess = currentScale;
2940     }
2941     
2942     scaleFromUIProcess = std::min<float>(m_viewportConfiguration.maximumScale(), std::max<float>(m_viewportConfiguration.minimumScale(), scaleFromUIProcess));
2943     if (areEssentiallyEqualAsFloat(currentScale, scaleFromUIProcess))
2944         return WTF::nullopt;
2945
2946     return scaleFromUIProcess;
2947 }
2948
2949 static bool selectionIsInsideFixedPositionContainer(Frame& frame)
2950 {
2951     auto& selection = frame.selection().selection();
2952     if (selection.isNone())
2953         return false;
2954
2955     bool isInsideFixedPosition = false;
2956     if (selection.isCaret()) {
2957         frame.selection().absoluteCaretBounds(&isInsideFixedPosition);
2958         return isInsideFixedPosition;
2959     }
2960
2961     selection.visibleStart().absoluteCaretBounds(&isInsideFixedPosition);
2962     if (isInsideFixedPosition)
2963         return true;
2964
2965     selection.visibleEnd().absoluteCaretBounds(&isInsideFixedPosition);
2966     return isInsideFixedPosition;
2967 }
2968
2969 void WebPage::updateVisibleContentRects(const VisibleContentRectUpdateInfo& visibleContentRectUpdateInfo, MonotonicTime oldestTimestamp)
2970 {
2971     LOG_WITH_STREAM(VisibleRects, stream << "\nWebPage " << m_pageID << " updateVisibleContentRects " << visibleContentRectUpdateInfo);
2972
2973     // Skip any VisibleContentRectUpdate that have been queued before DidCommitLoad suppresses the updates in the UIProcess.
2974     if (visibleContentRectUpdateInfo.lastLayerTreeTransactionID() < m_mainFrame->firstLayerTreeTransactionIDAfterDidCommitLoad() && !visibleContentRectUpdateInfo.isFirstUpdateForNewViewSize())
2975         return;
2976
2977     m_hasReceivedVisibleContentRectsAfterDidCommitLoad = true;
2978     m_isInStableState = visibleContentRectUpdateInfo.inStableState();
2979
2980     auto scaleFromUIProcess = this->scaleFromUIProcess(visibleContentRectUpdateInfo);
2981
2982     // Skip progressively redrawing tiles if pinch-zooming while the system is under memory pressure.
2983     if (scaleFromUIProcess && !m_isInStableState && MemoryPressureHandler::singleton().isUnderMemoryPressure())
2984         return;
2985
2986     if (m_isInStableState)
2987         m_hasStablePageScaleFactor = true;
2988     else {
2989         if (!m_oldestNonStableUpdateVisibleContentRectsTimestamp)
2990             m_oldestNonStableUpdateVisibleContentRectsTimestamp = oldestTimestamp;
2991     }
2992
2993     float scaleToUse = scaleFromUIProcess.value_or(m_page->pageScaleFactor());
2994     FloatRect exposedContentRect = visibleContentRectUpdateInfo.exposedContentRect();
2995     FloatRect adjustedExposedContentRect = adjustExposedRectForNewScale(exposedContentRect, visibleContentRectUpdateInfo.scale(), scaleToUse);
2996     m_drawingArea->setExposedContentRect(adjustedExposedContentRect);
2997
2998     IntPoint scrollPosition = roundedIntPoint(visibleContentRectUpdateInfo.unobscuredContentRect().location());
2999
3000     bool hasSetPageScale = false;
3001     if (scaleFromUIProcess) {
3002         m_scaleWasSetByUIProcess = true;
3003         m_hasStablePageScaleFactor = m_isInStableState;
3004
3005         m_dynamicSizeUpdateHistory.clear();
3006
3007         m_page->setPageScaleFactor(scaleFromUIProcess.value(), scrollPosition, m_isInStableState);
3008         hasSetPageScale = true;
3009         send(Messages::WebPageProxy::PageScaleFactorDidChange(scaleFromUIProcess.value()));
3010     }
3011     
3012     if (!hasSetPageScale && m_isInStableState) {
3013         m_page->setPageScaleFactor(scaleToUse, scrollPosition, true);
3014         hasSetPageScale = true;
3015     }
3016
3017     auto& frame = m_page->mainFrame();
3018     FrameView& frameView = *frame.view();
3019     if (scrollPosition != frameView.scrollPosition())
3020         m_dynamicSizeUpdateHistory.clear();
3021
3022     if (m_viewportConfiguration.setCanIgnoreScalingConstraints(m_ignoreViewportScalingConstraints && visibleContentRectUpdateInfo.allowShrinkToFit()))
3023         viewportConfigurationChanged();
3024
3025     frameView.setUnobscuredContentSize(visibleContentRectUpdateInfo.unobscuredContentRect().size());
3026     m_page->setObscuredInsets(visibleContentRectUpdateInfo.obscuredInsets());
3027     m_page->setUnobscuredSafeAreaInsets(visibleContentRectUpdateInfo.unobscuredSafeAreaInsets());
3028     m_page->setEnclosedInScrollableAncestorView(visibleContentRectUpdateInfo.enclosedInScrollableAncestorView());
3029
3030     double horizontalVelocity = visibleContentRectUpdateInfo.horizontalVelocity();
3031     double verticalVelocity = visibleContentRectUpdateInfo.verticalVelocity();
3032     double scaleChangeRate = visibleContentRectUpdateInfo.scaleChangeRate();
3033     adjustVelocityDataForBoundedScale(horizontalVelocity, verticalVelocity, scaleChangeRate, visibleContentRectUpdateInfo.scale(), m_viewportConfiguration.minimumScale(), m_viewportConfiguration.maximumScale());
3034
3035     frameView.setScrollVelocity(horizontalVelocity, verticalVelocity, scaleChangeRate, visibleContentRectUpdateInfo.timestamp());
3036
3037     if (m_isInStableState) {
3038         if (frameView.frame().settings().visualViewportEnabled()) {
3039             if (visibleContentRectUpdateInfo.unobscuredContentRect() != visibleContentRectUpdateInfo.unobscuredContentRectRespectingInputViewBounds())
3040                 frameView.setVisualViewportOverrideRect(LayoutRect(visibleContentRectUpdateInfo.unobscuredContentRectRespectingInputViewBounds()));
3041             else
3042                 frameView.setVisualViewportOverrideRect(WTF::nullopt);
3043
3044             LOG_WITH_STREAM(VisibleRects, stream << "WebPage::updateVisibleContentRects - setLayoutViewportOverrideRect " << visibleContentRectUpdateInfo.customFixedPositionRect());
3045             frameView.setLayoutViewportOverrideRect(LayoutRect(visibleContentRectUpdateInfo.customFixedPositionRect()));
3046             if (selectionIsInsideFixedPositionContainer(frame)) {
3047                 // Ensure that the next layer tree commit contains up-to-date caret/selection rects.
3048                 frameView.frame().selection().setCaretRectNeedsUpdate();
3049                 sendPartialEditorStateAndSchedulePostLayoutUpdate();
3050             }
3051         } else
3052             frameView.setCustomFixedPositionLayoutRect(enclosingIntRect(visibleContentRectUpdateInfo.customFixedPositionRect()));
3053     }
3054
3055     if (!visibleContentRectUpdateInfo.isChangingObscuredInsetsInteractively())
3056         frameView.setCustomSizeForResizeEvent(expandedIntSize(visibleContentRectUpdateInfo.unobscuredRectInScrollViewCoordinates().size()));
3057
3058     if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator()) {
3059         ViewportRectStability viewportStability = ViewportRectStability::Stable;
3060         ScrollingLayerPositionAction layerAction = ScrollingLayerPositionAction::Sync;
3061         
3062         if (visibleContentRectUpdateInfo.isChangingObscuredInsetsInteractively()) {
3063             viewportStability = ViewportRectStability::ChangingObscuredInsetsInteractively;
3064             layerAction = ScrollingLayerPositionAction::SetApproximate;
3065         } else if (!m_isInStableState) {
3066             viewportStability = ViewportRectStability::Unstable;
3067             layerAction = ScrollingLayerPositionAction::SetApproximate;
3068         }
3069         scrollingCoordinator->reconcileScrollingState(frameView, scrollPosition, visibleContentRectUpdateInfo.customFixedPositionRect(), false, viewportStability, layerAction);
3070     }
3071 }
3072
3073 void WebPage::willStartUserTriggeredZooming()
3074 {
3075     m_page->diagnosticLoggingClient().logDiagnosticMessage(DiagnosticLoggingKeys::webViewKey(), DiagnosticLoggingKeys::userZoomActionKey(), ShouldSample::No);
3076     m_userHasChangedPageScaleFactor = true;
3077 }
3078
3079 #if ENABLE(IOS_TOUCH_EVENTS)
3080 void WebPage::dispatchAsynchronousTouchEvents(const Vector<WebTouchEvent, 1>& queue)
3081 {
3082     bool ignored;
3083     for (const WebTouchEvent& event : queue)
3084         dispatchTouchEvent(event, ignored);
3085 }
3086 #endif
3087
3088 void WebPage::computePagesForPrintingAndDrawToPDF(uint64_t frameID, const PrintInfo& printInfo, CallbackID callbackID, Messages::WebPage::ComputePagesForPrintingAndDrawToPDF::DelayedReply&& reply)
3089 {
3090     if (printInfo.snapshotFirstPage) {
3091         reply(1);
3092         IntSize snapshotSize { FloatSize { printInfo.availablePaperWidth, printInfo.availablePaperHeight } };
3093         IntRect snapshotRect { {0, 0}, snapshotSize };
3094         auto pdfData = pdfSnapshotAtSize(snapshotRect, snapshotSize, 0);
3095         send(Messages::WebPageProxy::DrawToPDFCallback(IPC::DataReference(CFDataGetBytePtr(pdfData.get()), CFDataGetLength(pdfData.get())), callbackID));
3096         return;
3097     }
3098
3099     Vector<WebCore::IntRect> pageRects;
3100     double totalScaleFactor;
3101     computePagesForPrintingImpl(frameID, printInfo, pageRects, totalScaleFactor);
3102
3103     ASSERT(pageRects.size() >= 1);
3104     std::size_t pageCount = pageRects.size();
3105     ASSERT(pageCount <= std::numeric_limits<uint32_t>::max());
3106     reply(pageCount);
3107
3108     RetainPtr<CFMutableDataRef> pdfPageData;
3109     drawPagesToPDFImpl(frameID, printInfo, 0, pageCount, pdfPageData);
3110     send(Messages::WebPageProxy::DrawToPDFCallback(IPC::DataReference(CFDataGetBytePtr(pdfPageData.get()), CFDataGetLength(pdfPageData.get())), callbackID));
3111
3112     endPrinting();
3113 }
3114
3115 void WebPage::contentSizeCategoryDidChange(const String& contentSizeCategory)
3116 {
3117     RenderThemeIOS::setContentSizeCategory(contentSizeCategory);
3118     Page::updateStyleForAllPagesAfterGlobalChangeInEnvironment();
3119 }
3120
3121 String WebPage::platformUserAgent(const URL&) const
3122 {
3123     return String();
3124 }
3125
3126 void WebPage::hardwareKeyboardAvailabilityChanged()
3127 {
3128     if (auto* focusedFrame = m_page->focusController().focusedFrame())
3129         focusedFrame->eventHandler().capsLockStateMayHaveChanged();
3130 }
3131
3132 #if USE(QUICK_LOOK)
3133 void WebPage::didReceivePasswordForQuickLookDocument(const String& password)
3134 {
3135     WebPreviewLoaderClient::didReceivePassword(password, m_pageID);
3136 }
3137 #endif
3138
3139 bool WebPage::platformPrefersTextLegibilityBasedZoomScaling() const
3140 {
3141 #if PLATFORM(WATCHOS)
3142     return true;
3143 #else
3144     return false;
3145 #endif
3146 }
3147
3148 #if ENABLE(MEDIA_STREAM)
3149 void WebPage::prepareToSendUserMediaPermissionRequest()
3150 {
3151     static std::once_flag once;
3152     std::call_once(once, [] {
3153         if (!canLoadAVSystemController_PIDToInheritApplicationStateFrom())
3154             return;
3155
3156         NSError *error = nil;
3157         [[getAVSystemControllerClass() sharedAVSystemController] setAttribute:@(WebCore::presentingApplicationPID()) forKey:getAVSystemController_PIDToInheritApplicationStateFrom() error:&error];
3158         if (error)
3159             WTFLogAlways("Failed to set up PID proxying: %s", error.localizedDescription.UTF8String);
3160     });
3161 }
3162 #endif
3163
3164 } // namespace WebKit
3165
3166 #endif // PLATFORM(IOS_FAMILY)