WebBaseNetscapePluginView.m 60.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
/*
 * Copyright (C) 2005 Apple Computer, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1.  Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer. 
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution. 
 * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
 *     its contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission. 
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
cblu's avatar
cblu committed
28

29
#import <WebKit/WebBaseNetscapePluginView.h>
darin's avatar
darin committed
30

31
#import <WebKit/WebAssertions.h>
darin's avatar
darin committed
32
#import <WebKit/WebBridge.h>
33
#import <WebKit/WebDataSource.h>
rjw's avatar
WebKit:  
rjw committed
34
#import <WebKit/WebDefaultUIDelegate.h>
35
#import <WebKit/WebFrameInternal.h> 
rjw's avatar
WebKit:  
rjw committed
36
#import <WebKit/WebFrameView.h>
37
#import <WebKit/WebKitLogging.h>
38
#import <WebKit/WebKitNSStringExtras.h>
39
#import <WebKit/WebNetscapePluginStream.h>
40
#import <WebKit/WebNullPluginView.h>
mjs's avatar
mjs committed
41
#import <WebKit/WebNSDataExtras.h>
mjs's avatar
mjs committed
42
#import <WebKit/WebNSDictionaryExtras.h>
43
#import <WebKit/WebNSObjectExtras.h>
kocienda's avatar
WebKit:  
kocienda committed
44
#import <WebKit/WebNSURLExtras.h>
mjs's avatar
mjs committed
45
#import <WebKit/WebNSURLRequestExtras.h>
46
#import <WebKit/WebNSViewExtras.h>
47
#import <WebKit/WebNetscapePluginPackage.h>
48
#import <WebKit/WebPreferences.h>
rjw's avatar
WebKit:  
rjw committed
49
#import <WebKit/WebViewPrivate.h>
rjw's avatar
WebKit:  
rjw committed
50
#import <WebKit/WebUIDelegate.h>
mjs's avatar
mjs committed
51
#import <WebKitSystemInterface.h>
52

cblu's avatar
 
cblu committed
53 54
#import <Carbon/Carbon.h>

justing's avatar
justing committed
55 56
#import <objc/objc-runtime.h>

57 58
// Send null events 50 times a second when active, so plug-ins like Flash get high frame rates.
#define NullEventIntervalActive 	0.02
59 60
#define NullEventIntervalNotActive	0.25

61 62
#define LoginWindowDidSwitchFromUserNotification    @"WebLoginWindowDidSwitchFromUserNotification"
#define LoginWindowDidSwitchToUserNotification      @"WebLoginWindowDidSwitchToUserNotification"
63 64


cblu's avatar
cblu committed
65 66
static WebBaseNetscapePluginView *currentPluginView = nil;

kocienda's avatar
kocienda committed
67 68 69 70 71 72 73 74 75
typedef struct {
    GrafPtr oldPort;
    Point oldOrigin;
    RgnHandle oldClipRegion;
    RgnHandle oldVisibleRegion;
    RgnHandle clipRegion;
    BOOL forUpdate;
} PortState;

darin's avatar
darin committed
76 77
@interface WebPluginRequest : NSObject
{
kocienda's avatar
Tests:  
kocienda committed
78
    NSURLRequest *_request;
mjs's avatar
mjs committed
79
    NSString *_frameName;
darin's avatar
darin committed
80
    void *_notifyData;
kdecker's avatar
kdecker committed
81
    BOOL _didStartFromUserGesture;
82
    BOOL _sendNotification;
darin's avatar
darin committed
83 84
}

kdecker's avatar
kdecker committed
85
- (id)initWithRequest:(NSURLRequest *)request frameName:(NSString *)frameName notifyData:(void *)notifyData sendNotification:(BOOL)sendNotification didStartFromUserGesture:(BOOL)currentEventIsUserGesture;
darin's avatar
darin committed
86

kocienda's avatar
Tests:  
kocienda committed
87
- (NSURLRequest *)request;
mjs's avatar
mjs committed
88
- (NSString *)frameName;
darin's avatar
darin committed
89
- (void *)notifyData;
kdecker's avatar
kdecker committed
90
- (BOOL)isCurrentEventUserGesture;
91
- (BOOL)sendNotification;
darin's avatar
darin committed
92 93 94

@end

95 96 97
@interface NSData (WebPluginDataExtras)
- (BOOL)_web_startsWithBlankLine;
- (unsigned)_web_locationAfterFirstBlankLine;
cblu's avatar
cblu committed
98 99
@end

100
static OSStatus TSMEventHandler(EventHandlerCallRef inHandlerRef, EventRef inEvent, void *pluginView);
cblu's avatar
cblu committed
101

102 103 104 105
@interface WebBaseNetscapePluginView (ForwardDeclarations)
- (void)setWindowIfNecessary;
@end

106
@implementation WebBaseNetscapePluginView
107

108 109
+ (void)initialize
{
mjs's avatar
mjs committed
110
	WKSendUserChangeNotifications();
111 112
}

darin's avatar
darin committed
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
#pragma mark EVENTS

+ (void)getCarbonEvent:(EventRecord *)carbonEvent
{
    carbonEvent->what = nullEvent;
    carbonEvent->message = 0;
    carbonEvent->when = TickCount();
    GetGlobalMouse(&carbonEvent->where);
    carbonEvent->modifiers = GetCurrentKeyModifiers();
    if (!Button())
        carbonEvent->modifiers |= btnState;
}

- (void)getCarbonEvent:(EventRecord *)carbonEvent
{
    [[self class] getCarbonEvent:carbonEvent];
}

cblu's avatar
cblu committed
131
- (EventModifiers)modifiersForEvent:(NSEvent *)event
darin's avatar
darin committed
132 133 134
{
    EventModifiers modifiers;
    unsigned int modifierFlags = [event modifierFlags];
cblu's avatar
cblu committed
135
    NSEventType eventType = [event type];
darin's avatar
darin committed
136 137 138
    
    modifiers = 0;
    
cblu's avatar
cblu committed
139
    if (eventType != NSLeftMouseDown && eventType != NSRightMouseDown)
darin's avatar
darin committed
140 141 142 143 144 145 146 147 148 149 150 151 152 153
        modifiers |= btnState;
    
    if (modifierFlags & NSCommandKeyMask)
        modifiers |= cmdKey;
    
    if (modifierFlags & NSShiftKeyMask)
        modifiers |= shiftKey;

    if (modifierFlags & NSAlphaShiftKeyMask)
        modifiers |= alphaLock;

    if (modifierFlags & NSAlternateKeyMask)
        modifiers |= optionKey;

cblu's avatar
cblu committed
154
    if (modifierFlags & NSControlKeyMask || eventType == NSRightMouseDown)
darin's avatar
darin committed
155
        modifiers |= controlKey;
cblu's avatar
cblu committed
156
    
darin's avatar
darin committed
157 158 159
    return modifiers;
}

cblu's avatar
cblu committed
160
- (void)getCarbonEvent:(EventRecord *)carbonEvent withEvent:(NSEvent *)cocoaEvent
darin's avatar
darin committed
161
{
mjs's avatar
mjs committed
162
    if (WKConvertNSEventToCarbonEvent(carbonEvent, cocoaEvent)) {
cblu's avatar
cblu committed
163 164
        return;
    }
165 166 167 168 169 170 171 172 173
    
    NSPoint where = [[cocoaEvent window] convertBaseToScreen:[cocoaEvent locationInWindow]];
        
    carbonEvent->what = nullEvent;
    carbonEvent->message = 0;
    carbonEvent->when = (UInt32)([cocoaEvent timestamp] * 60); // seconds to ticks
    carbonEvent->where.h = (short)where.x;
    carbonEvent->where.v = (short)(NSMaxY([[[NSScreen screens] objectAtIndex:0] frame]) - where.y);
    carbonEvent->modifiers = [self modifiersForEvent:cocoaEvent];
darin's avatar
darin committed
174 175
}

176 177 178 179 180 181 182 183 184 185 186 187
- (BOOL)superviewsHaveSuperviews
{
    NSView *contentView = [[self window] contentView];
    NSView *view;
    for (view = self; view != nil; view = [view superview]) { 
        if (view == contentView) {
            return YES;
        }
    }
    return NO;
}

justing's avatar
justing committed
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
// The WindowRef created by -[NSWindow windowRef] has a QuickDraw GrafPort that covers 
// the entire window frame (or structure region to use the Carbon term) rather then just the window content.
// We can remove this when <rdar://problem/4201099> is fixed.
- (void)fixWindowPort
{
    NSWindow *currentWindow = [self currentWindow];
    if ([currentWindow isKindOfClass:objc_getClass("NSCarbonWindow")])
        return;
    
    float windowHeight = [currentWindow frame].size.height;
    NSView *contentView = [currentWindow contentView];
    NSRect contentRect = [contentView convertRect:[contentView frame] toView:nil]; // convert to window-relative coordinates
    
    CGrafPtr oldPort;
    GetPort(&oldPort);    
    SetPort(GetWindowPort([currentWindow windowRef]));
    
    MovePortTo(contentRect.origin.x, /* Flip Y */ windowHeight - NSMaxY(contentRect));
    PortSize(contentRect.size.width, contentRect.size.height);
    
    SetPort(oldPort);
}

