Upstream version 9.38.204.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 #if defined(OS_TIZEN)
32 #include "xwalk/application/browser/application_tizen.h"
33 #endif
34
35 using content::RenderProcessHost;
36
37 namespace xwalk {
38
39 namespace keys = application_manifest_keys;
40 namespace widget_keys = application_widget_keys;
41
42 namespace {
43 const char* kDefaultWidgetEntryPage[] = {
44 "index.html",
45 "index.htm",
46 "index.svg",
47 "index.xhtml",
48 "index.xht"};
49
50 GURL GetDefaultWidgetEntryPage(
51     scoped_refptr<xwalk::application::ApplicationData> data) {
52   base::ThreadRestrictions::SetIOAllowed(true);
53   base::FileEnumerator iter(
54       data->Path(), true,
55       base::FileEnumerator::FILES,
56       FILE_PATH_LITERAL("index.*"));
57   size_t priority = arraysize(kDefaultWidgetEntryPage);
58   std::string source;
59
60   for (base::FilePath file = iter.Next(); !file.empty(); file = iter.Next()) {
61     for (size_t i = 0; i < arraysize(kDefaultWidgetEntryPage); ++i) {
62       if (file.BaseName().MaybeAsASCII() == kDefaultWidgetEntryPage[i] &&
63           i < priority) {
64         source = kDefaultWidgetEntryPage[i];
65         priority = i;
66       }
67     }
68   }
69
70   return source.empty() ? GURL() : data->GetResourceURL(source);
71 }
72
73 }  // namespace
74
75 namespace application {
76
77 scoped_ptr<Application> Application::Create(
78     scoped_refptr<ApplicationData> data,
79     RuntimeContext* context) {
80 #if defined(OS_TIZEN)
81   return make_scoped_ptr<Application>(new ApplicationTizen(data, context));
82 #else
83   return make_scoped_ptr(new Application(data, context));
84 #endif
85 }
86
87 Application::Application(
88     scoped_refptr<ApplicationData> data,
89     RuntimeContext* runtime_context)
90     : data_(data),
91       render_process_host_(NULL),
92       web_contents_(NULL),
93       security_mode_enabled_(false),
94       runtime_context_(runtime_context),
95       observer_(NULL),
96       remote_debugging_enabled_(false),
97       weak_factory_(this) {
98   DCHECK(runtime_context_);
99   DCHECK(data_);
100 }
101
102 Application::~Application() {
103   Terminate();
104   if (render_process_host_)
105     render_process_host_->RemoveObserver(this);
106 }
107
108 template<>
109 GURL Application::GetStartURL<Package::WGT>() {
110   GURL url = GetAbsoluteURLFromKey(widget_keys::kLaunchLocalPathKey);
111   if (!url.is_valid()) {
112     LOG(WARNING) << "Failed to find start URL from the 'config.xml'"
113                  << "trying to find default entry page.";
114     url = GetDefaultWidgetEntryPage(data_);
115   }
116
117   if (url.is_valid()) {
118 #if defined(OS_TIZEN)
119     if (data_->IsHostedApp() && !url.SchemeIsHTTPOrHTTPS()) {
120       LOG(ERROR) << "Hosted apps are only supported with"
121                     "http:// or https:// scheme.";
122       return GURL();
123     }
124 #endif
125     return url;
126   }
127
128   LOG(WARNING) << "Failed to find a valid start URL in the manifest.";
129   return GURL();
130 }
131
132 template<>
133 GURL Application::GetStartURL<Package::XPK>() {
134   GURL url = GetAbsoluteURLFromKey(keys::kStartURLKey);
135   if (url.is_valid())
136     return url;
137
138   url = GetAbsoluteURLFromKey(keys::kLaunchLocalPathKey);
139   if (url.is_valid())
140     return url;
141
142   url = GetAbsoluteURLFromKey(keys::kDeprecatedURLKey);
143   if (url.is_valid()) {
144     LOG(WARNING) << "Deprecated key '" << keys::kDeprecatedURLKey
145         << "' found. Please migrate to using '" << keys::kStartURLKey
146         << "' instead.";
147     return url;
148   }
149
150   LOG(WARNING) << "Failed to find a valid start URL in the manifest.";
151   return GURL();
152 }
153
154
155 template<>
156 ui::WindowShowState Application::GetWindowShowState<Package::WGT>(
157     const LaunchParams& params) {
158   if (params.force_fullscreen)
159     return ui::SHOW_STATE_FULLSCREEN;
160
161   const Manifest* manifest = data_->GetManifest();
162   std::string view_modes_string;
163   if (manifest->GetString(widget_keys::kViewModesKey, &view_modes_string)) {
164     // FIXME: ATM only 'fullscreen' and 'windowed' values are supported.
165     // If the first user prefererence is 'fullscreen', set window show state
166     // FULLSCREEN, otherwise set the default window show state.
167     std::vector<std::string> modes;
168     base::SplitString(view_modes_string, ' ', &modes);
169     if (!modes.empty() && modes[0] == "fullscreen")
170       return ui::SHOW_STATE_FULLSCREEN;
171   }
172
173   return ui::SHOW_STATE_DEFAULT;
174 }
175
176 template<>
177 ui::WindowShowState Application::GetWindowShowState<Package::XPK>(
178     const LaunchParams& params) {
179   if (params.force_fullscreen)
180     return ui::SHOW_STATE_FULLSCREEN;
181
182   const Manifest* manifest = data_->GetManifest();
183   std::string display_string;
184   if (manifest->GetString(keys::kDisplay, &display_string)) {
185     // FIXME: ATM only 'fullscreen' and 'standalone' (which is fallback value)
186     // values are supported.
187     if (display_string.find("fullscreen") != std::string::npos)
188       return ui::SHOW_STATE_FULLSCREEN;
189   }
190
191   return ui::SHOW_STATE_DEFAULT;
192 }
193
194 bool Application::Launch(const LaunchParams& launch_params) {
195   if (!runtimes_.empty()) {
196     LOG(ERROR) << "Attempt to launch app with id " << id()
197                << ", but it is already running.";
198     return false;
199   }
200
201   CHECK(!render_process_host_);
202   bool is_wgt = data_->GetPackageType() == Package::WGT;
203
204   GURL url = is_wgt ? GetStartURL<Package::WGT>():
205                       GetStartURL<Package::XPK>();
206   if (!url.is_valid())
207     return false;
208
209   remote_debugging_enabled_ = launch_params.remote_debugging;
210
211   Runtime* runtime = Runtime::Create(
212       runtime_context_,
213       this, content::SiteInstance::CreateForURL(runtime_context_, url));
214   render_process_host_ = runtime->GetRenderProcessHost();
215   render_process_host_->AddObserver(this);
216   web_contents_ = runtime->web_contents();
217   InitSecurityPolicy();
218   runtime->LoadURL(url);
219
220   NativeAppWindow::CreateParams params;
221   params.net_wm_pid = launch_params.launcher_pid;
222   params.state = is_wgt ? GetWindowShowState<Package::WGT>(launch_params):
223                           GetWindowShowState<Package::XPK>(launch_params);
224
225   params.splash_screen_path = GetSplashScreenPath();
226
227   runtime->AttachWindow(params);
228
229   return true;
230 }
231
232 GURL Application::GetAbsoluteURLFromKey(const std::string& key) {
233   const Manifest* manifest = data_->GetManifest();
234   std::string source;
235
236   if (!manifest->GetString(key, &source) || source.empty())
237     return GURL();
238
239   std::size_t found = source.find("://");
240   if (found == std::string::npos)
241     return data_->GetResourceURL(source);
242   return GURL(source);
243 }
244
245 void Application::Terminate() {
246   std::set<Runtime*> to_be_closed(runtimes_);
247   std::for_each(to_be_closed.begin(), to_be_closed.end(),
248                 std::mem_fun(&Runtime::Close));
249 }
250
251 int Application::GetRenderProcessHostID() const {
252   DCHECK(render_process_host_);
253   return render_process_host_->GetID();
254 }
255
256 void Application::OnRuntimeAdded(Runtime* runtime) {
257   DCHECK(runtime);
258   runtime->set_remote_debugging_enabled(remote_debugging_enabled_);
259   runtimes_.insert(runtime);
260 }
261
262 void Application::OnRuntimeRemoved(Runtime* runtime) {
263   DCHECK(runtime);
264   runtimes_.erase(runtime);
265
266   if (runtimes_.empty()) {
267 #if defined(OS_TIZEN_MOBILE)
268     runtime->CloseRootWindow();
269 #endif
270     base::MessageLoop::current()->PostTask(FROM_HERE,
271         base::Bind(&Application::NotifyTermination,
272                    weak_factory_.GetWeakPtr()));
273   }
274 }
275
276 void Application::RenderProcessExited(RenderProcessHost* host,
277                                       base::ProcessHandle,
278                                       base::TerminationStatus,
279                                       int) {
280   DCHECK(render_process_host_ == host);
281   VLOG(1) << "RenderProcess id: " << host->GetID() << " is gone!";
282   XWalkRunner::GetInstance()->OnRenderProcessHostGone(host);
283 }
284
285 void Application::RenderProcessHostDestroyed(RenderProcessHost* host) {
286   DCHECK(render_process_host_ == host);
287   render_process_host_ = NULL;
288   web_contents_ = NULL;
289 }
290
291 void Application::NotifyTermination() {
292   CHECK(!render_process_host_);
293   if (observer_)
294     observer_->OnApplicationTerminated(this);
295 }
296
297 bool Application::UseExtension(const std::string& extension_name) const {
298   // TODO(Bai): Tells whether the application contains the specified extension
299   return true;
300 }
301
302 bool Application::RegisterPermissions(const std::string& extension_name,
303                                       const std::string& perm_table) {
304   // TODO(Bai): Parse the permission table and fill in the name_perm_map_
305   // The perm_table format is a simple JSON string, like
306   // [{"permission_name":"echo","apis":["add","remove","get"]}]
307   scoped_ptr<base::Value> root;
308   root.reset(base::JSONReader().ReadToValue(perm_table));
309   if (root.get() == NULL || !root->IsType(base::Value::TYPE_LIST))
310     return false;
311
312   base::ListValue* permission_list = static_cast<base::ListValue*>(root.get());
313   if (permission_list->GetSize() == 0)
314     return false;
315
316   for (base::ListValue::const_iterator iter = permission_list->begin();
317       iter != permission_list->end(); ++iter) {
318     if (!(*iter)->IsType(base::Value::TYPE_DICTIONARY))
319         return false;
320
321     base::DictionaryValue* dict_val =
322         static_cast<base::DictionaryValue*>(*iter);
323     std::string permission_name;
324     if (!dict_val->GetString("permission_name", &permission_name))
325       return false;
326
327     base::ListValue* api_list = NULL;
328     if (!dict_val->GetList("apis", &api_list))
329       return false;
330
331     for (base::ListValue::const_iterator api_iter = api_list->begin();
332         api_iter != api_list->end(); ++api_iter) {
333       std::string api;
334       if (!((*api_iter)->IsType(base::Value::TYPE_STRING)
335           && (*api_iter)->GetAsString(&api)))
336         return false;
337       // register the permission and api
338       name_perm_map_[api] = permission_name;
339       DLOG(INFO) << "Permission Registered [PERM] " << permission_name
340                  << " [API] " << api;
341     }
342   }
343
344   return true;
345 }
346
347 std::string Application::GetRegisteredPermissionName(
348     const std::string& extension_name,
349     const std::string& api_name) const {
350   std::map<std::string, std::string>::const_iterator iter =
351       name_perm_map_.find(api_name);
352   if (iter == name_perm_map_.end())
353     return std::string("");
354   return iter->second;
355 }
356
357 StoredPermission Application::GetPermission(PermissionType type,
358                                const std::string& permission_name) const {
359   if (type == SESSION_PERMISSION) {
360     StoredPermissionMap::const_iterator iter =
361         permission_map_.find(permission_name);
362     if (iter == permission_map_.end())
363       return UNDEFINED_STORED_PERM;
364     return iter->second;
365   }
366   if (type == PERSISTENT_PERMISSION) {
367     return data_->GetPermission(permission_name);
368   }
369   NOTREACHED();
370   return UNDEFINED_STORED_PERM;
371 }
372
373 bool Application::SetPermission(PermissionType type,
374                                 const std::string& permission_name,
375                                 StoredPermission perm) {
376   if (type == SESSION_PERMISSION) {
377     permission_map_[permission_name] = perm;
378     return true;
379   }
380   if (type == PERSISTENT_PERMISSION)
381     return data_->SetPermission(permission_name, perm);
382
383   NOTREACHED();
384   return false;
385 }
386
387 void Application::InitSecurityPolicy() {
388   // CSP policy takes precedence over WARP.
389   if (data_->HasCSPDefined())
390     security_policy_.reset(new SecurityPolicyCSP(this));
391   else if (data_->GetPackageType() == Package::WGT)
392     security_policy_.reset(new SecurityPolicyWARP(this));
393
394   if (security_policy_)
395     security_policy_->Enforce();
396 }
397
398 bool Application::CanRequestURL(const GURL& url) const {
399   if (security_policy_)
400     return security_policy_->IsAccessAllowed(url);
401   return true;
402 }
403
404 base::FilePath Application::GetSplashScreenPath() {
405   return base::FilePath();
406 }
407
408 }  // namespace application
409 }  // namespace xwalk