1 // Copyright (c) 2013 Intel Corporation. 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.
5 #include "xwalk/application/browser/application.h"
9 #include "base/files/file_enumerator.h"
10 #include "base/json/json_reader.h"
11 #include "base/macros.h"
12 #include "base/message_loop/message_loop.h"
13 #include "base/stl_util.h"
14 #include "base/strings/string_split.h"
15 #include "base/threading/thread_restrictions.h"
16 #include "base/values.h"
17 #include "content/public/browser/web_contents.h"
18 #include "content/public/browser/render_process_host.h"
19 #include "content/public/browser/site_instance.h"
20 #include "net/base/net_util.h"
21 #include "xwalk/application/browser/application_service.h"
22 #include "xwalk/application/browser/application_system.h"
23 #include "xwalk/application/common/application_storage.h"
24 #include "xwalk/application/common/application_manifest_constants.h"
25 #include "xwalk/application/common/constants.h"
26 #include "xwalk/application/common/manifest_handlers/warp_handler.h"
27 #include "xwalk/runtime/browser/runtime.h"
28 #include "xwalk/runtime/browser/runtime_context.h"
29 #include "xwalk/runtime/browser/xwalk_runner.h"
32 #include "xwalk/application/browser/application_tizen.h"
35 using content::RenderProcessHost;
39 namespace keys = application_manifest_keys;
40 namespace widget_keys = application_widget_keys;
43 const char* kDefaultWidgetEntryPage[] = {
50 GURL GetDefaultWidgetEntryPage(
51 scoped_refptr<xwalk::application::ApplicationData> data) {
52 base::ThreadRestrictions::SetIOAllowed(true);
53 base::FileEnumerator iter(
55 base::FileEnumerator::FILES,
56 FILE_PATH_LITERAL("index.*"));
57 size_t priority = arraysize(kDefaultWidgetEntryPage);
60 for (base::FilePath file = iter.Next(); !file.empty(); file = iter.Next()) {
61 for (size_t i = 0; i < arraysize(kDefaultWidgetEntryPage); ++i) {
62 if (file.BaseName().MaybeAsASCII() == kDefaultWidgetEntryPage[i] &&
64 source = kDefaultWidgetEntryPage[i];
70 return source.empty() ? GURL() : data->GetResourceURL(source);
75 namespace application {
77 scoped_ptr<Application> Application::Create(
78 scoped_refptr<ApplicationData> data,
79 RuntimeContext* context) {
81 return make_scoped_ptr<Application>(new ApplicationTizen(data, context));
83 return make_scoped_ptr(new Application(data, context));
87 Application::Application(
88 scoped_refptr<ApplicationData> data,
89 RuntimeContext* runtime_context)
91 render_process_host_(NULL),
93 security_mode_enabled_(false),
94 runtime_context_(runtime_context),
96 remote_debugging_enabled_(false),
98 DCHECK(runtime_context_);
102 Application::~Application() {
104 if (render_process_host_)
105 render_process_host_->RemoveObserver(this);
109 GURL Application::GetStartURL<Package::WGT>() {
110 GURL url = GetAbsoluteURLFromKey(widget_keys::kLaunchLocalPathKey);
111 if (!url.is_valid()) {
112 LOG(WARNING) << "Failed to find start URL from the 'config.xml'"
113 << "trying to find default entry page.";
114 url = GetDefaultWidgetEntryPage(data_);
117 if (url.is_valid()) {
118 #if defined(OS_TIZEN)
119 if (data_->IsHostedApp() && !url.SchemeIsHTTPOrHTTPS()) {
120 LOG(ERROR) << "Hosted apps are only supported with"
121 "http:// or https:// scheme.";
128 LOG(WARNING) << "Failed to find a valid start URL in the manifest.";
133 GURL Application::GetStartURL<Package::XPK>() {
134 GURL url = GetAbsoluteURLFromKey(keys::kStartURLKey);
138 url = GetAbsoluteURLFromKey(keys::kLaunchLocalPathKey);
142 url = GetAbsoluteURLFromKey(keys::kDeprecatedURLKey);
143 if (url.is_valid()) {
144 LOG(WARNING) << "Deprecated key '" << keys::kDeprecatedURLKey
145 << "' found. Please migrate to using '" << keys::kStartURLKey
150 LOG(WARNING) << "Failed to find a valid start URL in the manifest.";
156 ui::WindowShowState Application::GetWindowShowState<Package::WGT>(
157 const LaunchParams& params) {
158 if (params.force_fullscreen)
159 return ui::SHOW_STATE_FULLSCREEN;
161 const Manifest* manifest = data_->GetManifest();
162 std::string view_modes_string;
163 if (manifest->GetString(widget_keys::kViewModesKey, &view_modes_string)) {
164 // FIXME: ATM only 'fullscreen' and 'windowed' values are supported.
165 // If the first user prefererence is 'fullscreen', set window show state
166 // FULLSCREEN, otherwise set the default window show state.
167 std::vector<std::string> modes;
168 base::SplitString(view_modes_string, ' ', &modes);
169 if (!modes.empty() && modes[0] == "fullscreen")
170 return ui::SHOW_STATE_FULLSCREEN;
173 return ui::SHOW_STATE_DEFAULT;
177 ui::WindowShowState Application::GetWindowShowState<Package::XPK>(
178 const LaunchParams& params) {
179 if (params.force_fullscreen)
180 return ui::SHOW_STATE_FULLSCREEN;
182 const Manifest* manifest = data_->GetManifest();
183 std::string display_string;
184 if (manifest->GetString(keys::kDisplay, &display_string)) {
185 // FIXME: ATM only 'fullscreen' and 'standalone' (which is fallback value)
186 // values are supported.
187 if (display_string.find("fullscreen") != std::string::npos)
188 return ui::SHOW_STATE_FULLSCREEN;
191 return ui::SHOW_STATE_DEFAULT;
194 bool Application::Launch(const LaunchParams& launch_params) {
195 if (!runtimes_.empty()) {
196 LOG(ERROR) << "Attempt to launch app with id " << id()
197 << ", but it is already running.";
201 CHECK(!render_process_host_);
202 bool is_wgt = data_->GetPackageType() == Package::WGT;
204 GURL url = is_wgt ? GetStartURL<Package::WGT>():
205 GetStartURL<Package::XPK>();
209 remote_debugging_enabled_ = launch_params.remote_debugging;
211 Runtime* runtime = Runtime::Create(
213 this, content::SiteInstance::CreateForURL(runtime_context_, url));
214 render_process_host_ = runtime->GetRenderProcessHost();
215 render_process_host_->AddObserver(this);
216 web_contents_ = runtime->web_contents();
217 InitSecurityPolicy();
218 runtime->LoadURL(url);
220 NativeAppWindow::CreateParams params;
221 params.net_wm_pid = launch_params.launcher_pid;
222 params.state = is_wgt ? GetWindowShowState<Package::WGT>(launch_params):
223 GetWindowShowState<Package::XPK>(launch_params);
225 params.splash_screen_path = GetSplashScreenPath();
227 runtime->AttachWindow(params);
232 GURL Application::GetAbsoluteURLFromKey(const std::string& key) {
233 const Manifest* manifest = data_->GetManifest();
236 if (!manifest->GetString(key, &source) || source.empty())
239 std::size_t found = source.find("://");
240 if (found == std::string::npos)
241 return data_->GetResourceURL(source);
245 void Application::Terminate() {
246 std::set<Runtime*> to_be_closed(runtimes_);
247 std::for_each(to_be_closed.begin(), to_be_closed.end(),
248 std::mem_fun(&Runtime::Close));
251 int Application::GetRenderProcessHostID() const {
252 DCHECK(render_process_host_);
253 return render_process_host_->GetID();
256 void Application::OnRuntimeAdded(Runtime* runtime) {
258 runtime->set_remote_debugging_enabled(remote_debugging_enabled_);
259 runtimes_.insert(runtime);
262 void Application::OnRuntimeRemoved(Runtime* runtime) {
264 runtimes_.erase(runtime);
266 if (runtimes_.empty()) {
267 #if defined(OS_TIZEN_MOBILE)
268 runtime->CloseRootWindow();
270 base::MessageLoop::current()->PostTask(FROM_HERE,
271 base::Bind(&Application::NotifyTermination,
272 weak_factory_.GetWeakPtr()));
276 void Application::RenderProcessExited(RenderProcessHost* host,
278 base::TerminationStatus,
280 DCHECK(render_process_host_ == host);
281 VLOG(1) << "RenderProcess id: " << host->GetID() << " is gone!";
282 XWalkRunner::GetInstance()->OnRenderProcessHostGone(host);
285 void Application::RenderProcessHostDestroyed(RenderProcessHost* host) {
286 DCHECK(render_process_host_ == host);
287 render_process_host_ = NULL;
288 web_contents_ = NULL;
291 void Application::NotifyTermination() {
292 CHECK(!render_process_host_);
294 observer_->OnApplicationTerminated(this);
297 bool Application::UseExtension(const std::string& extension_name) const {
298 // TODO(Bai): Tells whether the application contains the specified extension
302 bool Application::RegisterPermissions(const std::string& extension_name,
303 const std::string& perm_table) {
304 // TODO(Bai): Parse the permission table and fill in the name_perm_map_
305 // The perm_table format is a simple JSON string, like
306 // [{"permission_name":"echo","apis":["add","remove","get"]}]
307 scoped_ptr<base::Value> root;
308 root.reset(base::JSONReader().ReadToValue(perm_table));
309 if (root.get() == NULL || !root->IsType(base::Value::TYPE_LIST))
312 base::ListValue* permission_list = static_cast<base::ListValue*>(root.get());
313 if (permission_list->GetSize() == 0)
316 for (base::ListValue::const_iterator iter = permission_list->begin();
317 iter != permission_list->end(); ++iter) {
318 if (!(*iter)->IsType(base::Value::TYPE_DICTIONARY))
321 base::DictionaryValue* dict_val =
322 static_cast<base::DictionaryValue*>(*iter);
323 std::string permission_name;
324 if (!dict_val->GetString("permission_name", &permission_name))
327 base::ListValue* api_list = NULL;
328 if (!dict_val->GetList("apis", &api_list))
331 for (base::ListValue::const_iterator api_iter = api_list->begin();
332 api_iter != api_list->end(); ++api_iter) {
334 if (!((*api_iter)->IsType(base::Value::TYPE_STRING)
335 && (*api_iter)->GetAsString(&api)))
337 // register the permission and api
338 name_perm_map_[api] = permission_name;
339 DLOG(INFO) << "Permission Registered [PERM] " << permission_name
347 std::string Application::GetRegisteredPermissionName(
348 const std::string& extension_name,
349 const std::string& api_name) const {
350 std::map<std::string, std::string>::const_iterator iter =
351 name_perm_map_.find(api_name);
352 if (iter == name_perm_map_.end())
353 return std::string("");
357 StoredPermission Application::GetPermission(PermissionType type,
358 const std::string& permission_name) const {
359 if (type == SESSION_PERMISSION) {
360 StoredPermissionMap::const_iterator iter =
361 permission_map_.find(permission_name);
362 if (iter == permission_map_.end())
363 return UNDEFINED_STORED_PERM;
366 if (type == PERSISTENT_PERMISSION) {
367 return data_->GetPermission(permission_name);
370 return UNDEFINED_STORED_PERM;
373 bool Application::SetPermission(PermissionType type,
374 const std::string& permission_name,
375 StoredPermission perm) {
376 if (type == SESSION_PERMISSION) {
377 permission_map_[permission_name] = perm;
380 if (type == PERSISTENT_PERMISSION)
381 return data_->SetPermission(permission_name, perm);
387 void Application::InitSecurityPolicy() {
388 // CSP policy takes precedence over WARP.
389 if (data_->HasCSPDefined())
390 security_policy_.reset(new SecurityPolicyCSP(this));
391 else if (data_->GetPackageType() == Package::WGT)
392 security_policy_.reset(new SecurityPolicyWARP(this));
394 if (security_policy_)
395 security_policy_->Enforce();
398 bool Application::CanRequestURL(const GURL& url) const {
399 if (security_policy_)
400 return security_policy_->IsAccessAllowed(url);
404 base::FilePath Application::GetSplashScreenPath() {
405 return base::FilePath();
408 } // namespace application