[Common] Simplified handling of JS<->C++ communication.
authorPawel Andruszkiewicz <p.andruszkie@samsung.com>
Fri, 5 Feb 2016 07:49:32 +0000 (08:49 +0100)
committerPawel Andruszkiewicz <p.andruszkie@samsung.com>
Wed, 10 Feb 2016 08:54:41 +0000 (17:54 +0900)
Change-Id: I56abb9f1912e76c6d54e75d9bb577ed29fe45040
Signed-off-by: Pawel Andruszkiewicz <p.andruszkie@samsung.com>
src/common/common.gyp
src/common/logger.h
src/common/tizen_instance.cc [new file with mode: 0644]
src/common/tizen_instance.h [new file with mode: 0644]
src/common/tizen_result.cc [new file with mode: 0644]
src/common/tizen_result.h [new file with mode: 0644]

index e93b7cbd736bea4805942b7099f2b95aca702acb..f89186c4b01a6a6019779c9a71f534642cee14e0 100644 (file)
         'filesystem/filesystem_provider.cc',
         'filesystem/filesystem_provider_storage.h',
         'filesystem/filesystem_provider_storage.cc',
+        'tizen_result.cc',
+        'tizen_result.h',
+        'tizen_instance.cc',
+        'tizen_instance.h',
       ],
       'cflags': [
         '-fvisibility=default',
index 1da429dd002954fdd3bb266dd578292b94226040..a807bdb0f841d16ec7e08bbc6946f62f7d33ebb1 100644 (file)
@@ -195,4 +195,57 @@ public:
      LogAndCreateResult_1(__VA_ARGS__) \
   )
 
+// internal macros
+#define LogAndCreateTizenError_1(error_name) \
+  ( \
+    LoggerE("Creating TizenError"), \
+    common::error_name() \
+  )
+
+#define LogAndCreateTizenError_2(error_name, msg) \
+  ( \
+    LoggerE("Creating TizenError"), \
+    common::error_name(msg) \
+  )
+
+#define LogAndCreateTizenError_3(error_name, msg, log) \
+  ( \
+    LoggerE log, \
+    common::error_name(msg) \
+  )
+
+#define LogAndCreateTizenError_X(_0, _1, _2, _3, FUNC, ...) FUNC
+
+#define LogAndCreateTizenError(...) \
+  LogAndCreateTizenError_X(, ##__VA_ARGS__, \
+     LogAndCreateTizenError_3(__VA_ARGS__), \
+     LogAndCreateTizenError_2(__VA_ARGS__), \
+     LogAndCreateTizenError_1(__VA_ARGS__) \
+  )
+
+namespace common {
+
+// defined here, so LoggerD() depends on TIZEN_DEBUG_ENABLE flag on per-module
+// basis
+class ScopeLogger {
+ public:
+  ScopeLogger(const std::string& f, const std::string& m, int l, const std::string& ex = "")
+      : file_(f), method_(m), extra_(ex) {
+    LoggerD("%s: %s(%d) > Enter %s", file_.c_str(), method_.c_str(), l, extra_.c_str());
+  }
+
+  ~ScopeLogger() {
+    LoggerD("%s: %s > Exit %s", file_.c_str(), method_.c_str(), extra_.c_str());
+  }
+
+ private:
+  std::string file_;
+  std::string method_;
+  std::string extra_;
+};
+
+}  // common
+
+#define ScopeLogger(EX) const common::ScopeLogger __sl__{__MODULE__, __func__, __LINE__, EX}
+
 #endif // COMMON_LOGGER_H_
