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()) {
112 data_->GetManifest()->GetString(widget_keys::kLaunchLocalPathKey, &source);
113 GURL url = GURL(source);
115 if (url.is_valid() && url.SchemeIsHTTPOrHTTPS())
120 GURL url = GetAbsoluteURLFromKey(widget_keys::kLaunchLocalPathKey);
124 LOG(WARNING) << "Failed to find start URL from the 'config.xml'"
125 << "trying to find default entry page.";
126 url = GetDefaultWidgetEntryPage(data_);
130 LOG(WARNING) << "Failed to find a valid start URL in the manifest.";
135 GURL Application::GetStartURL<Manifest::TYPE_MANIFEST>() {
136 if (data_->IsHostedApp()) {
138 data_->GetManifest()->GetString(keys::kStartURLKey, &source);
139 // Not trying to get a relative path for the "fake" application.
143 GURL url = GetAbsoluteURLFromKey(keys::kStartURLKey);
147 url = GetAbsoluteURLFromKey(keys::kLaunchLocalPathKey);
151 url = GetAbsoluteURLFromKey(keys::kDeprecatedURLKey);
152 if (url.is_valid()) {
153 LOG(WARNING) << "Deprecated key '" << keys::kDeprecatedURLKey
154 << "' found. Please migrate to using '" << keys::kStartURLKey
159 LOG(WARNING) << "Failed to find a valid start URL in the manifest.";
165 ui::WindowShowState Application::GetWindowShowState<Manifest::TYPE_WIDGET>(
166 const LaunchParams& params) {
167 if (params.force_fullscreen)
168 return ui::SHOW_STATE_FULLSCREEN;
170 const Manifest* manifest = data_->GetManifest();
171 std::string view_modes_string;
172 if (manifest->GetString(widget_keys::kViewModesKey, &view_modes_string)) {
173 // FIXME: ATM only 'fullscreen' and 'windowed' values are supported.
174 // If the first user prefererence is 'fullscreen', set window show state
175 // FULLSCREEN, otherwise set the default window show state.
176 std::vector<std::string> modes;
177 base::SplitString(view_modes_string, ' ', &modes);
178 if (!modes.empty() && modes[0] == "fullscreen")
179 return ui::SHOW_STATE_FULLSCREEN;
182 return ui::SHOW_STATE_DEFAULT;
186 ui::WindowShowState Application::GetWindowShowState<Manifest::TYPE_MANIFEST>(
187 const LaunchParams& params) {
188 if (params.force_fullscreen)
189 return ui::SHOW_STATE_FULLSCREEN;
191 const Manifest* manifest = data_->GetManifest();
192 std::string display_string;
193 if (manifest->GetString(keys::kDisplay, &display_string)) {
194 // FIXME: ATM only 'fullscreen' and 'standalone' (which is fallback value)
195 // values are supported.
196 if (display_string.find("fullscreen") != std::string::npos)
197 return ui::SHOW_STATE_FULLSCREEN;
200 return ui::SHOW_STATE_DEFAULT;
203 bool Application::Launch(const LaunchParams& launch_params) {
204 if (!runtimes_.empty()) {
205 LOG(ERROR) << "Attempt to launch app with id " << id()
206 << ", but it is already running.";
210 CHECK(!render_process_host_);
211 bool is_wgt = data_->manifest_type() == Manifest::TYPE_WIDGET;
213 GURL url = is_wgt ? GetStartURL<Manifest::TYPE_WIDGET>() :
214 GetStartURL<Manifest::TYPE_MANIFEST>();
218 remote_debugging_enabled_ = launch_params.remote_debugging;
220 Runtime* runtime = Runtime::Create(
222 this, content::SiteInstance::CreateForURL(runtime_context_, url));
223 render_process_host_ = runtime->GetRenderProcessHost();
224 render_process_host_->AddObserver(this);
225 web_contents_ = runtime->web_contents();
226 InitSecurityPolicy();
227 runtime->LoadURL(url);
229 NativeAppWindow::CreateParams params;
230 params.net_wm_pid = launch_params.launcher_pid;
231 params.state = is_wgt ?
232 GetWindowShowState<Manifest::TYPE_WIDGET>(launch_params):
233 GetWindowShowState<Manifest::TYPE_MANIFEST>(launch_params);
234 window_show_params_.state = params.state;
236 params.splash_screen_path = GetSplashScreenPath();
238 ui_strategy_->Show(runtime, params);
243 GURL Application::GetAbsoluteURLFromKey(const std::string& key) {
244 const Manifest* manifest = data_->GetManifest();
247 if (!manifest->GetString(key, &source) || source.empty())
250 return data_->GetResourceURL(source);
253 void Application::Terminate() {
254 std::set<Runtime*> to_be_closed(runtimes_);
255 std::for_each(to_be_closed.begin(), to_be_closed.end(),
256 std::mem_fun(&Runtime::Close));
259 int Application::GetRenderProcessHostID() const {
260 DCHECK(render_process_host_);
261 return render_process_host_->GetID();
264 void Application::OnRuntimeAdded(Runtime* runtime) {
266 runtime->set_remote_debugging_enabled(remote_debugging_enabled_);
267 if (!runtimes_.empty())
268 ui_strategy_->Show(runtime, window_show_params_);
269 runtimes_.insert(runtime);
272 void Application::OnRuntimeRemoved(Runtime* runtime) {
274 runtimes_.erase(runtime);
276 if (runtimes_.empty())
277 base::MessageLoop::current()->PostTask(FROM_HERE,
278 base::Bind(&Application::NotifyTermination,
279 weak_factory_.GetWeakPtr()));
282 void Application::RenderProcessExited(RenderProcessHost* host,
284 base::TerminationStatus,
286 DCHECK(render_process_host_ == host);
287 VLOG(1) << "RenderProcess id: " << host->GetID() << " is gone!";
288 XWalkRunner::GetInstance()->OnRenderProcessHostGone(host);
291 void Application::RenderProcessHostDestroyed(RenderProcessHost* host) {
292 DCHECK(render_process_host_ == host);
293 render_process_host_ = NULL;
294 web_contents_ = NULL;
297 void Application::NotifyTermination() {
298 CHECK(!render_process_host_);
300 observer_->OnApplicationTerminated(this);
303 bool Application::UseExtension(const std::string& extension_name) const {
304 // TODO(Bai): Tells whether the application contains the specified extension
308 bool Application::RegisterPermissions(const std::string& extension_name,
309 const std::string& perm_table) {
310 // TODO(Bai): Parse the permission table and fill in the name_perm_map_
311 // The perm_table format is a simple JSON string, like
312 // [{"permission_name":"echo","apis":["add","remove","get"]}]
313 scoped_ptr<base::Value> root;
314 root.reset(base::JSONReader().ReadToValue(perm_table));
315 if (root.get() == NULL || !root->IsType(base::Value::TYPE_LIST))
318 base::ListValue* permission_list = static_cast<base::ListValue*>(root.get());
319 if (permission_list->GetSize() == 0)
322 for (base::ListValue::const_iterator iter = permission_list->begin();
323 iter != permission_list->end(); ++iter) {
324 if (!(*iter)->IsType(base::Value::TYPE_DICTIONARY))
327 base::DictionaryValue* dict_val =
328 static_cast<base::DictionaryValue*>(*iter);
329 std::string permission_name;
330 if (!dict_val->GetString("permission_name", &permission_name))
333 base::ListValue* api_list = NULL;
334 if (!dict_val->GetList("apis", &api_list))
337 for (base::ListValue::const_iterator api_iter = api_list->begin();
338 api_iter != api_list->end(); ++api_iter) {
340 if (!((*api_iter)->IsType(base::Value::TYPE_STRING)
341 && (*api_iter)->GetAsString(&api)))
343 // register the permission and api
344 name_perm_map_[api] = permission_name;
345 DLOG(INFO) << "Permission Registered [PERM] " << permission_name
353 std::string Application::GetRegisteredPermissionName(
354 const std::string& extension_name,
355 const std::string& api_name) const {
356 std::map<std::string, std::string>::const_iterator iter =
357 name_perm_map_.find(api_name);
358 if (iter == name_perm_map_.end())
359 return std::string("");
363 StoredPermission Application::GetPermission(PermissionType type,
364 const std::string& permission_name) const {
365 if (type == SESSION_PERMISSION) {
366 StoredPermissionMap::const_iterator iter =
367 permission_map_.find(permission_name);
368 if (iter == permission_map_.end())
369 return UNDEFINED_STORED_PERM;
372 if (type == PERSISTENT_PERMISSION) {
373 return data_->GetPermission(permission_name);
376 return UNDEFINED_STORED_PERM;
379 bool Application::SetPermission(PermissionType type,
380 const std::string& permission_name,
381 StoredPermission perm) {
382 if (type == SESSION_PERMISSION) {
383 permission_map_[permission_name] = perm;
386 if (type == PERSISTENT_PERMISSION)
387 return data_->SetPermission(permission_name, perm);
393 void Application::InitSecurityPolicy() {
394 // CSP policy takes precedence over WARP.
395 if (data_->HasCSPDefined())
396 security_policy_.reset(new SecurityPolicyCSP(this));
397 else if (data_->manifest_type() == Manifest::TYPE_WIDGET)
398 security_policy_.reset(new SecurityPolicyWARP(this));
400 if (security_policy_)
401 security_policy_->Enforce();
404 bool Application::CanRequestURL(const GURL& url) const {
405 if (security_policy_)
406 return security_policy_->IsAccessAllowed(url);
410 base::FilePath Application::GetSplashScreenPath() {
411 return base::FilePath();
414 } // namespace application