1 // Copyright (c) 2012 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 <Carbon/Carbon.h>
6 #import <Cocoa/Cocoa.h>
7 #import <Foundation/Foundation.h>
8 #import <Foundation/NSAppleEventDescriptor.h>
9 #import <objc/message.h>
10 #import <objc/runtime.h>
12 #include "apps/app_window_registry.h"
13 #include "base/command_line.h"
14 #include "base/mac/foundation_util.h"
15 #include "base/mac/scoped_nsobject.h"
16 #include "base/prefs/pref_service.h"
17 #include "chrome/app/chrome_command_ids.h"
18 #import "chrome/browser/app_controller_mac.h"
19 #include "chrome/browser/apps/app_browsertest_util.h"
20 #include "chrome/browser/browser_process.h"
21 #include "chrome/browser/extensions/extension_test_message_listener.h"
22 #include "chrome/browser/profiles/profile_manager.h"
23 #include "chrome/browser/ui/browser.h"
24 #include "chrome/browser/ui/browser_list.h"
25 #include "chrome/browser/ui/browser_window.h"
26 #import "chrome/browser/ui/cocoa/profiles/user_manager_mac.h"
27 #include "chrome/browser/ui/host_desktop.h"
28 #include "chrome/browser/ui/tabs/tab_strip_model.h"
29 #include "chrome/common/chrome_constants.h"
30 #include "chrome/common/chrome_switches.h"
31 #include "chrome/common/pref_names.h"
32 #include "chrome/common/url_constants.h"
33 #include "chrome/test/base/in_process_browser_test.h"
34 #include "chrome/test/base/ui_test_utils.h"
35 #include "components/signin/core/common/profile_management_switches.h"
36 #include "content/public/browser/web_contents.h"
37 #include "extensions/common/extension.h"
38 #include "net/test/embedded_test_server/embedded_test_server.h"
42 GURL g_open_shortcut_url = GURL::EmptyGURL();
46 @interface TestOpenShortcutOnStartup : NSObject
47 - (void)applicationWillFinishLaunching:(NSNotification*)notification;
50 @implementation TestOpenShortcutOnStartup
52 - (void)applicationWillFinishLaunching:(NSNotification*)notification {
53 if (!g_open_shortcut_url.is_valid())
56 AppController* controller =
57 base::mac::ObjCCast<AppController>([NSApp delegate]);
58 Method getUrl = class_getInstanceMethod([controller class],
59 @selector(getUrl:withReply:));
64 base::scoped_nsobject<NSAppleEventDescriptor> shortcutEvent(
65 [[NSAppleEventDescriptor alloc]
66 initWithEventClass:kASAppleScriptSuite
67 eventID:kASSubroutineEvent
69 returnID:kAutoGenerateReturnID
70 transactionID:kAnyTransactionID]);
72 [NSString stringWithUTF8String:g_open_shortcut_url.spec().c_str()];
73 [shortcutEvent setParamDescriptor:
74 [NSAppleEventDescriptor descriptorWithString:url]
75 forKeyword:keyDirectObject];
77 method_invoke(controller, getUrl, shortcutEvent.get(), NULL);
84 class AppControllerPlatformAppBrowserTest
85 : public extensions::PlatformAppBrowserTest {
87 AppControllerPlatformAppBrowserTest()
88 : active_browser_list_(BrowserList::GetInstance(
89 chrome::GetActiveDesktop())) {
92 virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
93 PlatformAppBrowserTest::SetUpCommandLine(command_line);
94 command_line->AppendSwitchASCII(switches::kAppId,
98 const BrowserList* active_browser_list_;
101 // Test that if only a platform app window is open and no browser windows are
102 // open then a reopen event does nothing.
103 IN_PROC_BROWSER_TEST_F(AppControllerPlatformAppBrowserTest,
104 PlatformAppReopenWithWindows) {
105 base::scoped_nsobject<AppController> ac([[AppController alloc] init]);
106 NSUInteger old_window_count = [[NSApp windows] count];
107 EXPECT_EQ(1u, active_browser_list_->size());
108 [ac applicationShouldHandleReopen:NSApp hasVisibleWindows:YES];
109 // We do not EXPECT_TRUE the result here because the method
110 // deminiaturizes windows manually rather than return YES and have
113 EXPECT_EQ(old_window_count, [[NSApp windows] count]);
114 EXPECT_EQ(1u, active_browser_list_->size());
117 IN_PROC_BROWSER_TEST_F(AppControllerPlatformAppBrowserTest,
118 ActivationFocusesBrowserWindow) {
119 base::scoped_nsobject<AppController> app_controller(
120 [[AppController alloc] init]);
122 ExtensionTestMessageListener listener("Launched", false);
123 const extensions::Extension* app =
124 InstallAndLaunchPlatformApp("minimal");
125 ASSERT_TRUE(listener.WaitUntilSatisfied());
127 NSWindow* app_window = apps::AppWindowRegistry::Get(profile())
128 ->GetAppWindowsForApp(app->id())
131 NSWindow* browser_window = browser()->window()->GetNativeWindow();
133 EXPECT_LE([[NSApp orderedWindows] indexOfObject:app_window],
134 [[NSApp orderedWindows] indexOfObject:browser_window]);
135 [app_controller applicationShouldHandleReopen:NSApp
136 hasVisibleWindows:YES];
137 EXPECT_LE([[NSApp orderedWindows] indexOfObject:browser_window],
138 [[NSApp orderedWindows] indexOfObject:app_window]);
141 class AppControllerWebAppBrowserTest : public InProcessBrowserTest {
143 AppControllerWebAppBrowserTest()
144 : active_browser_list_(BrowserList::GetInstance(
145 chrome::GetActiveDesktop())) {
148 virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
149 command_line->AppendSwitchASCII(switches::kApp, GetAppURL());
152 std::string GetAppURL() const {
153 return "http://example.com/";
156 const BrowserList* active_browser_list_;
159 // Test that in web app mode a reopen event opens the app URL.
160 IN_PROC_BROWSER_TEST_F(AppControllerWebAppBrowserTest,
161 WebAppReopenWithNoWindows) {
162 base::scoped_nsobject<AppController> ac([[AppController alloc] init]);
163 EXPECT_EQ(1u, active_browser_list_->size());
164 BOOL result = [ac applicationShouldHandleReopen:NSApp hasVisibleWindows:NO];
166 EXPECT_FALSE(result);
167 EXPECT_EQ(2u, active_browser_list_->size());
169 Browser* browser = active_browser_list_->get(0);
171 browser->tab_strip_model()->GetActiveWebContents()->GetURL();
172 EXPECT_EQ(GetAppURL(), current_url.spec());
175 // Called when the ProfileManager has created a profile.
176 void CreateProfileCallback(const base::Closure& quit_closure,
178 Profile::CreateStatus status) {
179 EXPECT_TRUE(profile);
180 EXPECT_NE(Profile::CREATE_STATUS_LOCAL_FAIL, status);
181 EXPECT_NE(Profile::CREATE_STATUS_REMOTE_FAIL, status);
182 // This will be called multiple times. Wait until the profile is initialized
183 // fully to quit the loop.
184 if (status == Profile::CREATE_STATUS_INITIALIZED)
188 void CreateAndWaitForGuestProfile() {
189 ProfileManager::CreateCallback create_callback =
190 base::Bind(&CreateProfileCallback,
191 base::MessageLoop::current()->QuitClosure());
192 g_browser_process->profile_manager()->CreateProfileAsync(
193 ProfileManager::GetGuestProfilePath(),
198 base::RunLoop().Run();
201 class AppControllerNewProfileManagementBrowserTest
202 : public InProcessBrowserTest {
204 AppControllerNewProfileManagementBrowserTest()
205 : active_browser_list_(BrowserList::GetInstance(
206 chrome::GetActiveDesktop())) {
209 virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
210 switches::EnableNewProfileManagementForTesting(command_line);
213 const BrowserList* active_browser_list_;
216 // Test that for a regular last profile, a reopen event opens a browser.
217 IN_PROC_BROWSER_TEST_F(AppControllerNewProfileManagementBrowserTest,
218 RegularProfileReopenWithNoWindows) {
219 base::scoped_nsobject<AppController> ac([[AppController alloc] init]);
220 EXPECT_EQ(1u, active_browser_list_->size());
221 BOOL result = [ac applicationShouldHandleReopen:NSApp hasVisibleWindows:NO];
223 EXPECT_FALSE(result);
224 EXPECT_EQ(2u, active_browser_list_->size());
225 EXPECT_FALSE(UserManagerMac::IsShowing());
228 // Test that for a locked last profile, a reopen event opens the User Manager.
229 IN_PROC_BROWSER_TEST_F(AppControllerNewProfileManagementBrowserTest,
230 LockedProfileReopenWithNoWindows) {
231 // The User Manager uses the guest profile as its underlying profile. To
232 // minimize flakiness due to the scheduling/descheduling of tasks on the
233 // different threads, pre-initialize the guest profile before it is needed.
234 CreateAndWaitForGuestProfile();
235 base::scoped_nsobject<AppController> ac([[AppController alloc] init]);
237 // Lock the active profile.
238 Profile* profile = [ac lastProfile];
239 ProfileInfoCache& cache =
240 g_browser_process->profile_manager()->GetProfileInfoCache();
241 size_t profile_index = cache.GetIndexOfProfileWithPath(profile->GetPath());
242 cache.SetProfileSigninRequiredAtIndex(profile_index, true);
243 EXPECT_TRUE(cache.ProfileIsSigninRequiredAtIndex(profile_index));
245 EXPECT_EQ(1u, active_browser_list_->size());
246 BOOL result = [ac applicationShouldHandleReopen:NSApp hasVisibleWindows:NO];
247 EXPECT_FALSE(result);
249 base::RunLoop().RunUntilIdle();
250 EXPECT_EQ(1u, active_browser_list_->size());
251 EXPECT_TRUE(UserManagerMac::IsShowing());
252 UserManagerMac::Hide();
255 // Test that for a guest last profile, a reopen event opens the User Manager.
256 IN_PROC_BROWSER_TEST_F(AppControllerNewProfileManagementBrowserTest,
257 GuestProfileReopenWithNoWindows) {
258 // Create the guest profile, and set it as the last used profile so the
259 // app controller can use it on init.
260 CreateAndWaitForGuestProfile();
261 PrefService* local_state = g_browser_process->local_state();
262 local_state->SetString(prefs::kProfileLastUsed, chrome::kGuestProfileDir);
264 base::scoped_nsobject<AppController> ac([[AppController alloc] init]);
266 Profile* profile = [ac lastProfile];
267 EXPECT_EQ(ProfileManager::GetGuestProfilePath(), profile->GetPath());
268 EXPECT_TRUE(profile->IsGuestSession());
270 EXPECT_EQ(1u, active_browser_list_->size());
271 BOOL result = [ac applicationShouldHandleReopen:NSApp hasVisibleWindows:NO];
272 EXPECT_FALSE(result);
274 base::RunLoop().RunUntilIdle();
276 EXPECT_EQ(1u, active_browser_list_->size());
277 EXPECT_TRUE(UserManagerMac::IsShowing());
278 UserManagerMac::Hide();
281 class AppControllerOpenShortcutBrowserTest : public InProcessBrowserTest {
283 AppControllerOpenShortcutBrowserTest() {
286 virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
287 // In order to mimic opening shortcut during browser startup, we need to
288 // send the event before -applicationDidFinishLaunching is called, but
289 // after AppController is loaded.
291 // Since -applicationWillFinishLaunching does nothing now, we swizzle it to
292 // our function to send the event. We need to do this early before running
293 // the main message loop.
295 // NSApp does not exist yet. We need to get the AppController using
297 Class appControllerClass = NSClassFromString(@"AppController");
298 Class openShortcutClass = NSClassFromString(@"TestOpenShortcutOnStartup");
300 ASSERT_TRUE(appControllerClass != nil);
301 ASSERT_TRUE(openShortcutClass != nil);
303 SEL targetMethod = @selector(applicationWillFinishLaunching:);
304 Method original = class_getInstanceMethod(appControllerClass,
306 Method destination = class_getInstanceMethod(openShortcutClass,
309 ASSERT_TRUE(original != NULL);
310 ASSERT_TRUE(destination != NULL);
312 method_exchangeImplementations(original, destination);
314 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
315 g_open_shortcut_url = embedded_test_server()->GetURL("/simple.html");
318 virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
319 // If the arg is empty, PrepareTestCommandLine() after this function will
320 // append about:blank as default url.
321 command_line->AppendArg(chrome::kChromeUINewTabURL);
325 IN_PROC_BROWSER_TEST_F(AppControllerOpenShortcutBrowserTest,
326 OpenShortcutOnStartup) {
327 EXPECT_EQ(1, browser()->tab_strip_model()->count());
328 EXPECT_EQ(g_open_shortcut_url,
329 browser()->tab_strip_model()->GetActiveWebContents()
330 ->GetLastCommittedURL());