Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / ui / extensions / application_launch.cc
1 // Copyright (c) 2012 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/ui/extensions/application_launch.h"
6
7 #include <string>
8
9 #include "apps/launcher.h"
10 #include "base/command_line.h"
11 #include "base/metrics/field_trial.h"
12 #include "base/metrics/histogram.h"
13 #include "base/strings/utf_string_conversions.h"
14 #include "chrome/browser/app_mode/app_mode_utils.h"
15 #include "chrome/browser/apps/per_app_settings_service.h"
16 #include "chrome/browser/apps/per_app_settings_service_factory.h"
17 #include "chrome/browser/extensions/extension_service.h"
18 #include "chrome/browser/extensions/launch_util.h"
19 #include "chrome/browser/extensions/tab_helper.h"
20 #include "chrome/browser/profiles/profile.h"
21 #include "chrome/browser/signin/signin_manager.h"
22 #include "chrome/browser/signin/signin_manager_factory.h"
23 #include "chrome/browser/ui/app_list/app_list_service.h"
24 #include "chrome/browser/ui/browser.h"
25 #include "chrome/browser/ui/browser_commands.h"
26 #include "chrome/browser/ui/browser_finder.h"
27 #include "chrome/browser/ui/browser_tabstrip.h"
28 #include "chrome/browser/ui/browser_window.h"
29 #include "chrome/browser/ui/extensions/extension_enable_flow.h"
30 #include "chrome/browser/ui/extensions/extension_enable_flow_delegate.h"
31 #include "chrome/browser/ui/tabs/tab_strip_model.h"
32 #include "chrome/browser/web_applications/web_app.h"
33 #include "chrome/common/chrome_switches.h"
34 #include "chrome/common/extensions/extension_constants.h"
35 #include "chrome/common/extensions/manifest_handlers/app_launch_info.h"
36 #include "chrome/common/extensions/manifest_url_handler.h"
37 #include "chrome/common/url_constants.h"
38 #include "content/public/browser/render_view_host.h"
39 #include "content/public/browser/web_contents.h"
40 #include "content/public/browser/web_contents_view.h"
41 #include "content/public/common/renderer_preferences.h"
42 #include "extensions/browser/extension_prefs.h"
43 #include "extensions/browser/extension_registry.h"
44 #include "extensions/browser/extension_system.h"
45 #include "extensions/common/constants.h"
46 #include "extensions/common/extension.h"
47 #include "grit/generated_resources.h"
48 #include "ui/base/l10n/l10n_util.h"
49 #include "ui/base/window_open_disposition.h"
50 #include "ui/gfx/rect.h"
51
52 #if defined(OS_MACOSX)
53 #include "chrome/browser/ui/browser_commands_mac.h"
54 #endif
55
56 #if defined(OS_WIN)
57 #include "win8/util/win8_util.h"
58 #endif
59
60 using content::WebContents;
61 using extensions::Extension;
62 using extensions::ExtensionPrefs;
63 using extensions::ExtensionRegistry;
64
65 namespace {
66
67 // Attempts to launch a packaged app, prompting the user to enable it if
68 // necessary. If a prompt is required it will be shown inside the AppList.
69 // This class manages its own lifetime.
70 class EnableViaAppListFlow : public ExtensionEnableFlowDelegate {
71  public:
72   EnableViaAppListFlow(ExtensionService* service,
73                        Profile* profile,
74                        chrome::HostDesktopType desktop_type,
75                        const std::string& extension_id,
76                        const base::Closure& callback)
77       : service_(service),
78         profile_(profile),
79         desktop_type_(desktop_type),
80         extension_id_(extension_id),
81         callback_(callback) {
82   }
83
84   virtual ~EnableViaAppListFlow() {
85   }
86
87   void Run() {
88     DCHECK(!service_->IsExtensionEnabled(extension_id_));
89     flow_.reset(new ExtensionEnableFlow(profile_, extension_id_, this));
90     flow_->StartForCurrentlyNonexistentWindow(
91         base::Bind(&EnableViaAppListFlow::ShowAppList, base::Unretained(this)));
92   }
93
94  private:
95   gfx::NativeWindow ShowAppList() {
96     AppListService* app_list_service = AppListService::Get(desktop_type_);
97     app_list_service->Show();
98     return app_list_service->GetAppListWindow();
99   }
100
101   // ExtensionEnableFlowDelegate overrides.
102   virtual void ExtensionEnableFlowFinished() OVERRIDE {
103     const Extension* extension =
104         service_->GetExtensionById(extension_id_, false);
105     if (!extension)
106       return;
107     callback_.Run();
108     delete this;
109   }
110
111   virtual void ExtensionEnableFlowAborted(bool user_initiated) OVERRIDE {
112     delete this;
113   }
114
115   ExtensionService* service_;
116   Profile* profile_;
117   chrome::HostDesktopType desktop_type_;
118   std::string extension_id_;
119   base::Closure callback_;
120   scoped_ptr<ExtensionEnableFlow> flow_;
121
122   DISALLOW_COPY_AND_ASSIGN(EnableViaAppListFlow);
123 };
124
125 const Extension* GetExtension(const AppLaunchParams& params) {
126   if (params.extension_id.empty())
127     return NULL;
128   ExtensionRegistry* registry = ExtensionRegistry::Get(params.profile);
129   return registry->GetExtensionById(params.extension_id,
130                                     ExtensionRegistry::ENABLED |
131                                         ExtensionRegistry::DISABLED |
132                                         ExtensionRegistry::TERMINATED);
133 }
134
135 // Get the launch URL for a given extension, with optional override/fallback.
136 // |override_url|, if non-empty, will be preferred over the extension's
137 // launch url.
138 GURL UrlForExtension(const Extension* extension,
139                      const GURL& override_url) {
140   if (!extension)
141     return override_url;
142
143   GURL url;
144   if (!override_url.is_empty()) {
145     DCHECK(extension->web_extent().MatchesURL(override_url) ||
146            override_url.GetOrigin() == extension->url());
147     url = override_url;
148   } else {
149     url = extensions::AppLaunchInfo::GetFullLaunchURL(extension);
150   }
151
152   // For extensions lacking launch urls, determine a reasonable fallback.
153   if (!url.is_valid()) {
154     url = extensions::ManifestURL::GetOptionsPage(extension);
155     if (!url.is_valid())
156       url = GURL(chrome::kChromeUIExtensionsURL);
157   }
158
159   return url;
160 }
161
162 ui::WindowShowState DetermineWindowShowState(
163     Profile* profile,
164     extensions::LaunchContainer container,
165     const Extension* extension) {
166   if (!extension || container != extensions::LAUNCH_CONTAINER_WINDOW)
167     return ui::SHOW_STATE_DEFAULT;
168
169   if (chrome::IsRunningInForcedAppMode())
170     return ui::SHOW_STATE_FULLSCREEN;
171
172 #if defined(USE_ASH)
173   // In ash, LAUNCH_TYPE_FULLSCREEN launches in a maximized app window and
174   // LAUNCH_TYPE_WINDOW launches in a normal app window.
175   ExtensionService* service =
176       extensions::ExtensionSystem::Get(profile)->extension_service();
177   extensions::LaunchType launch_type = extensions::GetLaunchType(
178       service->extension_prefs(), extension);
179   if (launch_type == extensions::LAUNCH_TYPE_FULLSCREEN)
180     return ui::SHOW_STATE_MAXIMIZED;
181   else if (launch_type == extensions::LAUNCH_TYPE_WINDOW)
182     return ui::SHOW_STATE_NORMAL;
183 #endif
184
185   return ui::SHOW_STATE_DEFAULT;
186 }
187
188 WebContents* OpenApplicationWindow(const AppLaunchParams& params) {
189   Profile* const profile = params.profile;
190   const Extension* const extension = GetExtension(params);
191   const GURL url_input = params.override_url;
192
193   DCHECK(!url_input.is_empty() || extension);
194   GURL url = UrlForExtension(extension, url_input);
195   Browser::CreateParams browser_params(
196       Browser::TYPE_POPUP, profile, params.desktop_type);
197
198   browser_params.app_name = extension ?
199       web_app::GenerateApplicationNameFromExtensionId(extension->id()) :
200       web_app::GenerateApplicationNameFromURL(url);
201
202   if (!params.override_bounds.IsEmpty()) {
203     browser_params.initial_bounds = params.override_bounds;
204   } else if (extension) {
205     browser_params.initial_bounds.set_width(
206         extensions::AppLaunchInfo::GetLaunchWidth(extension));
207     browser_params.initial_bounds.set_height(
208         extensions::AppLaunchInfo::GetLaunchHeight(extension));
209   }
210
211   browser_params.initial_show_state = DetermineWindowShowState(profile,
212                                                                params.container,
213                                                                extension);
214
215   Browser* browser = NULL;
216 #if defined(OS_WIN)
217   // On Windows 8's single window Metro mode we don't allow multiple Chrome
218   // windows to be created. We instead attempt to reuse an existing Browser
219   // window.
220   if (win8::IsSingleWindowMetroMode())
221     browser = chrome::FindBrowserWithProfile(profile, params.desktop_type);
222
223 #endif
224   if (!browser)
225     browser = new Browser(browser_params);
226
227   WebContents* web_contents = chrome::AddSelectedTabWithURL(
228       browser, url, content::PAGE_TRANSITION_AUTO_TOPLEVEL);
229   web_contents->GetMutableRendererPrefs()->can_accept_load_drops = false;
230   web_contents->GetRenderViewHost()->SyncRendererPrefs();
231
232   browser->window()->Show();
233
234   // TODO(jcampan): http://crbug.com/8123 we should not need to set the initial
235   //                focus explicitly.
236   web_contents->GetView()->SetInitialFocus();
237   return web_contents;
238 }
239
240 WebContents* OpenApplicationTab(const AppLaunchParams& launch_params) {
241   const Extension* extension = GetExtension(launch_params);
242   CHECK(extension);
243   Profile* const profile = launch_params.profile;
244   WindowOpenDisposition disposition = launch_params.disposition;
245
246   Browser* browser = chrome::FindTabbedBrowser(profile,
247                                                false,
248                                                launch_params.desktop_type);
249   WebContents* contents = NULL;
250   if (!browser) {
251     // No browser for this profile, need to open a new one.
252     browser = new Browser(Browser::CreateParams(Browser::TYPE_TABBED,
253                                                 profile,
254                                                 launch_params.desktop_type));
255     browser->window()->Show();
256     // There's no current tab in this browser window, so add a new one.
257     disposition = NEW_FOREGROUND_TAB;
258   } else {
259     // For existing browser, ensure its window is shown and activated.
260     browser->window()->Show();
261     browser->window()->Activate();
262   }
263
264   // Check the prefs for overridden mode.
265   ExtensionService* extension_service =
266       extensions::ExtensionSystem::Get(profile)->extension_service();
267   DCHECK(extension_service);
268
269   extensions::LaunchType launch_type = extensions::GetLaunchType(
270       extension_service->extension_prefs(), extension);
271   UMA_HISTOGRAM_ENUMERATION("Extensions.AppTabLaunchType", launch_type, 100);
272
273   int add_type = TabStripModel::ADD_ACTIVE;
274   if (launch_type == extensions::LAUNCH_TYPE_PINNED)
275     add_type |= TabStripModel::ADD_PINNED;
276
277   GURL extension_url = UrlForExtension(extension, launch_params.override_url);
278   chrome::NavigateParams params(browser, extension_url,
279                                 content::PAGE_TRANSITION_AUTO_TOPLEVEL);
280   params.tabstrip_add_types = add_type;
281   params.disposition = disposition;
282
283   if (disposition == CURRENT_TAB) {
284     WebContents* existing_tab =
285         browser->tab_strip_model()->GetActiveWebContents();
286     TabStripModel* model = browser->tab_strip_model();
287     int tab_index = model->GetIndexOfWebContents(existing_tab);
288
289     existing_tab->OpenURL(content::OpenURLParams(
290           extension_url,
291           content::Referrer(existing_tab->GetURL(),
292                             blink::WebReferrerPolicyDefault),
293           disposition, content::PAGE_TRANSITION_LINK, false));
294     // Reset existing_tab as OpenURL() may have clobbered it.
295     existing_tab = browser->tab_strip_model()->GetActiveWebContents();
296     if (params.tabstrip_add_types & TabStripModel::ADD_PINNED) {
297       model->SetTabPinned(tab_index, true);
298       // Pinning may have moved the tab.
299       tab_index = model->GetIndexOfWebContents(existing_tab);
300     }
301     if (params.tabstrip_add_types & TabStripModel::ADD_ACTIVE)
302       model->ActivateTabAt(tab_index, true);
303
304     contents = existing_tab;
305   } else {
306     chrome::Navigate(&params);
307     contents = params.target_contents;
308   }
309
310   // On Chrome OS the host desktop type for a browser window is always set to
311   // HOST_DESKTOP_TYPE_ASH. On Windows 8 it is only the case for Chrome ASH
312   // in metro mode.
313   if (browser->host_desktop_type() == chrome::HOST_DESKTOP_TYPE_ASH) {
314     // In ash, LAUNCH_FULLSCREEN launches in the OpenApplicationWindow function
315     // i.e. it should not reach here.
316     DCHECK(launch_type != extensions::LAUNCH_TYPE_FULLSCREEN);
317   } else {
318     // TODO(skerner):  If we are already in full screen mode, and the user
319     // set the app to open as a regular or pinned tab, what should happen?
320     // Today we open the tab, but stay in full screen mode.  Should we leave
321     // full screen mode in this case?
322     if (launch_type == extensions::LAUNCH_TYPE_FULLSCREEN &&
323         !browser->window()->IsFullscreen()) {
324 #if defined(OS_MACOSX)
325       chrome::ToggleFullscreenWithChromeOrFallback(browser);
326 #else
327       chrome::ToggleFullscreenMode(browser);
328 #endif
329     }
330   }
331   return contents;
332 }
333
334 WebContents* OpenEnabledApplication(const AppLaunchParams& params) {
335   const Extension* extension = GetExtension(params);
336   if (!extension)
337     return NULL;
338   Profile* profile = params.profile;
339
340   WebContents* tab = NULL;
341   ExtensionPrefs* prefs = extensions::ExtensionSystem::Get(profile)->
342       extension_service()->extension_prefs();
343   prefs->SetActiveBit(extension->id(), true);
344
345   UMA_HISTOGRAM_ENUMERATION(
346       "Extensions.AppLaunchContainer", params.container, 100);
347
348   if (extension->is_platform_app()) {
349     // Remember what desktop the launch happened on so that when the app opens a
350     // window we can open them on the right desktop.
351     PerAppSettingsServiceFactory::GetForBrowserContext(profile)->
352         SetDesktopLastLaunchedFrom(extension->id(), params.desktop_type);
353 #if !defined(OS_CHROMEOS)
354     SigninManager* signin_manager =
355         SigninManagerFactory::GetForProfile(profile);
356     if (signin_manager && signin_manager->GetAuthenticatedUsername().empty()) {
357       const char kEnforceSigninToUseAppsFieldTrial[] = "EnforceSigninToUseApps";
358
359       std::string field_trial_value =
360           base::FieldTrialList::FindFullName(kEnforceSigninToUseAppsFieldTrial);
361
362       // Only enforce signin if the field trial is set.
363       if (!field_trial_value.empty()) {
364         GURL gurl(l10n_util::GetStringFUTF8(
365             IDS_APP_LAUNCH_NOT_SIGNED_IN_LINK,
366             base::UTF8ToUTF16(extension->id())));
367         chrome::NavigateParams navigate_params(profile, gurl,
368                                                content::PAGE_TRANSITION_LINK);
369         navigate_params.host_desktop_type = params.desktop_type;
370         chrome::Navigate(&navigate_params);
371         return NULL;
372       }
373     }
374 #endif
375
376     apps::LaunchPlatformAppWithCommandLine(
377         profile, extension, params.command_line, params.current_directory);
378     return NULL;
379   }
380
381   // Record v1 app launch. Platform app launch is recorded when dispatching
382   // the onLaunched event.
383   prefs->SetLastLaunchTime(extension->id(), base::Time::Now());
384
385   switch (params.container) {
386     case extensions::LAUNCH_CONTAINER_NONE: {
387       NOTREACHED();
388       break;
389     }
390     case extensions::LAUNCH_CONTAINER_PANEL:
391     case extensions::LAUNCH_CONTAINER_WINDOW:
392       tab = OpenApplicationWindow(params);
393       break;
394     case extensions::LAUNCH_CONTAINER_TAB: {
395       tab = OpenApplicationTab(params);
396       break;
397     }
398     default:
399       NOTREACHED();
400       break;
401   }
402   return tab;
403 }
404
405 }  // namespace
406
407 AppLaunchParams::AppLaunchParams(Profile* profile,
408                                  const extensions::Extension* extension,
409                                  extensions::LaunchContainer container,
410                                  WindowOpenDisposition disposition)
411     : profile(profile),
412       extension_id(extension ? extension->id() : std::string()),
413       container(container),
414       disposition(disposition),
415       desktop_type(chrome::GetActiveDesktop()),
416       override_url(),
417       override_bounds(),
418       command_line(CommandLine::NO_PROGRAM) {}
419
420 AppLaunchParams::AppLaunchParams(Profile* profile,
421                                  const extensions::Extension* extension,
422                                  WindowOpenDisposition disposition)
423     : profile(profile),
424       extension_id(extension ? extension->id() : std::string()),
425       container(extensions::LAUNCH_CONTAINER_NONE),
426       disposition(disposition),
427       desktop_type(chrome::GetActiveDesktop()),
428       override_url(),
429       override_bounds(),
430       command_line(CommandLine::NO_PROGRAM) {
431   ExtensionService* service =
432       extensions::ExtensionSystem::Get(profile)->extension_service();
433   DCHECK(service);
434
435   // Look up the app preference to find out the right launch container. Default
436   // is to launch as a regular tab.
437   container = extensions::GetLaunchContainer(
438       service->extension_prefs(), extension);
439 }
440
441 AppLaunchParams::AppLaunchParams(Profile* profile,
442                                  const extensions::Extension* extension,
443                                  int event_flags,
444                                  chrome::HostDesktopType desktop_type)
445     : profile(profile),
446       extension_id(extension ? extension->id() : std::string()),
447       container(extensions::LAUNCH_CONTAINER_NONE),
448       disposition(ui::DispositionFromEventFlags(event_flags)),
449       desktop_type(desktop_type),
450       override_url(),
451       override_bounds(),
452       command_line(CommandLine::NO_PROGRAM) {
453   if (disposition == NEW_FOREGROUND_TAB || disposition == NEW_BACKGROUND_TAB) {
454     container = extensions::LAUNCH_CONTAINER_TAB;
455   } else if (disposition == NEW_WINDOW) {
456     container = extensions::LAUNCH_CONTAINER_WINDOW;
457   } else {
458     ExtensionService* service =
459         extensions::ExtensionSystem::Get(profile)->extension_service();
460     DCHECK(service);
461
462     // Look at preference to find the right launch container.  If no preference
463     // is set, launch as a regular tab.
464     container = extensions::GetLaunchContainer(
465         service->extension_prefs(), extension);
466     disposition = NEW_FOREGROUND_TAB;
467   }
468 }
469
470 AppLaunchParams::~AppLaunchParams() {
471 }
472
473 WebContents* OpenApplication(const AppLaunchParams& params) {
474   return OpenEnabledApplication(params);
475 }
476
477 void OpenApplicationWithReenablePrompt(const AppLaunchParams& params) {
478   const Extension* extension = GetExtension(params);
479   if (!extension)
480     return;
481   Profile* profile = params.profile;
482
483   ExtensionService* service =
484       extensions::ExtensionSystem::Get(profile)->extension_service();
485   if (!service->IsExtensionEnabled(extension->id())) {
486     (new EnableViaAppListFlow(
487         service, profile, params.desktop_type, extension->id(),
488         base::Bind(base::IgnoreResult(OpenEnabledApplication), params)))->Run();
489     return;
490   }
491
492   OpenEnabledApplication(params);
493 }
494
495 WebContents* OpenAppShortcutWindow(Profile* profile,
496                                    const GURL& url,
497                                    const gfx::Rect& override_bounds) {
498   AppLaunchParams launch_params(
499       profile,
500       NULL,  // this is a URL app.  No extension.
501       extensions::LAUNCH_CONTAINER_WINDOW,
502       NEW_WINDOW);
503   launch_params.override_url = url;
504   launch_params.override_bounds = override_bounds;
505
506   WebContents* tab = OpenApplicationWindow(launch_params);
507
508   if (!tab)
509     return NULL;
510
511   // Set UPDATE_SHORTCUT as the pending web app action. This action is picked
512   // up in LoadingStateChanged to schedule a GetApplicationInfo. And when
513   // the web app info is available, extensions::TabHelper notifies Browser via
514   // OnDidGetApplicationInfo, which calls
515   // web_app::UpdateShortcutForTabContents when it sees UPDATE_SHORTCUT as
516   // pending web app action.
517   extensions::TabHelper::FromWebContents(tab)->set_pending_web_app_action(
518       extensions::TabHelper::UPDATE_SHORTCUT);
519
520   return tab;
521 }