Upstream version 8.36.171.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_system.h"
23 #include "xwalk/application/common/application_storage.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
100   params.splash_screen_path = GetSplashScreenPath();
101
102   runtime->AttachWindow(params);
103
104   return true;
105 }
106
107 GURL Application::GetStartURL(const LaunchParams& params,
108                                   LaunchEntryPoint* used) {
109   if (params.entry_points & StartURLKey) {
110     GURL url = GetURLFromRelativePathKey(keys::kStartURLKey);
111     if (url.is_valid()) {
112       *used = StartURLKey;
113       return url;
114     }
115   }
116
117   if (params.entry_points & LaunchLocalPathKey) {
118     GURL url = GetURLFromRelativePathKey(
119         GetLaunchLocalPathKey(data_->GetPackageType()));
120     if (url.is_valid()) {
121       *used = LaunchLocalPathKey;
122       return url;
123     }
124   }
125
126   if (params.entry_points & URLKey) {
127     GURL url = GetURLFromURLKey();
128     if (url.is_valid()) {
129       *used = URLKey;
130       return url;
131     }
132   }
133
134   LOG(WARNING) << "Failed to find a valid launch URL for the app.";
135   return GURL();
136 }
137
138 ui::WindowShowState Application::GetWindowShowStateWGT(
139     const LaunchParams& params) {
140   if (params.force_fullscreen)
141     return ui::SHOW_STATE_FULLSCREEN;
142
143   const Manifest* manifest = data_->GetManifest();
144   std::string view_modes_string;
145   if (manifest->GetString(widget_keys::kViewModesKey, &view_modes_string)) {
146     // FIXME: ATM only 'fullscreen' and 'windowed' values are supported.
147     // If the first user prefererence is 'fullscreen', set window show state
148     // FULLSCREEN, otherwise set the default window show state.
149     std::vector<std::string> modes;
150     base::SplitString(view_modes_string, ' ', &modes);
151     if (!modes.empty() && modes[0] == "fullscreen")
152       return ui::SHOW_STATE_FULLSCREEN;
153   }
154
155   return ui::SHOW_STATE_DEFAULT;
156 }
157
158 ui::WindowShowState Application::GetWindowShowStateXPK(
159     const LaunchParams& params) {
160   if (params.force_fullscreen)
161     return ui::SHOW_STATE_FULLSCREEN;
162
163   const Manifest* manifest = data_->GetManifest();
164   std::string display_string;
165   if (manifest->GetString(keys::kDisplay, &display_string)) {
166     // FIXME: ATM only 'fullscreen' and 'standalone' (which is fallback value)
167     // values are supported.
168     if (display_string.find("fullscreen") != std::string::npos)
169       return ui::SHOW_STATE_FULLSCREEN;
170   }
171
172   return ui::SHOW_STATE_DEFAULT;
173 }
174
175 GURL Application::GetURLFromURLKey() {
176   const Manifest* manifest = data_->GetManifest();
177   std::string url_string;
178   if (!manifest->GetString(keys::kURLKey, &url_string))
179     return GURL();
180
181   return GURL(url_string);
182 }
183
184 GURL Application::GetURLFromRelativePathKey(const std::string& key) {
185   const Manifest* manifest = data_->GetManifest();
186   std::string entry_page;
187   if (!manifest->GetString(key, &entry_page)
188       || entry_page.empty()) {
189     if (data_->GetPackageType() == Package::XPK)
190       return GURL();
191
192     base::ThreadRestrictions::SetIOAllowed(true);
193     base::FileEnumerator iter(data_->Path(), true,
194                               base::FileEnumerator::FILES,
195                               FILE_PATH_LITERAL("index.*"));
196     int priority = arraysize(kDefaultWidgetEntryPage);
197
198     for (base::FilePath file = iter.Next(); !file.empty(); file = iter.Next()) {
199       for (size_t i = 0; i < arraysize(kDefaultWidgetEntryPage); ++i) {
200         if (file.BaseName().MaybeAsASCII() == kDefaultWidgetEntryPage[i] &&
201             i < priority) {
202           entry_page = kDefaultWidgetEntryPage[i];
203           priority = i;
204         }
205       }
206     }
207
208     if (entry_page.empty())
209       return GURL();
210   }
211
212   return data_->GetResourceURL(entry_page);
213 }
214
215 void Application::Terminate() {
216   std::set<Runtime*> to_be_closed(runtimes_);
217   std::for_each(to_be_closed.begin(), to_be_closed.end(),
218                 std::mem_fun(&Runtime::Close));
219 }
220
221 int Application::GetRenderProcessHostID() const {
222   DCHECK(render_process_host_);
223   return render_process_host_->GetID();
224 }
225
226 void Application::OnRuntimeAdded(Runtime* runtime) {
227   DCHECK(runtime);
228   runtimes_.insert(runtime);
229 }
230
231 void Application::OnRuntimeRemoved(Runtime* runtime) {
232   DCHECK(runtime);
233   runtimes_.erase(runtime);
234
235   if (runtimes_.empty()) {
236 #if defined(OS_TIZEN_MOBILE)
237     runtime->CloseRootWindow();
238 #endif
239     base::MessageLoop::current()->PostTask(FROM_HERE,
240         base::Bind(&Application::NotifyTermination,
241                    weak_factory_.GetWeakPtr()));
242     return;
243   }
244 }
245
246 void Application::RenderProcessExited(RenderProcessHost* host,
247                                       base::ProcessHandle,
248                                       base::TerminationStatus,
249                                       int) {
250   DCHECK(render_process_host_ == host);
251   VLOG(1) << "RenderProcess id: " << host->GetID() << " is gone!";
252   XWalkRunner::GetInstance()->OnRenderProcessHostGone(host);
253 }
254
255 void Application::RenderProcessHostDestroyed(RenderProcessHost* host) {
256   DCHECK(render_process_host_ == host);
257   render_process_host_ = NULL;
258 }
259
260 void Application::NotifyTermination() {
261   CHECK(!render_process_host_);
262   observer_->OnApplicationTerminated(this);
263 }
264
265 bool Application::UseExtension(const std::string& extension_name) const {
266   // TODO(Bai): Tells whether the application contains the specified extension
267   return true;
268 }
269
270 bool Application::RegisterPermissions(const std::string& extension_name,
271                                       const std::string& perm_table) {
272   // TODO(Bai): Parse the permission table and fill in the name_perm_map_
273   // The perm_table format is a simple JSON string, like
274   // [{"permission_name":"echo","apis":["add","remove","get"]}]
275   scoped_ptr<base::Value> root;
276   root.reset(base::JSONReader().ReadToValue(perm_table));
277   if (root.get() == NULL || !root->IsType(base::Value::TYPE_LIST))
278     return false;
279
280   base::ListValue* permission_list = static_cast<base::ListValue*>(root.get());
281   if (permission_list->GetSize() == 0)
282     return false;
283
284   for (base::ListValue::const_iterator iter = permission_list->begin();
285       iter != permission_list->end(); ++iter) {
286     if (!(*iter)->IsType(base::Value::TYPE_DICTIONARY))
287         return false;
288
289     base::DictionaryValue* dict_val =
290         static_cast<base::DictionaryValue*>(*iter);
291     std::string permission_name;
292     if (!dict_val->GetString("permission_name", &permission_name))
293       return false;
294
295     base::ListValue* api_list = NULL;
296     if (!dict_val->GetList("apis", &api_list))
297       return false;
298
299     for (base::ListValue::const_iterator api_iter = api_list->begin();
300         api_iter != api_list->end(); ++api_iter) {
301       std::string api;
302       if (!((*api_iter)->IsType(base::Value::TYPE_STRING)
303           && (*api_iter)->GetAsString(&api)))
304         return false;
305       // register the permission and api
306       name_perm_map_[api] = permission_name;
307       DLOG(INFO) << "Permission Registered [PERM] " << permission_name
308                  << " [API] " << api;
309     }
310   }
311
312   return true;
313 }
314
315 std::string Application::GetRegisteredPermissionName(
316     const std::string& extension_name,
317     const std::string& api_name) const {
318   std::map<std::string, std::string>::const_iterator iter =
319       name_perm_map_.find(api_name);
320   if (iter == name_perm_map_.end())
321     return std::string("");
322   return iter->second;
323 }
324
325 StoredPermission Application::GetPermission(PermissionType type,
326                                const std::string& permission_name) const {
327   if (type == SESSION_PERMISSION) {
328     StoredPermissionMap::const_iterator iter =
329         permission_map_.find(permission_name);
330     if (iter == permission_map_.end())
331       return UNDEFINED_STORED_PERM;
332     return iter->second;
333   }
334   if (type == PERSISTENT_PERMISSION) {
335     return data_->GetPermission(permission_name);
336   }
337   NOTREACHED();
338   return UNDEFINED_STORED_PERM;
339 }
340
341 bool Application::SetPermission(PermissionType type,
342                                 const std::string& permission_name,
343                                 StoredPermission perm) {
344   if (type == SESSION_PERMISSION) {
345     permission_map_[permission_name] = perm;
346     return true;
347   }
348   if (type == PERSISTENT_PERMISSION)
349     return data_->SetPermission(permission_name, perm);
350
351   NOTREACHED();
352   return false;
353 }
354
355 void Application::InitSecurityPolicy() {
356   // CSP policy takes precedence over WARP.
357   if (data_->HasCSPDefined())
358     security_policy_.reset(new SecurityPolicyCSP(this));
359   else if (data_->GetPackageType() == Package::WGT)
360     security_policy_.reset(new SecurityPolicyWARP(this));
361
362   if (security_policy_)
363     security_policy_->Enforce();
364 }
365
366 bool Application::CanRequestURL(const GURL& url) const {
367   if (security_policy_)
368     return security_policy_->IsAccessAllowed(url);
369   return true;
370 }
371
372 base::FilePath Application::GetSplashScreenPath() {
373   return base::FilePath();
374 }
375
376 }  // namespace application
377 }  // namespace xwalk