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