Upstream version 6.34.113.0
[platform/framework/web/crosswalk.git] / src / xwalk / application / browser / application.cc
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.
4
5 #include "xwalk/application/browser/application.h"
6
7 #include <string>
8
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"
31
32 namespace xwalk {
33
34 namespace keys = application_manifest_keys;
35 namespace widget_keys = application_widget_keys;
36
37 namespace {
38 const char* kDefaultWidgetEntryPage[] = {
39 "index.html",
40 "index.htm",
41 "index.svg",
42 "index.xhtml",
43 "index.xht"};
44
45 content::RenderProcessHost* GetHost(Runtime* runtime) {
46   DCHECK(runtime);
47   return runtime->web_contents()->GetRenderProcessHost();
48 }
49 }  // namespace
50
51 namespace application {
52
53 class FinishEventObserver : public EventObserver {
54  public:
55   FinishEventObserver(
56       ApplicationEventManager* event_manager,
57       Application* application)
58       : EventObserver(event_manager),
59         application_(application) {
60   }
61
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();
69   }
70
71  private:
72   Application* application_;
73 };
74
75 Application::Application(
76     scoped_refptr<ApplicationData> data,
77     RuntimeContext* runtime_context,
78     Observer* observer)
79     : runtime_context_(runtime_context),
80       application_data_(data),
81       main_runtime_(NULL),
82       observer_(observer),
83       entry_point_used_(Default),
84       termination_mode_used_(Normal),
85       weak_factory_(this) {
86   DCHECK(runtime_context_);
87   DCHECK(application_data_);
88   DCHECK(observer_);
89 }
90
91 Application::~Application() {
92   Terminate(Immediate);
93 }
94
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.";
99     return false;
100   }
101
102   GURL url = GetURLForLaunch(launch_params, &entry_point_used_);
103   if (!url.is_valid())
104     return false;
105
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;
113
114     main_runtime_->AttachWindow(params);
115   }
116
117   return true;
118 }
119
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()) {
125       *used = AppMainKey;
126       return url;
127     }
128   }
129
130   if (params.entry_points & LaunchLocalPathKey) {
131     GURL url = GetURLFromLocalPathKey();
132     if (url.is_valid()) {
133       *used = LaunchLocalPathKey;
134       return url;
135     }
136   }
137
138   if (params.entry_points & URLKey) {
139     GURL url = GetURLFromURLKey();
140     if (url.is_valid()) {
141       *used = URLKey;
142       return url;
143     }
144   }
145   LOG(WARNING) << "Failed to find a valid launch URL for the app.";
146   return GURL();
147 }
148
149 GURL Application::GetURLFromAppMainKey() {
150   MainDocumentInfo* main_info = ToMainDocumentInfo(
151     application_data_->GetManifestData(keys::kAppMainKey));
152   if (!main_info)
153     return GURL();
154
155   DCHECK(application_data_->HasMainDocument());
156   return main_info->GetMainURL();
157 }
158
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()));
164
165   if (!manifest->GetString(key, &entry_page)
166       || entry_page.empty()) {
167     if (application_data_->GetPackageType() == Manifest::TYPE_XPK)
168       return GURL();
169
170     base::FileEnumerator iter(application_data_->Path(), true,
171                               base::FileEnumerator::FILES,
172                               FILE_PATH_LITERAL("index.*"));
173     int priority = arraysize(kDefaultWidgetEntryPage);
174
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] &&
178             i < priority) {
179           entry_page = kDefaultWidgetEntryPage[i];
180           priority = i;
181         }
182       }
183     }
184
185     if (entry_page.empty())
186       return GURL();
187   }
188
189   return application_data_->GetResourceURL(entry_page);
190 }
191
192 GURL Application::GetURLFromURLKey() {
193   const Manifest* manifest = application_data_->GetManifest();
194   std::string url_string;
195   if (!manifest->GetString(keys::kURLKey, &url_string))
196     return GURL();
197
198   return GURL(url_string);
199 }
200
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)
207       CloseMainDocument();
208
209     return;
210   }
211
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_);
217   }
218
219   std::for_each(to_be_closed.begin(), to_be_closed.end(),
220                 std::mem_fun(&Runtime::Close));
221 }
222
223 Runtime* Application::GetMainDocumentRuntime() const {
224   return HasMainDocument() ? main_runtime_ : NULL;
225 }
226
227 int Application::GetRenderProcessHostID() const {
228   DCHECK(main_runtime_);
229   return main_runtime_->web_contents()->
230           GetRenderProcessHost()->GetID();
231 }
232
233 bool Application::HasMainDocument() const {
234   return entry_point_used_ == AppMainKey;
235 }
236
237 void Application::OnRuntimeAdded(Runtime* runtime) {
238   DCHECK(runtime);
239   runtimes_.insert(runtime);
240 }
241
242 void Application::OnRuntimeRemoved(Runtime* runtime) {
243   DCHECK(runtime);
244   runtimes_.erase(runtime);
245
246   if (runtimes_.empty()) {
247 #if defined(OS_TIZEN_MOBILE)
248     runtime->CloseRootWindow();
249 #endif
250     base::MessageLoop::current()->PostTask(FROM_HERE,
251         base::Bind(&Application::NotifyTermination,
252                    weak_factory_.GetWeakPtr()));
253     return;
254   }
255
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();
260
261     // If onSuspend is not registered in main document,
262     // we close the main document immediately.
263     if (!IsOnSuspendHandlerRegistered() ||
264         termination_mode_used_ == Immediate) {
265       CloseMainDocument();
266       return;
267     }
268
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());
275
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);
280   }
281 }
282
283 void Application::CloseMainDocument() {
284   DCHECK(main_runtime_);
285
286   finish_observer_.reset();
287   main_runtime_->Close();
288   main_runtime_ = NULL;
289 }
290
291 void Application::NotifyTermination() {
292   observer_->OnApplicationTerminated(this);
293 }
294
295 bool Application::IsOnSuspendHandlerRegistered() const {
296   const std::set<std::string>& events = data()->GetEvents();
297   if (events.find(kOnSuspend) == events.end())
298     return false;
299
300   return true;
301 }
302
303 bool Application::UseExtension(const std::string& extension_name) const {
304   // TODO(Bai): Tells whether the application contains the specified extension
305   return true;
306 }
307
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))
316     return false;
317
318   base::ListValue* permission_list = static_cast<base::ListValue*>(root.get());
319   if (permission_list->GetSize() == 0)
320     return false;
321
322   for (base::ListValue::const_iterator iter = permission_list->begin();
323       iter != permission_list->end(); ++iter) {
324     if (!(*iter)->IsType(base::Value::TYPE_DICTIONARY))
325         return false;
326
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))
331       return false;
332
333     base::ListValue* api_list = NULL;
334     if (!dict_val->GetList("apis", &api_list))
335       return false;
336
337     for (base::ListValue::const_iterator api_iter = api_list->begin();
338         api_iter != api_list->end(); ++api_iter) {
339       std::string api;
340       if (!((*api_iter)->IsType(base::Value::TYPE_STRING)
341           && (*api_iter)->GetAsString(&api)))
342         return false;
343       // register the permission and api
344       name_perm_map_[api] = permission_name;
345       DLOG(INFO) << "Permission Registered [PERM] " << permission_name
346                  << " [API] " << api;
347     }
348   }
349
350   return true;
351 }
352
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("");
360   return iter->second;
361 }
362
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;
370     return iter->second;
371   }
372   if (type == PERSISTENT_PERMISSION) {
373     return application_data_->GetPermission(permission_name);
374   }
375   NOTREACHED();
376   return UNDEFINED_STORED_PERM;
377 }
378
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;
384     return true;
385   }
386   if (type == PERSISTENT_PERMISSION)
387     return application_data_->SetPermission(permission_name, perm);
388
389   NOTREACHED();
390   return false;
391 }
392
393 void Application::InitSecurityPolicy() {
394   if (application_data_->GetPackageType() != Manifest::TYPE_WGT)
395     return;
396   const WARPInfo* info = static_cast<WARPInfo*>(
397       application_data_->GetManifestData(widget_keys::kAccessKey));
398   if (!info
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()
403 #endif
404       )
405     return;
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);
413     std::string dest;
414     if (!value || !value->GetString(widget_keys::kAccessOriginKey, &dest) ||
415         dest.empty())
416       continue;
417     if (dest == "*") {
418       enable_warp_mode = false;
419       break;
420     }
421
422     GURL dest_url(dest);
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")));
429   }
430   if (enable_warp_mode)
431     GetHost(main_runtime_)->Send(new ViewMsg_EnableWarpMode());
432 }
433
434 }  // namespace application
435 }  // namespace xwalk