1 // Copyright 2014 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/gfx/test/ui_cocoa_test_helper.h"
7 #include "base/debug/debugger.h"
8 #include "base/logging.h"
9 #include "base/stl_util.h"
10 #include "base/test/test_timeouts.h"
12 @implementation CocoaTestHelperWindow
14 - (id)initWithContentRect:(NSRect)contentRect {
15 return [self initWithContentRect:contentRect
16 styleMask:NSBorderlessWindowMask
17 backing:NSBackingStoreBuffered
22 return [self initWithContentRect:NSMakeRect(0, 0, 800, 600)];
26 // Just a good place to put breakpoints when having problems with
27 // unittests and CocoaTestHelperWindow.
31 - (void)makePretendKeyWindowAndSetFirstResponder:(NSResponder*)responder {
32 EXPECT_TRUE([self makeFirstResponder:responder]);
33 [self setPretendIsKeyWindow:YES];
36 - (void)clearPretendKeyWindowAndFirstResponder {
37 [self setPretendIsKeyWindow:NO];
38 EXPECT_TRUE([self makeFirstResponder:NSApp]);
41 - (void)setPretendIsKeyWindow:(BOOL)flag {
42 pretendIsKeyWindow_ = flag;
46 return pretendIsKeyWindow_;
53 CocoaTest::CocoaTest() : called_tear_down_(false), test_window_(nil) {
57 CocoaTest::~CocoaTest() {
58 // Must call CocoaTest's teardown from your overrides.
59 DCHECK(called_tear_down_);
62 void CocoaTest::Init() {
63 // Set the duration of AppKit-evaluated animations (such as frame changes)
64 // to zero for testing purposes. That way they take effect immediately.
65 [[NSAnimationContext currentContext] setDuration:0.0];
67 // The above does not affect window-resize time, such as for an
68 // attached sheet dropping in. Set that duration for the current
69 // process (this is not persisted). Empirically, the value of 0.0
72 [NSDictionary dictionaryWithObject:@"0.01" forKey:@"NSWindowResizeTime"];
73 [[NSUserDefaults standardUserDefaults] registerDefaults:dict];
75 // Collect the list of windows that were open when the test started so
76 // that we don't wait for them to close in TearDown. Has to be done
77 // after BootstrapCocoa is called.
78 initial_windows_ = ApplicationWindows();
81 void CocoaTest::TearDown() {
82 called_tear_down_ = true;
83 // Call close on our test_window to clean it up if one was opened.
84 [test_window_ clearPretendKeyWindowAndFirstResponder];
88 // Recycle the pool to clean up any stuff that was put on the
89 // autorelease pool due to window or windowcontroller closures.
92 // Some controls (NSTextFields, NSComboboxes etc) use
93 // performSelector:withDelay: to clean up drag handlers and other
94 // things (Radar 5851458 "Closing a window with a NSTextView in it
95 // should get rid of it immediately"). The event loop must be spun
96 // to get everything cleaned up correctly. It normally only takes
97 // one to two spins through the event loop to see a change.
99 // NOTE(shess): Under valgrind, -nextEventMatchingMask:* in one test
100 // needed to run twice, once taking .2 seconds, the next time .6
101 // seconds. The loop exit condition attempts to be scalable.
103 // Get the set of windows which weren't present when the test
105 std::set<NSWindow*> windows_left(WindowsLeft());
107 while (!windows_left.empty()) {
108 // Cover delayed actions by spinning the loop at least once after
110 const NSTimeInterval kCloseTimeoutSeconds =
111 TestTimeouts::action_timeout().InSecondsF();
113 // Cover chains of delayed actions by spinning the loop at least
115 const int kCloseSpins = 3;
117 // Track the set of remaining windows so that everything can be
118 // reset if progress is made.
119 std::set<NSWindow*> still_left = windows_left;
121 NSDate* start_date = [NSDate date];
122 bool one_more_time = true;
124 while (still_left.size() == windows_left.size() &&
125 (spins < kCloseSpins || one_more_time)) {
126 // Check the timeout before pumping events, so that we'll spin
127 // the loop once after the timeout.
129 ([start_date timeIntervalSinceNow] > -kCloseTimeoutSeconds);
131 // Autorelease anything thrown up by the event loop.
133 base::mac::ScopedNSAutoreleasePool pool;
135 NSEvent *next_event = [NSApp nextEventMatchingMask:NSAnyEventMask
137 inMode:NSDefaultRunLoopMode
139 [NSApp sendEvent:next_event];
140 [NSApp updateWindows];
143 // Refresh the outstanding windows.
144 still_left = WindowsLeft();
147 // If no progress is being made, log a failure and continue.
148 if (still_left.size() == windows_left.size()) {
149 // NOTE(shess): Failing this expectation means that the test
150 // opened windows which have not been fully released. Either
151 // there is a leak, or perhaps one of |kCloseTimeoutSeconds| or
152 // |kCloseSpins| needs adjustment.
153 EXPECT_EQ(0U, windows_left.size());
154 for (std::set<NSWindow*>::iterator iter = windows_left.begin();
155 iter != windows_left.end(); ++iter) {
156 const char* desc = [[*iter description] UTF8String];
157 LOG(WARNING) << "Didn't close window " << desc;
162 windows_left = still_left;
164 PlatformTest::TearDown();
167 std::set<NSWindow*> CocoaTest::ApplicationWindows() {
168 // This must NOT retain the windows it is returning.
169 std::set<NSWindow*> windows;
171 // Must create a pool here because [NSApp windows] has created an array
172 // with retains on all the windows in it.
173 base::mac::ScopedNSAutoreleasePool pool;
174 NSArray *appWindows = [NSApp windows];
175 for (NSWindow *window in appWindows) {
176 windows.insert(window);
181 std::set<NSWindow*> CocoaTest::WindowsLeft() {
182 const std::set<NSWindow*> windows(ApplicationWindows());
183 std::set<NSWindow*> windows_left =
184 base::STLSetDifference<std::set<NSWindow*> >(windows, initial_windows_);
188 CocoaTestHelperWindow* CocoaTest::test_window() {
190 test_window_ = [[CocoaTestHelperWindow alloc] init];
191 if (base::debug::BeingDebugged()) {
192 [test_window_ orderFront:nil];
194 [test_window_ orderBack:nil];