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_storage.h"
23 #include "xwalk/application/browser/application_system.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),
56 security_mode_enabled_(false),
57 runtime_context_(runtime_context),
59 entry_point_used_(Default),
61 DCHECK(runtime_context_);
66 Application::~Application() {
68 if (render_process_host_)
69 render_process_host_->RemoveObserver(this);
72 bool Application::Launch(const LaunchParams& launch_params) {
73 if (!runtimes_.empty()) {
74 LOG(ERROR) << "Attempt to launch app: " << id()
75 << " that was already launched.";
79 CHECK(!render_process_host_);
81 GURL url = GetStartURL(launch_params, &entry_point_used_);
85 Runtime* runtime = Runtime::Create(
87 this, content::SiteInstance::CreateForURL(runtime_context_, url));
88 render_process_host_ = runtime->GetRenderProcessHost();
89 render_process_host_->AddObserver(this);
91 runtime->LoadURL(url);
93 NativeAppWindow::CreateParams params;
94 params.net_wm_pid = launch_params.launcher_pid;
95 if (data_->GetPackageType() == Package::WGT)
96 params.state = GetWindowShowStateWGT(launch_params);
98 params.state = GetWindowShowStateXPK(launch_params);
99 runtime->AttachWindow(params);
104 GURL Application::GetStartURL(const LaunchParams& params,
105 LaunchEntryPoint* used) {
106 if (params.entry_points & StartURLKey) {
107 GURL url = GetURLFromRelativePathKey(keys::kStartURLKey);
108 if (url.is_valid()) {
114 if (params.entry_points & LaunchLocalPathKey) {
115 GURL url = GetURLFromRelativePathKey(
116 GetLaunchLocalPathKey(data_->GetPackageType()));
117 if (url.is_valid()) {
118 *used = LaunchLocalPathKey;
123 if (params.entry_points & URLKey) {
124 GURL url = GetURLFromURLKey();
125 if (url.is_valid()) {
131 LOG(WARNING) << "Failed to find a valid launch URL for the app.";
135 ui::WindowShowState Application::GetWindowShowStateWGT(
136 const LaunchParams& params) {
137 if (params.force_fullscreen)
138 return ui::SHOW_STATE_FULLSCREEN;
140 const Manifest* manifest = data_->GetManifest();
141 std::string view_modes_string;
142 if (manifest->GetString(widget_keys::kViewModesKey, &view_modes_string)) {
143 // FIXME: ATM only 'fullscreen' and 'windowed' values are supported.
144 // If the first user prefererence is 'fullscreen', set window show state
145 // FULLSCREEN, otherwise set the default window show state.
146 std::vector<std::string> modes;
147 base::SplitString(view_modes_string, ' ', &modes);
148 if (!modes.empty() && modes[0] == "fullscreen")
149 return ui::SHOW_STATE_FULLSCREEN;
152 return ui::SHOW_STATE_DEFAULT;
155 ui::WindowShowState Application::GetWindowShowStateXPK(
156 const LaunchParams& params) {
157 if (params.force_fullscreen)
158 return ui::SHOW_STATE_FULLSCREEN;
160 const Manifest* manifest = data_->GetManifest();
161 std::string display_string;
162 if (manifest->GetString(keys::kDisplay, &display_string)) {
163 // FIXME: ATM only 'fullscreen' and 'standalone' (which is fallback value)
164 // values are supported.
165 if (display_string.find("fullscreen") != std::string::npos)
166 return ui::SHOW_STATE_FULLSCREEN;
169 return ui::SHOW_STATE_DEFAULT;
172 GURL Application::GetURLFromURLKey() {
173 const Manifest* manifest = data_->GetManifest();
174 std::string url_string;
175 if (!manifest->GetString(keys::kURLKey, &url_string))
178 return GURL(url_string);
181 GURL Application::GetURLFromRelativePathKey(const std::string& key) {
182 const Manifest* manifest = data_->GetManifest();
183 std::string entry_page;
184 if (!manifest->GetString(key, &entry_page)
185 || entry_page.empty()) {
186 if (data_->GetPackageType() == Package::XPK)
189 base::ThreadRestrictions::SetIOAllowed(true);
190 base::FileEnumerator iter(data_->Path(), true,
191 base::FileEnumerator::FILES,
192 FILE_PATH_LITERAL("index.*"));
193 int priority = arraysize(kDefaultWidgetEntryPage);
195 for (base::FilePath file = iter.Next(); !file.empty(); file = iter.Next()) {
196 for (int i = 0; i < arraysize(kDefaultWidgetEntryPage); ++i) {
197 if (file.BaseName().MaybeAsASCII() == kDefaultWidgetEntryPage[i] &&
199 entry_page = kDefaultWidgetEntryPage[i];
205 if (entry_page.empty())
209 return data_->GetResourceURL(entry_page);
212 void Application::Terminate() {
213 std::set<Runtime*> to_be_closed(runtimes_);
214 std::for_each(to_be_closed.begin(), to_be_closed.end(),
215 std::mem_fun(&Runtime::Close));
218 int Application::GetRenderProcessHostID() const {
219 DCHECK(render_process_host_);
220 return render_process_host_->GetID();
223 void Application::OnRuntimeAdded(Runtime* runtime) {
225 runtimes_.insert(runtime);
228 void Application::OnRuntimeRemoved(Runtime* runtime) {
230 runtimes_.erase(runtime);
232 if (runtimes_.empty()) {
233 #if defined(OS_TIZEN_MOBILE)
234 runtime->CloseRootWindow();
236 base::MessageLoop::current()->PostTask(FROM_HERE,
237 base::Bind(&Application::NotifyTermination,
238 weak_factory_.GetWeakPtr()));
243 void Application::RenderProcessExited(RenderProcessHost* host,
245 base::TerminationStatus,
247 DCHECK(render_process_host_ == host);
248 VLOG(1) << "RenderProcess id: " << host->GetID() << " is gone!";
249 XWalkRunner::GetInstance()->OnRenderProcessHostGone(host);
252 void Application::RenderProcessHostDestroyed(RenderProcessHost* host) {
253 DCHECK(render_process_host_ == host);
254 render_process_host_ = NULL;
257 void Application::NotifyTermination() {
258 CHECK(!render_process_host_);
259 observer_->OnApplicationTerminated(this);
262 bool Application::UseExtension(const std::string& extension_name) const {
263 // TODO(Bai): Tells whether the application contains the specified extension
267 bool Application::RegisterPermissions(const std::string& extension_name,
268 const std::string& perm_table) {
269 // TODO(Bai): Parse the permission table and fill in the name_perm_map_
270 // The perm_table format is a simple JSON string, like
271 // [{"permission_name":"echo","apis":["add","remove","get"]}]
272 scoped_ptr<base::Value> root;
273 root.reset(base::JSONReader().ReadToValue(perm_table));
274 if (root.get() == NULL || !root->IsType(base::Value::TYPE_LIST))
277 base::ListValue* permission_list = static_cast<base::ListValue*>(root.get());
278 if (permission_list->GetSize() == 0)
281 for (base::ListValue::const_iterator iter = permission_list->begin();
282 iter != permission_list->end(); ++iter) {
283 if (!(*iter)->IsType(base::Value::TYPE_DICTIONARY))
286 base::DictionaryValue* dict_val =
287 static_cast<base::DictionaryValue*>(*iter);
288 std::string permission_name;
289 if (!dict_val->GetString("permission_name", &permission_name))
292 base::ListValue* api_list = NULL;
293 if (!dict_val->GetList("apis", &api_list))
296 for (base::ListValue::const_iterator api_iter = api_list->begin();
297 api_iter != api_list->end(); ++api_iter) {
299 if (!((*api_iter)->IsType(base::Value::TYPE_STRING)
300 && (*api_iter)->GetAsString(&api)))
302 // register the permission and api
303 name_perm_map_[api] = permission_name;
304 DLOG(INFO) << "Permission Registered [PERM] " << permission_name
312 std::string Application::GetRegisteredPermissionName(
313 const std::string& extension_name,
314 const std::string& api_name) const {
315 std::map<std::string, std::string>::const_iterator iter =
316 name_perm_map_.find(api_name);
317 if (iter == name_perm_map_.end())
318 return std::string("");
322 StoredPermission Application::GetPermission(PermissionType type,
323 const std::string& permission_name) const {
324 if (type == SESSION_PERMISSION) {
325 StoredPermissionMap::const_iterator iter =
326 permission_map_.find(permission_name);
327 if (iter == permission_map_.end())
328 return UNDEFINED_STORED_PERM;
331 if (type == PERSISTENT_PERMISSION) {
332 return data_->GetPermission(permission_name);
335 return UNDEFINED_STORED_PERM;
338 bool Application::SetPermission(PermissionType type,
339 const std::string& permission_name,
340 StoredPermission perm) {
341 if (type == SESSION_PERMISSION) {
342 permission_map_[permission_name] = perm;
345 if (type == PERSISTENT_PERMISSION)
346 return data_->SetPermission(permission_name, perm);
352 void Application::InitSecurityPolicy() {
353 // CSP policy takes precedence over WARP.
354 if (data_->HasCSPDefined())
355 security_policy_.reset(new SecurityPolicyCSP(this));
356 else if (data_->GetPackageType() == Package::WGT)
357 security_policy_.reset(new SecurityPolicyWARP(this));
359 if (security_policy_)
360 security_policy_->Enforce();
363 bool Application::CanRequestURL(const GURL& url) const {
364 if (security_policy_)
365 return security_policy_->IsAccessAllowed(url);
369 } // namespace application