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