cocoa_window.m 135 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/*
 * MACDRV Cocoa window code
 *
 * Copyright 2011, 2012, 2013 Ken Thomases for CodeWeavers Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
 */

21 22
#include "config.h"

23
#define GL_SILENCE_DEPRECATION
24
#import <Carbon/Carbon.h>
25
#import <CoreVideo/CoreVideo.h>
26 27 28
#ifdef HAVE_METAL_METAL_H
#import <Metal/Metal.h>
#endif
29
#import <QuartzCore/QuartzCore.h>
30

31 32 33 34
#import "cocoa_window.h"

#include "macdrv_cocoa.h"
#import "cocoa_app.h"
35
#import "cocoa_event.h"
36
#import "cocoa_opengl.h"
37 38


39
#if !defined(MAC_OS_X_VERSION_10_12) || MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_12
40 41 42 43
/* Additional Mac virtual keycode, to complement those in Carbon's <HIToolbox/Events.h>. */
enum {
    kVK_RightCommand              = 0x36, /* Invented for Wine; was unused */
};
44
#endif
45 46


47 48 49 50 51 52 53 54 55 56
@interface NSWindow (PrivatePreventsActivation)

/* Needed to ensure proper behavior after adding or removing
 * NSWindowStyleMaskNonactivatingPanel.
 * Available since at least macOS 10.6. */
- (void)_setPreventsActivation:(BOOL)flag;

@end


57 58 59 60 61 62
static NSUInteger style_mask_for_features(const struct macdrv_window_features* wf)
{
    NSUInteger style_mask;

    if (wf->title_bar)
    {
63 64 65 66 67
        style_mask = NSWindowStyleMaskTitled;
        if (wf->close_button) style_mask |= NSWindowStyleMaskClosable;
        if (wf->minimize_button) style_mask |= NSWindowStyleMaskMiniaturizable;
        if (wf->resizable || wf->maximize_button) style_mask |= NSWindowStyleMaskResizable;
        if (wf->utility) style_mask |= NSWindowStyleMaskUtilityWindow;
68
    }
69
    else style_mask = NSWindowStyleMaskBorderless;
70

71 72
    if (wf->prevents_app_activation) style_mask |= NSWindowStyleMaskNonactivatingPanel;

73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
    return style_mask;
}


static BOOL frame_intersects_screens(NSRect frame, NSArray* screens)
{
    NSScreen* screen;
    for (screen in screens)
    {
        if (NSIntersectsRect(frame, [screen frame]))
            return TRUE;
    }
    return FALSE;
}


89 90 91 92 93 94 95 96 97 98 99
static NSScreen* screen_covered_by_rect(NSRect rect, NSArray* screens)
{
    for (NSScreen* screen in screens)
    {
        if (NSContainsRect(rect, [screen frame]))
            return screen;
    }
    return nil;
}


100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
/* We rely on the supposedly device-dependent modifier flags to distinguish the
   keys on the left side of the keyboard from those on the right.  Some event
   sources don't set those device-depdendent flags.  If we see a device-independent
   flag for a modifier without either corresponding device-dependent flag, assume
   the left one. */
static inline void fix_device_modifiers_by_generic(NSUInteger* modifiers)
{
    if ((*modifiers & (NX_COMMANDMASK | NX_DEVICELCMDKEYMASK | NX_DEVICERCMDKEYMASK)) == NX_COMMANDMASK)
        *modifiers |= NX_DEVICELCMDKEYMASK;
    if ((*modifiers & (NX_SHIFTMASK | NX_DEVICELSHIFTKEYMASK | NX_DEVICERSHIFTKEYMASK)) == NX_SHIFTMASK)
        *modifiers |= NX_DEVICELSHIFTKEYMASK;
    if ((*modifiers & (NX_CONTROLMASK | NX_DEVICELCTLKEYMASK | NX_DEVICERCTLKEYMASK)) == NX_CONTROLMASK)
        *modifiers |= NX_DEVICELCTLKEYMASK;
    if ((*modifiers & (NX_ALTERNATEMASK | NX_DEVICELALTKEYMASK | NX_DEVICERALTKEYMASK)) == NX_ALTERNATEMASK)
        *modifiers |= NX_DEVICELALTKEYMASK;
}

/* As we manipulate individual bits of a modifier mask, we can end up with
   inconsistent sets of flags.  In particular, we might set or clear one of the
   left/right-specific bits, but not the corresponding non-side-specific bit.
   Fix that.  If either side-specific bit is set, set the non-side-specific bit,
   otherwise clear it. */
static inline void fix_generic_modifiers_by_device(NSUInteger* modifiers)
{
    if (*modifiers & (NX_DEVICELCMDKEYMASK | NX_DEVICERCMDKEYMASK))
        *modifiers |= NX_COMMANDMASK;
    else
        *modifiers &= ~NX_COMMANDMASK;
    if (*modifiers & (NX_DEVICELSHIFTKEYMASK | NX_DEVICERSHIFTKEYMASK))
        *modifiers |= NX_SHIFTMASK;
    else
        *modifiers &= ~NX_SHIFTMASK;
    if (*modifiers & (NX_DEVICELCTLKEYMASK | NX_DEVICERCTLKEYMASK))
        *modifiers |= NX_CONTROLMASK;
    else
        *modifiers &= ~NX_CONTROLMASK;
    if (*modifiers & (NX_DEVICELALTKEYMASK | NX_DEVICERALTKEYMASK))
        *modifiers |= NX_ALTERNATEMASK;
    else
        *modifiers &= ~NX_ALTERNATEMASK;
}

142
static inline NSUInteger adjusted_modifiers_for_settings(NSUInteger modifiers)
143 144
{
    fix_device_modifiers_by_generic(&modifiers);
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
    NSUInteger new_modifiers = modifiers & ~(NX_DEVICELALTKEYMASK | NX_DEVICERALTKEYMASK |
                                             NX_DEVICELCMDKEYMASK | NX_DEVICERCMDKEYMASK);

    // The MACDRV keyboard driver translates Command keys to Alt. If the
    // Option key (NX_DEVICE[LR]ALTKEYMASK) should behave like Alt in
    // Windows, rewrite it to Command (NX_DEVICE[LR]CMDKEYMASK).
    if (modifiers & NX_DEVICELALTKEYMASK)
        new_modifiers |= left_option_is_alt ? NX_DEVICELCMDKEYMASK : NX_DEVICELALTKEYMASK;
    if (modifiers & NX_DEVICERALTKEYMASK)
        new_modifiers |= right_option_is_alt ? NX_DEVICERCMDKEYMASK : NX_DEVICERALTKEYMASK;

    if (modifiers & NX_DEVICELCMDKEYMASK)
        new_modifiers |= left_command_is_ctrl ? NX_DEVICELCTLKEYMASK : NX_DEVICELCMDKEYMASK;
    if (modifiers & NX_DEVICERCMDKEYMASK)
        new_modifiers |= right_command_is_ctrl ? NX_DEVICERCTLKEYMASK : NX_DEVICERCMDKEYMASK;

    fix_generic_modifiers_by_device(&new_modifiers);
    return new_modifiers;
163 164
}

165

166 167 168 169 170
@interface NSWindow (WineAccessPrivateMethods)
    - (id) _displayChanged;
@end


171 172 173 174 175
@interface WineDisplayLink : NSObject
{
    CGDirectDisplayID _displayID;
    CVDisplayLinkRef _link;
    NSMutableSet* _windows;
176 177 178

    NSTimeInterval _actualRefreshPeriod;
    NSTimeInterval _nominalRefreshPeriod;
179 180

    NSTimeInterval _lastDisplayTime;
181 182 183 184 185 186 187
}

    - (id) initWithDisplayID:(CGDirectDisplayID)displayID;

    - (void) addWindow:(WineWindow*)window;
    - (void) removeWindow:(WineWindow*)window;

188 189 190 191
    - (NSTimeInterval) refreshPeriod;

    - (void) start;

192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
@end

@implementation WineDisplayLink

static CVReturn WineDisplayLinkCallback(CVDisplayLinkRef displayLink, const CVTimeStamp* inNow, const CVTimeStamp* inOutputTime, CVOptionFlags flagsIn, CVOptionFlags* flagsOut, void* displayLinkContext);

    - (id) initWithDisplayID:(CGDirectDisplayID)displayID
    {
        self = [super init];
        if (self)
        {
            CVReturn status = CVDisplayLinkCreateWithCGDisplay(displayID, &_link);
            if (status == kCVReturnSuccess && !_link)
                status = kCVReturnError;
            if (status == kCVReturnSuccess)
                status = CVDisplayLinkSetOutputCallback(_link, WineDisplayLinkCallback, self);
            if (status != kCVReturnSuccess)
            {
                [self release];
                return nil;
            }

            _displayID = displayID;
            _windows = [[NSMutableSet alloc] init];
        }
        return self;
    }

    - (void) dealloc
    {
        if (_link)
        {
            CVDisplayLinkStop(_link);
            CVDisplayLinkRelease(_link);
        }
        [_windows release];
        [super dealloc];
    }

    - (void) addWindow:(WineWindow*)window
    {
233
        BOOL firstWindow;
234
        @synchronized(self) {
235
            firstWindow = !_windows.count;
236 237
            [_windows addObject:window];
        }
238
        if (firstWindow || !CVDisplayLinkIsRunning(_link))
239
            [self start];
240 241 242 243
    }

    - (void) removeWindow:(WineWindow*)window
    {
244
        BOOL lastWindow = FALSE;
245
        @synchronized(self) {
246
            BOOL hadWindows = _windows.count > 0;
247
            [_windows removeObject:window];
248 249
            if (hadWindows && !_windows.count)
                lastWindow = TRUE;
250
        }
251
        if (lastWindow && CVDisplayLinkIsRunning(_link))
252
            CVDisplayLinkStop(_link);
253 254 255 256 257 258 259 260 261
    }

    - (void) fire
    {
        NSSet* windows;
        @synchronized(self) {
            windows = [_windows copy];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
262
            BOOL anyDisplayed = FALSE;
263
            for (WineWindow* window in windows)
264 265 266 267 268 269 270
            {
                if ([window viewsNeedDisplay])
                {
                    [window displayIfNeeded];
                    anyDisplayed = YES;
                }
            }
271 272 273 274 275

            NSTimeInterval now = [[NSProcessInfo processInfo] systemUptime];
            if (anyDisplayed)
                _lastDisplayTime = now;
            else if (_lastDisplayTime + 2.0 < now)
276
                CVDisplayLinkStop(_link);
277 278 279 280
        });
        [windows release];
    }

281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
    - (NSTimeInterval) refreshPeriod
    {
        if (_actualRefreshPeriod || (_actualRefreshPeriod = CVDisplayLinkGetActualOutputVideoRefreshPeriod(_link)))
            return _actualRefreshPeriod;

        if (_nominalRefreshPeriod)
            return _nominalRefreshPeriod;

        CVTime time = CVDisplayLinkGetNominalOutputVideoRefreshPeriod(_link);
        if (time.flags & kCVTimeIsIndefinite)
            return 1.0 / 60.0;
        _nominalRefreshPeriod = time.timeValue / (double)time.timeScale;
        return _nominalRefreshPeriod;
    }

    - (void) start
    {
298
        _lastDisplayTime = [[NSProcessInfo processInfo] systemUptime];
299 300 301
        CVDisplayLinkStart(_link);
    }

302 303 304 305 306 307 308 309 310 311
static CVReturn WineDisplayLinkCallback(CVDisplayLinkRef displayLink, const CVTimeStamp* inNow, const CVTimeStamp* inOutputTime, CVOptionFlags flagsIn, CVOptionFlags* flagsOut, void* displayLinkContext)
{
    WineDisplayLink* link = displayLinkContext;
    [link fire];
    return kCVReturnSuccess;
}

@end


312 313 314 315 316 317 318 319 320 321
#ifndef MAC_OS_X_VERSION_10_14
@protocol NSViewLayerContentScaleDelegate <NSObject>
@optional

    - (BOOL) layer:(CALayer*)layer shouldInheritContentsScale:(CGFloat)newScale fromWindow:(NSWindow*)window;

@end
#endif


322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
@interface CAShapeLayer (WineShapeMaskExtensions)

@property(readonly, nonatomic, getter=isEmptyShaped) BOOL emptyShaped;

@end

@implementation CAShapeLayer (WineShapeMaskExtensions)

    - (BOOL) isEmptyShaped
    {
        return CGRectEqualToRect(CGPathGetBoundingBox(self.path), CGRectZero);
    }

@end


338 339 340 341
@interface WineBaseView : NSView
@end


342 343 344 345 346 347 348 349 350 351 352 353
#ifdef HAVE_METAL_METAL_H
@interface WineMetalView : WineBaseView
{
    id<MTLDevice> _device;
}

    - (id) initWithFrame:(NSRect)frame device:(id<MTLDevice>)device;

@end
#endif


354
@interface WineContentView : WineBaseView <NSTextInputClient, NSViewLayerContentScaleDelegate>
355 356 357
{
    NSMutableArray* glContexts;
    NSMutableArray* pendingGlContexts;
358
    BOOL _everHadGLContext;
359 360
    BOOL _cachedHasGLDescendant;
    BOOL _cachedHasGLDescendantValid;
361
    BOOL clearedGlSurface;
362 363 364

    NSMutableAttributedString* markedText;
    NSRange markedTextSelection;
365

366
    BOOL _retinaMode;
367
    int backingSize[2];
368 369 370 371

#ifdef HAVE_METAL_METAL_H
    WineMetalView *_metalView;
#endif
372 373
}

374 375
@property (readonly, nonatomic) BOOL everHadGLContext;

376 377 378 379
    - (void) addGLContext:(WineOpenGLContext*)context;
    - (void) removeGLContext:(WineOpenGLContext*)context;
    - (void) updateGLContexts;

380 381 382
    - (void) wine_getBackingSize:(int*)outBackingSize;
    - (void) wine_setBackingSize:(const int*)newBackingSize;

383 384 385 386
#ifdef HAVE_METAL_METAL_H
    - (WineMetalView*) newMetalViewWithDevice:(id<MTLDevice>)device;
#endif

387 388 389 390 391
@end


@interface WineWindow ()

392
@property (readwrite, nonatomic) BOOL disabled;
393
@property (readwrite, nonatomic) BOOL noForeground;
394
@property (readwrite, nonatomic) BOOL preventsAppActivation;
395
@property (readwrite, nonatomic) BOOL floating;
396
@property (readwrite, nonatomic) BOOL drawnSinceShown;
397
@property (readwrite, nonatomic) BOOL closing;
398
@property (readwrite, getter=isFakingClose, nonatomic) BOOL fakingClose;
399
@property (retain, nonatomic) NSWindow* latentParentWindow;
400

401
@property (nonatomic) void* hwnd;
402
@property (retain, readwrite, nonatomic) WineEventQueue* queue;
403

404 405 406
@property (nonatomic) void* surface;
@property (nonatomic) pthread_mutex_t* surface_mutex;

407 408 409
@property (nonatomic) BOOL shapeChangedSinceLastDraw;
@property (readonly, nonatomic) BOOL needsTransparency;

410 411 412 413
@property (nonatomic) BOOL colorKeyed;
@property (nonatomic) CGFloat colorKeyRed, colorKeyGreen, colorKeyBlue;
@property (nonatomic) BOOL usePerPixelAlpha;

414 415 416
@property (assign, nonatomic) void* imeData;
@property (nonatomic) BOOL commandDone;

417 418
@property (readonly, copy, nonatomic) NSArray* childWineWindows;

419 420
    - (void) setShape:(CGPathRef)newShape;

421
    - (void) updateForGLSubviews;
422

423 424 425
    - (BOOL) becameEligibleParentOrChild;
    - (void) becameIneligibleChild;

426 427
    - (void) windowDidDrawContent;

428 429 430
@end


431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
@implementation WineBaseView

    - (void) setRetinaMode:(int)mode
    {
        for (WineBaseView* subview in [self subviews])
        {
            if ([subview isKindOfClass:[WineBaseView class]])
                [subview setRetinaMode:mode];
        }
    }

    - (BOOL) acceptsFirstMouse:(NSEvent*)theEvent
    {
        return YES;
    }

    - (BOOL) preservesContentDuringLiveResize
    {
        // Returning YES from this tells Cocoa to keep our view's content during
        // a Cocoa-driven resize.  In theory, we're also supposed to override
        // -setFrameSize: to mark exposed sections as needing redisplay, but
        // user32 will take care of that in a roundabout way.  This way, we don't
        // redraw until the window surface is flushed.
        //
        // This doesn't do anything when we resize the window ourselves.
        return YES;
    }

    - (BOOL)acceptsFirstResponder
    {
        return [[self window] contentView] == self;
    }

    - (BOOL) mouseDownCanMoveWindow
    {
        return NO;
    }

    - (NSFocusRingType) focusRingType
    {
        return NSFocusRingTypeNone;
    }

@end


477 478
@implementation WineContentView

479 480
@synthesize everHadGLContext = _everHadGLContext;

481 482
    - (void) dealloc
    {
483
        [markedText release];
484 485 486 487 488
        [glContexts release];
        [pendingGlContexts release];
        [super dealloc];
    }

489 490 491 492 493
    - (BOOL) isFlipped
    {
        return YES;
    }

494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
    - (BOOL) wantsUpdateLayer
    {
        return YES /*!_everHadGLContext*/;
    }

    - (void) updateLayer
    {
        WineWindow* window = (WineWindow*)[self window];
        CGImageRef image = NULL;
        CGRect imageRect;
        CALayer* layer = [self layer];

        if ([window contentView] != self)
            return;

509
        if (window.closing || !window.surface || !window.surface_mutex)
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
            return;

        pthread_mutex_lock(window.surface_mutex);
        if (get_surface_blit_rects(window.surface, NULL, NULL))
        {
            imageRect = layer.bounds;
            imageRect.origin.x *= layer.contentsScale;
            imageRect.origin.y *= layer.contentsScale;
            imageRect.size.width *= layer.contentsScale;
            imageRect.size.height *= layer.contentsScale;
            image = create_surface_image(window.surface, &imageRect, FALSE, window.colorKeyed,
                                         window.colorKeyRed, window.colorKeyGreen, window.colorKeyBlue);
        }
        pthread_mutex_unlock(window.surface_mutex);

        if (image)
        {
            layer.contents = (id)image;
            CFRelease(image);
            [window windowDidDrawContent];

            // If the window may be transparent, then we have to invalidate the
            // shadow every time we draw.  Also, if this is the first time we've
            // drawn since changing from transparent to opaque.
            if (window.colorKeyed || window.usePerPixelAlpha || window.shapeChangedSinceLastDraw)
            {
                window.shapeChangedSinceLastDraw = FALSE;
                [window invalidateShadow];
            }
        }
    }

