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