2 * MACDRV Cocoa application class
4 * Copyright 2011, 2012, 2013 Ken Thomases for CodeWeavers Inc.
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 #import <Carbon/Carbon.h>
25 #import "cocoa_event.h"
26 #import "cocoa_window.h"
29 static NSString* const WineAppWaitQueryResponseMode = @"WineAppWaitQueryResponseMode";
35 @implementation WineApplication
37 @synthesize wineController;
39 - (void) sendEvent:(NSEvent*)anEvent
41 if (![wineController handleEvent:anEvent])
43 [super sendEvent:anEvent];
44 [wineController didSendEvent:anEvent];
48 - (void) setWineController:(WineApplicationController*)newController
50 wineController = newController;
51 [self setDelegate:wineController];
57 @interface WarpRecord : NSObject
59 CGEventTimestamp timeBefore, timeAfter;
63 @property (nonatomic) CGEventTimestamp timeBefore;
64 @property (nonatomic) CGEventTimestamp timeAfter;
65 @property (nonatomic) CGPoint from;
66 @property (nonatomic) CGPoint to;
71 @implementation WarpRecord
73 @synthesize timeBefore, timeAfter, from, to;
78 @interface WineApplicationController ()
80 @property (readwrite, copy, nonatomic) NSEvent* lastFlagsChanged;
81 @property (copy, nonatomic) NSArray* cursorFrames;
82 @property (retain, nonatomic) NSTimer* cursorTimer;
83 @property (retain, nonatomic) NSCursor* cursor;
84 @property (retain, nonatomic) NSImage* applicationIcon;
85 @property (readonly, nonatomic) BOOL inputSourceIsInputMethod;
86 @property (retain, nonatomic) WineWindow* mouseCaptureWindow;
88 - (void) setupObservations;
89 - (void) applicationDidBecomeActive:(NSNotification *)notification;
91 static void PerformRequest(void *info);
96 @implementation WineApplicationController
98 @synthesize keyboardType, lastFlagsChanged;
99 @synthesize applicationIcon;
100 @synthesize cursorFrames, cursorTimer, cursor;
101 @synthesize mouseCaptureWindow;
103 @synthesize clippingCursor;
107 if (self == [WineApplicationController class])
109 NSDictionary* defaults = [NSDictionary dictionaryWithObjectsAndKeys:
110 @"", @"NSQuotedKeystrokeBinding",
111 @"", @"NSRepeatCountBinding",
112 [NSNumber numberWithBool:NO], @"ApplePressAndHoldEnabled",
114 [[NSUserDefaults standardUserDefaults] registerDefaults:defaults];
118 + (WineApplicationController*) sharedController
120 static WineApplicationController* sharedController;
121 static dispatch_once_t once;
123 dispatch_once(&once, ^{
124 sharedController = [[self alloc] init];
127 return sharedController;
135 CFRunLoopSourceContext context = { 0 };
136 context.perform = PerformRequest;
137 requestSource = CFRunLoopSourceCreate(NULL, 0, &context);
143 CFRunLoopAddSource(CFRunLoopGetMain(), requestSource, kCFRunLoopCommonModes);
144 CFRunLoopAddSource(CFRunLoopGetMain(), requestSource, (CFStringRef)WineAppWaitQueryResponseMode);
146 requests = [[NSMutableArray alloc] init];
147 requestsManipQueue = dispatch_queue_create("org.winehq.WineAppRequestManipQueue", NULL);
149 eventQueues = [[NSMutableArray alloc] init];
150 eventQueuesLock = [[NSLock alloc] init];
152 keyWindows = [[NSMutableArray alloc] init];
154 originalDisplayModes = [[NSMutableDictionary alloc] init];
155 latentDisplayModes = [[NSMutableDictionary alloc] init];
157 warpRecords = [[NSMutableArray alloc] init];
159 windowsBeingDragged = [[NSMutableSet alloc] init];
161 if (!requests || !requestsManipQueue || !eventQueues || !eventQueuesLock ||
162 !keyWindows || !originalDisplayModes || !latentDisplayModes || !warpRecords)
168 [self setupObservations];
170 keyboardType = LMGetKbdType();
172 if ([NSApp isActive])
173 [self applicationDidBecomeActive:nil];
180 [windowsBeingDragged release];
182 [screenFrameCGRects release];
183 [applicationIcon release];
184 [warpRecords release];
185 [cursorTimer release];
186 [cursorFrames release];
187 [latentDisplayModes release];
188 [originalDisplayModes release];
189 [keyWindows release];
190 [eventQueues release];
191 [eventQueuesLock release];
192 if (requestsManipQueue) dispatch_release(requestsManipQueue);
196 CFRunLoopSourceInvalidate(requestSource);
197 CFRelease(requestSource);
202 - (void) transformProcessToForeground
204 if ([NSApp activationPolicy] != NSApplicationActivationPolicyRegular)
208 NSString* bundleName;
212 [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
213 [NSApp activateIgnoringOtherApps:YES];
215 mainMenu = [[[NSMenu alloc] init] autorelease];
218 submenu = [[[NSMenu alloc] initWithTitle:@"Wine"] autorelease];
219 bundleName = [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString*)kCFBundleNameKey];
221 if ([bundleName length])
222 title = [NSString stringWithFormat:@"Hide %@", bundleName];
225 item = [submenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@""];
227 item = [submenu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"];
228 [item setKeyEquivalentModifierMask:NSCommandKeyMask | NSAlternateKeyMask];
230 item = [submenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""];
232 [submenu addItem:[NSMenuItem separatorItem]];
234 if ([bundleName length])
235 title = [NSString stringWithFormat:@"Quit %@", bundleName];
238 item = [submenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"];
239 [item setKeyEquivalentModifierMask:NSCommandKeyMask | NSAlternateKeyMask];
240 item = [[[NSMenuItem alloc] init] autorelease];
241 [item setTitle:@"Wine"];
242 [item setSubmenu:submenu];
243 [mainMenu addItem:item];
246 submenu = [[[NSMenu alloc] initWithTitle:@"Window"] autorelease];
247 [submenu addItemWithTitle:@"Minimize" action:@selector(performMiniaturize:) keyEquivalent:@""];
248 [submenu addItemWithTitle:@"Zoom" action:@selector(performZoom:) keyEquivalent:@""];
249 if ([NSWindow instancesRespondToSelector:@selector(toggleFullScreen:)])
251 item = [submenu addItemWithTitle:@"Enter Full Screen" action:@selector(toggleFullScreen:) keyEquivalent:@"f"];
252 [item setKeyEquivalentModifierMask:NSCommandKeyMask | NSAlternateKeyMask | NSControlKeyMask];
254 [submenu addItem:[NSMenuItem separatorItem]];
255 [submenu addItemWithTitle:@"Bring All to Front" action:@selector(arrangeInFront:) keyEquivalent:@""];
256 item = [[[NSMenuItem alloc] init] autorelease];
257 [item setTitle:@"Window"];
258 [item setSubmenu:submenu];
259 [mainMenu addItem:item];
261 [NSApp setMainMenu:mainMenu];
262 [NSApp setWindowsMenu:submenu];
264 [NSApp setApplicationIconImage:self.applicationIcon];
268 - (BOOL) waitUntilQueryDone:(int*)done timeout:(NSDate*)timeout processEvents:(BOOL)processEvents
270 PerformRequest(NULL);
276 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
277 NSEvent* event = [NSApp nextEventMatchingMask:NSAnyEventMask
279 inMode:NSDefaultRunLoopMode
282 [NSApp sendEvent:event];
286 [[NSRunLoop currentRunLoop] runMode:WineAppWaitQueryResponseMode beforeDate:timeout];
287 } while (!*done && [timeout timeIntervalSinceNow] >= 0);
292 - (BOOL) registerEventQueue:(WineEventQueue*)queue
294 [eventQueuesLock lock];
295 [eventQueues addObject:queue];
296 [eventQueuesLock unlock];
300 - (void) unregisterEventQueue:(WineEventQueue*)queue
302 [eventQueuesLock lock];
303 [eventQueues removeObjectIdenticalTo:queue];
304 [eventQueuesLock unlock];
307 - (void) computeEventTimeAdjustmentFromTicks:(unsigned long long)tickcount uptime:(uint64_t)uptime_ns
309 eventTimeAdjustment = (tickcount / 1000.0) - (uptime_ns / (double)NSEC_PER_SEC);
312 - (double) ticksForEventTime:(NSTimeInterval)eventTime
314 return (eventTime + eventTimeAdjustment) * 1000;
317 /* Invalidate old focus offers across all queues. */
318 - (void) invalidateGotFocusEvents
320 WineEventQueue* queue;
324 [eventQueuesLock lock];
325 for (queue in eventQueues)
327 [queue discardEventsMatchingMask:event_mask_for_type(WINDOW_GOT_FOCUS)
330 [eventQueuesLock unlock];
333 - (void) windowGotFocus:(WineWindow*)window
337 [self invalidateGotFocusEvents];
339 event = macdrv_create_event(WINDOW_GOT_FOCUS, window);
340 event->window_got_focus.serial = windowFocusSerial;
342 event->window_got_focus.tried_windows = [triedWindows retain];
344 event->window_got_focus.tried_windows = [[NSMutableSet alloc] init];
345 [window.queue postEvent:event];
346 macdrv_release_event(event);
349 - (void) windowRejectedFocusEvent:(const macdrv_event*)event
351 if (event->window_got_focus.serial == windowFocusSerial)
353 NSMutableArray* windows = [keyWindows mutableCopy];
354 NSNumber* windowNumber;
357 for (windowNumber in [NSWindow windowNumbersWithOptions:NSWindowNumberListAllSpaces])
359 window = (WineWindow*)[NSApp windowWithWindowNumber:[windowNumber integerValue]];
360 if ([window isKindOfClass:[WineWindow class]] && [window screen] &&
361 ![windows containsObject:window])
362 [windows addObject:window];
365 triedWindows = (NSMutableSet*)event->window_got_focus.tried_windows;
366 [triedWindows addObject:(WineWindow*)event->window];
367 for (window in windows)
369 if (![triedWindows containsObject:window] && [window canBecomeKeyWindow])
371 [window makeKeyWindow];
380 - (void) keyboardSelectionDidChange
382 TISInputSourceRef inputSourceLayout;
384 inputSourceIsInputMethodValid = FALSE;
386 inputSourceLayout = TISCopyCurrentKeyboardLayoutInputSource();
387 if (inputSourceLayout)
390 uchr = TISGetInputSourceProperty(inputSourceLayout,
391 kTISPropertyUnicodeKeyLayoutData);
395 WineEventQueue* queue;
397 event = macdrv_create_event(KEYBOARD_CHANGED, nil);
398 event->keyboard_changed.keyboard_type = self.keyboardType;
399 event->keyboard_changed.iso_keyboard = (KBGetLayoutType(self.keyboardType) == kKeyboardISO);
400 event->keyboard_changed.uchr = CFDataCreateCopy(NULL, uchr);
401 event->keyboard_changed.input_source = TISCopyCurrentKeyboardInputSource();
403 if (event->keyboard_changed.uchr)
405 [eventQueuesLock lock];
407 for (queue in eventQueues)
408 [queue postEvent:event];
410 [eventQueuesLock unlock];
413 macdrv_release_event(event);
416 CFRelease(inputSourceLayout);
420 - (void) enabledKeyboardInputSourcesChanged
422 macdrv_layout_list_needs_update = TRUE;
425 - (CGFloat) primaryScreenHeight
427 if (!primaryScreenHeightValid)
429 NSArray* screens = [NSScreen screens];
430 NSUInteger count = [screens count];
437 primaryScreenHeight = NSHeight([[screens objectAtIndex:0] frame]);
438 primaryScreenHeightValid = TRUE;
440 size = count * sizeof(CGRect);
441 if (!screenFrameCGRects)
442 screenFrameCGRects = [[NSMutableData alloc] initWithLength:size];
444 [screenFrameCGRects setLength:size];
446 rect = [screenFrameCGRects mutableBytes];
447 for (screen in screens)
449 CGRect temp = NSRectToCGRect([screen frame]);
450 temp.origin.y = primaryScreenHeight - CGRectGetMaxY(temp);
455 return 1280; /* arbitrary value */
458 return primaryScreenHeight;
461 - (NSPoint) flippedMouseLocation:(NSPoint)point
463 /* This relies on the fact that Cocoa's mouse location points are
464 actually off by one (precisely because they were flipped from
465 Quartz screen coordinates using this same technique). */
466 point.y = [self primaryScreenHeight] - point.y;
470 - (void) flipRect:(NSRect*)rect
472 // We don't use -primaryScreenHeight here so there's no chance of having
473 // out-of-date cached info. This method is called infrequently enough
474 // that getting the screen height each time is not prohibitively expensive.
475 rect->origin.y = NSMaxY([[[NSScreen screens] objectAtIndex:0] frame]) - NSMaxY(*rect);
478 - (WineWindow*) frontWineWindow
480 NSNumber* windowNumber;
481 for (windowNumber in [NSWindow windowNumbersWithOptions:NSWindowNumberListAllSpaces])
483 NSWindow* window = [NSApp windowWithWindowNumber:[windowNumber integerValue]];
484 if ([window isKindOfClass:[WineWindow class]] && [window screen])
485 return (WineWindow*)window;
491 - (void) adjustWindowLevels:(BOOL)active
493 NSArray* windowNumbers;
494 NSMutableArray* wineWindows;
495 NSNumber* windowNumber;
496 NSUInteger nextFloatingIndex = 0;
497 __block NSInteger maxLevel = NSIntegerMin;
498 __block NSInteger maxNonfloatingLevel = NSNormalWindowLevel;
499 __block WineWindow* prev = nil;
502 if ([NSApp isHidden]) return;
504 windowNumbers = [NSWindow windowNumbersWithOptions:0];
505 wineWindows = [[NSMutableArray alloc] initWithCapacity:[windowNumbers count]];
507 // For the most part, we rely on the window server's ordering of the windows
508 // to be authoritative. The one exception is if the "floating" property of
509 // one of the windows has been changed, it may be in the wrong level and thus
510 // in the order. This method is what's supposed to fix that up. So build
511 // a list of Wine windows sorted first by floating-ness and then by order
512 // as indicated by the window server.
513 for (windowNumber in windowNumbers)
515 window = (WineWindow*)[NSApp windowWithWindowNumber:[windowNumber integerValue]];
516 if ([window isKindOfClass:[WineWindow class]])
519 [wineWindows insertObject:window atIndex:nextFloatingIndex++];
521 [wineWindows addObject:window];
525 NSDisableScreenUpdates();
527 // Go from back to front so that all windows in front of one which is
528 // elevated for full-screen are also elevated.
529 [wineWindows enumerateObjectsWithOptions:NSEnumerationReverse
530 usingBlock:^(id obj, NSUInteger idx, BOOL *stop){
531 WineWindow* window = (WineWindow*)obj;
532 NSInteger origLevel = [window level];
533 NSInteger newLevel = [window minimumLevelForActive:active];
535 if (newLevel < maxLevel)
540 if (!window.floating && maxNonfloatingLevel < newLevel)
541 maxNonfloatingLevel = newLevel;
543 if (newLevel != origLevel)
545 [window setLevel:newLevel];
547 // -setLevel: puts the window at the front of its new level. If
548 // we decreased the level, that's good (it was in front of that
549 // level before, so it should still be now). But if we increased
550 // the level, the window should be toward the back (but still
551 // ahead of the previous windows we did this to).
552 if (origLevel < newLevel)
555 [window orderWindow:NSWindowAbove relativeTo:[prev windowNumber]];
557 [window orderBack:nil];
564 NSEnableScreenUpdates();
566 [wineWindows release];
568 // The above took care of the visible windows on the current space. That
569 // leaves windows on other spaces, minimized windows, and windows which
570 // are not ordered in. We want to leave windows on other spaces alone
571 // so the space remains just as they left it (when viewed in Exposé or
572 // Mission Control, for example). We'll adjust the window levels again
573 // after we switch to another space, anyway. Windows which aren't
574 // ordered in will be handled when we order them in. Minimized windows
575 // on the current space should be set to the level they would have gotten
576 // if they were at the front of the windows with the same floating-ness,
577 // because that's where they'll go if/when they are unminimized. Again,
578 // for good measure we'll adjust window levels again when a window is
580 for (window in [NSApp windows])
582 if ([window isKindOfClass:[WineWindow class]] && [window isMiniaturized] &&
583 [window isOnActiveSpace])
585 NSInteger origLevel = [window level];
586 NSInteger newLevel = [window minimumLevelForActive:YES];
587 NSInteger maxLevelForType = window.floating ? maxLevel : maxNonfloatingLevel;
589 if (newLevel < maxLevelForType)
590 newLevel = maxLevelForType;
592 if (newLevel != origLevel)
593 [window setLevel:newLevel];
598 - (void) adjustWindowLevels
600 [self adjustWindowLevels:[NSApp isActive]];
603 - (void) updateFullscreenWindows
605 if (capture_displays_for_fullscreen && [NSApp isActive])
607 BOOL anyFullscreen = FALSE;
608 NSNumber* windowNumber;
609 for (windowNumber in [NSWindow windowNumbersWithOptions:0])
611 WineWindow* window = (WineWindow*)[NSApp windowWithWindowNumber:[windowNumber integerValue]];
612 if ([window isKindOfClass:[WineWindow class]] && window.fullscreen)
614 anyFullscreen = TRUE;
621 if ([self areDisplaysCaptured] || CGCaptureAllDisplays() == CGDisplayNoErr)
622 displaysCapturedForFullscreen = TRUE;
624 else if (displaysCapturedForFullscreen)
626 if ([originalDisplayModes count] || CGReleaseAllDisplays() == CGDisplayNoErr)
627 displaysCapturedForFullscreen = FALSE;
632 - (void) activeSpaceDidChange
634 [self updateFullscreenWindows];
635 [self adjustWindowLevels];
638 - (void) sendDisplaysChanged:(BOOL)activating
641 WineEventQueue* queue;
643 event = macdrv_create_event(DISPLAYS_CHANGED, nil);
644 event->displays_changed.activating = activating;
646 [eventQueuesLock lock];
648 // If we're activating, then we just need one of our threads to get the
649 // event, so it can send it directly to the desktop window. Otherwise,
650 // we need all of the threads to get it because we don't know which owns
651 // the desktop window and only that one will do anything with it.
652 if (activating) event->deliver = 1;
654 for (queue in eventQueues)
655 [queue postEvent:event];
656 [eventQueuesLock unlock];
658 macdrv_release_event(event);
661 // We can compare two modes directly using CFEqual, but that may require that
662 // they are identical to a level that we don't need. In particular, when the
663 // OS switches between the integrated and discrete GPUs, the set of display
664 // modes can change in subtle ways. We're interested in whether two modes
665 // match in their most salient features, even if they aren't identical.
666 - (BOOL) mode:(CGDisplayModeRef)mode1 matchesMode:(CGDisplayModeRef)mode2
668 NSString *encoding1, *encoding2;
669 uint32_t ioflags1, ioflags2, different;
670 double refresh1, refresh2;
672 if (CGDisplayModeGetWidth(mode1) != CGDisplayModeGetWidth(mode2)) return FALSE;
673 if (CGDisplayModeGetHeight(mode1) != CGDisplayModeGetHeight(mode2)) return FALSE;
675 #if defined(MAC_OS_X_VERSION_10_8) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_8
676 if (CGDisplayModeGetPixelWidth != NULL &&
677 CGDisplayModeGetPixelWidth(mode1) != CGDisplayModeGetPixelWidth(mode2)) return FALSE;
678 if (CGDisplayModeGetPixelHeight != NULL &&
679 CGDisplayModeGetPixelHeight(mode1) != CGDisplayModeGetPixelHeight(mode2)) return FALSE;
682 encoding1 = [(NSString*)CGDisplayModeCopyPixelEncoding(mode1) autorelease];
683 encoding2 = [(NSString*)CGDisplayModeCopyPixelEncoding(mode2) autorelease];
684 if (![encoding1 isEqualToString:encoding2]) return FALSE;
686 ioflags1 = CGDisplayModeGetIOFlags(mode1);
687 ioflags2 = CGDisplayModeGetIOFlags(mode2);
688 different = ioflags1 ^ ioflags2;
689 if (different & (kDisplayModeValidFlag | kDisplayModeSafeFlag | kDisplayModeStretchedFlag |
690 kDisplayModeInterlacedFlag | kDisplayModeTelevisionFlag))
693 refresh1 = CGDisplayModeGetRefreshRate(mode1);
694 if (refresh1 == 0) refresh1 = 60;
695 refresh2 = CGDisplayModeGetRefreshRate(mode2);
696 if (refresh2 == 0) refresh2 = 60;
697 if (fabs(refresh1 - refresh2) > 0.1) return FALSE;
702 - (CGDisplayModeRef)modeMatchingMode:(CGDisplayModeRef)mode forDisplay:(CGDirectDisplayID)displayID
704 CGDisplayModeRef ret = NULL;
705 NSDictionary* options = nil;
707 #if defined(MAC_OS_X_VERSION_10_8) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_8
708 if (&kCGDisplayShowDuplicateLowResolutionModes != NULL)
709 options = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:TRUE]
710 forKey:(NSString*)kCGDisplayShowDuplicateLowResolutionModes];
713 NSArray *modes = [(NSArray*)CGDisplayCopyAllDisplayModes(displayID, (CFDictionaryRef)options) autorelease];
714 for (id candidateModeObject in modes)
716 CGDisplayModeRef candidateMode = (CGDisplayModeRef)candidateModeObject;
717 if ([self mode:candidateMode matchesMode:mode])
726 - (BOOL) setMode:(CGDisplayModeRef)mode forDisplay:(CGDirectDisplayID)displayID
729 NSNumber* displayIDKey = [NSNumber numberWithUnsignedInt:displayID];
730 CGDisplayModeRef originalMode;
732 originalMode = (CGDisplayModeRef)[originalDisplayModes objectForKey:displayIDKey];
734 if (originalMode && [self mode:mode matchesMode:originalMode])
736 if ([originalDisplayModes count] == 1) // If this is the last changed display, do a blanket reset
738 CGRestorePermanentDisplayConfiguration();
739 if (!displaysCapturedForFullscreen)
740 CGReleaseAllDisplays();
741 [originalDisplayModes removeAllObjects];
744 else // ... otherwise, try to restore just the one display
746 mode = [self modeMatchingMode:mode forDisplay:displayID];
747 if (mode && CGDisplaySetDisplayMode(displayID, mode, NULL) == CGDisplayNoErr)
749 [originalDisplayModes removeObjectForKey:displayIDKey];
756 BOOL active = [NSApp isActive];
757 CGDisplayModeRef currentMode;
759 currentMode = CGDisplayModeRetain((CGDisplayModeRef)[latentDisplayModes objectForKey:displayIDKey]);
761 currentMode = CGDisplayCopyDisplayMode(displayID);
762 if (!currentMode) // Invalid display ID
765 if ([self mode:mode matchesMode:currentMode]) // Already there!
767 CGDisplayModeRelease(currentMode);
771 CGDisplayModeRelease(currentMode);
774 mode = [self modeMatchingMode:mode forDisplay:displayID];
778 if ([originalDisplayModes count] || displaysCapturedForFullscreen ||
779 !active || CGCaptureAllDisplays() == CGDisplayNoErr)
783 // If we get here, we have the displays captured. If we don't
784 // know the original mode of the display, the current mode must
785 // be the original. We should re-query the current mode since
786 // another process could have changed it between when we last
787 // checked and when we captured the displays.
789 originalMode = currentMode = CGDisplayCopyDisplayMode(displayID);
792 ret = (CGDisplaySetDisplayMode(displayID, mode, NULL) == CGDisplayNoErr);
793 if (ret && !(currentMode && [self mode:mode matchesMode:currentMode]))
794 [originalDisplayModes setObject:(id)originalMode forKey:displayIDKey];
795 else if (![originalDisplayModes count])
797 CGRestorePermanentDisplayConfiguration();
798 if (!displaysCapturedForFullscreen)
799 CGReleaseAllDisplays();
803 CGDisplayModeRelease(currentMode);
807 [latentDisplayModes setObject:(id)mode forKey:displayIDKey];
814 [self adjustWindowLevels];
819 - (BOOL) areDisplaysCaptured
821 return ([originalDisplayModes count] > 0 || displaysCapturedForFullscreen);
824 - (void) updateCursor:(BOOL)force
826 if (force || lastTargetWindow)
828 if (clientWantsCursorHidden && !cursorHidden)
834 if (!cursorIsCurrent)
837 cursorIsCurrent = TRUE;
840 if (!clientWantsCursorHidden && cursorHidden)
843 cursorHidden = FALSE;
850 [[NSCursor arrowCursor] set];
851 cursorIsCurrent = FALSE;
856 cursorHidden = FALSE;
863 if (!clientWantsCursorHidden)
865 clientWantsCursorHidden = TRUE;
866 [self updateCursor:TRUE];
870 - (void) unhideCursor
872 if (clientWantsCursorHidden)
874 clientWantsCursorHidden = FALSE;
875 [self updateCursor:FALSE];
879 - (void) setCursor:(NSCursor*)newCursor
881 if (newCursor != cursor)
884 cursor = [newCursor retain];
885 cursorIsCurrent = FALSE;
886 [self updateCursor:FALSE];
892 NSDictionary* frame = [cursorFrames objectAtIndex:cursorFrame];
893 CGImageRef cgimage = (CGImageRef)[frame objectForKey:@"image"];
894 NSImage* image = [[NSImage alloc] initWithCGImage:cgimage size:NSZeroSize];
895 CFDictionaryRef hotSpotDict = (CFDictionaryRef)[frame objectForKey:@"hotSpot"];
898 if (!CGPointMakeWithDictionaryRepresentation(hotSpotDict, &hotSpot))
899 hotSpot = CGPointZero;
900 self.cursor = [[[NSCursor alloc] initWithImage:image hotSpot:NSPointFromCGPoint(hotSpot)] autorelease];
905 - (void) nextCursorFrame:(NSTimer*)theTimer
908 NSTimeInterval duration;
912 if (cursorFrame >= [cursorFrames count])
916 frame = [cursorFrames objectAtIndex:cursorFrame];
917 duration = [[frame objectForKey:@"duration"] doubleValue];
918 date = [[theTimer fireDate] dateByAddingTimeInterval:duration];
919 [cursorTimer setFireDate:date];
922 - (void) setCursorWithFrames:(NSArray*)frames
924 if (self.cursorFrames == frames)
927 self.cursorFrames = frames;
929 [cursorTimer invalidate];
930 self.cursorTimer = nil;
934 if ([frames count] > 1)
936 NSDictionary* frame = [frames objectAtIndex:0];
937 NSTimeInterval duration = [[frame objectForKey:@"duration"] doubleValue];
938 NSDate* date = [NSDate dateWithTimeIntervalSinceNow:duration];
939 self.cursorTimer = [[[NSTimer alloc] initWithFireDate:date
942 selector:@selector(nextCursorFrame:)
944 repeats:YES] autorelease];
945 [[NSRunLoop currentRunLoop] addTimer:cursorTimer forMode:NSRunLoopCommonModes];
952 - (void) setApplicationIconFromCGImageArray:(NSArray*)images
954 NSImage* nsimage = nil;
958 NSSize bestSize = NSZeroSize;
961 nsimage = [[[NSImage alloc] initWithSize:NSZeroSize] autorelease];
963 for (image in images)
965 CGImageRef cgimage = (CGImageRef)image;
966 NSBitmapImageRep* imageRep = [[NSBitmapImageRep alloc] initWithCGImage:cgimage];
969 NSSize size = [imageRep size];
971 [nsimage addRepresentation:imageRep];
974 if (MIN(size.width, size.height) > MIN(bestSize.width, bestSize.height))
979 if ([[nsimage representations] count] && bestSize.width && bestSize.height)
980 [nsimage setSize:bestSize];
985 self.applicationIcon = nsimage;
988 - (void) handleCommandTab
990 if ([NSApp isActive])
992 NSRunningApplication* thisApp = [NSRunningApplication currentApplication];
993 NSRunningApplication* app;
994 NSRunningApplication* otherValidApp = nil;
996 if ([originalDisplayModes count] || displaysCapturedForFullscreen)
999 for (displayID in originalDisplayModes)
1001 CGDisplayModeRef mode = CGDisplayCopyDisplayMode([displayID unsignedIntValue]);
1002 [latentDisplayModes setObject:(id)mode forKey:displayID];
1003 CGDisplayModeRelease(mode);
1006 CGRestorePermanentDisplayConfiguration();
1007 CGReleaseAllDisplays();
1008 [originalDisplayModes removeAllObjects];
1009 displaysCapturedForFullscreen = FALSE;
1012 for (app in [[NSWorkspace sharedWorkspace] runningApplications])
1014 if (![app isEqual:thisApp] && !app.terminated &&
1015 app.activationPolicy == NSApplicationActivationPolicyRegular)
1019 // There's another visible app. Just hide ourselves and let
1020 // the system activate the other app.
1026 otherValidApp = app;
1030 // Didn't find a visible GUI app. Try the Finder or, if that's not
1031 // running, the first hidden GUI app. If even that doesn't work, we
1032 // just fail to switch and remain the active app.
1033 app = [[NSRunningApplication runningApplicationsWithBundleIdentifier:@"com.apple.finder"] lastObject];
1034 if (!app) app = otherValidApp;
1036 [app activateWithOptions:0];
1041 * ---------- Cursor clipping methods ----------
1043 * Neither Quartz nor Cocoa has an exact analog for Win32 cursor clipping.
1044 * For one simple case, clipping to a 1x1 rectangle, Quartz does have an
1045 * equivalent: CGAssociateMouseAndMouseCursorPosition(false). For the
1046 * general case, we leverage that. We disassociate mouse movements from
1047 * the cursor position and then move the cursor manually, keeping it within
1048 * the clipping rectangle.
1050 * Moving the cursor manually isn't enough. We need to modify the event
1051 * stream so that the events have the new location, too. We need to do
1052 * this at a point before the events enter Cocoa, so that Cocoa will assign
1053 * the correct window to the event. So, we install a Quartz event tap to
1056 * Also, there's a complication when we move the cursor. We use
1057 * CGWarpMouseCursorPosition(). That doesn't generate mouse movement
1058 * events, but the change of cursor position is incorporated into the
1059 * deltas of the next mouse move event. When the mouse is disassociated
1060 * from the cursor position, we need the deltas to only reflect actual
1061 * device movement, not programmatic changes. So, the event tap cancels
1062 * out the change caused by our calls to CGWarpMouseCursorPosition().
1064 - (void) clipCursorLocation:(CGPoint*)location
1066 if (location->x < CGRectGetMinX(cursorClipRect))
1067 location->x = CGRectGetMinX(cursorClipRect);
1068 if (location->y < CGRectGetMinY(cursorClipRect))
1069 location->y = CGRectGetMinY(cursorClipRect);
1070 if (location->x > CGRectGetMaxX(cursorClipRect) - 1)
1071 location->x = CGRectGetMaxX(cursorClipRect) - 1;
1072 if (location->y > CGRectGetMaxY(cursorClipRect) - 1)
1073 location->y = CGRectGetMaxY(cursorClipRect) - 1;
1076 - (BOOL) warpCursorTo:(CGPoint*)newLocation from:(const CGPoint*)currentLocation
1078 CGPoint oldLocation;
1080 if (currentLocation)
1081 oldLocation = *currentLocation;
1083 oldLocation = NSPointToCGPoint([self flippedMouseLocation:[NSEvent mouseLocation]]);
1085 if (!CGPointEqualToPoint(oldLocation, *newLocation))
1087 WarpRecord* warpRecord = [[[WarpRecord alloc] init] autorelease];
1090 warpRecord.from = oldLocation;
1091 warpRecord.timeBefore = [[NSProcessInfo processInfo] systemUptime] * NSEC_PER_SEC;
1093 /* Actually move the cursor. */
1094 err = CGWarpMouseCursorPosition(*newLocation);
1095 if (err != kCGErrorSuccess)
1098 warpRecord.timeAfter = [[NSProcessInfo processInfo] systemUptime] * NSEC_PER_SEC;
1099 *newLocation = NSPointToCGPoint([self flippedMouseLocation:[NSEvent mouseLocation]]);
1101 if (!CGPointEqualToPoint(oldLocation, *newLocation))
1103 warpRecord.to = *newLocation;
1104 [warpRecords addObject:warpRecord];
1111 - (BOOL) isMouseMoveEventType:(CGEventType)type
1115 case kCGEventMouseMoved:
1116 case kCGEventLeftMouseDragged:
1117 case kCGEventRightMouseDragged:
1118 case kCGEventOtherMouseDragged:
1125 - (int) warpsFinishedByEventTime:(CGEventTimestamp)eventTime location:(CGPoint)eventLocation
1127 int warpsFinished = 0;
1128 for (WarpRecord* warpRecord in warpRecords)
1130 if (warpRecord.timeAfter < eventTime ||
1131 (warpRecord.timeBefore <= eventTime && CGPointEqualToPoint(eventLocation, warpRecord.to)))
1137 return warpsFinished;
1140 - (CGEventRef) eventTapWithProxy:(CGEventTapProxy)proxy
1141 type:(CGEventType)type
1142 event:(CGEventRef)event
1144 CGEventTimestamp eventTime;
1145 CGPoint eventLocation, cursorLocation;
1147 if (type == kCGEventTapDisabledByUserInput)
1149 if (type == kCGEventTapDisabledByTimeout)
1151 CGEventTapEnable(cursorClippingEventTap, TRUE);
1155 if (!clippingCursor)
1158 eventTime = CGEventGetTimestamp(event);
1159 lastEventTapEventTime = eventTime / (double)NSEC_PER_SEC;
1161 eventLocation = CGEventGetLocation(event);
1163 cursorLocation = NSPointToCGPoint([self flippedMouseLocation:[NSEvent mouseLocation]]);
1165 if ([self isMouseMoveEventType:type])
1167 double deltaX, deltaY;
1168 int warpsFinished = [self warpsFinishedByEventTime:eventTime location:eventLocation];
1171 deltaX = CGEventGetDoubleValueField(event, kCGMouseEventDeltaX);
1172 deltaY = CGEventGetDoubleValueField(event, kCGMouseEventDeltaY);
1174 for (i = 0; i < warpsFinished; i++)
1176 WarpRecord* warpRecord = [warpRecords objectAtIndex:0];
1177 deltaX -= warpRecord.to.x - warpRecord.from.x;
1178 deltaY -= warpRecord.to.y - warpRecord.from.y;
1179 [warpRecords removeObjectAtIndex:0];
1184 CGEventSetDoubleValueField(event, kCGMouseEventDeltaX, deltaX);
1185 CGEventSetDoubleValueField(event, kCGMouseEventDeltaY, deltaY);
1188 synthesizedLocation.x += deltaX;
1189 synthesizedLocation.y += deltaY;
1192 // If the event is destined for another process, don't clip it. This may
1193 // happen if the user activates Exposé or Mission Control. In that case,
1194 // our app does not resign active status, so clipping is still in effect,
1195 // but the cursor should not actually be clipped.
1197 // In addition, the fact that mouse moves may have been delivered to a
1198 // different process means we have to treat the next one we receive as
1199 // absolute rather than relative.
1200 if (CGEventGetIntegerValueField(event, kCGEventTargetUnixProcessID) == getpid())
1201 [self clipCursorLocation:&synthesizedLocation];
1203 lastSetCursorPositionTime = lastEventTapEventTime;
1205 [self warpCursorTo:&synthesizedLocation from:&cursorLocation];
1206 if (!CGPointEqualToPoint(eventLocation, synthesizedLocation))
1207 CGEventSetLocation(event, synthesizedLocation);
1212 CGEventRef WineAppEventTapCallBack(CGEventTapProxy proxy, CGEventType type,
1213 CGEventRef event, void *refcon)
1215 WineApplicationController* controller = refcon;
1216 return [controller eventTapWithProxy:proxy type:type event:event];
1219 - (BOOL) installEventTap
1221 ProcessSerialNumber psn;
1223 CGEventMask mask = CGEventMaskBit(kCGEventLeftMouseDown) |
1224 CGEventMaskBit(kCGEventLeftMouseUp) |
1225 CGEventMaskBit(kCGEventRightMouseDown) |
1226 CGEventMaskBit(kCGEventRightMouseUp) |
1227 CGEventMaskBit(kCGEventMouseMoved) |
1228 CGEventMaskBit(kCGEventLeftMouseDragged) |
1229 CGEventMaskBit(kCGEventRightMouseDragged) |
1230 CGEventMaskBit(kCGEventOtherMouseDown) |
1231 CGEventMaskBit(kCGEventOtherMouseUp) |
1232 CGEventMaskBit(kCGEventOtherMouseDragged) |
1233 CGEventMaskBit(kCGEventScrollWheel);
1234 CFRunLoopSourceRef source;
1236 OSErr (*pGetCurrentProcess)(ProcessSerialNumber* PSN);
1238 if (cursorClippingEventTap)
1241 // We need to get the Mac GetCurrentProcess() from the ApplicationServices
1242 // framework with dlsym() because the Win32 function of the same name
1244 appServices = dlopen("/System/Library/Frameworks/ApplicationServices.framework/ApplicationServices", RTLD_LAZY);
1248 pGetCurrentProcess = dlsym(appServices, "GetCurrentProcess");
1249 if (!pGetCurrentProcess)
1251 dlclose(appServices);
1255 err = pGetCurrentProcess(&psn);
1256 dlclose(appServices);
1260 // We create an annotated session event tap rather than a process-specific
1261 // event tap because we need to programmatically move the cursor even when
1262 // mouse moves are directed to other processes. We disable our tap when
1263 // other processes are active, but things like Exposé are handled by other
1264 // processes even when we remain active.
1265 cursorClippingEventTap = CGEventTapCreate(kCGAnnotatedSessionEventTap, kCGHeadInsertEventTap,
1266 kCGEventTapOptionDefault, mask, WineAppEventTapCallBack, self);
1267 if (!cursorClippingEventTap)
1270 CGEventTapEnable(cursorClippingEventTap, FALSE);
1272 source = CFMachPortCreateRunLoopSource(NULL, cursorClippingEventTap, 0);
1275 CFRelease(cursorClippingEventTap);
1276 cursorClippingEventTap = NULL;
1280 CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopCommonModes);
1285 - (BOOL) setCursorPosition:(CGPoint)pos
1289 if ([windowsBeingDragged count])
1291 else if (clippingCursor)
1293 [self clipCursorLocation:&pos];
1295 ret = [self warpCursorTo:&pos from:NULL];
1296 synthesizedLocation = pos;
1299 // We want to discard mouse-move events that have already been
1300 // through the event tap, because it's too late to account for
1301 // the setting of the cursor position with them. However, the
1302 // events that may be queued with times after that but before
1303 // the above warp can still be used. So, use the last event
1304 // tap event time so that -sendEvent: doesn't discard them.
1305 lastSetCursorPositionTime = lastEventTapEventTime;
1310 ret = (CGWarpMouseCursorPosition(pos) == kCGErrorSuccess);
1313 lastSetCursorPositionTime = [[NSProcessInfo processInfo] systemUptime];
1315 // Annoyingly, CGWarpMouseCursorPosition() effectively disassociates
1316 // the mouse from the cursor position for 0.25 seconds. This means
1317 // that mouse movement during that interval doesn't move the cursor
1318 // and events carry a constant location (the warped-to position)
1319 // even though they have delta values. This screws us up because
1320 // the accumulated deltas we send to Wine don't match any eventual
1321 // absolute position we send (like with a button press). We can
1322 // work around this by simply forcibly reassociating the mouse and
1324 CGAssociateMouseAndMouseCursorPosition(true);
1330 WineEventQueue* queue;
1332 // Discard all pending mouse move events.
1333 [eventQueuesLock lock];
1334 for (queue in eventQueues)
1336 [queue discardEventsMatchingMask:event_mask_for_type(MOUSE_MOVED) |
1337 event_mask_for_type(MOUSE_MOVED_ABSOLUTE)
1339 [queue resetMouseEventPositions:pos];
1341 [eventQueuesLock unlock];
1347 - (void) activateCursorClipping
1349 if (cursorClippingEventTap && !CGEventTapIsEnabled(cursorClippingEventTap))
1351 CGEventTapEnable(cursorClippingEventTap, TRUE);
1352 [self setCursorPosition:NSPointToCGPoint([self flippedMouseLocation:[NSEvent mouseLocation]])];
1356 - (void) deactivateCursorClipping
1358 if (cursorClippingEventTap && CGEventTapIsEnabled(cursorClippingEventTap))
1360 CGEventTapEnable(cursorClippingEventTap, FALSE);
1361 [warpRecords removeAllObjects];
1362 lastSetCursorPositionTime = [[NSProcessInfo processInfo] systemUptime];
1366 - (void) updateCursorClippingState
1368 if (clippingCursor && [NSApp isActive] && ![windowsBeingDragged count])
1369 [self activateCursorClipping];
1371 [self deactivateCursorClipping];
1374 - (void) updateWindowsForCursorClipping
1377 for (window in [NSApp windows])
1379 if ([window isKindOfClass:[WineWindow class]])
1380 [window updateForCursorClipping];
1384 - (BOOL) startClippingCursor:(CGRect)rect
1388 if (!cursorClippingEventTap && ![self installEventTap])
1391 if (clippingCursor && CGRectEqualToRect(rect, cursorClipRect) &&
1392 CGEventTapIsEnabled(cursorClippingEventTap))
1395 err = CGAssociateMouseAndMouseCursorPosition(false);
1396 if (err != kCGErrorSuccess)
1399 clippingCursor = TRUE;
1400 cursorClipRect = rect;
1401 [self updateCursorClippingState];
1402 [self updateWindowsForCursorClipping];
1407 - (BOOL) stopClippingCursor
1409 CGError err = CGAssociateMouseAndMouseCursorPosition(true);
1410 if (err != kCGErrorSuccess)
1413 clippingCursor = FALSE;
1414 [self updateCursorClippingState];
1415 [self updateWindowsForCursorClipping];
1420 - (BOOL) isKeyPressed:(uint16_t)keyCode
1422 int bits = sizeof(pressedKeyCodes[0]) * 8;
1423 int index = keyCode / bits;
1424 uint32_t mask = 1 << (keyCode % bits);
1425 return (pressedKeyCodes[index] & mask) != 0;
1428 - (void) noteKey:(uint16_t)keyCode pressed:(BOOL)pressed
1430 int bits = sizeof(pressedKeyCodes[0]) * 8;
1431 int index = keyCode / bits;
1432 uint32_t mask = 1 << (keyCode % bits);
1434 pressedKeyCodes[index] |= mask;
1436 pressedKeyCodes[index] &= ~mask;
1439 - (void) handleMouseMove:(NSEvent*)anEvent
1441 WineWindow* targetWindow;
1442 BOOL drag = [anEvent type] != NSMouseMoved;
1444 if ([windowsBeingDragged count])
1446 else if (mouseCaptureWindow)
1447 targetWindow = mouseCaptureWindow;
1449 targetWindow = (WineWindow*)[anEvent window];
1452 /* Because of the way -[NSWindow setAcceptsMouseMovedEvents:] works, the
1453 event indicates its window is the main window, even if the cursor is
1454 over a different window. Find the actual WineWindow that is under the
1455 cursor and post the event as being for that window. */
1456 CGPoint cgpoint = CGEventGetLocation([anEvent CGEvent]);
1457 NSPoint point = [self flippedMouseLocation:NSPointFromCGPoint(cgpoint)];
1458 NSInteger windowUnderNumber;
1460 windowUnderNumber = [NSWindow windowNumberAtPoint:point
1461 belowWindowWithWindowNumber:0];
1462 targetWindow = (WineWindow*)[NSApp windowWithWindowNumber:windowUnderNumber];
1463 if (!NSMouseInRect(point, [targetWindow contentRectForFrameRect:[targetWindow frame]], NO))
1467 if ([targetWindow isKindOfClass:[WineWindow class]])
1469 CGPoint point = CGEventGetLocation([anEvent CGEvent]);
1470 macdrv_event* event;
1473 // If we recently warped the cursor (other than in our cursor-clipping
1474 // event tap), discard mouse move events until we see an event which is
1475 // later than that time.
1476 if (lastSetCursorPositionTime)
1478 if ([anEvent timestamp] <= lastSetCursorPositionTime)
1481 lastSetCursorPositionTime = 0;
1482 forceNextMouseMoveAbsolute = TRUE;
1485 if (forceNextMouseMoveAbsolute || targetWindow != lastTargetWindow)
1488 forceNextMouseMoveAbsolute = FALSE;
1492 // Send absolute move events if the cursor is in the interior of
1493 // its range. Only send relative moves if the cursor is pinned to
1494 // the boundaries of where it can go. We compute the position
1495 // that's one additional point in the direction of movement. If
1496 // that is outside of the clipping rect or desktop region (the
1497 // union of the screen frames), then we figure the cursor would
1498 // have moved outside if it could but it was pinned.
1499 CGPoint computedPoint = point;
1500 CGFloat deltaX = [anEvent deltaX];
1501 CGFloat deltaY = [anEvent deltaY];
1505 else if (deltaX < -0.001)
1510 else if (deltaY < -0.001)
1513 // Assume cursor is pinned for now
1515 if (!clippingCursor || CGRectContainsPoint(cursorClipRect, computedPoint))
1517 const CGRect* rects;
1518 NSUInteger count, i;
1520 // Caches screenFrameCGRects if necessary
1521 [self primaryScreenHeight];
1523 rects = [screenFrameCGRects bytes];
1524 count = [screenFrameCGRects length] / sizeof(rects[0]);
1526 for (i = 0; i < count; i++)
1528 if (CGRectContainsPoint(rects[i], computedPoint))
1540 [self clipCursorLocation:&point];
1542 event = macdrv_create_event(MOUSE_MOVED_ABSOLUTE, targetWindow);
1543 event->mouse_moved.x = point.x;
1544 event->mouse_moved.y = point.y;
1546 mouseMoveDeltaX = 0;
1547 mouseMoveDeltaY = 0;
1551 /* Add event delta to accumulated delta error */
1552 /* deltaY is already flipped */
1553 mouseMoveDeltaX += [anEvent deltaX];
1554 mouseMoveDeltaY += [anEvent deltaY];
1556 event = macdrv_create_event(MOUSE_MOVED, targetWindow);
1557 event->mouse_moved.x = mouseMoveDeltaX;
1558 event->mouse_moved.y = mouseMoveDeltaY;
1560 /* Keep the remainder after integer truncation. */
1561 mouseMoveDeltaX -= event->mouse_moved.x;
1562 mouseMoveDeltaY -= event->mouse_moved.y;
1565 if (event->type == MOUSE_MOVED_ABSOLUTE || event->mouse_moved.x || event->mouse_moved.y)
1567 event->mouse_moved.time_ms = [self ticksForEventTime:[anEvent timestamp]];
1568 event->mouse_moved.drag = drag;
1570 [targetWindow.queue postEvent:event];
1573 macdrv_release_event(event);
1575 lastTargetWindow = targetWindow;
1578 lastTargetWindow = nil;
1580 [self updateCursor:FALSE];
1583 - (void) handleMouseButton:(NSEvent*)theEvent
1585 WineWindow* window = (WineWindow*)[theEvent window];
1586 NSEventType type = [theEvent type];
1587 BOOL broughtWindowForward = FALSE;
1589 if ([window isKindOfClass:[WineWindow class]] &&
1590 !window.disabled && !window.noActivate &&
1591 type == NSLeftMouseDown &&
1592 (([theEvent modifierFlags] & (NSShiftKeyMask | NSControlKeyMask| NSAlternateKeyMask | NSCommandKeyMask)) != NSCommandKeyMask))
1594 NSWindowButton windowButton;
1596 broughtWindowForward = TRUE;
1598 /* Any left-click on our window anyplace other than the close or
1599 minimize buttons will bring it forward. */
1600 for (windowButton = NSWindowCloseButton;
1601 windowButton <= NSWindowMiniaturizeButton;
1604 NSButton* button = [window standardWindowButton:windowButton];
1607 NSPoint point = [button convertPoint:[theEvent locationInWindow] fromView:nil];
1608 if ([button mouse:point inRect:[button bounds]])
1610 broughtWindowForward = FALSE;
1617 if ([windowsBeingDragged count])
1619 else if (mouseCaptureWindow)
1620 window = mouseCaptureWindow;
1622 if ([window isKindOfClass:[WineWindow class]])
1624 BOOL pressed = (type == NSLeftMouseDown || type == NSRightMouseDown || type == NSOtherMouseDown);
1625 CGPoint pt = CGEventGetLocation([theEvent CGEvent]);
1629 [self clipCursorLocation:&pt];
1633 if (mouseCaptureWindow)
1637 // Test if the click was in the window's content area.
1638 NSPoint nspoint = [self flippedMouseLocation:NSPointFromCGPoint(pt)];
1639 NSRect contentRect = [window contentRectForFrameRect:[window frame]];
1640 process = NSMouseInRect(nspoint, contentRect, NO);
1641 if (process && [window styleMask] & NSResizableWindowMask)
1643 // Ignore clicks in the grow box (resize widget).
1644 HIPoint origin = { 0, 0 };
1645 HIThemeGrowBoxDrawInfo info = { 0 };
1649 info.kind = kHIThemeGrowBoxKindNormal;
1650 info.direction = kThemeGrowRight | kThemeGrowDown;
1651 if ([window styleMask] & NSUtilityWindowMask)
1652 info.size = kHIThemeGrowBoxSizeSmall;
1654 info.size = kHIThemeGrowBoxSizeNormal;
1656 status = HIThemeGetGrowBoxBounds(&origin, &info, &bounds);
1657 if (status == noErr)
1659 NSRect growBox = NSMakeRect(NSMaxX(contentRect) - bounds.size.width,
1660 NSMinY(contentRect),
1662 bounds.size.height);
1663 process = !NSMouseInRect(nspoint, growBox, NO);
1668 unmatchedMouseDowns |= NSEventMaskFromType(type);
1672 NSEventType downType = type - 1;
1673 NSUInteger downMask = NSEventMaskFromType(downType);
1674 process = (unmatchedMouseDowns & downMask) != 0;
1675 unmatchedMouseDowns &= ~downMask;
1680 macdrv_event* event;
1682 event = macdrv_create_event(MOUSE_BUTTON, window);
1683 event->mouse_button.button = [theEvent buttonNumber];
1684 event->mouse_button.pressed = pressed;
1685 event->mouse_button.x = pt.x;
1686 event->mouse_button.y = pt.y;
1687 event->mouse_button.time_ms = [self ticksForEventTime:[theEvent timestamp]];
1689 [window.queue postEvent:event];
1691 macdrv_release_event(event);
1693 else if (broughtWindowForward)
1695 [[window ancestorWineWindow] postBroughtForwardEvent];
1696 if (![window isKeyWindow])
1697 [self windowGotFocus:window];
1701 // Since mouse button events deliver absolute cursor position, the
1702 // accumulating delta from move events is invalidated. Make sure
1703 // next mouse move event starts over from an absolute baseline.
1704 // Also, it's at least possible that the title bar widgets (e.g. close
1705 // button, etc.) could enter an internal event loop on a mouse down that
1706 // wouldn't exit until a mouse up. In that case, we'd miss any mouse
1707 // dragged events and, after that, any notion of the cursor position
1708 // computed from accumulating deltas would be wrong.
1709 forceNextMouseMoveAbsolute = TRUE;
1712 - (void) handleScrollWheel:(NSEvent*)theEvent
1716 if (mouseCaptureWindow)
1717 window = mouseCaptureWindow;
1719 window = (WineWindow*)[theEvent window];
1721 if ([window isKindOfClass:[WineWindow class]])
1723 CGEventRef cgevent = [theEvent CGEvent];
1724 CGPoint pt = CGEventGetLocation(cgevent);
1728 [self clipCursorLocation:&pt];
1730 if (mouseCaptureWindow)
1734 // Only process the event if it was in the window's content area.
1735 NSPoint nspoint = [self flippedMouseLocation:NSPointFromCGPoint(pt)];
1736 NSRect contentRect = [window contentRectForFrameRect:[window frame]];
1737 process = NSMouseInRect(nspoint, contentRect, NO);
1742 macdrv_event* event;
1744 BOOL continuous = FALSE;
1746 event = macdrv_create_event(MOUSE_SCROLL, window);
1747 event->mouse_scroll.x = pt.x;
1748 event->mouse_scroll.y = pt.y;
1749 event->mouse_scroll.time_ms = [self ticksForEventTime:[theEvent timestamp]];
1751 if (CGEventGetIntegerValueField(cgevent, kCGScrollWheelEventIsContinuous))
1755 /* Continuous scroll wheel events come from high-precision scrolling
1756 hardware like Apple's Magic Mouse, Mighty Mouse, and trackpads.
1757 For these, we can get more precise data from the CGEvent API. */
1758 /* Axis 1 is vertical, axis 2 is horizontal. */
1759 x = CGEventGetDoubleValueField(cgevent, kCGScrollWheelEventPointDeltaAxis2);
1760 y = CGEventGetDoubleValueField(cgevent, kCGScrollWheelEventPointDeltaAxis1);
1764 double pixelsPerLine = 10;
1765 CGEventSourceRef source;
1767 /* The non-continuous values are in units of "lines", not pixels. */
1768 if ((source = CGEventCreateSourceFromEvent(cgevent)))
1770 pixelsPerLine = CGEventSourceGetPixelsPerLine(source);
1774 x = pixelsPerLine * [theEvent deltaX];
1775 y = pixelsPerLine * [theEvent deltaY];
1778 /* Mac: negative is right or down, positive is left or up.
1779 Win32: negative is left or down, positive is right or up.
1780 So, negate the X scroll value to translate. */
1783 /* The x,y values so far are in pixels. Win32 expects to receive some
1784 fraction of WHEEL_DELTA == 120. By my estimation, that's roughly
1785 6 times the pixel value. */
1789 if (use_precise_scrolling)
1791 event->mouse_scroll.x_scroll = x;
1792 event->mouse_scroll.y_scroll = y;
1796 /* For non-continuous "clicky" wheels, if there was any motion, make
1797 sure there was at least WHEEL_DELTA motion. This is so, at slow
1798 speeds where the system's acceleration curve is actually reducing the
1799 scroll distance, the user is sure to get some action out of each click.
1800 For example, this is important for rotating though weapons in a
1801 first-person shooter. */
1802 if (0 < event->mouse_scroll.x_scroll && event->mouse_scroll.x_scroll < 120)
1803 event->mouse_scroll.x_scroll = 120;
1804 else if (-120 < event->mouse_scroll.x_scroll && event->mouse_scroll.x_scroll < 0)
1805 event->mouse_scroll.x_scroll = -120;
1807 if (0 < event->mouse_scroll.y_scroll && event->mouse_scroll.y_scroll < 120)
1808 event->mouse_scroll.y_scroll = 120;
1809 else if (-120 < event->mouse_scroll.y_scroll && event->mouse_scroll.y_scroll < 0)
1810 event->mouse_scroll.y_scroll = -120;
1815 /* If it's been a while since the last scroll event or if the scrolling has
1816 reversed direction, reset the accumulated scroll value. */
1817 if ([theEvent timestamp] - lastScrollTime > 1)
1818 accumScrollX = accumScrollY = 0;
1821 /* The accumulated scroll value is in the opposite direction/sign of the last
1822 scroll. That's because it's the "debt" resulting from over-scrolling in
1823 that direction. We accumulate by adding in the scroll amount and then, if
1824 it has the same sign as the scroll value, we subtract any whole or partial
1825 WHEEL_DELTAs, leaving it 0 or the opposite sign. So, the user switched
1826 scroll direction if the accumulated debt and the new scroll value have the
1828 if ((accumScrollX < 0 && x < 0) || (accumScrollX > 0 && x > 0))
1830 if ((accumScrollY < 0 && y < 0) || (accumScrollY > 0 && y > 0))
1833 lastScrollTime = [theEvent timestamp];
1838 if (accumScrollX > 0 && x > 0)
1839 event->mouse_scroll.x_scroll = 120 * ceil(accumScrollX / 120);
1840 if (accumScrollX < 0 && x < 0)
1841 event->mouse_scroll.x_scroll = 120 * -ceil(-accumScrollX / 120);
1842 if (accumScrollY > 0 && y > 0)
1843 event->mouse_scroll.y_scroll = 120 * ceil(accumScrollY / 120);
1844 if (accumScrollY < 0 && y < 0)
1845 event->mouse_scroll.y_scroll = 120 * -ceil(-accumScrollY / 120);
1847 accumScrollX -= event->mouse_scroll.x_scroll;
1848 accumScrollY -= event->mouse_scroll.y_scroll;
1851 if (event->mouse_scroll.x_scroll || event->mouse_scroll.y_scroll)
1852 [window.queue postEvent:event];
1854 macdrv_release_event(event);
1856 // Since scroll wheel events deliver absolute cursor position, the
1857 // accumulating delta from move events is invalidated. Make sure next
1858 // mouse move event starts over from an absolute baseline.
1859 forceNextMouseMoveAbsolute = TRUE;
1864 // Returns TRUE if the event was handled and caller should do nothing more
1865 // with it. Returns FALSE if the caller should process it as normal and
1866 // then call -didSendEvent:.
1867 - (BOOL) handleEvent:(NSEvent*)anEvent
1870 NSEventType type = [anEvent type];
1872 if (type == NSFlagsChanged)
1873 self.lastFlagsChanged = anEvent;
1874 else if (type == NSMouseMoved || type == NSLeftMouseDragged ||
1875 type == NSRightMouseDragged || type == NSOtherMouseDragged)
1877 [self handleMouseMove:anEvent];
1878 ret = mouseCaptureWindow && ![windowsBeingDragged count];
1880 else if (type == NSLeftMouseDown || type == NSLeftMouseUp ||
1881 type == NSRightMouseDown || type == NSRightMouseUp ||
1882 type == NSOtherMouseDown || type == NSOtherMouseUp)
1884 [self handleMouseButton:anEvent];
1885 ret = mouseCaptureWindow && ![windowsBeingDragged count];
1887 else if (type == NSScrollWheel)
1889 [self handleScrollWheel:anEvent];
1890 ret = mouseCaptureWindow != nil;
1892 else if (type == NSKeyUp)
1894 uint16_t keyCode = [anEvent keyCode];
1895 if ([self isKeyPressed:keyCode])
1897 WineWindow* window = (WineWindow*)[anEvent window];
1898 [self noteKey:keyCode pressed:FALSE];
1899 if ([window isKindOfClass:[WineWindow class]])
1900 [window postKeyEvent:anEvent];
1903 else if (type == NSAppKitDefined)
1905 short subtype = [anEvent subtype];
1907 // These subtypes are not documented but they appear to mean
1908 // "a window is being dragged" and "a window is no longer being
1909 // dragged", respectively.
1910 if (subtype == 20 || subtype == 21)
1912 WineWindow* window = (WineWindow*)[anEvent window];
1913 if ([window isKindOfClass:[WineWindow class]])
1915 macdrv_event* event;
1920 [windowsBeingDragged addObject:window];
1921 eventType = WINDOW_DRAG_BEGIN;
1925 [windowsBeingDragged removeObject:window];
1926 eventType = WINDOW_DRAG_END;
1928 [self updateCursorClippingState];
1930 event = macdrv_create_event(eventType, window);
1931 [window.queue postEvent:event];
1932 macdrv_release_event(event);
1940 - (void) didSendEvent:(NSEvent*)anEvent
1942 NSEventType type = [anEvent type];
1944 if (type == NSKeyDown && ![anEvent isARepeat] && [anEvent keyCode] == kVK_Tab)
1946 NSUInteger modifiers = [anEvent modifierFlags];
1947 if ((modifiers & NSCommandKeyMask) &&
1948 !(modifiers & (NSControlKeyMask | NSAlternateKeyMask)))
1950 // Command-Tab and Command-Shift-Tab would normally be intercepted
1951 // by the system to switch applications. If we're seeing it, it's
1952 // presumably because we've captured the displays, preventing
1953 // normal application switching. Do it manually.
1954 [self handleCommandTab];
1959 - (void) setupObservations
1961 NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
1962 NSNotificationCenter* wsnc = [[NSWorkspace sharedWorkspace] notificationCenter];
1963 NSDistributedNotificationCenter* dnc = [NSDistributedNotificationCenter defaultCenter];
1965 [nc addObserverForName:NSWindowDidBecomeKeyNotification
1968 usingBlock:^(NSNotification *note){
1969 NSWindow* window = [note object];
1970 [keyWindows removeObjectIdenticalTo:window];
1971 [keyWindows insertObject:window atIndex:0];
1974 [nc addObserverForName:NSWindowWillCloseNotification
1976 queue:[NSOperationQueue mainQueue]
1977 usingBlock:^(NSNotification *note){
1978 NSWindow* window = [note object];
1979 if ([window isKindOfClass:[WineWindow class]] && [(WineWindow*)window isFakingClose])
1981 [keyWindows removeObjectIdenticalTo:window];
1982 if (window == lastTargetWindow)
1983 lastTargetWindow = nil;
1984 if (window == self.mouseCaptureWindow)
1985 self.mouseCaptureWindow = nil;
1986 if ([window isKindOfClass:[WineWindow class]] && [(WineWindow*)window isFullscreen])
1988 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0), dispatch_get_main_queue(), ^{
1989 [self updateFullscreenWindows];
1992 [windowsBeingDragged removeObject:window];
1993 [self updateCursorClippingState];
1996 [nc addObserver:self
1997 selector:@selector(keyboardSelectionDidChange)
1998 name:NSTextInputContextKeyboardSelectionDidChangeNotification
2001 /* The above notification isn't sent unless the NSTextInputContext
2002 class has initialized itself. Poke it. */
2003 [NSTextInputContext self];
2005 [wsnc addObserver:self
2006 selector:@selector(activeSpaceDidChange)
2007 name:NSWorkspaceActiveSpaceDidChangeNotification
2010 [nc addObserver:self
2011 selector:@selector(releaseMouseCapture)
2012 name:NSMenuDidBeginTrackingNotification
2015 [dnc addObserver:self
2016 selector:@selector(releaseMouseCapture)
2017 name:@"com.apple.HIToolbox.beginMenuTrackingNotification"
2019 suspensionBehavior:NSNotificationSuspensionBehaviorDrop];
2021 [dnc addObserver:self
2022 selector:@selector(enabledKeyboardInputSourcesChanged)
2023 name:(NSString*)kTISNotifyEnabledKeyboardInputSourcesChanged
2027 - (BOOL) inputSourceIsInputMethod
2029 if (!inputSourceIsInputMethodValid)
2031 TISInputSourceRef inputSource = TISCopyCurrentKeyboardInputSource();
2034 CFStringRef type = TISGetInputSourceProperty(inputSource, kTISPropertyInputSourceType);
2035 inputSourceIsInputMethod = !CFEqual(type, kTISTypeKeyboardLayout);
2036 CFRelease(inputSource);
2039 inputSourceIsInputMethod = FALSE;
2040 inputSourceIsInputMethodValid = TRUE;
2043 return inputSourceIsInputMethod;
2046 - (void) releaseMouseCapture
2048 // This might be invoked on a background thread by the distributed
2049 // notification center. Shunt it to the main thread.
2050 if (![NSThread isMainThread])
2052 dispatch_async(dispatch_get_main_queue(), ^{ [self releaseMouseCapture]; });
2056 if (mouseCaptureWindow)
2058 macdrv_event* event;
2060 event = macdrv_create_event(RELEASE_CAPTURE, mouseCaptureWindow);
2061 [mouseCaptureWindow.queue postEvent:event];
2062 macdrv_release_event(event);
2066 - (void) unminimizeWindowIfNoneVisible
2068 if (![self frontWineWindow])
2070 for (WineWindow* window in [NSApp windows])
2072 if ([window isKindOfClass:[WineWindow class]] && [window isMiniaturized])
2074 [window deminiaturize:self];
2083 * ---------- NSApplicationDelegate methods ----------
2085 - (void)applicationDidBecomeActive:(NSNotification *)notification
2087 NSNumber* displayID;
2088 NSDictionary* modesToRealize = [latentDisplayModes autorelease];
2090 latentDisplayModes = [[NSMutableDictionary alloc] init];
2091 for (displayID in modesToRealize)
2093 CGDisplayModeRef mode = (CGDisplayModeRef)[modesToRealize objectForKey:displayID];
2094 [self setMode:mode forDisplay:[displayID unsignedIntValue]];
2097 [self updateCursorClippingState];
2099 [self updateFullscreenWindows];
2100 [self adjustWindowLevels:YES];
2103 [self unminimizeWindowIfNoneVisible];
2106 // If a Wine process terminates abruptly while it has the display captured
2107 // and switched to a different resolution, Mac OS X will uncapture the
2108 // displays and switch their resolutions back. However, the other Wine
2109 // processes won't have their notion of the desktop rect changed back.
2110 // This can lead them to refuse to draw or acknowledge clicks in certain
2111 // portions of their windows.
2113 // To solve this, we synthesize a displays-changed event whenever we're
2114 // activated. This will provoke a re-synchronization of Wine's notion of
2115 // the desktop rect with the actual state.
2116 [self sendDisplaysChanged:TRUE];
2118 // The cursor probably moved while we were inactive. Accumulated mouse
2119 // movement deltas are invalidated. Make sure the next mouse move event
2120 // starts over from an absolute baseline.
2121 forceNextMouseMoveAbsolute = TRUE;
2124 - (void)applicationDidChangeScreenParameters:(NSNotification *)notification
2126 primaryScreenHeightValid = FALSE;
2127 [self sendDisplaysChanged:FALSE];
2128 [self adjustWindowLevels];
2130 // When the display configuration changes, the cursor position may jump.
2131 // Accumulated mouse movement deltas are invalidated. Make sure the next
2132 // mouse move event starts over from an absolute baseline.
2133 forceNextMouseMoveAbsolute = TRUE;
2136 - (void)applicationDidResignActive:(NSNotification *)notification
2138 macdrv_event* event;
2139 WineEventQueue* queue;
2141 [self updateCursorClippingState];
2143 [self invalidateGotFocusEvents];
2145 event = macdrv_create_event(APP_DEACTIVATED, nil);
2147 [eventQueuesLock lock];
2148 for (queue in eventQueues)
2149 [queue postEvent:event];
2150 [eventQueuesLock unlock];
2152 macdrv_release_event(event);
2154 [self releaseMouseCapture];
2157 - (void) applicationDidUnhide:(NSNotification*)aNotification
2159 [self adjustWindowLevels];
2162 - (BOOL) applicationShouldHandleReopen:(NSApplication*)theApplication hasVisibleWindows:(BOOL)flag
2164 // Note that "flag" is often wrong. WineWindows are NSPanels and NSPanels
2165 // don't count as "visible windows" for this purpose.
2166 [self unminimizeWindowIfNoneVisible];
2170 - (NSApplicationTerminateReply) applicationShouldTerminate:(NSApplication *)sender
2172 NSApplicationTerminateReply ret = NSTerminateNow;
2173 NSAppleEventManager* m = [NSAppleEventManager sharedAppleEventManager];
2174 NSAppleEventDescriptor* desc = [m currentAppleEvent];
2175 macdrv_event* event;
2176 WineEventQueue* queue;
2178 event = macdrv_create_event(APP_QUIT_REQUESTED, nil);
2180 switch ([[desc attributeDescriptorForKeyword:kAEQuitReason] int32Value])
2183 case kAEReallyLogOut:
2184 event->app_quit_requested.reason = QUIT_REASON_LOGOUT;
2186 case kAEShowRestartDialog:
2187 event->app_quit_requested.reason = QUIT_REASON_RESTART;
2189 case kAEShowShutdownDialog:
2190 event->app_quit_requested.reason = QUIT_REASON_SHUTDOWN;
2193 event->app_quit_requested.reason = QUIT_REASON_NONE;
2197 [eventQueuesLock lock];
2199 if ([eventQueues count])
2201 for (queue in eventQueues)
2202 [queue postEvent:event];
2203 ret = NSTerminateLater;
2206 [eventQueuesLock unlock];
2208 macdrv_release_event(event);
2213 - (void)applicationWillResignActive:(NSNotification *)notification
2215 [self adjustWindowLevels:NO];
2218 /***********************************************************************
2221 * Run-loop-source perform callback. Pull request blocks from the
2222 * array of queued requests and invoke them.
2224 static void PerformRequest(void *info)
2226 WineApplicationController* controller = [WineApplicationController sharedController];
2230 __block dispatch_block_t block;
2232 dispatch_sync(controller->requestsManipQueue, ^{
2233 if ([controller->requests count])
2235 block = (dispatch_block_t)[[controller->requests objectAtIndex:0] retain];
2236 [controller->requests removeObjectAtIndex:0];
2250 /***********************************************************************
2253 * Run a block on the main thread asynchronously.
2255 void OnMainThreadAsync(dispatch_block_t block)
2257 WineApplicationController* controller = [WineApplicationController sharedController];
2259 block = [block copy];
2260 dispatch_sync(controller->requestsManipQueue, ^{
2261 [controller->requests addObject:block];
2264 CFRunLoopSourceSignal(controller->requestSource);
2265 CFRunLoopWakeUp(CFRunLoopGetMain());
2270 /***********************************************************************
2273 void LogError(const char* func, NSString* format, ...)
2276 va_start(args, format);
2277 LogErrorv(func, format, args);
2281 /***********************************************************************
2284 void LogErrorv(const char* func, NSString* format, va_list args)
2286 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
2288 NSString* message = [[NSString alloc] initWithFormat:format arguments:args];
2289 fprintf(stderr, "err:%s:%s", func, [message UTF8String]);
2295 /***********************************************************************
2296 * macdrv_window_rejected_focus
2298 * Pass focus to the next window that hasn't already rejected this same
2299 * WINDOW_GOT_FOCUS event.
2301 void macdrv_window_rejected_focus(const macdrv_event *event)
2304 [[WineApplicationController sharedController] windowRejectedFocusEvent:event];
2308 /***********************************************************************
2309 * macdrv_get_input_source_info
2311 * Returns the keyboard layout uchr data, keyboard type and input source.
2313 void macdrv_get_input_source_info(CFDataRef* uchr, CGEventSourceKeyboardType* keyboard_type, int* is_iso, TISInputSourceRef* input_source)
2316 TISInputSourceRef inputSourceLayout;
2318 inputSourceLayout = TISCopyCurrentKeyboardLayoutInputSource();
2319 if (inputSourceLayout)
2321 CFDataRef data = TISGetInputSourceProperty(inputSourceLayout,
2322 kTISPropertyUnicodeKeyLayoutData);
2323 *uchr = CFDataCreateCopy(NULL, data);
2324 CFRelease(inputSourceLayout);
2326 *keyboard_type = [WineApplicationController sharedController].keyboardType;
2327 *is_iso = (KBGetLayoutType(*keyboard_type) == kKeyboardISO);
2328 *input_source = TISCopyCurrentKeyboardInputSource();
2333 /***********************************************************************
2336 * Play the beep sound configured by the user in System Preferences.
2338 void macdrv_beep(void)
2340 OnMainThreadAsync(^{
2345 /***********************************************************************
2346 * macdrv_set_display_mode
2348 int macdrv_set_display_mode(const struct macdrv_display* display,
2349 CGDisplayModeRef display_mode)
2354 ret = [[WineApplicationController sharedController] setMode:display_mode forDisplay:display->displayID];
2360 /***********************************************************************
2365 * If name is non-NULL, it is a selector for a class method on NSCursor
2366 * identifying the cursor to set. In that case, frames is ignored. If
2367 * name is NULL, then frames is used.
2369 * frames is an array of dictionaries. Each dictionary is a frame of
2370 * an animated cursor. Under the key "image" is a CGImage for the
2371 * frame. Under the key "duration" is a CFNumber time interval, in
2372 * seconds, for how long that frame is presented before proceeding to
2373 * the next frame. Under the key "hotSpot" is a CFDictionary encoding a
2374 * CGPoint, to be decoded using CGPointMakeWithDictionaryRepresentation().
2375 * This is the hot spot, measured in pixels down and to the right of the
2376 * top-left corner of the image.
2378 * If the array has exactly 1 element, the cursor is static, not
2379 * animated. If frames is NULL or has 0 elements, the cursor is hidden.
2381 void macdrv_set_cursor(CFStringRef name, CFArrayRef frames)
2385 sel = NSSelectorFromString((NSString*)name);
2388 OnMainThreadAsync(^{
2389 WineApplicationController* controller = [WineApplicationController sharedController];
2390 [controller setCursorWithFrames:nil];
2391 controller.cursor = [NSCursor performSelector:sel];
2392 [controller unhideCursor];
2397 NSArray* nsframes = (NSArray*)frames;
2398 if ([nsframes count])
2400 OnMainThreadAsync(^{
2401 [[WineApplicationController sharedController] setCursorWithFrames:nsframes];
2406 OnMainThreadAsync(^{
2407 WineApplicationController* controller = [WineApplicationController sharedController];
2408 [controller setCursorWithFrames:nil];
2409 [controller hideCursor];
2415 /***********************************************************************
2416 * macdrv_get_cursor_position
2418 * Obtains the current cursor position. Returns zero on failure,
2419 * non-zero on success.
2421 int macdrv_get_cursor_position(CGPoint *pos)
2424 NSPoint location = [NSEvent mouseLocation];
2425 location = [[WineApplicationController sharedController] flippedMouseLocation:location];
2426 *pos = NSPointToCGPoint(location);
2432 /***********************************************************************
2433 * macdrv_set_cursor_position
2435 * Sets the cursor position without generating events. Returns zero on
2436 * failure, non-zero on success.
2438 int macdrv_set_cursor_position(CGPoint pos)
2443 ret = [[WineApplicationController sharedController] setCursorPosition:pos];
2449 /***********************************************************************
2450 * macdrv_clip_cursor
2452 * Sets the cursor cursor clipping rectangle. If the rectangle is equal
2453 * to or larger than the whole desktop region, the cursor is unclipped.
2454 * Returns zero on failure, non-zero on success.
2456 int macdrv_clip_cursor(CGRect rect)
2461 WineApplicationController* controller = [WineApplicationController sharedController];
2462 BOOL clipping = FALSE;
2464 if (!CGRectIsInfinite(rect))
2466 NSRect nsrect = NSRectFromCGRect(rect);
2469 /* Convert the rectangle from top-down coords to bottom-up. */
2470 [controller flipRect:&nsrect];
2473 for (screen in [NSScreen screens])
2475 if (!NSContainsRect(nsrect, [screen frame]))
2484 ret = [controller startClippingCursor:rect];
2486 ret = [controller stopClippingCursor];
2492 /***********************************************************************
2493 * macdrv_set_application_icon
2495 * Set the application icon. The images array contains CGImages. If
2496 * there are more than one, then they represent different sizes or
2497 * color depths from the icon resource. If images is NULL or empty,
2498 * restores the default application image.
2500 void macdrv_set_application_icon(CFArrayRef images)
2502 NSArray* imageArray = (NSArray*)images;
2504 OnMainThreadAsync(^{
2505 [[WineApplicationController sharedController] setApplicationIconFromCGImageArray:imageArray];
2509 /***********************************************************************
2512 void macdrv_quit_reply(int reply)
2515 [NSApp replyToApplicationShouldTerminate:reply];
2519 /***********************************************************************
2520 * macdrv_using_input_method
2522 int macdrv_using_input_method(void)
2527 ret = [[WineApplicationController sharedController] inputSourceIsInputMethod];
2533 /***********************************************************************
2534 * macdrv_set_mouse_capture_window
2536 void macdrv_set_mouse_capture_window(macdrv_window window)
2538 WineWindow* w = (WineWindow*)window;
2540 [w.queue discardEventsMatchingMask:event_mask_for_type(RELEASE_CAPTURE) forWindow:w];
2543 [[WineApplicationController sharedController] setMouseCaptureWindow:w];
2547 const CFStringRef macdrv_input_source_input_key = CFSTR("input");
2548 const CFStringRef macdrv_input_source_type_key = CFSTR("type");
2549 const CFStringRef macdrv_input_source_lang_key = CFSTR("lang");
2551 /***********************************************************************
2552 * macdrv_create_input_source_list
2554 CFArrayRef macdrv_create_input_source_list(void)
2556 CFMutableArrayRef ret = CFArrayCreateMutable(NULL, 0, &kCFTypeArrayCallBacks);
2559 CFArrayRef input_list;
2560 CFDictionaryRef filter_dict;
2561 const void *filter_keys[2] = { kTISPropertyInputSourceCategory, kTISPropertyInputSourceIsSelectCapable };
2562 const void *filter_values[2] = { kTISCategoryKeyboardInputSource, kCFBooleanTrue };
2565 filter_dict = CFDictionaryCreate(NULL, filter_keys, filter_values, sizeof(filter_keys)/sizeof(filter_keys[0]),
2566 &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
2567 input_list = TISCreateInputSourceList(filter_dict, false);
2569 for (i = 0; i < CFArrayGetCount(input_list); i++)
2571 TISInputSourceRef input = (TISInputSourceRef)CFArrayGetValueAtIndex(input_list, i);
2572 CFArrayRef source_langs = TISGetInputSourceProperty(input, kTISPropertyInputSourceLanguages);
2573 CFDictionaryRef entry;
2574 const void *input_keys[3] = { macdrv_input_source_input_key,
2575 macdrv_input_source_type_key,
2576 macdrv_input_source_lang_key };
2577 const void *input_values[3];
2579 input_values[0] = input;
2580 input_values[1] = TISGetInputSourceProperty(input, kTISPropertyInputSourceType);
2581 input_values[2] = CFArrayGetValueAtIndex(source_langs, 0);
2583 entry = CFDictionaryCreate(NULL, input_keys, input_values, sizeof(input_keys) / sizeof(input_keys[0]),
2584 &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
2586 CFArrayAppendValue(ret, entry);
2589 CFRelease(input_list);
2590 CFRelease(filter_dict);
2596 int macdrv_select_input_source(TISInputSourceRef input_source)
2598 __block int ret = FALSE;
2601 ret = (TISSelectInputSource(input_source) == noErr);