542
    - (void) viewWillDraw
543
    {
544
        [super viewWillDraw];
545

546
        for (WineOpenGLContext* context in pendingGlContexts)
547 548 549 550 551 552
        {
            if (!clearedGlSurface)
            {
                context.shouldClearToBlack = TRUE;
                clearedGlSurface = TRUE;
            }
553
            context.needsUpdate = TRUE;
554
        }
555 556
        [glContexts addObjectsFromArray:pendingGlContexts];
        [pendingGlContexts removeAllObjects];
557 558
    }

559 560
    - (void) addGLContext:(WineOpenGLContext*)context
    {
561
        BOOL hadContext = _everHadGLContext;
562 563 564 565
        if (!glContexts)
            glContexts = [[NSMutableArray alloc] init];
        if (!pendingGlContexts)
            pendingGlContexts = [[NSMutableArray alloc] init];
566 567 568 569

        if ([[self window] windowNumber] > 0 && !NSIsEmptyRect([self visibleRect]))
        {
            [glContexts addObject:context];
570 571 572 573 574
            if (!clearedGlSurface)
            {
                context.shouldClearToBlack = TRUE;
                clearedGlSurface = TRUE;
            }
575 576 577 578 579 580 581 582
            context.needsUpdate = TRUE;
        }
        else
        {
            [pendingGlContexts addObject:context];
            [self setNeedsDisplay:YES];
        }

583
        _everHadGLContext = YES;
584 585
        if (!hadContext)
            [self invalidateHasGLDescendant];
586
        [(WineWindow*)[self window] updateForGLSubviews];
587 588 589 590 591 592
    }

    - (void) removeGLContext:(WineOpenGLContext*)context
    {
        [glContexts removeObjectIdenticalTo:context];
        [pendingGlContexts removeObjectIdenticalTo:context];
593
        [(WineWindow*)[self window] updateForGLSubviews];
594 595
    }

596
    - (void) updateGLContexts:(BOOL)reattach
597 598
    {
        for (WineOpenGLContext* context in glContexts)
599
        {
600
            context.needsUpdate = TRUE;
601 602 603 604 605 606 607 608
            if (reattach)
                context.needsReattach = TRUE;
        }
    }

    - (void) updateGLContexts
    {
        [self updateGLContexts:NO];
609 610
    }

611 612
    - (BOOL) _hasGLDescendant
    {
613 614
        if ([self isHidden])
            return NO;
615
        if (_everHadGLContext)
616 617 618
            return YES;
        for (WineContentView* view in [self subviews])
        {
619
            if ([view isKindOfClass:[WineContentView class]] && [view hasGLDescendant])
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
                return YES;
        }
        return NO;
    }

    - (BOOL) hasGLDescendant
    {
        if (!_cachedHasGLDescendantValid)
        {
            _cachedHasGLDescendant = [self _hasGLDescendant];
            _cachedHasGLDescendantValid = YES;
        }
        return _cachedHasGLDescendant;
    }

    - (void) invalidateHasGLDescendant
    {
        BOOL invalidateAncestors = _cachedHasGLDescendantValid;
        _cachedHasGLDescendantValid = NO;
        if (invalidateAncestors && self != [[self window] contentView])
        {
            WineContentView* superview = (WineContentView*)[self superview];
            if ([superview isKindOfClass:[WineContentView class]])
                [superview invalidateHasGLDescendant];
        }
    }

647 648 649 650 651 652 653 654 655 656 657 658 659
    - (void) wine_getBackingSize:(int*)outBackingSize
    {
        @synchronized(self) {
            memcpy(outBackingSize, backingSize, sizeof(backingSize));
        }
    }
    - (void) wine_setBackingSize:(const int*)newBackingSize
    {
        @synchronized(self) {
            memcpy(backingSize, newBackingSize, sizeof(backingSize));
        }
    }

