Move function definition to aul header
[platform/core/appfw/aul-1.git] / src / aul_window.cc
index aa09949..56b5752 100644 (file)
 #include <bundle_cpp.h>
 
 #include <memory>
+#include <mutex>
 #include <string>
 
 #include "app_request.h"
 #include "aul_api.h"
 #include "aul_util.h"
 #include "include/aul.h"
+#include "include/aul_app_com.h"
 #include "include/aul_cmd.h"
 #include "include/aul_window.h"
 #include "launch.h"
@@ -147,6 +149,76 @@ void WindowInfoDestroyFunc(gpointer data) {
   delete info;
 }
 
+class WindowEventListener {
+ public:
+  WindowEventListener() = default;
+
+  ~WindowEventListener() {
+    Deregister();
+  }
+
+  int Register(aul_window_event_cb cb, void* user_data) {
+    std::lock_guard<std::recursive_mutex> lock(GetMutex());
+    cb_ = cb;
+    user_data_ = user_data;
+
+    if (conn_ != nullptr)
+      return AUL_R_OK;
+
+    int ret = aul_app_com_create_async("aul_window_event", nullptr,
+        AppComMessageCb, this, &conn_);
+    if (ret != AUL_R_OK) {
+      _E("aul_app_com_create_async() is failed. error(%d)", ret);
+      return ret;
+    }
+
+    return AUL_R_OK;
+  }
+
+  void Deregister() {
+    std::lock_guard<std::recursive_mutex> lock(GetMutex());
+    cb_ = nullptr;
+    user_data_ = nullptr;
+
+    if (conn_ == nullptr)
+      return;
+
+    aul_app_com_leave(conn_);
+    conn_ = nullptr;
+  }
+
+ private:
+  static int AppComMessageCb(const char* endpoint, aul_app_com_result_e res,
+      bundle* envelope, void* user_data) {
+    tizen_base::Bundle b(envelope, false, false);
+    std::string event_name = b.GetString(AUL_K_EVENT_NAME);
+    std::string appid = b.GetString(AUL_K_APPID);
+    int wid = std::stoi(b.GetString(AUL_K_WID));
+    int pid = std::stoi(b.GetString(AUL_K_PID));
+
+    auto* handle = static_cast<WindowEventListener*>(user_data);
+    std::lock_guard<std::recursive_mutex> lock(handle->GetMutex());
+    if (handle->cb_) {
+      handle->cb_(event_name.c_str(), appid.c_str(), wid, pid,
+          handle->user_data_);
+    }
+
+    return 0;
+  }
+
+  std::recursive_mutex& GetMutex() const {
+    return mutex_;
+  }
+
+ private:
+  aul_app_com_connection_h conn_ = nullptr;
+  aul_window_event_cb cb_ = nullptr;
+  void* user_data_ = nullptr;
+  mutable std::recursive_mutex mutex_;
+};
+
+WindowEventListener listener;
+
 }  // namespace
 
 extern "C" API int aul_window_stack_get(aul_window_stack_h* handle) {
@@ -499,3 +571,21 @@ extern "C" API int aul_window_attach_below(const char* parent_appid,
 
   return AUL_R_OK;
 }
+
+extern "C" API int aul_window_register_event_cb(aul_window_event_cb callback,
+    void* user_data) {
+  if (callback == nullptr) {
+    _E("Invalid parameter");
+    return AUL_R_EINVAL;
+  }
+
+  int ret = listener.Register(callback, user_data);
+  if (ret != AUL_R_OK)
+    return ret;
+
+  return AUL_R_OK;
+}
+
+extern "C" API void aul_window_deregister_event_cb(void) {
+  listener.Deregister();
+}