Initial service app implementation
[platform/framework/web/crosswalk-tizen.git] / tizen / src / browser / wrt_service.cc
1 #include "tizen/src/browser/wrt_service.h"
2
3 #include "base/logging.h"
4 #include "tizen/src/browser/api/wrt_api_core.h"
5
6 namespace tizen {
7
8 Service::Service(std::string source_name)
9     : source_name_(source_name) {}
10
11 const std::string Service::ReadFile(const std::string file) {
12   std::string content;
13   ServiceManager::Get()->ipc_.SendMessageAndWaitReply(source_name_.c_str(), "ReadFile", file.c_str(), content);
14   return content;
15 }
16
17 ServiceManager::ServiceManager() {
18   uv_async_init(uv_default_loop(), &handle_, OnMainThread);
19   handle_.data = this;
20   uv_mutex_init(&mutex_);
21 }
22
23 ServiceManager::~ServiceManager() {
24   uv_close(reinterpret_cast<uv_handle_t*>(&handle_), nullptr);
25   uv_mutex_destroy(&mutex_);
26 }
27
28 // static
29 ServiceManager* ServiceManager::Get() {
30   static ServiceManager* manager = nullptr;
31   if (!manager) {
32     manager = new ServiceManager;
33   }
34   return manager;
35 }
36
37 Service* ServiceManager::GetService(const std::string app_id) {
38   auto iter = services_.find(app_id);
39   if (iter == services_.end()) {
40     return nullptr;
41   }
42   return iter->second;
43 }
44
45 void ServiceManager::Prepare(const std::string app_id, const std::string source_name) {
46   Service* service = new Service(source_name);
47   uv_mutex_lock(&mutex_);
48   prepared_services_.push_back(app_id);
49   services_[app_id] = service;
50   uv_mutex_unlock(&mutex_);
51   uv_async_send(&handle_);
52 }
53
54 // static
55 void ServiceManager::OnMainThread(uv_async_t* handle) {
56   ServiceManager* manager = reinterpret_cast<ServiceManager*>(handle->data);
57   std::vector<std::string> services;
58
59   auto wrt = tizen::api::WebRuntime::GetInstance();
60   if (!wrt) {
61     LOG(ERROR) << "JS WRT object is not created";
62     return;
63   }
64
65   uv_mutex_lock(&manager->mutex_);
66   services.swap(manager->prepared_services_);
67   uv_mutex_unlock(&manager->mutex_);
68
69   for (auto it = services.begin(); it != services.end(); it++) {
70     std::string app_id = *it;
71     wrt->Emit("start-service", app_id);
72   }
73 }
74
75 }  // namespace tizen