kocienda's avatar
kocienda committed
211 212
- (PortState)saveAndSetPortStateForUpdate:(BOOL)forUpdate
{
213
    ASSERT([self currentWindow] != nil);
justing's avatar
justing committed
214 215 216
 
    [self fixWindowPort];
   
217
    WindowRef windowRef = [[self currentWindow] windowRef];
kocienda's avatar
kocienda committed
218
    CGrafPtr port = GetWindowPort(windowRef);
justing's avatar
justing committed
219
        
darin's avatar
darin committed
220 221 222 223
    Rect portBounds;
    GetPortBounds(port, &portBounds);

    // Use AppKit to convert view coordinates to NSWindow coordinates.
kocienda's avatar
kocienda committed
224 225 226
    NSRect boundsInWindow = [self convertRect:[self bounds] toView:nil];
    NSRect visibleRectInWindow = [self convertRect:[self visibleRect] toView:nil];
    
darin's avatar
darin committed
227
    // Flip Y to convert NSWindow coordinates to top-left-based window coordinates.
228
    float borderViewHeight = [[self currentWindow] frame].size.height;
darin's avatar
darin committed
229 230 231 232 233 234 235 236 237
    boundsInWindow.origin.y = borderViewHeight - NSMaxY(boundsInWindow);
    visibleRectInWindow.origin.y = borderViewHeight - NSMaxY(visibleRectInWindow);
    
    // Look at the Carbon port to convert top-left-based window coordinates into top-left-based content coordinates.
    PixMap *pix = *GetPortPixMap(port);
    boundsInWindow.origin.x += pix->bounds.left - portBounds.left;
    boundsInWindow.origin.y += pix->bounds.top - portBounds.top;
    visibleRectInWindow.origin.x += pix->bounds.left - portBounds.left;
    visibleRectInWindow.origin.y += pix->bounds.top - portBounds.top;
kocienda's avatar
kocienda committed
238 239 240 241 242 243 244 245 246 247 248
    
    // Set up NS_Port.
    nPort.port = port;
    nPort.portx = (int32)-boundsInWindow.origin.x;
    nPort.porty = (int32)-boundsInWindow.origin.y;
    
    // Set up NPWindow.
    window.window = &nPort;
    
    window.x = (int32)boundsInWindow.origin.x; 
    window.y = (int32)boundsInWindow.origin.y;
darin's avatar
darin committed
249 250
    window.width = NSWidth(boundsInWindow);
    window.height = NSHeight(boundsInWindow);
251 252 253 254 255 256 257
    
    // "Clip-out" the plug-in when:
    // 1) it's not really in a window or off-screen or has no height or width.
    // 2) window.x is a "big negative number" which is how WebCore expresses off-screen widgets.
    // 3) the window is miniaturized or the app is hidden
    // 4) we're inside of viewWillMoveToWindow: with a nil window. In this case, superviews may already have nil 
    // superviews and nil windows and results from convertRect:toView: are incorrect.
258
    NSWindow *realWindow = [self window];
darin's avatar
darin committed
259 260 261 262 263
    if (window.width <= 0 || window.height <= 0 || window.x < -100000
            || realWindow == nil || [realWindow isMiniaturized]
            || [NSApp isHidden]
            || ![self superviewsHaveSuperviews]
            || [self isHiddenOrHasHiddenAncestor]) {
darin's avatar
darin committed
264 265 266 267 268 269 270 271 272 273 274 275 276 277
        // The following code tries to give plug-ins the same size they will eventually have.
        // The specifiedWidth and specifiedHeight variables are used to predict the size that
        // WebCore will eventually resize us to.

        // The QuickTime plug-in has problems if you give it a width or height of 0.
        // Since other plug-ins also might have the same sort of trouble, we make sure
        // to always give plug-ins a size other than 0,0.

        if (window.width <= 0) {
            window.width = specifiedWidth > 0 ? specifiedWidth : 100;
        }
        if (window.height <= 0) {
            window.height = specifiedHeight > 0 ? specifiedHeight : 100;
        }
278 279 280

        window.clipRect.bottom = window.clipRect.top;
        window.clipRect.left = window.clipRect.right;
281 282 283 284 285
    } else {
        window.clipRect.top = (uint16)visibleRectInWindow.origin.y;
        window.clipRect.left = (uint16)visibleRectInWindow.origin.x;
        window.clipRect.bottom = (uint16)(visibleRectInWindow.origin.y + visibleRectInWindow.size.height);
        window.clipRect.right = (uint16)(visibleRectInWindow.origin.x + visibleRectInWindow.size.width);        
286
    }
darin's avatar
darin committed
287

kocienda's avatar
kocienda committed
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
    window.type = NPWindowTypeWindow;
    
    // Save the port state.
    PortState portState;
    
    GetPort(&portState.oldPort);    

    portState.oldOrigin.h = portBounds.left;
    portState.oldOrigin.v = portBounds.top;

    portState.oldClipRegion = NewRgn();
    GetPortClipRegion(port, portState.oldClipRegion);
    
    portState.oldVisibleRegion = NewRgn();
    GetPortVisibleRegion(port, portState.oldVisibleRegion);
    
    RgnHandle clipRegion = NewRgn();
    portState.clipRegion = clipRegion;
    
    MacSetRectRgn(clipRegion,
        window.clipRect.left + nPort.portx, window.clipRect.top + nPort.porty,
        window.clipRect.right + nPort.portx, window.clipRect.bottom + nPort.porty);
    
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
    // Clip to dirty region when updating in "windowless" mode (transparent)
    if (forUpdate && isTransparent) {
        RgnHandle viewClipRegion = NewRgn();
        
        // Get list of dirty rects from the opaque ancestor -- WebKit does some tricks with invalidation and
        // display to enable z-ordering for NSViews; a side-effect of this is that only the WebHTMLView
        // knows about the true set of dirty rects.
        NSView *opaqueAncestor = [self opaqueAncestor];
        const NSRect *dirtyRects;
        int dirtyRectCount, dirtyRectIndex;
        [opaqueAncestor getRectsBeingDrawn:&dirtyRects count:&dirtyRectCount];

        for (dirtyRectIndex = 0; dirtyRectIndex < dirtyRectCount; dirtyRectIndex++) {
            NSRect dirtyRect = [self convertRect:dirtyRects[dirtyRectIndex] fromView:opaqueAncestor];
            if (!NSEqualSizes(dirtyRect.size, NSZeroSize)) {
                // Create a region for this dirty rect
                RgnHandle dirtyRectRegion = NewRgn();
                SetRectRgn(dirtyRectRegion, NSMinX(dirtyRect), NSMinY(dirtyRect), NSMaxX(dirtyRect), NSMaxY(dirtyRect));
                
                // Union this dirty rect with the rest of the dirty rects
                UnionRgn(viewClipRegion, dirtyRectRegion, viewClipRegion);
                DisposeRgn(dirtyRectRegion);
            }
        }
    
        // Intersect the dirty region with the clip region, so that we only draw over dirty parts
        SectRgn(clipRegion, viewClipRegion, clipRegion);
        DisposeRgn(viewClipRegion);
    }
    
kocienda's avatar
kocienda committed
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
    portState.forUpdate = forUpdate;
    
    // Switch to the port and set it up.
    SetPort(port);

    PenNormal();
    ForeColor(blackColor);
    BackColor(whiteColor);
    
    SetOrigin(nPort.portx, nPort.porty);

    SetPortClipRegion(nPort.port, clipRegion);

    if (forUpdate) {
        // AppKit may have tried to help us by doing a BeginUpdate.
        // But the invalid region at that level didn't include AppKit's notion of what was not valid.
        // We reset the port's visible region to counteract what BeginUpdate did.
        SetPortVisibleRegion(nPort.port, clipRegion);

        // Some plugins do their own BeginUpdate/EndUpdate.
        // For those, we must make sure that the update region contains the area we want to draw.
        InvalWindowRgn(windowRef, clipRegion);
    }
    
    return portState;
}

