ozone: Fix typo in platform_object.h
[chromium-blink-merge.git] / apps / app_shim / extension_app_shim_handler_mac.cc
blobcef6ca2d3a6c4fdf1c312c177df502224b92aefc
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/app_window.h"
11 #include "apps/app_window_registry.h"
12 #include "apps/launcher.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/profiles/profile.h"
19 #include "chrome/browser/profiles/profile_manager.h"
20 #include "chrome/browser/ui/extensions/extension_enable_flow.h"
21 #include "chrome/browser/ui/extensions/extension_enable_flow_delegate.h"
22 #include "chrome/browser/ui/webui/ntp/core_app_launcher_handler.h"
23 #include "chrome/browser/web_applications/web_app_mac.h"
24 #include "chrome/common/extensions/extension_constants.h"
25 #include "content/public/browser/notification_details.h"
26 #include "content/public/browser/notification_service.h"
27 #include "content/public/browser/notification_source.h"
28 #include "extensions/browser/extension_host.h"
29 #include "extensions/browser/extension_registry.h"
30 #include "ui/base/cocoa/focus_window_set.h"
32 using extensions::ExtensionRegistry;
34 namespace {
36 typedef apps::AppWindowRegistry::AppWindowList AppWindowList;
38 void ProfileLoadedCallback(base::Callback<void(Profile*)> callback,
39 Profile* profile,
40 Profile::CreateStatus status) {
41 if (status == Profile::CREATE_STATUS_INITIALIZED) {
42 callback.Run(profile);
43 return;
46 // This should never get an error since it only loads existing profiles.
47 DCHECK_EQ(Profile::CREATE_STATUS_CREATED, status);
50 void SetAppHidden(Profile* profile, const std::string& app_id, bool hidden) {
51 AppWindowList windows =
52 apps::AppWindowRegistry::Get(profile)->GetAppWindowsForApp(app_id);
53 for (AppWindowList::const_reverse_iterator it = windows.rbegin();
54 it != windows.rend();
55 ++it) {
56 if (hidden)
57 (*it)->GetBaseWindow()->HideWithApp();
58 else
59 (*it)->GetBaseWindow()->ShowWithApp();
63 bool FocusWindows(const AppWindowList& windows) {
64 if (windows.empty())
65 return false;
67 std::set<gfx::NativeWindow> native_windows;
68 for (AppWindowList::const_iterator it = windows.begin(); it != windows.end();
69 ++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);
76 return 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 {
83 public:
84 EnableViaPrompt(Profile* profile,
85 const std::string& extension_id,
86 const base::Callback<void()>& callback)
87 : profile_(profile),
88 extension_id_(extension_id),
89 callback_(callback) {
92 virtual ~EnableViaPrompt() {
95 void Run() {
96 flow_.reset(new ExtensionEnableFlow(profile_, extension_id_, this));
97 flow_->StartForCurrentlyNonexistentWindow(
98 base::Callback<gfx::NativeWindow(void)>());
101 private:
102 // ExtensionEnableFlowDelegate overrides.
103 virtual void ExtensionEnableFlowFinished() OVERRIDE {
104 callback_.Run();
105 delete this;
108 virtual void ExtensionEnableFlowAborted(bool user_initiated) OVERRIDE {
109 callback_.Run();
110 delete this;
113 Profile* profile_;
114 std::string extension_id_;
115 base::Callback<void()> callback_;
116 scoped_ptr<ExtensionEnableFlow> flow_;
118 DISALLOW_COPY_AND_ASSIGN(EnableViaPrompt);
121 } // namespace
123 namespace apps {
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(
151 full_path,
152 base::Bind(&ProfileLoadedCallback, callback),
153 base::string16(), base::string16(), std::string());
156 AppWindowList ExtensionAppShimHandler::Delegate::GetWindows(
157 Profile* profile,
158 const std::string& extension_id) {
159 return AppWindowRegistry::Get(profile)->GetAppWindowsForApp(extension_id);
162 const extensions::Extension*
163 ExtensionAppShimHandler::Delegate::GetAppExtension(
164 Profile* profile,
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(
173 Profile* profile,
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(
180 Profile* profile,
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());
185 if (files.empty()) {
186 apps::LaunchPlatformApp(profile, extension);
187 } else {
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(
196 Profile* profile,
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(
222 Profile* profile,
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;
228 // static
229 void ExtensionAppShimHandler::QuitAppForWindow(AppWindow* app_window) {
230 ExtensionAppShimHandler* handler = GetInstance();
231 Host* host = handler->FindHost(
232 Profile::FromBrowserContext(app_window->browser_context()),
233 app_window->extension_id());
234 if (host) {
235 handler->OnShimQuit(host);
236 } else {
237 // App shims might be disabled or the shim is still starting up.
238 AppWindowRegistry::Get(
239 Profile::FromBrowserContext(app_window->browser_context()))
240 ->CloseAllAppWindowsForApp(app_window->extension_id());
244 void ExtensionAppShimHandler::HideAppForWindow(AppWindow* app_window) {
245 ExtensionAppShimHandler* handler = GetInstance();
246 Profile* profile = Profile::FromBrowserContext(app_window->browser_context());
247 Host* host = handler->FindHost(profile, app_window->extension_id());
248 if (host)
249 host->OnAppHide();
250 else
251 SetAppHidden(profile, app_window->extension_id(), true);
254 void ExtensionAppShimHandler::FocusAppForWindow(AppWindow* app_window) {
255 ExtensionAppShimHandler* handler = GetInstance();
256 Profile* profile = Profile::FromBrowserContext(app_window->browser_context());
257 const std::string& app_id = app_window->extension_id();
258 Host* host = handler->FindHost(profile, app_id);
259 if (host) {
260 handler->OnShimFocus(host,
261 APP_SHIM_FOCUS_NORMAL,
262 std::vector<base::FilePath>());
263 } else {
264 FocusWindows(
265 apps::AppWindowRegistry::Get(profile)->GetAppWindowsForApp(app_id));
269 // static
270 bool ExtensionAppShimHandler::RequestUserAttentionForWindow(
271 AppWindow* app_window) {
272 ExtensionAppShimHandler* handler = GetInstance();
273 Profile* profile = Profile::FromBrowserContext(app_window->browser_context());
274 Host* host = handler->FindHost(profile, app_window->extension_id());
275 if (host) {
276 // Bring the window to the front without showing it.
277 AppWindowRegistry::Get(profile)->AppWindowActivated(app_window);
278 host->OnAppRequestUserAttention();
279 return true;
280 } else {
281 // Just show the app.
282 SetAppHidden(profile, app_window->extension_id(), false);
283 return false;
287 // static
288 void ExtensionAppShimHandler::OnChromeWillHide() {
289 // Send OnAppHide to all the shims so that they go into the hidden state.
290 // This is necessary so that when the shim is next focused, it will know to
291 // unhide.
292 ExtensionAppShimHandler* handler = GetInstance();
293 for (HostMap::iterator it = handler->hosts_.begin();
294 it != handler->hosts_.end();
295 ++it) {
296 it->second->OnAppHide();
300 void ExtensionAppShimHandler::OnShimLaunch(
301 Host* host,
302 AppShimLaunchType launch_type,
303 const std::vector<base::FilePath>& files) {
304 const std::string& app_id = host->GetAppId();
305 DCHECK(extensions::Extension::IdIsValid(app_id));
307 const base::FilePath& profile_path = host->GetProfilePath();
308 DCHECK(!profile_path.empty());
310 if (!delegate_->ProfileExistsForPath(profile_path)) {
311 // User may have deleted the profile this shim was originally created for.
312 // TODO(jackhou): Add some UI for this case and remove the LOG.
313 LOG(ERROR) << "Requested directory is not a known profile '"
314 << profile_path.value() << "'.";
315 host->OnAppLaunchComplete(APP_SHIM_LAUNCH_PROFILE_NOT_FOUND);
316 return;
319 Profile* profile = delegate_->ProfileForPath(profile_path);
321 if (profile) {
322 OnProfileLoaded(host, launch_type, files, profile);
323 return;
326 // If the profile is not loaded, this must have been a launch by the shim.
327 // Load the profile asynchronously, the host will be registered in
328 // OnProfileLoaded.
329 DCHECK_EQ(APP_SHIM_LAUNCH_NORMAL, launch_type);
330 delegate_->LoadProfileAsync(
331 profile_path,
332 base::Bind(&ExtensionAppShimHandler::OnProfileLoaded,
333 weak_factory_.GetWeakPtr(),
334 host, launch_type, files));
336 // Return now. OnAppLaunchComplete will be called when the app is activated.
339 // static
340 ExtensionAppShimHandler* ExtensionAppShimHandler::GetInstance() {
341 return g_browser_process->platform_part()
342 ->app_shim_host_manager()
343 ->extension_app_shim_handler();
346 void ExtensionAppShimHandler::OnProfileLoaded(
347 Host* host,
348 AppShimLaunchType launch_type,
349 const std::vector<base::FilePath>& files,
350 Profile* profile) {
351 const std::string& app_id = host->GetAppId();
353 // The first host to claim this (profile, app_id) becomes the main host.
354 // For any others, focus or relaunch the app.
355 if (!hosts_.insert(make_pair(make_pair(profile, app_id), host)).second) {
356 OnShimFocus(host,
357 launch_type == APP_SHIM_LAUNCH_NORMAL ?
358 APP_SHIM_FOCUS_REOPEN : APP_SHIM_FOCUS_NORMAL,
359 files);
360 host->OnAppLaunchComplete(APP_SHIM_LAUNCH_DUPLICATE_HOST);
361 return;
364 if (launch_type != APP_SHIM_LAUNCH_NORMAL) {
365 host->OnAppLaunchComplete(APP_SHIM_LAUNCH_SUCCESS);
366 return;
369 // TODO(jeremya): Handle the case that launching the app fails. Probably we
370 // need to watch for 'app successfully launched' or at least 'background page
371 // exists/was created' and time out with failure if we don't see that sign of
372 // life within a certain window.
373 const extensions::Extension* extension =
374 delegate_->GetAppExtension(profile, app_id);
375 if (extension) {
376 delegate_->LaunchApp(profile, extension, files);
377 return;
380 delegate_->EnableExtension(
381 profile, app_id,
382 base::Bind(&ExtensionAppShimHandler::OnExtensionEnabled,
383 weak_factory_.GetWeakPtr(),
384 host->GetProfilePath(), app_id, files));
387 void ExtensionAppShimHandler::OnExtensionEnabled(
388 const base::FilePath& profile_path,
389 const std::string& app_id,
390 const std::vector<base::FilePath>& files) {
391 Profile* profile = delegate_->ProfileForPath(profile_path);
392 if (!profile)
393 return;
395 const extensions::Extension* extension =
396 delegate_->GetAppExtension(profile, app_id);
397 if (!extension || !delegate_->ProfileExistsForPath(profile_path)) {
398 // If !extension, the extension doesn't exist, or was not re-enabled.
399 // If the profile doesn't exist, it may have been deleted during the enable
400 // prompt. In this case, NOTIFICATION_PROFILE_DESTROYED may not be fired
401 // until later, so respond to the host now.
402 Host* host = FindHost(profile, app_id);
403 if (host)
404 host->OnAppLaunchComplete(APP_SHIM_LAUNCH_APP_NOT_FOUND);
405 return;
408 delegate_->LaunchApp(profile, extension, files);
412 void ExtensionAppShimHandler::OnShimClose(Host* host) {
413 // This might be called when shutting down. Don't try to look up the profile
414 // since profile_manager might not be around.
415 for (HostMap::iterator it = hosts_.begin(); it != hosts_.end(); ) {
416 HostMap::iterator current = it++;
417 if (current->second == host)
418 hosts_.erase(current);
422 void ExtensionAppShimHandler::OnShimFocus(
423 Host* host,
424 AppShimFocusType focus_type,
425 const std::vector<base::FilePath>& files) {
426 DCHECK(delegate_->ProfileExistsForPath(host->GetProfilePath()));
427 Profile* profile = delegate_->ProfileForPath(host->GetProfilePath());
429 const AppWindowList windows =
430 delegate_->GetWindows(profile, host->GetAppId());
431 bool windows_focused = FocusWindows(windows);
433 if (focus_type == APP_SHIM_FOCUS_NORMAL ||
434 (focus_type == APP_SHIM_FOCUS_REOPEN && windows_focused)) {
435 return;
438 const extensions::Extension* extension =
439 delegate_->GetAppExtension(profile, host->GetAppId());
440 if (extension) {
441 delegate_->LaunchApp(profile, extension, files);
442 } else {
443 // Extensions may have been uninstalled or disabled since the shim
444 // started.
445 host->OnAppClosed();
449 void ExtensionAppShimHandler::OnShimSetHidden(Host* host, bool hidden) {
450 DCHECK(delegate_->ProfileExistsForPath(host->GetProfilePath()));
451 Profile* profile = delegate_->ProfileForPath(host->GetProfilePath());
453 SetAppHidden(profile, host->GetAppId(), hidden);
456 void ExtensionAppShimHandler::OnShimQuit(Host* host) {
457 DCHECK(delegate_->ProfileExistsForPath(host->GetProfilePath()));
458 Profile* profile = delegate_->ProfileForPath(host->GetProfilePath());
460 const std::string& app_id = host->GetAppId();
461 const AppWindowList windows = delegate_->GetWindows(profile, app_id);
462 for (AppWindowRegistry::const_iterator it = windows.begin();
463 it != windows.end();
464 ++it) {
465 (*it)->GetBaseWindow()->Close();
467 // Once the last window closes, flow will end up in OnAppDeactivated via
468 // AppLifetimeMonitor.
471 void ExtensionAppShimHandler::set_delegate(Delegate* delegate) {
472 delegate_.reset(delegate);
475 void ExtensionAppShimHandler::Observe(
476 int type,
477 const content::NotificationSource& source,
478 const content::NotificationDetails& details) {
479 Profile* profile = content::Source<Profile>(source).ptr();
480 if (profile->IsOffTheRecord())
481 return;
483 switch (type) {
484 case chrome::NOTIFICATION_PROFILE_CREATED: {
485 AppLifetimeMonitorFactory::GetForProfile(profile)->AddObserver(this);
486 break;
488 case chrome::NOTIFICATION_PROFILE_DESTROYED: {
489 AppLifetimeMonitorFactory::GetForProfile(profile)->RemoveObserver(this);
490 // Shut down every shim associated with this profile.
491 for (HostMap::iterator it = hosts_.begin(); it != hosts_.end(); ) {
492 // Increment the iterator first as OnAppClosed may call back to
493 // OnShimClose and invalidate the iterator.
494 HostMap::iterator current = it++;
495 if (profile->IsSameProfile(current->first.first)) {
496 Host* host = current->second;
497 host->OnAppClosed();
500 break;
502 default: {
503 NOTREACHED(); // Unexpected notification.
504 break;
509 void ExtensionAppShimHandler::OnAppStart(Profile* profile,
510 const std::string& app_id) {}
512 void ExtensionAppShimHandler::OnAppActivated(Profile* profile,
513 const std::string& app_id) {
514 const extensions::Extension* extension =
515 delegate_->GetAppExtension(profile, app_id);
516 if (!extension)
517 return;
519 Host* host = FindHost(profile, app_id);
520 if (host) {
521 host->OnAppLaunchComplete(APP_SHIM_LAUNCH_SUCCESS);
522 OnShimFocus(host, APP_SHIM_FOCUS_NORMAL, std::vector<base::FilePath>());
523 return;
526 delegate_->LaunchShim(profile, extension);
529 void ExtensionAppShimHandler::OnAppDeactivated(Profile* profile,
530 const std::string& app_id) {
531 Host* host = FindHost(profile, app_id);
532 if (host)
533 host->OnAppClosed();
535 if (hosts_.empty())
536 delegate_->MaybeTerminate();
539 void ExtensionAppShimHandler::OnAppStop(Profile* profile,
540 const std::string& app_id) {}
542 void ExtensionAppShimHandler::OnChromeTerminating() {}
544 } // namespace apps