940a4fda1d6d0865c9b3564f708c975722b51b6a
[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/values.h"
15 #include "content/public/browser/web_contents.h"
16 #include "content/public/browser/render_process_host.h"
17 #include "net/base/net_util.h"
18 #include "xwalk/application/browser/application_event_manager.h"
19 #include "xwalk/application/browser/application_service.h"
20 #include "xwalk/application/browser/application_storage.h"
21 #include "xwalk/application/browser/application_system.h"
22 #include "xwalk/application/common/application_manifest_constants.h"
23 #include "xwalk/application/common/constants.h"
24 #include "xwalk/application/common/manifest_handlers/main_document_handler.h"
25 #include "xwalk/application/common/event_names.h"
26 #include "xwalk/runtime/browser/runtime.h"
27 #include "xwalk/runtime/browser/runtime_context.h"
28 #include "xwalk/runtime/browser/xwalk_runner.h"
29
30 namespace xwalk {
31
32 namespace keys = application_manifest_keys;
33 namespace widget_keys = application_widget_keys;
34
35 namespace {
36 const char* kDefaultWidgetEntryPage[] = {
37 "index.html",
38 "index.htm",
39 "index.svg",
40 "index.xhtml",
41 "index.xht"};
42 }  // namespace
43
44 namespace application {
45
46 class FinishEventObserver : public EventObserver {
47  public:
48   FinishEventObserver(
49       ApplicationEventManager* event_manager,
50       Application* application)
51       : EventObserver(event_manager),
52         application_(application) {
53   }
54
55   virtual void Observe(const std::string& app_id,
56                        scoped_refptr<Event> event) OVERRIDE {
57     DCHECK(xwalk::application::kOnJavaScriptEventAck == event->name());
58     std::string ack_event_name;
59     event->args()->GetString(0, &ack_event_name);
60     if (ack_event_name == xwalk::application::kOnSuspend)
61       application_->CloseMainDocument();
62   }
63
64  private:
65   Application* application_;
66 };
67
68 Application::Application(
69     scoped_refptr<ApplicationData> data,
70     RuntimeContext* runtime_context,
71     Observer* observer)
72     : runtime_context_(runtime_context),
73       application_data_(data),
74       main_runtime_(NULL),
75       observer_(observer),
76       entry_point_used_(Default),
77       termination_mode_used_(Normal),
78       weak_factory_(this) {
79   DCHECK(runtime_context_);
80   DCHECK(application_data_);
81   DCHECK(observer_);
82 }
83
84 Application::~Application() {
85   Terminate(Immediate);
86 }
87
88 bool Application::Launch(const LaunchParams& launch_params) {
89   if (!runtimes_.empty()) {
90     LOG(ERROR) << "Attempt to launch app: " << id()
91                << " that was already launched.";
92     return false;
93   }
94
95   GURL url = GetURLForLaunch(launch_params, &entry_point_used_);
96   if (!url.is_valid())
97     return false;
98
99   main_runtime_ = Runtime::Create(runtime_context_, this);
100   main_runtime_->LoadURL(url);
101   if (entry_point_used_ != AppMainKey) {
102     NativeAppWindow::CreateParams params;
103     params.net_wm_pid = launch_params.launcher_pid;
104     params.state = launch_params.window_state;
105
106     main_runtime_->AttachWindow(params);
107   }
108
109   return true;
110 }
111
112 GURL Application::GetURLForLaunch(const LaunchParams& params,
113                                   LaunchEntryPoint* used) {
114   if (params.entry_points & AppMainKey) {
115     GURL url = GetURLFromAppMainKey();
116     if (url.is_valid()) {
117       *used = AppMainKey;
118       return url;
119     }
120   }
121
122   if (params.entry_points & LaunchLocalPathKey) {
123     GURL url = GetURLFromLocalPathKey();
124     if (url.is_valid()) {
125       *used = LaunchLocalPathKey;
126       return url;
127     }
128   }
129
130   if (params.entry_points & URLKey) {
131     GURL url = GetURLFromURLKey();
132     if (url.is_valid()) {
133       *used = URLKey;
134       return url;
135     }
136   }
137   LOG(WARNING) << "Failed to find a valid launch URL for the app.";
138   return GURL();
139 }
140
141 GURL Application::GetURLFromAppMainKey() {
142   MainDocumentInfo* main_info = ToMainDocumentInfo(
143     application_data_->GetManifestData(keys::kAppMainKey));
144   if (!main_info)
145     return GURL();
146
147   DCHECK(application_data_->HasMainDocument());
148   return main_info->GetMainURL();
149 }
150
151 GURL Application::GetURLFromLocalPathKey() {
152   const Manifest* manifest = application_data_->GetManifest();
153   std::string entry_page;
154   std::string key(GetLaunchLocalPathKey(
155       application_data_->GetPackageType()));
156
157   if (!manifest->GetString(key, &entry_page)
158       || entry_page.empty()) {
159     if (application_data_->GetPackageType() == Manifest::TYPE_XPK)
160       return GURL();
161
162     base::FileEnumerator iter(application_data_->Path(), true,
163                               base::FileEnumerator::FILES,
164                               FILE_PATH_LITERAL("index.*"));
165     int priority = arraysize(kDefaultWidgetEntryPage);
166
167     for (base::FilePath file = iter.Next(); !file.empty(); file = iter.Next()) {
168       for (int i = 0; i < arraysize(kDefaultWidgetEntryPage); ++i) {
169         if (file.BaseName().MaybeAsASCII() == kDefaultWidgetEntryPage[i] &&
170             i < priority) {
171           entry_page = kDefaultWidgetEntryPage[i];
172           priority = i;
173         }
174       }
175     }
176
177     if (entry_page.empty())
178       return GURL();
179   }
180
181   return application_data_->GetResourceURL(entry_page);
182 }
183
184 GURL Application::GetURLFromURLKey() {
185   const Manifest* manifest = application_data_->GetManifest();
186   std::string url_string;
187   if (!manifest->GetString(keys::kURLKey, &url_string))
188     return GURL();
189
190   return GURL(url_string);
191 }
192
193 void Application::Terminate(TerminationMode mode) {
194   termination_mode_used_ = mode;
195   if (IsTerminating()) {
196     LOG(WARNING) << "Attempt to Terminate app: " << id()
197                  << ", which is already in the process of being terminated.";
198     if (mode == Immediate)
199       CloseMainDocument();
200
201     return;
202   }
203
204   std::set<Runtime*> to_be_closed(runtimes_);
205   if (HasMainDocument() && to_be_closed.size() > 1) {
206     // The main document runtime is closed separately
207     // (needs some extra logic) in Application::OnRuntimeRemoved.
208     to_be_closed.erase(main_runtime_);
209   }
210
211   std::for_each(to_be_closed.begin(), to_be_closed.end(),
212                 std::mem_fun(&Runtime::Close));
213 }
214
215 Runtime* Application::GetMainDocumentRuntime() const {
216   return HasMainDocument() ? main_runtime_ : NULL;
217 }
218
219 int Application::GetRenderProcessHostID() const {
220   DCHECK(main_runtime_);
221   return main_runtime_->web_contents()->
222           GetRenderProcessHost()->GetID();
223 }
224
225 bool Application::HasMainDocument() const {
226   return entry_point_used_ == AppMainKey;
227 }
228
229 void Application::OnRuntimeAdded(Runtime* runtime) {
230   DCHECK(runtime);
231   runtimes_.insert(runtime);
232 }
233
234 void Application::OnRuntimeRemoved(Runtime* runtime) {
235   DCHECK(runtime);
236   runtimes_.erase(runtime);
237
238   if (runtimes_.empty()) {
239 #if defined(OS_TIZEN_MOBILE)
240     runtime->CloseRootWindow();
241 #endif
242     base::MessageLoop::current()->PostTask(FROM_HERE,
243         base::Bind(&Application::NotifyTermination,
244                    weak_factory_.GetWeakPtr()));
245     return;
246   }
247
248   if (runtimes_.size() == 1 && HasMainDocument() &&
249       ContainsKey(runtimes_, main_runtime_)) {
250     ApplicationSystem* system = XWalkRunner::GetInstance()->app_system();
251     ApplicationEventManager* event_manager = system->event_manager();
252
253     // If onSuspend is not registered in main document,
254     // we close the main document immediately.
255     if (!IsOnSuspendHandlerRegistered() ||
256         termination_mode_used_ == Immediate) {
257       CloseMainDocument();
258       return;
259     }
260
261     DCHECK(!finish_observer_);
262     finish_observer_.reset(
263         new FinishEventObserver(event_manager, this));
264     event_manager->AttachObserver(
265         application_data_->ID(), kOnJavaScriptEventAck,
266         finish_observer_.get());
267
268     scoped_ptr<base::ListValue> event_args(new base::ListValue);
269     scoped_refptr<Event> event = Event::CreateEvent(
270         xwalk::application::kOnSuspend, event_args.Pass());
271     event_manager->SendEvent(application_data_->ID(), event);
272   }
273 }
274
275 void Application::CloseMainDocument() {
276   DCHECK(main_runtime_);
277
278   finish_observer_.reset();
279   main_runtime_->Close();
280   main_runtime_ = NULL;
281 }
282
283 void Application::NotifyTermination() {
284   observer_->OnApplicationTerminated(this);
285 }
286
287 bool Application::IsOnSuspendHandlerRegistered() const {
288   const std::set<std::string>& events = data()->GetEvents();
289   if (events.find(kOnSuspend) == events.end())
290     return false;
291
292   return true;
293 }
294
295 bool Application::UseExtension(const std::string& extension_name) const {
296   // TODO(Bai): Tells whether the application contains the specified extension
297   return true;
298 }
299
300 bool Application::RegisterPermissions(const std::string& extension_name,
301                                       const std::string& perm_table) {
302   // TODO(Bai): Parse the permission table and fill in the name_perm_map_
303   // The perm_table format is a simple JSON string, like
304   // [{"permission_name":"echo","apis":["add","remove","get"]}]
305   scoped_ptr<base::Value> root;
306   root.reset(base::JSONReader().ReadToValue(perm_table));
307   if (root.get() == NULL || !root->IsType(base::Value::TYPE_LIST))
308     return false;
309
310   base::ListValue* permission_list = static_cast<base::ListValue*>(root.get());
311   if (permission_list->GetSize() == 0)
312     return false;
313
314   for (base::ListValue::const_iterator iter = permission_list->begin();
315       iter != permission_list->end(); ++iter) {
316     if (!(*iter)->IsType(base::Value::TYPE_DICTIONARY))
317         return false;
318
319     base::DictionaryValue* dict_val =
320         static_cast<base::DictionaryValue*>(*iter);
321     std::string permission_name;
322     if (!dict_val->GetString("permission_name", &permission_name))
323       return false;
324
325     base::ListValue* api_list = NULL;
326     if (!dict_val->GetList("apis", &api_list))
327       return false;
328
329     for (base::ListValue::const_iterator api_iter = api_list->begin();
330         api_iter != api_list->end(); ++api_iter) {
331       std::string api;
332       if (!((*api_iter)->IsType(base::Value::TYPE_STRING)
333           && (*api_iter)->GetAsString(&api)))
334         return false;
335       // register the permission and api
336       name_perm_map_[api] = permission_name;
337       DLOG(INFO) << "Permission Registered [PERM] " << permission_name
338                  << " [API] " << api;
339     }
340   }
341
342   return true;
343 }
344
345 std::string Application::GetRegisteredPermissionName(
346     const std::string& extension_name,
347     const std::string& api_name) const {
348   std::map<std::string, std::string>::const_iterator iter =
349       name_perm_map_.find(api_name);
350   if (iter == name_perm_map_.end())
351     return std::string("");
352   return iter->second;
353 }
354
355 StoredPermission Application::GetPermission(PermissionType type,
356                                std::string& permission_name) const {
357   if (type == SESSION_PERMISSION) {
358     StoredPermissionMap::const_iterator iter =
359         permission_map_.find(permission_name);
360     if (iter == permission_map_.end())
361       return UNDEFINED_STORED_PERM;
362     return iter->second;
363   }
364   if (type == PERSISTENT_PERMISSION) {
365     return application_data_->GetPermission(permission_name);
366   }
367   NOTREACHED();
368   return UNDEFINED_STORED_PERM;
369 }
370
371 bool Application::SetPermission(PermissionType type,
372                                 const std::string& permission_name,
373                                 StoredPermission perm) {
374   if (type == SESSION_PERMISSION) {
375     permission_map_[permission_name] = perm;
376     return true;
377   }
378   if (type == PERSISTENT_PERMISSION)
379     return application_data_->SetPermission(permission_name, perm);
380
381   NOTREACHED();
382   return false;
383 }
384
385 }  // namespace application
386 }  // namespace xwalk