660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
#ifdef HAVE_METAL_METAL_H
    - (WineMetalView*) newMetalViewWithDevice:(id<MTLDevice>)device
    {
        if (_metalView) return _metalView;

        WineMetalView* view = [[WineMetalView alloc] initWithFrame:[self bounds] device:device];
        [view setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
        [self setAutoresizesSubviews:YES];
        [self addSubview:view positioned:NSWindowBelow relativeTo:nil];
        _metalView = view;

        [(WineWindow*)self.window windowDidDrawContent];

        return _metalView;
    }
#endif

677 678 679 680 681 682 683 684 685
    - (void) setRetinaMode:(int)mode
    {
        double scale = mode ? 0.5 : 2.0;
        NSRect frame = self.frame;
        frame.origin.x *= scale;
        frame.origin.y *= scale;
        frame.size.width *= scale;
        frame.size.height *= scale;
        [self setFrame:frame];
686
        [self setWantsBestResolutionOpenGLSurface:mode];
687 688
        [self updateGLContexts];

689
        _retinaMode = !!mode;
690 691 692
        [self layer].contentsScale = mode ? 2.0 : 1.0;
        [self layer].minificationFilter = mode ? kCAFilterLinear : kCAFilterNearest;
        [self layer].magnificationFilter = mode ? kCAFilterLinear : kCAFilterNearest;
693
        [super setRetinaMode:mode];
694 695
    }

696 697 698 699 700
    - (BOOL) layer:(CALayer*)layer shouldInheritContentsScale:(CGFloat)newScale fromWindow:(NSWindow*)window
    {
        return (_retinaMode || newScale == 1.0);
    }

701 702 703
    - (void) viewDidHide
    {
        [super viewDidHide];
704
        [self invalidateHasGLDescendant];
705 706 707 708 709
    }

    - (void) viewDidUnhide
    {
        [super viewDidUnhide];
710 711
        [self updateGLContexts:YES];
        [self invalidateHasGLDescendant];
712 713
    }

714 715 716 717 718 719 720
    - (void) clearMarkedText
    {
        [markedText deleteCharactersInRange:NSMakeRange(0, [markedText length])];
        markedTextSelection = NSMakeRange(0, 0);
        [[self inputContext] discardMarkedText];
    }

721 722 723 724 725 726 727 728 729 730 731 732 733 734
    - (void) completeText:(NSString*)text
    {
        macdrv_event* event;
        WineWindow* window = (WineWindow*)[self window];

        event = macdrv_create_event(IM_SET_TEXT, window);
        event->im_set_text.data = [window imeData];
        event->im_set_text.text = (CFStringRef)[text copy];
        event->im_set_text.complete = TRUE;

        [[window queue] postEvent:event];

        macdrv_release_event(event);

735
        [self clearMarkedText];
736 737
    }

738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756
    - (void) didAddSubview:(NSView*)subview
    {
        if ([subview isKindOfClass:[WineContentView class]])
        {
            WineContentView* view = (WineContentView*)subview;
            if (!view->_cachedHasGLDescendantValid || view->_cachedHasGLDescendant)
                [self invalidateHasGLDescendant];
        }
        [super didAddSubview:subview];
    }

    - (void) willRemoveSubview:(NSView*)subview
    {
        if ([subview isKindOfClass:[WineContentView class]])
        {
            WineContentView* view = (WineContentView*)subview;
            if (!view->_cachedHasGLDescendantValid || view->_cachedHasGLDescendant)
                [self invalidateHasGLDescendant];
        }
757 758 759 760
#ifdef HAVE_METAL_METAL_H
        if (subview == _metalView)
            _metalView = nil;
#endif
761 762 763
        [super willRemoveSubview:subview];
    }

764 765 766 767 768 769
    - (void) setLayer:(CALayer*)newLayer
    {
        [super setLayer:newLayer];
        [self updateGLContexts];
    }

770 771 772 773 774 775 776 777 778 779 780 781 782 783 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
    /*
     * ---------- NSTextInputClient methods ----------
     */
    - (NSTextInputContext*) inputContext
    {
        if (!markedText)
            markedText = [[NSMutableAttributedString alloc] init];
        return [super inputContext];
    }

    - (void) insertText:(id)string replacementRange:(NSRange)replacementRange
    {
        if ([string isKindOfClass:[NSAttributedString class]])
            string = [string string];

        if ([string isKindOfClass:[NSString class]])
            [self completeText:string];
    }

    - (void) doCommandBySelector:(SEL)aSelector
    {
        [(WineWindow*)[self window] setCommandDone:TRUE];
    }

    - (void) setMarkedText:(id)string selectedRange:(NSRange)selectedRange replacementRange:(NSRange)replacementRange
    {
        if ([string isKindOfClass:[NSAttributedString class]])
            string = [string string];

        if ([string isKindOfClass:[NSString class]])
        {
            macdrv_event* event;
            WineWindow* window = (WineWindow*)[self window];

            if (replacementRange.location == NSNotFound)
                replacementRange = NSMakeRange(0, [markedText length]);

            [markedText replaceCharactersInRange:replacementRange withString:string];
            markedTextSelection = selectedRange;
            markedTextSelection.location += replacementRange.location;

            event = macdrv_create_event(IM_SET_TEXT, window);
            event->im_set_text.data = [window imeData];
            event->im_set_text.text = (CFStringRef)[[markedText string] copy];
            event->im_set_text.complete = FALSE;
815
            event->im_set_text.cursor_pos = markedTextSelection.location + markedTextSelection.length;
816 817 818 819

            [[window queue] postEvent:event];

            macdrv_release_event(event);
820 821

            [[self inputContext] invalidateCharacterCoordinates];
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 859 860 861 862 863 864 865
        }
    }

    - (void) unmarkText
    {
        [self completeText:nil];
    }

    - (NSRange) selectedRange
    {
        return markedTextSelection;
    }

    - (NSRange) markedRange
    {
        NSRange range = NSMakeRange(0, [markedText length]);
        if (!range.length)
            range.location = NSNotFound;
        return range;
    }

    - (BOOL) hasMarkedText
    {
        return [markedText length] > 0;
    }

    - (NSAttributedString*) attributedSubstringForProposedRange:(NSRange)aRange actualRange:(NSRangePointer)actualRange
    {
        if (aRange.location >= [markedText length])
            return nil;

        aRange = NSIntersectionRange(aRange, NSMakeRange(0, [markedText length]));
        if (actualRange)
            *actualRange = aRange;
        return [markedText attributedSubstringFromRange:aRange];
    }

    - (NSArray*) validAttributesForMarkedText
    {
        return [NSArray array];
    }

    - (NSRect) firstRectForCharacterRange:(NSRange)aRange actualRange:(NSRangePointer)actualRange
    {
866 867 868 869
        macdrv_query* query;
        WineWindow* window = (WineWindow*)[self window];
        NSRect ret;

870
        aRange = NSIntersectionRange(aRange, NSMakeRange(0, [markedText length]));
871 872 873 874 875 876 877

        query = macdrv_create_query();
        query->type = QUERY_IME_CHAR_RECT;
        query->window = (macdrv_window)[window retain];
        query->ime_char_rect.data = [window imeData];
        query->ime_char_rect.range = CFRangeMake(aRange.location, aRange.length);

878
        if ([window.queue query:query timeout:0.3 flags:WineQueryNoPreemptWait])
879 880
        {
            aRange = NSMakeRange(query->ime_char_rect.range.location, query->ime_char_rect.range.length);
881
            ret = NSRectFromCGRect(cgrect_mac_from_win(query->ime_char_rect.rect));
882 883 884 885 886 887 888
            [[WineApplicationController sharedController] flipRect:&ret];
        }
        else
            ret = NSMakeRect(100, 100, aRange.length ? 1 : 0, 12);

        macdrv_release_query(query);

889 890
        if (actualRange)
            *actualRange = aRange;
891
        return ret;
892 893 894 895 896 897 898 899 900 901 902 903
    }

    - (NSUInteger) characterIndexForPoint:(NSPoint)aPoint
    {
        return NSNotFound;
    }

    - (NSInteger) windowLevel
    {
        return [[self window] level];
    }

904 905 906
@end


907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953
#ifdef HAVE_METAL_METAL_H
@implementation WineMetalView

    - (id) initWithFrame:(NSRect)frame device:(id<MTLDevice>)device
    {
        self = [super initWithFrame:frame];
        if (self)
        {
            _device = [device retain];
            self.wantsLayer = YES;
            self.layerContentsRedrawPolicy = NSViewLayerContentsRedrawNever;
        }
        return self;
    }

    - (void) dealloc
    {
        [_device release];
        [super dealloc];
    }

    - (void) setRetinaMode:(int)mode
    {
        self.layer.contentsScale = mode ? 2.0 : 1.0;
        [super setRetinaMode:mode];
    }

    - (CALayer*) makeBackingLayer
    {
        CAMetalLayer *layer = [CAMetalLayer layer];
        layer.device = _device;
        layer.framebufferOnly = YES;
        layer.magnificationFilter = kCAFilterNearest;
        layer.backgroundColor = CGColorGetConstantColor(kCGColorBlack);
        layer.contentsScale = retina_on ? 2.0 : 1.0;
        return layer;
    }

    - (BOOL) isOpaque
    {
        return YES;
    }

@end
#endif


954 955
@implementation WineWindow

956 957
    static WineWindow* causing_becomeKeyWindow;

958
    @synthesize disabled, noForeground, preventsAppActivation, floating, fullscreen, fakingClose, closing, latentParentWindow, hwnd, queue;
959
    @synthesize drawnSinceShown;
960
    @synthesize surface, surface_mutex;
961
    @synthesize shapeChangedSinceLastDraw;
962 963
    @synthesize colorKeyed, colorKeyRed, colorKeyGreen, colorKeyBlue;
    @synthesize usePerPixelAlpha;
964
    @synthesize imeData, commandDone;
965

966 967
    + (WineWindow*) createWindowWithFeatures:(const struct macdrv_window_features*)wf
                                 windowFrame:(NSRect)window_frame
968
                                        hwnd:(void*)hwnd
969
                                       queue:(WineEventQueue*)queue
970 971 972
    {
        WineWindow* window;
        WineContentView* contentView;
973
        NSTrackingArea* trackingArea;
974
        NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
975

976
        [[WineApplicationController sharedController] flipRect:&window_frame];
977 978 979 980 981 982

        window = [[[self alloc] initWithContentRect:window_frame
                                          styleMask:style_mask_for_features(wf)
                                            backing:NSBackingStoreBuffered
                                              defer:YES] autorelease];

983 984
        if (!window) return nil;

985 986 987 988 989
        /* Standardize windows to eliminate differences between titled and
           borderless windows and between NSWindow and NSPanel. */
        [window setHidesOnDeactivate:NO];
        [window setReleasedWhenClosed:NO];

990
        [window setOneShot:YES];
991 992 993
        [window disableCursorRects];
        [window setShowsResizeIndicator:NO];
        [window setHasShadow:wf->shadow];
994
        [window setAcceptsMouseMovedEvents:YES];
995
        [window setDelegate:window];
996 997
        [window setBackgroundColor:[NSColor clearColor]];
        [window setOpaque:NO];
998
        window.hwnd = hwnd;
999
        window.queue = queue;
1000 1001
        window->savedContentMinSize = NSZeroSize;
        window->savedContentMaxSize = NSMakeSize(FLT_MAX, FLT_MAX);
1002
        window->resizable = wf->resizable;
1003
        window->_lastDisplayTime = [[NSDate distantPast] timeIntervalSinceReferenceDate];
1004

1005 1006 1007 1008
        [window registerForDraggedTypes:[NSArray arrayWithObjects:(NSString*)kUTTypeData,
                                                                  (NSString*)kUTTypeContent,
                                                                  nil]];

1009 1010 1011
        contentView = [[[WineContentView alloc] initWithFrame:NSZeroRect] autorelease];
        if (!contentView)
            return nil;
1012
        [contentView setWantsLayer:YES];
1013 1014 1015
        [contentView layer].minificationFilter = retina_on ? kCAFilterLinear : kCAFilterNearest;
        [contentView layer].magnificationFilter = retina_on ? kCAFilterLinear : kCAFilterNearest;
        [contentView layer].contentsScale = retina_on ? 2.0 : 1.0;
1016 1017
        [contentView setAutoresizesSubviews:NO];

1018 1019
        /* We use tracking areas in addition to setAcceptsMouseMovedEvents:YES
           because they give us mouse moves in the background. */
1020
        trackingArea = [[[NSTrackingArea alloc] initWithRect:[contentView bounds]
1021
                                                     options:(NSTrackingMouseMoved |
1022 1023 1024 1025 1026 1027 1028 1029
                                                              NSTrackingActiveAlways |
                                                              NSTrackingInVisibleRect)
                                                       owner:window
                                                    userInfo:nil] autorelease];
        if (!trackingArea)
            return nil;
        [contentView addTrackingArea:trackingArea];

1030
        [window setContentView:contentView];
1031
        [window setInitialFirstResponder:contentView];
1032

1033 1034 1035 1036
        [nc addObserver:window
               selector:@selector(updateFullscreen)
                   name:NSApplicationDidChangeScreenParametersNotification
                 object:NSApp];
1037 1038
        [window updateFullscreen];

1039 1040 1041 1042 1043 1044 1045 1046 1047
        [nc addObserver:window
               selector:@selector(applicationWillHide)
                   name:NSApplicationWillHideNotification
                 object:NSApp];
        [nc addObserver:window
               selector:@selector(applicationDidUnhide)
                   name:NSApplicationDidUnhideNotification
                 object:NSApp];

1048 1049 1050 1051 1052
        [[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:window
                                                              selector:@selector(checkWineDisplayLink)
                                                                  name:NSWorkspaceActiveSpaceDidChangeNotification
                                                                object:[NSWorkspace sharedWorkspace]];

1053 1054
        [window setFrameAndWineFrame:[window frameRectForContentRect:window_frame]];

1055 1056 1057
        return window;
    }

1058 1059
    - (void) dealloc
    {
1060
        [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self];
1061
        [[NSNotificationCenter defaultCenter] removeObserver:self];
1062
        [queue release];
1063
        [latentChildWindows release];
1064 1065 1066 1067
        [latentParentWindow release];
        [super dealloc];
    }

1068 1069
    - (BOOL) preventResizing
    {
1070
        BOOL preventForClipping = cursor_clipping_locks_windows && [[WineApplicationController sharedController] clippingCursor];
1071
        return ([self styleMask] & NSWindowStyleMaskResizable) && (disabled || !resizable || preventForClipping);
1072 1073
    }

1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
    - (BOOL) allowsMovingWithMaximized:(BOOL)inMaximized
    {
        if (allow_immovable_windows && (disabled || inMaximized))
            return NO;
        else if (cursor_clipping_locks_windows && [[WineApplicationController sharedController] clippingCursor])
            return NO;
        else
            return YES;
    }

1084 1085
    - (void) adjustFeaturesForState
    {
1086
        NSUInteger style = [self styleMask];
1087

1088
        if (style & NSWindowStyleMaskClosable)
1089
            [[self standardWindowButton:NSWindowCloseButton] setEnabled:!self.disabled];
1090
        if (style & NSWindowStyleMaskMiniaturizable)
1091
            [[self standardWindowButton:NSWindowMiniaturizeButton] setEnabled:!self.disabled];
1092
        if (style & NSWindowStyleMaskResizable)
1093
            [[self standardWindowButton:NSWindowZoomButton] setEnabled:!self.disabled];
1094 1095
        if ([self collectionBehavior] & NSWindowCollectionBehaviorFullScreenPrimary)
            [[self standardWindowButton:NSWindowFullScreenButton] setEnabled:!self.disabled];
1096

1097
        if ([self preventResizing])
1098
        {
1099
            NSSize size = [self contentRectForFrameRect:self.wine_fractionalFrame].size;
1100 1101 1102 1103 1104 1105 1106 1107
            [self setContentMinSize:size];
            [self setContentMaxSize:size];
        }
        else
        {
            [self setContentMaxSize:savedContentMaxSize];
            [self setContentMinSize:savedContentMinSize];
        }
1108

1109
        if (allow_immovable_windows || cursor_clipping_locks_windows)
1110
            [self setMovable:[self allowsMovingWithMaximized:maximized]];
1111 1112 1113 1114
    }

    - (void) adjustFullScreenBehavior:(NSWindowCollectionBehavior)behavior
    {
1115
        NSUInteger style = [self styleMask];
1116

1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129
        if (behavior & NSWindowCollectionBehaviorParticipatesInCycle &&
            style & NSWindowStyleMaskResizable && !(style & NSWindowStyleMaskUtilityWindow) && !maximized &&
            !(self.parentWindow || self.latentParentWindow))
        {
            behavior |= NSWindowCollectionBehaviorFullScreenPrimary;
            behavior &= ~NSWindowCollectionBehaviorFullScreenAuxiliary;
        }
        else
        {
            behavior &= ~NSWindowCollectionBehaviorFullScreenPrimary;
            behavior |= NSWindowCollectionBehaviorFullScreenAuxiliary;
            if (style & NSWindowStyleMaskFullScreen)
                [super toggleFullScreen:nil];
1130 1131 1132 1133 1134 1135 1136
        }

        if (behavior != [self collectionBehavior])
        {
            [self setCollectionBehavior:behavior];
            [self adjustFeaturesForState];
        }
1137 1138
    }

1139 1140
    - (void) setWindowFeatures:(const struct macdrv_window_features*)wf
    {
1141
        static const NSUInteger usedStyles = NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable |
1142 1143
                                             NSWindowStyleMaskResizable | NSWindowStyleMaskUtilityWindow | NSWindowStyleMaskBorderless |
                                             NSWindowStyleMaskNonactivatingPanel;
1144
        NSUInteger currentStyle = [self styleMask];
1145
        NSUInteger newStyle = style_mask_for_features(wf) | (currentStyle & ~usedStyles);
1146

1147 1148
        self.preventsAppActivation = wf->prevents_app_activation;

1149 1150
        if (newStyle != currentStyle)
        {
1151
            NSString* title = [[[self title] copy] autorelease];
1152 1153 1154
            BOOL showingButtons = (currentStyle & (NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskResizable)) != 0;
            BOOL shouldShowButtons = (newStyle & (NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskResizable)) != 0;
            if (shouldShowButtons != showingButtons && !((newStyle ^ currentStyle) & NSWindowStyleMaskClosable))
1155
            {
1156 1157 1158
                // -setStyleMask: is buggy on 10.7+ with respect to NSWindowStyleMaskResizable.
                // If transitioning from NSWindowStyleMaskTitled | NSWindowStyleMaskResizable to
                // just NSWindowStyleMaskTitled, the window buttons should disappear rather
1159
                // than just being disabled.  But they don't.  Similarly in reverse.
1160 1161
                // The workaround is to also toggle NSWindowStyleMaskClosable at the same time.
                [self setStyleMask:newStyle ^ NSWindowStyleMaskClosable];
1162 1163
            }
            [self setStyleMask:newStyle];
1164

1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
            BOOL isNonActivating = (currentStyle & NSWindowStyleMaskNonactivatingPanel) != 0;
            BOOL shouldBeNonActivating = (newStyle & NSWindowStyleMaskNonactivatingPanel) != 0;
            if (isNonActivating != shouldBeNonActivating) {
                // Changing NSWindowStyleMaskNonactivatingPanel with -setStyleMask is also
                // buggy. If it's added, clicking the title bar will still activate the
                // app. If it's removed, nothing changes at all.
                // This private method ensures the correct behavior.
                if ([self respondsToSelector:@selector(_setPreventsActivation:)])
                    [self _setPreventsActivation:shouldBeNonActivating];
            }

1176 1177 1178 1179 1180
            // -setStyleMask: resets the firstResponder to the window.  Set it
            // back to the content view.
            if ([[self contentView] acceptsFirstResponder])
                [self makeFirstResponder:[self contentView]];

1181
            [self adjustFullScreenBehavior:[self collectionBehavior]];
1182 1183 1184

            if ([[self title] length] == 0 && [title length] > 0)
                [self setTitle:title];
1185 1186
        }

1187
        resizable = wf->resizable;
1188
        [self adjustFeaturesForState];
1189 1190 1191
        [self setHasShadow:wf->shadow];
    }

1192 1193 1194 1195 1196 1197
    // Indicates if the window would be visible if the app were not hidden.
    - (BOOL) wouldBeVisible
    {
        return [NSApp isHidden] ? savedVisibleState : [self isVisible];
    }

1198 1199
    - (BOOL) isOrderedIn
    {
1200
        return [self wouldBeVisible] || [self isMiniaturized];
1201 1202
    }

1203
    - (NSInteger) minimumLevelForActive:(BOOL)active
1204
    {
1205
        NSInteger level;
1206

1207 1208
        if (self.floating && (active || topmost_float_inactive == TOPMOST_FLOAT_INACTIVE_ALL ||
                              (topmost_float_inactive == TOPMOST_FLOAT_INACTIVE_NONFULLSCREEN && !fullscreen)))
1209 1210 1211 1212
            level = NSFloatingWindowLevel;
        else
            level = NSNormalWindowLevel;

1213
        if (active)
1214
        {
1215
            BOOL captured;
1216

1217
            captured = (fullscreen || [self screen]) && [[WineApplicationController sharedController] areDisplaysCaptured];
1218 1219

            if (captured || fullscreen)
1220
            {
1221 1222 1223
                if (captured)
                    level = CGShieldingWindowLevel() + 1; /* Need +1 or we don't get mouse moves */
                else
1224
                    level = NSStatusWindowLevel + 1;
1225 1226 1227

                if (self.floating)
                    level++;
1228 1229
            }
        }
1230 1231

        return level;
1232 1233
    }

1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
    - (void) postDidUnminimizeEvent
    {
        macdrv_event* event;

        /* Coalesce events by discarding any previous ones still in the queue. */
        [queue discardEventsMatchingMask:event_mask_for_type(WINDOW_DID_UNMINIMIZE)
                               forWindow:self];

        event = macdrv_create_event(WINDOW_DID_UNMINIMIZE, self);
        [queue postEvent:event];
        macdrv_release_event(event);
    }

1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
    - (void) sendResizeStartQuery
    {
        macdrv_query* query = macdrv_create_query();
        query->type = QUERY_RESIZE_START;
        query->window = (macdrv_window)[self retain];

        [self.queue query:query timeout:0.3];
        macdrv_release_query(query);
    }

1257 1258
    - (void) setMacDrvState:(const struct macdrv_window_state*)state
    {
1259
        NSWindowCollectionBehavior behavior;
1260

1261
        self.disabled = state->disabled;
1262
        self.noForeground = state->no_foreground;
1263

1264 1265 1266
        if (self.floating != state->floating)
        {
            self.floating = state->floating;
1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
            if (state->floating)
            {
                // Became floating.  If child of non-floating window, make that
                // relationship latent.
                WineWindow* parent = (WineWindow*)[self parentWindow];
                if (parent && !parent.floating)
                    [self becameIneligibleChild];
            }
            else
            {
                // Became non-floating.  If parent of floating children, make that
                // relationship latent.
                WineWindow* child;
1280
                for (child in [self childWineWindows])
1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
                {
                    if (child.floating)
                        [child becameIneligibleChild];
                }
            }

            // Check our latent relationships.  If floating status was the only
            // reason they were latent, then make them active.
            if ([self isVisible])
                [self becameEligibleParentOrChild];

1292 1293
            [[WineApplicationController sharedController] adjustWindowLevels];
        }
1294

1295
        if (state->minimized_valid)
1296
        {
1297
            macdrv_event_mask discard = event_mask_for_type(WINDOW_DID_UNMINIMIZE);
1298

1299 1300 1301
            pendingMinimize = FALSE;
            if (state->minimized && ![self isMiniaturized])
            {
1302
                if ([self wouldBeVisible])
1303
                {
1304
                    if ([self styleMask] & NSWindowStyleMaskFullScreen)
1305 1306
                    {
                        [self postDidUnminimizeEvent];
1307
                        discard &= ~event_mask_for_type(WINDOW_DID_UNMINIMIZE);
1308 1309
                    }
                    else
1310
                    {
1311
                        [self setStyleMask:([self styleMask] | NSWindowStyleMaskMiniaturizable)];
1312
                        [super miniaturize:nil];
1313 1314 1315 1316
                        discard |= event_mask_for_type(WINDOW_BROUGHT_FORWARD) |
                                   event_mask_for_type(WINDOW_GOT_FOCUS) |
                                   event_mask_for_type(WINDOW_LOST_FOCUS);
                    }
1317
                }
1318 1319 1320 1321 1322 1323 1324
                else
                    pendingMinimize = TRUE;
            }
            else if (!state->minimized && [self isMiniaturized])
            {
                ignore_windowDeminiaturize = TRUE;
                [self deminiaturize:nil];
1325
                discard |= event_mask_for_type(WINDOW_LOST_FOCUS);
1326
            }
1327

1328 1329
            if (discard)
                [queue discardEventsMatchingMask:discard forWindow:self];
1330
        }
1331 1332 1333 1334 1335

        if (state->maximized != maximized)
        {
            maximized = state->maximized;
            [self adjustFeaturesForState];
1336 1337 1338

            if (!maximized && [self inLiveResize])
                [self sendResizeStartQuery];
1339
        }
1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358

        behavior = NSWindowCollectionBehaviorDefault;
        if (state->excluded_by_expose)
            behavior |= NSWindowCollectionBehaviorTransient;
        else
            behavior |= NSWindowCollectionBehaviorManaged;
        if (state->excluded_by_cycle)
        {
            behavior |= NSWindowCollectionBehaviorIgnoresCycle;
            if ([self isOrderedIn])
                [NSApp removeWindowsItem:self];
        }
        else
        {
            behavior |= NSWindowCollectionBehaviorParticipatesInCycle;
            if ([self isOrderedIn])
                [NSApp addWindowsItem:self title:[self title] filename:NO];
        }
        [self adjustFullScreenBehavior:behavior];
1359 1360
    }

1361 1362 1363 1364
    - (BOOL) addChildWineWindow:(WineWindow*)child assumeVisible:(BOOL)assumeVisible
    {
        BOOL reordered = FALSE;

1365
        if ([self isVisible] && (assumeVisible || [child isVisible]) && (self.floating || !child.floating))
1366 1367 1368
        {
            if ([self level] > [child level])
                [child setLevel:[self level]];
1369 1370
            if (![child isVisible])
                [child setAutodisplay:YES];
1371
            [self addChildWindow:child ordered:NSWindowAbove];
1372
            [child checkWineDisplayLink];
1373
            [latentChildWindows removeObjectIdenticalTo:child];
1374 1375 1376 1377
            child.latentParentWindow = nil;
            reordered = TRUE;
        }
        else
1378 1379 1380 1381 1382
        {
            if (!latentChildWindows)
                latentChildWindows = [[NSMutableArray alloc] init];
            if (![latentChildWindows containsObject:child])
                [latentChildWindows addObject:child];
1383
            child.latentParentWindow = self;
1384
        }
1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398

        return reordered;
    }

    - (BOOL) addChildWineWindow:(WineWindow*)child
    {
        return [self addChildWineWindow:child assumeVisible:FALSE];
    }

    - (void) removeChildWineWindow:(WineWindow*)child
    {
        [self removeChildWindow:child];
        if (child.latentParentWindow == self)
            child.latentParentWindow = nil;
1399
        [latentChildWindows removeObjectIdenticalTo:child];
1400 1401
    }

1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455
    - (void) setChildWineWindows:(NSArray*)childWindows
    {
        NSArray* origChildren;
        NSUInteger count, start, limit, i;

        origChildren = self.childWineWindows;

        // If the current and desired children arrays match up to a point, leave
        // those matching children alone.
        count = childWindows.count;
        limit = MIN(origChildren.count, count);
        for (start = 0; start < limit; start++)
        {
            if ([origChildren objectAtIndex:start] != [childWindows objectAtIndex:start])
                break;
        }

        // Remove all of the child windows and re-add them back-to-front so they
        // are in the desired order.
        for (i = start; i < count; i++)
        {
            WineWindow* child = [childWindows objectAtIndex:i];
            [self removeChildWindow:child];
        }
        for (i = start; i < count; i++)
        {
            WineWindow* child = [childWindows objectAtIndex:i];
            [self addChildWindow:child ordered:NSWindowAbove];
        }
    }

    static NSComparisonResult compare_windows_back_to_front(NSWindow* window1, NSWindow* window2, NSArray* windowNumbers)
    {
        NSNumber* window1Number = [NSNumber numberWithInteger:[window1 windowNumber]];
        NSNumber* window2Number = [NSNumber numberWithInteger:[window2 windowNumber]];
        NSUInteger index1 = [windowNumbers indexOfObject:window1Number];
        NSUInteger index2 = [windowNumbers indexOfObject:window2Number];
        if (index1 == NSNotFound)
        {
            if (index2 == NSNotFound)
                return NSOrderedSame;
            else
                return NSOrderedAscending;
        }
        else if (index2 == NSNotFound)
            return NSOrderedDescending;
        else if (index1 < index2)
            return NSOrderedDescending;
        else if (index2 < index1)
            return NSOrderedAscending;

        return NSOrderedSame;
    }

1456 1457
    - (BOOL) becameEligibleParentOrChild
    {
1458 1459 1460
        BOOL reordered = FALSE;
        NSUInteger count;

1461 1462 1463 1464 1465 1466 1467 1468 1469
        if (latentParentWindow.floating || !self.floating)
        {
            // If we aren't visible currently, we assume that we should be and soon
            // will be.  So, if the latent parent is visible that's enough to assume
            // we can establish the parent-child relationship in Cocoa.  That will
            // actually make us visible, which is fine.
            if ([latentParentWindow addChildWineWindow:self assumeVisible:TRUE])
                reordered = TRUE;
        }
1470 1471 1472 1473 1474 1475

        // Here, though, we may not actually be visible yet and adding a child
        // won't make us visible.  The caller will have to call this method
        // again after actually making us visible.
        if ([self isVisible] && (count = [latentChildWindows count]))
        {
1476 1477
            NSMutableArray* windowNumbers;
            NSMutableArray* childWindows = [[self.childWineWindows mutableCopy] autorelease];
1478 1479 1480
            NSMutableIndexSet* indexesToRemove = [NSMutableIndexSet indexSet];
            NSUInteger i;

1481 1482
            windowNumbers = [[[[self class] windowNumbersWithOptions:NSWindowNumberListAllSpaces] mutableCopy] autorelease];

1483 1484 1485
            for (i = 0; i < count; i++)
            {
                WineWindow* child = [latentChildWindows objectAtIndex:i];
1486
                if ([child isVisible] && (self.floating || !child.floating))
1487 1488 1489 1490 1491
                {
                    if (child.latentParentWindow == self)
                    {
                        if ([self level] > [child level])
                            [child setLevel:[self level]];
1492
                        [childWindows addObject:child];
1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
                        child.latentParentWindow = nil;
                        reordered = TRUE;
                    }
                    else
                        ERR(@"shouldn't happen: %@ thinks %@ is a latent child, but it doesn't agree\n", self, child);
                    [indexesToRemove addIndex:i];
                }
            }

            [latentChildWindows removeObjectsAtIndexes:indexesToRemove];
1503 1504 1505 1506 1507 1508

            [childWindows sortWithOptions:NSSortStable
                          usingComparator:^NSComparisonResult(id obj1, id obj2){
                return compare_windows_back_to_front(obj1, obj2, windowNumbers);
            }];
            [self setChildWineWindows:childWindows];
1509 1510 1511
        }

        return reordered;
1512 1513
    }

1514
    - (void) becameIneligibleChild
1515 1516 1517 1518
    {
        WineWindow* parent = (WineWindow*)[self parentWindow];
        if (parent)
        {
1519 1520 1521
            if (!parent->latentChildWindows)
                parent->latentChildWindows = [[NSMutableArray alloc] init];
            [parent->latentChildWindows insertObject:self atIndex:0];
1522 1523 1524
            self.latentParentWindow = parent;
            [parent removeChildWindow:self];
        }
1525 1526 1527 1528
    }

    - (void) becameIneligibleParentOrChild
    {
1529
        NSArray* childWindows = [self childWineWindows];
1530 1531

        [self becameIneligibleChild];
1532 1533 1534 1535

        if ([childWindows count])
        {
            WineWindow* child;
1536 1537

            for (child in childWindows)
1538 1539 1540 1541
            {
                child.latentParentWindow = self;
                [self removeChildWindow:child];
            }
1542 1543 1544 1545 1546

            if (latentChildWindows)
                [latentChildWindows replaceObjectsInRange:NSMakeRange(0, 0) withObjectsFromArray:childWindows];
            else
                latentChildWindows = [childWindows mutableCopy];
1547
        }
1548 1549
    }

1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598
    // Determine if, among Wine windows, this window is directly above or below
    // a given other Wine window with no other Wine window intervening.
    // Intervening non-Wine windows are ignored.
    - (BOOL) isOrdered:(NSWindowOrderingMode)orderingMode relativeTo:(WineWindow*)otherWindow
    {
        NSNumber* windowNumber;
        NSNumber* otherWindowNumber;
        NSArray* windowNumbers;
        NSUInteger windowIndex, otherWindowIndex, lowIndex, highIndex, i;

        if (![self isVisible] || ![otherWindow isVisible])
            return FALSE;

        windowNumber = [NSNumber numberWithInteger:[self windowNumber]];
        otherWindowNumber = [NSNumber numberWithInteger:[otherWindow windowNumber]];
        windowNumbers = [[self class] windowNumbersWithOptions:0];
        windowIndex = [windowNumbers indexOfObject:windowNumber];
        otherWindowIndex = [windowNumbers indexOfObject:otherWindowNumber];

        if (windowIndex == NSNotFound || otherWindowIndex == NSNotFound)
            return FALSE;

        if (orderingMode == NSWindowAbove)
        {
            lowIndex = windowIndex;
            highIndex = otherWindowIndex;
        }
        else if (orderingMode == NSWindowBelow)
        {
            lowIndex = otherWindowIndex;
            highIndex = windowIndex;
        }
        else
            return FALSE;

        if (highIndex <= lowIndex)
            return FALSE;

        for (i = lowIndex + 1; i < highIndex; i++)
        {
            NSInteger interveningWindowNumber = [[windowNumbers objectAtIndex:i] integerValue];
            NSWindow* interveningWindow = [NSApp windowWithWindowNumber:interveningWindowNumber];
            if ([interveningWindow isKindOfClass:[WineWindow class]])
                return FALSE;
        }

        return TRUE;
    }

1599 1600 1601 1602
    - (void) order:(NSWindowOrderingMode)mode childWindow:(WineWindow*)child relativeTo:(WineWindow*)other
    {
        NSMutableArray* windowNumbers;
        NSNumber* childWindowNumber;
1603
        NSUInteger otherIndex;
1604
        NSArray* origChildren;
1605 1606 1607 1608
        NSMutableArray* children;

        // Get the z-order from the window server and modify it to reflect the
        // requested window ordering.
1609
        windowNumbers = [[[[self class] windowNumbersWithOptions:NSWindowNumberListAllSpaces] mutableCopy] autorelease];
1610 1611
        childWindowNumber = [NSNumber numberWithInteger:[child windowNumber]];
        [windowNumbers removeObject:childWindowNumber];
1612 1613 1614 1615 1616 1617 1618 1619 1620
        if (other)
        {
            otherIndex = [windowNumbers indexOfObject:[NSNumber numberWithInteger:[other windowNumber]]];
            [windowNumbers insertObject:childWindowNumber atIndex:otherIndex + (mode == NSWindowAbove ? 0 : 1)];
        }
        else if (mode == NSWindowAbove)
            [windowNumbers insertObject:childWindowNumber atIndex:0];
        else
            [windowNumbers addObject:childWindowNumber];
1621 1622 1623

        // Get our child windows and sort them in the reverse of the desired
        // z-order (back-to-front).
1624
        origChildren = [self childWineWindows];
1625
        children = [[origChildren mutableCopy] autorelease];
1626 1627
        [children sortWithOptions:NSSortStable
                  usingComparator:^NSComparisonResult(id obj1, id obj2){
1628
            return compare_windows_back_to_front(obj1, obj2, windowNumbers);
1629 1630
        }];

1631
        [self setChildWineWindows:children];
1632 1633
    }

1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679
    // Search the ancestor windows of self and other to find a place where some ancestors are siblings of each other.
    // There are three possible results in terms of the values of *ancestor and *ancestorOfOther on return:
    //      (non-nil, non-nil)  there is a level in the window tree where the two windows have sibling ancestors
    //                          if *ancestor has a parent Wine window, then it's the parent of the other ancestor, too
    //                          otherwise, the two ancestors are each roots of disjoint window trees
    //      (nil, non-nil)      the other window is a descendent of self and *ancestorOfOther is the direct child
    //      (non-nil, nil)      self is a descendent of other and *ancestor is the direct child
    - (void) getSiblingWindowsForWindow:(WineWindow*)other ancestor:(WineWindow**)ancestor ancestorOfOther:(WineWindow**)ancestorOfOther
    {
        NSMutableArray* otherAncestors = [NSMutableArray arrayWithObject:other];
        WineWindow* child;
        WineWindow* parent;
        for (child = other;
             (parent = (WineWindow*)child.parentWindow) && [parent isKindOfClass:[WineWindow class]];
             child = parent)
        {
            if (parent == self)
            {
                *ancestor = nil;
                *ancestorOfOther = child;
                return;
            }

            [otherAncestors addObject:parent];
        }

        for (child = self;
             (parent = (WineWindow*)child.parentWindow) && [parent isKindOfClass:[WineWindow class]];
             child = parent)
        {
            NSUInteger index = [otherAncestors indexOfObjectIdenticalTo:parent];
            if (index != NSNotFound)
            {
                *ancestor = child;
                if (index == 0)
                    *ancestorOfOther = nil;
                else
                    *ancestorOfOther = [otherAncestors objectAtIndex:index - 1];
                return;
            }
        }

        *ancestor = child;
        *ancestorOfOther = otherAncestors.lastObject;;
    }

1680 1681
    /* Returns whether or not the window was ordered in, which depends on if
       its frame intersects any screen. */
1682
    - (void) orderBelow:(WineWindow*)prev orAbove:(WineWindow*)next activate:(BOOL)activate
1683
    {
1684
        WineApplicationController* controller = [WineApplicationController sharedController];
1685
        if (![self isMiniaturized])
1686
        {
1687
            BOOL needAdjustWindowLevels = FALSE;
1688
            BOOL wasVisible;
1689 1690
            WineWindow* parent;
            WineWindow* child;
1691

1692
            [controller transformProcessToForeground:!self.preventsAppActivation];
1693 1694
            if ([NSApp isHidden])
                [NSApp unhide:nil];
1695
            wasVisible = [self isVisible];
1696

1697 1698 1699
            if (activate)
                [NSApp activateIgnoringOtherApps:YES];

1700 1701
            NSDisableScreenUpdates();

1702
            if ([self becameEligibleParentOrChild])
1703
                needAdjustWindowLevels = TRUE;
1704

1705
            if (prev || next)
1706
            {
1707 1708 1709
                WineWindow* other = [prev isVisible] ? prev : next;
                NSWindowOrderingMode orderingMode = [prev isVisible] ? NSWindowBelow : NSWindowAbove;

1710 1711
                if (![self isOrdered:orderingMode relativeTo:other])
                {
1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734
                    WineWindow* ancestor;
                    WineWindow* ancestorOfOther;

                    [self getSiblingWindowsForWindow:other ancestor:&ancestor ancestorOfOther:&ancestorOfOther];
                    if (ancestor)
                    {
                        [self setAutodisplay:YES];
                        if (ancestorOfOther)
                        {
                            // This window level may not be right for this window based
                            // on floating-ness, fullscreen-ness, etc.  But we set it
                            // temporarily to allow us to order the windows properly.
                            // Then the levels get fixed by -adjustWindowLevels.
                            if ([ancestor level] != [ancestorOfOther level])
                                [ancestor setLevel:[ancestorOfOther level]];

                            parent = (WineWindow*)ancestor.parentWindow;
                            if ([parent isKindOfClass:[WineWindow class]])
                                [parent order:orderingMode childWindow:ancestor relativeTo:ancestorOfOther];
                            else
                                [ancestor orderWindow:orderingMode relativeTo:[ancestorOfOther windowNumber]];
                        }

1735
                        if (!ancestorOfOther || ancestor != self)
1736
                        {
1737 1738 1739 1740 1741 1742 1743 1744 1745
                            for (child = self;
                                 (parent = (WineWindow*)child.parentWindow);
                                 child = parent)
                            {
                                if ([parent isKindOfClass:[WineWindow class]])
                                    [parent order:-orderingMode childWindow:child relativeTo:nil];
                                if (parent == ancestor)
                                    break;
                            }
1746 1747 1748 1749 1750
                        }

                        [self checkWineDisplayLink];
                        needAdjustWindowLevels = TRUE;
                    }
1751
                }
1752
            }
1753
            else
1754
            {
1755 1756 1757 1758 1759 1760 1761
                for (child = self;
                     (parent = (WineWindow*)child.parentWindow) && [parent isKindOfClass:[WineWindow class]];
                     child = parent)
                {
                    [parent order:NSWindowAbove childWindow:child relativeTo:nil];
                }

1762 1763 1764 1765 1766
                // Again, temporarily set level to make sure we can order to
                // the right place.
                next = [controller frontWineWindow];
                if (next && [self level] < [next level])
                    [self setLevel:[next level]];
1767
                [self setAutodisplay:YES];
1768
                [self orderFront:nil];
1769
                [self checkWineDisplayLink];
1770
                needAdjustWindowLevels = TRUE;
1771
            }
1772
            pendingOrderOut = FALSE;
1773 1774 1775 1776

            if ([self becameEligibleParentOrChild])
                needAdjustWindowLevels = TRUE;

1777
            if (needAdjustWindowLevels)
1778 1779 1780
            {
                if (!wasVisible && fullscreen && [self isOnActiveSpace])
                    [controller updateFullscreenWindows];
1781
                [controller adjustWindowLevels];
1782
            }
1783

1784 1785
            if (pendingMinimize)
            {
1786
                [self setStyleMask:([self styleMask] | NSWindowStyleMaskMiniaturizable)];
1787
                [super miniaturize:nil];
1788 1789 1790
                pendingMinimize = FALSE;
            }

1791
            NSEnableScreenUpdates();
1792

1793 1794 1795
            /* Cocoa may adjust the frame when the window is ordered onto the screen.
               Generate a frame-changed event just in case.  The back end will ignore
               it if nothing actually changed. */
1796
            [self windowDidResize:nil skipSizeMove:TRUE];
1797

1798 1799
            if (![self isExcludedFromWindowsMenu])
                [NSApp addWindowsItem:self title:[self title] filename:NO];
1800 1801 1802
        }
    }

1803 1804
    - (void) doOrderOut
    {
1805 1806 1807 1808
        WineApplicationController* controller = [WineApplicationController sharedController];
        BOOL wasVisible = [self isVisible];
        BOOL wasOnActiveSpace = [self isOnActiveSpace];

1809 1810 1811
        [self endWindowDragging];
        [controller windowWillOrderOut:self];

1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826
        if (enteringFullScreen || exitingFullScreen)
        {
            pendingOrderOut = TRUE;
            [queue discardEventsMatchingMask:event_mask_for_type(WINDOW_BROUGHT_FORWARD) |
                                             event_mask_for_type(WINDOW_GOT_FOCUS) |
                                             event_mask_for_type(WINDOW_LOST_FOCUS) |
                                             event_mask_for_type(WINDOW_MAXIMIZE_REQUESTED) |
                                             event_mask_for_type(WINDOW_MINIMIZE_REQUESTED) |
                                             event_mask_for_type(WINDOW_RESTORE_REQUESTED)
                                   forWindow:self];
            return;
        }

        pendingOrderOut = FALSE;

1827 1828
        if ([self isMiniaturized])
            pendingMinimize = TRUE;
1829

1830 1831 1832 1833
        WineWindow* parent = (WineWindow*)self.parentWindow;
        if ([parent isKindOfClass:[WineWindow class]])
            [parent grabDockIconSnapshotFromWindow:self force:NO];

1834
        [self becameIneligibleParentOrChild];
1835
        if ([self isMiniaturized] || [self styleMask] & NSWindowStyleMaskFullScreen)
1836 1837 1838 1839 1840 1841 1842
        {
            fakingClose = TRUE;
            [self close];
            fakingClose = FALSE;
        }
        else
            [self orderOut:nil];
1843
        [self checkWineDisplayLink];
1844 1845 1846
        [self setBackgroundColor:[NSColor clearColor]];
        [self setOpaque:NO];
        drawnSinceShown = NO;
1847
        savedVisibleState = FALSE;
1848 1849 1850
        if (wasVisible && wasOnActiveSpace && fullscreen)
            [controller updateFullscreenWindows];
        [controller adjustWindowLevels];
1851
        [NSApp removeWindowsItem:self];
1852 1853 1854 1855 1856 1857 1858 1859

        [queue discardEventsMatchingMask:event_mask_for_type(WINDOW_BROUGHT_FORWARD) |
                                         event_mask_for_type(WINDOW_GOT_FOCUS) |
                                         event_mask_for_type(WINDOW_LOST_FOCUS) |
                                         event_mask_for_type(WINDOW_MAXIMIZE_REQUESTED) |
                                         event_mask_for_type(WINDOW_MINIMIZE_REQUESTED) |
                                         event_mask_for_type(WINDOW_RESTORE_REQUESTED)
                               forWindow:self];
1860 1861
    }

1862 1863
    - (void) updateFullscreen
    {
1864
        NSRect contentRect = [self contentRectForFrameRect:self.wine_fractionalFrame];
1865
        BOOL nowFullscreen = !([self styleMask] & NSWindowStyleMaskFullScreen) && screen_covered_by_rect(contentRect, [NSScreen screens]);
1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878

        if (nowFullscreen != fullscreen)
        {
            WineApplicationController* controller = [WineApplicationController sharedController];

            fullscreen = nowFullscreen;
            if ([self isVisible] && [self isOnActiveSpace])
                [controller updateFullscreenWindows];

            [controller adjustWindowLevels];
        }
    }

1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904
    - (void) setFrameAndWineFrame:(NSRect)frame
    {
        [self setFrame:frame display:YES];

        wineFrame = frame;
        roundedWineFrame = self.frame;
        CGFloat junk;
#if CGFLOAT_IS_DOUBLE
        if ((!modf(wineFrame.origin.x, &junk) && !modf(wineFrame.origin.y, &junk) &&
             !modf(wineFrame.size.width, &junk) && !modf(wineFrame.size.height, &junk)) ||
            fabs(wineFrame.origin.x - roundedWineFrame.origin.x) >= 1 ||
            fabs(wineFrame.origin.y - roundedWineFrame.origin.y) >= 1 ||
            fabs(wineFrame.size.width - roundedWineFrame.size.width) >= 1 ||
            fabs(wineFrame.size.height - roundedWineFrame.size.height) >= 1)
            roundedWineFrame = wineFrame;
#else
        if ((!modff(wineFrame.origin.x, &junk) && !modff(wineFrame.origin.y, &junk) &&
             !modff(wineFrame.size.width, &junk) && !modff(wineFrame.size.height, &junk)) ||
            fabsf(wineFrame.origin.x - roundedWineFrame.origin.x) >= 1 ||
            fabsf(wineFrame.origin.y - roundedWineFrame.origin.y) >= 1 ||
            fabsf(wineFrame.size.width - roundedWineFrame.size.width) >= 1 ||
            fabsf(wineFrame.size.height - roundedWineFrame.size.height) >= 1)
            roundedWineFrame = wineFrame;
#endif
    }

1905
    - (void) setFrameFromWine:(NSRect)contentRect
1906 1907 1908
    {
        /* Origin is (left, top) in a top-down space.  Need to convert it to
           (left, bottom) in a bottom-up space. */
1909
        [[WineApplicationController sharedController] flipRect:&contentRect];
1910

1911 1912 1913 1914 1915 1916
        /* The back end is establishing a new window size and position.  It's
           not interested in any stale events regarding those that may be sitting
           in the queue. */
        [queue discardEventsMatchingMask:event_mask_for_type(WINDOW_FRAME_CHANGED)
                               forWindow:self];

1917
        if (!NSIsEmptyRect(contentRect))
1918
        {
1919 1920
            NSRect frame, oldFrame;

1921
            oldFrame = self.wine_fractionalFrame;
1922 1923 1924
            frame = [self frameRectForContentRect:contentRect];
            if (!NSEqualRects(frame, oldFrame))
            {
1925 1926 1927
                BOOL equalSizes = NSEqualSizes(frame.size, oldFrame.size);
                BOOL needEnableScreenUpdates = FALSE;

1928
                if ([self preventResizing])
1929 1930 1931 1932 1933 1934 1935 1936 1937
                {
                    // Allow the following calls to -setFrame:display: to work even
                    // if they would violate the content size constraints. This
                    // shouldn't be necessary since the content size constraints are
                    // documented to not constrain that method, but it seems to be.
                    [self setContentMinSize:NSZeroSize];
                    [self setContentMaxSize:NSMakeSize(FLT_MAX, FLT_MAX)];
                }

1938
                if (equalSizes && [[self childWineWindows] count])
1939
                {
1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952
                    // If we change the window frame such that the origin moves
                    // but the size doesn't change, then Cocoa moves child
                    // windows with the parent.  We don't want that so we fake
                    // a change of the size and then change it back.
                    NSRect bogusFrame = frame;
                    bogusFrame.size.width++;

                    NSDisableScreenUpdates();
                    needEnableScreenUpdates = TRUE;

                    ignore_windowResize = TRUE;
                    [self setFrame:bogusFrame display:NO];
                    ignore_windowResize = FALSE;
1953
                }
1954

1955
                [self setFrameAndWineFrame:frame];
1956
                if ([self preventResizing])
1957 1958 1959 1960
                {
                    [self setContentMinSize:contentRect.size];
                    [self setContentMaxSize:contentRect.size];
                }
1961 1962 1963 1964

                if (needEnableScreenUpdates)
                    NSEnableScreenUpdates();

1965 1966 1967 1968
                if (!enteringFullScreen &&
                    [[NSProcessInfo processInfo] systemUptime] - enteredFullScreenTime > 1.0)
                    nonFullscreenFrame = frame;

1969 1970
                [self updateFullscreen];

1971
                if ([self isOrderedIn])
1972 1973 1974
                {
                    /* In case Cocoa adjusted the frame we tried to set, generate a frame-changed
                       event.  The back end will ignore it if nothing actually changed. */
1975
                    [self windowDidResize:nil skipSizeMove:TRUE];
1976 1977
                }
            }
1978
        }
1979 1980
    }

1981 1982 1983 1984 1985 1986 1987 1988
    - (NSRect) wine_fractionalFrame
    {
        NSRect frame = self.frame;
        if (NSEqualRects(frame, roundedWineFrame))
            frame = wineFrame;
        return frame;
    }

1989 1990
    - (void) setMacDrvParentWindow:(WineWindow*)parent
    {
1991 1992
        WineWindow* oldParent = (WineWindow*)[self parentWindow];
        if ((oldParent && oldParent != parent) || (!oldParent && latentParentWindow != parent))
1993
        {
1994 1995 1996
            [oldParent removeChildWineWindow:self];
            [latentParentWindow removeChildWineWindow:self];
            if ([parent addChildWineWindow:self])
1997
                [[WineApplicationController sharedController] adjustWindowLevels];
1998
            [self adjustFullScreenBehavior:[self collectionBehavior]];
1999 2000 2001
        }
    }

2002 2003 2004 2005 2006 2007 2008 2009 2010
    - (void) setDisabled:(BOOL)newValue
    {
        if (disabled != newValue)
        {
            disabled = newValue;
            [self adjustFeaturesForState];
        }
    }

2011 2012
    - (BOOL) needsTransparency
    {
2013
        return self.contentView.layer.mask || self.colorKeyed || self.usePerPixelAlpha ||
2014
                (gl_surface_mode == GL_SURFACE_BEHIND && [(WineContentView*)self.contentView hasGLDescendant]);
2015 2016 2017 2018 2019 2020
    }

    - (void) checkTransparency
    {
        if (![self isOpaque] && !self.needsTransparency)
        {
2021 2022
            self.shapeChangedSinceLastDraw = TRUE;
            [[self contentView] setNeedsDisplay:YES];
2023 2024 2025 2026 2027
            [self setBackgroundColor:[NSColor windowBackgroundColor]];
            [self setOpaque:YES];
        }
        else if ([self isOpaque] && self.needsTransparency)
        {
2028 2029
            self.shapeChangedSinceLastDraw = TRUE;
            [[self contentView] setNeedsDisplay:YES];
2030 2031 2032 2033 2034
            [self setBackgroundColor:[NSColor clearColor]];
            [self setOpaque:NO];
        }
    }

2035
    - (void) setShape:(CGPathRef)newShape
2036
    {
2037 2038 2039
        CALayer* layer = [[self contentView] layer];
        CAShapeLayer* mask = (CAShapeLayer*)layer.mask;
        if (CGPathEqualToPath(newShape, mask.path)) return;
2040

2041 2042 2043 2044 2045 2046 2047
        if (newShape && !layer.mask)
            layer.mask = mask = [CAShapeLayer layer];
        else if (!newShape)
            layer.mask = mask = nil;

        if (mask.path)
            [[self contentView] setNeedsDisplayInRect:NSRectFromCGRect(CGPathGetBoundingBox(mask.path))];
2048
        if (newShape)
2049
            [[self contentView] setNeedsDisplayInRect:NSRectFromCGRect(CGPathGetBoundingBox(newShape))];
2050

2051
        mask.path = newShape;
2052 2053 2054
        self.shapeChangedSinceLastDraw = TRUE;

        [self checkTransparency];
2055
        [self checkEmptyShaped];
2056 2057
    }

2058
    - (void) makeFocused:(BOOL)activate
2059
    {
2060 2061
        if (activate)
        {
2062
            [[WineApplicationController sharedController] transformProcessToForeground:YES];
2063 2064
            [NSApp activateIgnoringOtherApps:YES];
        }
2065

2066
        causing_becomeKeyWindow = self;
2067
        [self makeKeyWindow];
2068
        causing_becomeKeyWindow = nil;
2069 2070 2071 2072

        [queue discardEventsMatchingMask:event_mask_for_type(WINDOW_GOT_FOCUS) |
                                         event_mask_for_type(WINDOW_LOST_FOCUS)
                               forWindow:self];
2073 2074
    }

2075 2076 2077 2078 2079
    - (void) postKey:(uint16_t)keyCode
             pressed:(BOOL)pressed
           modifiers:(NSUInteger)modifiers
               event:(NSEvent*)theEvent
    {
2080
        macdrv_event* event;
2081
        CGEventRef cgevent;
2082
        WineApplicationController* controller = [WineApplicationController sharedController];
2083

2084 2085 2086
        event = macdrv_create_event(pressed ? KEY_PRESS : KEY_RELEASE, self);
        event->key.keycode   = keyCode;
        event->key.modifiers = modifiers;
2087
        event->key.time_ms   = [controller ticksForEventTime:[theEvent timestamp]];
2088 2089

        if ((cgevent = [theEvent CGEvent]))
2090
            controller.keyboardType = CGEventGetIntegerValueField(cgevent, kCGKeyboardEventKeyboardType);
2091

2092 2093 2094
        [queue postEvent:event];

        macdrv_release_event(event);
2095 2096

        [controller noteKey:keyCode pressed:pressed];
2097 2098 2099 2100 2101 2102
    }

    - (void) postKeyEvent:(NSEvent *)theEvent
    {
        [self flagsChanged:theEvent];
        [self postKey:[theEvent keyCode]
2103
              pressed:[theEvent type] == NSEventTypeKeyDown
2104
            modifiers:adjusted_modifiers_for_settings([theEvent modifierFlags])
2105 2106 2107
                event:theEvent];
    }

2108 2109 2110 2111
    - (void) setWineMinSize:(NSSize)minSize maxSize:(NSSize)maxSize
    {
        savedContentMinSize = minSize;
        savedContentMaxSize = maxSize;
2112
        if (![self preventResizing])
2113 2114 2115 2116 2117 2118
        {
            [self setContentMinSize:minSize];
            [self setContentMaxSize:maxSize];
        }
    }

2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139
    - (WineWindow*) ancestorWineWindow
    {
        WineWindow* ancestor = self;
        for (;;)
        {
            WineWindow* parent = (WineWindow*)[ancestor parentWindow];
            if ([parent isKindOfClass:[WineWindow class]])
                ancestor = parent;
            else
                break;
        }
        return ancestor;
    }

    - (void) postBroughtForwardEvent
    {
        macdrv_event* event = macdrv_create_event(WINDOW_BROUGHT_FORWARD, self);
        [queue postEvent:event];
        macdrv_release_event(event);
    }

2140
    - (void) postWindowFrameChanged:(NSRect)frame fullscreen:(BOOL)isFullscreen resizing:(BOOL)resizing skipSizeMove:(BOOL)skipSizeMove
2141 2142 2143 2144 2145
    {
        macdrv_event* event;
        NSUInteger style = self.styleMask;

        if (isFullscreen)
2146
            style |= NSWindowStyleMaskFullScreen;
2147
        else
2148
            style &= ~NSWindowStyleMaskFullScreen;
2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159
        frame = [[self class] contentRectForFrameRect:frame styleMask:style];
        [[WineApplicationController sharedController] flipRect:&frame];

        /* Coalesce events by discarding any previous ones still in the queue. */
        [queue discardEventsMatchingMask:event_mask_for_type(WINDOW_FRAME_CHANGED)
                               forWindow:self];

        event = macdrv_create_event(WINDOW_FRAME_CHANGED, self);
        event->window_frame_changed.frame = cgrect_win_from_mac(NSRectToCGRect(frame));
        event->window_frame_changed.fullscreen = isFullscreen;
        event->window_frame_changed.in_resize = resizing;
2160
        event->window_frame_changed.skip_size_move_loop = skipSizeMove;
2161 2162 2163 2164
        [queue postEvent:event];
        macdrv_release_event(event);
    }

2165 2166 2167 2168 2169
    - (void) updateForCursorClipping
    {
        [self adjustFeaturesForState];
    }

2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185
    - (void) endWindowDragging
    {
        if (draggingPhase)
        {
            if (draggingPhase == 3)
            {
                macdrv_event* event = macdrv_create_event(WINDOW_DRAG_END, self);
                [queue postEvent:event];
                macdrv_release_event(event);
            }

            draggingPhase = 0;
            [[WineApplicationController sharedController] window:self isBeingDragged:NO];
        }
    }

2186
    - (NSMutableDictionary*) displayIDToDisplayLinkMap
2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202
    {
        static NSMutableDictionary* displayIDToDisplayLinkMap;
        if (!displayIDToDisplayLinkMap)
        {
            displayIDToDisplayLinkMap = [[NSMutableDictionary alloc] init];

            [[NSNotificationCenter defaultCenter] addObserverForName:NSApplicationDidChangeScreenParametersNotification
                                                              object:NSApp
                                                               queue:nil
                                                          usingBlock:^(NSNotification *note){
                NSMutableSet* badDisplayIDs = [NSMutableSet setWithArray:displayIDToDisplayLinkMap.allKeys];
                NSSet* validDisplayIDs = [NSSet setWithArray:[[NSScreen screens] valueForKeyPath:@"deviceDescription.NSScreenNumber"]];
                [badDisplayIDs minusSet:validDisplayIDs];
                [displayIDToDisplayLinkMap removeObjectsForKeys:[badDisplayIDs allObjects]];
            }];
        }
2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230
        return displayIDToDisplayLinkMap;
    }

    - (WineDisplayLink*) wineDisplayLink
    {
        if (!_lastDisplayID)
            return nil;

        NSMutableDictionary* displayIDToDisplayLinkMap = [self displayIDToDisplayLinkMap];
        return [displayIDToDisplayLinkMap objectForKey:[NSNumber numberWithUnsignedInt:_lastDisplayID]];
    }

    - (void) checkWineDisplayLink
    {
        NSScreen* screen = self.screen;
        if (![self isVisible] || ![self isOnActiveSpace] || [self isMiniaturized] || [self isEmptyShaped])
            screen = nil;
#if defined(MAC_OS_X_VERSION_10_9) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_9
        if ([self respondsToSelector:@selector(occlusionState)] && !(self.occlusionState & NSWindowOcclusionStateVisible))
            screen = nil;
#endif

        NSNumber* displayIDNumber = [screen.deviceDescription objectForKey:@"NSScreenNumber"];
        CGDirectDisplayID displayID = [displayIDNumber unsignedIntValue];
        if (displayID == _lastDisplayID)
            return;

        NSMutableDictionary* displayIDToDisplayLinkMap = [self displayIDToDisplayLinkMap];
2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250

        if (_lastDisplayID)
        {
            WineDisplayLink* link = [displayIDToDisplayLinkMap objectForKey:[NSNumber numberWithUnsignedInt:_lastDisplayID]];
            [link removeWindow:self];
        }
        if (displayID)
        {
            WineDisplayLink* link = [displayIDToDisplayLinkMap objectForKey:displayIDNumber];
            if (!link)
            {
                link = [[[WineDisplayLink alloc] initWithDisplayID:displayID] autorelease];
                [displayIDToDisplayLinkMap setObject:link forKey:displayIDNumber];
            }
            [link addWindow:self];
            [self displayIfNeeded];
        }
        _lastDisplayID = displayID;
    }

2251 2252
    - (BOOL) isEmptyShaped
    {
2253 2254
        CAShapeLayer* mask = (CAShapeLayer*)[[self contentView] layer].mask;
        return ([mask isEmptyShaped]);
2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327
    }

    - (BOOL) canProvideSnapshot
    {
        return (self.windowNumber > 0 && ![self isEmptyShaped]);
    }

    - (void) grabDockIconSnapshotFromWindow:(WineWindow*)window force:(BOOL)force
    {
        if (![self isEmptyShaped])
            return;

        NSTimeInterval now = [[NSProcessInfo processInfo] systemUptime];
        if (!force && now < lastDockIconSnapshot + 1)
            return;

        if (window)
        {
            if (![window canProvideSnapshot])
                return;
        }
        else
        {
            CGFloat bestArea;
            for (WineWindow* childWindow in self.childWindows)
            {
                if (![childWindow isKindOfClass:[WineWindow class]] || ![childWindow canProvideSnapshot])
                    continue;

                NSSize size = childWindow.frame.size;
                CGFloat area = size.width * size.height;
                if (!window || area > bestArea)
                {
                    window = childWindow;
                    bestArea = area;
                }
            }

            if (!window)
                return;
        }

        const void* windowID = (const void*)(CGWindowID)window.windowNumber;
        CFArrayRef windowIDs = CFArrayCreate(NULL, &windowID, 1, NULL);
        CGImageRef windowImage = CGWindowListCreateImageFromArray(CGRectNull, windowIDs, kCGWindowImageBoundsIgnoreFraming);
        CFRelease(windowIDs);
        if (!windowImage)
            return;

        NSImage* appImage = [NSApp applicationIconImage];
        if (!appImage)
            appImage = [NSImage imageNamed:NSImageNameApplicationIcon];

        NSImage* dockIcon = [[[NSImage alloc] initWithSize:NSMakeSize(256, 256)] autorelease];
        [dockIcon lockFocus];

        CGContextRef cgcontext = [[NSGraphicsContext currentContext] graphicsPort];

        CGRect rect = CGRectMake(8, 8, 240, 240);
        size_t width = CGImageGetWidth(windowImage);
        size_t height = CGImageGetHeight(windowImage);
        if (width > height)
        {
            rect.size.height *= height / (double)width;
            rect.origin.y += (CGRectGetWidth(rect) - CGRectGetHeight(rect)) / 2;
        }
        else if (width != height)
        {
            rect.size.width *= width / (double)height;
            rect.origin.x += (CGRectGetHeight(rect) - CGRectGetWidth(rect)) / 2;
        }

        CGContextDrawImage(cgcontext, rect, windowImage);
2328 2329
        [appImage drawInRect:NSMakeRect(156, 4, 96, 96)
                    fromRect:NSZeroRect
2330
                   operation:NSCompositingOperationSourceOver
2331 2332 2333
                    fraction:1
              respectFlipped:YES
                       hints:nil];
2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357

        [dockIcon unlockFocus];

        CGImageRelease(windowImage);

        NSImageView* imageView = (NSImageView*)self.dockTile.contentView;
        if (![imageView isKindOfClass:[NSImageView class]])
        {
            imageView = [[[NSImageView alloc] initWithFrame:NSMakeRect(0, 0, 256, 256)] autorelease];
            imageView.imageScaling = NSImageScaleProportionallyUpOrDown;
            self.dockTile.contentView = imageView;
        }
        imageView.image = dockIcon;
        [self.dockTile display];
        lastDockIconSnapshot = now;
    }

    - (void) checkEmptyShaped
    {
        if (self.dockTile.contentView && ![self isEmptyShaped])
        {
            self.dockTile.contentView = nil;
            lastDockIconSnapshot = 0;
        }
2358
        [self checkWineDisplayLink];
2359 2360
    }

2361 2362 2363 2364 2365 2366

    /*
     * ---------- NSWindow method overrides ----------
     */
    - (BOOL) canBecomeKeyWindow
    {
2367
        if (causing_becomeKeyWindow == self) return YES;
2368
        if (self.disabled || self.noForeground) return NO;
2369 2370 2371 2372 2373
        if ([self isKeyWindow]) return YES;

        // If a window's collectionBehavior says it participates in cycling,
        // it must return YES from this method to actually be eligible.
        return ![self isExcludedFromWindowsMenu];
2374 2375 2376 2377 2378 2379 2380
    }

    - (BOOL) canBecomeMainWindow
    {
        return [self canBecomeKeyWindow];
    }

2381 2382 2383 2384 2385
    - (NSRect) constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen *)screen
    {
        // If a window is sized to completely cover a screen, then it's in
        // full-screen mode.  In that case, we don't allow NSWindow to constrain
        // it.
2386
        NSArray* screens = [NSScreen screens];
2387
        NSRect contentRect = [self contentRectForFrameRect:frameRect];
2388 2389
        if (!screen_covered_by_rect(contentRect, screens) &&
            frame_intersects_screens(frameRect, screens))
2390 2391 2392 2393
            frameRect = [super constrainFrameRect:frameRect toScreen:screen];
        return frameRect;
    }

2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425
    // This private method of NSWindow is called as Cocoa reacts to the display
    // configuration changing.  Among other things, it adjusts the window's
    // frame based on how the screen(s) changed size.  That tells Wine that the
    // window has been moved.  We don't want that.  Rather, we want to make
    // sure that the WinAPI notion of the window position is maintained/
    // restored, possibly undoing or overriding Cocoa's adjustment.
    //
    // So, we queue a REASSERT_WINDOW_POSITION event to the back end before
    // Cocoa has a chance to adjust the frame, thus preceding any resulting
    // WINDOW_FRAME_CHANGED event that may get queued.  The back end will
    // reassert its notion of the position.  That call won't get processed
    // until after this method returns, so it will override whatever this
    // method does to the window position.  It will also discard any pending
    // WINDOW_FRAME_CHANGED events.
    //
    // Unfortunately, the only way I've found to know when Cocoa is _about to_
    // adjust the window's position due to a display change is to hook into
    // this private method.  This private method has remained stable from 10.6
    // through 10.11.  If it does change, the most likely thing is that it
    // will be removed and no longer called and this fix will simply stop
    // working.  The only real danger would be if Apple changed the return type
    // to a struct or floating-point type, which would change the calling
    // convention.
    - (id) _displayChanged
    {
        macdrv_event* event = macdrv_create_event(REASSERT_WINDOW_POSITION, self);
        [queue postEvent:event];
        macdrv_release_event(event);

        return [super _displayChanged];
    }

2426 2427 2428 2429 2430 2431 2432
    - (BOOL) isExcludedFromWindowsMenu
    {
        return !([self collectionBehavior] & NSWindowCollectionBehaviorParticipatesInCycle);
    }

    - (BOOL) validateMenuItem:(NSMenuItem *)menuItem
    {
2433 2434
        BOOL ret = [super validateMenuItem:menuItem];

2435
        if ([menuItem action] == @selector(makeKeyAndOrderFront:))
2436
            ret = [self isKeyWindow] || (!self.disabled && !self.noForeground);
2437
        if ([menuItem action] == @selector(toggleFullScreen:) && (self.disabled || maximized))
2438
            ret = NO;
2439 2440

        return ret;
2441 2442
    }

2443 2444 2445
    /* We don't call this.  It's the action method of the items in the Window menu. */
    - (void) makeKeyAndOrderFront:(id)sender
    {
2446 2447 2448
        if ([self isMiniaturized])
            [self deminiaturize:nil];
        [self orderBelow:nil orAbove:nil activate:NO];
2449 2450
        [[self ancestorWineWindow] postBroughtForwardEvent];

2451
        if (![self isKeyWindow] && !self.disabled && !self.noForeground)
2452
            [[WineApplicationController sharedController] windowGotFocus:self];
2453 2454
    }

2455 2456
    - (void) sendEvent:(NSEvent*)event
    {
2457 2458
        NSEventType type = event.type;

2459 2460 2461 2462
        /* NSWindow consumes certain key-down events as part of Cocoa's keyboard
           interface control.  For example, Control-Tab switches focus among
           views.  We want to bypass that feature, so directly route key-down
           events to -keyDown:. */
2463
        if (type == NSEventTypeKeyDown)
2464 2465
            [[self firstResponder] keyDown:event];
        else
2466 2467 2468
        {
            if (!draggingPhase && maximized && ![self isMovable] &&
                ![self allowsMovingWithMaximized:YES] && [self allowsMovingWithMaximized:NO] &&
2469
                type == NSEventTypeLeftMouseDown && (self.styleMask & NSWindowStyleMaskTitled))
2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490
            {
                NSRect titleBar = self.frame;
                NSRect contentRect = [self contentRectForFrameRect:titleBar];
                titleBar.size.height = NSMaxY(titleBar) - NSMaxY(contentRect);
                titleBar.origin.y = NSMaxY(contentRect);

                dragStartPosition = [self convertBaseToScreen:event.locationInWindow];

                if (NSMouseInRect(dragStartPosition, titleBar, NO))
                {
                    static const NSWindowButton buttons[] = {
                        NSWindowCloseButton,
                        NSWindowMiniaturizeButton,
                        NSWindowZoomButton,
                        NSWindowFullScreenButton,
                    };
                    BOOL hitButton = NO;
                    int i;

                    for (i = 0; i < sizeof(buttons) / sizeof(buttons[0]); i++)
                    {
2491
                        NSButton* button = [self standardWindowButton:buttons[i]];
2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506
                        if ([button hitTest:[button.superview convertPoint:event.locationInWindow fromView:nil]])
                        {
                            hitButton = YES;
                            break;
                        }
                    }

                    if (!hitButton)
                    {
                        draggingPhase = 1;
                        dragWindowStartPosition = NSMakePoint(NSMinX(titleBar), NSMaxY(titleBar));
                        [[WineApplicationController sharedController] window:self isBeingDragged:YES];
                    }
                }
            }
2507
            else if (draggingPhase && (type == NSEventTypeLeftMouseDragged || type == NSEventTypeLeftMouseUp))
2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518
            {
                if ([self isMovable])
                {
                    NSPoint point = [self convertBaseToScreen:event.locationInWindow];
                    NSPoint newTopLeft = dragWindowStartPosition;

                    newTopLeft.x += point.x - dragStartPosition.x;
                    newTopLeft.y += point.y - dragStartPosition.y;

                    if (draggingPhase == 2)
                    {
2519 2520 2521 2522
                        macdrv_event* mevent = macdrv_create_event(WINDOW_DRAG_BEGIN, self);
                        mevent->window_drag_begin.no_activate = [event wine_commandKeyDown];
                        [queue postEvent:mevent];
                        macdrv_release_event(mevent);
2523 2524 2525 2526 2527 2528

                        draggingPhase = 3;
                    }

                    [self setFrameTopLeftPoint:newTopLeft];
                }
2529
                else if (draggingPhase == 1 && type == NSEventTypeLeftMouseDragged)
2530 2531 2532 2533 2534 2535 2536 2537
                {
                    macdrv_event* event;
                    NSRect frame = [self contentRectForFrameRect:self.frame];

                    [[WineApplicationController sharedController] flipRect:&frame];

                    event = macdrv_create_event(WINDOW_RESTORE_REQUESTED, self);
                    event->window_restore_requested.keep_frame = TRUE;
2538
                    event->window_restore_requested.frame = cgrect_win_from_mac(NSRectToCGRect(frame));
2539 2540 2541 2542 2543 2544
                    [queue postEvent:event];
                    macdrv_release_event(event);

                    draggingPhase = 2;
                }

2545
                if (type == NSEventTypeLeftMouseUp)
2546 2547 2548
                    [self endWindowDragging];
            }

2549
            [super sendEvent:event];
2550
        }
2551 2552
    }

2553 2554 2555 2556 2557
    - (void) miniaturize:(id)sender
    {
        macdrv_event* event = macdrv_create_event(WINDOW_MINIMIZE_REQUESTED, self);
        [queue postEvent:event];
        macdrv_release_event(event);
2558 2559 2560 2561

        WineWindow* parent = (WineWindow*)self.parentWindow;
        if ([parent isKindOfClass:[WineWindow class]])
            [parent grabDockIconSnapshotFromWindow:self force:YES];
2562 2563
    }

2564 2565
    - (void) toggleFullScreen:(id)sender
    {
2566
        if (!self.disabled && !maximized)
2567 2568 2569
            [super toggleFullScreen:sender];
    }

2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585
    - (void) setViewsNeedDisplay:(BOOL)value
    {
        if (value && ![self viewsNeedDisplay])
        {
            WineDisplayLink* link = [self wineDisplayLink];
            if (link)
            {
                NSTimeInterval now = [[NSProcessInfo processInfo] systemUptime];
                if (_lastDisplayTime + [link refreshPeriod] < now)
                    [self setAutodisplay:YES];
                else
                {
                    [link start];
                    _lastDisplayTime = now;
                }
            }
2586 2587
            else
                [self setAutodisplay:YES];
2588 2589 2590 2591 2592 2593 2594 2595
        }
        [super setViewsNeedDisplay:value];
    }

    - (void) display
    {
        _lastDisplayTime = [[NSProcessInfo processInfo] systemUptime];
        [super display];
2596 2597
        if (_lastDisplayID)
            [self setAutodisplay:NO];
2598 2599 2600 2601 2602 2603
    }

    - (void) displayIfNeeded
    {
        _lastDisplayTime = [[NSProcessInfo processInfo] systemUptime];
        [super displayIfNeeded];
2604 2605
        if (_lastDisplayID)
            [self setAutodisplay:NO];
2606 2607
    }

2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621
    - (void) setFrame:(NSRect)frameRect display:(BOOL)flag
    {
        if (flag)
            [self setAutodisplay:YES];
        [super setFrame:frameRect display:flag];
    }

    - (void) setFrame:(NSRect)frameRect display:(BOOL)displayFlag animate:(BOOL)animateFlag
    {
        if (displayFlag)
            [self setAutodisplay:YES];
        [super setFrame:frameRect display:displayFlag animate:animateFlag];
    }

2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632
    - (void) windowDidDrawContent
    {
        if (!drawnSinceShown)
        {
            drawnSinceShown = YES;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self checkTransparency];
            });
        }
    }

