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/common/application_manifest_constants.h"
22 #include "xwalk/application/common/constants.h"
23 #include "xwalk/application/common/manifest_handlers/warp_handler.h"
24 #include "xwalk/runtime/browser/runtime.h"
25 #include "xwalk/runtime/browser/runtime_ui_delegate.h"
26 #include "xwalk/runtime/browser/xwalk_browser_context.h"
27 #include "xwalk/runtime/browser/xwalk_runner.h"
30 #include "xwalk/application/browser/application_tizen.h"
33 using content::RenderProcessHost;
37 namespace keys = application_manifest_keys;
38 namespace widget_keys = application_widget_keys;
41 const char* kDefaultWidgetEntryPage[] = {
48 GURL GetDefaultWidgetEntryPage(
49 scoped_refptr<xwalk::application::ApplicationData> data) {
50 base::ThreadRestrictions::SetIOAllowed(true);
51 base::FileEnumerator iter(
53 base::FileEnumerator::FILES,
54 FILE_PATH_LITERAL("index.*"));
55 size_t priority = arraysize(kDefaultWidgetEntryPage);
58 for (base::FilePath file = iter.Next(); !file.empty(); file = iter.Next()) {
59 for (size_t i = 0; i < priority; ++i) {
60 if (file.BaseName().MaybeAsASCII() == kDefaultWidgetEntryPage[i]) {
61 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 XWalkBrowserContext* 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 XWalkBrowserContext* browser_context)
91 render_process_host_(NULL),
93 security_mode_enabled_(false),
94 browser_context_(browser_context),
96 remote_debugging_enabled_(false),
98 DCHECK(browser_context_);
102 Application::~Application() {
104 if (render_process_host_)
105 render_process_host_->RemoveObserver(this);
109 GURL Application::GetStartURL<Manifest::TYPE_WIDGET>() {
110 #if defined(OS_TIZEN)
111 if (data_->IsHostedApp()) {
114 if (data_->GetManifest()->GetString(
115 widget_keys::kLaunchLocalPathKey, &source)) {
119 if (url.is_valid() && url.SchemeIsHTTPOrHTTPS())
124 GURL url = GetAbsoluteURLFromKey(widget_keys::kLaunchLocalPathKey);
128 LOG(WARNING) << "Failed to find start URL from the 'config.xml'"
129 << "trying to find default entry page.";
130 url = GetDefaultWidgetEntryPage(data_);
134 LOG(WARNING) << "Failed to find a valid start URL in the manifest.";
139 GURL Application::GetStartURL<Manifest::TYPE_MANIFEST>() {
140 if (data_->IsHostedApp()) {
142 // Not trying to get a relative path for the "fake" application.
143 if (data_->GetManifest()->GetString(keys::kStartURLKey, &source))
148 GURL url = GetAbsoluteURLFromKey(keys::kStartURLKey);
152 url = GetAbsoluteURLFromKey(keys::kLaunchLocalPathKey);
156 url = GetAbsoluteURLFromKey(keys::kDeprecatedURLKey);
157 if (url.is_valid()) {
158 LOG(WARNING) << "Deprecated key '" << keys::kDeprecatedURLKey
159 << "' found. Please migrate to using '" << keys::kStartURLKey
164 LOG(WARNING) << "Failed to find a valid start URL in the manifest.";
170 ui::WindowShowState Application::GetWindowShowState<Manifest::TYPE_WIDGET>(
171 const LaunchParams& params) {
172 if (params.force_fullscreen)
173 return ui::SHOW_STATE_FULLSCREEN;
175 const Manifest* manifest = data_->GetManifest();
176 std::string view_modes_string;
177 if (manifest->GetString(widget_keys::kViewModesKey, &view_modes_string)) {
178 // FIXME: ATM only 'fullscreen' and 'windowed' values are supported.
179 // If the first user prefererence is 'fullscreen', set window show state
180 // FULLSCREEN, otherwise set the default window show state.
181 std::vector<std::string> modes;
182 base::SplitString(view_modes_string, ' ', &modes);
183 if (!modes.empty() && modes[0] == "fullscreen")
184 return ui::SHOW_STATE_FULLSCREEN;
187 return ui::SHOW_STATE_DEFAULT;
191 ui::WindowShowState Application::GetWindowShowState<Manifest::TYPE_MANIFEST>(
192 const LaunchParams& params) {
193 if (params.force_fullscreen)
194 return ui::SHOW_STATE_FULLSCREEN;
196 const Manifest* manifest = data_->GetManifest();
197 std::string display_string;
198 if (manifest->GetString(keys::kDisplay, &display_string)) {
199 // FIXME: ATM only 'fullscreen' and 'standalone' (which is fallback value)
200 // values are supported.
201 if (display_string.find("fullscreen") != std::string::npos)
202 return ui::SHOW_STATE_FULLSCREEN;
205 return ui::SHOW_STATE_DEFAULT;
208 bool Application::Launch(const LaunchParams& launch_params) {
209 if (!runtimes_.empty()) {
210 LOG(ERROR) << "Attempt to launch app with id " << id()
211 << ", but it is already running.";
215 CHECK(!render_process_host_);
216 bool is_wgt = data_->manifest_type() == Manifest::TYPE_WIDGET;
218 GURL url = is_wgt ? GetStartURL<Manifest::TYPE_WIDGET>() :
219 GetStartURL<Manifest::TYPE_MANIFEST>();
223 remote_debugging_enabled_ = launch_params.remote_debugging;
224 auto site = content::SiteInstance::CreateForURL(browser_context_, url);
225 Runtime* runtime = Runtime::Create(browser_context_, site);
226 runtime->set_observer(this);
227 runtime->set_remote_debugging_enabled(remote_debugging_enabled_);
228 runtimes_.push_back(runtime);
229 render_process_host_ = runtime->GetRenderProcessHost();
230 render_process_host_->AddObserver(this);
231 web_contents_ = runtime->web_contents();
232 InitSecurityPolicy();
233 runtime->LoadURL(url);
235 NativeAppWindow::CreateParams params;
236 params.net_wm_pid = launch_params.launcher_pid;
237 params.state = is_wgt ?
238 GetWindowShowState<Manifest::TYPE_WIDGET>(launch_params) :
239 GetWindowShowState<Manifest::TYPE_MANIFEST>(launch_params);
241 window_show_params_ = params;
242 // Only the first runtime can have a launch screen.
243 params.splash_screen_path = GetSplashScreenPath();
244 runtime->set_ui_delegate(DefaultRuntimeUIDelegate::Create(runtime, params));
245 // We call "Show" after RP is initialized to reduce
246 // the application start up time.
251 GURL Application::GetAbsoluteURLFromKey(const std::string& key) {
252 const Manifest* manifest = data_->GetManifest();
255 if (!manifest->GetString(key, &source) || source.empty())
258 return data_->GetResourceURL(source);
261 void Application::Terminate() {
262 std::vector<Runtime*> to_be_closed(runtimes_.get());
263 for (Runtime* runtime : to_be_closed)
267 int Application::GetRenderProcessHostID() const {
268 DCHECK(render_process_host_);
269 return render_process_host_->GetID();
272 void Application::OnNewRuntimeAdded(Runtime* runtime) {
273 runtime->set_remote_debugging_enabled(remote_debugging_enabled_);
274 runtime->set_observer(this);
275 runtime->set_ui_delegate(
276 DefaultRuntimeUIDelegate::Create(runtime, window_show_params_));
278 runtimes_.push_back(runtime);
281 void Application::OnRuntimeClosed(Runtime* runtime) {
282 auto found = std::find(runtimes_.begin(), runtimes_.end(), runtime);
283 CHECK(found != runtimes_.end());
284 LOG(INFO) << "Application::OnRuntimeClosed " << runtime;
285 runtimes_.erase(found);
287 if (runtimes_.empty())
288 base::MessageLoop::current()->PostTask(FROM_HERE,
289 base::Bind(&Application::NotifyTermination,
290 weak_factory_.GetWeakPtr()));
293 void Application::RenderProcessExited(RenderProcessHost* host,
294 base::TerminationStatus,
296 DCHECK(render_process_host_ == host);
297 VLOG(1) << "RenderProcess id: " << host->GetID() << " is gone!";
298 XWalkRunner::GetInstance()->OnRenderProcessHostGone(host);
301 void Application::RenderProcessHostDestroyed(RenderProcessHost* host) {
302 DCHECK(render_process_host_ == host);
303 render_process_host_ = NULL;
304 web_contents_ = NULL;
307 void Application::NotifyTermination() {
308 CHECK(!render_process_host_);
310 observer_->OnApplicationTerminated(this);
313 void Application::RenderChannelCreated() {
314 CHECK(!runtimes_.empty());
315 runtimes_.front()->Show();
318 bool Application::UseExtension(const std::string& extension_name) const {
319 // TODO(Bai): Tells whether the application contains the specified extension
323 bool Application::RegisterPermissions(const std::string& extension_name,
324 const std::string& perm_table) {
325 // TODO(Bai): Parse the permission table and fill in the name_perm_map_
326 // The perm_table format is a simple JSON string, like
327 // [{"permission_name":"echo","apis":["add","remove","get"]}]
328 scoped_ptr<base::Value> root;
329 root.reset(base::JSONReader().ReadToValue(perm_table));
330 if (root.get() == NULL || !root->IsType(base::Value::TYPE_LIST))
333 base::ListValue* permission_list = static_cast<base::ListValue*>(root.get());
334 if (permission_list->GetSize() == 0)
337 for (base::ListValue::const_iterator iter = permission_list->begin();
338 iter != permission_list->end(); ++iter) {
339 if (!(*iter)->IsType(base::Value::TYPE_DICTIONARY))
342 base::DictionaryValue* dict_val =
343 static_cast<base::DictionaryValue*>(*iter);
344 std::string permission_name;
345 if (!dict_val->GetString("permission_name", &permission_name))
348 base::ListValue* api_list = NULL;
349 if (!dict_val->GetList("apis", &api_list))
352 for (base::ListValue::const_iterator api_iter = api_list->begin();
353 api_iter != api_list->end(); ++api_iter) {
355 if (!((*api_iter)->IsType(base::Value::TYPE_STRING)
356 && (*api_iter)->GetAsString(&api)))
358 // register the permission and api
359 name_perm_map_[api] = permission_name;
360 DLOG(INFO) << "Permission Registered [PERM] " << permission_name
368 std::string Application::GetRegisteredPermissionName(
369 const std::string& extension_name,
370 const std::string& api_name) const {
371 std::map<std::string, std::string>::const_iterator iter =
372 name_perm_map_.find(api_name);
373 if (iter == name_perm_map_.end())
374 return std::string();
378 StoredPermission Application::GetPermission(PermissionType type,
379 const std::string& permission_name) const {
380 if (type == SESSION_PERMISSION) {
381 StoredPermissionMap::const_iterator iter =
382 permission_map_.find(permission_name);
383 if (iter == permission_map_.end())
384 return UNDEFINED_STORED_PERM;
387 if (type == PERSISTENT_PERMISSION) {
388 return data_->GetPermission(permission_name);
391 return UNDEFINED_STORED_PERM;
394 bool Application::SetPermission(PermissionType type,
395 const std::string& permission_name,
396 StoredPermission perm) {
397 if (type == SESSION_PERMISSION) {
398 permission_map_[permission_name] = perm;
401 if (type == PERSISTENT_PERMISSION)
402 return data_->SetPermission(permission_name, perm);
408 void Application::InitSecurityPolicy() {
409 // CSP policy takes precedence over WARP.
410 if (data_->HasCSPDefined())
411 security_policy_.reset(new ApplicationSecurityPolicyCSP(this));
412 else if (data_->manifest_type() == Manifest::TYPE_WIDGET)
413 security_policy_.reset(new ApplicationSecurityPolicyWARP(this));
415 if (security_policy_)
416 security_policy_->Enforce();
419 bool Application::CanRequestURL(const GURL& url) const {
420 if (security_policy_)
421 return security_policy_->IsAccessAllowed(url);
425 base::FilePath Application::GetSplashScreenPath() {
426 return base::FilePath();
429 } // namespace application