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 "apps/app_shim/extension_app_shim_handler_mac.h"
7 #include "apps/app_lifetime_monitor_factory.h"
8 #include "apps/app_shim/app_shim_host_manager_mac.h"
9 #include "apps/app_shim/app_shim_messages.h"
10 #include "apps/launcher.h"
11 #include "apps/shell_window.h"
12 #include "apps/shell_window_registry.h"
13 #include "apps/ui/native_app_window.h"
14 #include "base/files/file_path.h"
15 #include "base/logging.h"
16 #include "chrome/browser/browser_process.h"
17 #include "chrome/browser/chrome_notification_types.h"
18 #include "chrome/browser/extensions/extension_host.h"
19 #include "chrome/browser/profiles/profile.h"
20 #include "chrome/browser/profiles/profile_manager.h"
21 #include "chrome/browser/ui/extensions/extension_enable_flow.h"
22 #include "chrome/browser/ui/extensions/extension_enable_flow_delegate.h"
23 #include "chrome/browser/ui/web_applications/web_app_ui.h"
24 #include "chrome/browser/ui/webui/ntp/core_app_launcher_handler.h"
25 #include "chrome/browser/web_applications/web_app_mac.h"
26 #include "chrome/common/extensions/extension_constants.h"
27 #include "content/public/browser/notification_details.h"
28 #include "content/public/browser/notification_service.h"
29 #include "content/public/browser/notification_source.h"
30 #include "extensions/browser/extension_registry.h"
31 #include "ui/base/cocoa/focus_window_set.h"
33 using extensions::ExtensionRegistry;
37 typedef apps::ShellWindowRegistry::ShellWindowList ShellWindowList;
39 void ProfileLoadedCallback(base::Callback<void(Profile*)> callback,
41 Profile::CreateStatus status) {
42 if (status == Profile::CREATE_STATUS_INITIALIZED) {
43 callback.Run(profile);
47 // This should never get an error since it only loads existing profiles.
48 DCHECK_EQ(Profile::CREATE_STATUS_CREATED, status);
51 void SetAppHidden(Profile* profile, const std::string& app_id, bool hidden) {
52 ShellWindowList windows =
53 apps::ShellWindowRegistry::Get(profile)->GetShellWindowsForApp(app_id);
54 for (ShellWindowList::const_reverse_iterator it = windows.rbegin();
55 it != windows.rend(); ++it) {
57 (*it)->GetBaseWindow()->HideWithApp();
59 (*it)->GetBaseWindow()->ShowWithApp();
63 bool FocusWindows(const ShellWindowList& windows) {
67 std::set<gfx::NativeWindow> native_windows;
68 for (ShellWindowList::const_iterator it = windows.begin();
69 it != windows.end(); ++it) {
70 native_windows.insert((*it)->GetNativeWindow());
72 // Allow workspace switching. For the browser process, we can reasonably rely
73 // on OS X to switch spaces for us and honor relevant user settings. But shims
74 // don't have windows, so we have to do it ourselves.
75 ui::FocusWindowSet(native_windows, true);
79 // Attempts to launch a packaged app, prompting the user to enable it if
80 // necessary. The prompt is shown in its own window.
81 // This class manages its own lifetime.
82 class EnableViaPrompt : public ExtensionEnableFlowDelegate {
84 EnableViaPrompt(Profile* profile,
85 const std::string& extension_id,
86 const base::Callback<void()>& callback)
88 extension_id_(extension_id),
92 virtual ~EnableViaPrompt() {
96 flow_.reset(new ExtensionEnableFlow(profile_, extension_id_, this));
97 flow_->StartForCurrentlyNonexistentWindow(
98 base::Callback<gfx::NativeWindow(void)>());
102 // ExtensionEnableFlowDelegate overrides.
103 virtual void ExtensionEnableFlowFinished() OVERRIDE {
108 virtual void ExtensionEnableFlowAborted(bool user_initiated) OVERRIDE {
114 std::string extension_id_;
115 base::Callback<void()> callback_;
116 scoped_ptr<ExtensionEnableFlow> flow_;
118 DISALLOW_COPY_AND_ASSIGN(EnableViaPrompt);
125 bool ExtensionAppShimHandler::Delegate::ProfileExistsForPath(
126 const base::FilePath& path) {
127 ProfileManager* profile_manager = g_browser_process->profile_manager();
128 // Check for the profile name in the profile info cache to ensure that we
129 // never access any directory that isn't a known profile.
130 base::FilePath full_path = profile_manager->user_data_dir().Append(path);
131 ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
132 return cache.GetIndexOfProfileWithPath(full_path) != std::string::npos;
135 Profile* ExtensionAppShimHandler::Delegate::ProfileForPath(
136 const base::FilePath& path) {
137 ProfileManager* profile_manager = g_browser_process->profile_manager();
138 base::FilePath full_path = profile_manager->user_data_dir().Append(path);
139 Profile* profile = profile_manager->GetProfileByPath(full_path);
141 // Use IsValidProfile to check if the profile has been created.
142 return profile && profile_manager->IsValidProfile(profile) ? profile : NULL;
145 void ExtensionAppShimHandler::Delegate::LoadProfileAsync(
146 const base::FilePath& path,
147 base::Callback<void(Profile*)> callback) {
148 ProfileManager* profile_manager = g_browser_process->profile_manager();
149 base::FilePath full_path = profile_manager->user_data_dir().Append(path);
150 profile_manager->CreateProfileAsync(
152 base::Bind(&ProfileLoadedCallback, callback),
153 base::string16(), base::string16(), std::string());
156 ShellWindowList ExtensionAppShimHandler::Delegate::GetWindows(
158 const std::string& extension_id) {
159 return ShellWindowRegistry::Get(profile)->GetShellWindowsForApp(extension_id);
162 const extensions::Extension*
163 ExtensionAppShimHandler::Delegate::GetAppExtension(
165 const std::string& extension_id) {
166 ExtensionRegistry* registry = ExtensionRegistry::Get(profile);
167 const extensions::Extension* extension =
168 registry->GetExtensionById(extension_id, ExtensionRegistry::ENABLED);
169 return extension && extension->is_platform_app() ? extension : NULL;
172 void ExtensionAppShimHandler::Delegate::EnableExtension(
174 const std::string& extension_id,
175 const base::Callback<void()>& callback) {
176 (new EnableViaPrompt(profile, extension_id, callback))->Run();
179 void ExtensionAppShimHandler::Delegate::LaunchApp(
181 const extensions::Extension* extension,
182 const std::vector<base::FilePath>& files) {
183 CoreAppLauncherHandler::RecordAppLaunchType(
184 extension_misc::APP_LAUNCH_CMD_LINE_APP, extension->GetType());
186 apps::LaunchPlatformApp(profile, extension);
188 for (std::vector<base::FilePath>::const_iterator it = files.begin();
189 it != files.end(); ++it) {
190 apps::LaunchPlatformAppWithPath(profile, extension, *it);
195 void ExtensionAppShimHandler::Delegate::LaunchShim(
197 const extensions::Extension* extension) {
198 web_app::MaybeLaunchShortcut(
199 web_app::ShortcutInfoForExtensionAndProfile(extension, profile));
202 void ExtensionAppShimHandler::Delegate::MaybeTerminate() {
203 AppShimHandler::MaybeTerminate();
206 ExtensionAppShimHandler::ExtensionAppShimHandler()
207 : delegate_(new Delegate),
208 weak_factory_(this) {
209 // This is instantiated in BrowserProcessImpl::PreMainMessageLoopRun with
210 // AppShimHostManager. Since PROFILE_CREATED is not fired until
211 // ProfileManager::GetLastUsedProfile/GetLastOpenedProfiles, this should catch
212 // notifications for all profiles.
213 registrar_.Add(this, chrome::NOTIFICATION_PROFILE_CREATED,
214 content::NotificationService::AllBrowserContextsAndSources());
215 registrar_.Add(this, chrome::NOTIFICATION_PROFILE_DESTROYED,
216 content::NotificationService::AllBrowserContextsAndSources());
219 ExtensionAppShimHandler::~ExtensionAppShimHandler() {}
221 AppShimHandler::Host* ExtensionAppShimHandler::FindHost(
223 const std::string& app_id) {
224 HostMap::iterator it = hosts_.find(make_pair(profile, app_id));
225 return it == hosts_.end() ? NULL : it->second;
229 void ExtensionAppShimHandler::QuitAppForWindow(ShellWindow* shell_window) {
230 ExtensionAppShimHandler* handler =
231 g_browser_process->platform_part()->app_shim_host_manager()->
232 extension_app_shim_handler();
233 Host* host = handler->FindHost(shell_window->profile(),
234 shell_window->extension_id());
236 handler->OnShimQuit(host);
238 // App shims might be disabled or the shim is still starting up.
239 ShellWindowRegistry::Get(shell_window->profile())->
240 CloseAllShellWindowsForApp(shell_window->extension_id());
244 void ExtensionAppShimHandler::HideAppForWindow(ShellWindow* shell_window) {
245 ExtensionAppShimHandler* handler =
246 g_browser_process->platform_part()->app_shim_host_manager()->
247 extension_app_shim_handler();
248 Profile* profile = shell_window->profile();
249 Host* host = handler->FindHost(profile, shell_window->extension_id());
253 SetAppHidden(profile, shell_window->extension_id(), true);
257 void ExtensionAppShimHandler::FocusAppForWindow(ShellWindow* shell_window) {
258 ExtensionAppShimHandler* handler =
259 g_browser_process->platform_part()->app_shim_host_manager()->
260 extension_app_shim_handler();
261 Profile* profile = shell_window->profile();
262 const std::string& app_id = shell_window->extension_id();
263 Host* host = handler->FindHost(profile, app_id);
265 handler->OnShimFocus(host,
266 APP_SHIM_FOCUS_NORMAL,
267 std::vector<base::FilePath>());
270 apps::ShellWindowRegistry::Get(profile)->GetShellWindowsForApp(app_id));
275 bool ExtensionAppShimHandler::RequestUserAttentionForWindow(
276 ShellWindow* shell_window) {
277 ExtensionAppShimHandler* handler =
278 g_browser_process->platform_part()->app_shim_host_manager()->
279 extension_app_shim_handler();
280 Profile* profile = shell_window->profile();
281 Host* host = handler->FindHost(profile, shell_window->extension_id());
283 // Bring the window to the front without showing it.
284 ShellWindowRegistry::Get(profile)->ShellWindowActivated(shell_window);
285 host->OnAppRequestUserAttention();
288 // Just show the app.
289 SetAppHidden(profile, shell_window->extension_id(), false);
294 void ExtensionAppShimHandler::OnShimLaunch(
296 AppShimLaunchType launch_type,
297 const std::vector<base::FilePath>& files) {
298 const std::string& app_id = host->GetAppId();
299 DCHECK(extensions::Extension::IdIsValid(app_id));
301 const base::FilePath& profile_path = host->GetProfilePath();
302 DCHECK(!profile_path.empty());
304 if (!delegate_->ProfileExistsForPath(profile_path)) {
305 // User may have deleted the profile this shim was originally created for.
306 // TODO(jackhou): Add some UI for this case and remove the LOG.
307 LOG(ERROR) << "Requested directory is not a known profile '"
308 << profile_path.value() << "'.";
309 host->OnAppLaunchComplete(APP_SHIM_LAUNCH_PROFILE_NOT_FOUND);
313 Profile* profile = delegate_->ProfileForPath(profile_path);
316 OnProfileLoaded(host, launch_type, files, profile);
320 // If the profile is not loaded, this must have been a launch by the shim.
321 // Load the profile asynchronously, the host will be registered in
323 DCHECK_EQ(APP_SHIM_LAUNCH_NORMAL, launch_type);
324 delegate_->LoadProfileAsync(
326 base::Bind(&ExtensionAppShimHandler::OnProfileLoaded,
327 weak_factory_.GetWeakPtr(),
328 host, launch_type, files));
330 // Return now. OnAppLaunchComplete will be called when the app is activated.
333 void ExtensionAppShimHandler::OnProfileLoaded(
335 AppShimLaunchType launch_type,
336 const std::vector<base::FilePath>& files,
338 const std::string& app_id = host->GetAppId();
340 // The first host to claim this (profile, app_id) becomes the main host.
341 // For any others, focus or relaunch the app.
342 if (!hosts_.insert(make_pair(make_pair(profile, app_id), host)).second) {
344 launch_type == APP_SHIM_LAUNCH_NORMAL ?
345 APP_SHIM_FOCUS_REOPEN : APP_SHIM_FOCUS_NORMAL,
347 host->OnAppLaunchComplete(APP_SHIM_LAUNCH_DUPLICATE_HOST);
351 if (launch_type != APP_SHIM_LAUNCH_NORMAL) {
352 host->OnAppLaunchComplete(APP_SHIM_LAUNCH_SUCCESS);
356 // TODO(jeremya): Handle the case that launching the app fails. Probably we
357 // need to watch for 'app successfully launched' or at least 'background page
358 // exists/was created' and time out with failure if we don't see that sign of
359 // life within a certain window.
360 const extensions::Extension* extension =
361 delegate_->GetAppExtension(profile, app_id);
363 delegate_->LaunchApp(profile, extension, files);
367 delegate_->EnableExtension(
369 base::Bind(&ExtensionAppShimHandler::OnExtensionEnabled,
370 weak_factory_.GetWeakPtr(),
371 host->GetProfilePath(), app_id, files));
374 void ExtensionAppShimHandler::OnExtensionEnabled(
375 const base::FilePath& profile_path,
376 const std::string& app_id,
377 const std::vector<base::FilePath>& files) {
378 Profile* profile = delegate_->ProfileForPath(profile_path);
382 const extensions::Extension* extension =
383 delegate_->GetAppExtension(profile, app_id);
384 if (!extension || !delegate_->ProfileExistsForPath(profile_path)) {
385 // If !extension, the extension doesn't exist, or was not re-enabled.
386 // If the profile doesn't exist, it may have been deleted during the enable
387 // prompt. In this case, NOTIFICATION_PROFILE_DESTROYED may not be fired
388 // until later, so respond to the host now.
389 Host* host = FindHost(profile, app_id);
391 host->OnAppLaunchComplete(APP_SHIM_LAUNCH_APP_NOT_FOUND);
395 delegate_->LaunchApp(profile, extension, files);
399 void ExtensionAppShimHandler::OnShimClose(Host* host) {
400 // This might be called when shutting down. Don't try to look up the profile
401 // since profile_manager might not be around.
402 for (HostMap::iterator it = hosts_.begin(); it != hosts_.end(); ) {
403 HostMap::iterator current = it++;
404 if (current->second == host)
405 hosts_.erase(current);
409 void ExtensionAppShimHandler::OnShimFocus(
411 AppShimFocusType focus_type,
412 const std::vector<base::FilePath>& files) {
413 DCHECK(delegate_->ProfileExistsForPath(host->GetProfilePath()));
414 Profile* profile = delegate_->ProfileForPath(host->GetProfilePath());
416 const ShellWindowList windows =
417 delegate_->GetWindows(profile, host->GetAppId());
418 bool windows_focused = FocusWindows(windows);
420 if (focus_type == APP_SHIM_FOCUS_NORMAL ||
421 (focus_type == APP_SHIM_FOCUS_REOPEN && windows_focused)) {
425 const extensions::Extension* extension =
426 delegate_->GetAppExtension(profile, host->GetAppId());
428 delegate_->LaunchApp(profile, extension, files);
430 // Extensions may have been uninstalled or disabled since the shim
436 void ExtensionAppShimHandler::OnShimSetHidden(Host* host, bool hidden) {
437 DCHECK(delegate_->ProfileExistsForPath(host->GetProfilePath()));
438 Profile* profile = delegate_->ProfileForPath(host->GetProfilePath());
440 SetAppHidden(profile, host->GetAppId(), hidden);
443 void ExtensionAppShimHandler::OnShimQuit(Host* host) {
444 DCHECK(delegate_->ProfileExistsForPath(host->GetProfilePath()));
445 Profile* profile = delegate_->ProfileForPath(host->GetProfilePath());
447 const std::string& app_id = host->GetAppId();
448 const ShellWindowList windows =
449 delegate_->GetWindows(profile, app_id);
450 for (ShellWindowRegistry::const_iterator it = windows.begin();
451 it != windows.end(); ++it) {
452 (*it)->GetBaseWindow()->Close();
454 // Once the last window closes, flow will end up in OnAppDeactivated via
455 // AppLifetimeMonitor.
458 void ExtensionAppShimHandler::set_delegate(Delegate* delegate) {
459 delegate_.reset(delegate);
462 void ExtensionAppShimHandler::Observe(
464 const content::NotificationSource& source,
465 const content::NotificationDetails& details) {
466 Profile* profile = content::Source<Profile>(source).ptr();
467 if (profile->IsOffTheRecord())
471 case chrome::NOTIFICATION_PROFILE_CREATED: {
472 AppLifetimeMonitorFactory::GetForProfile(profile)->AddObserver(this);
475 case chrome::NOTIFICATION_PROFILE_DESTROYED: {
476 AppLifetimeMonitorFactory::GetForProfile(profile)->RemoveObserver(this);
477 // Shut down every shim associated with this profile.
478 for (HostMap::iterator it = hosts_.begin(); it != hosts_.end(); ) {
479 // Increment the iterator first as OnAppClosed may call back to
480 // OnShimClose and invalidate the iterator.
481 HostMap::iterator current = it++;
482 if (profile->IsSameProfile(current->first.first)) {
483 Host* host = current->second;
490 NOTREACHED(); // Unexpected notification.
496 void ExtensionAppShimHandler::OnAppStart(Profile* profile,
497 const std::string& app_id) {}
499 void ExtensionAppShimHandler::OnAppActivated(Profile* profile,
500 const std::string& app_id) {
501 const extensions::Extension* extension =
502 delegate_->GetAppExtension(profile, app_id);
506 Host* host = FindHost(profile, app_id);
508 host->OnAppLaunchComplete(APP_SHIM_LAUNCH_SUCCESS);
509 OnShimFocus(host, APP_SHIM_FOCUS_NORMAL, std::vector<base::FilePath>());
513 delegate_->LaunchShim(profile, extension);
516 void ExtensionAppShimHandler::OnAppDeactivated(Profile* profile,
517 const std::string& app_id) {
518 Host* host = FindHost(profile, app_id);
523 delegate_->MaybeTerminate();
526 void ExtensionAppShimHandler::OnAppStop(Profile* profile,
527 const std::string& app_id) {}
529 void ExtensionAppShimHandler::OnChromeTerminating() {}