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 #include "chrome/browser/apps/app_shim/extension_app_shim_handler_mac.h"
7 #include "apps/app_lifetime_monitor_factory.h"
8 #include "apps/launcher.h"
9 #include "base/files/file_path.h"
10 #include "base/logging.h"
11 #include "chrome/browser/apps/app_shim/app_shim_host_manager_mac.h"
12 #include "chrome/browser/browser_process.h"
13 #include "chrome/browser/chrome_notification_types.h"
14 #include "chrome/browser/profiles/profile.h"
15 #include "chrome/browser/profiles/profile_manager.h"
16 #include "chrome/browser/ui/extensions/extension_enable_flow.h"
17 #include "chrome/browser/ui/extensions/extension_enable_flow_delegate.h"
18 #include "chrome/browser/ui/webui/ntp/core_app_launcher_handler.h"
19 #include "chrome/browser/web_applications/web_app_mac.h"
20 #include "chrome/common/extensions/extension_constants.h"
21 #include "chrome/common/mac/app_shim_messages.h"
22 #include "components/crx_file/id_util.h"
23 #include "content/public/browser/notification_details.h"
24 #include "content/public/browser/notification_service.h"
25 #include "content/public/browser/notification_source.h"
26 #include "extensions/browser/app_window/app_window.h"
27 #include "extensions/browser/app_window/app_window_registry.h"
28 #include "extensions/browser/app_window/native_app_window.h"
29 #include "extensions/browser/extension_host.h"
30 #include "extensions/browser/extension_registry.h"
31 #include "extensions/common/constants.h"
32 #include "ui/base/cocoa/focus_window_set.h"
34 using extensions::AppWindow;
35 using extensions::AppWindowRegistry;
36 using extensions::ExtensionRegistry;
40 typedef AppWindowRegistry::AppWindowList AppWindowList;
42 void ProfileLoadedCallback(base::Callback<void(Profile*)> callback,
44 Profile::CreateStatus status) {
45 if (status == Profile::CREATE_STATUS_INITIALIZED) {
46 callback.Run(profile);
50 // This should never get an error since it only loads existing profiles.
51 DCHECK_EQ(Profile::CREATE_STATUS_CREATED, status);
54 void SetAppHidden(Profile* profile, const std::string& app_id, bool hidden) {
55 AppWindowList windows =
56 AppWindowRegistry::Get(profile)->GetAppWindowsForApp(app_id);
57 for (AppWindowList::const_reverse_iterator it = windows.rbegin();
61 (*it)->GetBaseWindow()->HideWithApp();
63 (*it)->GetBaseWindow()->ShowWithApp();
67 bool FocusWindows(const AppWindowList& windows) {
71 std::set<gfx::NativeWindow> native_windows;
72 for (AppWindowList::const_iterator it = windows.begin(); it != windows.end();
74 native_windows.insert((*it)->GetNativeWindow());
76 // Allow workspace switching. For the browser process, we can reasonably rely
77 // on OS X to switch spaces for us and honor relevant user settings. But shims
78 // don't have windows, so we have to do it ourselves.
79 ui::FocusWindowSet(native_windows);
83 // Attempts to launch a packaged app, prompting the user to enable it if
84 // necessary. The prompt is shown in its own window.
85 // This class manages its own lifetime.
86 class EnableViaPrompt : public ExtensionEnableFlowDelegate {
88 EnableViaPrompt(Profile* profile,
89 const std::string& extension_id,
90 const base::Callback<void()>& callback)
92 extension_id_(extension_id),
96 ~EnableViaPrompt() override {}
99 flow_.reset(new ExtensionEnableFlow(profile_, extension_id_, this));
100 flow_->StartForCurrentlyNonexistentWindow(
101 base::Callback<gfx::NativeWindow(void)>());
105 // ExtensionEnableFlowDelegate overrides.
106 void ExtensionEnableFlowFinished() override {
111 void ExtensionEnableFlowAborted(bool user_initiated) override {
117 std::string extension_id_;
118 base::Callback<void()> callback_;
119 scoped_ptr<ExtensionEnableFlow> flow_;
121 DISALLOW_COPY_AND_ASSIGN(EnableViaPrompt);
128 bool ExtensionAppShimHandler::Delegate::ProfileExistsForPath(
129 const base::FilePath& path) {
130 ProfileManager* profile_manager = g_browser_process->profile_manager();
131 // Check for the profile name in the profile info cache to ensure that we
132 // never access any directory that isn't a known profile.
133 base::FilePath full_path = profile_manager->user_data_dir().Append(path);
134 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
135 return cache.GetIndexOfProfileWithPath(full_path) != std::string::npos;
138 Profile* ExtensionAppShimHandler::Delegate::ProfileForPath(
139 const base::FilePath& path) {
140 ProfileManager* profile_manager = g_browser_process->profile_manager();
141 base::FilePath full_path = profile_manager->user_data_dir().Append(path);
142 Profile* profile = profile_manager->GetProfileByPath(full_path);
144 // Use IsValidProfile to check if the profile has been created.
145 return profile && profile_manager->IsValidProfile(profile) ? profile : NULL;
148 void ExtensionAppShimHandler::Delegate::LoadProfileAsync(
149 const base::FilePath& path,
150 base::Callback<void(Profile*)> callback) {
151 ProfileManager* profile_manager = g_browser_process->profile_manager();
152 base::FilePath full_path = profile_manager->user_data_dir().Append(path);
153 profile_manager->CreateProfileAsync(
155 base::Bind(&ProfileLoadedCallback, callback),
156 base::string16(), base::string16(), std::string());
159 AppWindowList ExtensionAppShimHandler::Delegate::GetWindows(
161 const std::string& extension_id) {
162 return AppWindowRegistry::Get(profile)->GetAppWindowsForApp(extension_id);
165 const extensions::Extension*
166 ExtensionAppShimHandler::Delegate::GetAppExtension(
168 const std::string& extension_id) {
169 ExtensionRegistry* registry = ExtensionRegistry::Get(profile);
170 const extensions::Extension* extension =
171 registry->GetExtensionById(extension_id, ExtensionRegistry::ENABLED);
172 return extension && extension->is_platform_app() ? extension : NULL;
175 void ExtensionAppShimHandler::Delegate::EnableExtension(
177 const std::string& extension_id,
178 const base::Callback<void()>& callback) {
179 (new EnableViaPrompt(profile, extension_id, callback))->Run();
182 void ExtensionAppShimHandler::Delegate::LaunchApp(
184 const extensions::Extension* extension,
185 const std::vector<base::FilePath>& files) {
186 CoreAppLauncherHandler::RecordAppLaunchType(
187 extension_misc::APP_LAUNCH_CMD_LINE_APP, extension->GetType());
189 apps::LaunchPlatformApp(
190 profile, extension, extensions::SOURCE_COMMAND_LINE);
192 for (std::vector<base::FilePath>::const_iterator it = files.begin();
193 it != files.end(); ++it) {
194 apps::LaunchPlatformAppWithPath(profile, extension, *it);
199 void ExtensionAppShimHandler::Delegate::LaunchShim(
201 const extensions::Extension* extension) {
202 web_app::MaybeLaunchShortcut(
203 web_app::ShortcutInfoForExtensionAndProfile(extension, profile));
206 void ExtensionAppShimHandler::Delegate::MaybeTerminate() {
207 AppShimHandler::MaybeTerminate();
210 ExtensionAppShimHandler::ExtensionAppShimHandler()
211 : delegate_(new Delegate),
212 weak_factory_(this) {
213 // This is instantiated in BrowserProcessImpl::PreMainMessageLoopRun with
214 // AppShimHostManager. Since PROFILE_CREATED is not fired until
215 // ProfileManager::GetLastUsedProfile/GetLastOpenedProfiles, this should catch
216 // notifications for all profiles.
217 registrar_.Add(this, chrome::NOTIFICATION_PROFILE_CREATED,
218 content::NotificationService::AllBrowserContextsAndSources());
219 registrar_.Add(this, chrome::NOTIFICATION_PROFILE_DESTROYED,
220 content::NotificationService::AllBrowserContextsAndSources());
223 ExtensionAppShimHandler::~ExtensionAppShimHandler() {}
225 AppShimHandler::Host* ExtensionAppShimHandler::FindHost(
227 const std::string& app_id) {
228 HostMap::iterator it = hosts_.find(make_pair(profile, app_id));
229 return it == hosts_.end() ? NULL : it->second;
233 void ExtensionAppShimHandler::QuitAppForWindow(AppWindow* app_window) {
234 ExtensionAppShimHandler* handler = GetInstance();
235 Host* host = handler->FindHost(
236 Profile::FromBrowserContext(app_window->browser_context()),
237 app_window->extension_id());
239 handler->OnShimQuit(host);
241 // App shims might be disabled or the shim is still starting up.
242 AppWindowRegistry::Get(
243 Profile::FromBrowserContext(app_window->browser_context()))
244 ->CloseAllAppWindowsForApp(app_window->extension_id());
248 void ExtensionAppShimHandler::HideAppForWindow(AppWindow* app_window) {
249 ExtensionAppShimHandler* handler = GetInstance();
250 Profile* profile = Profile::FromBrowserContext(app_window->browser_context());
251 Host* host = handler->FindHost(profile, app_window->extension_id());
255 SetAppHidden(profile, app_window->extension_id(), true);
258 void ExtensionAppShimHandler::FocusAppForWindow(AppWindow* app_window) {
259 ExtensionAppShimHandler* handler = GetInstance();
260 Profile* profile = Profile::FromBrowserContext(app_window->browser_context());
261 const std::string& app_id = app_window->extension_id();
262 Host* host = handler->FindHost(profile, app_id);
264 handler->OnShimFocus(host,
265 APP_SHIM_FOCUS_NORMAL,
266 std::vector<base::FilePath>());
268 FocusWindows(AppWindowRegistry::Get(profile)->GetAppWindowsForApp(app_id));
273 bool ExtensionAppShimHandler::ActivateAndRequestUserAttentionForWindow(
274 AppWindow* app_window) {
275 ExtensionAppShimHandler* handler = GetInstance();
276 Profile* profile = Profile::FromBrowserContext(app_window->browser_context());
277 Host* host = handler->FindHost(profile, app_window->extension_id());
279 // Bring the window to the front without showing it.
280 AppWindowRegistry::Get(profile)->AppWindowActivated(app_window);
281 host->OnAppRequestUserAttention(APP_SHIM_ATTENTION_INFORMATIONAL);
284 // Just show the app.
285 SetAppHidden(profile, app_window->extension_id(), false);
291 void ExtensionAppShimHandler::RequestUserAttentionForWindow(
292 AppWindow* app_window,
293 AppShimAttentionType attention_type) {
294 ExtensionAppShimHandler* handler = GetInstance();
295 Profile* profile = Profile::FromBrowserContext(app_window->browser_context());
296 Host* host = handler->FindHost(profile, app_window->extension_id());
298 host->OnAppRequestUserAttention(attention_type);
302 void ExtensionAppShimHandler::OnChromeWillHide() {
303 // Send OnAppHide to all the shims so that they go into the hidden state.
304 // This is necessary so that when the shim is next focused, it will know to
306 ExtensionAppShimHandler* handler = GetInstance();
307 for (HostMap::iterator it = handler->hosts_.begin();
308 it != handler->hosts_.end();
310 it->second->OnAppHide();
314 void ExtensionAppShimHandler::OnShimLaunch(
316 AppShimLaunchType launch_type,
317 const std::vector<base::FilePath>& files) {
318 const std::string& app_id = host->GetAppId();
319 DCHECK(crx_file::id_util::IdIsValid(app_id));
321 const base::FilePath& profile_path = host->GetProfilePath();
322 DCHECK(!profile_path.empty());
324 if (!delegate_->ProfileExistsForPath(profile_path)) {
325 // User may have deleted the profile this shim was originally created for.
326 // TODO(jackhou): Add some UI for this case and remove the LOG.
327 LOG(ERROR) << "Requested directory is not a known profile '"
328 << profile_path.value() << "'.";
329 host->OnAppLaunchComplete(APP_SHIM_LAUNCH_PROFILE_NOT_FOUND);
333 Profile* profile = delegate_->ProfileForPath(profile_path);
336 OnProfileLoaded(host, launch_type, files, profile);
340 // If the profile is not loaded, this must have been a launch by the shim.
341 // Load the profile asynchronously, the host will be registered in
343 DCHECK_EQ(APP_SHIM_LAUNCH_NORMAL, launch_type);
344 delegate_->LoadProfileAsync(
346 base::Bind(&ExtensionAppShimHandler::OnProfileLoaded,
347 weak_factory_.GetWeakPtr(),
348 host, launch_type, files));
350 // Return now. OnAppLaunchComplete will be called when the app is activated.
354 ExtensionAppShimHandler* ExtensionAppShimHandler::GetInstance() {
355 return g_browser_process->platform_part()
356 ->app_shim_host_manager()
357 ->extension_app_shim_handler();
360 void ExtensionAppShimHandler::OnProfileLoaded(
362 AppShimLaunchType launch_type,
363 const std::vector<base::FilePath>& files,
365 const std::string& app_id = host->GetAppId();
367 // The first host to claim this (profile, app_id) becomes the main host.
368 // For any others, focus or relaunch the app.
369 if (!hosts_.insert(make_pair(make_pair(profile, app_id), host)).second) {
371 launch_type == APP_SHIM_LAUNCH_NORMAL ?
372 APP_SHIM_FOCUS_REOPEN : APP_SHIM_FOCUS_NORMAL,
374 host->OnAppLaunchComplete(APP_SHIM_LAUNCH_DUPLICATE_HOST);
378 if (launch_type != APP_SHIM_LAUNCH_NORMAL) {
379 host->OnAppLaunchComplete(APP_SHIM_LAUNCH_SUCCESS);
383 // TODO(jeremya): Handle the case that launching the app fails. Probably we
384 // need to watch for 'app successfully launched' or at least 'background page
385 // exists/was created' and time out with failure if we don't see that sign of
386 // life within a certain window.
387 const extensions::Extension* extension =
388 delegate_->GetAppExtension(profile, app_id);
390 delegate_->LaunchApp(profile, extension, files);
394 delegate_->EnableExtension(
396 base::Bind(&ExtensionAppShimHandler::OnExtensionEnabled,
397 weak_factory_.GetWeakPtr(),
398 host->GetProfilePath(), app_id, files));
401 void ExtensionAppShimHandler::OnExtensionEnabled(
402 const base::FilePath& profile_path,
403 const std::string& app_id,
404 const std::vector<base::FilePath>& files) {
405 Profile* profile = delegate_->ProfileForPath(profile_path);
409 const extensions::Extension* extension =
410 delegate_->GetAppExtension(profile, app_id);
411 if (!extension || !delegate_->ProfileExistsForPath(profile_path)) {
412 // If !extension, the extension doesn't exist, or was not re-enabled.
413 // If the profile doesn't exist, it may have been deleted during the enable
414 // prompt. In this case, NOTIFICATION_PROFILE_DESTROYED may not be fired
415 // until later, so respond to the host now.
416 Host* host = FindHost(profile, app_id);
418 host->OnAppLaunchComplete(APP_SHIM_LAUNCH_APP_NOT_FOUND);
422 delegate_->LaunchApp(profile, extension, files);
426 void ExtensionAppShimHandler::OnShimClose(Host* host) {
427 // This might be called when shutting down. Don't try to look up the profile
428 // since profile_manager might not be around.
429 for (HostMap::iterator it = hosts_.begin(); it != hosts_.end(); ) {
430 HostMap::iterator current = it++;
431 if (current->second == host)
432 hosts_.erase(current);
436 void ExtensionAppShimHandler::OnShimFocus(
438 AppShimFocusType focus_type,
439 const std::vector<base::FilePath>& files) {
440 DCHECK(delegate_->ProfileExistsForPath(host->GetProfilePath()));
441 Profile* profile = delegate_->ProfileForPath(host->GetProfilePath());
443 const AppWindowList windows =
444 delegate_->GetWindows(profile, host->GetAppId());
445 bool windows_focused = FocusWindows(windows);
447 if (focus_type == APP_SHIM_FOCUS_NORMAL ||
448 (focus_type == APP_SHIM_FOCUS_REOPEN && windows_focused)) {
452 const extensions::Extension* extension =
453 delegate_->GetAppExtension(profile, host->GetAppId());
455 delegate_->LaunchApp(profile, extension, files);
457 // Extensions may have been uninstalled or disabled since the shim
463 void ExtensionAppShimHandler::OnShimSetHidden(Host* host, bool hidden) {
464 DCHECK(delegate_->ProfileExistsForPath(host->GetProfilePath()));
465 Profile* profile = delegate_->ProfileForPath(host->GetProfilePath());
467 SetAppHidden(profile, host->GetAppId(), hidden);
470 void ExtensionAppShimHandler::OnShimQuit(Host* host) {
471 DCHECK(delegate_->ProfileExistsForPath(host->GetProfilePath()));
472 Profile* profile = delegate_->ProfileForPath(host->GetProfilePath());
474 const std::string& app_id = host->GetAppId();
475 const AppWindowList windows = delegate_->GetWindows(profile, app_id);
476 for (AppWindowRegistry::const_iterator it = windows.begin();
479 (*it)->GetBaseWindow()->Close();
481 // Once the last window closes, flow will end up in OnAppDeactivated via
482 // AppLifetimeMonitor.
485 void ExtensionAppShimHandler::set_delegate(Delegate* delegate) {
486 delegate_.reset(delegate);
489 void ExtensionAppShimHandler::Observe(
491 const content::NotificationSource& source,
492 const content::NotificationDetails& details) {
493 Profile* profile = content::Source<Profile>(source).ptr();
494 if (profile->IsOffTheRecord())
498 case chrome::NOTIFICATION_PROFILE_CREATED: {
499 AppLifetimeMonitorFactory::GetForProfile(profile)->AddObserver(this);
502 case chrome::NOTIFICATION_PROFILE_DESTROYED: {
503 AppLifetimeMonitorFactory::GetForProfile(profile)->RemoveObserver(this);
504 // Shut down every shim associated with this profile.
505 for (HostMap::iterator it = hosts_.begin(); it != hosts_.end(); ) {
506 // Increment the iterator first as OnAppClosed may call back to
507 // OnShimClose and invalidate the iterator.
508 HostMap::iterator current = it++;
509 if (profile->IsSameProfile(current->first.first)) {
510 Host* host = current->second;
517 NOTREACHED(); // Unexpected notification.
523 void ExtensionAppShimHandler::OnAppStart(Profile* profile,
524 const std::string& app_id) {}
526 void ExtensionAppShimHandler::OnAppActivated(Profile* profile,
527 const std::string& app_id) {
528 const extensions::Extension* extension =
529 delegate_->GetAppExtension(profile, app_id);
533 Host* host = FindHost(profile, app_id);
535 host->OnAppLaunchComplete(APP_SHIM_LAUNCH_SUCCESS);
536 OnShimFocus(host, APP_SHIM_FOCUS_NORMAL, std::vector<base::FilePath>());
540 delegate_->LaunchShim(profile, extension);
543 void ExtensionAppShimHandler::OnAppDeactivated(Profile* profile,
544 const std::string& app_id) {
545 Host* host = FindHost(profile, app_id);
550 delegate_->MaybeTerminate();
553 void ExtensionAppShimHandler::OnAppStop(Profile* profile,
554 const std::string& app_id) {}
556 void ExtensionAppShimHandler::OnChromeTerminating() {}