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/event_names.h"
26 #include "xwalk/runtime/browser/runtime.h"
27 #include "xwalk/runtime/browser/runtime_context.h"
28 #include "xwalk/runtime/browser/xwalk_runner.h"
32 namespace keys = application_manifest_keys;
33 namespace widget_keys = application_widget_keys;
36 const char* kDefaultWidgetEntryPage[] = {
44 namespace application {
46 class FinishEventObserver : public EventObserver {
49 ApplicationEventManager* event_manager,
50 Application* application)
51 : EventObserver(event_manager),
52 application_(application) {
55 virtual void Observe(const std::string& app_id,
56 scoped_refptr<Event> event) OVERRIDE {
57 DCHECK(xwalk::application::kOnJavaScriptEventAck == event->name());
58 std::string ack_event_name;
59 event->args()->GetString(0, &ack_event_name);
60 if (ack_event_name == xwalk::application::kOnSuspend)
61 application_->CloseMainDocument();
65 Application* application_;
68 Application::Application(
69 scoped_refptr<ApplicationData> data,
70 RuntimeContext* runtime_context,
72 : runtime_context_(runtime_context),
73 application_data_(data),
76 entry_point_used_(Default),
77 termination_mode_used_(Normal),
79 DCHECK(runtime_context_);
80 DCHECK(application_data_);
84 Application::~Application() {
88 bool Application::Launch(const LaunchParams& launch_params) {
89 if (!runtimes_.empty()) {
90 LOG(ERROR) << "Attempt to launch app: " << id()
91 << " that was already launched.";
95 GURL url = GetURLForLaunch(launch_params, &entry_point_used_);
99 main_runtime_ = Runtime::Create(runtime_context_, this);
100 main_runtime_->LoadURL(url);
101 if (entry_point_used_ != AppMainKey) {
102 NativeAppWindow::CreateParams params;
103 params.net_wm_pid = launch_params.launcher_pid;
104 params.state = launch_params.window_state;
106 main_runtime_->AttachWindow(params);
112 GURL Application::GetURLForLaunch(const LaunchParams& params,
113 LaunchEntryPoint* used) {
114 if (params.entry_points & AppMainKey) {
115 GURL url = GetURLFromAppMainKey();
116 if (url.is_valid()) {
122 if (params.entry_points & LaunchLocalPathKey) {
123 GURL url = GetURLFromLocalPathKey();
124 if (url.is_valid()) {
125 *used = LaunchLocalPathKey;
130 if (params.entry_points & URLKey) {
131 GURL url = GetURLFromURLKey();
132 if (url.is_valid()) {
137 LOG(WARNING) << "Failed to find a valid launch URL for the app.";
141 GURL Application::GetURLFromAppMainKey() {
142 MainDocumentInfo* main_info = ToMainDocumentInfo(
143 application_data_->GetManifestData(keys::kAppMainKey));
147 DCHECK(application_data_->HasMainDocument());
148 return main_info->GetMainURL();
151 GURL Application::GetURLFromLocalPathKey() {
152 const Manifest* manifest = application_data_->GetManifest();
153 std::string entry_page;
154 std::string key(GetLaunchLocalPathKey(
155 application_data_->GetPackageType()));
157 if (!manifest->GetString(key, &entry_page)
158 || entry_page.empty()) {
159 if (application_data_->GetPackageType() == Manifest::TYPE_XPK)
162 base::FileEnumerator iter(application_data_->Path(), true,
163 base::FileEnumerator::FILES,
164 FILE_PATH_LITERAL("index.*"));
165 int priority = arraysize(kDefaultWidgetEntryPage);
167 for (base::FilePath file = iter.Next(); !file.empty(); file = iter.Next()) {
168 for (int i = 0; i < arraysize(kDefaultWidgetEntryPage); ++i) {
169 if (file.BaseName().MaybeAsASCII() == kDefaultWidgetEntryPage[i] &&
171 entry_page = kDefaultWidgetEntryPage[i];
177 if (entry_page.empty())
181 return application_data_->GetResourceURL(entry_page);
184 GURL Application::GetURLFromURLKey() {
185 const Manifest* manifest = application_data_->GetManifest();
186 std::string url_string;
187 if (!manifest->GetString(keys::kURLKey, &url_string))
190 return GURL(url_string);
193 void Application::Terminate(TerminationMode mode) {
194 termination_mode_used_ = mode;
195 if (IsTerminating()) {
196 LOG(WARNING) << "Attempt to Terminate app: " << id()
197 << ", which is already in the process of being terminated.";
198 if (mode == Immediate)
204 std::set<Runtime*> to_be_closed(runtimes_);
205 if (HasMainDocument() && to_be_closed.size() > 1) {
206 // The main document runtime is closed separately
207 // (needs some extra logic) in Application::OnRuntimeRemoved.
208 to_be_closed.erase(main_runtime_);
211 std::for_each(to_be_closed.begin(), to_be_closed.end(),
212 std::mem_fun(&Runtime::Close));
215 Runtime* Application::GetMainDocumentRuntime() const {
216 return HasMainDocument() ? main_runtime_ : NULL;
219 int Application::GetRenderProcessHostID() const {
220 DCHECK(main_runtime_);
221 return main_runtime_->web_contents()->
222 GetRenderProcessHost()->GetID();
225 bool Application::HasMainDocument() const {
226 return entry_point_used_ == AppMainKey;
229 void Application::OnRuntimeAdded(Runtime* runtime) {
231 runtimes_.insert(runtime);
234 void Application::OnRuntimeRemoved(Runtime* runtime) {
236 runtimes_.erase(runtime);
238 if (runtimes_.empty()) {
239 #if defined(OS_TIZEN_MOBILE)
240 runtime->CloseRootWindow();
242 base::MessageLoop::current()->PostTask(FROM_HERE,
243 base::Bind(&Application::NotifyTermination,
244 weak_factory_.GetWeakPtr()));
248 if (runtimes_.size() == 1 && HasMainDocument() &&
249 ContainsKey(runtimes_, main_runtime_)) {
250 ApplicationSystem* system = XWalkRunner::GetInstance()->app_system();
251 ApplicationEventManager* event_manager = system->event_manager();
253 // If onSuspend is not registered in main document,
254 // we close the main document immediately.
255 if (!IsOnSuspendHandlerRegistered() ||
256 termination_mode_used_ == Immediate) {
261 DCHECK(!finish_observer_);
262 finish_observer_.reset(
263 new FinishEventObserver(event_manager, this));
264 event_manager->AttachObserver(
265 application_data_->ID(), kOnJavaScriptEventAck,
266 finish_observer_.get());
268 scoped_ptr<base::ListValue> event_args(new base::ListValue);
269 scoped_refptr<Event> event = Event::CreateEvent(
270 xwalk::application::kOnSuspend, event_args.Pass());
271 event_manager->SendEvent(application_data_->ID(), event);
275 void Application::CloseMainDocument() {
276 DCHECK(main_runtime_);
278 finish_observer_.reset();
279 main_runtime_->Close();
280 main_runtime_ = NULL;
283 void Application::NotifyTermination() {
284 observer_->OnApplicationTerminated(this);
287 bool Application::IsOnSuspendHandlerRegistered() const {
288 const std::set<std::string>& events = data()->GetEvents();
289 if (events.find(kOnSuspend) == events.end())
295 bool Application::UseExtension(const std::string& extension_name) const {
296 // TODO(Bai): Tells whether the application contains the specified extension
300 bool Application::RegisterPermissions(const std::string& extension_name,
301 const std::string& perm_table) {
302 // TODO(Bai): Parse the permission table and fill in the name_perm_map_
303 // The perm_table format is a simple JSON string, like
304 // [{"permission_name":"echo","apis":["add","remove","get"]}]
305 scoped_ptr<base::Value> root;
306 root.reset(base::JSONReader().ReadToValue(perm_table));
307 if (root.get() == NULL || !root->IsType(base::Value::TYPE_LIST))
310 base::ListValue* permission_list = static_cast<base::ListValue*>(root.get());
311 if (permission_list->GetSize() == 0)
314 for (base::ListValue::const_iterator iter = permission_list->begin();
315 iter != permission_list->end(); ++iter) {
316 if (!(*iter)->IsType(base::Value::TYPE_DICTIONARY))
319 base::DictionaryValue* dict_val =
320 static_cast<base::DictionaryValue*>(*iter);
321 std::string permission_name;
322 if (!dict_val->GetString("permission_name", &permission_name))
325 base::ListValue* api_list = NULL;
326 if (!dict_val->GetList("apis", &api_list))
329 for (base::ListValue::const_iterator api_iter = api_list->begin();
330 api_iter != api_list->end(); ++api_iter) {
332 if (!((*api_iter)->IsType(base::Value::TYPE_STRING)
333 && (*api_iter)->GetAsString(&api)))
335 // register the permission and api
336 name_perm_map_[api] = permission_name;
337 DLOG(INFO) << "Permission Registered [PERM] " << permission_name
345 std::string Application::GetRegisteredPermissionName(
346 const std::string& extension_name,
347 const std::string& api_name) const {
348 std::map<std::string, std::string>::const_iterator iter =
349 name_perm_map_.find(api_name);
350 if (iter == name_perm_map_.end())
351 return std::string("");
355 StoredPermission Application::GetPermission(PermissionType type,
356 std::string& permission_name) const {
357 if (type == SESSION_PERMISSION) {
358 StoredPermissionMap::const_iterator iter =
359 permission_map_.find(permission_name);
360 if (iter == permission_map_.end())
361 return UNDEFINED_STORED_PERM;
364 if (type == PERSISTENT_PERMISSION) {
365 return application_data_->GetPermission(permission_name);
368 return UNDEFINED_STORED_PERM;
371 bool Application::SetPermission(PermissionType type,
372 const std::string& permission_name,
373 StoredPermission perm) {
374 if (type == SESSION_PERMISSION) {
375 permission_map_[permission_name] = perm;
378 if (type == PERSISTENT_PERMISSION)
379 return application_data_->SetPermission(permission_name, perm);
385 } // namespace application