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_context.h"
26 #include "xwalk/runtime/browser/runtime_defered_ui_strategy.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 < arraysize(kDefaultWidgetEntryPage); ++i) {
60 if (file.BaseName().MaybeAsASCII() == kDefaultWidgetEntryPage[i] &&
62 source = kDefaultWidgetEntryPage[i];
68 return source.empty() ? GURL() : data->GetResourceURL(source);
73 namespace application {
75 scoped_ptr<Application> Application::Create(
76 scoped_refptr<ApplicationData> data,
77 RuntimeContext* context) {
79 return make_scoped_ptr<Application>(new ApplicationTizen(data, context));
81 return make_scoped_ptr(new Application(data, context));
85 Application::Application(
86 scoped_refptr<ApplicationData> data,
87 RuntimeContext* runtime_context)
89 render_process_host_(NULL),
91 security_mode_enabled_(false),
92 runtime_context_(runtime_context),
94 ui_strategy_(new RuntimeDeferedUIStrategy),
95 remote_debugging_enabled_(false),
97 DCHECK(runtime_context_);
101 Application::~Application() {
103 if (render_process_host_)
104 render_process_host_->RemoveObserver(this);
108 GURL Application::GetStartURL<Manifest::TYPE_WIDGET>() {
109 #if defined(OS_TIZEN)
110 if (data_->IsHostedApp()) {
113 if (data_->GetManifest()->GetString(
114 widget_keys::kLaunchLocalPathKey, &source)) {
118 if (url.is_valid() && url.SchemeIsHTTPOrHTTPS())
123 GURL url = GetAbsoluteURLFromKey(widget_keys::kLaunchLocalPathKey);
127 LOG(WARNING) << "Failed to find start URL from the 'config.xml'"
128 << "trying to find default entry page.";
129 url = GetDefaultWidgetEntryPage(data_);
133 LOG(WARNING) << "Failed to find a valid start URL in the manifest.";
138 GURL Application::GetStartURL<Manifest::TYPE_MANIFEST>() {
139 if (data_->IsHostedApp()) {
141 // Not trying to get a relative path for the "fake" application.
142 if (data_->GetManifest()->GetString(keys::kStartURLKey, &source))
147 GURL url = GetAbsoluteURLFromKey(keys::kStartURLKey);
151 url = GetAbsoluteURLFromKey(keys::kLaunchLocalPathKey);
155 url = GetAbsoluteURLFromKey(keys::kDeprecatedURLKey);
156 if (url.is_valid()) {
157 LOG(WARNING) << "Deprecated key '" << keys::kDeprecatedURLKey
158 << "' found. Please migrate to using '" << keys::kStartURLKey
163 LOG(WARNING) << "Failed to find a valid start URL in the manifest.";
169 ui::WindowShowState Application::GetWindowShowState<Manifest::TYPE_WIDGET>(
170 const LaunchParams& params) {
171 if (params.force_fullscreen)
172 return ui::SHOW_STATE_FULLSCREEN;
174 const Manifest* manifest = data_->GetManifest();
175 std::string view_modes_string;
176 if (manifest->GetString(widget_keys::kViewModesKey, &view_modes_string)) {
177 // FIXME: ATM only 'fullscreen' and 'windowed' values are supported.
178 // If the first user prefererence is 'fullscreen', set window show state
179 // FULLSCREEN, otherwise set the default window show state.
180 std::vector<std::string> modes;
181 base::SplitString(view_modes_string, ' ', &modes);
182 if (!modes.empty() && modes[0] == "fullscreen")
183 return ui::SHOW_STATE_FULLSCREEN;
186 return ui::SHOW_STATE_DEFAULT;
190 ui::WindowShowState Application::GetWindowShowState<Manifest::TYPE_MANIFEST>(
191 const LaunchParams& params) {
192 if (params.force_fullscreen)
193 return ui::SHOW_STATE_FULLSCREEN;
195 const Manifest* manifest = data_->GetManifest();
196 std::string display_string;
197 if (manifest->GetString(keys::kDisplay, &display_string)) {
198 // FIXME: ATM only 'fullscreen' and 'standalone' (which is fallback value)
199 // values are supported.
200 if (display_string.find("fullscreen") != std::string::npos)
201 return ui::SHOW_STATE_FULLSCREEN;
204 return ui::SHOW_STATE_DEFAULT;
207 bool Application::Launch(const LaunchParams& launch_params) {
208 if (!runtimes_.empty()) {
209 LOG(ERROR) << "Attempt to launch app with id " << id()
210 << ", but it is already running.";
214 CHECK(!render_process_host_);
215 bool is_wgt = data_->manifest_type() == Manifest::TYPE_WIDGET;
217 GURL url = is_wgt ? GetStartURL<Manifest::TYPE_WIDGET>() :
218 GetStartURL<Manifest::TYPE_MANIFEST>();
222 remote_debugging_enabled_ = launch_params.remote_debugging;
224 Runtime* runtime = Runtime::Create(
226 this, content::SiteInstance::CreateForURL(runtime_context_, url));
227 render_process_host_ = runtime->GetRenderProcessHost();
228 render_process_host_->AddObserver(this);
229 web_contents_ = runtime->web_contents();
230 InitSecurityPolicy();
231 runtime->LoadURL(url);
233 NativeAppWindow::CreateParams params;
234 params.net_wm_pid = launch_params.launcher_pid;
235 params.state = is_wgt ?
236 GetWindowShowState<Manifest::TYPE_WIDGET>(launch_params):
237 GetWindowShowState<Manifest::TYPE_MANIFEST>(launch_params);
238 window_show_params_.state = params.state;
240 params.splash_screen_path = GetSplashScreenPath();
242 ui_strategy_->Show(runtime, params);
247 GURL Application::GetAbsoluteURLFromKey(const std::string& key) {
248 const Manifest* manifest = data_->GetManifest();
251 if (!manifest->GetString(key, &source) || source.empty())
254 return data_->GetResourceURL(source);
257 void Application::Terminate() {
258 std::set<Runtime*> to_be_closed(runtimes_);
259 std::for_each(to_be_closed.begin(), to_be_closed.end(),
260 std::mem_fun(&Runtime::Close));
263 int Application::GetRenderProcessHostID() const {
264 DCHECK(render_process_host_);
265 return render_process_host_->GetID();
268 void Application::OnRuntimeAdded(Runtime* runtime) {
270 runtime->set_remote_debugging_enabled(remote_debugging_enabled_);
271 if (!runtimes_.empty())
272 ui_strategy_->Show(runtime, window_show_params_);
273 runtimes_.insert(runtime);
276 void Application::OnRuntimeRemoved(Runtime* runtime) {
278 runtimes_.erase(runtime);
280 if (runtimes_.empty())
281 base::MessageLoop::current()->PostTask(FROM_HERE,
282 base::Bind(&Application::NotifyTermination,
283 weak_factory_.GetWeakPtr()));
286 void Application::RenderProcessExited(RenderProcessHost* host,
288 base::TerminationStatus,
290 DCHECK(render_process_host_ == host);
291 VLOG(1) << "RenderProcess id: " << host->GetID() << " is gone!";
292 XWalkRunner::GetInstance()->OnRenderProcessHostGone(host);
295 void Application::RenderProcessHostDestroyed(RenderProcessHost* host) {
296 DCHECK(render_process_host_ == host);
297 render_process_host_ = NULL;
298 web_contents_ = NULL;
301 void Application::NotifyTermination() {
302 CHECK(!render_process_host_);
304 observer_->OnApplicationTerminated(this);
307 bool Application::UseExtension(const std::string& extension_name) const {
308 // TODO(Bai): Tells whether the application contains the specified extension
312 bool Application::RegisterPermissions(const std::string& extension_name,
313 const std::string& perm_table) {
314 // TODO(Bai): Parse the permission table and fill in the name_perm_map_
315 // The perm_table format is a simple JSON string, like
316 // [{"permission_name":"echo","apis":["add","remove","get"]}]
317 scoped_ptr<base::Value> root;
318 root.reset(base::JSONReader().ReadToValue(perm_table));
319 if (root.get() == NULL || !root->IsType(base::Value::TYPE_LIST))
322 base::ListValue* permission_list = static_cast<base::ListValue*>(root.get());
323 if (permission_list->GetSize() == 0)
326 for (base::ListValue::const_iterator iter = permission_list->begin();
327 iter != permission_list->end(); ++iter) {
328 if (!(*iter)->IsType(base::Value::TYPE_DICTIONARY))
331 base::DictionaryValue* dict_val =
332 static_cast<base::DictionaryValue*>(*iter);
333 std::string permission_name;
334 if (!dict_val->GetString("permission_name", &permission_name))
337 base::ListValue* api_list = NULL;
338 if (!dict_val->GetList("apis", &api_list))
341 for (base::ListValue::const_iterator api_iter = api_list->begin();
342 api_iter != api_list->end(); ++api_iter) {
344 if (!((*api_iter)->IsType(base::Value::TYPE_STRING)
345 && (*api_iter)->GetAsString(&api)))
347 // register the permission and api
348 name_perm_map_[api] = permission_name;
349 DLOG(INFO) << "Permission Registered [PERM] " << permission_name
357 std::string Application::GetRegisteredPermissionName(
358 const std::string& extension_name,
359 const std::string& api_name) const {
360 std::map<std::string, std::string>::const_iterator iter =
361 name_perm_map_.find(api_name);
362 if (iter == name_perm_map_.end())
363 return std::string("");
367 StoredPermission Application::GetPermission(PermissionType type,
368 const std::string& permission_name) const {
369 if (type == SESSION_PERMISSION) {
370 StoredPermissionMap::const_iterator iter =
371 permission_map_.find(permission_name);
372 if (iter == permission_map_.end())
373 return UNDEFINED_STORED_PERM;
376 if (type == PERSISTENT_PERMISSION) {
377 return data_->GetPermission(permission_name);
380 return UNDEFINED_STORED_PERM;
383 bool Application::SetPermission(PermissionType type,
384 const std::string& permission_name,
385 StoredPermission perm) {
386 if (type == SESSION_PERMISSION) {
387 permission_map_[permission_name] = perm;
390 if (type == PERSISTENT_PERMISSION)
391 return data_->SetPermission(permission_name, perm);
397 void Application::InitSecurityPolicy() {
398 // CSP policy takes precedence over WARP.
399 if (data_->HasCSPDefined())
400 security_policy_.reset(new ApplicationSecurityPolicyCSP(this));
401 else if (data_->manifest_type() == Manifest::TYPE_WIDGET)
402 security_policy_.reset(new ApplicationSecurityPolicyWARP(this));
404 if (security_policy_)
405 security_policy_->Enforce();
408 bool Application::CanRequestURL(const GURL& url) const {
409 if (security_policy_)
410 return security_policy_->IsAccessAllowed(url);
414 base::FilePath Application::GetSplashScreenPath() {
415 return base::FilePath();
418 } // namespace application