02ae36d7459a12fa313aef56324251851d778b39
[WebKit-https.git] / Source / WebKit2 / WebProcess / WebPage / mac / WebPageMac.mm
1 /*
2  * Copyright (C) 2010, 2011, 2012 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(MAC)
30
31 #import "ActionMenuHitTestResult.h"
32 #import "AttributedString.h"
33 #import "DataReference.h"
34 #import "DictionaryPopupInfo.h"
35 #import "EditingRange.h"
36 #import "EditorState.h"
37 #import "PDFKitImports.h"
38 #import "PageBanner.h"
39 #import "PluginView.h"
40 #import "PrintInfo.h"
41 #import "WKAccessibilityWebPageObjectMac.h"
42 #import "WebCoreArgumentCoders.h"
43 #import "WebEvent.h"
44 #import "WebEventConversion.h"
45 #import "WebFrame.h"
46 #import "WebImage.h"
47 #import "WebInspector.h"
48 #import "WebPageProxyMessages.h"
49 #import "WebPasteboardOverrides.h"
50 #import "WebPreferencesStore.h"
51 #import "WebProcess.h"
52 #import <PDFKit/PDFKit.h>
53 #import <QuartzCore/QuartzCore.h>
54 #import <WebCore/AXObjectCache.h>
55 #import <WebCore/BackForwardController.h>
56 #import <WebCore/DataDetectorsSPI.h>
57 #import <WebCore/EventHandler.h>
58 #import <WebCore/FocusController.h>
59 #import <WebCore/FrameLoader.h>
60 #import <WebCore/FrameView.h>
61 #import <WebCore/GraphicsContext.h>
62 #import <WebCore/HTMLConverter.h>
63 #import <WebCore/HitTestResult.h>
64 #import <WebCore/KeyboardEvent.h>
65 #import <WebCore/MIMETypeRegistry.h>
66 #import <WebCore/MainFrame.h>
67 #import <WebCore/NetworkingContext.h>
68 #import <WebCore/Page.h>
69 #import <WebCore/PlatformKeyboardEvent.h>
70 #import <WebCore/PluginDocument.h>
71 #import <WebCore/RenderElement.h>
72 #import <WebCore/RenderObject.h>
73 #import <WebCore/RenderStyle.h>
74 #import <WebCore/RenderView.h>
75 #import <WebCore/ResourceHandle.h>
76 #import <WebCore/ScrollView.h>
77 #import <WebCore/StyleInheritedData.h>
78 #import <WebCore/TextIterator.h>
79 #import <WebCore/VisibleUnits.h>
80 #import <WebCore/WindowsKeyboardCodes.h>
81 #import <WebCore/htmlediting.h>
82 #import <WebKitSystemInterface.h>
83
84 using namespace WebCore;
85
86 namespace WebKit {
87
88 void WebPage::platformInitialize()
89 {
90 #if USE(CFNETWORK)
91     m_page->addSchedulePair(SchedulePair::create([[NSRunLoop currentRunLoop] getCFRunLoop], kCFRunLoopCommonModes));
92 #else
93     m_page->addSchedulePair(SchedulePair::create([NSRunLoop currentRunLoop], kCFRunLoopCommonModes));
94 #endif
95
96     WKAccessibilityWebPageObject* mockAccessibilityElement = [[[WKAccessibilityWebPageObject alloc] init] autorelease];
97
98     // Get the pid for the starting process.
99     pid_t pid = WebProcess::shared().presenterApplicationPid();    
100     WKAXInitializeElementWithPresenterPid(mockAccessibilityElement, pid);
101     [mockAccessibilityElement setWebPage:this];
102     
103     // send data back over
104     NSData* remoteToken = (NSData *)WKAXRemoteTokenForElement(mockAccessibilityElement); 
105     IPC::DataReference dataToken = IPC::DataReference(reinterpret_cast<const uint8_t*>([remoteToken bytes]), [remoteToken length]);
106     send(Messages::WebPageProxy::RegisterWebProcessAccessibilityToken(dataToken));
107     m_mockAccessibilityElement = mockAccessibilityElement;
108 }
109
110 void WebPage::platformDetach()
111 {
112     [m_mockAccessibilityElement setWebPage:nullptr];
113 }
114     
115 NSObject *WebPage::accessibilityObjectForMainFramePlugin()
116 {
117     if (!m_page)
118         return 0;
119     
120     if (PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame()))
121         return pluginView->accessibilityObject();
122
123     return 0;
124 }
125
126 void WebPage::platformPreferencesDidChange(const WebPreferencesStore& store)
127 {
128 }
129
130 bool WebPage::shouldUsePDFPlugin() const
131 {
132     return pdfPluginEnabled() && classFromPDFKit(@"PDFLayerController");
133 }
134
135 typedef HashMap<String, String> SelectorNameMap;
136
137 // Map selectors into Editor command names.
138 // This is not needed for any selectors that have the same name as the Editor command.
139 static const SelectorNameMap* createSelectorExceptionMap()
140 {
141     SelectorNameMap* map = new HashMap<String, String>;
142
143     map->add("insertNewlineIgnoringFieldEditor:", "InsertNewline");
144     map->add("insertParagraphSeparator:", "InsertNewline");
145     map->add("insertTabIgnoringFieldEditor:", "InsertTab");
146     map->add("pageDown:", "MovePageDown");
147     map->add("pageDownAndModifySelection:", "MovePageDownAndModifySelection");
148     map->add("pageUp:", "MovePageUp");
149     map->add("pageUpAndModifySelection:", "MovePageUpAndModifySelection");
150
151     return map;
152 }
153
154 static String commandNameForSelectorName(const String& selectorName)
155 {
156     // Check the exception map first.
157     static const SelectorNameMap* exceptionMap = createSelectorExceptionMap();
158     SelectorNameMap::const_iterator it = exceptionMap->find(selectorName);
159     if (it != exceptionMap->end())
160         return it->value;
161
162     // Remove the trailing colon.
163     // No need to capitalize the command name since Editor command names are not case sensitive.
164     size_t selectorNameLength = selectorName.length();
165     if (selectorNameLength < 2 || selectorName[selectorNameLength - 1] != ':')
166         return String();
167     return selectorName.left(selectorNameLength - 1);
168 }
169
170 static Frame* frameForEvent(KeyboardEvent* event)
171 {
172     Node* node = event->target()->toNode();
173     ASSERT(node);
174     Frame* frame = node->document().frame();
175     ASSERT(frame);
176     return frame;
177 }
178
179 bool WebPage::executeKeypressCommandsInternal(const Vector<WebCore::KeypressCommand>& commands, KeyboardEvent* event)
180 {
181     Frame& frame = event ? *frameForEvent(event) : m_page->focusController().focusedOrMainFrame();
182     ASSERT(frame.page() == corePage());
183
184     bool eventWasHandled = false;
185     for (size_t i = 0; i < commands.size(); ++i) {
186         if (commands[i].commandName == "insertText:") {
187             if (frame.editor().hasComposition()) {
188                 eventWasHandled = true;
189                 frame.editor().confirmComposition(commands[i].text);
190             } else {
191                 if (!frame.editor().canEdit())
192                     continue;
193
194                 // An insertText: might be handled by other responders in the chain if we don't handle it.
195                 // One example is space bar that results in scrolling down the page.
196                 eventWasHandled |= frame.editor().insertText(commands[i].text, event);
197             }
198         } else {
199             Editor::Command command = frame.editor().command(commandNameForSelectorName(commands[i].commandName));
200             if (command.isSupported()) {
201                 bool commandExecutedByEditor = command.execute(event);
202                 eventWasHandled |= commandExecutedByEditor;
203                 if (!commandExecutedByEditor) {
204                     bool performedNonEditingBehavior = event->keyEvent()->type() == PlatformEvent::RawKeyDown && performNonEditingBehaviorForSelector(commands[i].commandName, event);
205                     eventWasHandled |= performedNonEditingBehavior;
206                 }
207             } else {
208                 bool commandWasHandledByUIProcess = false;
209                 WebProcess::shared().parentProcessConnection()->sendSync(Messages::WebPageProxy::ExecuteSavedCommandBySelector(commands[i].commandName), 
210                     Messages::WebPageProxy::ExecuteSavedCommandBySelector::Reply(commandWasHandledByUIProcess), m_pageID);
211                 eventWasHandled |= commandWasHandledByUIProcess;
212             }
213         }
214     }
215     return eventWasHandled;
216 }
217
218 bool WebPage::handleEditingKeyboardEvent(KeyboardEvent* event)
219 {
220     Frame* frame = frameForEvent(event);
221     
222     const PlatformKeyboardEvent* platformEvent = event->keyEvent();
223     if (!platformEvent)
224         return false;
225     const Vector<KeypressCommand>& commands = event->keypressCommands();
226
227     ASSERT(!platformEvent->macEvent()); // Cannot have a native event in WebProcess.
228
229     // Don't handle Esc while handling keydown event, we need to dispatch a keypress first.
230     if (platformEvent->type() != PlatformEvent::Char && platformEvent->windowsVirtualKeyCode() == VK_ESCAPE && commands.size() == 1 && commandNameForSelectorName(commands[0].commandName) == "cancelOperation")
231         return false;
232
233     bool eventWasHandled = false;
234
235     // Are there commands that could just cause text insertion if executed via Editor?
236     // WebKit doesn't have enough information about mode to decide how they should be treated, so we leave it upon WebCore
237     // to either handle them immediately (e.g. Tab that changes focus) or let a keypress event be generated
238     // (e.g. Tab that inserts a Tab character, or Enter).
239     bool haveTextInsertionCommands = false;
240     for (auto& command : commands) {
241         if (frame->editor().command(commandNameForSelectorName(command.commandName)).isTextInsertion())
242             haveTextInsertionCommands = true;
243     }
244     // If there are no text insertion commands, default keydown handler is the right time to execute the commands.
245     // Keypress (Char event) handler is the latest opportunity to execute.
246     if (!haveTextInsertionCommands || platformEvent->type() == PlatformEvent::Char) {
247         eventWasHandled = executeKeypressCommandsInternal(event->keypressCommands(), event);
248         event->keypressCommands().clear();
249     }
250
251     return eventWasHandled;
252 }
253
254 void WebPage::sendComplexTextInputToPlugin(uint64_t pluginComplexTextInputIdentifier, const String& textInput)
255 {
256     for (auto* pluginView : m_pluginViews) {
257         if (pluginView->sendComplexTextInput(pluginComplexTextInputIdentifier, textInput))
258             break;
259     }
260 }
261
262 #if !USE(ASYNC_NSTEXTINPUTCLIENT)
263
264 void WebPage::setComposition(const String& text, Vector<CompositionUnderline> underlines, const EditingRange& selectionRange, const EditingRange& replacementEditingRange, EditorState& newState)
265 {
266     Frame& frame = m_page->focusController().focusedOrMainFrame();
267
268     if (frame.selection().selection().isContentEditable()) {
269         RefPtr<Range> replacementRange;
270         if (replacementEditingRange.location != notFound) {
271             replacementRange = rangeFromEditingRange(frame, replacementEditingRange);
272             frame.selection().setSelection(VisibleSelection(replacementRange.get(), SEL_DEFAULT_AFFINITY));
273         }
274
275         frame.editor().setComposition(text, underlines, selectionRange.location, selectionRange.location + selectionRange.length);
276     }
277
278     newState = editorState();
279 }
280
281 void WebPage::confirmComposition(EditorState& newState)
282 {
283     Frame& frame = m_page->focusController().focusedOrMainFrame();
284     frame.editor().confirmComposition();
285     newState = editorState();
286 }
287
288 void WebPage::insertText(const String& text, const EditingRange& replacementEditingRange, bool& handled, EditorState& newState)
289 {
290     Frame& frame = m_page->focusController().focusedOrMainFrame();
291
292     if (replacementEditingRange.location != notFound) {
293         RefPtr<Range> replacementRange = rangeFromEditingRange(frame, replacementEditingRange);
294         if (replacementRange)
295             frame.selection().setSelection(VisibleSelection(replacementRange.get(), SEL_DEFAULT_AFFINITY));
296     }
297
298     if (!frame.editor().hasComposition()) {
299         // An insertText: might be handled by other responders in the chain if we don't handle it.
300         // One example is space bar that results in scrolling down the page.
301         handled = frame.editor().insertText(text, nullptr);
302     } else {
303         handled = true;
304         frame.editor().confirmComposition(text);
305     }
306
307     newState = editorState();
308 }
309
310 void WebPage::insertDictatedText(const String& text, const EditingRange& replacementEditingRange, const Vector<WebCore::DictationAlternative>& dictationAlternativeLocations, bool& handled, EditorState& newState)
311 {
312     Frame& frame = m_page->focusController().focusedOrMainFrame();
313
314     if (replacementEditingRange.location != notFound) {
315         RefPtr<Range> replacementRange = rangeFromEditingRange(frame, replacementEditingRange);
316         if (replacementRange)
317             frame.selection().setSelection(VisibleSelection(replacementRange.get(), SEL_DEFAULT_AFFINITY));
318     }
319
320     ASSERT(!frame.editor().hasComposition());
321     handled = frame.editor().insertDictatedText(text, dictationAlternativeLocations, nullptr);
322     newState = editorState();
323 }
324
325 void WebPage::getMarkedRange(EditingRange& result)
326 {
327     Frame& frame = m_page->focusController().focusedOrMainFrame();
328
329     RefPtr<Range> range = frame.editor().compositionRange();
330     size_t locationSize;
331     size_t lengthSize;
332     if (range && TextIterator::getLocationAndLengthFromRange(frame.selection().rootEditableElementOrDocumentElement(), range.get(), locationSize, lengthSize))
333         result = EditingRange(static_cast<uint64_t>(locationSize), static_cast<uint64_t>(lengthSize));
334     else
335         result = EditingRange();
336 }
337
338 void WebPage::getSelectedRange(EditingRange& result)
339 {
340     Frame& frame = m_page->focusController().focusedOrMainFrame();
341
342     size_t locationSize;
343     size_t lengthSize;
344     RefPtr<Range> range = frame.selection().toNormalizedRange();
345     if (range && TextIterator::getLocationAndLengthFromRange(frame.selection().rootEditableElementOrDocumentElement(), range.get(), locationSize, lengthSize))
346         result = EditingRange(static_cast<uint64_t>(locationSize), static_cast<uint64_t>(lengthSize));
347     else
348         result = EditingRange();
349 }
350
351 void WebPage::getAttributedSubstringFromRange(const EditingRange& editingRange, AttributedString& result)
352 {
353     Frame& frame = m_page->focusController().focusedOrMainFrame();
354
355     const VisibleSelection& selection = frame.selection().selection();
356     if (selection.isNone() || !selection.isContentEditable() || selection.isInPasswordField())
357         return;
358
359     RefPtr<Range> range = rangeFromEditingRange(frame, editingRange);
360     if (!range)
361         return;
362
363     result.string = editingAttributedStringFromRange(*range);
364     NSAttributedString* attributedString = result.string.get();
365     
366     // WebCore::editingAttributedStringFromRange() insists on inserting a trailing
367     // whitespace at the end of the string which breaks the ATOK input method.  <rdar://problem/5400551>
368     // To work around this we truncate the resultant string to the correct length.
369     if ([attributedString length] > editingRange.length) {
370         ASSERT([attributedString length] == editingRange.length + 1);
371         ASSERT([[attributedString string] characterAtIndex:editingRange.length] == '\n' || [[attributedString string] characterAtIndex:editingRange.length] == ' ');
372         result.string = [attributedString attributedSubstringFromRange:NSMakeRange(0, editingRange.length)];
373     }
374 }
375
376 void WebPage::characterIndexForPoint(IntPoint point, uint64_t& index)
377 {
378     index = notFound;
379
380     HitTestResult result = m_page->mainFrame().eventHandler().hitTestResultAtPoint(point);
381     Frame* frame = result.innerNonSharedNode() ? result.innerNodeFrame() : &m_page->focusController().focusedOrMainFrame();
382     
383     RefPtr<Range> range = frame->rangeForPoint(result.roundedPointInInnerNodeFrame());
384     if (!range)
385         return;
386
387     size_t location;
388     size_t length;
389     if (TextIterator::getLocationAndLengthFromRange(frame->selection().rootEditableElementOrDocumentElement(), range.get(), location, length))
390         index = static_cast<uint64_t>(location);
391 }
392     
393 void WebPage::firstRectForCharacterRange(const EditingRange& editingRange, WebCore::IntRect& resultRect)
394 {
395     Frame& frame = m_page->focusController().focusedOrMainFrame();
396     resultRect.setLocation(IntPoint(0, 0));
397     resultRect.setSize(IntSize(0, 0));
398     
399     RefPtr<Range> range = rangeFromEditingRange(frame, editingRange);
400     if (!range)
401         return;
402     
403     ASSERT(range->startContainer());
404     ASSERT(range->endContainer());
405      
406     IntRect rect = frame.editor().firstRectForRange(range.get());
407     resultRect = frame.view()->contentsToWindow(rect);
408 }
409
410 void WebPage::executeKeypressCommands(const Vector<WebCore::KeypressCommand>& commands, bool& handled, EditorState& newState)
411 {
412     handled = executeKeypressCommandsInternal(commands, nullptr);
413     newState = editorState();
414 }
415
416 void WebPage::cancelComposition(EditorState& newState)
417 {
418     Frame& frame = m_page->focusController().focusedOrMainFrame();
419     frame.editor().cancelComposition();
420     newState = editorState();
421 }
422
423 #endif // !USE(ASYNC_NSTEXTINPUTCLIENT)
424
425 void WebPage::insertDictatedTextAsync(const String& text, const EditingRange& replacementEditingRange, const Vector<WebCore::DictationAlternative>& dictationAlternativeLocations, bool registerUndoGroup)
426 {
427     Frame& frame = m_page->focusController().focusedOrMainFrame();
428
429     if (replacementEditingRange.location != notFound) {
430         RefPtr<Range> replacementRange = rangeFromEditingRange(frame, replacementEditingRange);
431         if (replacementRange)
432             frame.selection().setSelection(VisibleSelection(replacementRange.get(), SEL_DEFAULT_AFFINITY));
433     }
434
435     if (registerUndoGroup)
436         send(Messages::WebPageProxy::RegisterInsertionUndoGrouping());
437     
438     ASSERT(!frame.editor().hasComposition());
439     frame.editor().insertDictatedText(text, dictationAlternativeLocations, nullptr);
440 }
441
442 void WebPage::attributedSubstringForCharacterRangeAsync(const EditingRange& editingRange, uint64_t callbackID)
443 {
444     AttributedString result;
445
446     Frame& frame = m_page->focusController().focusedOrMainFrame();
447
448     const VisibleSelection& selection = frame.selection().selection();
449     if (selection.isNone() || !selection.isContentEditable() || selection.isInPasswordField()) {
450         send(Messages::WebPageProxy::AttributedStringForCharacterRangeCallback(result, EditingRange(), callbackID));
451         return;
452     }
453
454     RefPtr<Range> range = rangeFromEditingRange(frame, editingRange);
455     if (!range) {
456         send(Messages::WebPageProxy::AttributedStringForCharacterRangeCallback(result, EditingRange(), callbackID));
457         return;
458     }
459
460     result.string = editingAttributedStringFromRange(*range);
461     NSAttributedString* attributedString = result.string.get();
462     
463     // WebCore::editingAttributedStringFromRange() insists on inserting a trailing
464     // whitespace at the end of the string which breaks the ATOK input method.  <rdar://problem/5400551>
465     // To work around this we truncate the resultant string to the correct length.
466     if ([attributedString length] > editingRange.length) {
467         ASSERT([attributedString length] == editingRange.length + 1);
468         ASSERT([[attributedString string] characterAtIndex:editingRange.length] == '\n' || [[attributedString string] characterAtIndex:editingRange.length] == ' ');
469         result.string = [attributedString attributedSubstringFromRange:NSMakeRange(0, editingRange.length)];
470     }
471
472     send(Messages::WebPageProxy::AttributedStringForCharacterRangeCallback(result, EditingRange(editingRange.location, [result.string length]), callbackID));
473 }
474
475 static bool isPositionInRange(const VisiblePosition& position, Range* range)
476 {
477     RefPtr<Range> positionRange = makeRange(position, position);
478
479     ExceptionCode ec = 0;
480     range->compareBoundaryPoints(Range::START_TO_START, positionRange.get(), ec);
481     if (ec)
482         return false;
483
484     if (!range->isPointInRange(positionRange->startContainer(), positionRange->startOffset(), ec))
485         return false;
486     if (ec)
487         return false;
488
489     return true;
490 }
491
492 static bool shouldUseSelection(const VisiblePosition& position, const VisibleSelection& selection)
493 {
494     if (!selection.isRange())
495         return false;
496
497     RefPtr<Range> selectedRange = selection.toNormalizedRange();
498     if (!selectedRange)
499         return false;
500
501     return isPositionInRange(position, selectedRange.get());
502 }
503
504 static PassRefPtr<Range> rangeExpandedAroundPosition(const VisiblePosition& position, int numberOfLinesToExpand)
505 {
506     VisiblePosition contextStart = position;
507     VisiblePosition contextEnd = position;
508     for (int i = 0; i < numberOfLinesToExpand; i++) {
509         VisiblePosition n = previousLinePosition(contextStart, contextStart.lineDirectionPointForBlockDirectionNavigation());
510         if (n.isNull() || n == contextStart)
511             break;
512         contextStart = n;
513     }
514     for (int i = 0; i < numberOfLinesToExpand; i++) {
515         VisiblePosition n = nextLinePosition(contextEnd, contextEnd.lineDirectionPointForBlockDirectionNavigation());
516         if (n.isNull() || n == contextEnd)
517             break;
518         contextEnd = n;
519     }
520
521     VisiblePosition lineStart = startOfLine(contextStart);
522     if (!lineStart.isNull())
523         contextStart = lineStart;
524
525     VisiblePosition lineEnd = endOfLine(contextEnd);
526     if (!lineEnd.isNull())
527         contextEnd = lineEnd;
528     
529     return makeRange(contextStart, contextEnd);
530 }
531
532 void WebPage::performDictionaryLookupAtLocation(const FloatPoint& floatPoint)
533 {
534     if (PluginView* pluginView = pluginViewForFrame(&m_page->mainFrame())) {
535         if (pluginView->performDictionaryLookupAtLocation(floatPoint))
536             return;
537     }
538
539     // Find the frame the point is over.
540     IntPoint point = roundedIntPoint(floatPoint);
541     HitTestResult result = m_page->mainFrame().eventHandler().hitTestResultAtPoint(m_page->mainFrame().view()->windowToContents(point));
542     Frame* frame = result.innerNonSharedNode() ? result.innerNonSharedNode()->document().frame() : &m_page->focusController().focusedOrMainFrame();
543
544     IntPoint translatedPoint = frame->view()->windowToContents(point);
545
546     // Don't do anything if there is no character at the point.
547     if (!frame->rangeForPoint(translatedPoint))
548         return;
549
550     VisiblePosition position = frame->visiblePositionForPoint(translatedPoint);
551     VisibleSelection selection = m_page->focusController().focusedOrMainFrame().selection().selection();
552     if (shouldUseSelection(position, selection)) {
553         performDictionaryLookupForSelection(frame, selection);
554         return;
555     }
556
557     NSDictionary *options = nil;
558
559     // As context, we are going to use four lines of text before and after the point. (Dictionary can sometimes look up things that are four lines long)
560     RefPtr<Range> fullCharacterRange = rangeExpandedAroundPosition(position, 4);
561     NSRange rangeToPass = NSMakeRange(TextIterator::rangeLength(makeRange(fullCharacterRange->startPosition(), position).get()), 0);
562
563     String fullPlainTextString = plainText(fullCharacterRange.get());
564
565     NSRange extractedRange = WKExtractWordDefinitionTokenRangeFromContextualString(fullPlainTextString, rangeToPass, &options);
566
567     // This function sometimes returns {NSNotFound, 0} if it was unable to determine a good string.
568     if (extractedRange.location == NSNotFound)
569         return;
570
571     RefPtr<Range> finalRange = TextIterator::subrange(fullCharacterRange.get(), extractedRange.location, extractedRange.length);
572     if (!finalRange)
573         return;
574
575     performDictionaryLookupForRange(frame, *finalRange, options);
576 }
577
578 void WebPage::performDictionaryLookupForSelection(Frame* frame, const VisibleSelection& selection)
579 {
580     RefPtr<Range> selectedRange = selection.toNormalizedRange();
581     if (!selectedRange)
582         return;
583
584     NSDictionary *options = nil;
585
586     VisiblePosition selectionStart = selection.visibleStart();
587     VisiblePosition selectionEnd = selection.visibleEnd();
588
589     // As context, we are going to use the surrounding paragraphs of text.
590     VisiblePosition paragraphStart = startOfParagraph(selectionStart);
591     VisiblePosition paragraphEnd = endOfParagraph(selectionEnd);
592
593     int lengthToSelectionStart = TextIterator::rangeLength(makeRange(paragraphStart, selectionStart).get());
594     int lengthToSelectionEnd = TextIterator::rangeLength(makeRange(paragraphStart, selectionEnd).get());
595     NSRange rangeToPass = NSMakeRange(lengthToSelectionStart, lengthToSelectionEnd - lengthToSelectionStart);
596
597     String fullPlainTextString = plainText(makeRange(paragraphStart, paragraphEnd).get());
598
599     // Since we already have the range we want, we just need to grab the returned options.
600     WKExtractWordDefinitionTokenRangeFromContextualString(fullPlainTextString, rangeToPass, &options);
601
602     performDictionaryLookupForRange(frame, *selectedRange, options);
603 }
604
605 void WebPage::performDictionaryLookupForRange(Frame* frame, Range& range, NSDictionary *options)
606 {
607     if (range.text().stripWhiteSpace().isEmpty())
608         return;
609     
610     RenderObject* renderer = range.startContainer()->renderer();
611     const RenderStyle& style = renderer->style();
612
613     Vector<FloatQuad> quads;
614     range.textQuads(quads);
615     if (quads.isEmpty())
616         return;
617
618     IntRect rangeRect = frame->view()->contentsToWindow(quads[0].enclosingBoundingBox());
619     
620     DictionaryPopupInfo dictionaryPopupInfo;
621     dictionaryPopupInfo.origin = FloatPoint(rangeRect.x(), rangeRect.y() + (style.fontMetrics().ascent() * pageScaleFactor()));
622     dictionaryPopupInfo.options = (CFDictionaryRef)options;
623
624     NSAttributedString *nsAttributedString = editingAttributedStringFromRange(range);
625
626     RetainPtr<NSMutableAttributedString> scaledNSAttributedString = adoptNS([[NSMutableAttributedString alloc] initWithString:[nsAttributedString string]]);
627
628     NSFontManager *fontManager = [NSFontManager sharedFontManager];
629
630     [nsAttributedString enumerateAttributesInRange:NSMakeRange(0, [nsAttributedString length]) options:0 usingBlock:^(NSDictionary *attributes, NSRange range, BOOL *stop) {
631         RetainPtr<NSMutableDictionary> scaledAttributes = adoptNS([attributes mutableCopy]);
632
633         NSFont *font = [scaledAttributes objectForKey:NSFontAttributeName];
634         if (font) {
635             font = [fontManager convertFont:font toSize:[font pointSize] * pageScaleFactor()];
636             [scaledAttributes setObject:font forKey:NSFontAttributeName];
637         }
638
639         [scaledNSAttributedString addAttributes:scaledAttributes.get() range:range];
640     }];
641
642     AttributedString attributedString;
643     attributedString.string = scaledNSAttributedString;
644
645     send(Messages::WebPageProxy::DidPerformDictionaryLookup(attributedString, dictionaryPopupInfo));
646 }
647
648 bool WebPage::performNonEditingBehaviorForSelector(const String& selector, KeyboardEvent* event)
649 {
650     // First give accessibility a chance to handle the event.
651     Frame* frame = frameForEvent(event);
652     frame->eventHandler().handleKeyboardSelectionMovementForAccessibility(event);
653     if (event->defaultHandled())
654         return true;
655
656     // FIXME: All these selectors have corresponding Editor commands, but the commands only work in editable content.
657     // Should such non-editing behaviors be implemented in Editor or EventHandler::defaultArrowEventHandler() perhaps?
658     
659     bool didPerformAction = false;
660
661     if (selector == "moveUp:")
662         didPerformAction = scroll(m_page.get(), ScrollUp, ScrollByLine);
663     else if (selector == "moveToBeginningOfParagraph:")
664         didPerformAction = scroll(m_page.get(), ScrollUp, ScrollByPage);
665     else if (selector == "moveToBeginningOfDocument:") {
666         didPerformAction = scroll(m_page.get(), ScrollUp, ScrollByDocument);
667         didPerformAction |= scroll(m_page.get(), ScrollLeft, ScrollByDocument);
668     } else if (selector == "moveDown:")
669         didPerformAction = scroll(m_page.get(), ScrollDown, ScrollByLine);
670     else if (selector == "moveToEndOfParagraph:")
671         didPerformAction = scroll(m_page.get(), ScrollDown, ScrollByPage);
672     else if (selector == "moveToEndOfDocument:") {
673         didPerformAction = scroll(m_page.get(), ScrollDown, ScrollByDocument);
674         didPerformAction |= scroll(m_page.get(), ScrollLeft, ScrollByDocument);
675     } else if (selector == "moveLeft:")
676         didPerformAction = scroll(m_page.get(), ScrollLeft, ScrollByLine);
677     else if (selector == "moveWordLeft:")
678         didPerformAction = scroll(m_page.get(), ScrollLeft, ScrollByPage);
679     else if (selector == "moveToLeftEndOfLine:")
680         didPerformAction = m_page->backForward().goBack();
681     else if (selector == "moveRight:")
682         didPerformAction = scroll(m_page.get(), ScrollRight, ScrollByLine);
683     else if (selector == "moveWordRight:")
684         didPerformAction = scroll(m_page.get(), ScrollRight, ScrollByPage);
685     else if (selector == "moveToRightEndOfLine:")
686         didPerformAction = m_page->backForward().goForward();
687
688     return didPerformAction;
689 }
690
691 #if ENABLE(SERVICE_CONTROLS)
692 static String& replaceSelectionPasteboardName()
693 {
694     static NeverDestroyed<String> string("ReplaceSelectionPasteboard");
695     return string;
696 }
697
698 void WebPage::replaceSelectionWithPasteboardData(const Vector<String>& types, const IPC::DataReference& data)
699 {
700     for (auto& type : types)
701         WebPasteboardOverrides::sharedPasteboardOverrides().addOverride(replaceSelectionPasteboardName(), type, data.vector());
702
703     bool result;
704     readSelectionFromPasteboard(replaceSelectionPasteboardName(), result);
705
706     for (auto& type : types)
707         WebPasteboardOverrides::sharedPasteboardOverrides().removeOverride(replaceSelectionPasteboardName(), type);
708 }
709 #endif
710
711 bool WebPage::performDefaultBehaviorForKeyEvent(const WebKeyboardEvent&)
712 {
713     return false;
714 }
715
716 void WebPage::registerUIProcessAccessibilityTokens(const IPC::DataReference& elementToken, const IPC::DataReference& windowToken)
717 {
718     NSData* elementTokenData = [NSData dataWithBytes:elementToken.data() length:elementToken.size()];
719     NSData* windowTokenData = [NSData dataWithBytes:windowToken.data() length:windowToken.size()];
720     id remoteElement = WKAXRemoteElementForToken(elementTokenData);
721     id remoteWindow = WKAXRemoteElementForToken(windowTokenData);
722     WKAXSetWindowForRemoteElement(remoteWindow, remoteElement);
723     
724     [accessibilityRemoteObject() setRemoteParent:remoteElement];
725 }
726
727 void WebPage::readSelectionFromPasteboard(const String& pasteboardName, bool& result)
728 {
729     Frame& frame = m_page->focusController().focusedOrMainFrame();
730     if (frame.selection().isNone()) {
731         result = false;
732         return;
733     }
734     frame.editor().readSelectionFromPasteboard(pasteboardName);
735     result = true;
736 }
737
738 void WebPage::getStringSelectionForPasteboard(String& stringValue)
739 {
740     Frame& frame = m_page->focusController().focusedOrMainFrame();
741
742     if (PluginView* pluginView = focusedPluginViewForFrame(frame)) {
743         String selection = pluginView->getSelectionString();
744         if (!selection.isNull()) {
745             stringValue = selection;
746             return;
747         }
748     }
749
750     if (frame.selection().isNone())
751         return;
752
753     stringValue = frame.editor().stringSelectionForPasteboard();
754 }
755
756 void WebPage::getDataSelectionForPasteboard(const String pasteboardType, SharedMemory::Handle& handle, uint64_t& size)
757 {
758     Frame& frame = m_page->focusController().focusedOrMainFrame();
759     if (frame.selection().isNone())
760         return;
761
762     RefPtr<SharedBuffer> buffer = frame.editor().dataSelectionForPasteboard(pasteboardType);
763     if (!buffer) {
764         size = 0;
765         return;
766     }
767     size = buffer->size();
768     RefPtr<SharedMemory> sharedMemoryBuffer = SharedMemory::create(size);
769     memcpy(sharedMemoryBuffer->data(), buffer->data(), size);
770     sharedMemoryBuffer->createHandle(handle, SharedMemory::ReadOnly);
771 }
772
773 WKAccessibilityWebPageObject* WebPage::accessibilityRemoteObject()
774 {
775     return m_mockAccessibilityElement.get();
776 }
777          
778 bool WebPage::platformHasLocalDataForURL(const WebCore::URL& url)
779 {
780     NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];
781     [request setValue:(NSString*)userAgent(url) forHTTPHeaderField:@"User-Agent"];
782     NSCachedURLResponse *cachedResponse;
783     if (CFURLStorageSessionRef storageSession = corePage()->mainFrame().loader().networkingContext()->storageSession().platformSession())
784         cachedResponse = WKCachedResponseForRequest(storageSession, request);
785     else
786         cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request];
787     [request release];
788     
789     return cachedResponse;
790 }
791
792 static NSCachedURLResponse *cachedResponseForURL(WebPage* webPage, const URL& url)
793 {
794     RetainPtr<NSMutableURLRequest> request = adoptNS([[NSMutableURLRequest alloc] initWithURL:url]);
795     [request setValue:(NSString *)webPage->userAgent(url) forHTTPHeaderField:@"User-Agent"];
796
797     if (CFURLStorageSessionRef storageSession = webPage->corePage()->mainFrame().loader().networkingContext()->storageSession().platformSession())
798         return WKCachedResponseForRequest(storageSession, request.get());
799
800     return [[NSURLCache sharedURLCache] cachedResponseForRequest:request.get()];
801 }
802
803 String WebPage::cachedSuggestedFilenameForURL(const URL& url)
804 {
805     return [[cachedResponseForURL(this, url) response] suggestedFilename];
806 }
807
808 String WebPage::cachedResponseMIMETypeForURL(const URL& url)
809 {
810     return [[cachedResponseForURL(this, url) response] MIMEType];
811 }
812
813 PassRefPtr<SharedBuffer> WebPage::cachedResponseDataForURL(const URL& url)
814 {
815     return SharedBuffer::wrapNSData([cachedResponseForURL(this, url) data]);
816 }
817
818 bool WebPage::platformCanHandleRequest(const WebCore::ResourceRequest& request)
819 {
820     if ([NSURLConnection canHandleRequest:request.nsURLRequest(DoNotUpdateHTTPBody)])
821         return true;
822
823     // FIXME: Return true if this scheme is any one WebKit2 knows how to handle.
824     return request.url().protocolIs("applewebdata");
825 }
826
827 void WebPage::shouldDelayWindowOrderingEvent(const WebKit::WebMouseEvent& event, bool& result)
828 {
829     Frame& frame = m_page->focusController().focusedOrMainFrame();
830
831 #if ENABLE(DRAG_SUPPORT)
832     HitTestResult hitResult = frame.eventHandler().hitTestResultAtPoint(frame.view()->windowToContents(event.position()), HitTestRequest::ReadOnly | HitTestRequest::Active);
833     if (hitResult.isSelected())
834         result = frame.eventHandler().eventMayStartDrag(platform(event));
835     else
836 #endif
837         result = false;
838 }
839
840 void WebPage::acceptsFirstMouse(int eventNumber, const WebKit::WebMouseEvent& event, bool& result)
841 {
842     result = false;
843     Frame& frame = m_page->focusController().focusedOrMainFrame();
844
845     HitTestResult hitResult = frame.eventHandler().hitTestResultAtPoint(frame.view()->windowToContents(event.position()), HitTestRequest::ReadOnly | HitTestRequest::Active);
846     frame.eventHandler().setActivationEventNumber(eventNumber);
847 #if ENABLE(DRAG_SUPPORT)
848     if (hitResult.isSelected())
849         result = frame.eventHandler().eventMayStartDrag(platform(event));
850     else
851 #endif
852         result = !!hitResult.scrollbar();
853 }
854
855 void WebPage::setTopOverhangImage(PassRefPtr<WebImage> image)
856 {
857     FrameView* frameView = m_mainFrame->coreFrame()->view();
858     if (!frameView)
859         return;
860
861     GraphicsLayer* layer = frameView->setWantsLayerForTopOverHangArea(image.get());
862     if (!layer)
863         return;
864
865     layer->setSize(image->size());
866     layer->setPosition(FloatPoint(0, -image->size().height()));
867
868     RetainPtr<CGImageRef> cgImage = image->bitmap()->makeCGImageCopy();
869     layer->platformLayer().contents = (id)cgImage.get();
870 }
871
872 void WebPage::setBottomOverhangImage(PassRefPtr<WebImage> image)
873 {
874     FrameView* frameView = m_mainFrame->coreFrame()->view();
875     if (!frameView)
876         return;
877
878     GraphicsLayer* layer = frameView->setWantsLayerForBottomOverHangArea(image.get());
879     if (!layer)
880         return;
881
882     layer->setSize(image->size());
883     
884     RetainPtr<CGImageRef> cgImage = image->bitmap()->makeCGImageCopy();
885     layer->platformLayer().contents = (id)cgImage.get();
886 }
887
888 void WebPage::updateHeaderAndFooterLayersForDeviceScaleChange(float scaleFactor)
889 {    
890     if (m_headerBanner)
891         m_headerBanner->didChangeDeviceScaleFactor(scaleFactor);
892     if (m_footerBanner)
893         m_footerBanner->didChangeDeviceScaleFactor(scaleFactor);
894 }
895
896 void WebPage::computePagesForPrintingPDFDocument(uint64_t frameID, const PrintInfo& printInfo, Vector<IntRect>& resultPageRects)
897 {
898     ASSERT(resultPageRects.isEmpty());
899     WebFrame* frame = WebProcess::shared().webFrame(frameID);
900     Frame* coreFrame = frame ? frame->coreFrame() : 0;
901     RetainPtr<PDFDocument> pdfDocument = coreFrame ? pdfDocumentForPrintingFrame(coreFrame) : 0;
902     if ([pdfDocument allowsPrinting]) {
903         NSUInteger pageCount = [pdfDocument pageCount];
904         IntRect pageRect(0, 0, ceilf(printInfo.availablePaperWidth), ceilf(printInfo.availablePaperHeight));
905         for (NSUInteger i = 1; i <= pageCount; ++i) {
906             resultPageRects.append(pageRect);
907             pageRect.move(0, pageRect.height());
908         }
909     }
910 }
911
912 static inline CGFloat roundCGFloat(CGFloat f)
913 {
914     if (sizeof(CGFloat) == sizeof(float))
915         return roundf(static_cast<float>(f));
916     return static_cast<CGFloat>(round(f));
917 }
918
919 static void drawPDFPage(PDFDocument *pdfDocument, CFIndex pageIndex, CGContextRef context, CGFloat pageSetupScaleFactor, CGSize paperSize)
920 {
921     CGContextSaveGState(context);
922
923     CGContextScaleCTM(context, pageSetupScaleFactor, pageSetupScaleFactor);
924
925     PDFPage *pdfPage = [pdfDocument pageAtIndex:pageIndex];
926     NSRect cropBox = [pdfPage boundsForBox:kPDFDisplayBoxCropBox];
927     if (NSIsEmptyRect(cropBox))
928         cropBox = [pdfPage boundsForBox:kPDFDisplayBoxMediaBox];
929     else
930         cropBox = NSIntersectionRect(cropBox, [pdfPage boundsForBox:kPDFDisplayBoxMediaBox]);
931
932     // Always auto-rotate PDF content regardless of the paper orientation.
933     NSInteger rotation = [pdfPage rotation];
934     if (rotation == 90 || rotation == 270)
935         std::swap(cropBox.size.width, cropBox.size.height);
936
937     bool shouldRotate = (paperSize.width < paperSize.height) != (cropBox.size.width < cropBox.size.height);
938     if (shouldRotate)
939         std::swap(cropBox.size.width, cropBox.size.height);
940
941     // Center.
942     CGFloat widthDifference = paperSize.width / pageSetupScaleFactor - cropBox.size.width;
943     CGFloat heightDifference = paperSize.height / pageSetupScaleFactor - cropBox.size.height;
944     if (widthDifference || heightDifference)
945         CGContextTranslateCTM(context, roundCGFloat(widthDifference / 2), roundCGFloat(heightDifference / 2));
946
947     if (shouldRotate) {
948         CGContextRotateCTM(context, static_cast<CGFloat>(piOverTwoDouble));
949         CGContextTranslateCTM(context, 0, -cropBox.size.width);
950     }
951
952     [NSGraphicsContext saveGraphicsState];
953     [NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithGraphicsPort:context flipped:NO]];
954     [pdfPage drawWithBox:kPDFDisplayBoxCropBox];
955     [NSGraphicsContext restoreGraphicsState];
956
957     CGAffineTransform transform = CGContextGetCTM(context);
958
959     for (PDFAnnotation *annotation in [pdfPage annotations]) {
960         if (![annotation isKindOfClass:pdfAnnotationLinkClass()])
961             continue;
962
963         PDFAnnotationLink *linkAnnotation = (PDFAnnotationLink *)annotation;
964         NSURL *url = [linkAnnotation URL];
965         if (!url)
966             continue;
967
968         CGRect urlRect = NSRectToCGRect([linkAnnotation bounds]);
969         CGRect transformedRect = CGRectApplyAffineTransform(urlRect, transform);
970         CGPDFContextSetURLForRect(context, (CFURLRef)url, transformedRect);
971     }
972
973     CGContextRestoreGState(context);
974 }
975
976 void WebPage::drawPDFDocument(CGContextRef context, PDFDocument *pdfDocument, const PrintInfo& printInfo, const WebCore::IntRect& rect)
977 {
978     NSUInteger pageCount = [pdfDocument pageCount];
979     IntSize paperSize(ceilf(printInfo.availablePaperWidth), ceilf(printInfo.availablePaperHeight));
980     IntRect pageRect(IntPoint(), paperSize);
981     for (NSUInteger i = 0; i < pageCount; ++i) {
982         if (pageRect.intersects(rect)) {
983             CGContextSaveGState(context);
984
985             CGContextTranslateCTM(context, pageRect.x() - rect.x(), pageRect.y() - rect.y());
986             drawPDFPage(pdfDocument, i, context, printInfo.pageSetupScaleFactor, paperSize);
987
988             CGContextRestoreGState(context);
989         }
990         pageRect.move(0, pageRect.height());
991     }
992 }
993
994 void WebPage::drawPagesToPDFFromPDFDocument(CGContextRef context, PDFDocument *pdfDocument, const PrintInfo& printInfo, uint32_t first, uint32_t count)
995 {
996     NSUInteger pageCount = [pdfDocument pageCount];
997     for (uint32_t page = first; page < first + count; ++page) {
998         if (page >= pageCount)
999             break;
1000
1001         RetainPtr<CFDictionaryRef> pageInfo = adoptCF(CFDictionaryCreateMutable(0, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
1002
1003         CGPDFContextBeginPage(context, pageInfo.get());
1004         drawPDFPage(pdfDocument, page, context, printInfo.pageSetupScaleFactor, CGSizeMake(printInfo.availablePaperWidth, printInfo.availablePaperHeight));
1005         CGPDFContextEndPage(context);
1006     }
1007 }
1008
1009 #if ENABLE(WEBGL)
1010 WebCore::WebGLLoadPolicy WebPage::webGLPolicyForURL(WebFrame* frame, const String& url)
1011 {
1012     uint32_t policyResult = 0;
1013
1014     if (sendSync(Messages::WebPageProxy::WebGLPolicyForURL(url), Messages::WebPageProxy::WebGLPolicyForURL::Reply(policyResult)))
1015         return static_cast<WebGLLoadPolicy>(policyResult);
1016
1017     return WebGLAllowCreation;
1018 }
1019
1020 WebCore::WebGLLoadPolicy WebPage::resolveWebGLPolicyForURL(WebFrame* frame, const String& url)
1021 {
1022     uint32_t policyResult = 0;
1023
1024     if (sendSync(Messages::WebPageProxy::ResolveWebGLPolicyForURL(url), Messages::WebPageProxy::ResolveWebGLPolicyForURL::Reply(policyResult)))
1025         return static_cast<WebGLLoadPolicy>(policyResult);
1026
1027     return WebGLAllowCreation;
1028 }
1029 #endif // ENABLE(WEBGL)
1030
1031 #if ENABLE(TELEPHONE_NUMBER_DETECTION)
1032 void WebPage::handleTelephoneNumberClick(const String& number, const IntPoint& point)
1033 {
1034     send(Messages::WebPageProxy::ShowTelephoneNumberMenu(number, point));
1035 }
1036 #endif
1037
1038 #if ENABLE(SERVICE_CONTROLS)
1039 void WebPage::handleSelectionServiceClick(FrameSelection& selection, const Vector<String>& phoneNumbers, const IntPoint& point)
1040 {
1041     RefPtr<Range> range = selection.selection().firstRange();
1042     if (!range)
1043         return;
1044
1045     NSAttributedString *attributedSelection = attributedStringFromRange(*range);
1046     if (!attributedSelection)
1047         return;
1048
1049     NSData *selectionData = [attributedSelection RTFDFromRange:NSMakeRange(0, [attributedSelection length]) documentAttributes:nil];
1050     IPC::DataReference data = IPC::DataReference(reinterpret_cast<const uint8_t*>([selectionData bytes]), [selectionData length]);
1051     bool isEditable = selection.selection().isContentEditable();
1052
1053     send(Messages::WebPageProxy::ShowSelectionServiceMenu(data, phoneNumbers, isEditable, point));
1054 }
1055 #endif
1056
1057 String WebPage::platformUserAgent(const URL&) const
1058 {
1059     return String();
1060 }
1061
1062 static RetainPtr<DDActionContext> scanForDataDetectedItems(const HitTestResult& hitTestResult, FloatRect& actionBoundingBox)
1063 {
1064     Node* node = hitTestResult.innerNonSharedNode();
1065     if (!node)
1066         return nullptr;
1067     auto renderer = node->renderer();
1068     if (!renderer)
1069         return nullptr;
1070     VisiblePosition position = renderer->positionForPoint(hitTestResult.localPoint(), nullptr);
1071     if (position.isNull())
1072         position = firstPositionInOrBeforeNode(node);
1073
1074     RefPtr<Range> contextRange = rangeExpandedAroundPosition(position, 4);
1075     if (!contextRange)
1076         return nullptr;
1077
1078     String fullPlainTextString = plainText(contextRange.get());
1079     int hitLocation = TextIterator::rangeLength(makeRange(contextRange->startPosition(), position).get());
1080
1081     RetainPtr<DDScannerRef> scanner = adoptCF(DDScannerCreate(DDScannerTypeStandard, 0, nullptr));
1082     RetainPtr<DDScanQueryRef> scanQuery = adoptCF(DDScanQueryCreateFromString(kCFAllocatorDefault, fullPlainTextString.createCFString().get(), CFRangeMake(0, fullPlainTextString.length())));
1083
1084     if (!DDScannerScanQuery(scanner.get(), scanQuery.get()))
1085         return nullptr;
1086
1087     RetainPtr<CFArrayRef> results = adoptCF(DDScannerCopyResultsWithOptions(scanner.get(), DDScannerCopyResultsOptionsNoOverlap));
1088
1089     // Find the DDResultRef that intersects the hitTestResult's VisiblePosition.
1090     DDResultRef mainResult = nullptr;
1091     RefPtr<Range> mainResultRange;
1092     CFIndex resultCount = CFArrayGetCount(results.get());
1093     for (CFIndex i = 0; i < resultCount; i++) {
1094         DDResultRef result = (DDResultRef)CFArrayGetValueAtIndex(results.get(), i);
1095         CFRange resultRangeInContext = DDResultGetRange(result);
1096         if (hitLocation >= resultRangeInContext.location && (hitLocation - resultRangeInContext.location) < resultRangeInContext.length) {
1097             mainResult = result;
1098             mainResultRange = TextIterator::subrange(contextRange.get(), resultRangeInContext.location, resultRangeInContext.length);
1099             break;
1100         }
1101     }
1102
1103     if (!mainResult)
1104         return nullptr;
1105
1106     RetainPtr<DDActionContext> actionContext = adoptNS([[getDDActionContextClass() alloc] init]);
1107     [actionContext setAllResults:(NSArray *)results.get()];
1108     [actionContext setMainResult:mainResult];
1109
1110     Vector<FloatQuad> quads;
1111     mainResultRange->textQuads(quads);
1112     if (!quads.isEmpty())
1113         actionBoundingBox = mainResultRange->ownerDocument().view()->contentsToWindow(quads[0].enclosingBoundingBox());
1114
1115     return actionContext;
1116 }
1117
1118 void WebPage::performActionMenuHitTestAtLocation(WebCore::FloatPoint locationInViewCooordinates)
1119 {
1120     layoutIfNeeded();
1121
1122     MainFrame& mainFrame = corePage()->mainFrame();
1123     if (!mainFrame.view() || !mainFrame.view()->renderView()) {
1124         send(Messages::WebPageProxy::DidPerformActionMenuHitTest(ActionMenuHitTestResult()));
1125         return;
1126     }
1127
1128     RenderView& mainRenderView = *mainFrame.view()->renderView();
1129
1130     HitTestRequest request(HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::AllowChildFrameContent | HitTestRequest::IgnoreClipping | HitTestRequest::DisallowShadowContent);
1131
1132     IntPoint locationInContentCoordinates = mainFrame.view()->rootViewToContents(roundedIntPoint(locationInViewCooordinates));
1133     HitTestResult hitTestResult(locationInContentCoordinates);
1134     mainRenderView.hitTest(request, hitTestResult);
1135
1136     ActionMenuHitTestResult actionMenuResult;
1137
1138     if (Image* image = hitTestResult.image()) {
1139         actionMenuResult.image = ShareableBitmap::createShareable(IntSize(image->size()), ShareableBitmap::SupportsAlpha);
1140         if (actionMenuResult.image)
1141             actionMenuResult.image->createGraphicsContext()->drawImage(image, ColorSpaceDeviceRGB, IntPoint());
1142     }
1143
1144     // FIXME: Avoid scanning if we will just throw away the result (e.g. we're over a link).
1145     if (hitTestResult.innerNode() && hitTestResult.innerNode()->isTextNode()) {
1146         FloatRect actionBoundingBox;
1147         actionMenuResult.actionContext = scanForDataDetectedItems(hitTestResult, actionBoundingBox);
1148         actionMenuResult.actionBoundingBox = actionBoundingBox;
1149     }
1150     
1151     send(Messages::WebPageProxy::DidPerformActionMenuHitTest(actionMenuResult));
1152 }
1153
1154 } // namespace WebKit
1155
1156 #endif // PLATFORM(MAC)