Implement ScrollableArea::scrollOffset()
[WebKit-https.git] / Source / WebKit / WebProcess / Plugins / PDF / PDFPlugin.mm
1 /*
2  * Copyright (C) 2009-2017 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 "PDFPlugin.h"
28
29 #if ENABLE(PDFKIT_PLUGIN)
30
31 #import "ArgumentCoders.h"
32 #import "DataReference.h"
33 #import "PDFAnnotationTextWidgetDetails.h"
34 #import "PDFContextMenu.h"
35 #import "PDFLayerControllerSPI.h"
36 #import "PDFPluginAnnotation.h"
37 #import "PDFPluginPasswordField.h"
38 #import "PluginView.h"
39 #import "WKAccessibilityWebPageObjectMac.h"
40 #import "WKPageFindMatchesClient.h"
41 #import "WebCoreArgumentCoders.h"
42 #import "WebEvent.h"
43 #import "WebEventConversion.h"
44 #import "WebFindOptions.h"
45 #import "WebPage.h"
46 #import "WebPageProxyMessages.h"
47 #import "WebPasteboardProxyMessages.h"
48 #import "WebProcess.h"
49 #import <JavaScriptCore/JSContextRef.h>
50 #import <JavaScriptCore/JSObjectRef.h>
51 #import <Quartz/Quartz.h>
52 #import <QuartzCore/QuartzCore.h>
53 #import <WebCore/AXObjectCache.h>
54 #import <WebCore/ArchiveResource.h>
55 #import <WebCore/Chrome.h>
56 #import <WebCore/Cursor.h>
57 #import <WebCore/DictionaryLookup.h>
58 #import <WebCore/DocumentLoader.h>
59 #import <WebCore/EventNames.h>
60 #import <WebCore/FocusController.h>
61 #import <WebCore/FormState.h>
62 #import <WebCore/Frame.h>
63 #import <WebCore/FrameLoader.h>
64 #import <WebCore/FrameView.h>
65 #import <WebCore/GraphicsContext.h>
66 #import <WebCore/HTMLElement.h>
67 #import <WebCore/HTMLFormElement.h>
68 #import <WebCore/HTMLPlugInElement.h>
69 #import <WebCore/LegacyNSPasteboardTypes.h>
70 #import <WebCore/LocalDefaultSystemAppearance.h>
71 #import <WebCore/LocalizedStrings.h>
72 #import <WebCore/MouseEvent.h>
73 #import <WebCore/PDFDocumentImage.h>
74 #import <WebCore/Page.h>
75 #import <WebCore/Pasteboard.h>
76 #import <WebCore/PlatformScreen.h>
77 #import <WebCore/PluginData.h>
78 #import <WebCore/PluginDocument.h>
79 #import <WebCore/RenderBoxModelObject.h>
80 #import <WebCore/ScrollAnimator.h>
81 #import <WebCore/ScrollbarTheme.h>
82 #import <WebCore/Settings.h>
83 #import <WebCore/WebAccessibilityObjectWrapperMac.h>
84 #import <WebCore/WheelEventTestTrigger.h>
85 #import <pal/spi/cg/CoreGraphicsSPI.h>
86 #import <pal/spi/mac/NSMenuSPI.h>
87 #import <wtf/UUID.h>
88
89 // Set overflow: hidden on the annotation container so <input> elements scrolled out of view don't show
90 // scrollbars on the body. We can't add annotations directly to the body, because overflow: hidden on the body
91 // will break rubber-banding.
92 static const char* annotationStyle =
93 "#annotationContainer {"
94 "    overflow: hidden; "
95 "    position: absolute; "
96 "    pointer-events: none; "
97 "    top: 0; "
98 "    left: 0; "
99 "    right: 0; "
100 "    bottom: 0; "
101 "    display: -webkit-box; "
102 "    -webkit-box-align: center; "
103 "    -webkit-box-pack: center; "
104 "} "
105 ".annotation { "
106 "    position: absolute; "
107 "    pointer-events: auto; "
108 "} "
109 "textarea.annotation { "
110 "    resize: none; "
111 "} "
112 "input.annotation[type='password'] { "
113 "    position: static; "
114 "    width: 200px; "
115 "    margin-top: 100px; "
116 "} ";
117
118 // In non-continuous modes, a single scroll event with a magnitude of >= 20px
119 // will jump to the next or previous page, to match PDFKit behavior.
120 static const int defaultScrollMagnitudeThresholdForPageFlip = 20;
121
122 @interface WKPDFPluginAccessibilityObject : NSObject {
123     PDFLayerController *_pdfLayerController;
124     __unsafe_unretained NSObject *_parent;
125     WebKit::PDFPlugin* _pdfPlugin;
126 }
127
128 @property (assign) PDFLayerController *pdfLayerController;
129 @property (assign) NSObject *parent;
130 @property (assign) WebKit::PDFPlugin* pdfPlugin;
131
132 - (id)initWithPDFPlugin:(WebKit::PDFPlugin *)plugin;
133
134 @end
135
136 @implementation WKPDFPluginAccessibilityObject
137
138 @synthesize parent=_parent;
139 @synthesize pdfPlugin=_pdfPlugin;
140
141 - (id)initWithPDFPlugin:(WebKit::PDFPlugin *)plugin
142 {
143     if (!(self = [super init]))
144         return nil;
145
146     _pdfPlugin = plugin;
147
148     return self;
149 }
150
151 - (PDFLayerController *)pdfLayerController
152 {
153     return _pdfLayerController;
154 }
155
156 - (void)setPdfLayerController:(PDFLayerController *)pdfLayerController
157 {
158     _pdfLayerController = pdfLayerController;
159 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101300
160     [_pdfLayerController setAccessibilityParent:self];
161 #endif
162 }
163
164 IGNORE_WARNINGS_BEGIN("deprecated-implementations")
165 - (BOOL)accessibilityIsIgnored
166 IGNORE_WARNINGS_END
167 {
168     return NO;
169 }
170
171 // This is called by PDFAccessibilityNodes from inside PDFKit to get final bounds.
172 - (NSRect)convertRectToScreenSpace:(NSRect)rect
173 {
174     return _pdfPlugin->convertFromPDFViewToScreen(rect);
175 }
176
177 IGNORE_WARNINGS_BEGIN("deprecated-implementations")
178 - (id)accessibilityAttributeValue:(NSString *)attribute
179 IGNORE_WARNINGS_END
180 {
181     if ([attribute isEqualToString:NSAccessibilityParentAttribute])
182         return _parent;
183     if ([attribute isEqualToString:NSAccessibilityTopLevelUIElementAttribute])
184         return [_parent accessibilityAttributeValue:NSAccessibilityTopLevelUIElementAttribute];
185     if ([attribute isEqualToString:NSAccessibilityWindowAttribute])
186         return [_parent accessibilityAttributeValue:NSAccessibilityWindowAttribute];
187     if ([attribute isEqualToString:NSAccessibilitySizeAttribute])
188         return [NSValue valueWithSize:_pdfPlugin->boundsOnScreen().size()];
189     if ([attribute isEqualToString:NSAccessibilityEnabledAttribute])
190         return [_parent accessibilityAttributeValue:NSAccessibilityEnabledAttribute];
191     if ([attribute isEqualToString:NSAccessibilityPositionAttribute])
192         return [NSValue valueWithPoint:_pdfPlugin->boundsOnScreen().location()];
193
194 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101300
195     if ([attribute isEqualToString:NSAccessibilityChildrenAttribute])
196         return @[ _pdfLayerController ];
197     if ([attribute isEqualToString:NSAccessibilityRoleAttribute])
198         return NSAccessibilityGroupRole;
199 #else
200     if ([attribute isEqualToString:NSAccessibilityValueAttribute])
201         return [_pdfLayerController accessibilityValueAttribute];
202     if ([attribute isEqualToString:NSAccessibilitySelectedTextAttribute])
203         return [_pdfLayerController accessibilitySelectedTextAttribute];
204     if ([attribute isEqualToString:NSAccessibilitySelectedTextRangeAttribute])
205         return [_pdfLayerController accessibilitySelectedTextRangeAttribute];
206     if ([attribute isEqualToString:NSAccessibilityNumberOfCharactersAttribute])
207         return [_pdfLayerController accessibilityNumberOfCharactersAttribute];
208     if ([attribute isEqualToString:NSAccessibilityVisibleCharacterRangeAttribute])
209         return [_pdfLayerController accessibilityVisibleCharacterRangeAttribute];
210     if ([attribute isEqualToString:NSAccessibilityRoleAttribute])
211         return [_pdfLayerController accessibilityRoleAttribute];
212     if ([attribute isEqualToString:NSAccessibilityRoleDescriptionAttribute])
213         return [_pdfLayerController accessibilityRoleDescriptionAttribute];
214     if ([attribute isEqualToString:NSAccessibilityFocusedAttribute])
215         return [_parent accessibilityAttributeValue:NSAccessibilityFocusedAttribute];
216 #endif
217
218     return 0;
219 }
220
221 IGNORE_WARNINGS_BEGIN("deprecated-implementations")
222 - (id)accessibilityAttributeValue:(NSString *)attribute forParameter:(id)parameter
223 IGNORE_WARNINGS_END
224 {
225     if ([attribute isEqualToString:NSAccessibilityBoundsForRangeParameterizedAttribute]) {
226         NSRect boundsInPDFViewCoordinates = [[_pdfLayerController accessibilityBoundsForRangeAttributeForParameter:parameter] rectValue];
227         NSRect boundsInScreenCoordinates = _pdfPlugin->convertFromPDFViewToScreen(boundsInPDFViewCoordinates);
228         return [NSValue valueWithRect:boundsInScreenCoordinates];
229     }
230
231     if ([attribute isEqualToString:NSAccessibilityLineForIndexParameterizedAttribute])
232         return [_pdfLayerController accessibilityLineForIndexAttributeForParameter:parameter];
233     if ([attribute isEqualToString:NSAccessibilityRangeForLineParameterizedAttribute])
234         return [_pdfLayerController accessibilityRangeForLineAttributeForParameter:parameter];
235     if ([attribute isEqualToString:NSAccessibilityStringForRangeParameterizedAttribute])
236         return [_pdfLayerController accessibilityStringForRangeAttributeForParameter:parameter];
237
238     return 0;
239 }
240
241 - (CPReadingModel *)readingModel
242 {
243     return [_pdfLayerController readingModel];
244 }
245
246 IGNORE_WARNINGS_BEGIN("deprecated-implementations")
247 - (NSArray *)accessibilityAttributeNames
248 IGNORE_WARNINGS_END
249 {
250     static NSArray *attributeNames = 0;
251
252     if (!attributeNames) {
253         attributeNames = @[
254             NSAccessibilityParentAttribute,
255             NSAccessibilityWindowAttribute,
256             NSAccessibilityTopLevelUIElementAttribute,
257             NSAccessibilityRoleDescriptionAttribute,
258             NSAccessibilitySizeAttribute,
259             NSAccessibilityEnabledAttribute,
260             NSAccessibilityPositionAttribute,
261             NSAccessibilityFocusedAttribute,
262             // PDFLayerController has its own accessibilityChildren.
263 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101300
264             NSAccessibilityChildrenAttribute
265 #else
266             NSAccessibilityRoleAttribute,
267             NSAccessibilityValueAttribute,
268             NSAccessibilitySelectedTextAttribute,
269             NSAccessibilitySelectedTextRangeAttribute,
270             NSAccessibilityNumberOfCharactersAttribute,
271             NSAccessibilityVisibleCharacterRangeAttribute
272 #endif
273             ];
274         [attributeNames retain];
275     }
276
277     return attributeNames;
278 }
279
280 IGNORE_WARNINGS_BEGIN("deprecated-implementations")
281 - (NSArray *)accessibilityActionNames
282 IGNORE_WARNINGS_END
283 {
284 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101300
285     return nil;
286 #else
287     static NSArray *actionNames = 0;
288     
289     if (!actionNames)
290         actionNames = [[NSArray arrayWithObject:NSAccessibilityShowMenuAction] retain];
291     
292     return actionNames;
293 #endif
294 }
295
296 IGNORE_WARNINGS_BEGIN("deprecated-implementations")
297 - (void)accessibilityPerformAction:(NSString *)action
298 IGNORE_WARNINGS_END
299 {
300     if ([action isEqualToString:NSAccessibilityShowMenuAction])
301         _pdfPlugin->showContextMenuAtPoint(WebCore::IntRect(WebCore::IntPoint(), _pdfPlugin->size()).center());
302 }
303
304 IGNORE_WARNINGS_BEGIN("deprecated-implementations")
305 - (BOOL)accessibilityIsAttributeSettable:(NSString *)attribute
306 IGNORE_WARNINGS_END
307 {
308     return [_pdfLayerController accessibilityIsAttributeSettable:attribute];
309 }
310
311 IGNORE_WARNINGS_BEGIN("deprecated-implementations")
312 - (void)accessibilitySetValue:(id)value forAttribute:(NSString *)attribute
313 IGNORE_WARNINGS_END
314 {
315     return [_pdfLayerController accessibilitySetValue:value forAttribute:attribute];
316 }
317
318 IGNORE_WARNINGS_BEGIN("deprecated-implementations")
319 - (NSArray *)accessibilityParameterizedAttributeNames
320 IGNORE_WARNINGS_END
321 {
322 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101300
323     return nil;
324 #else
325     return [_pdfLayerController accessibilityParameterizedAttributeNames];
326 #endif
327 }
328
329 - (id)accessibilityFocusedUIElement
330 {
331 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101300
332     if (WebKit::PDFPluginAnnotation* activeAnnotation = _pdfPlugin->activeAnnotation()) {
333         if (WebCore::AXObjectCache* existingCache = _pdfPlugin->axObjectCache()) {
334             if (WebCore::AccessibilityObject* object = existingCache->getOrCreate(activeAnnotation->element()))
335                 ALLOW_DEPRECATED_DECLARATIONS_BEGIN
336                 return [object->wrapper() accessibilityAttributeValue:@"_AXAssociatedPluginParent"];
337                 ALLOW_DEPRECATED_DECLARATIONS_END
338         }
339     }
340     return nil;
341 #else
342     return self;
343 #endif
344 }
345
346 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101300
347 - (id)accessibilityAssociatedControlForAnnotation:(PDFAnnotation *)annotation
348 {
349     // Only active annotations seem to have their associated controls available.
350     WebKit::PDFPluginAnnotation* activeAnnotation = _pdfPlugin->activeAnnotation();
351     if (!activeAnnotation || ![activeAnnotation->annotation() isEqual:annotation])
352         return nil;
353     
354     WebCore::AXObjectCache* cache = _pdfPlugin->axObjectCache();
355     if (!cache)
356         return nil;
357     
358     WebCore::AccessibilityObject* object = cache->getOrCreate(activeAnnotation->element());
359     if (!object)
360         return nil;
361
362     return object->wrapper();
363 }
364 #endif
365
366 - (id)accessibilityHitTest:(NSPoint)point
367 {
368 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101300
369     point = _pdfPlugin->convertFromRootViewToPDFView(WebCore::IntPoint(point));
370     return [_pdfLayerController accessibilityHitTest:point];
371 #else
372     return self;
373 #endif
374 }
375
376 @end
377
378
379 @interface WKPDFPluginScrollbarLayer : CALayer {
380     WebKit::PDFPlugin* _pdfPlugin;
381 }
382
383 @property (assign) WebKit::PDFPlugin* pdfPlugin;
384
385 @end
386
387 @implementation WKPDFPluginScrollbarLayer
388
389 @synthesize pdfPlugin=_pdfPlugin;
390
391 - (id)initWithPDFPlugin:(WebKit::PDFPlugin *)plugin
392 {
393     if (!(self = [super init]))
394         return nil;
395     
396     _pdfPlugin = plugin;
397     
398     return self;
399 }
400
401 - (id<CAAction>)actionForKey:(NSString *)key
402 {
403     return nil;
404 }
405
406 - (void)drawInContext:(CGContextRef)ctx
407 {
408     _pdfPlugin->paintControlForLayerInContext(self, ctx);
409 }
410
411 @end
412
413 @interface WKPDFLayerControllerDelegate : NSObject<PDFLayerControllerDelegate> {
414     WebKit::PDFPlugin* _pdfPlugin;
415 }
416
417 @property (assign) WebKit::PDFPlugin* pdfPlugin;
418
419 @end
420
421 @implementation WKPDFLayerControllerDelegate
422
423 @synthesize pdfPlugin=_pdfPlugin;
424
425 - (id)initWithPDFPlugin:(WebKit::PDFPlugin *)plugin
426 {
427     if (!(self = [super init]))
428         return nil;
429     
430     _pdfPlugin = plugin;
431     
432     return self;
433 }
434
435 - (void)updateScrollPosition:(CGPoint)newPosition
436 {
437     _pdfPlugin->notifyScrollPositionChanged(WebCore::IntPoint(newPosition));
438 }
439
440 - (void)writeItemsToPasteboard:(NSArray *)items withTypes:(NSArray *)types
441 {
442     ALLOW_DEPRECATED_DECLARATIONS_BEGIN
443     _pdfPlugin->writeItemsToPasteboard(NSGeneralPboard, items, types);
444     ALLOW_DEPRECATED_DECLARATIONS_END
445 }
446
447 - (void)showDefinitionForAttributedString:(NSAttributedString *)string atPoint:(CGPoint)point
448 {
449     _pdfPlugin->showDefinitionForAttributedString(string, point);
450 }
451
452 - (void)performWebSearch:(NSString *)string
453 {
454     _pdfPlugin->performWebSearch(string);
455 }
456
457 - (void)performSpotlightSearch:(NSString *)string
458 {
459     _pdfPlugin->performSpotlightSearch(string);
460 }
461
462 - (void)openWithNativeApplication
463 {
464     _pdfPlugin->openWithNativeApplication();
465 }
466
467 - (void)saveToPDF
468 {
469     _pdfPlugin->saveToPDF();
470 }
471
472 - (void)pdfLayerController:(PDFLayerController *)pdfLayerController clickedLinkWithURL:(NSURL *)url
473 {
474     _pdfPlugin->clickedLink(url);
475 }
476
477 - (void)pdfLayerController:(PDFLayerController *)pdfLayerController didChangeActiveAnnotation:(PDFAnnotation *)annotation
478 {
479     _pdfPlugin->setActiveAnnotation(annotation);
480 }
481
482 - (void)pdfLayerController:(PDFLayerController *)pdfLayerController didChangeContentScaleFactor:(CGFloat)scaleFactor
483 {
484     _pdfPlugin->notifyContentScaleFactorChanged(scaleFactor);
485 }
486
487 - (void)pdfLayerController:(PDFLayerController *)pdfLayerController didChangeDisplayMode:(int)mode
488 {
489     _pdfPlugin->notifyDisplayModeChanged(mode);
490 }
491
492 - (void)pdfLayerController:(PDFLayerController *)pdfLayerController didChangeSelection:(PDFSelection *)selection
493 {
494     _pdfPlugin->notifySelectionChanged(selection);
495 }
496
497 - (void)setMouseCursor:(PDFLayerControllerCursorType)cursorType
498 {
499     _pdfPlugin->notifyCursorChanged(cursorType);
500 }
501
502 - (void)didChangeAnnotationState
503 {
504     _pdfPlugin->didMutatePDFDocument();
505 }
506
507 @end
508
509 @interface PDFViewLayout
510 - (NSPoint)convertPoint:(NSPoint)point toPage:(PDFPage *)page forScaleFactor:(CGFloat)scaleFactor;
511 - (NSRect)convertRect:(NSRect)rect fromPage:(PDFPage *) page forScaleFactor:(CGFloat) scaleFactor;
512 - (PDFPage *)pageNearestPoint:(NSPoint)point currentPage:(PDFPage *)currentPage;
513 @end
514
515 namespace WebKit {
516 using namespace WebCore;
517 using namespace HTMLNames;
518
519 static const char* postScriptMIMEType = "application/postscript";
520 const uint64_t pdfDocumentRequestID = 1; // PluginController supports loading multiple streams, but we only need one for PDF.
521
522 static void appendValuesInPDFNameSubtreeToVector(CGPDFDictionaryRef subtree, Vector<CGPDFObjectRef>& values)
523 {
524     CGPDFArrayRef names;
525     if (CGPDFDictionaryGetArray(subtree, "Names", &names)) {
526         size_t nameCount = CGPDFArrayGetCount(names) / 2;
527         for (size_t i = 0; i < nameCount; ++i) {
528             CGPDFObjectRef object;
529             CGPDFArrayGetObject(names, 2 * i + 1, &object);
530             values.append(object);
531         }
532         return;
533     }
534
535     CGPDFArrayRef kids;
536     if (!CGPDFDictionaryGetArray(subtree, "Kids", &kids))
537         return;
538
539     size_t kidCount = CGPDFArrayGetCount(kids);
540     for (size_t i = 0; i < kidCount; ++i) {
541         CGPDFDictionaryRef kid;
542         if (!CGPDFArrayGetDictionary(kids, i, &kid))
543             continue;
544         appendValuesInPDFNameSubtreeToVector(kid, values);
545     }
546 }
547
548 static void getAllValuesInPDFNameTree(CGPDFDictionaryRef tree, Vector<CGPDFObjectRef>& allValues)
549 {
550     appendValuesInPDFNameSubtreeToVector(tree, allValues);
551 }
552
553 static void getAllScriptsInPDFDocument(CGPDFDocumentRef pdfDocument, Vector<RetainPtr<CFStringRef>>& scripts)
554 {
555     if (!pdfDocument)
556         return;
557
558     CGPDFDictionaryRef pdfCatalog = CGPDFDocumentGetCatalog(pdfDocument);
559     if (!pdfCatalog)
560         return;
561
562     // Get the dictionary of all document-level name trees.
563     CGPDFDictionaryRef namesDictionary;
564     if (!CGPDFDictionaryGetDictionary(pdfCatalog, "Names", &namesDictionary))
565         return;
566
567     // Get the document-level "JavaScript" name tree.
568     CGPDFDictionaryRef javaScriptNameTree;
569     if (!CGPDFDictionaryGetDictionary(namesDictionary, "JavaScript", &javaScriptNameTree))
570         return;
571
572     // The names are arbitrary. We are only interested in the values.
573     Vector<CGPDFObjectRef> objects;
574     getAllValuesInPDFNameTree(javaScriptNameTree, objects);
575     size_t objectCount = objects.size();
576
577     for (size_t i = 0; i < objectCount; ++i) {
578         CGPDFDictionaryRef javaScriptAction;
579         if (!CGPDFObjectGetValue(reinterpret_cast<CGPDFObjectRef>(objects[i]), kCGPDFObjectTypeDictionary, &javaScriptAction))
580             continue;
581
582         // A JavaScript action must have an action type of "JavaScript".
583         const char* actionType;
584         if (!CGPDFDictionaryGetName(javaScriptAction, "S", &actionType) || strcmp(actionType, "JavaScript"))
585             continue;
586
587         const UInt8* bytes = 0;
588         CFIndex length;
589         CGPDFStreamRef stream;
590         CGPDFStringRef string;
591         RetainPtr<CFDataRef> data;
592         if (CGPDFDictionaryGetStream(javaScriptAction, "JS", &stream)) {
593             CGPDFDataFormat format;
594             data = adoptCF(CGPDFStreamCopyData(stream, &format));
595             if (!data)
596                 continue;
597             bytes = CFDataGetBytePtr(data.get());
598             length = CFDataGetLength(data.get());
599         } else if (CGPDFDictionaryGetString(javaScriptAction, "JS", &string)) {
600             bytes = CGPDFStringGetBytePtr(string);
601             length = CGPDFStringGetLength(string);
602         }
603         if (!bytes)
604             continue;
605
606         CFStringEncoding encoding = (length > 1 && bytes[0] == 0xFE && bytes[1] == 0xFF) ? kCFStringEncodingUnicode : kCFStringEncodingUTF8;
607         RetainPtr<CFStringRef> script = adoptCF(CFStringCreateWithBytes(kCFAllocatorDefault, bytes, length, encoding, true));
608         if (!script)
609             continue;
610         
611         scripts.append(script);
612     }
613 }
614
615 Ref<PDFPlugin> PDFPlugin::create(WebFrame& frame)
616 {
617     return adoptRef(*new PDFPlugin(frame));
618 }
619
620 inline PDFPlugin::PDFPlugin(WebFrame& frame)
621     : Plugin(PDFPluginType)
622     , m_frame(&frame)
623     , m_containerLayer(adoptNS([[CALayer alloc] init]))
624     , m_contentLayer(adoptNS([[CALayer alloc] init]))
625     , m_scrollCornerLayer(adoptNS([[WKPDFPluginScrollbarLayer alloc] initWithPDFPlugin:this]))
626     , m_pdfLayerController(adoptNS([[pdfLayerControllerClass() alloc] init]))
627     , m_pdfLayerControllerDelegate(adoptNS([[WKPDFLayerControllerDelegate alloc] initWithPDFPlugin:this]))
628 {
629     m_pdfLayerController.get().delegate = m_pdfLayerControllerDelegate.get();
630     m_pdfLayerController.get().parentLayer = m_contentLayer.get();
631
632     if (supportsForms()) {
633         Document* document = webFrame()->coreFrame()->document();
634         m_annotationContainer = document->createElement(divTag, false);
635         m_annotationContainer->setAttributeWithoutSynchronization(idAttr, AtomicString("annotationContainer", AtomicString::ConstructFromLiteral));
636
637         auto annotationStyleElement = document->createElement(styleTag, false);
638         annotationStyleElement->setTextContent(annotationStyle);
639
640         m_annotationContainer->appendChild(annotationStyleElement);
641         document->bodyOrFrameset()->appendChild(*m_annotationContainer);
642     }
643
644     m_accessibilityObject = adoptNS([[WKPDFPluginAccessibilityObject alloc] initWithPDFPlugin:this]);
645     [m_accessibilityObject setPdfLayerController:m_pdfLayerController.get()];
646     [m_accessibilityObject setParent:webFrame()->page()->accessibilityRemoteObject()];
647
648     [m_containerLayer addSublayer:m_contentLayer.get()];
649     [m_containerLayer addSublayer:m_scrollCornerLayer.get()];
650 #if ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
651     if ([m_pdfLayerController respondsToSelector:@selector(setDeviceColorSpace:)]) {
652         auto view = webFrame()->coreFrame()->view();
653         [m_pdfLayerController setDeviceColorSpace:screenColorSpace(view)];
654     }
655 #endif
656 }
657
658 PDFPlugin::~PDFPlugin()
659 {
660 }
661
662 PluginInfo PDFPlugin::pluginInfo()
663 {
664     PluginInfo info;
665     info.name = builtInPDFPluginName();
666     info.isApplicationPlugin = true;
667     info.clientLoadPolicy = PluginLoadClientPolicyUndefined;
668     info.bundleIdentifier = "com.apple.webkit.builtinpdfplugin"_s;
669
670     MimeClassInfo pdfMimeClassInfo;
671     pdfMimeClassInfo.type = "application/pdf";
672     pdfMimeClassInfo.desc = pdfDocumentTypeDescription();
673     pdfMimeClassInfo.extensions.append("pdf");
674     info.mimes.append(pdfMimeClassInfo);
675
676     MimeClassInfo textPDFMimeClassInfo;
677     textPDFMimeClassInfo.type = "text/pdf";
678     textPDFMimeClassInfo.desc = pdfDocumentTypeDescription();
679     textPDFMimeClassInfo.extensions.append("pdf");
680     info.mimes.append(textPDFMimeClassInfo);
681
682     MimeClassInfo postScriptMimeClassInfo;
683     postScriptMimeClassInfo.type = postScriptMIMEType;
684     postScriptMimeClassInfo.desc = postScriptDocumentTypeDescription();
685     postScriptMimeClassInfo.extensions.append("ps");
686     info.mimes.append(postScriptMimeClassInfo);
687     
688     return info;
689 }
690
691 void PDFPlugin::updateScrollbars()
692 {
693     bool hadScrollbars = m_horizontalScrollbar || m_verticalScrollbar;
694
695     if (m_horizontalScrollbar) {
696         if (m_size.width() >= m_pdfDocumentSize.width())
697             destroyScrollbar(HorizontalScrollbar);
698     } else if (m_size.width() < m_pdfDocumentSize.width())
699         m_horizontalScrollbar = createScrollbar(HorizontalScrollbar);
700
701     if (m_verticalScrollbar) {
702         if (m_size.height() >= m_pdfDocumentSize.height())
703             destroyScrollbar(VerticalScrollbar);
704     } else if (m_size.height() < m_pdfDocumentSize.height())
705         m_verticalScrollbar = createScrollbar(VerticalScrollbar);
706
707     IntSize scrollbarSpace = scrollbarIntrusion();
708
709     if (m_horizontalScrollbar) {
710         m_horizontalScrollbar->setSteps(Scrollbar::pixelsPerLineStep(), m_firstPageHeight);
711         m_horizontalScrollbar->setProportion(m_size.width() - scrollbarSpace.width(), m_pdfDocumentSize.width());
712         IntRect scrollbarRect(pluginView()->x(), pluginView()->y() + m_size.height() - m_horizontalScrollbar->height(), m_size.width(), m_horizontalScrollbar->height());
713         if (m_verticalScrollbar)
714             scrollbarRect.contract(m_verticalScrollbar->width(), 0);
715         m_horizontalScrollbar->setFrameRect(scrollbarRect);
716     }
717
718     if (m_verticalScrollbar) {
719         m_verticalScrollbar->setSteps(Scrollbar::pixelsPerLineStep(), m_firstPageHeight);
720         m_verticalScrollbar->setProportion(m_size.height() - scrollbarSpace.height(), m_pdfDocumentSize.height());
721         IntRect scrollbarRect(IntRect(pluginView()->x() + m_size.width() - m_verticalScrollbar->width(), pluginView()->y(), m_verticalScrollbar->width(), m_size.height()));
722         if (m_horizontalScrollbar)
723             scrollbarRect.contract(0, m_horizontalScrollbar->height());
724         m_verticalScrollbar->setFrameRect(scrollbarRect);
725     }
726
727     FrameView* frameView = m_frame->coreFrame()->view();
728     if (!frameView)
729         return;
730
731     bool hasScrollbars = m_horizontalScrollbar || m_verticalScrollbar;
732     if (hadScrollbars != hasScrollbars) {
733         if (hasScrollbars)
734             frameView->addScrollableArea(this);
735         else
736             frameView->removeScrollableArea(this);
737
738         frameView->setNeedsLayoutAfterViewConfigurationChange();
739     }
740     
741     if (m_verticalScrollbarLayer) {
742         m_verticalScrollbarLayer.get().frame = verticalScrollbar()->frameRect();
743         [m_verticalScrollbarLayer setNeedsDisplay];
744     }
745     
746     if (m_horizontalScrollbarLayer) {
747         m_horizontalScrollbarLayer.get().frame = horizontalScrollbar()->frameRect();
748         [m_horizontalScrollbarLayer setNeedsDisplay];
749     }
750     
751     if (m_scrollCornerLayer) {
752         m_scrollCornerLayer.get().frame = scrollCornerRect();
753         [m_scrollCornerLayer setNeedsDisplay];
754     }
755 }
756
757 PluginView* PDFPlugin::pluginView()
758 {
759     return static_cast<PluginView*>(controller());
760 }
761
762 const PluginView* PDFPlugin::pluginView() const
763 {
764     return static_cast<const PluginView*>(controller());
765 }
766
767 Ref<Scrollbar> PDFPlugin::createScrollbar(ScrollbarOrientation orientation)
768 {
769     auto widget = Scrollbar::createNativeScrollbar(*this, orientation, RegularScrollbar);
770     if (orientation == HorizontalScrollbar) {
771         m_horizontalScrollbarLayer = adoptNS([[WKPDFPluginScrollbarLayer alloc] initWithPDFPlugin:this]);
772         [m_containerLayer addSublayer:m_horizontalScrollbarLayer.get()];
773     } else {
774         m_verticalScrollbarLayer = adoptNS([[WKPDFPluginScrollbarLayer alloc] initWithPDFPlugin:this]);
775         [m_containerLayer addSublayer:m_verticalScrollbarLayer.get()];
776     }
777     didAddScrollbar(widget.ptr(), orientation);
778     if (Frame* frame = webFrame()->coreFrame()) {
779         if (Page* page = frame->page()) {
780             if (page->expectsWheelEventTriggers())
781                 scrollAnimator().setWheelEventTestTrigger(page->testTrigger());
782         }
783     }
784     pluginView()->frame()->view()->addChild(widget);
785     return widget;
786 }
787
788 void PDFPlugin::destroyScrollbar(ScrollbarOrientation orientation)
789 {
790     RefPtr<Scrollbar>& scrollbar = orientation == HorizontalScrollbar ? m_horizontalScrollbar : m_verticalScrollbar;
791     if (!scrollbar)
792         return;
793
794     willRemoveScrollbar(scrollbar.get(), orientation);
795     scrollbar->removeFromParent();
796     scrollbar = nullptr;
797
798     if (orientation == HorizontalScrollbar) {
799         [m_horizontalScrollbarLayer removeFromSuperlayer];
800         m_horizontalScrollbarLayer = 0;
801     } else {
802         [m_verticalScrollbarLayer removeFromSuperlayer];
803         m_verticalScrollbarLayer = 0;
804     }
805 }
806
807 IntRect PDFPlugin::convertFromScrollbarToContainingView(const Scrollbar& scrollbar, const IntRect& scrollbarRect) const
808 {
809     IntRect rect = scrollbarRect;
810     rect.move(scrollbar.location() - pluginView()->location());
811
812     return pluginView()->frame()->view()->convertFromRendererToContainingView(pluginView()->pluginElement()->renderer(), rect);
813 }
814
815 IntRect PDFPlugin::convertFromContainingViewToScrollbar(const Scrollbar& scrollbar, const IntRect& parentRect) const
816 {
817     IntRect rect = pluginView()->frame()->view()->convertFromContainingViewToRenderer(pluginView()->pluginElement()->renderer(), parentRect);
818     rect.move(pluginView()->location() - scrollbar.location());
819
820     return rect;
821 }
822
823 IntPoint PDFPlugin::convertFromScrollbarToContainingView(const Scrollbar& scrollbar, const IntPoint& scrollbarPoint) const
824 {
825     IntPoint point = scrollbarPoint;
826     point.move(scrollbar.location() - pluginView()->location());
827
828     return pluginView()->frame()->view()->convertFromRendererToContainingView(pluginView()->pluginElement()->renderer(), point);
829 }
830
831 IntPoint PDFPlugin::convertFromContainingViewToScrollbar(const Scrollbar& scrollbar, const IntPoint& parentPoint) const
832 {
833     IntPoint point = pluginView()->frame()->view()->convertFromContainingViewToRenderer(pluginView()->pluginElement()->renderer(), parentPoint);
834     point.move(pluginView()->location() - scrollbar.location());
835     
836     return point;
837 }
838
839 bool PDFPlugin::handleScroll(ScrollDirection direction, ScrollGranularity granularity)
840 {
841     return scroll(direction, granularity);
842 }
843
844 IntRect PDFPlugin::scrollCornerRect() const
845 {
846     if (!m_horizontalScrollbar || !m_verticalScrollbar)
847         return IntRect();
848     if (m_horizontalScrollbar->isOverlayScrollbar()) {
849         ASSERT(m_verticalScrollbar->isOverlayScrollbar());
850         return IntRect();
851     }
852     return IntRect(pluginView()->width() - m_verticalScrollbar->width(), pluginView()->height() - m_horizontalScrollbar->height(), m_verticalScrollbar->width(), m_horizontalScrollbar->height());
853 }
854
855 ScrollableArea* PDFPlugin::enclosingScrollableArea() const
856 {
857     // FIXME: Walk up the frame tree and look for a scrollable parent frame or RenderLayer.
858     return nullptr;
859 }
860
861 IntRect PDFPlugin::scrollableAreaBoundingBox(bool*) const
862 {
863     return pluginView()->frameRect();
864 }
865
866 bool PDFPlugin::isActive() const
867 {
868     if (Frame* coreFrame = m_frame->coreFrame()) {
869         if (Page* page = coreFrame->page())
870             return page->focusController().isActive();
871     }
872
873     return false;
874 }
875
876 bool PDFPlugin::forceUpdateScrollbarsOnMainThreadForPerformanceTesting() const
877 {
878     if (Frame* coreFrame = m_frame->coreFrame()) {
879         if (Page* page = coreFrame->page())
880             return page->settings().forceUpdateScrollbarsOnMainThreadForPerformanceTesting();
881     }
882
883     return false;
884 }
885
886 ScrollPosition PDFPlugin::scrollPosition() const
887 {
888     return IntPoint(m_scrollOffset.width(), m_scrollOffset.height());
889 }
890
891 ScrollPosition PDFPlugin::minimumScrollPosition() const
892 {
893     return IntPoint();
894 }
895
896 ScrollPosition PDFPlugin::maximumScrollPosition() const
897 {
898     IntSize scrollbarSpace = scrollbarIntrusion();
899
900     IntPoint maximumOffset(m_pdfDocumentSize.width() - m_size.width() + scrollbarSpace.width(), m_pdfDocumentSize.height() - m_size.height() + scrollbarSpace.height());
901     maximumOffset.clampNegativeToZero();
902     return maximumOffset;
903 }
904
905 void PDFPlugin::scrollbarStyleChanged(ScrollbarStyle style, bool forceUpdate)
906 {
907     if (!forceUpdate)
908         return;
909
910     // If the PDF was scrolled all the way to bottom right and scrollbars change to overlay style, we don't want to display white rectangles where scrollbars were.
911     IntPoint newScrollOffset = IntPoint(m_scrollOffset).shrunkTo(maximumScrollPosition());
912     setScrollOffset(newScrollOffset);
913     
914     ScrollableArea::scrollbarStyleChanged(style, forceUpdate);
915     // As size of the content area changes, scrollbars may need to appear or to disappear.
916     updateScrollbars();
917 }
918
919 void PDFPlugin::addArchiveResource()
920 {
921     // FIXME: It's a hack to force add a resource to DocumentLoader. PDF documents should just be fetched as CachedResources.
922
923     // Add just enough data for context menu handling and web archives to work.
924     NSDictionary* headers = @{ @"Content-Disposition": (NSString *)m_suggestedFilename, @"Content-Type" : @"application/pdf" };
925     RetainPtr<NSURLResponse> response = adoptNS([[NSHTTPURLResponse alloc] initWithURL:m_sourceURL statusCode:200 HTTPVersion:(NSString*)kCFHTTPVersion1_1 headerFields:headers]);
926     ResourceResponse synthesizedResponse(response.get());
927
928     auto resource = ArchiveResource::create(SharedBuffer::create(m_data.get()), m_sourceURL, "application/pdf", String(), String(), synthesizedResponse);
929     pluginView()->frame()->document()->loader()->addArchiveResource(resource.releaseNonNull());
930 }
931
932 static void jsPDFDocInitialize(JSContextRef ctx, JSObjectRef object)
933 {
934     PDFPlugin* pdfView = static_cast<PDFPlugin*>(JSObjectGetPrivate(object));
935     pdfView->ref();
936 }
937
938 static void jsPDFDocFinalize(JSObjectRef object)
939 {
940     PDFPlugin* pdfView = static_cast<PDFPlugin*>(JSObjectGetPrivate(object));
941     pdfView->deref();
942 }
943
944 JSValueRef PDFPlugin::jsPDFDocPrint(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
945 {
946     PDFPlugin* pdfView = static_cast<PDFPlugin*>(JSObjectGetPrivate(thisObject));
947
948     WebFrame* frame = pdfView->m_frame;
949     if (!frame)
950         return JSValueMakeUndefined(ctx);
951
952     Frame* coreFrame = frame->coreFrame();
953     if (!coreFrame)
954         return JSValueMakeUndefined(ctx);
955
956     Page* page = coreFrame->page();
957     if (!page)
958         return JSValueMakeUndefined(ctx);
959
960     page->chrome().print(*coreFrame);
961
962     return JSValueMakeUndefined(ctx);
963 }
964
965 JSObjectRef PDFPlugin::makeJSPDFDoc(JSContextRef ctx)
966 {
967     static JSStaticFunction jsPDFDocStaticFunctions[] = {
968         { "print", jsPDFDocPrint, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete },
969         { 0, 0, 0 },
970     };
971
972     static JSClassDefinition jsPDFDocClassDefinition = {
973         0,
974         kJSClassAttributeNone,
975         "Doc",
976         0,
977         0,
978         jsPDFDocStaticFunctions,
979         jsPDFDocInitialize, jsPDFDocFinalize, 0, 0, 0, 0, 0, 0, 0, 0, 0
980     };
981
982     static JSClassRef jsPDFDocClass = JSClassCreate(&jsPDFDocClassDefinition);
983
984     return JSObjectMake(ctx, jsPDFDocClass, this);
985 }
986
987 void PDFPlugin::convertPostScriptDataIfNeeded()
988 {
989     if (!m_isPostScript)
990         return;
991
992     m_suggestedFilename = String(m_suggestedFilename + ".pdf");
993     m_data = PDFDocumentImage::convertPostScriptDataToPDF(WTFMove(m_data));
994 }
995
996 void PDFPlugin::pdfDocumentDidLoad()
997 {
998     addArchiveResource();
999     
1000     RetainPtr<PDFDocument> document = adoptNS([[pdfDocumentClass() alloc] initWithData:rawData()]);
1001
1002     setPDFDocument(document);
1003
1004     updatePageAndDeviceScaleFactors();
1005
1006     [m_pdfLayerController setFrameSize:size()];
1007     m_pdfLayerController.get().document = document.get();
1008
1009     if (handlesPageScaleFactor())
1010         pluginView()->setPageScaleFactor([m_pdfLayerController contentScaleFactor], IntPoint());
1011
1012     notifyScrollPositionChanged(IntPoint([m_pdfLayerController scrollPosition]));
1013
1014     calculateSizes();
1015     updateScrollbars();
1016
1017     runScriptsInPDFDocument();
1018
1019     if ([document isLocked])
1020         createPasswordEntryForm();
1021
1022 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101300
1023     if ([m_pdfLayerController respondsToSelector:@selector(setURLFragment:)]) {
1024         String pdfURLFragment = webFrame()->url().fragmentIdentifier();
1025         [m_pdfLayerController setURLFragment:pdfURLFragment];
1026     }
1027 #endif
1028 }
1029     
1030 void PDFPlugin::streamDidReceiveResponse(uint64_t streamID, const URL&, uint32_t, uint32_t, const String& mimeType, const String&, const String& suggestedFilename)
1031 {
1032     ASSERT_UNUSED(streamID, streamID == pdfDocumentRequestID);
1033
1034     m_suggestedFilename = suggestedFilename;
1035
1036     if (equalIgnoringASCIICase(mimeType, postScriptMIMEType))
1037         m_isPostScript = true;
1038 }
1039
1040 void PDFPlugin::streamDidReceiveData(uint64_t streamID, const char* bytes, int length)
1041 {
1042     ASSERT_UNUSED(streamID, streamID == pdfDocumentRequestID);
1043
1044     if (!m_data)
1045         m_data = adoptCF(CFDataCreateMutable(0, 0));
1046
1047     CFDataAppendBytes(m_data.get(), reinterpret_cast<const UInt8*>(bytes), length);
1048 }
1049
1050 void PDFPlugin::streamDidFinishLoading(uint64_t streamID)
1051 {
1052     ASSERT_UNUSED(streamID, streamID == pdfDocumentRequestID);
1053
1054     convertPostScriptDataIfNeeded();
1055     pdfDocumentDidLoad();
1056 }
1057
1058 void PDFPlugin::streamDidFail(uint64_t streamID, bool wasCancelled)
1059 {
1060     ASSERT_UNUSED(streamID, streamID == pdfDocumentRequestID);
1061
1062     m_data.clear();
1063 }
1064
1065 void PDFPlugin::manualStreamDidReceiveResponse(const URL& responseURL, uint32_t streamLength,  uint32_t lastModifiedTime, const String& mimeType, const String& headers, const String& suggestedFilename)
1066 {
1067     m_suggestedFilename = suggestedFilename;
1068
1069     if (equalIgnoringASCIICase(mimeType, postScriptMIMEType))
1070         m_isPostScript = true;
1071 }
1072
1073 void PDFPlugin::manualStreamDidReceiveData(const char* bytes, int length)
1074 {
1075     if (!m_data)
1076         m_data = adoptCF(CFDataCreateMutable(0, 0));
1077
1078     CFDataAppendBytes(m_data.get(), reinterpret_cast<const UInt8*>(bytes), length);
1079 }
1080
1081 void PDFPlugin::manualStreamDidFinishLoading()
1082 {
1083     convertPostScriptDataIfNeeded();
1084     pdfDocumentDidLoad();
1085 }
1086
1087 void PDFPlugin::manualStreamDidFail(bool)
1088 {
1089     m_data.clear();
1090 }
1091
1092 void PDFPlugin::runScriptsInPDFDocument()
1093 {
1094     Vector<RetainPtr<CFStringRef>> scripts;
1095     getAllScriptsInPDFDocument([m_pdfDocument documentRef], scripts);
1096
1097     if (scripts.isEmpty())
1098         return;
1099
1100     JSGlobalContextRef ctx = JSGlobalContextCreate(0);
1101     JSObjectRef jsPDFDoc = makeJSPDFDoc(ctx);
1102     for (auto& script : scripts)
1103         JSEvaluateScript(ctx, OpaqueJSString::tryCreate(script.get()).get(), jsPDFDoc, nullptr, 0, nullptr);
1104     JSGlobalContextRelease(ctx);
1105 }
1106
1107 void PDFPlugin::createPasswordEntryForm()
1108 {
1109     if (!supportsForms())
1110         return;
1111
1112     m_passwordField = PDFPluginPasswordField::create(m_pdfLayerController.get(), this);
1113     m_passwordField->attach(m_annotationContainer.get());
1114 }
1115
1116 void PDFPlugin::attemptToUnlockPDF(const String& password)
1117 {
1118     [m_pdfLayerController attemptToUnlockWithPassword:password];
1119
1120     if (![pdfDocument() isLocked]) {
1121         m_passwordField = nullptr;
1122
1123         calculateSizes();
1124         updateScrollbars();
1125     }
1126 }
1127
1128 void PDFPlugin::updatePageAndDeviceScaleFactors()
1129 {
1130     double newScaleFactor = controller()->contentsScaleFactor();
1131     if (!handlesPageScaleFactor())
1132         newScaleFactor *= webFrame()->page()->pageScaleFactor();
1133
1134     if (newScaleFactor != [m_pdfLayerController deviceScaleFactor])
1135         [m_pdfLayerController setDeviceScaleFactor:newScaleFactor];
1136 }
1137
1138 void PDFPlugin::contentsScaleFactorChanged(float)
1139 {
1140     updatePageAndDeviceScaleFactors();
1141 }
1142
1143 void PDFPlugin::calculateSizes()
1144 {
1145     if ([pdfDocument() isLocked]) {
1146         m_firstPageHeight = 0;
1147         setPDFDocumentSize(IntSize(0, 0));
1148         return;
1149     }
1150
1151     m_firstPageHeight = [m_pdfDocument pageCount] ? static_cast<unsigned>(CGCeiling([[m_pdfDocument pageAtIndex:0] boundsForBox:kPDFDisplayBoxCropBox].size.height)) : 0;
1152     setPDFDocumentSize(IntSize([m_pdfLayerController contentSizeRespectingZoom]));
1153 }
1154
1155 bool PDFPlugin::initialize(const Parameters& parameters)
1156 {
1157     m_sourceURL = parameters.url;
1158     if (!parameters.shouldUseManualLoader && !parameters.url.isEmpty())
1159         controller()->loadURL(pdfDocumentRequestID, "GET", parameters.url.string(), String(), HTTPHeaderMap(), Vector<uint8_t>(), false);
1160
1161     controller()->didInitializePlugin();
1162     return true;
1163 }
1164
1165 void PDFPlugin::willDetachRenderer()
1166 {
1167     if (webFrame()) {
1168         if (FrameView* frameView = webFrame()->coreFrame()->view())
1169             frameView->removeScrollableArea(this);
1170     }
1171 }
1172
1173 void PDFPlugin::destroy()
1174 {
1175     m_pdfLayerController.get().delegate = 0;
1176
1177     if (webFrame()) {
1178         if (FrameView* frameView = webFrame()->coreFrame()->view())
1179             frameView->removeScrollableArea(this);
1180     }
1181
1182     m_activeAnnotation = nullptr;
1183     m_annotationContainer = nullptr;
1184
1185     destroyScrollbar(HorizontalScrollbar);
1186     destroyScrollbar(VerticalScrollbar);
1187     
1188     [m_scrollCornerLayer removeFromSuperlayer];
1189     [m_contentLayer removeFromSuperlayer];
1190 }
1191
1192 void PDFPlugin::updateControlTints(GraphicsContext& graphicsContext)
1193 {
1194     ASSERT(graphicsContext.invalidatingControlTints());
1195
1196     if (m_horizontalScrollbar)
1197         m_horizontalScrollbar->invalidate();
1198     if (m_verticalScrollbar)
1199         m_verticalScrollbar->invalidate();
1200     invalidateScrollCorner(scrollCornerRect());
1201 }
1202
1203 void PDFPlugin::paintControlForLayerInContext(CALayer *layer, CGContextRef context)
1204 {
1205 #if PLATFORM(MAC)
1206     auto* page = webFrame()->coreFrame()->page();
1207     LocalDefaultSystemAppearance localAppearance(page->useDarkAppearance());
1208 #endif
1209
1210     GraphicsContext graphicsContext(context);
1211     GraphicsContextStateSaver stateSaver(graphicsContext);
1212
1213     graphicsContext.setIsCALayerContext(true);
1214
1215     if (layer == m_scrollCornerLayer) {
1216         IntRect scrollCornerRect = this->scrollCornerRect();
1217         graphicsContext.translate(-scrollCornerRect.x(), -scrollCornerRect.y());
1218         ScrollbarTheme::theme().paintScrollCorner(graphicsContext, scrollCornerRect);
1219         return;
1220     }
1221
1222     Scrollbar* scrollbar = nullptr;
1223
1224     if (layer == m_verticalScrollbarLayer)
1225         scrollbar = verticalScrollbar();
1226     else if (layer == m_horizontalScrollbarLayer)
1227         scrollbar = horizontalScrollbar();
1228
1229     if (!scrollbar)
1230         return;
1231
1232     graphicsContext.translate(-scrollbar->x(), -scrollbar->y());
1233     scrollbar->paint(graphicsContext, scrollbar->frameRect());
1234 }
1235
1236 RefPtr<ShareableBitmap> PDFPlugin::snapshot()
1237 {
1238     if (size().isEmpty())
1239         return nullptr;
1240
1241     float contentsScaleFactor = controller()->contentsScaleFactor();
1242     IntSize backingStoreSize = size();
1243     backingStoreSize.scale(contentsScaleFactor);
1244
1245     auto bitmap = ShareableBitmap::createShareable(backingStoreSize, { });
1246     auto context = bitmap->createGraphicsContext();
1247
1248     context->scale(FloatSize(contentsScaleFactor, -contentsScaleFactor));
1249     context->translate(-m_scrollOffset.width(), -m_pdfDocumentSize.height() + m_scrollOffset.height());
1250
1251     [m_pdfLayerController snapshotInContext:context->platformContext()];
1252
1253     return bitmap;
1254 }
1255
1256 PlatformLayer* PDFPlugin::pluginLayer()
1257 {
1258     return m_containerLayer.get();
1259 }
1260
1261 IntPoint PDFPlugin::convertFromPluginToPDFView(const IntPoint& point) const
1262 {
1263     return IntPoint(point.x(), size().height() - point.y());
1264 }
1265
1266 IntPoint PDFPlugin::convertFromRootViewToPlugin(const IntPoint& point) const
1267 {
1268     return m_rootViewToPluginTransform.mapPoint(point);
1269 }
1270
1271 IntPoint PDFPlugin::convertFromPDFViewToRootView(const IntPoint& point) const
1272 {
1273     IntPoint pointInPluginCoordinates(point.x(), size().height() - point.y());
1274     return m_rootViewToPluginTransform.inverse().valueOr(AffineTransform()).mapPoint(pointInPluginCoordinates);
1275 }
1276     
1277 IntPoint PDFPlugin::convertFromRootViewToPDFView(const IntPoint& point) const
1278 {
1279     IntPoint pointInPluginCoordinates = m_rootViewToPluginTransform.mapPoint(point);
1280     return IntPoint(pointInPluginCoordinates.x(), size().height() - pointInPluginCoordinates.y());
1281 }
1282
1283 FloatRect PDFPlugin::convertFromPDFViewToScreen(const FloatRect& rect) const
1284 {
1285     FrameView* frameView = webFrame()->coreFrame()->view();
1286
1287     if (!frameView)
1288         return FloatRect();
1289
1290     FloatRect updatedRect = rect;
1291     updatedRect.setLocation(convertFromPDFViewToRootView(IntPoint(updatedRect.location())));
1292     return webFrame()->coreFrame()->page()->chrome().rootViewToScreen(enclosingIntRect(updatedRect));
1293 }
1294
1295 IntRect PDFPlugin::boundsOnScreen() const
1296 {
1297     FrameView* frameView = webFrame()->coreFrame()->view();
1298
1299     if (!frameView)
1300         return IntRect();
1301
1302     FloatRect bounds = FloatRect(FloatPoint(), size());
1303     FloatRect rectInRootViewCoordinates = m_rootViewToPluginTransform.inverse().valueOr(AffineTransform()).mapRect(bounds);
1304     return frameView->contentsToScreen(enclosingIntRect(rectInRootViewCoordinates));
1305 }
1306
1307 void PDFPlugin::geometryDidChange(const IntSize& pluginSize, const IntRect&, const AffineTransform& pluginToRootViewTransform)
1308 {
1309     if (size() == pluginSize && pluginView()->pageScaleFactor() == [m_pdfLayerController contentScaleFactor])
1310         return;
1311
1312     m_size = pluginSize;
1313     m_rootViewToPluginTransform = pluginToRootViewTransform.inverse().valueOr(AffineTransform());
1314     [m_pdfLayerController setFrameSize:pluginSize];
1315
1316     [CATransaction begin];
1317     [CATransaction setDisableActions:YES];
1318     CATransform3D transform = CATransform3DMakeScale(1, -1, 1);
1319     transform = CATransform3DTranslate(transform, 0, -pluginSize.height(), 0);
1320     
1321     if (handlesPageScaleFactor()) {
1322         CGFloat magnification = pluginView()->pageScaleFactor() - [m_pdfLayerController contentScaleFactor];
1323
1324         // FIXME: Instead of m_lastMousePositionInPluginCoordinates, we should use the zoom origin from PluginView::setPageScaleFactor.
1325         if (magnification)
1326             [m_pdfLayerController magnifyWithMagnification:magnification atPoint:convertFromPluginToPDFView(m_lastMousePositionInPluginCoordinates) immediately:NO];
1327     } else {
1328         // If we don't handle page scale ourselves, we need to respect our parent page's
1329         // scale, which may have changed.
1330         updatePageAndDeviceScaleFactors();
1331     } 
1332
1333     calculateSizes();
1334     updateScrollbars();
1335
1336     if (m_activeAnnotation)
1337         m_activeAnnotation->updateGeometry();
1338
1339     [m_contentLayer setSublayerTransform:transform];
1340     [CATransaction commit];
1341 }
1342
1343 void PDFPlugin::frameDidFinishLoading(uint64_t)
1344 {
1345     ASSERT_NOT_REACHED();
1346 }
1347
1348 void PDFPlugin::frameDidFail(uint64_t, bool)
1349 {
1350     ASSERT_NOT_REACHED();
1351 }
1352
1353 void PDFPlugin::didEvaluateJavaScript(uint64_t, const WTF::String&)
1354 {
1355     ASSERT_NOT_REACHED();
1356 }
1357
1358     
1359 static NSUInteger modifierFlagsFromWebEvent(const WebEvent& event)
1360 {
1361     return (event.shiftKey() ? NSEventModifierFlagShift : 0)
1362         | (event.controlKey() ? NSEventModifierFlagControl : 0)
1363         | (event.altKey() ? NSEventModifierFlagOption : 0)
1364         | (event.metaKey() ? NSEventModifierFlagCommand : 0);
1365 }
1366     
1367 static bool getEventTypeFromWebEvent(const WebEvent& event, NSEventType& eventType)
1368 {
1369     switch (event.type()) {
1370     case WebEvent::KeyDown:
1371         eventType = NSEventTypeKeyDown;
1372         return true;
1373     case WebEvent::KeyUp:
1374         eventType = NSEventTypeKeyUp;
1375         return true;
1376     case WebEvent::MouseDown:
1377         switch (static_cast<const WebMouseEvent&>(event).button()) {
1378         case WebMouseEvent::LeftButton:
1379             eventType = NSEventTypeLeftMouseDown;
1380             return true;
1381         case WebMouseEvent::RightButton:
1382             eventType = NSEventTypeRightMouseDown;
1383             return true;
1384         default:
1385             return false;
1386         }
1387     case WebEvent::MouseUp:
1388         switch (static_cast<const WebMouseEvent&>(event).button()) {
1389         case WebMouseEvent::LeftButton:
1390             eventType = NSEventTypeLeftMouseUp;
1391             return true;
1392         case WebMouseEvent::RightButton:
1393             eventType = NSEventTypeRightMouseUp;
1394             return true;
1395         default:
1396             return false;
1397         }
1398     case WebEvent::MouseMove:
1399         switch (static_cast<const WebMouseEvent&>(event).button()) {
1400         case WebMouseEvent::LeftButton:
1401             eventType = NSEventTypeLeftMouseDragged;
1402             return true;
1403         case WebMouseEvent::RightButton:
1404             eventType = NSEventTypeRightMouseDragged;
1405             return true;
1406         case WebMouseEvent::NoButton:
1407             eventType = NSEventTypeMouseMoved;
1408             return true;
1409         default:
1410             return false;
1411         }
1412     default:
1413         return false;
1414     }
1415 }
1416     
1417 NSEvent *PDFPlugin::nsEventForWebMouseEvent(const WebMouseEvent& event)
1418 {
1419     m_lastMousePositionInPluginCoordinates = convertFromRootViewToPlugin(event.position());
1420
1421     IntPoint positionInPDFViewCoordinates(convertFromPluginToPDFView(m_lastMousePositionInPluginCoordinates));
1422
1423     NSEventType eventType;
1424
1425     if (!getEventTypeFromWebEvent(event, eventType))
1426         return 0;
1427
1428     NSUInteger modifierFlags = modifierFlagsFromWebEvent(event);
1429
1430     return [NSEvent mouseEventWithType:eventType location:positionInPDFViewCoordinates modifierFlags:modifierFlags timestamp:0 windowNumber:0 context:nil eventNumber:0 clickCount:event.clickCount() pressure:0];
1431 }
1432
1433 #if __MAC_OS_X_VERSION_MIN_REQUIRED < 101300
1434 void PDFPlugin::updateCursor(const WebMouseEvent& event, UpdateCursorMode mode)
1435 {
1436     HitTestResult hitTestResult = None;
1437
1438     PDFSelection *selectionUnderMouse = [m_pdfLayerController getSelectionForWordAtPoint:convertFromPluginToPDFView(event.position())];
1439     if (selectionUnderMouse && [[selectionUnderMouse string] length])
1440         hitTestResult = Text;
1441
1442     if (hitTestResult == m_lastHitTestResult && mode == UpdateIfNeeded)
1443         return;
1444
1445     webFrame()->page()->send(Messages::WebPageProxy::SetCursor(hitTestResult == Text ? WebCore::iBeamCursor() : WebCore::pointerCursor()));
1446     m_lastHitTestResult = hitTestResult;
1447 }
1448 #endif
1449
1450 bool PDFPlugin::handleMouseEvent(const WebMouseEvent& event)
1451 {
1452     PlatformMouseEvent platformEvent = platform(event);
1453     IntPoint mousePosition = convertFromRootViewToPlugin(event.position());
1454
1455     m_lastMouseEvent = event;
1456
1457     RefPtr<Scrollbar> targetScrollbar;
1458     RefPtr<Scrollbar> targetScrollbarForLastMousePosition;
1459
1460     if (m_verticalScrollbarLayer) {
1461         IntRect verticalScrollbarFrame(m_verticalScrollbarLayer.get().frame);
1462         if (verticalScrollbarFrame.contains(mousePosition))
1463             targetScrollbar = verticalScrollbar();
1464         if (verticalScrollbarFrame.contains(m_lastMousePositionInPluginCoordinates))
1465             targetScrollbarForLastMousePosition = verticalScrollbar();
1466     }
1467
1468     if (m_horizontalScrollbarLayer) {
1469         IntRect horizontalScrollbarFrame(m_horizontalScrollbarLayer.get().frame);
1470         if (horizontalScrollbarFrame.contains(mousePosition))
1471             targetScrollbar = horizontalScrollbar();
1472         if (horizontalScrollbarFrame.contains(m_lastMousePositionInPluginCoordinates))
1473             targetScrollbarForLastMousePosition = horizontalScrollbar();
1474     }
1475
1476     if (m_scrollCornerLayer && IntRect(m_scrollCornerLayer.get().frame).contains(mousePosition))
1477         return false;
1478
1479     if ([pdfDocument() isLocked])
1480         return false;
1481
1482     // Right-clicks and Control-clicks always call handleContextMenuEvent as well.
1483     if (event.button() == WebMouseEvent::RightButton || (event.button() == WebMouseEvent::LeftButton && event.controlKey()))
1484         return true;
1485
1486     NSEvent *nsEvent = nsEventForWebMouseEvent(event);
1487
1488     switch (event.type()) {
1489     case WebEvent::MouseMove:
1490         mouseMovedInContentArea();
1491 #if __MAC_OS_X_VERSION_MIN_REQUIRED < 101300
1492         updateCursor(event);
1493 #endif
1494
1495         if (targetScrollbar) {
1496             if (!targetScrollbarForLastMousePosition) {
1497                 targetScrollbar->mouseEntered();
1498                 return true;
1499             }
1500             return targetScrollbar->mouseMoved(platformEvent);
1501         }
1502
1503         if (!targetScrollbar && targetScrollbarForLastMousePosition)
1504             targetScrollbarForLastMousePosition->mouseExited();
1505
1506         switch (event.button()) {
1507         case WebMouseEvent::LeftButton:
1508             [m_pdfLayerController mouseDragged:nsEvent];
1509             return true;
1510         case WebMouseEvent::RightButton:
1511         case WebMouseEvent::MiddleButton:
1512             return false;
1513         case WebMouseEvent::NoButton:
1514             [m_pdfLayerController mouseMoved:nsEvent];
1515             return true;
1516         }
1517         break;
1518     case WebEvent::MouseDown:
1519         switch (event.button()) {
1520         case WebMouseEvent::LeftButton:
1521             if (targetScrollbar)
1522                 return targetScrollbar->mouseDown(platformEvent);
1523
1524             [m_pdfLayerController mouseDown:nsEvent];
1525             return true;
1526         case WebMouseEvent::RightButton:
1527             [m_pdfLayerController rightMouseDown:nsEvent];
1528             return true;
1529         case WebMouseEvent::MiddleButton:
1530         case WebMouseEvent::NoButton:
1531             return false;
1532         }
1533         break;
1534     case WebEvent::MouseUp:
1535         switch (event.button()) {
1536         case WebMouseEvent::LeftButton:
1537             if (targetScrollbar)
1538                 return targetScrollbar->mouseUp(platformEvent);
1539
1540             [m_pdfLayerController mouseUp:nsEvent];
1541             return true;
1542         case WebMouseEvent::RightButton:
1543         case WebMouseEvent::MiddleButton:
1544         case WebMouseEvent::NoButton:
1545             return false;
1546         }
1547         break;
1548     default:
1549         break;
1550     }
1551
1552     return false;
1553 }
1554
1555 bool PDFPlugin::handleMouseEnterEvent(const WebMouseEvent& event)
1556 {
1557     mouseEnteredContentArea();
1558 #if __MAC_OS_X_VERSION_MIN_REQUIRED < 101300
1559     updateCursor(event, ForceUpdate);
1560 #endif
1561     return false;
1562 }
1563
1564 bool PDFPlugin::handleMouseLeaveEvent(const WebMouseEvent&)
1565 {
1566     mouseExitedContentArea();
1567     return false;
1568 }
1569     
1570 bool PDFPlugin::showContextMenuAtPoint(const IntPoint& point)
1571 {
1572     FrameView* frameView = webFrame()->coreFrame()->view();
1573     IntPoint contentsPoint = frameView->contentsToRootView(point);
1574     WebMouseEvent event(WebEvent::MouseDown, WebMouseEvent::RightButton, 0, contentsPoint, contentsPoint, 0, 0, 0, 1, OptionSet<WebEvent::Modifier> { }, WallTime::now(), WebCore::ForceAtClick);
1575     return handleContextMenuEvent(event);
1576 }
1577
1578 bool PDFPlugin::handleContextMenuEvent(const WebMouseEvent& event)
1579 {
1580     if (!webFrame()->page())
1581         return false;
1582
1583     WebPage* webPage = webFrame()->page();
1584     FrameView* frameView = webFrame()->coreFrame()->view();
1585     IntPoint point = frameView->contentsToScreen(IntRect(frameView->windowToContents(event.position()), IntSize())).location();
1586
1587 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101300
1588     NSUserInterfaceLayoutDirection uiLayoutDirection = webPage->userInterfaceLayoutDirection() == UserInterfaceLayoutDirection::LTR ? NSUserInterfaceLayoutDirectionLeftToRight : NSUserInterfaceLayoutDirectionRightToLeft;
1589     NSMenu *nsMenu = [m_pdfLayerController menuForEvent:nsEventForWebMouseEvent(event) withUserInterfaceLayoutDirection:uiLayoutDirection];
1590 #else
1591     NSMenu *nsMenu = [m_pdfLayerController menuForEvent:nsEventForWebMouseEvent(event)];
1592 #endif
1593
1594     if (!nsMenu)
1595         return false;
1596     
1597     Vector<PDFContextMenuItem> items;
1598     auto itemCount = [nsMenu numberOfItems];
1599     for (int i = 0; i < itemCount; i++) {
1600         auto item = [nsMenu itemAtIndex:i];
1601         if ([item submenu])
1602             continue;
1603         PDFContextMenuItem menuItem { String([item title]), !![item isEnabled], !![item isSeparatorItem], static_cast<int>([item state]), [item action], i };
1604         items.append(WTFMove(menuItem));
1605     }
1606     PDFContextMenu contextMenu { point, WTFMove(items) };
1607
1608     Optional<int> selectedIndex = -1;
1609     webPage->sendSync(Messages::WebPageProxy::ShowPDFContextMenu(contextMenu), Messages::WebPageProxy::ShowPDFContextMenu::Reply(selectedIndex));
1610
1611     if (selectedIndex && *selectedIndex >= 0 && *selectedIndex < itemCount)
1612         [nsMenu performActionForItemAtIndex:*selectedIndex];
1613
1614     return true;
1615 }
1616
1617 bool PDFPlugin::handleKeyboardEvent(const WebKeyboardEvent& event)
1618 {
1619     NSEventType eventType;
1620
1621     if (!getEventTypeFromWebEvent(event, eventType))
1622         return false;
1623
1624     NSUInteger modifierFlags = modifierFlagsFromWebEvent(event);
1625     
1626     NSEvent *fakeEvent = [NSEvent keyEventWithType:eventType location:NSZeroPoint modifierFlags:modifierFlags timestamp:0 windowNumber:0 context:0 characters:event.text() charactersIgnoringModifiers:event.unmodifiedText() isARepeat:event.isAutoRepeat() keyCode:event.nativeVirtualKeyCode()];
1627     
1628     switch (event.type()) {
1629     case WebEvent::KeyDown:
1630         return [m_pdfLayerController keyDown:fakeEvent];
1631     default:
1632         return false;
1633     }
1634     
1635     return false;
1636 }
1637     
1638 bool PDFPlugin::handleEditingCommand(const String& commandName, const String& argument)
1639 {
1640     if (commandName == "copy")
1641         [m_pdfLayerController copySelection];
1642     else if (commandName == "selectAll")
1643         [m_pdfLayerController selectAll];
1644     else if (commandName == "takeFindStringFromSelection") {
1645         NSString *string = [m_pdfLayerController currentSelection].string;
1646         ALLOW_DEPRECATED_DECLARATIONS_BEGIN
1647         if (string.length)
1648             writeItemsToPasteboard(NSFindPboard, @[ [string dataUsingEncoding:NSUTF8StringEncoding] ], @[ NSPasteboardTypeString ]);
1649         ALLOW_DEPRECATED_DECLARATIONS_END
1650     }
1651
1652     return true;
1653 }
1654
1655 bool PDFPlugin::isEditingCommandEnabled(const String& commandName)
1656 {
1657     if (commandName == "copy" || commandName == "takeFindStringFromSelection")
1658         return [m_pdfLayerController currentSelection];
1659
1660     if (commandName == "selectAll")
1661         return true;
1662
1663     return false;
1664 }
1665
1666 void PDFPlugin::setScrollOffset(const ScrollOffset& offset)
1667 {
1668     m_scrollOffset = IntSize(offset.x(), offset.y());
1669
1670     [CATransaction begin];
1671     [m_pdfLayerController setScrollPosition:offset];
1672
1673     if (m_activeAnnotation)
1674         m_activeAnnotation->updateGeometry();
1675
1676     [CATransaction commit];
1677 }
1678
1679 void PDFPlugin::invalidateScrollbarRect(Scrollbar& scrollbar, const IntRect& rect)
1680 {
1681     if (&scrollbar == horizontalScrollbar())
1682         [m_horizontalScrollbarLayer setNeedsDisplay];
1683     else if (&scrollbar == verticalScrollbar())
1684         [m_verticalScrollbarLayer setNeedsDisplay];
1685 }
1686
1687 void PDFPlugin::invalidateScrollCornerRect(const IntRect& rect)
1688 {
1689     [m_scrollCornerLayer setNeedsDisplay];
1690 }
1691
1692 bool PDFPlugin::isFullFramePlugin() const
1693 {
1694     // <object> or <embed> plugins will appear to be in their parent frame, so we have to
1695     // check whether our frame's widget is exactly our PluginView.
1696     Document* document = webFrame()->coreFrame()->document();
1697     return document->isPluginDocument() && static_cast<PluginDocument*>(document)->pluginWidget() == pluginView();
1698 }
1699
1700 bool PDFPlugin::handlesPageScaleFactor() const
1701 {
1702     return webFrame()->isMainFrame() && isFullFramePlugin();
1703 }
1704
1705 void PDFPlugin::clickedLink(NSURL *url)
1706 {
1707     URL coreURL = url;
1708     if (WTF::protocolIsJavaScript(coreURL))
1709         return;
1710
1711     Frame* frame = webFrame()->coreFrame();
1712
1713     RefPtr<Event> coreEvent;
1714     if (m_lastMouseEvent.type() != WebEvent::NoType)
1715         coreEvent = MouseEvent::create(eventNames().clickEvent, &frame->windowProxy(), platform(m_lastMouseEvent), 0, 0);
1716
1717     frame->loader().urlSelected(coreURL, emptyString(), coreEvent.get(), LockHistory::No, LockBackForwardList::No, NeverSendReferrer, ShouldOpenExternalURLsPolicy::ShouldAllow);
1718 }
1719
1720 void PDFPlugin::setActiveAnnotation(PDFAnnotation *annotation)
1721 {
1722     if (!supportsForms())
1723         return;
1724
1725     if (m_activeAnnotation)
1726         m_activeAnnotation->commit();
1727
1728     if (annotation) {
1729         ALLOW_DEPRECATED_DECLARATIONS_BEGIN
1730         if ([annotation isKindOfClass:pdfAnnotationTextWidgetClass()] && static_cast<PDFAnnotationTextWidget *>(annotation).isReadOnly) {
1731             m_activeAnnotation = nullptr;
1732             return;
1733         }
1734         ALLOW_DEPRECATED_DECLARATIONS_END
1735
1736         m_activeAnnotation = PDFPluginAnnotation::create(annotation, m_pdfLayerController.get(), this);
1737         m_activeAnnotation->attach(m_annotationContainer.get());
1738     } else
1739         m_activeAnnotation = nullptr;
1740 }
1741
1742 bool PDFPlugin::supportsForms()
1743 {
1744     // FIXME: We support forms for full-main-frame and <iframe> PDFs, but not <embed> or <object>, because those cases do not have their own Document into which to inject form elements.
1745     return isFullFramePlugin();
1746 }
1747
1748 void PDFPlugin::notifyContentScaleFactorChanged(CGFloat scaleFactor)
1749 {
1750     if (handlesPageScaleFactor())
1751         pluginView()->setPageScaleFactor(scaleFactor, IntPoint());
1752
1753     calculateSizes();
1754     updateScrollbars();
1755 }
1756
1757 void PDFPlugin::notifyDisplayModeChanged(int)
1758 {
1759     calculateSizes();
1760     updateScrollbars();
1761 }
1762
1763 RefPtr<SharedBuffer> PDFPlugin::liveResourceData() const
1764 {
1765     NSData *pdfData = liveData();
1766
1767     if (!pdfData)
1768         return nullptr;
1769
1770     return SharedBuffer::create(pdfData);
1771 }
1772
1773 bool PDFPlugin::pluginHandlesContentOffsetForAccessibilityHitTest() const
1774 {
1775     // The PDF plugin handles the scroll view offset natively as part of the layer conversions.
1776 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101300
1777     return true;
1778 #else
1779     return false;
1780 #endif
1781 }
1782
1783     
1784 void PDFPlugin::saveToPDF()
1785 {
1786     // FIXME: We should probably notify the user that they can't save before the document is finished loading.
1787     // PDFViewController does an NSBeep(), but that seems insufficient.
1788     if (!pdfDocument())
1789         return;
1790
1791     NSData *data = liveData();
1792     webFrame()->page()->savePDFToFileInDownloadsFolder(m_suggestedFilename, webFrame()->url(), static_cast<const unsigned char *>([data bytes]), [data length]);
1793 }
1794
1795 void PDFPlugin::openWithNativeApplication()
1796 {
1797     if (!m_temporaryPDFUUID) {
1798         // FIXME: We should probably notify the user that they can't save before the document is finished loading.
1799         // PDFViewController does an NSBeep(), but that seems insufficient.
1800         if (!pdfDocument())
1801             return;
1802
1803         NSData *data = liveData();
1804
1805         m_temporaryPDFUUID = createCanonicalUUIDString();
1806         ASSERT(m_temporaryPDFUUID);
1807
1808         webFrame()->page()->savePDFToTemporaryFolderAndOpenWithNativeApplication(m_suggestedFilename, webFrame()->url(), static_cast<const unsigned char *>([data bytes]), [data length], m_temporaryPDFUUID);
1809         return;
1810     }
1811
1812     webFrame()->page()->send(Messages::WebPageProxy::OpenPDFFromTemporaryFolderWithNativeApplication(m_temporaryPDFUUID));
1813 }
1814
1815 void PDFPlugin::writeItemsToPasteboard(NSString *pasteboardName, NSArray *items, NSArray *types)
1816 {
1817     Vector<String> pasteboardTypes;
1818
1819     for (NSString *type in types)
1820         pasteboardTypes.append(type);
1821
1822     uint64_t newChangeCount;
1823     auto& webProcess = WebProcess::singleton();
1824     webProcess.parentProcessConnection()->sendSync(Messages::WebPasteboardProxy::SetPasteboardTypes(pasteboardName, pasteboardTypes),
1825         Messages::WebPasteboardProxy::SetPasteboardTypes::Reply(newChangeCount), 0);
1826
1827     for (NSUInteger i = 0, count = items.count; i < count; ++i) {
1828         NSString *type = [types objectAtIndex:i];
1829         NSData *data = [items objectAtIndex:i];
1830
1831         // We don't expect the data for any items to be empty, but aren't completely sure.
1832         // Avoid crashing in the SharedMemory constructor in release builds if we're wrong.
1833         ASSERT(data.length);
1834         if (!data.length)
1835             continue;
1836
1837         if ([type isEqualToString:legacyStringPasteboardType()] || [type isEqualToString:NSPasteboardTypeString]) {
1838             RetainPtr<NSString> plainTextString = adoptNS([[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
1839             webProcess.parentProcessConnection()->sendSync(Messages::WebPasteboardProxy::SetPasteboardStringForType(pasteboardName, type, plainTextString.get()), Messages::WebPasteboardProxy::SetPasteboardStringForType::Reply(newChangeCount), 0);
1840         } else {
1841             auto buffer = SharedBuffer::create(data);
1842             SharedMemory::Handle handle;
1843             RefPtr<SharedMemory> sharedMemory = SharedMemory::allocate(buffer->size());
1844             memcpy(sharedMemory->data(), buffer->data(), buffer->size());
1845             sharedMemory->createHandle(handle, SharedMemory::Protection::ReadOnly);
1846             webProcess.parentProcessConnection()->sendSync(Messages::WebPasteboardProxy::SetPasteboardBufferForType(pasteboardName, type, handle, buffer->size()), Messages::WebPasteboardProxy::SetPasteboardBufferForType::Reply(newChangeCount), 0);
1847         }
1848     }
1849 }
1850
1851 void PDFPlugin::showDefinitionForAttributedString(NSAttributedString *string, CGPoint point)
1852 {
1853     DictionaryPopupInfo dictionaryPopupInfo;
1854     dictionaryPopupInfo.origin = convertFromPDFViewToRootView(IntPoint(point));
1855     dictionaryPopupInfo.attributedString = string;
1856     
1857     
1858     NSRect rangeRect;
1859     rangeRect.origin = NSMakePoint(point.x, point.y);
1860     CGFloat scaleFactor = PDFPlugin::scaleFactor();
1861
1862     rangeRect.size.height = string.size.height * scaleFactor;
1863     rangeRect.size.width = string.size.width * scaleFactor;
1864
1865     rangeRect.origin.y -= rangeRect.size.height;
1866
1867     TextIndicatorData dataForSelection;
1868     dataForSelection.selectionRectInRootViewCoordinates = rangeRect;
1869     dataForSelection.textBoundingRectInRootViewCoordinates = rangeRect;
1870     dataForSelection.contentImageScaleFactor = scaleFactor;
1871     dataForSelection.presentationTransition = TextIndicatorPresentationTransition::FadeIn;
1872     dictionaryPopupInfo.textIndicator = dataForSelection;
1873     
1874     webFrame()->page()->send(Messages::WebPageProxy::DidPerformDictionaryLookup(dictionaryPopupInfo));
1875 }
1876
1877 unsigned PDFPlugin::countFindMatches(const String& target, WebCore::FindOptions options, unsigned /*maxMatchCount*/)
1878 {
1879     // FIXME: Why is it OK to ignore the passed-in maximum match count?
1880
1881     if (!target.length())
1882         return 0;
1883
1884     NSStringCompareOptions nsOptions = options.contains(WebCore::CaseInsensitive) ? NSCaseInsensitiveSearch : 0;
1885     return [[pdfDocument() findString:target withOptions:nsOptions] count];
1886 }
1887
1888 PDFSelection *PDFPlugin::nextMatchForString(const String& target, BOOL searchForward, BOOL caseSensitive, BOOL wrapSearch, PDFSelection *initialSelection, BOOL startInSelection)
1889 {
1890     if (!target.length())
1891         return nil;
1892
1893     NSStringCompareOptions options = 0;
1894     if (!searchForward)
1895         options |= NSBackwardsSearch;
1896     if (!caseSensitive)
1897         options |= NSCaseInsensitiveSearch;
1898
1899     PDFDocument *document = pdfDocument().get();
1900
1901     RetainPtr<PDFSelection> selectionForInitialSearch = adoptNS([initialSelection copy]);
1902     if (startInSelection) {
1903         // Initially we want to include the selected text in the search. So we must modify the starting search
1904         // selection to fit PDFDocument's search requirements: selection must have a length >= 1, begin before
1905         // the current selection (if searching forwards) or after (if searching backwards).
1906         int initialSelectionLength = [[initialSelection string] length];
1907         if (searchForward) {
1908             [selectionForInitialSearch extendSelectionAtStart:1];
1909             [selectionForInitialSearch extendSelectionAtEnd:-initialSelectionLength];
1910         } else {
1911             [selectionForInitialSearch extendSelectionAtEnd:1];
1912             [selectionForInitialSearch extendSelectionAtStart:-initialSelectionLength];
1913         }
1914     }
1915
1916     PDFSelection *foundSelection = [document findString:target fromSelection:selectionForInitialSearch.get() withOptions:options];
1917
1918     // If we first searched in the selection, and we found the selection, search again from just past the selection.
1919     if (startInSelection && [foundSelection isEqual:initialSelection])
1920         foundSelection = [document findString:target fromSelection:initialSelection withOptions:options];
1921
1922     if (!foundSelection && wrapSearch) {
1923         auto emptySelection = adoptNS([[pdfSelectionClass() alloc] initWithDocument:document]);
1924         foundSelection = [document findString:target fromSelection:emptySelection.get() withOptions:options];
1925     }
1926
1927     return foundSelection;
1928 }
1929
1930 bool PDFPlugin::findString(const String& target, WebCore::FindOptions options, unsigned maxMatchCount)
1931 {
1932     bool searchForward = !options.contains(WebCore::Backwards);
1933     bool caseSensitive = !options.contains(WebCore::CaseInsensitive);
1934     bool wrapSearch = options.contains(WebCore::WrapAround);
1935
1936     // If the max was zero, any result means we exceeded the max, so we can skip computing the actual count.
1937     // FIXME: How can always returning true without searching if passed a max of 0 be right?
1938     // Even if it is right, why not put that special case inside countFindMatches instead of here?
1939     bool foundMatch = !maxMatchCount || countFindMatches(target, options, maxMatchCount);
1940
1941     if (target.isEmpty()) {
1942         auto searchSelection = [m_pdfLayerController searchSelection];
1943         [m_pdfLayerController findString:target caseSensitive:caseSensitive highlightMatches:YES];
1944         [m_pdfLayerController setSearchSelection:searchSelection];
1945         m_lastFoundString = emptyString();
1946         return false;
1947     }
1948
1949     if (m_lastFoundString == target) {
1950         auto selection = nextMatchForString(target, searchForward, caseSensitive, wrapSearch, [m_pdfLayerController searchSelection], NO);
1951         if (!selection)
1952             return false;
1953         [m_pdfLayerController setSearchSelection:selection];
1954         [m_pdfLayerController gotoSelection:selection];
1955     } else {
1956         [m_pdfLayerController findString:target caseSensitive:caseSensitive highlightMatches:YES];
1957         m_lastFoundString = target;
1958     }
1959
1960     return foundMatch;
1961 }
1962
1963 bool PDFPlugin::performDictionaryLookupAtLocation(const WebCore::FloatPoint& point)
1964 {
1965     IntPoint localPoint = convertFromRootViewToPlugin(roundedIntPoint(point));
1966     PDFSelection* lookupSelection = [m_pdfLayerController getSelectionForWordAtPoint:convertFromPluginToPDFView(localPoint)];
1967     if ([[lookupSelection string] length])
1968         [m_pdfLayerController searchInDictionaryWithSelection:lookupSelection];
1969     return true;
1970 }
1971
1972 void PDFPlugin::focusNextAnnotation()
1973 {
1974     [m_pdfLayerController activateNextAnnotation:false];
1975 }
1976
1977 void PDFPlugin::focusPreviousAnnotation()
1978 {
1979     [m_pdfLayerController activateNextAnnotation:true];
1980 }
1981
1982 void PDFPlugin::notifySelectionChanged(PDFSelection *)
1983 {
1984     webFrame()->page()->didChangeSelection();
1985 }
1986
1987 static const WebCore::Cursor& coreCursor(PDFLayerControllerCursorType type)
1988 {
1989     switch (type) {
1990     case kPDFLayerControllerCursorTypeHand:
1991         return WebCore::handCursor();
1992     case kPDFLayerControllerCursorTypeIBeam:
1993         return WebCore::iBeamCursor();
1994     case kPDFLayerControllerCursorTypePointer:
1995     default:
1996         return WebCore::pointerCursor();
1997     }
1998 }
1999
2000 void PDFPlugin::notifyCursorChanged(uint64_t type)
2001 {
2002     webFrame()->page()->send(Messages::WebPageProxy::SetCursor(coreCursor(static_cast<PDFLayerControllerCursorType>(type))));
2003 }
2004
2005 String PDFPlugin::getSelectionString() const
2006 {
2007     return [[m_pdfLayerController currentSelection] string];
2008 }
2009
2010 String PDFPlugin::getSelectionForWordAtPoint(const WebCore::FloatPoint& point) const
2011 {
2012     IntPoint pointInView = convertFromPluginToPDFView(convertFromRootViewToPlugin(roundedIntPoint(point)));
2013     PDFSelection *selectionForWord = [m_pdfLayerController getSelectionForWordAtPoint:pointInView];
2014     [m_pdfLayerController setCurrentSelection:selectionForWord];
2015     return [selectionForWord string];
2016 }
2017
2018 bool PDFPlugin::existingSelectionContainsPoint(const WebCore::FloatPoint& locationInViewCoordinates) const
2019 {
2020     PDFSelection *currentSelection = [m_pdfLayerController currentSelection];
2021     if (!currentSelection)
2022         return false;
2023     
2024     IntPoint pointInPDFView = convertFromPluginToPDFView(convertFromRootViewToPlugin(roundedIntPoint(locationInViewCoordinates)));
2025     PDFSelection *selectionForWord = [m_pdfLayerController getSelectionForWordAtPoint:pointInPDFView];
2026
2027     NSUInteger currentPageIndex = [m_pdfLayerController currentPageIndex];
2028     
2029     NSArray *selectionRects = [m_pdfLayerController rectsForSelectionInLayoutSpace:currentSelection];
2030     if (!selectionRects || !selectionRects.count)
2031         return false;
2032     
2033     if (currentPageIndex >= selectionRects.count)
2034         currentPageIndex = selectionRects.count - 1;
2035
2036     NSArray *wordSelectionRects = [m_pdfLayerController rectsForSelectionInLayoutSpace:selectionForWord];
2037     if (!wordSelectionRects || !wordSelectionRects.count)
2038         return false;
2039
2040     NSValue *selectionBounds = [selectionRects objectAtIndex:currentPageIndex];
2041     NSValue *wordSelectionBounds = [wordSelectionRects objectAtIndex:0];
2042
2043     NSRect selectionBoundsRect = selectionBounds.rectValue;
2044     NSRect wordSelectionBoundsRect = wordSelectionBounds.rectValue;
2045     return NSIntersectsRect(wordSelectionBoundsRect, selectionBoundsRect);
2046 }
2047
2048 static NSPoint pointInLayoutSpaceForPointInWindowSpace(PDFLayerController* pdfLayerController, NSPoint pointInView)
2049 {
2050     CGPoint point = NSPointToCGPoint(pointInView);
2051     CGPoint scrollOffset = [pdfLayerController scrollPosition];
2052     CGFloat scaleFactor = [pdfLayerController contentScaleFactor];
2053
2054     scrollOffset.y = [pdfLayerController contentSizeRespectingZoom].height - NSRectToCGRect([pdfLayerController frame]).size.height - scrollOffset.y;
2055
2056     CGPoint newPoint = CGPointMake(scrollOffset.x + point.x, scrollOffset.y + point.y);
2057     newPoint.x /= scaleFactor;
2058     newPoint.y /= scaleFactor;
2059     return NSPointFromCGPoint(newPoint);
2060 }
2061
2062 std::tuple<String, PDFSelection *, NSDictionary *> PDFPlugin::lookupTextAtLocation(const WebCore::FloatPoint& locationInViewCoordinates, WebHitTestResultData& data) const
2063 {
2064     auto selection = [m_pdfLayerController currentSelection];
2065     if (existingSelectionContainsPoint(locationInViewCoordinates))
2066         return { selection.string, selection, nil };
2067
2068     IntPoint pointInPDFView = convertFromPluginToPDFView(convertFromRootViewToPlugin(roundedIntPoint(locationInViewCoordinates)));
2069     selection = [m_pdfLayerController getSelectionForWordAtPoint:pointInPDFView];
2070     if (!selection)
2071         return { emptyString(), nil, nil };
2072
2073     NSPoint pointInLayoutSpace = pointInLayoutSpaceForPointInWindowSpace(m_pdfLayerController.get(), pointInPDFView);
2074     PDFPage *currentPage = [[m_pdfLayerController layout] pageNearestPoint:pointInLayoutSpace currentPage:[m_pdfLayerController currentPage]];
2075     NSPoint pointInPageSpace = [[m_pdfLayerController layout] convertPoint:pointInLayoutSpace toPage:currentPage forScaleFactor:1.0];
2076
2077     for (PDFAnnotation *annotation in currentPage.annotations) {
2078         if (![annotation isKindOfClass:pdfAnnotationLinkClass()])
2079             continue;
2080
2081         NSRect bounds = annotation.bounds;
2082         if (!NSPointInRect(pointInPageSpace, bounds))
2083             continue;
2084
2085         ALLOW_DEPRECATED_DECLARATIONS_BEGIN
2086         PDFAnnotationLink *linkAnnotation = (PDFAnnotationLink *)annotation;
2087         ALLOW_DEPRECATED_DECLARATIONS_END
2088         NSURL *url = linkAnnotation.URL;
2089         if (!url)
2090             continue;
2091
2092         data.absoluteLinkURL = url.absoluteString;
2093         data.linkLabel = selection.string;
2094         return { selection.string, selection, nil };
2095     }
2096
2097     NSString *lookupText;
2098     NSDictionary *options;
2099     std::tie(lookupText, options) = DictionaryLookup::stringForPDFSelection(selection);
2100     if (!lookupText.length)
2101         return { emptyString(), selection, nil };
2102
2103     [m_pdfLayerController setCurrentSelection:selection];
2104     return { lookupText, selection, options };
2105 }
2106
2107 static NSRect rectInViewSpaceForRectInLayoutSpace(PDFLayerController* pdfLayerController, NSRect layoutSpaceRect)
2108 {
2109     CGRect newRect = NSRectToCGRect(layoutSpaceRect);
2110     CGFloat scaleFactor = pdfLayerController.contentScaleFactor;
2111     CGPoint scrollOffset = pdfLayerController.scrollPosition;
2112
2113     scrollOffset.y = pdfLayerController.contentSizeRespectingZoom.height - NSRectToCGRect(pdfLayerController.frame).size.height - scrollOffset.y;
2114
2115     newRect.origin.x *= scaleFactor;
2116     newRect.origin.y *= scaleFactor;
2117     newRect.size.width *= scaleFactor;
2118     newRect.size.height *= scaleFactor;
2119
2120     newRect.origin.x -= scrollOffset.x;
2121     newRect.origin.y -= scrollOffset.y;
2122
2123     return NSRectFromCGRect(newRect);
2124 }
2125     
2126 WebCore::AXObjectCache* PDFPlugin::axObjectCache() const
2127 {
2128     return webFrame()->coreFrame()->document()->axObjectCache();
2129 }
2130
2131 WebCore::FloatRect PDFPlugin::rectForSelectionInRootView(PDFSelection *selection) const
2132 {
2133     PDFPage *currentPage = nil;
2134     NSArray *pages = selection.pages;
2135     if (pages.count)
2136         currentPage = (PDFPage *)[pages objectAtIndex:0];
2137
2138     if (!currentPage)
2139         currentPage = [m_pdfLayerController currentPage];
2140
2141     NSRect rectInPageSpace = [selection boundsForPage:currentPage];
2142     NSRect rectInLayoutSpace = [[m_pdfLayerController layout] convertRect:rectInPageSpace fromPage:currentPage forScaleFactor:1.0];
2143     NSRect rectInView = rectInViewSpaceForRectInLayoutSpace(m_pdfLayerController.get(), rectInLayoutSpace);
2144
2145     rectInView.origin = convertFromPDFViewToRootView(IntPoint(rectInView.origin));
2146
2147     return rectInView;
2148 }
2149
2150 CGFloat PDFPlugin::scaleFactor() const
2151 {
2152     return [m_pdfLayerController contentScaleFactor];
2153 }
2154
2155 void PDFPlugin::performWebSearch(NSString *string)
2156 {
2157     webFrame()->page()->send(Messages::WebPageProxy::SearchTheWeb(string));
2158 }
2159
2160 void PDFPlugin::performSpotlightSearch(NSString *string)
2161 {
2162     webFrame()->page()->send(Messages::WebPageProxy::SearchWithSpotlight(string));
2163 }
2164
2165 bool PDFPlugin::handleWheelEvent(const WebWheelEvent& event)
2166 {
2167     PDFDisplayMode displayMode = [m_pdfLayerController displayMode];
2168
2169     if (displayMode == kPDFDisplaySinglePageContinuous || displayMode == kPDFDisplayTwoUpContinuous)
2170         return ScrollableArea::handleWheelEvent(platform(event));
2171
2172     NSUInteger currentPageIndex = [m_pdfLayerController currentPageIndex];
2173     bool inFirstPage = !currentPageIndex;
2174     bool inLastPage = [m_pdfLayerController lastPageIndex] == currentPageIndex;
2175
2176     bool atScrollTop = !scrollPosition().y();
2177     bool atScrollBottom = scrollPosition().y() == maximumScrollPosition().y();
2178
2179     bool inMomentumScroll = event.momentumPhase() != WebWheelEvent::PhaseNone;
2180
2181     int scrollMagnitudeThresholdForPageFlip = defaultScrollMagnitudeThresholdForPageFlip;
2182
2183     // Imprecise input devices should have a lower threshold so that "clicky" scroll wheels can flip pages.
2184     if (!event.hasPreciseScrollingDeltas())
2185         scrollMagnitudeThresholdForPageFlip = 0;
2186
2187     if (atScrollBottom && !inLastPage && event.delta().height() < 0) {
2188         if (event.delta().height() <= -scrollMagnitudeThresholdForPageFlip && !inMomentumScroll)
2189             [m_pdfLayerController gotoNextPage];
2190         return true;
2191     }
2192
2193     if (atScrollTop && !inFirstPage && event.delta().height() > 0) {
2194         if (event.delta().height() >= scrollMagnitudeThresholdForPageFlip && !inMomentumScroll) {
2195             [CATransaction begin];
2196             [m_pdfLayerController gotoPreviousPage];
2197             scrollToOffsetWithoutAnimation(maximumScrollPosition());
2198             [CATransaction commit];
2199         }
2200         return true;
2201     }
2202
2203     return ScrollableArea::handleWheelEvent(platform(event));
2204 }
2205
2206 NSData *PDFPlugin::liveData() const
2207 {
2208     if (m_activeAnnotation)
2209         m_activeAnnotation->commit();
2210
2211     // Save data straight from the resource instead of PDFKit if the document is
2212     // untouched by the user, so that PDFs which PDFKit can't display will still be downloadable.
2213     if (m_pdfDocumentWasMutated)
2214         return [m_pdfDocument dataRepresentation];
2215
2216     return rawData();
2217 }
2218
2219 id PDFPlugin::accessibilityAssociatedPluginParentForElement(WebCore::Element* element) const
2220 {
2221 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 101300
2222     if (!m_activeAnnotation)
2223         return nil;
2224
2225     if (m_activeAnnotation->element() != element)
2226         return nil;
2227
2228     return [m_activeAnnotation->annotation() accessibilityNode];
2229 #else
2230     return nil;
2231 #endif
2232 }
2233
2234 NSObject *PDFPlugin::accessibilityObject() const
2235 {
2236     return m_accessibilityObject.get();
2237 }
2238
2239 } // namespace WebKit
2240
2241 #endif // ENABLE(PDFKIT_PLUGIN)