2633 2634 2635 2636 2637 2638 2639 2640 2641
    - (NSArray*) childWineWindows
    {
        NSArray* childWindows = self.childWindows;
        NSIndexSet* indexes = [childWindows indexesOfObjectsPassingTest:^BOOL(id child, NSUInteger idx, BOOL *stop){
            return [child isKindOfClass:[WineWindow class]];
        }];
        return [childWindows objectsAtIndexes:indexes];
    }

2642 2643 2644 2645 2646 2647
    - (void) updateForGLSubviews
    {
        if (gl_surface_mode == GL_SURFACE_BEHIND)
            [self checkTransparency];
    }

2648 2649 2650 2651 2652 2653 2654 2655
    - (void) setRetinaMode:(int)mode
    {
        NSRect frame;
        double scale = mode ? 0.5 : 2.0;
        NSAffineTransform* transform = [NSAffineTransform transform];

        [transform scaleBy:scale];

2656
        [[self contentView] layer].mask.contentsScale = mode ? 2.0 : 1.0;
2657

2658
        for (WineBaseView* subview in [self.contentView subviews])
2659
        {
2660
            if ([subview isKindOfClass:[WineBaseView class]])
2661
                [subview setRetinaMode:mode];
2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689
        }

        frame = [self contentRectForFrameRect:self.wine_fractionalFrame];
        frame.origin.x *= scale;
        frame.origin.y *= scale;
        frame.size.width *= scale;
        frame.size.height *= scale;
        frame = [self frameRectForContentRect:frame];

        savedContentMinSize = [transform transformSize:savedContentMinSize];
        if (savedContentMaxSize.width != FLT_MAX && savedContentMaxSize.width != CGFLOAT_MAX)
            savedContentMaxSize.width *= scale;
        if (savedContentMaxSize.height != FLT_MAX && savedContentMaxSize.height != CGFLOAT_MAX)
            savedContentMaxSize.height *= scale;

        self.contentMinSize = [transform transformSize:self.contentMinSize];
        NSSize temp = self.contentMaxSize;
        if (temp.width != FLT_MAX && temp.width != CGFLOAT_MAX)
            temp.width *= scale;
        if (temp.height != FLT_MAX && temp.height != CGFLOAT_MAX)
            temp.height *= scale;
        self.contentMaxSize = temp;

        ignore_windowResize = TRUE;
        [self setFrameAndWineFrame:frame];
        ignore_windowResize = FALSE;
    }

