Upstream version 11.39.244.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_context.h"
26 #include "xwalk/runtime/browser/runtime_defered_ui_strategy.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 < arraysize(kDefaultWidgetEntryPage); ++i) {
60       if (file.BaseName().MaybeAsASCII() == kDefaultWidgetEntryPage[i] &&
61           i < priority) {
62         source = kDefaultWidgetEntryPage[i];
63         priority = i;
64       }
65     }
66   }
67
68   return source.empty() ? GURL() : data->GetResourceURL(source);
69 }
70
71 }  // namespace
72
73 namespace application {
74
75 scoped_ptr<Application> Application::Create(
76     scoped_refptr<ApplicationData> data,
77     RuntimeContext* context) {
78 #if defined(OS_TIZEN)
79   return make_scoped_ptr<Application>(new ApplicationTizen(data, context));
80 #else
81   return make_scoped_ptr(new Application(data, context));
82 #endif
83 }
84
85 Application::Application(
86     scoped_refptr<ApplicationData> data,
87     RuntimeContext* runtime_context)
88     : data_(data),
89       render_process_host_(NULL),
90       web_contents_(NULL),
91       security_mode_enabled_(false),
92       runtime_context_(runtime_context),
93       observer_(NULL),
94       ui_strategy_(new RuntimeDeferedUIStrategy),
95       remote_debugging_enabled_(false),
96       weak_factory_(this) {
97   DCHECK(runtime_context_);
98   DCHECK(data_.get());
99 }
100
101 Application::~Application() {
102   Terminate();
103   if (render_process_host_)
104     render_process_host_->RemoveObserver(this);
105 }
106
107 template<>
108 GURL Application::GetStartURL<Manifest::TYPE_WIDGET>() {
109 #if defined(OS_TIZEN)
110   if (data_->IsHostedApp()) {
111     std::string source;
112     data_->GetManifest()->GetString(widget_keys::kLaunchLocalPathKey, &source);
113     GURL url = GURL(source);
114
115     if (url.is_valid() && url.SchemeIsHTTPOrHTTPS())
116       return url;
117   }
118 #endif
119
120   GURL url = GetAbsoluteURLFromKey(widget_keys::kLaunchLocalPathKey);
121   if (url.is_valid())
122     return url;
123
124   LOG(WARNING) << "Failed to find start URL from the 'config.xml'"
125                << "trying to find default entry page.";
126   url = GetDefaultWidgetEntryPage(data_);
127   if (url.is_valid())
128     return url;
129
130   LOG(WARNING) << "Failed to find a valid start URL in the manifest.";
131   return GURL();
132 }
133
134 template<>
135 GURL Application::GetStartURL<Manifest::TYPE_MANIFEST>() {
136   if (data_->IsHostedApp()) {
137     std::string source;
138     data_->GetManifest()->GetString(keys::kStartURLKey, &source);
139     // Not trying to get a relative path for the "fake" application.
140     return GURL(source);
141   }
142
143   GURL url = GetAbsoluteURLFromKey(keys::kStartURLKey);
144   if (url.is_valid())
145     return url;
146
147   url = GetAbsoluteURLFromKey(keys::kLaunchLocalPathKey);
148   if (url.is_valid())
149     return url;
150
151   url = GetAbsoluteURLFromKey(keys::kDeprecatedURLKey);
152   if (url.is_valid()) {
153     LOG(WARNING) << "Deprecated key '" << keys::kDeprecatedURLKey
154         << "' found. Please migrate to using '" << keys::kStartURLKey
155         << "' instead.";
156     return url;
157   }
158
159   LOG(WARNING) << "Failed to find a valid start URL in the manifest.";
160   return GURL();
161 }
162
163
164 template<>
165 ui::WindowShowState Application::GetWindowShowState<Manifest::TYPE_WIDGET>(
166     const LaunchParams& params) {
167   if (params.force_fullscreen)
168     return ui::SHOW_STATE_FULLSCREEN;
169
170   const Manifest* manifest = data_->GetManifest();
171   std::string view_modes_string;
172   if (manifest->GetString(widget_keys::kViewModesKey, &view_modes_string)) {
173     // FIXME: ATM only 'fullscreen' and 'windowed' values are supported.
174     // If the first user prefererence is 'fullscreen', set window show state
175     // FULLSCREEN, otherwise set the default window show state.
176     std::vector<std::string> modes;
177     base::SplitString(view_modes_string, ' ', &modes);
178     if (!modes.empty() && modes[0] == "fullscreen")
179       return ui::SHOW_STATE_FULLSCREEN;
180   }
181
182   return ui::SHOW_STATE_DEFAULT;
183 }
184
185 template<>
186 ui::WindowShowState Application::GetWindowShowState<Manifest::TYPE_MANIFEST>(
187     const LaunchParams& params) {
188   if (params.force_fullscreen)
189     return ui::SHOW_STATE_FULLSCREEN;
190
191   const Manifest* manifest = data_->GetManifest();
192   std::string display_string;
193   if (manifest->GetString(keys::kDisplay, &display_string)) {
194     // FIXME: ATM only 'fullscreen' and 'standalone' (which is fallback value)
195     // values are supported.
196     if (display_string.find("fullscreen") != std::string::npos)
197       return ui::SHOW_STATE_FULLSCREEN;
198   }
199
200   return ui::SHOW_STATE_DEFAULT;
201 }
202
203 bool Application::Launch(const LaunchParams& launch_params) {
204   if (!runtimes_.empty()) {
205     LOG(ERROR) << "Attempt to launch app with id " << id()
206                << ", but it is already running.";
207     return false;
208   }
209
210   CHECK(!render_process_host_);
211   bool is_wgt = data_->manifest_type() == Manifest::TYPE_WIDGET;
212
213   GURL url = is_wgt ? GetStartURL<Manifest::TYPE_WIDGET>() :
214                       GetStartURL<Manifest::TYPE_MANIFEST>();
215   if (!url.is_valid())
216     return false;
217
218   remote_debugging_enabled_ = launch_params.remote_debugging;
219
220   Runtime* runtime = Runtime::Create(
221       runtime_context_,
222       this, content::SiteInstance::CreateForURL(runtime_context_, url));
223   render_process_host_ = runtime->GetRenderProcessHost();
224   render_process_host_->AddObserver(this);
225   web_contents_ = runtime->web_contents();
226   InitSecurityPolicy();
227   runtime->LoadURL(url);
228
229   NativeAppWindow::CreateParams params;
230   params.net_wm_pid = launch_params.launcher_pid;
231   params.state = is_wgt ?
232       GetWindowShowState<Manifest::TYPE_WIDGET>(launch_params):
233       GetWindowShowState<Manifest::TYPE_MANIFEST>(launch_params);
234   window_show_params_.state = params.state;
235
236   params.splash_screen_path = GetSplashScreenPath();
237
238   ui_strategy_->Show(runtime, params);
239
240   return true;
241 }
242
243 GURL Application::GetAbsoluteURLFromKey(const std::string& key) {
244   const Manifest* manifest = data_->GetManifest();
245   std::string source;
246
247   if (!manifest->GetString(key, &source) || source.empty())
248     return GURL();
249
250   return data_->GetResourceURL(source);
251 }
252
253 void Application::Terminate() {
254   std::set<Runtime*> to_be_closed(runtimes_);
255   std::for_each(to_be_closed.begin(), to_be_closed.end(),
256                 std::mem_fun(&Runtime::Close));
257 }
258
259 int Application::GetRenderProcessHostID() const {
260   DCHECK(render_process_host_);
261   return render_process_host_->GetID();
262 }
263
264 void Application::OnRuntimeAdded(Runtime* runtime) {
265   DCHECK(runtime);
266   runtime->set_remote_debugging_enabled(remote_debugging_enabled_);
267   if (!runtimes_.empty())
268     ui_strategy_->Show(runtime, window_show_params_);
269   runtimes_.insert(runtime);
270 }
271
272 void Application::OnRuntimeRemoved(Runtime* runtime) {
273   DCHECK(runtime);
274   runtimes_.erase(runtime);
275
276   if (runtimes_.empty())
277     base::MessageLoop::current()->PostTask(FROM_HERE,
278         base::Bind(&Application::NotifyTermination,
279                    weak_factory_.GetWeakPtr()));
280 }
281
282 void Application::RenderProcessExited(RenderProcessHost* host,
283                                       base::ProcessHandle,
284                                       base::TerminationStatus,
285                                       int) {
286   DCHECK(render_process_host_ == host);
287   VLOG(1) << "RenderProcess id: " << host->GetID() << " is gone!";
288   XWalkRunner::GetInstance()->OnRenderProcessHostGone(host);
289 }
290
291 void Application::RenderProcessHostDestroyed(RenderProcessHost* host) {
292   DCHECK(render_process_host_ == host);
293   render_process_host_ = NULL;
294   web_contents_ = NULL;
295 }
296
297 void Application::NotifyTermination() {
298   CHECK(!render_process_host_);
299   if (observer_)
300     observer_->OnApplicationTerminated(this);
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                                const 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 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 data_->SetPermission(permission_name, perm);
388
389   NOTREACHED();
390   return false;
391 }
392
393 void Application::InitSecurityPolicy() {
394   // CSP policy takes precedence over WARP.
395   if (data_->HasCSPDefined())
396     security_policy_.reset(new SecurityPolicyCSP(this));
397   else if (data_->manifest_type() == Manifest::TYPE_WIDGET)
398     security_policy_.reset(new SecurityPolicyWARP(this));
399
400   if (security_policy_)
401     security_policy_->Enforce();
402 }
403
404 bool Application::CanRequestURL(const GURL& url) const {
405   if (security_policy_)
406     return security_policy_->IsAccessAllowed(url);
407   return true;
408 }
409
410 base::FilePath Application::GetSplashScreenPath() {
411   return base::FilePath();
412 }
413
414 }  // namespace application
415 }  // namespace xwalk