diff --git a/src/common/tizen_instance.cc b/src/common/tizen_instance.cc
new file mode 100644 (file)
index 0000000..8c8d526
--- /dev/null
@@ -0,0 +1,88 @@
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+
+#include "common/tizen_instance.h"
+
+#include "common/logger.h"
+#include "common/task-queue.h"
+
+namespace common {
+
+AsyncToken::AsyncToken(const picojson::object& obj) {
+  value_ = obj.at("callbackId").get<double>();
+}
+
+void AsyncToken::ToJson(picojson::object* obj) const {
+  obj->insert(std::make_pair("callbackId", picojson::value{value_}));
+}
+
+void ListenerToken::ToJson(picojson::object* obj) const {
+  obj->insert(std::make_pair("listenerId", picojson::value{lid_}));
+}
+
+TizenInstance::TizenInstance() {
+  ScopeLogger();
+}
+
+TizenInstance::~TizenInstance() {
+  ScopeLogger();
+}
+
+void TizenInstance::RegisterHandler(const std::string& name, const AsyncHandler& func) {
+  ScopeLogger();
+
+  // TODO: change to RegisterHandler() when applicable
+  ParsedInstance::RegisterSyncHandler(name, [func](const picojson::value& args, picojson::object& out) -> void {
+    const auto& a = args.get<picojson::object>();
+    auto result = func(a, AsyncToken(a));
+    result.ToJson(&out);
+  });
+}
+
+void TizenInstance::RegisterSyncHandler(const std::string& name, const SyncHandler& func) {
+  ScopeLogger();
+
+  ParsedInstance::RegisterSyncHandler(name, [func](const picojson::value& args, picojson::object& out) -> void {
+    auto result = func(args.get<picojson::object>());
+    result.ToJson(&out);
+  });
+}
+
+void TizenInstance::Post(const AsyncToken& token, const TizenResult& result) {
+  ScopeLogger();
+
+  picojson::value msg{picojson::object{}};
+  auto& obj = msg.get<picojson::object>();
+
+  token.ToJson(&obj);
+  result.ToJson(&obj);
+
+  TaskQueue::GetInstance().Async([this, msg]() {
+    ParsedInstance::PostMessage(this, msg.serialize().c_str());
+  });
+}
+
+PostCallback TizenInstance::SimplePost(const AsyncToken& token) {
+  ScopeLogger();
+
+  return [this, token](const common::TizenResult& result, const picojson::value& value) {
+    ScopeLogger("simple post");
+
+    Post(token, result ? TizenSuccess{value} : result);
+  };
+}
+
+}  // namespace common
diff --git a/src/common/tizen_instance.h b/src/common/tizen_instance.h
new file mode 100644 (file)
index 0000000..b8537ff
--- /dev/null
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+
+#ifndef COMMON_TIZEN_INSTANCE_H_
+#define COMMON_TIZEN_INSTANCE_H_
+
+#include <memory>
+#include <unordered_map>
+
+#include "common/extension.h"
+#include "common/picojson.h"
+#include "common/tizen_result.h"
+
+namespace common {
+
+class AsyncToken {
+ public:
+  explicit AsyncToken(const picojson::object& msg);
+  virtual ~AsyncToken() {}
+
+  virtual void ToJson(picojson::object* msg) const;
+
+ protected:
+  AsyncToken() : value_(-1.0) {}
+
+ private:
+  double value_;
+};
+
+class ListenerToken : public AsyncToken {
+ public:
+  explicit ListenerToken(const std::string& lid) : lid_(lid) {}
+
+  virtual void ToJson(picojson::object* msg) const override;
+
+ private:
+  std::string lid_;
+};
+
+using AsyncHandler = std::function<TizenResult(const picojson::object&, const AsyncToken&)>;
+using SyncHandler = std::function<TizenResult(const picojson::object&)>;
+using PostCallback = std::function<void(const TizenResult&, const picojson::value&)>;
+
+class TizenInstance : public ParsedInstance {
+ public:
+  TizenInstance();
+  ~TizenInstance();
+
+ protected:
+  void RegisterHandler(const std::string& name, const AsyncHandler& func);
+  void RegisterSyncHandler(const std::string& name, const SyncHandler& func);
+  void Post(const AsyncToken& token, const TizenResult& result);
+  PostCallback SimplePost(const AsyncToken& token);
+};
+
+}  // namespace common
+
+#endif  // COMMON_TIZEN_INSTANCE_H_
diff --git a/src/common/tizen_result.cc b/src/common/tizen_result.cc
new file mode 100644 (file)
index 0000000..ed8a4c8
--- /dev/null
@@ -0,0 +1,89 @@
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+
+#include "common/tizen_result.h"
+
+#include "common/tools.h"
+
+namespace common {
+
+void TizenResult::ToJson(picojson::object* msg) const {
+  for (auto& d : data_) {
+    msg->insert(d);
+  }
+}
+
+TizenSuccess::TizenSuccess()
+    : TizenResult(ErrorCode::NO_ERROR) {
+  tools::ReportSuccess(data_);
+}
+
+TizenSuccess::TizenSuccess(const picojson::value& r)
+    : TizenResult(ErrorCode::NO_ERROR) {
+  tools::ReportSuccess(r, data_);
+}
+
+TizenError::TizenError(const ErrorCode& error_code, const std::string& msg)
+    : TizenResult(error_code, msg) {
+  tools::ReportError(*this, &data_);
+}
+
+TizenError::TizenError(const ErrorCode& error_code, int platform_error)
+    : TizenResult(error_code, std::string("Platform error: ") + get_error_message(platform_error)) {
+  tools::ReportError(*this, &data_);
+}
+
+#define DefineErrorClass(name) \
+const ErrorCode name::code_; \
+name::name(const std::string& msg) : TizenError(code_, msg) {} \
+name::name(int error_code) : TizenError(code_, error_code) {}
+
+DefineErrorClass(IndexSizeError);
+DefineErrorClass(DomStringSizeError);
+DefineErrorClass(HierarchyRequestError);
+DefineErrorClass(WrongDocumentError);
+DefineErrorClass(InvalidCharacterError);
+DefineErrorClass(NoDataAllowedError);
+DefineErrorClass(NoModificationAllowedError);
+DefineErrorClass(NotFoundError);
+DefineErrorClass(NotSupportedError);
+DefineErrorClass(InUseAttributeError);
+DefineErrorClass(InvalidStateError);
+DefineErrorClass(SyntaxError);
+DefineErrorClass(InvalidModificationError);
+DefineErrorClass(NamespacesError);
+DefineErrorClass(InvalidAccessError);
+DefineErrorClass(ValidationError);
+DefineErrorClass(TypeMismatchError);
+DefineErrorClass(SecurityError);
+DefineErrorClass(NetworkError);
+DefineErrorClass(AbortError);
+DefineErrorClass(UrlMismatchError);
+DefineErrorClass(QuotaExceededError);
+DefineErrorClass(TimeoutError);
+DefineErrorClass(InvalidNodeTypeError);
+DefineErrorClass(DataCloneError);
+DefineErrorClass(InvalidValuesError);
+DefineErrorClass(IoError);
+DefineErrorClass(PermissionDeniedError);
+DefineErrorClass(ServiceNotAvailableError);
+DefineErrorClass(DatabaseError);
+DefineErrorClass(VerificationError);
+DefineErrorClass(OperationCanceledError);
+DefineErrorClass(UnknownError);
+#undef DefineErrorClass
+
+}  // namespace common
diff --git a/src/common/tizen_result.h b/src/common/tizen_result.h
new file mode 100644 (file)
index 0000000..d1e18a4
--- /dev/null
@@ -0,0 +1,93 @@
+/*
+ * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+
+#ifndef COMMON_TIZEN_RESULT_H_
+#define COMMON_TIZEN_RESULT_H_
+
+#include "common/picojson.h"
+#include "common/platform_result.h"
+
+namespace common {
+
+class TizenResult : public PlatformResult {
+ public:
+  void ToJson(picojson::object* msg) const;
+
+ protected:
+  using PlatformResult::PlatformResult;
+
+  picojson::object data_;
+};
+
+class TizenSuccess : public TizenResult {
+ public:
+  TizenSuccess();
+  explicit TizenSuccess(const picojson::value& r);
+};
+
+class TizenError : public TizenResult {
+ protected:
+  TizenError(const ErrorCode& error_code, const std::string& msg = "");
+  TizenError(const ErrorCode& error_code, int platform_error);
+};
+
+#define DeclareErrorClass(name, code) \
+class name : public TizenError { \
+ public: \
+  explicit name(const std::string& msg = ""); \
+  explicit name(int error_code); \
+ private: \
+  static const ErrorCode code_ = code; \
+}
+
+DeclareErrorClass(IndexSizeError, ErrorCode::INDEX_SIZE_ERR);
+DeclareErrorClass(DomStringSizeError, ErrorCode::DOMSTRING_SIZE_ERR);
+DeclareErrorClass(HierarchyRequestError, ErrorCode::HIERARCHY_REQUEST_ERR);
+DeclareErrorClass(WrongDocumentError, ErrorCode::WRONG_DOCUMENT_ERR);
+DeclareErrorClass(InvalidCharacterError, ErrorCode::INVALID_CHARACTER_ERR);
+DeclareErrorClass(NoDataAllowedError, ErrorCode::NO_DATA_ALLOWED_ERR);
+DeclareErrorClass(NoModificationAllowedError, ErrorCode::NO_MODIFICATION_ALLOWED_ERR);
+DeclareErrorClass(NotFoundError, ErrorCode::NOT_FOUND_ERR);
+DeclareErrorClass(NotSupportedError, ErrorCode::NOT_SUPPORTED_ERR);
+DeclareErrorClass(InUseAttributeError, ErrorCode::INUSE_ATTRIBUTE_ERR);
+DeclareErrorClass(InvalidStateError, ErrorCode::INVALID_STATE_ERR);
+DeclareErrorClass(SyntaxError, ErrorCode::SYNTAX_ERR);
+DeclareErrorClass(InvalidModificationError, ErrorCode::INVALID_MODIFICATION_ERR);
+DeclareErrorClass(NamespacesError, ErrorCode::NAMESPACE_ERR);
+DeclareErrorClass(InvalidAccessError, ErrorCode::INVALID_ACCESS_ERR);
+DeclareErrorClass(ValidationError, ErrorCode::VALIDATION_ERR);
+DeclareErrorClass(TypeMismatchError, ErrorCode::TYPE_MISMATCH_ERR);
+DeclareErrorClass(SecurityError, ErrorCode::SECURITY_ERR);
+DeclareErrorClass(NetworkError, ErrorCode::NETWORK_ERR);
+DeclareErrorClass(AbortError, ErrorCode::ABORT_ERR);
+DeclareErrorClass(UrlMismatchError, ErrorCode::URL_MISMATCH_ERR);
+DeclareErrorClass(QuotaExceededError, ErrorCode::QUOTA_EXCEEDED_ERR);
+DeclareErrorClass(TimeoutError, ErrorCode::TIMEOUT_ERR);
+DeclareErrorClass(InvalidNodeTypeError, ErrorCode::INVALID_NODE_TYPE_ERR);
+DeclareErrorClass(DataCloneError, ErrorCode::DATA_CLONE_ERR);
+DeclareErrorClass(InvalidValuesError, ErrorCode::INVALID_VALUES_ERR);
+DeclareErrorClass(IoError, ErrorCode::IO_ERR);
+DeclareErrorClass(PermissionDeniedError, ErrorCode::PERMISSION_DENIED_ERR);
+DeclareErrorClass(ServiceNotAvailableError, ErrorCode::SERVICE_NOT_AVAILABLE_ERR);
+DeclareErrorClass(DatabaseError, ErrorCode::DATABASE_ERR);
+DeclareErrorClass(VerificationError, ErrorCode::VERIFICATION_ERR);
+DeclareErrorClass(OperationCanceledError, ErrorCode::OPERATION_CANCELED_ERR);
+DeclareErrorClass(UnknownError, ErrorCode::UNKNOWN_ERR);
+#undef DeclareErrorClass
+
+}  // namespace common
+
+#endif  // COMMON_TIZEN_RESULT_H_