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