- (PortState)saveAndSetPortState
{
    return [self saveAndSetPortStateForUpdate:NO];
}

- (void)restorePortState:(PortState)portState
{
375 376 377
    ASSERT([self currentWindow]);
    
    WindowRef windowRef = [[self currentWindow] windowRef];
kocienda's avatar
kocienda committed
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
    CGrafPtr port = GetWindowPort(windowRef);

    if (portState.forUpdate) {
        ValidWindowRgn(windowRef, portState.clipRegion);
    }
    
    SetOrigin(portState.oldOrigin.h, portState.oldOrigin.v);

    SetPortClipRegion(port, portState.oldClipRegion);
    if (portState.forUpdate) {
        SetPortVisibleRegion(port, portState.oldVisibleRegion);
    }

    DisposeRgn(portState.oldClipRegion);
    DisposeRgn(portState.oldVisibleRegion);
    DisposeRgn(portState.clipRegion);

    SetPort(portState.oldPort);
}

398 399
- (BOOL)sendEvent:(EventRecord *)event
{
400
    ASSERT([self window]);
kdecker's avatar
kdecker committed
401 402 403 404 405 406 407 408 409
    ASSERT(event);
   
    // If at any point the user clicks or presses a key from within a plugin, set the 
    // currentEventIsUserGesture flag to true. This is important to differentiate legitimate 
    // window.open() calls;  we still want to allow those.  See rdar://problem/4010765
    if(event->what == mouseDown || event->what == keyDown || event->what == mouseUp || event->what == autoKey) {
        currentEventIsUserGesture = YES;
    }
    
cblu's avatar
cblu committed
410 411
    suspendKeyUpEvents = NO;
    
412
    if (!isStarted) {
darin's avatar
darin committed
413 414
        return NO;
    }
415 416

    ASSERT(NPP_HandleEvent);
darin's avatar
darin committed
417
    
darin's avatar
darin committed
418 419 420 421 422 423 424 425
    // Make sure we don't call NPP_HandleEvent while we're inside NPP_SetWindow.
    // We probably don't want more general reentrancy protection; we are really
    // protecting only against this one case, which actually comes up when
    // you first install the SVG viewer plug-in.
    if (inSetWindow) {
        return NO;
    }

darin's avatar
WebKit:  
darin committed
426
    BOOL defers = [[self webView] defersCallbacks];
427
    if (!defers) {
darin's avatar
WebKit:  
darin committed
428
        [[self webView] setDefersCallbacks:YES];
429 430
    }

kocienda's avatar
kocienda committed
431
    PortState portState = [self saveAndSetPortStateForUpdate:event->what == updateEvt];
432 433 434
    
    // We may have changed the window, so inform the plug-in.
    [self setWindowIfNecessary];
kocienda's avatar
kocienda committed
435 436 437 438

#ifndef NDEBUG
    // Draw green to help debug.
    // If we see any green we know something's wrong.
439
    if (!isTransparent && event->what == updateEvt) {
kocienda's avatar
kocienda committed
440 441 442 443 444 445
        ForeColor(greenColor);
        const Rect bigRect = { -10000, -10000, 10000, 10000 };
        PaintRect(&bigRect);
        ForeColor(blackColor);
    }
#endif
446 447 448
    
    // Temporarily retain self in case the plug-in view is released while sending an event. 
    [self retain];
kocienda's avatar
kocienda committed
449

darin's avatar
darin committed
450
    BOOL acceptedEvent = NPP_HandleEvent(instance, event);
451

kdecker's avatar
kdecker committed
452 453
    currentEventIsUserGesture = NO;
    
454 455 456
    if ([self currentWindow]) {
        [self restorePortState:portState];
    }
kocienda's avatar
kocienda committed
457

458
    if (!defers) {
darin's avatar
WebKit:  
darin committed
459
        [[self webView] setDefersCallbacks:NO];
460 461
    }
    
462 463
    [self release];
    
464 465 466 467
    return acceptedEvent;
}

