101c26e3893f7ce406a6a419d6558c476ce10e58
[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_);
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 = GetURLFromRelativePathKey(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 = GetURLFromRelativePathKey(
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     GURL url = GetURLFromURLKey();
130     if (url.is_valid()) {
131       *used = URLKey;
132       return url;
133     }
134   }
135
136   LOG(WARNING) << "Failed to find a valid launch URL for the app.";
137   return GURL();
138 }
139
140 ui::WindowShowState Application::GetWindowShowStateWGT(
141     const LaunchParams& params) {
142   if (params.force_fullscreen)
143     return ui::SHOW_STATE_FULLSCREEN;
144
145   const Manifest* manifest = data_->GetManifest();
146   std::string view_modes_string;
147   if (manifest->GetString(widget_keys::kViewModesKey, &view_modes_string)) {
148     // FIXME: ATM only 'fullscreen' and 'windowed' values are supported.
149     // If the first user prefererence is 'fullscreen', set window show state
150     // FULLSCREEN, otherwise set the default window show state.
151     std::vector<std::string> modes;
152     base::SplitString(view_modes_string, ' ', &modes);
153     if (!modes.empty() && modes[0] == "fullscreen")
154       return ui::SHOW_STATE_FULLSCREEN;
155   }
156
157   return ui::SHOW_STATE_DEFAULT;
158 }
159
160 ui::WindowShowState Application::GetWindowShowStateXPK(
161     const LaunchParams& params) {
162   if (params.force_fullscreen)
163     return ui::SHOW_STATE_FULLSCREEN;
164
165   const Manifest* manifest = data_->GetManifest();
166   std::string display_string;
167   if (manifest->GetString(keys::kDisplay, &display_string)) {
168     // FIXME: ATM only 'fullscreen' and 'standalone' (which is fallback value)
169     // values are supported.
170     if (display_string.find("fullscreen") != std::string::npos)
171       return ui::SHOW_STATE_FULLSCREEN;
172   }
173
174   return ui::SHOW_STATE_DEFAULT;
175 }
176
177 GURL Application::GetURLFromURLKey() {
178   const Manifest* manifest = data_->GetManifest();
179   std::string url_string;
180   if (!manifest->GetString(keys::kURLKey, &url_string))
181     return GURL();
182
183   return GURL(url_string);
184 }
185
186 GURL Application::GetURLFromRelativePathKey(const std::string& key) {
187   const Manifest* manifest = data_->GetManifest();
188   std::string entry_page;
189   if (!manifest->GetString(key, &entry_page)
190       || entry_page.empty()) {
191     if (data_->GetPackageType() == Package::XPK)
192       return GURL();
193
194     base::ThreadRestrictions::SetIOAllowed(true);
195     base::FileEnumerator iter(data_->Path(), true,
196                               base::FileEnumerator::FILES,
197                               FILE_PATH_LITERAL("index.*"));
198     int priority = arraysize(kDefaultWidgetEntryPage);
199
200     for (base::FilePath file = iter.Next(); !file.empty(); file = iter.Next()) {
201       for (size_t i = 0; i < arraysize(kDefaultWidgetEntryPage); ++i) {
202         if (file.BaseName().MaybeAsASCII() == kDefaultWidgetEntryPage[i] &&
203             i < priority) {
204           entry_page = kDefaultWidgetEntryPage[i];
205           priority = i;
206         }
207       }
208     }
209
210     if (entry_page.empty())
211       return GURL();
212   }
213
214   return data_->GetResourceURL(entry_page);
215 }
216
217 void Application::Terminate() {
218   std::set<Runtime*> to_be_closed(runtimes_);
219   std::for_each(to_be_closed.begin(), to_be_closed.end(),
220                 std::mem_fun(&Runtime::Close));
221 }
222
223 int Application::GetRenderProcessHostID() const {
224   DCHECK(render_process_host_);
225   return render_process_host_->GetID();
226 }
227
228 void Application::OnRuntimeAdded(Runtime* runtime) {
229   DCHECK(runtime);
230   runtimes_.insert(runtime);
231 }
232
233 void Application::OnRuntimeRemoved(Runtime* runtime) {
234   DCHECK(runtime);
235   runtimes_.erase(runtime);
236
237   if (runtimes_.empty()) {
238 #if defined(OS_TIZEN_MOBILE)
239     runtime->CloseRootWindow();
240 #endif
241     base::MessageLoop::current()->PostTask(FROM_HERE,
242         base::Bind(&Application::NotifyTermination,
243                    weak_factory_.GetWeakPtr()));
244     return;
245   }
246 }
247
248 void Application::RenderProcessExited(RenderProcessHost* host,
249                                       base::ProcessHandle,
250                                       base::TerminationStatus,
251                                       int) {
252   DCHECK(render_process_host_ == host);
253   VLOG(1) << "RenderProcess id: " << host->GetID() << " is gone!";
254   XWalkRunner::GetInstance()->OnRenderProcessHostGone(host);
255 }
256
257 void Application::RenderProcessHostDestroyed(RenderProcessHost* host) {
258   DCHECK(render_process_host_ == host);
259   render_process_host_ = NULL;
260   web_contents_ = NULL;
261 }
262
263 void Application::NotifyTermination() {
264   CHECK(!render_process_host_);
265   observer_->OnApplicationTerminated(this);
266 }
267
268 bool Application::UseExtension(const std::string& extension_name) const {
269   // TODO(Bai): Tells whether the application contains the specified extension
270   return true;
271 }
272
273 bool Application::RegisterPermissions(const std::string& extension_name,
274                                       const std::string& perm_table) {
275   // TODO(Bai): Parse the permission table and fill in the name_perm_map_
276   // The perm_table format is a simple JSON string, like
277   // [{"permission_name":"echo","apis":["add","remove","get"]}]
278   scoped_ptr<base::Value> root;
279   root.reset(base::JSONReader().ReadToValue(perm_table));
280   if (root.get() == NULL || !root->IsType(base::Value::TYPE_LIST))
281     return false;
282
283   base::ListValue* permission_list = static_cast<base::ListValue*>(root.get());
284   if (permission_list->GetSize() == 0)
285     return false;
286
287   for (base::ListValue::const_iterator iter = permission_list->begin();
288       iter != permission_list->end(); ++iter) {
289     if (!(*iter)->IsType(base::Value::TYPE_DICTIONARY))
290         return false;
291
292     base::DictionaryValue* dict_val =
293         static_cast<base::DictionaryValue*>(*iter);
294     std::string permission_name;
295     if (!dict_val->GetString("permission_name", &permission_name))
296       return false;
297
298     base::ListValue* api_list = NULL;
299     if (!dict_val->GetList("apis", &api_list))
300       return false;
301
302     for (base::ListValue::const_iterator api_iter = api_list->begin();
303         api_iter != api_list->end(); ++api_iter) {
304       std::string api;
305       if (!((*api_iter)->IsType(base::Value::TYPE_STRING)
306           && (*api_iter)->GetAsString(&api)))
307         return false;
308       // register the permission and api
309       name_perm_map_[api] = permission_name;
310       DLOG(INFO) << "Permission Registered [PERM] " << permission_name
311                  << " [API] " << api;
312     }
313   }
314
315   return true;
316 }
317
318 std::string Application::GetRegisteredPermissionName(
319     const std::string& extension_name,
320     const std::string& api_name) const {
321   std::map<std::string, std::string>::const_iterator iter =
322       name_perm_map_.find(api_name);
323   if (iter == name_perm_map_.end())
324     return std::string("");
325   return iter->second;
326 }
327
328 StoredPermission Application::GetPermission(PermissionType type,
329                                const std::string& permission_name) const {
330   if (type == SESSION_PERMISSION) {
331     StoredPermissionMap::const_iterator iter =
332         permission_map_.find(permission_name);
333     if (iter == permission_map_.end())
334       return UNDEFINED_STORED_PERM;
335     return iter->second;
336   }
337   if (type == PERSISTENT_PERMISSION) {
338     return data_->GetPermission(permission_name);
339   }
340   NOTREACHED();
341   return UNDEFINED_STORED_PERM;
342 }
343
344 bool Application::SetPermission(PermissionType type,
345                                 const std::string& permission_name,
346                                 StoredPermission perm) {
347   if (type == SESSION_PERMISSION) {
348     permission_map_[permission_name] = perm;
349     return true;
350   }
351   if (type == PERSISTENT_PERMISSION)
352     return data_->SetPermission(permission_name, perm);
353
354   NOTREACHED();
355   return false;
356 }
357
358 void Application::InitSecurityPolicy() {
359   // CSP policy takes precedence over WARP.
360   if (data_->HasCSPDefined())
361     security_policy_.reset(new SecurityPolicyCSP(this));
362   else if (data_->GetPackageType() == Package::WGT)
363     security_policy_.reset(new SecurityPolicyWARP(this));
364
365   if (security_policy_)
366     security_policy_->Enforce();
367 }
368
369 bool Application::CanRequestURL(const GURL& url) const {
370   if (security_policy_)
371     return security_policy_->IsAccessAllowed(url);
372   return true;
373 }
374
375 base::FilePath Application::GetSplashScreenPath() {
376   return base::FilePath();
377 }
378
379 }  // namespace application
380 }  // namespace xwalk