2690

2691 2692 2693
    /*
     * ---------- NSResponder method overrides ----------
     */
2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705
    - (void) keyDown:(NSEvent *)theEvent
    {
        if ([theEvent isARepeat])
        {
            if (!allowKeyRepeats)
                return;
        }
        else
            allowKeyRepeats = YES;

        [self postKeyEvent:theEvent];
    }
2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723

    - (void) flagsChanged:(NSEvent *)theEvent
    {
        static const struct {
            NSUInteger  mask;
            uint16_t    keycode;
        } modifiers[] = {
            { NX_ALPHASHIFTMASK,        kVK_CapsLock },
            { NX_DEVICELSHIFTKEYMASK,   kVK_Shift },
            { NX_DEVICERSHIFTKEYMASK,   kVK_RightShift },
            { NX_DEVICELCTLKEYMASK,     kVK_Control },
            { NX_DEVICERCTLKEYMASK,     kVK_RightControl },
            { NX_DEVICELALTKEYMASK,     kVK_Option },
            { NX_DEVICERALTKEYMASK,     kVK_RightOption },
            { NX_DEVICELCMDKEYMASK,     kVK_Command },
            { NX_DEVICERCMDKEYMASK,     kVK_RightCommand },
        };

2724
        NSUInteger modifierFlags = adjusted_modifiers_for_settings([theEvent modifierFlags]);
2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741
        NSUInteger changed;
        int i, last_changed;

        fix_device_modifiers_by_generic(&modifierFlags);
        changed = modifierFlags ^ lastModifierFlags;

        last_changed = -1;
        for (i = 0; i < sizeof(modifiers)/sizeof(modifiers[0]); i++)
            if (changed & modifiers[i].mask)
                last_changed = i;

        for (i = 0; i <= last_changed; i++)
        {
            if (changed & modifiers[i].mask)
            {
                BOOL pressed = (modifierFlags & modifiers[i].mask) != 0;

2742 2743 2744
                if (pressed)
                    allowKeyRepeats = NO;

2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771
                if (i == last_changed)
                    lastModifierFlags = modifierFlags;
                else
                {
                    lastModifierFlags ^= modifiers[i].mask;
                    fix_generic_modifiers_by_device(&lastModifierFlags);
                }

                // Caps lock generates one event for each press-release action.
                // We need to simulate a pair of events for each actual event.
                if (modifiers[i].mask == NX_ALPHASHIFTMASK)
                {
                    [self postKey:modifiers[i].keycode
                          pressed:TRUE
                        modifiers:lastModifierFlags
                            event:(NSEvent*)theEvent];
                    pressed = FALSE;
                }

                [self postKey:modifiers[i].keycode
                      pressed:pressed
                    modifiers:lastModifierFlags
                        event:(NSEvent*)theEvent];
            }
        }
    }