- (void)sendActivateEvent:(BOOL)activate
darin's avatar
darin committed
468 469 470 471 472
{
    EventRecord event;
    
    [self getCarbonEvent:&event];
    event.what = activateEvt;
473
    WindowRef windowRef = [[self window] windowRef];
474
    event.message = (UInt32)windowRef;
475
    if (activate) {
476
        event.modifiers |= activeFlag;
477
    }
darin's avatar
darin committed
478
    
cblu's avatar
cblu committed
479 480
    BOOL acceptedEvent;
    acceptedEvent = [self sendEvent:&event]; 
darin's avatar
darin committed
481
    
482
    LOG(PluginEvents, "NPP_HandleEvent(activateEvent): %d  isActive: %d", acceptedEvent, activate);
darin's avatar
darin committed
483 484
}

485
- (BOOL)sendUpdateEvent
darin's avatar
darin committed
486 487 488 489 490
{
    EventRecord event;
    
    [self getCarbonEvent:&event];
    event.what = updateEvt;
491
    WindowRef windowRef = [[self window] windowRef];
492
    event.message = (UInt32)windowRef;
darin's avatar
darin committed
493

494
    BOOL acceptedEvent = [self sendEvent:&event];
cblu's avatar
cblu committed
495

496
    LOG(PluginEvents, "NPP_HandleEvent(updateEvt): %d", acceptedEvent);
497

498
    return acceptedEvent;
darin's avatar
darin committed
499 500
}

501 502 503 504 505 506
-(void)sendNullEvent
{
    EventRecord event;

    [self getCarbonEvent:&event];

507 508 509
    // Plug-in should not react to cursor position when not active or when a menu is down.
    MenuTrackingData trackingData;
    OSStatus error = GetMenuTrackingData(NULL, &trackingData);
510 511 512

    // Plug-in should not react to cursor position when the actual window is not key.
    if (![[self window] isKeyWindow] || (error == noErr && trackingData.menu)) {
kocienda's avatar
kocienda committed
513
        // FIXME: Does passing a v and h of -1 really prevent it from reacting to the cursor position?
514 515
        event.where.v = -1;
        event.where.h = -1;
516 517 518 519 520 521 522 523 524 525 526 527 528 529
    }

    [self sendEvent:&event];
}

