Upstream version 11.39.260.0
[platform/framework/web/crosswalk.git] / src / xwalk / application / browser / application.cc
index f6c4b6f..fe87c27 100644 (file)
 #include "base/macros.h"
 #include "base/message_loop/message_loop.h"
 #include "base/stl_util.h"
+#include "base/strings/string_split.h"
+#include "base/threading/thread_restrictions.h"
 #include "base/values.h"
 #include "content/public/browser/web_contents.h"
 #include "content/public/browser/render_process_host.h"
+#include "content/public/browser/site_instance.h"
 #include "net/base/net_util.h"
-#include "xwalk/application/browser/application_service.h"
-#include "xwalk/application/browser/application_storage.h"
-#include "xwalk/application/browser/application_system.h"
 #include "xwalk/application/common/application_manifest_constants.h"
 #include "xwalk/application/common/constants.h"
 #include "xwalk/application/common/manifest_handlers/warp_handler.h"
 #include "xwalk/runtime/browser/runtime.h"
-#include "xwalk/runtime/browser/runtime_context.h"
+#include "xwalk/runtime/browser/runtime_ui_delegate.h"
+#include "xwalk/runtime/browser/xwalk_browser_context.h"
 #include "xwalk/runtime/browser/xwalk_runner.h"
-#include "xwalk/runtime/common/xwalk_common_messages.h"
+
+#if defined(OS_TIZEN)
+#include "xwalk/application/browser/application_tizen.h"
+#endif
 
 using content::RenderProcessHost;
 
@@ -41,24 +45,56 @@ const char* kDefaultWidgetEntryPage[] = {
 "index.xhtml",
 "index.xht"};
 
+GURL GetDefaultWidgetEntryPage(
+    scoped_refptr<xwalk::application::ApplicationData> data) {
+  base::ThreadRestrictions::SetIOAllowed(true);
+  base::FileEnumerator iter(
+      data->path(), true,
+      base::FileEnumerator::FILES,
+      FILE_PATH_LITERAL("index.*"));
+  size_t priority = arraysize(kDefaultWidgetEntryPage);
+  std::string source;
+
+  for (base::FilePath file = iter.Next(); !file.empty(); file = iter.Next()) {
+    for (size_t i = 0; i < arraysize(kDefaultWidgetEntryPage); ++i) {
+      if (file.BaseName().MaybeAsASCII() == kDefaultWidgetEntryPage[i] &&
+          i < priority) {
+        source = kDefaultWidgetEntryPage[i];
+        priority = i;
+      }
+    }
+  }
+
+  return source.empty() ? GURL() : data->GetResourceURL(source);
+}
+
 }  // namespace
 
 namespace application {
 
+scoped_ptr<Application> Application::Create(
+    scoped_refptr<ApplicationData> data,
+    XWalkBrowserContext* context) {
+#if defined(OS_TIZEN)
+  return make_scoped_ptr<Application>(new ApplicationTizen(data, context));
+#else
+  return make_scoped_ptr(new Application(data, context));
+#endif
+}
+
 Application::Application(
     scoped_refptr<ApplicationData> data,
-    RuntimeContext* runtime_context,
-    Observer* observer)
+    XWalkBrowserContext* browser_context)
     : data_(data),
       render_process_host_(NULL),
+      web_contents_(NULL),
       security_mode_enabled_(false),