2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782
    - (void) applicationWillHide
    {
        savedVisibleState = [self isVisible];
    }

    - (void) applicationDidUnhide
    {
        if ([self isVisible])
            [self becameEligibleParentOrChild];
    }

2783

2784 2785 2786
    /*
     * ---------- NSWindowDelegate methods ----------
     */
2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805
    - (NSSize) window:(NSWindow*)window willUseFullScreenContentSize:(NSSize)proposedSize
    {
        macdrv_query* query;
        NSSize size;

        query = macdrv_create_query();
        query->type = QUERY_MIN_MAX_INFO;
        query->window = (macdrv_window)[self retain];
        [self.queue query:query timeout:0.5];
        macdrv_release_query(query);

        size = [self contentMaxSize];
        if (proposedSize.width < size.width)
            size.width = proposedSize.width;
        if (proposedSize.height < size.height)
            size.height = proposedSize.height;
        return size;
    }

2806 2807
    - (void)windowDidBecomeKey:(NSNotification *)notification
    {
2808 2809
        WineApplicationController* controller = [WineApplicationController sharedController];
        NSEvent* event = [controller lastFlagsChanged];
2810 2811 2812
        if (event)
            [self flagsChanged:event];

2813
        if (causing_becomeKeyWindow == self) return;
2814

2815
        [controller windowGotFocus:self];
2816 2817
    }

2818 2819 2820 2821 2822 2823 2824 2825 2826 2827
    - (void) windowDidChangeOcclusionState:(NSNotification*)notification
    {
        [self checkWineDisplayLink];
    }

    - (void) windowDidChangeScreen:(NSNotification*)notification
    {
        [self checkWineDisplayLink];
    }

2828 2829
    - (void)windowDidDeminiaturize:(NSNotification *)notification
    {
2830 2831
        WineApplicationController* controller = [WineApplicationController sharedController];

2832
        if (!ignore_windowDeminiaturize)
2833
            [self postDidUnminimizeEvent];
2834
        ignore_windowDeminiaturize = FALSE;
2835

2836 2837
        [self becameEligibleParentOrChild];

2838 2839
        if (fullscreen && [self isOnActiveSpace])
            [controller updateFullscreenWindows];
2840 2841
        [controller adjustWindowLevels];

2842 2843 2844
        if (![self parentWindow])
            [self postBroughtForwardEvent];

2845
        if (!self.disabled && !self.noForeground)
2846
        {
2847
            causing_becomeKeyWindow = self;
2848
            [self makeKeyWindow];
2849
            causing_becomeKeyWindow = nil;
2850 2851
            [controller windowGotFocus:self];
        }
2852 2853

        [self windowDidResize:notification];
2854
        [self checkWineDisplayLink];
2855 2856
    }

2857 2858
    - (void) windowDidEndLiveResize:(NSNotification *)notification
    {
2859 2860 2861 2862 2863 2864
        if (!maximized)
        {
            macdrv_event* event = macdrv_create_event(WINDOW_RESIZE_ENDED, self);
            [queue postEvent:event];
            macdrv_release_event(event);
        }
2865 2866
    }

2867 2868 2869 2870
    - (void) windowDidEnterFullScreen:(NSNotification*)notification
    {
        enteringFullScreen = FALSE;
        enteredFullScreenTime = [[NSProcessInfo processInfo] systemUptime];
2871 2872
        if (pendingOrderOut)
            [self doOrderOut];
2873 2874 2875 2876 2877
    }

    - (void) windowDidExitFullScreen:(NSNotification*)notification
    {
        exitingFullScreen = FALSE;
2878
        [self setFrameAndWineFrame:nonFullscreenFrame];
2879
        [self windowDidResize:nil];
2880 2881
        if (pendingOrderOut)
            [self doOrderOut];
2882 2883 2884 2885 2886 2887
    }

    - (void) windowDidFailToEnterFullScreen:(NSWindow*)window
    {
        enteringFullScreen = FALSE;
        enteredFullScreenTime = 0;
2888 2889
        if (pendingOrderOut)
            [self doOrderOut];
2890 2891 2892 2893 2894 2895
    }

    - (void) windowDidFailToExitFullScreen:(NSWindow*)window
    {
        exitingFullScreen = FALSE;
        [self windowDidResize:nil];
2896 2897
        if (pendingOrderOut)
            [self doOrderOut];
2898 2899
    }