- (void)stopNullEvents
{
    [nullEventTimer invalidate];
    [nullEventTimer release];
    nullEventTimer = nil;
}

- (void)restartNullEvents
{
530 531
    ASSERT([self window]);
    
532
    if (nullEventTimer) {
533 534
        [self stopNullEvents];
    }
535 536 537 538
    
    if ([[self window] isMiniaturized]) {
        return;
    }
539 540

    NSTimeInterval interval;
541

rjw's avatar
WebKit:  
rjw committed
542 543 544
    // Send null events less frequently when the actual window is not key.  Also, allow the DB
    // to override this behavior and send full speed events to non key windows.
    if ([[self window] isKeyWindow] || [[self webView] _dashboardBehavior:WebDashboardBehaviorAlwaysSendActiveNullEventsToPlugIns]) {
545
        interval = NullEventIntervalActive;
546
    } else {
547 548 549 550 551 552 553 554 555 556
        interval = NullEventIntervalNotActive;
    }
    
    nullEventTimer = [[NSTimer scheduledTimerWithTimeInterval:interval
                                                       target:self
                                                     selector:@selector(sendNullEvent)
                                                     userInfo:nil
                                                      repeats:YES] retain];
}

557
- (BOOL)acceptsFirstResponder
darin's avatar
darin committed
558 559 560 561
{
    return YES;
}

562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
- (void)installKeyEventHandler
{
    static const EventTypeSpec sTSMEvents[] =
    {
    { kEventClassTextInput, kEventTextInputUnicodeForKeyEvent }
    };
    
    if (!keyEventHandler) {
        InstallEventHandler(GetWindowEventTarget([[self window] windowRef]),
                            NewEventHandlerUPP(TSMEventHandler),
                            GetEventTypeCount(sTSMEvents),
                            sTSMEvents,
                            self,
                            &keyEventHandler);
    }
}

- (void)removeKeyEventHandler
{
    if (keyEventHandler) {
        RemoveEventHandler(keyEventHandler);
        keyEventHandler = NULL;
    }
}

587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
- (void)setHasFocus:(BOOL)flag
{
    if (hasFocus != flag) {
        hasFocus = flag;
        EventRecord event;
        [self getCarbonEvent:&event];
        BOOL acceptedEvent;
        if (hasFocus) {
            event.what = getFocusEvent;
            acceptedEvent = [self sendEvent:&event]; 
            LOG(PluginEvents, "NPP_HandleEvent(getFocusEvent): %d", acceptedEvent);
            [self installKeyEventHandler];
        } else {
            event.what = loseFocusEvent;
            acceptedEvent = [self sendEvent:&event]; 
            LOG(PluginEvents, "NPP_HandleEvent(loseFocusEvent): %d", acceptedEvent);
            [self removeKeyEventHandler];
        }
    }
}

darin's avatar
darin committed
608 609
- (BOOL)becomeFirstResponder
{
610
    [self setHasFocus:YES];
darin's avatar
darin committed
611 612 613 614 615
    return YES;
}

- (BOOL)resignFirstResponder
{
616
    [self setHasFocus:NO];    
darin's avatar
darin committed
617 618 619
    return YES;
}

cblu's avatar
cblu committed
620
// AppKit doesn't call mouseDown or mouseUp on right-click. Simulate control-click
621 622 623 624 625 626 627 628 629 630 631
// mouseDown and mouseUp so plug-ins get the right-click event as they do in Carbon (3125743).
- (void)rightMouseDown:(NSEvent *)theEvent
{
    [self mouseDown:theEvent];
}

- (void)rightMouseUp:(NSEvent *)theEvent
{
    [self mouseUp:theEvent];
}

632
- (void)mouseDown:(NSEvent *)theEvent
darin's avatar
darin committed
633 634
{
    EventRecord event;
cblu's avatar
cblu committed
635

cblu's avatar
cblu committed
636
    [self getCarbonEvent:&event withEvent:theEvent];
darin's avatar
darin committed
637
    event.what = mouseDown;
cblu's avatar
cblu committed
638

cblu's avatar
cblu committed
639 640
    BOOL acceptedEvent;
    acceptedEvent = [self sendEvent:&event]; 
641
    
642
    LOG(PluginEvents, "NPP_HandleEvent(mouseDown): %d pt.v=%d, pt.h=%d", acceptedEvent, event.where.v, event.where.h);
darin's avatar
darin committed
643 644
}

645
- (void)mouseUp:(NSEvent *)theEvent
darin's avatar
darin committed
646 647 648
{
    EventRecord event;
    
cblu's avatar
cblu committed
649
    [self getCarbonEvent:&event withEvent:theEvent];
darin's avatar
darin committed
650 651
    event.what = mouseUp;

cblu's avatar
cblu committed
652 653
    BOOL acceptedEvent;
    acceptedEvent = [self sendEvent:&event]; 
darin's avatar
darin committed
654
    
655
    LOG(PluginEvents, "NPP_HandleEvent(mouseUp): %d pt.v=%d, pt.h=%d", acceptedEvent, event.where.v, event.where.h);
darin's avatar
darin committed
656 657 658 659 660 661 662 663 664
}

- (void)mouseEntered:(NSEvent *)theEvent
{
    EventRecord event;
    
    [self getCarbonEvent:&event withEvent:theEvent];
    event.what = adjustCursorEvent;

cblu's avatar
cblu committed
665 666
    BOOL acceptedEvent;
    acceptedEvent = [self sendEvent:&event]; 
darin's avatar
darin committed
667
    
668
    LOG(PluginEvents, "NPP_HandleEvent(mouseEntered): %d", acceptedEvent);
darin's avatar
darin committed
669 670 671 672 673
}