-      runtime_context_(runtime_context),
-      observer_(observer),
-      entry_point_used_(Default),
+      browser_context_(browser_context),
+      observer_(NULL),
+      remote_debugging_enabled_(false),
       weak_factory_(this) {
-  DCHECK(runtime_context_);
-  DCHECK(data_);
-  DCHECK(observer_);
+  DCHECK(browser_context_);
+  DCHECK(data_.get());
 }
 
 Application::~Application() {
@@ -67,65 +103,90 @@ Application::~Application() {
     render_process_host_->RemoveObserver(this);
 }
 
-bool Application::Launch(const LaunchParams& launch_params) {
-  if (!runtimes_.empty()) {
-    LOG(ERROR) << "Attempt to launch app: " << id()
-               << " that was already launched.";
-    return false;
+template<>
+GURL Application::GetStartURL<Manifest::TYPE_WIDGET>() {
+#if defined(OS_TIZEN)
+  if (data_->IsHostedApp()) {
+    std::string source;
+    GURL url;
+    if (data_->GetManifest()->GetString(
+        widget_keys::kLaunchLocalPathKey, &source)) {
+      url = GURL(source);
+    }
+
+    if (url.is_valid() && url.SchemeIsHTTPOrHTTPS())
+      return url;
   }
+#endif
 
-  CHECK(!render_process_host_);
+  GURL url = GetAbsoluteURLFromKey(widget_keys::kLaunchLocalPathKey);
+  if (url.is_valid())
+    return url;
 
-  GURL url = GetStartURL(launch_params, &entry_point_used_);
-  if (!url.is_valid())
-    return false;
+  LOG(WARNING) << "Failed to find start URL from the 'config.xml'"
+               << "trying to find default entry page.";
+  url = GetDefaultWidgetEntryPage(data_);
+  if (url.is_valid())
+    return url;
 
-  Runtime* runtime = Runtime::Create(runtime_context_, this);
-  render_process_host_ = runtime->GetRenderProcessHost();
-  render_process_host_->AddObserver(this);
-  InitSecurityPolicy();
-  runtime->LoadURL(url);
-
-  NativeAppWindow::CreateParams params;
-  params.net_wm_pid = launch_params.launcher_pid;
-  params.state = GetWindowShowState(launch_params);
-  runtime->AttachWindow(params);
-
-  return true;
+  LOG(WARNING) << "Failed to find a valid start URL in the manifest.";
+  return GURL();
 }
 
-GURL Application::GetStartURL(const LaunchParams& params,
-                                  LaunchEntryPoint* used) {
-  if (params.entry_points & StartURLKey) {
-    GURL url = GetURLFromRelativePathKey(keys::kStartURLKey);
-    if (url.is_valid()) {
-      *used = StartURLKey;
-      return url;
-    }
+template<>
+GURL Application::GetStartURL<Manifest::TYPE_MANIFEST>() {
+  if (data_->IsHostedApp()) {
+    std::string source;
+    // Not trying to get a relative path for the "fake" application.
+    if (data_->GetManifest()->GetString(keys::kStartURLKey, &source))
+      return GURL(source);
+    return GURL();
   }
 
-  if (params.entry_points & LaunchLocalPathKey) {
-    GURL url = GetURLFromRelativePathKey(
-        GetLaunchLocalPathKey(data_->GetPackageType()));
-    if (url.is_valid()) {
-      *used = LaunchLocalPathKey;
-      return url;
-    }
-  }
+  GURL url = GetAbsoluteURLFromKey(keys::kStartURLKey);
+  if (url.is_valid())
+    return url;
 
-  if (params.entry_points & URLKey) {
-    GURL url = GetURLFromURLKey();
-    if (url.is_valid()) {
-      *used = URLKey;
-      return url;
-    }
+  url = GetAbsoluteURLFromKey(keys::kLaunchLocalPathKey);
+  if (url.is_valid())
+    return url;
+
+  url = GetAbsoluteURLFromKey(keys::kDeprecatedURLKey);
+  if (url.is_valid()) {
+    LOG(WARNING) << "Deprecated key '" << keys::kDeprecatedURLKey
+        << "' found. Please migrate to using '" << keys::kStartURLKey
+        << "' instead.";
+    return url;
   }
 
-  LOG(WARNING) << "Failed to find a valid launch URL for the app.";
+  LOG(WARNING) << "Failed to find a valid start URL in the manifest.";
   return GURL();
 }
 
-ui::WindowShowState Application::GetWindowShowState(
+
+template<>
+ui::WindowShowState Application::GetWindowShowState<Manifest::TYPE_WIDGET>(
+    const LaunchParams& params) {
+  if (params.force_fullscreen)
+    return ui::SHOW_STATE_FULLSCREEN;
+
+  const Manifest* manifest = data_->GetManifest();
+  std::string view_modes_string;
+  if (manifest->GetString(widget_keys::kViewModesKey, &view_modes_string)) {
+    // FIXME: ATM only 'fullscreen' and 'windowed' values are supported.
+    // If the first user prefererence is 'fullscreen', set window show state
+    // FULLSCREEN, otherwise set the default window show state.
+    std::vector<std::string> modes;
+    base::SplitString(view_modes_string, ' ', &modes);
+    if (!modes.empty() && modes[0] == "fullscreen")
+      return ui::SHOW_STATE_FULLSCREEN;
+  }
+
+  return ui::SHOW_STATE_DEFAULT;
+}
+
+template<>
+ui::WindowShowState Application::GetWindowShowState<Manifest::TYPE_MANIFEST>(
     const LaunchParams& params) {
   if (params.force_fullscreen)
     return ui::SHOW_STATE_FULLSCREEN;
@@ -142,49 +203,63 @@ ui::WindowShowState Application::GetWindowShowState(
   return ui::SHOW_STATE_DEFAULT;
 }
 
-GURL Application::GetURLFromURLKey() {
-  const Manifest* manifest = data_->GetManifest();
-  std::string url_string;
-  if (!manifest->GetString(keys::kURLKey, &url_string))
-    return GURL();
+bool Application::Launch(const LaunchParams& launch_params) {
+  if (!runtimes_.empty()) {
+    LOG(ERROR) << "Attempt to launch app with id " << id()
+               << ", but it is already running.";
+    return false;
+  }
 
-  return GURL(url_string);
+  CHECK(!render_process_host_);
+  bool is_wgt = data_->manifest_type() == Manifest::TYPE_WIDGET;
+
+  GURL url = is_wgt ? GetStartURL<Manifest::TYPE_WIDGET>() :
+                      GetStartURL<Manifest::TYPE_MANIFEST>();
+  if (!url.is_valid())
+    return false;
+
+  remote_debugging_enabled_ = launch_params.remote_debugging;
+  auto site = content::SiteInstance::CreateForURL(browser_context_, url);
+  Runtime* runtime = Runtime::Create(browser_context_, site);
+  runtime->set_observer(this);
+  runtime->set_remote_debugging_enabled(remote_debugging_enabled_);
+  runtimes_.push_back(runtime);
+  render_process_host_ = runtime->GetRenderProcessHost();
+  render_process_host_->AddObserver(this);
+  web_contents_ = runtime->web_contents();
+  InitSecurityPolicy();
+  runtime->LoadURL(url);
+
+  NativeAppWindow::CreateParams params;
+  params.net_wm_pid = launch_params.launcher_pid;
+  params.state = is_wgt ?
+      GetWindowShowState<Manifest::TYPE_WIDGET>(launch_params) :
+      GetWindowShowState<Manifest::TYPE_MANIFEST>(launch_params);
+
+  window_show_params_ = params;
+  // Only the first runtime can have a launch screen.
+  params.splash_screen_path = GetSplashScreenPath();
+  runtime->set_ui_delegate(DefaultRuntimeUIDelegate::Create(runtime, params));
+  // We call "Show" after RP is initialized to reduce
+  // the application start up time.
+
+  return true;
 }
 
-GURL Application::GetURLFromRelativePathKey(const std::string& key) {
+GURL Application::GetAbsoluteURLFromKey(const std::string& key) {
   const Manifest* manifest = data_->GetManifest();
-  std::string entry_page;
-  if (!manifest->GetString(key, &entry_page)
-      || entry_page.empty()) {
-    if (data_->GetPackageType() == Manifest::TYPE_XPK)
-      return GURL();
-
-    base::FileEnumerator iter(data_->Path(), true,
-                              base::FileEnumerator::FILES,
-                              FILE_PATH_LITERAL("index.*"));
-    int priority = arraysize(kDefaultWidgetEntryPage);
-
-    for (base::FilePath file = iter.Next(); !file.empty(); file = iter.Next()) {
-      for (int i = 0; i < arraysize(kDefaultWidgetEntryPage); ++i) {
-        if (file.BaseName().MaybeAsASCII() == kDefaultWidgetEntryPage[i] &&
-            i < priority) {
-          entry_page = kDefaultWidgetEntryPage[i];
-          priority = i;
-        }
-      }
-    }
+  std::string source;
 
-    if (entry_page.empty())
-      return GURL();
-  }
+  if (!manifest->GetString(key, &source) || source.empty())
+    return GURL();
 
-  return data_->GetResourceURL(entry_page);
+  return data_->GetResourceURL(source);
 }
 
 void Application::Terminate() {
-  std::set<Runtime*> to_be_closed(runtimes_);
-  std::for_each(to_be_closed.begin(), to_be_closed.end(),
-                std::mem_fun(&Runtime::Close));
+  std::vector<Runtime*> to_be_closed(runtimes_.get());
+  for (Runtime* runtime : to_be_closed)
+    runtime->Close();
 }
 
 int Application::GetRenderProcessHostID() const {
@@ -192,24 +267,25 @@ int Application::GetRenderProcessHostID() const {
   return render_process_host_->GetID();
 }
 
-void Application::OnRuntimeAdded(Runtime* runtime) {
-  DCHECK(runtime);
-  runtimes_.insert(runtime);
+void Application::OnNewRuntimeAdded(Runtime* runtime) {
+  runtime->set_remote_debugging_enabled(remote_debugging_enabled_);
+  runtime->set_observer(this);
+  runtime->set_ui_delegate(
+      DefaultRuntimeUIDelegate::Create(runtime, window_show_params_));
+  runtime->Show();
+  runtimes_.push_back(runtime);
 }
 
-void Application::OnRuntimeRemoved(Runtime* runtime) {
-  DCHECK(runtime);
-  runtimes_.erase(runtime);
+void Application::OnRuntimeClosed(Runtime* runtime) {
+  auto found = std::find(runtimes_.begin(), runtimes_.end(), runtime);
+  CHECK(found != runtimes_.end());
+  LOG(INFO) << "Application::OnRuntimeClosed " << runtime;
+  runtimes_.erase(found);
 
-  if (runtimes_.empty()) {
-#if defined(OS_TIZEN_MOBILE)
-    runtime->CloseRootWindow();
-#endif
+  if (runtimes_.empty())
     base::MessageLoop::current()->PostTask(FROM_HERE,
         base::Bind(&Application::NotifyTermination,
                    weak_factory_.GetWeakPtr()));
-    return;
-  }
 }
 
 void Application::RenderProcessExited(RenderProcessHost* host,
@@ -224,11 +300,18 @@ void Application::RenderProcessExited(RenderProcessHost* host,
 void Application::RenderProcessHostDestroyed(RenderProcessHost* host) {
   DCHECK(render_process_host_ == host);
   render_process_host_ = NULL;
+  web_contents_ = NULL;
 }
 
 void Application::NotifyTermination() {
   CHECK(!render_process_host_);
-  observer_->OnApplicationTerminated(this);
+  if (observer_)
+    observer_->OnApplicationTerminated(this);
+}
+
+void Application::RenderChannelCreated() {
+  CHECK(!runtimes_.empty());
+  runtimes_.front()->Show();
 }
 
 bool Application::UseExtension(const std::string& extension_name) const {
@@ -292,7 +375,7 @@ std::string Application::GetRegisteredPermissionName(
 }
 
 StoredPermission Application::GetPermission(PermissionType type,
-                               std::string& permission_name) const {
+                               const std::string& permission_name) const {
   if (type == SESSION_PERMISSION) {
     StoredPermissionMap::const_iterator iter =
         permission_map_.find(permission_name);
@@ -322,76 +405,24 @@ bool Application::SetPermission(PermissionType type,
 }
 
 void Application::InitSecurityPolicy() {
-  if (data_->GetPackageType() != Manifest::TYPE_WGT)
-    return;
-
-  const WARPInfo* info = static_cast<WARPInfo*>(
-      data_->GetManifestData(widget_keys::kAccessKey));
-  // FIXME(xinchao): Need to enable WARP mode by default.
-  if (!info)
-    return;
-
-  const base::ListValue* whitelist = info->GetWARP();
-  for (base::ListValue::const_iterator it = whitelist->begin();
-       it != whitelist->end(); ++it) {
-    base::DictionaryValue* value = NULL;
-    (*it)->GetAsDictionary(&value);
-    std::string dest;
-    if (!value || !value->GetString(widget_keys::kAccessOriginKey, &dest) ||
-        dest.empty())
-      continue;
-    if (dest == "*") {
-      security_mode_enabled_ = false;
-      break;
-    }
-
-    GURL dest_url(dest);
-    // The default subdomains attrubute should be "false".
-    std::string subdomains = "false";
-    value->GetString(widget_keys::kAccessSubdomainsKey, &subdomains);
-    AddSecurityPolicy(dest_url, (subdomains == "true"));
-    security_mode_enabled_ = true;
-  }
-  if (security_mode_enabled_) {
-    DCHECK(render_process_host_);
-    render_process_host_->Send(
-        new ViewMsg_EnableSecurityMode(
-            ApplicationData::GetBaseURLFromApplicationId(id()),
-            SecurityPolicy::WARP));
-  }
-}
-
-void Application::AddSecurityPolicy(const GURL& url, bool subdomains) {
-  GURL app_url = data_->URL();
-  DCHECK(render_process_host_);
-  render_process_host_->Send(
-      new ViewMsg_SetAccessWhiteList(
-          app_url, url, subdomains));
-  security_policy_.push_back(new SecurityPolicy(url, subdomains));
+  // CSP policy takes precedence over WARP.
+  if (data_->HasCSPDefined())
+    security_policy_.reset(new ApplicationSecurityPolicyCSP(this));
+  else if (data_->manifest_type() == Manifest::TYPE_WIDGET)
+    security_policy_.reset(new ApplicationSecurityPolicyWARP(this));
+
+  if (security_policy_)
+    security_policy_->Enforce();
 }
 
 bool Application::CanRequestURL(const GURL& url) const {
-  if (!security_mode_enabled_)
-    return true;
-
-  // Only WGT package need to check the url request permission.
-  if (data_->GetPackageType() != Manifest::TYPE_WGT)
-    return true;
-
-  // Always can request itself resources.
-  if (url.SchemeIs(application::kApplicationScheme) &&
-      url.host() == id())
-    return true;
+  if (security_policy_)
+    return security_policy_->IsAccessAllowed(url);
+  return true;
+}
 
-  for (unsigned i = 0; i < security_policy_.size(); ++i) {
-    const GURL& policy = security_policy_[i]->url();
-    bool subdomains = security_policy_[i]->subdomains();
-    bool is_host_matched = subdomains ?
-        url.DomainIs(policy.host().c_str()) : url.host() == policy.host();
-    if (url.scheme() == policy.scheme() && is_host_matched)
-      return true;
-  }
-  return false;
+base::FilePath Application::GetSplashScreenPath() {
+  return base::FilePath();
 }
 
 }  // namespace application