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/values.h"
15 #include "content/public/browser/web_contents.h"
16 #include "content/public/browser/render_process_host.h"
17 #include "net/base/net_util.h"
18 #include "xwalk/application/browser/application_event_manager.h"
19 #include "xwalk/application/browser/application_service.h"
20 #include "xwalk/application/browser/application_storage.h"
21 #include "xwalk/application/browser/application_system.h"
22 #include "xwalk/application/common/application_manifest_constants.h"
23 #include "xwalk/application/common/constants.h"
24 #include "xwalk/application/common/manifest_handlers/main_document_handler.h"
25 #include "xwalk/application/common/manifest_handlers/warp_handler.h"
26 #include "xwalk/application/common/event_names.h"
27 #include "xwalk/runtime/browser/runtime.h"
28 #include "xwalk/runtime/browser/runtime_context.h"
29 #include "xwalk/runtime/browser/xwalk_runner.h"
30 #include "xwalk/runtime/common/xwalk_common_messages.h"
34 namespace keys = application_manifest_keys;
35 namespace widget_keys = application_widget_keys;
38 const char* kDefaultWidgetEntryPage[] = {
47 namespace application {
49 class FinishEventObserver : public EventObserver {
52 ApplicationEventManager* event_manager,
53 Application* application)
54 : EventObserver(event_manager),
55 application_(application) {
58 virtual void Observe(const std::string& app_id,
59 scoped_refptr<Event> event) OVERRIDE {
60 DCHECK(xwalk::application::kOnJavaScriptEventAck == event->name());
61 std::string ack_event_name;
62 event->args()->GetString(0, &ack_event_name);
63 if (ack_event_name == xwalk::application::kOnSuspend)
64 application_->CloseMainDocument();
68 Application* application_;
71 Application::Application(
72 scoped_refptr<ApplicationData> data,
73 RuntimeContext* runtime_context,
75 : main_runtime_(NULL),
76 application_data_(data),
77 is_security_mode_(false),
78 runtime_context_(runtime_context),
80 entry_point_used_(Default),
81 termination_mode_used_(Normal),
83 DCHECK(runtime_context_);
84 DCHECK(application_data_);
88 Application::~Application() {
92 bool Application::Launch(const LaunchParams& launch_params) {
93 if (!runtimes_.empty()) {
94 LOG(ERROR) << "Attempt to launch app: " << id()
95 << " that was already launched.";
99 GURL url = GetStartURL(launch_params, &entry_point_used_);
103 main_runtime_ = Runtime::Create(runtime_context_, this);
104 InitSecurityPolicy();
105 main_runtime_->LoadURL(url);
106 if (entry_point_used_ != AppMainKey) {
107 NativeAppWindow::CreateParams params;
108 params.net_wm_pid = launch_params.launcher_pid;
109 params.state = GetWindowShowState(launch_params);
110 main_runtime_->AttachWindow(params);
116 GURL Application::GetStartURL(const LaunchParams& params,
117 LaunchEntryPoint* used) {
118 if (params.entry_points & StartURLKey) {
119 GURL url = GetURLFromRelativePathKey(keys::kStartURLKey);
120 if (url.is_valid()) {
126 if (params.entry_points & AppMainKey) {
127 GURL url = GetURLFromAppMainKey();
128 if (url.is_valid()) {
134 if (params.entry_points & LaunchLocalPathKey) {
135 GURL url = GetURLFromRelativePathKey(
136 GetLaunchLocalPathKey(application_data_->GetPackageType()));
137 if (url.is_valid()) {
138 *used = LaunchLocalPathKey;
143 if (params.entry_points & URLKey) {
144 GURL url = GetURLFromURLKey();
145 if (url.is_valid()) {
151 LOG(WARNING) << "Failed to find a valid launch URL for the app.";
155 GURL Application::GetURLFromAppMainKey() {
156 MainDocumentInfo* main_info = ToMainDocumentInfo(
157 application_data_->GetManifestData(keys::kAppMainKey));
161 DCHECK(application_data_->HasMainDocument());
162 return main_info->GetMainURL();
165 ui::WindowShowState Application::GetWindowShowState(
166 const LaunchParams& params) {
167 if (params.force_fullscreen)
168 return ui::SHOW_STATE_FULLSCREEN;
170 const Manifest* manifest = application_data_->GetManifest();
171 std::string display_string;
172 if (manifest->GetString(keys::kDisplay, &display_string)) {
173 // FIXME: ATM only 'fullscreen' and 'standalone' (which is fallback value)
174 // values are supported.
175 if (display_string.find("fullscreen") != std::string::npos)
176 return ui::SHOW_STATE_FULLSCREEN;
179 return ui::SHOW_STATE_DEFAULT;
182 GURL Application::GetURLFromURLKey() {
183 const Manifest* manifest = application_data_->GetManifest();
184 std::string url_string;
185 if (!manifest->GetString(keys::kURLKey, &url_string))
188 return GURL(url_string);
191 GURL Application::GetURLFromRelativePathKey(const std::string& key) {
192 const Manifest* manifest = application_data_->GetManifest();
193 std::string entry_page;
194 if (!manifest->GetString(key, &entry_page)
195 || entry_page.empty()) {
196 if (application_data_->GetPackageType() == Manifest::TYPE_XPK)
199 base::FileEnumerator iter(application_data_->Path(), true,
200 base::FileEnumerator::FILES,
201 FILE_PATH_LITERAL("index.*"));
202 int priority = arraysize(kDefaultWidgetEntryPage);
204 for (base::FilePath file = iter.Next(); !file.empty(); file = iter.Next()) {
205 for (int i = 0; i < arraysize(kDefaultWidgetEntryPage); ++i) {
206 if (file.BaseName().MaybeAsASCII() == kDefaultWidgetEntryPage[i] &&
208 entry_page = kDefaultWidgetEntryPage[i];
214 if (entry_page.empty())
218 return application_data_->GetResourceURL(entry_page);
221 void Application::Terminate(TerminationMode mode) {
222 termination_mode_used_ = mode;
223 if (IsTerminating()) {
224 LOG(WARNING) << "Attempt to Terminate app: " << id()
225 << ", which is already in the process of being terminated.";
226 if (mode == Immediate)
232 std::set<Runtime*> to_be_closed(runtimes_);
233 if (HasMainDocument() && to_be_closed.size() > 1) {
234 // The main document runtime is closed separately
235 // (needs some extra logic) in Application::OnRuntimeRemoved.
236 to_be_closed.erase(main_runtime_);
239 std::for_each(to_be_closed.begin(), to_be_closed.end(),
240 std::mem_fun(&Runtime::Close));
243 Runtime* Application::GetMainDocumentRuntime() const {
244 return HasMainDocument() ? main_runtime_ : NULL;
247 int Application::GetRenderProcessHostID() const {
248 DCHECK(main_runtime_);
249 return main_runtime_->web_contents()->
250 GetRenderProcessHost()->GetID();
253 bool Application::HasMainDocument() const {
254 return entry_point_used_ == AppMainKey;
257 void Application::OnRuntimeAdded(Runtime* runtime) {
259 runtimes_.insert(runtime);
262 void Application::OnRuntimeRemoved(Runtime* runtime) {
264 runtimes_.erase(runtime);
266 if (runtimes_.empty()) {
267 #if defined(OS_TIZEN_MOBILE)
268 runtime->CloseRootWindow();
270 base::MessageLoop::current()->PostTask(FROM_HERE,
271 base::Bind(&Application::NotifyTermination,
272 weak_factory_.GetWeakPtr()));
276 if (runtimes_.size() == 1 && HasMainDocument() &&
277 ContainsKey(runtimes_, main_runtime_)) {
278 ApplicationSystem* system = XWalkRunner::GetInstance()->app_system();
279 ApplicationEventManager* event_manager = system->event_manager();
281 // If onSuspend is not registered in main document,
282 // we close the main document immediately.
283 if (!IsOnSuspendHandlerRegistered() ||
284 termination_mode_used_ == Immediate) {
289 DCHECK(!finish_observer_);
290 finish_observer_.reset(
291 new FinishEventObserver(event_manager, this));
292 event_manager->AttachObserver(
293 application_data_->ID(), kOnJavaScriptEventAck,
294 finish_observer_.get());
296 scoped_ptr<base::ListValue> event_args(new base::ListValue);
297 scoped_refptr<Event> event = Event::CreateEvent(
298 xwalk::application::kOnSuspend, event_args.Pass());
299 event_manager->SendEvent(application_data_->ID(), event);
303 void Application::CloseMainDocument() {
304 DCHECK(main_runtime_);
306 finish_observer_.reset();
307 main_runtime_->Close();
308 main_runtime_ = NULL;
311 void Application::NotifyTermination() {
312 observer_->OnApplicationTerminated(this);
315 bool Application::IsOnSuspendHandlerRegistered() const {
316 const std::set<std::string>& events = data()->GetEvents();
317 if (events.find(kOnSuspend) == events.end())
323 bool Application::UseExtension(const std::string& extension_name) const {
324 // TODO(Bai): Tells whether the application contains the specified extension
328 bool Application::RegisterPermissions(const std::string& extension_name,
329 const std::string& perm_table) {
330 // TODO(Bai): Parse the permission table and fill in the name_perm_map_
331 // The perm_table format is a simple JSON string, like
332 // [{"permission_name":"echo","apis":["add","remove","get"]}]
333 scoped_ptr<base::Value> root;
334 root.reset(base::JSONReader().ReadToValue(perm_table));
335 if (root.get() == NULL || !root->IsType(base::Value::TYPE_LIST))
338 base::ListValue* permission_list = static_cast<base::ListValue*>(root.get());
339 if (permission_list->GetSize() == 0)
342 for (base::ListValue::const_iterator iter = permission_list->begin();
343 iter != permission_list->end(); ++iter) {
344 if (!(*iter)->IsType(base::Value::TYPE_DICTIONARY))
347 base::DictionaryValue* dict_val =
348 static_cast<base::DictionaryValue*>(*iter);
349 std::string permission_name;
350 if (!dict_val->GetString("permission_name", &permission_name))
353 base::ListValue* api_list = NULL;
354 if (!dict_val->GetList("apis", &api_list))
357 for (base::ListValue::const_iterator api_iter = api_list->begin();
358 api_iter != api_list->end(); ++api_iter) {
360 if (!((*api_iter)->IsType(base::Value::TYPE_STRING)
361 && (*api_iter)->GetAsString(&api)))
363 // register the permission and api
364 name_perm_map_[api] = permission_name;
365 DLOG(INFO) << "Permission Registered [PERM] " << permission_name
373 std::string Application::GetRegisteredPermissionName(
374 const std::string& extension_name,
375 const std::string& api_name) const {
376 std::map<std::string, std::string>::const_iterator iter =
377 name_perm_map_.find(api_name);
378 if (iter == name_perm_map_.end())
379 return std::string("");
383 StoredPermission Application::GetPermission(PermissionType type,
384 std::string& permission_name) const {
385 if (type == SESSION_PERMISSION) {
386 StoredPermissionMap::const_iterator iter =
387 permission_map_.find(permission_name);
388 if (iter == permission_map_.end())
389 return UNDEFINED_STORED_PERM;
392 if (type == PERSISTENT_PERMISSION) {
393 return application_data_->GetPermission(permission_name);
396 return UNDEFINED_STORED_PERM;
399 bool Application::SetPermission(PermissionType type,
400 const std::string& permission_name,
401 StoredPermission perm) {
402 if (type == SESSION_PERMISSION) {
403 permission_map_[permission_name] = perm;
406 if (type == PERSISTENT_PERMISSION)
407 return application_data_->SetPermission(permission_name, perm);
413 void Application::InitSecurityPolicy() {
414 if (application_data_->GetPackageType() != Manifest::TYPE_WGT)
417 const WARPInfo* info = static_cast<WARPInfo*>(
418 application_data_->GetManifestData(widget_keys::kAccessKey));
419 // FIXME(xinchao): Need to enable WARP mode by default.
423 const base::ListValue* whitelist = info->GetWARP();
424 for (base::ListValue::const_iterator it = whitelist->begin();
425 it != whitelist->end(); ++it) {
426 base::DictionaryValue* value = NULL;
427 (*it)->GetAsDictionary(&value);
429 if (!value || !value->GetString(widget_keys::kAccessOriginKey, &dest) ||
433 is_security_mode_ = false;
438 // The default subdomains attrubute should be "false".
439 std::string subdomains = "false";
440 value->GetString(widget_keys::kAccessSubdomainsKey, &subdomains);
441 AddSecurityPolicy(dest_url, (subdomains == "true"));
442 is_security_mode_ = true;
444 if (is_security_mode_)
445 main_runtime_->GetRenderProcessHost()->Send(
446 new ViewMsg_EnableSecurityMode(
447 ApplicationData::GetBaseURLFromApplicationId(id()),
448 SecurityPolicy::WARP));
451 void Application::AddSecurityPolicy(const GURL& url, bool subdomains) {
452 GURL app_url = application_data_->URL();
453 main_runtime_->GetRenderProcessHost()->Send(
454 new ViewMsg_SetAccessWhiteList(
455 app_url, url, subdomains));
456 security_policy_.push_back(new SecurityPolicy(url, subdomains));
459 bool Application::CanRequestURL(const GURL& url) const {
460 if (!is_security_mode_)
463 // Only WGT package need to check the url request permission.
464 if (application_data_->GetPackageType() != Manifest::TYPE_WGT)
467 // Always can request itself resources.
468 if (url.SchemeIs(application::kApplicationScheme) &&
472 for (unsigned i = 0; i < security_policy_.size(); ++i) {
473 const GURL& policy = security_policy_[i]->url();
474 bool subdomains = security_policy_[i]->subdomains();
475 bool is_host_matched = subdomains ?
476 url.DomainIs(policy.host().c_str()) : url.host() == policy.host();
477 if (url.scheme() == policy.scheme() && is_host_matched)
483 } // namespace application