- (void)mouseExited:(NSEvent *)theEvent
{
    EventRecord event;
cblu's avatar
cblu committed
674
        
darin's avatar
darin committed
675 676 677
    [self getCarbonEvent:&event withEvent:theEvent];
    event.what = adjustCursorEvent;

cblu's avatar
cblu committed
678 679
    BOOL acceptedEvent;
    acceptedEvent = [self sendEvent:&event]; 
darin's avatar
darin committed
680
    
681
    LOG(PluginEvents, "NPP_HandleEvent(mouseExited): %d", acceptedEvent);
cblu's avatar
cblu committed
682 683 684
    
    // Set cursor back to arrow cursor.
    [[NSCursor arrowCursor] set];
darin's avatar
darin committed
685 686
}

687 688 689 690 691
- (void)mouseDragged:(NSEvent *)theEvent
{
    // Do nothing so that other responders don't respond to the drag that initiated in this view.
}

cblu's avatar
cblu committed
692 693 694 695 696 697 698 699 700 701 702 703
- (UInt32)keyMessageForEvent:(NSEvent *)event
{
    NSData *data = [[event characters] dataUsingEncoding:CFStringConvertEncodingToNSStringEncoding(CFStringGetSystemEncoding())];
    if (!data) {
        return 0;
    }
    UInt8 characterCode;
    [data getBytes:&characterCode length:1];
    UInt16 keyCode = [event keyCode];
    return keyCode << 8 | characterCode;
}

darin's avatar
darin committed
704 705
- (void)keyUp:(NSEvent *)theEvent
{
mjs's avatar
mjs committed
706
	WKSendKeyEventToTSM(theEvent);
cblu's avatar
cblu committed
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721
    
    // TSM won't send keyUp events so we have to send them ourselves.
    // Only send keyUp events after we receive the TSM callback because this is what plug-in expect from OS 9.
    if (!suspendKeyUpEvents) {
        EventRecord event;
        
        [self getCarbonEvent:&event withEvent:theEvent];
        event.what = keyUp;
        
        if (event.message == 0) {
            event.message = [self keyMessageForEvent:theEvent];
        }
        
        [self sendEvent:&event];
    }
darin's avatar
darin committed
722 723 724 725
}

- (void)keyDown:(NSEvent *)theEvent
{
cblu's avatar
cblu committed
726
    suspendKeyUpEvents = YES;
mjs's avatar
mjs committed
727
    WKSendKeyEventToTSM(theEvent);
cblu's avatar
cblu committed
728 729
}

730
static OSStatus TSMEventHandler(EventHandlerCallRef inHandlerRef, EventRef inEvent, void *pluginView)
cblu's avatar
cblu committed
731
{    
732 733 734 735 736
    EventRef rawKeyEventRef;
    OSStatus status = GetEventParameter(inEvent, kEventParamTextInputSendKeyboardEvent, typeEventRef, NULL, sizeof(EventRef), NULL, &rawKeyEventRef);
    if (status != noErr) {
        ERROR("GetEventParameter failed with error: %d", status);
        return noErr;
cblu's avatar
WebKit:  
cblu committed
737
    }
738 739 740 741 742 743 744 745 746 747 748 749 750 751
    
    // Two-pass read to allocate/extract Mac charCodes
    UInt32 numBytes;    
    status = GetEventParameter(rawKeyEventRef, kEventParamKeyMacCharCodes, typeChar, NULL, 0, &numBytes, NULL);
    if (status != noErr) {
        ERROR("GetEventParameter failed with error: %d", status);
        return noErr;
    }
    char *buffer = malloc(numBytes);
    status = GetEventParameter(rawKeyEventRef, kEventParamKeyMacCharCodes, typeChar, NULL, numBytes, NULL, buffer);
    if (status != noErr) {
        ERROR("GetEventParameter failed with error: %d", status);
        free(buffer);
        return noErr;
cblu's avatar
WebKit:  
cblu committed
752 753
    }
    
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
    EventRef cloneEvent = CopyEvent(rawKeyEventRef);
    unsigned i;
    for (i = 0; i < numBytes; i++) {
        status = SetEventParameter(cloneEvent, kEventParamKeyMacCharCodes, typeChar, 1 /* one char code */, &buffer[i]);
        if (status != noErr) {
            ERROR("SetEventParameter failed with error: %d", status);
            free(buffer);
            return noErr;
        }
        
        EventRecord eventRec;
        if (ConvertEventRefToEventRecord(cloneEvent, &eventRec)) {
            BOOL acceptedEvent;
            acceptedEvent = [(WebBaseNetscapePluginView *)pluginView sendEvent:&eventRec];
            
769
            LOG(PluginEvents, "NPP_HandleEvent(keyDown): %d charCode:%c keyCode:%lu",
770 771 772 773 774 775 776
                acceptedEvent, (char) (eventRec.message & charCodeMask), (eventRec.message & keyCodeMask));
            
            // We originally thought that if the plug-in didn't accept this event,
            // we should pass it along so that keyboard scrolling, for example, will work.
            // In practice, this is not a good idea, because plug-ins tend to eat the event but return false.
            // MacIE handles each key event twice because of this, but we will emulate the other browsers instead.
        }
777
    }
778
    ReleaseEvent(cloneEvent);
779
    
780 781
    free(buffer);
    return noErr;
782 783
}

cblu's avatar
cblu committed
784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814
// Fake up command-modified events so cut, copy, paste and select all menus work.
- (void)sendModifierEventWithKeyCode:(int)keyCode character:(char)character
{
    EventRecord event;
    [self getCarbonEvent:&event];
    event.what = keyDown;
    event.modifiers |= cmdKey;
    event.message = keyCode << 8 | character;
    [self sendEvent:&event];
}

- (void)cut:(id)sender
{
    [self sendModifierEventWithKeyCode:7 character:'x'];
}

- (void)copy:(id)sender
{
    [self sendModifierEventWithKeyCode:8 character:'c'];
}

- (void)paste:(id)sender
{
    [self sendModifierEventWithKeyCode:9 character:'v'];
}

