c4992bb264049ff17c198d33a29f84d96670ccd7
[WebKit-https.git] / Source / WebKit2 / UIProcess / API / mac / WKView.mm
1 /*
2  * Copyright (C) 2010, 2011 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 "WKView.h"
28
29 #if PLATFORM(MAC)
30
31 #if USE(DICTATION_ALTERNATIVES)
32 #import <AppKit/NSTextAlternatives.h>
33 #import <AppKit/NSAttributedString.h>
34 #endif
35
36 #import "APILegacyContextHistoryClient.h"
37 #import "APIPageConfiguration.h"
38 #import "AppKitSPI.h"
39 #import "AttributedString.h"
40 #import "DataReference.h"
41 #import "EditingRange.h"
42 #import "EditorState.h"
43 #import "LayerTreeContext.h"
44 #import "Logging.h"
45 #import "NativeWebKeyboardEvent.h"
46 #import "NativeWebMouseEvent.h"
47 #import "NativeWebWheelEvent.h"
48 #import "PageClientImpl.h"
49 #import "PasteboardTypes.h"
50 #import "StringUtilities.h"
51 #import "TextChecker.h"
52 #import "TextCheckerState.h"
53 #import "WKAPICast.h"
54 #import "WKFullScreenWindowController.h"
55 #import "WKLayoutMode.h"
56 #import "WKPrintingView.h"
57 #import "WKProcessPoolInternal.h"
58 #import "WKStringCF.h"
59 #import "WKTextInputWindowController.h"
60 #import "WKViewInternal.h"
61 #import "WKViewPrivate.h"
62 #import "WKWebView.h"
63 #import "WebBackForwardList.h"
64 #import "WebEventFactory.h"
65 #import "WebHitTestResultData.h"
66 #import "WebKit2Initialize.h"
67 #import "WebPage.h"
68 #import "WebPageGroup.h"
69 #import "WebPageProxy.h"
70 #import "WebPreferences.h"
71 #import "WebProcessPool.h"
72 #import "WebProcessProxy.h"
73 #import "WebSystemInterface.h"
74 #import "WebViewImpl.h"
75 #import <QuartzCore/QuartzCore.h>
76 #import <WebCore/AXObjectCache.h>
77 #import <WebCore/ColorMac.h>
78 #import <WebCore/CoreGraphicsSPI.h>
79 #import <WebCore/DataDetectorsSPI.h>
80 #import <WebCore/DictionaryLookup.h>
81 #import <WebCore/DragController.h>
82 #import <WebCore/DragData.h>
83 #import <WebCore/FloatRect.h>
84 #import <WebCore/Image.h>
85 #import <WebCore/IntRect.h>
86 #import <WebCore/FileSystem.h>
87 #import <WebCore/KeyboardEvent.h>
88 #import <WebCore/LocalizedStrings.h>
89 #import <WebCore/NSMenuSPI.h>
90 #import <WebCore/PlatformEventFactoryMac.h>
91 #import <WebCore/PlatformScreen.h>
92 #import <WebCore/Region.h>
93 #import <WebCore/RuntimeApplicationChecks.h>
94 #import <WebCore/SharedBuffer.h>
95 #import <WebCore/TextAlternativeWithRange.h>
96 #import <WebCore/TextIndicator.h>
97 #import <WebCore/TextIndicatorWindow.h>
98 #import <WebCore/TextUndoInsertionMarkupMac.h>
99 #import <WebCore/WebCoreCALayerExtras.h>
100 #import <WebCore/WebCoreFullScreenPlaceholderView.h>
101 #import <WebCore/WebCoreFullScreenWindow.h>
102 #import <WebCore/WebCoreNSStringExtras.h>
103 #import <WebKitSystemInterface.h>
104 #import <sys/stat.h>
105 #import <wtf/RefPtr.h>
106 #import <wtf/RetainPtr.h>
107 #import <wtf/RunLoop.h>
108
109 /* API internals. */
110 #import "WKBrowsingContextGroupPrivate.h"
111 #import "WKProcessGroupPrivate.h"
112
113 using namespace WebKit;
114 using namespace WebCore;
115
116 #if USE(ASYNC_NSTEXTINPUTCLIENT)
117 @interface NSTextInputContext (WKNSTextInputContextDetails)
118 - (void)handleEvent:(NSEvent *)event completionHandler:(void(^)(BOOL handled))completionHandler;
119 - (void)handleEventByInputMethod:(NSEvent *)event completionHandler:(void(^)(BOOL handled))completionHandler;
120 - (BOOL)handleEventByKeyboardLayout:(NSEvent *)event;
121 @end
122 #endif
123
124 @interface WKViewData : NSObject {
125 @public
126     std::unique_ptr<PageClientImpl> _pageClient;
127     RefPtr<WebPageProxy> _page;
128     std::unique_ptr<WebViewImpl> _impl;
129 }
130
131 @end
132
133 @implementation WKViewData
134 @end
135
136 @interface WKView () <WebViewImplDelegate>
137 @end
138
139 @implementation WKView
140
141 #if WK_API_ENABLED
142
143 - (id)initWithFrame:(NSRect)frame processGroup:(WKProcessGroup *)processGroup browsingContextGroup:(WKBrowsingContextGroup *)browsingContextGroup
144 {
145     return [self initWithFrame:frame contextRef:processGroup._contextRef pageGroupRef:browsingContextGroup._pageGroupRef relatedToPage:nil];
146 }
147
148 - (id)initWithFrame:(NSRect)frame processGroup:(WKProcessGroup *)processGroup browsingContextGroup:(WKBrowsingContextGroup *)browsingContextGroup relatedToView:(WKView *)relatedView
149 {
150     return [self initWithFrame:frame contextRef:processGroup._contextRef pageGroupRef:browsingContextGroup._pageGroupRef relatedToPage:relatedView ? toAPI(relatedView->_data->_page.get()) : nil];
151 }
152
153 #endif // WK_API_ENABLED
154
155 - (void)dealloc
156 {
157 #if WK_API_ENABLED
158     _data->_impl->destroyRemoteObjectRegistry();
159 #endif
160
161     _data->_page->close();
162
163     _data->_impl = nullptr;
164
165     [_data release];
166     _data = nil;
167
168     NSNotificationCenter* workspaceNotificationCenter = [[NSWorkspace sharedWorkspace] notificationCenter];
169     [workspaceNotificationCenter removeObserver:self name:NSWorkspaceActiveSpaceDidChangeNotification object:nil];
170
171     WebProcessPool::statistics().wkViewCount--;
172
173     [super dealloc];
174 }
175
176 #if WK_API_ENABLED
177 - (WKBrowsingContextController *)browsingContextController
178 {
179     return _data->_impl->browsingContextController();
180 }
181 #endif // WK_API_ENABLED
182
183 - (void)setDrawsBackground:(BOOL)drawsBackground
184 {
185     _data->_impl->setDrawsBackground(drawsBackground);
186 }
187
188 - (BOOL)drawsBackground
189 {
190     return _data->_impl->drawsBackground();
191 }
192
193 - (void)setDrawsTransparentBackground:(BOOL)drawsTransparentBackground
194 {
195     _data->_impl->setDrawsTransparentBackground(drawsTransparentBackground);
196 }
197
198 - (BOOL)drawsTransparentBackground
199 {
200     return _data->_impl->drawsTransparentBackground();
201 }
202
203 - (BOOL)acceptsFirstResponder
204 {
205     return _data->_impl->acceptsFirstResponder();
206 }
207
208 - (BOOL)becomeFirstResponder
209 {
210     return _data->_impl->becomeFirstResponder();
211 }
212
213 - (BOOL)resignFirstResponder
214 {
215     return _data->_impl->resignFirstResponder();
216 }
217
218 - (void)viewWillStartLiveResize
219 {
220     _data->_impl->viewWillStartLiveResize();
221 }
222
223 - (void)viewDidEndLiveResize
224 {
225     _data->_impl->viewDidEndLiveResize();
226 }
227
228 - (BOOL)isFlipped
229 {
230     return YES;
231 }
232
233 - (NSSize)intrinsicContentSize
234 {
235     return NSSizeFromCGSize(_data->_impl->intrinsicContentSize());
236 }
237
238 - (void)prepareContentInRect:(NSRect)rect
239 {
240     _data->_impl->setContentPreparationRect(NSRectToCGRect(rect));
241     _data->_impl->updateViewExposedRect();
242 }
243
244 - (void)setFrameSize:(NSSize)size
245 {
246     [super setFrameSize:size];
247     _data->_impl->setFrameSize(NSSizeToCGSize(size));
248 }
249
250 - (void)renewGState
251 {
252     _data->_impl->renewGState();
253     [super renewGState];
254 }
255
256 #define WEBCORE_COMMAND(command) - (void)command:(id)sender { _data->_impl->executeEditCommandForSelector(_cmd); }
257
258 WEBCORE_COMMAND(alignCenter)
259 WEBCORE_COMMAND(alignJustified)
260 WEBCORE_COMMAND(alignLeft)
261 WEBCORE_COMMAND(alignRight)
262 WEBCORE_COMMAND(copy)
263 WEBCORE_COMMAND(cut)
264 WEBCORE_COMMAND(delete)
265 WEBCORE_COMMAND(deleteBackward)
266 WEBCORE_COMMAND(deleteBackwardByDecomposingPreviousCharacter)
267 WEBCORE_COMMAND(deleteForward)
268 WEBCORE_COMMAND(deleteToBeginningOfLine)
269 WEBCORE_COMMAND(deleteToBeginningOfParagraph)
270 WEBCORE_COMMAND(deleteToEndOfLine)
271 WEBCORE_COMMAND(deleteToEndOfParagraph)
272 WEBCORE_COMMAND(deleteToMark)
273 WEBCORE_COMMAND(deleteWordBackward)
274 WEBCORE_COMMAND(deleteWordForward)
275 WEBCORE_COMMAND(ignoreSpelling)
276 WEBCORE_COMMAND(indent)
277 WEBCORE_COMMAND(insertBacktab)
278 WEBCORE_COMMAND(insertLineBreak)
279 WEBCORE_COMMAND(insertNewline)
280 WEBCORE_COMMAND(insertNewlineIgnoringFieldEditor)
281 WEBCORE_COMMAND(insertParagraphSeparator)
282 WEBCORE_COMMAND(insertTab)
283 WEBCORE_COMMAND(insertTabIgnoringFieldEditor)
284 WEBCORE_COMMAND(makeTextWritingDirectionLeftToRight)
285 WEBCORE_COMMAND(makeTextWritingDirectionNatural)
286 WEBCORE_COMMAND(makeTextWritingDirectionRightToLeft)
287 WEBCORE_COMMAND(moveBackward)
288 WEBCORE_COMMAND(moveBackwardAndModifySelection)
289 WEBCORE_COMMAND(moveDown)
290 WEBCORE_COMMAND(moveDownAndModifySelection)
291 WEBCORE_COMMAND(moveForward)
292 WEBCORE_COMMAND(moveForwardAndModifySelection)
293 WEBCORE_COMMAND(moveLeft)
294 WEBCORE_COMMAND(moveLeftAndModifySelection)
295 WEBCORE_COMMAND(moveParagraphBackwardAndModifySelection)
296 WEBCORE_COMMAND(moveParagraphForwardAndModifySelection)
297 WEBCORE_COMMAND(moveRight)
298 WEBCORE_COMMAND(moveRightAndModifySelection)
299 WEBCORE_COMMAND(moveToBeginningOfDocument)
300 WEBCORE_COMMAND(moveToBeginningOfDocumentAndModifySelection)
301 WEBCORE_COMMAND(moveToBeginningOfLine)
302 WEBCORE_COMMAND(moveToBeginningOfLineAndModifySelection)
303 WEBCORE_COMMAND(moveToBeginningOfParagraph)
304 WEBCORE_COMMAND(moveToBeginningOfParagraphAndModifySelection)
305 WEBCORE_COMMAND(moveToBeginningOfSentence)
306 WEBCORE_COMMAND(moveToBeginningOfSentenceAndModifySelection)
307 WEBCORE_COMMAND(moveToEndOfDocument)
308 WEBCORE_COMMAND(moveToEndOfDocumentAndModifySelection)
309 WEBCORE_COMMAND(moveToEndOfLine)
310 WEBCORE_COMMAND(moveToEndOfLineAndModifySelection)
311 WEBCORE_COMMAND(moveToEndOfParagraph)
312 WEBCORE_COMMAND(moveToEndOfParagraphAndModifySelection)
313 WEBCORE_COMMAND(moveToEndOfSentence)
314 WEBCORE_COMMAND(moveToEndOfSentenceAndModifySelection)
315 WEBCORE_COMMAND(moveToLeftEndOfLine)
316 WEBCORE_COMMAND(moveToLeftEndOfLineAndModifySelection)
317 WEBCORE_COMMAND(moveToRightEndOfLine)
318 WEBCORE_COMMAND(moveToRightEndOfLineAndModifySelection)
319 WEBCORE_COMMAND(moveUp)
320 WEBCORE_COMMAND(moveUpAndModifySelection)
321 WEBCORE_COMMAND(moveWordBackward)
322 WEBCORE_COMMAND(moveWordBackwardAndModifySelection)
323 WEBCORE_COMMAND(moveWordForward)
324 WEBCORE_COMMAND(moveWordForwardAndModifySelection)
325 WEBCORE_COMMAND(moveWordLeft)
326 WEBCORE_COMMAND(moveWordLeftAndModifySelection)
327 WEBCORE_COMMAND(moveWordRight)
328 WEBCORE_COMMAND(moveWordRightAndModifySelection)
329 WEBCORE_COMMAND(outdent)
330 WEBCORE_COMMAND(pageDown)
331 WEBCORE_COMMAND(pageDownAndModifySelection)
332 WEBCORE_COMMAND(pageUp)
333 WEBCORE_COMMAND(pageUpAndModifySelection)
334 WEBCORE_COMMAND(paste)
335 WEBCORE_COMMAND(pasteAsPlainText)
336 WEBCORE_COMMAND(scrollPageDown)
337 WEBCORE_COMMAND(scrollPageUp)
338 WEBCORE_COMMAND(scrollLineDown)
339 WEBCORE_COMMAND(scrollLineUp)
340 WEBCORE_COMMAND(scrollToBeginningOfDocument)
341 WEBCORE_COMMAND(scrollToEndOfDocument)
342 WEBCORE_COMMAND(selectAll)
343 WEBCORE_COMMAND(selectLine)
344 WEBCORE_COMMAND(selectParagraph)
345 WEBCORE_COMMAND(selectSentence)
346 WEBCORE_COMMAND(selectToMark)
347 WEBCORE_COMMAND(selectWord)
348 WEBCORE_COMMAND(setMark)
349 WEBCORE_COMMAND(subscript)
350 WEBCORE_COMMAND(superscript)
351 WEBCORE_COMMAND(swapWithMark)
352 WEBCORE_COMMAND(takeFindStringFromSelection)
353 WEBCORE_COMMAND(transpose)
354 WEBCORE_COMMAND(underline)
355 WEBCORE_COMMAND(unscript)
356 WEBCORE_COMMAND(yank)
357 WEBCORE_COMMAND(yankAndSelect)
358
359 #undef WEBCORE_COMMAND
360
361 - (BOOL)writeSelectionToPasteboard:(NSPasteboard *)pasteboard types:(NSArray *)types
362 {
363     return _data->_impl->writeSelectionToPasteboard(pasteboard, types);
364 }
365
366 - (void)centerSelectionInVisibleArea:(id)sender 
367
368     _data->_impl->centerSelectionInVisibleArea();
369 }
370
371 - (id)validRequestorForSendType:(NSString *)sendType returnType:(NSString *)returnType
372 {
373     return _data->_impl->validRequestorForSendAndReturnTypes(sendType, returnType);
374 }
375
376 - (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pasteboard 
377 {
378     return _data->_impl->readSelectionFromPasteboard(pasteboard);
379 }
380
381 - (void)changeFont:(id)sender
382 {
383     _data->_impl->changeFontFromFontPanel();
384 }
385
386 /*
387
388 When possible, editing-related methods should be implemented in WebCore with the
389 EditorCommand mechanism and invoked via WEBCORE_COMMAND, rather than implementing
390 individual methods here with Mac-specific code.
391
392 Editing-related methods still unimplemented that are implemented in WebKit1:
393
394 - (void)complete:(id)sender;
395 - (void)copyFont:(id)sender;
396 - (void)makeBaseWritingDirectionLeftToRight:(id)sender;
397 - (void)makeBaseWritingDirectionNatural:(id)sender;
398 - (void)makeBaseWritingDirectionRightToLeft:(id)sender;
399 - (void)pasteFont:(id)sender;
400 - (void)scrollLineDown:(id)sender;
401 - (void)scrollLineUp:(id)sender;
402 - (void)showGuessPanel:(id)sender;
403
404 Some other editing-related methods still unimplemented:
405
406 - (void)changeCaseOfLetter:(id)sender;
407 - (void)copyRuler:(id)sender;
408 - (void)insertContainerBreak:(id)sender;
409 - (void)insertDoubleQuoteIgnoringSubstitution:(id)sender;
410 - (void)insertSingleQuoteIgnoringSubstitution:(id)sender;
411 - (void)pasteRuler:(id)sender;
412 - (void)toggleRuler:(id)sender;
413 - (void)transposeWords:(id)sender;
414
415 */
416
417 - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item
418 {
419     return _data->_impl->validateUserInterfaceItem(item);
420 }
421
422 - (IBAction)startSpeaking:(id)sender
423 {
424     _data->_impl->startSpeaking();
425 }
426
427 - (IBAction)stopSpeaking:(id)sender
428 {
429     _data->_impl->stopSpeaking(sender);
430 }
431
432 - (IBAction)showGuessPanel:(id)sender
433 {
434     _data->_impl->showGuessPanel(sender);
435 }
436
437 - (IBAction)checkSpelling:(id)sender
438 {
439     _data->_impl->checkSpelling();
440 }
441
442 - (void)changeSpelling:(id)sender
443 {
444     _data->_impl->changeSpelling(sender);
445 }
446
447 - (IBAction)toggleContinuousSpellChecking:(id)sender
448 {
449     _data->_impl->toggleContinuousSpellChecking();
450 }
451
452 - (BOOL)isGrammarCheckingEnabled
453 {
454     return _data->_impl->isGrammarCheckingEnabled();
455 }
456
457 - (void)setGrammarCheckingEnabled:(BOOL)flag
458 {
459     _data->_impl->setGrammarCheckingEnabled(flag);
460 }
461
462 - (IBAction)toggleGrammarChecking:(id)sender
463 {
464     _data->_impl->toggleGrammarChecking();
465 }
466
467 - (IBAction)toggleAutomaticSpellingCorrection:(id)sender
468 {
469     _data->_impl->toggleAutomaticSpellingCorrection();
470 }
471
472 - (void)orderFrontSubstitutionsPanel:(id)sender
473 {
474     _data->_impl->orderFrontSubstitutionsPanel(sender);
475 }
476
477 - (IBAction)toggleSmartInsertDelete:(id)sender
478 {
479     _data->_impl->toggleSmartInsertDelete();
480 }
481
482 - (BOOL)isAutomaticQuoteSubstitutionEnabled
483 {
484     return _data->_impl->isAutomaticQuoteSubstitutionEnabled();
485 }
486
487 - (void)setAutomaticQuoteSubstitutionEnabled:(BOOL)flag
488 {
489     _data->_impl->setAutomaticQuoteSubstitutionEnabled(flag);
490 }
491
492 - (void)toggleAutomaticQuoteSubstitution:(id)sender
493 {
494     _data->_impl->toggleAutomaticQuoteSubstitution();
495 }
496
497 - (BOOL)isAutomaticDashSubstitutionEnabled
498 {
499     return _data->_impl->isAutomaticDashSubstitutionEnabled();
500 }
501
502 - (void)setAutomaticDashSubstitutionEnabled:(BOOL)flag
503 {
504     _data->_impl->setAutomaticDashSubstitutionEnabled(flag);
505 }
506
507 - (void)toggleAutomaticDashSubstitution:(id)sender
508 {
509     _data->_impl->toggleAutomaticDashSubstitution();
510 }
511
512 - (BOOL)isAutomaticLinkDetectionEnabled
513 {
514     return _data->_impl->isAutomaticLinkDetectionEnabled();
515 }
516
517 - (void)setAutomaticLinkDetectionEnabled:(BOOL)flag
518 {
519     _data->_impl->setAutomaticLinkDetectionEnabled(flag);
520 }
521
522 - (void)toggleAutomaticLinkDetection:(id)sender
523 {
524     _data->_impl->toggleAutomaticLinkDetection();
525 }
526
527 - (BOOL)isAutomaticTextReplacementEnabled
528 {
529     return _data->_impl->isAutomaticTextReplacementEnabled();
530 }
531
532 - (void)setAutomaticTextReplacementEnabled:(BOOL)flag
533 {
534     _data->_impl->setAutomaticTextReplacementEnabled(flag);
535 }
536
537 - (void)toggleAutomaticTextReplacement:(id)sender
538 {
539     _data->_impl->toggleAutomaticTextReplacement();
540 }
541
542 - (void)uppercaseWord:(id)sender
543 {
544     _data->_impl->uppercaseWord();
545 }
546
547 - (void)lowercaseWord:(id)sender
548 {
549     _data->_impl->lowercaseWord();
550 }
551
552 - (void)capitalizeWord:(id)sender
553 {
554     _data->_impl->capitalizeWord();
555 }
556
557 // Events
558
559 // Override this so that AppKit will send us arrow keys as key down events so we can
560 // support them via the key bindings mechanism.
561 - (BOOL)_wantsKeyDownForEvent:(NSEvent *)event
562 {
563     return YES;
564 }
565
566 #if USE(ASYNC_NSTEXTINPUTCLIENT)
567 #define NATIVE_MOUSE_EVENT_HANDLER(Selector) \
568     - (void)Selector:(NSEvent *)theEvent \
569     { \
570         if (_data->_impl->ignoresNonWheelEvents()) \
571             return; \
572         if (NSTextInputContext *context = [self inputContext]) { \
573             [context handleEvent:theEvent completionHandler:^(BOOL handled) { \
574                 if (handled) \
575                     LOG(TextInput, "%s was handled by text input context", String(#Selector).substring(0, String(#Selector).find("Internal")).ascii().data()); \
576                 else { \
577                     NativeWebMouseEvent webEvent(theEvent, _data->_impl->lastPressureEvent(), self); \
578                     _data->_page->handleMouseEvent(webEvent); \
579                 } \
580             }]; \
581             return; \
582         } \
583         NativeWebMouseEvent webEvent(theEvent, _data->_impl->lastPressureEvent(), self); \
584         _data->_page->handleMouseEvent(webEvent); \
585     }
586 #define NATIVE_MOUSE_EVENT_HANDLER_INTERNAL(Selector) \
587     - (void)Selector:(NSEvent *)theEvent \
588     { \
589         if (_data->_impl->ignoresNonWheelEvents()) \
590             return; \
591         if (NSTextInputContext *context = [self inputContext]) { \
592             [context handleEvent:theEvent completionHandler:^(BOOL handled) { \
593                 if (handled) \
594                     LOG(TextInput, "%s was handled by text input context", String(#Selector).substring(0, String(#Selector).find("Internal")).ascii().data()); \
595                 else { \
596                     NativeWebMouseEvent webEvent(theEvent, _data->_impl->lastPressureEvent(), self); \
597                     _data->_page->handleMouseEvent(webEvent); \
598                 } \
599             }]; \
600             return; \
601         } \
602         NativeWebMouseEvent webEvent(theEvent, _data->_impl->lastPressureEvent(), self); \
603         _data->_page->handleMouseEvent(webEvent); \
604     }
605 #else
606 #define NATIVE_MOUSE_EVENT_HANDLER(Selector) \
607     - (void)Selector:(NSEvent *)theEvent \
608     { \
609         if (_data->_impl->ignoresNonWheelEvents()) \
610             return; \
611         if ([[self inputContext] handleEvent:theEvent]) { \
612             LOG(TextInput, "%s was handled by text input context", String(#Selector).substring(0, String(#Selector).find("Internal")).ascii().data()); \
613             return; \
614         } \
615         NativeWebMouseEvent webEvent(theEvent, _data->_impl->lastPressureEvent(), self); \
616         _data->_page->handleMouseEvent(webEvent); \
617     }
618 #define NATIVE_MOUSE_EVENT_HANDLER_INTERNAL(Selector) \
619     - (void)Selector:(NSEvent *)theEvent \
620     { \
621         if (_data->_impl->ignoresNonWheelEvents()) \
622             return; \
623         if ([[self inputContext] handleEvent:theEvent]) { \
624             LOG(TextInput, "%s was handled by text input context", String(#Selector).substring(0, String(#Selector).find("Internal")).ascii().data()); \
625             return; \
626         } \
627         NativeWebMouseEvent webEvent(theEvent, _data->_impl->lastPressureEvent(), self); \
628         _data->_page->handleMouseEvent(webEvent); \
629     }
630 #endif
631
632 NATIVE_MOUSE_EVENT_HANDLER(mouseEntered)
633 NATIVE_MOUSE_EVENT_HANDLER(mouseExited)
634 NATIVE_MOUSE_EVENT_HANDLER(otherMouseDown)
635 NATIVE_MOUSE_EVENT_HANDLER(otherMouseDragged)
636 NATIVE_MOUSE_EVENT_HANDLER(otherMouseUp)
637 NATIVE_MOUSE_EVENT_HANDLER(rightMouseDown)
638 NATIVE_MOUSE_EVENT_HANDLER(rightMouseDragged)
639 NATIVE_MOUSE_EVENT_HANDLER(rightMouseUp)
640
641 NATIVE_MOUSE_EVENT_HANDLER_INTERNAL(mouseMovedInternal)
642 NATIVE_MOUSE_EVENT_HANDLER_INTERNAL(mouseDownInternal)
643 NATIVE_MOUSE_EVENT_HANDLER_INTERNAL(mouseUpInternal)
644 NATIVE_MOUSE_EVENT_HANDLER_INTERNAL(mouseDraggedInternal)
645
646 #undef NATIVE_MOUSE_EVENT_HANDLER
647
648 - (void)scrollWheel:(NSEvent *)event
649 {
650     _data->_impl->scrollWheel(event);
651 }
652
653 - (void)swipeWithEvent:(NSEvent *)event
654 {
655     _data->_impl->swipeWithEvent(event);
656 }
657
658 - (void)mouseMoved:(NSEvent *)event
659 {
660     if (_data->_impl->ignoresNonWheelEvents())
661         return;
662
663     // When a view is first responder, it gets mouse moved events even when the mouse is outside its visible rect.
664     if (self == [[self window] firstResponder] && !NSPointInRect([self convertPoint:[event locationInWindow] fromView:nil], [self visibleRect]))
665         return;
666
667     [self mouseMovedInternal:event];
668 }
669
670 - (void)mouseDown:(NSEvent *)event
671 {
672     if (_data->_impl->ignoresNonWheelEvents())
673         return;
674
675     _data->_impl->setLastMouseDownEvent(event);
676     _data->_impl->setIgnoresMouseDraggedEvents(false);
677
678     [self mouseDownInternal:event];
679 }
680
681 - (void)mouseUp:(NSEvent *)event
682 {
683     if (_data->_impl->ignoresNonWheelEvents())
684         return;
685
686     _data->_impl->setLastMouseDownEvent(nil);
687     [self mouseUpInternal:event];
688 }
689
690 - (void)mouseDragged:(NSEvent *)event
691 {
692     if (_data->_impl->ignoresNonWheelEvents())
693         return;
694     if (_data->_impl->ignoresMouseDraggedEvents())
695         return;
696
697     [self mouseDraggedInternal:event];
698 }
699
700 - (void)pressureChangeWithEvent:(NSEvent *)event
701 {
702     _data->_impl->pressureChangeWithEvent(event);
703 }
704
705 - (BOOL)acceptsFirstMouse:(NSEvent *)event
706 {
707     // There's a chance that responding to this event will run a nested event loop, and
708     // fetching a new event might release the old one. Retaining and then autoreleasing
709     // the current event prevents that from causing a problem inside WebKit or AppKit code.
710     [[event retain] autorelease];
711     
712     if (![self hitTest:[event locationInWindow]])
713         return NO;
714     
715     _data->_impl->setLastMouseDownEvent(event);
716     bool result = _data->_page->acceptsFirstMouse([event eventNumber], WebEventFactory::createWebMouseEvent(event, _data->_impl->lastPressureEvent(), self));
717     _data->_impl->setLastMouseDownEvent(nil);
718     return result;
719 }
720
721 - (BOOL)shouldDelayWindowOrderingForEvent:(NSEvent *)event
722 {
723     // If this is the active window or we don't have a range selection, there is no need to perform additional checks
724     // and we can avoid making a synchronous call to the WebProcess.
725     if ([[self window] isKeyWindow] || _data->_page->editorState().selectionIsNone || !_data->_page->editorState().selectionIsRange)
726         return NO;
727
728     // There's a chance that responding to this event will run a nested event loop, and
729     // fetching a new event might release the old one. Retaining and then autoreleasing
730     // the current event prevents that from causing a problem inside WebKit or AppKit code.
731     [[event retain] autorelease];
732     
733     if (![self hitTest:[event locationInWindow]])
734         return NO;
735     
736     _data->_impl->setLastMouseDownEvent(event);
737     bool result = _data->_page->shouldDelayWindowOrderingForEvent(WebEventFactory::createWebMouseEvent(event, _data->_impl->lastPressureEvent(), self));
738     _data->_impl->setLastMouseDownEvent(nil);
739     return result;
740 }
741
742 - (void)doCommandBySelector:(SEL)selector
743 {
744     _data->_impl->doCommandBySelector(selector);
745 }
746
747 - (void)insertText:(id)string
748 {
749     _data->_impl->insertText(string);
750 }
751
752 - (void)insertText:(id)string replacementRange:(NSRange)replacementRange
753 {
754     _data->_impl->insertText(string, replacementRange);
755 }
756
757 - (NSTextInputContext *)inputContext
758 {
759     return _data->_impl->inputContext();
760 }
761
762 - (BOOL)performKeyEquivalent:(NSEvent *)event
763 {
764     return _data->_impl->performKeyEquivalent(event);
765 }
766
767 - (void)keyUp:(NSEvent *)theEvent
768 {
769     _data->_impl->keyUp(theEvent);
770 }
771
772 - (void)keyDown:(NSEvent *)theEvent
773 {
774     _data->_impl->keyDown(theEvent);
775 }
776
777 - (void)flagsChanged:(NSEvent *)theEvent
778 {
779     _data->_impl->flagsChanged(theEvent);
780 }
781
782 - (void)setMarkedText:(id)string selectedRange:(NSRange)newSelectedRange replacementRange:(NSRange)replacementRange
783 {
784     _data->_impl->setMarkedText(string, newSelectedRange, replacementRange);
785 }
786
787 - (void)unmarkText
788 {
789     _data->_impl->unmarkText();
790 }
791
792 - (NSRange)selectedRange
793 {
794     return _data->_impl->selectedRange();
795 }
796
797 - (BOOL)hasMarkedText
798 {
799     return _data->_impl->hasMarkedText();
800 }
801
802 - (NSRange)markedRange
803 {
804     return _data->_impl->markedRange();
805 }
806
807 - (NSAttributedString *)attributedSubstringForProposedRange:(NSRange)nsRange actualRange:(NSRangePointer)actualRange
808 {
809     return _data->_impl->attributedSubstringForProposedRange(nsRange, actualRange);
810 }
811
812 - (NSUInteger)characterIndexForPoint:(NSPoint)thePoint
813 {
814     return _data->_impl->characterIndexForPoint(thePoint);
815 }
816
817 - (NSRect)firstRectForCharacterRange:(NSRange)theRange actualRange:(NSRangePointer)actualRange
818 {
819     return _data->_impl->firstRectForCharacterRange(theRange, actualRange);
820 }
821
822 #if USE(ASYNC_NSTEXTINPUTCLIENT)
823
824 - (void)selectedRangeWithCompletionHandler:(void(^)(NSRange selectedRange))completionHandlerPtr
825 {
826     _data->_impl->selectedRangeWithCompletionHandler(completionHandlerPtr);
827 }
828
829 - (void)markedRangeWithCompletionHandler:(void(^)(NSRange markedRange))completionHandlerPtr
830 {
831     _data->_impl->markedRangeWithCompletionHandler(completionHandlerPtr);
832 }
833
834 - (void)hasMarkedTextWithCompletionHandler:(void(^)(BOOL hasMarkedText))completionHandlerPtr
835 {
836     _data->_impl->hasMarkedTextWithCompletionHandler(completionHandlerPtr);
837 }
838
839 - (void)attributedSubstringForProposedRange:(NSRange)nsRange completionHandler:(void(^)(NSAttributedString *attrString, NSRange actualRange))completionHandlerPtr
840 {
841     _data->_impl->attributedSubstringForProposedRange(nsRange, completionHandlerPtr);
842 }
843
844 - (void)firstRectForCharacterRange:(NSRange)theRange completionHandler:(void(^)(NSRect firstRect, NSRange actualRange))completionHandlerPtr
845 {
846     _data->_impl->firstRectForCharacterRange(theRange, completionHandlerPtr);
847 }
848
849 - (void)characterIndexForPoint:(NSPoint)thePoint completionHandler:(void(^)(NSUInteger))completionHandlerPtr
850 {
851     _data->_impl->characterIndexForPoint(thePoint, completionHandlerPtr);
852 }
853
854 #endif // USE(ASYNC_NSTEXTINPUTCLIENT)
855
856 - (NSTextInputContext *)_superInputContext
857 {
858     return [super inputContext];
859 }
860
861 - (void)_superQuickLookWithEvent:(NSEvent *)event
862 {
863     [super quickLookWithEvent:event];
864 }
865
866 - (void)_superSwipeWithEvent:(NSEvent *)event
867 {
868     [super swipeWithEvent:event];
869 }
870
871 - (void)_superMagnifyWithEvent:(NSEvent *)event
872 {
873     [super magnifyWithEvent:event];
874 }
875
876 - (void)_superSmartMagnifyWithEvent:(NSEvent *)event
877 {
878     [super smartMagnifyWithEvent:event];
879 }
880
881 - (void)_superRemoveTrackingRect:(NSTrackingRectTag)tag
882 {
883     [super removeTrackingRect:tag];
884 }
885
886 - (id)_superAccessibilityAttributeValue:(NSString *)attribute
887 {
888 #pragma clang diagnostic push
889 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
890     return [super accessibilityAttributeValue:attribute];
891 #pragma clang diagnostic pop
892 }
893
894 - (void)_superDoCommandBySelector:(SEL)selector
895 {
896     [super doCommandBySelector:selector];
897 }
898
899 - (BOOL)_superPerformKeyEquivalent:(NSEvent *)event
900 {
901     return [super performKeyEquivalent:event];
902 }
903
904 - (void)_superKeyDown:(NSEvent *)event
905 {
906     [super keyDown:event];
907 }
908
909 - (NSArray *)validAttributesForMarkedText
910 {
911     static NSArray *validAttributes;
912     if (!validAttributes) {
913         validAttributes = [[NSArray alloc] initWithObjects:
914                            NSUnderlineStyleAttributeName, NSUnderlineColorAttributeName,
915                            NSMarkedClauseSegmentAttributeName,
916 #if USE(DICTATION_ALTERNATIVES)
917                            NSTextAlternativesAttributeName,
918 #endif
919 #if USE(INSERTION_UNDO_GROUPING)
920                            NSTextInsertionUndoableAttributeName,
921 #endif
922                            nil];
923         // NSText also supports the following attributes, but it's
924         // hard to tell which are really required for text input to
925         // work well; I have not seen any input method make use of them yet.
926         //     NSFontAttributeName, NSForegroundColorAttributeName,
927         //     NSBackgroundColorAttributeName, NSLanguageAttributeName.
928         CFRetain(validAttributes);
929     }
930     LOG(TextInput, "validAttributesForMarkedText -> (...)");
931     return validAttributes;
932 }
933
934 #if ENABLE(DRAG_SUPPORT)
935 - (void)draggedImage:(NSImage *)image endedAt:(NSPoint)endPoint operation:(NSDragOperation)operation
936 {
937     _data->_impl->draggedImage(image, NSPointToCGPoint(endPoint), operation);
938 }
939
940 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)draggingInfo
941 {
942     return _data->_impl->draggingEntered(draggingInfo);
943 }
944
945 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)draggingInfo
946 {
947     return _data->_impl->draggingUpdated(draggingInfo);
948 }
949
950 - (void)draggingExited:(id <NSDraggingInfo>)draggingInfo
951 {
952     _data->_impl->draggingExited(draggingInfo);
953 }
954
955 - (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)draggingInfo
956 {
957     return _data->_impl->prepareForDragOperation(draggingInfo);
958 }
959
960 - (BOOL)performDragOperation:(id <NSDraggingInfo>)draggingInfo
961 {
962     return _data->_impl->performDragOperation(draggingInfo);
963 }
964
965 - (NSView *)_hitTest:(NSPoint *)point dragTypes:(NSSet *)types
966 {
967     return _data->_impl->hitTestForDragTypes(NSPointToCGPoint(*point), types);
968 }
969 #endif // ENABLE(DRAG_SUPPORT)
970
971 - (BOOL)_windowResizeMouseLocationIsInVisibleScrollerThumb:(NSPoint)loc
972 {
973     NSPoint localPoint = [self convertPoint:loc fromView:nil];
974     NSRect visibleThumbRect = NSRect(_data->_page->visibleScrollerThumbRect());
975     return NSMouseInRect(localPoint, visibleThumbRect, [self isFlipped]);
976 }
977
978 - (void)_addFontPanelObserver
979 {
980     _data->_impl->startObservingFontPanel();
981 }
982
983 - (void)viewWillMoveToWindow:(NSWindow *)window
984 {
985     _data->_impl->viewWillMoveToWindow(window);
986 }
987
988 - (void)viewDidMoveToWindow
989 {
990     _data->_impl->viewDidMoveToWindow();
991 }
992
993 - (void)drawRect:(NSRect)rect
994 {
995     LOG(Printing, "drawRect: x:%g, y:%g, width:%g, height:%g", rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
996     _data->_page->endPrinting();
997 }
998
999 - (BOOL)isOpaque
1000 {
1001     return _data->_page->drawsBackground();
1002 }
1003
1004 - (BOOL)mouseDownCanMoveWindow
1005 {
1006     // -[NSView mouseDownCanMoveWindow] returns YES when the NSView is transparent,
1007     // but we don't want a drag in the NSView to move the window, even if it's transparent.
1008     return NO;
1009 }
1010
1011 - (void)viewDidHide
1012 {
1013     _data->_page->viewStateDidChange(ViewState::IsVisible);
1014 }
1015
1016 - (void)viewDidUnhide
1017 {
1018     _data->_page->viewStateDidChange(ViewState::IsVisible);
1019 }
1020
1021 - (void)viewDidChangeBackingProperties
1022 {
1023     _data->_impl->viewDidChangeBackingProperties();
1024 }
1025
1026 - (void)_activeSpaceDidChange:(NSNotification *)notification
1027 {
1028     _data->_page->viewStateDidChange(ViewState::IsVisible);
1029 }
1030
1031 - (id)accessibilityFocusedUIElement
1032 {
1033     return _data->_impl->accessibilityFocusedUIElement();
1034 }
1035
1036 - (BOOL)accessibilityIsIgnored
1037 {
1038     return _data->_impl->accessibilityIsIgnored();
1039 }
1040
1041 - (id)accessibilityHitTest:(NSPoint)point
1042 {
1043     return _data->_impl->accessibilityHitTest(NSPointToCGPoint(point));
1044 }
1045
1046 - (id)accessibilityAttributeValue:(NSString *)attribute
1047 {
1048     return _data->_impl->accessibilityAttributeValue(attribute);
1049 }
1050
1051 - (NSView *)hitTest:(NSPoint)point
1052 {
1053     NSView *hitView = [super hitTest:point];
1054     if (hitView && _data && hitView == _data->_impl->layerHostingView())
1055         hitView = self;
1056
1057     return hitView;
1058 }
1059
1060 - (NSInteger)conversationIdentifier
1061 {
1062     return (NSInteger)self;
1063 }
1064
1065 - (void)quickLookWithEvent:(NSEvent *)event
1066 {
1067     _data->_impl->quickLookWithEvent(event);
1068 }
1069
1070 - (NSTrackingRectTag)addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside
1071 {
1072     return _data->_impl->addTrackingRect(NSRectToCGRect(rect), owner, data, assumeInside);
1073 }
1074
1075 - (NSTrackingRectTag)_addTrackingRect:(NSRect)rect owner:(id)owner userData:(void *)data assumeInside:(BOOL)assumeInside useTrackingNum:(int)tag
1076 {
1077     return _data->_impl->addTrackingRectWithTrackingNum(NSRectToCGRect(rect), owner, data, assumeInside, tag);
1078 }
1079
1080 - (void)_addTrackingRects:(NSRect *)rects owner:(id)owner userDataList:(void **)userDataList assumeInsideList:(BOOL *)assumeInsideList trackingNums:(NSTrackingRectTag *)trackingNums count:(int)count
1081 {
1082     CGRect *cgRects = (CGRect *)calloc(1, sizeof(CGRect));
1083     for (int i = 0; i < count; i++)
1084         cgRects[i] = NSRectToCGRect(rects[i]);
1085     _data->_impl->addTrackingRectsWithTrackingNums(cgRects, owner, userDataList, assumeInsideList, trackingNums, count);
1086     free(cgRects);
1087 }
1088
1089 - (void)removeTrackingRect:(NSTrackingRectTag)tag
1090 {
1091     if (!_data)
1092         return;
1093     _data->_impl->removeTrackingRect(tag);
1094 }
1095
1096 - (void)_removeTrackingRects:(NSTrackingRectTag *)tags count:(int)count
1097 {
1098     if (!_data)
1099         return;
1100     _data->_impl->removeTrackingRects(tags, count);
1101 }
1102
1103 - (NSString *)view:(NSView *)view stringForToolTip:(NSToolTipTag)tag point:(NSPoint)point userData:(void *)data
1104 {
1105     return _data->_impl->stringForToolTip(tag);
1106 }
1107
1108 - (void)pasteboardChangedOwner:(NSPasteboard *)pasteboard
1109 {
1110     _data->_impl->pasteboardChangedOwner(pasteboard);
1111 }
1112
1113 - (void)pasteboard:(NSPasteboard *)pasteboard provideDataForType:(NSString *)type
1114 {
1115     _data->_impl->provideDataForPasteboard(pasteboard, type);
1116 }
1117
1118 - (NSArray *)namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination
1119 {
1120     return _data->_impl->namesOfPromisedFilesDroppedAtDestination(dropDestination);
1121 }
1122
1123 - (instancetype)initWithFrame:(NSRect)frame processPool:(WebProcessPool&)processPool configuration:(Ref<API::PageConfiguration>&&)configuration webView:(WKWebView *)webView
1124 {
1125     self = [super initWithFrame:frame];
1126     if (!self)
1127         return nil;
1128
1129     [NSApp registerServicesMenuSendTypes:PasteboardTypes::forSelection() returnTypes:PasteboardTypes::forEditing()];
1130
1131     InitializeWebKit2();
1132
1133     _data = [[WKViewData alloc] init];
1134
1135     _data->_pageClient = std::make_unique<PageClientImpl>(self, webView);
1136     _data->_page = processPool.createWebPage(*_data->_pageClient, WTF::move(configuration));
1137
1138     _data->_impl = std::make_unique<WebViewImpl>(self, *_data->_page, *_data->_pageClient);
1139     static_cast<PageClientImpl&>(*_data->_pageClient).setImpl(*_data->_impl);
1140
1141     _data->_page->setAddsVisitedLinks(processPool.historyClient().addsVisitedLinks());
1142
1143     _data->_page->initializeWebPage();
1144
1145     _data->_impl->registerDraggedTypes();
1146
1147     self.wantsLayer = YES;
1148
1149     // Explicitly set the layer contents placement so AppKit will make sure that our layer has masksToBounds set to YES.
1150     self.layerContentsPlacement = NSViewLayerContentsPlacementTopLeft;
1151
1152     WebProcessPool::statistics().wkViewCount++;
1153
1154     NSNotificationCenter* workspaceNotificationCenter = [[NSWorkspace sharedWorkspace] notificationCenter];
1155     [workspaceNotificationCenter addObserver:self selector:@selector(_activeSpaceDidChange:) name:NSWorkspaceActiveSpaceDidChangeNotification object:nil];
1156
1157     return self;
1158 }
1159
1160 #if WK_API_ENABLED
1161 - (void)_setThumbnailView:(_WKThumbnailView *)thumbnailView
1162 {
1163     _data->_impl->setThumbnailView(thumbnailView);
1164 }
1165
1166 - (_WKThumbnailView *)_thumbnailView
1167 {
1168     if (!_data->_impl)
1169         return nil;
1170     return _data->_impl->thumbnailView();
1171 }
1172 #endif // WK_API_ENABLED
1173
1174
1175 // FIXME: Get rid of this when we have better plumbing to WKViewLayoutStrategy.
1176 - (void)_updateViewExposedRect
1177 {
1178     _data->_impl->updateViewExposedRect();
1179 }
1180
1181 @end
1182
1183 @implementation WKView (Private)
1184
1185 - (void)saveBackForwardSnapshotForCurrentItem
1186 {
1187     _data->_impl->saveBackForwardSnapshotForCurrentItem();
1188 }
1189
1190 - (void)saveBackForwardSnapshotForItem:(WKBackForwardListItemRef)item
1191 {
1192     _data->_impl->saveBackForwardSnapshotForItem(*toImpl(item));
1193 }
1194
1195 - (id)initWithFrame:(NSRect)frame contextRef:(WKContextRef)contextRef pageGroupRef:(WKPageGroupRef)pageGroupRef
1196 {
1197     return [self initWithFrame:frame contextRef:contextRef pageGroupRef:pageGroupRef relatedToPage:nil];
1198 }
1199
1200 - (id)initWithFrame:(NSRect)frame contextRef:(WKContextRef)contextRef pageGroupRef:(WKPageGroupRef)pageGroupRef relatedToPage:(WKPageRef)relatedPage
1201 {
1202     auto configuration = API::PageConfiguration::create();
1203     configuration->setProcessPool(toImpl(contextRef));
1204     configuration->setPageGroup(toImpl(pageGroupRef));
1205     configuration->setRelatedPage(toImpl(relatedPage));
1206
1207     return [self initWithFrame:frame processPool:*toImpl(contextRef) configuration:WTF::move(configuration) webView:nil];
1208 }
1209
1210 - (id)initWithFrame:(NSRect)frame configurationRef:(WKPageConfigurationRef)configurationRef
1211 {
1212     Ref<API::PageConfiguration> configuration = toImpl(configurationRef)->copy();
1213     auto& processPool = *configuration->processPool();
1214
1215     return [self initWithFrame:frame processPool:processPool configuration:WTF::move(configuration) webView:nil];
1216 }
1217
1218 - (BOOL)wantsUpdateLayer
1219 {
1220     return YES;
1221 }
1222
1223 - (void)updateLayer
1224 {
1225     _data->_impl->updateLayer();
1226 }
1227
1228 - (WKPageRef)pageRef
1229 {
1230     return toAPI(_data->_page.get());
1231 }
1232
1233 - (BOOL)canChangeFrameLayout:(WKFrameRef)frameRef
1234 {
1235     // PDF documents are already paginated, so we can't change them to add headers and footers.
1236     return !toImpl(frameRef)->isDisplayingPDFDocument();
1237 }
1238
1239 - (NSPrintOperation *)printOperationWithPrintInfo:(NSPrintInfo *)printInfo forFrame:(WKFrameRef)frameRef
1240 {
1241     LOG(Printing, "Creating an NSPrintOperation for frame '%s'", toImpl(frameRef)->url().utf8().data());
1242
1243     // FIXME: If the frame cannot be printed (e.g. if it contains an encrypted PDF that disallows
1244     // printing), this function should return nil.
1245     RetainPtr<WKPrintingView> printingView = adoptNS([[WKPrintingView alloc] initWithFrameProxy:toImpl(frameRef) view:self]);
1246     // NSPrintOperation takes ownership of the view.
1247     NSPrintOperation *printOperation = [NSPrintOperation printOperationWithView:printingView.get() printInfo:printInfo];
1248     [printOperation setCanSpawnSeparateThread:YES];
1249     [printOperation setJobTitle:toImpl(frameRef)->title()];
1250     printingView->_printOperation = printOperation;
1251     return printOperation;
1252 }
1253
1254 - (void)setFrame:(NSRect)rect andScrollBy:(NSSize)offset
1255 {
1256     _data->_impl->setFrameAndScrollBy(NSRectToCGRect(rect), NSSizeToCGSize(offset));
1257 }
1258
1259 - (void)disableFrameSizeUpdates
1260 {
1261     _data->_impl->disableFrameSizeUpdates();
1262 }
1263
1264 - (void)enableFrameSizeUpdates
1265 {
1266     _data->_impl->enableFrameSizeUpdates();
1267 }
1268
1269 - (BOOL)frameSizeUpdatesDisabled
1270 {
1271     return _data->_impl->frameSizeUpdatesDisabled();
1272 }
1273
1274 + (void)hideWordDefinitionWindow
1275 {
1276     DictionaryLookup::hidePopup();
1277 }
1278
1279 - (NSSize)minimumSizeForAutoLayout
1280 {
1281     return NSSizeFromCGSize(_data->_impl->minimumSizeForAutoLayout());
1282 }
1283
1284 - (void)setMinimumSizeForAutoLayout:(NSSize)minimumSizeForAutoLayout
1285 {
1286     _data->_impl->setMinimumSizeForAutoLayout(NSSizeToCGSize(minimumSizeForAutoLayout));
1287 }
1288
1289 - (BOOL)shouldExpandToViewHeightForAutoLayout
1290 {
1291     return _data->_impl->shouldExpandToViewHeightForAutoLayout();
1292 }
1293
1294 - (void)setShouldExpandToViewHeightForAutoLayout:(BOOL)shouldExpand
1295 {
1296     return _data->_impl->setShouldExpandToViewHeightForAutoLayout(shouldExpand);
1297 }
1298
1299 - (BOOL)shouldClipToVisibleRect
1300 {
1301     return _data->_impl->clipsToVisibleRect();
1302 }
1303
1304 - (void)setShouldClipToVisibleRect:(BOOL)clipsToVisibleRect
1305 {
1306     _data->_impl->setClipsToVisibleRect(clipsToVisibleRect);
1307 }
1308
1309 - (NSColor *)underlayColor
1310 {
1311     return _data->_impl->underlayColor();
1312 }
1313
1314 - (void)setUnderlayColor:(NSColor *)underlayColor
1315 {
1316     _data->_impl->setUnderlayColor(underlayColor);
1317 }
1318
1319 #if WK_API_ENABLED
1320 - (NSView *)_inspectorAttachmentView
1321 {
1322     return _data->_impl->inspectorAttachmentView();
1323 }
1324
1325 - (void)_setInspectorAttachmentView:(NSView *)newView
1326 {
1327     _data->_impl->setInspectorAttachmentView(newView);
1328 }
1329 #endif
1330
1331 - (NSView *)fullScreenPlaceholderView
1332 {
1333     return _data->_impl->fullScreenPlaceholderView();
1334 }
1335
1336 // FIXME: This returns an autoreleased object. Should it really be prefixed 'create'?
1337 - (NSWindow *)createFullScreenWindow
1338 {
1339     return _data->_impl->createFullScreenWindow();
1340 }
1341
1342 - (void)beginDeferringViewInWindowChanges
1343 {
1344     _data->_impl->beginDeferringViewInWindowChanges();
1345 }
1346
1347 - (void)endDeferringViewInWindowChanges
1348 {
1349     _data->_impl->endDeferringViewInWindowChanges();
1350 }
1351
1352 - (void)endDeferringViewInWindowChangesSync
1353 {
1354     _data->_impl->endDeferringViewInWindowChangesSync();
1355 }
1356
1357 - (void)_prepareForMoveToWindow:(NSWindow *)targetWindow withCompletionHandler:(void(^)(void))completionHandler
1358 {
1359     _data->_impl->prepareForMoveToWindow(targetWindow, completionHandler);
1360 }
1361
1362 - (BOOL)isDeferringViewInWindowChanges
1363 {
1364     return _data->_impl->isDeferringViewInWindowChanges();
1365 }
1366
1367 - (BOOL)windowOcclusionDetectionEnabled
1368 {
1369     return _data->_impl->windowOcclusionDetectionEnabled();
1370 }
1371
1372 - (void)setWindowOcclusionDetectionEnabled:(BOOL)enabled
1373 {
1374     _data->_impl->setWindowOcclusionDetectionEnabled(enabled);
1375 }
1376
1377 - (void)setAllowsBackForwardNavigationGestures:(BOOL)allowsBackForwardNavigationGestures
1378 {
1379     _data->_impl->setAllowsBackForwardNavigationGestures(allowsBackForwardNavigationGestures);
1380 }
1381
1382 - (BOOL)allowsBackForwardNavigationGestures
1383 {
1384     return _data->_impl->allowsBackForwardNavigationGestures();
1385 }
1386
1387 - (BOOL)allowsLinkPreview
1388 {
1389     return _data->_impl->allowsLinkPreview();
1390 }
1391
1392 - (void)setAllowsLinkPreview:(BOOL)allowsLinkPreview
1393 {
1394     _data->_impl->setAllowsLinkPreview(allowsLinkPreview);
1395 }
1396
1397 - (void)_setIgnoresAllEvents:(BOOL)ignoresAllEvents
1398 {
1399     _data->_impl->setIgnoresAllEvents(ignoresAllEvents);
1400 }
1401
1402 // Forward _setIgnoresNonWheelMouseEvents to _setIgnoresNonWheelEvents to avoid breaking existing clients.
1403 - (void)_setIgnoresNonWheelMouseEvents:(BOOL)ignoresNonWheelMouseEvents
1404 {
1405     _data->_impl->setIgnoresNonWheelEvents(ignoresNonWheelMouseEvents);
1406 }
1407
1408 - (void)_setIgnoresNonWheelEvents:(BOOL)ignoresNonWheelEvents
1409 {
1410     _data->_impl->setIgnoresNonWheelEvents(ignoresNonWheelEvents);
1411 }
1412
1413 - (BOOL)_ignoresNonWheelEvents
1414 {
1415     return _data->_impl->ignoresNonWheelEvents();
1416 }
1417
1418 - (BOOL)_ignoresAllEvents
1419 {
1420     return _data->_impl->ignoresAllEvents();
1421 }
1422
1423 - (void)_setOverrideDeviceScaleFactor:(CGFloat)deviceScaleFactor
1424 {
1425     _data->_impl->setOverrideDeviceScaleFactor(deviceScaleFactor);
1426 }
1427
1428 - (CGFloat)_overrideDeviceScaleFactor
1429 {
1430     return _data->_impl->overrideDeviceScaleFactor();
1431 }
1432
1433 - (WKLayoutMode)_layoutMode
1434 {
1435     return _data->_impl->layoutMode();
1436 }
1437
1438 - (void)_setLayoutMode:(WKLayoutMode)layoutMode
1439 {
1440     _data->_impl->setLayoutMode(layoutMode);
1441 }
1442
1443 - (CGSize)_fixedLayoutSize
1444 {
1445     return _data->_impl->fixedLayoutSize();
1446 }
1447
1448 - (void)_setFixedLayoutSize:(CGSize)fixedLayoutSize
1449 {
1450     _data->_impl->setFixedLayoutSize(fixedLayoutSize);
1451 }
1452
1453 - (CGFloat)_viewScale
1454 {
1455     return _data->_impl->viewScale();
1456 }
1457
1458 - (void)_setViewScale:(CGFloat)viewScale
1459 {
1460     _data->_impl->setViewScale(viewScale);
1461 }
1462
1463 - (void)_setTopContentInset:(CGFloat)contentInset
1464 {
1465     return _data->_impl->setTopContentInset(contentInset);
1466 }
1467
1468 - (CGFloat)_topContentInset
1469 {
1470     return _data->_impl->topContentInset();
1471 }
1472
1473 - (void)_setTotalHeightOfBanners:(CGFloat)totalHeightOfBanners
1474 {
1475     _data->_impl->setTotalHeightOfBanners(totalHeightOfBanners);
1476 }
1477
1478 - (CGFloat)_totalHeightOfBanners
1479 {
1480     return _data->_impl->totalHeightOfBanners();
1481 }
1482
1483 static WTF::Optional<WebCore::ScrollbarOverlayStyle> toCoreScrollbarStyle(_WKOverlayScrollbarStyle scrollbarStyle)
1484 {
1485     switch (scrollbarStyle) {
1486     case _WKOverlayScrollbarStyleDark:
1487         return WebCore::ScrollbarOverlayStyleDark;
1488     case _WKOverlayScrollbarStyleLight:
1489         return WebCore::ScrollbarOverlayStyleLight;
1490     case _WKOverlayScrollbarStyleDefault:
1491         return WebCore::ScrollbarOverlayStyleDefault;
1492     case _WKOverlayScrollbarStyleAutomatic:
1493     default:
1494         break;
1495     }
1496
1497     return Nullopt;
1498 }
1499
1500 static _WKOverlayScrollbarStyle toAPIScrollbarStyle(WTF::Optional<WebCore::ScrollbarOverlayStyle> coreScrollbarStyle)
1501 {
1502     if (!coreScrollbarStyle)
1503         return _WKOverlayScrollbarStyleAutomatic;
1504
1505     switch (coreScrollbarStyle.value()) {
1506     case WebCore::ScrollbarOverlayStyleDark:
1507         return _WKOverlayScrollbarStyleDark;
1508     case WebCore::ScrollbarOverlayStyleLight:
1509         return _WKOverlayScrollbarStyleLight;
1510     case WebCore::ScrollbarOverlayStyleDefault:
1511         return _WKOverlayScrollbarStyleDefault;
1512     default:
1513         return _WKOverlayScrollbarStyleAutomatic;
1514     }
1515 }
1516
1517 - (void)_setOverlayScrollbarStyle:(_WKOverlayScrollbarStyle)scrollbarStyle
1518 {
1519     _data->_impl->setOverlayScrollbarStyle(toCoreScrollbarStyle(scrollbarStyle));
1520 }
1521
1522 - (_WKOverlayScrollbarStyle)_overlayScrollbarStyle
1523 {
1524     return toAPIScrollbarStyle(_data->_impl->overlayScrollbarStyle());
1525 }
1526
1527 - (NSColor *)_pageExtendedBackgroundColor
1528 {
1529     return _data->_impl->pageExtendedBackgroundColor();
1530 }
1531
1532 - (void)forceAsyncDrawingAreaSizeUpdate:(NSSize)size
1533 {
1534     _data->_impl->forceAsyncDrawingAreaSizeUpdate(NSSizeToCGSize(size));
1535 }
1536
1537 - (void)waitForAsyncDrawingAreaSizeUpdate
1538 {
1539     _data->_impl->waitForAsyncDrawingAreaSizeUpdate();
1540 }
1541
1542 - (BOOL)isUsingUISideCompositing
1543 {
1544     return _data->_impl->isUsingUISideCompositing();
1545 }
1546
1547 - (void)setAllowsMagnification:(BOOL)allowsMagnification
1548 {
1549     _data->_impl->setAllowsMagnification(allowsMagnification);
1550 }
1551
1552 - (BOOL)allowsMagnification
1553 {
1554     return _data->_impl->allowsMagnification();
1555 }
1556
1557 - (void)magnifyWithEvent:(NSEvent *)event
1558 {
1559     _data->_impl->magnifyWithEvent(event);
1560 }
1561
1562 #if ENABLE(MAC_GESTURE_EVENTS)
1563 - (void)rotateWithEvent:(NSEvent *)event
1564 {
1565     _data->_impl->rotateWithEvent(event);
1566 }
1567 #endif
1568
1569 - (void)_gestureEventWasNotHandledByWebCore:(NSEvent *)event
1570 {
1571     _data->_impl->gestureEventWasNotHandledByWebCoreFromViewOnly(event);
1572 }
1573
1574 - (void)smartMagnifyWithEvent:(NSEvent *)event
1575 {
1576     _data->_impl->smartMagnifyWithEvent(event);
1577 }
1578
1579 - (void)setMagnification:(double)magnification centeredAtPoint:(NSPoint)point
1580 {
1581     _data->_impl->setMagnification(magnification, NSPointToCGPoint(point));
1582 }
1583
1584 - (void)setMagnification:(double)magnification
1585 {
1586     _data->_impl->setMagnification(magnification);
1587 }
1588
1589 - (double)magnification
1590 {
1591     return _data->_impl->magnification();
1592 }
1593
1594 - (void)_setCustomSwipeViews:(NSArray *)customSwipeViews
1595 {
1596     _data->_impl->setCustomSwipeViews(customSwipeViews);
1597 }
1598
1599 - (void)_setCustomSwipeViewsTopContentInset:(float)topContentInset
1600 {
1601     _data->_impl->setCustomSwipeViewsTopContentInset(topContentInset);
1602 }
1603
1604 - (BOOL)_tryToSwipeWithEvent:(NSEvent *)event ignoringPinnedState:(BOOL)ignoringPinnedState
1605 {
1606     return _data->_impl->tryToSwipeWithEvent(event, ignoringPinnedState);
1607 }
1608
1609 - (void)_setDidMoveSwipeSnapshotCallback:(void(^)(CGRect))callback
1610 {
1611     _data->_impl->setDidMoveSwipeSnapshotCallback(callback);
1612 }
1613
1614 - (id)_immediateActionAnimationControllerForHitTestResult:(WKHitTestResultRef)hitTestResult withType:(uint32_t)type userData:(WKTypeRef)userData
1615 {
1616     return nil;
1617 }
1618
1619 - (void)_prepareForImmediateActionAnimation
1620 {
1621 }
1622
1623 - (void)_cancelImmediateActionAnimation
1624 {
1625 }
1626
1627 - (void)_completeImmediateActionAnimation
1628 {
1629 }
1630
1631 - (void)_didChangeContentSize:(NSSize)newSize
1632 {
1633 }
1634
1635 - (void)_dismissContentRelativeChildWindows
1636 {
1637     _data->_impl->dismissContentRelativeChildWindowsFromViewOnly();
1638 }
1639
1640 - (void)_dismissContentRelativeChildWindowsWithAnimation:(BOOL)withAnimation
1641 {
1642     _data->_impl->dismissContentRelativeChildWindowsWithAnimationFromViewOnly(withAnimation);
1643 }
1644
1645 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101000
1646
1647 - (void)_setAutomaticallyAdjustsContentInsets:(BOOL)automaticallyAdjustsContentInsets
1648 {
1649     _data->_impl->setAutomaticallyAdjustsContentInsets(automaticallyAdjustsContentInsets);
1650 }
1651
1652 - (BOOL)_automaticallyAdjustsContentInsets
1653 {
1654     return _data->_impl->automaticallyAdjustsContentInsets();
1655 }
1656
1657 #endif
1658
1659 @end
1660
1661 #endif // PLATFORM(MAC)