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