- (void)selectAll:(id)sender
{
    [self sendModifierEventWithKeyCode:0 character:'a'];
}

815
#pragma mark WEB_NETSCAPE_PLUGIN
816

817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
- (BOOL)isNewWindowEqualToOldWindow
{
    if (window.x != lastSetWindow.x) {
        return NO;
    }
    if (window.y != lastSetWindow.y) {
        return NO;
    }
    if (window.width != lastSetWindow.width) {
        return NO;
    }
    if (window.height != lastSetWindow.height) {
        return NO;
    }
    if (window.clipRect.top != lastSetWindow.clipRect.top) {
        return NO;
    }
    if (window.clipRect.left != lastSetWindow.clipRect.left) {
        return NO;
    }
    if (window.clipRect.bottom  != lastSetWindow.clipRect.bottom ) {
        return NO;
    }
    if (window.clipRect.right != lastSetWindow.clipRect.right) {
        return NO;
    }
    if (window.type != lastSetWindow.type) {
        return NO;
    }
    if (nPort.portx != lastSetPort.portx) {
        return NO;
    }
    if (nPort.porty != lastSetPort.porty) {
        return NO;
    }
    if (nPort.port != lastSetPort.port) {
        return NO;
    }
    
    return YES;
}

859 860 861 862 863 864 865 866
- (void)updateAndSetWindow
{    
    PortState portState = [self saveAndSetPortState];
    [self setWindowIfNecessary];
    [self restorePortState:portState];
}

- (void)setWindowIfNecessary
867
{
darin's avatar
darin committed
868 869 870
    if (!isStarted) {
        return;
    }
darin's avatar
darin committed
871
    
872 873 874 875 876 877 878 879 880 881 882 883 884 885
    if (![self isNewWindowEqualToOldWindow]) {        
        // Make sure we don't call NPP_HandleEvent while we're inside NPP_SetWindow.
        // We probably don't want more general reentrancy protection; we are really
        // protecting only against this one case, which actually comes up when
        // you first install the SVG viewer plug-in.
        NPError npErr;
        ASSERT(!inSetWindow);
        
        inSetWindow = YES;
        npErr = NPP_SetWindow(instance, &window);
        inSetWindow = NO;

        LOG(Plugins, "NPP_SetWindow: %d, port=0x%08x, window.x:%d window.y:%d",
            npErr, (int)nPort.port, (int)window.x, (int)window.y);
886
        
887 888 889
        lastSetWindow = window;
        lastSetPort = nPort;
    }
890 891
}

892 893 894 895
- (void)removeTrackingRect
{
    if (trackingTag) {
        [self removeTrackingRect:trackingTag];
darin's avatar
darin committed
896 897
        trackingTag = 0;

898
        // Must release the window to balance the retain in resetTrackingRect.
darin's avatar
darin committed
899
        // But must do it after setting trackingTag to 0 so we don't re-enter.
900 901 902 903 904 905 906 907 908 909 910 911 912 913
        [[self window] release];
    }
}

- (void)resetTrackingRect
{
    [self removeTrackingRect];
    if (isStarted) {
        // Must retain the window so that removeTrackingRect can work after the window is closed.
        [[self window] retain];
        trackingTag = [self addTrackingRect:[self bounds] owner:self userData:nil assumeInside:NO];
    }
}

cblu's avatar
cblu committed
914
+ (void)setCurrentPluginView:(WebBaseNetscapePluginView *)view
cblu's avatar
cblu committed
915
{
cblu's avatar
cblu committed
916 917 918 919 920 921 922 923
    currentPluginView = view;
}

+ (WebBaseNetscapePluginView *)currentPluginView
{
    return currentPluginView;
}

924 925 926 927 928 929 930 931 932 933 934
- (BOOL)canStart
{
    return YES;
}

- (void)didStart
{
    // Do nothing. Overridden by subclasses.
}

- (void)addWindowObservers
cblu's avatar
cblu committed
935
{
936
    ASSERT([self window]);
937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957

    NSWindow *theWindow = [self window];
    
    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
    NSView *view;
    for (view = self; view; view = [view superview]) {
        [notificationCenter addObserver:self selector:@selector(viewHasMoved:)
                                   name:NSViewFrameDidChangeNotification object:view];
        [notificationCenter addObserver:self selector:@selector(viewHasMoved:)
                                   name:NSViewBoundsDidChangeNotification object:view];
    }
    [notificationCenter addObserver:self selector:@selector(windowWillClose:)
                               name:NSWindowWillCloseNotification object:theWindow];
    [notificationCenter addObserver:self selector:@selector(windowBecameKey:)
                               name:NSWindowDidBecomeKeyNotification object:theWindow];
    [notificationCenter addObserver:self selector:@selector(windowResignedKey:)
                               name:NSWindowDidResignKeyNotification object:theWindow];
    [notificationCenter addObserver:self selector:@selector(windowDidMiniaturize:)
                               name:NSWindowDidMiniaturizeNotification object:theWindow];
    [notificationCenter addObserver:self selector:@selector(windowDidDeminiaturize:)
                               name:NSWindowDidDeminiaturizeNotification object:theWindow];
958 959
    
    [notificationCenter addObserver:self selector:@selector(loginWindowDidSwitchFromUser:)
960
                               name:LoginWindowDidSwitchFromUserNotification object:nil];
961
    [notificationCenter addObserver:self selector:@selector(loginWindowDidSwitchToUser:)
962
                               name:LoginWindowDidSwitchToUserNotification object:nil];
963 964 965 966 967 968 969 970 971 972 973 974
}