2900 2901
    - (void)windowDidMiniaturize:(NSNotification *)notification
    {
2902 2903
        macdrv_event* event;

2904 2905
        if (fullscreen && [self isOnActiveSpace])
            [[WineApplicationController sharedController] updateFullscreenWindows];
2906

2907
        [self checkWineDisplayLink];
2908 2909 2910 2911

        event = macdrv_create_event(WINDOW_DID_MINIMIZE, self);
        [queue postEvent:event];
        macdrv_release_event(event);
2912 2913
    }

2914 2915 2916 2917 2918
    - (void)windowDidMove:(NSNotification *)notification
    {
        [self windowDidResize:notification];
    }

2919 2920
    - (void)windowDidResignKey:(NSNotification *)notification
    {
2921
        macdrv_event* event;
2922 2923 2924

        if (causing_becomeKeyWindow) return;

2925 2926 2927
        event = macdrv_create_event(WINDOW_LOST_FOCUS, self);
        [queue postEvent:event];
        macdrv_release_event(event);
2928 2929
    }

2930
    - (void)windowDidResize:(NSNotification *)notification skipSizeMove:(BOOL)skipSizeMove
2931
    {
2932
        NSRect frame = self.wine_fractionalFrame;
2933 2934 2935 2936 2937 2938 2939 2940 2941

        if ([self inLiveResize])
        {
            if (NSMinX(frame) != NSMinX(frameAtResizeStart))
                resizingFromLeft = TRUE;
            if (NSMaxY(frame) != NSMaxY(frameAtResizeStart))
                resizingFromTop = TRUE;
        }

2942
        if (ignore_windowResize || exitingFullScreen) return;
2943

2944
        if ([self preventResizing])
2945
        {
2946 2947 2948
            NSRect contentRect = [self contentRectForFrameRect:frame];
            [self setContentMinSize:contentRect.size];
            [self setContentMaxSize:contentRect.size];
2949
        }
2950

2951
        [self postWindowFrameChanged:frame
2952
                          fullscreen:([self styleMask] & NSWindowStyleMaskFullScreen) != 0
2953 2954
                            resizing:[self inLiveResize]
                        skipSizeMove:skipSizeMove];
2955 2956

        [[[self contentView] inputContext] invalidateCharacterCoordinates];
2957
        [self updateFullscreen];
2958 2959
    }

2960 2961 2962 2963 2964
    - (void)windowDidResize:(NSNotification *)notification
    {
        [self windowDidResize:notification skipSizeMove:FALSE];
    }

2965 2966
    - (BOOL)windowShouldClose:(id)sender
    {
2967 2968 2969
        macdrv_event* event = macdrv_create_event(WINDOW_CLOSE_REQUESTED, self);
        [queue postEvent:event];
        macdrv_release_event(event);
2970 2971 2972
        return NO;
    }

2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992
    - (BOOL) windowShouldZoom:(NSWindow*)window toFrame:(NSRect)newFrame
    {
        if (maximized)
        {
            macdrv_event* event = macdrv_create_event(WINDOW_RESTORE_REQUESTED, self);
            [queue postEvent:event];
            macdrv_release_event(event);
            return NO;
        }
        else if (!resizable)
        {
            macdrv_event* event = macdrv_create_event(WINDOW_MAXIMIZE_REQUESTED, self);
            [queue postEvent:event];
            macdrv_release_event(event);
            return NO;
        }

        return YES;
    }

2993 2994
    - (void) windowWillClose:(NSNotification*)notification
    {
2995 2996
        WineWindow* child;

2997
        if (fakingClose) return;
2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009
        if (latentParentWindow)
        {
            [latentParentWindow->latentChildWindows removeObjectIdenticalTo:self];
            self.latentParentWindow = nil;
        }

        for (child in latentChildWindows)
        {
            if (child.latentParentWindow == self)
                child.latentParentWindow = nil;
        }
        [latentChildWindows removeAllObjects];
3010 3011
    }

3012 3013 3014
    - (void) windowWillEnterFullScreen:(NSNotification*)notification
    {
        enteringFullScreen = TRUE;
3015
        nonFullscreenFrame = self.wine_fractionalFrame;
3016 3017 3018 3019 3020
    }

    - (void) windowWillExitFullScreen:(NSNotification*)notification
    {
        exitingFullScreen = TRUE;
3021
        [self postWindowFrameChanged:nonFullscreenFrame fullscreen:FALSE resizing:FALSE skipSizeMove:FALSE];
3022 3023
    }

3024 3025
    - (void)windowWillMiniaturize:(NSNotification *)notification
    {
3026
        [self becameIneligibleParentOrChild];
3027
        [self grabDockIconSnapshotFromWindow:nil force:NO];
3028 3029
    }

3030 3031 3032 3033
    - (NSSize) windowWillResize:(NSWindow*)sender toSize:(NSSize)frameSize
    {
        if ([self inLiveResize])
        {
3034
            if (maximized)
3035
                return self.wine_fractionalFrame.size;
3036

3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051
            NSRect rect;
            macdrv_query* query;

            rect = [self frame];
            if (resizingFromLeft)
                rect.origin.x = NSMaxX(rect) - frameSize.width;
            if (!resizingFromTop)
                rect.origin.y = NSMaxY(rect) - frameSize.height;
            rect.size = frameSize;
            rect = [self contentRectForFrameRect:rect];
            [[WineApplicationController sharedController] flipRect:&rect];

            query = macdrv_create_query();
            query->type = QUERY_RESIZE_SIZE;
            query->window = (macdrv_window)[self retain];
3052
            query->resize_size.rect = cgrect_win_from_mac(NSRectToCGRect(rect));
3053 3054 3055 3056 3057
            query->resize_size.from_left = resizingFromLeft;
            query->resize_size.from_top = resizingFromTop;

            if ([self.queue query:query timeout:0.1])
            {
3058
                rect = NSRectFromCGRect(cgrect_mac_from_win(query->resize_size.rect));
3059 3060 3061 3062 3063 3064 3065 3066 3067 3068
                rect = [self frameRectForContentRect:rect];
                frameSize = rect.size;
            }

            macdrv_release_query(query);
        }

        return frameSize;
    }

3069 3070
    - (void) windowWillStartLiveResize:(NSNotification *)notification
    {
3071 3072
        [self endWindowDragging];

3073 3074 3075 3076
        if (maximized)
        {
            macdrv_event* event;
            NSRect frame = [self contentRectForFrameRect:self.frame];
3077

3078 3079 3080 3081
            [[WineApplicationController sharedController] flipRect:&frame];

            event = macdrv_create_event(WINDOW_RESTORE_REQUESTED, self);
            event->window_restore_requested.keep_frame = TRUE;
3082
            event->window_restore_requested.frame = cgrect_win_from_mac(NSRectToCGRect(frame));
3083 3084 3085 3086 3087
            [queue postEvent:event];
            macdrv_release_event(event);
        }
        else
            [self sendResizeStartQuery];
3088

3089 3090
        frameAtResizeStart = [self frame];
        resizingFromLeft = resizingFromTop = FALSE;
3091 3092
    }

3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133
    - (NSRect) windowWillUseStandardFrame:(NSWindow*)window defaultFrame:(NSRect)proposedFrame
    {
        macdrv_query* query;
        NSRect currentContentRect, proposedContentRect, newContentRect, screenRect;
        NSSize maxSize;

        query = macdrv_create_query();
        query->type = QUERY_MIN_MAX_INFO;
        query->window = (macdrv_window)[self retain];
        [self.queue query:query timeout:0.5];
        macdrv_release_query(query);

        currentContentRect = [self contentRectForFrameRect:[self frame]];
        proposedContentRect = [self contentRectForFrameRect:proposedFrame];

        maxSize = [self contentMaxSize];
        newContentRect.size.width = MIN(NSWidth(proposedContentRect), maxSize.width);
        newContentRect.size.height = MIN(NSHeight(proposedContentRect), maxSize.height);

        // Try to keep the top-left corner where it is.
        newContentRect.origin.x = NSMinX(currentContentRect);
        newContentRect.origin.y = NSMaxY(currentContentRect) - NSHeight(newContentRect);

        // If that pushes the bottom or right off the screen, pull it up and to the left.
        screenRect = [self contentRectForFrameRect:[[self screen] visibleFrame]];
        if (NSMaxX(newContentRect) > NSMaxX(screenRect))
            newContentRect.origin.x = NSMaxX(screenRect) - NSWidth(newContentRect);
        if (NSMinY(newContentRect) < NSMinY(screenRect))
            newContentRect.origin.y = NSMinY(screenRect);

        // If that pushes the top or left off the screen, push it down and the right
        // again.  Do this last because the top-left corner is more important than the
        // bottom-right.
        if (NSMinX(newContentRect) < NSMinX(screenRect))
            newContentRect.origin.x = NSMinX(screenRect);
        if (NSMaxY(newContentRect) > NSMaxY(screenRect))
            newContentRect.origin.y = NSMaxY(screenRect) - NSHeight(newContentRect);

        return [self frameRectForContentRect:newContentRect];
    }

3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148

    /*
     * ---------- NSPasteboardOwner methods ----------
     */
    - (void) pasteboard:(NSPasteboard *)sender provideDataForType:(NSString *)type
    {
        macdrv_query* query = macdrv_create_query();
        query->type = QUERY_PASTEBOARD_DATA;
        query->window = (macdrv_window)[self retain];
        query->pasteboard_data.type = (CFStringRef)[type copy];

        [self.queue query:query timeout:3];
        macdrv_release_query(query);
    }

3149 3150 3151 3152 3153 3154 3155
    - (void) pasteboardChangedOwner:(NSPasteboard*)sender
    {
        macdrv_event* event = macdrv_create_event(LOST_PASTEBOARD_OWNERSHIP, self);
        [queue postEvent:event];
        macdrv_release_event(event);
    }

3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181

    /*
     * ---------- NSDraggingDestination methods ----------
     */
    - (NSDragOperation) draggingEntered:(id <NSDraggingInfo>)sender
    {
        return [self draggingUpdated:sender];
    }

    - (void) draggingExited:(id <NSDraggingInfo>)sender
    {
        // This isn't really a query.  We don't need any response.  However, it
        // has to be processed in a similar manner as the other drag-and-drop
        // queries in order to maintain the proper order of operations.
        macdrv_query* query = macdrv_create_query();
        query->type = QUERY_DRAG_EXITED;
        query->window = (macdrv_window)[self retain];

        [self.queue query:query timeout:0.1];
        macdrv_release_query(query);
    }

    - (NSDragOperation) draggingUpdated:(id <NSDraggingInfo>)sender
    {
        NSDragOperation ret;
        NSPoint pt = [[self contentView] convertPoint:[sender draggingLocation] fromView:nil];
3182
        CGPoint cgpt = cgpoint_win_from_mac(NSPointToCGPoint(pt));
3183 3184 3185 3186 3187
        NSPasteboard* pb = [sender draggingPasteboard];

        macdrv_query* query = macdrv_create_query();
        query->type = QUERY_DRAG_OPERATION;
        query->window = (macdrv_window)[self retain];
3188 3189
        query->drag_operation.x = floor(cgpt.x);
        query->drag_operation.y = floor(cgpt.y);
3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204
        query->drag_operation.offered_ops = [sender draggingSourceOperationMask];
        query->drag_operation.accepted_op = NSDragOperationNone;
        query->drag_operation.pasteboard = (CFTypeRef)[pb retain];

        [self.queue query:query timeout:3];
        ret = query->status ? query->drag_operation.accepted_op : NSDragOperationNone;
        macdrv_release_query(query);

        return ret;
    }

    - (BOOL) performDragOperation:(id <NSDraggingInfo>)sender
    {
        BOOL ret;
        NSPoint pt = [[self contentView] convertPoint:[sender draggingLocation] fromView:nil];
3205
        CGPoint cgpt = cgpoint_win_from_mac(NSPointToCGPoint(pt));
3206 3207 3208 3209 3210
        NSPasteboard* pb = [sender draggingPasteboard];

        macdrv_query* query = macdrv_create_query();
        query->type = QUERY_DRAG_DROP;
        query->window = (macdrv_window)[self retain];
3211 3212
        query->drag_drop.x = floor(cgpt.x);
        query->drag_drop.y = floor(cgpt.y);
3213 3214 3215
        query->drag_drop.op = [sender draggingSourceOperationMask];
        query->drag_drop.pasteboard = (CFTypeRef)[pb retain];

3216
        [self.queue query:query timeout:3 * 60 flags:WineQueryProcessEvents];
3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227
        ret = query->status;
        macdrv_release_query(query);

        return ret;
    }

    - (BOOL) wantsPeriodicDraggingUpdates
    {
        return NO;
    }

3228 3229 3230 3231 3232 3233 3234 3235 3236 3237
@end


/***********************************************************************
 *              macdrv_create_cocoa_window
 *
 * Create a Cocoa window with the given content frame and features (e.g.
 * title bar, close box, etc.).
 */
macdrv_window macdrv_create_cocoa_window(const struct macdrv_window_features* wf,
3238
        CGRect frame, void* hwnd, macdrv_event_queue queue)
3239 3240 3241 3242 3243
{
    __block WineWindow* window;

    OnMainThread(^{
        window = [[WineWindow createWindowWithFeatures:wf
3244
                                           windowFrame:NSRectFromCGRect(cgrect_mac_from_win(frame))
3245
                                                  hwnd:hwnd
3246
                                                 queue:(WineEventQueue*)queue] retain];
3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261
    });

    return (macdrv_window)window;
}

/***********************************************************************
 *              macdrv_destroy_cocoa_window
 *
 * Destroy a Cocoa window.
 */
void macdrv_destroy_cocoa_window(macdrv_window w)
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    WineWindow* window = (WineWindow*)w;

3262
    OnMainThread(^{
3263
        window.closing = TRUE;
3264 3265 3266
        [window doOrderOut];
        [window close];
    });
3267
    [window.queue discardEventsMatchingMask:-1 forWindow:window];
3268 3269 3270 3271 3272
    [window release];

    [pool release];
}

3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283
/***********************************************************************
 *              macdrv_get_window_hwnd
 *
 * Get the hwnd that was set for the window at creation.
 */
void* macdrv_get_window_hwnd(macdrv_window w)
{
    WineWindow* window = (WineWindow*)w;
    return window.hwnd;
}

3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298
/***********************************************************************
 *              macdrv_set_cocoa_window_features
 *
 * Update a Cocoa window's features.
 */
void macdrv_set_cocoa_window_features(macdrv_window w,
        const struct macdrv_window_features* wf)
{
    WineWindow* window = (WineWindow*)w;

    OnMainThread(^{
        [window setWindowFeatures:wf];
    });
}

3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313
/***********************************************************************
 *              macdrv_set_cocoa_window_state
 *
 * Update a Cocoa window's state.
 */
void macdrv_set_cocoa_window_state(macdrv_window w,
        const struct macdrv_window_state* state)
{
    WineWindow* window = (WineWindow*)w;

    OnMainThread(^{
        [window setMacDrvState:state];
    });
}

3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331
/***********************************************************************
 *              macdrv_set_cocoa_window_title
 *
 * Set a Cocoa window's title.
 */
void macdrv_set_cocoa_window_title(macdrv_window w, const unsigned short* title,
        size_t length)
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    WineWindow* window = (WineWindow*)w;
    NSString* titleString;

    if (title)
        titleString = [NSString stringWithCharacters:title length:length];
    else
        titleString = @"";
    OnMainThreadAsync(^{
        [window setTitle:titleString];
3332
        if ([window isOrderedIn] && ![window isExcludedFromWindowsMenu])
3333
            [NSApp changeWindowsItem:window title:titleString filename:NO];
3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346
    });

    [pool release];
}

/***********************************************************************
 *              macdrv_order_cocoa_window
 *
 * Reorder a Cocoa window relative to other windows.  If prev is
 * non-NULL, it is ordered below that window.  Else, if next is non-NULL,
 * it is ordered above that window.  Otherwise, it is ordered to the
 * front.
 */
3347 3348
void macdrv_order_cocoa_window(macdrv_window w, macdrv_window p,
        macdrv_window n, int activate)
3349 3350
{
    WineWindow* window = (WineWindow*)w;
3351 3352
    WineWindow* prev = (WineWindow*)p;
    WineWindow* next = (WineWindow*)n;
3353

3354 3355 3356 3357
    OnMainThreadAsync(^{
        [window orderBelow:prev
                   orAbove:next
                  activate:activate];
3358
    });
3359 3360 3361 3362
    [window.queue discardEventsMatchingMask:event_mask_for_type(WINDOW_BROUGHT_FORWARD)
                                  forWindow:window];
    [next.queue discardEventsMatchingMask:event_mask_for_type(WINDOW_BROUGHT_FORWARD)
                                forWindow:next];
3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374
}

/***********************************************************************
 *              macdrv_hide_cocoa_window
 *
 * Hides a Cocoa window.
 */
void macdrv_hide_cocoa_window(macdrv_window w)
{
    WineWindow* window = (WineWindow*)w;

    OnMainThread(^{
3375
        [window doOrderOut];
3376 3377 3378 3379 3380 3381
    });
}

/***********************************************************************
 *              macdrv_set_cocoa_window_frame
 *
3382
 * Move a Cocoa window.
3383
 */
3384
void macdrv_set_cocoa_window_frame(macdrv_window w, const CGRect* new_frame)
3385 3386 3387
{
    WineWindow* window = (WineWindow*)w;

3388
    OnMainThread(^{
3389
        [window setFrameFromWine:NSRectFromCGRect(cgrect_mac_from_win(*new_frame))];
3390 3391
    });
}
3392

3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404
/***********************************************************************
 *              macdrv_get_cocoa_window_frame
 *
 * Gets the frame of a Cocoa window.
 */
void macdrv_get_cocoa_window_frame(macdrv_window w, CGRect* out_frame)
{
    WineWindow* window = (WineWindow*)w;

    OnMainThread(^{
        NSRect frame;

3405
        frame = [window contentRectForFrameRect:[window wine_fractionalFrame]];
3406
        [[WineApplicationController sharedController] flipRect:&frame];
3407
        *out_frame = cgrect_win_from_mac(NSRectToCGRect(frame));
3408 3409 3410
    });
}

