Don't show supervised user as "already on this device" while they're being imported.
[chromium-blink-merge.git] / chrome / browser / ui / app_list / app_list_service_mac.mm
blobe981f2c98ccbc22855e01f331f52a69a78d71f45
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 "base/bind.h"
11 #include "base/command_line.h"
12 #include "base/files/file_util.h"
13 #include "base/lazy_instance.h"
14 #include "base/memory/singleton.h"
15 #include "base/message_loop/message_loop.h"
16 #include "base/prefs/pref_service.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/profiles/profile_info_cache.h"
21 #include "chrome/browser/profiles/profile_manager.h"
22 #include "chrome/browser/ui/app_list/app_list_positioner.h"
23 #include "chrome/browser/ui/app_list/app_list_service.h"
24 #include "chrome/browser/ui/app_list/app_list_service_cocoa_mac.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/browser_commands.h"
28 #include "chrome/browser/ui/extensions/application_launch.h"
29 #include "chrome/browser/web_applications/web_app.h"
30 #include "chrome/browser/web_applications/web_app_mac.h"
31 #include "chrome/common/chrome_switches.h"
32 #include "chrome/common/chrome_version_info.h"
33 #include "chrome/common/extensions/manifest_handlers/app_launch_info.h"
34 #include "chrome/common/mac/app_mode_common.h"
35 #include "chrome/common/pref_names.h"
36 #include "chrome/grit/google_chrome_strings.h"
37 #include "content/public/browser/browser_thread.h"
38 #include "extensions/browser/extension_system.h"
39 #include "extensions/common/manifest_handlers/file_handler_info.h"
40 #include "grit/chrome_unscaled_resources.h"
41 #include "net/base/url_util.h"
42 #include "ui/app_list/app_list_switches.h"
43 #include "ui/app_list/search_box_model.h"
44 #include "ui/base/l10n/l10n_util.h"
45 #include "ui/base/resource/resource_bundle.h"
46 #include "ui/gfx/display.h"
47 #include "ui/gfx/screen.h"
49 namespace gfx {
50 class ImageSkia;
53 // Controller for animations that show or hide the app list.
54 @interface AppListAnimationController : NSObject<NSAnimationDelegate> {
55  @private
56   // When closing, the window to close. Retained until the animation ends.
57   base::scoped_nsobject<NSWindow> window_;
58   // The animation started and owned by |self|. Reset when the animation ends.
59   base::scoped_nsobject<NSViewAnimation> animation_;
62 // Returns whether |window_| is scheduled to be closed when the animation ends.
63 - (BOOL)isClosing;
65 // Animate |window| to show or close it, after cancelling any current animation.
66 // Translates from the current location to |targetOrigin| and fades in or out.
67 - (void)animateWindow:(NSWindow*)window
68          targetOrigin:(NSPoint)targetOrigin
69               closing:(BOOL)closing;
71 // Called on the UI thread once the animation has completed to reset the
72 // animation state, close the window (if it is a close animation), and possibly
73 // terminate Chrome.
74 - (void)cleanupOnUIThread;
76 @end
78 namespace {
80 // Version of the app list shortcut version installed.
81 const int kShortcutVersion = 2;
83 // Duration of show and hide animations.
84 const NSTimeInterval kAnimationDuration = 0.2;
86 // Distance towards the screen edge that the app list moves from when showing.
87 const CGFloat kDistanceMovedOnShow = 20;
89 scoped_ptr<web_app::ShortcutInfo> GetAppListShortcutInfo(
90     const base::FilePath& profile_path) {
91   scoped_ptr<web_app::ShortcutInfo> shortcut_info(new web_app::ShortcutInfo);
92   chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
93   if (channel == chrome::VersionInfo::CHANNEL_CANARY) {
94     shortcut_info->title =
95         l10n_util::GetStringUTF16(IDS_APP_LIST_SHORTCUT_NAME_CANARY);
96   } else {
97     shortcut_info->title =
98         l10n_util::GetStringUTF16(IDS_APP_LIST_SHORTCUT_NAME);
99   }
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_CURRENTLY_ON(content::BrowserThread::UI);
110   WebApplicationInfo web_app_info;
111   scoped_ptr<web_app::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));
126 #else
127     NOTREACHED();
128 #endif
129   } else {
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));
138   }
140   web_app::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::CreateNonAppShortcut(shortcut_locations, shortcut_info.Pass());
154   local_state->SetInteger(prefs::kAppLauncherShortcutVersion,
155                           kShortcutVersion);
158 NSRunningApplication* ActiveApplicationNotChrome() {
159   NSArray* applications = [[NSWorkspace sharedWorkspace] runningApplications];
160   for (NSRunningApplication* application in applications) {
161     if (![application isActive])
162       continue;
164     if ([application isEqual:[NSRunningApplication currentApplication]])
165       return nil;  // Chrome is active.
167     return application;
168   }
170   return nil;
173 // Determines which screen edge the dock is aligned to.
174 AppListPositioner::ScreenEdge DockLocationInDisplay(
175     const gfx::Display& display) {
176   // Assume the dock occupies part of the work area either on the left, right or
177   // bottom of the display. Note in the autohide case, it is always 4 pixels.
178   const gfx::Rect work_area = display.work_area();
179   const gfx::Rect display_bounds = display.bounds();
180   if (work_area.bottom() != display_bounds.bottom())
181     return AppListPositioner::SCREEN_EDGE_BOTTOM;
183   if (work_area.x() != display_bounds.x())
184     return AppListPositioner::SCREEN_EDGE_LEFT;
186   if (work_area.right() != display_bounds.right())
187     return AppListPositioner::SCREEN_EDGE_RIGHT;
189   return AppListPositioner::SCREEN_EDGE_UNKNOWN;
192 // If |display|'s work area is too close to its boundary on |dock_edge|, adjust
193 // the work area away from the edge by a constant amount to reduce overlap and
194 // ensure the dock icon can still be clicked to dismiss the app list.
195 void AdjustWorkAreaForDock(const gfx::Display& display,
196                            AppListPositioner* positioner,
197                            AppListPositioner::ScreenEdge dock_edge) {
198   const int kAutohideDockThreshold = 10;
199   const int kExtraDistance = 50;  // A dock with 40 items is about this size.
201   const gfx::Rect work_area = display.work_area();
202   const gfx::Rect display_bounds = display.bounds();
204   switch (dock_edge) {
205     case AppListPositioner::SCREEN_EDGE_LEFT:
206       if (work_area.x() - display_bounds.x() <= kAutohideDockThreshold)
207         positioner->WorkAreaInset(kExtraDistance, 0, 0, 0);
208       break;
209     case AppListPositioner::SCREEN_EDGE_RIGHT:
210       if (display_bounds.right() - work_area.right() <= kAutohideDockThreshold)
211         positioner->WorkAreaInset(0, 0, kExtraDistance, 0);
212       break;
213     case AppListPositioner::SCREEN_EDGE_BOTTOM:
214       if (display_bounds.bottom() - work_area.bottom() <=
215           kAutohideDockThreshold) {
216         positioner->WorkAreaInset(0, 0, 0, kExtraDistance);
217       }
218       break;
219     case AppListPositioner::SCREEN_EDGE_UNKNOWN:
220     case AppListPositioner::SCREEN_EDGE_TOP:
221       NOTREACHED();
222       break;
223   }
226 void GetAppListWindowOrigins(
227     NSWindow* window, NSPoint* target_origin, NSPoint* start_origin) {
228   gfx::Screen* const screen = gfx::Screen::GetScreenFor([window contentView]);
229   // Ensure y coordinates are flipped back into AppKit's coordinate system.
230   bool cursor_is_visible = CGCursorIsVisible();
231   gfx::Display display;
232   gfx::Point cursor;
233   if (!cursor_is_visible) {
234     // If Chrome is the active application, display on the same display as
235     // Chrome's keyWindow since this will catch activations triggered, e.g, via
236     // WebStore install. If another application is active, OSX doesn't provide a
237     // reliable way to get the display in use. Fall back to the primary display
238     // since it has the menu bar and is likely to be correct, e.g., for
239     // activations from Spotlight.
240     const gfx::NativeView key_view = [[NSApp keyWindow] contentView];
241     display = key_view && [NSApp isActive] ?
242         screen->GetDisplayNearestWindow(key_view) :
243         screen->GetPrimaryDisplay();
244   } else {
245     cursor = screen->GetCursorScreenPoint();
246     display = screen->GetDisplayNearestPoint(cursor);
247   }
249   const NSSize ns_window_size = [window frame].size;
250   gfx::Size window_size(ns_window_size.width, ns_window_size.height);
251   int primary_display_height =
252       NSMaxY([[[NSScreen screens] objectAtIndex:0] frame]);
253   AppListServiceMac::FindAnchorPoint(window_size,
254                                      display,
255                                      primary_display_height,
256                                      cursor_is_visible,
257                                      cursor,
258                                      target_origin,
259                                      start_origin);
262 AppListServiceMac* GetActiveInstance() {
263   if (app_list::switches::IsMacViewsAppListListEnabled()) {
264 #if defined(TOOLKIT_VIEWS)
265     // TODO(tapted): Return AppListServiceViewsMac instance.
266 #else
267     NOTREACHED();
268 #endif
269   }
270   return AppListServiceCocoaMac::GetInstance();
273 }  // namespace
275 AppListServiceMac::AppListServiceMac() {
276   animation_controller_.reset([[AppListAnimationController alloc] init]);
279 AppListServiceMac::~AppListServiceMac() {}
281 // static
282 void AppListServiceMac::FindAnchorPoint(const gfx::Size& window_size,
283                                         const gfx::Display& display,
284                                         int primary_display_height,
285                                         bool cursor_is_visible,
286                                         const gfx::Point& cursor,
287                                         NSPoint* target_origin,
288                                         NSPoint* start_origin) {
289   AppListPositioner positioner(display, window_size, 0);
290   AppListPositioner::ScreenEdge dock_location = DockLocationInDisplay(display);
292   gfx::Point anchor;
293   // Snap to the dock edge. If the cursor is greater than the window
294   // width/height away or not visible, anchor to the center of the dock.
295   // Otherwise, anchor to the cursor position.
296   if (dock_location == AppListPositioner::SCREEN_EDGE_UNKNOWN) {
297     anchor = positioner.GetAnchorPointForScreenCorner(
298         AppListPositioner::SCREEN_CORNER_BOTTOM_LEFT);
299   } else {
300     int snap_distance =
301         dock_location == AppListPositioner::SCREEN_EDGE_BOTTOM ||
302                 dock_location == AppListPositioner::SCREEN_EDGE_TOP ?
303             window_size.height() :
304             window_size.width();
305     // Subtract the dock area since the display's default work_area will not
306     // subtract it if the dock is set to auto-hide, and the app list should
307     // never overlap the dock.
308     AdjustWorkAreaForDock(display, &positioner, dock_location);
309     if (!cursor_is_visible || positioner.GetCursorDistanceFromShelf(
310                                   dock_location, cursor) > snap_distance) {
311       anchor = positioner.GetAnchorPointForShelfCenter(dock_location);
312     } else {
313       anchor = positioner.GetAnchorPointForShelfCursor(dock_location, cursor);
314     }
315   }
317   *target_origin = NSMakePoint(
318       anchor.x() - window_size.width() / 2,
319       primary_display_height - anchor.y() - window_size.height() / 2);
320   *start_origin = *target_origin;
322   // If the launcher is anchored to the dock (regardless of whether the cursor
323   // is visible), animate in inwards from the edge of screen
324   switch (dock_location) {
325     case AppListPositioner::SCREEN_EDGE_UNKNOWN:
326       break;
327     case AppListPositioner::SCREEN_EDGE_LEFT:
328       start_origin->x -= kDistanceMovedOnShow;
329       break;
330     case AppListPositioner::SCREEN_EDGE_RIGHT:
331       start_origin->x += kDistanceMovedOnShow;
332       break;
333     case AppListPositioner::SCREEN_EDGE_TOP:
334       NOTREACHED();
335       break;
336     case AppListPositioner::SCREEN_EDGE_BOTTOM:
337       start_origin->y -= kDistanceMovedOnShow;
338       break;
339   }
342 void AppListServiceMac::Init(Profile* initial_profile) {
343   InitWithProfilePath(initial_profile, initial_profile->GetPath());
346 void AppListServiceMac::InitWithProfilePath(
347     Profile* initial_profile,
348     const base::FilePath& profile_path) {
349   // App list profiles should not be off-the-record. It is currently possible to
350   // get here in an off-the-record profile via the Web Store
351   // (http://crbug.com/416380).
352   // TODO(mgiuca): DCHECK that requested_profile->IsOffTheRecord() and
353   // requested_profile->IsGuestSession() are false, once that is resolved.
355   // On Mac, Init() is called multiple times for a process: any time there is no
356   // browser window open and a new window is opened, and during process startup
357   // to handle the silent launch case (e.g. for app shims). In the startup case,
358   // a profile has not yet been determined so |initial_profile| will be NULL.
359   static bool init_called_with_profile = false;
360   if (initial_profile && !init_called_with_profile) {
361     init_called_with_profile = true;
362     PerformStartupChecks(initial_profile);
363     PrefService* local_state = g_browser_process->local_state();
364     if (!IsAppLauncherEnabled()) {
365       local_state->SetInteger(prefs::kAppLauncherShortcutVersion, 0);
366     } else {
367       int installed_shortcut_version =
368           local_state->GetInteger(prefs::kAppLauncherShortcutVersion);
370       if (kShortcutVersion > installed_shortcut_version)
371         CreateShortcut();
372     }
373   }
375   static bool init_called = false;
376   if (init_called)
377     return;
379   init_called = true;
380   apps::AppShimHandler::RegisterHandler(app_mode::kAppListModeId, this);
382   // Handle the case where Chrome was not running and was started with the app
383   // launcher shim. The profile has not yet been loaded. To improve response
384   // times, start animating an empty window which will be populated via
385   // OnShimLaunch(). Note that if --silent-launch is not also passed, the window
386   // will instead populate via StartupBrowserCreator::Launch(). Shim-initiated
387   // launches will always have --silent-launch.
388   if (base::CommandLine::ForCurrentProcess()->
389       HasSwitch(switches::kShowAppList)) {
390     // Do not show the launcher window when the profile is locked, or if it
391     // can't be displayed unpopulated. In the latter case, the Show will occur
392     // in OnShimLaunch() or AppListService::HandleLaunchCommandLine().
393     const ProfileInfoCache& profile_info_cache =
394         g_browser_process->profile_manager()->GetProfileInfoCache();
395     size_t profile_index = profile_info_cache.
396         GetIndexOfProfileWithPath(profile_path);
397     if (profile_index != std::string::npos &&
398         !profile_info_cache.ProfileIsSigninRequiredAtIndex(profile_index) &&
399         ReadyToShow())
400       ShowWindowNearDock();
401   }
404 void AppListServiceMac::DismissAppList() {
405   if (!IsAppListVisible())
406     return;
408   NSWindow* app_list_window = GetNativeWindow();
409   // If the app list is currently the main window, it will activate the next
410   // Chrome window when dismissed. But if a different application was active
411   // when the app list was shown, activate that instead.
412   base::scoped_nsobject<NSRunningApplication> prior_app;
413   if ([app_list_window isMainWindow])
414     prior_app.swap(previously_active_application_);
415   else
416     previously_active_application_.reset();
418   // If activation is successful, the app list will lose main status and try to
419   // close itself again. It can't be closed in this runloop iteration without
420   // OSX deciding to raise the next Chrome window, and _then_ activating the
421   // application on top. This also occurs if no activation option is given.
422   if ([prior_app activateWithOptions:NSApplicationActivateIgnoringOtherApps])
423     return;
425   [animation_controller_ animateWindow:app_list_window
426                           targetOrigin:last_start_origin_
427                                closing:YES];
430 void AppListServiceMac::ShowForCustomLauncherPage(Profile* profile) {
431   NOTIMPLEMENTED();
434 void AppListServiceMac::HideCustomLauncherPage() {
435   NOTIMPLEMENTED();
438 bool AppListServiceMac::IsAppListVisible() const {
439   return [GetNativeWindow() isVisible] &&
440       ![animation_controller_ isClosing];
443 void AppListServiceMac::EnableAppList(Profile* initial_profile,
444                                       AppListEnableSource enable_source) {
445   AppListServiceImpl::EnableAppList(initial_profile, enable_source);
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 GetNativeWindow();
459 void AppListServiceMac::OnShimLaunch(apps::AppShimHandler::Host* host,
460                                      apps::AppShimLaunchType launch_type,
461                                      const std::vector<base::FilePath>& files) {
462   if (GetCurrentAppListProfile() && IsAppListVisible()) {
463     DismissAppList();
464   } else {
465     // Start by showing a possibly empty window to handle the case where Chrome
466     // is running, but hasn't yet loaded the app launcher profile.
467     if (ReadyToShow())
468       ShowWindowNearDock();
469     Show();
470   }
472   // Always close the shim process immediately.
473   host->OnAppLaunchComplete(apps::APP_SHIM_LAUNCH_DUPLICATE_HOST);
476 void AppListServiceMac::OnShimClose(apps::AppShimHandler::Host* host) {}
478 void AppListServiceMac::OnShimFocus(apps::AppShimHandler::Host* host,
479                                     apps::AppShimFocusType focus_type,
480                                     const std::vector<base::FilePath>& files) {}
482 void AppListServiceMac::OnShimSetHidden(apps::AppShimHandler::Host* host,
483                                         bool hidden) {}
485 void AppListServiceMac::OnShimQuit(apps::AppShimHandler::Host* host) {}
487 void AppListServiceMac::ShowWindowNearDock() {
488   if (IsAppListVisible())
489     return;
491   NSWindow* window = GetAppListWindow();
492   DCHECK(window);
493   NSPoint target_origin;
494   GetAppListWindowOrigins(window, &target_origin, &last_start_origin_);
495   [window setFrameOrigin:last_start_origin_];
497   // Before activating, see if an application other than Chrome is currently the
498   // active application, so that it can be reactivated when dismissing.
499   previously_active_application_.reset([ActiveApplicationNotChrome() retain]);
501   [animation_controller_ animateWindow:window
502                           targetOrigin:target_origin
503                                closing:NO];
504   [window makeKeyAndOrderFront:nil];
505   [NSApp activateIgnoringOtherApps:YES];
506   RecordAppListLaunch();
509 void AppListServiceMac::WindowAnimationDidEnd() {
510   [animation_controller_ cleanupOnUIThread];
513 // static
514 AppListService* AppListService::Get(chrome::HostDesktopType desktop_type) {
515   return GetActiveInstance();
518 // static
519 void AppListService::InitAll(Profile* initial_profile,
520                              const base::FilePath& profile_path) {
521   GetActiveInstance()->InitWithProfilePath(initial_profile, profile_path);
524 @implementation AppListAnimationController
526 - (BOOL)isClosing {
527   return !!window_;
530 - (void)animateWindow:(NSWindow*)window
531          targetOrigin:(NSPoint)targetOrigin
532               closing:(BOOL)closing {
533   // First, stop the existing animation, if there is one.
534   [animation_ stopAnimation];
536   NSRect targetFrame = [window frame];
537   targetFrame.origin = targetOrigin;
539   // NSViewAnimation has a quirk when setting the curve to NSAnimationEaseOut
540   // where it attempts to auto-reverse the animation. FadeOut becomes FadeIn
541   // (good), but FrameKey is also switched (bad). So |targetFrame| needs to be
542   // put on the StartFrameKey when using NSAnimationEaseOut for showing.
543   NSArray* animationArray = @[
544     @{
545       NSViewAnimationTargetKey : window,
546       NSViewAnimationEffectKey : NSViewAnimationFadeOutEffect,
547       (closing ? NSViewAnimationEndFrameKey : NSViewAnimationStartFrameKey) :
548           [NSValue valueWithRect:targetFrame]
549     }
550   ];
551   animation_.reset(
552       [[NSViewAnimation alloc] initWithViewAnimations:animationArray]);
553   [animation_ setDuration:kAnimationDuration];
554   [animation_ setDelegate:self];
556   if (closing) {
557     [animation_ setAnimationCurve:NSAnimationEaseIn];
558     window_.reset([window retain]);
559   } else {
560     [window setAlphaValue:0.0f];
561     [animation_ setAnimationCurve:NSAnimationEaseOut];
562     window_.reset();
563   }
564   // This once used a threaded animation, but AppKit would too often ignore
565   // -[NSView canDrawConcurrently:] and just redraw whole view hierarchies on
566   // the animation thread anyway, creating a minefield of race conditions.
567   // Non-threaded means the animation isn't as smooth and doesn't begin unless
568   // the UI runloop has spun up (after profile loading).
569   [animation_ setAnimationBlockingMode:NSAnimationNonblocking];
571   [animation_ startAnimation];
574 - (void)cleanupOnUIThread {
575   bool closing = [self isClosing];
576   [window_ close];
577   window_.reset();
578   animation_.reset();
580   if (closing)
581     apps::AppShimHandler::MaybeTerminate();
584 - (void)animationDidEnd:(NSAnimation*)animation {
585   content::BrowserThread::PostTask(
586       content::BrowserThread::UI,
587       FROM_HERE,
588       base::Bind(&AppListServiceMac::WindowAnimationDidEnd,
589                  base::Unretained(GetActiveInstance())));
592 @end