[Password manager] Temporarily add some CHECKs to investigate a crash
[chromium-blink-merge.git] / chrome / browser / ui / app_list / app_list_service_mac.mm
blobf33787952a5cf644c7bc20e3b115a7bff42d029e
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   // On Mac, Init() is called multiple times for a process: any time there is no
350   // browser window open and a new window is opened, and during process startup
351   // to handle the silent launch case (e.g. for app shims). In the startup case,
352   // a profile has not yet been determined so |initial_profile| will be NULL.
353   static bool init_called_with_profile = false;
354   if (initial_profile && !init_called_with_profile) {
355     init_called_with_profile = true;
356     PerformStartupChecks(initial_profile);
357     PrefService* local_state = g_browser_process->local_state();
358     if (!IsAppLauncherEnabled()) {
359       local_state->SetInteger(prefs::kAppLauncherShortcutVersion, 0);
360     } else {
361       int installed_shortcut_version =
362           local_state->GetInteger(prefs::kAppLauncherShortcutVersion);
364       if (kShortcutVersion > installed_shortcut_version)
365         CreateShortcut();
366     }
367   }
369   static bool init_called = false;
370   if (init_called)
371     return;
373   init_called = true;
374   apps::AppShimHandler::RegisterHandler(app_mode::kAppListModeId, this);
376   // Handle the case where Chrome was not running and was started with the app
377   // launcher shim. The profile has not yet been loaded. To improve response
378   // times, start animating an empty window which will be populated via
379   // OnShimLaunch(). Note that if --silent-launch is not also passed, the window
380   // will instead populate via StartupBrowserCreator::Launch(). Shim-initiated
381   // launches will always have --silent-launch.
382   if (base::CommandLine::ForCurrentProcess()->
383       HasSwitch(switches::kShowAppList)) {
384     // Do not show the launcher window when the profile is locked, or if it
385     // can't be displayed unpopulated. In the latter case, the Show will occur
386     // in OnShimLaunch() or AppListService::HandleLaunchCommandLine().
387     const ProfileInfoCache& profile_info_cache =
388         g_browser_process->profile_manager()->GetProfileInfoCache();
389     size_t profile_index = profile_info_cache.
390         GetIndexOfProfileWithPath(profile_path);
391     if (profile_index != std::string::npos &&
392         !profile_info_cache.ProfileIsSigninRequiredAtIndex(profile_index) &&
393         ReadyToShow())
394       ShowWindowNearDock();
395   }
398 void AppListServiceMac::DismissAppList() {
399   if (!IsAppListVisible())
400     return;
402   NSWindow* app_list_window = GetNativeWindow();
403   // If the app list is currently the main window, it will activate the next
404   // Chrome window when dismissed. But if a different application was active
405   // when the app list was shown, activate that instead.
406   base::scoped_nsobject<NSRunningApplication> prior_app;
407   if ([app_list_window isMainWindow])
408     prior_app.swap(previously_active_application_);
409   else
410     previously_active_application_.reset();
412   // If activation is successful, the app list will lose main status and try to
413   // close itself again. It can't be closed in this runloop iteration without
414   // OSX deciding to raise the next Chrome window, and _then_ activating the
415   // application on top. This also occurs if no activation option is given.
416   if ([prior_app activateWithOptions:NSApplicationActivateIgnoringOtherApps])
417     return;
419   [animation_controller_ animateWindow:app_list_window
420                           targetOrigin:last_start_origin_
421                                closing:YES];
424 void AppListServiceMac::ShowForCustomLauncherPage(Profile* profile) {
425   NOTIMPLEMENTED();
428 bool AppListServiceMac::IsAppListVisible() const {
429   return [GetNativeWindow() isVisible] &&
430       ![animation_controller_ isClosing];
433 void AppListServiceMac::EnableAppList(Profile* initial_profile,
434                                       AppListEnableSource enable_source) {
435   AppListServiceImpl::EnableAppList(initial_profile, enable_source);
436   AppController* controller = [NSApp delegate];
437   [controller initAppShimMenuController];
440 void AppListServiceMac::CreateShortcut() {
441   CreateAppListShim(GetProfilePath(
442       g_browser_process->profile_manager()->user_data_dir()));
445 NSWindow* AppListServiceMac::GetAppListWindow() {
446   return GetNativeWindow();
449 void AppListServiceMac::OnShimLaunch(apps::AppShimHandler::Host* host,
450                                      apps::AppShimLaunchType launch_type,
451                                      const std::vector<base::FilePath>& files) {
452   if (GetCurrentAppListProfile() && IsAppListVisible()) {
453     DismissAppList();
454   } else {
455     // Start by showing a possibly empty window to handle the case where Chrome
456     // is running, but hasn't yet loaded the app launcher profile.
457     if (ReadyToShow())
458       ShowWindowNearDock();
459     Show();
460   }
462   // Always close the shim process immediately.
463   host->OnAppLaunchComplete(apps::APP_SHIM_LAUNCH_DUPLICATE_HOST);
466 void AppListServiceMac::OnShimClose(apps::AppShimHandler::Host* host) {}
468 void AppListServiceMac::OnShimFocus(apps::AppShimHandler::Host* host,
469                                     apps::AppShimFocusType focus_type,
470                                     const std::vector<base::FilePath>& files) {}
472 void AppListServiceMac::OnShimSetHidden(apps::AppShimHandler::Host* host,
473                                         bool hidden) {}
475 void AppListServiceMac::OnShimQuit(apps::AppShimHandler::Host* host) {}
477 void AppListServiceMac::ShowWindowNearDock() {
478   if (IsAppListVisible())
479     return;
481   NSWindow* window = GetAppListWindow();
482   DCHECK(window);
483   NSPoint target_origin;
484   GetAppListWindowOrigins(window, &target_origin, &last_start_origin_);
485   [window setFrameOrigin:last_start_origin_];
487   // Before activating, see if an application other than Chrome is currently the
488   // active application, so that it can be reactivated when dismissing.
489   previously_active_application_.reset([ActiveApplicationNotChrome() retain]);
491   [animation_controller_ animateWindow:window
492                           targetOrigin:target_origin
493                                closing:NO];
494   [window makeKeyAndOrderFront:nil];
495   [NSApp activateIgnoringOtherApps:YES];
496   RecordAppListLaunch();
499 void AppListServiceMac::WindowAnimationDidEnd() {
500   [animation_controller_ cleanupOnUIThread];
503 // static
504 AppListService* AppListService::Get(chrome::HostDesktopType desktop_type) {
505   return GetActiveInstance();
508 // static
509 void AppListService::InitAll(Profile* initial_profile,
510                              const base::FilePath& profile_path) {
511   GetActiveInstance()->InitWithProfilePath(initial_profile, profile_path);
514 @implementation AppListAnimationController
516 - (BOOL)isClosing {
517   return !!window_;
520 - (void)animateWindow:(NSWindow*)window
521          targetOrigin:(NSPoint)targetOrigin
522               closing:(BOOL)closing {
523   // First, stop the existing animation, if there is one.
524   [animation_ stopAnimation];
526   NSRect targetFrame = [window frame];
527   targetFrame.origin = targetOrigin;
529   // NSViewAnimation has a quirk when setting the curve to NSAnimationEaseOut
530   // where it attempts to auto-reverse the animation. FadeOut becomes FadeIn
531   // (good), but FrameKey is also switched (bad). So |targetFrame| needs to be
532   // put on the StartFrameKey when using NSAnimationEaseOut for showing.
533   NSArray* animationArray = @[
534     @{
535       NSViewAnimationTargetKey : window,
536       NSViewAnimationEffectKey : NSViewAnimationFadeOutEffect,
537       (closing ? NSViewAnimationEndFrameKey : NSViewAnimationStartFrameKey) :
538           [NSValue valueWithRect:targetFrame]
539     }
540   ];
541   animation_.reset(
542       [[NSViewAnimation alloc] initWithViewAnimations:animationArray]);
543   [animation_ setDuration:kAnimationDuration];
544   [animation_ setDelegate:self];
546   if (closing) {
547     [animation_ setAnimationCurve:NSAnimationEaseIn];
548     window_.reset([window retain]);
549   } else {
550     [window setAlphaValue:0.0f];
551     [animation_ setAnimationCurve:NSAnimationEaseOut];
552     window_.reset();
553   }
554   // This once used a threaded animation, but AppKit would too often ignore
555   // -[NSView canDrawConcurrently:] and just redraw whole view hierarchies on
556   // the animation thread anyway, creating a minefield of race conditions.
557   // Non-threaded means the animation isn't as smooth and doesn't begin unless
558   // the UI runloop has spun up (after profile loading).
559   [animation_ setAnimationBlockingMode:NSAnimationNonblocking];
561   [animation_ startAnimation];
564 - (void)cleanupOnUIThread {
565   bool closing = [self isClosing];
566   [window_ close];
567   window_.reset();
568   animation_.reset();
570   if (closing)
571     apps::AppShimHandler::MaybeTerminate();
574 - (void)animationDidEnd:(NSAnimation*)animation {
575   content::BrowserThread::PostTask(
576       content::BrowserThread::UI,
577       FROM_HERE,
578       base::Bind(&AppListServiceMac::WindowAnimationDidEnd,
579                  base::Unretained(GetActiveInstance())));
582 @end