3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424
/***********************************************************************
 *              macdrv_set_cocoa_parent_window
 *
 * Sets the parent window for a Cocoa window.  If parent is NULL, clears
 * the parent window.
 */
void macdrv_set_cocoa_parent_window(macdrv_window w, macdrv_window parent)
{
    WineWindow* window = (WineWindow*)w;

    OnMainThread(^{
        [window setMacDrvParentWindow:(WineWindow*)parent];
    });
}
3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453

/***********************************************************************
 *              macdrv_set_window_surface
 */
void macdrv_set_window_surface(macdrv_window w, void *surface, pthread_mutex_t *mutex)
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    WineWindow* window = (WineWindow*)w;

    OnMainThread(^{
        window.surface = surface;
        window.surface_mutex = mutex;
    });

    [pool release];
}

/***********************************************************************
 *              macdrv_window_needs_display
 *
 * Mark a window as needing display in a specified rect (in non-client
 * area coordinates).
 */
void macdrv_window_needs_display(macdrv_window w, CGRect rect)
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    WineWindow* window = (WineWindow*)w;

    OnMainThreadAsync(^{
3454
        [[window contentView] setNeedsDisplayInRect:NSRectFromCGRect(cgrect_mac_from_win(rect))];
3455 3456 3457 3458
    });

    [pool release];
}
3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472

/***********************************************************************
 *              macdrv_set_window_shape
 *
 * Sets the shape of a Cocoa window from an array of rectangles.  If
 * rects is NULL, resets the window's shape to its frame.
 */
void macdrv_set_window_shape(macdrv_window w, const CGRect *rects, int count)
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    WineWindow* window = (WineWindow*)w;

    OnMainThread(^{
        if (!rects || !count)
3473
        {
3474
            [window setShape:NULL];
3475
            [window checkEmptyShaped];
3476
        }
3477 3478
        else
        {
3479 3480
            CGMutablePathRef path;
            unsigned int i;
3481

3482 3483 3484 3485 3486
            path = CGPathCreateMutable();
            for (i = 0; i < count; i++)
                CGPathAddRect(path, NULL, cgrect_mac_from_win(rects[i]));
            [window setShape:path];
            CGPathRelease(path);
3487 3488 3489 3490 3491
        }
    });

    [pool release];
}
3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556

/***********************************************************************
 *              macdrv_set_window_alpha
 */
void macdrv_set_window_alpha(macdrv_window w, CGFloat alpha)
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    WineWindow* window = (WineWindow*)w;

    [window setAlphaValue:alpha];

    [pool release];
}

/***********************************************************************
 *              macdrv_set_window_color_key
 */
void macdrv_set_window_color_key(macdrv_window w, CGFloat keyRed, CGFloat keyGreen,
                                 CGFloat keyBlue)
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    WineWindow* window = (WineWindow*)w;

    OnMainThread(^{
        window.colorKeyed       = TRUE;
        window.colorKeyRed      = keyRed;
        window.colorKeyGreen    = keyGreen;
        window.colorKeyBlue     = keyBlue;
        [window checkTransparency];
    });

    [pool release];
}

/***********************************************************************
 *              macdrv_clear_window_color_key
 */
void macdrv_clear_window_color_key(macdrv_window w)
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    WineWindow* window = (WineWindow*)w;

    OnMainThread(^{
        window.colorKeyed = FALSE;
        [window checkTransparency];
    });

    [pool release];
}

/***********************************************************************
 *              macdrv_window_use_per_pixel_alpha
 */
void macdrv_window_use_per_pixel_alpha(macdrv_window w, int use_per_pixel_alpha)
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    WineWindow* window = (WineWindow*)w;

    OnMainThread(^{
        window.usePerPixelAlpha = use_per_pixel_alpha;
        [window checkTransparency];
    });

    [pool release];
}
3557 3558 3559 3560 3561 3562 3563 3564

/***********************************************************************
 *              macdrv_give_cocoa_window_focus
 *
 * Makes the Cocoa window "key" (gives it keyboard focus).  This also
 * orders it front and, if its frame was not within the desktop bounds,
 * Cocoa will typically move it on-screen.
 */
3565
void macdrv_give_cocoa_window_focus(macdrv_window w, int activate)
3566 3567 3568 3569
{
    WineWindow* window = (WineWindow*)w;

    OnMainThread(^{
3570
        [window makeFocused:activate];
3571 3572
    });
}
3573

3574 3575 3576 3577 3578 3579 3580 3581 3582 3583
/***********************************************************************
 *              macdrv_set_window_min_max_sizes
 *
 * Sets the window's minimum and maximum content sizes.
 */
void macdrv_set_window_min_max_sizes(macdrv_window w, CGSize min_size, CGSize max_size)
{
    WineWindow* window = (WineWindow*)w;

    OnMainThread(^{
3584
        [window setWineMinSize:NSSizeFromCGSize(cgsize_mac_from_win(min_size)) maxSize:NSSizeFromCGSize(cgsize_mac_from_win(max_size))];
3585 3586 3587
    });
}

3588 3589 3590
/***********************************************************************
 *              macdrv_create_view
 *
3591
 * Creates and returns a view with the specified frame rect.  The
3592 3593 3594
 * caller is responsible for calling macdrv_dispose_view() on the view
 * when it is done with it.
 */
3595
macdrv_view macdrv_create_view(CGRect rect)
3596 3597 3598 3599 3600 3601 3602 3603 3604
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    __block WineContentView* view;

    if (CGRectIsNull(rect)) rect = CGRectZero;

    OnMainThread(^{
        NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];

3605
        view = [[WineContentView alloc] initWithFrame:NSRectFromCGRect(cgrect_mac_from_win(rect))];
3606
        [view setWantsLayer:YES];
3607 3608 3609
        [view layer].minificationFilter = retina_on ? kCAFilterLinear : kCAFilterNearest;
        [view layer].magnificationFilter = retina_on ? kCAFilterLinear : kCAFilterNearest;
        [view layer].contentsScale = retina_on ? 2.0 : 1.0;
3610
        [view setAutoresizesSubviews:NO];
3611
        [view setAutoresizingMask:NSViewNotSizable];
3612
        [view setHidden:YES];
3613
        [view setWantsBestResolutionOpenGLSurface:retina_on];
3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639
        [nc addObserver:view
               selector:@selector(updateGLContexts)
                   name:NSViewGlobalFrameDidChangeNotification
                 object:view];
        [nc addObserver:view
               selector:@selector(updateGLContexts)
                   name:NSApplicationDidChangeScreenParametersNotification
                 object:NSApp];
    });

    [pool release];
    return (macdrv_view)view;
}

/***********************************************************************
 *              macdrv_dispose_view
 *
 * Destroys a view previously returned by macdrv_create_view.
 */
void macdrv_dispose_view(macdrv_view v)
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    WineContentView* view = (WineContentView*)v;

    OnMainThread(^{
        NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
3640
        WineWindow* window = (WineWindow*)[view window];
3641 3642 3643 3644 3645 3646 3647 3648 3649

        [nc removeObserver:view
                      name:NSViewGlobalFrameDidChangeNotification
                    object:view];
        [nc removeObserver:view
                      name:NSApplicationDidChangeScreenParametersNotification
                    object:NSApp];
        [view removeFromSuperview];
        [view release];
3650
        [window updateForGLSubviews];
3651 3652 3653 3654 3655 3656
    });

    [pool release];
}

/***********************************************************************
3657
 *              macdrv_set_view_frame
3658
 */
3659
void macdrv_set_view_frame(macdrv_view v, CGRect rect)
3660 3661 3662 3663 3664 3665
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    WineContentView* view = (WineContentView*)v;

    if (CGRectIsNull(rect)) rect = CGRectZero;

3666
    OnMainThreadAsync(^{
3667
        NSRect newFrame = NSRectFromCGRect(cgrect_mac_from_win(rect));
3668 3669 3670 3671
        NSRect oldFrame = [view frame];

        if (!NSEqualRects(oldFrame, newFrame))
        {
3672
            [[view superview] setNeedsDisplayInRect:oldFrame];
3673 3674 3675 3676 3677 3678 3679
            if (NSEqualPoints(oldFrame.origin, newFrame.origin))
                [view setFrameSize:newFrame.size];
            else if (NSEqualSizes(oldFrame.size, newFrame.size))
                [view setFrameOrigin:newFrame.origin];
            else
                [view setFrame:newFrame];
            [view setNeedsDisplay:YES];
3680 3681 3682 3683 3684 3685

            if (retina_enabled)
            {
                int backing_size[2] = { 0 };
                [view wine_setBackingSize:backing_size];
            }
3686
            [(WineWindow*)[view window] updateForGLSubviews];
3687
        }
3688 3689 3690 3691 3692
    });

    [pool release];
}

3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712
/***********************************************************************
 *              macdrv_set_view_superview
 *
 * Move a view to a new superview and position it relative to its
 * siblings.  If p is non-NULL, the view is ordered behind it.
 * Otherwise, the view is ordered above n.  If s is NULL, use the
 * content view of w as the new superview.
 */
void macdrv_set_view_superview(macdrv_view v, macdrv_view s, macdrv_window w, macdrv_view p, macdrv_view n)
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    WineContentView* view = (WineContentView*)v;
    WineContentView* superview = (WineContentView*)s;
    WineWindow* window = (WineWindow*)w;
    WineContentView* prev = (WineContentView*)p;
    WineContentView* next = (WineContentView*)n;

    if (!superview)
        superview = [window contentView];

3713
    OnMainThreadAsync(^{
3714 3715 3716 3717
        if (superview == [view superview])
        {
            NSArray* subviews = [superview subviews];
            NSUInteger index = [subviews indexOfObjectIdenticalTo:view];
3718
            if (!prev && !next && index == [subviews count] - 1)
3719
                return;
3720
            if (prev && index + 1 < [subviews count] && [subviews objectAtIndex:index + 1] == prev)
3721
                return;
3722
            if (!prev && next && index > 0 && [subviews objectAtIndex:index - 1] == next)
3723 3724 3725 3726 3727 3728
                return;
        }

        WineWindow* oldWindow = (WineWindow*)[view window];
        WineWindow* newWindow = (WineWindow*)[superview window];

3729 3730 3731 3732
#if !defined(MAC_OS_X_VERSION_10_10) || MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_10
        if (floor(NSAppKitVersionNumber) <= 1265 /*NSAppKitVersionNumber10_9*/)
            [view removeFromSuperview];
#endif
3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747
        if (prev)
            [superview addSubview:view positioned:NSWindowBelow relativeTo:prev];
        else
            [superview addSubview:view positioned:NSWindowAbove relativeTo:next];

        if (oldWindow != newWindow)
        {
            [oldWindow updateForGLSubviews];
            [newWindow updateForGLSubviews];
        }
    });

    [pool release];
}

3748 3749 3750 3751 3752 3753 3754 3755
/***********************************************************************
 *              macdrv_set_view_hidden
 */
void macdrv_set_view_hidden(macdrv_view v, int hidden)
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    WineContentView* view = (WineContentView*)v;

3756
    OnMainThreadAsync(^{
3757
        [view setHidden:hidden];
3758
        [(WineWindow*)view.window updateForGLSubviews];
3759 3760 3761 3762 3763
    });

    [pool release];
}

3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774
/***********************************************************************
 *              macdrv_add_view_opengl_context
 *
 * Add an OpenGL context to the list being tracked for each view.
 */
void macdrv_add_view_opengl_context(macdrv_view v, macdrv_opengl_context c)
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    WineContentView* view = (WineContentView*)v;
    WineOpenGLContext *context = (WineOpenGLContext*)c;

3775
    OnMainThread(^{
3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798
        [view addGLContext:context];
    });

    [pool release];
}

/***********************************************************************
 *              macdrv_remove_view_opengl_context
 *
 * Add an OpenGL context to the list being tracked for each view.
 */
void macdrv_remove_view_opengl_context(macdrv_view v, macdrv_opengl_context c)
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    WineContentView* view = (WineContentView*)v;
    WineOpenGLContext *context = (WineOpenGLContext*)c;

    OnMainThreadAsync(^{
        [view removeGLContext:context];
    });

    [pool release];
}
3799

3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835
#ifdef HAVE_METAL_METAL_H
macdrv_metal_device macdrv_create_metal_device(void)
{
    macdrv_metal_device ret;

#if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_11
    if (MTLCreateSystemDefaultDevice == NULL)
        return NULL;
#endif

    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    ret = (macdrv_metal_device)MTLCreateSystemDefaultDevice();
    [pool release];
    return ret;
}

void macdrv_release_metal_device(macdrv_metal_device d)
{
    NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
    [(id<MTLDevice>)d release];
    [pool release];
}

macdrv_metal_view macdrv_view_create_metal_view(macdrv_view v, macdrv_metal_device d)
{
    id<MTLDevice> device = (id<MTLDevice>)d;
    WineContentView* view = (WineContentView*)v;
    __block WineMetalView *metalView;

    OnMainThread(^{
        metalView = [view newMetalViewWithDevice:device];
    });

    return (macdrv_metal_view)metalView;
}

3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847
macdrv_metal_layer macdrv_view_get_metal_layer(macdrv_metal_view v)
{
    WineMetalView* view = (WineMetalView*)v;
    __block CAMetalLayer* layer;

    OnMainThread(^{
        layer = (CAMetalLayer*)view.layer;
    });

    return (macdrv_metal_layer)layer;
}

3848 3849 3850 3851 3852 3853 3854 3855 3856 3857
void macdrv_view_release_metal_view(macdrv_metal_view v)
{
    WineMetalView* view = (WineMetalView*)v;
    OnMainThread(^{
        [view removeFromSuperview];
        [view release];
    });
}
#endif

3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876
int macdrv_get_view_backing_size(macdrv_view v, int backing_size[2])
{
    WineContentView* view = (WineContentView*)v;

    if (![view isKindOfClass:[WineContentView class]])
        return FALSE;

    [view wine_getBackingSize:backing_size];
    return TRUE;
}

void macdrv_set_view_backing_size(macdrv_view v, const int backing_size[2])
{
    WineContentView* view = (WineContentView*)v;

    if ([view isKindOfClass:[WineContentView class]])
        [view wine_setBackingSize:backing_size];
}

3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917
/***********************************************************************
 *              macdrv_window_background_color
 *
 * Returns the standard Mac window background color as a 32-bit value of
 * the form 0x00rrggbb.
 */
uint32_t macdrv_window_background_color(void)
{
    static uint32_t result;
    static dispatch_once_t once;

    // Annoyingly, [NSColor windowBackgroundColor] refuses to convert to other
    // color spaces (RGB or grayscale).  So, the only way to get RGB values out
    // of it is to draw with it.
    dispatch_once(&once, ^{
        OnMainThread(^{
            unsigned char rgbx[4];
            unsigned char *planes = rgbx;
            NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:&planes
                                                                               pixelsWide:1
                                                                               pixelsHigh:1
                                                                            bitsPerSample:8
                                                                          samplesPerPixel:3
                                                                                 hasAlpha:NO
                                                                                 isPlanar:NO
                                                                           colorSpaceName:NSCalibratedRGBColorSpace
                                                                             bitmapFormat:0
                                                                              bytesPerRow:4
                                                                             bitsPerPixel:32];
            [NSGraphicsContext saveGraphicsState];
            [NSGraphicsContext setCurrentContext:[NSGraphicsContext graphicsContextWithBitmapImageRep:bitmap]];
            [[NSColor windowBackgroundColor] set];
            NSRectFill(NSMakeRect(0, 0, 1, 1));
            [NSGraphicsContext restoreGraphicsState];
            [bitmap release];
            result = rgbx[0] << 16 | rgbx[1] << 8 | rgbx[2];
        });
    });

    return result;
}
3918 3919 3920 3921

/***********************************************************************
 *              macdrv_send_text_input_event
 */
3922
void macdrv_send_text_input_event(int pressed, unsigned int flags, int repeat, int keyc, void* data, int* done)
3923
{
3924 3925 3926
    OnMainThreadAsync(^{
        BOOL ret;
        macdrv_event* event;
3927 3928 3929 3930
        WineWindow* window = (WineWindow*)[NSApp keyWindow];
        if (![window isKindOfClass:[WineWindow class]])
        {
            window = (WineWindow*)[NSApp mainWindow];
3931 3932
            if (![window isKindOfClass:[WineWindow class]])
                window = [[WineApplicationController sharedController] frontWineWindow];
3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958
        }

        if (window)
        {
            NSUInteger localFlags = flags;
            CGEventRef c;
            NSEvent* event;

            window.imeData = data;
            fix_device_modifiers_by_generic(&localFlags);

            // An NSEvent created with +keyEventWithType:... is internally marked
            // as synthetic and doesn't get sent through input methods.  But one
            // created from a CGEvent doesn't have that problem.
            c = CGEventCreateKeyboardEvent(NULL, keyc, pressed);
            CGEventSetFlags(c, localFlags);
            CGEventSetIntegerValueField(c, kCGKeyboardEventAutorepeat, repeat);
            event = [NSEvent eventWithCGEvent:c];
            CFRelease(c);

            window.commandDone = FALSE;
            ret = [[[window contentView] inputContext] handleEvent:event] && !window.commandDone;
        }
        else
            ret = FALSE;

3959 3960 3961 3962 3963 3964
        event = macdrv_create_event(SENT_TEXT_INPUT, window);
        event->sent_text_input.handled = ret;
        event->sent_text_input.done = done;
        [[window queue] postEvent:event];
        macdrv_release_event(event);
    });
3965
}
3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980

void macdrv_clear_ime_text(void)
{
    OnMainThreadAsync(^{
        WineWindow* window = (WineWindow*)[NSApp keyWindow];
        if (![window isKindOfClass:[WineWindow class]])
        {
            window = (WineWindow*)[NSApp mainWindow];
            if (![window isKindOfClass:[WineWindow class]])
                window = [[WineApplicationController sharedController] frontWineWindow];
        }
        if (window)
            [[window contentView] clearMarkedText];
    });
}