diff options
author | jk7744.park <jk7744.park@samsung.com> | 2015-02-01 14:25:43 +0900 |
---|---|---|
committer | jk7744.park <jk7744.park@samsung.com> | 2015-02-01 14:25:43 +0900 |
commit | 31a89b1fbe57b96011f45b9f7a7e48d906b03847 (patch) | |
tree | 1a75b71523a9c75025b81894eedb4c2814df7ce7 /src/Commons | |
parent | c9b61219b0310b8c4672c18dc20887a779830204 (diff) | |
download | wrt-plugins-common-tizen_2.3.tar.gz wrt-plugins-common-tizen_2.3.tar.bz2 wrt-plugins-common-tizen_2.3.zip |
tizen 2.3 releasetizen_2.3_releasesubmit/tizen_2.3/20150202.074142tizen_2.3
Diffstat (limited to 'src/Commons')
39 files changed, 4346 insertions, 0 deletions
diff --git a/src/Commons/Base64.cpp b/src/Commons/Base64.cpp new file mode 100644 index 0000000..94ac901 --- /dev/null +++ b/src/Commons/Base64.cpp @@ -0,0 +1,182 @@ +/* + * Copyright (c) 2011 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. + */ +/* + * Copyright (c) 2003-2007, Bicom Systems Ltd. + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * - Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * - Neither the name of the Bicom Systems Ltd nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * Denis Komadaric, + * Bicom Systems Ltd. + */ +#include <ctype.h> +#include "Exception.h" +#include "Base64.h" + +namespace WrtDeviceApis { +namespace Commons { +const std::string Base64::chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789+/"; + +bool Base64::is_base64(unsigned char c) +{ + return (isalnum(c) || (c == '+') || (c == '/')); +} + +std::string Base64::encode(unsigned char* data, + std::size_t num) +{ + std::string ret; + int i = 0; + int j = 0; + unsigned char char_array_3[3]; + unsigned char char_array_4[4]; + + while (num--) { + char_array_3[i++] = *(data++); + if (i == 3) { + char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; + char_array_4[1] = + ((char_array_3[0] & + 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); + char_array_4[2] = + ((char_array_3[1] & + 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); + char_array_4[3] = char_array_3[2] & 0x3f; + + for (i = 0; i < 4; ++i) { + ret += chars[char_array_4[i]]; + } + i = 0; + } + } + + if (i != 0) { + for (j = i; j < 3; ++j) { + char_array_3[j] = '\0'; + } + + char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; + char_array_4[1] = + ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); + char_array_4[2] = + ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); + char_array_4[3] = char_array_3[2] & 0x3f; + + for (j = 0; (j < i + 1); ++j) { + ret += chars[char_array_4[j]]; + } + + while ((i++ < 3)) { + ret += '='; + } + } + + return ret; +} + +std::string Base64::decode(const std::string& str) +{ + if (!is_base64_string(str)) { + ThrowMsg(InvalidArgumentException, + "Invalid length of base64 string."); + } + int in_len = str.size(); + int i = 0; + int j = 0; + int in_ = 0; + unsigned char char_array_4[4], char_array_3[3]; + std::string ret; + + while (in_len-- && (str[in_] != '=')) { + if (!is_base64(str[in_])) { + ThrowMsg(InvalidArgumentException, + "Invalid characters in base64 string."); + } + char_array_4[i++] = str[in_]; + in_++; + if (i == 4) { + for (i = 0; i < 4; ++i) { + char_array_4[i] = chars.find(char_array_4[i]); + } + + char_array_3[0] = + (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); + char_array_3[1] = + ((char_array_4[1] & + 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); + char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; + + for (i = 0; i < 3; ++i) { + ret += char_array_3[i]; + } + i = 0; + } + } + + if (i != 0) { + for (j = i; j < 4; ++j) { + char_array_4[j] = 0; + } + + for (j = 0; j < 4; ++j) { + char_array_4[j] = chars.find(char_array_4[j]); + } + + char_array_3[0] = + (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); + char_array_3[1] = + ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); + char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; + + for (j = 0; (j < i - 1); ++j) { + ret += char_array_3[j]; + } + } + + return ret; +} + +bool Base64::is_base64_string(const std::string& str) +{ + return ((str.size() % 4) == 0); +} +} +} //WrtDeviceApisCommon diff --git a/src/Commons/Base64.h b/src/Commons/Base64.h new file mode 100644 index 0000000..5f42802 --- /dev/null +++ b/src/Commons/Base64.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2011 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 WRTDEVICEAPIS_COMMONS_BASE64_H_ +#define WRTDEVICEAPIS_COMMONS_BASE64_H_ + +#include <string> +#include <cstddef> + +namespace WrtDeviceApis { +namespace Commons { +class Base64 +{ + public: + static std::string encode(unsigned char* data, + std::size_t num); + static std::string decode(const std::string& str); + + private: + static bool is_base64(unsigned char c); + static bool is_base64_string(const std::string& str); + + private: + static const std::string chars; +}; // Base64 +} +} // WrtDeviceApisCommon + +#endif /* WRTDEVICEAPIS_COMMONS_BASE64_H_ */ diff --git a/src/Commons/CMakeLists.txt b/src/Commons/CMakeLists.txt new file mode 100644 index 0000000..40d7424 --- /dev/null +++ b/src/Commons/CMakeLists.txt @@ -0,0 +1,108 @@ +# Copyright (c) 2011 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. +# +MACRO(install_header_file HEADER_FILE) + INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/${HEADER_FILE} + DESTINATION ${DESTINATION_HEADERS_NON_JS}) +ENDMACRO() + +MACRO(install_wrtaccess_header_file HEADER_FILE) + INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/${HEADER_FILE} + DESTINATION ${DESTINATION_HEADERS_NON_JS}/WrtAccess) +ENDMACRO() + +MACRO(install_widget_interface_header_file HEADER_FILE) + INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/${HEADER_FILE} + DESTINATION ${DESTINATION_HEADERS_NON_JS}/WidgetInterface) +ENDMACRO() + +INCLUDE_CONFIG_FILE(WrtAccess) + +PKG_SEARCH_MODULE(plugin-types REQUIRED wrt-plugins-types) +PKG_SEARCH_MODULE(ace-client REQUIRED security-client) +PKG_SEARCH_MODULE(dpl-event REQUIRED dpl-event-efl) +PKG_SEARCH_MODULE(icu REQUIRED icu-i18n) +PKG_SEARCH_MODULE(pcrecpp REQUIRED libpcrecpp) + +SET(WRT_COMMONS_DEPENDECIES_INCLUDES + ${wrt-plugin-api_INCLUDE_DIRS} + ${ace-client_INCLUDE_DIRS} + ${plugin-types_INCLUDE_DIRS} + ${icu_INCLUDE_DIRS} +) + +INCLUDE_DIRECTORIES(${WRT_COMMONS_DEPENDECIES_INCLUDES}) + +SET(TARGET_NAME ${TARGET_COMMONS}) + +SET(SRCS + ${SRCS_WRT_ACCESS} + ${CMAKE_CURRENT_SOURCE_DIR}/Base64.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/FunctionDefinition.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/Regex.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/RegexUtils.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/StringBuilder.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/StringUtils.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/ThreadPool.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/JSObjectDeclaration.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/JSObject.cpp + #PARENT_SCOPE +) + +ADD_LIBRARY(${TARGET_NAME} SHARED ${SRCS}) +TARGET_LINK_LIBRARIES(${TARGET_NAME} + ${LIBS_COMMONS} + ${ace-client_LIBRARIES} + ${dpl-event_LIBRARIES} + ${icu_LIBRARIES} + ${pcrecpp_LIBRARIES} + ${TARGET_POPUP_ACE_RUNNER_LIB} +) + +SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES + COMPILE_DEFINITIONS LOG_TAG="${LOG_TAG}") + +SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES + SOVERSION ${CMAKE_PROJECT_API_VERSION} + VERSION ${CMAKE_PROJECT_VERSION} +) + +INSTALL(TARGETS ${TARGET_NAME} LIBRARY DESTINATION ${DESTINATION_LIB_PREFIX}) + +INSTALL_HEADER_FILE(FunctionDeclaration.h) +INSTALL_HEADER_FILE(FunctionDefinition.h) +INSTALL_HEADER_FILE(Base64.h) +INSTALL_HEADER_FILE(Dimension.h) +INSTALL_HEADER_FILE(Emitters.h) +INSTALL_HEADER_FILE(EventListener.h) +INSTALL_HEADER_FILE(EventReceiver.h) +INSTALL_HEADER_FILE(Exception.h) +INSTALL_HEADER_FILE(IEvent.h) +INSTALL_HEADER_FILE(IExternEventCanceler.h) +INSTALL_HEADER_FILE(ListenerEventEmitter.h) +INSTALL_HEADER_FILE(ListenerEvent.h) +INSTALL_HEADER_FILE(Range.h) +INSTALL_HEADER_FILE(Regex.h) +INSTALL_HEADER_FILE(RegexPatterns.h) +INSTALL_HEADER_FILE(RegexUtils.h) +INSTALL_HEADER_FILE(StaticAssert.h) +INSTALL_HEADER_FILE(StringBuilder.h) +INSTALL_HEADER_FILE(StringUtils.h) +INSTALL_HEADER_FILE(ThreadPool.h) +INSTALL_HEADER_FILE(TypesDeclaration.h) +INSTALL_HEADER_FILE(TypeTraits.h) +INSTALL_HEADER_FILE(plugin_initializer_def.h) +INSTALL_HEADER_FILE(JSObjectDeclaration.h) +INSTALL_HEADER_FILE(JSObject.h) +INSTALL_WRTACCESS_HEADER_FILE(WrtAccess/WrtAccess.h) diff --git a/src/Commons/DESCRIPTION b/src/Commons/DESCRIPTION new file mode 100644 index 0000000..7f04546 --- /dev/null +++ b/src/Commons/DESCRIPTION @@ -0,0 +1 @@ +Common code diff --git a/src/Commons/Dimension.h b/src/Commons/Dimension.h new file mode 100644 index 0000000..703e0c0 --- /dev/null +++ b/src/Commons/Dimension.h @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2011 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. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_COMMONS_DIMENSION_H_ +#define WRTDEVICEAPIS_COMMONS_DIMENSION_H_ + +namespace WrtDeviceApis { +namespace Commons { +/** + * Encapsulates width and height of a component. + */ +class Dimension +{ + public: + /** + * Type of dimension's values. + */ + typedef unsigned int ValueType; + + public: + /** + * Creates an instance of Dimension with specified width and height. + * @param width Specified width. + * @param height Specified height. + */ + Dimension(ValueType width, + ValueType height) : + m_width(width), + m_height(height) + {} + + ValueType getWidth() const + { + return m_width; + } + + ValueType getHeight() const + { + return m_height; + } + + void setSize(ValueType width, + ValueType height) + { + m_width = width; + m_height = height; + } + + private: + ValueType m_width; + ValueType m_height; +}; +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_DIMENSION_H_ diff --git a/src/Commons/Emitters.h b/src/Commons/Emitters.h new file mode 100644 index 0000000..3673e16 --- /dev/null +++ b/src/Commons/Emitters.h @@ -0,0 +1,157 @@ +/* + * Copyright (c) 2011 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. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_COMMONS_EMITTERS_H_ +#define WRTDEVICEAPIS_COMMONS_EMITTERS_H_ + +#include <cstddef> +#include <map> +#include <memory> +#include <dpl/mutex.h> +#include <Commons/ListenerEventEmitter.h> + +namespace WrtDeviceApis { +namespace Commons { +/** + * Manages listener events emitters. + * Template parameter should be class that derives from @see ListenerEvent. + */ +template<class EmitterClass> +class Emitters +{ + public: + typedef EmitterClass EmitterType; + typedef std::shared_ptr<EmitterType> EmitterPtrType; + typedef typename EmitterType::IdType EmitterIdType; + typedef typename EmitterType::EventType EventType; + typedef typename EmitterType::EventPtrType EventPtrType; + typedef std::auto_ptr<DPL::Mutex::ScopedLock> LockType; + + public: + ~Emitters() + { + DPL::Mutex::ScopedLock lock(&m_mtx); + m_emitters.clear(); + } + + /** + * Attaches emitter. + * @param emitter Emitter. + * @remarks Thread-safe. Do not use it in the scope of getLock() result. + */ + void attach(const EmitterPtrType& emitter) + { + DPL::Mutex::ScopedLock lock(&m_mtx); + m_emitters[emitter->getId()] = emitter; + } + + /** + * Detaches emitter. + * @param id Id of an emitter. + * @return True when emitter was found and successfully detached, + * false otherwise. + * @remarks Thread-safe. Do not use it in the scope of getLock() result. + */ + bool detach(const EmitterIdType id) + { + DPL::Mutex::ScopedLock lock(&m_mtx); + return (m_emitters.erase(id) > 0); + } + + /** + * Emits event through all emitters. + * @param event Event to emit. + * @remarks Thread-safe. Do not use it in the scope of getLock() result. + */ + void emit(const EventPtrType& event) + { + DPL::Mutex::ScopedLock lock(&m_mtx); + for (Iterator it = m_emitters.begin(); it != m_emitters.end(); ++it) { + it->second->emit(event); + } + } + + /** + * Emits event through those emitters that when passed to predicate result + * in + * returning true by it. + * @param event Event to emit. + * @param pred Predicate - a callable object (function, functor) that takes + * an argument of type EmitterPtrType and returns boolean value. + */ + template<typename Predicate> + void emitIf(const EventPtrType& event, + Predicate pred) + { + DPL::Mutex::ScopedLock lock(&m_mtx); + for (Iterator it = m_emitters.begin(); it != m_emitters.end(); ++it) { + if (bool(pred(it->second))) { + it->second->emit(event); + } + } + } + + /** + * Checks whether emitter of supplied id is attached. + * @param emitter Emitter. + * @return True when emitter has been found, false otherwise. + * @remarks Can be used within scope of getLock() call. + */ + bool isAttached(const EmitterIdType id) const + { + return (m_emitters.count(id) > 0); + } + + /** + * Returns number of attached emitters. + * @return Number of emitters. + * @remarks Can be used within scope of getLock() call. + */ + std::size_t size() const + { + return m_emitters.size(); + } + + /** + * Lock this object. + * This lock will be automatically released when out of scope (unless + * someone + * copies it). Do not use in the same scope as other API of this class. + * @return Lock object. + * @remarks Provided to allow locking emitters in scope of some client + * code. + */ + LockType getLock() + { + return LockType(new DPL::Mutex::ScopedLock(&m_mtx)); + } + + private: + typedef std::map<EmitterIdType, EmitterPtrType> Map; + typedef typename Map::iterator Iterator; + typedef typename Map::const_iterator ConstIterator; + + private: + DPL::Mutex m_mtx; ///< Synchronizes operation on this object. + Map m_emitters; ///< Emitters container. +}; +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_EMITTERS_H_ diff --git a/src/Commons/EventListener.h b/src/Commons/EventListener.h new file mode 100644 index 0000000..eab6e95 --- /dev/null +++ b/src/Commons/EventListener.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2011 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 WRTDEVICEAPIS_COMMONS_EVENT_LISTENER_H_ +#define WRTDEVICEAPIS_COMMONS_EVENT_LISTENER_H_ + +#include <memory> + +#include <Commons/ThreadPool.h> +#include <Commons/EventReceiver.h> + +namespace WrtDeviceApis { +namespace Commons { +/** + * Base class for listeners. + * Object that is to act as listener should dervie from this class and implement + * OnAnswerReceived() function. + */ +template<class TemplateEvent> +class EventListener : private EventReceiver<TemplateEvent> +{ + public: + EventListener(ThreadEnum::Enumeration threadType) : + EventReceiver<TemplateEvent>(threadType) + {} + + virtual void onAnswerReceived(const std::shared_ptr<TemplateEvent>& event) = 0; + + void postAnswer(const std::shared_ptr<TemplateEvent>& event) + { + DPL::Event::ControllerEventHandler<std::shared_ptr<TemplateEvent> >:: + PostEvent( + event); + } + + protected: + void OnEventReceived(const std::shared_ptr<TemplateEvent> &event) + { + onAnswerReceived(event); + } +}; + +} +} // WrtDeviceApisCommon + +#endif /* WRTDEVICEAPIS_COMMONS_EVENT_LISTENER_H_ */ diff --git a/src/Commons/EventReceiver.h b/src/Commons/EventReceiver.h new file mode 100644 index 0000000..5fe5514 --- /dev/null +++ b/src/Commons/EventReceiver.h @@ -0,0 +1,319 @@ +/* + * Copyright (c) 2011 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. + */ +/* + * @author Karol Majewski (k.majewski@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef WRTDEVICEAPIS_COMMONS_EVENT_RECEIVER_H_ +#define WRTDEVICEAPIS_COMMONS_EVENT_RECEIVER_H_ + +#include <memory> +#include <assert.h> +#include <dpl/event/thread_event_dispatcher.h> +#include <dpl/event/controller.h> +#include <dpl/type_list.h> +#include <dpl/event/abstract_event_call.h> +#include <dpl/log/wrt_log.h> +#include <dpl/mutex.h> +#include <Commons/ThreadPool.h> + +namespace WrtDeviceApis { +namespace Commons { +template<class TemplateEvent> +class SignalEventCall : public DPL::Event::AbstractEventCall +{ + std::shared_ptr<TemplateEvent> m_event; + + public: + + SignalEventCall(const std::shared_ptr<TemplateEvent> &event) : m_event(event) + {} + virtual void Call() + { + WrtLogD("signaling in SignalEventCall"); + m_event->signalSynchronousEventFlag(); + } +}; + +template<class TemplateEvent> +class EventReceiver : + protected DPL::Event::Controller< + typename DPL::TypeListDecl<std::shared_ptr<TemplateEvent> >::Type> +{ + DPL::Event::ThreadEventDispatcher m_threadDispatcher; + + protected: + + EventReceiver(ThreadEnum::Enumeration threadType) + { + DPL::Thread *thread = + ThreadPool::getInstance().getThreadRef(threadType); + DPL::Event::ControllerEventHandler<std::shared_ptr<TemplateEvent> >:: + Touch(); + DPL::Event::ControllerEventHandler<std::shared_ptr<TemplateEvent> >:: + SwitchToThread(thread); + } + + void signalEventByDispatcher(const std::shared_ptr<TemplateEvent> &event) + { + WrtLogD("called"); + Try { + DPL::Event::AbstractEventDispatcher *dispatcher = + ThreadPool::getInstance().getDispatcher(m_threadDispatcher); + dispatcher->AddEventCall(new SignalEventCall<TemplateEvent>(event)); + } + Catch(DPL::Thread::Exception::UnmanagedThread) { + // if called on unmanaged thread, + // call signalSynchronousEventFlag() directly + WrtLogE("signalSynchronousEventFlag() is called" + "by unmanaged thread"); + event->signalSynchronousEventFlag(); + } + } + + virtual ~EventReceiver() + { + DPL::Event::ControllerEventHandler<std::shared_ptr<TemplateEvent> >:: + SwitchToThread(NULL); + } +}; + +template<class TemplateEvent> +class EventRequestReceiver : private EventReceiver<TemplateEvent> +{ + public: + EventRequestReceiver(ThreadEnum::Enumeration threadType) : EventReceiver< + TemplateEvent>(threadType) + {} + + virtual void OnRequestReceived(const std::shared_ptr<TemplateEvent> &) = 0; + + /* + * + * @argument delaySeconds - event will be received not sooner than after + * delay (in seconds) + */ + void PostRequest(const std::shared_ptr<TemplateEvent> &event, + double delaySeconds = 0.0) + { + WrtLogD("called"); + { + DPL::Mutex::ScopedLock lock(&event->m_stateMutex); + assert(TemplateEvent::STATE_INITIAL == event->m_state); + event->m_state = TemplateEvent::STATE_REQUEST_SEND; + } + + if (TemplateEvent::HANDLING_SYNCHRONOUS == event->getHandlingType() && + !event->m_synchronousEventFlag) + { + event->m_synchronousEventFlag = new DPL::WaitableEvent(); + } + + if (0.0 == delaySeconds) { + DPL::Event::ControllerEventHandler<std::shared_ptr<TemplateEvent> > + :: + PostEvent(event); + } else { + DPL::Event::ControllerEventHandler<std::shared_ptr<TemplateEvent> > + :: + PostTimedEvent(event, delaySeconds); + } + + switch (event->getHandlingType()) { + case TemplateEvent::HANDLING_NOT_SET: + assert(0); + break; + case TemplateEvent::HANDLING_SYNCHRONOUS: + event->waitForAnswer(); + break; + } + } + + void OnEventReceived(const std::shared_ptr<TemplateEvent> &event) + { + WrtLogD("called"); + { + DPL::Mutex::ScopedLock lock(&event->m_stateMutex); + if (event->m_cancelled) { + event->handleCancel(); + event->m_cancelAllowed = true; + event->signalCancelStatusFlag(); + event->signalFinishedFlag(); + return; + } else { + assert( + TemplateEvent::STATE_REQUEST_SEND == event->m_state && + "Wrong state!"); + } + event->m_state = TemplateEvent::STATE_REQUEST_RECEIVED; + } + + OnRequestReceived(event); + event->signalCancelStatusFlag(); + //After Controller ends processing it should call it to signal that work + // is done + { + DPL::Mutex::ScopedLock lock(&event->m_stateMutex); + + if (event->m_cancelled) { + //if cancel was not handled in OnRequestReceived when we should + //process as if it was not cancelled at all. + if (event->m_cancelAllowed) { + event->handleCancel(); + event->signalFinishedFlag(); + return; + } + } + //when event is not in manual answer mode we will answer now + if (TemplateEvent::HANDLING_ASYNCHRONOUS_MANUAL_ANSWER != + event->m_handlingType && + TemplateEvent::HANDLING_SYNCHRONOUS_MANUAL_ANSWER != + event->m_handlingType) + { + event->m_state = TemplateEvent::STATE_ANSWER_SEND; + } + } + + switch (event->m_handlingType) { + case TemplateEvent::HANDLING_NOT_SET: + assert(0); + break; + case TemplateEvent::HANDLING_SYNCHRONOUS: + //event->Signal(); + this->signalEventByDispatcher(event); + break; + case TemplateEvent::HANDLING_ASYNCHRONOUS: + ///TODO check - shouldn't it be in signalEventByDispatcher? + if (NULL != event->m_remoteController) { + event->m_remoteController->PostAnswer(event); + } + //event->Signal(); + this->signalEventByDispatcher(event); + break; + //when event is in manual answer mode we do nothing - the answer will be + // send explicit from the code + case TemplateEvent::HANDLING_SYNCHRONOUS_MANUAL_ANSWER: + case TemplateEvent::HANDLING_ASYNCHRONOUS_MANUAL_ANSWER: + break; + } + } + + virtual void ManualAnswer(const std::shared_ptr<TemplateEvent> &event) + { + WrtLogD("called"); + assert( + event->m_handlingType == + TemplateEvent::HANDLING_ASYNCHRONOUS_MANUAL_ANSWER || + event->m_handlingType == + TemplateEvent::HANDLING_SYNCHRONOUS_MANUAL_ANSWER); + { + DPL::Mutex::ScopedLock lock(&event->m_stateMutex); + if (event->m_cancelled) { + //if cancel was not handled in OnRequestReceived when we should + //process as if it was not cancelled at all. + if (event->m_cancelAllowed) { + event->handleCancel(); + event->signalCancelStatusFlag(); + event->signalFinishedFlag(); + return; + } + } + event->m_state = TemplateEvent::STATE_ANSWER_SEND; + } + switch (event->m_handlingType) { + case TemplateEvent::HANDLING_SYNCHRONOUS_MANUAL_ANSWER: + //event->Signal(); + this->signalEventByDispatcher(event); + break; + case TemplateEvent::HANDLING_ASYNCHRONOUS_MANUAL_ANSWER: + //event->Signal(); + if (NULL != event->m_remoteController) { + event->m_remoteController->PostAnswer(event); + } + this->signalEventByDispatcher(event); + break; + default: + break; + } + } +}; + +template<class TemplateEvent> +class EventAnswerReceiver : private EventReceiver<TemplateEvent> +{ + public: + EventAnswerReceiver(ThreadEnum::Enumeration threadType) : EventReceiver< + TemplateEvent>(threadType) + {} + + virtual void OnAnswerReceived(const std::shared_ptr<TemplateEvent> &) = 0; + + //it should be hidden outside, but I can't do it! I can't! :| + void PostAnswer(const std::shared_ptr<TemplateEvent> &event) + { + WrtLogD("called"); + event->signalCancelStatusFlag(); + DPL::Event::ControllerEventHandler<std::shared_ptr<TemplateEvent> >:: + PostEvent( + event); + } + + void OnEventReceived(const std::shared_ptr<TemplateEvent> &event) + { + WrtLogD("EventAnswerReceiver: answer received"); + //check if it can be processed and set the state + { + DPL::Mutex::ScopedLock lock(&event->m_stateMutex); + + //in case someone changed it to synchronous call, we don't process + // it + if (TemplateEvent::STATE_CHANGED_TO_SYNCHRONOUS == + event->m_state || TemplateEvent::STATE_ENDED == + event->m_state) + { + return; + } + //we should get cancelled or answer_send state here + assert( + TemplateEvent::STATE_ANSWER_SEND == event->m_state && + "Wrong state!"); + + if (event->m_cancelled && event->m_cancelAllowed) { + event->handleCancel(); + event->signalFinishedFlag(); + return; + } + event->m_state = TemplateEvent::STATE_ANSWER_RECEIVED; + } + + OnAnswerReceived(event); + + { + DPL::Mutex::ScopedLock lock(&event->m_stateMutex); + assert(TemplateEvent::STATE_ANSWER_RECEIVED == event->m_state); + event->m_state = TemplateEvent::STATE_ENDED; + delete event->m_cancelStatusFlag; + event->m_cancelStatusFlag = NULL; + //if someone is waiting + event->signalFinishedFlag(); + } + } +}; +} +} // WrtDeviceApisCommon + +#endif /* WRTDEVICEAPIS_COMMONS_EVENT_RECEIVER_H_ */ diff --git a/src/Commons/Exception.h b/src/Commons/Exception.h new file mode 100644 index 0000000..78eba65 --- /dev/null +++ b/src/Commons/Exception.h @@ -0,0 +1,174 @@ +/* + * Copyright (c) 2011 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 WRTDEVICEAPIS_COMMONS_EXCEPTION_H_ +#define WRTDEVICEAPIS_COMMONS_EXCEPTION_H_ + +#include <string> +#include <dpl/exception.h> + +namespace WrtDeviceApis { +namespace Commons { +#define PLUGINS_DECLARE_EXCEPTION_TYPE(BaseClass, Class) \ + class Class : public BaseClass \ + { \ + public: \ + Class() = default; \ + \ + Class(const char *path, \ + const char *function, \ + int line, \ + const std::string & message = std::string()) : \ + BaseClass(path, function, line, message) \ + { } \ + \ + Class(const char *path, \ + const char *function, \ + int line, \ + const DPL::Exception & reason, \ + const std::string & message = std::string()) : \ + BaseClass(path, function, line, reason, message) \ + { } \ + \ + virtual ::WrtDeviceApis::Commons::ExceptionCodes::Enumeration getCode() const \ + { \ + return ::WrtDeviceApis::Commons::ExceptionCodes::Class; \ + } \ + }; + +class ExceptionCodes +{ + public: + enum Enumeration + { + None, + Exception, + InvalidArgumentException, + ConversionException, + NullPointerException, + UnknownException, + PlatformException, + OutOfRangeException, + EventCancelledException, + EventWrongStateException, + SecurityException, + UnsupportedException, + PlatformWrongStateException, + PendingOperationException, + AlreadyInUseException, + CameraCaptureException, + CameraLiveVideoException, + LocalStorageValueNoModifableException, + NotFoundException + }; +}; + +/** + * General exception. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(DPL::Exception, Exception) + +/** + * Thrown when passed argument is not of expected type. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, InvalidArgumentException) + +/** + * Thrown when type conversion is not possible. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, ConversionException) + +/** + * Thrown when trying to operate on an object which is set to NULL. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, NullPointerException) + +/** + * Thrown when unknown error occured. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, UnknownException) + +/** + * Thrown when platform function returned error code or threw an exception. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, PlatformException) + +/** + * Thrown when trying to access out of range element from array + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, OutOfRangeException) + +/** + * Thrown when trying to operate on cancelled event + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, EventCancelledException) + +/** + * Thrown when trying to operate on event in wrong state + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, EventWrongStateException) + +/** + * Thrown when trying to perform some action w/o proper permissions. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, SecurityException) + +/** + * Thrown when trying to perform action that is not supported by current + * platform. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, UnsupportedException) + +/** + * Thrown when trying to perform action on platform in wrong state. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, PlatformWrongStateException) + +/** + * Thrown when trying to perform asynchronous action on JS object + * that already executes other asynchronous operation. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, PendingOperationException) + +/** + * Thrown when used camera is already in use. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, AlreadyInUseException) + +/** + * Thrown when unpredicted error occurs while a picture or video is being + * captured + * or if endRecording is called while no video is currently captured. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, CameraCaptureException) + +/** + * camera live video cannot be provided. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, CameraLiveVideoException) + +/** + * Error trying to modify read only value + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, LocalStorageValueNoModifableException) + +/** + * Thrown when object is not found. + */ +PLUGINS_DECLARE_EXCEPTION_TYPE(Exception, NotFoundException) +} +} // WrtDeviceApisCommon + +#endif /* WRTDEVICEAPIS_COMMONS_EXCEPTION_H_ */ diff --git a/src/Commons/FunctionDeclaration.h b/src/Commons/FunctionDeclaration.h new file mode 100644 index 0000000..695caa6 --- /dev/null +++ b/src/Commons/FunctionDeclaration.h @@ -0,0 +1,168 @@ +/* + * Copyright (c) 2011 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 WRTDEVICEAPIS_COMMONS_FUNCTION_DECLARATION_ +#define WRTDEVICEAPIS_COMMONS_FUNCTION_DECLARATION_ + +#include <string> +#include <algorithm> +#include <dpl/log/wrt_log.h> +#include <Commons/WrtAccess/WrtAccess.h> +#include <Commons/Exception.h> +#include <Commons/TypesDeclaration.h> +#include <Commons/TypeTraits.h> +#include <Commons/plugin_initializer_def.h> + +#define ACE_DECLARE_FUNCTION(function_definition) \ + extern WrtDeviceApis::Commons::AceFunction ace_##function_definition + +#define ACE_DECLARE_PARAM(param_definition) \ + extern WrtDeviceApis::Commons::AceDeviceCapParam ace_param_## \ + param_definition + +class DevCapFinder +{ + public: + explicit DevCapFinder(const std::string& devcap) : m_searchFor(devcap) + {} + explicit DevCapFinder(const char* devcap) : m_searchFor(devcap) + {} + bool operator()(const WrtDeviceApis::Commons::AceDeviceCapability& dc) + const + { + return m_searchFor == dc.devCapName; + } + + private: + std::string m_searchFor; +}; + +#define ACE_ADD_DEV_CAP_PARAM(dev_caps_list, dev_cap_name, param) \ + do { \ + WrtDeviceApis::Commons::AceDeviceCaps::iterator devcapit = \ + std::find_if(dev_caps_list.begin(), \ + dev_caps_list.end(), \ + DevCapFinder(dev_cap_name)); \ + if (devcapit == dev_caps_list.end()) \ + { \ + ThrowMsg( \ + WrtDeviceApis::Commons::InvalidArgumentException, \ + "Trying to set a param that doesn't exist: " << \ + dev_cap_name); \ + } \ + else \ + { \ + WrtLogD("Setting dev cap %s param: %s to value %s", \ + dev_cap_name, param.name.c_str(), param.value.c_str()); \ + devcapit->devCapParams.push_back(param); \ + } \ + } while (0) + +/* + * Macro must be run inside plugin function. Plugin function must follow this + * declaration: + * plugin_example_function(JScontextRef cotext, JSObjectRef function, + * JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + * JSValueRef *exception); + * where context, arguments, argumentsCount, exception are fixed and could not + * be change. + * */ + +#define DECLARE_FUNCTION_GETTER(Plugin_Module) \ + WrtDeviceApis::Commons::AceFunction get##Plugin_Module##FunctionData( \ + const std::string & functionId); + +#define DEFINE_FUNCTION_GETTER(Plugin_Module, FunctionMap) \ + WrtDeviceApis::Commons::AceFunction get##Plugin_Module##FunctionData( \ + const std::string & functionId) \ + { \ + WrtDeviceApis::Commons::FunctionMapping::const_iterator it = \ + FunctionMap.find(functionId); \ + if (it == FunctionMap.end()) \ + { \ + std::string errorMsg(); \ + ThrowMsg(WrtDeviceApis::Commons::InvalidArgumentException, \ + "Function with id " << functionId << "not found"); \ + } \ + return it->second; \ + } + +typedef WrtDeviceApis::Commons::AceFunction (&AceFunctionGetter)(const std:: + string&); + +namespace WrtDeviceApis { +namespace Commons { +enum class AceSecurityStatus +{ + AccessGranted, + AccessDenied, + PrivacyDenied, + InternalError +}; + +template <typename ... Args> +class DefaultArgsVerifier +{ + public: + void operator()(AceFunction& aceFunction, Args && ... args) const + { + static_assert( + WrtDeviceApis::Commons::AlwaysFalse<Args ...>::value, + "Please provide a specialization for these argument types!"); + } +}; + +template <> +class DefaultArgsVerifier<> +{ + public: + void operator()(AceFunction& /*aceFunction*/) const + {} +}; + +template <typename FunctionGetter, + typename ArgumentsVerifier, + typename ... Args> +AceSecurityStatus aceCheckAccess( + const FunctionGetter& f, + const char* functionName, + Args && ... args) +{ + using namespace WrtDeviceApis::Commons; + + AceFunction aceFunction = f(functionName); + + ArgumentsVerifier argsVerify; + argsVerify(aceFunction, args ...); + + WrtAccess::CheckAccessReturnType ret = + WrtAccessSingleton::Instance().checkAccessControl(aceFunction); + + if (ret == WrtAccess::CHECK_ACCESS_PRIVILEGE_DENIED) { + return AceSecurityStatus::AccessDenied; + } + else if (ret == WrtAccess::CHECK_ACCESS_PRIVACY_DENIED) { + return AceSecurityStatus::PrivacyDenied; + } + else if (ret == WrtAccess::CHECK_ACCESS_INTERNAL_ERROR) { + return AceSecurityStatus::InternalError; + } + + return AceSecurityStatus::AccessGranted; +} +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_FUNCTION_DECLARARION_ diff --git a/src/Commons/FunctionDefinition.cpp b/src/Commons/FunctionDefinition.cpp new file mode 100644 index 0000000..4209994 --- /dev/null +++ b/src/Commons/FunctionDefinition.cpp @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2011 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 "FunctionDefinition.h" + +namespace WrtDeviceApis { +namespace Commons { +int aceAddDeviceCap(const AceDeviceCapability& cap, + AceDeviceCaps &instance) +{ + instance.push_back(cap); + return 0; +} + +int aceAddApiFeature(const AceFeature& apiFeature, + AceFeatures& instance) +{ + instance.push_back(apiFeature); + return 0; +} +} +} // WrtDeviceApisCommon diff --git a/src/Commons/FunctionDefinition.h b/src/Commons/FunctionDefinition.h new file mode 100644 index 0000000..fa8b32c --- /dev/null +++ b/src/Commons/FunctionDefinition.h @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2011 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 WRTDEVICEAPIS_COMMONS_FUNCTION_DEFINITION_ +#define WRTDEVICEAPIS_COMMONS_FUNCTION_DEFINITION_ + +#include <map> +#include <string> +#include <Commons/FunctionDeclaration.h> + +namespace WrtDeviceApis { +namespace Commons { +/** + * Creates an empty device cap list. Additional device-caps may be added by + * ACE_CREATE_DEVICE_CAP and ACE_ADD_DEVICE_CAP macros + */ +#define ACE_CREATE_DEVICE_CAPS_LIST(device) \ + WrtDeviceApis::Commons::AceDeviceCaps ace_##device + +/** + * Creates an empty api features list. Additional api features may be added by + * ACE_CREATE_FEATURE and ACE_ADD_API_FEATURE macros + */ +#define ACE_CREATE_FEATURE_LIST(apifeature) \ + WrtDeviceApis::Commons::AceFeatures ace_##apifeature + +/** + * Creates a device capability which should be later added to device cap list + */ +#define ACE_CREATE_DEVICE_CAP(device_cap_id, cap_id) \ + WrtDeviceApis::Commons::AceDeviceCapability ace_##device_cap_id = \ + AceDeviceCapability(cap_id, WrtDeviceApis::Commons::AceDeviceCapParams()); + +/** + * Create an api feature which should be later added to api features list + */ +#define ACE_CREATE_FEATURE(feature_id, feature_api) \ + WrtDeviceApis::Commons::AceFeature ace_##feature_id = { feature_api \ + }; + +/** + * Adds an existing device-cap created by ACE_CREATE_DEVICE_CAP macro to + * device cap list + */ +#define ACE_ADD_DEVICE_CAP(device, device_cap_id) \ + WrtDeviceApis::Commons::aceAddDeviceCap(ace_##device_cap_id, ace_##device) + +/** + * Adds an existing api feature created by ACE_CREATE_FEATURE macro to + * api feature list + */ +#define ACE_ADD_API_FEATURE(apifeature, feature_id) \ + WrtDeviceApis::Commons::aceAddApiFeature(ace_##feature_id, \ + ace_##apifeature) + +/** + * Creates a function definition with given id that uses provided api feature + * and device capability lists + */ +#define ACE_CREATE_FUNCTION(function_id, function_name, feature_id, device) \ + { function_name, ace_##feature_id, ace_##device } + +// Support for param:name begin +#define ACE_CREATE_PARAM(param_definition, param_name, position) \ + static WrtDeviceApis::Commons::AceDeviceCapParam ace_param_## \ + param_definition = \ + { std::string(param_name), position }; + +// Support for param:name end + +typedef std::map <std::string, AceFunction> FunctionMapping; + +int aceAddDeviceCap(const AceDeviceCapability &cap, + AceDeviceCaps & instance); +int aceAddApiFeature(const AceFeature &apiFeature, + AceFeatures & instance); +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_FUNCTION_DEFINITION diff --git a/src/Commons/IEvent.h b/src/Commons/IEvent.h new file mode 100644 index 0000000..3c29590 --- /dev/null +++ b/src/Commons/IEvent.h @@ -0,0 +1,385 @@ +/* + * Copyright (c) 2011 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. + */ +/* + * @author Karol Majewski (k.majewski@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRTDEVICEAPIS_COMMONS_IEVENT_H_ +#define WRTDEVICEAPIS_COMMONS_IEVENT_H_ + +#include <memory> + +#include <assert.h> +#include <dpl/log/wrt_log.h> +#include <dpl/event/controller.h> +#include <dpl/mutex.h> +#include <Commons/Exception.h> +#include <Commons/EventReceiver.h> + +namespace WrtDeviceApis { +namespace Commons { +class IEventPrivateData +{ + public: + virtual ~IEventPrivateData() + {} +}; + +class IEventController +{ + std::shared_ptr<IEventPrivateData> m_privateData; + + public: + virtual void waitTillProcessed() = 0; + virtual void waitForAnswer() = 0; + virtual bool cancelRequest() + { + return false; + } + virtual bool changeCallToSynchronous() = 0; + virtual ~IEventController() + {} + + void setPrivateData( + const std::shared_ptr<IEventPrivateData> &privateData) + { + m_privateData = privateData; + } + const std::shared_ptr<IEventPrivateData>& getPrivateData() + { + return m_privateData; + } +}; +typedef std::shared_ptr<IEventController> IEventControllerPtr; + +// CRTP pattern +template<class Super> +class IEvent : /*private DPL::WaitableEvent, */ public IEventController +{ + public: + friend class EventRequestReceiver<Super>; + friend class EventAnswerReceiver<Super>; + friend class SignalEventCall<Super>; + friend class EventReceiver<Super>; + + enum HandlingType + { + HANDLING_NOT_SET = -1, + HANDLING_SYNCHRONOUS = 0, + HANDLING_ASYNCHRONOUS = 1, + HANDLING_SYNCHRONOUS_MANUAL_ANSWER = 2, + HANDLING_ASYNCHRONOUS_MANUAL_ANSWER = 3 + }; + + enum State + { + STATE_INITIAL, + STATE_REQUEST_SEND, + STATE_REQUEST_RECEIVED, + STATE_ANSWER_SEND, + STATE_ANSWER_RECEIVED, + STATE_ENDED, + STATE_CHANGED_TO_SYNCHRONOUS + }; + + private: + void handleCancel() + { + clearOnCancel(); + m_state = STATE_ENDED; + m_exceptionCode = Commons::ExceptionCodes::EventCancelledException; + //if someone is waiting + signalSynchronousEventFlag(); + } + + protected: + DPL::Mutex m_stateMutex; + State m_state; + HandlingType m_handlingType; + EventAnswerReceiver< Super > *m_remoteController; + Commons::ExceptionCodes::Enumeration m_exceptionCode; + DPL::WaitableEvent *m_synchronousEventFlag; + DPL::WaitableEvent *m_finishedFlag; + DPL::WaitableEvent *m_cancelStatusFlag; + bool m_cancelSignalAhead; + bool m_cancelled; + bool m_cancelAllowed; + + IEvent() : + m_state(STATE_INITIAL), + m_handlingType(HANDLING_NOT_SET), + m_remoteController(NULL), + m_exceptionCode(Commons::ExceptionCodes::None), + m_synchronousEventFlag(NULL), + m_finishedFlag(NULL), + m_cancelStatusFlag(NULL), + m_cancelSignalAhead(false), + m_cancelled(false), + m_cancelAllowed(false) + {} + + virtual void waitForAnswer() + { + assert(HANDLING_SYNCHRONOUS == m_handlingType); + DPL::WaitForSingleHandle(m_synchronousEventFlag->GetHandle()); + { + DPL::Mutex::ScopedLock lock(&m_stateMutex); + m_state = STATE_ENDED; + } + signalFinishedFlag(); + WrtLogD("deleting m_processEvent"); + delete m_synchronousEventFlag; + m_synchronousEventFlag = NULL; + } + + void signalFinishedFlag() + { + if (m_finishedFlag) { + m_finishedFlag->Signal(); + } + } + + DPL::WaitableEvent &getFinishedFlag() + { + if (!m_finishedFlag) { + m_finishedFlag = new DPL::WaitableEvent(); + } + return *m_finishedFlag; + } + + void signalCancelStatusFlag() + { + WrtLogD("signaling cancel"); + DPL::Mutex::ScopedLock lock(&m_stateMutex); + m_cancelSignalAhead = true; + if (m_cancelStatusFlag) { + m_cancelStatusFlag->Signal(); + } + } + + DPL::WaitableEvent &getCancelStatusFlag() + { + if (!m_cancelStatusFlag) { + m_cancelStatusFlag = new DPL::WaitableEvent(); + } + return *m_cancelStatusFlag; + } + + void signalSynchronousEventFlag() + { + if (m_synchronousEventFlag) { + m_synchronousEventFlag->Signal(); + } + } + + public: + + /* + * Gets the answer receiver pointer. + */ + EventAnswerReceiver< Super > * getAnswerReceiverRef() const + { + return m_remoteController; + } + + virtual ~IEvent() + { + delete m_cancelStatusFlag; + delete m_finishedFlag; + delete m_synchronousEventFlag; + } + + virtual bool changeCallToSynchronous() + { + return setForSynchronousCall(); + } + + virtual void waitTillProcessed() + { + DPL::WaitForSingleHandle(getFinishedFlag().GetHandle()); + delete m_finishedFlag; + m_finishedFlag = NULL; + } + + virtual void clearOnCancel() + {} + + Commons::ExceptionCodes::Enumeration getExceptionCode() const + { + return m_exceptionCode; + } + void setExceptionCode(Commons::ExceptionCodes::Enumeration exceptionCode) + { + m_exceptionCode = exceptionCode; + } + + short getHandlingType() const + { + return m_handlingType; + } + + virtual bool setForSynchronousCall() + { + DPL::Mutex::ScopedLock lock(&m_stateMutex); + if (m_cancelled) { + return false; + } + switch (m_state) { + case STATE_ANSWER_SEND: + m_state = STATE_CHANGED_TO_SYNCHRONOUS; + break; + case STATE_ANSWER_RECEIVED: + case STATE_ENDED: + return false; + default: + break; + } + m_handlingType = HANDLING_SYNCHRONOUS; + return true; + } + + virtual bool setForAsynchronousCall( + EventAnswerReceiver< Super > *remoteController) + { + DPL::Mutex::ScopedLock lock(&m_stateMutex); + if (m_cancelled) { + return false; + } + switch (m_state) { + case STATE_ANSWER_SEND: + case STATE_ANSWER_RECEIVED: + case STATE_ENDED: + return false; + default: + break; + } + m_handlingType = HANDLING_ASYNCHRONOUS; + m_remoteController = remoteController; + return true; + } + + /* + * Normally, after invoking OnRequestReceived in RequestReceiver, the answer + * is being send automatically (after flow leaves OnRequestReceived). + * After calling this function, the answer is not being send automatically, + * you need to call ManualAnswer to send event back. + * It works both in asynchronous and synchronous handling type. + */ + virtual bool switchToManualAnswer() + { + assert( + m_handlingType == HANDLING_ASYNCHRONOUS || m_handlingType == + HANDLING_SYNCHRONOUS); + + DPL::Mutex::ScopedLock lock(&m_stateMutex); + if (m_cancelled) { + return false; + } + switch (m_state) { + case STATE_ANSWER_SEND: + case STATE_ANSWER_RECEIVED: + case STATE_ENDED: + return false; + default: + break; + } + + switch (m_handlingType) { + case HANDLING_ASYNCHRONOUS: + m_handlingType = HANDLING_ASYNCHRONOUS_MANUAL_ANSWER; + break; + case HANDLING_SYNCHRONOUS: + m_handlingType = HANDLING_SYNCHRONOUS_MANUAL_ANSWER; + break; + default: + break; + } + return true; + } + + bool checkCancelled() + { + //DPL::Mutex::ScopedLock lock(&m_stateMutex); + return m_cancelled; + } + + void tryCancelled() + { + //DPL::Mutex::ScopedLock lock(&m_stateMutex); + if (m_cancelled) { + Throw(Commons::EventCancelledException); + } + } + + bool getCancelAllowed() const + { + return m_cancelAllowed; + } + + void setCancelAllowed(bool cancelAllowed) + { + m_cancelAllowed = cancelAllowed; + } + + bool cancelRequest() + { + WrtLogD("trying to cancel"); + assert(HANDLING_ASYNCHRONOUS == m_handlingType || + HANDLING_ASYNCHRONOUS_MANUAL_ANSWER == m_handlingType); + bool signaled = false; + { + DPL::Mutex::ScopedLock lock(&m_stateMutex); + if (m_cancelled) { + return false; + } + switch (m_state) { + case STATE_INITIAL: + assert(0); + case STATE_ANSWER_SEND: + WrtLogD("cancelling"); + m_cancelled = true; + delete m_cancelStatusFlag; + m_cancelStatusFlag = NULL; + return m_cancelAllowed; + case STATE_ANSWER_RECEIVED: + case STATE_ENDED: + return false; + default: + break; + } + WrtLogD("cancelling"); + m_cancelled = true; + signaled = m_cancelSignalAhead; + if (!signaled) { + //create waitable handle + getCancelStatusFlag(); + } + } + WrtLogD("waiting for cancel flag"); + if (!signaled) { + DPL::WaitForSingleHandle(getCancelStatusFlag().GetHandle()); + } + delete m_cancelStatusFlag; + m_cancelStatusFlag = NULL; + return m_cancelAllowed; + } +}; +} +} // WrtDeviceApisCommon + +#endif /* WRTDEVICEAPIS_COMMONS_IEVENT_H_ */ diff --git a/src/Commons/IExternEventCanceler.h b/src/Commons/IExternEventCanceler.h new file mode 100644 index 0000000..487b33b --- /dev/null +++ b/src/Commons/IExternEventCanceler.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2011 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. + */ +/* + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRTDEVICEAPIS_COMMONS_IEXTERN_EVENT_CANCELER_H_ +#define WRTDEVICEAPIS_COMMONS_IEXTERN_EVENT_CANCELER_H_ + +#include <memory> + +#include <dpl/log/wrt_log.h> + +namespace WrtDeviceApis { +namespace Commons { +/** + * This class is related to JSPendingOperation object. + * + * It is interface for controllers which want to perform + * an additional accation when the PendingOberation object + * is canceled. + * */ +template<class TemplateEvent> +class IExternEventCanceler +{ + public: + virtual void OnCancelEvent(const std::shared_ptr<TemplateEvent>& event) = 0; + + virtual ~IExternEventCanceler() + {} +}; +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_IEXTERN_EVENT_CANCELER_H_ diff --git a/src/Commons/JSObject.cpp b/src/Commons/JSObject.cpp new file mode 100644 index 0000000..12d21f3 --- /dev/null +++ b/src/Commons/JSObject.cpp @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2011 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. + */ +/** + * @file js_object.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ + +#include "JSObject.h" +#include <dpl/log/wrt_log.h> + +JSObject::JSObject(RealObject object) : m_object(object) +{ + if (!object) { + WrtLogE("Object is NULL"); + } +} + +JSObject::RealObject JSObject::getObject() const +{ + return m_object; +} diff --git a/src/Commons/JSObject.h b/src/Commons/JSObject.h new file mode 100644 index 0000000..399b6da --- /dev/null +++ b/src/Commons/JSObject.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2011 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. + */ +/** + * @file js_object.h + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ + +#ifndef WRT_SRC_PLUGIN_SERVICE_JS_OBJECT_H_ +#define WRT_SRC_PLUGIN_SERVICE_JS_OBJECT_H_ + +#include <memory> + +#include <dpl/noncopyable.h> + +class JSObject : private DPL::Noncopyable +{ + public: + typedef void* RealObject; + + public: + explicit JSObject(RealObject object); + + /** + * returns javascript engine object + * @throw NullPtrException + * */ + virtual RealObject getObject() const; + + virtual ~JSObject() + {} + + private: + RealObject m_object; +}; + +typedef std::shared_ptr<JSObject> JSObjectPtr; + +#endif diff --git a/src/Commons/JSObjectDeclaration.cpp b/src/Commons/JSObjectDeclaration.cpp new file mode 100755 index 0000000..978caaf --- /dev/null +++ b/src/Commons/JSObjectDeclaration.cpp @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2011 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. + */ +/** + * @file js_object_declaration.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ + +#include <dpl/log/wrt_log.h> +#include <dpl/assert.h> +#include "JSObjectDeclaration.h" + +JSObjectDeclaration::JSObjectDeclaration(js_entity_definition_ptr_t classD) : + m_name(classD->object_name), + m_parentName(classD->parent_name), + m_interfaceName(classD->interface_name), + m_classTemplate(NULL), + m_constructorCallback(classD->js_class_constructor_cb) +{ + if (NULL != classD->js_class_template_getter_fun) { + m_classTemplate = classD->js_class_template_getter_fun(); + } + if (classD->class_options) { + m_options = OptionsPtr(new Options(classD->class_options)); + } +} + +JSObjectDeclaration::~JSObjectDeclaration() +{} + +bool JSObjectDeclaration::checkIframesSupported() const +{ + if (!m_options || + m_options->getIframeObject() == Options::IFrameObject::None) + { + return false; + } + + return true; +} + +JSObjectDeclaration::Options::ClassType +JSObjectDeclaration::Options::getType() const +{ + AssertMsg(m_options, "Pointer to options is NULL"); + + switch (m_options->type) { + case JS_CLASS: return ClassType::Class; + case JS_FUNCTION: return ClassType::Function; + case JS_INTERFACE: return ClassType::Interface; + default: Assert(!"Wrong value of type"); + } +} + +JSObjectDeclaration::Options::IFrameObject +JSObjectDeclaration::Options::getIframeObject() const +{ + AssertMsg(m_options, "Options object is NULL"); + + switch (m_options->iframe_option) { + case NONE: return IFrameObject::None; + case REFERENCE: return IFrameObject::Reference; // deprecated + case CREATE_INSTANCE: return IFrameObject::CreateInstance; + default: + Assert(!"Wrong value of behaviour type"); + } +} + +JSObjectDeclaration::Options::IFrameNotice +JSObjectDeclaration::Options::getIframeNotice() const +{ + AssertMsg(m_options, "Pointer to options is null"); + + switch (m_options->iframe_notice) { + case NONE_NOTICE: return IFrameNotice::None; + case ALWAYS_NOTICE: return IFrameNotice::AlwaysNotice; + default: + Assert(!"Wrong value of notice option"); + } +} + +js_function_impl JSObjectDeclaration::Options::getFunctionImpl() const +{ + AssertMsg(m_options, "Pointer to options is null"); + return m_options->function; +} + +void JSObjectDeclaration::Options::invokeCallback(JsContext ctx, + ObjectInstance iframe, + ObjectInstance object) const +{ + WrtLogD("JS Object create, notice."); + AssertMsg(m_options && m_options->cb, "Empty callback pointer"); + m_options->cb(ctx, iframe, object); +} + +JSObjectDeclaration::Options::PrivateData +JSObjectDeclaration::Options::getPrivateData() const +{ + AssertMsg(m_options && m_options->private_data, "empty private data"); + return m_options->private_data; +} diff --git a/src/Commons/JSObjectDeclaration.h b/src/Commons/JSObjectDeclaration.h new file mode 100644 index 0000000..f19ba19 --- /dev/null +++ b/src/Commons/JSObjectDeclaration.h @@ -0,0 +1,151 @@ +/* + * Copyright (c) 2011 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. + */ +/** + * @file js_object_declaration.h + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ + +#ifndef WRT_SRC_PLUGIN_SERVICE_JS_OBJECT_DECLARATION_H_ +#define WRT_SRC_PLUGIN_SERVICE_JS_OBJECT_DECLARATION_H_ + +#include <string> +#include <memory> +#include <cassert> +#include <dpl/noncopyable.h> +#include <wrt_plugin_export.h> + +class JSObjectDeclaration : private DPL::Noncopyable +{ + public: + typedef const void* ConstClassTemplate; + typedef void* ClassTemplate; + typedef js_class_constructor_cb_t ConstructorCallback; + typedef class_definition_options_t ClassOptions; + + class Options : DPL::Noncopyable + { + public: + enum class ClassType + { + Class, + Function, + Interface + }; + + enum class IFrameObject + { + None, + Reference, + CreateInstance + }; + + enum class IFrameNotice + { + None, + AlwaysNotice + }; + + //only for function + enum class IFrameOverlay + { + Ignored, + UseOverlayed, //deprecated + OverlayedBeforeOriginal //deprecated + }; + + typedef js_object_instance_t ObjectInstance; + typedef java_script_context_t JsContext; + typedef void* PrivateData; + + public: + ClassType getType() const; + + IFrameObject getIframeObject() const; + IFrameNotice getIframeNotice() const; + js_function_impl getFunctionImpl() const; + + void invokeCallback(JsContext ctx, + ObjectInstance iframe, + ObjectInstance object) const; + + PrivateData getPrivateData() const; + + private: + const ClassOptions* m_options; + + private: + explicit Options(const ClassOptions* options) : m_options(options) + { + assert(options && "Dont create empty options"); + } + + friend class JSObjectDeclaration; + }; + + typedef std::shared_ptr<Options> OptionsPtr; + + public: + + explicit JSObjectDeclaration(js_entity_definition_ptr_t declaration); + + virtual const std::string& getName() const + { + return m_name; + } + + virtual const std::string& getParentName() const + { + return m_parentName; + } + + virtual ConstClassTemplate getClassTemplate() const + { + return m_classTemplate; + } + + virtual const std::string& getInterfaceName() const + { + return m_interfaceName; + } + + virtual ConstructorCallback getConstructorCallback() const + { + return m_constructorCallback; + } + + const OptionsPtr getOptions() const + { + return m_options; + } + + bool checkIframesSupported() const; + + virtual ~JSObjectDeclaration(); + + private: + std::string m_name; + std::string m_parentName; + std::string m_interfaceName; + ConstClassTemplate m_classTemplate; + ConstructorCallback m_constructorCallback; + OptionsPtr m_options; +}; + +typedef std::shared_ptr<JSObjectDeclaration> JSObjectDeclarationPtr; + +#endif diff --git a/src/Commons/ListenerEvent.h b/src/Commons/ListenerEvent.h new file mode 100644 index 0000000..462c0ad --- /dev/null +++ b/src/Commons/ListenerEvent.h @@ -0,0 +1,132 @@ +/* + * Copyright (c) 2011 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. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_COMMONS_LISTENER_EVENT_H_ +#define WRTDEVICEAPIS_COMMONS_LISTENER_EVENT_H_ + +#include <memory> + +#include <dpl/mutex.h> +#include <dpl/noncopyable.h> +#include <Commons/Exception.h> +#include <Commons/IEvent.h> + +namespace WrtDeviceApis { +namespace Commons { +template<class EventClass> +class ListenerEventEmitter; + +/** + * This is base class for events that should act as signals between abstract + * layer and layer that uses it (e.g. JS layer in WRT plugins). + * Such event is created by specific event emitter from abstract layer + * and passed asynchronously to object that acts as event listener. + * Template parameter should be class of an event which derives from + * this class (co called CRTP pattern). + */ +template<class Derived> +class ListenerEvent +{ + friend class ListenerEventEmitter<Derived>; + + public: + typedef IEventPrivateData PrivateDataType; + typedef std::shared_ptr<PrivateDataType> PrivateDataTypePtr; + + public: + virtual ~ListenerEvent() + { + delete m_mtx; + } + + /** + * Gets exception code. + * @return Exception code. + */ + Commons::ExceptionCodes::Enumeration getExceptionCode() const + { + DPL::Mutex::ScopedLock lock(m_mtx); + return m_code; + } + + /** + * Sets exception code. + * @param code Exception code. + * @throw EventWrongStateExeption When event has already been emitted. + */ + void setExceptionCode(Commons::ExceptionCodes::Enumeration code) + { + DPL::Mutex::ScopedLock lock(m_mtx); + m_code = code; + } + + /** + * Gets event's private data. + * @return Private data (use DPL cast to proper object). + */ + const PrivateDataTypePtr& getPrivateData() const + { + DPL::Mutex::ScopedLock lock(m_mtx); + return m_privateData; + } + + protected: + ListenerEvent() : + m_mtx(new DPL::Mutex()), + m_code(Commons::ExceptionCodes::None) + {} + + ListenerEvent(const ListenerEvent &ths) : + m_mtx(new DPL::Mutex()), + m_code(ths.m_code), + m_privateData(ths.m_privateData) + {} + + ListenerEvent& operator=(const ListenerEvent &other) + { + if (this != &other) { + m_mtx = new DPL::Mutex(); + m_code = other.m_code; + m_privateData = other.m_privateData; + } + return *this; + } + + /** + * Sets event's private data. + * Event's private data object has to implement @see IEventPrivateData + * interface. + * @param data Private data. + * @throw EventWrongStateExeption When event has already been emitted. + */ + void setPrivateData(const PrivateDataTypePtr& data) + { + DPL::Mutex::ScopedLock lock(m_mtx); + m_privateData = data; + } + + protected: + mutable DPL::Mutex *m_mtx; + Commons::ExceptionCodes::Enumeration m_code; ///< Exception code. + PrivateDataTypePtr m_privateData; ///< Private data. +}; +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_LISTENER_EVENT_H_ diff --git a/src/Commons/ListenerEventEmitter.h b/src/Commons/ListenerEventEmitter.h new file mode 100644 index 0000000..b48876c --- /dev/null +++ b/src/Commons/ListenerEventEmitter.h @@ -0,0 +1,148 @@ +/* + * Copyright (c) 2011 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. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_COMMONS_LISTENER_EVENT_EMITTER_H_ +#define WRTDEVICEAPIS_COMMONS_LISTENER_EVENT_EMITTER_H_ + +#include <memory> + +#include <stdint.h> +#include <dpl/noncopyable.h> +#include <dpl/mutex.h> +#include <Commons/EventListener.h> +#include <Commons/ListenerEvent.h> + +namespace WrtDeviceApis { +namespace Commons { +template<class EmitterClass> +class Emitters; + +/** + * Creates listener events in the abstraction layer in response to some + * asynchronous action. + * To enable passing events from abstract layer to layer that uses it, first + * proper event emitter should be registered in abstract layer by the layer + * that uses it. Then when some action happens in abstract layer event should be + * created and passed to this emitter's emit() function. Then emitter passes + * this event to proper listener. + * Template parameter should be class that derives from @see ListenerEvent. + */ +template<class EventClass> +class ListenerEventEmitter : private DPL::Noncopyable +{ + public: + typedef EventClass EventType; + typedef std::shared_ptr<EventType> EventPtrType; + typedef ListenerEventEmitter<EventType> Type; + typedef typename ListenerEvent<EventType>::PrivateDataType + EventPrivateDataType; + typedef typename ListenerEvent<EventType>::PrivateDataTypePtr + EventPrivateDataTypePtr; + typedef EventListener<EventType> ListenerType; + typedef uintptr_t IdType; + + /** + * Empty (NULL) value of emitter's Id. + */ + static const IdType emptyId; + + public: + ListenerEventEmitter() : m_listener(NULL) + {} + + public: + virtual ~ListenerEventEmitter() + {} + + /** + * Sets event's private data. + * Event's private data object has to implement @see IEventPrivateData + * interface. + * @param data Private data. + * @remarks Practically private dat should be only set at object creation + * and + * not chaged during this object lifetime. + */ + virtual void setEventPrivateData(const EventPrivateDataTypePtr& data) + { + DPL::Mutex::ScopedLock lock(&m_mtx); + m_privateData = data; + } + + /** + * Gets event's private data. + * @return Private data. + */ + virtual EventPrivateDataTypePtr getEventPrivateData() + { + DPL::Mutex::ScopedLock lock(&m_mtx); + return m_privateData; + } + + /** + * Sets listener. + * Object set as listener has to implement @see EventListener interface. + * @param listener Listener object. + * @remarks Doesn't take ownership over this object. + * It's suggested to use singletons to have one listener for all + * events (no dynamic allocation overhead). + */ + virtual void setListener(ListenerType* listener) + { + DPL::Mutex::ScopedLock lock(&m_mtx); + m_listener = listener; + } + + /** + * Emits event. + * @param event Event to emit. + */ + virtual void emit(const EventPtrType& event) + { + DPL::Mutex::ScopedLock lock(&m_mtx); + EventPtrType copy(new EventType(*event.get())); + if (m_listener) { + copy->setPrivateData(m_privateData); + m_listener->postAnswer(copy); + } + } + + /** + * Gets id. + * @return Event's id. + * @remarks Id is implemented as value of `this` pointer. + */ + virtual IdType getId() + { + return reinterpret_cast<IdType>(this); + } + + protected: + DPL::Mutex m_mtx; ///< Mutex for thread-safety. + ListenerType* m_listener; ///< Event listener object. + EventPrivateDataTypePtr m_privateData; ///< Private data. +}; + +template<class EventClass> +const typename ListenerEventEmitter<EventClass>::IdType ListenerEventEmitter< + EventClass>::emptyId = 0; +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_LISTENER_EVENT_EMITTER_H_ diff --git a/src/Commons/Range.h b/src/Commons/Range.h new file mode 100644 index 0000000..ab731e1 --- /dev/null +++ b/src/Commons/Range.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2011 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. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_COMMONS_RANGE_H_ +#define WRTDEVICEAPIS_COMMONS_RANGE_H_ + +namespace WrtDeviceApis { +namespace Commons { +/** + * Stores data describing a range of values. + */ +template<typename Type> +struct Range +{ + /** + * Type of value. + */ + typedef Type ValueType; + + /** + * Value representing minimum. + */ + ValueType min; + + /** + * Value representing maximum. + */ + ValueType max; +}; +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_RANGE_H_ diff --git a/src/Commons/Regex.cpp b/src/Commons/Regex.cpp new file mode 100644 index 0000000..9284d3f --- /dev/null +++ b/src/Commons/Regex.cpp @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2011 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 <pcrecpp.h> +#include "Regex.h" + +namespace WrtDeviceApis { +namespace Commons { +bool validate(const std::string &pattern, + const std::string &value, + unsigned int options) +{ + pcrecpp::RE_Options pcreOpt; + if (options & VALIDATE_MATCH_CASELESS) { + pcreOpt.set_caseless(true); + } + pcrecpp::RE re(pattern, pcreOpt); + if (options & VALIDATE_MATCH_FULL) { + return re.FullMatch(value); + } + return re.PartialMatch(value); +} + +std::string filter(const std::string &pattern, + const std::string &value) +{ + pcrecpp::RE re(pattern); + std::string ret = static_cast<std::string>(value); + re.GlobalReplace("", &ret); + return ret; +} + +std::string toUpper(const std::string &value) +{ + pcrecpp::RE re(LOWER_P); + std::string ret = static_cast<std::string>(value); + re.GlobalReplace(UPPER_P, &ret); + return ret; +} +} +} // WrtDeviceApisCommon diff --git a/src/Commons/Regex.h b/src/Commons/Regex.h new file mode 100644 index 0000000..f6c046b --- /dev/null +++ b/src/Commons/Regex.h @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2011 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 WRTDEVICEAPIS_COMMONS_REGEX_H_ +#define WRTDEVICEAPIS_COMMONS_REGEX_H_ + +#include <string> + +namespace WrtDeviceApis { +namespace Commons { +const unsigned int VALIDATE_MATCH_CASELESS = 0x0001; //use when you want to + // make caseless match +const unsigned int VALIDATE_MATCH_FULL = 0x0002; //use when you want + // supplied text + // matches a supplied + // pattern exactly +const std::string LOWER_P = "p"; +const std::string UPPER_P = "P"; + +/** + * Validates value against pattern + * @param pattern Regexp pattern + * @param value String to validate + * @param options Modifiers for a match. + * @return True when value is matched against pattern + */ +bool validate(const std::string &pattern, + const std::string &value, + unsigned int options = 0); + +/** + * Filter value against pattern(Any character except "0-9+#*Pp" will be removed + * from value) + * @param pattern Regexp pattern + * @param value String to be filtered + * @return filtered value + */ +std::string filter(const std::string &pattern, + const std::string &value); + +/** + * Replace character "p" in value by "P" + * @param value String to be replaced + * @return replaced value + */ +std::string toUpper(const std::string &value); +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_REGEX_H_ diff --git a/src/Commons/RegexPatterns.h b/src/Commons/RegexPatterns.h new file mode 100644 index 0000000..3c9ceb6 --- /dev/null +++ b/src/Commons/RegexPatterns.h @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2011 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 WRTDEVICEAPIS_COMMONS_REGEX_PATTERNS_H_ +#define WRTDEVICEAPIS_COMMONS_REGEX_PATTERNS_H_ + +#include <string> + +namespace WrtDeviceApis { +namespace Commons { +const std::string PATTERN_PHONE_NUMBER_FILTER("[^0-9+#*Pp]"); +const std::string PATTERN_PHONE_NUMBER("^[0-9#+*]+$"); +const std::string PATTERN_PHONE_NUMBER_P("^\\+?[0-9#*Pp]*[0-9][0-9#*Pp]*$"); +const std::string PATTERN_PHONE_NUMBER_PW("^[0-9#+*PpWw]+$"); +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_REGEX_PATTERNS_H_ diff --git a/src/Commons/RegexUtils.cpp b/src/Commons/RegexUtils.cpp new file mode 100644 index 0000000..db749e7 --- /dev/null +++ b/src/Commons/RegexUtils.cpp @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2011 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 "RegexUtils.h" +#include <pcrecpp.h> +#include "StringUtils.h" + +namespace WrtDeviceApis { +namespace Commons { +std::string addStartPositionMark(const std::string &value) +{ + if (!String::startsWith(value, "^") && !String::startsWith(value, ".*")) { + return "^" + value; + } + return value; +} + +std::string addEndPositionMark(const std::string &value) +{ + if ((!String::endsWith(value, "$") || String::endsWith(value, "\\$")) && + !String::endsWith(value, ".*")) + { + return value + "$"; + } + return value; +} + +std::string addStartAndEndPositionMark(const std::string &value) +{ + return addEndPositionMark(addStartPositionMark(value)); +} + +std::string preparePercent(const std::string& str) +{ + std::string result = escape(str); + pcrecpp::RE("(([^\\\\])\\*|^()\\*)").GlobalReplace("\\2\\\\*", &result); + pcrecpp::RE("(([^\\\\])%|^()%)").GlobalReplace("\\2.*", &result); + return result; +} + +std::string prepareAsterisk(const std::string& str) +{ + std::string result = escape(str); + // Replaces single wildcard "*" with version more compliant with Perl + // regular exrepssions, i.e. ".*". + pcrecpp::RE("(([^\\\\])\\*|^()\\*)").GlobalReplace("\\2.*", &result); + return result; +} + +std::string escape(const std::string& str) +{ + std::string result = str; + // Escape standard regular expressions' metacharacters, + // i.e.: \, ., -, +, ?, (, ), [, ], ^, $, | + const char* metas = "(\\.|\\-|\\+|\\?|\\(|\\)|\\[|\\]|\\^|\\$|\\|" + "|(\\\\[^\\*\\%]|\\\\$))"; // \*, \% won't get + // additional '\' + pcrecpp::RE(metas).GlobalReplace("\\\\\\1", &result); + return result; +} +} +} // WrtDeviceApisCommon diff --git a/src/Commons/RegexUtils.h b/src/Commons/RegexUtils.h new file mode 100644 index 0000000..a06e1cd --- /dev/null +++ b/src/Commons/RegexUtils.h @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2011 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 WRTDEVICEAPIS_COMMONS_REGEX_UTILS_H_ +#define WRTDEVICEAPIS_COMMONS_REGEX_UTILS_H_ + +#include <string> + +namespace WrtDeviceApis { +namespace Commons { +/** + * Adds ^ character at the beginning in proper way + * @param value Regexp pattern + * @return Proper regular expression's pattern. + */ +std::string addStartPositionMark(const std::string &value); + +/** + * Adds $ character at the end in proper way + * @param value Regexp pattern + * @return Proper regular expression's pattern. + */ +std::string addEndPositionMark(const std::string &value); + +/** + * Adds ^ character at the beginning and $ the end in proper way + * @param value Regexp pattern + * @return Proper regular expression's pattern. + */ +std::string addStartAndEndPositionMark(const std::string &value); + +/** + * Converts typical string with wildcard '%' to proper perl-like regular + * expression's pattern. + * @param str String that came from JS. + * @return Proper regular expression's pattern. + * @remarks Calling it twice will (probably?) cause double escaping. + */ +std::string preparePercent(const std::string& str); + +/** + * Converts typical string with wildcard '*' to proper perl-like regular + * expression's pattern. + * @param str String that came from JS. + * @return Proper regular expression's pattern. + * @remarks Calling it twice will (probably?) cause double escaping. + */ +std::string prepareAsterisk(const std::string& str); + +/** + * Escapes regex special characters. + * @param str String to escape. + * @return String with regex special characters escaped. + */ +std::string escape(const std::string& str); +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_REGEX_UTILS_H_ diff --git a/src/Commons/StaticAssert.h b/src/Commons/StaticAssert.h new file mode 100644 index 0000000..bbd19f2 --- /dev/null +++ b/src/Commons/StaticAssert.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2011 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. + */ +/** + * @file StaticAssert.h + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + */ + +#ifndef WRTDEVICEAPIS_COMMONS_STATIC_ASSERT_H +#define WRTDEVICEAPIS_COMMONS_STATIC_ASSERT_H + +namespace WrtDeviceApis { +namespace Commons { +template<bool> +struct CompileTimeChecker +{ + CompileTimeChecker(...); +}; + +template<> +struct CompileTimeChecker<false> {}; + +#define STATIC_CHECK(expr, msg) \ + { \ + class ERROR_##msg {}; \ + CompileTimeChecker<(expr) != 0>((ERROR_##msg())); \ + } + +/** + * Define used to inform about errors in compilation time + * useful in templates + * @param msg - message to be displayed, + * msg have to be a valid C++ identifier, + * other way reported errors will be meaningless + * @param C - instance of object which caused problem + * error generated by compiler display type of C + * */ +#define STATIC_ERROR(msg, C) \ + { \ + C->_##msg(); \ + } +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_STATIC_ASSERT_H diff --git a/src/Commons/StringBuilder.cpp b/src/Commons/StringBuilder.cpp new file mode 100644 index 0000000..7fb1cb9 --- /dev/null +++ b/src/Commons/StringBuilder.cpp @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2011 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. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ +#include <sstream> +#include "Exception.h" +#include "StringBuilder.h" + +namespace WrtDeviceApis { +namespace Commons { +class StringBuilderImpl +{ + public: + StringBuilderImpl() : m_counter(1) + {} + + void append(const std::string& str) + { + if (!(m_ss << str)) { + m_ss.clear(); + ThrowMsg(PlatformException, "Couldn't append string."); + } + } + + void append(const StringBuilderImpl* impl) + { + if (!(m_ss << impl->m_ss)) { + m_ss.clear(); + ThrowMsg(PlatformException, + "Couldn't append string builder."); + } + } + + void addRef() + { + ++m_counter; + } + + void deref() + { + if (0 == --m_counter) { + delete this; + } + } + + StringBuilderImpl* clone() + { + if (1 == m_counter) { + return this; + } + + --m_counter; + + StringBuilderImpl* result = new StringBuilderImpl(); + result->m_ss << m_ss; + return result; + } + + std::string toString() const + { + return m_ss.str(); + } + + private: + std::stringstream m_ss; + unsigned int m_counter; +}; + +StringBuilder::StringBuilder() : m_impl(new StringBuilderImpl()) +{} + +StringBuilder::~StringBuilder() +{ + m_impl->deref(); +} + +StringBuilder::StringBuilder(const StringBuilder& other) +{ + other.m_impl->addRef(); + m_impl = other.m_impl; +} + +StringBuilder & StringBuilder::operator=(const StringBuilder& other) +{ + if (this == &other) { + return *this; + } + + other.m_impl->addRef(); + + m_impl->deref(); + m_impl = other.m_impl; + + return *this; +} + +StringBuilder& StringBuilder::append(const std::string& str) +{ + m_impl = m_impl->clone(); + m_impl->append(str); + return *this; +} + +StringBuilder& StringBuilder::append(const StringBuilder& builder) +{ + m_impl = m_impl->clone(); + m_impl->append(builder.m_impl); + return *this; +} + +std::string StringBuilder::toString() const +{ + return m_impl->toString(); +} +} +} // WrtDeviceApisCommon diff --git a/src/Commons/StringBuilder.h b/src/Commons/StringBuilder.h new file mode 100644 index 0000000..fa12c37 --- /dev/null +++ b/src/Commons/StringBuilder.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2011 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. + */ +/** + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_COMMONS_STRINGBUILDER_H_ +#define WRTDEVICEAPIS_COMMONS_STRINGBUILDER_H_ + +#include <string> + +namespace WrtDeviceApis { +namespace Commons { +class StringBuilderImpl; + +class StringBuilder +{ + public: + StringBuilder(); + StringBuilder(const StringBuilder& other); + ~StringBuilder(); + + StringBuilder& operator=(const StringBuilder& other); + + StringBuilder& append(const std::string& str); + StringBuilder& append(const StringBuilder& builder); + std::string toString() const; + + private: + StringBuilderImpl* m_impl; +}; +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_STRINGBUILDER_H_ diff --git a/src/Commons/StringUtils.cpp b/src/Commons/StringUtils.cpp new file mode 100644 index 0000000..0b432b6 --- /dev/null +++ b/src/Commons/StringUtils.cpp @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2011 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 <cstring> +#include <algorithm> +#include <iterator> +#include <new> +#include "StringUtils.h" + +namespace WrtDeviceApis { +namespace Commons { +namespace String { +std::string lTrim(const std::string& str) +{ + std::string result = str; + result.erase(result.begin(), + std::find_if(result.begin(), result.end(), + std::not1(std::ptr_fun<int, int>(std::isspace)))); + return result; +} + +std::string rTrim(const std::string& str) +{ + std::string result = str; + result.erase(std::find_if(result.rbegin(), result.rend(), + std::not1(std::ptr_fun<int, int>( + std::isspace))).base(), result.end()); + return result; +} + +std::string trim(const std::string& str) +{ + return lTrim(rTrim(str)); +} + +bool startsWith(const std::string& str, + const std::string& startStr) +{ + return str.find(startStr) == 0; +} + +bool endsWith(const std::string& str, + const std::string& endStr) +{ + std::size_t pos = str.rfind(endStr); + if (pos == std::string::npos) { + return false; + } + return pos == str.length() - endStr.length(); +} + +std::string unique(const std::string& str, + const char needle) +{ + std::string result = str; + + std::string::size_type pos = 0; + while ((pos = result.find_first_of(needle, pos)) < std::string::npos) { + std::string::size_type last = result.find_first_not_of(needle, pos); + if (last == std::string::npos) { + last = result.size(); + } + if (last - pos > 1) { + result.erase(pos + 1, last - pos - 1); + } + pos = last; + } + + return result; +} + +bool inCStringArray(const std::string& needle, + const char* stack[]) +{ + while (*stack) { + if (needle == *stack) { + return true; + } + ++stack; + } + return false; +} + +char* strdup(const char* str) +{ + char* result = ::strdup(str); + if (NULL == result) { + throw std::bad_alloc(); + } + return result; +} + +std::string merge(const std::vector<std::string>& strs, + std::string::value_type delim) +{ + typedef std::vector<std::string> Strings; + + std::ostringstream ss; + if (!strs.empty()) { + for (Strings::size_type i = 0; i < strs.size() - 1; ++i) { + ss << strs[i] << delim; + } + ss << strs.at(strs.size() - 1); + } + return ss.str(); +} + +std::vector<std::string> split(const std::string& str, + std::string::value_type delim) +{ + std::vector<std::string> result; + std::string::size_type begin = 0, end = 0; + while ((end = str.find_first_of(delim, begin))) { + std::string part = (std::string::npos == end ? + str.substr(begin) : + str.substr(begin, end - begin)); + if (!part.empty()) { + result.push_back(part); + } + if (std::string::npos == end) { + break; + } + begin = end + 1; + } + return result; +} + +int toInt(const std::string& str) +{ + return convertTo<int>(str); +} +} +} +} diff --git a/src/Commons/StringUtils.h b/src/Commons/StringUtils.h new file mode 100644 index 0000000..2427048 --- /dev/null +++ b/src/Commons/StringUtils.h @@ -0,0 +1,166 @@ +/* + * Copyright (c) 2011 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. + */ +/** + * @file StringUtils.h + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef WRTDEVICEAPIS_COMMONS_STRINGUTILS_H_ +#define WRTDEVICEAPIS_COMMONS_STRINGUTILS_H_ + +#include <string> +#include <vector> +#include <sstream> +#include <utility> +#include <Commons/Exception.h> +#include <dpl/availability.h> + +namespace WrtDeviceApis { +namespace Commons { +namespace String { +/** + * Removes spaces from begining of the string. + * @param str String to remove spaces from. + * @return String with spaces removed. + */ +std::string lTrim(const std::string& str); + +/** + * Removes spaces from end of the string. + * @param str String to remove spaces from. + * @return String with spaces removed. + */ +std::string rTrim(const std::string& str); + +/** + * Removes spaces from begining and end of the string. + * @param str String to remove spaces from. + * @return String with spaces removed. + */ +std::string trim(const std::string& str); + +/** + * Checks if str starts with startStr + * @param str String to be searched. + * @param startStr String to be found at the beginning of str. + * @return true when str starts with startStr, false otherwise. + */ +bool startsWith(const std::string& str, const std::string& startStr); + +/** + * Checks if str ends with startStr + * @param str String to be searched. + * @param endStr String to be found at the end of str. + * @return true when str starts with startStr, false otherwise. + */ +bool endsWith(const std::string& str, const std::string& endStr); + +/** + * Merges consecutive groups of duplicate characters into one. + * @param str String to remove characters from. + * @param needle Character for which groups of duplicates to merge. + * @return String with group of duplicate characters merged. + * @code + * ... + * std::string str = "Aala maa kota"; + * std::string uniq = unique(str, 'a'); + * uniq == "Ala ma kota"; + * ... + * @endcode + */ +std::string unique(const std::string& str, const char needle); + +/** + * Checks if supplied string exists in specified array of c-strings. + * @param needle String to verify. + * @param stack Array of c-strings which last element should be NULL. + * @return True if string exists in array, false otherwise. + * @remarks Last element of array should be NULL, otherwise there is no + * way to calculate its number of elements. + */ +bool inCStringArray(const std::string& needle, const char* stack[]); + +/** + * Duplicates a string. + * @param str String to duplicate. + * @return String copy. + * @throw std::bad_alloc If allocation fails. + * @remarks Ownership passed to the caller. String has to be deallocated using + * free() function. + */ +char* strdup(const char* str); +inline char* strdup(const std::string& str) +{ + return strdup(str.c_str()); +} + +std::string merge(const std::vector<std::string>& strs, + std::string::value_type delim); + +std::vector<std::string> split(const std::string& str, + std::string::value_type delim); + +/** + * @deprecated Use convertTo<int>(). + */ +int toInt(const std::string& str) DPL_DEPRECATED; + +/** + * Converts string to specified type. + * + * @tparam T Type to convert to. + * @param str String to convert. + * @return Converted value. + * @throw ConversionException If conversion fails. + * + * @remarks T must implement default constructor and an implementation + * of input string operator for T must exist. + */ +template<typename T> +T convertTo(const std::string& str) +{ + T result; + std::istringstream iss(str); + if (!(iss >> result)) { + Throw(ConversionException); + } + return std::move(result); +} + +/** + * Converts a given value to string. + * + * @tparam T Type of the value to convert. It is deduced by the compiler. + * @param data Value to convert. + * @return Value converted to string. + * @throw ConversionException If operation fails. + * + * @remarks Output stream operator for type T must exist. + */ +template<typename T> +std::string parse(const T& data) +{ + std::ostringstream oss; + if (!(oss << data)) { + Throw(ConversionException); + } + return oss.str(); +} +} +} +} + +#endif diff --git a/src/Commons/ThreadPool.cpp b/src/Commons/ThreadPool.cpp new file mode 100644 index 0000000..1b94e5d --- /dev/null +++ b/src/Commons/ThreadPool.cpp @@ -0,0 +1,212 @@ +/* + * Copyright (c) 2011 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. + */ +/* + * ControllersFactory.cpp + * + * Created on: 2010-06-28 + * Author: kmajewski + */ + +#include <assert.h> + +#include <dpl/log/wrt_log.h> +#include <dpl/thread.h> + +#include "ThreadPool.h" +#include "Exception.h" + +namespace WrtDeviceApis { +namespace Commons { +ThreadPool &ThreadPool::getInstance() +{ + static ThreadPool theInstance; + return theInstance; +} + +DPL::Event::AbstractEventDispatcher *ThreadPool::getDispatcher( + DPL::Event::ThreadEventDispatcher &callingThreadDispatcher) +{ + DPL::Thread *currentThread = DPL::Thread::GetCurrentThread(); + //if we are in main thread + if (NULL == currentThread) { + return &DPL::Event::GetMainEventDispatcherInstance(); + } + callingThreadDispatcher.SetThread(currentThread); + return &callingThreadDispatcher; +} + +ThreadPool::ThreadPool() +{} + +ThreadPool::~ThreadPool() +{ + for (ThreadHandleMap::const_iterator it = m_threadHandlers.begin(); it + != m_threadHandlers.end(); ++it) + { + delete (*it).second; + } +} + +DPL::Thread* ThreadPool::getThreadHandleCreateIfNotExists( + ThreadEnum::Enumeration type) +{ + DPL::Mutex::ScopedLock lock(&m_threadHandlersMutex); + ThreadHandleMap::iterator element = m_threadHandlers.find(type); + + //if element does not exists in the map + if (m_threadHandlers.end() == element) { + DPL::Thread* newThread = new DPL::Thread(); + m_threadHandlers.insert( + m_threadHandlers.begin(), + std::pair<ThreadEnum::Enumeration, DPL::Thread*>(type, newThread)); + newThread->Run(); + return newThread; + } + return (*element).second; +} + +DPL::Thread *ThreadPool::getThreadRef(ThreadEnum::Enumeration type) +{ + DPL::Thread *thandle = NULL; + if (type < 0 || type >= ThreadEnum::size) { + Throw(InvalidArgumentException); + } + /* we could stay with + * getThreadHandleCreateIfNotExists(type); + * but by switch we can attach actually one thread to more than one + * ThreadEnums + */ + switch (type) { + case ThreadEnum::NULL_THREAD: + thandle = NULL; + break; + case ThreadEnum::CAMERA_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::CAMERA_THREAD); + break; + case ThreadEnum::CALENDAR_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::CALENDAR_THREAD); + break; + case ThreadEnum::TELEPHONY_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::TELEPHONY_THREAD); + break; + case ThreadEnum::APPLAUNCHER_THREAD: + thandle = getThreadHandleCreateIfNotExists( + ThreadEnum::APPLAUNCHER_THREAD); + break; + case ThreadEnum::APPCONFIG_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::APPCONFIG_THREAD); + break; + case ThreadEnum::MESSAGING_THREAD: + thandle = getThreadHandleCreateIfNotExists(type); + break; + case ThreadEnum::FILESYSTEM_THREAD: + thandle = getThreadHandleCreateIfNotExists( + ThreadEnum::FILESYSTEM_THREAD); + break; + case ThreadEnum::GALLERY_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::GALLERY_THREAD); + break; + case ThreadEnum::CONTACT_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::CONTACT_THREAD); + break; + case ThreadEnum::BONDI_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::BONDI_THREAD); + break; + case ThreadEnum::GEOLOCATION_THREAD: + thandle = getThreadHandleCreateIfNotExists( + ThreadEnum::GEOLOCATION_THREAD); + break; + case ThreadEnum::DEVICESTATUS_THREAD: + thandle = getThreadHandleCreateIfNotExists( + ThreadEnum::DEVICESTATUS_THREAD); + break; + case ThreadEnum::PROFILE_THREAD: + thandle = getThreadHandleCreateIfNotExists(type); + break; + case ThreadEnum::HAPTICS_THREAD: + thandle = getThreadHandleCreateIfNotExists(type); + break; + case ThreadEnum::ACCELEROMETER_THREAD: + thandle = getThreadHandleCreateIfNotExists( + ThreadEnum::ACCELEROMETER_THREAD); + break; + case ThreadEnum::ORIENTATION_THREAD: + thandle = getThreadHandleCreateIfNotExists( + ThreadEnum::ORIENTATION_THREAD); + break; + case ThreadEnum::TASK_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::TASK_THREAD); + break; + case ThreadEnum::POWER_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::POWER_THREAD); + break; + case ThreadEnum::PLUGIN_TEMPLETE_THREAD: + thandle = getThreadHandleCreateIfNotExists( + ThreadEnum::PLUGIN_TEMPLETE_THREAD); + break; + case ThreadEnum::BLUETOOTH_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::BLUETOOTH_THREAD); + break; + case ThreadEnum::APPLICATION_THREAD: + thandle = getThreadHandleCreateIfNotExists( + ThreadEnum::APPLICATION_THREAD); + break; + case ThreadEnum::GYROSCOPE_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::GYROSCOPE_THREAD); + break; + case ThreadEnum::CLOCK_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::CLOCK_THREAD); + break; + case ThreadEnum::SYSTEMINFO_THREAD: + thandle = getThreadHandleCreateIfNotExists( + ThreadEnum::SYSTEMINFO_THREAD); + break; + case ThreadEnum::CALLHISTORY_THREAD: + thandle = getThreadHandleCreateIfNotExists( + ThreadEnum::CALLHISTORY_THREAD); + break; + case ThreadEnum::ACCOUNT_THREAD: + thandle = getThreadHandleCreateIfNotExists( + ThreadEnum::CALLHISTORY_THREAD); + break; + case ThreadEnum::NFC_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::NFC_THREAD); + break; + case ThreadEnum::MEDIACONTENT_THREAD: + thandle = getThreadHandleCreateIfNotExists( + ThreadEnum::MEDIACONTENT_THREAD); + break; + case ThreadEnum::SE_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::SE_THREAD); + break; + case ThreadEnum::DOWNLOAD_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::DOWNLOAD_THREAD); + break; + case ThreadEnum::PUSH_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::PUSH_THREAD); + break; + case ThreadEnum::SYNC_THREAD: + thandle = getThreadHandleCreateIfNotExists(ThreadEnum::SYNC_THREAD); + break; + // ..... + default: + WrtLogE("no case statement for ThreadEnum"); + Throw(InvalidArgumentException); + } + return thandle; +} +} +} // WrtDeviceApisCommon diff --git a/src/Commons/ThreadPool.h b/src/Commons/ThreadPool.h new file mode 100644 index 0000000..9d0bb57 --- /dev/null +++ b/src/Commons/ThreadPool.h @@ -0,0 +1,115 @@ +/* + * Copyright (c) 2011 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. + */ +/* + * ControllersFactory.h + * + * Created on: 2010-06-28 + * Author: kmajewski + */ + +#ifndef WRTDEVICEAPIS_COMMONS_THREADPOOL_H_ +#define WRTDEVICEAPIS_COMMONS_THREADPOOL_H_ + +#include <map> +#include <dpl/thread.h> +#include <dpl/event/main_event_dispatcher.h> +#include <dpl/event/thread_event_dispatcher.h> +#include <dpl/event/event_support.h> +#include <dpl/mutex.h> + +namespace WrtDeviceApis { +namespace Commons { +class ThreadEnum +{ + private: + ThreadEnum() + {} + + public: + enum Enumeration + { + NULL_THREAD = 0, + CAMERA_THREAD, + CALENDAR_THREAD, + TELEPHONY_THREAD, + APPLAUNCHER_THREAD, + MESSAGING_THREAD, + FILESYSTEM_THREAD, + UI_THREAD, + APPCONFIG_THREAD, + GALLERY_THREAD, + CONTACT_THREAD, + BONDI_THREAD, + GEOLOCATION_THREAD, + DEVICESTATUS_THREAD, + PROFILE_THREAD, + HAPTICS_THREAD, + ACCELEROMETER_THREAD, + ORIENTATION_THREAD, + TASK_THREAD, + POWER_THREAD, + PLUGIN_TEMPLETE_THREAD, + BLUETOOTH_THREAD, + APPLICATION_THREAD, + GYROSCOPE_THREAD, + CLOCK_THREAD, + SYSTEMINFO_THREAD, + CALLHISTORY_THREAD, + ACCOUNT_THREAD, + NFC_THREAD, + MEDIACONTENT_THREAD, + SE_THREAD, + DOWNLOAD_THREAD, + PUSH_THREAD, + SYNC_THREAD, + //.... + size + }; +}; + +class ThreadPool : private DPL::Noncopyable +{ + private: + typedef std::map<ThreadEnum::Enumeration, DPL::Thread*> ThreadHandleMap; + ThreadHandleMap m_threadHandlers; + DPL::Mutex m_threadHandlersMutex; + + DPL::Thread *getThreadHandleCreateIfNotExists(ThreadEnum::Enumeration type); + + //DPL::MainEventDispatcher m_mainEventDispatcher; + + ThreadPool(); + + public: + ~ThreadPool(); + + /* + * @throws: WrtDeviceApis::Commons::InvalidArgumentException + */ + DPL::Thread * getThreadRef(ThreadEnum::Enumeration type); + + /* + * Get proper dispatcher for current calling thread + */ + DPL::Event::AbstractEventDispatcher *getDispatcher( + DPL::Event::ThreadEventDispatcher &callingThreadDispatcher); + + static ThreadPool& getInstance(); +}; +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_THREADPOOL_H_ diff --git a/src/Commons/TypeTraits.h b/src/Commons/TypeTraits.h new file mode 100644 index 0000000..a921fb2 --- /dev/null +++ b/src/Commons/TypeTraits.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2011 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 WRTDEVICEAPIS_COMMONS_TYPE_TRAITS_H_ +#define WRTDEVICEAPIS_COMMONS_TYPE_TRAITS_H_ + +#include <memory> + +namespace WrtDeviceApis { +namespace Commons { +template<typename T> +struct IsNull +{ + static bool value(const T&) + { + return false; + } +}; + +template<typename T> +struct IsNull<T*> +{ + static bool value(T* ptr) + { + return ptr == NULL; + } +}; + +template<typename Class> +struct IsNull<std::shared_ptr<Class> > +{ + static bool value(const std::shared_ptr<Class>& ptr) + { + return ptr.get() == NULL; + } +}; + +template<typename ... T> +struct AlwaysFalse +{ + static const bool value = false; +}; +} +} // WrtDeviceApisCommon + +#endif // WRTDEVICEAPIS_COMMONS_TYPE_TRAITS_H_ diff --git a/src/Commons/TypesDeclaration.h b/src/Commons/TypesDeclaration.h new file mode 100644 index 0000000..0f2dca2 --- /dev/null +++ b/src/Commons/TypesDeclaration.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2011 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 WRTDEVICEAPIS_COMMONS_TYPES_DECLARATION_ +#define WRTDEVICEAPIS_COMMONS_TYPES_DECLARATION_ + +#include <string> +#include <vector> + +namespace WrtDeviceApis { +namespace Commons { +struct AceFeature +{ + AceFeature(const std::string& featName) : name(featName) {} + std::string name; +}; + +typedef std::vector <AceFeature> AceFeatures; + +struct AceDeviceCapParam +{ + AceDeviceCapParam(const std::string& parName, + const std::string& parVal) : name(parName), + value(parVal) + {} + + std::string name; + std::string value; +}; + +typedef std::vector <AceDeviceCapParam> AceDeviceCapParams; + +struct AceDeviceCapability +{ + AceDeviceCapability() {} + AceDeviceCapability(const std::string& name, + const AceDeviceCapParams& params) : + devCapName(name), + devCapParams(params) + {} + + std::string devCapName; + AceDeviceCapParams devCapParams; +}; + +typedef std::vector <AceDeviceCapability> AceDeviceCaps; + +struct AceFunction +{ + std::string name; + AceFeatures features; + AceDeviceCaps deviceCapabilities; +}; +} // namespace Commons +} // namespace WrtDeviceApis + +#endif diff --git a/src/Commons/WrtAccess/WrtAccess.cpp b/src/Commons/WrtAccess/WrtAccess.cpp new file mode 100644 index 0000000..c675a9a --- /dev/null +++ b/src/Commons/WrtAccess/WrtAccess.cpp @@ -0,0 +1,272 @@ +/* + * Copyright (c) 2011 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. + */ +/* + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#include <memory> +#include <sstream> +#include <stdlib.h> +#include <unistd.h> +#include <sys/types.h> + +#include <dpl/log/wrt_log.h> +#include <dpl/scoped_resource.h> +#include <dpl/assert.h> +#include <Commons/Exception.h> +#include "WrtAccess.h" +#include <ace_api_client.h> +#include <dpl/singleton_safe_impl.h> + +#include "popup-runner.h" +IMPLEMENT_SAFE_SINGLETON(WrtDeviceApis::Commons::WrtAccess) + +namespace { +/** + * Helper class - single parameter and its value + */ +struct AceParam +{ + const char *name; + const char *value; + + AceParam() : + name(NULL), value(NULL) + {} + + AceParam(const char *name, const char *value) : + name(name), value(value) + {} +}; + +/** + * Helper class - list of params for single dev cap + */ +struct AceParamList +{ + size_t count; + AceParam* param; + AceParamList() : + count(0), + param(NULL) + {} +}; + +struct DeviceCapParamPolicy +{ + typedef AceParamList* Type; + static Type NullValue() + { + return NULL; + } + static void Destroy(Type ptr) + { + if (ptr) { + delete[] ptr->param; + } + delete[] ptr; + } +}; + +/** + * Helper class - modified ScopedArray for ace_param_list_t + */ +class ScopedDeviceCapArray : public DPL::ScopedResource<DeviceCapParamPolicy> +{ + public: + explicit ScopedDeviceCapArray(AceParamList *ptr = + DeviceCapParamPolicy::NullValue()) : + DPL::ScopedResource<DeviceCapParamPolicy>(ptr) + {} + + AceParamList & operator [](std::ptrdiff_t k) const + { + AssertMsg(this->m_value != DeviceCapParamPolicy::NullValue(), + "Dereference of scoped NULL array!"); + AssertMsg(k >= 0, "Negative array index"); + + return this->m_value[k]; + } +}; +} // namespace + +namespace WrtDeviceApis { +namespace Commons { +WrtAccess::WrtAccess() : + m_sessionId(GenerateSessionId()), + m_pluginOwners(0) +{} + +WrtAccess::~WrtAccess() +{} + +WrtAccess::SessionId WrtAccess::GenerateSessionId() +{ + const size_t SESSION_ID_LENGTH = 32; + + std::ostringstream pid; + pid << static_cast<int>(getpid()); + + std::string session_id = pid.str(); + + session_id.reserve(session_id.length() + SESSION_ID_LENGTH); + + for (size_t i = 0; i < SESSION_ID_LENGTH; ++i) { + int c = random() % 16; + + session_id += (c < 10 ? + static_cast<char>('0' + c) : + static_cast<char>('A' + c - 10)); + } + return session_id; +} + +void WrtAccess::initialize(WidgetHandle widgetId) +{ + WrtLogD("initialize"); + if (widgetId < 0) { + WrtLogE("Invalid widget id"); + Throw(Exception); + } + + m_widgetId = widgetId; + + if (!m_pluginOwners++) { + ace_return_t ret = ace_client_initialize(Wrt::Popup::run_popup); + Assert(ACE_OK == ret); + } +} + +void WrtAccess::deinitialize(WidgetHandle /*widgetId*/) +{ + WrtLogD("deinitialize"); + + if (!--m_pluginOwners) { + ace_return_t ret = ace_client_shutdown(); + Assert(ACE_OK == ret); + } +} + +WidgetHandle WrtAccess::getWidgetId() const +{ + return m_widgetId; +} + +WrtAccess::CheckAccessReturnType WrtAccess::checkAccessControl(const AceFunction& aceFunction) const +{ + AssertMsg( + m_pluginOwners, "WrtAccessSingleton needs to be initialized with" + "WidgetId during on_widget_start_callback in each plugin"); + size_t deviceCount = aceFunction.deviceCapabilities.size(); + + std::unique_ptr<const char*[]> deviceScopedArray; + ScopedDeviceCapArray paramsScopedArray; + + if (deviceCount) { + deviceScopedArray.reset(new const char*[deviceCount]); + paramsScopedArray.Reset(new AceParamList[deviceCount]); + + for (size_t i = 0; i < deviceCount; ++i) { + deviceScopedArray[i] = + aceFunction.deviceCapabilities.at(i).devCapName.c_str(); + paramsScopedArray[i].count = + aceFunction.deviceCapabilities.at(i).devCapParams.size(); + + paramsScopedArray[i].param = + new AceParam[paramsScopedArray[i].count]; + + for (size_t j = 0; j < paramsScopedArray[i].count; ++j) { + paramsScopedArray[i].param[j].name = + aceFunction.deviceCapabilities.at(i). + devCapParams[j].name.c_str(); + paramsScopedArray[i].param[j].value = + aceFunction.deviceCapabilities.at(i). + devCapParams[j].value.c_str(); + } + } + } + + size_t featuresCount = aceFunction.features.size(); + + std::unique_ptr<const char*[]> featureScopedArray; + if (featuresCount) { + featureScopedArray.reset(new const char*[featuresCount]); + + for (size_t i = 0; i < featuresCount; ++i) { + featureScopedArray[i] = + aceFunction.features.at(i).name.c_str(); + } + } + + WrtLogD("constructing ACE request"); + + ace_request_t aceRequest; + aceRequest.session_id = + const_cast<const ace_session_id_t>(m_sessionId.c_str()); + aceRequest.widget_handle = static_cast<ace_widget_handle_t>(getWidgetId()); + aceRequest.feature_list.count = featuresCount; + aceRequest.feature_list.items = + const_cast<ace_string_t*>(featureScopedArray.get()); + aceRequest.dev_cap_list.count = deviceCount; + aceRequest.dev_cap_list.items = new ace_dev_cap_t[deviceCount]; + + const char** devCapNames = deviceScopedArray.get(); + AceParamList* paramList = paramsScopedArray.Get(); + + unsigned int i; + for (i = 0; i < deviceCount; ++i) { + aceRequest.dev_cap_list.items[i].name = + const_cast<const ace_string_t>(devCapNames[i]); + aceRequest.dev_cap_list.items[i].param_list.count = paramList[i].count; + aceRequest.dev_cap_list.items[i].param_list.items = + new ace_param_t[paramList[i].count]; + unsigned int j; + for (j = 0; j < paramList[i].count; ++j) { + aceRequest.dev_cap_list.items[i].param_list.items[j].name = + const_cast<ace_string_t>(paramList[i].param[j].name); + aceRequest.dev_cap_list.items[i].param_list.items[j].value = + const_cast<ace_string_t>(paramList[i].param[j].value); + } + } + + ace_check_result_t aceCheckResult = ACE_PRIVILEGE_DENIED; + ace_return_t ret = ace_check_access_ex(&aceRequest, &aceCheckResult); + for (i = 0; i < deviceCount; ++i) { + delete[] aceRequest.dev_cap_list.items[i].param_list.items; + } + delete[] aceRequest.dev_cap_list.items; + + if (ACE_OK != ret) { + WrtLogE("Error in ace check: %d", static_cast<int>(ret)); + return CHECK_ACCESS_INTERNAL_ERROR; + } + + if (aceCheckResult == ACE_ACCESS_GRANTED) { + return CHECK_ACCESS_GRANTED; + } + else if (aceCheckResult == ACE_PRIVILEGE_DENIED) { + return CHECK_ACCESS_PRIVILEGE_DENIED; + } + else if (aceCheckResult == ACE_PRIVACY_DENIED) { + return CHECK_ACCESS_PRIVACY_DENIED; + } + + return CHECK_ACCESS_INTERNAL_ERROR; +} +} +} // WrtDeviceApisCommon diff --git a/src/Commons/WrtAccess/WrtAccess.h b/src/Commons/WrtAccess/WrtAccess.h new file mode 100644 index 0000000..533d008 --- /dev/null +++ b/src/Commons/WrtAccess/WrtAccess.h @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2011 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. + */ +/* + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRT_PLUGINS_WRT_ACCESS_H_ +#define WRT_PLUGINS_WRT_ACCESS_H_ + +#include <string> + +#include <dpl/singleton.h> +#include <Commons/TypesDeclaration.h> +#include <dpl/wrt-dao-ro/wrt_db_types.h> + +namespace WrtDeviceApis { +namespace Commons { +class WrtAccess +{ + public: + enum CheckAccessReturnType + { + CHECK_ACCESS_GRANTED, + CHECK_ACCESS_PRIVILEGE_DENIED, + CHECK_ACCESS_PRIVACY_DENIED, + CHECK_ACCESS_INTERNAL_ERROR + }; + + void initialize(WidgetHandle widgetId); + void deinitialize(WidgetHandle widgetId); + WidgetHandle getWidgetId() const; + CheckAccessReturnType checkAccessControl(const AceFunction &aceFunction) const; + + private: + + typedef std::string SessionId; + SessionId GenerateSessionId(); + + WrtAccess(); + virtual ~WrtAccess(); + + WidgetHandle m_widgetId; + SessionId m_sessionId; + size_t m_pluginOwners; + + + friend class DPL::Singleton<WrtAccess>; +}; + +typedef DPL::Singleton<WrtAccess> WrtAccessSingleton; +} +} // WrtDeviceApisCommon + +#endif //WRT_PLUGINS_WRT_ACCESS_H_ diff --git a/src/Commons/WrtAccess/config.cmake b/src/Commons/WrtAccess/config.cmake new file mode 100644 index 0000000..a31ce63 --- /dev/null +++ b/src/Commons/WrtAccess/config.cmake @@ -0,0 +1,5 @@ +get_current_path() + +set(SRCS_WRT_ACCESS + ${CURRENT_PATH}/WrtAccess.cpp +) diff --git a/src/Commons/plugin_initializer_def.h b/src/Commons/plugin_initializer_def.h new file mode 100644 index 0000000..cd7e549 --- /dev/null +++ b/src/Commons/plugin_initializer_def.h @@ -0,0 +1,181 @@ +/* + * Copyright (c) 2011 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. + */ +/* + * @author Karol Majewski (k.majewski@samsung.com) + * @version 0.1 + * @brief This is a file that you provides interface for wrt-engine while + * loading and using plugin + * If you are a plugin developer you need to plugin_initializer.cpp + * in your module and provide implementation for macros below + */ + +#ifndef WRTDEVICEAPIS_COMMONS_PLUGIN_INITIALIZER_DEF_H_ +#define WRTDEVICEAPIS_COMMONS_PLUGIN_INITIALIZER_DEF_H_ + +#include <wrt_plugin_export.h> + +typedef java_script_context_t JavaScriptContext; + +#define EXPORT_SYMBOL __attribute__((__visibility__("default"))) + +//DEFINES FOR GLOBAL OBJECTS AVAILABLE IN JAVASCRIPT +/** + * each object which declare this object as parent + * will ba available as global object in javascript + */ +#define WRT_JS_EXTENSION_OBJECT_GLOBAL "window" + +/** + * global object bondi + * */ +#define WRT_JS_EXTENSION_OBJECT_BONDI "bondi" + +/** + * global object Widget + * */ +#define WRT_JS_EXTENSION_OBJECT_WIDGET "Widget" + +/** + * global object deviceapis + * */ +#define WRT_JS_EXTENSION_OBJECT_DEVICEAPIS "deviceapis" + +/** + * global object tizen + * */ +#define WRT_JS_EXTENSION_OBJECT_TIZEN "tizen" + +//HAVE TO BE IMPLEMENTED IN EVERY PLUGIN +/* + * You have to(!) call this macro in your plugin_initializer.cpp(!) file + * providing callback that will be called while loading each widget (for every + * loaded widget this function will be called) + * Example: + * plugin_initializer.cpp + * void on_widget_start_callback(WidgetHandle widgetId, JSContextRef context, + * const engine_interface_t *interface) + * { + * //... + * } + * PLUGIN_ON_WIDGET_START(on_widget_start_callback) + */ +#define PLUGIN_ON_WIDGET_START(CALLBACK_NAME) extern "C" const \ + on_widget_start_proc PLUGIN_WIDGET_START_PROC EXPORT_SYMBOL = CALLBACK_NAME; + +/* + * You have to(!) call this macro in your plugin_initializer.cpp(!) file + * providing callback that will be called while loading each widget + * (for every loaded widget this function will be called) + * Example: + * plugin_initializer.cpp + * void on_widget_init_callback(feature_mapping_interface_t *mapping) + * { + * //... + * } + * PLUGIN_ON_WIDGET_INIT(on_widget_init_callback) + */ +#define PLUGIN_ON_WIDGET_INIT(CALLBACK_NAME) extern "C" \ + const on_widget_init_proc PLUGIN_WIDGET_INIT_PROC EXPORT_SYMBOL = \ + CALLBACK_NAME; + +/* + * You have to(!) call this macro in your plugin_initializer.cpp(!) file + * providing callback that will be called while unloading each widget (for + * every unloaded widget this function will be called) + * Example: + * void on_widget_stop_callback(WidgetHandle widgetId) + * { + * //... + * } + * PLUGIN_ON_WIDGET_STOP(on_widget_stop_callback) + */ +#define PLUGIN_ON_WIDGET_STOP(CALLBACK_NAME) extern "C" const \ + on_widget_stop_proc PLUGIN_WIDGET_STOP_PROC EXPORT_SYMBOL = CALLBACK_NAME; + +/* + * You have to(!) call this macro in your plugin_initializer.cpp(!) file + * providing callback that will be called while unloading each page (for every + * loaded page, including nested page, this function will be called) + * Example: + * void on_frame_load_callback(java_script_context_t context) + * { + * //... + * } + * PLUGIN_ON_FRAME_LOAD(on_frame_load_callback) + */ +#define PLUGIN_ON_FRAME_LOAD(CALLBACK_NAME) extern "C" const on_frame_load_proc \ + PLUGIN_FRAME_LOAD_PROC EXPORT_SYMBOL = CALLBACK_NAME; + +/* + * You have to(!) call this macro in your plugin_initializer.cpp(!) file + * providing callback that will be called while ununloading each page (for + * every unloaded page, including nested page, this function will be called) + * Example: + * void on_frame_unload_callback(java_script_context_t context) + * { + * //... + * } + * PLUGIN_ON_FRAME_UNLOAD(on_frame_unload_callback) + */ +#define PLUGIN_ON_FRAME_UNLOAD(CALLBACK_NAME) extern "C" const \ + on_frame_unload_proc PLUGIN_FRAME_UNLOAD_PROC EXPORT_SYMBOL = CALLBACK_NAME; + +/* + * You have to(!) define an array of structures in your + * plugin_initializer.cpp(!) file describing a JS class (class_definition) and + * it's parent class name (parent_name). + * JS class will be bind to a parent class name (parent_name.jsclass_name). + * Example: + * plugin_initializer.cpp + * PLUGIN_CLASS_MAP_BEGIN + * PLUGIN_CLASS_MAP_ADD_CLASS( + * "bondi", + * WrtPluginBondi::JSICameraManager::getClassInfo()) + * PLUGIN_CLASS_MAP_ADD_CLASS( + * "bondi", + * WrtPluginBondi::JSICameraAnotherClass::getClassInfo()) + * PLUGIN_CLASS_MAP_END + * + */ +#define PLUGIN_CLASS_MAP_BEGIN extern "C" const js_entity_definition_t \ + PLUGIN_CLASS_MAP[] EXPORT_SYMBOL = { + +#define PLUGIN_CLASS_MAP_ADD_INTERFACE(PARENTNAME, \ + INTERFACENAME, \ + JSPRODUCTCLASSTEMPLATE, \ + PRODUCTCONSTRUCTORCB, \ + PRIVDATA) \ + { PARENTNAME, INTERFACENAME, "", JSPRODUCTCLASSTEMPLATE, \ + PRODUCTCONSTRUCTORCB, PRIVDATA }, + +#define PLUGIN_CLASS_MAP_ADD_INTERFACE_PRODUCT(PARENTNAME, OBJECTNAME, \ + INTERFACENAME, PRIVDATA) \ + { PARENTNAME, OBJECTNAME, INTERFACENAME, NULL, NULL, PRIVDATA }, + +#define PLUGIN_CLASS_MAP_ADD_CLASS(PARENTNAME, CLASSNAME, JSCLASSTEMPLATE, \ + PRIVDATA) \ + { PARENTNAME, CLASSNAME, "", JSCLASSTEMPLATE, NULL, PRIVDATA }, + +#define PLUGIN_CLASS_MAP_END { NULL, NULL, NULL, NULL, NULL, NULL } }; + +#define PLUGIN_CLASS_MAP_BEGIN_STATIC static const js_entity_definition_t \ + PLUGIN_CLASS_MAP[] = { + +#define PLUGIN_GET_CLASS_MAP(CALLBACK_NAME) extern "C" const \ + get_widget_entity_map_proc \ + PLUGIN_GET_CLASS_PROC_MAP EXPORT_SYMBOL = CALLBACK_NAME; + +#endif // WRTDEVICEAPIS_COMMONS_PLUGIN_INITIALIZER_DEF_H_ |