- (void)removeWindowObservers
{
    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
    [notificationCenter removeObserver:self name:NSViewFrameDidChangeNotification     object:nil];
    [notificationCenter removeObserver:self name:NSViewBoundsDidChangeNotification    object:nil];
    [notificationCenter removeObserver:self name:NSWindowWillCloseNotification        object:nil];
    [notificationCenter removeObserver:self name:NSWindowDidBecomeKeyNotification     object:nil];
    [notificationCenter removeObserver:self name:NSWindowDidResignKeyNotification     object:nil];
    [notificationCenter removeObserver:self name:NSWindowDidMiniaturizeNotification   object:nil];
    [notificationCenter removeObserver:self name:NSWindowDidDeminiaturizeNotification object:nil];
975 976
    [notificationCenter removeObserver:self name:LoginWindowDidSwitchFromUserNotification   object:nil];
    [notificationCenter removeObserver:self name:LoginWindowDidSwitchToUserNotification     object:nil];
977 978 979 980 981
}

- (BOOL)start
{
    ASSERT([self currentWindow]);
982
    
cblu's avatar
cblu committed
983 984
    if (isStarted) {
        return YES;
985
    }
cblu's avatar
cblu committed
986

987 988 989 990
    if (![self canStart]) {
        return NO;
    }
    
sullivan's avatar
sullivan committed
991
    ASSERT([self webView]);
992 993
    
    if (![[[self webView] preferences] arePlugInsEnabled]) {
cblu's avatar
cblu committed
994 995 996
        return NO;
    }

997 998
    ASSERT(NPP_New);

cblu's avatar
cblu committed
999 1000
    [[self class] setCurrentPluginView:self];
    NPError npErr = NPP_New((char *)[MIMEType cString], instance, mode, argsCount, cAttributes, cValues, NULL);
1001 1002
    [[self class] setCurrentPluginView:nil];
    
1003
    LOG(Plugins, "NPP_New: %d", npErr);
cblu's avatar
cblu committed
1004 1005 1006 1007 1008 1009
    if (npErr != NPERR_NO_ERROR) {
        ERROR("NPP_New failed with error: %d", npErr);
        return NO;
    }

    isStarted = YES;
cblu's avatar
cblu committed
1010
        
1011
    [self updateAndSetWindow];
sullivan's avatar
WebKit:  
sullivan committed
1012

1013 1014 1015 1016 1017
    if ([self window]) {
        [self addWindowObservers];
        if ([[self window] isKeyWindow]) {
            [self sendActivateEvent:YES];
        }
1018
        [self restartNullEvents];
1019
    }
1020

1021
    [self resetTrackingRect];
1022 1023
    
    [self didStart];
1024
    
cblu's avatar
cblu committed
1025
    return YES;
cblu's avatar
cblu committed
1026
}
1027

cblu's avatar
cblu committed
1028
- (void)stop
1029
{
1030
    [self removeTrackingRect];
1031

1032
    if (!isStarted) {
cblu's avatar
cblu committed
1033
        return;
1034 1035
    }
    
cblu's avatar
cblu committed
1036
    isStarted = NO;
1037
    
cblu's avatar
cblu committed
1038
    // Stop any active streams
cblu's avatar
WebKit:  
cblu committed
1039
    [streams makeObjectsPerformSelector:@selector(stop)];
cblu's avatar
cblu committed
1040 1041
    
    // Stop the null events
1042
    [self stopNullEvents];
cblu's avatar
cblu committed
1043 1044 1045 1046

    // Set cursor back to arrow cursor
    [[NSCursor arrowCursor] set];
    
darin's avatar
darin committed
1047
    // Stop notifications and callbacks.
1048
    [self removeWindowObservers];
1049
    [[pendingFrameLoads allKeys] makeObjectsPerformSelector:@selector(_setInternalLoadDelegate:) withObject:nil];
darin's avatar
darin committed
1050
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
1051 1052 1053

    // Setting the window type to 0 ensures that NPP_SetWindow will be called if the plug-in is restarted.
    lastSetWindow.type = 0;
cblu's avatar
cblu committed
1054
    
kocienda's avatar
kocienda committed
1055 1056
    NPError npErr;
    npErr = NPP_Destroy(instance, NULL);
1057
    LOG(Plugins, "NPP_Destroy: %d", npErr);
1058 1059

    instance->pdata = NULL;
1060 1061 1062 1063
    
    // We usually remove the key event handler in resignFirstResponder but it is possible that resignFirstResponder 
    // may never get called so we can't completely rely on it.
    [self removeKeyEventHandler];
1064 1065 1066 1067 1068
}

- (BOOL)isStarted
{
    return isStarted;
1069 1070
}

1071
- (WebDataSource *)dataSource
cblu's avatar
WebKit:  
cblu committed
1072
{
1073 1074
    // Do nothing. Overridden by subclasses.
    return nil;
cblu's avatar
WebKit:  
cblu committed
1075 1076
}

1077
- (WebFrame *)webFrame
cblu's avatar
WebKit:  
cblu committed
1078
{
1079
    return [[self dataSource] webFrame];
cblu's avatar
WebKit:  
cblu committed
1080 1081
}

darin's avatar
WebKit:  
darin committed
1082
- (WebView *)webView
1083
{
rjw's avatar
WebKit:  
rjw committed
1084
    return [[self webFrame] webView];
1085
}
cblu's avatar
cblu committed
1086

1087 1088
- (NSWindow *)currentWindow
{
darin's avatar
WebKit:  
darin committed
1089
    return [self window] ? [self window] : [[self webView] hostWindow];
1090 1091
}

1092 1093 1094 1095 1096
- (NPP)pluginPointer
{
    return instance;
}

1097
- (WebNetscapePluginPackage *)plugin
cblu's avatar
cblu committed
1098
{
1099
    return plugin;
cblu's avatar
cblu committed
1100 1101
}

1102
- (void)setPlugin:(WebNetscapePluginPackage *)thePlugin;
cblu's avatar
cblu committed
1103
{
cblu's avatar
cblu committed
1104
    [thePlugin retain];
1105
    [plugin release];
cblu's avatar
cblu committed
1106
    plugin = thePlugin;
1107

cblu's avatar
cblu committed