4a580a5e3ae9507177a819d42ff6de95a969be84
[platform/framework/web/crosswalk.git] / src / 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 "apps/app_shim/extension_app_shim_handler_mac.h"
6
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"
32
33 using extensions::ExtensionRegistry;
34
35 namespace {
36
37 typedef apps::ShellWindowRegistry::ShellWindowList ShellWindowList;
38
39 void ProfileLoadedCallback(base::Callback<void(Profile*)> callback,
40                            Profile* profile,
41                            Profile::CreateStatus status) {
42   if (status == Profile::CREATE_STATUS_INITIALIZED) {
43     callback.Run(profile);
44     return;
45   }
46
47   // This should never get an error since it only loads existing profiles.
48   DCHECK_EQ(Profile::CREATE_STATUS_CREATED, status);
49 }
50
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) {
56     if (hidden)
57       (*it)->GetBaseWindow()->HideWithApp();
58     else
59       (*it)->GetBaseWindow()->ShowWithApp();
60   }
61 }
62
63 bool FocusWindows(const ShellWindowList& windows) {
64   if (windows.empty())
65     return false;
66
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());
71   }
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);
76   return true;
77 }
78
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) {
90   }
91
92   virtual ~EnableViaPrompt() {
93   }
94
95   void Run() {
96     flow_.reset(new ExtensionEnableFlow(profile_, extension_id_, this));
97     flow_->StartForCurrentlyNonexistentWindow(
98         base::Callback<gfx::NativeWindow(void)>());
99   }
100
101  private:
102   // ExtensionEnableFlowDelegate overrides.
103   virtual void ExtensionEnableFlowFinished() OVERRIDE {
104     callback_.Run();
105     delete this;
106   }
107
108   virtual void ExtensionEnableFlowAborted(bool user_initiated) OVERRIDE {
109     callback_.Run();
110     delete this;
111   }
112
113   Profile* profile_;
114   std::string extension_id_;
115   base::Callback<void()> callback_;
116   scoped_ptr<ExtensionEnableFlow> flow_;
117
118   DISALLOW_COPY_AND_ASSIGN(EnableViaPrompt);
119 };
120
121 }  // namespace
122
123 namespace apps {
124
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;
133 }
134
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);
140
141   // Use IsValidProfile to check if the profile has been created.
142   return profile && profile_manager->IsValidProfile(profile) ? profile : NULL;
143 }
144
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());
154 }
155
156 ShellWindowList ExtensionAppShimHandler::Delegate::GetWindows(
157     Profile* profile,
158     const std::string& extension_id) {
159   return ShellWindowRegistry::Get(profile)->GetShellWindowsForApp(extension_id);
160 }
161
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;
170 }
171
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();
177 }
178
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);
191     }
192   }
193 }
194
195 void ExtensionAppShimHandler::Delegate::LaunchShim(
196     Profile* profile,
197     const extensions::Extension* extension) {
198   web_app::MaybeLaunchShortcut(
199       web_app::ShortcutInfoForExtensionAndProfile(extension, profile));
200 }
201
202 void ExtensionAppShimHandler::Delegate::MaybeTerminate() {
203   AppShimHandler::MaybeTerminate();
204 }
205
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());
217 }
218
219 ExtensionAppShimHandler::~ExtensionAppShimHandler() {}
220
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;
226 }
227
228 // static
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());
235   if (host) {
236     handler->OnShimQuit(host);
237   } else {
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());
241   }
242 }
243
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());
250   if (host)
251     host->OnAppHide();
252   else
253     SetAppHidden(profile, shell_window->extension_id(), true);
254 }
255
256
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);
264   if (host) {
265     handler->OnShimFocus(host,
266                          APP_SHIM_FOCUS_NORMAL,
267                          std::vector<base::FilePath>());
268   } else {
269     FocusWindows(
270         apps::ShellWindowRegistry::Get(profile)->GetShellWindowsForApp(app_id));
271   }
272 }
273
274 // static
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());
282   if (host) {
283     // Bring the window to the front without showing it.
284     ShellWindowRegistry::Get(profile)->ShellWindowActivated(shell_window);
285     host->OnAppRequestUserAttention();
286     return true;
287   } else {
288     // Just show the app.
289     SetAppHidden(profile, shell_window->extension_id(), false);
290     return false;
291   }
292 }
293
294 void ExtensionAppShimHandler::OnShimLaunch(
295     Host* host,
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));
300
301   const base::FilePath& profile_path = host->GetProfilePath();
302   DCHECK(!profile_path.empty());
303
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);
310     return;
311   }
312
313   Profile* profile = delegate_->ProfileForPath(profile_path);
314
315   if (profile) {
316     OnProfileLoaded(host, launch_type, files, profile);
317     return;
318   }
319
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
322   // OnProfileLoaded.
323   DCHECK_EQ(APP_SHIM_LAUNCH_NORMAL, launch_type);
324   delegate_->LoadProfileAsync(
325       profile_path,
326       base::Bind(&ExtensionAppShimHandler::OnProfileLoaded,
327                  weak_factory_.GetWeakPtr(),
328                  host, launch_type, files));
329
330   // Return now. OnAppLaunchComplete will be called when the app is activated.
331 }
332
333 void ExtensionAppShimHandler::OnProfileLoaded(
334     Host* host,
335     AppShimLaunchType launch_type,
336     const std::vector<base::FilePath>& files,
337     Profile* profile) {
338   const std::string& app_id = host->GetAppId();
339
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) {
343     OnShimFocus(host,
344                 launch_type == APP_SHIM_LAUNCH_NORMAL ?
345                     APP_SHIM_FOCUS_REOPEN : APP_SHIM_FOCUS_NORMAL,
346                 files);
347     host->OnAppLaunchComplete(APP_SHIM_LAUNCH_DUPLICATE_HOST);
348     return;
349   }
350
351   if (launch_type != APP_SHIM_LAUNCH_NORMAL) {
352     host->OnAppLaunchComplete(APP_SHIM_LAUNCH_SUCCESS);
353     return;
354   }
355
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);
362   if (extension) {
363     delegate_->LaunchApp(profile, extension, files);
364     return;
365   }
366
367   delegate_->EnableExtension(
368       profile, app_id,
369       base::Bind(&ExtensionAppShimHandler::OnExtensionEnabled,
370                  weak_factory_.GetWeakPtr(),
371                  host->GetProfilePath(), app_id, files));
372 }
373
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);
379   if (!profile)
380     return;
381
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);
390     if (host)
391       host->OnAppLaunchComplete(APP_SHIM_LAUNCH_APP_NOT_FOUND);
392     return;
393   }
394
395   delegate_->LaunchApp(profile, extension, files);
396 }
397
398
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);
406   }
407 }
408
409 void ExtensionAppShimHandler::OnShimFocus(
410     Host* host,
411     AppShimFocusType focus_type,
412     const std::vector<base::FilePath>& files) {
413   DCHECK(delegate_->ProfileExistsForPath(host->GetProfilePath()));
414   Profile* profile = delegate_->ProfileForPath(host->GetProfilePath());
415
416   const ShellWindowList windows =
417       delegate_->GetWindows(profile, host->GetAppId());
418   bool windows_focused = FocusWindows(windows);
419
420   if (focus_type == APP_SHIM_FOCUS_NORMAL ||
421       (focus_type == APP_SHIM_FOCUS_REOPEN && windows_focused)) {
422     return;
423   }
424
425   const extensions::Extension* extension =
426       delegate_->GetAppExtension(profile, host->GetAppId());
427   if (extension) {
428     delegate_->LaunchApp(profile, extension, files);
429   } else {
430     // Extensions may have been uninstalled or disabled since the shim
431     // started.
432     host->OnAppClosed();
433   }
434 }
435
436 void ExtensionAppShimHandler::OnShimSetHidden(Host* host, bool hidden) {
437   DCHECK(delegate_->ProfileExistsForPath(host->GetProfilePath()));
438   Profile* profile = delegate_->ProfileForPath(host->GetProfilePath());
439
440   SetAppHidden(profile, host->GetAppId(), hidden);
441 }
442
443 void ExtensionAppShimHandler::OnShimQuit(Host* host) {
444   DCHECK(delegate_->ProfileExistsForPath(host->GetProfilePath()));
445   Profile* profile = delegate_->ProfileForPath(host->GetProfilePath());
446
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();
453   }
454   // Once the last window closes, flow will end up in OnAppDeactivated via
455   // AppLifetimeMonitor.
456 }
457
458 void ExtensionAppShimHandler::set_delegate(Delegate* delegate) {
459   delegate_.reset(delegate);
460 }
461
462 void ExtensionAppShimHandler::Observe(
463     int type,
464     const content::NotificationSource& source,
465     const content::NotificationDetails& details) {
466   Profile* profile = content::Source<Profile>(source).ptr();
467   if (profile->IsOffTheRecord())
468     return;
469
470   switch (type) {
471     case chrome::NOTIFICATION_PROFILE_CREATED: {
472       AppLifetimeMonitorFactory::GetForProfile(profile)->AddObserver(this);
473       break;
474     }
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;
484           host->OnAppClosed();
485         }
486       }
487       break;
488     }
489     default: {
490       NOTREACHED();  // Unexpected notification.
491       break;
492     }
493   }
494 }
495
496 void ExtensionAppShimHandler::OnAppStart(Profile* profile,
497                                          const std::string& app_id) {}
498
499 void ExtensionAppShimHandler::OnAppActivated(Profile* profile,
500                                              const std::string& app_id) {
501   const extensions::Extension* extension =
502       delegate_->GetAppExtension(profile, app_id);
503   if (!extension)
504     return;
505
506   Host* host = FindHost(profile, app_id);
507   if (host) {
508     host->OnAppLaunchComplete(APP_SHIM_LAUNCH_SUCCESS);
509     OnShimFocus(host, APP_SHIM_FOCUS_NORMAL, std::vector<base::FilePath>());
510     return;
511   }
512
513   delegate_->LaunchShim(profile, extension);
514 }
515
516 void ExtensionAppShimHandler::OnAppDeactivated(Profile* profile,
517                                                const std::string& app_id) {
518   Host* host = FindHost(profile, app_id);
519   if (host)
520     host->OnAppClosed();
521
522   if (hosts_.empty())
523     delegate_->MaybeTerminate();
524 }
525
526 void ExtensionAppShimHandler::OnAppStop(Profile* profile,
527                                         const std::string& app_id) {}
528
529 void ExtensionAppShimHandler::OnChromeTerminating() {}
530
531 }  // namespace apps