Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / xwalk / application / browser / application.cc
index 7f11417..29ea3ad 100644 (file)
@@ -6,72 +6,92 @@
 
 #include <string>
 
+#include "base/files/file_enumerator.h"
 #include "base/json/json_reader.h"
+#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_event_manager.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_storage.h"
 #include "xwalk/application/common/application_manifest_constants.h"
 #include "xwalk/application/common/constants.h"
-#include "xwalk/application/common/manifest_handlers/main_document_handler.h"
-#include "xwalk/application/common/event_names.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/xwalk_runner.h"
 
+using content::RenderProcessHost;
+
 namespace xwalk {
 
 namespace keys = application_manifest_keys;
 namespace widget_keys = application_widget_keys;
 
-namespace application {
-
-class FinishEventObserver : public EventObserver {
- public:
-  FinishEventObserver(
-      ApplicationEventManager* event_manager,
-      Application* application)
-      : EventObserver(event_manager),
-        application_(application) {
+namespace {
+const char* kDefaultWidgetEntryPage[] = {
+"index.html",
+"index.htm",
+"index.svg",
+"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;
+      }
+    }
   }
 
-  virtual void Observe(const std::string& app_id,
-                       scoped_refptr<Event> event) OVERRIDE {
-    DCHECK(xwalk::application::kOnJavaScriptEventAck == event->name());
-    std::string ack_event_name;
-    event->args()->GetString(0, &ack_event_name);
-    if (ack_event_name == xwalk::application::kOnSuspend)
-      application_->CloseMainDocument();
-  }
+  return source.empty() ? GURL() : data->GetResourceURL(source);
+}
+
+}  // namespace
 
- private:
-  Application* application_;
-};
+namespace application {
 
 Application::Application(
     scoped_refptr<ApplicationData> data,
     RuntimeContext* runtime_context,
     Observer* observer)
-    : runtime_context_(runtime_context),
-      application_data_(data),
-      main_runtime_(NULL),
+    : data_(data),
+      render_process_host_(NULL),
+      web_contents_(NULL),
+      security_mode_enabled_(false),
+      runtime_context_(runtime_context),
       observer_(observer),
       entry_point_used_(Default),
-      termination_mode_used_(Normal),
+      remote_debugging_enabled_(false),
       weak_factory_(this) {
   DCHECK(runtime_context_);
-  DCHECK(application_data_);
+  DCHECK(data_.get());
   DCHECK(observer_);
 }
 
 Application::~Application() {
-  Terminate(Immediate);
+  Terminate();
+  if (render_process_host_)
+    render_process_host_->RemoveObserver(this);
 }
 
 bool Application::Launch(const LaunchParams& launch_params) {
@@ -81,120 +101,146 @@ bool Application::Launch(const LaunchParams& launch_params) {
     return false;
   }
 
-  GURL url = GetURLForLaunch(launch_params, &entry_point_used_);
+  CHECK(!render_process_host_);
+
+  GURL url = GetStartURL(launch_params, &entry_point_used_);
   if (!url.is_valid())
     return false;
 
-  main_runtime_ = Runtime::Create(runtime_context_, this);
-  main_runtime_->LoadURL(url);
-  if (entry_point_used_ != AppMainKey) {
-    NativeAppWindow::CreateParams params;
-    params.net_wm_pid = launch_params.launcher_pid;
-    main_runtime_->AttachWindow(params);
-  }
+  remote_debugging_enabled_ = launch_params.remote_debugging;
+
+  Runtime* runtime = Runtime::Create(
+      runtime_context_,
+      this, content::SiteInstance::CreateForURL(runtime_context_, url));
+  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;
+  if (data_->GetPackageType() == Package::WGT)
+    params.state = GetWindowShowStateWGT(launch_params);
+  else
+    params.state = GetWindowShowStateXPK(launch_params);
+
+  params.splash_screen_path = GetSplashScreenPath();
+
+  runtime->AttachWindow(params);
 
   return true;
 }
 
-GURL Application::GetURLForLaunch(const LaunchParams& params,
-                                  LaunchEntryPoint* used) {
-  if (params.entry_points & AppMainKey) {
-    GURL url = GetURLFromAppMainKey();
+GURL Application::GetStartURL(const LaunchParams& params,
+    LaunchEntryPoint* used) {
+  if (params.entry_points & StartURLKey) {
+    GURL url = GetAbsoluteURLFromKey(keys::kStartURLKey);
     if (url.is_valid()) {
-      *used = AppMainKey;
+      *used = StartURLKey;
       return url;
     }
   }
 
   if (params.entry_points & LaunchLocalPathKey) {
-    GURL url = GetURLFromLocalPathKey();
+    GURL url = GetAbsoluteURLFromKey(
+        GetLaunchLocalPathKey(data_->GetPackageType()));
+
+    if (!url.is_valid() && data_->GetPackageType() == Package::WGT)
+      url = GetDefaultWidgetEntryPage(data_);
+
     if (url.is_valid()) {
+#if defined(OS_TIZEN)
+      if (data_->IsHostedApp() && !url.SchemeIsHTTPOrHTTPS()) {
+        LOG(ERROR) << "Hosted application should use the url start with"
+                      "http or https as its entry page.";
+        return GURL();
+      }
+#endif
       *used = LaunchLocalPathKey;
       return url;
     }
   }
 
   if (params.entry_points & URLKey) {
-    GURL url = GetURLFromURLKey();
+    LOG(WARNING) << "Deprecated key '" << keys::kDeprecatedURLKey
+        << "' found. Please migrate to using '" << keys::kStartURLKey
+        << "' instead.";
+    GURL url = GetAbsoluteURLFromKey(keys::kDeprecatedURLKey);
     if (url.is_valid()) {
       *used = URLKey;
       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();
 }
 
-GURL Application::GetURLFromAppMainKey() {
-  MainDocumentInfo* main_info = ToMainDocumentInfo(
-    application_data_->GetManifestData(keys::kAppMainKey));
-  if (!main_info)
-    return GURL();
+ui::WindowShowState Application::GetWindowShowStateWGT(
+    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;
+  }
 
-  DCHECK(application_data_->HasMainDocument());
-  return main_info->GetMainURL();
+  return ui::SHOW_STATE_DEFAULT;
 }
 
-GURL Application::GetURLFromLocalPathKey() {
-  const Manifest* manifest = application_data_->GetManifest();
-  std::string entry_page;
-  std::string key(GetLaunchLocalPathKey(
-      application_data_->GetPackageType()));
-
-  if (!manifest->GetString(key, &entry_page)
-      || entry_page.empty())
-    return GURL();
+ui::WindowShowState Application::GetWindowShowStateXPK(
+    const LaunchParams& params) {
+  if (params.force_fullscreen)
+    return ui::SHOW_STATE_FULLSCREEN;
+
+  const Manifest* manifest = data_->GetManifest();
+  std::string display_string;
+  if (manifest->GetString(keys::kDisplay, &display_string)) {
+    // FIXME: ATM only 'fullscreen' and 'standalone' (which is fallback value)
+    // values are supported.
+    if (display_string.find("fullscreen") != std::string::npos)
+      return ui::SHOW_STATE_FULLSCREEN;
+  }
 
-  return application_data_->GetResourceURL(entry_page);
+  return ui::SHOW_STATE_DEFAULT;
 }
 
-GURL Application::GetURLFromURLKey() {
-  const Manifest* manifest = application_data_->GetManifest();
-  std::string url_string;
-  if (!manifest->GetString(keys::kURLKey, &url_string))
+GURL Application::GetAbsoluteURLFromKey(const std::string& key) {
+  const Manifest* manifest = data_->GetManifest();
+  std::string source;
+
+  if (!manifest->GetString(key, &source) || source.empty())
     return GURL();
 
-  return GURL(url_string);
+  std::size_t found = source.find_first_of("://");
+  if (found == std::string::npos)
+    return data_->GetResourceURL(source);
+  return GURL(source);
 }
 
-void Application::Terminate(TerminationMode mode) {
-  termination_mode_used_ = mode;
-  if (IsTerminating()) {
-    LOG(WARNING) << "Attempt to Terminate app: " << id()
-                 << ", which is already in the process of being terminated.";
-    if (mode == Immediate)
-      CloseMainDocument();
-
-    return;
-  }
-
+void Application::Terminate() {
   std::set<Runtime*> to_be_closed(runtimes_);
-  if (HasMainDocument() && to_be_closed.size() > 1) {
-    // The main document runtime is closed separately
-    // (needs some extra logic) in Application::OnRuntimeRemoved.
-    to_be_closed.erase(main_runtime_);
-  }
-
   std::for_each(to_be_closed.begin(), to_be_closed.end(),
                 std::mem_fun(&Runtime::Close));
 }
 
-Runtime* Application::GetMainDocumentRuntime() const {
-  return HasMainDocument() ? main_runtime_ : NULL;
-}
-
 int Application::GetRenderProcessHostID() const {
-  DCHECK(main_runtime_);
-  return main_runtime_->web_contents()->
-          GetRenderProcessHost()->GetID();
-}
-
-bool Application::HasMainDocument() const {
-  return entry_point_used_ == AppMainKey;
+  DCHECK(render_process_host_);
+  return render_process_host_->GetID();
 }
 
 void Application::OnRuntimeAdded(Runtime* runtime) {
   DCHECK(runtime);
+  runtime->set_remote_debugging_enabled(remote_debugging_enabled_);
   runtimes_.insert(runtime);
 }
 
@@ -203,7 +249,7 @@ void Application::OnRuntimeRemoved(Runtime* runtime) {
   runtimes_.erase(runtime);
 
   if (runtimes_.empty()) {
-#if defined(OS_TIZEN)
+#if defined(OS_TIZEN_MOBILE)
     runtime->CloseRootWindow();
 #endif
     base::MessageLoop::current()->PostTask(FROM_HERE,
@@ -211,54 +257,28 @@ void Application::OnRuntimeRemoved(Runtime* runtime) {
                    weak_factory_.GetWeakPtr()));
     return;
   }
-
-  if (runtimes_.size() == 1 && HasMainDocument() &&
-      ContainsKey(runtimes_, main_runtime_)) {
-    ApplicationSystem* system = XWalkRunner::GetInstance()->app_system();
-    ApplicationEventManager* event_manager = system->event_manager();
-
-    // If onSuspend is not registered in main document,
-    // we close the main document immediately.
-    if (!IsOnSuspendHandlerRegistered() ||
-        termination_mode_used_ == Immediate) {
-      CloseMainDocument();
-      return;
-    }
-
-    DCHECK(!finish_observer_);
-    finish_observer_.reset(
-        new FinishEventObserver(event_manager, this));
-    event_manager->AttachObserver(
-        application_data_->ID(), kOnJavaScriptEventAck,
-        finish_observer_.get());
-
-    scoped_ptr<base::ListValue> event_args(new base::ListValue);
-    scoped_refptr<Event> event = Event::CreateEvent(
-        xwalk::application::kOnSuspend, event_args.Pass());
-    event_manager->SendEvent(application_data_->ID(), event);
-  }
 }
 
-void Application::CloseMainDocument() {
-  DCHECK(main_runtime_);
+void Application::RenderProcessExited(RenderProcessHost* host,
+                                      base::ProcessHandle,
+                                      base::TerminationStatus,
+                                      int) {
+  DCHECK(render_process_host_ == host);
+  VLOG(1) << "RenderProcess id: " << host->GetID() << " is gone!";
+  XWalkRunner::GetInstance()->OnRenderProcessHostGone(host);
+}
 
-  finish_observer_.reset();
-  main_runtime_->Close();
-  main_runtime_ = NULL;
+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);
 }
 
-bool Application::IsOnSuspendHandlerRegistered() const {
-  const std::set<std::string>& events = data()->GetEvents();
-  if (events.find(kOnSuspend) == events.end())
-    return false;
-
-  return true;
-}
-
 bool Application::UseExtension(const std::string& extension_name) const {
   // TODO(Bai): Tells whether the application contains the specified extension
   return true;
@@ -320,7 +340,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);
@@ -329,7 +349,7 @@ StoredPermission Application::GetPermission(PermissionType type,
     return iter->second;
   }
   if (type == PERSISTENT_PERMISSION) {
-    return application_data_->GetPermission(permission_name);
+    return data_->GetPermission(permission_name);
   }
   NOTREACHED();
   return UNDEFINED_STORED_PERM;
@@ -343,11 +363,32 @@ bool Application::SetPermission(PermissionType type,
     return true;
   }
   if (type == PERSISTENT_PERMISSION)
-    return application_data_->SetPermission(permission_name, perm);
+    return data_->SetPermission(permission_name, perm);
 
   NOTREACHED();
   return false;
 }
 
+void Application::InitSecurityPolicy() {
+  // CSP policy takes precedence over WARP.
+  if (data_->HasCSPDefined())
+    security_policy_.reset(new SecurityPolicyCSP(this));
+  else if (data_->GetPackageType() == Package::WGT)
+    security_policy_.reset(new SecurityPolicyWARP(this));
+
+  if (security_policy_)
+    security_policy_->Enforce();
+}
+
+bool Application::CanRequestURL(const GURL& url) const {
+  if (security_policy_)
+    return security_policy_->IsAccessAllowed(url);
+  return true;
+}
+
+base::FilePath Application::GetSplashScreenPath() {
+  return base::FilePath();
+}
+
 }  // namespace application
 }  // namespace xwalk