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