webengine/osswebengine/WebKit/WebView/WebPDFView.mm
changeset 0 dd21522fd290
equal deleted inserted replaced
-1:000000000000 0:dd21522fd290
       
     1 /*
       
     2  * Copyright (C) 2005, 2006, 2007 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  *
       
     8  * 1.  Redistributions of source code must retain the above copyright
       
     9  *     notice, this list of conditions and the following disclaimer. 
       
    10  * 2.  Redistributions in binary form must reproduce the above copyright
       
    11  *     notice, this list of conditions and the following disclaimer in the
       
    12  *     documentation and/or other materials provided with the distribution. 
       
    13  * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
       
    14  *     its contributors may be used to endorse or promote products derived
       
    15  *     from this software without specific prior written permission. 
       
    16  *
       
    17  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
       
    18  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
       
    19  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
       
    20  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
       
    21  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
       
    22  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
       
    23  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
       
    24  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
       
    25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
       
    26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
       
    27  */
       
    28 
       
    29 #import "WebPDFView.h"
       
    30 
       
    31 #import "WebDataSourceInternal.h"
       
    32 #import "WebDocumentInternal.h"
       
    33 #import "WebDocumentPrivate.h"
       
    34 #import "WebFrame.h"
       
    35 #import "WebFrameInternal.h"
       
    36 #import "WebFrameView.h"
       
    37 #import "WebLocalizableStrings.h"
       
    38 #import "WebNSArrayExtras.h"
       
    39 #import "WebNSAttributedStringExtras.h"
       
    40 #import "WebNSPasteboardExtras.h"
       
    41 #import "WebNSViewExtras.h"
       
    42 #import "WebPDFRepresentation.h"
       
    43 #import "WebPreferencesPrivate.h"
       
    44 #import "WebUIDelegate.h"
       
    45 #import "WebUIDelegatePrivate.h"
       
    46 #import "WebView.h"
       
    47 #import "WebViewInternal.h"
       
    48 #import <JavaScriptCore/Assertions.h>
       
    49 #import <PDFKit/PDFKit.h>
       
    50 #import <WebCore/EventNames.h>
       
    51 #import <WebCore/FrameLoader.h>
       
    52 #import <WebCore/KURL.h>
       
    53 #import <WebCore/KeyboardEvent.h>
       
    54 #import <WebCore/MouseEvent.h>
       
    55 #import <WebCore/PlatformKeyboardEvent.h>
       
    56 #import <WebKitSystemInterface.h>
       
    57 
       
    58 using namespace WebCore;
       
    59 using namespace EventNames;
       
    60 
       
    61 // Redeclarations of PDFKit notifications. We can't use the API since we use a weak link to the framework.
       
    62 #define _webkit_PDFViewDisplayModeChangedNotification @"PDFViewDisplayModeChanged"
       
    63 #define _webkit_PDFViewScaleChangedNotification @"PDFViewScaleChanged"
       
    64 #define _webkit_PDFViewPageChangedNotification @"PDFViewChangedPage"
       
    65 
       
    66 @interface PDFDocument (PDFKitSecretsIKnow)
       
    67 - (NSPrintOperation *)getPrintOperationForPrintInfo:(NSPrintInfo *)printInfo autoRotate:(BOOL)doRotate;
       
    68 @end
       
    69 
       
    70 extern "C" NSString *_NSPathForSystemFramework(NSString *framework);
       
    71 
       
    72 @interface WebPDFView (FileInternal)
       
    73 + (Class)_PDFPreviewViewClass;
       
    74 + (Class)_PDFViewClass;
       
    75 - (BOOL)_anyPDFTagsFoundInMenu:(NSMenu *)menu;
       
    76 - (void)_applyPDFDefaults;
       
    77 - (BOOL)_canLookUpInDictionary;
       
    78 - (NSClipView *)_clipViewForPDFDocumentView;
       
    79 - (NSEvent *)_fakeKeyEventWithFunctionKey:(unichar)functionKey;
       
    80 - (NSMutableArray *)_menuItemsFromPDFKitForEvent:(NSEvent *)theEvent;
       
    81 - (PDFSelection *)_nextMatchFor:(NSString *)string direction:(BOOL)forward caseSensitive:(BOOL)caseFlag wrap:(BOOL)wrapFlag fromSelection:(PDFSelection *)initialSelection startInSelection:(BOOL)startInSelection;
       
    82 - (void)_openWithFinder:(id)sender;
       
    83 - (NSString *)_path;
       
    84 - (void)_PDFDocumentViewMightHaveScrolled:(NSNotification *)notification;
       
    85 - (BOOL)_pointIsInSelection:(NSPoint)point;
       
    86 - (NSAttributedString *)_scaledAttributedString:(NSAttributedString *)unscaledAttributedString;
       
    87 - (void)_setTextMatches:(NSArray *)array;
       
    88 - (NSString *)_temporaryPDFDirectoryPath;
       
    89 - (void)_trackFirstResponder;
       
    90 - (void)_updatePreferencesSoon;
       
    91 - (NSSet *)_visiblePDFPages;
       
    92 @end;
       
    93 
       
    94 // PDFPrefUpdatingProxy is a class that forwards everything it gets to a target and updates the PDF viewing prefs
       
    95 // after each of those messages.  We use it as a way to hook all the places that the PDF viewing attrs change.
       
    96 @interface PDFPrefUpdatingProxy : NSProxy {
       
    97     WebPDFView *view;
       
    98 }
       
    99 - (id)initWithView:(WebPDFView *)view;
       
   100 @end
       
   101 
       
   102 #pragma mark C UTILITY FUNCTIONS
       
   103 
       
   104 static void _applicationInfoForMIMEType(NSString *type, NSString **name, NSImage **image)
       
   105 {
       
   106     NSURL *appURL = nil;
       
   107     
       
   108     OSStatus error = LSCopyApplicationForMIMEType((CFStringRef)type, kLSRolesAll, (CFURLRef *)&appURL);
       
   109     if (error != noErr)
       
   110         return;
       
   111     
       
   112     NSString *appPath = [appURL path];
       
   113     CFRelease (appURL);
       
   114     
       
   115     *image = [[NSWorkspace sharedWorkspace] iconForFile:appPath];  
       
   116     [*image setSize:NSMakeSize(16.f,16.f)];  
       
   117     
       
   118     NSString *appName = [[NSFileManager defaultManager] displayNameAtPath:appPath];
       
   119     *name = appName;
       
   120 }
       
   121 
       
   122 // FIXME 4182876: We can eliminate this function in favor if -isEqual: if [PDFSelection isEqual:] is overridden
       
   123 // to compare contents.
       
   124 static BOOL _PDFSelectionsAreEqual(PDFSelection *selectionA, PDFSelection *selectionB)
       
   125 {
       
   126     NSArray *aPages = [selectionA pages];
       
   127     NSArray *bPages = [selectionB pages];
       
   128     
       
   129     if (![aPages isEqual:bPages])
       
   130         return NO;
       
   131     
       
   132     int count = [aPages count];
       
   133     int i;
       
   134     for (i = 0; i < count; ++i) {
       
   135         NSRect aBounds = [selectionA boundsForPage:[aPages objectAtIndex:i]];
       
   136         NSRect bBounds = [selectionB boundsForPage:[bPages objectAtIndex:i]];
       
   137         if (!NSEqualRects(aBounds, bBounds)) {
       
   138             return NO;
       
   139         }
       
   140     }
       
   141     
       
   142     return YES;
       
   143 }
       
   144 
       
   145 @implementation WebPDFView
       
   146 
       
   147 #pragma mark WebPDFView API
       
   148 
       
   149 + (NSBundle *)PDFKitBundle
       
   150 {
       
   151     static NSBundle *PDFKitBundle = nil;
       
   152     if (PDFKitBundle == nil) {
       
   153         NSString *PDFKitPath = [_NSPathForSystemFramework(@"Quartz.framework") stringByAppendingString:@"/Frameworks/PDFKit.framework"];
       
   154         if (PDFKitPath == nil) {
       
   155             LOG_ERROR("Couldn't find PDFKit.framework");
       
   156             return nil;
       
   157         }
       
   158         PDFKitBundle = [NSBundle bundleWithPath:PDFKitPath];
       
   159         if (![PDFKitBundle load]) {
       
   160             LOG_ERROR("Couldn't load PDFKit.framework");
       
   161         }
       
   162     }
       
   163     return PDFKitBundle;
       
   164 }
       
   165 
       
   166 + (NSArray *)supportedMIMETypes
       
   167 {
       
   168     return [WebPDFRepresentation supportedMIMETypes];
       
   169 }
       
   170 
       
   171 - (void)setPDFDocument:(PDFDocument *)doc
       
   172 {
       
   173     // Both setDocument: and _applyPDFDefaults will trigger scale and mode-changed notifications.
       
   174     // Those aren't reflecting user actions, so we need to ignore them.
       
   175     _ignoreScaleAndDisplayModeAndPageNotifications = YES;
       
   176     [PDFSubview setDocument:doc];
       
   177     [self _applyPDFDefaults];
       
   178     _ignoreScaleAndDisplayModeAndPageNotifications = NO;
       
   179 }
       
   180 
       
   181 #pragma mark NSObject OVERRIDES
       
   182 
       
   183 - (void)dealloc
       
   184 {
       
   185     ASSERT(!trackedFirstResponder);
       
   186     [previewView release];
       
   187     [PDFSubview release];
       
   188     [path release];
       
   189     [PDFSubviewProxy release];
       
   190     [textMatches release];
       
   191     [super dealloc];
       
   192 }
       
   193 
       
   194 #pragma mark NSResponder OVERRIDES
       
   195 
       
   196 - (void)centerSelectionInVisibleArea:(id)sender
       
   197 {
       
   198     [PDFSubview scrollSelectionToVisible:nil];
       
   199 }
       
   200 
       
   201 - (void)scrollPageDown:(id)sender
       
   202 {
       
   203     // PDFView doesn't support this responder method directly, so we pass it a fake key event
       
   204     [PDFSubview keyDown:[self _fakeKeyEventWithFunctionKey:NSPageDownFunctionKey]];
       
   205 }
       
   206 
       
   207 - (void)scrollPageUp:(id)sender
       
   208 {
       
   209     // PDFView doesn't support this responder method directly, so we pass it a fake key event
       
   210     [PDFSubview keyDown:[self _fakeKeyEventWithFunctionKey:NSPageUpFunctionKey]];
       
   211 }
       
   212 
       
   213 - (void)scrollLineDown:(id)sender
       
   214 {
       
   215     // PDFView doesn't support this responder method directly, so we pass it a fake key event
       
   216     [PDFSubview keyDown:[self _fakeKeyEventWithFunctionKey:NSDownArrowFunctionKey]];
       
   217 }
       
   218 
       
   219 - (void)scrollLineUp:(id)sender
       
   220 {
       
   221     // PDFView doesn't support this responder method directly, so we pass it a fake key event
       
   222     [PDFSubview keyDown:[self _fakeKeyEventWithFunctionKey:NSUpArrowFunctionKey]];
       
   223 }
       
   224 
       
   225 - (void)scrollToBeginningOfDocument:(id)sender
       
   226 {
       
   227     // PDFView doesn't support this responder method directly, so we pass it a fake key event
       
   228     [PDFSubview keyDown:[self _fakeKeyEventWithFunctionKey:NSHomeFunctionKey]];
       
   229 }
       
   230 
       
   231 - (void)scrollToEndOfDocument:(id)sender
       
   232 {
       
   233     // PDFView doesn't support this responder method directly, so we pass it a fake key event
       
   234     [PDFSubview keyDown:[self _fakeKeyEventWithFunctionKey:NSEndFunctionKey]];
       
   235 }
       
   236 
       
   237 // jumpToSelection is the old name for what AppKit now calls centerSelectionInVisibleArea. Safari
       
   238 // was using the old jumpToSelection selector in its menu. Newer versions of Safari will us the
       
   239 // selector centerSelectionInVisibleArea. We'll leave this old selector in place for two reasons:
       
   240 // (1) compatibility between older Safari and newer WebKit; (2) other WebKit-based applications
       
   241 // might be using the jumpToSelection: selector, and we don't want to break them.
       
   242 - (void)jumpToSelection:(id)sender
       
   243 {
       
   244     [self centerSelectionInVisibleArea:nil];
       
   245 }
       
   246 
       
   247 #pragma mark NSView OVERRIDES
       
   248 
       
   249 - (BOOL)acceptsFirstResponder {
       
   250     return YES;
       
   251 }
       
   252 
       
   253 - (BOOL)becomeFirstResponder
       
   254 {
       
   255     // This works together with setNextKeyView to splice our PDFSubview into
       
   256     // the key loop similar to the way NSScrollView does this.
       
   257     NSWindow *window = [self window];
       
   258     id newFirstResponder = nil;
       
   259     
       
   260     if ([window keyViewSelectionDirection] == NSSelectingPrevious) {
       
   261         NSView *previousValidKeyView = [self previousValidKeyView];
       
   262         if ((previousValidKeyView != self) && (previousValidKeyView != PDFSubview))
       
   263             newFirstResponder = previousValidKeyView;
       
   264     } else {
       
   265         NSView *PDFDocumentView = [PDFSubview documentView];
       
   266         if ([PDFDocumentView acceptsFirstResponder])
       
   267             newFirstResponder = PDFDocumentView;
       
   268     }
       
   269     
       
   270     if (!newFirstResponder)
       
   271         return NO;
       
   272     
       
   273     if (![window makeFirstResponder:newFirstResponder])
       
   274         return NO;
       
   275     
       
   276     [[dataSource webFrame] _clearSelectionInOtherFrames];
       
   277     
       
   278     return YES;
       
   279 }
       
   280 
       
   281 - (NSView *)hitTest:(NSPoint)point
       
   282 {
       
   283     // Override hitTest so we can override menuForEvent.
       
   284     NSEvent *event = [NSApp currentEvent];
       
   285     NSEventType type = [event type];
       
   286     if (type == NSRightMouseDown || (type == NSLeftMouseDown && ([event modifierFlags] & NSControlKeyMask)))
       
   287         return self;
       
   288 
       
   289     return [super hitTest:point];
       
   290 }
       
   291 
       
   292 - (id)initWithFrame:(NSRect)frame
       
   293 {
       
   294     self = [super initWithFrame:frame];
       
   295     if (self) {
       
   296         [self setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
       
   297         
       
   298         Class previewViewClass = nil;
       
   299         if ([[WebPreferences standardPreferences] _usePDFPreviewView])
       
   300             previewViewClass = [[self class] _PDFPreviewViewClass];
       
   301         
       
   302         // We might not have found a previewViewClass even if we looked for one.
       
   303         // But if we found the class we should be able to create an instance.
       
   304         if (previewViewClass) {
       
   305             previewView = [[previewViewClass alloc] initWithFrame:frame];
       
   306             ASSERT(previewView);
       
   307         }
       
   308         
       
   309         NSView *topLevelPDFKitView = nil;
       
   310         if (previewView) {
       
   311             // We'll retain the PDFSubview here so that it is equally retained in all
       
   312             // code paths. That way we don't need to worry about conditionally releasing
       
   313             // it later.
       
   314             PDFSubview = [[previewView performSelector:@selector(pdfView)] retain];
       
   315             topLevelPDFKitView = previewView;
       
   316         } else {
       
   317             PDFSubview = [[[[self class] _PDFViewClass] alloc] initWithFrame:frame];
       
   318             topLevelPDFKitView = PDFSubview;
       
   319         }
       
   320         
       
   321         ASSERT(PDFSubview);
       
   322         
       
   323         [topLevelPDFKitView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
       
   324         [self addSubview:topLevelPDFKitView];
       
   325         
       
   326         [PDFSubview setDelegate:self];
       
   327         written = NO;
       
   328         // Messaging this proxy is the same as messaging PDFSubview, with the side effect that the
       
   329         // PDF viewing defaults are updated afterwards
       
   330         PDFSubviewProxy = (PDFView *)[[PDFPrefUpdatingProxy alloc] initWithView:self];
       
   331     }
       
   332     
       
   333     return self;
       
   334 }
       
   335 
       
   336 - (NSMenu *)menuForEvent:(NSEvent *)theEvent
       
   337 {
       
   338     // Start with the menu items supplied by PDFKit, with WebKit tags applied
       
   339     NSMutableArray *items = [self _menuItemsFromPDFKitForEvent:theEvent];
       
   340     
       
   341     // Add in an "Open with <default PDF viewer>" item
       
   342     NSString *appName = nil;
       
   343     NSImage *appIcon = nil;
       
   344     
       
   345     _applicationInfoForMIMEType([[dataSource response] MIMEType], &appName, &appIcon);
       
   346     if (!appName)
       
   347         appName = UI_STRING("Finder", "Default application name for Open With context menu");
       
   348     
       
   349     // To match the PDFKit style, we'll add Open with Preview even when there's no document yet to view, and
       
   350     // disable it using validateUserInterfaceItem.
       
   351     NSString *title = [NSString stringWithFormat:UI_STRING("Open with %@", "context menu item for PDF"), appName];
       
   352     NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:title action:@selector(_openWithFinder:) keyEquivalent:@""];
       
   353     [item setTag:WebMenuItemTagOpenWithDefaultApplication];
       
   354     if (appIcon)
       
   355         [item setImage:appIcon];
       
   356     [items insertObject:item atIndex:0];
       
   357     [item release];
       
   358     
       
   359     [items insertObject:[NSMenuItem separatorItem] atIndex:1];
       
   360     
       
   361     // pass the items off to the WebKit context menu mechanism
       
   362     WebView *webView = [[dataSource webFrame] webView];
       
   363     ASSERT(webView);
       
   364     NSMenu *menu = [webView _menuForElement:[self elementAtPoint:[self convertPoint:[theEvent locationInWindow] fromView:nil]] defaultItems:items];
       
   365     
       
   366     // The delegate has now had the opportunity to add items to the standard PDF-related items, or to
       
   367     // remove or modify some of the PDF-related items. In 10.4, the PDF context menu did not go through 
       
   368     // the standard WebKit delegate path, and so the standard PDF-related items always appeared. For
       
   369     // clients that create their own context menu by hand-picking specific items from the default list, such as
       
   370     // Safari, none of the PDF-related items will appear until the client is rewritten to explicitly
       
   371     // include these items. For backwards compatibility of tip-of-tree WebKit with the 10.4 version of Safari
       
   372     // (the configuration that people building open source WebKit use), we'll use the entire set of PDFKit-supplied
       
   373     // menu items. This backward-compatibility hack won't work with any non-Safari clients, but this seems OK since
       
   374     // (1) the symptom is fairly minor, and (2) we suspect that non-Safari clients are probably using the entire
       
   375     // set of default items, rather than manually choosing from them. We can remove this code entirely when we
       
   376     // ship a version of Safari that includes the fix for radar 3796579.
       
   377     if (![self _anyPDFTagsFoundInMenu:menu] && [[[NSBundle mainBundle] bundleIdentifier] isEqualToString:@"com.apple.Safari"]) {
       
   378         [menu addItem:[NSMenuItem separatorItem]];
       
   379         NSEnumerator *e = [items objectEnumerator];
       
   380         NSMenuItem *menuItem;
       
   381         while ((menuItem = [e nextObject]) != nil) {
       
   382             // copy menuItem since a given menuItem can be in only one menu at a time, and we don't
       
   383             // want to mess with the menu returned from PDFKit.
       
   384             [menu addItem:[menuItem copy]];
       
   385         }
       
   386     }
       
   387     
       
   388     return menu;
       
   389 }
       
   390 
       
   391 - (void)setNextKeyView:(NSView *)aView
       
   392 {
       
   393     // This works together with becomeFirstResponder to splice PDFSubview into
       
   394     // the key loop similar to the way NSScrollView and NSClipView do this.
       
   395     NSView *documentView = [PDFSubview documentView];
       
   396     if (documentView) {
       
   397         [documentView setNextKeyView:aView];
       
   398         
       
   399         // We need to make the documentView be the next view in the keyview loop.
       
   400         // It would seem more sensible to do this in our init method, but it turns out
       
   401         // that [NSClipView setDocumentView] won't call this method if our next key view
       
   402         // is already set, so we wait until we're called before adding this connection.
       
   403         // We'll also clear it when we're called with nil, so this could go through the
       
   404         // same code path more than once successfully.
       
   405         [super setNextKeyView: aView ? documentView : nil];
       
   406     } else
       
   407         [super setNextKeyView:aView];
       
   408 }
       
   409 
       
   410 - (void)viewDidMoveToWindow
       
   411 {
       
   412     // FIXME 2573089: we can observe a notification for first responder changes
       
   413     // instead of the very frequent NSWindowDidUpdateNotification if/when 2573089 is addressed.
       
   414     NSWindow *newWindow = [self window];
       
   415     if (!newWindow)
       
   416         return;
       
   417     
       
   418     [self _trackFirstResponder];
       
   419     NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
       
   420     [notificationCenter addObserver:self
       
   421                            selector:@selector(_trackFirstResponder) 
       
   422                                name:NSWindowDidUpdateNotification
       
   423                              object:newWindow];
       
   424     
       
   425     [notificationCenter addObserver:self
       
   426                            selector:@selector(_scaleOrDisplayModeOrPageChanged:) 
       
   427                                name:_webkit_PDFViewScaleChangedNotification
       
   428                              object:PDFSubview];
       
   429     
       
   430     [notificationCenter addObserver:self
       
   431                            selector:@selector(_scaleOrDisplayModeOrPageChanged:) 
       
   432                                name:_webkit_PDFViewDisplayModeChangedNotification
       
   433                              object:PDFSubview];
       
   434     
       
   435     [notificationCenter addObserver:self
       
   436                            selector:@selector(_scaleOrDisplayModeOrPageChanged:) 
       
   437                                name:_webkit_PDFViewPageChangedNotification
       
   438                              object:PDFSubview];
       
   439     
       
   440     [notificationCenter addObserver:self 
       
   441                            selector:@selector(_PDFDocumentViewMightHaveScrolled:)
       
   442                                name:NSViewBoundsDidChangeNotification 
       
   443                              object:[self _clipViewForPDFDocumentView]];
       
   444 }
       
   445 
       
   446 - (void)viewWillMoveToWindow:(NSWindow *)window
       
   447 {
       
   448     // FIXME 2573089: we can observe a notification for changes to the first responder
       
   449     // instead of the very frequent NSWindowDidUpdateNotification if/when 2573089 is addressed.
       
   450     NSWindow *oldWindow = [self window];
       
   451     if (!oldWindow)
       
   452         return;
       
   453     
       
   454     NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
       
   455     [notificationCenter removeObserver:self
       
   456                                   name:NSWindowDidUpdateNotification
       
   457                                 object:oldWindow];
       
   458     [notificationCenter removeObserver:self
       
   459                                   name:_webkit_PDFViewScaleChangedNotification
       
   460                                 object:PDFSubview];
       
   461     [notificationCenter removeObserver:self
       
   462                                   name:_webkit_PDFViewDisplayModeChangedNotification
       
   463                                 object:PDFSubview];
       
   464     [notificationCenter removeObserver:self
       
   465                                   name:_webkit_PDFViewPageChangedNotification
       
   466                                 object:PDFSubview];
       
   467     
       
   468     [notificationCenter removeObserver:self
       
   469                                   name:NSViewBoundsDidChangeNotification 
       
   470                                 object:[self _clipViewForPDFDocumentView]];
       
   471     
       
   472     [trackedFirstResponder release];
       
   473     trackedFirstResponder = nil;
       
   474 }
       
   475 
       
   476 #pragma mark NSUserInterfaceValidations PROTOCOL IMPLEMENTATION
       
   477 
       
   478 - (BOOL)validateUserInterfaceItemWithoutDelegate:(id <NSValidatedUserInterfaceItem>)item
       
   479 {
       
   480     SEL action = [item action];    
       
   481     if (action == @selector(takeFindStringFromSelection:) || action == @selector(centerSelectionInVisibleArea:) || action == @selector(jumpToSelection:))
       
   482         return [PDFSubview currentSelection] != nil;
       
   483     
       
   484     if (action == @selector(_openWithFinder:))
       
   485         return [PDFSubview document] != nil;
       
   486     
       
   487     if (action == @selector(_lookUpInDictionaryFromMenu:))
       
   488         return [self _canLookUpInDictionary];
       
   489 
       
   490     return YES;
       
   491 }
       
   492 
       
   493 - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)item
       
   494 {
       
   495     BOOL result = [self validateUserInterfaceItemWithoutDelegate:item];
       
   496     return CallUIDelegateReturningBoolean(result, [self _webView], @selector(webView:validateUserInterfaceItem:defaultValidation:), item, result);
       
   497 }
       
   498 
       
   499 #pragma mark INTERFACE BUILDER ACTIONS FOR SAFARI
       
   500 
       
   501 // Surprisingly enough, this isn't defined in any superclass, though it is defined in assorted AppKit classes since
       
   502 // it's a standard menu item IBAction.
       
   503 - (IBAction)copy:(id)sender
       
   504 {
       
   505     [PDFSubview copy:sender];
       
   506 }
       
   507 
       
   508 // This used to be a standard IBAction (for Use Selection For Find), but AppKit now uses performFindPanelAction:
       
   509 // with a menu item tag for this purpose.
       
   510 - (IBAction)takeFindStringFromSelection:(id)sender
       
   511 {
       
   512     [NSPasteboard _web_setFindPasteboardString:[[PDFSubview currentSelection] string] withOwner:self];
       
   513 }
       
   514 
       
   515 #pragma mark WebFrameView UNDECLARED "DELEGATE METHODS"
       
   516 
       
   517 // This is tested in -[WebFrameView canPrintHeadersAndFooters], but isn't declared anywhere (yuck)
       
   518 - (BOOL)canPrintHeadersAndFooters
       
   519 {
       
   520     return NO;
       
   521 }
       
   522 
       
   523 // This is tested in -[WebFrameView printOperationWithPrintInfo:], but isn't declared anywhere (yuck)
       
   524 - (NSPrintOperation *)printOperationWithPrintInfo:(NSPrintInfo *)printInfo
       
   525 {
       
   526     return [[PDFSubview document] getPrintOperationForPrintInfo:printInfo autoRotate:YES];
       
   527 }
       
   528 
       
   529 #pragma mark WebDocumentView PROTOCOL IMPLEMENTATION
       
   530 
       
   531 - (void)setDataSource:(WebDataSource *)ds
       
   532 {
       
   533     dataSource = ds;
       
   534     [self setFrame:[[self superview] frame]];
       
   535 }
       
   536 
       
   537 - (void)dataSourceUpdated:(WebDataSource *)dataSource
       
   538 {
       
   539 }
       
   540 
       
   541 - (void)setNeedsLayout:(BOOL)flag
       
   542 {
       
   543 }
       
   544 
       
   545 - (void)layout
       
   546 {
       
   547 }
       
   548 
       
   549 - (void)viewWillMoveToHostWindow:(NSWindow *)hostWindow
       
   550 {
       
   551 }
       
   552 
       
   553 - (void)viewDidMoveToHostWindow
       
   554 {
       
   555 }
       
   556 
       
   557 #pragma mark WebDocumentElement PROTOCOL IMPLEMENTATION
       
   558 
       
   559 - (NSDictionary *)elementAtPoint:(NSPoint)point
       
   560 {
       
   561     WebFrame *frame = [dataSource webFrame];
       
   562     ASSERT(frame);
       
   563     
       
   564     return [NSDictionary dictionaryWithObjectsAndKeys:
       
   565         frame, WebElementFrameKey, 
       
   566         [NSNumber numberWithBool:[self _pointIsInSelection:point]], WebElementIsSelectedKey,
       
   567         nil];
       
   568 }
       
   569 
       
   570 - (NSDictionary *)elementAtPoint:(NSPoint)point allowShadowContent:(BOOL)allow
       
   571 {
       
   572     return [self elementAtPoint:point];
       
   573 }
       
   574 
       
   575 #pragma mark WebDocumentSearching PROTOCOL IMPLEMENTATION
       
   576 
       
   577 - (BOOL)searchFor:(NSString *)string direction:(BOOL)forward caseSensitive:(BOOL)caseFlag wrap:(BOOL)wrapFlag
       
   578 {
       
   579     return [self searchFor:string direction:forward caseSensitive:caseFlag wrap:wrapFlag startInSelection:NO];
       
   580 }
       
   581 
       
   582 #pragma mark WebDocumentIncrementalSearching PROTOCOL IMPLEMENTATION
       
   583 
       
   584 - (BOOL)searchFor:(NSString *)string direction:(BOOL)forward caseSensitive:(BOOL)caseFlag wrap:(BOOL)wrapFlag startInSelection:(BOOL)startInSelection
       
   585 {
       
   586     PDFSelection *selection = [self _nextMatchFor:string direction:forward caseSensitive:caseFlag wrap:wrapFlag fromSelection:[PDFSubview currentSelection] startInSelection:startInSelection];
       
   587     if (!selection)
       
   588         return NO;
       
   589 
       
   590     [PDFSubview setCurrentSelection:selection];
       
   591     [PDFSubview scrollSelectionToVisible:nil];
       
   592     return YES;
       
   593 }
       
   594 
       
   595 #pragma mark WebMultipleTextMatches PROTOCOL IMPLEMENTATION
       
   596 
       
   597 - (void)setMarkedTextMatchesAreHighlighted:(BOOL)newValue
       
   598 {
       
   599     // This method is part of the WebMultipleTextMatches algorithm, but this class doesn't support
       
   600     // highlighting text matches inline.
       
   601 #ifndef NDEBUG
       
   602     if (newValue)
       
   603         LOG_ERROR("[WebPDFView setMarkedTextMatchesAreHighlighted:] called with YES, which isn't supported");
       
   604 #endif
       
   605 }
       
   606 
       
   607 - (BOOL)markedTextMatchesAreHighlighted
       
   608 {
       
   609     return NO;
       
   610 }
       
   611 
       
   612 - (NSUInteger)markAllMatchesForText:(NSString *)string caseSensitive:(BOOL)caseFlag limit:(NSUInteger)limit
       
   613 {
       
   614     PDFSelection *previousMatch = nil;
       
   615     PDFSelection *nextMatch = nil;
       
   616     NSMutableArray *matches = [[NSMutableArray alloc] initWithCapacity:limit];
       
   617     
       
   618     for (;;) {
       
   619         nextMatch = [self _nextMatchFor:string direction:YES caseSensitive:caseFlag wrap:NO fromSelection:previousMatch startInSelection:NO];
       
   620         if (!nextMatch)
       
   621             break;
       
   622         
       
   623         [matches addObject:nextMatch];
       
   624         previousMatch = nextMatch;
       
   625 
       
   626         if ([matches count] >= limit)
       
   627             break;
       
   628     }
       
   629     
       
   630     [self _setTextMatches:matches];
       
   631     [matches release];
       
   632     
       
   633     return [matches count];
       
   634 }
       
   635 
       
   636 - (void)unmarkAllTextMatches
       
   637 {
       
   638     [self _setTextMatches:nil];
       
   639 }
       
   640 
       
   641 - (NSArray *)rectsForTextMatches
       
   642 {
       
   643     NSMutableArray *result = [NSMutableArray arrayWithCapacity:[textMatches count]];
       
   644     NSSet *visiblePages = [self _visiblePDFPages];
       
   645     NSEnumerator *matchEnumerator = [textMatches objectEnumerator];
       
   646     PDFSelection *match;
       
   647     
       
   648     while ((match = [matchEnumerator nextObject]) != nil) {
       
   649         NSEnumerator *pages = [[match pages] objectEnumerator];
       
   650         PDFPage *page;
       
   651         while ((page = [pages nextObject]) != nil) {
       
   652             
       
   653             // Skip pages that aren't visible (needed for non-continuous modes, see 5362989)
       
   654             if (![visiblePages containsObject:page])
       
   655                 continue;
       
   656             
       
   657             NSRect selectionOnPageInPDFViewCoordinates = [PDFSubview convertRect:[match boundsForPage:page] fromPage:page];
       
   658             [result addObject:[NSValue valueWithRect:selectionOnPageInPDFViewCoordinates]];
       
   659         }
       
   660     }
       
   661 
       
   662     return result;
       
   663 }
       
   664 
       
   665 #pragma mark WebDocumentText PROTOCOL IMPLEMENTATION
       
   666 
       
   667 - (BOOL)supportsTextEncoding
       
   668 {
       
   669     return NO;
       
   670 }
       
   671 
       
   672 - (NSString *)string
       
   673 {
       
   674     return [[PDFSubview document] string];
       
   675 }
       
   676 
       
   677 - (NSAttributedString *)attributedString
       
   678 {
       
   679     // changing the selection is a hack, but the only way to get an attr string is via PDFSelection
       
   680     
       
   681     // must copy this selection object because we change the selection which seems to release it
       
   682     PDFSelection *savedSelection = [[PDFSubview currentSelection] copy];
       
   683     [PDFSubview selectAll:nil];
       
   684     NSAttributedString *result = [[PDFSubview currentSelection] attributedString];
       
   685     if (savedSelection) {
       
   686         [PDFSubview setCurrentSelection:savedSelection];
       
   687         [savedSelection release];
       
   688     } else {
       
   689         // FIXME: behavior of setCurrentSelection:nil is not documented - check 4182934 for progress
       
   690         // Otherwise, we could collapse this code with the case above.
       
   691         [PDFSubview clearSelection];
       
   692     }
       
   693     
       
   694     result = [self _scaledAttributedString:result];
       
   695     
       
   696     return result;
       
   697 }
       
   698 
       
   699 - (NSString *)selectedString
       
   700 {
       
   701     return [[PDFSubview currentSelection] string];
       
   702 }
       
   703 
       
   704 - (NSAttributedString *)selectedAttributedString
       
   705 {
       
   706     return [self _scaledAttributedString:[[PDFSubview currentSelection] attributedString]];
       
   707 }
       
   708 
       
   709 - (void)selectAll
       
   710 {
       
   711     [PDFSubview selectAll:nil];
       
   712 }
       
   713 
       
   714 - (void)deselectAll
       
   715 {
       
   716     [PDFSubview clearSelection];
       
   717 }
       
   718 
       
   719 #pragma mark WebDocumentViewState PROTOCOL IMPLEMENTATION
       
   720 
       
   721 // Even though to WebKit we are the "docView", in reality a PDFView contains its own scrollview and docView.
       
   722 // And it even turns out there is another PDFKit view between the docView and its enclosing ScrollView, so
       
   723 // we have to be sure to do our calculations based on that view, immediately inside the ClipView.  We try
       
   724 // to make as few assumptions about the PDFKit view hierarchy as possible.
       
   725 
       
   726 - (NSPoint)scrollPoint
       
   727 {
       
   728     NSView *realDocView = [PDFSubview documentView];
       
   729     NSClipView *clipView = [[realDocView enclosingScrollView] contentView];
       
   730     return [clipView bounds].origin;
       
   731 }
       
   732 
       
   733 - (void)setScrollPoint:(NSPoint)p
       
   734 {
       
   735     WebFrame *frame = [dataSource webFrame];
       
   736     //FIXME:  We only restore scroll state in the non-frames case because otherwise we get a crash due to
       
   737     // PDFKit calling display from within its drawRect:. See bugzilla 4164.
       
   738     if (![frame parentFrame]) {
       
   739         NSView *realDocView = [PDFSubview documentView];
       
   740         [[[realDocView enclosingScrollView] documentView] scrollPoint:p];
       
   741     }
       
   742 }
       
   743 
       
   744 - (id)viewState
       
   745 {
       
   746     NSMutableArray *state = [NSMutableArray arrayWithCapacity:4];
       
   747     PDFDisplayMode mode = [PDFSubview displayMode];
       
   748     [state addObject:[NSNumber numberWithInt:mode]];
       
   749     if (mode == kPDFDisplaySinglePage || mode == kPDFDisplayTwoUp) {
       
   750         unsigned int pageIndex = [[PDFSubview document] indexForPage:[PDFSubview currentPage]];
       
   751         [state addObject:[NSNumber numberWithUnsignedInt:pageIndex]];
       
   752     }  // else in continuous modes, scroll position gets us to the right page
       
   753     BOOL autoScaleFlag = [PDFSubview autoScales];
       
   754     [state addObject:[NSNumber numberWithBool:autoScaleFlag]];
       
   755     if (!autoScaleFlag)
       
   756         [state addObject:[NSNumber numberWithFloat:[PDFSubview scaleFactor]]];
       
   757 
       
   758     return state;
       
   759 }
       
   760 
       
   761 - (void)setViewState:(id)statePList
       
   762 {
       
   763     ASSERT([statePList isKindOfClass:[NSArray class]]);
       
   764     NSArray *state = statePList;
       
   765     int i = 0;
       
   766     PDFDisplayMode mode = [[state objectAtIndex:i++] intValue];
       
   767     [PDFSubview setDisplayMode:mode];
       
   768     if (mode == kPDFDisplaySinglePage || mode == kPDFDisplayTwoUp) {
       
   769         unsigned int pageIndex = [[state objectAtIndex:i++] unsignedIntValue];
       
   770         [PDFSubview goToPage:[[PDFSubview document] pageAtIndex:pageIndex]];
       
   771     }  // else in continuous modes, scroll position gets us to the right page
       
   772     BOOL autoScaleFlag = [[state objectAtIndex:i++] boolValue];
       
   773     [PDFSubview setAutoScales:autoScaleFlag];
       
   774     if (!autoScaleFlag)
       
   775         [PDFSubview setScaleFactor:[[state objectAtIndex:i++] floatValue]];
       
   776 }
       
   777 
       
   778 #pragma mark _WebDocumentTextSizing PROTOCOL IMPLEMENTATION
       
   779 
       
   780 - (IBAction)_makeTextSmaller:(id)sender
       
   781 {
       
   782     [PDFSubviewProxy zoomOut:sender];
       
   783 }
       
   784 
       
   785 - (IBAction)_makeTextLarger:(id)sender
       
   786 {
       
   787     [PDFSubviewProxy zoomIn:sender];
       
   788 }
       
   789 
       
   790 - (IBAction)_makeTextStandardSize:(id)sender
       
   791 {
       
   792     [PDFSubviewProxy setScaleFactor:1.0f];
       
   793 }
       
   794 
       
   795 // never sent because we do not track the common size factor
       
   796 - (void)_textSizeMultiplierChanged      { ASSERT_NOT_REACHED(); }
       
   797 
       
   798 - (BOOL)_tracksCommonSizeFactor
       
   799 {
       
   800     // We keep our own scale factor instead of tracking the common one in the WebView for a couple reasons.
       
   801     // First, PDFs tend to have visually smaller text because they are laid out for a printed page instead of
       
   802     // the screen.  Second, the PDFView feature of AutoScaling means our scaling factor can be quiet variable.
       
   803     return NO;
       
   804 }
       
   805 
       
   806 - (BOOL)_canMakeTextSmaller
       
   807 {
       
   808     return [PDFSubview canZoomOut];
       
   809 }
       
   810 
       
   811 - (BOOL)_canMakeTextLarger
       
   812 {
       
   813     return [PDFSubview canZoomIn];
       
   814 }
       
   815 
       
   816 - (BOOL)_canMakeTextStandardSize
       
   817 {
       
   818     return [PDFSubview scaleFactor] != 1.0;
       
   819 }
       
   820 
       
   821 #pragma mark WebDocumentSelection PROTOCOL IMPLEMENTATION
       
   822 
       
   823 - (NSRect)selectionRect
       
   824 {
       
   825     NSRect result = NSZeroRect;
       
   826     PDFSelection *selection = [PDFSubview currentSelection];
       
   827     NSEnumerator *pages = [[selection pages] objectEnumerator];
       
   828     PDFPage *page;
       
   829     while ((page = [pages nextObject]) != nil) {
       
   830         NSRect selectionOnPageInPDFViewCoordinates = [PDFSubview convertRect:[selection boundsForPage:page] fromPage:page];
       
   831         if (NSIsEmptyRect(result))
       
   832             result = selectionOnPageInPDFViewCoordinates;
       
   833         else
       
   834             result = NSUnionRect(result, selectionOnPageInPDFViewCoordinates);
       
   835     }
       
   836     
       
   837     // Convert result to be in documentView (selectionView) coordinates
       
   838     result = [PDFSubview convertRect:result toView:[PDFSubview documentView]];
       
   839     
       
   840     return result;
       
   841 }
       
   842 
       
   843 - (NSArray *)selectionTextRects
       
   844 {
       
   845     // FIXME: We'd need new PDFKit API/SPI to get multiple text rects for selections that intersect more than one line
       
   846     return [NSArray arrayWithObject:[NSValue valueWithRect:[self selectionRect]]];
       
   847 }
       
   848 
       
   849 - (NSView *)selectionView
       
   850 {
       
   851     return [PDFSubview documentView];
       
   852 }
       
   853 
       
   854 - (NSImage *)selectionImageForcingBlackText:(BOOL)forceBlackText
       
   855 {
       
   856     // Convert the selection to an attributed string, and draw that.
       
   857     // FIXME 4621154: this doesn't handle italics (and maybe other styles)
       
   858     // FIXME 4604366: this doesn't handle text at non-actual size
       
   859     NSMutableAttributedString *attributedString = [[self selectedAttributedString] mutableCopy];
       
   860     NSRange wholeStringRange = NSMakeRange(0, [attributedString length]);
       
   861     
       
   862     // Modify the styles in the attributed string to draw black text, no background, and no underline. We draw 
       
   863     // no underline because it would look ugly.
       
   864     [attributedString beginEditing];
       
   865     [attributedString removeAttribute:NSBackgroundColorAttributeName range:wholeStringRange];
       
   866     [attributedString removeAttribute:NSUnderlineStyleAttributeName range:wholeStringRange];
       
   867     if (forceBlackText)
       
   868         [attributedString addAttribute:NSForegroundColorAttributeName value:[NSColor colorWithDeviceWhite:0.0f alpha:1.0f] range:wholeStringRange];
       
   869     [attributedString endEditing];
       
   870     
       
   871     NSImage* selectionImage = [[[NSImage alloc] initWithSize:[self selectionRect].size] autorelease];
       
   872     
       
   873     [selectionImage lockFocus];
       
   874     [attributedString drawAtPoint:NSZeroPoint];
       
   875     [selectionImage unlockFocus];
       
   876     
       
   877     [attributedString release];
       
   878 
       
   879     return selectionImage;
       
   880 }
       
   881 
       
   882 - (NSImage *)selectionImageForcingWhiteText:(BOOL)forceWhiteText
       
   883 {
       
   884     // NOTE: this method is obsolete and doesn't behave as its name suggests.
       
   885     // See comment in WebDocumentPrivate.h.
       
   886     return [self selectionImageForcingBlackText:forceWhiteText];
       
   887 }
       
   888 
       
   889 - (NSRect)selectionImageRect
       
   890 {
       
   891     // FIXME: deal with clipping?
       
   892     return [self selectionRect];
       
   893 }
       
   894 
       
   895 - (NSArray *)pasteboardTypesForSelection
       
   896 {
       
   897     return [NSArray arrayWithObjects:NSRTFDPboardType, NSRTFPboardType, NSStringPboardType, nil];
       
   898 }
       
   899 
       
   900 - (void)writeSelectionWithPasteboardTypes:(NSArray *)types toPasteboard:(NSPasteboard *)pasteboard
       
   901 {
       
   902     NSAttributedString *attributedString = [self selectedAttributedString];
       
   903     
       
   904     if ([types containsObject:NSRTFDPboardType]) {
       
   905         NSData *RTFDData = [attributedString RTFDFromRange:NSMakeRange(0, [attributedString length]) documentAttributes:nil];
       
   906         [pasteboard setData:RTFDData forType:NSRTFDPboardType];
       
   907     }        
       
   908     
       
   909     if ([types containsObject:NSRTFPboardType]) {
       
   910         if ([attributedString containsAttachments])
       
   911             attributedString = [attributedString _web_attributedStringByStrippingAttachmentCharacters];
       
   912 
       
   913         NSData *RTFData = [attributedString RTFFromRange:NSMakeRange(0, [attributedString length]) documentAttributes:nil];
       
   914         [pasteboard setData:RTFData forType:NSRTFPboardType];
       
   915     }
       
   916     
       
   917     if ([types containsObject:NSStringPboardType])
       
   918         [pasteboard setString:[self selectedString] forType:NSStringPboardType];
       
   919 }
       
   920 
       
   921 #pragma mark PDFView DELEGATE METHODS
       
   922 
       
   923 - (void)PDFViewWillClickOnLink:(PDFView *)sender withURL:(NSURL *)URL
       
   924 {
       
   925     if (!URL)
       
   926         return;
       
   927 
       
   928     NSWindow *window = [sender window];
       
   929     NSEvent *nsEvent = [window currentEvent];
       
   930     const int noButton = -1;
       
   931     int button = noButton;
       
   932     RefPtr<Event> event;
       
   933     switch ([nsEvent type]) {
       
   934         case NSLeftMouseUp:
       
   935             button = 0;
       
   936             break;
       
   937         case NSRightMouseUp:
       
   938             button = 1;
       
   939             break;
       
   940         case NSOtherMouseUp:
       
   941             button = [nsEvent buttonNumber];
       
   942             break;
       
   943         case NSKeyDown: {
       
   944             PlatformKeyboardEvent pe(nsEvent);
       
   945             event = new KeyboardEvent(keydownEvent, true, true, 0,
       
   946                 pe.keyIdentifier(), pe.WindowsKeyCode(),
       
   947                 pe.ctrlKey(), pe.altKey(), pe.shiftKey(), pe.metaKey(), false);
       
   948         }
       
   949         default:
       
   950             break;
       
   951     }
       
   952     if (button != noButton)
       
   953         event = new MouseEvent(clickEvent, true, true, 0, [nsEvent clickCount], 0, 0, 0, 0,
       
   954             [nsEvent modifierFlags] & NSControlKeyMask,
       
   955             [nsEvent modifierFlags] & NSAlternateKeyMask,
       
   956             [nsEvent modifierFlags] & NSShiftKeyMask,
       
   957             [nsEvent modifierFlags] & NSCommandKeyMask,
       
   958             button, 0, 0, true);
       
   959 
       
   960     // Call to the frame loader because this is where our security checks are made.
       
   961     [[dataSource webFrame] _frameLoader]->load(URL, event.get());
       
   962 }
       
   963 
       
   964 - (void)PDFViewOpenPDFInNativeApplication:(PDFView *)sender
       
   965 {
       
   966     // Delegate method sent when the user requests opening the PDF file in the system's default app
       
   967     [self _openWithFinder:sender];
       
   968 }
       
   969 
       
   970 - (void)PDFViewSavePDFToDownloadFolder:(PDFView *)sender
       
   971 {
       
   972     // We don't want to write the file until we have a document to write (see 5267607).
       
   973     if (![PDFSubview document]) {
       
   974         NSBeep();
       
   975         return;
       
   976     }
       
   977 
       
   978     // Delegate method sent when the user requests downloading the PDF file to disk. We pass NO for
       
   979     // showingPanel: so that the PDF file is saved to the standard location without user intervention.
       
   980     CallUIDelegate([self _webView], @selector(webView:saveFrameView:showingPanel:), [[dataSource webFrame] frameView], NO);
       
   981 }
       
   982 
       
   983 @end
       
   984 
       
   985 @implementation WebPDFView (FileInternal)
       
   986 
       
   987 + (Class)_PDFPreviewViewClass
       
   988 {
       
   989     static Class PDFPreviewViewClass = nil;
       
   990     static BOOL checkedForPDFPreviewViewClass = NO;
       
   991     
       
   992     if (!checkedForPDFPreviewViewClass) {
       
   993         checkedForPDFPreviewViewClass = YES;
       
   994         PDFPreviewViewClass = [[WebPDFView PDFKitBundle] classNamed:@"PDFPreviewView"];
       
   995     }
       
   996     
       
   997     // This class might not be available; callers need to deal with a nil return here.
       
   998     return PDFPreviewViewClass;
       
   999 }
       
  1000 
       
  1001 + (Class)_PDFViewClass
       
  1002 {
       
  1003     static Class PDFViewClass = nil;
       
  1004     if (PDFViewClass == nil) {
       
  1005         PDFViewClass = [[WebPDFView PDFKitBundle] classNamed:@"PDFView"];
       
  1006         if (!PDFViewClass)
       
  1007             LOG_ERROR("Couldn't find PDFView class in PDFKit.framework");
       
  1008     }
       
  1009     return PDFViewClass;
       
  1010 }
       
  1011 
       
  1012 - (BOOL)_anyPDFTagsFoundInMenu:(NSMenu *)menu
       
  1013 {
       
  1014     NSEnumerator *e = [[menu itemArray] objectEnumerator];
       
  1015     NSMenuItem *item;
       
  1016     while ((item = [e nextObject]) != nil) {
       
  1017         switch ([item tag]) {
       
  1018             case WebMenuItemTagOpenWithDefaultApplication:
       
  1019             case WebMenuItemPDFActualSize:
       
  1020             case WebMenuItemPDFZoomIn:
       
  1021             case WebMenuItemPDFZoomOut:
       
  1022             case WebMenuItemPDFAutoSize:
       
  1023             case WebMenuItemPDFSinglePage:
       
  1024             case WebMenuItemPDFSinglePageScrolling:
       
  1025             case WebMenuItemPDFFacingPages:
       
  1026             case WebMenuItemPDFFacingPagesScrolling:
       
  1027             case WebMenuItemPDFContinuous:
       
  1028             case WebMenuItemPDFNextPage:
       
  1029             case WebMenuItemPDFPreviousPage:
       
  1030                 return YES;
       
  1031         }
       
  1032     }
       
  1033     return NO;
       
  1034 }
       
  1035 
       
  1036 - (void)_applyPDFDefaults
       
  1037 {
       
  1038     // Set up default viewing params
       
  1039     WebPreferences *prefs = [[dataSource _webView] preferences];
       
  1040     float scaleFactor = [prefs PDFScaleFactor];
       
  1041     if (scaleFactor == 0)
       
  1042         [PDFSubview setAutoScales:YES];
       
  1043     else {
       
  1044         [PDFSubview setAutoScales:NO];
       
  1045         [PDFSubview setScaleFactor:scaleFactor];
       
  1046     }
       
  1047     [PDFSubview setDisplayMode:[prefs PDFDisplayMode]];
       
  1048 }
       
  1049 
       
  1050 - (BOOL)_canLookUpInDictionary
       
  1051 {
       
  1052     return [PDFSubview respondsToSelector:@selector(_searchInDictionary:)];
       
  1053 }
       
  1054 
       
  1055 - (NSClipView *)_clipViewForPDFDocumentView
       
  1056 {
       
  1057     NSClipView *clipView = (NSClipView *)[[PDFSubview documentView] _web_superviewOfClass:[NSClipView class]];
       
  1058     ASSERT(clipView);
       
  1059     return clipView;
       
  1060 }
       
  1061 
       
  1062 - (NSEvent *)_fakeKeyEventWithFunctionKey:(unichar)functionKey
       
  1063 {
       
  1064     // FIXME 4400480: when PDFView implements the standard scrolling selectors that this
       
  1065     // method is used to mimic, we can eliminate this method and call them directly.
       
  1066     NSString *keyAsString = [NSString stringWithCharacters:&functionKey length:1];
       
  1067     return [NSEvent keyEventWithType:NSKeyDown
       
  1068                             location:NSZeroPoint
       
  1069                        modifierFlags:0
       
  1070                            timestamp:0
       
  1071                         windowNumber:0
       
  1072                              context:nil
       
  1073                           characters:keyAsString
       
  1074          charactersIgnoringModifiers:keyAsString
       
  1075                            isARepeat:NO
       
  1076                              keyCode:0];
       
  1077 }
       
  1078 
       
  1079 - (void)_lookUpInDictionaryFromMenu:(id)sender
       
  1080 {
       
  1081     // This method is used by WebKit's context menu item. Here we map to the method that
       
  1082     // PDFView uses. Since the PDFView method isn't API, and isn't available on all versions
       
  1083     // of PDFKit, we use performSelector after a respondsToSelector check, rather than calling it directly.
       
  1084     if ([self _canLookUpInDictionary])
       
  1085         [PDFSubview performSelector:@selector(_searchInDictionary:) withObject:sender];
       
  1086 }
       
  1087 
       
  1088 - (NSMutableArray *)_menuItemsFromPDFKitForEvent:(NSEvent *)theEvent
       
  1089 {
       
  1090     NSMutableArray *copiedItems = [NSMutableArray array];
       
  1091     NSDictionary *actionsToTags = [[NSDictionary alloc] initWithObjectsAndKeys:
       
  1092         [NSNumber numberWithInt:WebMenuItemPDFActualSize], NSStringFromSelector(@selector(_setActualSize:)),
       
  1093         [NSNumber numberWithInt:WebMenuItemPDFZoomIn], NSStringFromSelector(@selector(zoomIn:)),
       
  1094         [NSNumber numberWithInt:WebMenuItemPDFZoomOut], NSStringFromSelector(@selector(zoomOut:)),
       
  1095         [NSNumber numberWithInt:WebMenuItemPDFAutoSize], NSStringFromSelector(@selector(_setAutoSize:)),
       
  1096         [NSNumber numberWithInt:WebMenuItemPDFSinglePage], NSStringFromSelector(@selector(_setSinglePage:)),
       
  1097         [NSNumber numberWithInt:WebMenuItemPDFSinglePageScrolling], NSStringFromSelector(@selector(_setSinglePageScrolling:)),
       
  1098         [NSNumber numberWithInt:WebMenuItemPDFFacingPages], NSStringFromSelector(@selector(_setDoublePage:)),
       
  1099         [NSNumber numberWithInt:WebMenuItemPDFFacingPagesScrolling], NSStringFromSelector(@selector(_setDoublePageScrolling:)),
       
  1100         [NSNumber numberWithInt:WebMenuItemPDFContinuous], NSStringFromSelector(@selector(_toggleContinuous:)),
       
  1101         [NSNumber numberWithInt:WebMenuItemPDFNextPage], NSStringFromSelector(@selector(goToNextPage:)),
       
  1102         [NSNumber numberWithInt:WebMenuItemPDFPreviousPage], NSStringFromSelector(@selector(goToPreviousPage:)),
       
  1103         nil];
       
  1104     
       
  1105     // Leave these menu items out, since WebKit inserts equivalent ones. Note that we leave out PDFKit's "Look Up in Dictionary"
       
  1106     // item here because WebKit already includes an item with the same title and purpose. We map WebKit's to PDFKit's 
       
  1107     // "Look Up in Dictionary" via the implementation of -[WebPDFView _lookUpInDictionaryFromMenu:].
       
  1108     NSSet *unwantedActions = [[NSSet alloc] initWithObjects:
       
  1109                               NSStringFromSelector(@selector(_searchInSpotlight:)),
       
  1110                               NSStringFromSelector(@selector(_searchInGoogle:)),
       
  1111                               NSStringFromSelector(@selector(_searchInDictionary:)),
       
  1112                               NSStringFromSelector(@selector(copy:)),
       
  1113                               nil];
       
  1114     
       
  1115     NSEnumerator *e = [[[PDFSubview menuForEvent:theEvent] itemArray] objectEnumerator];
       
  1116     NSMenuItem *item;
       
  1117     while ((item = [e nextObject]) != nil) {
       
  1118         
       
  1119         NSString *actionString = NSStringFromSelector([item action]);
       
  1120         
       
  1121         if ([unwantedActions containsObject:actionString])
       
  1122             continue;
       
  1123         
       
  1124         // Copy items since a menu item can be in only one menu at a time, and we don't
       
  1125         // want to modify the original menu supplied by PDFKit.
       
  1126         NSMenuItem *itemCopy = [item copy];
       
  1127         [copiedItems addObject:itemCopy];
       
  1128         
       
  1129         // Include all of PDFKit's separators for now. At the end we'll remove any ones that were made
       
  1130         // useless by removing PDFKit's menu items.
       
  1131         if ([itemCopy isSeparatorItem])
       
  1132             continue;
       
  1133 
       
  1134         NSNumber *tagNumber = [actionsToTags objectForKey:actionString];
       
  1135         
       
  1136         int tag;
       
  1137         if (tagNumber != nil)
       
  1138             tag = [tagNumber intValue];
       
  1139         else {
       
  1140             // This should happen only if PDFKit updates behind WebKit's back. It's non-ideal because clients that only include tags
       
  1141             // that they recognize (like Safari) won't get these PDFKit additions until WebKit is updated to match.
       
  1142             tag = WebMenuItemTagOther;
       
  1143             LOG_ERROR("no WebKit menu item tag found for PDF context menu item action \"%@\", using WebMenuItemTagOther", actionString);
       
  1144         }
       
  1145         
       
  1146         if ([itemCopy tag] == 0) {
       
  1147             [itemCopy setTag:tag];
       
  1148             if ([itemCopy target] == PDFSubview) {
       
  1149                 // Note that updating the defaults is cheap because it catches redundant settings, so installing
       
  1150                 // the proxy for actions that don't impact the defaults is OK
       
  1151                 [itemCopy setTarget:PDFSubviewProxy];
       
  1152             }
       
  1153         } else
       
  1154             LOG_ERROR("PDF context menu item %@ came with tag %d, so no WebKit tag was applied. This could mean that the item doesn't appear in clients such as Safari.", [itemCopy title], [itemCopy tag]);
       
  1155     }
       
  1156     
       
  1157     [actionsToTags release];
       
  1158     [unwantedActions release];
       
  1159     
       
  1160     // Since we might have removed elements supplied by PDFKit, and we want to minimize our hardwired
       
  1161     // knowledge of the order and arrangement of PDFKit's menu items, we need to remove any bogus
       
  1162     // separators that were left behind.
       
  1163     [copiedItems _webkit_removeUselessMenuItemSeparators];
       
  1164     
       
  1165     return copiedItems;
       
  1166 }
       
  1167 
       
  1168 - (PDFSelection *)_nextMatchFor:(NSString *)string direction:(BOOL)forward caseSensitive:(BOOL)caseFlag wrap:(BOOL)wrapFlag fromSelection:(PDFSelection *)initialSelection startInSelection:(BOOL)startInSelection
       
  1169 {
       
  1170     if (![string length])
       
  1171         return nil;
       
  1172     
       
  1173     int options = 0;
       
  1174     if (!forward)
       
  1175         options |= NSBackwardsSearch;
       
  1176     
       
  1177     if (!caseFlag)
       
  1178         options |= NSCaseInsensitiveSearch;
       
  1179     
       
  1180     PDFDocument *document = [PDFSubview document];
       
  1181     
       
  1182     PDFSelection *selectionForInitialSearch = [initialSelection copy];
       
  1183     if (startInSelection) {
       
  1184         // Initially we want to include the selected text in the search. PDFDocument's API always searches from just
       
  1185         // past the passed-in selection, so we need to pass a selection that's modified appropriately. 
       
  1186         // FIXME 4182863: Ideally we'd use a zero-length selection at the edge of the current selection, but zero-length
       
  1187         // selections don't work in PDFDocument. So instead we make a one-length selection just before or after the
       
  1188         // current selection, which works for our purposes even when the current selection is at an edge of the
       
  1189         // document.
       
  1190         int initialSelectionLength = [[initialSelection string] length];
       
  1191         if (forward) {
       
  1192             [selectionForInitialSearch extendSelectionAtStart:1];
       
  1193             [selectionForInitialSearch extendSelectionAtEnd:-initialSelectionLength];
       
  1194         } else {
       
  1195             [selectionForInitialSearch extendSelectionAtEnd:1];
       
  1196             [selectionForInitialSearch extendSelectionAtStart:-initialSelectionLength];
       
  1197         }
       
  1198     }
       
  1199     PDFSelection *foundSelection = [document findString:string fromSelection:selectionForInitialSearch withOptions:options];
       
  1200     [selectionForInitialSearch release];
       
  1201 
       
  1202     // If we first searched in the selection, and we found the selection, search again from just past the selection
       
  1203     if (startInSelection && _PDFSelectionsAreEqual(foundSelection, initialSelection))
       
  1204         foundSelection = [document findString:string fromSelection:initialSelection withOptions:options];
       
  1205     
       
  1206     if (!foundSelection && wrapFlag)
       
  1207         foundSelection = [document findString:string fromSelection:nil withOptions:options];
       
  1208     
       
  1209     return foundSelection;
       
  1210 }
       
  1211 
       
  1212 - (void)_openWithFinder:(id)sender
       
  1213 {
       
  1214     // We don't want to write the file until we have a document to write (see 4892525).
       
  1215     if (![PDFSubview document]) {
       
  1216         NSBeep();
       
  1217         return;
       
  1218     }
       
  1219     
       
  1220     NSString *opath = [self _path];
       
  1221     
       
  1222     if (opath) {
       
  1223         if (!written) {
       
  1224             // Create a PDF file with the minimal permissions (only accessible to the current user, see 4145714)
       
  1225             NSNumber *permissions = [[NSNumber alloc] initWithInt:S_IRUSR];
       
  1226             NSDictionary *fileAttributes = [[NSDictionary alloc] initWithObjectsAndKeys:permissions, NSFilePosixPermissions, nil];
       
  1227             [permissions release];
       
  1228 
       
  1229             [[NSFileManager defaultManager] createFileAtPath:opath contents:[dataSource data] attributes:fileAttributes];
       
  1230             
       
  1231             [fileAttributes release];
       
  1232             written = YES;
       
  1233         }
       
  1234         
       
  1235         if (![[NSWorkspace sharedWorkspace] openFile:opath]) {
       
  1236             // NSWorkspace couldn't open file.  Do we need an alert
       
  1237             // here?  We ignore the error elsewhere.
       
  1238         }
       
  1239     }
       
  1240 }
       
  1241 
       
  1242 - (NSString *)_path
       
  1243 {
       
  1244     // Generate path once.
       
  1245     if (path)
       
  1246         return path;
       
  1247     
       
  1248     NSString *filename = [[dataSource response] suggestedFilename];
       
  1249     NSFileManager *manager = [NSFileManager defaultManager]; 
       
  1250     NSString *temporaryPDFDirectoryPath = [self _temporaryPDFDirectoryPath];
       
  1251     
       
  1252     if (!temporaryPDFDirectoryPath) {
       
  1253         // This should never happen; if it does we'll fail silently on non-debug builds.
       
  1254         ASSERT_NOT_REACHED();
       
  1255         return nil;
       
  1256     }
       
  1257     
       
  1258     path = [temporaryPDFDirectoryPath stringByAppendingPathComponent:filename];
       
  1259     if ([manager fileExistsAtPath:path]) {
       
  1260         NSString *pathTemplatePrefix = [temporaryPDFDirectoryPath stringByAppendingPathComponent:@"XXXXXX-"];
       
  1261         NSString *pathTemplate = [pathTemplatePrefix stringByAppendingString:filename];
       
  1262         // fileSystemRepresentation returns a const char *; copy it into a char * so we can modify it safely
       
  1263         char *cPath = strdup([pathTemplate fileSystemRepresentation]);
       
  1264         int fd = mkstemps(cPath, strlen(cPath) - strlen([pathTemplatePrefix fileSystemRepresentation]) + 1);
       
  1265         if (fd < 0) {
       
  1266             // Couldn't create a temporary file! Should never happen; if it does we'll fail silently on non-debug builds.
       
  1267             ASSERT_NOT_REACHED();
       
  1268             path = nil;
       
  1269         } else {
       
  1270             close(fd);
       
  1271             path = [manager stringWithFileSystemRepresentation:cPath length:strlen(cPath)];
       
  1272         }
       
  1273         free(cPath);
       
  1274     }
       
  1275     
       
  1276     [path retain];
       
  1277     
       
  1278     return path;
       
  1279 }
       
  1280 
       
  1281 - (void)_PDFDocumentViewMightHaveScrolled:(NSNotification *)notification
       
  1282 { 
       
  1283     NSClipView *clipView = [self _clipViewForPDFDocumentView];
       
  1284     ASSERT([notification object] == clipView);
       
  1285     
       
  1286     NSPoint scrollPosition = [clipView bounds].origin;
       
  1287     if (NSEqualPoints(scrollPosition, lastScrollPosition))
       
  1288         return;
       
  1289     
       
  1290     lastScrollPosition = scrollPosition;
       
  1291     WebView *webView = [self _webView];
       
  1292     [[webView _UIDelegateForwarder] webView:webView didScrollDocumentInFrameView:[[dataSource webFrame] frameView]];
       
  1293 }
       
  1294 
       
  1295 - (PDFView *)_PDFSubview
       
  1296 {
       
  1297     return PDFSubview;
       
  1298 }
       
  1299 
       
  1300 - (BOOL)_pointIsInSelection:(NSPoint)point
       
  1301 {
       
  1302     PDFPage *page = [PDFSubview pageForPoint:point nearest:NO];
       
  1303     if (!page)
       
  1304         return NO;
       
  1305     
       
  1306     NSRect selectionRect = [PDFSubview convertRect:[[PDFSubview currentSelection] boundsForPage:page] fromPage:page];
       
  1307     
       
  1308     return NSPointInRect(point, selectionRect);
       
  1309 }
       
  1310 
       
  1311 - (void)_scaleOrDisplayModeOrPageChanged:(NSNotification *)notification
       
  1312 {
       
  1313     ASSERT([notification object] == PDFSubview);
       
  1314     if (!_ignoreScaleAndDisplayModeAndPageNotifications) {
       
  1315         [self _updatePreferencesSoon];
       
  1316         // Notify UI delegate that the entire page has been redrawn, since (unlike for WebHTMLView)
       
  1317         // we can't hook into the drawing mechanism itself. This fixes 5337529.
       
  1318         WebView *webView = [self _webView];
       
  1319         [[webView _UIDelegateForwarder] webView:webView didDrawRect:[webView bounds]];
       
  1320     }
       
  1321 }
       
  1322 
       
  1323 - (NSAttributedString *)_scaledAttributedString:(NSAttributedString *)unscaledAttributedString
       
  1324 {
       
  1325     if (!unscaledAttributedString)
       
  1326         return nil;
       
  1327     
       
  1328     float scaleFactor = [PDFSubview scaleFactor];
       
  1329     if (scaleFactor == 1.0)
       
  1330         return unscaledAttributedString;
       
  1331     
       
  1332     NSMutableAttributedString *result = [[unscaledAttributedString mutableCopy] autorelease];
       
  1333     unsigned int length = [result length];
       
  1334     NSRange effectiveRange = NSMakeRange(0,0);
       
  1335     
       
  1336     [result beginEditing];    
       
  1337     while (NSMaxRange(effectiveRange) < length) {
       
  1338         NSFont *unscaledFont = [result attribute:NSFontAttributeName atIndex:NSMaxRange(effectiveRange) effectiveRange:&effectiveRange];
       
  1339         
       
  1340         if (!unscaledFont) {
       
  1341             // FIXME: We can't scale the font if we don't know what it is. We should always know what it is,
       
  1342             // but sometimes don't due to PDFKit issue 5089411. When that's addressed, we can remove this
       
  1343             // early continue.
       
  1344             LOG_ERROR("no font attribute found in range %@ for attributed string \"%@\" on page %@ (see radar 5089411)", NSStringFromRange(effectiveRange), result, [[dataSource request] URL]);
       
  1345             continue;
       
  1346         }
       
  1347         
       
  1348         NSFont *scaledFont = [NSFont fontWithName:[unscaledFont fontName] size:[unscaledFont pointSize]*scaleFactor];
       
  1349         [result addAttribute:NSFontAttributeName value:scaledFont range:effectiveRange];
       
  1350     }
       
  1351     [result endEditing];
       
  1352     
       
  1353     return result;
       
  1354 }
       
  1355 
       
  1356 - (void)_setTextMatches:(NSArray *)array
       
  1357 {
       
  1358     [array retain];
       
  1359     [textMatches release];
       
  1360     textMatches = array;
       
  1361 }
       
  1362 
       
  1363 - (NSString *)_temporaryPDFDirectoryPath
       
  1364 {
       
  1365     // Returns nil if the temporary PDF directory didn't exist and couldn't be created
       
  1366     
       
  1367     static NSString *_temporaryPDFDirectoryPath = nil;
       
  1368     
       
  1369     if (!_temporaryPDFDirectoryPath) {
       
  1370         NSString *temporaryDirectoryTemplate = [NSTemporaryDirectory() stringByAppendingPathComponent:@"WebKitPDFs-XXXXXX"];
       
  1371         char *cTemplate = strdup([temporaryDirectoryTemplate fileSystemRepresentation]);
       
  1372         
       
  1373         if (!mkdtemp(cTemplate)) {
       
  1374             // This should never happen; if it does we'll fail silently on non-debug builds.
       
  1375             ASSERT_NOT_REACHED();
       
  1376         } else {
       
  1377             // cTemplate has now been modified to be the just-created directory name. This directory has 700 permissions,
       
  1378             // so only the current user can add to it or view its contents.
       
  1379             _temporaryPDFDirectoryPath = [[[NSFileManager defaultManager] stringWithFileSystemRepresentation:cTemplate length:strlen(cTemplate)] retain];
       
  1380         }
       
  1381         
       
  1382         free(cTemplate);
       
  1383     }
       
  1384     
       
  1385     return _temporaryPDFDirectoryPath;
       
  1386 }
       
  1387 
       
  1388 - (void)_trackFirstResponder
       
  1389 {
       
  1390     ASSERT([self window]);
       
  1391     
       
  1392     id newFirstResponder = [[self window] firstResponder];
       
  1393     if (newFirstResponder == trackedFirstResponder)
       
  1394         return;
       
  1395     
       
  1396     // This next clause is the entire purpose of _trackFirstResponder. In other WebDocument
       
  1397     // view classes this is done in a resignFirstResponder override, but in this case the
       
  1398     // first responder view is a PDFKit class that we can't subclass.
       
  1399     if (trackedFirstResponder == [PDFSubview documentView] && ![[dataSource _webView] maintainsInactiveSelection])
       
  1400         [self deselectAll];
       
  1401     
       
  1402     
       
  1403     [trackedFirstResponder release];
       
  1404     trackedFirstResponder = [newFirstResponder retain];
       
  1405 }
       
  1406 
       
  1407 - (void)_updatePreferences:(WebPreferences *)prefs
       
  1408 {
       
  1409     float scaleFactor = [PDFSubview autoScales] ? 0.0f : [PDFSubview scaleFactor];
       
  1410     [prefs setPDFScaleFactor:scaleFactor];
       
  1411     [prefs setPDFDisplayMode:[PDFSubview displayMode]];
       
  1412     _willUpdatePreferencesSoon = NO;
       
  1413     [prefs release];
       
  1414     [self release];
       
  1415 }
       
  1416 
       
  1417 - (void)_updatePreferencesSoon
       
  1418 {   
       
  1419     // Consolidate calls; due to the PDFPrefUpdatingProxy method, this can be called multiple times with a single user action
       
  1420     // such as showing the context menu.
       
  1421     if (_willUpdatePreferencesSoon)
       
  1422         return;
       
  1423 
       
  1424     WebPreferences *prefs = [[dataSource _webView] preferences];
       
  1425 
       
  1426     [self retain];
       
  1427     [prefs retain];
       
  1428     [self performSelector:@selector(_updatePreferences:) withObject:prefs afterDelay:0];
       
  1429     _willUpdatePreferencesSoon = YES;
       
  1430 }
       
  1431 
       
  1432 - (NSSet *)_visiblePDFPages
       
  1433 {
       
  1434     // Returns the set of pages that are at least partly visible, used to avoid processing non-visible pages
       
  1435     PDFDocument *pdfDocument = [PDFSubview document];
       
  1436     if (!pdfDocument)
       
  1437         return nil;
       
  1438     
       
  1439     NSRect pdfViewBounds = [PDFSubview bounds];
       
  1440     PDFPage *topLeftPage = [PDFSubview pageForPoint:NSMakePoint(NSMinX(pdfViewBounds), NSMaxY(pdfViewBounds)) nearest:YES];
       
  1441     PDFPage *bottomRightPage = [PDFSubview pageForPoint:NSMakePoint(NSMaxX(pdfViewBounds), NSMinY(pdfViewBounds)) nearest:YES];
       
  1442     
       
  1443     // only page-free documents should return nil for either of these two since we passed YES for nearest:
       
  1444     if (!topLeftPage) {
       
  1445         ASSERT(!bottomRightPage);
       
  1446         return nil;
       
  1447     }
       
  1448     
       
  1449     NSUInteger firstVisiblePageIndex = [pdfDocument indexForPage:topLeftPage];
       
  1450     NSUInteger lastVisiblePageIndex = [pdfDocument indexForPage:bottomRightPage];
       
  1451     
       
  1452     if (firstVisiblePageIndex > lastVisiblePageIndex) {
       
  1453         NSUInteger swap = firstVisiblePageIndex;
       
  1454         firstVisiblePageIndex = lastVisiblePageIndex;
       
  1455         lastVisiblePageIndex = swap;
       
  1456     }
       
  1457     
       
  1458     NSMutableSet *result = [NSMutableSet set];
       
  1459     NSUInteger pageIndex;
       
  1460     for (pageIndex = firstVisiblePageIndex; pageIndex <= lastVisiblePageIndex; ++pageIndex)
       
  1461         [result addObject:[pdfDocument pageAtIndex:pageIndex]];
       
  1462 
       
  1463     return result;
       
  1464 }
       
  1465 
       
  1466 @end
       
  1467 
       
  1468 @implementation PDFPrefUpdatingProxy
       
  1469 
       
  1470 - (id)initWithView:(WebPDFView *)aView
       
  1471 {
       
  1472     // No [super init], since we inherit from NSProxy
       
  1473     view = aView;
       
  1474     return self;
       
  1475 }
       
  1476 
       
  1477 - (void)forwardInvocation:(NSInvocation *)invocation
       
  1478 {
       
  1479     [invocation invokeWithTarget:[view _PDFSubview]];    
       
  1480     [view _updatePreferencesSoon];
       
  1481 }
       
  1482 
       
  1483 - (NSMethodSignature *)methodSignatureForSelector:(SEL)sel
       
  1484 {
       
  1485     return [[view _PDFSubview] methodSignatureForSelector:sel];
       
  1486 }
       
  1487 
       
  1488 @end