Upstream version 7.36.153.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/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"
30
31 using content::RenderProcessHost;
32
33 namespace xwalk {
34
35 namespace keys = application_manifest_keys;
36 namespace widget_keys = application_widget_keys;
37
38 namespace {
39 const char* kDefaultWidgetEntryPage[] = {
40 "index.html",
41 "index.htm",
42 "index.svg",
43 "index.xhtml",
44 "index.xht"};
45
46 }  // namespace
47
48 namespace application {
49
50 Application::Application(
51     scoped_refptr<ApplicationData> data,
52     RuntimeContext* runtime_context,
53     Observer* observer)
54     : data_(data),
55       render_process_host_(NULL),
56       security_mode_enabled_(false),
57       runtime_context_(runtime_context),
58       observer_(observer),
59       entry_point_used_(Default),
60       weak_factory_(this) {
61   DCHECK(runtime_context_);
62   DCHECK(data_);
63   DCHECK(observer_);
64 }
65
66 Application::~Application() {
67   Terminate();
68   if (render_process_host_)
69     render_process_host_->RemoveObserver(this);
70 }
71
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.";
76     return false;
77   }
78
79   CHECK(!render_process_host_);
80
81   GURL url = GetStartURL(launch_params, &entry_point_used_);
82   if (!url.is_valid())
83     return false;
84
85   Runtime* runtime = Runtime::Create(
86       runtime_context_,
87       this, content::SiteInstance::CreateForURL(runtime_context_, url));
88   render_process_host_ = runtime->GetRenderProcessHost();
89   render_process_host_->AddObserver(this);
90   InitSecurityPolicy();
91   runtime->LoadURL(url);
92
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);
97   else
98     params.state = GetWindowShowStateXPK(launch_params);
99   runtime->AttachWindow(params);
100
101   return true;
102 }
103
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()) {
109       *used = StartURLKey;
110       return url;
111     }
112   }
113
114   if (params.entry_points & LaunchLocalPathKey) {
115     GURL url = GetURLFromRelativePathKey(
116         GetLaunchLocalPathKey(data_->GetPackageType()));
117     if (url.is_valid()) {
118       *used = LaunchLocalPathKey;
119       return url;
120     }
121   }
122
123   if (params.entry_points & URLKey) {
124     GURL url = GetURLFromURLKey();
125     if (url.is_valid()) {
126       *used = URLKey;
127       return url;
128     }
129   }
130
131   LOG(WARNING) << "Failed to find a valid launch URL for the app.";
132   return GURL();
133 }
134
135 ui::WindowShowState Application::GetWindowShowStateWGT(
136     const LaunchParams& params) {
137   if (params.force_fullscreen)
138     return ui::SHOW_STATE_FULLSCREEN;
139
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;
150   }
151
152   return ui::SHOW_STATE_DEFAULT;
153 }
154
155 ui::WindowShowState Application::GetWindowShowStateXPK(
156     const LaunchParams& params) {
157   if (params.force_fullscreen)
158     return ui::SHOW_STATE_FULLSCREEN;
159
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;
167   }
168
169   return ui::SHOW_STATE_DEFAULT;
170 }
171
172 GURL Application::GetURLFromURLKey() {
173   const Manifest* manifest = data_->GetManifest();
174   std::string url_string;
175   if (!manifest->GetString(keys::kURLKey, &url_string))
176     return GURL();
177
178   return GURL(url_string);
179 }
180
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)
187       return GURL();
188
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);
194
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] &&
198             i < priority) {
199           entry_page = kDefaultWidgetEntryPage[i];
200           priority = i;
201         }
202       }
203     }
204
205     if (entry_page.empty())
206       return GURL();
207   }
208
209   return data_->GetResourceURL(entry_page);
210 }
211
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));
216 }
217
218 int Application::GetRenderProcessHostID() const {
219   DCHECK(render_process_host_);
220   return render_process_host_->GetID();
221 }
222
223 void Application::OnRuntimeAdded(Runtime* runtime) {
224   DCHECK(runtime);
225   runtimes_.insert(runtime);
226 }
227
228 void Application::OnRuntimeRemoved(Runtime* runtime) {
229   DCHECK(runtime);
230   runtimes_.erase(runtime);
231
232   if (runtimes_.empty()) {
233 #if defined(OS_TIZEN_MOBILE)
234     runtime->CloseRootWindow();
235 #endif
236     base::MessageLoop::current()->PostTask(FROM_HERE,
237         base::Bind(&Application::NotifyTermination,
238                    weak_factory_.GetWeakPtr()));
239     return;
240   }
241 }
242
243 void Application::RenderProcessExited(RenderProcessHost* host,
244                                       base::ProcessHandle,
245                                       base::TerminationStatus,
246                                       int) {
247   DCHECK(render_process_host_ == host);
248   VLOG(1) << "RenderProcess id: " << host->GetID() << " is gone!";
249   XWalkRunner::GetInstance()->OnRenderProcessHostGone(host);
250 }
251
252 void Application::RenderProcessHostDestroyed(RenderProcessHost* host) {
253   DCHECK(render_process_host_ == host);
254   render_process_host_ = NULL;
255 }
256
257 void Application::NotifyTermination() {
258   CHECK(!render_process_host_);
259   observer_->OnApplicationTerminated(this);
260 }
261
262 bool Application::UseExtension(const std::string& extension_name) const {
263   // TODO(Bai): Tells whether the application contains the specified extension
264   return true;
265 }
266
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))
275     return false;
276
277   base::ListValue* permission_list = static_cast<base::ListValue*>(root.get());
278   if (permission_list->GetSize() == 0)
279     return false;
280
281   for (base::ListValue::const_iterator iter = permission_list->begin();
282       iter != permission_list->end(); ++iter) {
283     if (!(*iter)->IsType(base::Value::TYPE_DICTIONARY))
284         return false;
285
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))
290       return false;
291
292     base::ListValue* api_list = NULL;
293     if (!dict_val->GetList("apis", &api_list))
294       return false;
295
296     for (base::ListValue::const_iterator api_iter = api_list->begin();
297         api_iter != api_list->end(); ++api_iter) {
298       std::string api;
299       if (!((*api_iter)->IsType(base::Value::TYPE_STRING)
300           && (*api_iter)->GetAsString(&api)))
301         return false;
302       // register the permission and api
303       name_perm_map_[api] = permission_name;
304       DLOG(INFO) << "Permission Registered [PERM] " << permission_name
305                  << " [API] " << api;
306     }
307   }
308
309   return true;
310 }
311
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("");
319   return iter->second;
320 }
321
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;
329     return iter->second;
330   }
331   if (type == PERSISTENT_PERMISSION) {
332     return data_->GetPermission(permission_name);
333   }
334   NOTREACHED();
335   return UNDEFINED_STORED_PERM;
336 }
337
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;
343     return true;
344   }
345   if (type == PERSISTENT_PERMISSION)
346     return data_->SetPermission(permission_name, perm);
347
348   NOTREACHED();
349   return false;
350 }
351
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));
358
359   if (security_policy_)
360     security_policy_->Enforce();
361 }
362
363 bool Application::CanRequestURL(const GURL& url) const {
364   if (security_policy_)
365     return security_policy_->IsAccessAllowed(url);
366   return true;
367 }
368
369 }  // namespace application
370 }  // namespace xwalk