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[] = {
45 content::RenderProcessHost* GetHost(Runtime* runtime) {
47 return runtime->web_contents()->GetRenderProcessHost();
51 namespace application {
53 class FinishEventObserver : public EventObserver {
56 ApplicationEventManager* event_manager,
57 Application* application)
58 : EventObserver(event_manager),
59 application_(application) {
62 virtual void Observe(const std::string& app_id,
63 scoped_refptr<Event> event) OVERRIDE {
64 DCHECK(xwalk::application::kOnJavaScriptEventAck == event->name());
65 std::string ack_event_name;
66 event->args()->GetString(0, &ack_event_name);
67 if (ack_event_name == xwalk::application::kOnSuspend)
68 application_->CloseMainDocument();
72 Application* application_;
75 Application::Application(
76 scoped_refptr<ApplicationData> data,
77 RuntimeContext* runtime_context,
79 : runtime_context_(runtime_context),
80 application_data_(data),
83 entry_point_used_(Default),
84 termination_mode_used_(Normal),
86 DCHECK(runtime_context_);
87 DCHECK(application_data_);
91 Application::~Application() {
95 bool Application::Launch(const LaunchParams& launch_params) {
96 if (!runtimes_.empty()) {
97 LOG(ERROR) << "Attempt to launch app: " << id()
98 << " that was already launched.";
102 GURL url = GetURLForLaunch(launch_params, &entry_point_used_);
106 main_runtime_ = Runtime::Create(runtime_context_, this);
107 InitSecurityPolicy();
108 main_runtime_->LoadURL(url);
109 if (entry_point_used_ != AppMainKey) {
110 NativeAppWindow::CreateParams params;
111 params.net_wm_pid = launch_params.launcher_pid;
112 params.state = launch_params.window_state;
114 main_runtime_->AttachWindow(params);
120 GURL Application::GetURLForLaunch(const LaunchParams& params,
121 LaunchEntryPoint* used) {
122 if (params.entry_points & AppMainKey) {
123 GURL url = GetURLFromAppMainKey();
124 if (url.is_valid()) {
130 if (params.entry_points & LaunchLocalPathKey) {
131 GURL url = GetURLFromLocalPathKey();
132 if (url.is_valid()) {
133 *used = LaunchLocalPathKey;
138 if (params.entry_points & URLKey) {
139 GURL url = GetURLFromURLKey();
140 if (url.is_valid()) {
145 LOG(WARNING) << "Failed to find a valid launch URL for the app.";
149 GURL Application::GetURLFromAppMainKey() {
150 MainDocumentInfo* main_info = ToMainDocumentInfo(
151 application_data_->GetManifestData(keys::kAppMainKey));
155 DCHECK(application_data_->HasMainDocument());
156 return main_info->GetMainURL();
159 GURL Application::GetURLFromLocalPathKey() {
160 const Manifest* manifest = application_data_->GetManifest();
161 std::string entry_page;
162 std::string key(GetLaunchLocalPathKey(
163 application_data_->GetPackageType()));
165 if (!manifest->GetString(key, &entry_page)
166 || entry_page.empty()) {
167 if (application_data_->GetPackageType() == Manifest::TYPE_XPK)
170 base::FileEnumerator iter(application_data_->Path(), true,
171 base::FileEnumerator::FILES,
172 FILE_PATH_LITERAL("index.*"));
173 int priority = arraysize(kDefaultWidgetEntryPage);
175 for (base::FilePath file = iter.Next(); !file.empty(); file = iter.Next()) {
176 for (int i = 0; i < arraysize(kDefaultWidgetEntryPage); ++i) {
177 if (file.BaseName().MaybeAsASCII() == kDefaultWidgetEntryPage[i] &&
179 entry_page = kDefaultWidgetEntryPage[i];
185 if (entry_page.empty())
189 return application_data_->GetResourceURL(entry_page);
192 GURL Application::GetURLFromURLKey() {
193 const Manifest* manifest = application_data_->GetManifest();
194 std::string url_string;
195 if (!manifest->GetString(keys::kURLKey, &url_string))
198 return GURL(url_string);
201 void Application::Terminate(TerminationMode mode) {
202 termination_mode_used_ = mode;
203 if (IsTerminating()) {
204 LOG(WARNING) << "Attempt to Terminate app: " << id()
205 << ", which is already in the process of being terminated.";
206 if (mode == Immediate)
212 std::set<Runtime*> to_be_closed(runtimes_);
213 if (HasMainDocument() && to_be_closed.size() > 1) {
214 // The main document runtime is closed separately
215 // (needs some extra logic) in Application::OnRuntimeRemoved.
216 to_be_closed.erase(main_runtime_);
219 std::for_each(to_be_closed.begin(), to_be_closed.end(),
220 std::mem_fun(&Runtime::Close));
223 Runtime* Application::GetMainDocumentRuntime() const {
224 return HasMainDocument() ? main_runtime_ : NULL;
227 int Application::GetRenderProcessHostID() const {
228 DCHECK(main_runtime_);
229 return main_runtime_->web_contents()->
230 GetRenderProcessHost()->GetID();
233 bool Application::HasMainDocument() const {
234 return entry_point_used_ == AppMainKey;
237 void Application::OnRuntimeAdded(Runtime* runtime) {
239 runtimes_.insert(runtime);
242 void Application::OnRuntimeRemoved(Runtime* runtime) {
244 runtimes_.erase(runtime);
246 if (runtimes_.empty()) {
247 #if defined(OS_TIZEN_MOBILE)
248 runtime->CloseRootWindow();
250 base::MessageLoop::current()->PostTask(FROM_HERE,
251 base::Bind(&Application::NotifyTermination,
252 weak_factory_.GetWeakPtr()));
256 if (runtimes_.size() == 1 && HasMainDocument() &&
257 ContainsKey(runtimes_, main_runtime_)) {
258 ApplicationSystem* system = XWalkRunner::GetInstance()->app_system();
259 ApplicationEventManager* event_manager = system->event_manager();
261 // If onSuspend is not registered in main document,
262 // we close the main document immediately.
263 if (!IsOnSuspendHandlerRegistered() ||
264 termination_mode_used_ == Immediate) {
269 DCHECK(!finish_observer_);
270 finish_observer_.reset(
271 new FinishEventObserver(event_manager, this));
272 event_manager->AttachObserver(
273 application_data_->ID(), kOnJavaScriptEventAck,
274 finish_observer_.get());
276 scoped_ptr<base::ListValue> event_args(new base::ListValue);
277 scoped_refptr<Event> event = Event::CreateEvent(
278 xwalk::application::kOnSuspend, event_args.Pass());
279 event_manager->SendEvent(application_data_->ID(), event);
283 void Application::CloseMainDocument() {
284 DCHECK(main_runtime_);
286 finish_observer_.reset();
287 main_runtime_->Close();
288 main_runtime_ = NULL;
291 void Application::NotifyTermination() {
292 observer_->OnApplicationTerminated(this);
295 bool Application::IsOnSuspendHandlerRegistered() const {
296 const std::set<std::string>& events = data()->GetEvents();
297 if (events.find(kOnSuspend) == events.end())
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 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 application_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 application_data_->SetPermission(permission_name, perm);
393 void Application::InitSecurityPolicy() {
394 if (application_data_->GetPackageType() != Manifest::TYPE_WGT)
396 const WARPInfo* info = static_cast<WARPInfo*>(
397 application_data_->GetManifestData(widget_keys::kAccessKey));
399 #if defined(OS_TIZEN)
400 // On Tizen, CSP mode has higher priority, and WARP will be disabled
401 // if the application is under CSP mode.
402 || application_data_->HasCSPDefined()
406 GURL app_url = application_data_->URL();
407 const base::ListValue* whitelist = info->GetWARP();
408 bool enable_warp_mode = true;
409 for (base::ListValue::const_iterator it = whitelist->begin();
410 it != whitelist->end(); ++it) {
411 base::DictionaryValue* value = NULL;
412 (*it)->GetAsDictionary(&value);
414 if (!value || !value->GetString(widget_keys::kAccessOriginKey, &dest) ||
418 enable_warp_mode = false;
423 // The default subdomains attrubute should be "false".
424 std::string subdomains = "false";
425 value->GetString(widget_keys::kAccessSubdomainsKey, &subdomains);
426 GetHost(main_runtime_)->Send(
427 new ViewMsg_SetAccessWhiteList(
428 app_url, dest_url, (subdomains == "true")));
430 if (enable_warp_mode)
431 GetHost(main_runtime_)->Send(new ViewMsg_EnableWarpMode());
434 } // namespace application