Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / apps / app_shim / extension_app_shim_handler_mac.cc
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.
4
5 #include "chrome/browser/apps/app_shim/extension_app_shim_handler_mac.h"
6
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"
33
34 using extensions::AppWindow;
35 using extensions::AppWindowRegistry;
36 using extensions::ExtensionRegistry;
37
38 namespace {
39
40 typedef AppWindowRegistry::AppWindowList AppWindowList;
41
42 void ProfileLoadedCallback(base::Callback<void(Profile*)> callback,
43                            Profile* profile,
44                            Profile::CreateStatus status) {
45   if (status == Profile::CREATE_STATUS_INITIALIZED) {
46     callback.Run(profile);
47     return;
48   }
49
50   // This should never get an error since it only loads existing profiles.
51   DCHECK_EQ(Profile::CREATE_STATUS_CREATED, status);
52 }
53
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();
58        it != windows.rend();
59        ++it) {
60     if (hidden)
61       (*it)->GetBaseWindow()->HideWithApp();
62     else
63       (*it)->GetBaseWindow()->ShowWithApp();
64   }
65 }
66
67 bool FocusWindows(const AppWindowList& windows) {
68   if (windows.empty())
69     return false;
70
71   std::set<gfx::NativeWindow> native_windows;
72   for (AppWindowList::const_iterator it = windows.begin(); it != windows.end();
73        ++it) {
74     native_windows.insert((*it)->GetNativeWindow());
75   }
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);
80   return true;
81 }
82
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 {
87  public:
88   EnableViaPrompt(Profile* profile,
89                   const std::string& extension_id,
90                   const base::Callback<void()>& callback)
91       : profile_(profile),
92         extension_id_(extension_id),
93         callback_(callback) {
94   }
95
96   ~EnableViaPrompt() override {}
97
98   void Run() {
99     flow_.reset(new ExtensionEnableFlow(profile_, extension_id_, this));
100     flow_->StartForCurrentlyNonexistentWindow(
101         base::Callback<gfx::NativeWindow(void)>());
102   }
103
104  private:
105   // ExtensionEnableFlowDelegate overrides.
106   void ExtensionEnableFlowFinished() override {
107     callback_.Run();
108     delete this;
109   }
110
111   void ExtensionEnableFlowAborted(bool user_initiated) override {
112     callback_.Run();
113     delete this;
114   }
115
116   Profile* profile_;
117   std::string extension_id_;
118   base::Callback<void()> callback_;
119   scoped_ptr<ExtensionEnableFlow> flow_;
120
121   DISALLOW_COPY_AND_ASSIGN(EnableViaPrompt);
122 };
123
124 }  // namespace
125
126 namespace apps {
127
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;
136 }
137
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);
143
144   // Use IsValidProfile to check if the profile has been created.
145   return profile && profile_manager->IsValidProfile(profile) ? profile : NULL;
146 }
147
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(
154       full_path,
155       base::Bind(&ProfileLoadedCallback, callback),
156       base::string16(), base::string16(), std::string());
157 }
158
159 AppWindowList ExtensionAppShimHandler::Delegate::GetWindows(
160     Profile* profile,
161     const std::string& extension_id) {
162   return AppWindowRegistry::Get(profile)->GetAppWindowsForApp(extension_id);
163 }
164
165 const extensions::Extension*
166 ExtensionAppShimHandler::Delegate::GetAppExtension(
167     Profile* profile,
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;
173 }
174
175 void ExtensionAppShimHandler::Delegate::EnableExtension(
176     Profile* profile,
177     const std::string& extension_id,
178     const base::Callback<void()>& callback) {
179   (new EnableViaPrompt(profile, extension_id, callback))->Run();
180 }
181
182 void ExtensionAppShimHandler::Delegate::LaunchApp(
183     Profile* profile,
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());
188   if (files.empty()) {
189     apps::LaunchPlatformApp(
190         profile, extension, extensions::SOURCE_COMMAND_LINE);
191   } else {
192     for (std::vector<base::FilePath>::const_iterator it = files.begin();
193          it != files.end(); ++it) {
194       apps::LaunchPlatformAppWithPath(profile, extension, *it);
195     }
196   }
197 }
198
199 void ExtensionAppShimHandler::Delegate::LaunchShim(
200     Profile* profile,
201     const extensions::Extension* extension) {
202   web_app::MaybeLaunchShortcut(
203       web_app::ShortcutInfoForExtensionAndProfile(extension, profile));
204 }
205
206 void ExtensionAppShimHandler::Delegate::MaybeTerminate() {
207   AppShimHandler::MaybeTerminate();
208 }
209
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());
221 }
222
223 ExtensionAppShimHandler::~ExtensionAppShimHandler() {}
224
225 AppShimHandler::Host* ExtensionAppShimHandler::FindHost(
226     Profile* profile,
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;
230 }
231
232 // static
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());
238   if (host) {
239     handler->OnShimQuit(host);
240   } else {
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());
245   }
246 }
247
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());
252   if (host)
253     host->OnAppHide();
254   else
255     SetAppHidden(profile, app_window->extension_id(), true);
256 }
257
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);
263   if (host) {
264     handler->OnShimFocus(host,
265                          APP_SHIM_FOCUS_NORMAL,
266                          std::vector<base::FilePath>());
267   } else {
268     FocusWindows(AppWindowRegistry::Get(profile)->GetAppWindowsForApp(app_id));
269   }
270 }
271
272 // static
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());
278   if (host) {
279     // Bring the window to the front without showing it.
280     AppWindowRegistry::Get(profile)->AppWindowActivated(app_window);
281     host->OnAppRequestUserAttention(APP_SHIM_ATTENTION_INFORMATIONAL);
282     return true;
283   } else {
284     // Just show the app.
285     SetAppHidden(profile, app_window->extension_id(), false);
286     return false;
287   }
288 }
289
290 // static
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());
297   if (host)
298     host->OnAppRequestUserAttention(attention_type);
299 }
300
301 // static
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
305   // unhide.
306   ExtensionAppShimHandler* handler = GetInstance();
307   for (HostMap::iterator it = handler->hosts_.begin();
308        it != handler->hosts_.end();
309        ++it) {
310     it->second->OnAppHide();
311   }
312 }
313
314 void ExtensionAppShimHandler::OnShimLaunch(
315     Host* host,
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));
320
321   const base::FilePath& profile_path = host->GetProfilePath();
322   DCHECK(!profile_path.empty());
323
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);
330     return;
331   }
332
333   Profile* profile = delegate_->ProfileForPath(profile_path);
334
335   if (profile) {
336     OnProfileLoaded(host, launch_type, files, profile);
337     return;
338   }
339
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
342   // OnProfileLoaded.
343   DCHECK_EQ(APP_SHIM_LAUNCH_NORMAL, launch_type);
344   delegate_->LoadProfileAsync(
345       profile_path,
346       base::Bind(&ExtensionAppShimHandler::OnProfileLoaded,
347                  weak_factory_.GetWeakPtr(),
348                  host, launch_type, files));
349
350   // Return now. OnAppLaunchComplete will be called when the app is activated.
351 }
352
353 // static
354 ExtensionAppShimHandler* ExtensionAppShimHandler::GetInstance() {
355   return g_browser_process->platform_part()
356       ->app_shim_host_manager()
357       ->extension_app_shim_handler();
358 }
359
360 void ExtensionAppShimHandler::OnProfileLoaded(
361     Host* host,
362     AppShimLaunchType launch_type,
363     const std::vector<base::FilePath>& files,
364     Profile* profile) {
365   const std::string& app_id = host->GetAppId();
366
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) {
370     OnShimFocus(host,
371                 launch_type == APP_SHIM_LAUNCH_NORMAL ?
372                     APP_SHIM_FOCUS_REOPEN : APP_SHIM_FOCUS_NORMAL,
373                 files);
374     host->OnAppLaunchComplete(APP_SHIM_LAUNCH_DUPLICATE_HOST);
375     return;
376   }
377
378   if (launch_type != APP_SHIM_LAUNCH_NORMAL) {
379     host->OnAppLaunchComplete(APP_SHIM_LAUNCH_SUCCESS);
380     return;
381   }
382
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);
389   if (extension) {
390     delegate_->LaunchApp(profile, extension, files);
391     return;
392   }
393
394   delegate_->EnableExtension(
395       profile, app_id,
396       base::Bind(&ExtensionAppShimHandler::OnExtensionEnabled,
397                  weak_factory_.GetWeakPtr(),
398                  host->GetProfilePath(), app_id, files));
399 }
400
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);
406   if (!profile)
407     return;
408
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);
417     if (host)
418       host->OnAppLaunchComplete(APP_SHIM_LAUNCH_APP_NOT_FOUND);
419     return;
420   }
421
422   delegate_->LaunchApp(profile, extension, files);
423 }
424
425
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);
433   }
434 }
435
436 void ExtensionAppShimHandler::OnShimFocus(
437     Host* host,
438     AppShimFocusType focus_type,
439     const std::vector<base::FilePath>& files) {
440   DCHECK(delegate_->ProfileExistsForPath(host->GetProfilePath()));
441   Profile* profile = delegate_->ProfileForPath(host->GetProfilePath());
442
443   const AppWindowList windows =
444       delegate_->GetWindows(profile, host->GetAppId());
445   bool windows_focused = FocusWindows(windows);
446
447   if (focus_type == APP_SHIM_FOCUS_NORMAL ||
448       (focus_type == APP_SHIM_FOCUS_REOPEN && windows_focused)) {
449     return;
450   }
451
452   const extensions::Extension* extension =
453       delegate_->GetAppExtension(profile, host->GetAppId());
454   if (extension) {
455     delegate_->LaunchApp(profile, extension, files);
456   } else {
457     // Extensions may have been uninstalled or disabled since the shim
458     // started.
459     host->OnAppClosed();
460   }
461 }
462
463 void ExtensionAppShimHandler::OnShimSetHidden(Host* host, bool hidden) {
464   DCHECK(delegate_->ProfileExistsForPath(host->GetProfilePath()));
465   Profile* profile = delegate_->ProfileForPath(host->GetProfilePath());
466
467   SetAppHidden(profile, host->GetAppId(), hidden);
468 }
469
470 void ExtensionAppShimHandler::OnShimQuit(Host* host) {
471   DCHECK(delegate_->ProfileExistsForPath(host->GetProfilePath()));
472   Profile* profile = delegate_->ProfileForPath(host->GetProfilePath());
473
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();
477        it != windows.end();
478        ++it) {
479     (*it)->GetBaseWindow()->Close();
480   }
481   // Once the last window closes, flow will end up in OnAppDeactivated via
482   // AppLifetimeMonitor.
483 }
484
485 void ExtensionAppShimHandler::set_delegate(Delegate* delegate) {
486   delegate_.reset(delegate);
487 }
488
489 void ExtensionAppShimHandler::Observe(
490     int type,
491     const content::NotificationSource& source,
492     const content::NotificationDetails& details) {
493   Profile* profile = content::Source<Profile>(source).ptr();
494   if (profile->IsOffTheRecord())
495     return;
496
497   switch (type) {
498     case chrome::NOTIFICATION_PROFILE_CREATED: {
499       AppLifetimeMonitorFactory::GetForProfile(profile)->AddObserver(this);
500       break;
501     }
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;
511           host->OnAppClosed();
512         }
513       }
514       break;
515     }
516     default: {
517       NOTREACHED();  // Unexpected notification.
518       break;
519     }
520   }
521 }
522
523 void ExtensionAppShimHandler::OnAppStart(Profile* profile,
524                                          const std::string& app_id) {}
525
526 void ExtensionAppShimHandler::OnAppActivated(Profile* profile,
527                                              const std::string& app_id) {
528   const extensions::Extension* extension =
529       delegate_->GetAppExtension(profile, app_id);
530   if (!extension)
531     return;
532
533   Host* host = FindHost(profile, app_id);
534   if (host) {
535     host->OnAppLaunchComplete(APP_SHIM_LAUNCH_SUCCESS);
536     OnShimFocus(host, APP_SHIM_FOCUS_NORMAL, std::vector<base::FilePath>());
537     return;
538   }
539
540   delegate_->LaunchShim(profile, extension);
541 }
542
543 void ExtensionAppShimHandler::OnAppDeactivated(Profile* profile,
544                                                const std::string& app_id) {
545   Host* host = FindHost(profile, app_id);
546   if (host)
547     host->OnAppClosed();
548
549   if (hosts_.empty())
550     delegate_->MaybeTerminate();
551 }
552
553 void ExtensionAppShimHandler::OnAppStop(Profile* profile,
554                                         const std::string& app_id) {}
555
556 void ExtensionAppShimHandler::OnChromeTerminating() {}
557
558 }  // namespace apps