1 // Copyright 2013 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 "chrome/browser/ui/app_list/app_list_service_mac.h"
7 #include <ApplicationServices/ApplicationServices.h>
8 #import <Cocoa/Cocoa.h>
10 #include "apps/app_shim/app_shim_mac.h"
11 #include "base/bind.h"
12 #include "base/command_line.h"
13 #include "base/file_util.h"
14 #include "base/lazy_instance.h"
15 #include "base/memory/singleton.h"
16 #include "base/message_loop/message_loop.h"
17 #import "chrome/browser/app_controller_mac.h"
18 #include "chrome/browser/browser_process.h"
19 #include "chrome/browser/extensions/extension_service.h"
20 #include "chrome/browser/extensions/extension_system.h"
21 #include "chrome/browser/profiles/profile_manager.h"
22 #include "chrome/browser/ui/app_list/app_list_controller_delegate_impl.h"
23 #include "chrome/browser/ui/app_list/app_list_positioner.h"
24 #include "chrome/browser/ui/app_list/app_list_service.h"
25 #include "chrome/browser/ui/app_list/app_list_service_impl.h"
26 #include "chrome/browser/ui/app_list/app_list_util.h"
27 #include "chrome/browser/ui/app_list/app_list_view_delegate.h"
28 #include "chrome/browser/ui/browser_commands.h"
29 #include "chrome/browser/ui/extensions/application_launch.h"
30 #include "chrome/browser/ui/web_applications/web_app_ui.h"
31 #include "chrome/browser/web_applications/web_app.h"
32 #include "chrome/browser/web_applications/web_app_mac.h"
33 #include "chrome/common/chrome_switches.h"
34 #include "chrome/common/chrome_version_info.h"
35 #include "chrome/common/extensions/manifest_handlers/app_launch_info.h"
36 #include "chrome/common/mac/app_mode_common.h"
37 #include "chrome/common/pref_names.h"
38 #include "content/public/browser/browser_thread.h"
39 #include "grit/chrome_unscaled_resources.h"
40 #include "grit/google_chrome_strings.h"
41 #include "net/base/url_util.h"
42 #import "ui/app_list/cocoa/app_list_view_controller.h"
43 #import "ui/app_list/cocoa/app_list_window_controller.h"
44 #include "ui/app_list/search_box_model.h"
45 #include "ui/base/l10n/l10n_util.h"
46 #include "ui/base/resource/resource_bundle.h"
47 #include "ui/gfx/display.h"
48 #include "ui/gfx/screen.h"
54 // Controller for animations that show or hide the app list.
55 @interface AppListAnimationController : NSObject<NSAnimationDelegate> {
57 // When closing, the window to close. Retained until the animation ends.
58 base::scoped_nsobject<NSWindow> window_;
59 // The animation started and owned by |self|. Reset when the animation ends.
60 base::scoped_nsobject<NSViewAnimation> animation_;
63 // Returns whether |window_| is scheduled to be closed when the animation ends.
66 // Animate |window| to show or close it, after cancelling any current animation.
67 // Translates from the current location to |targetOrigin| and fades in or out.
68 - (void)animateWindow:(NSWindow*)window
69 targetOrigin:(NSPoint)targetOrigin
70 closing:(BOOL)closing;
72 // Called on the UI thread once the animation has completed to reset the
73 // animation state, close the window (if it is a close animation), and possibly
75 - (void)cleanupOnUIThread;
81 // Version of the app list shortcut version installed.
82 const int kShortcutVersion = 1;
84 // Duration of show and hide animations.
85 const NSTimeInterval kAnimationDuration = 0.2;
87 // Distance towards the screen edge that the app list moves from when showing.
88 const CGFloat kDistanceMovedOnShow = 20;
90 ShellIntegration::ShortcutInfo GetAppListShortcutInfo(
91 const base::FilePath& profile_path) {
92 ShellIntegration::ShortcutInfo shortcut_info;
93 chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
94 if (channel == chrome::VersionInfo::CHANNEL_CANARY) {
96 l10n_util::GetStringUTF16(IDS_APP_LIST_SHORTCUT_NAME_CANARY);
98 shortcut_info.title = l10n_util::GetStringUTF16(IDS_APP_LIST_SHORTCUT_NAME);
101 shortcut_info.extension_id = app_mode::kAppListModeId;
102 shortcut_info.description = shortcut_info.title;
103 shortcut_info.profile_path = profile_path;
105 return shortcut_info;
108 void CreateAppListShim(const base::FilePath& profile_path) {
109 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
110 WebApplicationInfo web_app_info;
111 ShellIntegration::ShortcutInfo shortcut_info =
112 GetAppListShortcutInfo(profile_path);
114 ResourceBundle& resource_bundle = ResourceBundle::GetSharedInstance();
115 chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
116 if (channel == chrome::VersionInfo::CHANNEL_CANARY) {
117 #if defined(GOOGLE_CHROME_BUILD)
118 shortcut_info.favicon.Add(
119 *resource_bundle.GetImageSkiaNamed(IDR_APP_LIST_CANARY_16));
120 shortcut_info.favicon.Add(
121 *resource_bundle.GetImageSkiaNamed(IDR_APP_LIST_CANARY_32));
122 shortcut_info.favicon.Add(
123 *resource_bundle.GetImageSkiaNamed(IDR_APP_LIST_CANARY_128));
124 shortcut_info.favicon.Add(
125 *resource_bundle.GetImageSkiaNamed(IDR_APP_LIST_CANARY_256));
130 shortcut_info.favicon.Add(
131 *resource_bundle.GetImageSkiaNamed(IDR_APP_LIST_16));
132 shortcut_info.favicon.Add(
133 *resource_bundle.GetImageSkiaNamed(IDR_APP_LIST_32));
134 shortcut_info.favicon.Add(
135 *resource_bundle.GetImageSkiaNamed(IDR_APP_LIST_128));
136 shortcut_info.favicon.Add(
137 *resource_bundle.GetImageSkiaNamed(IDR_APP_LIST_256));
140 ShellIntegration::ShortcutLocations shortcut_locations;
141 PrefService* local_state = g_browser_process->local_state();
142 int installed_version =
143 local_state->GetInteger(prefs::kAppLauncherShortcutVersion);
145 // If this is a first-time install, add a dock icon. Otherwise just update
146 // the target, and wait for OSX to refresh its icon caches. This might not
147 // occur until a reboot, but OSX does not offer a nicer way. Deleting cache
148 // files on disk and killing processes can easily result in icon corruption.
149 if (installed_version == 0)
150 shortcut_locations.in_quick_launch_bar = true;
152 web_app::CreateShortcuts(shortcut_info,
154 web_app::SHORTCUT_CREATION_AUTOMATED);
156 local_state->SetInteger(prefs::kAppLauncherShortcutVersion,
160 NSRunningApplication* ActiveApplicationNotChrome() {
161 NSArray* applications = [[NSWorkspace sharedWorkspace] runningApplications];
162 for (NSRunningApplication* application in applications) {
163 if (![application isActive])
166 if ([application isEqual:[NSRunningApplication currentApplication]])
167 return nil; // Chrome is active.
175 // Determines which screen edge the dock is aligned to.
176 AppListPositioner::ScreenEdge DockLocationInDisplay(
177 const gfx::Display& display) {
178 // Assume the dock occupies part of the work area either on the left, right or
179 // bottom of the display. Note in the autohide case, it is always 4 pixels.
180 const gfx::Rect work_area = display.work_area();
181 const gfx::Rect display_bounds = display.bounds();
182 if (work_area.bottom() != display_bounds.bottom())
183 return AppListPositioner::SCREEN_EDGE_BOTTOM;
185 if (work_area.x() != display_bounds.x())
186 return AppListPositioner::SCREEN_EDGE_LEFT;
188 if (work_area.right() != display_bounds.right())
189 return AppListPositioner::SCREEN_EDGE_RIGHT;
191 return AppListPositioner::SCREEN_EDGE_UNKNOWN;
194 // If |display|'s work area is too close to its boundary on |dock_edge|, adjust
195 // the work area away from the edge by a constant amount to reduce overlap and
196 // ensure the dock icon can still be clicked to dismiss the app list.
197 void AdjustWorkAreaForDock(const gfx::Display& display,
198 AppListPositioner* positioner,
199 AppListPositioner::ScreenEdge dock_edge) {
200 const int kAutohideDockThreshold = 10;
201 const int kExtraDistance = 50; // A dock with 40 items is about this size.
203 const gfx::Rect work_area = display.work_area();
204 const gfx::Rect display_bounds = display.bounds();
207 case AppListPositioner::SCREEN_EDGE_LEFT:
208 if (work_area.x() - display_bounds.x() <= kAutohideDockThreshold)
209 positioner->WorkAreaInset(kExtraDistance, 0, 0, 0);
211 case AppListPositioner::SCREEN_EDGE_RIGHT:
212 if (display_bounds.right() - work_area.right() <= kAutohideDockThreshold)
213 positioner->WorkAreaInset(0, 0, kExtraDistance, 0);
215 case AppListPositioner::SCREEN_EDGE_BOTTOM:
216 if (display_bounds.bottom() - work_area.bottom() <=
217 kAutohideDockThreshold) {
218 positioner->WorkAreaInset(0, 0, 0, kExtraDistance);
221 case AppListPositioner::SCREEN_EDGE_UNKNOWN:
222 case AppListPositioner::SCREEN_EDGE_TOP:
228 void GetAppListWindowOrigins(
229 NSWindow* window, NSPoint* target_origin, NSPoint* start_origin) {
230 gfx::Screen* const screen = gfx::Screen::GetScreenFor([window contentView]);
231 // Ensure y coordinates are flipped back into AppKit's coordinate system.
232 bool cursor_is_visible = CGCursorIsVisible();
233 gfx::Display display;
235 if (!cursor_is_visible) {
236 // If Chrome is the active application, display on the same display as
237 // Chrome's keyWindow since this will catch activations triggered, e.g, via
238 // WebStore install. If another application is active, OSX doesn't provide a
239 // reliable way to get the display in use. Fall back to the primary display
240 // since it has the menu bar and is likely to be correct, e.g., for
241 // activations from Spotlight.
242 const gfx::NativeView key_view = [[NSApp keyWindow] contentView];
243 display = key_view && [NSApp isActive] ?
244 screen->GetDisplayNearestWindow(key_view) :
245 screen->GetPrimaryDisplay();
247 cursor = screen->GetCursorScreenPoint();
248 display = screen->GetDisplayNearestPoint(cursor);
251 const NSSize ns_window_size = [window frame].size;
252 gfx::Size window_size(ns_window_size.width, ns_window_size.height);
253 int primary_display_height =
254 NSMaxY([[[NSScreen screens] objectAtIndex:0] frame]);
255 AppListServiceMac::FindAnchorPoint(window_size,
257 primary_display_height,
266 AppListServiceMac::AppListServiceMac()
268 controller_delegate_(new AppListControllerDelegateImpl(this)) {
269 animation_controller_.reset([[AppListAnimationController alloc] init]);
272 AppListServiceMac::~AppListServiceMac() {}
275 AppListServiceMac* AppListServiceMac::GetInstance() {
276 return Singleton<AppListServiceMac,
277 LeakySingletonTraits<AppListServiceMac> >::get();
281 void AppListServiceMac::FindAnchorPoint(const gfx::Size& window_size,
282 const gfx::Display& display,
283 int primary_display_height,
284 bool cursor_is_visible,
285 const gfx::Point& cursor,
286 NSPoint* target_origin,
287 NSPoint* start_origin) {
288 AppListPositioner positioner(display, window_size, 0);
289 AppListPositioner::ScreenEdge dock_location = DockLocationInDisplay(display);
292 // Snap to the dock edge. If the cursor is greater than the window
293 // width/height away or not visible, anchor to the center of the dock.
294 // Otherwise, anchor to the cursor position.
295 if (dock_location == AppListPositioner::SCREEN_EDGE_UNKNOWN) {
296 anchor = positioner.GetAnchorPointForScreenCorner(
297 AppListPositioner::SCREEN_CORNER_BOTTOM_LEFT);
300 dock_location == AppListPositioner::SCREEN_EDGE_BOTTOM ||
301 dock_location == AppListPositioner::SCREEN_EDGE_TOP ?
302 window_size.height() :
304 // Subtract the dock area since the display's default work_area will not
305 // subtract it if the dock is set to auto-hide, and the app list should
306 // never overlap the dock.
307 AdjustWorkAreaForDock(display, &positioner, dock_location);
308 if (!cursor_is_visible || positioner.GetCursorDistanceFromShelf(
309 dock_location, cursor) > snap_distance) {
310 anchor = positioner.GetAnchorPointForShelfCenter(dock_location);
312 anchor = positioner.GetAnchorPointForShelfCursor(dock_location, cursor);
316 *target_origin = NSMakePoint(
317 anchor.x() - window_size.width() / 2,
318 primary_display_height - anchor.y() - window_size.height() / 2);
319 *start_origin = *target_origin;
321 // If the launcher is anchored to the dock (regardless of whether the cursor
322 // is visible), animate in inwards from the edge of screen
323 switch (dock_location) {
324 case AppListPositioner::SCREEN_EDGE_UNKNOWN:
326 case AppListPositioner::SCREEN_EDGE_LEFT:
327 start_origin->x -= kDistanceMovedOnShow;
329 case AppListPositioner::SCREEN_EDGE_RIGHT:
330 start_origin->x += kDistanceMovedOnShow;
332 case AppListPositioner::SCREEN_EDGE_TOP:
335 case AppListPositioner::SCREEN_EDGE_BOTTOM:
336 start_origin->y -= kDistanceMovedOnShow;
341 void AppListServiceMac::Init(Profile* initial_profile) {
342 // On Mac, Init() is called multiple times for a process: any time there is no
343 // browser window open and a new window is opened, and during process startup
344 // to handle the silent launch case (e.g. for app shims). In the startup case,
345 // a profile has not yet been determined so |initial_profile| will be NULL.
346 static bool init_called_with_profile = false;
347 if (initial_profile && !init_called_with_profile) {
348 init_called_with_profile = true;
349 HandleCommandLineFlags(initial_profile);
350 PrefService* local_state = g_browser_process->local_state();
351 if (!IsAppLauncherEnabled()) {
352 local_state->SetInteger(prefs::kAppLauncherShortcutVersion, 0);
354 int installed_shortcut_version =
355 local_state->GetInteger(prefs::kAppLauncherShortcutVersion);
357 if (kShortcutVersion > installed_shortcut_version)
362 static bool init_called = false;
367 apps::AppShimHandler::RegisterHandler(app_mode::kAppListModeId,
368 AppListServiceMac::GetInstance());
370 // Handle the case where Chrome was not running and was started with the app
371 // launcher shim. The profile has not yet been loaded. To improve response
372 // times, start animating an empty window which will be populated via
373 // OnShimLaunch(). Note that if --silent-launch is not also passed, the window
374 // will instead populate via StartupBrowserCreator::Launch(). Shim-initiated
375 // launches will always have --silent-launch.
376 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kShowAppList))
377 ShowWindowNearDock();
380 Profile* AppListServiceMac::GetCurrentAppListProfile() {
384 void AppListServiceMac::CreateForProfile(Profile* requested_profile) {
385 if (profile_ == requested_profile)
388 profile_ = requested_profile;
390 if (!window_controller_)
391 window_controller_.reset([[AppListWindowController alloc] init]);
393 scoped_ptr<app_list::AppListViewDelegate> delegate(
394 new AppListViewDelegate(profile_, GetControllerDelegate()));
395 [[window_controller_ appListViewController] setDelegate:delegate.Pass()];
398 void AppListServiceMac::ShowForProfile(Profile* requested_profile) {
399 if (requested_profile->IsManaged())
402 InvalidatePendingProfileLoads();
404 if (requested_profile == profile_) {
405 ShowWindowNearDock();
409 SetProfilePath(requested_profile->GetPath());
410 CreateForProfile(requested_profile);
411 ShowWindowNearDock();
414 void AppListServiceMac::DismissAppList() {
415 if (!IsAppListVisible())
418 // If the app list is currently the main window, it will activate the next
419 // Chrome window when dismissed. But if a different application was active
420 // when the app list was shown, activate that instead.
421 base::scoped_nsobject<NSRunningApplication> prior_app;
422 if ([[window_controller_ window] isMainWindow])
423 prior_app.swap(previously_active_application_);
425 previously_active_application_.reset();
427 // If activation is successful, the app list will lose main status and try to
428 // close itself again. It can't be closed in this runloop iteration without
429 // OSX deciding to raise the next Chrome window, and _then_ activating the
430 // application on top. This also occurs if no activation option is given.
431 if ([prior_app activateWithOptions:NSApplicationActivateIgnoringOtherApps])
434 [animation_controller_ animateWindow:[window_controller_ window]
435 targetOrigin:last_start_origin_
439 bool AppListServiceMac::IsAppListVisible() const {
440 return [[window_controller_ window] isVisible] &&
441 ![animation_controller_ isClosing];
444 void AppListServiceMac::EnableAppList(Profile* initial_profile) {
445 AppListServiceImpl::EnableAppList(initial_profile);
446 AppController* controller = [NSApp delegate];
447 [controller initAppShimMenuController];
450 void AppListServiceMac::CreateShortcut() {
451 CreateAppListShim(GetProfilePath(
452 g_browser_process->profile_manager()->user_data_dir()));
455 NSWindow* AppListServiceMac::GetAppListWindow() {
456 return [window_controller_ window];
459 AppListControllerDelegate* AppListServiceMac::GetControllerDelegate() {
460 return controller_delegate_.get();
463 void AppListServiceMac::OnShimLaunch(apps::AppShimHandler::Host* host,
464 apps::AppShimLaunchType launch_type,
465 const std::vector<base::FilePath>& files) {
466 if (profile_ && IsAppListVisible()) {
469 // Start by showing a possibly empty window to handle the case where Chrome
470 // is running, but hasn't yet loaded the app launcher profile.
471 ShowWindowNearDock();
475 // Always close the shim process immediately.
476 host->OnAppLaunchComplete(apps::APP_SHIM_LAUNCH_DUPLICATE_HOST);
479 void AppListServiceMac::OnShimClose(apps::AppShimHandler::Host* host) {}
481 void AppListServiceMac::OnShimFocus(apps::AppShimHandler::Host* host,
482 apps::AppShimFocusType focus_type,
483 const std::vector<base::FilePath>& files) {}
485 void AppListServiceMac::OnShimSetHidden(apps::AppShimHandler::Host* host,
488 void AppListServiceMac::OnShimQuit(apps::AppShimHandler::Host* host) {}
490 void AppListServiceMac::ShowWindowNearDock() {
491 if (IsAppListVisible())
494 if (!window_controller_) {
495 // Note that this will start showing an unpopulated window, the caller needs
496 // to ensure it will be populated later.
497 window_controller_.reset([[AppListWindowController alloc] init]);
500 NSWindow* window = GetAppListWindow();
502 NSPoint target_origin;
503 GetAppListWindowOrigins(window, &target_origin, &last_start_origin_);
504 [window setFrameOrigin:last_start_origin_];
506 // Before activating, see if an application other than Chrome is currently the
507 // active application, so that it can be reactivated when dismissing.
508 previously_active_application_.reset([ActiveApplicationNotChrome() retain]);
510 [animation_controller_ animateWindow:[window_controller_ window]
511 targetOrigin:target_origin
513 [window makeKeyAndOrderFront:nil];
514 [NSApp activateIgnoringOtherApps:YES];
515 RecordAppListLaunch();
518 void AppListServiceMac::WindowAnimationDidEnd() {
519 [animation_controller_ cleanupOnUIThread];
523 AppListService* AppListService::Get(chrome::HostDesktopType desktop_type) {
524 return AppListServiceMac::GetInstance();
528 void AppListService::InitAll(Profile* initial_profile) {
529 AppListServiceMac::GetInstance()->Init(initial_profile);
532 @implementation AppListAnimationController
538 - (void)animateWindow:(NSWindow*)window
539 targetOrigin:(NSPoint)targetOrigin
540 closing:(BOOL)closing {
541 // First, stop the existing animation, if there is one.
542 [animation_ stopAnimation];
544 NSRect targetFrame = [window frame];
545 targetFrame.origin = targetOrigin;
547 // NSViewAnimation has a quirk when setting the curve to NSAnimationEaseOut
548 // where it attempts to auto-reverse the animation. FadeOut becomes FadeIn
549 // (good), but FrameKey is also switched (bad). So |targetFrame| needs to be
550 // put on the StartFrameKey when using NSAnimationEaseOut for showing.
551 NSArray* animationArray = @[
553 NSViewAnimationTargetKey : window,
554 NSViewAnimationEffectKey : NSViewAnimationFadeOutEffect,
555 (closing ? NSViewAnimationEndFrameKey : NSViewAnimationStartFrameKey) :
556 [NSValue valueWithRect:targetFrame]
560 [[NSViewAnimation alloc] initWithViewAnimations:animationArray]);
561 [animation_ setDuration:kAnimationDuration];
562 [animation_ setDelegate:self];
565 [animation_ setAnimationCurve:NSAnimationEaseIn];
566 window_.reset([window retain]);
568 [window setAlphaValue:0.0f];
569 [animation_ setAnimationCurve:NSAnimationEaseOut];
572 [animation_ setAnimationBlockingMode:NSAnimationNonblockingThreaded];
573 [animation_ startAnimation];
576 - (void)cleanupOnUIThread {
577 bool closing = [self isClosing];
583 apps::AppShimHandler::MaybeTerminate();
586 - (void)animationDidEnd:(NSAnimation*)animation {
587 content::BrowserThread::PostTask(
588 content::BrowserThread::UI,
590 base::Bind(&AppListServiceMac::WindowAnimationDidEnd,
591 base::Unretained(AppListServiceMac::GetInstance())));