1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #import "ui/base/test/scoped_fake_nswindow_focus.h"
7 #import <Cocoa/Cocoa.h>
9 #import "base/mac/foundation_util.h"
10 #import "base/mac/scoped_objc_class_swizzler.h"
12 using base::mac::ScopedObjCClassSwizzler;
16 NSWindow* g_fake_focused_window = nil;
18 void SetFocus(NSWindow* window) {
19 g_fake_focused_window = window;
20 [[NSNotificationCenter defaultCenter]
21 postNotificationName:NSWindowDidBecomeMainNotification
22 object:g_fake_focused_window];
23 [[NSNotificationCenter defaultCenter]
24 postNotificationName:NSWindowDidBecomeKeyNotification
25 object:g_fake_focused_window];
29 NSWindow* window = g_fake_focused_window;
30 g_fake_focused_window = nil;
31 [[NSNotificationCenter defaultCenter]
32 postNotificationName:NSWindowDidResignKeyNotification
35 [[NSNotificationCenter defaultCenter]
36 postNotificationName:NSWindowDidResignMainNotification
42 // Donates testing implementations of NSWindow methods.
43 @interface FakeNSWindowFocusDonor : NSObject
46 @implementation FakeNSWindowFocusDonor
49 NSWindow* selfAsWindow = base::mac::ObjCCastStrict<NSWindow>(self);
50 return selfAsWindow == g_fake_focused_window;
53 - (BOOL)isMainWindow {
54 NSWindow* selfAsWindow = base::mac::ObjCCastStrict<NSWindow>(self);
55 return selfAsWindow == g_fake_focused_window;
58 - (void)makeKeyWindow {
59 NSWindow* selfAsWindow = base::mac::ObjCCastStrict<NSWindow>(self);
60 if (selfAsWindow == g_fake_focused_window ||
61 ![selfAsWindow canBecomeKeyWindow])
65 SetFocus(selfAsWindow);
68 - (void)makeMainWindow {
77 ScopedFakeNSWindowFocus::ScopedFakeNSWindowFocus()
79 new ScopedObjCClassSwizzler([NSWindow class],
80 [FakeNSWindowFocusDonor class],
81 @selector(isMainWindow))),
83 new ScopedObjCClassSwizzler([NSWindow class],
84 [FakeNSWindowFocusDonor class],
85 @selector(makeMainWindow))),
87 new ScopedObjCClassSwizzler([NSWindow class],
88 [FakeNSWindowFocusDonor class],
89 @selector(isKeyWindow))),
91 new ScopedObjCClassSwizzler([NSWindow class],
92 [FakeNSWindowFocusDonor class],
93 @selector(makeKeyWindow))) {}
95 ScopedFakeNSWindowFocus::~ScopedFakeNSWindowFocus() {