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