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