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.
5 #include "xwalk/application/browser/application.h"
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"
30 #include "xwalk/application/browser/application_tizen.h"
33 using content::RenderProcessHost;
37 namespace keys = application_manifest_keys;
38 namespace widget_keys = application_widget_keys;
41 const char* kDefaultWidgetEntryPage[] = {
48 GURL GetDefaultWidgetEntryPage(
49 scoped_refptr<xwalk::application::ApplicationData> data) {
50 base::ThreadRestrictions::SetIOAllowed(true);
51 base::FileEnumerator iter(
53 base::FileEnumerator::FILES,
54 FILE_PATH_LITERAL("index.*"));
55 size_t priority = arraysize(kDefaultWidgetEntryPage);
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] &&
62 source = kDefaultWidgetEntryPage[i];
68 return source.empty() ? GURL() : data->GetResourceURL(source);
73 namespace application {
75 scoped_ptr<Application> Application::Create(
76 scoped_refptr<ApplicationData> data,
77 XWalkBrowserContext* context) {
79 return make_scoped_ptr<Application>(new ApplicationTizen(data, context));
81 return make_scoped_ptr(new Application(data, context));
85 Application::Application(
86 scoped_refptr<ApplicationData> data,
87 XWalkBrowserContext* browser_context)
89 render_process_host_(NULL),
91 security_mode_enabled_(false),
92 browser_context_(browser_context),
94 remote_debugging_enabled_(false),
96 DCHECK(browser_context_);
100 Application::~Application() {
102 if (render_process_host_)
103 render_process_host_->RemoveObserver(this);
107 GURL Application::GetStartURL<Manifest::TYPE_WIDGET>() {
108 #if defined(OS_TIZEN)
109 if (data_->IsHostedApp()) {
112 if (data_->GetManifest()->GetString(
113 widget_keys::kLaunchLocalPathKey, &source)) {
117 if (url.is_valid() && url.SchemeIsHTTPOrHTTPS())
122 GURL url = GetAbsoluteURLFromKey(widget_keys::kLaunchLocalPathKey);
126 LOG(WARNING) << "Failed to find start URL from the 'config.xml'"
127 << "trying to find default entry page.";
128 url = GetDefaultWidgetEntryPage(data_);
132 LOG(WARNING) << "Failed to find a valid start URL in the manifest.";
137 GURL Application::GetStartURL<Manifest::TYPE_MANIFEST>() {
138 if (data_->IsHostedApp()) {
140 // Not trying to get a relative path for the "fake" application.
141 if (data_->GetManifest()->GetString(keys::kStartURLKey, &source))
146 GURL url = GetAbsoluteURLFromKey(keys::kStartURLKey);
150 url = GetAbsoluteURLFromKey(keys::kLaunchLocalPathKey);
154 url = GetAbsoluteURLFromKey(keys::kDeprecatedURLKey);
155 if (url.is_valid()) {
156 LOG(WARNING) << "Deprecated key '" << keys::kDeprecatedURLKey
157 << "' found. Please migrate to using '" << keys::kStartURLKey
162 LOG(WARNING) << "Failed to find a valid start URL in the manifest.";
168 ui::WindowShowState Application::GetWindowShowState<Manifest::TYPE_WIDGET>(
169 const LaunchParams& params) {
170 if (params.force_fullscreen)
171 return ui::SHOW_STATE_FULLSCREEN;
173 const Manifest* manifest = data_->GetManifest();
174 std::string view_modes_string;
175 if (manifest->GetString(widget_keys::kViewModesKey, &view_modes_string)) {
176 // FIXME: ATM only 'fullscreen' and 'windowed' values are supported.
177 // If the first user prefererence is 'fullscreen', set window show state
178 // FULLSCREEN, otherwise set the default window show state.
179 std::vector<std::string> modes;
180 base::SplitString(view_modes_string, ' ', &modes);
181 if (!modes.empty() && modes[0] == "fullscreen")
182 return ui::SHOW_STATE_FULLSCREEN;
185 return ui::SHOW_STATE_DEFAULT;
189 ui::WindowShowState Application::GetWindowShowState<Manifest::TYPE_MANIFEST>(
190 const LaunchParams& params) {
191 if (params.force_fullscreen)
192 return ui::SHOW_STATE_FULLSCREEN;
194 const Manifest* manifest = data_->GetManifest();
195 std::string display_string;
196 if (manifest->GetString(keys::kDisplay, &display_string)) {
197 // FIXME: ATM only 'fullscreen' and 'standalone' (which is fallback value)
198 // values are supported.
199 if (display_string.find("fullscreen") != std::string::npos)
200 return ui::SHOW_STATE_FULLSCREEN;
203 return ui::SHOW_STATE_DEFAULT;
206 bool Application::Launch(const LaunchParams& launch_params) {
207 if (!runtimes_.empty()) {
208 LOG(ERROR) << "Attempt to launch app with id " << id()
209 << ", but it is already running.";
213 CHECK(!render_process_host_);
214 bool is_wgt = data_->manifest_type() == Manifest::TYPE_WIDGET;
216 GURL url = is_wgt ? GetStartURL<Manifest::TYPE_WIDGET>() :
217 GetStartURL<Manifest::TYPE_MANIFEST>();
221 remote_debugging_enabled_ = launch_params.remote_debugging;
222 auto site = content::SiteInstance::CreateForURL(browser_context_, url);
223 Runtime* runtime = Runtime::Create(browser_context_, site);
224 runtime->set_observer(this);
225 runtime->set_remote_debugging_enabled(remote_debugging_enabled_);
226 runtimes_.push_back(runtime);
227 render_process_host_ = runtime->GetRenderProcessHost();
228 render_process_host_->AddObserver(this);
229 web_contents_ = runtime->web_contents();
230 InitSecurityPolicy();
231 runtime->LoadURL(url);
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);
239 window_show_params_ = params;
240 // Only the first runtime can have a launch screen.
241 params.splash_screen_path = GetSplashScreenPath();
242 runtime->set_ui_delegate(DefaultRuntimeUIDelegate::Create(runtime, params));
243 // We call "Show" after RP is initialized to reduce
244 // the application start up time.
249 GURL Application::GetAbsoluteURLFromKey(const std::string& key) {
250 const Manifest* manifest = data_->GetManifest();
253 if (!manifest->GetString(key, &source) || source.empty())
256 return data_->GetResourceURL(source);
259 void Application::Terminate() {
260 std::vector<Runtime*> to_be_closed(runtimes_.get());
261 for (Runtime* runtime : to_be_closed)
265 int Application::GetRenderProcessHostID() const {
266 DCHECK(render_process_host_);
267 return render_process_host_->GetID();
270 void Application::OnNewRuntimeAdded(Runtime* runtime) {
271 runtime->set_remote_debugging_enabled(remote_debugging_enabled_);
272 runtime->set_observer(this);
273 runtime->set_ui_delegate(
274 DefaultRuntimeUIDelegate::Create(runtime, window_show_params_));
276 runtimes_.push_back(runtime);
279 void Application::OnRuntimeClosed(Runtime* runtime) {
280 auto found = std::find(runtimes_.begin(), runtimes_.end(), runtime);
281 CHECK(found != runtimes_.end());
282 LOG(INFO) << "Application::OnRuntimeClosed " << runtime;
283 runtimes_.erase(found);
285 if (runtimes_.empty())
286 base::MessageLoop::current()->PostTask(FROM_HERE,
287 base::Bind(&Application::NotifyTermination,
288 weak_factory_.GetWeakPtr()));
291 void Application::RenderProcessExited(RenderProcessHost* host,
293 base::TerminationStatus,
295 DCHECK(render_process_host_ == host);
296 VLOG(1) << "RenderProcess id: " << host->GetID() << " is gone!";
297 XWalkRunner::GetInstance()->OnRenderProcessHostGone(host);
300 void Application::RenderProcessHostDestroyed(RenderProcessHost* host) {
301 DCHECK(render_process_host_ == host);
302 render_process_host_ = NULL;
303 web_contents_ = NULL;
306 void Application::NotifyTermination() {
307 CHECK(!render_process_host_);
309 observer_->OnApplicationTerminated(this);
312 void Application::RenderChannelCreated() {
313 CHECK(!runtimes_.empty());
314 runtimes_.front()->Show();
317 bool Application::UseExtension(const std::string& extension_name) const {
318 // TODO(Bai): Tells whether the application contains the specified extension
322 bool Application::RegisterPermissions(const std::string& extension_name,
323 const std::string& perm_table) {
324 // TODO(Bai): Parse the permission table and fill in the name_perm_map_
325 // The perm_table format is a simple JSON string, like
326 // [{"permission_name":"echo","apis":["add","remove","get"]}]
327 scoped_ptr<base::Value> root;
328 root.reset(base::JSONReader().ReadToValue(perm_table));
329 if (root.get() == NULL || !root->IsType(base::Value::TYPE_LIST))
332 base::ListValue* permission_list = static_cast<base::ListValue*>(root.get());
333 if (permission_list->GetSize() == 0)
336 for (base::ListValue::const_iterator iter = permission_list->begin();
337 iter != permission_list->end(); ++iter) {
338 if (!(*iter)->IsType(base::Value::TYPE_DICTIONARY))
341 base::DictionaryValue* dict_val =
342 static_cast<base::DictionaryValue*>(*iter);
343 std::string permission_name;
344 if (!dict_val->GetString("permission_name", &permission_name))
347 base::ListValue* api_list = NULL;
348 if (!dict_val->GetList("apis", &api_list))
351 for (base::ListValue::const_iterator api_iter = api_list->begin();
352 api_iter != api_list->end(); ++api_iter) {
354 if (!((*api_iter)->IsType(base::Value::TYPE_STRING)
355 && (*api_iter)->GetAsString(&api)))
357 // register the permission and api
358 name_perm_map_[api] = permission_name;
359 DLOG(INFO) << "Permission Registered [PERM] " << permission_name
367 std::string Application::GetRegisteredPermissionName(
368 const std::string& extension_name,
369 const std::string& api_name) const {
370 std::map<std::string, std::string>::const_iterator iter =
371 name_perm_map_.find(api_name);
372 if (iter == name_perm_map_.end())
373 return std::string("");
377 StoredPermission Application::GetPermission(PermissionType type,
378 const std::string& permission_name) const {
379 if (type == SESSION_PERMISSION) {
380 StoredPermissionMap::const_iterator iter =
381 permission_map_.find(permission_name);
382 if (iter == permission_map_.end())
383 return UNDEFINED_STORED_PERM;
386 if (type == PERSISTENT_PERMISSION) {
387 return data_->GetPermission(permission_name);
390 return UNDEFINED_STORED_PERM;
393 bool Application::SetPermission(PermissionType type,
394 const std::string& permission_name,
395 StoredPermission perm) {
396 if (type == SESSION_PERMISSION) {
397 permission_map_[permission_name] = perm;
400 if (type == PERSISTENT_PERMISSION)
401 return data_->SetPermission(permission_name, perm);
407 void Application::InitSecurityPolicy() {
408 // CSP policy takes precedence over WARP.
409 if (data_->HasCSPDefined())
410 security_policy_.reset(new ApplicationSecurityPolicyCSP(this));
411 else if (data_->manifest_type() == Manifest::TYPE_WIDGET)
412 security_policy_.reset(new ApplicationSecurityPolicyWARP(this));
414 if (security_policy_)
415 security_policy_->Enforce();
418 bool Application::CanRequestURL(const GURL& url) const {
419 if (security_policy_)
420 return security_policy_->IsAccessAllowed(url);
424 base::FilePath Application::GetSplashScreenPath() {
425 return base::FilePath();
428 } // namespace application