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"
31 using content::RenderProcessHost;
35 namespace keys = application_manifest_keys;
36 namespace widget_keys = application_widget_keys;
39 const char* kDefaultWidgetEntryPage[] = {
48 namespace application {
50 Application::Application(
51 scoped_refptr<ApplicationData> data,
52 RuntimeContext* runtime_context,
55 render_process_host_(NULL),
57 security_mode_enabled_(false),
58 runtime_context_(runtime_context),
60 entry_point_used_(Default),
62 DCHECK(runtime_context_);
67 Application::~Application() {
69 if (render_process_host_)
70 render_process_host_->RemoveObserver(this);
73 bool Application::Launch(const LaunchParams& launch_params) {
74 if (!runtimes_.empty()) {
75 LOG(ERROR) << "Attempt to launch app: " << id()
76 << " that was already launched.";
80 CHECK(!render_process_host_);
82 GURL url = GetStartURL(launch_params, &entry_point_used_);
86 Runtime* runtime = Runtime::Create(
88 this, content::SiteInstance::CreateForURL(runtime_context_, url));
89 render_process_host_ = runtime->GetRenderProcessHost();
90 render_process_host_->AddObserver(this);
91 web_contents_ = runtime->web_contents();
93 runtime->LoadURL(url);
95 NativeAppWindow::CreateParams params;
96 params.net_wm_pid = launch_params.launcher_pid;
97 if (data_->GetPackageType() == Package::WGT)
98 params.state = GetWindowShowStateWGT(launch_params);
100 params.state = GetWindowShowStateXPK(launch_params);
102 params.splash_screen_path = GetSplashScreenPath();
104 runtime->AttachWindow(params);
109 GURL Application::GetStartURL(const LaunchParams& params,
110 LaunchEntryPoint* used) {
111 if (params.entry_points & StartURLKey) {
112 GURL url = GetAbsoluteURLFromKey(keys::kStartURLKey);
113 if (url.is_valid()) {
119 if (params.entry_points & LaunchLocalPathKey) {
120 GURL url = GetAbsoluteURLFromKey(
121 GetLaunchLocalPathKey(data_->GetPackageType()));
122 if (url.is_valid()) {
123 *used = LaunchLocalPathKey;
128 if (params.entry_points & URLKey) {
129 LOG(WARNING) << "Deprecated key '" << keys::kDeprecatedURLKey
130 << "' found. Please migrate to using '" << keys::kStartURLKey
132 GURL url = GetAbsoluteURLFromKey(keys::kDeprecatedURLKey);
133 if (url.is_valid()) {
139 LOG(WARNING) << "Failed to find a valid start URL in the manifest.";
143 ui::WindowShowState Application::GetWindowShowStateWGT(
144 const LaunchParams& params) {
145 if (params.force_fullscreen)
146 return ui::SHOW_STATE_FULLSCREEN;
148 const Manifest* manifest = data_->GetManifest();
149 std::string view_modes_string;
150 if (manifest->GetString(widget_keys::kViewModesKey, &view_modes_string)) {
151 // FIXME: ATM only 'fullscreen' and 'windowed' values are supported.
152 // If the first user prefererence is 'fullscreen', set window show state
153 // FULLSCREEN, otherwise set the default window show state.
154 std::vector<std::string> modes;
155 base::SplitString(view_modes_string, ' ', &modes);
156 if (!modes.empty() && modes[0] == "fullscreen")
157 return ui::SHOW_STATE_FULLSCREEN;
160 return ui::SHOW_STATE_DEFAULT;
163 ui::WindowShowState Application::GetWindowShowStateXPK(
164 const LaunchParams& params) {
165 if (params.force_fullscreen)
166 return ui::SHOW_STATE_FULLSCREEN;
168 const Manifest* manifest = data_->GetManifest();
169 std::string display_string;
170 if (manifest->GetString(keys::kDisplay, &display_string)) {
171 // FIXME: ATM only 'fullscreen' and 'standalone' (which is fallback value)
172 // values are supported.
173 if (display_string.find("fullscreen") != std::string::npos)
174 return ui::SHOW_STATE_FULLSCREEN;
177 return ui::SHOW_STATE_DEFAULT;
180 GURL Application::GetAbsoluteURLFromKey(const std::string& key) {
181 const Manifest* manifest = data_->GetManifest();
184 if (!manifest->GetString(key, &source) || source.empty()) {
185 if (data_->GetPackageType() == Package::XPK)
188 // FIXME: Refactor this Widget specific code out.
189 base::ThreadRestrictions::SetIOAllowed(true);
190 base::FileEnumerator iter(
192 base::FileEnumerator::FILES,
193 FILE_PATH_LITERAL("index.*"));
194 size_t priority = arraysize(kDefaultWidgetEntryPage);
196 for (base::FilePath file = iter.Next(); !file.empty(); file = iter.Next()) {
197 for (size_t i = 0; i < arraysize(kDefaultWidgetEntryPage); ++i) {
198 if (file.BaseName().MaybeAsASCII() == kDefaultWidgetEntryPage[i] &&
200 source = kDefaultWidgetEntryPage[i];
210 std::size_t found = source.find_first_of("://");
211 if (found == std::string::npos)
212 return data_->GetResourceURL(source);
216 void Application::Terminate() {
217 std::set<Runtime*> to_be_closed(runtimes_);
218 std::for_each(to_be_closed.begin(), to_be_closed.end(),
219 std::mem_fun(&Runtime::Close));
222 int Application::GetRenderProcessHostID() const {
223 DCHECK(render_process_host_);
224 return render_process_host_->GetID();
227 void Application::OnRuntimeAdded(Runtime* runtime) {
229 runtimes_.insert(runtime);
232 void Application::OnRuntimeRemoved(Runtime* runtime) {
234 runtimes_.erase(runtime);
236 if (runtimes_.empty()) {
237 #if defined(OS_TIZEN_MOBILE)
238 runtime->CloseRootWindow();
240 base::MessageLoop::current()->PostTask(FROM_HERE,
241 base::Bind(&Application::NotifyTermination,
242 weak_factory_.GetWeakPtr()));
247 void Application::RenderProcessExited(RenderProcessHost* host,
249 base::TerminationStatus,
251 DCHECK(render_process_host_ == host);
252 VLOG(1) << "RenderProcess id: " << host->GetID() << " is gone!";
253 XWalkRunner::GetInstance()->OnRenderProcessHostGone(host);
256 void Application::RenderProcessHostDestroyed(RenderProcessHost* host) {
257 DCHECK(render_process_host_ == host);
258 render_process_host_ = NULL;
259 web_contents_ = NULL;
262 void Application::NotifyTermination() {
263 CHECK(!render_process_host_);
264 observer_->OnApplicationTerminated(this);
267 bool Application::UseExtension(const std::string& extension_name) const {
268 // TODO(Bai): Tells whether the application contains the specified extension
272 bool Application::RegisterPermissions(const std::string& extension_name,
273 const std::string& perm_table) {
274 // TODO(Bai): Parse the permission table and fill in the name_perm_map_
275 // The perm_table format is a simple JSON string, like
276 // [{"permission_name":"echo","apis":["add","remove","get"]}]
277 scoped_ptr<base::Value> root;
278 root.reset(base::JSONReader().ReadToValue(perm_table));
279 if (root.get() == NULL || !root->IsType(base::Value::TYPE_LIST))
282 base::ListValue* permission_list = static_cast<base::ListValue*>(root.get());
283 if (permission_list->GetSize() == 0)
286 for (base::ListValue::const_iterator iter = permission_list->begin();
287 iter != permission_list->end(); ++iter) {
288 if (!(*iter)->IsType(base::Value::TYPE_DICTIONARY))
291 base::DictionaryValue* dict_val =
292 static_cast<base::DictionaryValue*>(*iter);
293 std::string permission_name;
294 if (!dict_val->GetString("permission_name", &permission_name))
297 base::ListValue* api_list = NULL;
298 if (!dict_val->GetList("apis", &api_list))
301 for (base::ListValue::const_iterator api_iter = api_list->begin();
302 api_iter != api_list->end(); ++api_iter) {
304 if (!((*api_iter)->IsType(base::Value::TYPE_STRING)
305 && (*api_iter)->GetAsString(&api)))
307 // register the permission and api
308 name_perm_map_[api] = permission_name;
309 DLOG(INFO) << "Permission Registered [PERM] " << permission_name
317 std::string Application::GetRegisteredPermissionName(
318 const std::string& extension_name,
319 const std::string& api_name) const {
320 std::map<std::string, std::string>::const_iterator iter =
321 name_perm_map_.find(api_name);
322 if (iter == name_perm_map_.end())
323 return std::string("");
327 StoredPermission Application::GetPermission(PermissionType type,
328 const std::string& permission_name) const {
329 if (type == SESSION_PERMISSION) {
330 StoredPermissionMap::const_iterator iter =
331 permission_map_.find(permission_name);
332 if (iter == permission_map_.end())
333 return UNDEFINED_STORED_PERM;
336 if (type == PERSISTENT_PERMISSION) {
337 return data_->GetPermission(permission_name);
340 return UNDEFINED_STORED_PERM;
343 bool Application::SetPermission(PermissionType type,
344 const std::string& permission_name,
345 StoredPermission perm) {
346 if (type == SESSION_PERMISSION) {
347 permission_map_[permission_name] = perm;
350 if (type == PERSISTENT_PERMISSION)
351 return data_->SetPermission(permission_name, perm);
357 void Application::InitSecurityPolicy() {
358 // CSP policy takes precedence over WARP.
359 if (data_->HasCSPDefined())
360 security_policy_.reset(new SecurityPolicyCSP(this));
361 else if (data_->GetPackageType() == Package::WGT)
362 security_policy_.reset(new SecurityPolicyWARP(this));
364 if (security_policy_)
365 security_policy_->Enforce();
368 bool Application::CanRequestURL(const GURL& url) const {
369 if (security_policy_)
370 return security_policy_->IsAccessAllowed(url);
374 base::FilePath Application::GetSplashScreenPath() {
375 return base::FilePath();
378 } // namespace application