diff options
291 files changed, 28793 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f32cf97 --- /dev/null +++ b/.gitignore @@ -0,0 +1,38 @@ +CMakeCache.txt +CMakeFiles/ +build-stamp +cmake_install.cmake +config.guess +config.sub +configure-stamp +debian/files +debian/tmp/ +install_manifest.txt +Makefile +debian/wrt-plugins-dev.install +debian/wrt-plugins.install +debian/wrt-plugins.postinst +debian/wrt-plugins-common-dbg.debhelper.log +debian/wrt-plugins-common-dbg.substvars +debian/wrt-plugins-common-dbg/ +debian/wrt-plugins-common.debhelper.log +debian/wrt-plugins-common.substvars +debian/wrt-plugins-common/ +src/Makefile + +debian/wrt-plugins-common-dev.debhelper.log +debian/wrt-plugins-common-dev.install +debian/wrt-plugins-common-dev.substvars +debian/wrt-plugins-common-dev/ +debian/wrt-plugins-common.install +debian/wrt-plugins-common.postinst +debian/wrt-plugins-common.postinst.debhelper +debian/wrt-plugins-common.postrm.debhelper + +pkgconfigs/*.pc + +*~ +*.swp +cmake_build/* + +/bin diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..dbb0ded --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,175 @@ +# 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. +# +CMAKE_MINIMUM_REQUIRED(VERSION 2.6) + +SET(CMAKE_PROJECT_NAME wrt-plugins-common) +SET(PACKAGE_NAME ${CMAKE_PROJECT_NAME}) +PROJECT(${CMAKE_PROJECT_NAME}) +STRING(REGEX MATCH "([^.]*)" CMAKE_PROJECT_API_VERSION "${CMAKE_PROJECT_VERSION}") + +################################################################################ +# Required platform modules + +INCLUDE(FindPkgConfig) + +PKG_SEARCH_MODULE(dpl REQUIRED dpl-efl>=0.2.21) + +INCLUDE_DIRECTORIES( + ${dpl_INCLUDE_DIRS} + ${CMAKE_CURRENT_SOURCE_DIR}/src/ + ${CMAKE_CURRENT_SOURCE_DIR}/src/modules/API + ${CMAKE_CURRENT_SOURCE_DIR}/src/Commons + ${CMAKE_CURRENT_SOURCE_DIR}/src/CommonsJavaScript + ${CMAKE_CURRENT_SOURCE_DIR}/src/plugin-loading + ${CMAKE_CURRENT_SOURCE_DIR}/src/js-overlay + ${CMAKE_CURRENT_SOURCE_DIR}/src/wrt-popup/ace/popup-runner + ${CMAKE_CURRENT_SOURCE_DIR}/src/plugins_ipc_message + ${CMAKE_CURRENT_SOURCE_DIR}/src/dispatch-event) + +############################################################################## +# Build type +IF(NOT CMAKE_BUILD_TYPE) + SET(CMAKE_BUILD_TYPE "Release") +ENDIF(NOT CMAKE_BUILD_TYPE) + +# Compiler flags +SET(CMAKE_C_FLAGS_PROFILING "-O2") +SET(CMAKE_CXX_FLAGS_PROFILING "-O2 -std=c++0x") +SET(CMAKE_C_FLAGS_DEBUG "-O0 -g") +SET(CMAKE_CXX_FLAGS_DEBUG "-O0 -std=c++0x -g") +SET(CMAKE_C_FLAGS_RELEASE "-O2 -g") +SET(CMAKE_CXX_FLAGS_RELEASE "-O2 -std=c++0x -g -fvisibility-inlines-hidden") +SET(CMAKE_CXX_FLAGS_CCOV "-O0 -std=c++0x -g --coverage") +#### + +OPTION(DPL_LOG "DPL logs status" ON) +SET(LOG_TAG "WRT_PLUGINS/COMMON") +OPTION(WITH_TESTS "Build tests" OFF) + +IF(DPL_LOG AND NOT CMAKE_BUILD_TYPE MATCHES "profiling") + MESSAGE(STATUS "Logging enabled for DPL") + ADD_DEFINITIONS("-DDPL_LOGS_ENABLED") +ELSE(DPL_LOG AND NOT CMAKE_BUILD_TYPE MATCHES "profiling") + MESSAGE(STATUS "Logging disabled for DPL") +ENDIF(DPL_LOG AND NOT CMAKE_BUILD_TYPE MATCHES "profiling") + +MESSAGE(STATUS "WITH_TESTS: " ${WITH_TESTS}) + +ADD_DEFINITIONS("-fPIC") +ADD_DEFINITIONS("-fvisibility=default") # mark all exported symbols as visible +ADD_DEFINITIONS("-fPIC") # If supported for the target machine, emit position-independent code, suitable for dynamic linking and avoiding +ADD_DEFINITIONS("-DEXPORT_API=") +ADD_DEFINITIONS("-Wall") +#ADD_DEFINITIONS("-Werror") +ADD_DEFINITIONS("-Wextra") +ADD_DEFINITIONS("-Wno-deprecated") +#ADD_DEFINITIONS("-DDEVPKG") +# GCC 4.7 changes the scheme of name lookup. Guide: http://gcc.gnu.org/gcc-4.7/porting_to.html +ADD_DEFINITIONS("-fpermissive") + +############################################################################## +# CMake flags +IF (DEVPKG) + SET(DEVPKG "ON") +ENDIF(DEVPKG) + +################################################################################ +# Miscellaneous variables + +SET(CONFIG_FILE_NAME "config.cmake") +SET(LIBS_COMMONS ${dpl_LDFLAGS} ) + +SET(DESTINATION_LIB_PREFIX lib) +SET(DESTINATION_HEADER_PREFIX include/${PROJECT_NAME}) + +SET(DESTINATION_HEADERS_NON_JS ${DESTINATION_HEADER_PREFIX}/Commons) +SET(DESTINATION_HEADERS_JS ${DESTINATION_HEADER_PREFIX}/CommonsJavaScript) +SET(DESTINATION_HEADERS_JS_OVERLAY ${DESTINATION_HEADER_PREFIX}/js-overlay) +SET(DESTINATION_HEADERS_WRT_POPUP_RUNNER ${DESTINATION_HEADER_PREFIX}/popup-runner) + +################################################################################ +# Target platform + +IF (NOT DEFINED PLATFORM) + SET(PLATFORM "tizen") +ENDIF () + +################################################################################ +# Schema of plugin's configuration file + +SET(COMMON_CONFIG_DTD ${CMAKE_CURRENT_SOURCE_DIR}/config.dtd) +SET(COMMON_CONFIG_DTD_DST /usr/etc/wrt-plugins) +INSTALL(FILES ${COMMON_CONFIG_DTD} DESTINATION ${COMMON_CONFIG_DTD_DST}) + +################################################################################ +# Macros used for including plugins from AL. + + +FUNCTION(add_subdir NAME) + MESSAGE(STATUS "Building: ${CMAKE_CURRENT_SOURCE_DIR}/${NAME}") + ADD_SUBDIRECTORY(${NAME}) +ENDFUNCTION() + +################################################################################ +# Subdirectories + +ADD_SUBDIRECTORY(src) + +IF(WITH_TESTS) + ADD_SUBDIRECTORY(tests) +ENDIF(WITH_TESTS) + +################################################################################ +# PKGCONFIG + +SET(PKGCONFIG_DIR ${PROJECT_SOURCE_DIR}/pkgconfigs) + +MACRO(configure_and_install_pkg PKG_FILE) + CONFIGURE_FILE(${PKGCONFIG_DIR}/${PKG_FILE}.in + ${PKGCONFIG_DIR}/${PKG_FILE} @ONLY) + INSTALL(FILES ${PKGCONFIG_DIR}/${PKG_FILE} DESTINATION lib/pkgconfig) +ENDMACRO(configure_and_install_pkg) + +CONFIGURE_AND_INSTALL_PKG(wrt-plugins-commons-javascript.pc) +CONFIGURE_AND_INSTALL_PKG(wrt-plugins-commons.pc) +CONFIGURE_AND_INSTALL_PKG(wrt-plugins-widget-interface.pc) +CONFIGURE_AND_INSTALL_PKG(wrt-plugins-widgetdb.pc) +CONFIGURE_AND_INSTALL_PKG(wrt-plugins-plugin-manager.pc) +CONFIGURE_AND_INSTALL_PKG(wrt-plugin-loading.pc) +CONFIGURE_AND_INSTALL_PKG(wrt-plugin-js-overlay.pc) +CONFIGURE_AND_INSTALL_PKG(wrt-popup-runner.pc) +CONFIGURE_AND_INSTALL_PKG(wrt-popup-ace-runner.pc) +CONFIGURE_AND_INSTALL_PKG(wrt-popup-wrt-runner.pc) +CONFIGURE_AND_INSTALL_PKG(wrt-plugins-api-support.pc) +CONFIGURE_AND_INSTALL_PKG(wrt-plugins-ipc-message.pc) +CONFIGURE_AND_INSTALL_PKG(wrt-dispatch-event.pc) + +################################################################################ +# Cache + +SET(PLATFORM "${PLATFORM}" CACHE STRING "Target platform" FORCE) +SET(CMAKE_CONFIG_FILE_NAME "${CMAKE_CONFIG_FILE_NAME}" CACHE + STRING "CMake configuration file name." FORCE) + +################################################################################ +# SMACK rule + +INSTALL(FILES ${CMAKE_SOURCE_DIR}/wrt-popup-ace-runtime.rule DESTINATION /etc/smack/accesses.d) +INSTALL(FILES ${CMAKE_SOURCE_DIR}/wrt-popup-wrt-runtime.rule DESTINATION /etc/smack/accesses.d) + +################################################################################ +# Summary + +MESSAGE(STATUS "PLATFORM = ${PLATFORM}") @@ -0,0 +1,203 @@ +Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. @@ -0,0 +1 @@ +Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
\ No newline at end of file diff --git a/clean.sh b/clean.sh new file mode 100755 index 0000000..d5d143a --- /dev/null +++ b/clean.sh @@ -0,0 +1,38 @@ +#!/bin/bash +# Copyright (c) 2012 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. +# + +echo Performing clean + +function clean { + rm -rf CMakeCache.txt + rm -rf CMakeFiles + rm -rf cmake_install.cmake + rm -rf Makefile + rm -rf install_manifest.txt + + for i in `ls`; do + if [ -d $i ]; then + cd $i; + clean; + cd .. + fi + done + } + + clean + + + diff --git a/config.dtd b/config.dtd new file mode 100644 index 0000000..d335eff --- /dev/null +++ b/config.dtd @@ -0,0 +1,25 @@ +<!ELEMENT plugin-properties (library-name, feature-set*, api-feature+) > + +<!ELEMENT library-name (#PCDATA)> + +<!ELEMENT feature-set (api-feature-ref+)> +<!ATTLIST feature-set name CDATA #REQUIRED > + +<!ELEMENT api-feature-ref EMPTY> +<!ATTLIST api-feature-ref name CDATA #REQUIRED > + +<!ELEMENT api-feature (name, device-capability*, Object*, Function*, Property* )> + +<!ELEMENT name (#PCDATA) > +<!ELEMENT device-capability (#PCDATA )> + +<!ELEMENT Object (Function*, Property*)> +<!ATTLIST Object name CDATA #REQUIRED > + +<!ELEMENT Function (#PCDATA )> +<!ATTLIST Function name CDATA #REQUIRED > +<!ATTLIST Function restricted CDATA #IMPLIED > + +<!ELEMENT Property (#PCDATA )> + + diff --git a/dir-struct.py b/dir-struct.py new file mode 100755 index 0000000..1d5edab --- /dev/null +++ b/dir-struct.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python +# 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. +# + +import os +import re + + +def countLines(path): + with open(path) as f: + return len(f.readlines()) + +# RETURNS: ( +# short description (string or None) +# long decsription (array of strings or None) +# options: stop +def parseDescr(lines): + if len(lines) == 0: + return (None, None, False) + linesRest = None + if re.match( r"!!!options!!!", lines[0] ): + optStop = True + linesRest = lines[1:] + else: + optStop = False + linesRest = lines + if len(linesRest) == 0: + return(None,None,optStop) + short = linesRest[0].rstrip() + long = [] + for l in linesRest[1:]: + ll = l.rstrip() + if re.search( r"\S", ll ): + long.append( ll ) + if len(long) == 0: + long = None + + return (short, long, optStop) + +# RETURNS a tree with nodes like: ( +# path (string) +# short description (string or None) +# long decsription (array of strings or None) +# LOC (integer) +# list of subdirs (child nodes like this one) +def parseDir(path): + short = None + long = None + optStop = False + try: + with open( path+'/DESCRIPTION' ) as f: + short, long, optStop = parseDescr( f.readlines() ) + except IOError: + pass + dirs = [] + cntLines = 0 + for fname in os.listdir(path): + if fname != '.git' and os.path.isdir(path+'/'+fname): + subdir = parseDir(path+'/'+fname) + if optStop == False: + dirs.append(subdir) + (dummy0, dummy1, dummy2, subLines, dummy4) = subdir + cntLines += subLines + + if os.path.isfile(path+'/'+fname) \ + and not os.path.islink(path+'/'+fname): + cntLines += countLines(path+'/'+fname) + + return path, short, long, cntLines, dirs + +##### PRINT AS a sort of CSV delimited by '|' + +# indent is a number (0..) +def printTabSub(tree,indent): + path, short, long, loc, subdirs = tree + p = re.sub(r"^\./", '', path) + m = re.search(r"/([^/]*$)", p) + if m != None: p = m.groups()[0] + if short == None: + print '%s%s|%d|' % (" "*indent, p, loc) + else: + print '%s%s|%d|%s' % (" "*indent, p, loc, short) + for dir in subdirs: + printTabSub(dir, indent+1) + +def printTab(tree): + printTabSub(tree,0) + +def printTabWoMain(tree): + path, short, long, loc, dirs = tree + for dir in dirs: + printTabSub(dir, 0) + + +##### MAIN + +tree = parseDir('.') +printTabWoMain(tree) + diff --git a/packaging/wrt-plugins-common.spec b/packaging/wrt-plugins-common.spec new file mode 100644 index 0000000..0ffbe31 --- /dev/null +++ b/packaging/wrt-plugins-common.spec @@ -0,0 +1,100 @@ +#git:framework/web/wrt-plugins-common +Name: wrt-plugins-common +Summary: wrt-plugins common library +Version: 0.3.153 +Release: 1 +Group: Development/Libraries +License: Apache License, Version 2.0 +Source0: %{name}-%{version}.tar.gz + +BuildRequires: cmake +BuildRequires: pkgconfig(dpl-efl) +BuildRequires: pkgconfig(wrt-plugins-types) +BuildRequires: pkgconfig(security-client) +BuildRequires: pkgconfig(dpl-event-efl) +BuildRequires: pkgconfig(ewebkit2) +BuildRequires: pkgconfig(dpl-wrt-dao-ro) +BuildRequires: pkgconfig(dpl-wrt-dao-rw) +BuildRequires: pkgconfig(libpcrecpp) +BuildRequires: pkgconfig(icu-i18n) +BuildRequires: pkgconfig(libxml-2.0) +BuildRequires: pkgconfig(cert-svc-vcore) +BuildRequires: pkgconfig(wrt-commons-widget-interface-dao) +Requires: ldconfig + +%description +JavaScript plugins for WebRuntime + +%package devel +Summary: wrt-plugins-common library development headers +Group: Development/Libraries +Requires: %{name} = %{version} + +%description devel +wrt-plugins common library development headers + +%prep +%setup -q + +%define with_tests 0 +%if "%{WITH_TESTS}" == "ON" || "%{WITH_TESTS}" == "Y" || "%{WITH_TESTS}" == "YES" || "%{WITH_TESTS}" == "TRUE" || "%{WITH_TESTS}" == "1" + %define with_tests 1 +%endif + +%build +%if 0%{?sec_build_binary_debug_enable} +export CFLAGS="$CFLAGS -DTIZEN_DEBUG_ENABLE" +export CXXFLAGS="$CXXFLAGS -DTIZEN_DEBUG_ENABLE" +export FFLAGS="$FFLAGS -DTIZEN_DEBUG_ENABLE" +%endif + +export LDFLAGS+="-Wl,--rpath=/usr/lib -Wl,--as-needed -Wl,--hash-style=both" + +cmake . -DCMAKE_INSTALL_PREFIX=%{_prefix} \ + -DDPL_LOG="ON" \ + -DCMAKE_PROJECT_VERSION=%{version} \ + -DCMAKE_BUILD_TYPE=%{?build_type:%build_type} \ + %{?WITH_TESTS:-DWITH_TESTS=%WITH_TESTS} +make %{?jobs:-j%jobs} + +%install +mkdir -p %{buildroot}/usr/share/license +cp LICENSE %{buildroot}/usr/share/license/%{name} +%make_install + +%clean +rm -rf %{buildroot} + +%post +mkdir -p %{_libdir}/wrt-plugins +mkdir -p /usr/etc/wrt/injected-javascript + +#update plugins +if [ -x /usr/bin/wrt-plugins-installer ] +then + /usr/bin/wrt-plugins-installer +else + echo "Cannot find executable: /usr/bin/wrt-plugins-installer!" +fi + +%files +%manifest wrt-plugins-common.manifest +/usr/etc/wrt-plugins/config.dtd +%{_libdir}/*.so +%{_libdir}/*.so.* +%{_libdir}/wrt-plugins/w3c-widget-interface/libwrt-plugins-w3c-widget-interface.so +%attr(755,root,root) %{_bindir}/wrt-popup-ace-runtime +%attr(755,root,root) %{_bindir}/wrt-popup-wrt-runtime +%attr(755,root,root) %{_bindir}/wrt-plugins-installer +%{_datadir}/license/%{name} +/etc/smack/accesses.d/wrt-popup-ace-runtime.rule +/etc/smack/accesses.d/wrt-popup-wrt-runtime.rule +%if %{with_tests} + %attr(755,root,root) %{_bindir}/widgetdb_tests_prepare_db.sh + %attr(755,root,root) %{_bindir}/wrt-plugins-common-tests-widgetdb + %attr(755,root,root) %{_bindir}/wrt-plugins-common-tests-Commons +%endif + +%files devel +%{_includedir}/* +%{_libdir}/pkgconfig/* diff --git a/pkgconfigs/wrt-dispatch-event.pc.in b/pkgconfigs/wrt-dispatch-event.pc.in new file mode 100644 index 0000000..937bcaf --- /dev/null +++ b/pkgconfigs/wrt-dispatch-event.pc.in @@ -0,0 +1,12 @@ +prefix=/usr +project_name=@CMAKE_PROJECT_NAME@ +exec_prefix=${prefix} +libdir=${prefix}/lib +includedir=${prefix}/include/wrt-dispatch-event + +Name: wrt dispatch event support +Description: Support to dispatch DOM event +Version: @CMAKE_PROJECT_VERSION@ +Requires: dpl-efl ewebkit2 +Libs: -L${libdir} -lwrt-dispatch-event +Cflags: -I${includedir} diff --git a/pkgconfigs/wrt-plugin-js-overlay.pc.in b/pkgconfigs/wrt-plugin-js-overlay.pc.in new file mode 100644 index 0000000..7b28b87 --- /dev/null +++ b/pkgconfigs/wrt-plugin-js-overlay.pc.in @@ -0,0 +1,11 @@ +prefix=/usr +project_name=@CMAKE_PROJECT_NAME@ +exec_prefix=${prefix} +includedir=${prefix}/include/${project_name} + +Name: wrt-plugin-js-overlay +Description: header for enum value of supported custom js event types +Version: @CMAKE_PROJECT_VERSION@ +Requires: +Libs: +Cflags: -I${includedir}/js-overlay diff --git a/pkgconfigs/wrt-plugin-loading.pc.in b/pkgconfigs/wrt-plugin-loading.pc.in new file mode 100644 index 0000000..69b9f8f --- /dev/null +++ b/pkgconfigs/wrt-plugin-loading.pc.in @@ -0,0 +1,11 @@ +prefix=/usr +exec_prefix=${prefix} +libdir=${prefix}/lib +includedir=${prefix}/include + +Name: wrt-plugin-loading +Description: wrt-plugin-loading +Version: @PROJECT_VERSION@ +Requires: dpl-efl dpl-wrt-dao-ro ewebkit2 +Libs: -lwrt-plugin-loading -L${libdir} +Cflags: -I${includedir}/wrt-plugin-loading -I${includedir}/wrt-plugins-common diff --git a/pkgconfigs/wrt-plugins-api-support.pc.in b/pkgconfigs/wrt-plugins-api-support.pc.in new file mode 100644 index 0000000..579a085 --- /dev/null +++ b/pkgconfigs/wrt-plugins-api-support.pc.in @@ -0,0 +1,11 @@ +prefix=/usr +exec_prefix=${prefix} +libdir=${prefix}/lib +includedir=${prefix}/include + +Name: wrt-plugins-api-support +Description: wrt-plugins-api-support +Version: @PROJECT_VERSION@ +Requires: +Libs: -lwrt-plugins-api-support -L${libdir} +Cflags: -I${includedir}/wrt-plugins-api-support diff --git a/pkgconfigs/wrt-plugins-commons-javascript.pc.in b/pkgconfigs/wrt-plugins-commons-javascript.pc.in new file mode 100644 index 0000000..b522b22 --- /dev/null +++ b/pkgconfigs/wrt-plugins-commons-javascript.pc.in @@ -0,0 +1,12 @@ +prefix=/usr +project_name=@CMAKE_PROJECT_NAME@ +exec_prefix=${prefix} +libdir=${prefix}/lib +includedir=${prefix}/include/${project_name} + +Name: WrtDeviceApis commons with JavaScrpt dependencies +Description: Commons for DeviceApis with JavaScrpt dependencies +Version: @CMAKE_PROJECT_VERSION@ +Requires: dpl-efl ewebkit2 wrt-plugins-commons +Libs: -L${libdir} -lwrt-plugins-commons-javascript +Cflags: -I${includedir} diff --git a/pkgconfigs/wrt-plugins-commons.pc.in b/pkgconfigs/wrt-plugins-commons.pc.in new file mode 100644 index 0000000..e3c8c7a --- /dev/null +++ b/pkgconfigs/wrt-plugins-commons.pc.in @@ -0,0 +1,12 @@ +prefix=/usr +project_name=@CMAKE_PROJECT_NAME@ +exec_prefix=${prefix} +libdir=${prefix}/lib +includedir=${prefix}/include/${project_name} + +Name: WrtDeviceApis commons +Description: Commons for DeviceApis +Version: @CMAKE_PROJECT_VERSION@ +Requires: dpl-efl +Libs: -L${libdir} -lwrt-plugins-commons +Cflags: -I${includedir} diff --git a/pkgconfigs/wrt-plugins-filesystem.pc.in b/pkgconfigs/wrt-plugins-filesystem.pc.in new file mode 100644 index 0000000..49563e1 --- /dev/null +++ b/pkgconfigs/wrt-plugins-filesystem.pc.in @@ -0,0 +1,12 @@ +prefix=/usr +project_name=@CMAKE_PROJECT_NAME@ +exec_prefix=${prefix} +libdir=${prefix}/lib +includedir=${prefix}/include/${project_name} + +Name: WebRuntime DeviceApis Filesystem module +Description: WebRuntime Filesystem module +Version: @CMAKE_PROJECT_VERSION@ +Requires: dpl-efl wrt-plugins-commons +Libs: -L${libdir} -lwrt-plugins-filesystem +Cflags: -I${includedir}/Filesystem diff --git a/pkgconfigs/wrt-plugins-ipc-message.pc.in b/pkgconfigs/wrt-plugins-ipc-message.pc.in new file mode 100644 index 0000000..8088720 --- /dev/null +++ b/pkgconfigs/wrt-plugins-ipc-message.pc.in @@ -0,0 +1,12 @@ +prefix=/usr +project_name=@CMAKE_PROJECT_NAME@ +exec_prefix=${prefix} +libdir=${prefix}/lib +includedir=${prefix}/include/${project_name} + +Name: wrt ipc message support +Description: Support IPC between plugins and UI Process +Version: @CMAKE_PROJECT_VERSION@ +Requires: dpl-efl ewebkit2 +Libs: -L${libdir} -lwrt-plugins-ipc-message +Cflags: -I${includedir} diff --git a/pkgconfigs/wrt-plugins-plugin-manager.pc.in b/pkgconfigs/wrt-plugins-plugin-manager.pc.in new file mode 100644 index 0000000..c6a3faa --- /dev/null +++ b/pkgconfigs/wrt-plugins-plugin-manager.pc.in @@ -0,0 +1,12 @@ +prefix=/usr +project_name=@CMAKE_PROJECT_NAME@ +exec_prefix=${prefix} +libdir=${prefix}/lib +includedir=${prefix}/include/${project_name} + +Name: WebRuntime DeviceApis Plugin Manager module +Description: WebRuntime Plugin Manager module +Version: @CMAKE_PROJECT_VERSION@ +Requires: dpl-efl wrt-plugins-commons wrt-plugins-commons-javascript dpl-wrt-dao-ro ewebkit2 +Libs: -L${libdir} -lwrt-plugins-plugin-manager +Cflags: -I${includedir}/PluginManager diff --git a/pkgconfigs/wrt-plugins-widget-interface.pc.in b/pkgconfigs/wrt-plugins-widget-interface.pc.in new file mode 100644 index 0000000..8792516 --- /dev/null +++ b/pkgconfigs/wrt-plugins-widget-interface.pc.in @@ -0,0 +1,12 @@ +prefix=/usr +project_name=@CMAKE_PROJECT_NAME@ +exec_prefix=${prefix} +libdir=${prefix}/lib +includedir=${prefix}/include/${project_name} + +Name: WebRuntime DeviceApis Widget Interface module +Description: WebRuntime Widget Interface module +Version: @CMAKE_PROJECT_VERSION@ +Requires: dpl-efl wrt-plugins-commons dpl-wrt-dao-ro wrt-plugins-localstorage wrt-commons-widget-interface-dao +Libs: -L${libdir} -lwrt-plugins-widget-interface +Cflags: -I${includedir}/WidgetInterface diff --git a/pkgconfigs/wrt-plugins-widgetdb.pc.in b/pkgconfigs/wrt-plugins-widgetdb.pc.in new file mode 100644 index 0000000..788423a --- /dev/null +++ b/pkgconfigs/wrt-plugins-widgetdb.pc.in @@ -0,0 +1,12 @@ +prefix=/usr +project_name=@CMAKE_PROJECT_NAME@ +exec_prefix=${prefix} +libdir=${prefix}/lib/ +includedir=${prefix}/include/${project_name} + +Name: WebRuntime DeviceApis WidgetDB module +Description: WebRuntime WidgetDB module +Version: @CMAKE_PROJECT_VERSION@ +Requires: dpl-efl wrt-plugins-commons +Libs: -L${libdir} -lwrt-plugins-widgetdb +Cflags: -I${includedir}/WidgetDB diff --git a/pkgconfigs/wrt-popup-ace-runner.pc.in b/pkgconfigs/wrt-popup-ace-runner.pc.in new file mode 100644 index 0000000..ad9605e --- /dev/null +++ b/pkgconfigs/wrt-popup-ace-runner.pc.in @@ -0,0 +1,12 @@ +prefix=/usr +project_name=@CMAKE_PROJECT_NAME@ +exec_prefix=${prefix} +libdir=${prefix}/lib +includedir=${prefix}/include/${project_name} + +Name: wrt-popup-runner +Description: Library with function to run wrt runtime popup +Version: @CMAKE_PROJECT_VERSION@ +Requires: dpl-efl dpl-dbus-efl elementary security-client +Libs: -L${libdir} -lwrt-popup-ace-runner +Cflags: -I${includedir} diff --git a/pkgconfigs/wrt-popup-runner.pc.in b/pkgconfigs/wrt-popup-runner.pc.in new file mode 100644 index 0000000..ad9605e --- /dev/null +++ b/pkgconfigs/wrt-popup-runner.pc.in @@ -0,0 +1,12 @@ +prefix=/usr +project_name=@CMAKE_PROJECT_NAME@ +exec_prefix=${prefix} +libdir=${prefix}/lib +includedir=${prefix}/include/${project_name} + +Name: wrt-popup-runner +Description: Library with function to run wrt runtime popup +Version: @CMAKE_PROJECT_VERSION@ +Requires: dpl-efl dpl-dbus-efl elementary security-client +Libs: -L${libdir} -lwrt-popup-ace-runner +Cflags: -I${includedir} diff --git a/pkgconfigs/wrt-popup-wrt-runner.pc.in b/pkgconfigs/wrt-popup-wrt-runner.pc.in new file mode 100644 index 0000000..a7b830f --- /dev/null +++ b/pkgconfigs/wrt-popup-wrt-runner.pc.in @@ -0,0 +1,12 @@ +prefix=/usr +project_name=@CMAKE_PROJECT_NAME@ +exec_prefix=${prefix} +libdir=${prefix}/lib +includedir=${prefix}/include/${project_name} + +Name: wrt-popup-runner +Description: Library with function to run wrt runtime popup +Version: @CMAKE_PROJECT_VERSION@ +Requires: dpl-efl +Libs: -L${libdir} -lwrt-popup-wrt-runner +Cflags: -I${includedir} diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt new file mode 100644 index 0000000..9e55bfd --- /dev/null +++ b/src/CMakeLists.txt @@ -0,0 +1,65 @@ +# 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. +# +# Includes CMake configuration file (*.cmake), preserving appropriate paths. + +MACRO(include_config_file INCLUDED_CONFIG_FILE_PATH) + GET_FILENAME_COMPONENT(CURRENT_CONFIG_FILE_PATH ${CMAKE_CURRENT_LIST_FILE} PATH) + INCLUDE(${CURRENT_CONFIG_FILE_PATH}/${INCLUDED_CONFIG_FILE_PATH}/${CONFIG_FILE_NAME} OPTIONAL) +ENDMACRO() + +# Gets actual path for CMake configuration file (*.cmake). +# By default, if no argument is passed, current path will be set to variable +# named CURRENT_PATH. +# @param [Optional] Name of the variable to set with current path. +MACRO(get_current_path) + SET(VARIABLE "CURRENT_PATH") + IF(${ARGC} GREATER 0) + SET(VARIABLE ${ARGV0}) + ENDIF() + GET_FILENAME_COMPONENT(${VARIABLE} ${CMAKE_CURRENT_LIST_FILE} PATH) +ENDMACRO() + +SET(HOST_ARCH $ENV{DEB_HOST_ARCH}) +IF("${HOST_ARCH}" MATCHES "armel") + SET(HOST_ARCH "armel") +ENDIF() + +#target names +SET(TARGET_PLUGIN_LOADING_LIB "wrt-plugin-loading") +SET(TARGET_COMMONS "wrt-plugins-commons") +SET(TARGET_COMMONS_JAVASCRIPT "wrt-plugins-commons-javascript") +SET(TARGET_JS_OVERLAY "wrt-plugins-js-overlay") +SET(TARGET_POPUP_ACE "wrt-popup-ace-runtime") +SET(TARGET_POPUP_ACE_RUNNER_LIB "wrt-popup-ace-runner") +SET(TARGET_POPUP_WRT "wrt-popup-wrt-runtime") +SET(TARGET_POPUP_WRT_RUNNER_LIB "wrt-popup-wrt-runner") +SET(TARGET_PLUGINS_API_SUPPORT "wrt-plugins-api-support") +SET(TARGET_PLUGINS_IPC_MESSAGE_LIB "wrt-plugins-ipc-message") + +SET(PLUGIN_LOADING_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/plugin-loading) +SET(PLUGINS_API_SUPPORT_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/plugins-api-support) +SET(PLUGINS_IPC_MESSAGE_DIRS ${CMAKE_CURRENT_SOURCE_DIR}/plugins-ipc-message) + +ADD_SUBDIRECTORY(plugins-api-support) +ADD_SUBDIRECTORY(plugin-loading) +ADD_SUBDIRECTORY(js-overlay) +ADD_SUBDIRECTORY(Commons) +ADD_SUBDIRECTORY(CommonsJavaScript) +ADD_SUBDIRECTORY(dispatch-event) +ADD_SUBDIRECTORY(modules) +ADD_SUBDIRECTORY(standards) +ADD_SUBDIRECTORY(wrt-popup) +ADD_SUBDIRECTORY(plugins-installer) +ADD_SUBDIRECTORY(plugins-ipc-message) 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_ diff --git a/src/CommonsJavaScript/CMakeLists.txt b/src/CommonsJavaScript/CMakeLists.txt new file mode 100755 index 0000000..f442852 --- /dev/null +++ b/src/CommonsJavaScript/CMakeLists.txt @@ -0,0 +1,81 @@ +# 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_JS}) +ENDMACRO() + + +PKG_SEARCH_MODULE(webkit2 REQUIRED ewebkit2) + +SET(TARGET_NAME ${TARGET_COMMONS_JAVASCRIPT}) + +INCLUDE_DIRECTORIES(${DIR_JS_COMMONS} + ${wrt-plugin-api_INCLUDE_DIRS} + ${webkit2_INCLUDE_DIRS}} + ) + + +SET(SRCS + ${CMAKE_CURRENT_SOURCE_DIR}/Converter.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/ScopedJSStringRef.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/JSCallbackManager.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/JSUtils.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/ScopedJSStringRef.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/Validator.cpp + # wrapper for simple version of aceCheckAcces + ${CMAKE_CURRENT_SOURCE_DIR}/Security/SecurityFunctionDeclaration.cpp + #ECMA Script Exception + ${CMAKE_CURRENT_SOURCE_DIR}/JSDOMException.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/DOMExceptionData.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/JSDOMExceptionFactory.cpp +) + + +ADD_LIBRARY(${TARGET_NAME} SHARED ${SRCS}) +TARGET_LINK_LIBRARIES(${TARGET_NAME} + ${LIBS_COMMONS} + ${webkit2_LIBRARIES} + ${TARGET_COMMONS} +) + +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}) + +#utils +INSTALL_HEADER_FILE(PrivateObject.h) +#tools +INSTALL_HEADER_FILE(Converter.h) +INSTALL_HEADER_FILE(Validator.h) +INSTALL_HEADER_FILE(JSUtils.h) +INSTALL_HEADER_FILE(ScopedJSStringRef.h) +#callback manager +INSTALL_HEADER_FILE(JSCallbackManager.h) +#exceptions +INSTALL_HEADER_FILE(JSDOMException.h) +INSTALL_HEADER_FILE(JSDOMExceptionFactory.h) +INSTALL_HEADER_FILE(DOMExceptionData.h) +INSTALL_HEADER_FILE(SecurityExceptions.h) +#static declarations +INSTALL_HEADER_FILE(Security/StaticDeclaration.h) +INSTALL_HEADER_FILE(Security/SecurityFunctionDeclaration.h) + diff --git a/src/CommonsJavaScript/Converter.cpp b/src/CommonsJavaScript/Converter.cpp new file mode 100644 index 0000000..e68c16b --- /dev/null +++ b/src/CommonsJavaScript/Converter.cpp @@ -0,0 +1,389 @@ +/* + * 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 <sstream> +#include <limits> +#include <dpl/scoped_free.h> +#include "ScopedJSStringRef.h" +#include "Converter.h" + +using namespace WrtDeviceApis::Commons; + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +Converter::Converter(JSContextRef context) : m_context(context) +{} + +Converter::~Converter() +{} + +JSObjectRef Converter::toJSObjectRef(const JSValueRef& arg) +{ + if (!arg) { + Throw(NullPointerException); + } + JSValueRef exception = NULL; + JSObjectRef result = JSValueToObject(m_context, arg, &exception); + if ((NULL == result) || (NULL != exception)) { + ThrowMsg(ConversionException, "Couldn't convert to a JS Object."); + } + return result; +} + +bool Converter::toBool(const JSValueRef& arg) +{ + return JSValueToBoolean(m_context, arg); +} + +unsigned char Converter::toUChar(const JSValueRef& arg) +{ + return static_cast<unsigned char>(toChar(arg)); +} + +char Converter::toChar(const JSValueRef& arg) +{ + double tmp = toNumber_(arg); + return (isNan(tmp) ? 0 : static_cast<char>(tmp)); +} + +int Converter::toInt(const JSValueRef& arg) +{ + double tmp = toNumber_(arg); + return (isNan(tmp) ? 0 : static_cast<int>(tmp)); +} + +int Converter::toInt(const std::string &arg) +{ + return static_cast<int>(toNumber_(arg)); +} + +long Converter::toLong(const JSValueRef& arg) +{ + double tmp = toNumber_(arg); + return (isNan(tmp) ? 0 : static_cast<long>(tmp)); +} + +long long Converter::toLongLong(const JSValueRef& arg) +{ + double tmp = toNumber_(arg); + return (isNan(tmp) ? 0 : static_cast<long long>(tmp)); +} + +unsigned long Converter::toULong(const JSValueRef& arg) +{ + double tmp = toNumber_(arg); + return (isNan(tmp) ? 0 : static_cast<unsigned long>(tmp)); +} + +std::size_t Converter::toSizeT(const JSValueRef& arg) +{ + double tmp = toNumber_(arg); + return (isNan(tmp) ? 0 : static_cast<std::size_t>(tmp)); +} + +std::size_t Converter::toSizeT(const JSStringRef& arg) +{ + return static_cast<std::size_t>(toNumber_(arg)); +} + +double Converter::toDouble(const JSValueRef& arg) +{ + return toNumber_(arg); +} + +std::string Converter::toString(int arg) +{ + return toString_(arg); +} + +std::string Converter::toString(unsigned long arg) +{ + return toString_(arg); +} + +std::string Converter::toString(long arg) +{ + return toString_(arg); +} + +std::string Converter::toString(std::size_t arg) +{ + return toString_(arg); +} + +std::string Converter::toString(const JSValueRef& arg) +{ + return toString_(arg); +} + +std::string Converter::tryString(const JSValueRef& arg) +{ + if (!JSValueIsString(m_context, arg) && + !JSValueIsNumber(m_context, arg) && + !JSValueIsBoolean(m_context, arg)) + { + ThrowMsg(ConversionException, + "Argument is not convertable to JS String."); + } + + return toString_(arg); +} + +std::string Converter::toDateString(const JSValueRef& arg) +{ + if (!JSValueIsObject(m_context, arg)) { + ThrowMsg(ConversionException, "Argument is not JS Date."); + } + + return toString_(arg); +} + +std::string Converter::toString(const JSStringRef& arg) +{ + std::string result; + size_t jsSize = JSStringGetMaximumUTF8CStringSize(arg); + if (jsSize > 0) { + jsSize = jsSize + 1; + std::unique_ptr<char[]> buffer(new char[jsSize]); + size_t written = JSStringGetUTF8CString(arg, buffer.get(), jsSize); + if (written > jsSize) { + ThrowMsg(ConversionException, + "Conversion could not be fully performed."); + } + result = buffer.get(); + } + + return result; +} + +time_t Converter::toDateTimeT(const JSValueRef& arg) +{ + struct tm tm = toDateTm(arg); + return mktime(&tm); +} + +tm Converter::toDateTm(const JSValueRef& arg) +{ + using namespace std::placeholders; + + std::string stringDate = toDateString(arg); + struct tm result; + char* currentLocale = setlocale(LC_TIME, NULL); + if (currentLocale == NULL) { + ThrowMsg(ConversionException, "Couldn't get current locale."); + } + std::unique_ptr<char, void(*)(void*)> currentLocaleCopy(strdup(currentLocale), &free); + if (setlocale(LC_TIME, "C") == NULL) { + ThrowMsg(ConversionException, "Couldn't set POSIX locale."); + } + if (strptime(stringDate.c_str(), "%a %b %d %Y %T", &result) == NULL) { + ThrowMsg(ConversionException, "Couldn't convert supplied date."); + } + if (setlocale(LC_TIME, currentLocaleCopy.get()) == NULL) { + ThrowMsg(ConversionException, "Couldn't set previous locale back."); + } + //strptime function doesn't affect tm_isdst flag. + //It may cause -1hr conversion error. Setting it to -1 informs that + //there is no information about daylight saving time. + result.tm_isdst = -1; + return result; +} + +std::vector<unsigned char> Converter::toVectorOfUChars(const JSValueRef& arg) +{ + return toVectorOfT_(arg, &Converter::toUChar); +} + +std::vector<char> Converter::toVectorOfChars(const JSValueRef& arg) +{ + return toVectorOfT_(arg, &Converter::toChar); +} + +std::vector<int> Converter::toVectorOfInts(const JSValueRef& arg) +{ + return toVectorOfT_(arg, &Converter::toInt); +} + +std::vector<std::string> Converter::toVectorOfStrings(const JSValueRef& arg) +{ + return toVectorOfT_(arg, &Converter::toString); +} + +std::vector<time_t> Converter::toVectorOfTimeT(const JSValueRef& arg) +{ + return toVectorOfT_(arg, &Converter::toDateTimeT); +} + +JSValueRef Converter::toJSValueRef(bool arg) +{ + return JSValueMakeBoolean(m_context, arg); +} + +JSValueRef Converter::toJSValueRef(int arg) +{ + return JSValueMakeNumber(m_context, arg); +} + +JSValueRef Converter::toJSValueRef(unsigned int arg) +{ + return JSValueMakeNumber(m_context, arg); +} + +JSValueRef Converter::toJSValueRef(unsigned long arg) +{ + return JSValueMakeNumber(m_context, arg); +} + +JSValueRef Converter::toJSValueRefLong(const long arg) +{ + return JSValueMakeNumber(m_context, arg); +} + +JSValueRef Converter::toJSValueRef(long long int arg) +{ + return JSValueMakeNumber(m_context, arg); +} + +JSValueRef Converter::toJSValueRef(double arg) +{ + return JSValueMakeNumber(m_context, arg); +} + +JSValueRef Converter::toJSValueRef(const std::string& arg) +{ + JSValueRef result = NULL; + JSStringRef jsString = JSStringCreateWithUTF8CString(arg.c_str()); + result = JSValueMakeString(m_context, jsString); + JSStringRelease(jsString); + return result; +} + +JSValueRef Converter::toJSValueRef(const tm& arg) +{ + JSValueRef args[6]; + args[0] = JSValueMakeNumber(m_context, arg.tm_year + 1900); + args[1] = JSValueMakeNumber(m_context, arg.tm_mon); + args[2] = JSValueMakeNumber(m_context, arg.tm_mday); + args[3] = JSValueMakeNumber(m_context, arg.tm_hour); + args[4] = JSValueMakeNumber(m_context, arg.tm_min); + args[5] = JSValueMakeNumber(m_context, arg.tm_sec); + + JSValueRef exception = NULL; + JSObjectRef result = JSObjectMakeDate(m_context, 6, args, &exception); + if (NULL != exception) { + ThrowMsg(ConversionException, "Couldn't convert to a JS Date."); + } + + return result; +} + +JSValueRef Converter::toJSValueRef(const time_t arg) +{ + struct tm tminfo; + memset(&tminfo,0,sizeof(tminfo)); + localtime_r(&arg, &tminfo); + return toJSValueRef(tminfo); +} + +JSValueRef Converter::toJSValueRef(const std::vector<std::string>& arg) +{ + return toJSValueRef_(arg); +} + +JSValueRef Converter::toJSValueRef(const char* arg) +{ + return toJSValueRef(std::string(arg)); +} + +JSValueRef Converter::toJSValueRef(const std::vector<int>& arg) +{ + return toJSValueRef_(arg); +} + +JSValueRef Converter::toJSValueRef(const std::vector<time_t>& arg) +{ + return toJSValueRef_(arg); +} + +JSValueRef Converter::toJSValueRef(JSValueRef arg) +{ + return arg; +} + +JSValueRef Converter::toJSValueRef(const std::vector<JSValueRef>& arg) +{ + return toJSValueRef_(arg); +} + +JSStringRef Converter::toJSStringRef(const std::string& arg) +{ + return JSStringCreateWithUTF8CString(arg.c_str()); +} + +double Converter::toNumber_(const JSStringRef& arg) +{ + return toNumber_(toString(arg)); +} + +double Converter::toNumber_(const std::string& arg) +{ + double result; + std::stringstream ss(arg); + if (!(ss >> result)) { + Throw(ConversionException); + } + return result; +} + +double Converter::toNumber_(const JSValueRef& arg) +{ + JSValueRef exception = NULL; + double result = JSValueToNumber(m_context, arg, &exception); + if (NULL != exception) { + ThrowMsg(ConversionException, "Couldn't convert to a number."); + } + return result; +} + +std::string Converter::toString_(const JSValueRef& arg) +{ + std::string result; + + JSValueRef exception = NULL; + JSStringRef str = JSValueToStringCopy(m_context, arg, &exception); + if (NULL == str) { + ThrowMsg(ConversionException, "Couldn't cast to a string."); + } + + size_t jsSize = JSStringGetMaximumUTF8CStringSize(str); + if (jsSize > 0) { + std::unique_ptr<char[]> buffer(new char[jsSize]); + JSStringGetUTF8CString(str, buffer.get(), jsSize); + result = buffer.get(); + } + JSStringRelease(str); + return result; +} + +bool Converter::isNan(double value) const +{ + // This should work unless -ffast-math (GCC) option is used. + STATIC_CHECK(std::numeric_limits<double>::is_iec559, + NOT_IEEE754_REPRESENTATION); + return (value != value); +} +} // CommonsJavaScript +} // WrtDeviceApis + diff --git a/src/CommonsJavaScript/Converter.h b/src/CommonsJavaScript/Converter.h new file mode 100644 index 0000000..0194c22 --- /dev/null +++ b/src/CommonsJavaScript/Converter.h @@ -0,0 +1,585 @@ +/* + * 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_COMMONSJAVASCRIPT_CONVERTER_H_ +#define WRTDEVICEAPIS_COMMONSJAVASCRIPT_CONVERTER_H_ + +#include <ctime> +#include <cstddef> +#include <string> +#include <vector> +#include <list> +#include <memory> +#include <JavaScriptCore/JavaScript.h> +#include <dpl/noncopyable.h> +#include <Commons/Exception.h> +#include <Commons/StaticAssert.h> + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +class Converter : private DPL::Noncopyable +{ + public: + explicit Converter(JSContextRef context); + virtual ~Converter(); + + /** + * Converts JSValueRef to JSObjectRef. + * @param arg JSValueRef object to convert. + * @return JSObjectRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSObjectRef toJSObjectRef(const JSValueRef& arg); + + /** + * Converts JSValueRef object to boolean value. + * @param arg JSValueRef object to convert. + * @return Boolean value. + * @throw ConversionException Thrown when conversion fails. + */ + bool toBool(const JSValueRef& arg); + + /** + * Converts JSValueRef object to unsigned char value. + * @param arg JSValueRef object to convert. + * @return Unsigned char value. + * @throw ConversionException Thrown when conversion fails. + */ + unsigned char toUChar(const JSValueRef& arg); + + /** + * Converts JSValueRef object to char value. + * @param arg JSValueRef object to convert. + * @return Char value. + * @throw ConversionException Thrown when conversion fails. + */ + char toChar(const JSValueRef& arg); + + /** + * Converts JSValueRef to integer value. + * @param arg JSValueRef object to convert. + * @return Integer value. + * @throw ConversionException Thrown when conversion fails. + */ + int toInt(const JSValueRef& arg); + + /** + * Converts string to integer value. + * @param arg string to convert. + * @return Integer value. + * @throw ConversionException Thrown when conversion fails. + */ + int toInt(const std::string& arg); + + /** + * Converts JSvalueRef to long integer value. + * @param arg JSValueRef object to convert. + * @return Long integer value. + * @throw ConversionException Thrown when conversion fails. + */ + long toLong(const JSValueRef& arg); + + /** + * Converts JSvalueRef to long long integer value. + * @param arg JSValueRef object to convert. + * @return Long long integer value. + * @throw ConversionException Thrown when conversion fails. + */ + long long toLongLong(const JSValueRef& arg); + /** + * Converts JSValueRef to unsigned long value. + * @param arg JSValueRef object to convert. + * @return Unsigned long value. + * @throw ConversionException Thrown when conversion fails. + */ + unsigned long toULong(const JSValueRef& arg); + + /** + * Converts JSValueRef to double value. + * @param arg JSValueRef object to convert. + * @return Double value. + * @throw ConversionException Thrown when conversion fails. + */ + double toDouble(const JSValueRef& arg); + + /** + * Converts JSValueRef to size_t value. + * @param arg JSValueRef object to convert. + * @return Size_t value. + * @throw ConversionException Thrown when conversion fails. + */ + std::size_t toSizeT(const JSValueRef& arg); + + /** + * Converts JSStringRef to size_t value. + * @param arg JSStringRef object to convert. + * @return Size_t value. + * @throw ConversionException Thrown when conversion fails. + */ + std::size_t toSizeT(const JSStringRef& arg); + + /** + * Converts int to STL string. + * @param arg int to convert. + * @return STL string. + * @throw ConversionException Thrown when conversion fails. + */ + std::string toString(int arg); + + std::string toString(unsigned long arg); + + std::string toString(long arg); + + std::string toString(std::size_t arg); + + /** + * Converts JSValueRef to STL string. + * @param arg JSValueRef to convert. + * @return STL string. + * @throw ConversionException Thrown when conversion fails. + * @remarks If one wants to convert JS Date object to a string then + * toDateString() should be used. + */ + std::string toString(const JSValueRef& arg); + + /** + * Converts JSStringRef to STL string. + * @param arg JSStringRef to convert. + * @return STL string. + * @throw ConversionException Thrown when conversion fails. + */ + std::string toString(const JSStringRef& arg); + + /** + * Converts JSSValueRef to STL string if + * arg is one of: String, Number, Bool + * @param arg JSValueReg to convert. + * @return STL string. + * @throw ConversionException Thrown when conversion fails. + */ + std::string tryString(const JSValueRef& arg); + + /** + * Converts JS Date object to STL string. + * @param arg JS Date object to convert. + * @return STL string. + * @throw ConversionException Thrown when conversion fails. + */ + std::string toDateString(const JSValueRef& arg); + + /** + * Converts JSValueRef to time_t value. + * @param arg JSValueRef to convert. + * @return time_t value. + * @throw ConversionException Thrown when conversion fails. + */ + time_t toDateTimeT(const JSValueRef& arg); + + /** + * Converts JSValueRef to tm struct. + * @param arg JSValueRef to convert. + * @return tm struct. + * @throw ConversionException Thrown when conversion fails. + */ + tm toDateTm(const JSValueRef& arg); + + /** + * Converts JSValueRef to vector<unsigned char>. + * @param arg JSValueRef to convert. + * @return vector<unsigned char>. + * @throw ConversionException Thrown when conversion fails. + */ + std::vector<unsigned char> toVectorOfUChars(const JSValueRef& arg); + + /** + * Converts JSValueRef to vector<char>. + * @param arg JSValueRef to convert. + * @return vector<char>. + * @throw ConversionException Thrown when conversion fails. + */ + std::vector<char> toVectorOfChars(const JSValueRef& arg); + + /** + * Converts JSValueRef to vector<int>. + * @param arg JSValueRef to convert. + * @return vector<int>. + * @throw ConversionException Thrown when conversion fails. + */ + std::vector<int> toVectorOfInts(const JSValueRef& arg); + + /** + * Converts JSValueRef to vector of string. + * @param arg JSValueRef to convert. + * @return std::vector<std::string> + * @throw ConversionException Thrown when conversion fails. + */ + std::vector<std::string> toVectorOfStrings(const JSValueRef& arg); + + /** + * Converts JSValueRef to vector of time_t. + * @param arg JSValueRef to convert. + * @return std::vector<std::time_t> + * @throw ConversionException Thrown when conversion fails. + */ + std::vector<std::time_t> toVectorOfTimeT(const JSValueRef& arg); + + /** + * Converts boolean value to JSValueRef. + * @param arg Boolean value to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(bool arg); + + /** + * Converts integer value to JSValueRef. + * @param arg Integer value to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(int arg); + + /** + * Converts unsigned integer value to JSValueRef. + * @param arg Unsigned integer value to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(unsigned int arg); + + /** + * Converts double value to JSValueRef. + * @param arg Double value to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(double arg); + + /** + * Converts unsigned long value to JSValueRef. + * @param arg unsigned long value to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(unsigned long arg); + + /** + * Converts long value to JSValueRef. + * @param arg long value to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRefLong(const long arg); + + /** + * Converts unsigned long value to JSValueRef. + * @param arg long long int value to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(long long int arg); + + /** + * Converts STL string to JSValueRef. + * @param arg STL string to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(const std::string& arg); + + /** + * Converts char sequence to JSValueRef. + * @param arg char sequence to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(const char* arg); + + /** + * Converts time_t value to JSValueRef. + * @param arg time_t value to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(const time_t arg); + + /** + * Converts tm struct to JSValueRef. + * @param arg tm struct to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(const tm& arg); + + /** + * Converts STL vector of integer to JSValueRef. + * @param arg STL vector of integer to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(const std::vector<int>& arg); + + /** + * Converts STL vector of time_t to JSValueRef. + * @param arg STL vector of time_t to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(const std::vector<time_t>& arg); + + /** + * Converts STL vector of string to JSStringRef. + * @param arg STL string to convert. + * @return JSValueRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(const std::vector<std::string>& arg); + + /** + * Converts JSValueRef to JSValueRef + * @param JSValueRef js value which is returned + * @return JSValueRef - parameter + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(JSValueRef arg); + + /** + * Converts std::vector to JSValueRef + * @param arg vecotr of JSValueRefs + * @return JSValueRef - js array + * @throw ConversionException Thrown when conversion fails. + */ + JSValueRef toJSValueRef(const std::vector<JSValueRef>& arg); + + /** + * Template specialization to catch errors caused + * by wrong usage of general template or + * implicit conversions from shared_ptr to + * specialized type + * */ + template<class Class> + JSValueRef toJSValueRef(const std::shared_ptr<Class>& c) + { + STATIC_ERROR(ERROR_INVALID_IMPLICIT_CONVERSION, c) + //above macro causes compilation error + return static_cast<JSValueRef>(NULL); + } + + /** + * Converts STL string to JSStringRef. + * @param arg STL string to convert. + * @return JSStringRef object. + * @throw ConversionException Thrown when conversion fails. + */ + JSStringRef toJSStringRef(const std::string& arg); + + protected: + bool isNan(double value) const; + + double toNumber_(const JSValueRef& arg); + + double toNumber_(const JSStringRef& arg); + + double toNumber_(const std::string& arg); + + template<typename T, class Derived> + std::vector<T> toVectorOfT_(const JSValueRef& arg, + T (Derived::*f)(const JSValueRef &), + Derived* object) + { + if (JSValueIsNull(m_context, + arg) || JSValueIsUndefined(m_context, arg)) + { + return std::vector<T>(); + } + + if (!JSIsArrayValue(m_context, arg)) { + ThrowMsg(Commons::ConversionException, + "Argument is not an JS array."); + } + + std::vector<T> result; + JSObjectRef objArg = toJSObjectRef(arg); + for (std::size_t i = 0; i < JSGetArrayLength(m_context, objArg); ++i) { + JSValueRef element = JSGetArrayElement(m_context, objArg, i); + result.push_back((object->*f)(element)); + } + return result; + } + + template<typename T> + std::vector<T> toVectorOfT_(const JSValueRef& arg, + T (Converter::*f)(const JSValueRef &)) + { + if (JSValueIsNull(m_context, + arg) || JSValueIsUndefined(m_context, arg)) + { + return std::vector<T>(); + } + + if (!JSIsArrayValue(m_context, arg)) { + ThrowMsg(Commons::ConversionException, + "Argument is not an JS array."); + } + + std::vector<T> result; + JSObjectRef objArg = toJSObjectRef(arg); + for (std::size_t i = 0; i < JSGetArrayLength(m_context, objArg); ++i) { + JSValueRef element = JSGetArrayElement(m_context, objArg, i); + result.push_back((this->*f)(element)); + } + return result; + } + + template<class T, class Derived> + JSValueRef toJSValueRef_(const std::vector<T>& arg, + JSValueRef (Derived::*f)(const T &), + Derived* object) + { + JSObjectRef jsResult = JSCreateArrayObject(m_context, 0, NULL); + + if (NULL == jsResult) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, + "Could not create js array object"); + } + + for (std::size_t i = 0; i < arg.size(); ++i) { + JSValueRef tmpVal = (object->*f)(arg[i]); + if (!JSSetArrayElement(m_context, jsResult, i, tmpVal)) { + ThrowMsg(WrtDeviceApis::Commons::UnknownException, + "Could not insert value into js array"); + } + } + + return jsResult; + } + + template<class T> + JSValueRef toJSValueRef_(const std::vector<T>& arg) + { + JSObjectRef jsResult = JSCreateArrayObject(m_context, 0, NULL); + + if (NULL == jsResult) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, + "Could not create js array object"); + } + + for (std::size_t i = 0; i < arg.size(); ++i) { + JSValueRef tmpVal = toJSValueRef(arg[i]); + if (!JSSetArrayElement(m_context, jsResult, i, tmpVal)) { + ThrowMsg(WrtDeviceApis::Commons::UnknownException, + "Could not insert value into js array"); + } + } + + return jsResult; + } + + template<class T> + JSValueRef toJSValueRef_(const std::list<T>& arg) + { + JSObjectRef jsResult = JSCreateArrayObject(m_context, 0, NULL); + + if (NULL == jsResult) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, + "Could not create js array object"); + } + + typename std::list<T>::const_iterator it = arg.begin(); + for (std::size_t i = 0; it != arg.end(); ++i, ++it) { + JSValueRef tmpVal = toJSValueRef(*it); + if (!JSSetArrayElement(m_context, jsResult, i, tmpVal)) { + ThrowMsg(WrtDeviceApis::Commons::UnknownException, + "Could not insert value into js array"); + } + } + + return jsResult; + } + + template<class T, class Derived> + JSValueRef toJSValueRef_(const std::list<T>& arg, + JSValueRef (Derived::*f)(const T &), + Derived* object) + { + JSObjectRef jsResult = JSCreateArrayObject(m_context, 0, NULL); + + if (NULL == jsResult) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, + "Could not create js array object"); + } + + typename std::list<T>::const_iterator it = arg.begin(); + for (std::size_t i = 0; it != arg.end(); ++i, ++it) { + JSValueRef tmpVal = (object->*f)(*it); + if (!JSSetArrayElement(m_context, jsResult, i, tmpVal)) { + ThrowMsg(WrtDeviceApis::Commons::UnknownException, + "Could not insert value into js array"); + } + } + + return jsResult; + } + + std::string toString_(const JSValueRef& arg); + + template<typename T> + std::string toString_(const T& arg) + { + std::stringstream ss; + if (!(ss << arg)) { + ThrowMsg(WrtDeviceApis::Commons::ConversionException, + "Could not convert to string."); + } + return ss.str(); + } + + protected: + JSContextRef m_context; +}; + +template<class C> +class ConverterFactory : private DPL::Noncopyable +{ + public: + /** + * Converter type which deletes itself when gets out of scope. + */ + typedef std::shared_ptr<C> ConverterType; + + public: + /** + * Gets converter object. + * @param context JavaScript context the conversion will be performed in. + * @param[out] exception JavaScript value for storing exception. + * @return Converter object. + */ + static ConverterType getConverter(JSContextRef context) + { + C* convert = new C(context); + return ConverterType(convert); + } + + private: + ConverterFactory(); +}; + +typedef ConverterFactory<Converter> BasicConverterFactory; + +typedef BasicConverterFactory::ConverterType BasicConverter; +} // CommonsJavaScript +} // WrtDeviceApis + +#endif /* WRTDEVICEAPIS_COMMONSJAVASCRIPT_CONVERTER_H_ */ diff --git a/src/CommonsJavaScript/DESCRIPTION b/src/CommonsJavaScript/DESCRIPTION new file mode 100644 index 0000000..7f04546 --- /dev/null +++ b/src/CommonsJavaScript/DESCRIPTION @@ -0,0 +1 @@ +Common code diff --git a/src/CommonsJavaScript/DOMExceptionData.cpp b/src/CommonsJavaScript/DOMExceptionData.cpp new file mode 100644 index 0000000..3eb148a --- /dev/null +++ b/src/CommonsJavaScript/DOMExceptionData.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. + */ +#include "DOMExceptionData.h" + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +DOMExceptionData::DOMExceptionData(int code, + const std::string& message) : + m_code(code), + m_message(message) +{} + +int DOMExceptionData::getCode() const +{ + return m_code; +} + +std::string DOMExceptionData::getMessage() const +{ + return m_message; +} +} // CommonsJavaScript +} // WrtDeviceApis diff --git a/src/CommonsJavaScript/DOMExceptionData.h b/src/CommonsJavaScript/DOMExceptionData.h new file mode 100644 index 0000000..140d875 --- /dev/null +++ b/src/CommonsJavaScript/DOMExceptionData.h @@ -0,0 +1,42 @@ +/* + * 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_COMMONSJAVASCRIPT_DOM_EXCEPTION_DATA_H_ +#define WRTDEVICEAPIS_COMMONSJAVASCRIPT_DOM_EXCEPTION_DATA_H_ + +#include <string> +#include <memory> + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +class DOMExceptionData +{ + public: + explicit DOMExceptionData(int code, + const std::string& message = std::string()); + + int getCode() const; + std::string getMessage() const; + + private: + int m_code; + std::string m_message; +}; + +typedef std::shared_ptr<DOMExceptionData> DOMExceptionDataPtr; +} // CommonsJavaScript +} // WrtDeviceApis + +#endif // WRT_DOM_EXCEPTION_DATA_H_ diff --git a/src/CommonsJavaScript/JSCallbackManager.cpp b/src/CommonsJavaScript/JSCallbackManager.cpp new file mode 100644 index 0000000..b2d29f0 --- /dev/null +++ b/src/CommonsJavaScript/JSCallbackManager.cpp @@ -0,0 +1,247 @@ +/* + * 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 JSCallbackManager.cpp + * @author Lukasz Marek (l.marek@samsung.com) + * @version 0.1 + */ + +#include "JSCallbackManager.h" +#include <WKBundle.h> +#include <dpl/log/wrt_log.h> + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +JSCallbackManagerPtr JSCallbackManager::createObject( + JSContextRef context, + JSValueRef onSuccess, + JSValueRef onError, + bool + acceptJSNullAsOnSuccess, + bool acceptJSNullAsOnError) +{ + JSObjectRef l_onSuccess = NULL; + JSObjectRef l_onError = NULL; + + if (NULL != onSuccess && + (!acceptJSNullAsOnSuccess || !JSValueIsNull(context, onSuccess))) + { + l_onSuccess = JSValueToObject(context, onSuccess, NULL); + if (!l_onSuccess || + !JSObjectIsFunction(context, l_onSuccess)) + { + ThrowMsg(Commons::InvalidArgumentException, + "success callback is not a function"); + } + } else { + //WrtLogW("onSuccessCallback is NULL and is not registred"); + } + if (NULL != onError && + (!acceptJSNullAsOnError || !JSValueIsNull(context, onError))) + { + l_onError = JSValueToObject(context, onError, NULL); + if (!l_onError || + !JSObjectIsFunction(context, l_onError)) + { + ThrowMsg(Commons::InvalidArgumentException, + "error callback is not a function"); + } + } else { + //WrtLogW("onErrorCallback is NULL and is not registred"); + } + return JSCallbackManagerPtr(new JSCallbackManager(context, l_onSuccess, + l_onError)); +} + +JSCallbackManager::JSCallbackManager(JSContextRef context, + JSObjectRef onSuccess, + JSObjectRef onError) : + m_onSuccess(NULL), + m_onError(NULL), + m_context(context), + m_object(NULL) +{ + setOnSuccess(onSuccess); + setOnError(onError); +} + +JSCallbackManager::~JSCallbackManager() +{ + if (m_onSuccess) { + JSValueUnprotect(m_context, m_onSuccess); + } + + if (m_onError) { + JSValueUnprotect(m_context, m_onError); + } + + if (m_object) { + JSValueUnprotect(m_context, m_object); + } +} + +void JSCallbackManager::setOnSuccess(JSValueRef onSuccess) +{ + if (m_onSuccess != NULL) { + JSValueUnprotect(m_context, m_onSuccess); + } + + if (onSuccess) { + m_onSuccess = JSValueToObject(m_context, onSuccess, NULL); + } else { + m_onSuccess = NULL; + } + + if (m_onSuccess != NULL) { + JSValueProtect(m_context, m_onSuccess); + } +} + +JSValueRef JSCallbackManager::getOnSuccess() const +{ + return m_onSuccess; +} + +void JSCallbackManager::setOnError(JSValueRef onError) +{ + if (m_onError != NULL) { + JSValueUnprotect(m_context, m_onError); + } + + if (onError) { + m_onError = JSValueToObject(m_context, onError, NULL); + } else { + m_onError = NULL; + } + + if (m_onError != NULL) { + JSValueProtect(m_context, m_onError); + } +} + +JSValueRef JSCallbackManager::getOnError() const +{ + return m_onError; +} + +void JSCallbackManager::setObject(JSObjectRef object) +{ + if (m_object != NULL) { + JSValueUnprotect(m_context, m_object); + } + + m_object = object; + + if (m_object != NULL) { + JSValueProtect(m_context, m_object); + } +} + +JSObjectRef JSCallbackManager::getObject() const +{ + return m_object; +} + +void JSCallbackManager::setContext(JSContextRef context) +{ + m_context = context; +} + +void JSCallbackManager::callOnSuccess() +{ + if (m_onSuccess == NULL) { + //WrtLogD("Success callback is not set"); + return; + } + makeCallback(m_context, NULL, m_onSuccess, NULL, 0); +} + +void JSCallbackManager::callOnSuccess(JSValueRef obj) +{ + if (m_onSuccess == NULL) { + //WrtLogD("Success callback is not set"); + return; + } + JSValueRef objParam[1] = { obj }; + makeCallback(m_context, NULL, m_onSuccess, objParam, 1); +} + +void JSCallbackManager::callOnSuccess(JSValueRef obj[], + int paramCount) +{ + if (m_onSuccess == NULL) { + //WrtLogD("Success callback is not set"); + return; + } + makeCallback(m_context, NULL, m_onSuccess, obj, paramCount); +} + +void JSCallbackManager::callOnError() +{ + if (m_onError == NULL) { + //WrtLogD("Error callback is not set"); + return; + } + makeCallback(m_context, NULL, m_onError, NULL, 0); +} + +void JSCallbackManager::callOnError(JSValueRef obj) +{ + if (m_onError == NULL) { + //WrtLogD("Error callback is not set"); + return; + } + JSValueRef objParam[1] = { obj }; + makeCallback(m_context, NULL, m_onError, objParam, 1); +} + +void JSCallbackManager::callOnError(JSValueRef obj[], + int paramCount) +{ + if (m_onError == NULL) { + //WrtLogD("Error callback is not set"); + return; + } + makeCallback(m_context, NULL, m_onError, obj, paramCount); +} + +void JSCallbackManager::makeCallback(JSContextRef context, + JSObjectRef object, + JSObjectRef callback, + JSValueRef argv[], + unsigned argc) +{ + if (callback == NULL) { + //WrtLogE("callback is NULL"); + return; + } + + if (JSObjectIsFunction(context, callback)) { + JSValueRef exception = NULL; + + if (argc == 0) { + JSObjectCallAsFunction(context, callback, object, 0, NULL, &exception); + } else { + JSObjectCallAsFunction(context, callback, object, argc, argv, &exception); + } + + if (exception) { + WKBundleReportException(context, exception); + } + } +} +} +} diff --git a/src/CommonsJavaScript/JSCallbackManager.h b/src/CommonsJavaScript/JSCallbackManager.h new file mode 100644 index 0000000..53e9058 --- /dev/null +++ b/src/CommonsJavaScript/JSCallbackManager.h @@ -0,0 +1,119 @@ +/* + * 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 JSCallbackManager.h + * @author Lukasz Marek (l.marel@samsung.com) + * @version 0.1 + */ + +#ifndef WRTDEVICEAPIS_COMMONSJAVASCRIPT_JS_CALLBACK_MANAGER_H_ +#define WRTDEVICEAPIS_COMMONSJAVASCRIPT_JS_CALLBACK_MANAGER_H_ + + +#include <memory> +#include <Commons/IEvent.h> +#include <JavaScriptCore/JavaScript.h> + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +class JSCallbackManager; +typedef std::shared_ptr<JSCallbackManager> JSCallbackManagerPtr; + +class JSCallbackManager : public WrtDeviceApis::Commons::IEventPrivateData +{ + private: + JSCallbackManager() + {} + + /** + * Used to create JSCallbackManagerPtr object by factory method + * createObject + */ + JSCallbackManager(JSContextRef context, + JSObjectRef onSuccess, + JSObjectRef onError); + + public: + + //JSCallbackManager( JSContextRef context, JSValueRef onSuccess, JSValueRef + // onError ); + + /** + * Create JSCallbackManagerPtr object witch checking callback parameters + * if callbacks are NULL it was programmer intention to not use callback and + * no exception will be rised + * if callbacks are some object but not a function it will rise exception + * @param[in] context - global context + * @param[in] onSuccess - success callback (may be NULL if not needed) + * @param[in] onError - error callback (may be NULL if not needed) + * @param[in] acceptJSNullAsOnSuccess - converts JSNull on onSuccess to NULL + * when true + * @param[in] acceptJSNullAsOnError - converts JSNull on onError to NULL + * when true + * @throw Commons::InvalidArgumentException - if callback is not null and is + * not a js function + */ + static JSCallbackManagerPtr createObject( + JSContextRef context, + JSValueRef onSuccess = NULL, + JSValueRef onError = NULL, + bool acceptJSNullAsOnSuccess = false, + bool acceptJSNullAsOnError = false); + + virtual ~JSCallbackManager(); + + void setContext(JSContextRef context); + + JSContextRef getContext() const + { + return m_context; + } + + void setOnSuccess(JSValueRef onSuccess); + JSValueRef getOnSuccess() const; + void setOnError(JSValueRef onError); + JSValueRef getOnError() const; + void setObject(JSObjectRef object); + JSObjectRef getObject() const; + + void callOnSuccess(); + void callOnSuccess(JSValueRef obj); + void callOnSuccess(JSValueRef obj[], int paramCount); + + void callOnError(); + void callOnError(JSValueRef obj); + void callOnError(JSValueRef obj[], int paramCount); + + private: + void makeCallback(JSContextRef context, + JSObjectRef object, + JSObjectRef callback, + JSValueRef argv[], + unsigned argc); + + JSObjectRef m_onSuccess; + JSObjectRef m_onError; + JSContextRef m_context; + JSObjectRef m_object; +}; + +bool isCallback(JSContextRef ctx, + JSValueRef value, + JSValueRef* exception); +} +} + +#endif // WRTDEVICEAPIS_COMMONSJAVASCRIPT_JS_CALLBACK_MANAGER_H_ diff --git a/src/CommonsJavaScript/JSDOMException.cpp b/src/CommonsJavaScript/JSDOMException.cpp new file mode 100644 index 0000000..df5a61c --- /dev/null +++ b/src/CommonsJavaScript/JSDOMException.cpp @@ -0,0 +1,238 @@ +/* + * 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 "JSDOMException.h" + +#include <dpl/log/wrt_log.h> + +#include "Converter.h" + +namespace { +const char* PLUGIN_NAME = "DOMException"; +const char* PROPERTY_CODE = "code"; +const char* PROPERTY_MESSAGE = "message"; + +struct Error +{ + const char* name; + const unsigned short value; +}; +// This array CAN'T be left empty! +const Error PROPERTY_ERROR[] = { + { "UNKNOWN_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::UNKNOWN_ERR }, + { "INDEX_SIZE_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::INDEX_SIZE_ERR }, + { "DOMSTRING_SIZE_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::DOMSTRING_SIZE_ERR }, + { "HIERARCHY_REQUEST_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException:: + HIERARCHY_REQUEST_ERR }, + { "WRONG_DOCUMENT_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::WRONG_DOCUMENT_ERR }, + { "INVALID_CHARACTER_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException:: + INVALID_CHARACTER_ERR }, + { "NO_DATA_ALLOWED_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException:: + NO_DATA_ALLOWED_ERR }, + { "NO_MODIFICATION_ALLOWED_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException:: + NO_MODIFICATION_ALLOWED_ERR }, + { "NOT_FOUND_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::NOT_FOUND_ERR }, + { "NOT_SUPPORTED_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::NOT_SUPPORTED_ERR }, + { "INUSE_ATTRIBUTE_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException:: + INUSE_ATTRIBUTE_ERR }, + { "INVALID_STATE_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::INVALID_STATE_ERR }, + { "SYNTAX_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::SYNTAX_ERR }, + { "INVALID_MODIFICATION_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException:: + INVALID_MODIFICATION_ERR }, + { "NAMESPACE_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::NAMESPACE_ERR }, + { "INVALID_ACCESS_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::INVALID_ACCESS_ERR }, + { "VALIDATION_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::VALIDATION_ERR }, + { "TYPE_MISMATCH_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::TYPE_MISMATCH_ERR }, + { "SECURITY_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::SECURITY_ERR }, + { "NETWORK_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::NETWORK_ERR }, + { "ABORT_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::ABORT_ERR }, + { "TIMEOUT_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::TIMEOUT_ERR }, + { "INVALID_VALUES_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::INVALID_VALUES_ERR }, + { "IO_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::IO_ERR }, + { "QUOTA_EXCEEDED_ERR", + WrtDeviceApis::CommonsJavaScript::JSDOMException::QUOTA_EXCEEDED_ERR } +}; +} // namespace + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +JSClassRef JSDOMException::m_classRef = NULL; + +JSClassDefinition JSDOMException::m_classInfo = { + 0, + kJSClassAttributeNone, + PLUGIN_NAME, + 0, + m_properties, + NULL, //__function, + initialize, + finalize, + hasProperty, + getProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + getPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + hasInstance, + NULL, //ConvertToType, +}; + +JSStaticValue JSDOMException::m_properties[] = { + { PROPERTY_CODE, getStaticProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_MESSAGE, getStaticProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +const JSClassDefinition* JSDOMException::getClassInfo() +{ + return &m_classInfo; +} + +JSClassRef JSDOMException::getClassRef() +{ + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +void JSDOMException::initialize(JSContextRef /*context*/, + JSObjectRef /*object*/) +{} + +void JSDOMException::finalize(JSObjectRef object) +{ + PrivateObject* privateObject = + static_cast<PrivateObject*>(JSObjectGetPrivate(object)); + if (privateObject) { + JSObjectSetPrivate(object, NULL); + delete privateObject; + } +} + +bool JSDOMException::hasProperty(JSContextRef /*context*/, + JSObjectRef /*object*/, + JSStringRef propertyName) +{ + const size_t size = sizeof(PROPERTY_ERROR) / sizeof(PROPERTY_ERROR[0]); + for (size_t i = 0; i < size; ++i) { + if (JSStringIsEqualToUTF8CString(propertyName, + PROPERTY_ERROR[i].name)) + { + return true; + } + } + return false; +} + +JSValueRef JSDOMException::getStaticProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* /*exception*/) +{ + PrivateObject* privateObject = + static_cast<PrivateObject*>(JSObjectGetPrivate(object)); + if (!privateObject) { + WrtLogE("Private object is not set."); + return JSValueMakeUndefined(context); + } + + Converter converter(context); + try { + if (JSStringIsEqualToUTF8CString(propertyName, PROPERTY_CODE)) { + return converter.toJSValueRef(privateObject->getObject()->getCode()); + } else if (JSStringIsEqualToUTF8CString(propertyName, + PROPERTY_MESSAGE)) + { + return converter.toJSValueRef( + privateObject->getObject()->getMessage()); + } + } catch (const Commons::ConversionException& ex) { + WrtLogE("Exception: %s", ex.GetMessage().c_str()); + } + + return JSValueMakeUndefined(context); +} + +JSValueRef JSDOMException::getProperty(JSContextRef context, + JSObjectRef /*object*/, + JSStringRef propertyName, + JSValueRef* /*exception*/) +{ + Converter converter(context); + try { + std::string prop = converter.toString(propertyName); + + const size_t size = sizeof(PROPERTY_ERROR) / sizeof(PROPERTY_ERROR[0]); + for (size_t i = 0; i < size; ++i) { + if (prop == PROPERTY_ERROR[i].name) { + return converter.toJSValueRef(PROPERTY_ERROR[i].value); + } + } + } catch (const Commons::ConversionException& ex) { + WrtLogE("Exception: %s", ex.GetMessage().c_str()); + } + + return JSValueMakeUndefined(context); +} + +void JSDOMException::getPropertyNames( + JSContextRef /*context*/, + JSObjectRef /*object*/, + JSPropertyNameAccumulatorRef accumulator) +{ + const size_t size = sizeof(PROPERTY_ERROR) / sizeof(PROPERTY_ERROR[0]); + for (size_t i = 0; i < size; ++i) { + JSPropertyNameAccumulatorAddName(accumulator, + JSStringCreateWithUTF8CString( + PROPERTY_ERROR[i].name)); + } +} + +bool JSDOMException::hasInstance(JSContextRef context, + JSObjectRef /*constructor*/, + JSValueRef possibleInstance, + JSValueRef* /*exception*/) +{ + return JSValueIsObjectOfClass(context, possibleInstance, getClassRef()); +} +} // CommonsJavaScript +} // WrtDeviceApis + diff --git a/src/CommonsJavaScript/JSDOMException.h b/src/CommonsJavaScript/JSDOMException.h new file mode 100644 index 0000000..dcea1e4 --- /dev/null +++ b/src/CommonsJavaScript/JSDOMException.h @@ -0,0 +1,131 @@ +/* + * 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_COMMONSJAVASCRIPT_JS_DOM_EXCEPTION_H_ +#define WRTDEVICEAPIS_COMMONSJAVASCRIPT_JS_DOM_EXCEPTION_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/PrivateObject.h> +#include <CommonsJavaScript/DOMExceptionData.h> + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +class JSDOMException +{ + public: + typedef PrivateObjectT<DOMExceptionDataPtr>::Type PrivateObject; + + public: + static const unsigned short UNKNOWN_ERR = 0; + static const unsigned short INDEX_SIZE_ERR = 1; + static const unsigned short DOMSTRING_SIZE_ERR = 2; + static const unsigned short HIERARCHY_REQUEST_ERR = 3; + static const unsigned short WRONG_DOCUMENT_ERR = 4; + static const unsigned short INVALID_CHARACTER_ERR = 5; + static const unsigned short NO_DATA_ALLOWED_ERR = 6; + static const unsigned short NO_MODIFICATION_ALLOWED_ERR = 7; + static const unsigned short NOT_FOUND_ERR = 8; + static const unsigned short NOT_SUPPORTED_ERR = 9; + static const unsigned short INUSE_ATTRIBUTE_ERR = 10; + static const unsigned short INVALID_STATE_ERR = 11; + static const unsigned short SYNTAX_ERR = 12; + static const unsigned short INVALID_MODIFICATION_ERR = 13; + static const unsigned short NAMESPACE_ERR = 14; + static const unsigned short INVALID_ACCESS_ERR = 15; + static const unsigned short VALIDATION_ERR = 16; + static const unsigned short TYPE_MISMATCH_ERR = 17; + static const unsigned short SECURITY_ERR = 18; + static const unsigned short NETWORK_ERR = 19; + static const unsigned short ABORT_ERR = 20; + static const unsigned short TIMEOUT_ERR = 21; + static const unsigned short INVALID_VALUES_ERR = 22; + static const unsigned short IO_ERR = 100; + + //TODO INVALID_VALUES_ERR has the same error code ?? + static const unsigned short QUOTA_EXCEEDED_ERR = 22; + + public: + static JSClassRef getClassRef(); + /** + * Gets object's class description. + */ + static const JSClassDefinition* getClassInfo(); + + private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, + JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * The callback invoked when getting a property's value. + */ + static bool hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName); + + /** + * The callback invoked when getting a property's value. + */ + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + /** + * The callback invoked when getting a property's value. + */ + static JSValueRef getStaticProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static void getPropertyNames(JSContextRef context, + JSObjectRef object, + JSPropertyNameAccumulatorRef accumulator); + + /** + * The callback invoked when an object is used as the target of an + * 'instanceof' expression. + */ + static bool hasInstance(JSContextRef context, + JSObjectRef constructor, + JSValueRef possibleInstance, + JSValueRef* exception); + + /** + * This structure contains properties and callbacks that define a type of + * object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared value property. + */ + static JSStaticValue m_properties[]; + + static JSClassRef m_classRef; +}; +} // CommonsJavaScript +} // WrtDeviceApis + +#endif // + diff --git a/src/CommonsJavaScript/JSDOMExceptionFactory.cpp b/src/CommonsJavaScript/JSDOMExceptionFactory.cpp new file mode 100644 index 0000000..b29727d --- /dev/null +++ b/src/CommonsJavaScript/JSDOMExceptionFactory.cpp @@ -0,0 +1,94 @@ +/* + * 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 "JSDOMExceptionFactory.h" + +#include <dpl/assert.h> + +#include "JSUtils.h" +#include "DOMExceptionData.h" +#include "JSDOMException.h" + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +#define DEFINE_JS_EXCEPTION_FACTORY(Class, Code) \ + JSDOMExceptionFactory JSDOMExceptionFactory::Class(Code) + +DEFINE_JS_EXCEPTION_FACTORY(UnknownException, JSDOMException::UNKNOWN_ERR); +DEFINE_JS_EXCEPTION_FACTORY(IndexSizeException, JSDOMException::INDEX_SIZE_ERR); +DEFINE_JS_EXCEPTION_FACTORY(DomstringSizeException, + JSDOMException::DOMSTRING_SIZE_ERR); +DEFINE_JS_EXCEPTION_FACTORY(HierarchyRequestException, + JSDOMException::HIERARCHY_REQUEST_ERR); +DEFINE_JS_EXCEPTION_FACTORY(WrongDocumentException, + JSDOMException::WRONG_DOCUMENT_ERR); +DEFINE_JS_EXCEPTION_FACTORY(InvalidCharacterException, + JSDOMException::INVALID_CHARACTER_ERR); +DEFINE_JS_EXCEPTION_FACTORY(NoDataAllowedException, + JSDOMException::NO_DATA_ALLOWED_ERR); +DEFINE_JS_EXCEPTION_FACTORY(NoModificationAllowedException, + JSDOMException::NO_MODIFICATION_ALLOWED_ERR); +DEFINE_JS_EXCEPTION_FACTORY(NotFoundException, JSDOMException::NOT_FOUND_ERR); +DEFINE_JS_EXCEPTION_FACTORY(NotSupportedException, + JSDOMException::NOT_SUPPORTED_ERR); +DEFINE_JS_EXCEPTION_FACTORY(InuseAttributeException, + JSDOMException::INUSE_ATTRIBUTE_ERR); +DEFINE_JS_EXCEPTION_FACTORY(InvalidStateException, + JSDOMException::INVALID_STATE_ERR); +DEFINE_JS_EXCEPTION_FACTORY(SyntaxException, JSDOMException::SYNTAX_ERR); +DEFINE_JS_EXCEPTION_FACTORY(InvalidModificationException, + JSDOMException::INVALID_MODIFICATION_ERR); +DEFINE_JS_EXCEPTION_FACTORY(NamespaceException, JSDOMException::NAMESPACE_ERR); +DEFINE_JS_EXCEPTION_FACTORY(InvalidAccessException, + JSDOMException::INVALID_ACCESS_ERR); +DEFINE_JS_EXCEPTION_FACTORY(ValidationException, JSDOMException::VALIDATION_ERR); +DEFINE_JS_EXCEPTION_FACTORY(TypeMismatchException, + JSDOMException::TYPE_MISMATCH_ERR); +DEFINE_JS_EXCEPTION_FACTORY(SecurityException, JSDOMException::SECURITY_ERR); +DEFINE_JS_EXCEPTION_FACTORY(NetworkException, JSDOMException::NETWORK_ERR); +DEFINE_JS_EXCEPTION_FACTORY(AbortException, JSDOMException::ABORT_ERR); +DEFINE_JS_EXCEPTION_FACTORY(TimeoutException, JSDOMException::TIMEOUT_ERR); +DEFINE_JS_EXCEPTION_FACTORY(InvalidValuesException, + JSDOMException::INVALID_VALUES_ERR); +DEFINE_JS_EXCEPTION_FACTORY(IOException, JSDOMException::IO_ERR); +DEFINE_JS_EXCEPTION_FACTORY(QuotaExceededException, + JSDOMException::QUOTA_EXCEEDED_ERR); + +JSDOMExceptionFactory::JSDOMExceptionFactory(int code) : m_code(code) +{} + +JSValueRef JSDOMExceptionFactory::make(JSContextRef context, + JSValueRef* exception, + const std::string& message) +{ + AssertMsg(exception, "Exception object can't be NULL."); + JSDOMException::PrivateObject::ObjectType data(new DOMExceptionData(m_code, + message)); + *exception = JSUtils::makeObject(context, + JSDOMException::getClassRef(), + data); + return JSValueMakeUndefined(context); +} + +JSObjectRef JSDOMExceptionFactory::make(JSContextRef context, + const std::string& message) +{ + JSDOMException::PrivateObject::ObjectType data(new DOMExceptionData(m_code, + message)); + return JSUtils::makeObject(context, + JSDOMException::getClassRef(), data); +} +} // CommonsJavaScript +} // WrtDeviceApis diff --git a/src/CommonsJavaScript/JSDOMExceptionFactory.h b/src/CommonsJavaScript/JSDOMExceptionFactory.h new file mode 100644 index 0000000..2bf8329 --- /dev/null +++ b/src/CommonsJavaScript/JSDOMExceptionFactory.h @@ -0,0 +1,99 @@ +/* + * 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 WRT_DOM_EXCEPTION_FACTORY_H_ +#define WRT_DOM_EXCEPTION_FACTORY_H_ + +#include <string> +#include <dpl/noncopyable.h> +#include <JavaScriptCore/JavaScript.h> + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +#define DECLARE_JS_EXCEPTION_FACTORY(Class) static JSDOMExceptionFactory Class + +class JSDOMExceptionFactory : public DPL::Noncopyable +{ + public: + DECLARE_JS_EXCEPTION_FACTORY(UnknownException); + DECLARE_JS_EXCEPTION_FACTORY(IndexSizeException); + DECLARE_JS_EXCEPTION_FACTORY(DomstringSizeException); + DECLARE_JS_EXCEPTION_FACTORY(HierarchyRequestException); + DECLARE_JS_EXCEPTION_FACTORY(WrongDocumentException); + DECLARE_JS_EXCEPTION_FACTORY(InvalidCharacterException); + DECLARE_JS_EXCEPTION_FACTORY(NoDataAllowedException); + DECLARE_JS_EXCEPTION_FACTORY(NoModificationAllowedException); + DECLARE_JS_EXCEPTION_FACTORY(NotFoundException); + DECLARE_JS_EXCEPTION_FACTORY(NotSupportedException); + DECLARE_JS_EXCEPTION_FACTORY(InuseAttributeException); + DECLARE_JS_EXCEPTION_FACTORY(InvalidStateException); + DECLARE_JS_EXCEPTION_FACTORY(SyntaxException); + DECLARE_JS_EXCEPTION_FACTORY(InvalidModificationException); + DECLARE_JS_EXCEPTION_FACTORY(NamespaceException); + DECLARE_JS_EXCEPTION_FACTORY(InvalidAccessException); + DECLARE_JS_EXCEPTION_FACTORY(ValidationException); + DECLARE_JS_EXCEPTION_FACTORY(TypeMismatchException); + DECLARE_JS_EXCEPTION_FACTORY(SecurityException); + DECLARE_JS_EXCEPTION_FACTORY(NetworkException); + DECLARE_JS_EXCEPTION_FACTORY(AbortException); + DECLARE_JS_EXCEPTION_FACTORY(TimeoutException); + DECLARE_JS_EXCEPTION_FACTORY(InvalidValuesException); + DECLARE_JS_EXCEPTION_FACTORY(IOException); + DECLARE_JS_EXCEPTION_FACTORY(QuotaExceededException); + + public: + explicit JSDOMExceptionFactory(int code); + + /** + * Creates exception object. + * @param context JS context of the exception. + * @param[out] exception Result object to which exception will be assigned. + * @return JS undefined value. + * @code + * JSValueRef JSClass::getProperty(JSContextRef context, + * JSObjectRef object, + * JSStringRef propertyName, + * JSValueRef* exception) + * { + * ... + * return JSExceptionFactory::InvalidArgumentException.make(context, + * exception); + * ... + * } + * @endcode + */ + JSValueRef make(JSContextRef context, + JSValueRef* exception, + const std::string& message = std::string()); + + /** + * Creates exception object. + * @param context JS context of the exception. + * @return JS exception object. + * @code + * JSObjectRef jsError = + * JSExceptionFactory::InvalidArgumentException.make(context); + * @endcode + */ + JSObjectRef make(JSContextRef context, + const std::string& message = std::string()); + + private: + int m_code; +}; +} // CommonsJavaScript +} // WrtDeviceApis + +#endif // diff --git a/src/CommonsJavaScript/JSPendingOperation.cpp b/src/CommonsJavaScript/JSPendingOperation.cpp new file mode 100644 index 0000000..5d69f1c --- /dev/null +++ b/src/CommonsJavaScript/JSPendingOperation.cpp @@ -0,0 +1,103 @@ +/* + * 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 JSPendingOperation.cpp + * @author Pete Cole (peter.cole@partner.samsung.com) + * @version 0.1 + * 0.2 k.majewski@samsung.com + * @brief Implementation of the JSPendingOperation class + */ + +#include <Commons/IEvent.h> +#include "JSPendingOperation.h" +#include "JSPendingOperationPrivateObject.h" + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +namespace { +const char* PLUGIN_NAME = "PendingOperation"; +} + +JSClassRef JSPendingOperation::m_classRef = NULL; + +JSClassDefinition JSPendingOperation::m_classInfo = { + 0, + kJSClassAttributeNone, + PLUGIN_NAME, + 0, + NULL, + m_functions, + initialize, + finalize, + NULL, //hasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //getPropertyNames, + NULL, + NULL, + NULL, + NULL, //ConvertToType, +}; + +JSStaticFunction JSPendingOperation::m_functions[] = { + { "cancel", cancel, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +JSClassRef JSPendingOperation::getClassRef() +{ + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +void JSPendingOperation::initialize(JSContextRef /*context*/, + JSObjectRef object) +{ + assert(NULL != JSObjectGetPrivate(object)); +} + +void JSPendingOperation::finalize(JSObjectRef object) +{ + delete static_cast<IJSPendingOperationPrivateObject *>( + JSObjectGetPrivate(object)); +} + +JSValueRef JSPendingOperation::cancel(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + (void) object; + (void) argumentCount; + (void) arguments; + (void) exception; + WrtLogD("%s", __FUNCTION__); + IJSPendingOperationPrivateObject *priv = + static_cast<IJSPendingOperationPrivateObject *>( + JSObjectGetPrivate(thisObject)); + assert(NULL != priv); + bool cancelResult = priv->cancel(); + WrtLogD("cancel result : %d", cancelResult); + return JSValueMakeBoolean(context, cancelResult); +} +} // CommonsJavaScript +} // WrtDeviceApis + diff --git a/src/CommonsJavaScript/JSPendingOperationPrivateObject.h b/src/CommonsJavaScript/JSPendingOperationPrivateObject.h new file mode 100644 index 0000000..2eddc2d --- /dev/null +++ b/src/CommonsJavaScript/JSPendingOperationPrivateObject.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. + */ +/* + * @author Karol Majewski (k.majewski@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRTDEVICEAPIS_COMMONSJAVASCRIPT_JS_PENDING_OPERATION_PRIVATE_OBJECT_H_ +#define WRTDEVICEAPIS_COMMONSJAVASCRIPT_JS_PENDING_OPERATION_PRIVATE_OBJECT_H_ + +#include <cassert> +#include <dpl/log/wrt_log.h> +#include <memory> +#include <Commons/EventReceiver.h> +#include <Commons/IExternEventCanceler.h> +#include <Commons/IEvent.h> + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +class IJSPendingOperationPrivateObject +{ + public: + explicit IJSPendingOperationPrivateObject( + const std::shared_ptr<Commons::IEventController> + &event) : + m_event(event) + { + assert(NULL != m_event.get()); + } + + virtual bool cancel() + { + WrtLogD("PendingOperation tries to cancel the request"); + return m_event->cancelRequest(); + } + + virtual ~IJSPendingOperationPrivateObject() + {} + + protected: + std::shared_ptr<Commons::IEventController> m_event; +}; + +/* + * This class implements private object for JavaScript PendingOperation + * with support to external cancel function. + * + * When the cancel() method is invoked on PendingOperation, + * the OnCancelEvent(<EventType>) method is invoked on user object + * with apropriate * arguments. + * It allows user to perform an additional action when PendingOperation + * is destroyed. + * + * The Object which want to handle OnCancelEvent have to inherit from + * Platform::IExternEventCanceler<EventType>. + * + * The cancel's handler have to be passed as second argument + * */ +template<class TemplateEvent> +class IJSExtCancelPendingOperationPrivateObject : + public IJSPendingOperationPrivateObject +{ + public: + IJSExtCancelPendingOperationPrivateObject( + const std::shared_ptr< TemplateEvent> &event, + const std::shared_ptr< + Commons::IExternEventCanceler<TemplateEvent> > & cancel) : + IJSPendingOperationPrivateObject( + std::static_pointer_cast<Commons::IEventController>(event)), + m_canceler(cancel) + { + assert(NULL != m_canceler); + } + + virtual bool cancel() + { + bool result = IJSPendingOperationPrivateObject::cancel(); + if (!result) { + WrtLogD("Controller can not cancel event, trying platform cancel"); + } else { + return result; + } + + if (m_canceler) { + WrtLogD("Calling extern cancel"); + m_canceler->OnCancelEvent( + std::static_pointer_cast<TemplateEvent>(m_event)); + } + + return result; + } + + virtual ~IJSExtCancelPendingOperationPrivateObject() + {} + + protected: + std::shared_ptr< Commons::IExternEventCanceler<TemplateEvent> > m_canceler; +}; +} +} +#endif /* _JS_WAC_PENDING_OPERATION_PRIVATE_OBJECT_H_ */ diff --git a/src/CommonsJavaScript/JSUtils.cpp b/src/CommonsJavaScript/JSUtils.cpp new file mode 100644 index 0000000..f4c9c95 --- /dev/null +++ b/src/CommonsJavaScript/JSUtils.cpp @@ -0,0 +1,88 @@ +/* + * 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 "Converter.h" +#include "ScopedJSStringRef.h" +#include "JSUtils.h" + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +using namespace WrtDeviceApis::Commons; + +bool JSUtils::hasProperty(JSStaticValue* properties, + JSStringRef name) +{ + JSStaticValue* property = properties; + while (property->name) { + if (JSStringIsEqualToUTF8CString(name, property->name)) { + return true; + } + ++property; + } + return false; +} + +JSValueRef JSUtils::getJSProperty(JSContextRef context, + JSValueRef jsValue, + const std::string &name, + JSValueRef *exception) +{ + ScopedJSStringRef jsPropName(JSStringCreateWithUTF8CString(name.c_str())); + Converter converter(context); + JSObjectRef jsObject = converter.toJSObjectRef(jsValue); + if (JSObjectHasProperty(context, jsObject, jsPropName.get())) { + return JSObjectGetProperty(context, jsObject, + jsPropName.get(), exception); + } + return NULL; +} + +JSValueRef JSUtils::getJSProperty(JSContextRef context, + JSObjectRef object, + const std::string& name) +{ + Converter converter(context); + Try { + ScopedJSStringRef propName(converter.toJSStringRef(name)); + if (JSObjectHasProperty(context, object, propName.get())) { + JSValueRef result = JSObjectGetProperty(context, + object, + propName.get(), + NULL); + if (!JSValueIsUndefined(context, result)) { + return result; + } + } + } + Catch(ConversionException) {} + return NULL; +} + +JSValueRef JSUtils::getJSPropertyOrUndefined(JSContextRef context, + JSObjectRef object, + const std::string& name) +{ + Converter converter(context); + Try { + ScopedJSStringRef propName(converter.toJSStringRef(name)); + if (JSObjectHasProperty(context, object, propName.get())) { + return JSObjectGetProperty(context, object, propName.get(), NULL); + } + } + Catch(ConversionException) {} + return JSValueMakeUndefined(context); +} +} // CommonsJavaScript +} // WrtDeviceApis diff --git a/src/CommonsJavaScript/JSUtils.h b/src/CommonsJavaScript/JSUtils.h new file mode 100644 index 0000000..885bcd0 --- /dev/null +++ b/src/CommonsJavaScript/JSUtils.h @@ -0,0 +1,84 @@ +/* + * 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_COMMONSJAVASCRIPT_JS_JSUTILS_H_ +#define WRTDEVICEAPIS_COMMONSJAVASCRIPT_JS_JSUTILS_H_ + +#include <string> +#include <JavaScriptCore/JavaScript.h> +#include <Commons/Exception.h> +#include <CommonsJavaScript/PrivateObject.h> + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +class JSUtils +{ + public: + static bool hasProperty(JSStaticValue* properties, + JSStringRef name); + + /** + * Gets a property from JSObject if exists + * @return JSValueRef if property exists, NULL if not + */ + static JSValueRef getJSProperty(JSContextRef context, + JSValueRef jsValue, + const std::string &name, + JSValueRef* exception = NULL); + + static JSValueRef getJSProperty(JSContextRef context, + JSObjectRef object, + const std::string& name); + + static JSValueRef getJSPropertyOrUndefined(JSContextRef context, + JSObjectRef object, + const std::string& name); + + template<class C> + static JSObjectRef makeObject(JSContextRef context, + JSClassRef classRef, + C data) + { + typedef typename PrivateObjectT<C>::Type Private; + + Private* priv = new Private(context, data); + JSObjectRef object = JSObjectMake(context, classRef, priv); + if (!object) { + ThrowMsg(Commons::NullPointerException, + "Could not create JS object."); + } + + return object; + } + + static JSObjectRef makeObject(JSContextRef context, + JSClassRef classRef) + { + typedef PrivateObjectT<void>::Type Private; + + Private* priv = new Private(context); + JSObjectRef object = JSObjectMake(context, classRef, priv); + if (!object) { + ThrowMsg(Commons::NullPointerException, + "Could not create JS object."); + } + + return object; + } +}; // JSUtils +} // CommonsJavaScript +} // WrtDeviceApis + +#endif /* WRTPLUGINS_COMMONS_JSUTILS_H_ */ diff --git a/src/CommonsJavaScript/PrivateObject.h b/src/CommonsJavaScript/PrivateObject.h new file mode 100644 index 0000000..8bd816a --- /dev/null +++ b/src/CommonsJavaScript/PrivateObject.h @@ -0,0 +1,238 @@ +/* + * 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_COMMONSJAVASCRIPT_PRIVATEOBJECT_H_ +#define WRTDEVICEAPIS_COMMONSJAVASCRIPT_PRIVATEOBJECT_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <dpl/noncopyable.h> +#include <dpl/assert.h> +#include <Commons/Exception.h> +#include <Commons/TypeTraits.h> + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +template<class T> +struct NoAcquire +{ + void acquire(T*) + {} + + protected: + ~NoAcquire() + {} +}; + +template<class T> +struct AcquireByProtect +{ + void acquire(T* object) + { + Assert(object && "Object passed to protect can't be NULL."); + JSValueProtect(object->getContext(), object->getObject()); + } + + protected: + ~AcquireByProtect() + {} +}; + +template<class T> +struct NoRelease +{ + void release(T* object) + { + (void)object; + } + + protected: + ~NoRelease() + {} +}; + +template<class T> +struct ReleaseByDelete +{ + void release(T* object) + { + delete object->getObject(); + } + + protected: + ~ReleaseByDelete() + {} +}; + +template<class T> +struct ReleaseByUnprotect +{ + void release(T* object) + { + Assert(object && "Object passed to unprotect can't be NULL."); + JSValueUnprotect(object->getContext(), object->getObject()); + } + + protected: + ~ReleaseByUnprotect() + {} +}; + +template<class T> +struct NoOwnership : protected NoAcquire<T>, + protected NoRelease<T> +{ + protected: + ~NoOwnership() + {} +}; + +template<class T> +struct OwnershipByAcquisition : protected NoAcquire<T>, + protected ReleaseByDelete<T> +{ + protected: + ~OwnershipByAcquisition() + {} +}; + +template<class T> +struct OwnershipByProtection : protected AcquireByProtect<T>, + protected ReleaseByUnprotect<T> +{ + protected: + ~OwnershipByProtection() + {} +}; + +template<class PrivateClass, + template <class> class OwnershipPolicy = OwnershipByAcquisition> +class PrivateObject : public DPL::Noncopyable, + protected OwnershipPolicy<PrivateObject<PrivateClass, OwnershipPolicy> > +{ + public: + typedef PrivateClass ObjectType; + + public: + /** + * Creates storage object for JS private data. + * @param context JS (root/global) context. + * @param object Object to store. + * @throw NullPointerException When object is pointer and is set to NULL. + */ + PrivateObject(JSContextRef context, + const PrivateClass& object) : + m_context(context), + m_object(object) + { + Assert(NULL != m_context && "Context is NULL."); + Assert(!Commons::IsNull<PrivateClass>::value( + object) && "Object is NULL."); + this->acquire(this); + } + + /** + * Destroys instance of the object. + */ + virtual ~PrivateObject() + { + this->release(this); + } + + /** + * Gets stored JS context. + * @return JavaScript context. + */ + virtual JSContextRef getContext() const + { + return m_context; + } + + /** + * Gets stored object. + * @return Stored object. + */ + virtual PrivateClass getObject() const + { + return m_object; + } + + protected: + JSContextRef m_context; ///< JS context. + PrivateClass m_object; ///< Stored object. +}; + +/** + * Specialization for type void. + */ +template<> +class PrivateObject<void, NoOwnership> : private DPL::Noncopyable +{ + public: + /** + * Creates storage object for JS private data. + * @param context JS (root/global) context. + * @remarks Takes ownership over stored object. + */ + explicit PrivateObject(JSContextRef context) : m_context(context) + { + Assert(NULL != m_context && "Context is NULL."); + } + + /** + * Destroys instance of the object. + */ + virtual ~PrivateObject() + {} + + /** + * Gets stored JS context. + * @return JavaScript context. + */ + virtual JSContextRef getContext() const + { + return m_context; + } + + protected: + JSContextRef m_context; +}; + +template<class C> +struct PrivateObjectT +{ + typedef PrivateObject<C, NoOwnership> Type; +}; + +template<class C> +struct PrivateObjectT<C*> +{ + typedef PrivateObject<C*, OwnershipByAcquisition> Type; +}; + +template<> +struct PrivateObjectT<JSObjectRef> +{ + typedef PrivateObject<JSObjectRef, NoOwnership> Type; +}; + +template<> +struct PrivateObjectT<void> +{ + typedef PrivateObject<void, NoOwnership> Type; +}; +} // CommonsJavaScript +} // WrtDeviceApis + +#endif /* PRIVATEOBJECT_H_ */ diff --git a/src/CommonsJavaScript/ScopedJSStringRef.cpp b/src/CommonsJavaScript/ScopedJSStringRef.cpp new file mode 100644 index 0000000..2f0c17f --- /dev/null +++ b/src/CommonsJavaScript/ScopedJSStringRef.cpp @@ -0,0 +1,35 @@ +/* + * 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 "ScopedJSStringRef.h" + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +ScopedJSStringRef::ScopedJSStringRef(JSStringRef ref) : m_ref(ref) +{} + +ScopedJSStringRef::~ScopedJSStringRef() +{ + if (m_ref != NULL) { + JSStringRelease(m_ref); + } +} + +JSStringRef ScopedJSStringRef::get() const +{ + return m_ref; +} +} // CommonsJavaScript +} // WrtDeviceApis diff --git a/src/CommonsJavaScript/ScopedJSStringRef.h b/src/CommonsJavaScript/ScopedJSStringRef.h new file mode 100644 index 0000000..d18238a --- /dev/null +++ b/src/CommonsJavaScript/ScopedJSStringRef.h @@ -0,0 +1,57 @@ +/* + * 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_COMMONSJAVASCRIPT_SCOPEDJSSTRINGREF_H_ +#define WRTDEVICEAPIS_COMMONSJAVASCRIPT_SCOPEDJSSTRINGREF_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <dpl/noncopyable.h> + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +/** + * Takes ownership over JSStringRef object to call JSSTringRelease on it + * when this object goes out of scope. + */ +class ScopedJSStringRef : private DPL::Noncopyable +{ + public: + /** + * Creates this class instance. + * @param ref JSStringRef to take ownership. + * @remarks Takes ownership. + */ + ScopedJSStringRef(JSStringRef ref); + + /** + * Destroys instance. + * @remarks Releases stored JSStringRef. + */ + ~ScopedJSStringRef(); + + /** + * Gets stored JSStringRef. + * @return JSStringRef object. + * @remarks Doesn't pass ownership to caller. + */ + JSStringRef get() const; + + private: + JSStringRef m_ref; +}; +} // CommonsJavaScript +} // WrtDeviceApis + +#endif /* WRTDEVICEAPIS_COMMONSJAVASCRIPT_SCOPEDJSSTRINGREF_H_ */ diff --git a/src/CommonsJavaScript/Security/SecurityFunctionDeclaration.cpp b/src/CommonsJavaScript/Security/SecurityFunctionDeclaration.cpp new file mode 100644 index 0000000..87111fd --- /dev/null +++ b/src/CommonsJavaScript/Security/SecurityFunctionDeclaration.cpp @@ -0,0 +1,27 @@ +/* + * 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 "SecurityFunctionDeclaration.h" +#include <JavaScriptCore/JavaScript.h> + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +AceSecurityStatus aceCheckAccessSimple( + WrtDeviceApis::Commons::AceFunction aceFunction) +{ + return aceCheckAccess2<DefaultArgsVerifier<> >(aceFunction); +} +} +} diff --git a/src/CommonsJavaScript/Security/SecurityFunctionDeclaration.h b/src/CommonsJavaScript/Security/SecurityFunctionDeclaration.h new file mode 100644 index 0000000..d1e56ba --- /dev/null +++ b/src/CommonsJavaScript/Security/SecurityFunctionDeclaration.h @@ -0,0 +1,96 @@ +/* + * 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 _FUNCTION_DECLARATION_ +#define _FUNCTION_DECLARATION_ + +#include <string> +#include <Commons/WrtAccess/WrtAccess.h> +#include <Commons/Exception.h> +#include <JavaScriptCore/JavaScript.h> +#include <Commons/TypesDeclaration.h> +#include <Commons/TypeTraits.h> +#include <dpl/log/wrt_log.h> + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +enum class AceSecurityStatus +{ + AccessGranted, + AccessDenied, + PrivacyDenied, + InternalError +}; + +template <typename ... Args> +class DefaultArgsVerifier +{ + public: + void operator()(WrtDeviceApis::Commons::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()(WrtDeviceApis::Commons::AceFunction& /*aceFunction*/) const + {} +}; + +template <typename ArgumentsVerifier, + typename ... Args> +AceSecurityStatus aceCheckAccess2( + WrtDeviceApis::Commons::AceFunction aceFunction, + Args && ... args) +{ + using namespace WrtDeviceApis::Commons; + + ArgumentsVerifier argsVerify; + argsVerify(aceFunction, args ...); + + WrtAccess::CheckAccessReturnType ret = + WrtAccessSingleton::Instance().checkAccessControl(aceFunction); + + if (ret == WrtAccess::CHECK_ACCESS_PRIVILEGE_DENIED) { + WrtLogE("Function is not allowed to run - AccessDenied"); + return AceSecurityStatus::AccessDenied; + } + else if (ret == WrtAccess::CHECK_ACCESS_PRIVACY_DENIED) { + WrtLogE("Function is not allowed to run - PrivacyDenied"); + return AceSecurityStatus::PrivacyDenied; + } + else if (ret == WrtAccess::CHECK_ACCESS_INTERNAL_ERROR) { + WrtLogE("InternalError"); + return AceSecurityStatus::InternalError; + } + + WrtLogD("Function accepted!"); + + return AceSecurityStatus::AccessGranted; +} + +//The simplest version +AceSecurityStatus aceCheckAccessSimple( + WrtDeviceApis::Commons::AceFunction aceFunction); +} +} + +#endif // _FUNCTION_DECLARARION_ diff --git a/src/CommonsJavaScript/Security/StaticDeclaration.h b/src/CommonsJavaScript/Security/StaticDeclaration.h new file mode 100644 index 0000000..c089d50 --- /dev/null +++ b/src/CommonsJavaScript/Security/StaticDeclaration.h @@ -0,0 +1,315 @@ +/* + * 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 _WRTPLUGINS_COMMONS_SRC_COMMONS_STATICDECLARATIOS_H_ +#define _WRTPLUGINS_COMMONS_SRC_COMMONS_STATICDECLARATIOS_H_ + +#include <map> +#include <vector> +#include <string> +#include <string.h> +#include <dpl/noncopyable.h> +#include <dpl/assert.h> +#include <dpl/foreach.h> +#include <Commons/TypesDeclaration.h> +#include <wrt-commons/wrt_plugin_export.h> + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +template<typename ParamType, + typename DeviceCapType, + typename FunctionType> +class StaticDeclarations : public DPL::Noncopyable +{ + struct FunctionTriplet { + const char* name; + std::vector<DeviceCapType> devCaps; + std::vector<const char*> features; + }; + + public: + + typedef typename std::map<ParamType, const char*> ParamsMap; + + typedef std::map<DeviceCapType, + std::pair<const char*, + std::vector<ParamType> > > DeviceCapsMaps; + + typedef std::map<FunctionType, FunctionTriplet > FunctionsMap; + + typedef std::map<FunctionType, WrtDeviceApis::Commons::AceFunction> + AceFunctionsMap; + + typedef std::map<std::string, std::vector<DeviceCapType> > FeaturesMap; + + static const std::string getParamName(const ParamType& paramId) + { + auto it = m_params.find(paramId); + + Assert(it != m_params.end() && "No such paramId"); + + return it->second; + } + + /** + * Returns set of device capabilities WITHOUT params + * for given device capability id + * */ + static WrtDeviceApis::Commons::AceDeviceCapability + getDeviceCapabilityWithoutParams(const DeviceCapType& devCapsId) + { + WrtDeviceApis::Commons::AceDeviceCapability deviceCap; + auto it = m_deviceCaps.find(devCapsId); + + Assert(it != m_deviceCaps.end() && "No such device cap"); + + deviceCap.devCapName = it->second.first; + + return deviceCap; + } + + /** + * Returns set of device capabilities with set params + * for given device capability id + * */ + static WrtDeviceApis::Commons::AceDeviceCapability + getDeviceCapability(const DeviceCapType& devCapsId) + { + auto it = m_deviceCaps.find(devCapsId); + + Assert(it != m_deviceCaps.end() && "No such dev-cap found"); + + WrtDeviceApis::Commons::AceDeviceCapability deviceCap; + deviceCap.devCapName = it->second.first; + + FOREACH(paramIt, it->second.second) + { + WrtDeviceApis::Commons::AceDeviceCapParam param( + getParamName(*paramIt), + std::string()); + + deviceCap.devCapParams.push_back(param); + } + + return deviceCap; + } + + static void addDeviceCapabilty( + const DeviceCapType& devCapsId, + WrtDeviceApis::Commons::AceFunction& aceFunction) + { + aceFunction.deviceCapabilities.push_back( + getDeviceCapability(devCapsId)); + } + + /** + * Returns names of device-capabilities base on capability id + */ + static std::string getDevCapNameById(DeviceCapType devCapId) + { + auto it = m_deviceCaps.find(devCapId); + Assert(it != m_deviceCaps.end() && "No such devcapid found!"); + return it->second.first; + } + + /** + * Sets parameter value for given paramId + */ + static bool setParamValue(WrtDeviceApis::Commons::AceFunction& function, + ParamType paramId, + DeviceCapType devCapId, + const std::string& value) + { + //get name of the deviceCaps + std::string devCapName = getDevCapNameById(devCapId); + std::string paramName = getParamName(paramId); + + //search throw all the device capabilities + FOREACH(devCapIt, function.deviceCapabilities) { + if (devCapIt->devCapName == devCapName) { + //device capability has been found + //check params + FOREACH(devParamIt, devCapIt->devCapParams) { + if (devParamIt->name == paramName) { + devParamIt->value = value; + return true; + } + } + } + } + return false; + } + /** + * Return struct Commons::AceFunction with set function name + * + * To set device capabilities you may use setDeviceCap function + * To set param value function you may use setParamValue Function + * */ + static WrtDeviceApis::Commons::AceFunction getEmptyFunction( + const FunctionType& functionId) + { + WrtDeviceApis::Commons::AceFunction function; + auto it = m_functions.find(functionId); + Assert(it != m_functions.end() && "No such a function"); + function.name = it->second.first; + + return function; + } + + /** + * The most useful Function + * Return Commons::AceFunction with filled all required fields: + * name, device caps and proper param namespace + * + * To set param value function you may use setParamValue function + * */ + static WrtDeviceApis::Commons::AceFunction getSecurityFunction( + const FunctionType& functionId) + { + WrtDeviceApis::Commons::AceFunction function; + auto it = m_functions.find(functionId); + Assert(it != m_functions.end() && "No such function found!"); + + function.name = it->second.name; + + FOREACH(featIt, it->second.features) + function.features.push_back(std::string(*featIt)); + + FOREACH(devCapIt, it->second.devCaps) { + function.deviceCapabilities.push_back( + getDeviceCapability(*devCapIt)); + } + return function; + } + + /** + * To create static map + * */ + static void createStaticAceFunctions() + { + FOREACH(functionIt, m_functions) + { + m_aceFunctions[functionIt->first] = + getSecurityFunction(functionIt->first); + } + } + + static feature_mapping_t* getFeaturesToDevCapMapping() + { + feature_mapping_t* mapping = new feature_mapping_t; + + mapping->featuresCount = m_features.size(); + mapping->features = new feature_devcaps_t[mapping->featuresCount]; + + size_t i = 0; + + FOREACH(featureIt, m_features) + { + mapping->features[i].feature_name = + strndup(featureIt->first.c_str(), featureIt->first.size() + 1); + + mapping->features[i].devCaps.devCapsCount = + featureIt->second.size(); + + mapping->features[i].devCaps.deviceCaps = + new char*[mapping->features[i].devCaps.devCapsCount]; + + for (size_t j = 0; + j < mapping->features[i].devCaps.devCapsCount; + ++j) + { + std::string dc = getDevCapNameById(featureIt->second[j]); + + mapping->features[i].devCaps.deviceCaps[j] = + strndup(dc.c_str(), dc.size() + 1); + } + + ++i; + } + + return mapping; + } + + static const devcaps_t* devcapsGetter(pfeature_mapping_t feats, + const char* featureName) + { + Assert(featureName && "Trying to extract info about NULL api feature"); + + std::string feature(featureName); + + devcaps_t* ret = NULL; + + for (size_t i = 0; i < feats->featuresCount; ++i) { + Assert(feats->features && + feats->features[i].feature_name && + "NULL api feature in feature mapping"); + + std::string feat(feats->features[i].feature_name); + + if (feature == feat) { + ret = &(feats->features[i].devCaps); + break; + } + } + + return ret; + } + + static void featuresDeinitializer(feature_mapping_t* mapping) + { + if (mapping) { + if (mapping->features) { + for (size_t i = 0; i < mapping->featuresCount; ++i) { + free(mapping->features[i].feature_name); + + devcaps_t& dc = mapping->features[i].devCaps; + + if (dc.deviceCaps) { + for (size_t j = 0; j < dc.devCapsCount; ++j) { + free(dc.deviceCaps[j]); + } + + delete[] dc.deviceCaps; + } + } + delete[] mapping->features; + } + delete mapping; + } + } + + static void getMappingInterface(feature_mapping_interface_t *mapping) + { + if (mapping) { + mapping->featGetter = + StaticDeclarations::getFeaturesToDevCapMapping; + mapping->dcGetter = StaticDeclarations::devcapsGetter; + mapping->release = StaticDeclarations::featuresDeinitializer; + } + } + + private: + static ParamsMap m_params; + static DeviceCapsMaps m_deviceCaps; + static FunctionsMap m_functions; + static AceFunctionsMap m_aceFunctions; + + static FeaturesMap m_features; +}; +} +} + +#endif diff --git a/src/CommonsJavaScript/SecurityExceptions.h b/src/CommonsJavaScript/SecurityExceptions.h new file mode 100644 index 0000000..ffc111b --- /dev/null +++ b/src/CommonsJavaScript/SecurityExceptions.h @@ -0,0 +1,73 @@ +/* + * 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_COMMONSJAVASCRIPT_JS_SECURITYEXCEPTIONS_H_ +#define WRTDEVICEAPIS_COMMONSJAVASCRIPT_JS_SECURITYEXCEPTIONS_H_ + +#include <JavaScriptCore/JavaScript.h> +#include "JSDOMExceptionFactory.h" + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +/** + * synchronously checks access status and throws JS Security exception if + * necessary + */ +#define SYNC_ACCESS_STATUS_HANDLER(status, context, exception) \ + do { \ + switch (status) \ + { \ + case AceSecurityStatus::InternalError: \ + return JSDOMExceptionFactory::UnknownException.make( \ + context, exception); \ + break; \ + \ + case AceSecurityStatus::AccessDenied: \ + return JSDOMExceptionFactory::SecurityException.make( \ + context, exception); \ + break; \ + \ + default: \ + break; \ + } \ + } while (0) + +/** + * checks access status and returns an error through JSCallbackManager if + * necessary + */ +#define ASYNC_CBM_ACCESS_STATUS_HANDLER(status, context, cbm) \ + do { \ + switch (status) \ + { \ + case AceSecurityStatus::InternalError: \ + cbm->callOnError(JSDOMExceptionFactory::UnknownException.make( \ + context)); \ + return JSValueMakeNull(context); \ + \ + case AceSecurityStatus::AccessDenied: \ + cbm->callOnError(JSDOMExceptionFactory::SecurityException.make( \ + context)); \ + return JSValueMakeNull(context); \ + \ + default: \ + break; \ + } \ + } while (0) +} +} +#endif /*WRTDEVICEAPIS_COMMONSJAVASCRIPT_JS_SECURITYEXCEPTIONS_H_ */ + diff --git a/src/CommonsJavaScript/Validator.cpp b/src/CommonsJavaScript/Validator.cpp new file mode 100644 index 0000000..fe30b08 --- /dev/null +++ b/src/CommonsJavaScript/Validator.cpp @@ -0,0 +1,131 @@ +/* + * 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 "Validator.h" +#include <list> +#include <dpl/assert.h> +#include "ScopedJSStringRef.h" +#include "Converter.h" + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +Validator::Validator(JSContextRef context, + JSValueRef* exception) : + m_context(context), + m_exception(exception) +{ + AssertMsg(NULL != m_context, "Context cannot be NULL."); +} + +Validator::~Validator() +{} + +bool Validator::isDate(const JSValueRef& arg) +{ + if (JSValueIsNull(m_context, + arg) || + JSValueIsUndefined(m_context, + arg) || !JSValueIsObject(m_context, arg)) + { + return false; + } + Converter converter(m_context); + Try + { + converter.toDateTm(arg); + } + Catch(Commons::ConversionException) + { + return false; + } + return true; +} + +bool +Validator::isCallback(const JSValueRef& arg) +{ + Converter converter(m_context); + return !JSValueIsNull(m_context, arg) && + !JSValueIsUndefined(m_context, arg) && + JSObjectIsFunction(m_context, converter.toJSObjectRef(arg)); +} + +bool +Validator::checkArrayKeys(const std::vector<std::string> &allowed, + JSValueRef argument) +{ + if (argument == NULL) { + return true; + } + if (!JSValueIsObject(m_context, argument)) { + return false; + } + JSObjectRef jsOptions = JSValueToObject(m_context, argument, NULL); + if (jsOptions == NULL) { + return false; + } + JSPropertyNameArrayRef jsProps = JSObjectCopyPropertyNames(m_context, + jsOptions); + if (jsProps == NULL) { + // No properties found; and empty array. + return true; + } + size_t nCount = JSPropertyNameArrayGetCount(jsProps); + bool found; + + std::list<JSStringRef> allowedJS; + for (size_t j = 0; j < allowed.size(); j++) { + allowedJS.push_back(JSStringCreateWithUTF8CString(allowed[j].c_str())); + } + + for (size_t i = 0; i < nCount; i++) { + found = false; + for (std::list<JSStringRef>::const_iterator it = allowedJS.begin(); + it != allowedJS.end(); + ++it) + { + if (JSStringIsEqual(*it, + JSPropertyNameArrayGetNameAtIndex(jsProps, + i))) + { + found = true; + break; + } + } + if (!found) { + for (size_t j = 0; j < allowed.size(); j++) { + JSStringRelease(allowedJS.front()); + allowedJS.pop_front(); + } + JSPropertyNameArrayRelease(jsProps); + return false; + } + } + + for (size_t j = 0; j < allowed.size(); j++) { + JSStringRelease(allowedJS.front()); + allowedJS.pop_front(); + } + JSPropertyNameArrayRelease(jsProps); + return true; +} + +bool Validator::isNullOrUndefined(const JSValueRef& arg) +{ + return (JSValueIsNull(m_context, arg) || + JSValueIsUndefined(m_context, arg)); +} +} // CommonsJavaScript +} // WrtDeviceApis diff --git a/src/CommonsJavaScript/Validator.h b/src/CommonsJavaScript/Validator.h new file mode 100644 index 0000000..315ffcf --- /dev/null +++ b/src/CommonsJavaScript/Validator.h @@ -0,0 +1,98 @@ +/* + * 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_COMMONSJAVASCRIPT_VALIDATOR_H_ +#define WRTDEVICEAPIS_COMMONSJAVASCRIPT_VALIDATOR_H_ + +#include <ctime> +#include <string> +#include <vector> +#include <JavaScriptCore/JavaScript.h> +#include <dpl/noncopyable.h> +#include <memory> +#include <Commons/Exception.h> + +namespace WrtDeviceApis { +namespace CommonsJavaScript { +class Validator : private DPL::Noncopyable +{ + public: + explicit Validator(JSContextRef context, + JSValueRef* exception = NULL); + virtual ~Validator(); + + /** + * Checks if arg is a Date. + * @param arg JSValueRef to check. + * @return true when object is a date, false otherwise + */ + bool isDate(const JSValueRef& arg); + + /** + * Checks if arg is a callback function. + * @param arg JSValueRef to check. + * @return true when object is a callback function, false otherwise + */ + bool isCallback(const JSValueRef& arg); + + /** + * Checks if arg have allowed properties. + * @param allowed allowed property names. + * @param arg JSValueRef to check. + * @return true when object's properties are subset of allowed + */ + bool checkArrayKeys(const std::vector<std::string> &allowed, + JSValueRef argument); + + bool isNullOrUndefined(const JSValueRef& arg); + + protected: + JSContextRef m_context; + JSValueRef* m_exception; +}; + +template<class C> +class ValidatorFactory : private DPL::Noncopyable +{ + public: + /** + * Validator type which deletes itself when gets out of scope. + */ + typedef std::shared_ptr<C> ValidatorType; + + public: + /** + * Gets converter object. + * @param context JavaScript context the conversion will be performed in. + * @param[out] exception JavaScript value for storing exception. + * @return Converter object. + */ + static ValidatorType getValidator(JSContextRef context, + JSValueRef* exception = NULL) + { + C* convert = new C(context, exception); + return ValidatorType(convert); + } + + private: + ValidatorFactory(); +}; + +typedef ValidatorFactory<Validator> BasicValidatorFactory; +typedef BasicValidatorFactory::ValidatorType BasicValidator; +} // CommonsJavaScript +} // WrtDeviceApis + +#endif /* _VALIDATOR_H_ */ diff --git a/src/DESCRIPTION b/src/DESCRIPTION new file mode 100644 index 0000000..bc2b1d7 --- /dev/null +++ b/src/DESCRIPTION @@ -0,0 +1 @@ +Main source folder diff --git a/src/dispatch-event/CMakeLists.txt b/src/dispatch-event/CMakeLists.txt new file mode 100644 index 0000000..7c9a2f3 --- /dev/null +++ b/src/dispatch-event/CMakeLists.txt @@ -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. +# + +# @file CMakeLists.txt +# @author Tae-Jeong Lee (taejeong.lee@samsung.com) +# @version 1.0 +# + +PKG_SEARCH_MODULE(webkit2 REQUIRED ewebkit2) +PKG_SEARCH_MODULE(dpl REQUIRED dpl-efl) + +SET(TARGET_NAME wrt-dispatch-event) + +SET(SRCS + ${CMAKE_CURRENT_SOURCE_DIR}/dispatch_event_support.cpp +) + +INCLUDE_DIRECTORIES( + ${CMAKE_CURRENT_SOURCE_DIR} + ${webkit2_INCLUDE_DIRS} + ${dpl_INCLUDE_DIRS} +) + +ADD_LIBRARY(${TARGET_NAME} SHARED ${SRCS}) + +TARGET_LINK_LIBRARIES(${TARGET_NAME} + ${webkit2_LIBRARIES} + ${dpl_LIBRARIES} +) + +SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES + COMPILE_DEFINITIONS LOG_TAG="${LOG_TAG}") + +SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES + COMPILE_FLAGS -fPIC + LINK_FLAGS "-Wl,--as-needed -Wl,--hash-style=both" +) + +SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES + SOVERSION ${CMAKE_PROJECT_API_VERSION} + VERSION ${CMAKE_PROJECT_VERSION} +) + +INSTALL(TARGETS ${TARGET_NAME} + DESTINATION ${DESTINATION_LIB_PREFIX} + PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE + GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE +) + +INSTALL(FILES dispatch_event_support.h DESTINATION include/wrt-dispatch-event) diff --git a/src/dispatch-event/dispatch_event_support.cpp b/src/dispatch-event/dispatch_event_support.cpp new file mode 100644 index 0000000..a60a6df --- /dev/null +++ b/src/dispatch-event/dispatch_event_support.cpp @@ -0,0 +1,219 @@ +/* + * 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 dispatch_event_support.cpp + * @author Tae-Jeong Lee (taejeong.lee@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _DISPATCH_EVENT_SUPPORT_CPP_ +#define _DISPATCH_EVENT_SUPPORT_CPP_ + +#include "dispatch_event_support.h" + +namespace DispatchEventSupport { + +static std::string getExceptionString(JSContextRef context, JSValueRef exception) +{ + if (exception) + { + JSStringRef jsString = JSValueToStringCopy(context, exception, NULL); + size_t bufSize = JSStringGetMaximumUTF8CStringSize(jsString); + + char* buf = new char[bufSize]; + JSStringGetUTF8CString(jsString, buf, bufSize); + JSStringRelease(jsString); + + std::string ret = buf; + delete[] buf; + + return ret; + } + else + { + return "NULL"; + } +} + +void dispatchAppServiceEvent(JSContextRef context, const float scale, const std::string bundle) +{ + WrtLogD("DispatchTizenServiceEvent(%f, %s)", scale, bundle.c_str()); + + if (context != NULL) + { + std::stringstream script; + + script << "var __event = document.createEvent(\"CustomEvent\");\n" + << "__event.initCustomEvent(\"appservice\", true, true);\n" + << "__event.scale = " << scale << ";\n" + << "__event.__bundle = \"" << bundle << "\";\n" + << "document.dispatchEvent(__event);\n" + << "\n" + << "for (var i=0; i < window.frames.length; i++)\n" + << "{ window.frames[i].document.dispatchEvent(__event); }"; + + // just for debugging + // WrtLogD("script :\n%s", script.str().c_str()); + + JSValueRef exception = NULL, ret = NULL; + JSStringRef jsScript = JSStringCreateWithUTF8CString(script.str().c_str()); + + ret = JSEvaluateScript(context, jsScript, NULL, NULL, 1, &exception); + + JSStringRelease(jsScript); + + WrtLogD("JSEvaluateScript() - ret: %p, exception: %s", + ret, getExceptionString(context, exception).c_str()); + } +} + +void dispatchSoftKeyboardChangeEvent(JSContextRef context, const std::string state, const int width, const int height) +{ + WrtLogD("dispatchSoftKeyboardChangeEvent(%s, %d, %d)", state.c_str(), width, height); + + if (context != NULL) + { + std::stringstream script; + + script << "var __event = document.createEvent(\"CustomEvent\");\n" + << "__event.initCustomEvent(\"softkeyboardchange\", true, true);\n" + << "__event.state = \"" << state << "\";\n" + << "__event.width = " << width << ";\n" + << "__event.height = " << height << ";\n" + << "document.dispatchEvent(__event);\n" + << "\n" + << "for (var i=0; i < window.frames.length; i++)\n" + << "{ window.frames[i].document.dispatchEvent(__event); }"; + + // just for debugging + // WrtLogD("script :\n%s", script.str().c_str()); + + JSValueRef exception = NULL, ret = NULL; + JSStringRef jsScript = JSStringCreateWithUTF8CString(script.str().c_str()); + + ret = JSEvaluateScript(context, jsScript, NULL, NULL, 1, &exception); + + JSStringRelease(jsScript); + + WrtLogD("JSEvaluateScript() - ret: %p, exception: %s", + ret, getExceptionString(context, exception).c_str()); + } +} + +void dispatchStorageEvent(JSContextRef context, + const DPL::OptionalStdString& key, + const DPL::OptionalStdString& oldValue, + const DPL::OptionalStdString& newValue, + const std::string& url) +{ + WrtLogD("dispatchStorageEvent(%s, %s, %s, %s)", + (!key ? "null" : (*key).c_str()), + (!oldValue ? "null" : (*oldValue).c_str()), + (!newValue ? "null" : (*newValue).c_str()), + url.c_str()); + + if (context != NULL) + { + std::stringstream script; + + auto toJSValue = + [](const DPL::OptionalStdString& value) -> std::string + { + return ((!value) ? "null" : "\"" + *value + "\""); + }; + + script << "var __event = document.createEvent(\"CustomEvent\");" + << "__event.initCustomEvent(\"storage\", true, true);" + << "__event.key = " << toJSValue(key) << ";" + << "__event.oldValue = " << toJSValue(oldValue) << ";" + << "__event.newValue = " << toJSValue(newValue) << ";" + << "__event.url = \"" << url << "\";" + << "__event.storageArea = widget.preferences;" + << "document.dispatchEvent(__event);" + << "for (var i=0; i < window.frames.length; i++)" + << "{ window.frames[i].document.dispatchEvent(__event); }"; + + + // just for debugging + // WrtLogD("script :\n%s", script.str().c_str()); + + JSValueRef exception = NULL, ret = NULL; + JSStringRef jsScript = JSStringCreateWithUTF8CString(script.str().c_str()); + + ret = JSEvaluateScript(context, jsScript, NULL, NULL, 1, &exception); + + JSStringRelease(jsScript); + + WrtLogD("JSEvaluateScript() - ret: %p, exception: (%s)", + ret, getExceptionString(context, exception).c_str()); + } +} + +void dispatchHwKeyEvent(Evas_Object* ewkView, const std::string key) +{ + WrtLogD("dispatchHwKeyEvent(%s)", key.c_str()); + + if (ewkView != NULL && !key.empty()) + { + std::stringstream script; + + script << "var __event = document.createEvent(\"CustomEvent\");\n" + << "__event.initCustomEvent(\"tizenhwkey\", true, true);\n" + << "__event.keyName = \"" << key << "\";\n" + << "document.dispatchEvent(__event);\n" + << "\n" + << "for (var i=0; i < window.frames.length; i++)\n" + << "{ window.frames[i].document.dispatchEvent(__event); }"; + + // just for debugging + // WrtLogD("script :\n%s", script.str().c_str()); + + if (ewk_view_script_execute(ewkView, script.str().c_str(), NULL, NULL) != EINA_TRUE) + { + WrtLogW("ewk_view_script_execute returned FALSE!"); + } + } +} + +void dispatchAppControlEvent(Evas_Object* ewkView) +{ + WrtLogD("dispatchAppControlEvent"); + + if (ewkView != NULL) + { + std::stringstream script; + + script << "var __event = document.createEvent(\"CustomEvent\");\n" + << "__event.initCustomEvent(\"appcontrol\", true, true);\n" + << "document.dispatchEvent(__event);\n" + << "\n" + << "for (var i=0; i < window.frames.length; i++)\n" + << "{ window.frames[i].document.dispatchEvent(__event); }"; + + // just for debugging + // WrtLogD("script :\n%s", script.str().c_str()); + + if (ewk_view_script_execute(ewkView, script.str().c_str(), NULL, NULL) != EINA_TRUE) + { + WrtLogW("ewk_view_script_execute returned FALSE!"); + } + } +} + +} +#endif //_DISPATCH_EVENT_SUPPORT_CPP_ diff --git a/src/dispatch-event/dispatch_event_support.h b/src/dispatch-event/dispatch_event_support.h new file mode 100644 index 0000000..abd26b9 --- /dev/null +++ b/src/dispatch-event/dispatch_event_support.h @@ -0,0 +1,46 @@ +/* + * 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 dispatch_event_support.h + * @author Tae-Jeong Lee (taejeong.lee@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _DISPATCH_EVENT_SUPPORT_H_ +#define _DISPATCH_EVENT_SUPPORT_H_ + +#include <string> +#include <dpl/optional_typedefs.h> +#include <dpl/log/wrt_log.h> +#include <EWebKit.h> +#include <EWebKit_internal.h> +#include <JavaScriptCore/JavaScript.h> + +namespace DispatchEventSupport { + +void dispatchAppServiceEvent(JSContextRef context, const float scale, const std::string bundle); +void dispatchSoftKeyboardChangeEvent(JSContextRef context, const std::string state, const int width, const int height); +void dispatchStorageEvent(JSContextRef context, + const DPL::OptionalStdString& key, + const DPL::OptionalStdString& oldValue, + const DPL::OptionalStdString& newValue, + const std::string& url); +void dispatchHwKeyEvent(Evas_Object* ewkView, const std::string key); +void dispatchAppControlEvent(Evas_Object* ewkView); +} +#endif //_DISPATCH_EVENT_SUPPORT_H_ diff --git a/src/js-overlay/CMakeLists.txt b/src/js-overlay/CMakeLists.txt new file mode 100644 index 0000000..52b4427 --- /dev/null +++ b/src/js-overlay/CMakeLists.txt @@ -0,0 +1,70 @@ +# 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 CMakeLists.txt +# @author Yunchan Cho (yunchan.cho@samsung.com) +# @version 1.0 +# +MACRO(INSTALL_HEADER_FILE HEADER_FILE) + INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/${HEADER_FILE} + DESTINATION ${DESTINATION_HEADERS_JS_OVERLAY}) +ENDMACRO() + +PKG_SEARCH_MODULE(webkit2 REQUIRED ewebkit2) +PKG_SEARCH_MODULE(plugin-types REQUIRED wrt-plugins-types) + +SET(TARGET_NAME ${TARGET_JS_OVERLAY}) + +SET(SRCS + ${CMAKE_CURRENT_SOURCE_DIR}/js_function_manager.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/js_overlay_functions.cpp +) + +INCLUDE_DIRECTORIES( + ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_CURRENT_SOURCE_DIR}/JSClass + ${webkit2_INCLUDE_DIRS} + ${plugin-types_INCLUDE_DIRS} +) + +ADD_LIBRARY(${TARGET_NAME} SHARED ${SRCS}) + +TARGET_LINK_LIBRARIES(${TARGET_NAME} + ${webkit2_LIBRARIES} + ${TARGET_COMMONS} + ${TARGET_COMMONS_JAVASCRIPT} +) + +SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES + COMPILE_DEFINITIONS LOG_TAG="${LOG_TAG}") + +SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES + COMPILE_FLAGS -fPIC + LINK_FLAGS "-Wl,--as-needed -Wl,--hash-style=both" +) + +SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES + SOVERSION ${CMAKE_PROJECT_API_VERSION} + VERSION ${CMAKE_PROJECT_VERSION} +) + +INSTALL(TARGETS ${TARGET_NAME} + DESTINATION ${DESTINATION_LIB_PREFIX} + PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE + GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE +) + +INSTALL_HEADER_FILE(js_overlay_types.h) + diff --git a/src/js-overlay/deprecated/JSClass/JSSoftKeyboardChangeEvent.cpp b/src/js-overlay/deprecated/JSClass/JSSoftKeyboardChangeEvent.cpp new file mode 100644 index 0000000..b02bcec --- /dev/null +++ b/src/js-overlay/deprecated/JSClass/JSSoftKeyboardChangeEvent.cpp @@ -0,0 +1,209 @@ +/* + * Copyright (c) 2012 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 JSSoftKeyboardChangeEvent.cpp + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 0.1 + */ + +#include "JSSoftKeyboardChangeEvent.h" +#include <dpl/log/wrt_log.h> +#include <dpl/assert.h> +#include <SoftKeyboardChangeEvent/ISoftKeyboardChangeEvent.h> +#include <CommonsJavaScript/Converter.h> +#include <CommonsJavaScript/JSDOMExceptionFactory.h> + +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::SoftKeyboardChangeEvent::Api; + +#define WIDGET_PLUGIN_NAME "SoftKeyboardChangeEvent" +#define SOFTKEYBOARD_CHANGE_EVENT_PROPERTY_STATE "state" +#define SOFTKEYBOARD_CHANGE_EVENT_PROPERTY_WIDTH "width" +#define SOFTKEYBOARD_CHANGE_EVENT_PROPERTY_HEIGHT "height" + +#define CATCH_EXCEPTION_CONVERSION \ + Catch(Commons::ConversionException) { \ + WrtLogE("Error on conversion"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_NULL_PTR \ + Catch(Commons::NullPointerException) { \ + WrtLogE("Error on pointer, null value"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_PLATFORM_ERROR \ + Catch(Commons::PlatformException){ \ + WrtLogE("PlatformException occured"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +namespace WrtPlugins { +namespace Tizen { +JSClassDefinition JSSoftKeyboardChangeEvent::m_classInfo = { + 0, + kJSClassAttributeNone, + WIDGET_PLUGIN_NAME, + 0, + m_property, + NULL, + initialize, + finalize, + NULL, //HasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL, //ConvertToType, +}; + +JSStaticValue JSSoftKeyboardChangeEvent::m_property[] = { + { SOFTKEYBOARD_CHANGE_EVENT_PROPERTY_STATE, + JSSoftKeyboardChangeEvent::getState, + 0, kJSPropertyAttributeReadOnly }, + { SOFTKEYBOARD_CHANGE_EVENT_PROPERTY_WIDTH, + JSSoftKeyboardChangeEvent::getWidth, + 0, kJSPropertyAttributeReadOnly }, + { SOFTKEYBOARD_CHANGE_EVENT_PROPERTY_HEIGHT, + JSSoftKeyboardChangeEvent::getHeight, + 0, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSClassRef JSSoftKeyboardChangeEvent::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSSoftKeyboardChangeEvent::getClassInfo() +{ + return &m_classInfo; +} + +JSClassRef JSSoftKeyboardChangeEvent::m_jsClassRef = JSClassCreate( + JSSoftKeyboardChangeEvent::getClassInfo()); + +void JSSoftKeyboardChangeEvent::initialize(JSContextRef /*context*/, + JSObjectRef object) +{ + WrtLogD("entered"); + + JSSoftKeyboardChangeEventPrivateObject* priv = + static_cast<JSSoftKeyboardChangeEventPrivateObject*>(JSObjectGetPrivate( + object)); + + AssertMsg(priv, "Missing private object"); +} + +void JSSoftKeyboardChangeEvent::finalize(JSObjectRef object) +{ + WrtLogD("entered"); + JSSoftKeyboardChangeEventPrivateObject* priv = + static_cast<JSSoftKeyboardChangeEventPrivateObject*>(JSObjectGetPrivate( + object)); + + delete priv; + WrtLogD("private object is realised"); +} + +JSValueRef JSSoftKeyboardChangeEvent::getState( + JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + WrtLogD("entered!"); + + Try + { + Converter converter(context); + return converter.toJSValueRef(getPrivateObject(object)->getState()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR +} + +JSValueRef JSSoftKeyboardChangeEvent::getWidth( + JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + WrtLogD("entered!"); + + Try + { + Converter converter(context); + return converter.toJSValueRef(getPrivateObject(object)->getWidth()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR +} + +JSValueRef JSSoftKeyboardChangeEvent::getHeight( + JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + WrtLogD("entered"); + + Try + { + Converter converter(context); + return converter.toJSValueRef(getPrivateObject(object)->getHeight()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR +} + +ISoftKeyboardChangeEventPtr JSSoftKeyboardChangeEvent::getPrivateObject( + JSObjectRef arg) +{ + JSSoftKeyboardChangeEventPrivateObject* priv = + static_cast<JSSoftKeyboardChangeEventPrivateObject*>(JSObjectGetPrivate( + arg)); + + if (!priv) { + WrtLogE("Private object not initialized"); + ThrowMsg(Commons::NullPointerException, + "Private object not initialized"); + } + + return priv->getObject(); +} + +#undef CATCH_EXCEPTION_CONVERSION +#undef CATCH_EXCEPTION_NULL_PTR +#undef CATCH_EXCEPTION_PLATFORM_ERROR +} +} diff --git a/src/js-overlay/deprecated/JSClass/JSSoftKeyboardChangeEvent.h b/src/js-overlay/deprecated/JSClass/JSSoftKeyboardChangeEvent.h new file mode 100644 index 0000000..49da22f --- /dev/null +++ b/src/js-overlay/deprecated/JSClass/JSSoftKeyboardChangeEvent.h @@ -0,0 +1,101 @@ +/* + * 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 JSSoftKeyboardChangeEvent.h + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRT_PLUGIN_JS_SOFTKEYBOARD_CHANGE_EVENT_H +#define WRT_PLUGIN_JS_SOFTKEYBOARD_CHANGE_EVENT_H + +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/PrivateObject.h> +#include <SoftKeyboardChangeEvent/ISoftKeyboardChangeEvent.h> + +namespace WrtPlugins { +namespace Tizen { +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT< + WrtDeviceApis::SoftKeyboardChangeEvent::Api::ISoftKeyboardChangeEventPtr>:: + Type +JSSoftKeyboardChangeEventPrivateObject; + +class JSSoftKeyboardChangeEvent +{ + public: + /** + * This method initializes this in the JS Engine. + */ + static JSClassRef getClassRef(); + + /** + * Gets object's class description. + */ + static const JSClassDefinition* getClassInfo(); + + private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * This structure describes a statically declared value property. + */ + static JSStaticValue m_property[]; + + /** + * This structure contains properties and callbacks that define a type of + * object. + */ + static JSClassDefinition m_classInfo; + + static JSClassRef m_jsClassRef; + + // getters for properties + static JSValueRef getState( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getWidth( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getHeight( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static WrtDeviceApis::SoftKeyboardChangeEvent::Api:: + ISoftKeyboardChangeEventPtr + getPrivateObject(JSObjectRef arg); +}; +} // Tizen +} // WrtPlugins + +#endif // WRT_PLUGIN_JS_SOFTKEYBOARD_CHANGE_EVENT_H diff --git a/src/js-overlay/deprecated/JSClass/JSStorageEvent.cpp b/src/js-overlay/deprecated/JSClass/JSStorageEvent.cpp new file mode 100644 index 0000000..7c627d8 --- /dev/null +++ b/src/js-overlay/deprecated/JSClass/JSStorageEvent.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. + */ +/** + * + * @file JSStorageEvent.cpp + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + */ + +#include "JSStorageEvent.h" +#include <dpl/log/wrt_log.h> +#include <dpl/assert.h> +#include <StorageEvent/IStorageEvent.h> +#include <CommonsJavaScript/Converter.h> +#include <CommonsJavaScript/JSDOMExceptionFactory.h> + +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::StorageEvent::Api; + +#define WIDGET_PLUGIN_NAME "StorageEvent" + +#define WRT_STORAGE_EVENT_PROPERTY_KEY "key" +#define WRT_STORAGE_EVENT_PROPERTY_OLD_VALUE "oldValue" +#define WRT_STORAGE_EVENT_PROPERTY_NEW_VALUE "newValue" +#define WRT_STORAGE_EVENT_PROPERTY_URL "url" +#define WRT_STORAGE_EVENT_PROPERTY_STORAGE_AREA "storageArea" + +#define CATCH_EXCEPTION_CONVERSION \ + Catch(Commons::ConversionException) { \ + WrtLogE("Error on conversion"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_NULL_PTR \ + Catch(Commons::NullPointerException) { \ + WrtLogE("Error on pointer, null value"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_PLATFORM_ERROR \ + Catch(Commons::PlatformException){ \ + WrtLogE("PlatformException occured"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_SECURITY \ + Catch(Commons::SecurityException){ \ + WrtLogE("Security exception occured"); \ + return JSDOMExceptionFactory:: \ + SecurityException.make(context, exception); \ + } + +namespace WrtPlugins { +namespace W3C { +JSClassDefinition JSStorageEvent::m_classInfo = { + 0, + kJSClassAttributeNone, + WIDGET_PLUGIN_NAME, + 0, + m_property, + NULL, + initialize, + finalize, + NULL, //HasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL, //ConvertToType, +}; + +JSStaticValue JSStorageEvent::m_property[] = { + { WRT_STORAGE_EVENT_PROPERTY_KEY, JSStorageEvent::getKey, + 0, kJSPropertyAttributeReadOnly }, + { WRT_STORAGE_EVENT_PROPERTY_OLD_VALUE, JSStorageEvent::getOldValue, + 0, kJSPropertyAttributeReadOnly }, + { WRT_STORAGE_EVENT_PROPERTY_NEW_VALUE, JSStorageEvent::getNewValue, + 0, kJSPropertyAttributeReadOnly }, + { WRT_STORAGE_EVENT_PROPERTY_URL, JSStorageEvent::getUrl, + 0, kJSPropertyAttributeReadOnly }, + { WRT_STORAGE_EVENT_PROPERTY_STORAGE_AREA, JSStorageEvent::getStorageArea, + 0, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSClassRef JSStorageEvent::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSStorageEvent::getClassInfo() +{ + return &m_classInfo; +} + +JSClassRef JSStorageEvent::m_jsClassRef = JSClassCreate( + JSStorageEvent::getClassInfo()); + +void JSStorageEvent::initialize(JSContextRef /*context*/, + JSObjectRef object) +{ + WrtLogD("entered"); + + JSStorageEventPrivateObject* priv = + static_cast<JSStorageEventPrivateObject*>(JSObjectGetPrivate(object)); + + AssertMsg(priv, "Missing private object"); +} + +void JSStorageEvent::finalize(JSObjectRef object) +{ + WrtLogD("entered"); + JSStorageEventPrivateObject* priv = + static_cast<JSStorageEventPrivateObject*>(JSObjectGetPrivate(object)); + + delete priv; + WrtLogD("private object is realised"); +} + +JSValueRef JSStorageEvent::getKey( + JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + WrtLogD("entered"); + + Try + { + Converter converter(context); + + return converter.toJSValueRef(getPrivateObject(object)->getKey()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_SECURITY +} + +JSValueRef JSStorageEvent::getOldValue( + JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + WrtLogD("entered"); + + Try + { + Converter converter(context); + + DPL::OptionalString oldValue = getPrivateObject(object)->getOldValue(); + + if (!oldValue) { + return JSValueMakeNull(context); + } else { + return converter.toJSValueRef(DPL::ToUTF8String(*oldValue)); + } + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_SECURITY +} + +JSValueRef JSStorageEvent::getNewValue( + JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + WrtLogD("entered"); + + Try + { + Converter converter(context); + + DPL::OptionalString newValue = getPrivateObject(object)->getNewValue(); + + if (!newValue) { + return JSValueMakeNull(context); + } else { + return converter.toJSValueRef(DPL::ToUTF8String(*newValue)); + } + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_SECURITY +} + +JSValueRef JSStorageEvent::getUrl( + JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + WrtLogD("entered"); + + Try + { + Converter converter(context); + + return converter.toJSValueRef(getPrivateObject(object)->getUrl()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR +} + +JSValueRef JSStorageEvent::getStorageArea( + JSContextRef context, + JSObjectRef /*object*/, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + WrtLogD("entered"); + + Try + { + WrtLogE("Not implemented"); + return JSValueMakeUndefined(context); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_SECURITY +} + +IStorageEventPtr JSStorageEvent::getPrivateObject(JSObjectRef arg) +{ + JSStorageEventPrivateObject* priv = + static_cast<JSStorageEventPrivateObject*>(JSObjectGetPrivate(arg)); + + if (!priv) { + WrtLogE("Private object not initialized"); + ThrowMsg(Commons::NullPointerException, + "Private object not initialized"); + } + + return priv->getObject(); +} + +#undef CATCH_EXCEPTION_CONVERSION +#undef CATCH_EXCEPTION_NULL_PTR +#undef CATCH_EXCEPTION_PLATFORM_ERROR +#undef CATCH_EXCEPTION_SECURITY +} +} diff --git a/src/js-overlay/deprecated/JSClass/JSStorageEvent.h b/src/js-overlay/deprecated/JSClass/JSStorageEvent.h new file mode 100644 index 0000000..0460f39 --- /dev/null +++ b/src/js-overlay/deprecated/JSClass/JSStorageEvent.h @@ -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. + */ +/** + * + * @file JSStorageEvent.h + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _WRT_PLUGIN_JS_STORAGE_EVENT_H_ +#define _WRT_PLUGIN_JS_STORAGE_EVENT_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/PrivateObject.h> +#include <StorageEvent/IStorageEvent.h> + +namespace WrtPlugins { +namespace W3C { +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT< + WrtDeviceApis::StorageEvent::Api::IStorageEventPtr>::Type +JSStorageEventPrivateObject; + +class JSStorageEvent +{ + public: + /** + * This method initializes this in the JS Engine. + */ + static JSClassRef getClassRef(); + + /** + * Gets object's class description. + */ + static const JSClassDefinition* getClassInfo(); + + private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, + JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * This structure describes a statically declared value property. + */ + static JSStaticValue m_property[]; + + /** + * This structure contains properties and callbacks that define a type of + * object. + */ + static JSClassDefinition m_classInfo; + + static JSClassRef m_jsClassRef; + + // getters for properties + static JSValueRef getKey( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getOldValue( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getNewValue( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getUrl( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getStorageArea( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static WrtDeviceApis::StorageEvent::Api::IStorageEventPtr + getPrivateObject(JSObjectRef arg); +}; +} // W3C +} // WrtPlugins + +#endif // _WRT_PLUGIN_JS_STORAGE_EVENT_H_ diff --git a/src/js-overlay/deprecated/JSClass/JSTizenServiceEvent.cpp b/src/js-overlay/deprecated/JSClass/JSTizenServiceEvent.cpp new file mode 100644 index 0000000..df5f21f --- /dev/null +++ b/src/js-overlay/deprecated/JSClass/JSTizenServiceEvent.cpp @@ -0,0 +1,194 @@ +/* + * 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 JSTizenServiceEvent.cpp + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 0.1 + */ + +#include "JSTizenServiceEvent.h" +#include <dpl/log/wrt_log.h> +#include <dpl/assert.h> +#include <TizenServiceEvent/ITizenServiceEvent.h> +#include <CommonsJavaScript/Converter.h> +#include <CommonsJavaScript/JSDOMExceptionFactory.h> + +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::TizenServiceEvent::Api; + +#define WIDGET_PLUGIN_NAME "TizenServiceEvent" + +#define TIZEN_SERVICE_EVENT_PROPERTY_SCALE "scale" +#define TIZEN_SERVICE_EVENT_PROPERTY_BUNDLE "__bundle" + +#define CATCH_EXCEPTION_CONVERSION \ + Catch(Commons::ConversionException) { \ + WrtLogE("Error on conversion"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_NULL_PTR \ + Catch(Commons::NullPointerException) { \ + WrtLogE("Error on pointer, null value"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_PLATFORM_ERROR \ + Catch(Commons::PlatformException){ \ + WrtLogE("PlatformException occured"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_SECURITY \ + Catch(Commons::SecurityException){ \ + WrtLogE("Security exception occured"); \ + return JSDOMExceptionFactory:: \ + SecurityException.make(context, exception); \ + } + +namespace WrtPlugins { +namespace Tizen { +JSClassDefinition JSTizenServiceEvent::m_classInfo = { + 0, + kJSClassAttributeNone, + WIDGET_PLUGIN_NAME, + 0, + m_property, + NULL, + initialize, + finalize, + NULL, //HasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL, //ConvertToType, +}; + +JSStaticValue JSTizenServiceEvent::m_property[] = { + { TIZEN_SERVICE_EVENT_PROPERTY_SCALE, JSTizenServiceEvent::getScale, + 0, kJSPropertyAttributeReadOnly }, + { TIZEN_SERVICE_EVENT_PROPERTY_BUNDLE, JSTizenServiceEvent::getBundle, + 0, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSClassRef JSTizenServiceEvent::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSTizenServiceEvent::getClassInfo() +{ + return &m_classInfo; +} + +JSClassRef JSTizenServiceEvent::m_jsClassRef = JSClassCreate( + JSTizenServiceEvent::getClassInfo()); + +void JSTizenServiceEvent::initialize(JSContextRef /*context*/, + JSObjectRef object) +{ + WrtLogD("entered"); + + JSTizenServiceEventPrivateObject* priv = + static_cast<JSTizenServiceEventPrivateObject*>(JSObjectGetPrivate( + object)); + + AssertMsg(priv, "Missing private object"); +} + +void JSTizenServiceEvent::finalize(JSObjectRef object) +{ + WrtLogD("entered"); + JSTizenServiceEventPrivateObject* priv = + static_cast<JSTizenServiceEventPrivateObject*>(JSObjectGetPrivate( + object)); + + delete priv; + WrtLogD("private object is realised"); +} + +JSValueRef JSTizenServiceEvent::getScale( + JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + WrtLogD("entered"); + + Try + { + Converter converter(context); + return converter.toJSValueRef(getPrivateObject(object)->getScale()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_SECURITY +} + +JSValueRef JSTizenServiceEvent::getBundle( + JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + WrtLogD("entered"); + + Try + { + Converter converter(context); + return converter.toJSValueRef(getPrivateObject(object)->getBundle()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_SECURITY +} + +ITizenServiceEventPtr JSTizenServiceEvent::getPrivateObject(JSObjectRef arg) +{ + JSTizenServiceEventPrivateObject* priv = + static_cast<JSTizenServiceEventPrivateObject*>(JSObjectGetPrivate(arg)); + + if (!priv) { + WrtLogE("Private object not initialized"); + ThrowMsg(Commons::NullPointerException, + "Private object not initialized"); + } + + return priv->getObject(); +} + +#undef CATCH_EXCEPTION_CONVERSION +#undef CATCH_EXCEPTION_NULL_PTR +#undef CATCH_EXCEPTION_PLATFORM_ERROR +#undef CATCH_EXCEPTION_SECURITY +} +} diff --git a/src/js-overlay/deprecated/JSClass/JSTizenServiceEvent.h b/src/js-overlay/deprecated/JSClass/JSTizenServiceEvent.h new file mode 100644 index 0000000..a079dc5 --- /dev/null +++ b/src/js-overlay/deprecated/JSClass/JSTizenServiceEvent.h @@ -0,0 +1,94 @@ +/* + * 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 JSTizenServiceEvent.h + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _WRT_PLUGIN_JS_TIZEN_SERVICE_EVENT_H_ +#define _WRT_PLUGIN_JS_TIZEN_SERVICE_EVENT_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/PrivateObject.h> +#include <TizenServiceEvent/ITizenServiceEvent.h> + +namespace WrtPlugins { +namespace Tizen { +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT< + WrtDeviceApis::TizenServiceEvent::Api::ITizenServiceEventPtr>::Type +JSTizenServiceEventPrivateObject; + +class JSTizenServiceEvent +{ + public: + /** + * This method initializes this in the JS Engine. + */ + static JSClassRef getClassRef(); + + /** + * Gets object's class description. + */ + static const JSClassDefinition* getClassInfo(); + + private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, + JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * This structure describes a statically declared value property. + */ + static JSStaticValue m_property[]; + + /** + * This structure contains properties and callbacks that define a type of + * object. + */ + static JSClassDefinition m_classInfo; + + static JSClassRef m_jsClassRef; + + // getters for properties + static JSValueRef getScale( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getBundle( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static WrtDeviceApis::TizenServiceEvent::Api::ITizenServiceEventPtr + getPrivateObject(JSObjectRef arg); +}; +} // Tizen +} // WrtPlugins + +#endif // _WRT_PLUGIN_JS_TIZEN_SERVICE_EVENT_H_ diff --git a/src/js-overlay/deprecated/js_iframe_support.cpp b/src/js-overlay/deprecated/js_iframe_support.cpp new file mode 100755 index 0000000..39ef906 --- /dev/null +++ b/src/js-overlay/deprecated/js_iframe_support.cpp @@ -0,0 +1,76 @@ +/* + * 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 IFrameSupport.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#include <dpl/foreach.h> +#include <dpl/assert.h> +#include <dpl/log/wrt_log.h> +#include <js_iframe_support.h> + +namespace WrtPlugins { +namespace W3C { +IFrameSupport::IFramesContainer IFrameSupport::m_iframesObject = + IFrameSupport::IFramesContainer(); + +void IFrameSupport::RegisterWidget(java_script_context_t /*global_context*/, + js_object_instance_t iframe, + js_object_instance_t object) +{ + WrtLogD("New widget instance registered"); + getIFrameData(static_cast<JSObjectRef>(iframe))->widget = + static_cast<JSObjectRef>(object); +} + +void IFrameSupport::RegisterAddEventListener( + java_script_context_t /*global_context*/, + js_object_instance_t iframe, + js_object_instance_t object) +{ + WrtLogD("New addEventListener instance registered"); + getIFrameData(static_cast<JSObjectRef>(iframe))->addEventListener + = static_cast<JSObjectRef>(object); +} + +JSObjectRef IFrameSupport::getIFrameObjectForWidget(JSObjectRef widgetObject) +{ + FOREACH(it, m_iframesObject) + { + if (it->second->widget == widgetObject) { + WrtLogD("iframe found"); + return it->first; + } + } + WrtLogD("Iframe not found"); + return NULL; +} + +IFrameDataPtr IFrameSupport::getIFrameData(JSObjectRef iframe) +{ + auto it = m_iframesObject.find(iframe); + if (it != m_iframesObject.end()) { + return it->second; + } + + return m_iframesObject[iframe] = IFrameDataPtr(new IFrameData()); +} +} +} diff --git a/src/js-overlay/deprecated/js_iframe_support.h b/src/js-overlay/deprecated/js_iframe_support.h new file mode 100755 index 0000000..de07932 --- /dev/null +++ b/src/js-overlay/deprecated/js_iframe_support.h @@ -0,0 +1,68 @@ +/* + * 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 IFrameSupport.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _WRT_PLUGINS_SRC_W3C_WIDGET_IFRAME_SUPPORT_H_ +#define _WRT_PLUGINS_SRC_W3C_WIDGET_IFRAME_SUPPORT_H_ + +#include <map> +#include <memory> +#include <JavaScriptCore/JavaScript.h> +#include <wrt_plugin_export.h> + +namespace WrtPlugins { +namespace W3C { +struct IFrameData +{ + IFrameData() : widget(0), addEventListener(0){} + + JSObjectRef widget; + JSObjectRef addEventListener; +}; +typedef std::shared_ptr<IFrameData> IFrameDataPtr; + +class IFrameSupport +{ + public: + static void RegisterWidget(java_script_context_t global_context, + js_object_instance_t iframe, + js_object_instance_t object); + + static void RegisterAddEventListener(java_script_context_t global_context, + js_object_instance_t iframe, + js_object_instance_t object); + + static JSObjectRef getIFrameObjectForWidget(JSObjectRef widgetObject); + + private: + //map iframe:objects + typedef std::map<JSObjectRef, IFrameDataPtr> IFramesContainer; + + static IFramesContainer m_iframesObject; + + private: + static IFrameDataPtr getIFrameData(JSObjectRef iframe); +}; +} +} + +#endif diff --git a/src/js-overlay/deprecated/js_overlay_addEventListener.cpp b/src/js-overlay/deprecated/js_overlay_addEventListener.cpp new file mode 100755 index 0000000..99b61b9 --- /dev/null +++ b/src/js-overlay/deprecated/js_overlay_addEventListener.cpp @@ -0,0 +1,202 @@ +/* + * 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 AddEventListenerSupport.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 0.1 + * @brief + */ + +#include <string> +#include <dpl/log/wrt_log.h> +#include <dpl/foreach.h> +#include <CommonsJavaScript/Converter.h> +#include <js_overlay_addEventListener.h> +#include <js_overlay_types.h> +#include <JSStorageEvent.h> + +namespace WrtPlugins { +namespace W3C { + +const std::string storageEventName = "storage"; +const std::string appServiceEventName = "appservice"; +const std::string softKeyboardChangeEventName = "softkeyboardchange"; + +AddEventListenerSupport::IFramesListeners +AddEventListenerSupport::m_listeners = + AddEventListenerSupport::IFramesListeners(); + +JSValueRef AddEventListenerSupport::AddEventListener( + JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* /*exception*/) +{ + WrtLogD("Add event listener invoked"); + + JSContextRef global_context = JSContextGetGlobalContext(context); + + if (argumentCount < 2 || !JSValueIsString(context, arguments[0])) { + WrtLogE("Wrong arguments"); + return JSValueMakeUndefined(context); + } + + std::string eventName = WrtDeviceApis::CommonsJavaScript:: + Converter(context).toString(arguments[0]); + WrtLogD("Event name: %s", eventName.c_str()); + + if (eventName != storageEventName && + eventName != appServiceEventName && + eventName != softKeyboardChangeEventName) + { + WrtLogD("Event type not supported"); + return JSValueMakeUndefined(context); + } + + JSObjectRef objectCb = JSValueToObject(context, arguments[1], NULL); + if (!JSObjectIsFunction(context, objectCb)) { + WrtLogE("JS object is not a function"); + return JSValueMakeUndefined(context); + } + JSValueProtect(global_context, arguments[1]); + //add object to Listeners + //set event information according to each event type + CallbackData data; + data.object = objectCb; + data.thisObject = thisObject; + data.context = global_context; + + if (eventName == storageEventName) { + data.eventType = StorageCustomEvent; + } else if (eventName == appServiceEventName) { + data.eventType = ServiceCustomEvent; + } else if (eventName == softKeyboardChangeEventName) { + data.eventType = SoftKeyboardChangeCustomEvent; + } + + getIFrameListeners(thisObject)->push_back(data); + + return JSValueMakeUndefined(context); +} + +void AddEventListenerSupport::RemoveIFrame(JSObjectPtr iframe) +{ + auto it = m_listeners.find(iframe->getObject()); + if (it == m_listeners.end()) { + WrtLogW("Iframe not registered"); + return; + } + + FOREACH(listener, *it->second) + { + JSValueUnprotect(listener->context, listener->object); + } + m_listeners.erase(it); + WrtLogD("Iframe removed from add event listener object"); +} + +void AddEventListenerSupport::CallStorageListenersFromDifferentIFrames( + JSObjectRef iframe, + const WrtDeviceApis::StorageEvent::Api::IStorageEventPtr& event) +{ + WrtLogD("Invoked callbacks"); + + FOREACH(it, m_listeners) + { + if (it->first == iframe) { + continue; + } + + FOREACH(listener, *it->second) + { + WrtLogD("Call"); + + auto eventPriv = + new JSStorageEventPrivateObject(listener->context, event); + + JSObjectRef eventObject = + JSObjectMake(listener->context, JSStorageEvent::getClassRef(), eventPriv); + const size_t argc = 1; + JSValueRef argv[argc] = { eventObject }; + + JSValueProtect(listener->context, eventObject); + + if (listener->eventType == StorageCustomEvent) + { + JSObjectCallAsFunction( + listener->context, + listener->object, + NULL, + argc, + argv, + NULL); + } + + JSValueUnprotect(listener->context, eventObject); + } + } + + WrtLogD("Done"); +} + +void AddEventListenerSupport::CallCustomEventListenersFromIFrame( + JSObjectRef iframe, + CustomEventType eventType, + JSObjectRef eventObject) +{ + WrtLogD("Invoked callbacks"); + + IFramesListeners::iterator it = m_listeners.find(iframe); + if (it == m_listeners.end()) { + WrtLogD("This frame object not existed"); + return; + } + + const size_t argc = 1; + JSValueRef argv[argc] = { eventObject }; + + FOREACH(listener, *it->second) + { + if (listener->eventType == eventType) { + WrtLogD("Call"); + JSObjectCallAsFunction( + listener->context, + listener->object, + iframe, + argc, + argv, + NULL); + } + } + WrtLogD("Done"); +} + +AddEventListenerSupport::ListenersPtr +AddEventListenerSupport::getIFrameListeners(JSObjectRef iframe) +{ + auto it = m_listeners.find(iframe); + if (it != m_listeners.end()) { + return it->second; + } + + return m_listeners[iframe] = ListenersPtr(new Listeners()); +} +} +} diff --git a/src/js-overlay/deprecated/js_overlay_addEventListener.h b/src/js-overlay/deprecated/js_overlay_addEventListener.h new file mode 100755 index 0000000..0a9717e --- /dev/null +++ b/src/js-overlay/deprecated/js_overlay_addEventListener.h @@ -0,0 +1,87 @@ +/* + * 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_overlay_addEventListener.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _WRT_PLUGINS_SRC_W3C_WIDGET_ADDEVENTLISTENERSUPPORT_H_ +#define _WRT_PLUGINS_SRC_W3C_WIDGET_ADDEVENTLISTENERSUPPORT_H_ + +#include <map> +#include <list> +#include <memory> +#include <JavaScriptCore/JavaScript.h> +#include <JavaScriptCore/JSContextRef.h> +#include <StorageEvent/IStorageEvent.h> +#include <TizenServiceEvent/ITizenServiceEvent.h> +#include <js_overlay_types.h> +#include <JSObject.h> + +// import temporarily from JSContextRefPrivate.h +extern "C" JSGlobalContextRef JSContextGetGlobalContext(JSContextRef ctx); + +namespace WrtPlugins { +namespace W3C { +class AddEventListenerSupport +{ + public: + static JSValueRef AddEventListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static void RemoveIFrame(JSObjectPtr iframe); + + static void CallStorageListenersFromDifferentIFrames( + JSObjectRef iframe, + const WrtDeviceApis::StorageEvent::Api::IStorageEventPtr& event); + + static void CallCustomEventListenersFromIFrame( + JSObjectRef iframe, + CustomEventType eventType, + JSObjectRef eventObject); + + private: + + struct CallbackData { + CustomEventType eventType; + JSObjectRef object; + JSObjectRef thisObject; + JSContextRef context; + }; + + typedef std::list<CallbackData> Listeners; + typedef std::shared_ptr<Listeners> ListenersPtr; + + //first-iframe, 2nd - listeners list + typedef std::map<JSObjectRef, ListenersPtr> IFramesListeners; + + static IFramesListeners m_listeners; + + private: + static ListenersPtr getIFrameListeners(JSObjectRef iframe); +}; +} +} + +#endif diff --git a/src/js-overlay/deprecated/js_overlay_support.cpp b/src/js-overlay/deprecated/js_overlay_support.cpp new file mode 100644 index 0000000..8e41d39 --- /dev/null +++ b/src/js-overlay/deprecated/js_overlay_support.cpp @@ -0,0 +1,183 @@ +/* + * 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_overlay_support.cpp + * @author + * @version 1.0 + * @brief + */ +#include <memory> +#include <dpl/log/wrt_log.h> +#include <dpl/foreach.h> +#include <JavaScriptCore/JavaScript.h> + +#include <js_overlay_support.h> + +namespace JSOverlaySupport { +class JSFunctionDispatcher +{ + public: + struct PrivateData + { + //required to unprotect object in destructor; + JSContextRef context; + JSObjectPtr originalFunction; + JSObjectPtr overlayFunction; + }; + + static JSClassRef getClassRef(); + + private: + static JSClassDefinition m_classInfo; + + private: + static void initialize(JSContextRef context, JSObjectRef object); + + static void finalize(JSObjectRef object); + + static JSValueRef callAsFunction(JSContextRef ctx, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); +}; + +JSObjectPtr createWrappedFunction( + JSGlobalContextRef ctx, + const JSObjectPtr& originalFunction, + const JSObjectPtr& overlayFunction, + const std::string& name) +{ + WrtLogD("Creation overlay for function: %s", name.c_str()); + JSStringRef name_js = JSStringCreateWithUTF8CString(name.c_str()); + + JSFunctionDispatcher::PrivateData* priv = + new JSFunctionDispatcher::PrivateData; + priv->context = ctx; + priv->overlayFunction = overlayFunction; + priv->originalFunction = originalFunction; + + auto fun = JSObjectMake(ctx, JSFunctionDispatcher::getClassRef(), priv); + + JSStringRelease(name_js); + + WrtLogD("JSValueProtect invoked"); + + //the value is unprotected in finalize of the JSFunctionDispatcher object + JSValueProtect(ctx, + static_cast<JSObjectRef>( + overlayFunction->getObject())); + + return JSObjectPtr(new JSObject(fun)); +} + +JSClassDefinition JSFunctionDispatcher::m_classInfo = { + 0, + kJSClassAttributeNone, + "IGNORED", + 0, + 0, + 0, + initialize, + finalize, + NULL, + NULL, + NULL, + NULL, + NULL, + callAsFunction, + NULL, + NULL, + NULL +}; + +JSClassRef JSFunctionDispatcher::getClassRef() +{ + static auto classRef = JSClassCreate(&m_classInfo); + return classRef; +} + +void JSFunctionDispatcher::initialize(JSContextRef /*context*/, + JSObjectRef /*object*/) +{ + WrtLogD("Initialize"); +} + +void JSFunctionDispatcher::finalize(JSObjectRef object) +{ + WrtLogD("finalize"); + + PrivateData* priv = static_cast<PrivateData*>(JSObjectGetPrivate(object)); + if (priv) { + JSValueUnprotect(priv->context, + static_cast<JSObjectRef>( + priv->overlayFunction->getObject())); + delete priv; + } +} + +JSValueRef JSFunctionDispatcher::callAsFunction( + JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + WrtLogD("Dispatcher invoked"); + + JSValueRef result = JSValueMakeUndefined(context); + + JSFunctionDispatcher::PrivateData* priv = + static_cast<JSFunctionDispatcher::PrivateData*> + (JSObjectGetPrivate(object)); + + if (!priv) { + WrtLogE("Private object is NULL"); + return result; + } + + //call overlayed function + if (priv->overlayFunction->getObject()) { + WrtLogD("Overlayed function will be invoked..."); + result = JSObjectCallAsFunction( + priv->context, + static_cast<JSObjectRef>( + priv->overlayFunction->getObject()), + thisObject, + argumentCount, + arguments, + exception); + } + + //call original function + if (priv->originalFunction->getObject()) { + WrtLogD("Original function will be invoked.."); + result = JSObjectCallAsFunction( + context, + static_cast<JSObjectRef>( + priv->originalFunction->getObject()), + thisObject, + argumentCount, + arguments, + exception); + } + + WrtLogD("Done"); + return result; +} +} diff --git a/src/js-overlay/deprecated/js_overlay_support.h b/src/js-overlay/deprecated/js_overlay_support.h new file mode 100644 index 0000000..0cfb19b --- /dev/null +++ b/src/js-overlay/deprecated/js_overlay_support.h @@ -0,0 +1,40 @@ +/* + * 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_function_wrapper.h + * @author + * @version 1.0 + * @brief + */ + +#ifndef _JAVASCRIPT_OVERLAY_SUPPORT_H +#define _JAVASCRIPT_OVERLAY_SUPPORT_H + +#include <string> +#include <dpl/noncopyable.h> +#include <JavaScriptCore/JavaScript.h> +#include <JavaScriptCore/JSObjectRef.h> +#include <Commons/JSObject.h> + +namespace JSOverlaySupport { +JSObjectPtr createWrappedFunction( + JSGlobalContextRef ctx, + const JSObjectPtr& originalFunction, + const JSObjectPtr& overlayFunction, + const std::string& name); +} + +#endif diff --git a/src/js-overlay/js_function_manager.cpp b/src/js-overlay/js_function_manager.cpp new file mode 100644 index 0000000..53a4d3c --- /dev/null +++ b/src/js-overlay/js_function_manager.cpp @@ -0,0 +1,103 @@ +/* + * 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_function_manager.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @author Yunchan Cho (yunchan.cho@samgsung.com) + * @version + * @brief + */ + +#include <dpl/singleton_safe_impl.h> +#include <js_function_manager.h> +#include <js_overlay_functions.h> +#include <wrt_plugin_export.h> +#include <dpl/log/wrt_log.h> + +IMPLEMENT_SAFE_SINGLETON(JsFunctionManager) + +namespace { +const char* JSPRINT_NAME = "jsPrint"; +const char* JSGLOBAL_OBJECT = "window"; +const char* JSHOOK_NAME = "jsHook"; +} + +namespace JavaScriptFunctions { +//options +class_definition_options_t jsHookfunctionsOptions = { + JS_FUNCTION, + CREATE_INSTANCE, + NONE_NOTICE, + USE_OVERLAYED, //ignored + NULL, + NULL, + reinterpret_cast<js_function_impl>(JSCFunctions::JavaScriptHookProc) +}; + +class_definition_options_t jsPrintfunctionsOptions = { + JS_FUNCTION, + CREATE_INSTANCE, + NONE_NOTICE, + USE_OVERLAYED, //ignored + NULL, + NULL, + reinterpret_cast<js_function_impl>(JSCFunctions::JavaScriptPrintProc) +}; + +js_entity_definition_t jsPrint = { + JSGLOBAL_OBJECT, + JSPRINT_NAME, + "", + NULL, + NULL, + &jsPrintfunctionsOptions +}; + +js_entity_definition_t jsHook = { + JSGLOBAL_OBJECT, + JSHOOK_NAME, + "", + NULL, + NULL, + &jsHookfunctionsOptions +}; + +const js_entity_definition_ptr_t jsPrintPtr = &jsPrint; +const js_entity_definition_ptr_t jsHookPtr = &jsHook; +} + +bool JsFunctionManager::initialize() +{ + WrtLogD("JSObjectDeclaration for js functions are intialized"); + JSObjectDeclarationPtr jsPrintObj( + new JSObjectDeclaration(JavaScriptFunctions::jsPrintPtr)); + + JSObjectDeclarationPtr jsHookObj( + new JSObjectDeclaration(JavaScriptFunctions::jsHookPtr)); + + m_functions.push_back(jsPrintObj); + m_functions.push_back(jsHookObj); + + return true; +} + +JsFunctionManager::Functions JsFunctionManager::getFunctions() +{ + WrtLogD("get standard js fucntions"); + static bool initialized = initialize(); + (void) initialized; + return m_functions; +} diff --git a/src/js-overlay/js_function_manager.h b/src/js-overlay/js_function_manager.h new file mode 100644 index 0000000..d6bd80e --- /dev/null +++ b/src/js-overlay/js_function_manager.h @@ -0,0 +1,55 @@ +/* + * 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_function_manager.h + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ + +#ifndef WRT_SRC_PLUGIN_SERVICE_JS_FUNCTION_MANGER_H_ +#define WRT_SRC_PLUGIN_SERVICE_JS_FUNCTION_MANGER_H_ + +#include <list> +#include <dpl/noncopyable.h> +#include <dpl/singleton.h> + +#include <Commons/JSObjectDeclaration.h> + +class JsFunctionManager : private DPL::Noncopyable +{ + public: + typedef std::list<JSObjectDeclarationPtr> Functions; + + public: + Functions getFunctions(); + + private: + JsFunctionManager() + {} + + bool initialize(); + + private: + Functions m_functions; + + friend class DPL::Singleton<JsFunctionManager>; +}; + +typedef DPL::Singleton<JsFunctionManager> JsFunctionManagerSingleton; + +#endif + diff --git a/src/js-overlay/js_overlay_functions.cpp b/src/js-overlay/js_overlay_functions.cpp new file mode 100644 index 0000000..0928ba5 --- /dev/null +++ b/src/js-overlay/js_overlay_functions.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 javascript_functions.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ + +#include <memory> +#include <string> +#include <dpl/log/wrt_log.h> +#include <js_overlay_functions.h> + +namespace JSCFunctions { +std::string ConvertJSStringToStdString(JSStringRef value) +{ + int nSize = JSStringGetLength(value) + 1; + std::unique_ptr<char[]> textStr(new char[nSize]); + JSStringGetUTF8CString(value, textStr.get(), nSize); + std::string ret = textStr.get(); + return ret; +} + +JSValueRef JavaScriptPrintProc(JSContextRef context, + JSObjectRef /*object*/, + JSObjectRef /*thisObject*/, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + if (argumentCount == 0 || !JSValueIsString(context, arguments[0])) { + WrtLogE("Argument is not string"); + return JSValueMakeUndefined(context); + } + + JSStringRef textRef = JSValueToStringCopy(context, arguments[0], exception); + int nSize = JSStringGetLength(textRef) + 1; + + std::unique_ptr<char[]> textStr(new char[nSize]); + + JSStringGetUTF8CString(textRef, textStr.get(), nSize); + WrtLogD("\033[00;35m[jsPrint] %s\033[00m", textStr.get()); + + JSStringRelease(textRef); + return JSValueMakeBoolean(context, true); +} + +JSValueRef JavaScriptHookProc( + JSContextRef context, + JSObjectRef /*object*/, + JSObjectRef /*thisObject*/, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + bool inError = false; + if (argumentCount < 2 || + argumentCount > 3 || + !JSValueIsString(context, arguments[0]) || + !JSValueIsString(context, arguments[1])) + { + inError = true; + } + + if (inError) { + WrtLogE("*********************************************"); + WrtLogE("*********************************************"); + WrtLogE("Cannot print test Result"); + WrtLogE("*********************************************"); + WrtLogE("*********************************************"); + return JSValueMakeUndefined(context); + } + + std::string id, result, message; + JSStringRef idRef = JSValueToStringCopy(context, arguments[0], exception); + id = ConvertJSStringToStdString(idRef); + JSStringRelease(idRef); + JSStringRef idResult = JSValueToStringCopy(context, + arguments[1], + exception); + result = ConvertJSStringToStdString(idResult); + JSStringRelease(idResult); + + if (argumentCount == 3 && !JSValueIsString(context, arguments[2])) { + JSStringRef idMessage = JSValueToStringCopy(context, + arguments[0], + exception); + message = ConvertJSStringToStdString(idMessage); + JSStringRelease(idMessage); + } + + WrtLogD("\033[00;35m***********************************************\033[00m"); + WrtLogD("\033[00;35m***********************************************\033[00m"); + WrtLogD("\033[00;35m TEST ID: %s\033[00m", id.c_str()); + WrtLogD("\033[00;35m RESULT: %s\033[00m", result.c_str()); + WrtLogD("\033[00;35m MESSAGE: %s\033[00m", message.c_str()); + WrtLogD("\033[00;35m***********************************************\033[00m"); + WrtLogD("\033[00;35m***********************************************\033[00m"); + + return JSValueMakeBoolean(context, true); +} +} diff --git a/src/js-overlay/js_overlay_functions.h b/src/js-overlay/js_overlay_functions.h new file mode 100644 index 0000000..3c7f86a --- /dev/null +++ b/src/js-overlay/js_overlay_functions.h @@ -0,0 +1,46 @@ +/* + * 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 javascript_functions.h + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ + +#ifndef WRT_SRC_PLUGIN_SERVICE_EFL_JAVASCRIPT_FUNCTIONS_H_ +#define WRT_SRC_PLUGIN_SERVICE_EFL_JAVASCRIPT_FUNCTIONS_H_ + +#include <JavaScriptCore/JavaScript.h> + +namespace JSCFunctions { +JSValueRef JavaScriptPrintProc( + JSContextRef context, + JSObjectRef /*object*/, + JSObjectRef /*thisObject*/, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef * exception); +JSValueRef JavaScriptHookProc( + JSContextRef context, + JSObjectRef /*object*/, + JSObjectRef /*thisObject*/, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef * exception); +} + +#endif + diff --git a/src/js-overlay/js_overlay_types.h b/src/js-overlay/js_overlay_types.h new file mode 100644 index 0000000..e47634f --- /dev/null +++ b/src/js-overlay/js_overlay_types.h @@ -0,0 +1,52 @@ +/* + * 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_overlay_types.h + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _WRT_PLUGINS_JS_OVERLAY_TYPES_H_ +#define _WRT_PLUGINS_JS_OVERLAY_TYPES_H_ + +#include <string> + +namespace WrtPlugins { +namespace W3C { +// If needed, enum for new custom event should be defined here +enum CustomEventType { + StorageCustomEvent, + ServiceCustomEvent, + SoftKeyboardChangeCustomEvent, +}; + +// Argument structure of SoftKeyboardChangeCustomEvent +typedef struct SoftKeyboardChangeArgs { + std::string state; // value is 'on' or 'off' + int width; + int height; + SoftKeyboardChangeArgs() : + width(0), + height(0) + {} +} SoftKeyboardChangeArgs; + +// If needed, argument structure of other custom events should be defined here +} // W3C +} // WrtPlugins +#endif // _WRT_PLUGINS_JS_OVERLAY_TYPES_H_ diff --git a/src/modules/API/CMakeLists.txt b/src/modules/API/CMakeLists.txt new file mode 100644 index 0000000..f8290dd --- /dev/null +++ b/src/modules/API/CMakeLists.txt @@ -0,0 +1,21 @@ +# 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_CONFIG_FILE(Widget) +INCLUDE_CONFIG_FILE(LocalStorage) +INCLUDE_CONFIG_FILE(WidgetDB) +INCLUDE_CONFIG_FILE(PluginManager) +INCLUDE_CONFIG_FILE(StorageEvent) +INCLUDE_CONFIG_FILE(TizenServiceEvent) +INCLUDE_CONFIG_FILE(SoftKeyboardChangeEvent) diff --git a/src/modules/API/DESCRIPTION b/src/modules/API/DESCRIPTION new file mode 100644 index 0000000..76eb35c --- /dev/null +++ b/src/modules/API/DESCRIPTION @@ -0,0 +1,2 @@ +!!!options!!! stop +Platform independent platform API diff --git a/src/modules/API/LocalStorage/ILocalStorage.h b/src/modules/API/LocalStorage/ILocalStorage.h new file mode 100644 index 0000000..9edced1 --- /dev/null +++ b/src/modules/API/LocalStorage/ILocalStorage.h @@ -0,0 +1,93 @@ +/* + * 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) + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief Local storage interface file + */ + +#ifndef WRTDEVICEAPIS_LOCALSTORAGE_LOCAL_STORAGE_INTERFACE_H_ +#define WRTDEVICEAPIS_LOCALSTORAGE_LOCAL_STORAGE_INTERFACE_H_ + +#include <string> +#include <memory> +#include <dpl/optional_typedefs.h> + +namespace WrtDeviceApis { +namespace LocalStorage { +namespace Api { +class ILocalStorage +{ + public: + + /** + * Save pair key/value in local storage + * @param key + * @param value + * @param readOnly - if true, the value will be read only + * otherwise the value will be modificable + */ + virtual void setItem(const std::string& key, + const std::string& value, + bool readOnly) = 0; + + /** + * Remove pair key/value from local storage + */ + virtual void removeItem(const std::string& key) = 0; + + /** + * Get value for key + * + */ + virtual DPL::OptionalStdString getValue( + const std::string& key) const = 0; + + /** + * Clears the local storage + * @param removeReadOnly - true -remove all elements + * false - ommit items which have read only flag + * set + */ + virtual void clear(bool removeReadOnly) = 0; + + /** + * Get number of elements in local storage + * @param removeReadOnly - true -remove all elements + * false - ommit items which have read only flag + * set + */ + virtual size_t getStorageSize() const = 0; + + /** + * Get key name for index + */ + virtual std::string getKeyByIndex(size_t index) const = 0; + + /** + * virtual destructor + */ + virtual ~ILocalStorage() + {} +}; + +typedef std::shared_ptr<ILocalStorage> ILocalStoragePtr; +} // Api +} // LocalStorage +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_LOCALSTORAGE_LOACA_STORAGE_INTERFACE_H_ diff --git a/src/modules/API/LocalStorage/LocalStorageMgr.cpp b/src/modules/API/LocalStorage/LocalStorageMgr.cpp new file mode 100644 index 0000000..3b44023 --- /dev/null +++ b/src/modules/API/LocalStorage/LocalStorageMgr.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 LocalStorageMgr.cpp + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief + */ +#include "LocalStorageMgr.h" +#include <WidgetInterface/WidgetInterface.h> + +namespace WrtDeviceApis { +namespace LocalStorage { +namespace Api { +ILocalStoragePtr getLocalStorage(WidgetHandle widgetId) +{ + return ILocalStoragePtr(new WrtDeviceApis::WidgetInterfaceObject(widgetId)); +} +} // Api +} // LocalStorage +} // WrtDeviceApis diff --git a/src/modules/API/LocalStorage/LocalStorageMgr.h b/src/modules/API/LocalStorage/LocalStorageMgr.h new file mode 100644 index 0000000..1366b54 --- /dev/null +++ b/src/modules/API/LocalStorage/LocalStorageMgr.h @@ -0,0 +1,38 @@ +/* + * 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 LocalStorageMgr.h + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRTDEVICEAPIS_LOCALSTORAGE_LOCAL_STORAGE_FACTORY_H +#define WRTDEVICEAPIS_LOCALSTORAGE_LOCAL_STORAGE_FACTORY_H + +#include <LocalStorage/ILocalStorage.h> +#include <dpl/wrt-dao-ro/wrt_db_types.h> + +namespace WrtDeviceApis { +namespace LocalStorage { +namespace Api { +ILocalStoragePtr getLocalStorage(WidgetHandle widgetId); +} // Api +} // LocalStorage +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_LOCALSTORAGE_LOCAL_STORAGE_FACTORY_H + diff --git a/src/modules/API/LocalStorage/config.cmake b/src/modules/API/LocalStorage/config.cmake new file mode 100644 index 0000000..f421686 --- /dev/null +++ b/src/modules/API/LocalStorage/config.cmake @@ -0,0 +1,11 @@ +get_current_path() + +set(API_LOCALSTORAGE_PATH + ${CURRENT_PATH} + PARENT_SCOPE + ) + +set(SRCS_API_LOCALSTORAGE + ${CURRENT_PATH}/LocalStorageMgr.cpp + PARENT_SCOPE +) diff --git a/src/modules/API/PluginManager/IPluginManager.h b/src/modules/API/PluginManager/IPluginManager.h new file mode 100644 index 0000000..cd925a3 --- /dev/null +++ b/src/modules/API/PluginManager/IPluginManager.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. + */ +/* + * @file IPluginManager.h + * @author Lukasz Marek (l.marek@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRTDEVICEAPIS_PLUGINMANAGER_IPLUGINMANAGER_H_ +#define WRTDEVICEAPIS_PLUGINMANAGER_IPLUGINMANAGER_H_ + +#include <string> +#include <vector> +#include <memory> +#include <JavaScriptCore/JavaScript.h> + +namespace WrtDeviceApis { +namespace PluginManager { +namespace Api { +class IPluginManager +{ + public: + typedef std::vector<std::string> PropertyList; + + virtual ~IPluginManager() {} + virtual bool hasChild(const std::string &name) const = 0; + virtual bool loadChild(const std::string &name) const = 0; + + virtual JSValueRef getProperty(const std::string &name) const = 0; + virtual bool setProperty(const std::string &name, + JSValueRef value) = 0; + virtual bool deleteProperty(const std::string &name) = 0; + + virtual PropertyList getProperties() const = 0; + virtual void addPropertiesToList( + JSPropertyNameAccumulatorRef propertyNames) const = 0; +}; + +typedef std::shared_ptr<IPluginManager> IPluginManagerPtr; +} +} +} + +#endif // WRTDEVICEAPIS_PLUGINMANAGER_IPLUGINMANAGER_H_ diff --git a/src/modules/API/PluginManager/PluginManagerFactory.cpp b/src/modules/API/PluginManager/PluginManagerFactory.cpp new file mode 100644 index 0000000..1a82948 --- /dev/null +++ b/src/modules/API/PluginManager/PluginManagerFactory.cpp @@ -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. + */ + +/** + * @file PluginManagerFactory.cpp + * @author Lukasz Marek (l.marek@samsung.com) + * @version 0.1 + */ + +#include "PluginManagerFactory.h" +#include <PluginManager/PluginManager.h> + +namespace WrtDeviceApis { +namespace PluginManager { +namespace Api { +PluginManagerFactory::PluginManagerFactory() +{} + +PluginManagerFactory& PluginManagerFactory::getInstance() +{ + static PluginManagerFactory instance; + return instance; +} + +IPluginManagerPtr PluginManagerFactory::getPluginManager( + WidgetHandle widgetHandle, + const std::string &objectUri, + JSObjectRef object, + JSContextRef context) const +{ + return IPluginManagerPtr( + new PluginManager(widgetHandle, objectUri, object, context)); +} +} +} +} diff --git a/src/modules/API/PluginManager/PluginManagerFactory.h b/src/modules/API/PluginManager/PluginManagerFactory.h new file mode 100644 index 0000000..03e3fb6 --- /dev/null +++ b/src/modules/API/PluginManager/PluginManagerFactory.h @@ -0,0 +1,51 @@ +/* + * 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 PluginManagerFactory.h + * @author Lukasz Marek (l.marek@samsung.com) + * @version 0.1 + */ + +#ifndef WRTDEVICEAPIS_PLUGIN_MANAGER_FACTORY_H_ +#define WRTDEVICEAPIS_PLUGIN_MANAGER_FACTORY_H_ + +#include <string> +#include <dpl/noncopyable.h> +#include <PluginManager/IPluginManager.h> +#include <dpl/wrt-dao-ro/wrt_db_types.h> + +namespace WrtDeviceApis { +namespace PluginManager { +namespace Api { +class PluginManagerFactory : private DPL::Noncopyable +{ + public: + static PluginManagerFactory& getInstance(); + IPluginManagerPtr getPluginManager( + WidgetHandle widgetHandle, + const std::string &objectUri, + JSObjectRef object, + JSContextRef context) const; + + private: + PluginManagerFactory(); +}; +} +} +} + +#endif // WRTDEVICEAPIS_PLUGIN_MANAGER_FACTORY_H_ diff --git a/src/modules/API/PluginManager/config.cmake b/src/modules/API/PluginManager/config.cmake new file mode 100644 index 0000000..f513d08 --- /dev/null +++ b/src/modules/API/PluginManager/config.cmake @@ -0,0 +1,11 @@ +get_current_path() + +set(API_PLUGIN_MANAGER_PATH + ${CURRENT_PATH} + PARENT_SCOPE +) + +set(SRCS_API_PLUGIN_MANAGER + ${CURRENT_PATH}/PluginManagerFactory.cpp + PARENT_SCOPE +) diff --git a/src/modules/API/SoftKeyboardChangeEvent/ISoftKeyboardChangeEvent.h b/src/modules/API/SoftKeyboardChangeEvent/ISoftKeyboardChangeEvent.h new file mode 100644 index 0000000..a001b71 --- /dev/null +++ b/src/modules/API/SoftKeyboardChangeEvent/ISoftKeyboardChangeEvent.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2012 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 ISoftKeyboardChangeEvent.h + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 0.1 + * @brief softkeyboardchange event interfece + */ + +#ifndef WRT_PLUGIN_SOFTKEYBOARD_CHANGE_EVENT_INTERFACE_H +#define WRT_PLUGIN_SOFTKEYBOARD_CHANGE_EVENT_INTERFACE_H + +#include <memory> + +namespace WrtDeviceApis { +namespace SoftKeyboardChangeEvent { +namespace Api { +class ISoftKeyboardChangeEvent +{ + public: + virtual std::string getState() const = 0; + virtual int getWidth() const = 0; + virtual int getHeight() const = 0; + + virtual ~ISoftKeyboardChangeEvent() {} +}; + +typedef std::shared_ptr<ISoftKeyboardChangeEvent> ISoftKeyboardChangeEventPtr; +} // Api +} // SoftKeyboardChangeEvent +} // WrtDeviceApis + +#endif // WRT_PLUGIN_SOFTKEYBOARD_CHANGE_EVENT_INTERFACE_H diff --git a/src/modules/API/SoftKeyboardChangeEvent/SoftKeyboardChangeEvent.cpp b/src/modules/API/SoftKeyboardChangeEvent/SoftKeyboardChangeEvent.cpp new file mode 100644 index 0000000..7cd04ba --- /dev/null +++ b/src/modules/API/SoftKeyboardChangeEvent/SoftKeyboardChangeEvent.cpp @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2012 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 SoftKeyboardChangeEvent.cpp + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 0.1 + * @brief softkeyboardchange event class implementation + */ + +#include "SoftKeyboardChangeEvent.h" + +namespace WrtDeviceApis { +namespace SoftKeyboardChangeEvent { +namespace Api { +SoftKeyboardChangeEvent::SoftKeyboardChangeEvent( + std::string state, int width, int height) : + m_state(state), m_width(width), m_height(height) +{} + +SoftKeyboardChangeEvent::~SoftKeyboardChangeEvent() +{} + +std::string SoftKeyboardChangeEvent::getState() const +{ + return m_state; +} + +int SoftKeyboardChangeEvent::getWidth() const +{ + return m_width; +} + +int SoftKeyboardChangeEvent::getHeight() const +{ + return m_height; +} +} // Api +} // SoftKeyboardChangeEvent +} // WrtDeviceApis diff --git a/src/modules/API/SoftKeyboardChangeEvent/SoftKeyboardChangeEvent.h b/src/modules/API/SoftKeyboardChangeEvent/SoftKeyboardChangeEvent.h new file mode 100644 index 0000000..df8f721 --- /dev/null +++ b/src/modules/API/SoftKeyboardChangeEvent/SoftKeyboardChangeEvent.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2012 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 SoftKeyboardChangeEvent.h + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 0.1 + * @brief softkeyboardchange event class + */ + +#ifndef WRT_PLUGIN_SOFTKEYBOARD_CHANGE_EVENT_CLASS_H +#define WRT_PLUGIN_SOFTKEYBOARD_CHANGE_EVENT_CLASS_H + +#include <string> +#include "ISoftKeyboardChangeEvent.h" + +namespace WrtDeviceApis { +namespace SoftKeyboardChangeEvent { +namespace Api { +class SoftKeyboardChangeEvent : public ISoftKeyboardChangeEvent +{ + public: + explicit SoftKeyboardChangeEvent( + std::string state, + int width, + int height); + ~SoftKeyboardChangeEvent(); + + std::string getState() const; + int getWidth() const; + int getHeight() const; + + private: + std::string m_state; + int m_width; + int m_height; +}; +} // Api +} // SoftKeyboardChangeEvent +} // WrtDeviceApis + +#endif // WRT_PLUGIN_SOFTKEYBOARD_CHANGE_EVENT_CLASS_H diff --git a/src/modules/API/SoftKeyboardChangeEvent/config.cmake b/src/modules/API/SoftKeyboardChangeEvent/config.cmake new file mode 100644 index 0000000..398a39b --- /dev/null +++ b/src/modules/API/SoftKeyboardChangeEvent/config.cmake @@ -0,0 +1,11 @@ +get_current_path() + +set(API_SOFTKEYBOARD_CHANGE_EVENT_PATH + ${CURRENT_PATH} + PARENT_SCOPE + ) + +set(SRCS_API_SOFTKEYBOARD_CHANGE_EVENT + ${CURRENT_PATH}/SoftKeyboardChangeEvent.cpp + PARENT_SCOPE +) diff --git a/src/modules/API/StorageEvent/IStorageEvent.h b/src/modules/API/StorageEvent/IStorageEvent.h new file mode 100644 index 0000000..d98924a --- /dev/null +++ b/src/modules/API/StorageEvent/IStorageEvent.h @@ -0,0 +1,57 @@ +/* + * 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 IStorageEvent.h + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief Storage event interfece + */ + +#ifndef WRTDEVICEAPIS_COMMONS_STORAGE_EVENT_INTERFACE_H +#define WRTDEVICEAPIS_COMMONS_STORAGE_EVENT_INTERFACE_H + +#include <dpl/optional_typedefs.h> +#include <memory> +#include <LocalStorage/ILocalStorage.h> + +namespace WrtDeviceApis { +namespace StorageEvent { +namespace Api { +class IStorageEvent +{ + public: + + virtual std::string getKey() const = 0; + virtual DPL::OptionalString getOldValue() const = 0; + virtual DPL::OptionalString getNewValue() const = 0; + virtual std::string getUrl() const = 0; + virtual LocalStorage::Api::ILocalStoragePtr getStorageArea() const = 0; + + virtual void setKey(const std::string &inKey) = 0; + virtual void setOldValue(const std::string &inValue) = 0; + virtual void setNewValue(const std::string &inValue) = 0; + virtual void setUrl(const std::string &inUrl) = 0; + virtual void setStorageArea( + const LocalStorage::Api::ILocalStoragePtr &inStorageArea) = 0; +}; + +typedef std::shared_ptr<IStorageEvent> IStorageEventPtr; +} // Api +} // StorageEvent +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_COMMONS_STORAGE_EVENT_INTERFACE_H diff --git a/src/modules/API/StorageEvent/StorageEvent.cpp b/src/modules/API/StorageEvent/StorageEvent.cpp new file mode 100644 index 0000000..e9a0beb --- /dev/null +++ b/src/modules/API/StorageEvent/StorageEvent.cpp @@ -0,0 +1,87 @@ +/* + * 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 StorageEvent.cpp + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief Storage event class implementation + */ + +#include "StorageEvent.h" + +namespace WrtDeviceApis { +namespace StorageEvent { +namespace Api { +StorageEvent::StorageEvent() : + m_storageArea() {} + +StorageEvent::StorageEvent( + const LocalStorage::Api::ILocalStoragePtr &storageArea) : + m_storageArea(storageArea) {} + +std::string StorageEvent::getKey() const +{ + return m_key; +} + +DPL::OptionalString StorageEvent::getOldValue() const +{ + return m_oldValue; +} + +DPL::OptionalString StorageEvent::getNewValue() const +{ + return m_newValue; +} +std::string StorageEvent::getUrl() const +{ + return m_url; +} + +LocalStorage::Api::ILocalStoragePtr StorageEvent::getStorageArea() const +{ + return m_storageArea; +} + +void StorageEvent::setKey(const std::string &inKey) +{ + m_key = inKey; +} + +void StorageEvent::setOldValue(const std::string &inValue) +{ + m_oldValue = DPL::FromUTF8String(inValue); +} + +void StorageEvent::setNewValue(const std::string &inValue) +{ + m_newValue = DPL::FromUTF8String(inValue); +} + +void StorageEvent::setUrl(const std::string &inUrl) +{ + m_url = inUrl; +} + +void StorageEvent::setStorageArea( + const LocalStorage::Api::ILocalStoragePtr &inStorageArea) +{ + m_storageArea = inStorageArea; +} +} // Api +} // StorageEvent +} // WrtDeviceApis diff --git a/src/modules/API/StorageEvent/StorageEvent.h b/src/modules/API/StorageEvent/StorageEvent.h new file mode 100644 index 0000000..37df421 --- /dev/null +++ b/src/modules/API/StorageEvent/StorageEvent.h @@ -0,0 +1,65 @@ +/* + * 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 StorageEvent.h + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief Storage event class + */ + +#ifndef WRTDEVICEAPIS_STORAGEEVENT_STORAGE_EVENT_H +#define WRTDEVICEAPIS_STORAGEEVENT_STORAGE_EVENT_H + +#include <dpl/optional_typedefs.h> +#include "IStorageEvent.h" + +namespace WrtDeviceApis { +namespace StorageEvent { +namespace Api { +class StorageEvent : public IStorageEvent +{ + public: + + StorageEvent(); + explicit StorageEvent( + const LocalStorage::Api::ILocalStoragePtr &storageArea); + + std::string getKey() const; + DPL::OptionalString getOldValue() const; + DPL::OptionalString getNewValue() const; + std::string getUrl() const; + LocalStorage::Api::ILocalStoragePtr getStorageArea() const; + + void setKey(const std::string &inKey); + void setOldValue(const std::string &inValue); + void setNewValue(const std::string &inValue); + void setUrl(const std::string &inUrl); + void setStorageArea( + const LocalStorage::Api::ILocalStoragePtr &inStorageArea); + + private: + std::string m_key; + DPL::OptionalString m_oldValue; + DPL::OptionalString m_newValue; + std::string m_url; + LocalStorage::Api::ILocalStoragePtr m_storageArea; +}; +} // Api +} // StorageEvent +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_STORAGEEVENT_STORAGE_EVENT_H diff --git a/src/modules/API/StorageEvent/StorageEventMgr.cpp b/src/modules/API/StorageEvent/StorageEventMgr.cpp new file mode 100644 index 0000000..92b8772 --- /dev/null +++ b/src/modules/API/StorageEvent/StorageEventMgr.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 StorageEventMgr.cpp + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief Storage event getter + */ + +#include "StorageEventMgr.h" +#include "StorageEvent.h" + +namespace WrtDeviceApis { +namespace StorageEvent { +namespace Api { +IStorageEventPtr getStorageEvent() +{ + return IStorageEventPtr(new StorageEvent()); +} +} // Api +} // StorageEvent +} // WrtDeviceApis diff --git a/src/modules/API/StorageEvent/StorageEventMgr.h b/src/modules/API/StorageEvent/StorageEventMgr.h new file mode 100644 index 0000000..b519abd --- /dev/null +++ b/src/modules/API/StorageEvent/StorageEventMgr.h @@ -0,0 +1,38 @@ +/* + * 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 StorageEventMgr.h + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief Storage event interfece + */ + +#ifndef WRTDEVICEAPIS_COMMONS_STORAGE_EVENT_MGR_H +#define WRTDEVICEAPIS_COMMONS_STORAGE_EVENT_MGR_H + +#include "IStorageEvent.h" + +namespace WrtDeviceApis { +namespace StorageEvent { +namespace Api { +IStorageEventPtr getStorageEvent(); +} // Api +} // StorageEvent +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_COMMONS_STORAGE_EVENT_MGR_H + diff --git a/src/modules/API/StorageEvent/config.cmake b/src/modules/API/StorageEvent/config.cmake new file mode 100644 index 0000000..a0029fc --- /dev/null +++ b/src/modules/API/StorageEvent/config.cmake @@ -0,0 +1,12 @@ +get_current_path() + +set(API_STORAGE_EVENT_PATH + ${CURRENT_PATH} + PARENT_SCOPE + ) + +set(SRCS_API_STORAGE_EVENT + ${CURRENT_PATH}/StorageEventMgr.cpp + ${CURRENT_PATH}/StorageEvent.cpp + PARENT_SCOPE +) diff --git a/src/modules/API/TizenServiceEvent/ITizenServiceEvent.h b/src/modules/API/TizenServiceEvent/ITizenServiceEvent.h new file mode 100644 index 0000000..4a77e0c --- /dev/null +++ b/src/modules/API/TizenServiceEvent/ITizenServiceEvent.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. + */ +/** + * + * @file ITizenServiceEvent.h + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 0.1 + * @brief Tizen Service event interfece + */ + +#ifndef _WRT_PLUGIN_TIZEN_SERVICE_EVENT_INTERFACE_H_ +#define _WRT_PLUGIN_TIZEN_SERVICE_EVENT_INTERFACE_H_ + +#include <string> +#include <memory> + +namespace WrtDeviceApis { +namespace TizenServiceEvent { +namespace Api { +class ITizenServiceEvent +{ + public: + virtual float getScale() const = 0; + virtual std::string getBundle() const = 0; + + virtual void setScale(const float scale) = 0; + virtual void setBundle(const std::string &bundle) = 0; + virtual ~ITizenServiceEvent() {} +}; + +typedef std::shared_ptr<ITizenServiceEvent> ITizenServiceEventPtr; +} // Api +} // TizenServiceEvent +} // WrtDeviceApis + +#endif // _WRT_PLUGIN_TIZEN_SERVICE_EVENT_INTERFACE_H_ diff --git a/src/modules/API/TizenServiceEvent/TizenServiceEvent.cpp b/src/modules/API/TizenServiceEvent/TizenServiceEvent.cpp new file mode 100644 index 0000000..b6233c6 --- /dev/null +++ b/src/modules/API/TizenServiceEvent/TizenServiceEvent.cpp @@ -0,0 +1,57 @@ +/* + * 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 TizenServiceEvent.cpp + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 0.1 + * @brief Tizen appservice event class implementation + */ + +#include "TizenServiceEvent.h" + +namespace WrtDeviceApis { +namespace TizenServiceEvent { +namespace Api { +TizenServiceEvent::TizenServiceEvent() : + m_scale(0) +{} + +TizenServiceEvent::~TizenServiceEvent() +{} + +float TizenServiceEvent::getScale() const +{ + return m_scale; +} + +std::string TizenServiceEvent::getBundle() const +{ + return m_bundle; +} + +void TizenServiceEvent::setScale(const float scale) +{ + m_scale = scale; +} + +void TizenServiceEvent::setBundle(const std::string& bundle) +{ + m_bundle = bundle; +} +} // Api +} // TizenServiceEvent +} // WrtDeviceApis diff --git a/src/modules/API/TizenServiceEvent/TizenServiceEvent.h b/src/modules/API/TizenServiceEvent/TizenServiceEvent.h new file mode 100644 index 0000000..3b577f0 --- /dev/null +++ b/src/modules/API/TizenServiceEvent/TizenServiceEvent.h @@ -0,0 +1,54 @@ +/* + * 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 TizenServiceEvent.h + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 0.1 + * @brief Tizen Service event class + */ + +#ifndef _WRT_PLUGIN_TIZEN_SERVICE_EVENT_CLASS_H_ +#define _WRT_PLUGIN_TIZEN_SERVICE_EVENT_CLASS_H_ + +#include <string> +#include "ITizenServiceEvent.h" + +namespace WrtDeviceApis { +namespace TizenServiceEvent { +namespace Api { +class TizenServiceEvent : public ITizenServiceEvent +{ + public: + + TizenServiceEvent(); + ~TizenServiceEvent(); + + float getScale() const; + std::string getBundle() const; + + void setScale(const float scale); + void setBundle(const std::string &bundle); + + private: + float m_scale; + std::string m_bundle; +}; +} // Api +} // TizenServiceEvent +} // WrtDeviceApis + +#endif // _WRT_PLUGIN_TIZEN_SERVICE_EVENT_CLASS_H_ diff --git a/src/modules/API/TizenServiceEvent/config.cmake b/src/modules/API/TizenServiceEvent/config.cmake new file mode 100644 index 0000000..5a64dcd --- /dev/null +++ b/src/modules/API/TizenServiceEvent/config.cmake @@ -0,0 +1,11 @@ +get_current_path() + +set(API_TIZEN_SERVICE_EVENT_PATH + ${CURRENT_PATH} + PARENT_SCOPE + ) + +set(SRCS_API_TIZEN_SERVICE_EVENT + ${CURRENT_PATH}/TizenServiceEvent.cpp + PARENT_SCOPE +) diff --git a/src/modules/API/Widget/IWidget.h b/src/modules/API/Widget/IWidget.h new file mode 100644 index 0000000..608dc4e --- /dev/null +++ b/src/modules/API/Widget/IWidget.h @@ -0,0 +1,128 @@ +/* + * 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 IWidget.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef INTERFACE_WIDGET_CONFIG_INFO_H +#define INTERFACE_WIDGET_CONFIG_INFO_H + +#include <string> + +#include <memory> + +namespace WrtDeviceApis { +namespace Widget { +namespace Api { +class IWidget; +typedef std::shared_ptr<IWidget> IWidgetPtr; + +class IWidget +{ + public: // methods + + /** + * getter for property from widget config xml + * @throw Commons::PlatformException if problem with platform occured + * @throw Commons::NullPointerException if problem with platform occured + * @throw Commons::SecurityException if wrt forbiden using this function + * */ + virtual std::string getAuthor() const = 0; + + /** + * getter for property from widget config xml + * @throw Commons::PlatformException if problem with platform occured + * @throw Commons::NullPointerException if problem with platform occured + * @throw Commons::SecurityException if wrt forbiden using this function + * */ + virtual std::string getAuthorEmail() const = 0; + + /** + * getter for property from widget config xml + * @throw Commons::PlatformException if problem with platform occured + * @throw Commons::NullPointerException if problem with platform occured + * @throw Commons::SecurityException if wrt forbiden using this function + * */ + virtual std::string getAuthorHref() const = 0; + + /** + * getter for property from widget config xml + * @throw Commons::PlatformException if problem with platform occured + * @throw Commons::NullPointerException if problem with platform occured + * @throw Commons::SecurityException if wrt forbiden using this function + * */ + virtual std::string getDescription() const = 0; + + /** + * getter for property from widget config xml + * @throw Commons::PlatformException if problem with platform occured + * @throw Commons::NullPointerException if problem with platform occured + * @throw Commons::SecurityException if wrt forbiden using this function + * */ + virtual std::string getId() const = 0; + + /** + * getter for property from widget config xml + * @throw Commons::PlatformException if problem with platform occured + * @throw Commons::NullPointerException if problem with platform occured + * @throw Commons::SecurityException if wrt forbiden using this function + * */ + virtual std::string getName() const = 0; + + /** + * getter for property from widget config xml + * @throw Commons::PlatformException if problem with platform occured + * @throw Commons::NullPointerException if problem with platform occured + * @throw Commons::SecurityException if wrt forbiden using this function + * */ + virtual std::string getShortName() const = 0; + + /** + * getter for property from widget config xml + * @throw Commons::PlatformException if problem with platform occured + * @throw Commons::NullPointerException if problem with platform occured + * @throw Commons::SecurityException if wrt forbiden using this function + * */ + virtual std::string getVersion() const = 0; + + /** + * getter for property from widget config xml + * @throw Commons::PlatformException if problem with platform occured + * @throw Commons::NullPointerException if problem with platform occured + * @throw Commons::SecurityException if wrt forbiden using this function + * */ + virtual unsigned int getHeight() const = 0; + + /** + * getter for property from widget config xml + * @throw Commons::PlatformException if problem with platform occured + * @throw Commons::NullPointerException if problem with platform occured + * @throw Commons::SecurityException if wrt forbiden using this function + * */ + virtual unsigned int getWidth() const = 0; + + virtual ~IWidget() + {} +}; +} +} +} + +#endif diff --git a/src/modules/API/Widget/WidgetFactory.cpp b/src/modules/API/Widget/WidgetFactory.cpp new file mode 100644 index 0000000..2197a75 --- /dev/null +++ b/src/modules/API/Widget/WidgetFactory.cpp @@ -0,0 +1,37 @@ +/* + * 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 WidgetFactory.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ +#include "WidgetFactory.h" + +#include <Widget/Widget.h> + +namespace WrtDeviceApis { +namespace Widget { +namespace Api { +IWidgetPtr WidgetFactory::createWidget() +{ + return IWidgetPtr(new WrtDeviceApis::Widget::Widget()); +} +} +} +} diff --git a/src/modules/API/Widget/WidgetFactory.h b/src/modules/API/Widget/WidgetFactory.h new file mode 100644 index 0000000..b068dc2 --- /dev/null +++ b/src/modules/API/Widget/WidgetFactory.h @@ -0,0 +1,52 @@ +/* + * 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 WidgetFactory.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef _WIDGET_FACTORY_H +#define _WIDGET_FACTORY_H + +#include <string> +#include <dpl/noncopyable.h> +#include <Widget/IWidget.h> + +namespace WrtDeviceApis { +namespace Widget { +namespace Api { +class WidgetFactory : private DPL::Noncopyable +{ + public: + + /** + * Create widget + * @param[in] id of the widget + */ + static IWidgetPtr createWidget(); + + private: + WidgetFactory() + {} +}; +} +} +} + +#endif diff --git a/src/modules/API/Widget/config.cmake b/src/modules/API/Widget/config.cmake new file mode 100644 index 0000000..11ffcc8 --- /dev/null +++ b/src/modules/API/Widget/config.cmake @@ -0,0 +1,11 @@ +get_current_path() + +set(API_WIDGET_PATH + ${CURRENT_PATH} + PARENT_SCOPE +) + +set(SRCS_API_WIDGET + ${CURRENT_PATH}/WidgetFactory.cpp + PARENT_SCOPE +) diff --git a/src/modules/API/WidgetDB/IWidgetDB.h b/src/modules/API/WidgetDB/IWidgetDB.h new file mode 100644 index 0000000..218eb1e --- /dev/null +++ b/src/modules/API/WidgetDB/IWidgetDB.h @@ -0,0 +1,100 @@ +/* + * 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 IWidgetDB.h + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief Widget interface to access WRT DB + */ + +#ifndef WRTDEVICEAPIS_WIDGETDB_IWIDGETDB_H_ +#define WRTDEVICEAPIS_WIDGETDB_IWIDGETDB_H_ + +#include "IWidgetFeature.h" +#include <vector> +#include <memory> +#include <dpl/wrt-dao-ro/wrt_db_types.h> + +namespace WrtDeviceApis { +namespace WidgetDB { +namespace Api { +class IWidgetDB; +typedef std::shared_ptr<IWidgetDB> IWidgetDBPtr; + +typedef std::vector<IWidgetFeaturePtr> Features; + +enum class ConfigAttribute +{ + ID, + VERSION, + DESCRIPTION, + LICENSE, + LICENSE_HREF, + AUTHOR_NAME, + AUTHOR_HREF, + AUTHOR_EMAIL, + NAME, + SHORT_NAME, + ICON, + WIDTH, + HEIGHT, + INSTALL_PATH, + PUBLIC_STORAGE_PATH +}; + +enum class InstallationStatus +{ + STATUS_INSTALLED, + STATUS_LATEST, + STATUS_UNINSTALLED +}; + +class IWidgetDB +{ + public: + + virtual WidgetHandle getWidgetId() const = 0; + + virtual std::string getLanguage() const = 0; + + virtual std::string getConfigValue(ConfigAttribute attribute) const = 0; + + virtual std::string getUserAgent() const = 0; + + virtual InstallationStatus checkInstallationStatus( + const std::string& gid, + const std::string& name, + const std::string& version) const = 0; + + virtual Features getWidgetFeatures() const = 0; + + virtual Features getRegisteredFeatures() const = 0; + + virtual std::string getWidgetInstallationPath() const = 0; + + virtual std::string getWidgetPersistentStoragePath() const = 0; + + virtual std::string getWidgetTemporaryStoragePath() const = 0; + + virtual ~IWidgetDB() + {} +}; +} // Api +} // WidgetDB +} // WrtDeviceApis + +#endif + diff --git a/src/modules/API/WidgetDB/IWidgetFeature.h b/src/modules/API/WidgetDB/IWidgetFeature.h new file mode 100644 index 0000000..13360b2 --- /dev/null +++ b/src/modules/API/WidgetDB/IWidgetFeature.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 Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRT_PLUGINS_WRT_ENGINE_WIDGET_FEATURE_INTERFACE_H_ +#define WRT_PLUGINS_WRT_ENGINE_WIDGET_FEATURE_INTERFACE_H_ + +#include <list> +#include <string> +#include <memory> + +namespace WrtDeviceApis { +namespace WidgetDB { +namespace Api { +class IWidgetFeature +{ + public: + + virtual ~IWidgetFeature() + {} + + virtual std::string getName() const = 0; + + virtual bool isRequestedByWidget() const = 0; +}; + +typedef std::shared_ptr<IWidgetFeature> IWidgetFeaturePtr; +} // Api +} // WidgetDB +} // WrtDeviceApis + +#endif diff --git a/src/modules/API/WidgetDB/WidgetDBMgr.cpp b/src/modules/API/WidgetDB/WidgetDBMgr.cpp new file mode 100644 index 0000000..b8940c9 --- /dev/null +++ b/src/modules/API/WidgetDB/WidgetDBMgr.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 IWidgetDBMgr.cpp + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief + */ + +#include <WidgetDB/WidgetDB.h> +#include "IWidgetDB.h" +#include "WidgetDBMgr.h" + +namespace WrtDeviceApis { +namespace WidgetDB { +namespace Api { +IWidgetDBPtr getWidgetDB(WidgetHandle widgetId) +{ + return IWidgetDBPtr(new WrtDeviceApis::WidgetDB::WidgetDB(widgetId)); +} +} // Api +} // WidgetDB +} // WrtDeviceApis diff --git a/src/modules/API/WidgetDB/WidgetDBMgr.h b/src/modules/API/WidgetDB/WidgetDBMgr.h new file mode 100644 index 0000000..cdf24bc --- /dev/null +++ b/src/modules/API/WidgetDB/WidgetDBMgr.h @@ -0,0 +1,37 @@ +/* + * 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 IWidgetDB.h + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief Widget interface to access WRT DB + */ + +#ifndef WRTDEVICEAPIS_WIDGETDB_WIDGETDB_MGR_H +#define WRTDEVICEAPIS_WIDGETDB_WIDGETDB_MGR_H + +#include "IWidgetDB.h" + +namespace WrtDeviceApis { +namespace WidgetDB { +namespace Api { +IWidgetDBPtr getWidgetDB(WidgetHandle widgetId); +} // Api +} // WidgetDB +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_WIDGETDB_WIDGETDB_MGR_H + diff --git a/src/modules/API/WidgetDB/config.cmake b/src/modules/API/WidgetDB/config.cmake new file mode 100644 index 0000000..14a6acc --- /dev/null +++ b/src/modules/API/WidgetDB/config.cmake @@ -0,0 +1,12 @@ +get_current_path() + +set(API_WIDGETDB_PATH + ${CURRENT_PATH} + PARENT_SCOPE +) + +set(SRCS_API_WIDGETDB + ${CURRENT_PATH}/WidgetDBMgr.cpp + PARENT_SCOPE +) + diff --git a/src/modules/API/config.cmake b/src/modules/API/config.cmake new file mode 100644 index 0000000..82b25da --- /dev/null +++ b/src/modules/API/config.cmake @@ -0,0 +1,3 @@ +include_config_file(Widget)
+include_config_file(StorageEvent)
+include_config_file(LocalStorage)
\ No newline at end of file diff --git a/src/modules/CMakeLists.txt b/src/modules/CMakeLists.txt new file mode 100644 index 0000000..94f05f2 --- /dev/null +++ b/src/modules/CMakeLists.txt @@ -0,0 +1,22 @@ +# 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_DIRECTORIES( + ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_CURRENT_SOURCE_DIR}/${PLATFORM} +) + +ADD_SUBDIRECTORY(API) +ADD_SUBDIRECTORY(${PLATFORM}) +ADD_SUBDIRECTORY(packages) diff --git a/src/modules/DESCRIPTION b/src/modules/DESCRIPTION new file mode 100644 index 0000000..a5d1510 --- /dev/null +++ b/src/modules/DESCRIPTION @@ -0,0 +1 @@ +Platform abstraction diff --git a/src/modules/packages/CMakeLists.txt b/src/modules/packages/CMakeLists.txt new file mode 100644 index 0000000..b28b471 --- /dev/null +++ b/src/modules/packages/CMakeLists.txt @@ -0,0 +1,32 @@ +# 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. +# + +SET(TARGET_MODULE_WIDGET "wrt-plugins-widget") +SET(TARGET_MODULE_LOCALSTORAGE "wrt-plugins-localstorage") +SET(TARGET_MODULE_WIDGET_INTERFACE "wrt-plugins-widget-interface") +SET(TARGET_MODULE_STORAGEEVENT "wrt-plugins-storageevent") +SET(TARGET_MODULE_TIZEN_SERVICE_EVENT "wrt-plugins-tizen-service-event") +SET(TARGET_MODULE_SOFTKEYBOARD_CHANGE_EVENT "wrt-plugins-softkeyboardchange-event") +SET(TARGET_MODULE_WIDGETDB "wrt-plugins-widgetdb") +SET(TARGET_MODULE_PLUGIN_MANAGER "wrt-plugins-plugin-manager") + +ADD_SUBDIRECTORY(Widget) +ADD_SUBDIRECTORY(LocalStorage) +ADD_SUBDIRECTORY(WidgetInterface) +ADD_SUBDIRECTORY(WidgetDB) +ADD_SUBDIRECTORY(PluginManager) +ADD_SUBDIRECTORY(StorageEvent) +ADD_SUBDIRECTORY(TizenServiceEvent) +ADD_SUBDIRECTORY(SoftKeyboardChangeEvent) diff --git a/src/modules/packages/LocalStorage/CMakeLists.txt b/src/modules/packages/LocalStorage/CMakeLists.txt new file mode 100644 index 0000000..33fb687 --- /dev/null +++ b/src/modules/packages/LocalStorage/CMakeLists.txt @@ -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. +# +SET(TARGET_NAME ${TARGET_MODULE_LOCALSTORAGE}) + +SET(SRCS + ${SRCS_API_LOCALSTORAGE} +) + +ADD_LIBRARY(${TARGET_NAME} STATIC ${SRCS}) + +TARGET_LINK_LIBRARIES(${TARGET_NAME} + ${LIBS_COMMONS} + ${TARGET_COMMONS} + ${TARGET_MODULE_WIDGET_INTERFACE} +) + +SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES + COMPILE_DEFINITIONS LOG_TAG="${LOG_TAG}") diff --git a/src/modules/packages/PluginManager/CMakeLists.txt b/src/modules/packages/PluginManager/CMakeLists.txt new file mode 100644 index 0000000..08e90da --- /dev/null +++ b/src/modules/packages/PluginManager/CMakeLists.txt @@ -0,0 +1,61 @@ +# 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 CMakeLists.txt +# @author Lukasz Marek (l.marek@samsung.com) +# @version 1.0 +# + +MACRO(install_header_file HEADER_FILE) + INSTALL(FILES ${API_PLUGIN_MANAGER_PATH}/${HEADER_FILE} + DESTINATION ${DESTINATION_HEADER_PREFIX}/PluginManager) +ENDMACRO() + +SET(TARGET_NAME ${TARGET_MODULE_PLUGIN_MANAGER}) + +PKG_SEARCH_MODULE(webkit2 REQUIRED ewebkit2) + +INCLUDE_DIRECTORIES( + ${INCLUDES_PLATFORM_IMPLEMENTATION_PLUGIN_MANAGER} + ${webkit2_INCLUDE_DIRS}} +) + +SET(SRCS + ${SRCS_API_PLUGIN_MANAGER} + ${SRCS_PLATFORM_IMPLEMENTATION_PLUGIN_MANAGER} +) + +ADD_LIBRARY(${TARGET_NAME} SHARED ${SRCS}) +TARGET_LINK_LIBRARIES(${TARGET_NAME} + ${LIBS_COMMONS} + ${TARGET_PLUGIN_LOADING_LIB} + ${TARGET_COMMONS} + ${TARGET_COMMONS_JAVASCRIPT} + ${LIBS_PLATFORM_IMPLEMENTATION_PLUGIN_MANAGER} +) + +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(PluginManagerFactory.h) +INSTALL_HEADER_FILE(IPluginManager.h) diff --git a/src/modules/packages/SoftKeyboardChangeEvent/CMakeLists.txt b/src/modules/packages/SoftKeyboardChangeEvent/CMakeLists.txt new file mode 100644 index 0000000..ef43411 --- /dev/null +++ b/src/modules/packages/SoftKeyboardChangeEvent/CMakeLists.txt @@ -0,0 +1,29 @@ +# Copyright (c) 2012 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 CMakeLists.txt +# @author Yunchan Cho (yunchan.cho@samsung.com) +# @version 0.1 + +SET(TARGET_NAME ${TARGET_MODULE_SOFTKEYBOARD_CHANGE_EVENT}) + +SET(SRCS + ${SRCS_API_SOFTKEYBOARD_CHANGE_EVENT} +) + +ADD_LIBRARY(${TARGET_NAME} STATIC ${SRCS}) + +SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES + COMPILE_DEFINITIONS LOG_TAG="${LOG_TAG}") diff --git a/src/modules/packages/StorageEvent/CMakeLists.txt b/src/modules/packages/StorageEvent/CMakeLists.txt new file mode 100644 index 0000000..50d90bf --- /dev/null +++ b/src/modules/packages/StorageEvent/CMakeLists.txt @@ -0,0 +1,28 @@ +# 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. +# +SET(TARGET_NAME ${TARGET_MODULE_STORAGEEVENT}) + +SET(SRCS + ${SRCS_API_STORAGE_EVENT} +) + +ADD_LIBRARY(${TARGET_NAME} STATIC ${SRCS}) + +TARGET_LINK_LIBRARIES(${TARGET_NAME} + ${TARGET_MODULE_LOCALSTORAGE} +) + +SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES + COMPILE_DEFINITIONS LOG_TAG="${LOG_TAG}") diff --git a/src/modules/packages/TizenServiceEvent/CMakeLists.txt b/src/modules/packages/TizenServiceEvent/CMakeLists.txt new file mode 100644 index 0000000..691f275 --- /dev/null +++ b/src/modules/packages/TizenServiceEvent/CMakeLists.txt @@ -0,0 +1,29 @@ +# 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 CMakeLists.txt +# @author Yunchan Cho (yunchan.cho@samsung.com) +# @version 0.1 + +SET(TARGET_NAME ${TARGET_MODULE_TIZEN_SERVICE_EVENT}) + +SET(SRCS + ${SRCS_API_TIZEN_SERVICE_EVENT} +) + +ADD_LIBRARY(${TARGET_NAME} STATIC ${SRCS}) + +SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES + COMPILE_DEFINITIONS LOG_TAG="${LOG_TAG}") diff --git a/src/modules/packages/Widget/CMakeLists.txt b/src/modules/packages/Widget/CMakeLists.txt new file mode 100644 index 0000000..b1c1b2f --- /dev/null +++ b/src/modules/packages/Widget/CMakeLists.txt @@ -0,0 +1,32 @@ +# 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. +# + +SET(TARGET_NAME ${TARGET_MODULE_WIDGET}) + +SET(SRCS + ${SRCS_API_WIDGET} + ${SRCS_IMPLEMENTATION_WIDGET} +) + +ADD_LIBRARY(${TARGET_NAME} STATIC ${SRCS}) + +TARGET_LINK_LIBRARIES(${TARGET_NAME} + ${LIBS_COMMONS} + ${TARGET_COMMONS} + ${TARGET_MODULE_WIDGETDB} +) + +SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES + COMPILE_DEFINITIONS LOG_TAG="${LOG_TAG}") diff --git a/src/modules/packages/WidgetDB/CMakeLists.txt b/src/modules/packages/WidgetDB/CMakeLists.txt new file mode 100644 index 0000000..58faa4c --- /dev/null +++ b/src/modules/packages/WidgetDB/CMakeLists.txt @@ -0,0 +1,54 @@ +# +# 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 ${API_WIDGETDB_PATH}/${HEADER_FILE} + DESTINATION ${DESTINATION_HEADER_PREFIX}/WidgetDB) +ENDMACRO() + +SET(TARGET_NAME ${TARGET_MODULE_WIDGETDB}) + +INCLUDE_DIRECTORIES( + ${INCLUDES_PLATFORM_IMPLEMENTATION_WIDGETDB} +) + +SET(SRCS + ${SRCS_API_WIDGETDB} + ${SRCS_PLATFORM_IMPLEMENTATION_WIDGETDB} +) + +ADD_LIBRARY(${TARGET_NAME} SHARED ${SRCS}) + +TARGET_LINK_LIBRARIES(${TARGET_NAME} + ${LIBS_COMMONS} + ${TARGET_COMMONS} + ${LIBS_PLATFORM_IMPLEMENTATION_WIDGETDB} +) + +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(IWidgetDB.h) +INSTALL_HEADER_FILE(IWidgetFeature.h) +INSTALL_HEADER_FILE(WidgetDBMgr.h) + diff --git a/src/modules/packages/WidgetInterface/CMakeLists.txt b/src/modules/packages/WidgetInterface/CMakeLists.txt new file mode 100644 index 0000000..10ed955 --- /dev/null +++ b/src/modules/packages/WidgetInterface/CMakeLists.txt @@ -0,0 +1,54 @@ +# 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 ${API_WIDGET_INTERFACE_PATH}/${HEADER_FILE} + DESTINATION ${DESTINATION_HEADER_PREFIX}/WidgetInterface) +ENDMACRO() + +PKG_SEARCH_MODULE(dpl-wrt-dao-ro REQUIRED dpl-wrt-dao-ro) +PKG_SEARCH_MODULE(wrt-commons-widget-interface-dao REQUIRED wrt-commons-widget-interface-dao) + +INCLUDE_DIRECTORIES( + ${WIDGET_INTERFACE_INCLUDE_DIRS} + ${dpl-wrt-dao-ro_INCLUDE_DIRS} + ${wrt-commons-widget-interface-dao_INCLUDE_DIRS}) + +SET(TARGET_NAME ${TARGET_MODULE_WIDGET_INTERFACE}) + +SET(SRCS + ${SRCS_WIDGET_INTERFACE} +) + +ADD_LIBRARY(${TARGET_NAME} SHARED ${SRCS}) + +TARGET_LINK_LIBRARIES(${TARGET_NAME} + ${LIBS_COMMONS} + ${dpl-wrt-dao-ro_LIBRARIES} + ${wrt-commons-widget-interface-dao_LIBRARIES} +) + +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(WidgetInterface.h) diff --git a/src/modules/tizen/CMakeLists.txt b/src/modules/tizen/CMakeLists.txt new file mode 100644 index 0000000..f212fb3 --- /dev/null +++ b/src/modules/tizen/CMakeLists.txt @@ -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. +# +############################################################################### +# In this section please add modules that shouldn't be visible directly +# beyond wac/ subdirectory, i.e. platform wrappers specific for wac - +# - used only as helpers in AL for wac platform implementation. VConf +# is a good example, its used i.e. in Power/Battery. Unfortunately order in +# in which this modules and AL modules are included is significant, i.e. VConf +# needs to be included before Power as there are some CMake variables set that +# are used in Power config.cmake file. +################################################################################ + +INCLUDE_CONFIG_FILE(Widget) +INCLUDE_CONFIG_FILE(LocalStorage) +INCLUDE_CONFIG_FILE(WidgetInterface) +ADD_SUBDIRECTORY(WidgetInterface) +INCLUDE_CONFIG_FILE(WidgetDB) +INCLUDE_CONFIG_FILE(PluginManager) diff --git a/src/modules/tizen/DESCRIPTION b/src/modules/tizen/DESCRIPTION new file mode 100644 index 0000000..45900ba --- /dev/null +++ b/src/modules/tizen/DESCRIPTION @@ -0,0 +1,2 @@ +!!!options!!! stop +API implementation for tizen platform diff --git a/src/modules/tizen/PluginManager/PluginManager.cpp b/src/modules/tizen/PluginManager/PluginManager.cpp new file mode 100644 index 0000000..d84a544 --- /dev/null +++ b/src/modules/tizen/PluginManager/PluginManager.cpp @@ -0,0 +1,265 @@ +/* + * 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 PluginManager.cpp + * @author Lukasz Marek (l.marek@samsung.com) + * @version 0.1 + * @brief + */ + +#include "PluginManager.h" +#include <algorithm> +#include <dpl/wrt-dao-ro/widget_dao_read_only.h> +#include <dpl/wrt-dao-ro/plugin_dao_read_only.h> +#include <dpl/wrt-dao-ro/WrtDatabase.h> +#include <plugin_logic.h> +#include <js_types.h> +#include <dpl/wrt-dao-ro/common_dao_types.h> +#include <Commons/Exception.h> +#include <CommonsJavaScript/Converter.h> +#include <dpl/exception.h> +#include <dpl/log/wrt_log.h> +#include <dpl/foreach.h> + +using namespace std; + +namespace { +const string GLOBAL_OBJECT_NAME = "window"; +const char* SEPARATOR = "."; +} + +namespace WrtDeviceApis { +namespace PluginManager { +PluginManager::PluginManager(WidgetHandle widgetHandle, + const string &objectUri, + JSObjectRef object, + JSContextRef context) : + m_widgetHandle(widgetHandle), + m_objectInstance(object), + m_objectUri(GLOBAL_OBJECT_NAME), + m_shortUri(objectUri), + m_context(context) +{ + m_objectUri.append(SEPARATOR).append(objectUri); + WrtDB::WrtDatabase::attachToThreadRO(); +} + +PluginManager::~PluginManager() +{ + ObjectList::iterator it = m_objectList.begin(); + for (; it != m_objectList.end(); ++it) { + JSValueUnprotect(m_context, it->second); + } + WrtDB::WrtDatabase::detachFromThread(); +} + +bool PluginManager::hasChild(const string &name) const +{ + const PropertyList &prop = getProperties(); + return prop.end() != find(prop.begin(), prop.end(), name); +} + +bool PluginManager::loadChild(const string &name) const +{ + WrtLogD("loading %s", name.c_str()); + string localUri = m_objectUri; + localUri.append(SEPARATOR).append(name); + + WrtDB::DbPluginHandle handle = + WrtDB::PluginDAOReadOnly::getPluginHandleForImplementedObject(localUri); + if (handle == WrtDB::INVALID_PLUGIN_HANDLE) { + WrtLogE("Plugin not found"); + return false; + } + + WrtDB::DbWidgetFeatureSet features; + WrtDB::WidgetType widgetType; + Try + { + WrtDB::WidgetDAOReadOnly dao(m_widgetHandle); + features = dao.getFeaturesList(); + widgetType = dao.getWidgetType(); + } + Catch(WrtDB::WidgetDAOReadOnly::Exception::Base) + { + // Error while reading database - widget handle may + // be invalid or some data may be missing in database + WrtLogE("Cannot get feature list"); + return false; + } + + if (widgetType == WrtDB::APP_TYPE_TIZENWEBAPP) { + JavaScriptObject jsObject = { m_objectInstance, + m_shortUri }; + return PluginLogicSingleton::Instance().loadPluginOnDemand( + handle, jsObject, const_cast<JSGlobalContextRef>(m_context)); + } + + //check does plugin with feature was requested + FOREACH(it, features) + { + if (it->pluginId == handle) { + if (it->rejected) { + WrtLogE("Feature rejected by ACE"); + continue; + } + + JavaScriptObject jsObject = { m_objectInstance, + m_shortUri }; + + return PluginLogicSingleton::Instance().loadPluginOnDemand( + handle, jsObject, + const_cast<JSGlobalContextRef>(m_context)); + } + } + WrtLogE("Plugin not loaded"); + return false; +} + +JSValueRef PluginManager::getProperty(const string &name) const +{ + WrtLogD("getProperty %s", name.c_str()); + ObjectList::const_iterator it = m_objectList.find(name); + if (it != m_objectList.end()) { + //return already set value + return it->second; + } + + if (!loadChild(name)) { + ThrowMsg(Commons::PlatformException, "Cannot load plugin"); + } + + it = m_objectList.find(name); + if (it != m_objectList.end()) { + //return set value + return it->second; + } + + ThrowMsg(Commons::PlatformException, "Cannot obtain property"); +} + +bool PluginManager::setProperty(const string &name, + JSValueRef value) +{ + WrtLogD("setProperty %s", name.c_str()); + if (m_objectList.count(name) > 0) { + JSValueUnprotect(m_context, m_objectList[name]); + } + JSValueProtect(m_context, value); + m_objectList[name] = value; + return true; +} + +bool PluginManager::deleteProperty(const string &name) +{ + if (m_objectList.count(name) > 0) { + WrtLogD("deleteProperty %s", name.c_str()); + JSValueUnprotect(m_context, m_objectList[name]); + m_objectList.erase(name); + return true; + } + return false; +} + +Api::IPluginManager::PropertyList PluginManager::getProperties() const +{ + using namespace WrtDB; + + if (!!m_propertyCache) { + return *m_propertyCache; + } + + m_propertyCache = PropertyList(); + + WidgetDAOReadOnly dao(m_widgetHandle); + string localUri = m_objectUri + SEPARATOR; + + if (dao.getWidgetType() == APP_TYPE_TIZENWEBAPP) + { + static ImplementedObjectsList implObjectList = + PluginDAOReadOnly::getImplementedObjects(); + + FOREACH(it_implObject, implObjectList) + { + //check if implemented object stats with localUri + if (it_implObject->find(localUri) == 0) { + string property = *it_implObject; + //remove local uri that predicts property name. + property.erase(0, localUri.size()); + //check if property has its own properties. + size_t pos = property.find(SEPARATOR); + if (pos != string::npos) { + //if so then remove them. + property.erase(pos); + } + + m_propertyCache->push_back(property); + } + } + } + else + { + DbWidgetFeatureSet features; + + Try + { + features = dao.getFeaturesList(); + } + Catch(WidgetDAOReadOnly::Exception::Base) + { + WrtLogE("Cannot get feature list"); + ReThrow(Commons::PlatformException); + } + + DbWidgetFeatureSet::const_iterator feature = features.begin(); + for (; feature != features.end(); ++feature) { + ImplementedObjectsList implObjs = + PluginDAOReadOnly::getImplementedObjectsForPluginHandle( + feature->pluginId); + FOREACH(it, implObjs) { + //check if implemented object stats with localUri + if (it->find(localUri) == 0) { + string property = *it; + //remove local uri that predicts property name. + property.erase(0, localUri.size()); + //check if property has its own properties. + size_t pos = property.find(SEPARATOR); + if (pos != string::npos) { + //if so then remove them. + property.erase(pos); + } + m_propertyCache->push_back(property); + } + } + } + } + + return *m_propertyCache; +} + +void PluginManager::addPropertiesToList( + JSPropertyNameAccumulatorRef propertyNames) const +{ + PropertyList properties = getProperties(); + CommonsJavaScript::Converter converter(m_context); + FOREACH(it, properties) { + JSStringRef name = converter.toJSStringRef(*it); + JSPropertyNameAccumulatorAddName(propertyNames, name); + JSStringRelease(name); + } +} +} +} diff --git a/src/modules/tizen/PluginManager/PluginManager.h b/src/modules/tizen/PluginManager/PluginManager.h new file mode 100644 index 0000000..fdf34ae --- /dev/null +++ b/src/modules/tizen/PluginManager/PluginManager.h @@ -0,0 +1,67 @@ +/* + * 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 PluginManager.h + * @author Lukasz Marek (l.marek@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRTDEVICEAPIS_PLUGINMANAGER_PLUGINMANAGER_H_ +#define WRTDEVICEAPIS_PLUGINMANAGER_PLUGINMANAGER_H_ + +#include <map> +#include <string> +#include <API/PluginManager/IPluginManager.h> +#include <boost/optional.hpp> +#include <dpl/wrt-dao-ro/wrt_db_types.h> + +namespace WrtDeviceApis { +namespace PluginManager { +class PluginManager : public Api::IPluginManager +{ + public: + PluginManager(WidgetHandle widgetHandle, + const std::string &objectUri, + JSObjectRef object, + JSContextRef context); + ~PluginManager(); + bool hasChild(const std::string &name) const; + bool loadChild(const std::string &name) const; + + JSValueRef getProperty(const std::string &name) const; + bool setProperty(const std::string &name, + JSValueRef value); + bool deleteProperty(const std::string &name); + + PropertyList getProperties() const; + void addPropertiesToList(JSPropertyNameAccumulatorRef propertyNames) const; + + private: + typedef std::map<std::string, JSValueRef> ObjectList; + + WidgetHandle m_widgetHandle; + JSObjectRef m_objectInstance; + std::string m_objectUri; + std::string m_shortUri; + mutable boost::optional<PropertyList> m_propertyCache; + ObjectList m_objectList; + JSContextRef m_context; +}; +} +} + +#endif diff --git a/src/modules/tizen/PluginManager/config.cmake b/src/modules/tizen/PluginManager/config.cmake new file mode 100644 index 0000000..ccf3c80 --- /dev/null +++ b/src/modules/tizen/PluginManager/config.cmake @@ -0,0 +1,23 @@ +get_current_path() + +pkg_search_module(dpl-wrt-dao-ro REQUIRED dpl-wrt-dao-ro) +#pkg_search_module(wrt-plugin-loading REQUIRED wrt-plugin-loading) + +set(INCLUDES_PLATFORM_IMPLEMENTATION_PLUGIN_MANAGER + ${dpl-wrt-dao-ro_INCLUDE_DIRS} + ${wrt-plugin-loading_INCLUDE_DIRS} + ${PLUGIN_LOADING_DIRS} + PARENT_SCOPE +) + +set(LIBS_PLATFORM_IMPLEMENTATION_PLUGIN_MANAGER + ${dpl-wrt-dao-ro_LIBRARIES} + ${wrt-plugin-loading_LIBRARIES} + ${TARGET_PLUGIN_LOADING_LIB} + PARENT_SCOPE +) + +set(SRCS_PLATFORM_IMPLEMENTATION_PLUGIN_MANAGER + ${CURRENT_PATH}/PluginManager.cpp + PARENT_SCOPE +) diff --git a/src/modules/tizen/Widget/Property.h b/src/modules/tizen/Widget/Property.h new file mode 100644 index 0000000..d1a19d1 --- /dev/null +++ b/src/modules/tizen/Widget/Property.h @@ -0,0 +1,73 @@ +/* + * 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 Property.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WIDGET_PROPERTY_H_ +#define WIDGET_PROPERTY_H_ + +#include <string> +#include <Commons/Exception.h> + +namespace WrtDeviceApis { +namespace Widget { +template<typename T> +class Property +{ + public: + explicit Property() : + m_value(), + m_valid(false) + {} + + void setValue(const T& value) + { + m_value = value; + m_valid = true; + } + + T getValue() const + { + if (!m_valid) { + Throw(Commons::PlatformException); + } + return m_value; + } + + bool isValid() const + { + return m_valid; + } + + virtual ~Property() + {} + + private: + T m_value; + bool m_valid; +}; + +typedef Property<std::string> StringProperty; +typedef Property<unsigned int> UIntProperty; +} +} +#endif diff --git a/src/modules/tizen/Widget/Widget.cpp b/src/modules/tizen/Widget/Widget.cpp new file mode 100644 index 0000000..db46b1d --- /dev/null +++ b/src/modules/tizen/Widget/Widget.cpp @@ -0,0 +1,175 @@ +/* + * 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 Widget.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#include <dpl/log/wrt_log.h> +#include <Commons/StringUtils.h> +#include <Commons/WrtAccess/WrtAccess.h> +#include "Widget.h" +#include <WidgetDB/IWidgetDB.h> +#include <WidgetDB/WidgetDBMgr.h> + +namespace WrtDeviceApis { +namespace Widget { +using namespace std; +using namespace WidgetDB::Api; + +Widget::Widget() +{ + using namespace WrtDeviceApis::Commons; + m_widgetId = WrtAccessSingleton::Instance().getWidgetId(); +} + +Widget::~Widget() +{} + +string Widget::getProperty(ConfigAttribute attr) const +{ + checkWidgetId(); + + string value; + Try { + IWidgetDBPtr widgetDB = getWidgetDB(m_widgetId); + value = widgetDB->getConfigValue(attr); + } + Catch(Commons::InvalidArgumentException){ + WrtLogE("Invalid argument exception"); + Throw(Commons::PlatformException); + } + + return value; +} + +string Widget::getAuthor() const +{ + checkWidgetId(); + + if (!m_author.isValid()) { + m_author.setValue(getProperty(ConfigAttribute::AUTHOR_NAME)); + } + return m_author.getValue(); +} + +string Widget::getAuthorEmail() const +{ + checkWidgetId(); + + if (!m_authorEmail.isValid()) { + m_authorEmail.setValue(getProperty(ConfigAttribute::AUTHOR_EMAIL)); + } + return m_authorEmail.getValue(); +} + +string Widget::getAuthorHref() const +{ + checkWidgetId(); + + if (!m_authorHref.isValid()) { + m_authorHref.setValue(getProperty(ConfigAttribute::AUTHOR_HREF)); + } + return m_authorHref.getValue(); +} + +string Widget::getDescription() const +{ + checkWidgetId(); + + if (!m_description.isValid()) { + m_description.setValue(getProperty(ConfigAttribute::DESCRIPTION)); + } + return m_description.getValue(); +} + +string Widget::getId() const +{ + checkWidgetId(); + + WrtLogD("entered"); + if (!m_id.isValid()) { + m_id.setValue(getProperty(ConfigAttribute::ID)); + } + return m_id.getValue(); +} + +string Widget::getName() const +{ + checkWidgetId(); + + if (!m_name.isValid()) { + m_name.setValue(getProperty(ConfigAttribute::NAME)); + } + return m_name.getValue(); +} + +string Widget::getShortName() const +{ + checkWidgetId(); + + if (!m_shortName.isValid()) { + m_shortName.setValue(getProperty(ConfigAttribute::SHORT_NAME)); + } + return m_shortName.getValue(); +} + +string Widget::getVersion() const +{ + checkWidgetId(); + + if (!m_version.isValid()) { + m_version.setValue(getProperty(ConfigAttribute::VERSION)); + } + return m_version.getValue(); +} + +unsigned int Widget::getHeight() const +{ + checkWidgetId(); + + if (!m_height.isValid()) { + m_height.setValue(Commons::String::convertTo<int>( + getProperty(ConfigAttribute::HEIGHT))); + } + return m_height.getValue(); +} + +unsigned int Widget::getWidth() const +{ + checkWidgetId(); + + if (!m_width.isValid()) { + m_width.setValue(Commons::String::convertTo<int>( + getProperty(ConfigAttribute::WIDTH))); + } + return m_width.getValue(); +} + +void Widget::checkWidgetId() const +{ + if (m_widgetId < 0) { + WrtLogE("Invalid widget id"); + Throw(Commons::InvalidArgumentException); + } + return; +} +} +} diff --git a/src/modules/tizen/Widget/Widget.h b/src/modules/tizen/Widget/Widget.h new file mode 100644 index 0000000..d46b9c7 --- /dev/null +++ b/src/modules/tizen/Widget/Widget.h @@ -0,0 +1,81 @@ +/* + * 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 Widget.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef PLATFORM_WIDGET_CONFIGURATION_H_ +#define PLATFORM_WIDGET_CONFIGURATION_H_ + +#include <string> + +#include <Commons/WrtAccess/WrtAccess.h> + +#include <Widget/IWidget.h> +#include <WidgetDB/IWidgetDB.h> +#include "Property.h" + +#include <dpl/wrt-dao-ro/wrt_db_types.h> + +namespace WrtDeviceApis { +namespace Widget { +class Widget : public Api::IWidget +{ + public: + + explicit Widget(); + ~Widget(); + + virtual std::string getAuthor() const; + virtual std::string getAuthorEmail() const; + virtual std::string getAuthorHref() const; + virtual std::string getDescription() const; + virtual std::string getId() const; + virtual std::string getName() const; + virtual std::string getShortName() const; + virtual std::string getVersion() const; + virtual unsigned int getHeight() const; + virtual unsigned int getWidth() const; + + protected: + + mutable StringProperty m_author; + mutable StringProperty m_authorEmail; + mutable StringProperty m_authorHref; + mutable StringProperty m_description; + mutable StringProperty m_id; + mutable StringProperty m_name; + mutable StringProperty m_shortName; + mutable StringProperty m_version; + mutable UIntProperty m_height; + mutable UIntProperty m_width; + + private: + + std::string getProperty(WidgetDB::Api::ConfigAttribute) const; + void checkWidgetId() const; + + WidgetHandle m_widgetId; +}; +} +} + +#endif diff --git a/src/modules/tizen/Widget/config.cmake b/src/modules/tizen/Widget/config.cmake new file mode 100644 index 0000000..c4a3adf --- /dev/null +++ b/src/modules/tizen/Widget/config.cmake @@ -0,0 +1,6 @@ +get_current_path() + +set(SRCS_IMPLEMENTATION_WIDGET + ${CURRENT_PATH}/Widget.cpp + PARENT_SCOPE +) diff --git a/src/modules/tizen/WidgetDB/WidgetDB.cpp b/src/modules/tizen/WidgetDB/WidgetDB.cpp new file mode 100644 index 0000000..278decd --- /dev/null +++ b/src/modules/tizen/WidgetDB/WidgetDB.cpp @@ -0,0 +1,388 @@ +/* + * 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 WidgetDB.cpp + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief + */ + +#include "WidgetDB.h" + +#include <string> +#include <set> + +#include <Commons/Exception.h> +#include <WidgetDB/IWidgetDB.h> +#include <WidgetDB/IWidgetFeature.h> +#include <dpl/log/wrt_log.h> +#include <dpl/wrt-dao-ro/property_dao_read_only.h> +#include <dpl/wrt-dao-ro/widget_dao_read_only.h> +#include <dpl/wrt-dao-ro/global_config.h> +#include <dpl/wrt-dao-ro/widget_config.h> +#include <dpl/wrt-dao-ro/feature_dao_read_only.h> +#include <dpl/wrt-dao-ro/widget_dao_read_only.h> +#include <dpl/wrt-dao-ro/feature_model.h> +#include <dpl/wrt-dao-ro/common_dao_types.h> + +#include <dpl/localization/w3c_file_localization.h> + +#include "WidgetFeature.h" + +namespace WrtDeviceApis { +namespace WidgetDB { +WidgetDB::WidgetDB(WidgetHandle widgetId) : m_widgetId(widgetId) {} + +WidgetHandle WidgetDB::getWidgetId() const +{ + return m_widgetId; +} + +std::string WidgetDB::getLanguage() const +{ + WrtLogD("getting language"); + + WrtDB::LanguageTagList languageTags; + std::string outLanguage; + Try + { + WrtDB::WidgetDAOReadOnly dao(getWidgetId()); + languageTags = dao.getLanguageTags(); + } + Catch(DPL::Exception) + { + ReThrow(Commons::SecurityException); + } + + // get 'en' language or first from the list if 'en' does not exist + if (languageTags.size() > 1) { + FOREACH(lang, languageTags) + { + if ("en" == DPL::ToUTF8String(*lang)) { + return "en"; + } + } + } + + if (!languageTags.empty()) { + // get first language tag + outLanguage = DPL::ToUTF8String(*(languageTags.begin())); + } + return outLanguage; +} + +/*License,LicenseHref,Description,Name can be \ + * returned with incorect language*/ +std::string WidgetDB::getConfigValue(Api::ConfigAttribute attribute) const +{ + WrtLogD("entered"); + std::string value; + Try + { + WrtDB::WidgetDAOReadOnlyPtr dao(new WrtDB::WidgetDAOReadOnly(getWidgetId())); + WrtDB::WidgetLocalizedInfo widgetInfo = + W3CFileLocalization::getLocalizedInfo(dao); + + std::ostringstream out; + + switch (attribute) { + case Api::ConfigAttribute::ID: { + DPL::OptionalString val = dao->getGUID(); + value = !val ? "" : DPL::ToUTF8String(*val); + break; + } + + case Api::ConfigAttribute::VERSION: { + DPL::OptionalString val = dao->getVersion(); + value = !val ? "" : DPL::ToUTF8String(*val); + break; + } + + case Api::ConfigAttribute::DESCRIPTION: { + DPL::OptionalString val = widgetInfo.description; + value = !val ? "" : DPL::ToUTF8String(*val); + break; + } + + case Api::ConfigAttribute::LICENSE: { + DPL::OptionalString val = widgetInfo.license; + value = !val ? "" : DPL::ToUTF8String(*val); + break; + } + + case Api::ConfigAttribute::LICENSE_HREF: { + DPL::OptionalString val = widgetInfo.licenseHref; + value = !val ? "" : DPL::ToUTF8String(*val); + break; + } + + case Api::ConfigAttribute::AUTHOR_NAME: { + DPL::OptionalString val = dao->getAuthorName(); + value = !val ? "" : DPL::ToUTF8String(*val); + break; + } + + case Api::ConfigAttribute::AUTHOR_EMAIL: { + DPL::OptionalString val = dao->getAuthorEmail(); + value = !val ? "" : DPL::ToUTF8String(*val); + break; + } + + case Api::ConfigAttribute::AUTHOR_HREF: { + DPL::OptionalString val = dao->getAuthorHref(); + value = !val ? "" : DPL::ToUTF8String(*val); + break; + } + + case Api::ConfigAttribute::NAME: { + DPL::OptionalString val = widgetInfo.name; + value = !val ? "" : DPL::ToUTF8String(*val); + break; + } + + case Api::ConfigAttribute::SHORT_NAME: { + DPL::OptionalString val = widgetInfo.shortName; + value = !val ? "" : DPL::ToUTF8String(*val); + break; + } + + case Api::ConfigAttribute::WIDTH: { + DPL::OptionalInt width = dao->getPreferredSize().width; + !width ? out << "0" : out << *width; + value = out.str(); + break; + } + + case Api::ConfigAttribute::HEIGHT: { + DPL::OptionalInt height = dao->getPreferredSize().height; + !height ? out << "0" : out << *height; + value = out.str(); + break; + } + + case Api::ConfigAttribute::INSTALL_PATH: + value = DPL::ToUTF8String(dao->getPath()); + break; + + case Api::ConfigAttribute::PUBLIC_STORAGE_PATH: + value = WrtDB::GlobalConfig::GetPublicVirtualRootPath(); + break; + + default: + WrtLogW("Unknown attribute requested"); + Throw(Commons::InvalidArgumentException); + } + } + Catch(Commons::InvalidArgumentException) + { + ReThrow(Commons::InvalidArgumentException); + } + Catch(DPL::Exception) + { + ReThrow(Commons::SecurityException); + } + + WrtLogD("exit"); + + return value; +} + +std::string WidgetDB::getUserAgent() const +{ + WrtLogD("Widget User_Agent data get"); + + std::string outUA("not implemented"); + return outUA; +} + +Api::InstallationStatus WidgetDB::checkInstallationStatus( + const std::string& gid, + const std::string& name, + const std::string& version) const +{ + WrtLogD("Checking widget (gid(%s), name(%s), version(%s)) installation status", + gid.c_str(), + name.c_str(), + version.c_str()); + + Api::InstallationStatus outStatus; + Try + { + const WrtDB::WidgetGUID w_guid = + WrtDB::WidgetGUID(DPL::FromUTF8String(gid)); + + try { + WrtDB::DbWidgetHandle widgetHandle = + WrtDB::WidgetDAOReadOnly::getHandle(w_guid); + + WrtDB::WidgetDAOReadOnly dao(widgetHandle); + DPL::OptionalString ver = dao.getVersion(); + if (!ver || version > DPL::ToUTF8String(*ver)) { + // if there is no version in DB + // or DB version is lover or equal than provided + outStatus = Api::InstallationStatus::STATUS_INSTALLED; + } else { + outStatus = Api::InstallationStatus::STATUS_LATEST; + } + } catch (WrtDB::WidgetDAOReadOnly::Exception::WidgetNotExist) { + outStatus = Api::InstallationStatus::STATUS_UNINSTALLED; + } + } + Catch(DPL::Exception) + { + ReThrow(Commons::SecurityException); + } + + return outStatus; +} + +Api::Features WidgetDB::getWidgetFeatures() const +{ + WrtLogD("entered"); + WrtDB::DbWidgetFeatureSet features; + Try + { + WrtDB::WidgetDAOReadOnly dao(getWidgetId()); + features = dao.getFeaturesList(); + } + Catch(DPL::Exception) + { + // exception handle + ReThrow(Commons::SecurityException); + } + + Api::Features outFeatures; + + WrtLogD("There is no exception"); + + FOREACH(it, features) + { + Api::IWidgetFeaturePtr feature( + new WidgetFeature(DPL::ToUTF8String((*it).name), + true)); // requested (WidgetFeature param) + outFeatures.push_back(feature); + } + + return outFeatures; +} + +Api::Features WidgetDB::getRegisteredFeatures() const +{ + Api::Features outRegisteredFeatures; + Try + { + // initialize with our widget features (they are required) + outRegisteredFeatures = getWidgetFeatures(); + + // searching for another features + + WrtDB::FeatureHandleList features = + WrtDB::FeatureDAOReadOnly::GetHandleList(); + + bool featureFound = false; + + // throught all features + FOREACH(registeredFeature, features) + { + WrtDB::FeatureHandle handle = *registeredFeature; + WrtDB::FeatureDAOReadOnly dao(handle); + + // check if this feature is aleready on outRegisteredFeatures list + // and if not, add it + + FOREACH(it, outRegisteredFeatures) + { + if (dao.GetName() == (*it)->getName()) { // *it = shared ptr + // this name is found on list, do not add + featureFound = true; + break; + } + } + + if (!featureFound) { + // feature is not on outRegisteredFeature so add it with + // 'required' property false + Api::IWidgetFeaturePtr newFeature(new WidgetFeature( + dao.GetName(), + false)); + + // TODO what about feature params? aren't they needed + outRegisteredFeatures.push_back(newFeature); + } + // reset the flag and check another feature + featureFound = false; + } + } + Catch(DPL::Exception) + { + ReThrow(Commons::SecurityException); + } + + return outRegisteredFeatures; +} + +std::string WidgetDB::getWidgetInstallationPath() const +{ + Try + { + WrtDB::WidgetDAOReadOnly dao(getWidgetId()); + std::string result(DPL::ToUTF8String(dao.getFullPath())); + result.erase(0, strlen("file://")); + std::string::size_type pos = result.size(); + std::string separator("/"); + pos = result.rfind(separator, pos); + if ((result.size() - pos) > 0 && (result.size() - pos) < 2) { + result.erase(pos, result.size()); + } + return result; + } + Catch(DPL::Exception) + { + ReThrow(Commons::PlatformException); + } +} + +std::string WidgetDB::getWidgetPersistentStoragePath() const +{ + Try + { + WrtDB::WidgetDAOReadOnly dao(getWidgetId()); + return + WrtDB::WidgetConfig::GetWidgetPersistentStoragePath( + dao.getTizenPkgId()); + } + Catch(DPL::Exception) + { + ReThrow(Commons::PlatformException); + } +} + +std::string WidgetDB::getWidgetTemporaryStoragePath() const +{ + Try + { + WrtDB::WidgetDAOReadOnly dao(getWidgetId()); + return + WrtDB::WidgetConfig::GetWidgetTemporaryStoragePath( + dao.getTizenPkgId()); + } + Catch(DPL::Exception) + { + ReThrow(Commons::PlatformException); + } +} +} // WidgetDB +} // WrtDeviceApis diff --git a/src/modules/tizen/WidgetDB/WidgetDB.h b/src/modules/tizen/WidgetDB/WidgetDB.h new file mode 100644 index 0000000..f91547e --- /dev/null +++ b/src/modules/tizen/WidgetDB/WidgetDB.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. + */ +/* + * @file WidgetDB.h + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRTDEVICEAPIS_WIDGETDB_WIDGETDB_H_ +#define WRTDEVICEAPIS_WIDGETDB_WIDGETDB_H_ + +#include <string> +#include <WidgetDB/IWidgetDB.h> +#include <dpl/wrt-dao-ro/wrt_db_types.h> + +namespace WrtDeviceApis { +namespace WidgetDB { +class WidgetDB : public Api::IWidgetDB +{ + public: + + explicit WidgetDB(WidgetHandle widgetId); + + virtual WidgetHandle getWidgetId() const; + + virtual std::string getLanguage() const; + + virtual std::string getConfigValue(Api::ConfigAttribute attribute) const; + + virtual std::string getUserAgent() const; + + virtual Api::InstallationStatus checkInstallationStatus( + const std::string& gid, + const std::string& name, + const std::string& version) const; + + virtual Api::Features getWidgetFeatures() const; + + virtual Api::Features getRegisteredFeatures() const; + + virtual std::string getWidgetInstallationPath() const; + + virtual std::string getWidgetPersistentStoragePath() const; + + virtual std::string getWidgetTemporaryStoragePath() const; + + private: + + WidgetHandle m_widgetId; +}; +} // WidgetDB +} // WrtDeviceApis + +#endif // WRTDEVICEAPIS_WIDGETDB_WIDGETDB_H + diff --git a/src/modules/tizen/WidgetDB/WidgetFeature.cpp b/src/modules/tizen/WidgetDB/WidgetFeature.cpp new file mode 100644 index 0000000..983282f --- /dev/null +++ b/src/modules/tizen/WidgetDB/WidgetFeature.cpp @@ -0,0 +1,51 @@ +/* + * 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 <dpl/log/wrt_log.h> +#include "WidgetFeature.h" + +namespace WrtDeviceApis { +namespace WidgetDB { +WidgetFeature::WidgetFeature(const std::string& name, + bool requested) : + m_name(name), + m_requested(requested) +{ + //WrtLogD("entered"); +} + +std::string WidgetFeature::getName() const +{ + //WrtLogD("entered"); + return m_name; +} + +WidgetFeature::~WidgetFeature() +{ + //WrtLogD("entered"); +} + +bool WidgetFeature::isRequestedByWidget() const +{ + return m_requested; +} +} // WidgetDB +} // WrtDeviceApis diff --git a/src/modules/tizen/WidgetDB/WidgetFeature.h b/src/modules/tizen/WidgetDB/WidgetFeature.h new file mode 100644 index 0000000..d14dc69 --- /dev/null +++ b/src/modules/tizen/WidgetDB/WidgetFeature.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 Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRT_PLUGINS_WRT_ENGINE_WIDGET_FEATURE_H_ +#define WRT_PLUGINS_WRT_ENGINE_WIDGET_FEATURE_H_ + +#include <string> +#include <WidgetDB/IWidgetFeature.h> + +namespace WrtDeviceApis { +namespace WidgetDB { +class WidgetFeature : public Api::IWidgetFeature +{ + public: + WidgetFeature(const std::string& name, + bool requested); + + std::string getName() const; + + virtual ~WidgetFeature(); + + virtual bool isRequestedByWidget() const; + + private: + std::string m_name; + bool m_requested; +}; +} // WidgetDB +} // WrtDeviceApis + +#endif diff --git a/src/modules/tizen/WidgetDB/config.cmake b/src/modules/tizen/WidgetDB/config.cmake new file mode 100644 index 0000000..6362668 --- /dev/null +++ b/src/modules/tizen/WidgetDB/config.cmake @@ -0,0 +1,22 @@ +get_current_path() + +pkg_search_module(dpl-wrt-dao-ro REQUIRED dpl-wrt-dao-ro) +pkg_search_module(dpl-utils-efl REQUIRED dpl-utils-efl) + +set(INCLUDES_PLATFORM_IMPLEMENTATION_WIDGETDB + ${dpl-wrt-dao-ro_INCLUDE_DIRS} + ${dpl-utils-efl_INCLUDE_DIRS} + PARENT_SCOPE +) + +set(LIBS_PLATFORM_IMPLEMENTATION_WIDGETDB + ${dpl-wrt-dao-ro_LDFLAGS} + ${dpl-utils-efl_LDFLAGS} + PARENT_SCOPE +) + +set(SRCS_PLATFORM_IMPLEMENTATION_WIDGETDB + ${CURRENT_PATH}/WidgetDB.cpp + ${CURRENT_PATH}/WidgetFeature.cpp + PARENT_SCOPE +) diff --git a/src/modules/tizen/WidgetInterface/CMakeLists.txt b/src/modules/tizen/WidgetInterface/CMakeLists.txt new file mode 100644 index 0000000..e6ddea1 --- /dev/null +++ b/src/modules/tizen/WidgetInterface/CMakeLists.txt @@ -0,0 +1,6 @@ + +GET_CURRENT_PATH() + +PKG_SEARCH_MODULE(wrt-commons-widget-interface-dao REQUIRED wrt-commons-widget-interface-dao) + +INCLUDE_DIRECTORIES(${CURRENT_PATH}) diff --git a/src/modules/tizen/WidgetInterface/WidgetInterface.cpp b/src/modules/tizen/WidgetInterface/WidgetInterface.cpp new file mode 100644 index 0000000..ccf2f4a --- /dev/null +++ b/src/modules/tizen/WidgetInterface/WidgetInterface.cpp @@ -0,0 +1,138 @@ +/* + * 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 Lukasz Marek (l.marek@samsung.com) + * @version 0.1 + * @brief + */ + +#include "WidgetInterface.h" +#include <string> +#include <dpl/exception.h> +#include <dpl/log/wrt_log.h> +#include <dpl/string.h> +#include <wrt-commons/widget-interface-dao/widget_interface_dao.h> +#include <Commons/Exception.h> + +namespace WrtDeviceApis { +using namespace WidgetInterfaceDB; + +WidgetInterfaceObject::WidgetInterfaceObject(WidgetHandle widgetHandle) +{ + Try + { + m_dao.reset(new WidgetInterfaceDAO(widgetHandle)); + } + Catch(WidgetInterfaceDAO::Exception::DatabaseError) + { + ReThrow(Commons::PlatformException); + } +} + +WidgetInterfaceObject::~WidgetInterfaceObject() +{ + m_dao.reset(); +} + +void WidgetInterfaceObject::setItem(const std::string& key, + const std::string& value, + bool readOnly) +{ + Try + { + m_dao->setItem(key, value, readOnly); + } + Catch(WidgetInterfaceDAO::Exception::DatabaseError) + { + ReThrow(Commons::PlatformException); + } + Catch(WidgetInterfaceDAO::Exception::LocalStorageValueNoModifableException) + { + WrtLogE("Cannot delete item. Item is readonly"); + ReThrow(Commons::LocalStorageValueNoModifableException); + } +} + +void WidgetInterfaceObject::removeItem(const std::string& key) +{ + Try + { + m_dao->removeItem(key); + } + Catch(WidgetInterfaceDAO::Exception::DatabaseError) + { + ReThrow(Commons::PlatformException); + } + Catch(WidgetInterfaceDAO::Exception::LocalStorageValueNoModifableException) + { + WrtLogE("Cannot delete item. Item is readonly"); + ReThrow(Commons::LocalStorageValueNoModifableException); + } +} + +DPL::OptionalStdString WidgetInterfaceObject::getValue( + const std::string& key) const +{ + Try + { + return m_dao->getValue(key); + } + Catch(WidgetInterfaceDAO::Exception::DatabaseError) + { + ReThrow(Commons::PlatformException); + } +} + +void WidgetInterfaceObject::clear(bool removeReadOnly) +{ + Try + { + m_dao->clear(removeReadOnly); + } + Catch(WidgetInterfaceDAO::Exception::DatabaseError) + { + ReThrow(Commons::PlatformException); + } +} + +size_t WidgetInterfaceObject::getStorageSize() const +{ + Try + { + return m_dao->getStorageSize(); + } + Catch(WidgetInterfaceDAO::Exception::DatabaseError) + { + ReThrow(Commons::PlatformException); + } +} + +std::string WidgetInterfaceObject::getKeyByIndex(size_t index) const +{ + Try + { + return m_dao->getKeyByIndex(index); + } + Catch(WidgetInterfaceDAO::Exception::DatabaseError) + { + ReThrow(Commons::PlatformException); + } + Catch(WidgetInterfaceDAO::Exception::InvalidArgumentException) + { + ReThrow(Commons::InvalidArgumentException); + } +} +} diff --git a/src/modules/tizen/WidgetInterface/WidgetInterface.h b/src/modules/tizen/WidgetInterface/WidgetInterface.h new file mode 100644 index 0000000..69b0d95 --- /dev/null +++ b/src/modules/tizen/WidgetInterface/WidgetInterface.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. + */ +/* + * @author Lukasz Marek (l.marek@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef WRTDEVICEAPIS_COMMONS_WIDGET_INTERFACE_H_ +#define WRTDEVICEAPIS_COMMONS_WIDGET_INTERFACE_H_ + +#include <string> +#include <dpl/optional_typedefs.h> +#include <wrt-commons/widget-interface-dao/widget_interface_dao.h> +#include <LocalStorage/ILocalStorage.h> +#include <dpl/wrt-dao-ro/wrt_db_types.h> + +namespace WrtDeviceApis { +class WidgetInterfaceObject : + public LocalStorage::Api::ILocalStorage +{ + public: + WidgetInterfaceObject(WidgetHandle widgetHandle); + virtual ~WidgetInterfaceObject(); + + void setItem(const std::string& key, + const std::string& value, + bool readOnly); + void removeItem(const std::string& key); + DPL::OptionalStdString getValue(const std::string& key) const; + void clear(bool removeReadOnly); + size_t getStorageSize() const; + std::string getKeyByIndex(size_t index) const; + + private: + WidgetInterfaceDB::WidgetInterfaceDAOPtr m_dao; +}; +} + +#endif //WRTDEVICEAPIS_COMMONS_WIDGET_INTERFACE_H_ diff --git a/src/modules/tizen/WidgetInterface/config.cmake b/src/modules/tizen/WidgetInterface/config.cmake new file mode 100644 index 0000000..a69d23e --- /dev/null +++ b/src/modules/tizen/WidgetInterface/config.cmake @@ -0,0 +1,17 @@ + +get_current_path() + +set(WIDGET_INTERFACE_INCLUDE_DIRS + ${CURRENT_PATH} + PARENT_SCOPE +) + +SET(API_WIDGET_INTERFACE_PATH + ${CURRENT_PATH} + PARENT_SCOPE +) + +set(SRCS_WIDGET_INTERFACE + ${CURRENT_PATH}/WidgetInterface.cpp + PARENT_SCOPE +) diff --git a/src/modules/tizen/config.cmake b/src/modules/tizen/config.cmake new file mode 100644 index 0000000..82b25da --- /dev/null +++ b/src/modules/tizen/config.cmake @@ -0,0 +1,3 @@ +include_config_file(Widget)
+include_config_file(StorageEvent)
+include_config_file(LocalStorage)
\ No newline at end of file diff --git a/src/plugin-loading/CMakeLists.txt b/src/plugin-loading/CMakeLists.txt new file mode 100644 index 0000000..7341e01 --- /dev/null +++ b/src/plugin-loading/CMakeLists.txt @@ -0,0 +1,86 @@ +# 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 CMakeLists.txt +# @author Lukasz Marek (l.marek@samsung.com) +# @version 1.0 +# + +PKG_SEARCH_MODULE(plugin-types REQUIRED wrt-plugins-types) +PKG_SEARCH_MODULE(dpl REQUIRED dpl-efl) +PKG_SEARCH_MODULE(dpl-event REQUIRED dpl-event-efl) +PKG_SEARCH_MODULE(dpl-wrt-dao-ro REQUIRED dpl-wrt-dao-ro) +PKG_SEARCH_MODULE(webkit2 REQUIRED ewebkit2) + +SET(PLUGIN_LOADING_SOURCES + ${PLUGIN_LOADING_DIRS}/plugin_logic.cpp + ${PLUGIN_LOADING_DIRS}/plugin.cpp + ${PLUGIN_LOADING_DIRS}/plugin_model.cpp + ${PLUGIN_LOADING_DIRS}/explorer.cpp + ${PLUGIN_LOADING_DIRS}/plugin_iframe_support.cpp + ${PLUGIN_LOADING_DIRS}/plugin_container_support.cpp + ${PLUGIN_LOADING_DIRS}/plugin_property_support.cpp + ${PLUGIN_LOADING_DIRS}/javascript_interface.cpp + ${PLUGIN_LOADING_DIRS}/js_page_session.cpp +) + +INCLUDE_DIRECTORIES( + ${PLUGIN_MODULE_SRC_DIR} + ${PLUGIN_LOADING_DIRS} + ${webkit2_INCLUDE_DIRS} + ${plugin-types_INCLUDE_DIRS} +) + +ADD_LIBRARY(${TARGET_PLUGIN_LOADING_LIB} SHARED + ${PLUGIN_LOADING_SOURCES} +) + +SET_TARGET_PROPERTIES(${TARGET_PLUGIN_LOADING_LIB} PROPERTIES + COMPILE_DEFINITIONS LOG_TAG="${LOG_TAG}") + +SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES + COMPILE_DEFINITIONS LOG_TAG="${LOG_TAG}") + +SET_TARGET_PROPERTIES(${TARGET_PLUGIN_LOADING_LIB} PROPERTIES + COMPILE_FLAGS -fPIC + LINK_FLAGS "-Wl,--as-needed -Wl,--hash-style=both" +) + +SET_TARGET_PROPERTIES(${TARGET_PLUGIN_LOADING_LIB} PROPERTIES + SOVERSION ${CMAKE_PROJECT_API_VERSION} + VERSION ${CMAKE_PROJECT_VERSION} +) + +TARGET_LINK_LIBRARIES(${TARGET_PLUGIN_LOADING_LIB} + ${dpl_LIBRARIES} + ${dpl-event_LIBRARIES} + ${dpl-wrt-dao-ro_LIBRARIES} + ${TARGET_COMMONS} + ${TARGET_JS_OVERLAY} + wrt-plugins-tizen-service-event # static lib + wrt-plugins-softkeyboardchange-event # static lib +) + +INSTALL(TARGETS ${TARGET_PLUGIN_LOADING_LIB} + DESTINATION lib + PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE + GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE +) + +# For wrt-plugins +INSTALL(FILES + ${PLUGIN_LOADING_DIRS}/plugin_logic.h + ${PLUGIN_LOADING_DIRS}/js_types.h + DESTINATION include/wrt-plugin-loading) diff --git a/src/plugin-loading/explorer.cpp b/src/plugin-loading/explorer.cpp new file mode 100644 index 0000000..c6e3969 --- /dev/null +++ b/src/plugin-loading/explorer.cpp @@ -0,0 +1,386 @@ +/* + * 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 explorer.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @author Yunchan Cho (yunchan.cho@samgsung.com) + * @version + * @brief + */ + +#include <algorithm> +#include <dpl/foreach.h> +#include <dpl/log/wrt_log.h> +#include "explorer.h" +#include "plugin_property_support.h" + +// JS overlay +#include <js_overlay_types.h> + +namespace { +//const char* SEPARATOR = "."; +const std::string GLOBAL_OBJECT_NAME = "window"; +} + +using namespace std; +using namespace PluginModule; +using namespace WrtPlugins::W3C; + +Explorer::Explorer(JSGlobalContextRef context) : + m_context(context) +{ + if (!context) { + WrtLogW("Context is NULL"); + return; + } + + m_globalObject = + JavaScriptInterfaceSingleton::Instance().getGlobalObject(context); + + //register main frame; + m_iframeSupport.registerIframe(m_globalObject); + + m_propertySupport.reset(new WindowPropertySupport(m_context)); +} + +Explorer::~Explorer() +{ +} + +JSObjectPtr Explorer::getJSObjectProperty(const std::string& propertyName, + JSObjectPtr object) +{ + return JavaScriptInterfaceSingleton::Instance().getJSObjectProperty( + m_context, object, propertyName); +} + +JSObjectPtr Explorer::getProperty( + const string& requestedProperty, + JSObjectPtr providedObject) +{ + WrtLogD("Requested Property: %s", requestedProperty.c_str()); + + if (!providedObject) { + WrtLogW("Provided object is empty"); + return JSObjectPtr(); + } + + std::string currentObjectName; + std::string currentPropertyRequested = requestedProperty; + JSObjectPtr currentObject = providedObject; + + while (true) { + auto pos = currentPropertyRequested.find("."); + if (pos == string::npos) { + return getJSObjectProperty(currentPropertyRequested, currentObject); + } + + //check if requested object has child + currentObjectName = currentPropertyRequested.substr(0, pos); + + if (currentPropertyRequested.size() <= pos + 1) { + WrtLogW("Wrong name of requested property"); + return JSObjectPtr(); + } + currentPropertyRequested = currentPropertyRequested.substr(pos + 1); + + currentObject = getJSObjectProperty(currentObjectName, currentObject); + if (!currentObject) { + WrtLogW("Failed to get property: %s", currentObjectName.c_str()); + return JSObjectPtr(); + } + } +} + +bool Explorer::registerObject(const JSObjectDeclarationPtr& declaration, + JSGlobalContextRef context) +{ + bool retValue; + + if (declaration->getParentName() == GLOBAL_OBJECT_NAME) { + retValue = register_(declaration, m_globalObject, context); + } else { //PIM support + //it should be master object name + string masterName = declaration->getParentName(); + auto pos = masterName.find("."); + if (string::npos != pos) { + WrtLogW("ParentName not allowed"); + return false; + } + auto masterObject = getJSObjectProperty(masterName, m_globalObject); + if (masterObject->getObject() == 0) { + return false; + } + retValue = registerObject(declaration, + masterName, + masterObject, + context); + } + + if (declaration->checkIframesSupported()) { + m_iframeSupport.registerDeclaration(declaration); + // m_iframeSupport.invokeCallbackForMainFrame(m_context, + // declaration, + // newObject); + } + + return retValue; +} + +bool Explorer::registerObject(const JSObjectDeclarationPtr& declaration, + const std::string& providedObjectName, + JSObjectPtr providedObject, + JSGlobalContextRef context) +{ + WrtLogD("%s <- %s", providedObjectName.c_str(), declaration->getName().c_str()); + std::string fullParentName = declaration->getParentName(); + + if (fullParentName == providedObjectName) { + WrtLogD("Provided object was matched!!"); + return register_(declaration, providedObject, context); + } + + //check if object exists in fullParentName + auto pos = fullParentName.find(providedObjectName); + if (pos == string::npos) { + WrtLogW("Object: %s should be child of: %s but you provided object: %s", + declaration->getName().c_str(), + declaration->getParentName().c_str(), + providedObjectName.c_str()); + return false; + } + + if (fullParentName.size() <= pos + providedObjectName.size() + 1) { + WrtLogW("Invalid object name"); + return false; + } + + auto currentRequesteProperty = + fullParentName.substr(pos + providedObjectName.size() + 1); + + JSObjectPtr jsObject = getProperty( + currentRequesteProperty, providedObject); + + if (!jsObject->getObject()) { + WrtLogW("Object: %s should be child of: %s. you provided object: %s but object is null", + declaration->getName().c_str(), + declaration->getParentName().c_str(), + providedObjectName.c_str()); + return false; + } + + return register_(declaration, jsObject, context); +} + +bool Explorer::register_(const JSObjectDeclarationPtr& declaration, + JSObjectPtr parent, + JSGlobalContextRef context) +{ + WrtLogD("Registration object: %s <- %s", + declaration->getParentName().c_str(), + declaration->getName().c_str()); + AssertMsg(parent, "parent object is NULL"); + + typedef JSObjectDeclaration::Options JO; + + JSGlobalContextRef gContext = (context == NULL) ? m_context : context; + JSObjectPtr objectInstance = JavaScriptInterfaceSingleton::Instance(). + createObject(gContext, declaration); + + JavaScriptInterfaceSingleton::Instance().setObjectProperty( + gContext, + parent, + declaration->getName(), + objectInstance); + + //notice + if (declaration->getOptions() && + (declaration->getOptions()->getIframeNotice() == + JO::IFrameNotice::AlwaysNotice)) + { + declaration->getOptions()->invokeCallback(gContext, + parent->getObject(), + objectInstance->getObject()); + } + + return true; +} + +void Explorer::registerObjectIntoIframe( + const JSObjectDeclarationPtr& declaration, + JSObjectPtr frameObject, + JSGlobalContextRef context) +{ + if (declaration->getParentName() == GLOBAL_OBJECT_NAME) { + WrtLogD("Connect to Global object of IFRAME"); + register_(declaration, frameObject, context); + return; + } + + //PIM SUPPORT + { + WrtLogD("Connect to NOT global object of IFRAME"); + //it should be master object name + string masterName = declaration->getParentName(); + auto pos = masterName.find("."); + if (string::npos != pos) { + WrtLogW("ParentName not allowed"); + return; + } + auto masterObject = getJSObjectProperty(masterName, frameObject); + if (!masterObject->getObject()) { + WrtLogW("Object not exist in frame"); + return; + } + register_(declaration, masterObject, context); + } +} + +void Explorer::loadFrame(JSGlobalContextRef context) +{ + JSObjectPtr frameObject = + JavaScriptInterfaceSingleton::Instance().getGlobalObject(context); + + if (frameObject->getObject() == m_globalObject->getObject()) { + // Main page was already loaded from constructor + WrtLogW("Main page loaded"); + return; + } + + m_iframeSupport.registerIframe(frameObject); + + auto iframeObjects = m_iframeSupport.getIframeObjects(); + + FOREACH(object, iframeObjects) + { + WrtLogD("Register object: %s", (*object)->getName().c_str()); + registerObjectIntoIframe(*object, frameObject, context); + } +} + +void Explorer::unloadFrame(JSGlobalContextRef context) +{ + JSObjectPtr frameObject = + JavaScriptInterfaceSingleton::Instance().getGlobalObject(context); + m_iframeSupport.unregisterIframe(frameObject); +} + +void Explorer::removePluginsFromIframes() +{ + if (m_iframeSupport.hasIframes()) { + JavaScriptInterfaceSingleton::Instance().removeIframes(m_context); + } +} + +void Explorer::deregisterObject(const JSObjectDeclarationPtr& declaration) +{ + if (GLOBAL_OBJECT_NAME != declaration->getParentName()) { + WrtLogW("Ignored remove property %s", declaration->getName().c_str()); + return; + } + + JavaScriptInterfaceSingleton::Instance(). + removeObjectProperty(m_context, + m_globalObject, + declaration->getName()); +} + +void Explorer::cleanIframesData() +{ + m_iframeSupport.clean(); +} + +void Explorer::callEventListeners(CustomEventType /*eventType*/, void* /*data*/) +{ +#if 0 // deprecated + using namespace WrtPlugins::Tizen; + // get iframe objects from javascript global context + JavaScriptInterface::ObjectsListPtr frameLists = + JavaScriptInterfaceSingleton::Instance().getIframesList(m_context); + + // get main frame object from javascript global context + JSObjectRef mainFrame = JSContextGetGlobalObject(m_context); + frameLists->push_back(JSObjectPtr(new JSObject(mainFrame))); + + if (eventType == ServiceCustomEvent) { + using namespace WrtDeviceApis::TizenServiceEvent::Api; + // set user data of js callback function for 'appservice' js event + ITizenServiceEventPtr event = ITizenServiceEventPtr( + new TizenServiceEvent()); + event->setScale(m_propertySupport->getScale()); + event->setBundle(m_propertySupport->getBundle()); + + // call js callback function for 'appservice' js event on each frame + FOREACH(it, *frameLists) + { + JSObjectRef frame = static_cast<JSObjectRef>((**it).Get()->getObject()); + + auto eventPriv = + new JSTizenServiceEventPrivateObject(m_context, event); + JSObjectRef eventObject = + JSObjectMake(m_context, + JSTizenServiceEvent::getClassRef(), eventPriv); + + AddEventListenerSupport::CallCustomEventListenersFromIFrame( + frame, eventType, eventObject); + } + } else if (eventType == SoftKeyboardChangeCustomEvent) { + using namespace WrtDeviceApis::SoftKeyboardChangeEvent::Api; + if (!data) { + WrtLogD("no ime size"); + return; + } + + // set user data of js callback function for 'softkeyboardchange' js + // event + SoftKeyboardChangeArgs* args = + static_cast<SoftKeyboardChangeArgs *>(data); + ISoftKeyboardChangeEventPtr event = + ISoftKeyboardChangeEventPtr( + new SoftKeyboardChangeEvent( + args->state, + args->width, + args->height)); + WrtLogD("softkeyboard event's state: " << args->state); + + // call js callback function for 'softkeyboardchange' js event on each + // frame + FOREACH(it, *frameLists) + { + JSObjectRef frame = static_cast<JSObjectRef>((**it).Get()->getObject()); + + auto eventPriv = + new JSSoftKeyboardChangeEventPrivateObject(m_context, event); + JSObjectRef eventObject = + JSObjectMake( + m_context, + JSSoftKeyboardChangeEvent::getClassRef(), + eventPriv); + + AddEventListenerSupport::CallCustomEventListenersFromIFrame( + frame, eventType, eventObject); + } + } else { + WrtLogD("Not supported custom event type"); + return; + } +#endif +} + +WindowPropertySupport* Explorer::getWindowPropertySupport() +{ + return m_propertySupport.get(); +} diff --git a/src/plugin-loading/explorer.h b/src/plugin-loading/explorer.h new file mode 100644 index 0000000..b47849c --- /dev/null +++ b/src/plugin-loading/explorer.h @@ -0,0 +1,102 @@ +/* + * 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 explorer.h + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ + +#ifndef WRT_SRC_PLUGIN_SERVICE_EXPLORER_H_ +#define WRT_SRC_PLUGIN_SERVICE_EXPLORER_H_ + +#include <string> + +#include <dpl/noncopyable.h> +#include <dpl/exception.h> +#include <memory> + +#include <Commons/JSObject.h> +#include <Commons/JSObjectDeclaration.h> +//JSGlobalContextRef +#include "javascript_interface.h" +#include "plugin_iframe_support.h" +#include "plugin_property_support.h" + +//JS overlay +#include <js_overlay_types.h> + +using namespace PluginModule; +using namespace WrtPlugins::W3C; + +class Explorer : private DPL::Noncopyable +{ + public: + explicit Explorer(JSGlobalContextRef context); + ~Explorer(); + + //register to global frame + bool registerObject(const JSObjectDeclarationPtr& declaration, + JSGlobalContextRef context); + + bool registerObject (const JSObjectDeclarationPtr& declaration, + const std::string& parentObjectName, + JSObjectPtr parentObject, + JSGlobalContextRef context); + + void deregisterObject(const JSObjectDeclarationPtr& declaration); + + // new load/unload frame API + void loadFrame(JSGlobalContextRef context); + void unloadFrame(JSGlobalContextRef context); + + void removePluginsFromIframes(); + void cleanIframesData(); + void callEventListeners(CustomEventType eventType, void* data); + + WindowPropertySupport* getWindowPropertySupport(); + + private: + + IframesSupport m_iframeSupport; + + //globalContext + JSGlobalContextRef m_context; + + //global object of main frame + JSObjectPtr m_globalObject; + + std::unique_ptr<WindowPropertySupport> m_propertySupport; + + private: + void registerObjectIntoIframe(const JSObjectDeclarationPtr& declaration, + JSObjectPtr parentObject, + JSGlobalContextRef context); + + bool register_(const JSObjectDeclarationPtr& declaration, + JSObjectPtr parent, + JSGlobalContextRef context); + + JSObjectPtr getJSObjectProperty(const std::string& propertyName, + JSObjectPtr object); + + JSObjectPtr getProperty( + const std::string& requestedProperty, + JSObjectPtr providedObject); +}; + +typedef std::shared_ptr<Explorer> ExplorerPtr; +#endif diff --git a/src/plugin-loading/javascript_interface.cpp b/src/plugin-loading/javascript_interface.cpp new file mode 100644 index 0000000..ec1c6b8 --- /dev/null +++ b/src/plugin-loading/javascript_interface.cpp @@ -0,0 +1,433 @@ +/* + * 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 plugin_webkit.h + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of webkit js plugin + * accessing routines in EFL + */ + +#include <memory> +#include <vector> +#include <string> + +#include <javascript_interface.h> + +#include <dpl/log/wrt_log.h> +#include <dpl/singleton_impl.h> +#include <dpl/foreach.h> +#include <dpl/noncopyable.h> + +#include <JavaScriptCore/JavaScript.h> +#include <JavaScriptCore/JSObjectRef.h> + +IMPLEMENT_SINGLETON(JavaScriptInterface) + +#define CHECK_JSVALUE_IS_UNDEFINED_RETURN(context, object, ret) \ + if (JSValueIsUndefined(context, object)) { \ + WrtLogE("Object %s is undefined", #object); \ + return ret; \ + } + +#define CHECK_JSOBJECT_IS_NULL_RETURN(object, ret) \ + if (!object) { \ + WrtLogE("Object %s is NULL", #object); \ + return ret; \ + } + +namespace { +/** + * Converts JSStringRef to std::string + * */ +std::string toString(const JSStringRef& arg) +{ + Assert(arg); + std::string result; + size_t jsSize = JSStringGetMaximumUTF8CStringSize(arg); + if (jsSize > 0) { + ++jsSize; + std::unique_ptr<char[]> buffer(new char[jsSize]); + size_t written = JSStringGetUTF8CString(arg, buffer.get(), jsSize); + if (written > jsSize) { + WrtLogE("Conversion could not be fully performed."); + return std::string(); + } + result = buffer.get(); + } + + return result; +} + +/** + * Converts JSValueRef to std::string + * */ +std::string toString(JSContextRef ctx, JSValueRef value) +{ + Assert(ctx && value); + std::string result; + JSStringRef str = JSValueToStringCopy(ctx, value, NULL); + result = toString(str); + JSStringRelease(str); + return result; +} + +JSValueRef getProperty(JSContextRef ctx, JSValueRef value, const char* name) +{ + Assert(ctx && value && name); + JSValueRef result = NULL; + JSObjectRef obj = JSValueToObject(ctx, value, NULL); + if (obj) { + JSStringRef str = JSStringCreateWithUTF8CString(name); + result = JSObjectGetProperty(ctx, obj, str, NULL); + JSStringRelease(str); + } + return result; +} + +JSValueRef getPropertyObj(JSContextRef ctx, JSObjectRef obj, const char* name) +{ + Assert(ctx && obj && name); + JSStringRef str = JSStringCreateWithUTF8CString(name); + JSValueRef result = JSObjectGetProperty(ctx, obj, str, NULL); + JSStringRelease(str); + return result; +} + +JSObjectRef getJSGlobalObject(JSGlobalContextRef context) +{ + return JSContextGetGlobalObject(context); +} +} + +typedef JSValueRef (*JSCFunction)( + JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + +void JavaScriptInterface::setObjectProperty(JSGlobalContextRef context, + const JSObjectPtr& parentObject, + const std::string &propertyName, + const JSObjectPtr& propertyObject) +{ + WrtLogD("JSObjectSetProperty(\"%s\")", propertyName.c_str()); + + //create name + JSStringRef name = JSStringCreateWithUTF8CString(propertyName.c_str()); + //set property + JSObjectSetProperty( + static_cast<JSGlobalContextRef>(context), + static_cast<JSObjectRef>(parentObject->getObject()), name, + static_cast<JSObjectRef>(propertyObject->getObject()), + kJSPropertyAttributeReadOnly, 0); + + JSStringRelease(name); +} + +void JavaScriptInterface::removeObjectProperty(JSGlobalContextRef context, + const JSObjectPtr& parentObject, + const std::string &propertyName) +{ + if (!context) { + //nothing to do -> no context + return; + } + WrtLogD("JSObjectDeleteProperty(\"%s\")", propertyName.c_str()); + + JSStringRef name = JSStringCreateWithUTF8CString(propertyName.c_str()); + JSObjectDeleteProperty( + static_cast<JSGlobalContextRef>(context), + static_cast<JSObjectRef>(parentObject->getObject()), name, 0); + + JSStringRelease(name); +} + +JavaScriptInterface::PropertiesList JavaScriptInterface:: + getObjectPropertiesList( + JSGlobalContextRef context, + const JSObjectPtr& object) const +{ + PropertiesList result; + JSPropertyNameArrayRef properties = JSObjectCopyPropertyNames( + static_cast<JSGlobalContextRef>(context), + static_cast<JSObjectRef>(object->getObject())); + std::size_t count = JSPropertyNameArrayGetCount(properties); + result.reserve(count); + WrtLogD("properties count %d", count); + for (std::size_t i = 0; i < count; ++i) { + JSStringRef property = JSPropertyNameArrayGetNameAtIndex(properties, i); + result.push_back(toString(property)); + } + JSPropertyNameArrayRelease(properties); + return result; +} + +JSObjectPtr JavaScriptInterface::makeJSFunctionObject( + JSGlobalContextRef context, + const std::string &name, + js_function_impl functionImplementation) const +{ + WrtLogD("JSObjectMakeFunctionWithCallback(\"%s\")", name.c_str()); + JSStringRef jsFunName = JSStringCreateWithUTF8CString(name.c_str()); + + JSObjectRef object = JSObjectMakeFunctionWithCallback( + context, + jsFunName, + reinterpret_cast<JSObjectCallAsFunctionCallback>( + functionImplementation)); + + JSStringRelease(jsFunName); + return JSObjectPtr(new JSObject(static_cast<void*>(object))); +} + +JSObjectPtr JavaScriptInterface::makeJSClassObject( + JSGlobalContextRef context, + JSObjectDeclaration::ConstClassTemplate classTemplate) const +{ + WrtLogD("JSObjectMake"); + JSObjectRef object = JSObjectMake( + context, + static_cast<JSClassRef>( + const_cast<JSObjectDeclaration::ClassTemplate>(classTemplate)), + NULL); + return JSObjectPtr(new JSObject(object)); +} + +JSObjectPtr JavaScriptInterface::makeJSObjectBasedOnInterface( + JSGlobalContextRef context, + const std::string &interfaceName) const +{ + WrtLogD("makeJSObjectBasedOnInterface(\"%s\")", interfaceName.c_str()); + JSObjectPtr jsInterfaceObj = getJSObjectProperty(context, + getGlobalObject( + context), + interfaceName); + JSObjectRef object = JSObjectCallAsConstructor(context, + static_cast<JSObjectRef>( + jsInterfaceObj-> + getObject()), 0, + NULL, + NULL); + return JSObjectPtr(new JSObject(static_cast<void*>(object))); +} + +JSObjectPtr JavaScriptInterface::makeJSInterface( + JSGlobalContextRef context, + JSObjectDeclaration::ConstClassTemplate classTemplate, + JSObjectDeclaration::ConstructorCallback constructorCallback) const +{ + WrtLogD("makeJSInterface"); + JSObjectRef object = JSObjectMakeConstructor(context, + static_cast<JSClassRef>( + const_cast< + JSObjectDeclaration:: + ClassTemplate>( + classTemplate)), + reinterpret_cast< + JSObjectCallAsConstructorCallback>( + constructorCallback) + ); + return JSObjectPtr(new JSObject(static_cast<void*>(object))); +} + +JSObjectPtr JavaScriptInterface::createObject( + JSGlobalContextRef context, + const JSObjectDeclarationPtr& + declaration) +{ + typedef JSObjectDeclaration::Options JO; + + if (declaration->getOptions()) { + switch (declaration->getOptions()->getType()) { + case JO::ClassType::Function: + return makeJSFunctionObject( + context, + declaration->getName(), + declaration->getOptions()->getFunctionImpl()); + + case JO::ClassType::Class: + if (declaration->getInterfaceName().empty()) { + return makeJSClassObject( + context, + declaration->getClassTemplate()); + } else { + return makeJSObjectBasedOnInterface( + context, + declaration->getInterfaceName()); + } + + case JO::ClassType::Interface: + return makeJSInterface( + context, + /* product class template */ + declaration->getClassTemplate(), + declaration->getConstructorCallback()); + + default: + WrtLogE("Invalid class type. Making empty JS object."); + return JSObjectPtr(new JSObject( + JSObjectMake(context, NULL, NULL))); + } + } else { + WrtLogD("No declaration options"); + return JSObjectPtr(new JSObject( + JSObjectMake( + context, + static_cast<JSClassRef>( + const_cast<JSObjectDeclaration:: + ClassTemplate>( + declaration->getClassTemplate())), + NULL))); + } +} + +JSObjectPtr JavaScriptInterface::getGlobalObject(JSGlobalContextRef context) +const +{ + return JSObjectPtr(new JSObject(static_cast<JSObject::RealObject>( + JSContextGetGlobalObject(static_cast< + JSGlobalContextRef>( + context))))); +} + +JSObjectPtr JavaScriptInterface::copyObjectToIframe( + JSGlobalContextRef context, + const JSObjectPtr& iframe, + const std::string& name) +{ + WrtLogD("copyObjectToIframe(%s)", name.c_str()); + + JSGlobalContextRef jsGlobalContext = + static_cast<JSGlobalContextRef>(context); + + JSObjectRef globalObject = JSContextGetGlobalObject(jsGlobalContext); + + JSValueRef requestedObject = getPropertyObj(jsGlobalContext, + globalObject, + name.c_str()); + CHECK_JSVALUE_IS_UNDEFINED_RETURN(jsGlobalContext, + requestedObject, + JSObjectPtr()); + + JSStringRef requestedObjectStr = + JSStringCreateWithUTF8CString(name.c_str()); + + JSObjectSetProperty(jsGlobalContext, + static_cast<JSObjectRef>(iframe->getObject()), + requestedObjectStr, + requestedObject, + kJSPropertyAttributeReadOnly, + NULL); + + JSStringRelease(requestedObjectStr); + + return JSObjectPtr( + new JSObject(const_cast<OpaqueJSValue*>(requestedObject))); +} + +JavaScriptInterface::ObjectsListPtr +JavaScriptInterface::getIframesList(JSGlobalContextRef ctx) const +{ + JSGlobalContextRef context = static_cast<JSGlobalContextRef>(ctx); + JSObjectRef globalObject = JSContextGetGlobalObject(context); + ObjectsListPtr retList = getIframesList(context, globalObject); + + return retList; +} + +JavaScriptInterface::ObjectsListPtr +JavaScriptInterface::getIframesList(JSContextRef context, + JSObjectRef globalObject) const +{ + JSValueRef frames = getPropertyObj(context, globalObject, "frames"); + CHECK_JSVALUE_IS_UNDEFINED_RETURN(context, frames, ObjectsListPtr()); + + JSObjectRef frames_o = JSValueToObject(context, frames, NULL); + CHECK_JSOBJECT_IS_NULL_RETURN(frames_o, ObjectsListPtr()); + + JSValueRef len = getPropertyObj(context, frames_o, "length"); + CHECK_JSVALUE_IS_UNDEFINED_RETURN(context, len, ObjectsListPtr()); + + size_t count = JSValueToNumber(context, len, NULL); + WrtLogD("frames_o.length = %d", count); + + ObjectsListPtr retList = ObjectsListPtr(new ObjectsList()); + + for (size_t i = 0; i < count; ++i) { + std::stringstream ss; + ss << i; + JSValueRef frame = getPropertyObj(context, + frames_o, + ss.str().c_str()); + if (JSValueIsUndefined(context, frame)) { + WrtLogE("Selected frame is null: frame[%d]", i); + continue; + } + JSObjectRef frame_obj = JSValueToObject(context, frame, NULL); + if (!frame_obj) { + WrtLogE("frame_obj is NULL."); + continue; + } + retList->push_back(JSObjectPtr(new JSObject(frame_obj))); + ObjectsListPtr childList = getIframesList(context, frame_obj); + + retList->merge(*childList); + } + + return retList; +} + +JSObjectPtr JavaScriptInterface::getJSObjectProperty(JSGlobalContextRef ctx, + const JSObjectPtr& frame, + const std::string& name) +const +{ + WrtLogD("makeJSObjectBasedOnInterface(\"%s\")", name.c_str()); + JSObjectRef frame_js = static_cast<JSObjectRef>(frame->getObject()); + JSValueRef property = getPropertyObj(ctx, frame_js, name.c_str()); + JSObjectRef objProp = JSValueToObject(ctx, property, NULL); + + return JSObjectPtr(new JSObject(objProp)); +} + +void JavaScriptInterface::removeIframes(JSGlobalContextRef context) +{ + const char* deleteIframesScript = + "frame_set = document.getElementsByTagName('iframe');" + "len = frame_set.length;" + "for(i=0; i< len; i++)" + " frame_set[0].parentNode.removeChild(frame_set[0]); "; + + JSGlobalContextRef ctx = static_cast<JSGlobalContextRef>(context); + + JSStringRef script_src = JSStringCreateWithUTF8CString(deleteIframesScript); + + JSEvaluateScript(ctx, script_src, 0, 0, 0, 0); + + JSStringRelease(script_src); +} + +void JavaScriptInterface::invokeGarbageCollector(JSGlobalContextRef context) +{ + WrtLogD("Garbage collection"); + JSGarbageCollect(context); + JSGarbageCollect(context); + JSGarbageCollect(context); + JSGarbageCollect(context); +} diff --git a/src/plugin-loading/javascript_interface.h b/src/plugin-loading/javascript_interface.h new file mode 100644 index 0000000..c3aa171 --- /dev/null +++ b/src/plugin-loading/javascript_interface.h @@ -0,0 +1,112 @@ +/* + * 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 JavaScriptInterface.h + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @author Piotr Fatyga (p.fatyga@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef WRT_SRC_PLUGIN_SERVICE_WEBKIT_INTERFACE_H_ +#define WRT_SRC_PLUGIN_SERVICE_WEBKIT_INTERFACE_H_ + +#include <string> +#include <vector> +#include <memory> +#include <list> +#include <dpl/noncopyable.h> +#include <dpl/singleton.h> +#include <Commons/JSObjectDeclaration.h> +#include <Commons/JSObject.h> + +//forward declaration of JSConectexRef +extern "C" { +typedef const struct OpaqueJSContext* JSContextRef; +typedef struct OpaqueJSContext* JSGlobalContextRef; +typedef struct OpaqueJSValue* JSObjectRef; +} + +class JavaScriptInterface : DPL::Noncopyable +{ + public: + + typedef std::vector<std::string> PropertiesList; + + typedef std::list<JSObjectPtr> ObjectsList; + typedef std::shared_ptr<ObjectsList> ObjectsListPtr; + + public: + JSObjectPtr getGlobalObject(JSGlobalContextRef context) const; + + // object creation + JSObjectPtr createObject(JSGlobalContextRef context, + const JSObjectDeclarationPtr& declaration); + + //properties + void setObjectProperty(JSGlobalContextRef context, + const JSObjectPtr& parentObject, + const std::string &propertyName, + const JSObjectPtr& propertyObject); + + void removeObjectProperty(JSGlobalContextRef context, + const JSObjectPtr& parentObject, + const std::string &propertyName); + + PropertiesList getObjectPropertiesList(JSGlobalContextRef context, + const JSObjectPtr& object) const; + + JSObjectPtr copyObjectToIframe(JSGlobalContextRef context, + const JSObjectPtr& iframe, + const std::string& name); + + ObjectsListPtr getIframesList(JSGlobalContextRef context) const; + + void removeIframes(JSGlobalContextRef context); + + void invokeGarbageCollector(JSGlobalContextRef context); + + JSObjectPtr getJSObjectProperty(JSGlobalContextRef ctx, + const JSObjectPtr& frame, + const std::string& name) const; + + private: + JavaScriptInterface() + {} + + JSObjectPtr makeJSFunctionObject( + JSGlobalContextRef context, + const std::string &name, + js_function_impl functionImplementation) const; + JSObjectPtr makeJSClassObject( + JSGlobalContextRef context, + JSObjectDeclaration::ConstClassTemplate classTemplate) const; + JSObjectPtr makeJSObjectBasedOnInterface( + JSGlobalContextRef context, + const std::string &interfaceName) const; + JSObjectPtr makeJSInterface( + JSGlobalContextRef context, + JSObjectDeclaration::ConstClassTemplate classTemplate, + JSObjectDeclaration::ConstructorCallback constructorCallback) const; + + ObjectsListPtr getIframesList(JSContextRef context, + JSObjectRef object) const; + + friend class DPL::Singleton<JavaScriptInterface>; +}; + +typedef DPL::Singleton<JavaScriptInterface> JavaScriptInterfaceSingleton; + +#endif diff --git a/src/plugin-loading/js_page_session.cpp b/src/plugin-loading/js_page_session.cpp new file mode 100644 index 0000000..16fd6d7 --- /dev/null +++ b/src/plugin-loading/js_page_session.cpp @@ -0,0 +1,599 @@ +/* + * 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 plugin_logic.cpp + * @author Piotr Fatyga (p.fatyga@samsung.com) + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of plugin and + * feature loading routines + * @brief This code is intended to work behind view controller + */ + +#include "plugin_logic.h" + +#include <dpl/assert.h> +#include <dpl/log/wrt_log.h> +#include <dpl/foreach.h> +#include <dpl/singleton_impl.h> +#include <dpl/wrt-dao-ro/widget_dao_read_only.h> +#include <dpl/wrt-dao-ro/common_dao_types.h> +#include <dpl/wrt-dao-ro/global_config.h> +#include <dpl/wrt-dao-ro/wrt_db_types.h> + +#include <JavaScriptCore/JavaScript.h> + +#include <string> +#include <sys/types.h> +#include <sys/stat.h> +#include <dirent.h> +#include <errno.h> +#include <fstream> +#include <map> +#include <list> +#include <vector> +#include <algorithm> +#include <cstring> + +#include <wrt_plugin_export.h> +#include <js_overlay_types.h> + +#include "explorer.h" +#include "plugin.h" +#include "plugin_model.h" +#include "javascript_interface.h" +#include "js_function_manager.h" +#include "plugin_container_support.h" + +#include "js_page_session.h" + +using namespace std; +using namespace WrtDB; +using namespace WrtPlugins::W3C; + +namespace { +const char *LIBRARY_PATH_SEPARATOR = "/"; +} + +class JSPageSession::Impl +{ + private: + typedef std::set<PluginPtr> LoadedPlugins; + typedef std::set<JSGlobalContextRef> LoadedContexts; + + private: + ///< Widget handle using this session + WidgetHandle m_widgetHandle; + + //view for this session + JSGlobalContextRef m_context; + + bool m_sessionStarted; + + ///< JS object explorer for this session + Explorer* m_objectExplorer; + + PluginContainerSupportPtr m_pluginsSupport; + + ///< All loaded plugins. Each one must be unloaded. Plugins means + //set of features connected with such plugin (library) + LoadedPlugins m_loadedPlugins; + + // Set of currently loaded web pages' contexts. These contexts are + // exactly matching with each frames' global context. + LoadedContexts m_loadedContexts; + + private: + PluginPtr loadLibrary(PluginModelPtr& pluginModel); + + void installStandardFunctions(); + void installRootPlugins(); + void installRequestedFeatures(); + + //returns true if success or false if failed + bool installPlugin(PluginModelPtr plugin); + bool installPluginOnDemand(PluginModelPtr plugin, + JavaScriptObject& parentObject, + JSGlobalContextRef context); + + void unloadPluginsFromSession(); + + public: + Impl(const PluginContainerSupportPtr& containerSupport); + ~Impl(); + + // Widget session + void startSession(WidgetHandle widgetHandle, + JSGlobalContextRef view, + double scaleFactor, + const char* encodedBundle, + const char* theme); + + void stopSession(); + + void performLibrariesUnload(); + + bool loadPluginOnDemand(const WrtDB::DbPluginHandle &pluginHandle, + JavaScriptObject& parentObject, + JSGlobalContextRef context); + + void loadFrame(JSGlobalContextRef context); + void unloadFrame(JSGlobalContextRef context); + + void setCustomProperties(double scaleFactor, + const char* encodedBundle, + const char* theme); + + void dispatchJavaScriptEvent(CustomEventType eventType, void* data); +}; + +JSPageSession::Impl::Impl(const PluginContainerSupportPtr& support) : + m_widgetHandle(0), + m_context(NULL), + m_sessionStarted(false), + m_objectExplorer(NULL) +{ + WrtLogD("Initializing Page Session"); + m_pluginsSupport = support; +} + +JSPageSession::Impl::~Impl() +{ + if (m_sessionStarted) { + WrtLogE("Must stop widget session before exit!"); + stopSession(); + } + + WrtLogD("Deinitializing Page Session"); +} + + void JSPageSession::Impl::installStandardFunctions() + { + WrtLogD("========== install standard Functions START =========="); + + //add standard functions + FOREACH(it, JsFunctionManagerSingleton::Instance().getFunctions()) { + m_objectExplorer->registerObject(*it, NULL); + } + + WrtLogD("========== install standard Functions END =========="); + } + +void JSPageSession::Impl::installRootPlugins() +{ + WrtLogD("========== install root Functions START =========="); + + PluginContainerSupport::PluginsList rootPlugins = + m_pluginsSupport->getRootPlugins(); + FOREACH(it, rootPlugins) + { + installPlugin(*it); + } + + WrtLogD("========== install root Functions END =========="); +} + +bool JSPageSession::Impl::installPlugin(PluginModelPtr plugin) +{ + AssertMsg(plugin, "Plugin Model is NULL"); + PluginPtr library = loadLibrary(plugin); + + if (!library) { + WrtLogE("Loading library failed"); + return false; + } + + WrtLogD("Install Plugin : %s", library->GetFileName().c_str()); + + // Register new class + FOREACH(it, *(library->GetClassList())) + { + if (!m_objectExplorer->registerObject(*it, NULL)) { + WrtLogE("Object Registration failed : %s", (*it)->getName().c_str()); + } + } + return true; +} + +void JSPageSession::Impl::installRequestedFeatures() +{ + WrtLogD("========== install requested Features START =========="); + + std::list<std::string> allowedFeatures = + m_pluginsSupport->getAllowedFeatures(m_widgetHandle); + + PluginContainerSupport::PluginsList allowedPlugins; + + FOREACH(feature, allowedFeatures) + { + WrtLogD("Processing feature: %s", (*feature).c_str()); + + PluginModelPtr plugin = m_pluginsSupport->getPluginForFeature(*feature); + + if (!plugin) { + WrtLogW("It didn't have plugins! : %s", (*feature).c_str()); + continue; + } + + ImplementedObjectsList implObjs = + PluginDAOReadOnly:: + getImplementedObjectsForPluginHandle(plugin->Handle.Get()); + + FOREACH(obj, implObjs) + { + WrtLogD("Processing object: %s", (*obj).c_str()); + /* This can be optimalized, but would need extra data in database. + * There should be a list of features that are allowed to be + * installed at widget start */ + if (obj->find(".") == obj->rfind(".")) { + allowedPlugins.push_back(plugin); + WrtLogD("Plugin will be added: %s", plugin->LibraryName.Get().c_str()); + break; + } + } + } + + FOREACH(plugin, allowedPlugins) + { + WrtLogD("Installation plugin: %s", (*plugin)->LibraryName.Get().c_str()); + installPlugin(*plugin); + } + + WrtLogD("========== install requested Features END =========="); +} + +bool JSPageSession::Impl::loadPluginOnDemand( + const WrtDB::DbPluginHandle &pluginHandle, + JavaScriptObject& parentObject, + JSGlobalContextRef context) +{ + AssertMsg(parentObject.instance && !parentObject.name.empty(), + "Wrong arguments"); + + if (!m_sessionStarted) { + WrtLogW("Session not started"); + return false; + } + // //TODO here may be a bug. if plugin contains feature rejected and + // accepted + // WrtLogD("Installing feature : " << widgetFeature.name); + // if (widgetFeature.rejected) { + // WrtLogW("This api-feature was rejected"); + // return; + // } + // + // auto plugin = m_pluginsSupport->getPluginModelById(pluginHandle); + // if (!plugin) { + // WrtLogE("Failed to load plugin. plugin handle: %i", pluginHandle); + // return false; + // } + m_pluginsSupport->registerPluginModel(pluginHandle); + return installPluginOnDemand( + m_pluginsSupport->getPluginModelById(pluginHandle), + parentObject, + context); +} + +bool JSPageSession::Impl::installPluginOnDemand(PluginModelPtr plugin, + JavaScriptObject& parentObject, + JSGlobalContextRef context) +{ + AssertMsg(plugin, "Plugin Model is NULL"); + PluginPtr library = loadLibrary(plugin); + + if (!library) { + WrtLogE("Loading library failed"); + return false; + } + + WrtLogD("Install Plugin %s", library->GetFileName().c_str()); + + if (!(parentObject.instance)) { + WrtLogE("NULL pointer value"); + return false; + } + + JSObjectPtr parent(new JSObject(parentObject.instance)); + + if (!parent->getObject()) { + WrtLogE("NULL pointer value"); + assert(false); + return false; + } + + FOREACH(it, *(library->GetClassList())) + { + bool installationStatus = + m_objectExplorer->registerObject(*it, + parentObject.name, + parent, + context); + + if (!installationStatus) { + WrtLogE("Object Registration failed : %s; Parent object name: %s", + (*it)->getName().c_str(), + parentObject.name.c_str()); + return false; + } + } + + WrtLogD("Plugin on demand registration completed"); + return true; +} + +void JSPageSession::Impl::setCustomProperties(double scaleFactor, + const char* encodedBundle, + const char* theme) +{ + m_objectExplorer->getWindowPropertySupport() + ->setScaleToNavigatorProperty(scaleFactor); + m_objectExplorer->getWindowPropertySupport() + ->setBundleToWindowProperty(encodedBundle); + m_objectExplorer->getWindowPropertySupport() + ->setThemeToNavigatorProperty(theme); +} + +void JSPageSession::Impl::dispatchJavaScriptEvent(CustomEventType eventType, + void* data) +{ + // Check if session is already started + if (!m_sessionStarted) { + WrtLogW("Session not started!"); + return; + } + m_objectExplorer->callEventListeners(eventType, data); +} + +void JSPageSession::Impl::startSession(WidgetHandle widgetHandle, + JSGlobalContextRef context, + double scaleFactor, + const char* encodedBundle, + const char* theme) +{ + + // Check if corresponding session if not already created + if (m_sessionStarted) { + WrtLogW("Session already started!"); + return; + } + + // Create js object explorer object + m_objectExplorer = new Explorer(context); + + m_sessionStarted = true; + m_widgetHandle = widgetHandle; + m_loadedPlugins.clear(); + m_context = context; + + // Register standard features + installStandardFunctions(); + + WidgetDAOReadOnly dao(m_widgetHandle); + WidgetType appType = dao.getWidgetType(); + if (appType == WrtDB::APP_TYPE_TIZENWEBAPP) { + installRootPlugins(); + } + // Register special features + installRequestedFeatures(); + + // set scale, bundle as window's property + setCustomProperties(scaleFactor, encodedBundle, theme); +} + +void JSPageSession::Impl::stopSession() +{ + if (!m_sessionStarted) { + WrtLogW("Session not started!"); + return; + } + + unloadPluginsFromSession(); + m_sessionStarted = false; +} + +void JSPageSession::Impl::unloadPluginsFromSession() +{ + m_objectExplorer->removePluginsFromIframes(); + m_objectExplorer->cleanIframesData(); + + // delete js object for overlayed js functions + FOREACH(it, JsFunctionManagerSingleton::Instance().getFunctions()) + { + m_objectExplorer->deregisterObject(*it); + } + + // delete js object for plugins + FOREACH(pluginIt, m_loadedPlugins) + { + WrtLogD("Unregistering plugin %s", (*pluginIt)->GetFileName().c_str()); + (*pluginIt)->OnWidgetStop(m_widgetHandle); + + FOREACH(it, *((*pluginIt)->GetClassList())) { + m_objectExplorer->deregisterObject(*it); + } + } + + JavaScriptInterfaceSingleton::Instance().invokeGarbageCollector(m_context); + + m_loadedPlugins.clear(); + + delete m_objectExplorer; + m_objectExplorer = NULL; +} + +void JSPageSession::Impl::performLibrariesUnload() +{ +#if 0 + WrtLogD("Perform library unload"); + + size_t unloadedLibraries = 0; + + FOREACH(pluginIt, m_loadedPlugins) + { + WrtLogD("Preparing library: %s", (*pluginIt)->LibraryName.Get().c_str()); + + PluginPtr plugin = (*pluginIt)->LibraryInstance.get(); + if (!plugin) { + WrtLogW("Library not loaded " << (*pluginIt)->LibraryName.Get()); + continue; + } + unloadedLibraries++; + (*pluginIt)->LibraryInstance.Set(PluginPtr()); + } + + WrtLogD("unloaded " << unloadedLibraries << " unreferenced libraries!"); +#endif +} + +PluginPtr JSPageSession::Impl::loadLibrary(PluginModelPtr& pluginModel) +{ + PluginPtr pluginLib = pluginModel->LibraryInstance.Get(); + if (!pluginLib) { + std::string path = pluginModel->LibraryPath.Get() + + std::string(LIBRARY_PATH_SEPARATOR) + + pluginModel->LibraryName.Get(); + + pluginLib = Plugin::LoadFromFile(path); + + if (!pluginLib) { + WrtLogE("Loading library failed"); + } else { + pluginModel->LibraryInstance.Set(pluginLib); + + WrtLogD("On widget start"); + // This is first time for this plugin, start widget Session + pluginLib->OnWidgetStart( + m_widgetHandle); + m_loadedPlugins.insert(pluginLib); + + FOREACH(context, m_loadedContexts) + { + pluginLib->OnFrameLoad(*context); + } + } + } else { + WrtLogD("Get from LibraryInstance"); + WrtLogD("On widget start"); + // This is first time for this plugin, start widget Session + pluginLib->OnWidgetStart( + m_widgetHandle); + m_loadedPlugins.insert(pluginLib); + + FOREACH(context, m_loadedContexts) + { + pluginLib->OnFrameLoad(*context); + } + } + + return pluginLib; +} + +void JSPageSession::Impl::loadFrame(JSGlobalContextRef context) +{ + if (!m_sessionStarted) { + WrtLogW("Session NOT started!"); + return; + } + + m_loadedContexts.insert(context); + + FOREACH(pluginIt, m_loadedPlugins) + { + WrtLogD("Try to call 'OnFrameLoad' callback : %s", + (*pluginIt)->GetFileName().c_str()); + (*pluginIt)->OnFrameLoad(context); + } + + m_objectExplorer->loadFrame(context); +} + +void JSPageSession::Impl::unloadFrame(JSGlobalContextRef context) +{ + if (!m_sessionStarted) { + WrtLogW("Session NOT started!"); + return; + } + + m_loadedContexts.erase(context); + + FOREACH(pluginIt, m_loadedPlugins) + { + WrtLogD("Try to call 'OnFrameUnload' callback : %s", + (*pluginIt)->GetFileName().c_str()); + (*pluginIt)->OnFrameUnload(context); + } + + m_objectExplorer->unloadFrame(context); +} + +void JSPageSession::startSession(WidgetHandle widgetHandle, + JSGlobalContextRef ctx, + double scaleFactor, + const char* encodedBundle, + const char* theme) +{ + m_impl->startSession(widgetHandle, ctx, scaleFactor, encodedBundle, theme); +} + +void JSPageSession::stopSession() +{ + m_impl->stopSession(); +} + +void JSPageSession::performLibrariesUnload() +{ + m_impl->performLibrariesUnload(); +} + +bool JSPageSession::loadPluginOnDemand( + const WrtDB::DbPluginHandle &pluginHandle, + JavaScriptObject& parentObject, + JSGlobalContextRef context) +{ + return m_impl->loadPluginOnDemand(pluginHandle, parentObject, context); +} + +void JSPageSession::setCustomProperties(double scaleFactor, + const char* encodedBundle, + const char* theme) +{ + m_impl->setCustomProperties(scaleFactor, encodedBundle, theme); +} + +void JSPageSession::dispatchJavaScriptEvent(CustomEventType eventType, + void* data) +{ + m_impl->dispatchJavaScriptEvent(eventType, data); +} + +void JSPageSession::loadFrame(JSGlobalContextRef context) +{ + m_impl->loadFrame(context); +} + +void JSPageSession::unloadFrame(JSGlobalContextRef context) +{ + m_impl->unloadFrame(context); +} + +JSPageSession::JSPageSession(const PluginContainerSupportPtr& containerSupport) + : + m_impl(new JSPageSession::Impl(containerSupport)) +{} + +JSPageSession::~JSPageSession() +{} diff --git a/src/plugin-loading/js_page_session.h b/src/plugin-loading/js_page_session.h new file mode 100644 index 0000000..e4bf13e --- /dev/null +++ b/src/plugin-loading/js_page_session.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. + */ +/** + * @file js_page_session.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 1.0 + */ +#ifndef WRT_PLUGIN_JS_PAGE_SESSION_H_ +#define WRT_PLUGIN_JS_PAGE_SESSION_H_ + +#include <memory> +#include <vector> +#include <dpl/wrt-dao-ro/plugin_dao_read_only.h> +#include <js_overlay_types.h> +#include "js_types.h" + +using namespace WrtPlugins::W3C; + +class JSPageSession +{ + public: + // Widget session + void startSession(WidgetHandle widgetHandle, + JSGlobalContextRef view, + double scaleFactor, + const char* encodedBundle, + const char* theme); + + void stopSession(); + + //TODO im not sure if it is needed. I think it should be hidden + void performLibrariesUnload(); + bool loadPluginOnDemand(const WrtDB::DbPluginHandle &pluginHandle, + JavaScriptObject& parentObject, + JSGlobalContextRef context); + + void loadFrame(JSGlobalContextRef context); + void unloadFrame(JSGlobalContextRef context); + + // reset custom window properties. (Tizen requirements) + void setCustomProperties(double scaleFactor, + const char* encodedBundle, + const char* theme); + + void dispatchJavaScriptEvent(CustomEventType eventType, void* data); + + JSPageSession(const PluginContainerSupportPtr& containerSupport); + + virtual ~JSPageSession(); + + private: + class Impl; + std::unique_ptr<Impl> m_impl; +}; + +typedef std::shared_ptr<JSPageSession> JSPageSessionPtr; + +#endif // PLUGIN_LOGIC_H diff --git a/src/plugin-loading/js_types.h b/src/plugin-loading/js_types.h new file mode 100644 index 0000000..076582e --- /dev/null +++ b/src/plugin-loading/js_types.h @@ -0,0 +1,37 @@ +/* + * 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_types.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 1.0 + */ + +#ifndef WRT_PLUGIN_JS_TYPES_H_ +#define WRT_PLUGIN_JS_TYPES_H_ + +//forward declaration of JSConectexRef +extern "C" { +typedef struct OpaqueJSContext* JSGlobalContextRef; +typedef struct OpaqueJSValue* JSObjectRef; +} + +struct JavaScriptObject +{ + JSObjectRef instance; + std::string name; +}; + +#endif diff --git a/src/plugin-loading/plugin.cpp b/src/plugin-loading/plugin.cpp new file mode 100644 index 0000000..00c5a28 --- /dev/null +++ b/src/plugin-loading/plugin.cpp @@ -0,0 +1,229 @@ +/* + * 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 plugin.cpp + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of plugin + */ +#include "plugin.h" +#include <dpl/log/wrt_log.h> +#include <dpl/assert.h> +#include <dlfcn.h> + +Plugin::Plugin(const std::string &fileName, + void *libHandle, + on_widget_start_proc *apiOnWidgetStart, + on_widget_init_proc *apiOnWidgetInit, + on_widget_stop_proc *apiOnWidgetStop, + on_frame_load_proc* apiOnFrameLoad, + on_frame_unload_proc* apiOnFrameUnload, + const ClassPtrList &apiClassList) : + m_fileName(fileName), + m_libHandle(libHandle), + m_apiOnWidgetStart(apiOnWidgetStart), + m_apiOnWidgetInit(apiOnWidgetInit), + m_apiOnWidgetStop(apiOnWidgetStop), + m_apiOnFrameLoad(apiOnFrameLoad), + m_apiOnFrameUnload(apiOnFrameUnload), + m_apiClassList(apiClassList) +{} + +Plugin::~Plugin() +{ + WrtLogD("Unloading plugin library: %s", m_fileName.c_str()); + + // Unload library + if (dlclose(m_libHandle) != 0) { + WrtLogE("Cannot close plugin handle"); + } else { + WrtLogD("Library is unloaded"); + } +} + +PluginPtr Plugin::LoadFromFile(const std::string& fileName) +{ + static bool logEnable = (getenv("WRT_LOAD_PLUGINS_LOG_ENABLE") != NULL); + + WrtLogD("LoadFromFile %s", fileName.c_str()); + + void *dllHandle; + dllHandle = dlopen(fileName.c_str(), RTLD_LAZY); + + WrtLogD("dlopen() done!"); + + if (dllHandle == NULL) { + const char* error = (const char*)dlerror(); + WrtLogE("Failed to load plugin: %s. Reason: %s", + fileName.c_str(), + (error != NULL ? error : "unknown")); + PluginPtr empty; + return empty; + } + + // Load new plugin API + on_widget_start_proc *onWidgetStartProcPtr = NULL; + on_widget_stop_proc *onWidgetStopProcPtr = NULL; + on_widget_init_proc *onWidgetInitProcPtr = NULL; + on_frame_load_proc *onFrameLoadProcPtr = NULL; + on_frame_unload_proc *onFrameUnloadProcPtr = NULL; + + const js_entity_definition_t *rawClassList = NULL; + get_widget_entity_map_proc *getWidgetEntityMapProcPtr = NULL; + + onWidgetStartProcPtr = + reinterpret_cast<on_widget_start_proc *>( + dlsym(dllHandle, PLUGIN_WIDGET_START_PROC_NAME)); + onWidgetInitProcPtr = + reinterpret_cast<on_widget_init_proc *>( + dlsym(dllHandle, PLUGIN_WIDGET_INIT_PROC_NAME)); + onWidgetStopProcPtr = + reinterpret_cast<on_widget_stop_proc *>( + dlsym(dllHandle, PLUGIN_WIDGET_STOP_PROC_NAME)); + onFrameLoadProcPtr = + reinterpret_cast<on_frame_load_proc *>( + dlsym(dllHandle, PLUGIN_FRAME_LOAD_PROC_NAME)); + onFrameUnloadProcPtr = + reinterpret_cast<on_frame_unload_proc *>( + dlsym(dllHandle, PLUGIN_FRAME_UNLOAD_PROC_NAME)); + getWidgetEntityMapProcPtr = + reinterpret_cast<get_widget_entity_map_proc *>( + dlsym(dllHandle, PLUGIN_GET_CLASS_MAP_PROC_NAME)); + + if (getWidgetEntityMapProcPtr) { + rawClassList = (*getWidgetEntityMapProcPtr)(); + } else { + rawClassList = + static_cast<const js_entity_definition_t *>(dlsym(dllHandle, + PLUGIN_CLASS_MAP_NAME)); + } + + if (NULL == onWidgetStartProcPtr || NULL == onWidgetStopProcPtr || + /*NULL == onWidgetInitProcPtr ||*/ NULL == rawClassList) + { + if (logEnable) { + WrtLogW("#####"); + WrtLogW("##### Warning: The following plugin does not support new plugin API."); + WrtLogW("##### Old plugin API is deprecated. Please update it to new API"); + WrtLogW("#####"); + WrtLogW("##### Plugin: %s has got deprecated or invalid API", fileName.c_str()); + WrtLogW("#####"); + } + + // Will not load plugin + dlclose(dllHandle); + + PluginPtr empty; + return empty; + } + + if (logEnable) { + WrtLogD("#####"); + WrtLogD("##### Plugin: %s supports new plugin API", fileName.c_str()); + WrtLogD("#####"); + WrtLogD("##### Class map:"); + } + + const js_entity_definition_t *rawEntityListIterator = rawClassList; + ClassPtrList classList(new Plugin::ClassList()); + + // Parse all class definitions + while (rawEntityListIterator->parent_name != NULL && + rawEntityListIterator->object_name != NULL) + { + if (logEnable) + { + // Logging + WrtLogD("#####"); + WrtLogD("##### [%s]", rawEntityListIterator->object_name); + WrtLogD("##### Interface: %s", rawEntityListIterator->interface_name); + WrtLogD("##### Parent: %s", rawEntityListIterator->parent_name); + } + + // Register class + classList->push_back(ClassPtr(new Class(rawEntityListIterator))); + + // Go to next class + ++rawEntityListIterator; + } + + // Load export table + WrtLogD("Plugin successfuly loaded"); + + // Insert to loaded modules list + + PluginPtr instance(new Plugin(fileName, + dllHandle, + onWidgetStartProcPtr, + onWidgetInitProcPtr, + onWidgetStopProcPtr, + onFrameLoadProcPtr, + onFrameUnloadProcPtr, + classList)); + + return instance; +} + +std::string Plugin::GetFileName() const +{ + return m_fileName; +} + +void Plugin::OnWidgetStart(WidgetHandle widgetId) +{ + if (NULL != m_apiOnWidgetStart) { + (*m_apiOnWidgetStart)(widgetId); + WrtLogD("Called!"); + } +} + +void Plugin::OnWidgetInit(feature_mapping_interface_t* mapping) +{ + AssertMsg(NULL != mapping, "NULL mapping interface provided"); + if (NULL != m_apiOnWidgetInit) { + (*m_apiOnWidgetInit)(mapping); + WrtLogD("Called!"); + } +} + +void Plugin::OnWidgetStop(WidgetHandle widgetId) +{ + if (NULL != m_apiOnWidgetStop) { + (*m_apiOnWidgetStop)(widgetId); + WrtLogD("Called!"); + } +} + +void Plugin::OnFrameLoad(java_script_context_t context) +{ + if (NULL != m_apiOnFrameLoad) { + (*m_apiOnFrameLoad)(context); + WrtLogD("Called!"); + } +} + +void Plugin::OnFrameUnload(java_script_context_t context) +{ + if (NULL != m_apiOnFrameUnload) { + (*m_apiOnFrameUnload)(context); + WrtLogD("Called!"); + } +} + +const Plugin::ClassPtrList Plugin::GetClassList() const +{ + return m_apiClassList; +} diff --git a/src/plugin-loading/plugin.h b/src/plugin-loading/plugin.h new file mode 100644 index 0000000..0eaa1a5 --- /dev/null +++ b/src/plugin-loading/plugin.h @@ -0,0 +1,93 @@ +/* + * 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 plugin.h + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of plugin + */ +#ifndef WRT_SRC_PLUGIN_SERVICE_PLUGIN_H_ +#define WRT_SRC_PLUGIN_SERVICE_PLUGIN_H_ + +#include <list> +#include <map> +#include <string> +#include <dpl/atomic.h> +#include <memory> +#include <dpl/noncopyable.h> +#include <wrt_plugin_export.h> +#include <Commons/JSObjectDeclaration.h> +#include <dpl/wrt-dao-ro/wrt_db_types.h> + +class Plugin; +typedef std::shared_ptr<Plugin> PluginPtr; + +class Plugin : private DPL::Noncopyable +{ + public: + typedef JSObjectDeclaration Class; + typedef JSObjectDeclarationPtr ClassPtr; + typedef std::list<ClassPtr> ClassList; + typedef std::shared_ptr<ClassList> ClassPtrList; + + private: + ///< Plug-in identifier. Currently plug-in file name is used as the ID + std::string m_fileName; + + ///< Handle for the plug-in library. A plug-in is a dynamic loadable library + void* m_libHandle; + + // Plugin API + on_widget_start_proc* m_apiOnWidgetStart; + on_widget_init_proc* m_apiOnWidgetInit; + on_widget_stop_proc* m_apiOnWidgetStop; + on_frame_load_proc* m_apiOnFrameLoad; + on_frame_unload_proc* m_apiOnFrameUnload; + const ClassPtrList m_apiClassList; + + Plugin(const std::string &fileName, + void *libHandle, + on_widget_start_proc* apiOnWidgetStart, + on_widget_init_proc* apiOnWidgetInit, + on_widget_stop_proc* apiOnWidgetStop, + on_frame_load_proc* apiOnFrameLoad, + on_frame_unload_proc* apiOnFrameUnload, + const ClassPtrList &apiClassList); + + public: + virtual ~Plugin(); + + // Loading + static PluginPtr LoadFromFile(const std::string &fileName); + + // Filename + std::string GetFileName() const; + + // API + void OnWidgetStart(WidgetHandle widgetId); + + void OnWidgetInit(feature_mapping_interface_t *interface); + + void OnWidgetStop(WidgetHandle widgetId); + + void OnFrameLoad(java_script_context_t context); + + void OnFrameUnload(java_script_context_t context); + + const ClassPtrList GetClassList() const; +}; + +#endif // PLUGIN_H diff --git a/src/plugin-loading/plugin_container_support.cpp b/src/plugin-loading/plugin_container_support.cpp new file mode 100644 index 0000000..00eb216 --- /dev/null +++ b/src/plugin-loading/plugin_container_support.cpp @@ -0,0 +1,276 @@ +/* + * 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 plugin_container_support.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 1.0 + */ + +#include "plugin_container_support.h" + +#include <fstream> + +#include <dpl/log/wrt_log.h> +#include <dpl/foreach.h> +#include <dpl/wrt-dao-ro/feature_dao_read_only.h> +#include <dpl/wrt-dao-ro/global_config.h> + +using namespace WrtDB; + +#include <dpl/wrt-dao-ro/widget_dao_read_only.h> + +PluginContainerSupport::PluginContainerSupport() : + m_initialized(false), + m_widgetHandle(0) +{ + // Reading root plugins list from so files + readRootPluginsList(); +} + +PluginContainerSupport::~PluginContainerSupport() +{ + // Remove all plugin models + m_pluginModels.clear(); + + // Remove all feature models + m_featureModels.clear(); + } + +void PluginContainerSupport::Initialize(WidgetHandle widgetHandle) +{ + if (isInitialized() == true && m_widgetHandle != widgetHandle) { + // re-initialize required + m_initialized = false; + + m_pluginModels.clear(); + m_featureModels.clear(); + } + + if (isInitialized() == false) { + m_initialized = true; + m_widgetHandle = widgetHandle; + + readAllowedPlugins(widgetHandle); + readRootPlugins(widgetHandle); + } +} + +std::list<std::string> PluginContainerSupport::getAllowedFeatures( + WidgetHandle widgetHandle) const +{ + //TODO it has to return LIST NOT SET!!! + WidgetDAOReadOnly widgetDao(widgetHandle); + DbWidgetFeatureSet features = widgetDao.getFeaturesList(); + + std::list<std::string> allowedFeatures; + FOREACH(it, features) { + WrtLogD("Loading api-feature: %ls", it->name.c_str()); + if (it->rejected) { + WrtLogW("Api-feature was rejected by ace. (Api-feature name: %ls)", + it->name.c_str()); + continue; + } + + allowedFeatures.push_back(DPL::ToUTF8String(it->name)); + } + return allowedFeatures; +} + +void PluginContainerSupport::readAllowedPlugins(WidgetHandle widgetHandle) +{ + std::list<std::string> allowedFeatures; + auto requested = getAllowedFeatures(widgetHandle); + FOREACH(f, requested) + { + allowedFeatures.push_back(*f); + } + + FeatureData* dt = NULL; + std::map<FeatureHandle, + FeatureData> featureDataList = FeatureDAOReadOnly::GetFeatures( + allowedFeatures); + DeviceCapList deviceCapabilities = + FeatureDAOReadOnly::GetDevCapWithFeatureHandle(); + FOREACH(data, featureDataList) { + dt = &(data->second); + registerPluginModel(dt->pluginHandle); + registerFeatureModel(data->first, dt, deviceCapabilities); + } +} + +void PluginContainerSupport::readRootPlugins(WidgetHandle widgetHandle) +{ + WidgetDAOReadOnly dao(widgetHandle); + WidgetType appType = dao.getWidgetType(); + if (appType == WrtDB::APP_TYPE_TIZENWEBAPP) { + FOREACH(it_rootPluginHandle, m_rootPluginsList) + { + WrtLogD("*it_rootPluginHandle: %d", *it_rootPluginHandle); + registerPluginModel(*it_rootPluginHandle); + } + } else { + WrtLogD("Not defined app type"); + } +} + +void PluginContainerSupport::registerFeatureModel( + FeatureHandle handle, + FeatureData* data, + DeviceCapList + deviceCapabilities) +{ + FeatureModelPtr model = getFeatureModel(handle); + if (model) { + WrtLogD("Model for feature: %d already created", handle); + return; + } + + WrtLogD("Creating Model for feature: %d", handle); + + model.reset(new FeatureModel(handle)); + + std::set<std::string> devCapList; + auto ret = deviceCapabilities.equal_range(handle); + for (auto devCapIt = ret.first; devCapIt != ret.second; devCapIt++) { + devCapList.insert((*devCapIt).second); + } + model->SetData(data->featureName, devCapList, data->pluginHandle); + m_featureModels.insert(model); +} + +void PluginContainerSupport::registerPluginModel(DbPluginHandle handle) +{ + PluginModelPtr model = getPluginModelById(handle); + + if (model) { + WrtLogD("Model for plugin: %d already registered", handle); + return; + } + + if (PluginDAOReadOnly::INSTALLATION_COMPLETED != + PluginDAOReadOnly::getInstallationStateForHandle(handle)) + { + WrtLogW("Failed To CreateModel for handle %d", handle); + return; + } + + Try { + model.reset(new PluginModel(handle)); + } Catch(WrtDB::PluginDAOReadOnly::Exception::PluginNotExist) { + // database changed between receiving plugin handle and creating PluginModel + WrtLogD("Failed to create PluginModel - database may be changed"); + return; + } + + WrtLogD("Model Created. Handle: %d, name: %s", + handle, + model->LibraryName.Get().c_str()); + + m_pluginModels.insert(model); +} + +void PluginContainerSupport::readRootPluginsList() +{ + WrtLogD("Reading root plugins list from so files..."); + m_rootPluginsList = PluginDAOReadOnly::getRootPluginHandleList(); +} + +FeatureModelPtr +PluginContainerSupport::getFeatureModel(const std::string &name) const +{ + FOREACH(iter, m_featureModels) + { + if ((*iter)->Name.Get() == name) { + return *iter; + } + } + + return FeatureModelPtr(); +} + +FeatureModelPtr +PluginContainerSupport::getFeatureModel(const FeatureHandle handle) const +{ + FOREACH(iter, m_featureModels) + { + if ((*iter)->FHandle.Get() == handle) { + return *iter; + } + } + + return FeatureModelPtr(); +} + +PluginModelPtr +PluginContainerSupport::getPluginModelById(DbPluginHandle handle) const +{ + FOREACH(pluginModel, m_pluginModels) + { + if ((*pluginModel)->Handle.Get() == handle) { + return *pluginModel; + } + } + + return PluginModelPtr(); +} + +PluginModelPtr +PluginContainerSupport::getPluginModel(const FeatureModelPtr &feature) const +{ + if (!feature) { + WrtLogD("Null Ptr for feature model"); + return PluginModelPtr(); + } else { + WrtLogD("Feature located in plugin: %d", feature->PHandle.Get()); + return getPluginModelById(feature->PHandle.Get()); + } +} + + PluginContainerSupport::PluginsList +PluginContainerSupport::getRootPlugins() const +{ + PluginsList plugins; + + FOREACH(it, m_rootPluginsList) { + PluginModelPtr plugin = getPluginModelById(*it); + if (!plugin) { + WrtLogW("PluginModel not found"); + continue; + } + + plugins.push_back(plugin); + } + + return plugins; +} + +PluginContainerSupport::PluginsList +PluginContainerSupport::getPluginsList() const +{ + PluginsList plugins; + + FOREACH(it, m_pluginModels) { + plugins.push_back(*it); + } + + return plugins; +} + +PluginModelPtr +PluginContainerSupport::getPluginForFeature(const std::string& featureName) +{ + return getPluginModel(getFeatureModel(featureName)); +} diff --git a/src/plugin-loading/plugin_container_support.h b/src/plugin-loading/plugin_container_support.h new file mode 100644 index 0000000..f710ee4 --- /dev/null +++ b/src/plugin-loading/plugin_container_support.h @@ -0,0 +1,102 @@ +/* + * 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 plugin_container_support.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 1.0 + */ +#ifndef PLUGIN_CONTAINER_SUPPORT_H +#define PLUGIN_CONTAINER_SUPPORT_H + +#include <memory> +#include <set> +#include <string> + +#include <dpl/wrt-dao-ro/feature_dao_read_only.h> +#include <dpl/wrt-dao-ro/feature_model.h> + +#include "plugin_model.h" + +class PluginContainerSupport +{ + public: + typedef std::list<WrtDB::FeatureModelPtr> FeaturesList; + typedef std::list<PluginModelPtr> PluginsList; + + private: + // Standard features + typedef std::list<std::string> StandardFeatureList; + + // Main feature list. Always equal to DB feature list + typedef std::set<WrtDB::FeatureModelPtr> FeatureModelContainer; + + // Main plugin list. Always equal to DB plugin list + typedef std::set<PluginModelPtr> PluginModelsContainer; + + WrtDB::PluginHandleList m_rootPluginsList; + + PluginModelsContainer m_pluginModels; + + FeatureModelContainer m_featureModels; + + bool m_initialized; + + WidgetHandle m_widgetHandle; + + private: + // Reading + void readRootPluginsList(); + + // Plugin models + typedef std::multimap<WrtDB::FeatureHandle, std::string> DeviceCapList; + void registerFeatureModel(WrtDB::FeatureHandle handle, + WrtDB::FeatureData* data, + DeviceCapList deviceCapabilities); + + WrtDB::FeatureModelPtr getFeatureModel(const std::string &name) const; + WrtDB::FeatureModelPtr getFeatureModel(WrtDB::FeatureHandle handle) const; + + PluginModelPtr getPluginModel(const WrtDB::FeatureModelPtr &feature) const; + + public: + PluginContainerSupport(); + + bool isInitialized() + { + return m_initialized; + } + bool isInitialized(WidgetHandle widgetHandle) + { + return (m_initialized && m_widgetHandle == widgetHandle); + } + void Initialize(WidgetHandle widgetHandle); + void registerPluginModel(WrtDB::DbPluginHandle handle); + std::list<std::string> getAllowedFeatures(WidgetHandle widgetHandle) const; + void readAllowedPlugins(WidgetHandle widgetHandle); + void readRootPlugins(WidgetHandle widgetHandle); + PluginsList getRootPlugins() const; + PluginsList getPluginsList() const; + + PluginModelPtr getPluginForFeature(const std::string& featureName); + + PluginModelPtr getPluginModelById(WrtDB::DbPluginHandle handle) const; + + ~PluginContainerSupport(); +}; + +typedef std::shared_ptr<PluginContainerSupport> PluginContainerSupportPtr; + +#endif // PLUGIN_CONTAINER_SUPPORT_H diff --git a/src/plugin-loading/plugin_iframe_support.cpp b/src/plugin-loading/plugin_iframe_support.cpp new file mode 100644 index 0000000..84c20b5 --- /dev/null +++ b/src/plugin-loading/plugin_iframe_support.cpp @@ -0,0 +1,77 @@ +/* + * 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 plugin_iframe_support.cpp + * @version 1.0 + * @brief + */ + +#include "plugin_iframe_support.h" + +#include <algorithm> +#include <dpl/foreach.h> +#include <dpl/log/wrt_log.h> + +void IframesSupport::registerDeclaration( + const JSObjectDeclarationPtr& declaration) +{ + WrtLogD("Registration iframes-supported plugins %s", declaration->getName().c_str()); + + if (declaration->getParentName().find('.') != std::string::npos) { + WrtLogE("The object will not be loaded to iframes"); + return; + } + m_iframesObjects.push_back(declaration); +} + +void IframesSupport::registerIframe(const JSObjectPtr& iframe) +{ + WrtLogD("LoadedIframes size: %d", m_loadedIframes.size() ); + + m_loadedIframes.insert(iframe); +} + +void IframesSupport::unregisterIframe(const JSObjectPtr& iframe) +{ + WrtLogD("LoadedIframes size: %d", m_loadedIframes.size() ); + + auto it_loaded = std::find_if(m_loadedIframes.begin(), + m_loadedIframes.end(), + std::bind2nd(EqualToJSObjectPtr(), iframe)); + //object not found, so thats the new iframe + if (it_loaded == m_loadedIframes.end()) { + WrtLogD("Nothing to unregister"); + return; + } + + m_loadedIframes.erase(it_loaded); +} + +bool IframesSupport::hasIframes() const +{ + return !m_loadedIframes.empty(); +} + +IframesSupport::DeclarationsList IframesSupport::getIframeObjects() const +{ + return m_iframesObjects; +} + +void IframesSupport::clean() +{ + m_iframesObjects.clear(); + m_loadedIframes.clear(); +} diff --git a/src/plugin-loading/plugin_iframe_support.h b/src/plugin-loading/plugin_iframe_support.h new file mode 100644 index 0000000..0c98768 --- /dev/null +++ b/src/plugin-loading/plugin_iframe_support.h @@ -0,0 +1,68 @@ +/* + * 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 plugin_iframe_support.h + * @version 1.0 + * @brief + */ + +#ifndef _WRTENGINE_SRC_PLUGINSERVICE_IFRAME_SUPPORT_H_ +#define _WRTENGINE_SRC_PLUGINSERVICE_IFRAME_SUPPORT_H_ + +#include <list> +#include <set> +#include <Commons/JSObjectDeclaration.h> +#include <Commons/JSObject.h> +#include "javascript_interface.h" + +class IframesSupport +{ + public: + typedef std::list<JSObjectDeclarationPtr> DeclarationsList; + + public: + void registerDeclaration(const JSObjectDeclarationPtr& declaration); + + void registerIframe(const JSObjectPtr& iframe); + + void unregisterIframe(const JSObjectPtr& iframe); + + DeclarationsList getIframeObjects() const; + + bool hasIframes() const; + + void clean(); + + private: + std::list<JSObjectDeclarationPtr> m_iframesObjects; + std::set<JSObjectPtr> m_loadedIframes; + + // used to find matching object from m_loadedIframes + struct EqualToJSObjectPtr + { + typedef JSObjectPtr first_argument_type; + typedef JSObjectPtr second_argument_type; + typedef bool result_type; + + result_type operator()(const first_argument_type &s1, + const second_argument_type &s2) const + { + return (s1->getObject() == s2->getObject()); + } + }; +}; + +#endif diff --git a/src/plugin-loading/plugin_logic.cpp b/src/plugin-loading/plugin_logic.cpp new file mode 100644 index 0000000..f5bcc4f --- /dev/null +++ b/src/plugin-loading/plugin_logic.cpp @@ -0,0 +1,418 @@ +/* + * 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 plugin_logic.cpp + * @author Piotr Fatyga (p.fatyga@samsung.com) + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of plugin and + * feature loading routines + * @brief This code is intended to work behind view controller + */ + +#include "plugin_logic.h" + +#include <dpl/assert.h> +#include <dpl/log/wrt_log.h> +#include <dpl/foreach.h> +#include <dpl/singleton_impl.h> +#include <dpl/wrt-dao-ro/widget_dao_read_only.h> +#include <dpl/wrt-dao-ro/common_dao_types.h> +#include <dpl/wrt-dao-ro/global_config.h> + +#include <JavaScriptCore/JavaScript.h> + +#include <string> +#include <sys/types.h> +#include <sys/stat.h> +#include <dirent.h> +#include <errno.h> +#include <fstream> +#include <map> +#include <list> +#include <vector> +#include <algorithm> +#include <cstring> + +#include <wrt_plugin_export.h> +#include <js_overlay_types.h> + +#include "explorer.h" +#include "plugin.h" +#include "plugin_model.h" +#include "javascript_interface.h" +#include "js_function_manager.h" +#include "plugin_container_support.h" + +#include "js_page_session.h" + +using namespace std; +using namespace WrtDB; +using namespace WrtPlugins::W3C; + +namespace { +const char *LIBRARY_PATH_SEPARATOR = "/"; +} + +class PluginLogic::Impl +{ + PluginContainerSupportPtr m_pluginsSupport; + + typedef std::map<JSContextRef, JSPageSessionPtr> PagesSessionsSet; + PagesSessionsSet m_sessions; + unsigned int m_windowHandle; + + public: + Impl(); + ~Impl(); + + // Widget session + void initSession(WidgetHandle widgetHandle); + void startSession(WidgetHandle widgetHandle, + JSGlobalContextRef context, + double scaleFactor, + const char* encodedBundle, + const char* theme); + + void stopSession(JSGlobalContextRef context); + + void performLibrariesUnload(); + + bool loadPluginOnDemand(const WrtDB::DbPluginHandle &pluginHandle, + JavaScriptObject& parentObject, + JSGlobalContextRef context); + + void loadFrame(JSGlobalContextRef context); + void unloadFrame(JSGlobalContextRef context); + + void setCustomProperties(JSGlobalContextRef ctx, + double scaleFactor, + const char* encodedBundle, + const char* theme); + + void dispatchJavaScriptEvent(JSGlobalContextRef ctx, + CustomEventType eventType, + void* data); + + unsigned int windowHandle() const; + void setWindowHandle(unsigned int handle); + + static bool s_sanityCheck; +}; + +IMPLEMENT_SINGLETON(PluginLogic); + +bool PluginLogic::Impl::s_sanityCheck = false; + +#define PLUGIN_LOGIC_SANITY_CHECK \ + if (!s_sanityCheck) \ + { \ + WrtLogE("Object is not available. Wrong flow occured"); \ + return; \ + } + +PluginLogic::Impl::Impl() : + m_windowHandle(0) +{ + s_sanityCheck = true; + + WrtLogD("Initializing Plugin Logic..."); + m_pluginsSupport = PluginContainerSupportPtr(new PluginContainerSupport()); + + // explicit call to keep singleton's lifetime until calling destructor. + JsFunctionManagerSingleton::Instance(); + JavaScriptInterfaceSingleton::Instance(); +} + +PluginLogic::Impl::~Impl() +{ + WrtLogD("called"); + + s_sanityCheck = false; + + FOREACH(it, m_sessions) + { + WrtLogW("Must stop widget session before exit!"); + it->second->stopSession(); + } +} + +void PluginLogic::initSession(WidgetHandle widgetHandle) +{ + m_impl->initSession(widgetHandle); +} + +void PluginLogic::startSession(WidgetHandle widgetHandle, + JSGlobalContextRef ctx, + double scaleFactor, + const char* encodedBundle, + const char* theme) +{ + m_impl->startSession(widgetHandle, ctx, scaleFactor, encodedBundle, theme); +} + +void PluginLogic::stopSession(JSGlobalContextRef context) +{ + m_impl->stopSession(context); +} + +void PluginLogic::performLibrariesUnload() +{ + WrtLogW("This function is DEPRECATED"); + // m_impl->performLibrariesUnload(); +} + +bool PluginLogic::loadPluginOnDemand( + const WrtDB::DbPluginHandle &pluginHandle, + JavaScriptObject& parentObject, + JSGlobalContextRef context) +{ + return m_impl->loadPluginOnDemand(pluginHandle, parentObject, context); +} + +void PluginLogic::loadPluginsIntoIframes(JSGlobalContextRef /*context*/) +{ + WrtLogW("This function is DEPRECATED"); +} + +void PluginLogic::setCustomProperties(double /*scaleFactor*/, + const char* /*encodedBundle*/, + const char* /*theme*/) +{ + WrtLogW("This function is DEPRECATED"); +} + +void PluginLogic::setCustomProperties(JSGlobalContextRef context, + double scaleFactor, + const char* encodedBundle, + const char* theme) +{ + m_impl->setCustomProperties(context, scaleFactor, encodedBundle, theme); +} + +void PluginLogic::dispatchJavaScriptEvent(CustomEventType /*eventType*/) +{ + WrtLogW("This function is DEPRECATED"); +} + +void PluginLogic::dispatchJavaScriptEvent(JSGlobalContextRef context, + CustomEventType eventType, + void *data) +{ + m_impl->dispatchJavaScriptEvent(context, eventType, data); +} + +void PluginLogic::loadFrame(JSGlobalContextRef context) +{ + m_impl->loadFrame(context); +} + +void PluginLogic::unloadFrame(JSGlobalContextRef context) +{ + m_impl->unloadFrame(context); +} + +unsigned int PluginLogic::windowHandle() const +{ + return m_impl->windowHandle(); +} + +void PluginLogic::setWindowHandle(unsigned int handle) +{ + m_impl->setWindowHandle(handle); +} + +PluginLogic::PluginLogic() : m_impl(new PluginLogic::Impl()) +{} + +PluginLogic::~PluginLogic() +{} + +void PluginLogic::Impl::initSession(WidgetHandle widgetHandle) +{ + WrtLogD(">---------------------[init session START]---------------------<"); + + m_pluginsSupport->Initialize(widgetHandle); + PluginContainerSupport::PluginsList rootPluginList = + m_pluginsSupport->getRootPlugins(); + + FOREACH(it, rootPluginList) + { + PluginModelPtr& pluginModel = *it; + PluginPtr pluginLib = pluginModel->LibraryInstance.Get(); + + if (!pluginLib) { + std::string path = pluginModel->LibraryPath.Get() + + std::string(LIBRARY_PATH_SEPARATOR) + + pluginModel->LibraryName.Get(); + + pluginLib = Plugin::LoadFromFile(path); + + if (!pluginLib) { + WrtLogW("Loading library failed"); + } else { + pluginModel->LibraryInstance.Set(pluginLib); + WrtLogD("pluginModel->LibraryInstance.Set() : %s", + pluginLib->GetFileName().c_str()); + } + } else { + WrtLogD("Already loaded"); + } + } + WrtLogD("========== init session END =========="); +} + +void PluginLogic::Impl::startSession(WidgetHandle widgetHandle, + JSGlobalContextRef context, + double scaleFactor, + const char* encodedBundle, + const char* theme) +{ + WrtLogD("========== start session START =========="); + + if (!m_pluginsSupport->isInitialized(widgetHandle)) { + m_pluginsSupport->Initialize(widgetHandle); + } + auto sessionIt = m_sessions.find(context); + + // Check if corresponding session if not already created + if (sessionIt != m_sessions.end()) { + WrtLogW("Session already started!"); + } else { + auto newSession = JSPageSessionPtr(new JSPageSession(m_pluginsSupport)); + newSession->startSession(widgetHandle, + context, + scaleFactor, + encodedBundle, + theme); + + m_sessions[context] = newSession; + } + WrtLogD("========== start session END =========="); +} + +void PluginLogic::Impl::stopSession(JSGlobalContextRef context) +{ + WrtLogD("========== stop session START =========="); + + auto sessionIt = m_sessions.find(context); + if (sessionIt == m_sessions.end()) { + WrtLogW("Session not exist!"); + } else { + sessionIt->second->stopSession(); + m_sessions.erase(sessionIt); + } + WrtLogD("========== stop session END =========="); +} + +bool PluginLogic::Impl::loadPluginOnDemand( + const WrtDB::DbPluginHandle &pluginHandle, + JavaScriptObject& parentObject, + JSGlobalContextRef context + ) +{ + WrtLogD("========== load ondemand plugin =========="); + + auto sessionIt = m_sessions.find(context); + if (sessionIt == m_sessions.end()) { + WrtLogW("Session not exist!"); + return false; + } + + return sessionIt->second->loadPluginOnDemand(pluginHandle, + parentObject, + context); +} + +void PluginLogic::Impl::loadFrame(JSGlobalContextRef context) +{ + WrtLogD("========== load frame START =========="); + PLUGIN_LOGIC_SANITY_CHECK + + auto sessionIt = m_sessions.find(context); + if (sessionIt == m_sessions.end()) { + WrtLogW("Session not exist!"); + } else { + sessionIt->second->loadFrame(context); + } + WrtLogD("========== load frame END =========="); +} + +void PluginLogic::Impl::unloadFrame(JSGlobalContextRef context) +{ + WrtLogD("========== unload frame START =========="); + PLUGIN_LOGIC_SANITY_CHECK + + auto sessionIt = m_sessions.find(context); + if (sessionIt == m_sessions.end()) { + WrtLogW("Session not exist!"); + } else { + sessionIt->second->unloadFrame(context); + + // I don't know why this session should be removed here. + // session list is removed also from stopSession(). + //m_sessions.erase(sessionIt); + } + WrtLogD("========== unload frame END =========="); +} + +void PluginLogic::Impl::setCustomProperties(JSGlobalContextRef context, + double scaleFactor, + const char* encodedBundle, + const char* theme) +{ + PLUGIN_LOGIC_SANITY_CHECK + + auto sessionIt = m_sessions.find(context); + if (sessionIt == m_sessions.end()) { + WrtLogW("Session not exist!"); + return; + } + + sessionIt->second->setCustomProperties(scaleFactor, + encodedBundle, + theme); +} + +void PluginLogic::Impl::dispatchJavaScriptEvent(JSGlobalContextRef context, + CustomEventType eventType, + void* data) +{ + PLUGIN_LOGIC_SANITY_CHECK + + auto sessionIt = m_sessions.find(context); + if (sessionIt == m_sessions.end()) { + WrtLogW("Session not exist!"); + return; + } + + sessionIt->second->dispatchJavaScriptEvent(eventType, data); +} + +unsigned int PluginLogic::Impl::windowHandle() const +{ + if (!s_sanityCheck) { + WrtLogE("Object is not available. Wrong flow occured"); + } + return m_windowHandle; +} + +void PluginLogic::Impl::setWindowHandle(unsigned int handle) +{ + PLUGIN_LOGIC_SANITY_CHECK + m_windowHandle = handle; +} diff --git a/src/plugin-loading/plugin_logic.h b/src/plugin-loading/plugin_logic.h new file mode 100644 index 0000000..579772d --- /dev/null +++ b/src/plugin-loading/plugin_logic.h @@ -0,0 +1,97 @@ +/* + * 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 plugin_logic.h + * @author Piotr Fatyga (p.fatyga@samsung.com) + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of plugin and feature + * loading routines + * @brief This code is intended to work behind view controller + */ +#ifndef PLUGIN_LOGIC_H +#define PLUGIN_LOGIC_H + +#include <memory> +#include <vector> +#include <set> +#include <dpl/singleton.h> +#include <dpl/noncopyable.h> +#include <dpl/wrt-dao-ro/plugin_dao_read_only.h> +#include <js_overlay_types.h> +#include <js_types.h> +#include <dpl/availability.h> +#include <dpl/wrt-dao-ro/wrt_db_types.h> + +using namespace WrtPlugins::W3C; + +class PluginLogic : DPL::Noncopyable +{ + public: + // Widget session + void initSession(WidgetHandle widgetHandle); + void startSession(WidgetHandle widgetHandle, + JSGlobalContextRef view, + double scaleFactor, + const char* encodedBundle, + const char* theme); + + void stopSession(JSGlobalContextRef context); + + //TODO im not sure if it is needed. I think it should be hidden + void performLibrariesUnload(); + bool loadPluginOnDemand(const WrtDB::DbPluginHandle &pluginHandle, + JavaScriptObject& parentObject, + JSGlobalContextRef context); + + DPL_DEPRECATED void loadPluginsIntoIframes(JSGlobalContextRef context); + + void loadFrame(JSGlobalContextRef context); + void unloadFrame(JSGlobalContextRef context); + + // reset custom window properties. (Tizen requirements) + DPL_DEPRECATED void setCustomProperties(double scaleFactor, + const char* encodedBundle, + const char* theme); + + void setCustomProperties(JSGlobalContextRef ctx, + double scaleFactor, + const char* encodedBundle, + const char* theme); + + DPL_DEPRECATED void dispatchJavaScriptEvent(CustomEventType eventType); + + void dispatchJavaScriptEvent(JSGlobalContextRef ctx, + CustomEventType eventType, + void* data); + + unsigned int windowHandle() const; + void setWindowHandle(unsigned int handle); + + private: + PluginLogic(); + ~PluginLogic(); + + class Impl; + std::unique_ptr<Impl> m_impl; + + friend class DPL::Singleton<PluginLogic>; +}; + +typedef DPL::Singleton<PluginLogic> PluginLogicSingleton; + +#endif // PLUGIN_LOGIC_H diff --git a/src/plugin-loading/plugin_model.cpp b/src/plugin-loading/plugin_model.cpp new file mode 100644 index 0000000..ee6dd6f --- /dev/null +++ b/src/plugin-loading/plugin_model.cpp @@ -0,0 +1,73 @@ +/* + * 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 plugin_model.cpp + * @author Pawel Sikorski (p.sikorski@samgsung.com) + * @author Przemyslaw Dobrowolski (p.dobrowolsk@samgsung.com) + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief This file contains PluginModel, PluginHandle definitions. + */ + +#include "plugin_model.h" +#include <dpl/event/model_bind_to_dao.h> +#include <dpl/wrt-dao-ro/feature_dao_read_only.h> + +using namespace WrtDB; + +template <typename RetType, RetType(PluginDAOReadOnly::*extFun) () const > +struct BindToPluginDAO : + DPL::Event::BindToDAO<PluginModel, + RetType, + WrtDB::DbPluginHandle, + PluginDAOReadOnly, + &PluginModel::getHandle, + extFun> +{}; + +template <typename RetType, RetType(*extFun) (WrtDB::DbPluginHandle)> +struct BindToFeatureDAOStatic : + DPL::Event::BindToDAO_Static<PluginModel, + RetType, + WrtDB::DbPluginHandle, + &PluginModel::getHandle, + extFun> +{}; + +PluginModel::PluginModel(const WrtDB::DbPluginHandle& handle) : + Handle(this, handle), + LibraryName(this, + BindToPluginDAO<std::string, + &PluginDAOReadOnly::getLibraryName>::Get), + LibraryPath(this, + BindToPluginDAO<std::string, + &PluginDAOReadOnly::getLibraryPath>::Get), + FeatureHandles(this, + BindToFeatureDAOStatic<FeatureHandleListPtr, + FeatureDAOReadOnly:: + GetFeatureHandleListForPlugin>:: + Get), + LibraryDependencies(this, + BindToPluginDAO<PluginHandleSetPtr, + &PluginDAOReadOnly:: + getLibraryDependencies>::Get), + LibraryInstance(this, PluginPtr()) +{} + +WrtDB::DbPluginHandle PluginModel::getHandle() const +{ + return Handle.Get(); +} diff --git a/src/plugin-loading/plugin_model.h b/src/plugin-loading/plugin_model.h new file mode 100644 index 0000000..f57c46e --- /dev/null +++ b/src/plugin-loading/plugin_model.h @@ -0,0 +1,95 @@ +/* + * 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 plugin_model.h + * @author Pawel Sikorski (p.sikorski@samgsung.com) + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief This file contains PluginModel, PluginHandle definitions. + */ + +#ifndef WRT_SRC_PLUGIN_SERVICE_PLUGIN_MODEL_H_ +#define WRT_SRC_PLUGIN_SERVICE_PLUGIN_MODEL_H_ + +#include <string> +#include <list> +#include <memory> +#include <dpl/event/model.h> +#include <dpl/event/property.h> + +#include <dpl/wrt-dao-ro/feature_model.h> +#include <dpl/wrt-dao-ro/plugin_dao_read_only.h> +#include <plugin.h> + +class PluginModel; + +class PluginModel : public DPL::Event::Model +{ + public: + + /** + * *@brief Plugin handle + */ + DPL::Event::Property<WrtDB::DbPluginHandle, + DPL::Event::PropertyReadOnly> Handle; + + /** + * *@brief LibraryName + */ + DPL::Event::Property<std::string, + DPL::Event::PropertyReadOnly, + DPL::Event::PropertyStorageDynamicInitCached> LibraryName; + + /** + * *@brief Library Path + */ + DPL::Event::Property<std::string, + DPL::Event::PropertyReadOnly, + DPL::Event::PropertyStorageDynamicInitCached> LibraryPath; + + /** + * *@brief Feature set + */ + DPL::Event::Property<WrtDB::FeatureHandleListPtr, + DPL::Event::PropertyReadOnly, + DPL::Event::PropertyStorageDynamicInitCached> + FeatureHandles; + + /** + * *@brief Librarydepencies + */ + DPL::Event::Property<WrtDB::PluginHandleSetPtr, + DPL::Event::PropertyReadOnly, + DPL::Event::PropertyStorageDynamicInitCached> + LibraryDependencies; + + /** + * *@brief Library instance Low Level + * */ + DPL::Event::Property<PluginPtr, + DPL::Event::PropertyReadWrite, + DPL::Event::PropertyStorageCached> LibraryInstance; + + public: + PluginModel(const WrtDB::DbPluginHandle& handle); + + private: + WrtDB::DbPluginHandle getHandle() const; +}; + +typedef std::shared_ptr<PluginModel> PluginModelPtr; + +#endif diff --git a/src/plugin-loading/plugin_property_support.cpp b/src/plugin-loading/plugin_property_support.cpp new file mode 100644 index 0000000..05d25c0 --- /dev/null +++ b/src/plugin-loading/plugin_property_support.cpp @@ -0,0 +1,141 @@ +/* + * 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 plugin_property_support.cpp + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 1.0 + * @brief + */ + +#include "plugin_property_support.h" +#include <dpl/log/wrt_log.h> + +using namespace PluginModule; + +const char *NAVIGATOR_PROPERTY_NAME = "navigator"; +const char *SCALE_PROPERTY_NAME = "scale"; +const char *BUNDLE_PROPERTY_NAME = "__bundle"; +const char *THEME_PROPERTY_NAME = "theme"; + +WindowPropertySupport::WindowPropertySupport( + JSGlobalContextRef context) : + m_scale(0), + m_bundle(""), + m_theme(""), + m_context(context) +{} + +WindowPropertySupport::~WindowPropertySupport() +{} + +float WindowPropertySupport::getScale() const +{ + return m_scale; +} + +std::string WindowPropertySupport::getBundle() const +{ + return m_bundle; +} + +std::string WindowPropertySupport::getTheme() const +{ + return m_theme; +} + +JSGlobalContextRef WindowPropertySupport::getJSContext() const +{ + return m_context; +} + +void WindowPropertySupport::setScaleToNavigatorProperty(const double scale) +{ + WrtLogD("set window.navigator.scale: %f", scale); + m_scale = scale; + setPropertyToNavigator(SCALE_PROPERTY_NAME, + JSValueMakeNumber(m_context, scale)); +} + +void WindowPropertySupport::setBundleToWindowProperty(const char* bundle) +{ + WrtLogD("set window.__bundle: %s", bundle); + if (bundle) { + m_bundle = bundle; + JSStringRef bundleString = JSStringCreateWithUTF8CString(bundle); + setPropertyToWindow(BUNDLE_PROPERTY_NAME, + JSValueMakeString(m_context, bundleString)); + JSStringRelease(bundleString); + } +} + +void WindowPropertySupport::setThemeToNavigatorProperty(const char* theme) +{ + WrtLogD("set window.navigator.__theme: %s", theme); + if (theme) { + m_theme = theme; + JSStringRef themeString = JSStringCreateWithUTF8CString(theme); + setPropertyToNavigator(THEME_PROPERTY_NAME, + JSValueMakeString(m_context, themeString)); + JSStringRelease(themeString); + } +} + +void WindowPropertySupport::setPropertyToWindow(const char* propertyName, + JSValueRef jsValue) +{ + WrtLogD("et property to window : %s", propertyName); + if (propertyName) { + JSObjectRef globalObject = JSContextGetGlobalObject(m_context); + JSStringRef propertyNameString = + JSStringCreateWithUTF8CString(propertyName); + JSObjectSetProperty(m_context, + globalObject, + propertyNameString, + jsValue, + kJSPropertyAttributeNone, + NULL); + JSStringRelease(propertyNameString); + } +} + +void WindowPropertySupport::setPropertyToNavigator(const char* propertyName, + JSValueRef jsValue) +{ + WrtLogD("set property to navigator : %s", propertyName); + if (propertyName) { + JSObjectRef globalObject = JSContextGetGlobalObject(m_context); + + JSStringRef navigatorString = + JSStringCreateWithUTF8CString(NAVIGATOR_PROPERTY_NAME); + JSValueRef navigatorValue = JSObjectGetProperty(m_context, + globalObject, + navigatorString, + NULL); + + JSStringRef propertyNameString = + JSStringCreateWithUTF8CString(propertyName); + JSObjectSetProperty(m_context, + JSValueToObject(m_context, navigatorValue, NULL), + propertyNameString, + jsValue, + kJSPropertyAttributeNone, + NULL); + + JSStringRelease(propertyNameString); + JSStringRelease(navigatorString); + } +} + diff --git a/src/plugin-loading/plugin_property_support.h b/src/plugin-loading/plugin_property_support.h new file mode 100644 index 0000000..fc946c4 --- /dev/null +++ b/src/plugin-loading/plugin_property_support.h @@ -0,0 +1,56 @@ +/* + * 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 plugin_property_support.h + * @author Yunchan Cho (yunchan.cho@samsung.com) + * @version 1.0 + * @brief + */ + +#ifndef _PLUGIN_LOGIC_PROPERTY_SUPPORT_H_ +#define _PLUGIN_LOGIC_PROPERTY_SUPPORT_H_ + +#include <string> +#include <JavaScriptCore/JavaScript.h> + +namespace PluginModule { +class WindowPropertySupport +{ + public: + float getScale() const; + std::string getBundle() const; + std::string getTheme() const; + JSGlobalContextRef getJSContext() const; + + void setScaleToNavigatorProperty(const double scale); + void setBundleToWindowProperty(const char* bundle); + void setThemeToNavigatorProperty(const char* theme); + + explicit WindowPropertySupport(JSGlobalContextRef m_context); + ~WindowPropertySupport(); + + private: + float m_scale; + std::string m_bundle; // string of base64 encoded bundle + std::string m_theme; + JSGlobalContextRef m_context; + + void setPropertyToWindow(const char* propertyName, JSValueRef jsValue); + void setPropertyToNavigator(const char* propertyName, JSValueRef jsValue); +}; +} // namespace PluginModule + +#endif // _PLUGIN_LOGIC_PROPERTY_SUPPORT_H_ diff --git a/src/plugins-api-support/CMakeLists.txt b/src/plugins-api-support/CMakeLists.txt new file mode 100644 index 0000000..5a8f7c5 --- /dev/null +++ b/src/plugins-api-support/CMakeLists.txt @@ -0,0 +1,73 @@ +# 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 CMakeLists.txt +# @author Grzegorz Krawczyk (g.krawczyk@samsung.com) +# @version 1.0 +# + +PKG_SEARCH_MODULE(dpl REQUIRED dpl-efl) + +SET(PLUGINS_API_SUPPORT_SOURCES + ${CMAKE_CURRENT_SOURCE_DIR}/Plugin.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/Object.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/ObjectFactory.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/PluginRegistration.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/PluginRegistry.cpp +) + +INCLUDE_DIRECTORIES( + ${CMAKE_CURRENT_SOURCE_DIR} + ${dpl_INCLUDE_DIRS} +) + +ADD_LIBRARY(${TARGET_PLUGINS_API_SUPPORT} SHARED + ${PLUGINS_API_SUPPORT_SOURCES} +) + +SET_TARGET_PROPERTIES(${TARGET_PLUGINS_API_SUPPORT} PROPERTIES + COMPILE_DEFINITIONS LOG_TAG="${LOG_TAG}") + +SET_TARGET_PROPERTIES(${TARGET_PLUGIN_API_SUPPORT} PROPERTIES + COMPILE_FLAGS -fPIC + LINK_FLAGS "-Wl,--as-needed -Wl,--hash-style=both" +) + +SET_TARGET_PROPERTIES(${TARGET_PLUGINS_API_SUPPORT} PROPERTIES + SOVERSION ${CMAKE_PROJECT_API_VERSION} + VERSION ${CMAKE_PROJECT_VERSION} +) + +TARGET_LINK_LIBRARIES(${TARGET_PLUGINS_API_SUPPORT} + ${dpl_LIBRARIES} +) + +INSTALL(TARGETS ${TARGET_PLUGINS_API_SUPPORT} + DESTINATION lib + PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE + GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE +) + +INSTALL(FILES + ${CMAKE_CURRENT_SOURCE_DIR}/ExportedApi.h + ${CMAKE_CURRENT_SOURCE_DIR}/Plugin.h + ${CMAKE_CURRENT_SOURCE_DIR}/IObject.h + ${CMAKE_CURRENT_SOURCE_DIR}/ObjectFactory.h + ${CMAKE_CURRENT_SOURCE_DIR}/CallbackSupport.h + ${CMAKE_CURRENT_SOURCE_DIR}/tuple.h + ${CMAKE_CURRENT_SOURCE_DIR}/PluginSignals.h + ${CMAKE_CURRENT_SOURCE_DIR}/SignalSignature.h + ${CMAKE_CURRENT_SOURCE_DIR}/PluginRegistration.h + DESTINATION include/wrt-plugins-api-support) diff --git a/src/plugins-api-support/CallbackSupport.h b/src/plugins-api-support/CallbackSupport.h new file mode 100644 index 0000000..bcaa849 --- /dev/null +++ b/src/plugins-api-support/CallbackSupport.h @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2012 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 CallbackSupport.h + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_CALLBACK_SUPPORT_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_CALLBACK_SUPPORT_H_ + +#include <map> +#include <vector> +#include <string> +#include <dpl/foreach.h> + +namespace WrtPluginsApi { +template<typename Sig> +class CallbackSupport +{ + public: + typedef typename Sig::Signature SlotSignature; + typedef typename Sig::Type SlotType; + typedef std::string GroupType; + typedef std::vector<SlotType> SlotList; + + void Connect(const GroupType& group, const SlotType& slot) + { + auto groupIt = m_slots.find(group); + if (m_slots.end() == groupIt) { + groupIt = m_slots.insert(std::make_pair(group, SlotList())).first; + } + groupIt->second.push_back(slot); + } + + void Disconnect(const GroupType& group) + { + m_slots.erase(group); + } + + template<typename ... Args> + void Invoke(const Args& ... args) + { + FOREACH(groupIt, m_slots) + { + FOREACH(slotIt, groupIt->second) + { + (*slotIt)(args ...); + } + } + } + + template<typename ... Args> + void InvokeGroup(const GroupType& group, const Args& ... args) + { + auto groupIt = m_slots.find(group); + + if (m_slots.end() != groupIt) { + FOREACH(slotIt, groupIt->second) + { + (*slotIt)(args ...); + } + } + } + + private: + std::map<GroupType, SlotList> m_slots; +}; +} +#endif diff --git a/src/plugins-api-support/ExportedApi.h b/src/plugins-api-support/ExportedApi.h new file mode 100644 index 0000000..4a71d95 --- /dev/null +++ b/src/plugins-api-support/ExportedApi.h @@ -0,0 +1,152 @@ +/* + * Copyright (c) 2012 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 ExportedApi.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_EXPORTED_API_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_EXPORTED_API_H_ + +#include <PluginRegistration.h> + +/** + * This file provides definition of entry point to the plugin's shared library + * used by wrt. + * + * Each plugin have to provide 1 symbol which is get by dlsym. + * The name of required symbol is specified by 'GetExportedSymbolName' function + * The type of this symbol is pointer to ExportedApi struct + * + * To allow access to your plugin, you have to: + * + * 1)define 3 functions: + * - Register, + * - Unregister, + * - GetProvidedFeatures + * (names are not important) + * + * 2)define global struct named "dll_api" and initialize it with above functions + * *Example: + * ExportedApi dll_api = {Register, Unregister, GetProvidedFeatures}; + * + * + * Detailed Example how the file with api may looks like file: + * + * #include <Commons/Exception.h> + * #include <Commons/WrtAccess/WrtAccess.h> + * + * #include <Plugin.h> + * #include <ObjectFactory.h> + * #include <PluginRegistration.h> + * #include <ExportedApi.h> + * + * #include "JSTest.h" + * #include "plugin_config.h" + * + * #include <dpl/wrt-dao-ro/wrt_db_types.h> + * + * #define OBJECT_WIDGET "widget" + * #define OBJECT_TEST "__test" + * + * using namespace WrtPlugins::W3C; + * using namespace WrtDeviceApis; + * using namespace WrtDeviceApis::Commons; + * using namespace WrtPluginsApi; + * + * namespace W3CTest + * { + * + * void on_widget_start_callback(WidgetHandle widgetId) + * { + * + * } + * + * void on_widget_stop_callback(WidgetHandle widgetId) + * { + * } + * + * } + * + * void Register(PluginRegistration& r) + * { + * Plugin* plugin = new Plugin(); + * + * auto test = ObjectFactory::createMainObject( + * OBJECT_TEST, + * WrtPlugins::W3C::JSTest::getClassRef, + * OBJECT_WIDGET); + * + * plugin->AddObject(test); + * + * r.Connect<OnWidgetStart>(W3CTest::on_widget_start_callback); + * + * r.Connect<OnWidgetStop>(W3CTest::on_widget_stop_callback); + * + * r.AddPlugin(*plugin); + * } + * + * void Unregister(PluginRegistration& r, Plugin* plugin) + * { + * r.DisconnectAll(); + * delete plugin; + * } + * + * void GetProvidedFeatures(feature_mapping_interface_t *mapping) + * { + * WrtPlugins::W3C::WidgetTestDeclarations::getMappingInterface(mapping); + * } + * + * ExportedApi dll_api={Register, Unregister, GetProvidedFeatures}; + * + * #undef OBJECT_WIDGET + * #undef OBJECT_TEST + * + * + * */ + +//forward declaration +struct feature_mapping_interface_s; +typedef struct feature_mapping_interface_s feature_mapping_interface_t; + +extern "C" struct ExportedApi +{ + /* + * This function is invoked when library is loaded + * */ + void (*Register)(WrtPluginsApi::PluginRegistration&); + + /* + * This function is invoked when library is unloaded + * */ + void (*Unregister)(WrtPluginsApi::PluginRegistration&, + WrtPluginsApi::Plugin* plugin); + + /* + * This function is invoked by wrt-plugins-installer to obtain + * info about features,functions,objects provided by plugin + * */ + void (*GetProvidedFeatures)(feature_mapping_interface_t*); +}; + +constexpr const char* GetExportedSymbolName() +{ + return "dll_api"; +} + +#endif diff --git a/src/plugins-api-support/IObject.h b/src/plugins-api-support/IObject.h new file mode 100644 index 0000000..4148d91 --- /dev/null +++ b/src/plugins-api-support/IObject.h @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2012 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 IObject.h + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_IOBJECT_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_IOBJECT_H_ + +#include <memory> +#include <list> + +extern "C" { +typedef struct OpaqueJSClass* (*ClassRef)(); +} + +namespace WrtPluginsApi { +enum class IObjectType +{ + Object, + Function, + Interface, + InterfaceInstance +}; + +enum class IObjectOption +{ + Overlayed +}; + +class IObject; +typedef std::shared_ptr<IObject> IObjectPtr; + +class IObject +{ + public: + constexpr static const char* WINDOW_OBJECT() + { + return "window"; + } + + virtual void AddChild(const IObjectPtr&) = 0; + + /* + * Optional + * */ + virtual void setBoolOption(IObjectOption option, bool value) = 0; + + virtual ~IObject(){} +}; + +typedef std::list<IObjectPtr> IObjectsList; +typedef std::shared_ptr<IObjectsList> IObjectsListPtr; +} +#endif diff --git a/src/plugins-api-support/IObject_cast.h b/src/plugins-api-support/IObject_cast.h new file mode 100644 index 0000000..105a31d --- /dev/null +++ b/src/plugins-api-support/IObject_cast.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2012 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 IObject_cast.h + * @author + * @version + * @brief + */ +#ifndef _WRT_PLUGINS_COMMON_PLUGINS_API_SUPPORT_CAST_H_ +#define _WRT_PLUGINS_COMMON_PLUGINS_API_SUPPORT_CAST_H_ + +#include <memory> +#include <IObject.h> +#include <Object.h> + +namespace WrtPluginsApi { +inline ObjectPtr CAST(const IObjectPtr& object) +{ + return std::dynamic_pointer_cast<Object>(object); +} +} +#endif diff --git a/src/plugins-api-support/Object.cpp b/src/plugins-api-support/Object.cpp new file mode 100644 index 0000000..7db93e4 --- /dev/null +++ b/src/plugins-api-support/Object.cpp @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2012 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 Object.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ + +#include "Object.h" + +namespace WrtPluginsApi { +void Object::AddChild(const IObjectPtr& child) +{ + if (!m_children) { + m_children = IObjectsListPtr(new IObjectsList); + } + m_children->push_back(child); +} + +void Object::setBoolOption(IObjectOption option, bool value) +{ + if (!m_options) { + m_options = ObjectOptionPtr(new ObjectOption); + } + + switch (option) { + case IObjectOption::Overlayed: + m_options->overlayedMode = value; + break; + default: + break; + } +} + +IObjectsListPtr Object::GetChildren() const +{ + return m_children; +} + +ClassRef Object::GetClass() const +{ + return m_classRef; +} + +ClassRef Object::GetClassConstructor() const +{ + return m_constructorRef; +} + +const char* Object::GetInterfaceName() const +{ + return m_interfaceName; +} + +const char* Object::GetName() const +{ + return m_name; +} + +IObjectType Object::GetType() const +{ + return m_type; +} + +const char* Object::GetParentName() const +{ + return m_parentName; +} + +ObjectOptionPtr Object::GetOptions() const +{ + return m_options; +} + +Object::Object(const char* name, + ClassRef ref, + IObjectType type) : + m_name(name), + m_classRef(ref), + m_parentName(0), + m_type(type), + m_interfaceRef(0), + m_interfaceName(0), + m_constructorRef(0) +{} + +Object::Object(const char* name, + ClassRef ref, + const char* parentName, + IObjectType type) : + m_name(name), + m_classRef(ref), + m_parentName(parentName), + m_type(type), + m_interfaceRef(0), + m_interfaceName(0), + m_constructorRef(0) +{} + +Object::Object(const char* name, + ClassRef interfaceRef, + const char* interfaceName, + ClassRef constructorRef, + const char* parentName, + IObjectType type) : + m_name(name), + m_parentName(parentName), + m_type(type), + m_interfaceRef(interfaceRef), + m_interfaceName(interfaceName), + m_constructorRef(constructorRef) +{} + +Object::~Object() +{} +} diff --git a/src/plugins-api-support/Object.h b/src/plugins-api-support/Object.h new file mode 100644 index 0000000..268a27f --- /dev/null +++ b/src/plugins-api-support/Object.h @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2012 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 IObject.h + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ + +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_OBJECT_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_OBJECT_H_ + +#include <memory> +#include <list> + +#include <IObject.h> +#include <dpl/optional_typedefs.h> + +namespace WrtPluginsApi { +class Object; +typedef std::shared_ptr<Object> ObjectPtr; + +struct ObjectOption +{ + DPL::OptionalBool overlayedMode; +}; +typedef std::shared_ptr<ObjectOption> ObjectOptionPtr; + +class Object : public IObject +{ + public: + Object(const char* name, + ClassRef ref, + IObjectType type = IObjectType::Object); + + Object(const char* name, + ClassRef ref, + const char* parentName = IObject::WINDOW_OBJECT(), + IObjectType type = IObjectType::Object); + + Object(const char* name, + ClassRef interfaceRef, + const char* interfaceName, + ClassRef constructorRef, + const char* parentName = IObject::WINDOW_OBJECT(), + IObjectType type = IObjectType::Object); + + ~Object(); + + void AddChild(const IObjectPtr&); + + void setBoolOption(IObjectOption option, bool value); + + IObjectsListPtr GetChildren() const; + + ClassRef GetClass() const; + + /* + * Available only for object with type InterfaceInstance + * */ + ClassRef GetClassConstructor() const; + + const char* GetInterfaceName() const; + + const char* GetName() const; + + IObjectType GetType() const; + + const char* GetParentName() const; + + ObjectOptionPtr GetOptions() const; + + private: + const char* m_name; + ClassRef m_classRef; + + const char* m_parentName; + + IObjectType m_type; + + ClassRef m_interfaceRef; + const char* m_interfaceName; + ClassRef m_constructorRef; + + ObjectOptionPtr m_options; + + IObjectsListPtr m_children; +}; +} + +#endif diff --git a/src/plugins-api-support/ObjectFactory.cpp b/src/plugins-api-support/ObjectFactory.cpp new file mode 100644 index 0000000..b897399 --- /dev/null +++ b/src/plugins-api-support/ObjectFactory.cpp @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2012 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 ObjectFactory.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ + +#include "ObjectFactory.h" +#include "Object.h" + +namespace WrtPluginsApi { +namespace ObjectFactory { +IObjectPtr createObject( + const char* name, + ClassRef ref, + IObjectType type) +{ + return IObjectPtr(new Object(name, ref, type)); +} + +IObjectPtr createMainObject( + const char* name, + ClassRef ref, + const char* parentName, + IObjectType type) +{ + return IObjectPtr(new Object(name, ref, parentName, type)); +} + +IObjectPtr createObjectWithInterface( + const char* name, + ClassRef interfaceRef, + const char* interfaceName, + ClassRef constructorRef, + const char* parentName, + IObjectType type) +{ + return IObjectPtr(new Object(name, + interfaceRef, + interfaceName, + constructorRef, + parentName, + type)); +} +} +} diff --git a/src/plugins-api-support/ObjectFactory.h b/src/plugins-api-support/ObjectFactory.h new file mode 100644 index 0000000..59bff1d --- /dev/null +++ b/src/plugins-api-support/ObjectFactory.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2012 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 ObjectFactory.h + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_OBJECT_FACTORY_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_OBJECT_FACTORY_H_ + +#include <memory> +#include <IObject.h> + +namespace WrtPluginsApi { +namespace ObjectFactory { +IObjectPtr createObject( + const char* name, + ClassRef ref, + IObjectType type = IObjectType::Object); + +IObjectPtr createMainObject( + const char* name, + ClassRef ref, + const char* parentName = IObject::WINDOW_OBJECT(), + IObjectType type = IObjectType::Object); + +IObjectPtr createObjectWithInterface( + const char* name, + ClassRef interfaceRef, + const char* interfaceName, + ClassRef constructorRef, + const char* parentName = IObject::WINDOW_OBJECT(), + IObjectType type = IObjectType::Object); +} +} +#endif diff --git a/src/plugins-api-support/Plugin.cpp b/src/plugins-api-support/Plugin.cpp new file mode 100644 index 0000000..6303c32 --- /dev/null +++ b/src/plugins-api-support/Plugin.cpp @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2012 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 Plugin.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ +#include "Plugin.h" + +namespace WrtPluginsApi { +void Plugin::AddObject(const IObjectPtr& object) +{ + m_objects->push_back(object); +} + +IObjectsListPtr Plugin::GetObjects() const +{ + return m_objects; +} + +Plugin::~Plugin() +{} + +Plugin::Plugin() : m_objects(new IObjectsList()) +{} +} diff --git a/src/plugins-api-support/Plugin.h b/src/plugins-api-support/Plugin.h new file mode 100644 index 0000000..5458714 --- /dev/null +++ b/src/plugins-api-support/Plugin.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2012 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 Plugin.h + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_PLUGIN_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_PLUGIN_H_ + +#include <list> +#include <IObject.h> + +namespace WrtPluginsApi { +class Plugin +{ + public: + void AddObject(const IObjectPtr& object); + + IObjectsListPtr GetObjects() const; + + Plugin(); + + virtual ~Plugin(); + + private: + IObjectsListPtr m_objects; +}; +} + +#endif diff --git a/src/plugins-api-support/PluginRegistration.cpp b/src/plugins-api-support/PluginRegistration.cpp new file mode 100644 index 0000000..4418e32 --- /dev/null +++ b/src/plugins-api-support/PluginRegistration.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2012 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 PluginRegistration.cpp + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#include "PluginRegistration.h" + +#include "PluginRegistrationImpl.h" +#include "Plugin.h" +#include <dpl/assert.h> + +namespace WrtPluginsApi { +PluginRegistration::PluginRegistration(Impl* impl) : m_impl(impl) +{ + AssertMsg(impl != 0, "impl is NULL"); +} + +template<typename SignalSignature> +void PluginRegistration::Connect(const typename SignalSignature::Type& slot) +{ + m_impl->Connect<SignalSignature>(slot); +} + +void PluginRegistration::DisconnectAll() +{ + m_impl->DisconnectAll(); +} + +void PluginRegistration::AddPlugin(Plugin& plugin) +{ + m_impl->AddPlugin(plugin); +} + +#define EXPLICIT_INSTATIATE_PLUGIN_REGISTRATION(SignalSignature) \ + template void PluginRegistration::Connect<SignalSignature>( \ + const typename SignalSignature::Type &) + +EXPLICIT_INSTATIATE_PLUGIN_REGISTRATION(OnWidgetStart); +EXPLICIT_INSTATIATE_PLUGIN_REGISTRATION(OnWidgetStop); +EXPLICIT_INSTATIATE_PLUGIN_REGISTRATION(OnFrameLoad); +EXPLICIT_INSTATIATE_PLUGIN_REGISTRATION(OnFrameUnload); +} diff --git a/src/plugins-api-support/PluginRegistration.h b/src/plugins-api-support/PluginRegistration.h new file mode 100644 index 0000000..e871a76 --- /dev/null +++ b/src/plugins-api-support/PluginRegistration.h @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2012 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 PluginRegistration.h + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_PLUGIN_REGISTRATION_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_PLUGIN_REGISTRATION_H_ + +#include <memory> +#include "Plugin.h" +#include "PluginSignals.h" + +namespace WrtPluginsApi { +class PluginRegistration +{ + public: + class Impl; + + explicit PluginRegistration(PluginRegistration::Impl* impl); + + template<typename SignalSignature> + void Connect(const typename SignalSignature::Type& slot); + + void DisconnectAll(); + + void AddPlugin(Plugin& plugin); + + private: + std::unique_ptr<Impl> m_impl; +}; +} + +#endif diff --git a/src/plugins-api-support/PluginRegistrationImpl.h b/src/plugins-api-support/PluginRegistrationImpl.h new file mode 100644 index 0000000..5954731 --- /dev/null +++ b/src/plugins-api-support/PluginRegistrationImpl.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2012 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 PluginRegistrationImpl.h + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_PLUGIN_REGISTRATION_IMPL_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_PLUGIN_REGISTRATION_IMPL_H_ + +#include <string> +#include "SignalsSupport.h" +#include "Plugin.h" +#include <dpl/log/wrt_log.h> + +namespace WrtPluginsApi { +class PluginRegistration::Impl +{ + public: + Impl(SignalsSupport& registry, const std::string& libraryName) : + m_registry(registry), + m_libraryName(libraryName) + {} + + void AddPlugin(Plugin& plugin) + { + m_registry.AddPlugin(m_libraryName, plugin); + } + + template<typename T> + void Connect(const typename T::Type& slot) + { + m_registry.Connect<T>(m_libraryName, slot); + } + + void DisconnectAll() + { + m_registry.Disconnect(m_libraryName); + } + + private: + SignalsSupport& m_registry; + std::string m_libraryName; +}; +} + +#endif diff --git a/src/plugins-api-support/PluginRegistry.cpp b/src/plugins-api-support/PluginRegistry.cpp new file mode 100644 index 0000000..0a94c23 --- /dev/null +++ b/src/plugins-api-support/PluginRegistry.cpp @@ -0,0 +1,169 @@ +/* + * Copyright (c) 2012 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 PluginRegistry.h + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ +#include "PluginRegistry.h" +#include "PluginRegistration.h" +#include "PluginRegistrationImpl.h" +#include "ExportedApi.h" + +#include <dlfcn.h> +#include <cstdio> +#include <cstdlib> +#include <string> +#include <algorithm> + +#include <dpl/log/wrt_log.h> +#include <dpl/foreach.h> +#include <dpl/scope_guard.h> + +namespace WrtPluginsApi { +void PluginRegistry::AddPlugin(const std::string& libraryName, + Plugin& plugin) +{ + WrtLogD("Adding plugin for library: %s", libraryName.c_str()); + + auto libraryIt = m_plugins.find(libraryName); + if (m_plugins.end() == libraryIt) { + m_plugins[libraryName] = &plugin; + } +} + +Plugin* PluginRegistry::GetPlugin(const std::string& libraryName) +{ + auto it = m_plugins.find(libraryName); + if (it == m_plugins.end()) { + if (!LoadFromFile(libraryName)) { + WrtLogE("Failed to load lib %s", libraryName.c_str()); + ThrowMsg(PluginNotFound, "Failed to load plugin"); + } + + return m_plugins[libraryName]; + } + + return it->second; +} + +void PluginRegistry::RemovePlugin(const std::string& libraryName, + Plugin& plugin) +{ + auto it = m_plugins.find(libraryName); + if (it != m_plugins.end()) { + if (&plugin == it->second) { + m_plugins.erase(it); + } + } +} + +void PluginRegistry::UnloadAll() +{ + WrtLogD("Unload all plugins"); + + typedef void (*UnregisterFunction)(PluginRegistration&, Plugin&); + + FOREACH(libraryIt, m_libraries) + { + auto pluginIt = m_plugins.find(libraryIt->first); + if (m_plugins.end() != pluginIt) { + void* handle = dlopen(libraryIt->first.c_str(), RTLD_NOW); + if (!handle) { + const char* error = (const char*)dlerror(); + WrtLogE("Error: %s", (error != NULL ? error : "unknown")); + continue; + } + DPL_SCOPE_EXIT(handle) { + if (dlclose(handle) != 0) { + const char* error = dlerror(); + if (error != NULL) + { + std::string errstr{error}; + WrtLogE("%s", errstr.c_str()); + } + else + { + WrtLogE("unknown error while closing plug-in library"); + } + } + }; + + ExportedApi* entryPoint = + static_cast<ExportedApi*> + (dlsym(handle, GetExportedSymbolName())); + if (NULL == entryPoint) { + const char* error = (const char*)dlerror(); + WrtLogE("Error: %s", (error != NULL ? error : "unknown")); + continue; + } + if (entryPoint->Unregister == NULL) { + WrtLogE("Error Unregister function not set"); + continue; + } + + PluginRegistration registration( + new PluginRegistration::Impl(*this, libraryIt->first)); + + entryPoint->Unregister(registration, (pluginIt->second)); + + m_plugins.erase(pluginIt); + } + dlclose(libraryIt->second); + } +} + +bool PluginRegistry::LoadFromFile(const std::string& libraryName) +{ + void* handle = dlopen(libraryName.c_str(), RTLD_NOW); + if (!handle) { + const char* error = (const char*)dlerror(); + WrtLogE("Error: %s", (error != NULL ? error : "unknown")); + return false; + } + m_libraries[libraryName] = handle; + + ExportedApi* entryPoint = + static_cast<ExportedApi*>(dlsym(handle, GetExportedSymbolName())); + if (NULL == entryPoint) { + const char* error = (const char*)dlerror(); + WrtLogE("Error: %s", (error != NULL ? error : "unknown")); + return false; + } + + if (entryPoint->Register == NULL) { + WrtLogE("Error Register function not set"); + return false; + } + if (entryPoint->Unregister == NULL) { + WrtLogE("Error Unregister function not set"); + return false; + } + + PluginRegistration registration( + new PluginRegistration::Impl(*this, libraryName)); + entryPoint->Register(registration); + + return true; +} + +PluginRegistry::~PluginRegistry() +{ + //TODO discuss ... when the unload should be called + // UnloadAll(); +} +} diff --git a/src/plugins-api-support/PluginRegistry.h b/src/plugins-api-support/PluginRegistry.h new file mode 100644 index 0000000..5db1ea4 --- /dev/null +++ b/src/plugins-api-support/PluginRegistry.h @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2012 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 PluginRegistry.h + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_LOADING_PLUGIN_REGISTRY_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_LOADING_PLUGIN_REGISTRY_H_ + +#include <map> +#include <string> +#include "SignalsSupport.h" +#include "Plugin.h" +#include <dpl/exception.h> + +namespace WrtPluginsApi { +typedef std::list<Plugin*> PluginsList; +typedef std::shared_ptr<PluginsList> PluginsListPtr; +typedef std::map< std::string, PluginsListPtr> PluginsSet; + +class PluginRegistry : public SignalsSupport +{ + public: + DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) + DECLARE_EXCEPTION_TYPE(Base, PluginNotFound) + + template <typename T, typename ... Args> + void Call(Args ... args) + { + Invoke<T>(args ...); + } + + template <typename T, typename ... Args> + void CallGroup(const typename CallbackSupport<T>::GroupType& type, + Args ... args) + { + InvokeGroup<T>(type, args ...); + } + + void AddPlugin(const std::string& libraryName, Plugin& plugin); + + /* + * @throw PluginNotFound + * */ + Plugin* GetPlugin(const std::string& libraryName); + + void RemovePlugin(const std::string& libraryName, Plugin& plugin); + + void UnloadAll(); + + ~PluginRegistry(); + + private: + bool LoadFromFile(const std::string& libraryName); + + typedef void* Symbol; + + std::map<std::string, Plugin*> m_plugins; + std::map<std::string, void*> m_libraries; +}; + +typedef std::shared_ptr<PluginRegistry> PluginRegistryPtr; +} + +#endif diff --git a/src/plugins-api-support/PluginSignals.h b/src/plugins-api-support/PluginSignals.h new file mode 100644 index 0000000..556d620 --- /dev/null +++ b/src/plugins-api-support/PluginSignals.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2012 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 PluginSignals.h + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_PLUGIN_SIGNALS_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_PLUGIN_SIGNALS_H_ + +#include "SignalSignature.h" + +namespace WrtPluginsApi { +struct OnWidgetStart : SignalSignature<void (int)> {}; + +struct OnWidgetStop : SignalSignature<void (int)> {}; + +struct OnFrameLoad : SignalSignature<void (void*)> {}; + +struct OnFrameUnload : SignalSignature<void (void*)> {}; +} + +#endif diff --git a/src/plugins-api-support/SignalSignature.h b/src/plugins-api-support/SignalSignature.h new file mode 100644 index 0000000..b43747e --- /dev/null +++ b/src/plugins-api-support/SignalSignature.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2012 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 SignalSignature.h + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_SIGNAL_SIGNATURE_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_SIGNAL_SIGNATURE_H_ + +#include <functional> + +namespace WrtPluginsApi { +template<typename> struct SignalSignature; + +template<typename R, typename ... Args> +struct SignalSignature<R(Args ...)> +{ + typedef R (*Signature)(Args ...); + typedef std::function<R(Args ...)> Type; +}; +} + +#endif diff --git a/src/plugins-api-support/SignalsSupport.h b/src/plugins-api-support/SignalsSupport.h new file mode 100644 index 0000000..9c47af2 --- /dev/null +++ b/src/plugins-api-support/SignalsSupport.h @@ -0,0 +1,98 @@ +/* + * Copyright (c) 2012 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 IPluginRegistry.h + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ + +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_SIGNALS_SUPPORT_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_SIGNALS_SUPPORT_H_ + +#include <tuple> +#include <string> +#include "CallbackSupport.h" +#include "tuple.h" +#include "PluginSignals.h" +#include "Plugin.h" + +namespace WrtPluginsApi { +class SignalsSupport +{ + public: + virtual ~SignalsSupport() {} + + template<typename T> + void Connect(const std::string& libraryName, const typename T::Type& slot) + { + Tuple::get_by_type<CallbackSupport<T> >(m_slots).Connect(libraryName, + slot); + } + + void Disconnect(const std::string& libraryName) + { + DisconnectGroup(m_slots, libraryName); + } + + virtual void AddPlugin(const std::string& libraryName, Plugin& plugin) = 0; + + protected: + template<typename T, typename ... Args> + void Invoke(const Args& ... args) + { + Tuple::get_by_type<CallbackSupport<T> >(m_slots).Invoke(args ...); + } + + template<typename T, typename ... Args> + void InvokeGroup(const std::string& libraryName, const Args& ... args) + { + Tuple::get_by_type<CallbackSupport<T> >(m_slots).InvokeGroup( + libraryName, + args ...); + } + + private: + template<int N, typename ... Args> + void DisconnectSlot(std::tuple<Args ...>& slots, + const std::string& libraryName, + typename std::enable_if<(N >= 0)>::type* = NULL) + { + std::get<N>(slots).Disconnect(libraryName); + DisconnectSlot<N - 1>(slots, libraryName); + } + + template<int N, typename ... Args> + void DisconnectSlot(std::tuple<Args ...>& /*slots*/, + const std::string& /*libraryName*/, + typename std::enable_if<(N == -1)>::type* = NULL) + {} + + template<typename ... Args> + void DisconnectGroup(std::tuple<Args ...>& slots, + const std::string& libraryName) + { + DisconnectSlot<sizeof ... (Args)-1>(slots, libraryName); + } + + std::tuple<CallbackSupport<OnWidgetStart>, + CallbackSupport<OnWidgetStop>, + CallbackSupport<OnFrameLoad>, + CallbackSupport<OnFrameUnload> > m_slots; +}; +} + +#endif diff --git a/src/plugins-api-support/detail/traits.h b/src/plugins-api-support/detail/traits.h new file mode 100644 index 0000000..7ab56db --- /dev/null +++ b/src/plugins-api-support/detail/traits.h @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2012 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 traits.h + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_DETAIL_TRAITS_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_DETAIL_TRAITS_H_ + +namespace WrtPluginsApi { +namespace Traits { +namespace Detail { +template<size_t, typename RequiredType, typename ... TupleArgTypes> +struct index_of_; + +/* + * CurrentArgType is not equal to RequiredType, check next tuple's argument + */ +template<size_t n, + typename RequiredType, + typename CurrentArgType, + typename ... TupleArgTypes> +struct index_of_<n, RequiredType, CurrentArgType, TupleArgTypes ...> +{ + static const size_t value = index_of_<n + 1, + RequiredType, + TupleArgTypes ...>::value; +}; + +/* + * RequiredType found on tuple's args list + * return position on tuple's list + */ +template<size_t n, typename RequiredType, typename ... TupleArgTypes> +struct index_of_<n, RequiredType, RequiredType, TupleArgTypes ...> +{ + static const size_t value = n; +}; + +/* + * RequiredType found on last position of tuple's args list + * return position on tuple's list + */ +template<size_t n, typename RequiredType> +struct index_of_<n, RequiredType, RequiredType> +{ + static const size_t value = n; +}; + +/* + * RequiredType was not found on tuple args list + */ +template<size_t n, typename RequiredType, typename LastArgType> +struct index_of_<n, RequiredType, LastArgType> +{ + static const size_t value = -1; +}; +} +} +} + +#endif diff --git a/src/plugins-api-support/js_types.h b/src/plugins-api-support/js_types.h new file mode 100644 index 0000000..387c5bc --- /dev/null +++ b/src/plugins-api-support/js_types.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2012 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_types.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 1.0 + */ + +#ifndef WRT_PLUGIN_COMMON_API_SUPPORT_JS_TYPES_H_ +#define WRT_PLUGIN_COMMON_API_SUPPORT_JS_TYPES_H_ + +#include <string> + +//forward declaration +extern "C" { +typedef struct OpaqueJSContext* JSGlobalContextRef; +typedef struct OpaqueJSValue* JSObjectRef; +} + +namespace WrtPluginsApi { +struct JavaScriptObject +{ + JSObjectRef instance; + std::string name; +}; +} + +#endif diff --git a/src/plugins-api-support/traits.h b/src/plugins-api-support/traits.h new file mode 100644 index 0000000..286c510 --- /dev/null +++ b/src/plugins-api-support/traits.h @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2012 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 traits.h + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_TRAITS_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_TRAITS_H_ + +#include "detail/traits.h" + +namespace WrtPluginsApi { +namespace Traits { +/** + * Gets index of specified type in the type list. + */ +template<typename RequiredType, typename ... TupleArgTypes> +struct index_of +{ + static const size_t value = Detail::index_of_<0, + RequiredType, + TupleArgTypes ...>::value; +}; +} +} + +#endif diff --git a/src/plugins-api-support/tuple.h b/src/plugins-api-support/tuple.h new file mode 100644 index 0000000..ec7c3b3 --- /dev/null +++ b/src/plugins-api-support/tuple.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2012 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 tuple.h + * @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) + */ + +#ifndef _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_TUPLE_H_ +#define _WRT_PLUGINS_COMMON_PLUGIN_API_SUPPORT_TUPLE_H_ + +#include <tuple> +#include "traits.h" + +namespace WrtPluginsApi { +namespace Tuple { +template<typename T, typename ... Args> +T& get_by_type(std::tuple<Args ...>& tuple) +{ + return std::get<Traits::index_of<T, Args ...>::value>(tuple); +} +} +} + +#endif diff --git a/src/plugins-installer/CMakeLists.txt b/src/plugins-installer/CMakeLists.txt new file mode 100644 index 0000000..b0bf8f0 --- /dev/null +++ b/src/plugins-installer/CMakeLists.txt @@ -0,0 +1,73 @@ +# 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 CMakeLists.txt +# @author Andrzej Surdej (a.surdej@samsung.com) +# @version 1.0 +# + +SET(TARGET_PLUGINS_INSTALLER "wrt-plugins-installer") + +SET(WRT_PLUGINS_INSTALLER_SRC_DIR + ${CMAKE_CURRENT_SOURCE_DIR} +) + +PKG_CHECK_MODULES(PLUGINS_INSTALLER_DEPS + libxml-2.0 + cert-svc-vcore + dpl-efl + dpl-utils-efl + dpl-wrt-dao-rw + libpcrecpp + REQUIRED +) + +INCLUDE_DIRECTORIES( + ${WRT_PLUGINS_INSTALLER_SRC_DIR} + ${PLUGINS_INSTALLER_INCLUDES} + ${PLUGINS_INSTALLER_DEPS_INCLUDE_DIRS} + ${PLUGINS_API_SUPPORT_DIRS} +) + +SET(WRT_PLUGINS_INSTALLER_SOURCES + ${WRT_PLUGINS_INSTALLER_SRC_DIR}/wrt_plugins_installer.cpp + ${WRT_PLUGINS_INSTALLER_SRC_DIR}/plugin_installer.cpp + ${WRT_PLUGINS_INSTALLER_SRC_DIR}/plugin_utils.cpp + ${WRT_PLUGINS_INSTALLER_SRC_DIR}/plugin_objects.cpp + ${WRT_PLUGINS_INSTALLER_SRC_DIR}/plugin_metafile_reader.cpp +) + +ADD_DEFINITIONS(${PLUGINS_INSTALLER_DEPS_CFLAGS}) +ADD_DEFINITIONS(${PLUGINS_INSTALLER_DEPS_CFLAGS_OTHERS}) + +ADD_EXECUTABLE(${TARGET_PLUGINS_INSTALLER} + ${WRT_PLUGINS_INSTALLER_SOURCES} +) + +SET_TARGET_PROPERTIES(${TARGET_PLUGINS_INSTALLER} PROPERTIES + COMPILE_DEFINITIONS LOG_TAG="${LOG_TAG}") + +TARGET_LINK_LIBRARIES(${TARGET_PLUGINS_INSTALLER} + ${PLUGINS_INSTALLER_DEPS_LIBRARIES} + ${TARGET_PLUGINS_API_SUPPORT} "-ldl" +) + +SET_TARGET_PROPERTIES(${TARGET_PLUGINS_INSTALLER} PROPERTIES + LINK_FLAGS "-Wl,--as-needed -Wl,--hash-style=both" + BUILD_WITH_INSTALL_RPATH ON + INSTALL_RPATH_USE_LINK_PATH ON +) + +INSTALL(TARGETS ${TARGET_PLUGINS_INSTALLER} DESTINATION bin) diff --git a/src/plugins-installer/DESCRIPTION b/src/plugins-installer/DESCRIPTION new file mode 100644 index 0000000..0e8c571 --- /dev/null +++ b/src/plugins-installer/DESCRIPTION @@ -0,0 +1,2 @@ +!!!options!!! stop +Widget (un)installer, plugin (un)installer diff --git a/src/plugins-installer/plugin_installer.cpp b/src/plugins-installer/plugin_installer.cpp new file mode 100644 index 0000000..e570c55 --- /dev/null +++ b/src/plugins-installer/plugin_installer.cpp @@ -0,0 +1,752 @@ +/* + * Copyright (c) 2012 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 plugin_installer.cpp + * @author Andrzej Surdej(a.surdej@samgsung.com) + * @version + * @brief + */ + +#include "plugin_installer.h" + +#include <sys/stat.h> +#include <cstdio> +#include <dlfcn.h> +#include <string> + +#include <vcore/VCore.h> +#include <libxml/parser.h> + +#include "plugin_objects.h" +#include "plugin_metafile_reader.h" +#include "plugin_installer_errors.h" + +#include <Plugin.h> +#include <IObject_cast.h> +#include <plugin_utils.h> +#include <ExportedApi.h> + +#include <wrt-commons/wrt_plugin_export.h> + +#include <dpl/log/wrt_log.h> +#include <dpl/exception.h> +#include <dpl/utils/path.h> +#include <dpl/wrt-dao-ro/global_config.h> +#include <dpl/wrt-dao-rw/feature_dao.h> +#include <dpl/foreach.h> +#include <dpl/wrt-dao-ro/WrtDatabase.h> + +#include <dpl/singleton_impl.h> + +using namespace WrtDB; +using namespace WrtPluginsApi; + + +IMPLEMENT_SINGLETON(PluginsInstaller) + +namespace { +const std::string DIRECTORY_SEPARATOR = std::string("/"); +} + +const int PluginsInstaller::INSTALLATION_ERROR = -1; + +PluginsInstaller::PluginsInstaller() : + m_initialized(false) +{ + WrtLogD("PluginsInstaller created."); +} +PluginsInstaller::~PluginsInstaller() +{ + WrtLogD("PluginsInstaller destroyed."); +} + +void PluginsInstaller::checkDatabaseTablesExistance() +{ + if (!WrtDB::WrtDatabase::CheckTableExist("FeaturesList") || + !WrtDB::WrtDatabase::CheckTableExist("PluginProperties") || + !WrtDB::WrtDatabase::CheckTableExist("PluginDependencies") || + !WrtDB::WrtDatabase::CheckTableExist("PluginImplementedObjects") || + !WrtDB::WrtDatabase::CheckTableExist("PluginRequiredObjects") || + !WrtDB::WrtDatabase::CheckTableExist("DeviceCapabilities") || + !WrtDB::WrtDatabase::CheckTableExist("FeatureDeviceCapProxy")) + { + WrtLogE("Wrong database. Required tables not exist."); + deinitialize(); + Assert(false && "Wrong database. Required tables not exist."); + } +} + +bool PluginsInstaller::initialize() +{ + WrtLogD("Initializing required systems."); + + // Check paths + if (!PluginUtils::checkPaths()) { + return false; + } + // Initialize ValidationCore - this must be done before AttachDatabases + ValidationCore::VCoreInit( + std::string(GlobalConfig::GetFingerprintListFile()), + std::string(GlobalConfig::GetFingerprintListSchema()), + std::string(GlobalConfig::GetVCoreDatabaseFilePath())); + + xmlInitParser(); + WrtDB::WrtDatabase::attachToThreadRW(); + ValidationCore::AttachToThreadRW(); + checkDatabaseTablesExistance(); + WrtLogD("Initialized."); + m_initialized = true; + return true; +} + +void PluginsInstaller::deinitialize() +{ + WrtLogD("Shuting systems down."); + m_initialized = false; + ValidationCore::DetachFromThread(); + WrtDB::WrtDatabase::detachFromThread(); + ValidationCore::VCoreDeinit(); + xmlCleanupParser(); + WrtLogD("Done"); +} + +PluginsInstaller::ReturnStatus PluginsInstaller::installPlugin( + const std::string& libPath) +{ + if (!m_initialized) { + WrtLogE("Plugins installer not initialized."); + return ReturnStatus::NotInitialized; + } + WrtLogD("Plugin installation started. Checking path: %s", libPath.c_str()); + + if (!PluginUtils::checkPath(libPath)) { + return ReturnStatus::WrongPluginPath; + } + + WrtLogD("Plugin path ok. Searching for config file..."); + + std::string metaFileName = libPath + DIRECTORY_SEPARATOR + + std::string(WrtDB::GlobalConfig::GetPluginMetafileName()); + if (PluginUtils::checkFileExistance(metaFileName)) { + return installPluginFromMetafile(libPath, metaFileName); + } + + PluginMetafileData pluginInfo; + pluginInfo.m_libraryName = getLibraryName(libPath); + + WrtLogD("Config file done. Lib name: %s. Searching for installed plugin...", + pluginInfo.m_libraryName.c_str()); + + if (WrtDB::PluginDAO::isPluginInstalled(pluginInfo.m_libraryName)) { + WrtLogD("Plugin already installed."); + return ReturnStatus::AlreadyInstalled; + } + WrtLogD("Plugin not installed. Loading library file..."); + + PluginObjectsPtr libraryObjects; + PluginHandle pluginHandle; + + std::string filename = libPath + DIRECTORY_SEPARATOR + + pluginInfo.m_libraryName; + + WrtLogD("Loading plugin: %s", filename.c_str()); + + Plugin* plugin; + Try + { + plugin = m_registry.GetPlugin(filename); + } + Catch(DPL::Exception) { + WrtLogE("Loading library failed %s", filename.c_str()); + return ReturnStatus::LoadingLibraryError; + } + libraryObjects = PluginObjectsPtr(new PluginObjects()); + + WrtLogD("#####"); + WrtLogD("##### Plugin: %s supports new plugin API", filename.c_str()); + WrtLogD("#####"); + + FOREACH(o, *plugin->GetObjects()) { + libraryObjects->addObjects(CAST(*o)->GetParentName(), + CAST(*o)->GetName()); + + WrtLogD("[Parent << Object] %s << %s", + CAST(*o)->GetParentName(), + CAST(*o)->GetName()); + + registerObjects(libraryObjects, plugin->GetObjects()); + } + + if (!fillMappingInterfaces(pluginInfo, filename)) { + m_registry.RemovePlugin(filename, *plugin); + return ReturnStatus::LoadingLibraryError; + } + + WrtLogD("Library loaded. Registering plugin..."); + + Try + { + pluginHandle = + PluginDAO::registerPlugin(pluginInfo, libPath); + + WrtLogD("Plugin registered. Registering features..."); + + FOREACH(it, pluginInfo.m_featureContainer) + { + WrtLogE("PluginHandle: %d", pluginHandle); + FeatureDAO::RegisterFeature(*it, pluginHandle); + } + + WrtLogD("Features registered. Registering objects..."); + + registerPluginObjects(pluginHandle, libraryObjects); + + WrtLogD("Registration done. Resolving dependencies..."); + + //TODO: can it be replaced with resolvePluginDependencies(handle) + if (!registerAndUpdateInstallation(pluginHandle, libraryObjects)) { + return ReturnStatus::InstallationWaiting; + } + } Catch(DPL::Exception) { + WrtLogE("Failed to make database entry."); + return ReturnStatus::DatabaseError; + } + + WrtLogD("Plugin installed successfully."); + return ReturnStatus::Success; +} + +PluginObjectsPtr PluginsInstaller::loadLibraryFromMetafile( + const std::string& libName) const +{ + WrtLogD("Loading library: %s", libName.c_str()); + + void *dlHandle = dlopen(libName.c_str(), RTLD_NOW); + if (dlHandle == NULL) { + const char* error = (const char*)dlerror(); + WrtLogE("Failed to load plugin: %s. Reason: %s", + libName.c_str(), + (error != NULL ? error : "unknown")); + ThrowMsg(PluginInstall::Exceptions::LibraryException, "Library error"); + } + + const js_entity_definition_t *rawEntityList = NULL; + get_widget_entity_map_proc *getWidgetEntityMapProcPtr = NULL; + + getWidgetEntityMapProcPtr = + reinterpret_cast<get_widget_entity_map_proc *>(dlsym(dlHandle, + PLUGIN_GET_CLASS_MAP_PROC_NAME)); + + if (getWidgetEntityMapProcPtr) { + rawEntityList = (*getWidgetEntityMapProcPtr)(); + } else { + rawEntityList = + static_cast<const js_entity_definition_t *>(dlsym(dlHandle, + PLUGIN_CLASS_MAP_NAME)); + } + + if (rawEntityList == NULL) { + dlclose(dlHandle); + WrtLogE("Failed to read class name %s", libName.c_str()); + ThrowMsg(PluginInstall::Exceptions::LibraryException, "Library error"); + } + + PluginObjectsPtr libraryObjects = PluginObjectsPtr(new PluginObjects()); + const js_entity_definition_t *rawEntityListIterator = rawEntityList; + + WrtLogD("#####"); + WrtLogD("##### Plugin: %s is using deprecated API", libName.c_str()); + WrtLogD("#####"); + + while (rawEntityListIterator->parent_name != NULL && + rawEntityListIterator->object_name != NULL) + { + WrtLogD("##### [%s]: ", rawEntityListIterator->object_name); + WrtLogD("##### Parent: %s", rawEntityListIterator->parent_name); + WrtLogD("#####"); + + libraryObjects->addObjects(rawEntityListIterator->parent_name, + rawEntityListIterator->object_name); + + ++rawEntityListIterator; + } + + // Unload library + if (dlclose(dlHandle) != 0) { + WrtLogE("Cannot close plugin handle"); + } else { + WrtLogD("Library is unloaded"); + } + + // Load export table + WrtLogD("Library successfuly loaded and parsed"); + + return libraryObjects; +} + +PluginsInstaller::ReturnStatus PluginsInstaller::installPluginFromMetafile( + const std::string& path, const std::string& metaFilePath) +{ + if (!m_initialized) { + WrtLogE("Plugins installer not initialized."); + return ReturnStatus::NotInitialized; + } + OptionalPluginMetafileData pluginData; + Try + { + pluginData = parseMetafile(metaFilePath); + } + Catch(PluginInstall::Exceptions::XMLFileParsingException) + { + WrtLogE("Parsing metafile failed."); + return ReturnStatus::MetafileError; + } + if (!pluginData) { + return ReturnStatus::MetafileError; + } + + if (WrtDB::PluginDAO::isPluginInstalled(pluginData->m_libraryName)) { + WrtLogD("Plugin already installed."); + return ReturnStatus::AlreadyInstalled; + } + Try { + WrtLogE("path is: %s, libraryName: %s", + path.c_str(), + pluginData->m_libraryName.c_str()); + PluginObjectsPtr objects = loadLibraryFromMetafile( + path + DIRECTORY_SEPARATOR + pluginData->m_libraryName); + + PluginHandle pluginHandle = + PluginDAO::registerPlugin(*pluginData, path); + + WrtLogD("Plugin registered. Registering features..."); + + FOREACH(it, pluginData->m_featureContainer) + { + WrtLogE("PluginHandle: %d", pluginHandle); + FeatureDAO::RegisterFeature(*it, pluginHandle); + } + + WrtLogD("Features registered. Registering objects..."); + + registerPluginObjects(pluginHandle, objects); + + WrtLogD("Objects registered. Finishing..."); + + if (!registerAndUpdateInstallation(pluginHandle, objects)) { + return ReturnStatus::InstallationWaiting; + } + } Catch(DPL::Exception) { + WrtLogE("Failed to make database entry."); + return ReturnStatus::DatabaseError; + } + + WrtLogD("Plugin installed successfully."); + return ReturnStatus::Success; +} + +int PluginsInstaller::installAllPlugins() +{ + if (!m_initialized) { + WrtLogE("Plugins installer not initialized."); + return INSTALLATION_ERROR; + } + WrtLogD("Installing plugins ..."); + + std::string PLUGIN_PATH = std::string(GlobalConfig::GetDevicePluginPath()); + + DIR *dir; + dir = opendir(PLUGIN_PATH.c_str()); + + if (!dir) { + return INSTALLATION_ERROR; + } + + WrtLogD("Plugin DIRECTORY IS %s", PLUGIN_PATH.c_str()); + int return_code; + struct dirent libdir; + struct dirent* result; + + errno = 0; + + std::list<std::string> pluginsPaths; + + for (return_code = readdir_r(dir, &libdir, &result); + result != NULL && return_code == 0; + return_code = readdir_r(dir, &libdir, &result)) { + if (strcmp(libdir.d_name, ".") == 0 || + strcmp(libdir.d_name, "..") == 0) + { + continue; + } + + std::string path = PLUGIN_PATH; + path += "/"; + path += libdir.d_name; + + struct stat tmp; + + if (stat(path.c_str(), &tmp) == -1) { + WrtLogE("Failed to open file %s", path.c_str()); + continue; + } + + if (!S_ISDIR(tmp.st_mode)) { + WrtLogE("Not a directory %s", path.c_str()); + continue; + } + + WrtLogD("Found plugin at %s", path.c_str()); + pluginsPaths.push_back(path); + } + + if (0 != return_code) + WrtLogE("Error while reading directory."); + + if (-1 == closedir(dir)) { + WrtLogE("Failed to close dir: %s", PLUGIN_PATH.c_str()); + } + + WrtLogD("Plugins to install: %d", pluginsPaths.size()); + + for (size_t k = 0; k <= pluginsPaths.size(); ++k) { + printf(" "); + } + printf("]\r["); + int installedPluginsCount = 0; + ReturnStatus ret = ReturnStatus::Unknown; + FOREACH(it, pluginsPaths) { + WrtLogD("Preparing to plugin installation: %s", (*it).c_str()); + ret = installPlugin(*it); + if (ReturnStatus::Success == ret) { + ++installedPluginsCount; + WrtLogD("Plugin %s installed.", (*it).c_str()); + } else if (ReturnStatus::InstallationWaiting == ret) { + WrtLogW("Plugin not installed. Waiting for dependency"); + } else { + WrtLogE("Plugin installation failed"); + } + printf("#"); + fflush(stdout); + } + printf("\n"); + installedPluginsCount += installWaitingPlugins(); + m_registry.UnloadAll(); + WrtLogD("Installed %d plugins of total: %d", + installedPluginsCount, + pluginsPaths.size()); + return installedPluginsCount; +} + +void PluginsInstaller::uninstallPlugin(WrtDB::DbPluginHandle handle, const PluginDAOReadOnly& dao) +{ + WrtLogD("Unregister plugin: %s ...", dao.getLibraryName().c_str()); + + // mark dependent plugins as waiting when their dependency disappered + auto dependentPlugins = *dao.getLibraryDependentPlugins(); + FOREACH(pl, dependentPlugins) { + PluginDAO::setPluginInstallationStatus(*pl, PluginDAO::INSTALLATION_WAITING); + PluginDAO::unregisterPluginLibrariesDependencies(*pl); + } + + PluginDAO::unregisterPlugin(handle); +} + +int PluginsInstaller::uninstallMissingAndChangedPlugins() +{ + int uninstalled = 0; + WrtDB::PluginHandleList list = PluginDAO::getPluginHandleList(); + FOREACH(item, list) + { + Try { + PluginDAOReadOnly dao(*item); + DPL::Utils::Path libPath(dao.getLibraryPath()); + if (!libPath.Exists()) { + // plugin deleted + uninstallPlugin(*item, dao); + ++uninstalled; + } else { + std::time_t timestamp = libPath.LastWriteTime(); + if (timestamp != dao.getLibraryTimestamp()) { + // plugin updated + uninstallPlugin(*item, dao); + ++uninstalled; + } + } + } Catch(PluginDAOReadOnly::Exception::PluginNotExist) { + // ignore, plugin may be already removed + } + } + return uninstalled; +} + +int PluginsInstaller::installWaitingPlugins() +{ + PluginHandleSetPtr waitingPlugins; + + waitingPlugins = + PluginDAO::getPluginHandleByStatus(PluginDAO::INSTALLATION_WAITING); + + int pluginsInstalled = 0; + FOREACH(it, *waitingPlugins) + { + if (resolvePluginDependencies(*it)) { + ++pluginsInstalled; + } + } + return pluginsInstalled; +} + +bool PluginsInstaller::resolvePluginDependencies(PluginHandle handle) +{ + PluginHandleSetPtr dependencies(new PluginHandleSet); + + PluginObjects::ObjectsPtr requiredObjects = + PluginDAO::getRequiredObjectsForPluginHandle(handle); + + PluginHandle depHandle = INVALID_PLUGIN_HANDLE; + + FOREACH(requiredObject, *requiredObjects) + { + depHandle = + PluginDAO::getPluginHandleForImplementedObject(*requiredObject); + + if (INVALID_PLUGIN_HANDLE == depHandle) { + WrtLogE("Library implementing: %s NOT FOUND", requiredObject->c_str()); + return false; + } + dependencies->insert(depHandle); + } + + PluginDAO::registerPluginLibrariesDependencies(handle, dependencies); + PluginDAO::setPluginInstallationStatus(handle, + PluginDAO::INSTALLATION_COMPLETED); + + return true; +} + +void PluginsInstaller::registerObjects(const PluginObjectsPtr& libObj, + const IObjectsListPtr& objects) const +{ + WrtLogD("registerObjects invoked"); + + FOREACH(o, *objects) + { + auto children = CAST(*o)->GetChildren(); + + if (children) { + FOREACH(c, *children) + { + libObj->addObjects(CAST(*o)->GetName(), CAST(*c)->GetName()); + + WrtLogD("[Parent << Object] %s << %s", + CAST(*c)->GetName(), + CAST(*o)->GetName()); + } + + registerObjects(libObj, children); + } + } +} + +PluginsInstaller::OptionalPluginMetafileData PluginsInstaller::parseMetafile( + const std::string& path) const +{ + WrtLogD("Plugin Config file: %s", path.c_str()); + Try + { + PluginMetafileData pluginInfo; + PluginMetafileReader reader; + reader.initialize(path); + reader.read(pluginInfo); + + FOREACH(it, pluginInfo.m_featureContainer) { + WrtLogD("Parsed feature : %s", it->m_name.c_str()); + + FOREACH(devCap, it->m_deviceCapabilities) { + WrtLogD(" | DevCap : %s", (*devCap).c_str()); + } + } + return OptionalPluginMetafileData(pluginInfo); + } + Catch(ValidationCore::ParserSchemaException::Base) { + WrtLogE("Error during file processing %s", path.c_str()); + ThrowMsg(PluginInstall::Exceptions::XMLFileParsingException, + "Parsing metafile failed"); + } +} + +std::string PluginsInstaller::getLibraryName(const std::string& dirPath) const +{ + std::string pluginPath = dirPath; + size_t indexpos = pluginPath.find_last_of('/'); + + if (std::string::npos == indexpos) { + indexpos = 0; + } else { + indexpos += 1; // move after '/' + } + + std::string libName = pluginPath.substr(indexpos); + libName = WrtDB::GlobalConfig::GetPluginPrefix() + libName + + WrtDB::GlobalConfig::GetPluginSuffix(); + WrtLogD("Plugin .so: %s", libName.c_str()); + return libName; +} + +bool PluginsInstaller::registerAndUpdateInstallation( + const WrtDB::DbPluginHandle& pluginHandle, + const PluginObjectsPtr& libraries) +{ + PluginHandleSetPtr handles = PluginHandleSetPtr(new PluginHandleSet); + + DbPluginHandle handle = INVALID_PLUGIN_HANDLE; + + //register requiredObjects + FOREACH(it, *(libraries->getDependentObjects())) + { + if (libraries->hasObject(*it)) { + WrtLogD("Dependency from the same library. ignored"); + continue; + } + + handle = PluginDAO::getPluginHandleForImplementedObject(*it); + if (handle == INVALID_PLUGIN_HANDLE) { + WrtLogE("Library implementing: %s NOT FOUND", (*it).c_str()); + PluginDAO::setPluginInstallationStatus( + pluginHandle, + PluginDAO::INSTALLATION_WAITING); + return false; + } + + handles->insert(handle); + } + + PluginDAO::registerPluginLibrariesDependencies(pluginHandle, handles); + + PluginDAO::setPluginInstallationStatus(pluginHandle, + PluginDAO::INSTALLATION_COMPLETED); + return true; +} + +bool PluginsInstaller::fillMappingInterfaces(PluginMetafileData& pluginData, + const std::string& filename) +{ + void *dlHandle = dlopen(filename.c_str(), RTLD_NOW); + if (dlHandle == NULL) { + const char* error = (const char*)dlerror(); + WrtLogE("Failed to load plugin: %s. Reason: %s", + filename.c_str(), + (error != NULL ? error : "unknown")); + return false; + } + Try + { + ExportedApi* entryPoint = + static_cast<ExportedApi*>(dlsym(dlHandle, GetExportedSymbolName())); + if (NULL == entryPoint) { + const char* error = (const char*)dlerror(); + WrtLogE("Error: %s", (error != NULL ? error : "unknown")); + ThrowMsg(PluginInstall::Exceptions::LibraryException, + "Library error"); + } + + // obtain feature -> dev-cap mapping + feature_mapping_interface_t mappingInterface = { NULL, NULL, NULL }; + entryPoint->GetProvidedFeatures(&mappingInterface); + + if (!mappingInterface.featGetter || !mappingInterface.release || + !mappingInterface.dcGetter) + { + WrtLogE("Failed to obtain mapping interface from .so"); + ThrowMsg(PluginInstall::Exceptions::LibraryException, + "Library error"); + } + + feature_mapping_t* devcapMapping = mappingInterface.featGetter(); + + WrtLogD("Getting mapping from features to device capabilities"); + + for (size_t i = 0; i < devcapMapping->featuresCount; ++i) { + PluginMetafileData::Feature feature; + feature.m_name = devcapMapping->features[i].feature_name; + + WrtLogD("Feature: %s", feature.m_name.c_str()); + + const devcaps_t* dc = + mappingInterface.dcGetter( + devcapMapping, + devcapMapping->features[i]. + feature_name); + + WrtLogD("device=cap: %p", dc); + + if (dc) { + WrtLogD("devcaps count: %d", dc->devCapsCount); + + for (size_t j = 0; j < dc->devCapsCount; ++j) { + WrtLogD("devcap: %s", dc->deviceCaps[j]); + feature.m_deviceCapabilities.insert(dc->deviceCaps[j]); + } + } + + pluginData.m_featureContainer.insert(feature); + } + + mappingInterface.release(devcapMapping); + } Catch(PluginInstall::Exceptions::PluginsInstallerException) + { + WrtLogE("Exception while feature mapping"); + dlclose(dlHandle); + return false; + } + + // Unload library + if (dlclose(dlHandle) != 0) { + WrtLogE("Cannot close plugin handle"); + } else { + WrtLogD("Library is unloaded"); + } + return true; +} + +void PluginsInstaller::registerPluginObjects( + const WrtDB::DbPluginHandle& handle, + const PluginObjectsPtr libObjects) +const +{ + //register implemented objects + PluginObjects::ObjectsPtr objects = + libObjects->getImplementedObject(); + + FOREACH(it, *objects) + { + WrtDB::PluginDAO::registerPluginImplementedObject(*it, handle); + } + + //register requiredObjects + objects = libObjects->getDependentObjects(); + + FOREACH(it, *objects) + { + if (libObjects->hasObject(*it)) { + WrtLogD("Dependency from the same library. ignored"); + continue; + } + WrtDB::PluginDAO::registerPluginRequiredObject(*it, handle); + } +} + diff --git a/src/plugins-installer/plugin_installer.h b/src/plugins-installer/plugin_installer.h new file mode 100644 index 0000000..f669e76 --- /dev/null +++ b/src/plugins-installer/plugin_installer.h @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2012 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 plugin_installer.h + * @author Andrzej Surdej(a.surdej@samgsung.com) + * @version + * @brief + */ + +#ifndef WRT_PLUGINS_INSTALLER_PLUGIN_INSTALLER_H +#define WRT_PLUGINS_INSTALLER_PLUGIN_INSTALLER_H + +#include <string> +#include <utility> +#include <boost/optional.hpp> +#include <plugin_installer_types.h> +#include <plugin_objects.h> +#include <IObject.h> +#include <PluginRegistry.h> + +#include <dpl/wrt-dao-rw/plugin_dao.h> +#include <dpl/singleton.h> + +class PluginsInstaller +{ + public: + static const int INSTALLATION_ERROR; + enum class ReturnStatus + { + Success, ///< Success + + NotInitialized, ///< Singleton not initialized + WrongPluginPath, ///< ? + MetafileError, ///< ? + AlreadyInstalled, ///< ? + LoadingLibraryError, ///< Loading library by dlopen failed. + /// It may be caused by missing symbols + InstallationWaiting, /// Installation failed due to dependencies + DatabaseError, /// Unable to update database + Unknown ///< Temporary error. Try to not use this. + }; + + bool initialize(); + int installAllPlugins(); + void deinitialize(); + + ReturnStatus installPlugin(const std::string& libPath); + ReturnStatus installPluginFromMetafile(const std::string& libPath, + const std::string& metaFilePath); + + int installWaitingPlugins(); + bool resolvePluginDependencies(PluginHandle handle); + + bool isInitialized(); + + int uninstallMissingAndChangedPlugins(); + void uninstallPlugin(WrtDB::DbPluginHandle handle, const WrtDB::PluginDAOReadOnly& dao); + + private: + friend class DPL::Singleton<PluginsInstaller>; + + PluginsInstaller(); + virtual ~PluginsInstaller(); + + void registerObjects(const PluginObjectsPtr& libObj, + const WrtPluginsApi::IObjectsListPtr& objects) const; + + typedef boost::optional<WrtDB::PluginMetafileData> OptionalPluginMetafileData; + OptionalPluginMetafileData parseMetafile(const std::string& path) const; + + std::string getLibraryName(const std::string& dirPath) const; + bool registerAndUpdateInstallation(const PluginHandle& pluginHandle, + const PluginObjectsPtr& libraries); + bool fillMappingInterfaces(WrtDB::PluginMetafileData& pluginData, + const std::string& filename); + void registerPluginObjects(const PluginHandle& handle, + const PluginObjectsPtr libObjects) const; + void checkDatabaseTablesExistance(); + PluginObjectsPtr loadLibraryFromMetafile(const std::string& libName) const; + + WrtPluginsApi::PluginRegistry m_registry; + bool m_initialized; + bool m_reinstall; +}; + +typedef DPL::Singleton<PluginsInstaller> PluginsInstallerSingleton; + +#endif /* WRT_PLUGINS_INSTALLER_PLUGIN_INSTALLER_H */ + diff --git a/src/plugins-installer/plugin_installer_errors.h b/src/plugins-installer/plugin_installer_errors.h new file mode 100644 index 0000000..9a94a79 --- /dev/null +++ b/src/plugins-installer/plugin_installer_errors.h @@ -0,0 +1,38 @@ +/* + * 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 plugin_installer_errors.h + * @author Pawel Sikorski (p.sikorski@samgsung.com) + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ + +#ifndef WRT_PLUGINS_INSTALLER_PLUGIN_INSTALLER_ERRORS_H +#define WRT_PLUGINS_INSTALLER_PLUGIN_INSTALLER_ERRORS_H + +#include <dpl/exception.h> + +namespace PluginInstall { +namespace Exceptions { +DECLARE_EXCEPTION_TYPE(DPL::Exception, PluginsInstallerException) +DECLARE_EXCEPTION_TYPE(PluginsInstallerException, LibraryException) +DECLARE_EXCEPTION_TYPE(PluginsInstallerException, XMLFileParsingException) +} //namespace +} //namespace + +#endif /* WRT_PLUGINS_INSTALLER_PLUGIN_INSTALLER_ERRORS_H */ + diff --git a/src/plugins-installer/plugin_installer_types.h b/src/plugins-installer/plugin_installer_types.h new file mode 100644 index 0000000..ae3a5db --- /dev/null +++ b/src/plugins-installer/plugin_installer_types.h @@ -0,0 +1,37 @@ +/* + * 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 plugin_installer_types.h + * @author Andrzej Surdej (a.surdej@samgsung.com) + * @version + * @brief + */ + +#ifndef WRT_PLUGINS_INSTALLER_PLUGIN_INSTALLER_TYPES_H +#define WRT_PLUGINS_INSTALLER_PLUGIN_INSTALLER_TYPES_H + +#include <dpl/wrt-dao-ro/common_dao_types.h> + +/* Define db type */ +typedef WrtDB::DbWidgetHandle WidgetHandle; +typedef WrtDB::DbWidgetHandleList WidgetHandleList; + +typedef WrtDB::DbWidgetFeature WidgetFeature; +typedef WrtDB::DbWidgetFeatureSet WidgetFeatureSet; + +typedef WrtDB::DbPluginHandle PluginHandle; + +#endif /* WRT_PLUGINS_INSTALLER_PLUGIN_INSTALLER_TYPES_H */ diff --git a/src/plugins-installer/plugin_metafile_reader.cpp b/src/plugins-installer/plugin_metafile_reader.cpp new file mode 100644 index 0000000..b65c2e3 --- /dev/null +++ b/src/plugins-installer/plugin_metafile_reader.cpp @@ -0,0 +1,82 @@ +/* + * 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 plugin_metafile_reader.cpp + * @author Grzegorz Krawczyk(g.krawczyk@samsung.com) + * @version 1.0 + * @brief + */ + +#include "plugin_metafile_reader.h" + +using namespace WrtDB; + +namespace { +const std::string XML_NAMESPACE = ""; + +const std::string TOKEN_LIBRARY_NAME = "library-name"; +const std::string TOKEN_API_FEATURE = "api-feature"; +const std::string TOKEN_NAME = "name"; +const std::string TOKEN_DEVICECAPABILITY = "device-capability"; +} + +PluginMetafileReader::PluginMetafileReader() : m_parserSchema(this) +{ + m_parserSchema.addEndTagCallback( + TOKEN_LIBRARY_NAME, + XML_NAMESPACE, + &PluginMetafileReader::tokenEndLibraryName); + + m_parserSchema.addEndTagCallback( + TOKEN_API_FEATURE, + XML_NAMESPACE, + &PluginMetafileReader::tokenEndApiFeature); + + m_parserSchema.addEndTagCallback( + TOKEN_NAME, + XML_NAMESPACE, + &PluginMetafileReader::tokenEndName); + + m_parserSchema.addEndTagCallback( + TOKEN_DEVICECAPABILITY, + XML_NAMESPACE, + &PluginMetafileReader::tokenEndDeviceCapability); +} + +void PluginMetafileReader::blankFunction(PluginMetafileData & /* data */) +{} + +void PluginMetafileReader::tokenEndLibraryName(PluginMetafileData &data) +{ + data.m_libraryName = m_parserSchema.getText(); +} + +void PluginMetafileReader::tokenEndApiFeature(PluginMetafileData &data) +{ + data.m_featureContainer.insert(m_feature); + m_feature.m_deviceCapabilities.clear(); +} + +void PluginMetafileReader::tokenEndName(PluginMetafileData & /* data */) +{ + m_feature.m_name = m_parserSchema.getText(); +} + +void PluginMetafileReader::tokenEndDeviceCapability(PluginMetafileData& /*data*/) +{ + m_feature.m_deviceCapabilities.insert(m_parserSchema.getText()); +} + diff --git a/src/plugins-installer/plugin_metafile_reader.h b/src/plugins-installer/plugin_metafile_reader.h new file mode 100644 index 0000000..b0c88f0 --- /dev/null +++ b/src/plugins-installer/plugin_metafile_reader.h @@ -0,0 +1,61 @@ +/* + * 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 plugin_metafile_reader.h + * @author Grzegorz Krawczyk(g.krawczyk@samsung.com) + * @version 1.0 + * @brief + */ + +#ifndef WRT_SRC_INSTALLER_CORE_PLUGIN_INSTALLER_TASKS_PLUGIN_METAFILE_READER_H_ +#define WRT_SRC_INSTALLER_CORE_PLUGIN_INSTALLER_TASKS_PLUGIN_METAFILE_READER_H_ + +#include <dpl/wrt-dao-ro/common_dao_types.h> +#include <vcore/ParserSchema.h> + +class PluginMetafileReader +{ + public: + PluginMetafileReader(); + + void initialize(const std::string &filename) + { + m_parserSchema.initialize(filename, + true, + ValidationCore::SaxReader::VALIDATION_DTD, + std::string()); + } + + void read(WrtDB::PluginMetafileData &data) + { + m_parserSchema.read(data); + } + + private: + void blankFunction(WrtDB::PluginMetafileData &data); + + void tokenEndLibraryName(WrtDB::PluginMetafileData &data); + void tokenEndApiFeature(WrtDB::PluginMetafileData &data); + void tokenEndName(WrtDB::PluginMetafileData &data); + void tokenEndDeviceCapability(WrtDB::PluginMetafileData &data); + + WrtDB::PluginMetafileData::Feature m_feature; + + ValidationCore::ParserSchema<PluginMetafileReader, + WrtDB::PluginMetafileData> m_parserSchema; +}; + +#endif diff --git a/src/plugins-installer/plugin_objects.cpp b/src/plugins-installer/plugin_objects.cpp new file mode 100644 index 0000000..5149225 --- /dev/null +++ b/src/plugins-installer/plugin_objects.cpp @@ -0,0 +1,125 @@ +/* + * 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 plugin_objects.h + * @author Grzegorz Krawczyk (g.krawczyk@samgsung.com) + * @version + * @brief + */ +#include <string> +#include <dpl/log/wrt_log.h> +#include "plugin_objects.h" +#include <IObject.h> + +namespace { +const char* SEPARATOR = "."; +const std::string GLOBAL_OBJECT_NAME = WrtPluginsApi::IObject::WINDOW_OBJECT(); +const std::string OLD_GLOBAL_OBJECT_NAME = "GLOBAL_OBJECT"; + +std::string normalizeName(const std::string& objectName) +{ + if (objectName.empty()) { + WrtLogE("Normalize name, name size is 0"); + return objectName; + } + + if (!objectName.compare(0, GLOBAL_OBJECT_NAME.size(), + GLOBAL_OBJECT_NAME)) + { + return objectName; + } + + //normalizing name of objects registered in old way + if (!objectName.compare(0, OLD_GLOBAL_OBJECT_NAME.size(), + OLD_GLOBAL_OBJECT_NAME)) + { + if (objectName.size() > OLD_GLOBAL_OBJECT_NAME.size() + 1) + { + return GLOBAL_OBJECT_NAME + std::string(SEPARATOR) + objectName.substr(OLD_GLOBAL_OBJECT_NAME.size() + 1); + } + else + { + return GLOBAL_OBJECT_NAME; + } + } + + //each object in storage has name started from $GLOBAL_OBJECT_NAME$ + return GLOBAL_OBJECT_NAME + std::string(SEPARATOR) + objectName; +} + +std::string normalizeName(const std::string& objectName, + const std::string& parentName) +{ + if (objectName.empty() || parentName.empty()) { + WrtLogE("Normalize name, name size or parent name size is 0"); + return std::string(); + } + + std::string normalizedName; + normalizedName = normalizeName(parentName) + + std::string(SEPARATOR) + objectName; + + return normalizedName; +} +} + +PluginObjects::PluginObjects() +{ + m_implemented = ObjectsPtr(new Objects()); + m_dependent = ObjectsPtr(new Objects()); +} + +PluginObjects::ObjectsPtr PluginObjects::getImplementedObject() const +{ + return m_implemented; +} + +PluginObjects::ObjectsPtr PluginObjects::getDependentObjects() const +{ + return m_dependent; +} + +void PluginObjects::addObjects(const std::string& parentName, + const std::string& name) +{ + WrtLogD("\n Parent: %s\n Name: %s\n After: Implemented: %s\n After Dependent: %s", + parentName.c_str(), + name.c_str(), + normalizeName(name, parentName).c_str(), + normalizeName(parentName).c_str()); + + addImplementedObject(normalizeName(name, parentName)); + addDependentObject(normalizeName(parentName)); +} + +void PluginObjects::addDependentObject(const std::string& value) +{ + if (!value.compare(GLOBAL_OBJECT_NAME)) { + //dont add dependency to GLOBAL_OBJECT + return; + } + m_dependent->insert(value); +} + +bool PluginObjects::hasObject(const std::string& name) const +{ + return m_implemented->find(name) != m_implemented->end(); +} + +void PluginObjects::addImplementedObject(const std::string& value) +{ + m_implemented->insert(value); +} diff --git a/src/plugins-installer/plugin_objects.h b/src/plugins-installer/plugin_objects.h new file mode 100644 index 0000000..0b27a14 --- /dev/null +++ b/src/plugins-installer/plugin_objects.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. + */ +/** + * @file plugin_objects.h + * @author Grzegorz Krawczyk(g.krawczyk@samsung.com) + * @version 1.0 + * @brief + */ + +#ifndef WRT_SRC_INSTALLER_CORE_PLUGIN_INSTALLER_TASKS_PLUGIN_OBJECTS_H_ +#define WRT_SRC_INSTALLER_CORE_PLUGIN_INSTALLER_TASKS_PLUGIN_OBJECTS_H_ + +#include <memory> +#include <string> +#include <set> +#include <list> + +#include <dpl/wrt-dao-ro/common_dao_types.h> +//TODO TO BE MOVED SOMEWHERE ELSE +// AS OTHER MODULES (LIKE DAO) USE IT + +class PluginObjects : public WrtDB::PluginObjectsDAO +{ + public: + explicit PluginObjects(); + + //getters for objects from library + ObjectsPtr getImplementedObject() const; + ObjectsPtr getDependentObjects() const; + + //add object declaration + void addObjects(const std::string& parentName, + const std::string& name); + + //check if library implemements object given as name + bool hasObject(const std::string& name) const; + + private: + void addImplementedObject(const std::string& value); + void addDependentObject(const std::string& value); +}; + +typedef std::shared_ptr<PluginObjects> PluginObjectsPtr; + +#endif diff --git a/src/plugins-installer/plugin_utils.cpp b/src/plugins-installer/plugin_utils.cpp new file mode 100644 index 0000000..18f49d6 --- /dev/null +++ b/src/plugins-installer/plugin_utils.cpp @@ -0,0 +1,83 @@ +/* + * 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 plugin-utils.cpp + * @author + * @version 1.0 + * @brief Header file for plugin util + */ + +#include "plugin_utils.h" +#include <dpl/semaphore.h> +#include <dpl/exception.h> +#include <dpl/log/wrt_log.h> +#include <dpl/wrt-dao-ro/global_config.h> + +using namespace WrtDB; + +namespace PluginUtils { +//checks if file exists and is regular file +bool checkFileExistance(const std::string& filename) +{ + struct stat tmp; + + if (0 == stat(filename.c_str(), &tmp) && S_ISREG(tmp.st_mode)) { + return true; + } + return false; +} + +std::string cutOffFileName(const std::string& path) +{ + size_t found = path.find_last_of("/"); + if (found == std::string::npos) { + return path; + } else { + return path.substr(0, found); + } +} + +bool checkPath(const std::string& path) +{ + struct stat st; + if (0 == stat(path.c_str(), &st) && S_ISDIR(st.st_mode)) { + return true; + } + WrtLogE("Cannot access directory [%s]", path.c_str()); + return false; +} + +bool checkPaths() +{ + bool if_ok = true; + if_ok &= (checkPath(cutOffFileName( + GlobalConfig::GetWrtDatabaseFilePath()))); + if (!if_ok) { + WrtLogE("Path <%s> does not exist.", GlobalConfig::GetWrtDatabaseFilePath()); + } + + if_ok &= (checkPath(GlobalConfig::GetDevicePluginPath())); + if (!if_ok) { + WrtLogE("Path <%s> does not exist.", GlobalConfig::GetDevicePluginPath()); + } + + if_ok &= (checkPath(GlobalConfig::GetUserInstalledWidgetPath())); + if (!if_ok) { + WrtLogE("Path <%s> does not exist.", GlobalConfig::GetUserInstalledWidgetPath()); + } + return if_ok; +} +} //namespace PluginUtils diff --git a/src/plugins-installer/plugin_utils.h b/src/plugins-installer/plugin_utils.h new file mode 100644 index 0000000..a542e28 --- /dev/null +++ b/src/plugins-installer/plugin_utils.h @@ -0,0 +1,35 @@ +/* + * 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 plugin-utils.h + * @author + * @version 1.0 + * @brief Header file for plugin util + */ +#ifndef PLUGIN_UTILS_H +#define PLUGIN_UTILS_H + +#include <string> +#include <sys/stat.h> + +namespace PluginUtils { +bool checkFileExistance(const std::string& filename); + +std::string cutOffFileName(const std::string& path); +bool checkPath(const std::string& path); +bool checkPaths(); +} +#endif // PLUGIN_UTILS_H diff --git a/src/plugins-installer/wrt_plugins_installer.cpp b/src/plugins-installer/wrt_plugins_installer.cpp new file mode 100644 index 0000000..aa7ea53 --- /dev/null +++ b/src/plugins-installer/wrt_plugins_installer.cpp @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2012 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 wrt_plugins_installer.cpp + * @author Andrzej Surdej(a.surdej@gmail.com) + * @version 1.0 + * @brief Main file for plugins installer + */ + +#include <plugin_installer.h> +#include <dpl/log/wrt_log.h> +#include <string> +#include <cstdio> +#include <dpl/exception.h> +#include <dpl/platform.h> + +int main(int /*argc*/, char */*argv*/[]) +{ + UNHANDLED_EXCEPTION_HANDLER_BEGIN + { + WrtLogD("Plugins installation started."); + + printf("Installing plugins...\n"); + PluginsInstallerSingleton::Instance().initialize(); + +#ifdef ENABLE(DOWNLOADABLE_PLUGIN) + int uninstalled = PluginsInstallerSingleton::Instance().uninstallMissingAndChangedPlugins(); + printf("# %d plugins uninstalled.\n", uninstalled); +#endif + + int installed = PluginsInstallerSingleton::Instance().installAllPlugins(); + printf("# %d plugins installed.\n", installed); + + PluginsInstallerSingleton::Instance().deinitialize(); + WrtLogD("All plugins installed successfuly"); + return 0; + } + UNHANDLED_EXCEPTION_HANDLER_END +} diff --git a/src/plugins-ipc-message/CMakeLists.txt b/src/plugins-ipc-message/CMakeLists.txt new file mode 100644 index 0000000..92ca185 --- /dev/null +++ b/src/plugins-ipc-message/CMakeLists.txt @@ -0,0 +1,63 @@ +# 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 CMakeLists.txt +# @author Jihoon Chung (jihoon.chung@samsung.com) +# @version 1.0 +# + +PKG_SEARCH_MODULE(dpl REQUIRED dpl-efl) +PKG_SEARCH_MODULE(webkit2 REQUIRED ewebkit2) + +SET(PLUGINS_IPC_MESSAGE_SOURCES + ${PLUGINS_IPC_MESSAGE_DIRS}/ipc_message_support.cpp +) + +INCLUDE_DIRECTORIES( + ${PLUGINS_IPC_MESSAGE_DIRS} + ${webkit2_INCLUDE_DIRS} +) + +ADD_LIBRARY(${TARGET_PLUGINS_IPC_MESSAGE_LIB} SHARED + ${PLUGINS_IPC_MESSAGE_SOURCES} +) + +SET_TARGET_PROPERTIES(${TARGET_PLUGINS_IPC_MESSAGE_LIB} PROPERTIES + COMPILE_FLAGS -fPIC + LINK_FLAGS "-Wl,--as-needed -Wl,--hash-style=both" +) + +SET_TARGET_PROPERTIES(${TARGET_PLUGINS_IPC_MESSAGE_LIB} PROPERTIES + SOVERSION ${CMAKE_PROJECT_API_VERSION} + VERSION ${CMAKE_PROJECT_VERSION} +) + +TARGET_LINK_LIBRARIES(${TARGET_PLUGINS_IPC_MESSAGE_LIB} + ${dpl_LIBRARIES} + ${webkit2_LIBRARIES} +) + +SET_TARGET_PROPERTIES(${TARGET_PLUGINS_IPC_MESSAGE_LIB} PROPERTIES + COMPILE_DEFINITIONS LOG_TAG="${LOG_TAG}") + +INSTALL(TARGETS ${TARGET_PLUGINS_IPC_MESSAGE_LIB} + DESTINATION lib + PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE + GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE +) + +INSTALL(FILES + ipc_message_support.h + DESTINATION include/plugins-ipc-message) diff --git a/src/plugins-ipc-message/ipc_message_support.cpp b/src/plugins-ipc-message/ipc_message_support.cpp new file mode 100644 index 0000000..1a405db --- /dev/null +++ b/src/plugins-ipc-message/ipc_message_support.cpp @@ -0,0 +1,237 @@ +/* + * 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 ipc_message_support.cpp + * @author Jihoon Chung (jihoon.chung@samsung.com) + * @version 1.0 + * @brief Implementation of IPC between plugins and UI Process + */ +#include "ipc_message_support.h" + +#include <string> +#include <sstream> +#include <WKBundle.h> +#include <WKString.h> +#include <WKType.h> +#include <dpl/log/wrt_log.h> +#include <dpl/assert.h> + +static WKBundleRef s_injectedBundleRef = NULL; +static unsigned int s_xWindowHandle = 0; + +namespace { +const char* const TIZEN_GET_WINDOW_HANDLE = "tizen://getWindowHandle"; +const char* const TIZEN_CLEAR_ALL_COOKIES = "tizen://clearAllCookies"; + +static void sendPostMessage(const char* name, const char* body) +{ + WKStringRef nameWKString = WKStringCreateWithUTF8CString(name); + WKStringRef bodyWKString = NULL; + if (body) { + bodyWKString = WKStringCreateWithUTF8CString(body); + } + + WKBundlePostMessage(s_injectedBundleRef, + nameWKString, + bodyWKString); + WKRelease(nameWKString); + if (bodyWKString) { + WKRelease(bodyWKString); + } +} + +static int sendAsyncMessage(const char* name, const char* body, AsyncReplyCallback replyCallback, void* data) +{ + using namespace IPCMessageSupport; + + int handle = AsyncConnectionManager::instance().addConnection(AsyncConnectionPtr(new AsyncConnection(replyCallback, data))); + + std::string strBody = body; + std::stringstream ss; + + ss << handle; + strBody = ss.str() + "_" + strBody; + + sendPostMessage(name, strBody.c_str()); + + return handle; +} + +} // namespace + + +namespace IPCMessageSupport { + +AsyncConnectionManager::~AsyncConnectionManager() +{ + m_connectionMap.clear(); +} + +AsyncConnectionManager &AsyncConnectionManager::instance() +{ + static AsyncConnectionManager instance; + + return instance; +} + +int AsyncConnectionManager::addConnection(AsyncConnectionPtr connection) +{ + static int latestHandle = -1; + int newHandle; + + latestHandle++; + if (latestHandle < 0) latestHandle = 0; + + newHandle = latestHandle; + + m_connectionMap.insert(AsyncConnectionMap::value_type(newHandle, connection)); + + return newHandle; +} + +bool AsyncConnectionManager::removeConnection(int handle) +{ + bool ret = (m_connectionMap.erase(handle) == 1); + + return ret; +} + +AsyncConnectionPtr AsyncConnectionManager::getConnection(int handle) +{ + AsyncConnectionMap::iterator iter = m_connectionMap.find(handle); + + if (iter != m_connectionMap.end()) + { + return iter->second; + } + + return AsyncConnectionPtr(); +} + + +} // namespace IPCMessageSupport + + +void IPCMessageSupport::setWKBundleRef(WKBundleRef bundleRef) +{ + WrtLogD("called"); + s_injectedBundleRef = bundleRef; +} + +void IPCMessageSupport::setXwindowHandle(unsigned int handle) +{ + WrtLogD("called"); + s_xWindowHandle = handle; +} + +const char* IPCMessageSupport::sendMessageToUiProcess( + const char* name, + const char* body) +{ + WrtLogD("called"); + if (s_injectedBundleRef == NULL) { + WrtLogE("UI Process information isn't set"); + return NULL; + } + WrtLogD("name = [%s]", name); + if (body) { + WrtLogD("body = [%s]", body); + } + + if (!name) { + return NULL; + } + + // tizen://getWindowHandle + if (!strcmp(name, TIZEN_GET_WINDOW_HANDLE)) { + if (s_xWindowHandle == 0) { + return NULL; + } else { + std::stringstream ss; + ss << s_xWindowHandle; + std::string ret = ss.str(); + return strdup(ret.c_str()); + } + } + + // tizen://clearAllCookies + if (!strcmp(name, TIZEN_CLEAR_ALL_COOKIES)) { + sendPostMessage(name, body); + return NULL; + } + + return NULL; +} + +int IPCMessageSupport::sendAsyncMessageToUiProcess(const char* name, const char* body, AsyncReplyCallback replyCallback, void* data) +{ + WrtLogD("called"); + + if (s_injectedBundleRef == NULL) + { + WrtLogE("UI Process information isn't set"); + return -1; + } + + if (name == NULL) + { + WrtLogE("msg name is null!"); + return -1; + } + + if (body == NULL) + { + body = ""; + } + + WrtLogD("name = [%s]\nbody = [%s]", name, body); + + return sendAsyncMessage(name, body, replyCallback, data); +} + +void* IPCMessageSupport::ignoreAsyncMessageReply(int handle) +{ + WrtLogD("called"); + + AsyncConnectionPtr connection = AsyncConnectionManager::instance().getConnection(handle); + + if (!connection) + { + return NULL; + } + + AsyncConnectionManager::instance().removeConnection(handle); + + return connection->data; +} + +void IPCMessageSupport::replyAsyncMessageToWebProcess(Ewk_Context* ewkContext, int handle, const char* body) +{ + WrtLogD("called"); + + if (ewkContext == NULL) + { + return; + } + + std::string strBody = (body) ? (body) : ""; + std::stringstream ss; + ss << handle; + + strBody = ss.str() + "_" + strBody; + + ewk_context_message_post_to_injected_bundle(ewkContext, REPLY_ASYNC, strBody.c_str()); +} diff --git a/src/plugins-ipc-message/ipc_message_support.h b/src/plugins-ipc-message/ipc_message_support.h new file mode 100644 index 0000000..352e774 --- /dev/null +++ b/src/plugins-ipc-message/ipc_message_support.h @@ -0,0 +1,83 @@ +/* + * 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 ipc_message_support.h + * @author Jihoon Chung (jihoon.chung@samsung.com) + * @version 1.0 + * @brief Implementation of IPC between plugins and UI Process + */ +#ifndef WRT_SRC_IPC_MESSAGE_SUPPORT +#define WRT_SRC_IPC_MESSAGE_SUPPORT + +#include <memory> +#include <map> +#include <string> +#include <WKBundle.h> +#include <EWebKit.h> +#include <EWebKit_internal.h> + +typedef void (*AsyncReplyCallback)(unsigned int, void*, const char*); + +namespace IPCMessageSupport { + +static const char * const REPLY_ASYNC = "ToInjectedBundle::REPLY_ASYNC"; +static const char * const TIZEN_CHANGE_USERAGENT = "tizen://changeUA"; +static const char * const TIZEN_DELETE_ALL_COOKIES = "tizen://deleteAllCookies"; +static const char * const TIZEN_EXIT = "tizen://exit"; +static const char * const TIZEN_HIDE = "tizen://hide"; + +class AsyncConnection +{ + public: + AsyncReplyCallback replyCallback; + void* data; + + AsyncConnection(AsyncReplyCallback r, void* d) : + replyCallback(r), + data(d) + { + } +}; + +typedef std::shared_ptr<AsyncConnection> AsyncConnectionPtr; +typedef std::map<unsigned int, AsyncConnectionPtr> AsyncConnectionMap; + +class AsyncConnectionManager +{ + private: + AsyncConnectionMap m_connectionMap; + + public: + ~AsyncConnectionManager(); + + // Singleton + static AsyncConnectionManager &instance(); + + int addConnection(AsyncConnectionPtr connection); + bool removeConnection(int handle); + AsyncConnectionPtr getConnection(int handle); + +}; + +void setWKBundleRef(WKBundleRef bundleRef); +void setXwindowHandle(unsigned int handle); +const char* sendMessageToUiProcess(const char* name, const char* body); +int sendAsyncMessageToUiProcess(const char* name, const char* body, AsyncReplyCallback replyCallback, void* data); +void* ignoreAsyncMessageReply(int handle); +void replyAsyncMessageToWebProcess(Ewk_Context* ewkContext, int handle, const char* body); +} + +#endif // WRT_SRC_IPC_MESSAGE_SUPPORT diff --git a/src/standards/CMakeLists.txt b/src/standards/CMakeLists.txt new file mode 100644 index 0000000..449083d --- /dev/null +++ b/src/standards/CMakeLists.txt @@ -0,0 +1,16 @@ +# 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. +# + +ADD_SUBDIRECTORY(W3C) diff --git a/src/standards/W3C/CMakeLists.txt b/src/standards/W3C/CMakeLists.txt new file mode 100644 index 0000000..18f64a9 --- /dev/null +++ b/src/standards/W3C/CMakeLists.txt @@ -0,0 +1,15 @@ +# 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. +# +ADD_SUBDIR(Widget) diff --git a/src/standards/W3C/DESCRIPTION b/src/standards/W3C/DESCRIPTION new file mode 100644 index 0000000..8e32c7b --- /dev/null +++ b/src/standards/W3C/DESCRIPTION @@ -0,0 +1,2 @@ +!!!options!!! stop +W3C plugin - Widget Interface diff --git a/src/standards/W3C/Widget/CMakeLists.txt b/src/standards/W3C/Widget/CMakeLists.txt new file mode 100644 index 0000000..9dcab6e --- /dev/null +++ b/src/standards/W3C/Widget/CMakeLists.txt @@ -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. +# + +SET(TARGET_NAME "wrt-plugins-w3c-widget-interface") + +PKG_SEARCH_MODULE(webkit2 REQUIRED ewebkit2) +PKG_SEARCH_MODULE(plugin-types REQUIRED wrt-plugins-types) + +SET(SRCS + ${SRCS_COMMONS} + JSWidget.cpp + JSPreferences.cpp + plugin_initializer.cpp + plugin_config.cpp +) + +INCLUDE_DIRECTORIES( + ${API_WIDGET_PATH} + ${webkit2_INCLUDE_DIRS} + ${plugin-types_INCLUDE_DIRS} + ${PLUGINS_API_SUPPORT_DIRS} +) + +ADD_LIBRARY(${TARGET_NAME} SHARED ${SRCS}) +TARGET_LINK_LIBRARIES(${TARGET_NAME} + ${LIBS_COMMON} + ${TARGET_COMMONS} + ${TARGET_COMMONS_JAVASCRIPT} + ${TARGET_JS_OVERLAY} + ${TARGET_PLUGINS_API_SUPPORT} + wrt-plugins-widget + wrt-plugins-localstorage + wrt-plugins-storageevent + wrt-dispatch-event +) + +# Override default tag +SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES + COMPILE_DEFINITIONS LOG_TAG="WRT_PLUGINS/WIDGET") + +INSTALL(TARGETS ${TARGET_NAME} LIBRARY DESTINATION /usr/lib/wrt-plugins/w3c-widget-interface) diff --git a/src/standards/W3C/Widget/JSPreferences.cpp b/src/standards/W3C/Widget/JSPreferences.cpp new file mode 100644 index 0000000..20377a8 --- /dev/null +++ b/src/standards/W3C/Widget/JSPreferences.cpp @@ -0,0 +1,528 @@ +/* + * 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 JSPreferences.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + */ + +#include "JSPreferences.h" + +#include <string> +#include <dpl/assert.h> +#include <dpl/log/wrt_log.h> +#include <dpl/optional_typedefs.h> +#include <CommonsJavaScript/Converter.h> +#include <CommonsJavaScript/JSDOMExceptionFactory.h> +#include <StorageEvent/StorageEventMgr.h> +#include <StorageEvent/IStorageEvent.h> +#include <dispatch-event/dispatch_event_support.h> + +// import temporarily from JSContextRefPrivate.h +extern "C" JSGlobalContextRef JSContextGetGlobalContext(JSContextRef ctx); + +using namespace std; +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::LocalStorage::Api; +using namespace WrtDeviceApis::StorageEvent::Api; + +#define PREFERENCES_PLUGIN_NAME "preferences" +#define LOCAL_STORAGE_PROPERTY_LENGTH "length" + +#define CATCH_EXCEPTION_NO_MODIFABLE \ + Catch(Commons::LocalStorageValueNoModifableException) { \ + WrtLogE("The item is read only"); \ + return JSDOMExceptionFactory:: \ + NoModificationAllowedException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_CONVERSION \ + Catch(Commons::ConversionException) { \ + WrtLogE("Error on conversion"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_NULL_PTR \ + Catch(Commons::NullPointerException) { \ + WrtLogE("Error on pointer, null value"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_PLATFORM_ERROR \ + Catch(Commons::PlatformException){ \ + WrtLogE("PlatformException occured"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_SECURITY \ + Catch(Commons::SecurityException){ \ + WrtLogE("Security exception occured"); \ + return JSDOMExceptionFactory:: \ + SecurityException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_OUT_OF_RANGE \ + Catch(Commons::OutOfRangeException) { \ + WrtLogE("OutOfRangeException"); \ + return JSDOMExceptionFactory:: \ + QuotaExceededException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_INVALID_ARG \ + Catch(Commons::InvalidArgumentException) { \ + WrtLogE("Pair for given key doesnt exist"); \ + return JSValueMakeNull(context); \ + } + +namespace WrtPlugins { +namespace W3C { +ILocalStoragePtr getIStorage(JSObjectRef arg) +{ + WrtLogD("get localstorage object"); + LocalStoragePrivateData* priv = + static_cast<LocalStoragePrivateData*>(JSObjectGetPrivate(arg)); + + if (!priv) { + WrtLogE("Private object not initialized"); + ThrowMsg(Commons::NullPointerException, + "Private object not initialized"); + } + + return priv->istorage; +} + +JSObjectRef getWidgetObject(JSObjectRef arg) +{ + WrtLogD("get widget object"); + LocalStoragePrivateData* priv = + static_cast<LocalStoragePrivateData*>(JSObjectGetPrivate(arg)); + + if (!priv) { + WrtLogE("Private object not initialized"); + ThrowMsg(Commons::NullPointerException, + "Private object not initialized"); + } + + return priv->widgetObject; +} + +enum class ModificationType +{ + RemoveItem, + SetItem +}; + +//this function may throw exceptions +IStorageEventPtr modifyItemAndCreateEvent(ModificationType type, + JSObjectRef thisObject, + const string& key, + const string& value = std::string()) +{ + DPL::OptionalStdString oldValue = + getIStorage(thisObject)->getValue(key); + + if (ModificationType::SetItem == type) { + getIStorage(thisObject)->setItem(key, value, false); + } else if (ModificationType::RemoveItem == type) { + getIStorage(thisObject)->removeItem(key); + } else { + Assert(!"Wrong Modification type"); + } + + DPL::OptionalStdString newValue = + getIStorage(thisObject)->getValue(key); + + //create event object + IStorageEventPtr storageEvent = getStorageEvent(); + + //key + storageEvent->setKey(key); + //oldvalue + if (!!oldValue) { + storageEvent->setOldValue(*oldValue); + } + //newValue + if (!!newValue) { + storageEvent->setNewValue(*newValue); + } + + return storageEvent; +} + +JSClassDefinition JSPreferences::m_classInfo = { + 0, + kJSClassAttributeNone, + PREFERENCES_PLUGIN_NAME, + 0, + m_property, + m_function, + initialize, + finalize, + hasProperty, + getProperty, + setProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL, //ConvertToType, +}; + +JSStaticFunction JSPreferences::m_function[] = { + { "setItem", JSPreferences::setItem, kJSPropertyAttributeNone }, + { "removeItem", JSPreferences::removeItem, kJSPropertyAttributeNone }, + { "getItem", JSPreferences::getItem, kJSPropertyAttributeNone }, + { "clear", JSPreferences::clear, kJSPropertyAttributeNone }, + { "key", JSPreferences::key, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +JSStaticValue JSPreferences::m_property[] = { + { LOCAL_STORAGE_PROPERTY_LENGTH, + JSPreferences::getLength, + NULL, + kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSClassRef JSPreferences::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSPreferences::getClassInfo() +{ + return &m_classInfo; +} + +JSClassRef JSPreferences::m_jsClassRef = + JSClassCreate(JSPreferences::getClassInfo()); + +void JSPreferences::initialize(JSContextRef context, + JSObjectRef object) +{ + WrtLogD("entered"); + + LocalStoragePrivateData* priv = + static_cast<LocalStoragePrivateData*>(JSObjectGetPrivate(object)); + + AssertMsg(priv, "private object of preferences is NULL"); +} + +void JSPreferences::finalize(JSObjectRef object) +{ + WrtLogD("entered"); + LocalStoragePrivateData* priv = + static_cast<LocalStoragePrivateData*>(JSObjectGetPrivate(object)); + + delete priv; +} + +JSValueRef JSPreferences::removeItem(JSContextRef context, + JSObjectRef /*object*/, + JSObjectRef thisObject, + size_t /*argumentCount*/, + const JSValueRef arguments[], + JSValueRef* exception) +{ + WrtLogD("entered"); + + Try { + Converter converter(context); + + std::string key = converter.toString(arguments[0]); + + DPL::OptionalStdString oldValue = getIStorage(thisObject)->getValue(key); + getIStorage(thisObject)->removeItem(key); + DPL::OptionalStdString newValue = getIStorage(thisObject)->getValue(key); + + JSContextRef g_context = JSContextGetGlobalContext(context); + + DispatchEventSupport::dispatchStorageEvent(g_context, key, oldValue, newValue, ""); + + return JSValueMakeNull(context); + } + CATCH_EXCEPTION_NO_MODIFABLE + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_SECURITY +} + +JSValueRef JSPreferences::setItem(JSContextRef context, + JSObjectRef /*object*/, + JSObjectRef thisObject, + size_t /*argumentCount*/, + const JSValueRef arguments[], + JSValueRef* exception) +{ + WrtLogD("entered"); + + Try { + Converter converter(context); + + std::string key = converter.toString(arguments[0]); + std::string value = converter.tryString(arguments[1]); + + DPL::OptionalStdString oldValue = getIStorage(thisObject)->getValue(key); + getIStorage(thisObject)->setItem(key, value, false); + DPL::OptionalStdString newValue = getIStorage(thisObject)->getValue(key); + + JSContextRef g_context = JSContextGetGlobalContext(context); + + DispatchEventSupport::dispatchStorageEvent(g_context, key, oldValue, newValue, ""); + + return JSValueMakeUndefined(context); + } + CATCH_EXCEPTION_NO_MODIFABLE + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_SECURITY + CATCH_EXCEPTION_OUT_OF_RANGE +} + +JSValueRef JSPreferences::clear(JSContextRef context, + JSObjectRef /*object*/, + JSObjectRef thisObject, + size_t /*argumentCount*/, + const JSValueRef /*arguments*/[], + JSValueRef* exception) +{ + WrtLogD("entered"); + + Try { + getIStorage(thisObject)->clear(false); + + JSContextRef g_context = JSContextGetGlobalContext(context); + + const auto& null = DPL::OptionalStdString(); + + DispatchEventSupport::dispatchStorageEvent(g_context, null, null, null, ""); + + return JSValueMakeNull(context); + } + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_SECURITY +} + +JSValueRef JSPreferences::getItem(JSContextRef context, + JSObjectRef /*object*/, + JSObjectRef thisObject, + size_t /*argumentCount*/, + const JSValueRef arguments[], + JSValueRef* exception) +{ + WrtLogD("entered"); + + Try { + Converter converter(context); + + std::string key = converter.tryString(arguments[0]); + + WrtLogD("Getting item for key %s", key.c_str()); + + DPL::OptionalStdString value = + getIStorage(thisObject)->getValue(key); + + if (!value) { + return JSValueMakeNull(context); + } else { + return converter.toJSValueRef(*value); + } + } + CATCH_EXCEPTION_INVALID_ARG + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_SECURITY +} + +JSValueRef JSPreferences::key(JSContextRef context, + JSObjectRef /*object*/, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + WrtLogD("entered"); + + Try { + if (argumentCount < 1) { + WrtLogE("No argument found"); + Throw(Commons::InvalidArgumentException); + } + + Converter converter(context); + + size_t n = converter.toSizeT(arguments[0]); + + std::string value = getIStorage(thisObject)->getKeyByIndex(n); + + return converter.toJSValueRef(value); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_SECURITY + CATCH_EXCEPTION_INVALID_ARG +} + +JSValueRef JSPreferences::getLength(JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + WrtLogD("enter"); + + Try + { + Converter converter(context); + + size_t value = getIStorage(object)->getStorageSize(); + return converter.toJSValueRef(value); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_SECURITY + CATCH_EXCEPTION_INVALID_ARG +} + +bool JSPreferences::hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName) +{ + WrtLogD("enter"); + + Try { + Converter converter(context); + + std::string key = converter.toString(propertyName); + + if (!getIStorage(object)->getValue(key)) { + return false; + } else { + return true; + } + } + + Catch(Commons::InvalidArgumentException) { + WrtLogE("Pair for given key doesnt exist"); + } + + Catch(Commons::ConversionException) { + WrtLogE("Error on conversion"); + } + + Catch(Commons::NullPointerException) { + WrtLogE("Error on pointer, null value"); + } + + Catch(Commons::PlatformException){ + WrtLogE("PlatformException occured"); + } + return false; +} + +JSValueRef JSPreferences::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + WrtLogD("enter"); + + Try { + Converter converter(context); + + std::string key = converter.toString(propertyName); + + DPL::OptionalStdString value = + getIStorage(object)->getValue(key); + + if (!value) { + return JSValueMakeNull(context); + } else { + return converter.toJSValueRef(*value); + } + } + + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_INVALID_ARG +} + +bool JSPreferences::setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef jvalue, + JSValueRef* exception) +{ + WrtLogD("enter"); + + Try { + Converter converter(context); + + std::string key = converter.toString(propertyName); + std::string value = converter.toString(jvalue); + + DPL::OptionalStdString oldValue = getIStorage(object)->getValue(key); + getIStorage(object)->setItem(key, value, false); + DPL::OptionalStdString newValue = getIStorage(object)->getValue(key); + + JSContextRef g_context = JSContextGetGlobalContext(context); + std::string oldValueStr = ""; + std::string newValueStr = ""; + + if (!!oldValue) { oldValueStr = *oldValue; } + if (!!newValue) { newValueStr = *newValue; } + + DispatchEventSupport::dispatchStorageEvent(g_context, key, oldValueStr, newValueStr, ""); + + return true; + } + CATCH_EXCEPTION_NO_MODIFABLE + CATCH_EXCEPTION_OUT_OF_RANGE + CATCH_EXCEPTION_INVALID_ARG + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR + CATCH_EXCEPTION_SECURITY + + return false; +} + +#undef CATCH_EXCEPTION_NO_MODIFABLE +#undef CATCH_EXCEPTION_CONVERSION +#undef CATCH_EXCEPTION_NULL_PTR +#undef CATCH_EXCEPTION_PLATFORM_ERROR +#undef CATCH_EXCEPTION_SECURITY +#undef CATCH_EXCEPTION_OUT_OF_RANGE +#undef CATCH_EXCEPTION_INVALID_ARG +} +} diff --git a/src/standards/W3C/Widget/JSPreferences.h b/src/standards/W3C/Widget/JSPreferences.h new file mode 100644 index 0000000..b86bae8 --- /dev/null +++ b/src/standards/W3C/Widget/JSPreferences.h @@ -0,0 +1,127 @@ +/* + * 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 JSPreferences.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _WRT_PLUGIN_JS_WIDGET_PREFERENCES_H_ +#define _WRT_PLUGIN_JS_WIDGET_PREFERENCES_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/PrivateObject.h> +#include <LocalStorage/ILocalStorage.h> + +namespace WrtPlugins { +namespace W3C { +struct LocalStoragePrivateData { + WrtDeviceApis::LocalStorage::Api::ILocalStoragePtr istorage; + //parent + JSObjectRef widgetObject; +}; + +class JSPreferences +{ + public: + /** + * This method initializes this in the JS Engine. + */ + static JSClassRef getClassRef(); + + /** + * Gets object's class description. + */ + static const JSClassDefinition* getClassInfo(); + + private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * This structure contains properties and callbacks + * that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function. + */ + static JSStaticFunction m_function[]; + + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; + + //Modified functions for Preference object + static JSValueRef removeItem(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef setItem(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef getItem(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef clear(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef key(JSContextRef context, JSObjectRef object, + JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef getLength(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName); + + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); +}; +} +} + +#endif diff --git a/src/standards/W3C/Widget/JSWidget.cpp b/src/standards/W3C/Widget/JSWidget.cpp new file mode 100644 index 0000000..33944ec --- /dev/null +++ b/src/standards/W3C/Widget/JSWidget.cpp @@ -0,0 +1,561 @@ +/* + * 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 JSWidget.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + */ + +#include "JSWidget.h" +#include <memory> +#include <CommonsJavaScript/Converter.h> +#include <dpl/log/wrt_log.h> +#include <dpl/assert.h> +#include <Widget/WidgetFactory.h> +#include <CommonsJavaScript/JSDOMExceptionFactory.h> +#include "JSPreferences.h" +#include <Widget/IWidget.h> +#include <LocalStorage/LocalStorageMgr.h> +#include <Commons/WrtAccess/WrtAccess.h> +#include <dpl/wrt-dao-ro/wrt_db_types.h> + +// temporary +extern "C" JSGlobalContextRef JSContextGetGlobalContext(JSContextRef ctx); + +#define CATCH_EXCEPTION_NO_MODIFABLE \ + Catch(Commons::LocalStorageValueNoModifableException) { \ + WrtLogE("The item is read only"); \ + return JSDOMExceptionFactory:: \ + NoModificationAllowedException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_CONVERSION \ + Catch(Commons::ConversionException) { \ + WrtLogE("Error on conversion"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_NULL_PTR \ + Catch(Commons::NullPointerException) { \ + WrtLogE("Error on pointer, null value"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_PLATFORM_ERROR \ + Catch(Commons::PlatformException){ \ + WrtLogE("PlatformException occured"); \ + return JSDOMExceptionFactory:: \ + UnknownException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_SECURITY \ + Catch(Commons::SecurityException){ \ + WrtLogE("Security exception occured"); \ + return JSDOMExceptionFactory:: \ + SecurityException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_OUT_OF_RANGE \ + Catch(Commons::OutOfRangeException) { \ + WrtLogE("OutOfRangeException"); \ + return JSDOMExceptionFactory:: \ + QuotaExceededException.make(context, exception); \ + } + +#define CATCH_EXCEPTION_INVALID_ARG \ + Catch(Commons::InvalidArgumentException) { \ + WrtLogE("Pair for given key doesnt exist"); \ + return JSValueMakeNull(context); \ + } + +#define WIDGET_PLUGIN_NAME "Widget" + +#define WRT_WIDGET_PROPERTY_AUTHOR "author" +#define WRT_WIDGET_PROPERTY_AUTHOR_EMAIL "authorEmail" +#define WRT_WIDGET_PROPERTY_AUTHOR_HREF "authorHref" +#define WRT_WIDGET_PROPERTY_DESCRIPTION "description" +#define WRT_WIDGET_PROPERTY_ID "id" +#define WRT_WIDGET_PROPERTY_NAME "name" +#define WRT_WIDGET_PROPERTY_SHORT_NAME "shortName" +#define WRT_WIDGET_PROPERTY_VERSION "version" +#define WRT_WIDGET_PROPERTY_HEIGHT "height" +#define WRT_WIDGET_PROPERTY_WIDTH "width" + +namespace WrtPlugins { +namespace W3C { +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::Widget; + +struct WidgetPrivateObject +{ + Widget::Api::IWidgetPtr iwidget; + JSObjectRef preferencesObject; + JSObjectRef widgetObject; +}; +typedef std::shared_ptr<WidgetPrivateObject> WidgetPrivateObjectPtr; + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT +<WidgetPrivateObjectPtr>::Type JSWidgetPrivateObject; + +WrtDeviceApis::Widget::Api::IWidgetPtr getIWidget(JSObjectRef arg) +{ + JSWidgetPrivateObject* priv = + static_cast<JSWidgetPrivateObject*>(JSObjectGetPrivate(arg)); + + if (!priv) { + WrtLogE("Private object not initialized"); + ThrowMsg(Commons::NullPointerException, + "Private object not initialized"); + } + + return priv->getObject()->iwidget; +} + +LocalStorage::Api::ILocalStoragePtr getLocalStorage(WidgetHandle widgetId) +{ + LocalStorage::Api::ILocalStoragePtr storage( + LocalStorage::Api::getLocalStorage(widgetId)); + + return storage; +} + +JSObjectRef getPreferences(JSObjectRef arg) +{ + JSWidgetPrivateObject* priv = + static_cast<JSWidgetPrivateObject*>(JSObjectGetPrivate(arg)); + + if (!priv) { + WrtLogE("Private object not initialized"); + return NULL; + } + + return priv->getObject()->preferencesObject; +} + +JSObjectRef createPreferencesObject(JSContextRef context, + JSObjectRef widgetObject, + WidgetHandle widgetId) +{ + AssertMsg(widgetObject, "Widget Object can'n be null"); + //delete is invoked in JSPreferences::finalize + LocalStoragePrivateData* priv = new LocalStoragePrivateData; + AssertMsg(priv, "Private data is null"); + priv->istorage = getLocalStorage(widgetId); + priv->widgetObject = widgetObject; + + JSObjectRef preferences = JSObjectMake(context, + JSPreferences::getClassRef(), + priv); + + if (!preferences) { + WrtLogE("Preferences object is null"); + delete priv; + } + //Unprotect is called in JSWidget::finalize + JSValueProtect(context, preferences); + + return preferences; +} + +JSClassDefinition JSWidget::m_classInfo = { + 0, + kJSClassAttributeNone, + WIDGET_PLUGIN_NAME, + 0, + m_property, + NULL, + initialize, + finalize, + hasProperty, + getProperty, + setProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + callAsConstructor, + NULL, //HasInstance, + NULL, //ConvertToType, +}; + +JSStaticValue JSWidget::m_property[] = { + { WRT_WIDGET_PROPERTY_AUTHOR, JSWidget::getAuthor, + 0, kJSPropertyAttributeReadOnly }, + { WRT_WIDGET_PROPERTY_AUTHOR_EMAIL, JSWidget::getAuthorEmail, + 0, kJSPropertyAttributeReadOnly }, + { WRT_WIDGET_PROPERTY_AUTHOR_HREF, JSWidget::getAuthorHref, + 0, kJSPropertyAttributeReadOnly }, + { WRT_WIDGET_PROPERTY_DESCRIPTION, JSWidget::getDescription, + 0, kJSPropertyAttributeReadOnly }, + { WRT_WIDGET_PROPERTY_ID, JSWidget::getId, + 0, kJSPropertyAttributeReadOnly }, + { WRT_WIDGET_PROPERTY_NAME, JSWidget::getName, + 0, kJSPropertyAttributeReadOnly }, + { WRT_WIDGET_PROPERTY_SHORT_NAME, JSWidget::getShortName, + 0, kJSPropertyAttributeReadOnly }, + { WRT_WIDGET_PROPERTY_VERSION, JSWidget::getVersion, + 0, kJSPropertyAttributeReadOnly }, + { WRT_WIDGET_PROPERTY_HEIGHT, JSWidget::getHeight, + 0, kJSPropertyAttributeReadOnly }, + { WRT_WIDGET_PROPERTY_WIDTH, JSWidget::getWidth, + 0, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + + +JSObjectRef JSWidget::m_widgetObjectRef = NULL; + +JSClassRef JSWidget::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSWidget::getClassInfo() +{ + return &m_classInfo; +} + +JSClassRef JSWidget::m_jsClassRef = JSClassCreate(JSWidget::getClassInfo()); + +void JSWidget::initialize(JSContextRef context, + JSObjectRef object) +{ + JSGlobalContextRef g_context = JSContextGetGlobalContext(context); + + WrtLogD("entered"); + + if (context != g_context) { + context = g_context; + } + + JSWidgetPrivateObject* priv = + static_cast<JSWidgetPrivateObject*>(JSObjectGetPrivate(object)); + + if (!priv) { + WrtLogD("creation private object"); + + Try { + using namespace WrtDeviceApis::Commons; + + Widget::Api::IWidgetPtr widget = + Api::WidgetFactory::createWidget(); + WidgetHandle widgetId = WrtAccessSingleton::Instance().getWidgetId(); + JSObjectRef preferences = + createPreferencesObject(context, + object, + widgetId); + if (!preferences) { + WrtLogE("Failed to create preferences object"); + } + + WidgetPrivateObjectPtr widgetPriv(new WidgetPrivateObject); + widgetPriv->iwidget = widget; + widgetPriv->preferencesObject = preferences; + + priv = new JSWidgetPrivateObject(context, widgetPriv); + JSObjectSetPrivate(object, priv); + } + Catch(Commons::InvalidArgumentException){ + WrtLogE("You should register widget id in ON_WIDGET_START"); + return; + } + Catch(DPL::Exception) { + WrtLogE("Failed to create private object for JSWidget"); + return; + } + } +} + +void JSWidget::finalize(JSObjectRef object) +{ + WrtLogD("entered"); + JSWidgetPrivateObject* priv = + static_cast<JSWidgetPrivateObject*>(JSObjectGetPrivate(object)); + + if (priv) { + JSValueUnprotect(priv->getContext(), + priv->getObject()->preferencesObject); + + delete priv; + WrtLogD("private object is released"); + } else { + WrtLogD("private object wasn't created"); + } + m_widgetObjectRef = NULL; +} + +JSValueRef JSWidget::getAuthor(JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + WrtLogD("entered"); + + Try { + Converter converter(context); + return converter.toJSValueRef(getIWidget(object)->getAuthor()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR +} + +JSValueRef JSWidget::getAuthorEmail(JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + Try { + Converter converter(context); + return converter.toJSValueRef(getIWidget(object)->getAuthorEmail()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR +} + +JSValueRef JSWidget::getAuthorHref(JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + Try { + Converter converter(context); + return converter.toJSValueRef(getIWidget(object)->getAuthorHref()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR +} + +JSValueRef JSWidget::getDescription(JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + Try { + Converter converter(context); + return converter.toJSValueRef(getIWidget(object)->getDescription()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR +} + +JSValueRef JSWidget::getId(JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + Try { + Converter converter(context); + return converter.toJSValueRef(getIWidget(object)->getId()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR +} + +JSValueRef JSWidget::getName(JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + Try { + Converter converter(context); + return converter.toJSValueRef(getIWidget(object)->getName()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR +} + +JSValueRef JSWidget::getShortName(JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + Try { + Converter converter(context); + return converter.toJSValueRef(getIWidget(object)->getShortName()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR +} + +JSValueRef JSWidget::getVersion(JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + Try { + Converter converter(context); + return converter.toJSValueRef(getIWidget(object)->getVersion()); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR +} + +JSValueRef JSWidget::getHeight(JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + Try { + Converter converter(context); + unsigned int height = getIWidget(object)->getHeight(); + if (0 == height) { + height = 1; + } + return converter.toJSValueRef(height); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR +} + +JSValueRef JSWidget::getWidth(JSContextRef context, + JSObjectRef object, + JSStringRef /*propertyName*/, + JSValueRef* exception) +{ + Try { + Converter converter(context); + unsigned int width = getIWidget(object)->getWidth(); + if (0 == width) { + width = 1; + } + return converter.toJSValueRef(width); + } + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_PLATFORM_ERROR +} + +bool JSWidget::hasProperty(JSContextRef context, + JSObjectRef /*object*/, + JSStringRef propertyName) +{ + WrtLogD("enter"); + + Try { + Converter converter(context); + + std::string key = converter.toString(propertyName); + if (key == "preferences") { + return true; + } + } + Catch(Commons::InvalidArgumentException) { + WrtLogD("Pair for given key doesnt exist"); + } + + Catch(Commons::ConversionException) { + WrtLogE("Error on conversion"); + } + + Catch(Commons::NullPointerException) { + WrtLogE("Error on pointer, null value"); + } + + Catch(Commons::PlatformException){ + WrtLogE("PlatformException occured"); + } + return false; +} + +JSValueRef JSWidget::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try { + Converter converter(context); + + std::string key = converter.toString(propertyName); + + if (key == "preferences") { + Converter converter(context); + JSObjectRef pref = getPreferences(object); + if (!pref) { + WrtLogE("Preferences object is NULL"); + return JSValueMakeUndefined(context); + } + return pref; + } + WrtLogE("Property NOT supported: %s", key.c_str()); + return JSValueMakeUndefined(context); + } + + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + CATCH_EXCEPTION_INVALID_ARG +} + +bool JSWidget::setProperty(JSContextRef context, + JSObjectRef /*object*/, + JSStringRef propertyName, + JSValueRef /*jvalue*/, + JSValueRef* exception) +{ + WrtLogD("enter"); + + Try { + Converter converter(context); + + std::string key = converter.toString(propertyName); + if (key == "preferences") { + WrtLogE("Object is read only"); + return true; + } + } + CATCH_EXCEPTION_INVALID_ARG + CATCH_EXCEPTION_CONVERSION + CATCH_EXCEPTION_NULL_PTR + + return false; +} + +JSObjectRef JSWidget::callAsConstructor(JSContextRef context, + JSObjectRef /*constructor*/, + size_t /*argumentCount*/, + const JSValueRef /*arguments*/[], + JSValueRef* /*exception*/) +{ + WrtLogD("widget constructor"); + if(!m_widgetObjectRef) + m_widgetObjectRef = JSObjectMake(context, JSWidget::getClassRef(), NULL); + return m_widgetObjectRef; +} + +#undef CATCH_EXCEPTION_NO_MODIFABLE +#undef CATCH_EXCEPTION_CONVERSION +#undef CATCH_EXCEPTION_NULL_PTR +#undef CATCH_EXCEPTION_PLATFORM_ERROR +#undef CATCH_EXCEPTION_SECURITY +#undef CATCH_EXCEPTION_OUT_OF_RANGE +#undef CATCH_EXCEPTION_INVALID_ARG +} +} diff --git a/src/standards/W3C/Widget/JSWidget.h b/src/standards/W3C/Widget/JSWidget.h new file mode 100644 index 0000000..38a5190 --- /dev/null +++ b/src/standards/W3C/Widget/JSWidget.h @@ -0,0 +1,140 @@ +/* + * 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 JSWidget.h + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _WRT_PLUGIN_JS_WIDGET_H_ +#define _WRT_PLUGIN_JS_WIDGET_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/PrivateObject.h> +#include <wrt_plugin_export.h> + +namespace WrtPlugins { +namespace W3C { +class JSWidget +{ + public: + /** + * This method initializes this in the JS Engine. + */ + static JSClassRef getClassRef(); + + /** + * Gets object's class description. + */ + static const JSClassDefinition* getClassInfo(); + + static JSObjectRef callAsConstructor(JSContextRef context, + JSObjectRef constructor, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + private: + /** + * The callback invoked when an object is first created. + */ + static void initialize(JSContextRef context, + JSObjectRef object); + + /** + * The callback invoked when an object is finalized. + */ + static void finalize(JSObjectRef object); + + /** + * This structure describes a statically declared value property. + */ + static JSStaticValue m_property[]; + + //This structure describes a statically declared value for widget object inorder to prevent leakage. + static JSObjectRef m_widgetObjectRef; + + /** + * This structure contains properties and callbacks that define a type of + * object. + */ + static JSClassDefinition m_classInfo; + + static JSClassRef m_jsClassRef; + + // getters for properties + static JSValueRef getAuthor(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getAuthorEmail(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getAuthorHref(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getDescription(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getId(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getShortName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getVersion(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getHeight(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + static JSValueRef getWidth(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool hasProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName); + + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); +}; +} +} + +#endif /* _WRT_PLUGIN_JS_WIDGET_INTERFACE_H_ */ diff --git a/src/standards/W3C/Widget/plugin_config.cpp b/src/standards/W3C/Widget/plugin_config.cpp new file mode 100644 index 0000000..8588aca --- /dev/null +++ b/src/standards/W3C/Widget/plugin_config.cpp @@ -0,0 +1,40 @@ +/* + * 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 "plugin_config.h" + +namespace WrtPlugins { +namespace W3C { +template <> +WidgetDeclarations::ParamsMap WidgetDeclarations::m_params = + WrtPlugins::W3C::WidgetDeclarations::ParamsMap(); + +template <> +WidgetDeclarations::DeviceCapsMaps WidgetDeclarations::m_deviceCaps = + WrtPlugins::W3C::WidgetDeclarations::DeviceCapsMaps(); + +template <> +WidgetDeclarations::FeaturesMap WidgetDeclarations::m_features = { + { + "http://w3cWidgetInterface.com/w3c-widget-interface", + {} + } +}; + +template <> +WidgetDeclarations::FunctionsMap WidgetDeclarations::m_functions = + WrtPlugins::W3C::WidgetDeclarations::FunctionsMap(); +} // namespace Wac2_0 +} // namespace WrtPlugins diff --git a/src/standards/W3C/Widget/plugin_config.h b/src/standards/W3C/Widget/plugin_config.h new file mode 100644 index 0000000..13de247 --- /dev/null +++ b/src/standards/W3C/Widget/plugin_config.h @@ -0,0 +1,39 @@ +/* + * 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 _WIDGET_PLUGIN_CONFIG_H_ +#define _WIDGET_PLUGIN_CONFIG_H_ + +#include <Security/StaticDeclaration.h> + +namespace WrtPlugins { +namespace W3C { +enum class WidgetParamId +{}; + +enum class WidgetDeviceCapId +{}; + +enum class WidgetFunctionId +{}; + +typedef WrtDeviceApis::CommonsJavaScript::StaticDeclarations < + WidgetParamId, + WidgetDeviceCapId, + WidgetFunctionId> WidgetDeclarations; +} +} + +#endif // _WIDGET_PLUGIN_CONFIG_H_ diff --git a/src/standards/W3C/Widget/plugin_initializer.cpp b/src/standards/W3C/Widget/plugin_initializer.cpp new file mode 100644 index 0000000..b428d12 --- /dev/null +++ b/src/standards/W3C/Widget/plugin_initializer.cpp @@ -0,0 +1,160 @@ +/* + * 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 plugin_initializer.cpp + * @author Grzegorz Krawczyk (g.krawczyk@samsung.com) + * @version 0.1 + * @brief + */ + +#include <dpl/log/wrt_log.h> + +#include <Commons/plugin_initializer_def.h> +#include <Commons/WrtAccess/WrtAccess.h> +#include <ExportedApi.h> +#include <ObjectFactory.h> +#include <Plugin.h> +#include <PluginRegistration.h> + +#include "JSWidget.h" +#include "JSPreferences.h" + +#include "plugin_config.h" + +#define OBJECT_WIDGET "widget" +#define INTERFACE_WIDGET_NAME "Widget" + +using namespace WrtPlugins::W3C; +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; +using namespace WrtPluginsApi; + +namespace Options { +class_definition_options_t WidgetOptions = { + JS_CLASS, + CREATE_INSTANCE, + NONE_NOTICE, + IGNORED, + NULL, + NULL, + NULL +}; + +class_definition_options_t WidgetInterfaceOptions = { + JS_INTERFACE, + CREATE_INSTANCE, + NONE_NOTICE, + IGNORED, //ignored + NULL, + NULL, + NULL +}; +} + +//TODO: remove this after switch to wrt-plugin-installer +void on_widget_init_callback(feature_mapping_interface_t *mapping) +{ + WrtLogD("[W3C\\widget] on_widget_init_callback"); + + WrtPlugins::W3C::WidgetDeclarations::getMappingInterface(mapping); +} +//... + +void on_widget_start_callback(WidgetHandle widgetId) +{ + WrtLogD("[W3C\\widget] on_widget_start_callback (%d)", widgetId); + + Try + { + WrtAccessSingleton::Instance().initialize(widgetId); + } + Catch(Commons::Exception) + { + WrtLogE("Wrt wrapper registration failed"); + return; + } +} + +void on_widget_stop_callback(WidgetHandle widgetId) +{ + WrtLogD("[W3C\\widget] on_widget_stop_callback (%d)", widgetId); + Try + { + WrtAccessSingleton::Instance().deinitialize(widgetId); + } + Catch(Commons::Exception) + { + WrtLogE("Wrt wrapper registration failed"); + return; + } +} + +void Register(PluginRegistration& r) +{ + Plugin* plugin = new Plugin(); + + auto widgetObject = ObjectFactory::createObjectWithInterface( + OBJECT_WIDGET, + (js_class_template_getter) WrtPlugins::W3C::JSWidget::getClassRef, + INTERFACE_WIDGET_NAME, + reinterpret_cast<js_class_constructor_cb_t>(WrtPlugins::W3C::JSWidget::callAsConstructor)); + + plugin->AddObject(widgetObject); + + r.Connect<OnWidgetStart>(on_widget_start_callback); + r.Connect<OnWidgetStop>(on_widget_stop_callback); + + r.AddPlugin(*plugin); +} + +void Unregister(PluginRegistration& r, Plugin* plugin) +{ + r.DisconnectAll(); + delete plugin; +} + +void GetProvidedFeatures(feature_mapping_interface_t *mapping) +{ + WrtPlugins::W3C::WidgetDeclarations::getMappingInterface(mapping); +} + +ExportedApi dll_api={Register, Unregister, GetProvidedFeatures}; + +//TODO: remove this after switch to wrt-plugin-installer +PLUGIN_ON_WIDGET_START(on_widget_start_callback) +PLUGIN_ON_WIDGET_STOP(on_widget_stop_callback) +PLUGIN_ON_WIDGET_INIT(on_widget_init_callback) + +PLUGIN_CLASS_MAP_BEGIN +PLUGIN_CLASS_MAP_ADD_INTERFACE( + WRT_JS_EXTENSION_OBJECT_GLOBAL, + INTERFACE_WIDGET_NAME, + (js_class_template_getter) WrtPlugins::W3C::JSWidget::getClassRef, + reinterpret_cast<js_class_constructor_cb_t>(WrtPlugins::W3C::JSWidget:: + callAsConstructor), + &Options::WidgetInterfaceOptions) +PLUGIN_CLASS_MAP_ADD_INTERFACE_PRODUCT( + WRT_JS_EXTENSION_OBJECT_GLOBAL, + OBJECT_WIDGET, + INTERFACE_WIDGET_NAME, + &Options::WidgetOptions) + +PLUGIN_CLASS_MAP_END +//... + +#undef OBJECT_WIDGET +#undef INTERFACE_WIDGET_NAME diff --git a/src/wrt-popup/CMakeLists.txt b/src/wrt-popup/CMakeLists.txt new file mode 100755 index 0000000..13a79cc --- /dev/null +++ b/src/wrt-popup/CMakeLists.txt @@ -0,0 +1,2 @@ +ADD_SUBDIRECTORY(ace) +ADD_SUBDIRECTORY(wrt) diff --git a/src/wrt-popup/ace/CMakeLists.txt b/src/wrt-popup/ace/CMakeLists.txt new file mode 100755 index 0000000..2ecd23d --- /dev/null +++ b/src/wrt-popup/ace/CMakeLists.txt @@ -0,0 +1,2 @@ +ADD_SUBDIRECTORY(popup-bin) +ADD_SUBDIRECTORY(popup-runner) diff --git a/src/wrt-popup/ace/popup-bin/CMakeLists.txt b/src/wrt-popup/ace/popup-bin/CMakeLists.txt new file mode 100644 index 0000000..30a635c --- /dev/null +++ b/src/wrt-popup/ace/popup-bin/CMakeLists.txt @@ -0,0 +1,67 @@ +# 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 CMakeLists.txt +# @author Janusz Kozerski (j.kozerski@samsung.com) +# +# @version 1.0 +# + +PKG_CHECK_MODULES(WRT_POPUP_DEP + dpl-efl + elementary + security-client + security-popup-validation + REQUIRED) + +SET(WRT_POPUP_SRC_DIR ${PROJECT_SOURCE_DIR}/src/wrt-popup/ace/popup-bin) + +SET(WRT_POPUP_SOURCES + ${WRT_POPUP_SRC_DIR}/Popup.cpp +) + +ADD_DEFINITIONS(${WRT_POPUP_DEP_CFLAGS}) + +INCLUDE_DIRECTORIES( + ${WRT_POPUP_SRC_DIR} + ${WRT_POPUP_DEP_INCLUDE_DIRS} +) + +ADD_EXECUTABLE(${TARGET_POPUP_ACE} + ${WRT_POPUP_SOURCES} +) + +SET_TARGET_PROPERTIES(${TARGET_POPUP_ACE} PROPERTIES + COMPILE_DEFINITIONS LOG_TAG="${LOG_TAG}") + +SET_TARGET_PROPERTIES(${TARGET_POPUP_ACE} PROPERTIES + COMPILE_FLAGS -fPIC +) + +SET_TARGET_PROPERTIES(${TARGET_POPUP_ACE} PROPERTIES + #LINK_FLAGS "-Wl,--as-needed -Wl" + SOVERSION ${PROJECT_API_VERSION} + VERSION ${PROJECT_VERSION} +) + +TARGET_LINK_LIBRARIES(${TARGET_POPUP_ACE} + ${WRT_POPUP_DEP_LIBRARIES} + ${TARGET_POPUP_ACE_RUNNER_LIB} + ${WRT_POPUP_DEP_LDFLAGS} +) + +INSTALL(TARGETS ${TARGET_POPUP_ACE} + DESTINATION bin +) diff --git a/src/wrt-popup/ace/popup-bin/Popup.cpp b/src/wrt-popup/ace/popup-bin/Popup.cpp new file mode 100644 index 0000000..130cf3c --- /dev/null +++ b/src/wrt-popup/ace/popup-bin/Popup.cpp @@ -0,0 +1,456 @@ +/* + * 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 Popup.c + * @author Janusz Kozerski (j.kozerski@samsung.com) + * @version 1.0 + */ + +/* + * This is just a example pop-up that shows how to use a new C-API in + * wrt-security. + * This pop-up should be re-implemented by members of NGWAP. + */ + +#include <stdio.h> +#include <unistd.h> +#include <string.h> +#include <errno.h> +#include <vector> +#include <ctime> + +#include <Elementary.h> + +#include <dpl/log/wrt_log.h> +#include <dpl/exception.h> +#include <dpl/serialization.h> +#include <ace_api_common.h> +#include <ace_api_popup_validation.h> + +#include "popup-runner.h" +#include "Popup.h" + +namespace { // anonymous +static void set_validity_from_checkbox(struct ace_popup_data *pdp) +{ + if (NULL == pdp) { + WrtLogE("pdp is NULL; return"); + return; + } + + if (pdp->always) { + WrtLogD("Remember ALWAYS"); + pdp->remember_choice = ACE_ALWAYS; + return; + } + if (pdp->per_session) { + WrtLogD("Remember PER_SESSION"); + pdp->remember_choice = ACE_PER_SESSION; + return; + } + WrtLogD("Remember ONCE"); + pdp->remember_choice = ACE_ONCE; + return; +} + +static void on_done(void) +{ + // Quit the efl-mainloop + WrtLogD("elm_exit()"); + elm_exit(); +} + +static void grant_answer(void *data, + Evas_Object * /* obj */, + void * /* event_info */) +{ + WrtLogD("grant_answer"); + if (NULL == data) { + WrtLogE("data is NULL; return"); + return; + } + struct ace_popup_data *pdp = static_cast <struct ace_popup_data *>(data); + + set_validity_from_checkbox(pdp); + + ace_popup_validation_initialize(); + pdp->validation_return = ace_validate_answer( + ACE_TRUE, + pdp->remember_choice, + pdp->resource_name, + pdp->session_id, + &(pdp->param_list), + pdp->handle, + &(pdp->validation_result)); + ace_popup_validation_shutdown(); + + on_done(); +} + +static void deny_answer(void *data, + Evas_Object * /* obj */, + void * /* event_info */) +{ + WrtLogD("deny_answer"); + if (NULL == data) { + WrtLogE("data is NULL; return"); + return; + } + struct ace_popup_data *pdp = static_cast <struct ace_popup_data *>(data); + + set_validity_from_checkbox(pdp); + + ace_popup_validation_initialize(); + pdp->validation_return = ace_validate_answer( + ACE_FALSE, + pdp->remember_choice, + pdp->resource_name, + pdp->session_id, + &(pdp->param_list), + pdp->handle, + &(pdp->validation_result)); + ace_popup_validation_shutdown(); + + on_done(); +} + +static int _ace_params_deserializer(ace_param_list_t* ace_param_list, + Wrt::Popup::BinaryStream *stream) +{ + WrtLogD("_ace_params_deserializer"); + + if (NULL == ace_param_list || NULL == stream) { + WrtLogE("ace_param_list or stream is NULL; return -1"); + return -1; + } + + // deserialize ace_param_list->count; + size_t count = 0; + DPL::Deserialization::Deserialize(*stream, count); + ace_param_list->count = count; + WrtLogD("count : %d", count); + + std::string name; + std::string value; + if (count == 0) { + ace_param_list->items = NULL; + return 0; + } + ace_param_list->items = + static_cast <ace_param_t *>(malloc(count * sizeof(ace_param_t))); + memset(ace_param_list->items, 0, count * sizeof(ace_param_t)); + + for (size_t i = 0; i < count; ++i) { + DPL::Deserialization::Deserialize(*stream, name); + ace_param_list->items[i].name = + strdup(const_cast <char *>(name.c_str())); + + DPL::Deserialization::Deserialize(*stream, value); + ace_param_list->items[i].value = + strdup(const_cast <char *>(value.c_str())); + } + return 0; +} + +static void _ace_params_finalize(ace_param_list_t* ace_param_list) +{ + if (!ace_param_list || !ace_param_list->items) { + WrtLogD("List is null, nothing to do"); + return; + } + for (size_t i = 0; i < ace_param_list->count; ++i) { + free(ace_param_list->items[i].name); + free(ace_param_list->items[i].value); + } + free(ace_param_list->items); + ace_param_list->items = NULL; + ace_param_list->count = 0; +} + +static void show_popup(struct ace_popup_data *pdp) +{ + WrtLogD("show_popup()"); + + if (NULL == pdp) { + WrtLogE("pdp is NULL; return"); + return; + } + + const char *resource_type = static_cast <char *>(pdp->resource_name); + + Evas_Object *win = NULL; + Evas_Object *box = NULL; + Evas_Object *label = NULL; + Evas_Object *grant_button = NULL; + Evas_Object *deny_button = NULL; + pdp->per_session = EINA_FALSE; + pdp->always = EINA_FALSE; + + win = elm_win_add(NULL, "The wrt-client popup", ELM_WIN_NOTIFICATION); + elm_win_autodel_set(win, EINA_TRUE); + elm_policy_set(ELM_POLICY_QUIT, ELM_POLICY_QUIT_LAST_WINDOW_CLOSED); + evas_object_show(win); + elm_win_indicator_opacity_set(win, ELM_WIN_INDICATOR_TRANSLUCENT); + + pdp->popup = elm_popup_add(win); + + box = elm_box_add(pdp->popup); + evas_object_size_hint_weight_set(box, EVAS_HINT_EXPAND, 0); + evas_object_size_hint_align_set(box, EVAS_HINT_FILL, 0.0); + + label = elm_label_add(pdp->popup); + elm_object_style_set(label, "popup_description/default"); + elm_label_line_wrap_set(label, ELM_WRAP_MIXED); + char *buff = NULL; + if (-1 == + asprintf(&buff, "Application need an access to %s.<br>Grant or deny?", + resource_type)) + { + WrtLogE("asprintf failed - returned -1"); + evas_object_del(label); + evas_object_del(pdp->popup); + evas_object_del(win); + return; + } + elm_object_text_set(label, buff); + free(buff); + evas_object_size_hint_weight_set(label, EVAS_HINT_EXPAND, 0.0); + evas_object_size_hint_align_set(label, EVAS_HINT_FILL, EVAS_HINT_FILL); + evas_object_show(label); + elm_box_pack_end(box, label); + + WrtLogD("popup_type == %d", pdp->popup_type); + if (pdp->popup_type == ACE_SESSION || pdp->popup_type == ACE_BLANKET) { + WrtLogD("popup_type == ACE_SESSION || ACE_BLANKET"); + Evas_Object *cb_session = elm_check_add(pdp->popup); + elm_object_text_set(cb_session, "Remember choice for this session"); + elm_check_state_pointer_set(cb_session, &(pdp->per_session)); + evas_object_smart_callback_add(cb_session, "changed", NULL, NULL); + evas_object_size_hint_align_set(cb_session, + EVAS_HINT_FILL, + EVAS_HINT_FILL); + evas_object_size_hint_weight_set(cb_session, + EVAS_HINT_EXPAND, + EVAS_HINT_EXPAND); + evas_object_show(cb_session); + elm_box_pack_end(box, cb_session); + + if (pdp->popup_type == ACE_BLANKET) { + WrtLogD("popup_type == ACE_BLANKET"); + Evas_Object *cb_always = elm_check_add(pdp->popup); + elm_object_text_set(cb_always, "Remember choice forever"); + elm_check_state_pointer_set(cb_always, &(pdp->always)); + evas_object_smart_callback_add(cb_always, "changed", NULL, NULL); + evas_object_size_hint_align_set(cb_always, + EVAS_HINT_FILL, + EVAS_HINT_FILL); + evas_object_size_hint_weight_set(cb_always, + EVAS_HINT_EXPAND, + EVAS_HINT_EXPAND); + evas_object_show(cb_always); + elm_box_pack_end(box, cb_always); + } + } + + elm_object_part_content_set(pdp->popup, "default", box); + + grant_button = elm_button_add(pdp->popup); + elm_object_style_set(grant_button, "popup"); + elm_object_text_set(grant_button, "Grant"); + elm_object_part_content_set(pdp->popup, "button1", grant_button); + evas_object_smart_callback_add(grant_button, "clicked", grant_answer, pdp); + + deny_button = elm_button_add(pdp->popup); + elm_object_style_set(deny_button, "popup"); + elm_object_text_set(deny_button, "Deny"); + elm_object_part_content_set(pdp->popup, "button2", deny_button); + evas_object_smart_callback_add(deny_button, "clicked", deny_answer, pdp); + + evas_object_show(pdp->popup); + + // Showing the popup window + evas_object_show(win); + + // Run the efl mainloop + elm_run(); +} +} // anonymous + +EAPI_MAIN int +elm_main(int argc, char ** argv) +{ + UNHANDLED_EXCEPTION_HANDLER_BEGIN + { + // int pipe_in and int pipe_out should be passed to Popup via args. + + // These parameters should be passed to Popup via pipe: + // ace_popup_t popup_type + // const ace_resource_t resource_name + // const ace_session_id_t session_id + // ace_widget_handle_t handle + // const ace_param_list_t param_list + + WrtLogD("######################## popup binary ############################"); + + if (argc < 3) { + WrtLogE("To few args passed in exec to popup-bin - should be at least 3:"); + WrtLogE("(binary-name, pipe_in, pipe_out)"); + WrtLogE("return ACE_INTERNAL_ERROR"); + return ACE_INTERNAL_ERROR; + } + WrtLogD("Passed args: %s, %s, %s", argv[0], argv[1], argv[2]); + + int pipe_in; + int pipe_out; + std::stringstream parsing_stream; + + // Parsing args (pipe_in, pipe_out) + parsing_stream.str(argv[1]); + parsing_stream >> pipe_in; + if ( parsing_stream.fail() ) { + WrtLogE("Error while parsing pipe_in; return ACE_INTERNAL_ERROR"); + return ACE_INTERNAL_ERROR; + } + parsing_stream.clear(); + parsing_stream.str(argv[2]); + parsing_stream >> pipe_out; + if ( parsing_stream.fail() ) { + WrtLogE("Error while parsing pipe_out; return ACE_INTERNAL_ERROR"); + return ACE_INTERNAL_ERROR; + } + parsing_stream.clear(); + WrtLogD("Parsed pipes: IN: %d, OUT: %d", pipe_in, pipe_out); + + int buff_size = 1024; + char line[buff_size]; + + struct ace_popup_data pd; + struct ace_popup_data *pdp = &pd; + + pdp->popup = NULL; + + ssize_t count = 0; + time_t time_start; + time(&time_start); // now + double timeout = 10.0; + // try to read parameters from pipe_in + // timeout is set for 10 seconds + do { + count = TEMP_FAILURE_RETRY(read(pipe_in, line, buff_size)); + if (timeout < difftime(time(NULL), time_start) ) { + WrtLogE("Timeout reached! Exit popup - ACE_INTERNAL_ERROR"); + close(pipe_in); + close(pipe_out); + return ACE_INTERNAL_ERROR; + } + } while (0 == count); + if (count < 0) { + close(pipe_in); + close(pipe_out); + WrtLogE("read returned a negative value (%d)", count); + WrtLogE("errno: %s", strerror(errno)); + WrtLogE("Exit popup - ACE_INTERNAL_ERROR"); + return ACE_INTERNAL_ERROR; + } + WrtLogD("Read bytes : %d (in %f seconds)", + count, difftime(time_start, time(NULL))); + close(pipe_in); // cleanup + + Wrt::Popup::BinaryStream stream; + stream.Write(count, static_cast <void *>(line)); + int popup_type = ACE_ONESHOT; + std::string resource_name_str; + std::string session_id_str; + int handle = 0; + + WrtLogD("------- Deserialization -------"); + // Deserialization order: + // popup_type, resource_name, session_id, handle, param_list + + DPL::Deserialization::Deserialize(stream, popup_type); + WrtLogD("popup_type_int : %d", popup_type); + pdp->popup_type = static_cast <ace_popup_t>(popup_type); + + DPL::Deserialization::Deserialize(stream, resource_name_str); + WrtLogD("resource_name_char : %s", resource_name_str.c_str()); + pdp->resource_name = + strdup(const_cast <ace_resource_t>(resource_name_str.c_str())); + + DPL::Deserialization::Deserialize(stream, session_id_str); + WrtLogD("session_id_char : %s", session_id_str.c_str()); + pdp->session_id = + strdup(const_cast <ace_session_id_t>(session_id_str.c_str())); + + DPL::Deserialization::Deserialize(stream, handle); + WrtLogD("handle_int : %d", handle); + pdp->handle = static_cast <ace_widget_handle_t>(handle); + + if (_ace_params_deserializer(&(pdp->param_list), &stream)) { + return ACE_INTERNAL_ERROR; + } + + pdp->per_session = EINA_FALSE; + pdp->always = EINA_FALSE; + pdp->validation_return = ACE_ACE_UNKNOWN_ERROR; + + show_popup(pdp); // Showing popup + + // sending validation_result to popup-runner + Wrt::Popup::BinaryStream stream_out; + + WrtLogD("pdp->validation_result : %d", pdp->validation_result); + int validation_result_int = (int) pdp->validation_result; + WrtLogD("validation_result_int : %d", validation_result_int); + DPL::Serialization::Serialize(stream_out, validation_result_int); + if (-1 == + TEMP_FAILURE_RETRY(write(pipe_out, stream_out.char_pointer(), + stream_out.size()))) + { + WrtLogE("Write to pipe failed!"); + close(pipe_out); + return ACE_INTERNAL_ERROR; + } + close(pipe_out); + + if (pdp->validation_return == ACE_OK) { + WrtLogD("ACE_OK"); + } else if (pdp->validation_return == ACE_INVALID_ARGUMENTS) { + WrtLogE("ACE_INVALID_ARGUMENTS"); + } else if (pdp->validation_return == ACE_INTERNAL_ERROR) { + WrtLogE("ACE_INTERNAL_ERROR"); + } else if (pdp->validation_return == ACE_ACE_UNKNOWN_ERROR) { + WrtLogE("ACE_ACE_UNKNOWN_ERROR"); + } else { + WrtLogE("Really unknown error!!!"); + } + + WrtLogD("###################### /popup binary ########################"); + + // Shutdown elementary + //WrtLogD("elm_shutdown()"); + //elm_shutdown(); + // This is commented because, it causes that popup exits with 139 code + // (Segmentatation violation). + // Not calling elm_shutdown() should not have any negative consequences + // because this binary ends + // in next line, and system should clear the memory. + + _ace_params_finalize(&(pdp->param_list)); + return pdp->validation_return; + } + UNHANDLED_EXCEPTION_HANDLER_END +} +ELM_MAIN() diff --git a/src/wrt-popup/ace/popup-bin/Popup.h b/src/wrt-popup/ace/popup-bin/Popup.h new file mode 100644 index 0000000..388c921 --- /dev/null +++ b/src/wrt-popup/ace/popup-bin/Popup.h @@ -0,0 +1,39 @@ +/* + * 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 Popup.h + * @author Janusz Kozerski (j.kozerski@samsung.com) + * @version 1.0 + */ + +#include <Elementary.h> +#include <ace_api_common.h> + +struct ace_popup_data { + ace_popup_t popup_type; + ace_resource_t resource_name; + ace_session_id_t session_id; + ace_param_list_t param_list; + ace_widget_handle_t handle; + ace_bool_t validation_result; + ace_return_t validation_return; + + Evas_Object *popup; + Eina_Bool per_session; + Eina_Bool always; + + ace_validity_t remember_choice; +}; diff --git a/src/wrt-popup/ace/popup-runner/CMakeLists.txt b/src/wrt-popup/ace/popup-runner/CMakeLists.txt new file mode 100644 index 0000000..519303c --- /dev/null +++ b/src/wrt-popup/ace/popup-runner/CMakeLists.txt @@ -0,0 +1,68 @@ +# 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 CMakeLists.txt +# @author Janusz Kozerski (j.kozerski@samsung.com) +# +# @version 1.0 +# + +PKG_CHECK_MODULES(WRT_POPUP_RUNNER_LIB_DEP + dpl-efl + elementary + security-client + REQUIRED) + +SET(WRT_POPUP_RUNNER_LIB_SRC_DIR ${PROJECT_SOURCE_DIR}/src/wrt-popup/ace/popup-runner) + +SET(WRT_POPUP_RUNNER_LIB_SOURCES + ${WRT_POPUP_RUNNER_LIB_SRC_DIR}/popup-runner.cpp +) + +ADD_DEFINITIONS(${WRT_POPUP_RUNNER_LIB_DEP_CFLAGS}) + +INCLUDE_DIRECTORIES( + ${WRT_POPUP_RUNNER_LIB_SRC_DIR} + ${WRT_POPUP_RUNNER_LIB_DEP_INCLUDE_DIRS} +) + +ADD_LIBRARY(${TARGET_POPUP_ACE_RUNNER_LIB} SHARED + ${WRT_POPUP_RUNNER_LIB_SOURCES} +) + +SET_TARGET_PROPERTIES(${TARGET_POPUP_ACE_RUNNER_LIB} PROPERTIES + COMPILE_DEFINITIONS LOG_TAG="${LOG_TAG}") + +SET_TARGET_PROPERTIES(${TARGET_POPUP_ACE_RUNNER_LIB} PROPERTIES + COMPILE_FLAGS -fPIC +) + +SET_TARGET_PROPERTIES(${TARGET_POPUP_ACE_RUNNER_LIB} PROPERTIES + SOVERSION ${CMAKE_PROJECT_API_VERSION} + VERSION ${CMAKE_PROJECT_VERSION} +) + +TARGET_LINK_LIBRARIES(${TARGET_POPUP_ACE_RUNNER_LIB} + ${WRT_POPUP_RUNNER_LIB_DEP_LIBRARIES} + ${WRT_POPUP_RUNNER_LIB_DEP_LDFLAGS} +) + +INSTALL(TARGETS ${TARGET_POPUP_ACE_RUNNER_LIB} + DESTINATION lib +) + +INSTALL(FILES ${WRT_POPUP_RUNNER_LIB_SRC_DIR}/popup-runner.h + DESTINATION ${DESTINATION_HEADERS_WRT_POPUP_RUNNER} +) diff --git a/src/wrt-popup/ace/popup-runner/popup-runner.cpp b/src/wrt-popup/ace/popup-runner/popup-runner.cpp new file mode 100644 index 0000000..4877876 --- /dev/null +++ b/src/wrt-popup/ace/popup-runner/popup-runner.cpp @@ -0,0 +1,290 @@ +/* + * 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 popup-runner.cpp + * @author Janusz Kozerski (j.kozerski@samsung.com) + * @version 1.0 + */ + +/* + * This is just a example pop-up that shows how to use a new C-API in + * wrt-security. + * This pop-up should be re-implemented by members of NGWAP. + */ + +#include <stdio.h> +#include <unistd.h> +#include <string.h> +#include <iostream> +#include <sstream> +#include <sys/types.h> +#include <sys/wait.h> + +#include <dpl/log/wrt_log.h> + +#include "popup-runner.h" + +namespace { // anonymous +const char *POPUP_EXEC = "/usr/bin/wrt-popup-ace-runtime"; + +void _ace_params_serializer (const ace_param_list_t* ace_param_list, + Wrt::Popup::BinaryStream *stream) +{ + WrtLogD("_ace_params_serializer"); + + if (NULL == ace_param_list || NULL == stream) { + WrtLogE("*ace_param_list or *stream is NULL; return"); + return; + } + WrtLogD("Param count : %d", ace_param_list->count); + + // serialize ace_param_list->count; + size_t count = static_cast <size_t>(ace_param_list->count); + DPL::Serialization::Serialize(*stream, count); + + for (size_t i = 0; i < count; ++i) { + std::string name(ace_param_list->items[i].name); + DPL::Serialization::Serialize(*stream, name); + + std::string value(ace_param_list->items[i].value); + DPL::Serialization::Serialize(*stream, value); + } +} +} // anonymous namespace + +namespace Wrt { +namespace Popup { +// BinaryStream class implementation +void BinaryStream::Read(size_t num, void * bytes) +{ + size_t max_size = m_data.size(); + for (size_t i = 0; i < num; ++i) { + if (i + m_readPosition >= max_size) { + return; + } + static_cast <unsigned char*>(bytes)[i] = m_data[i + m_readPosition]; + } + m_readPosition += num; +} + +void BinaryStream::Write(size_t num, const void * bytes) +{ + for (size_t i = 0; i < num; ++i) { + m_data.push_back(static_cast <const unsigned char*>(bytes)[i]); + } +} + +BinaryStream::BinaryStream() +{ + m_readPosition = 0; +} + +BinaryStream::~BinaryStream() {} + +const unsigned char* BinaryStream::char_pointer() const +{ + return &m_data[0]; +} + +size_t BinaryStream::size() const +{ + return m_data.size(); +} +// BinaryStream + +ace_return_t run_popup( + ace_popup_t popup_type, + const ace_resource_t resource_name, + const ace_session_id_t session_id, + const ace_param_list_t* ace_param_list, + ace_widget_handle_t handle, + ace_bool_t* validation_result) +{ + if (NULL == resource_name || + NULL == session_id || + NULL == ace_param_list || + NULL == validation_result) + { + WrtLogE("run_popup : ACE_INVALID_ARGUMENTS"); + return ACE_INVALID_ARGUMENTS; + } + WrtLogD("popup_type : %d", popup_type); + WrtLogD("resource_name : %s", resource_name); + WrtLogD("session_id : %s", session_id); + WrtLogD("widget handle : %d", handle); + + int popup_type_int = static_cast <int>(popup_type); + char *resource_name_char = static_cast <char *>(resource_name); + char *session_id_char = static_cast <char *>(session_id); + int handle_int = static_cast <int>(handle); + + // serialization + Wrt::Popup::BinaryStream stream; + DPL::Serialization::Serialize(stream, popup_type_int); + + std::string resource_name_str(resource_name_char); + DPL::Serialization::Serialize(stream, resource_name_str); + + std::string session_id_str(session_id_char); + DPL::Serialization::Serialize(stream, session_id_str); + + DPL::Serialization::Serialize(stream, handle_int); + + _ace_params_serializer(ace_param_list, &stream); + + int fd_send_to_child[2]; + int fd_send_to_parent[2]; + pid_t childpid; + + if (0 != pipe(fd_send_to_child)) { + WrtLogE("Cannot create pipes!"); + return ACE_INTERNAL_ERROR; + } + if (0 != pipe(fd_send_to_parent)) { + WrtLogE("Cannot create pipes!"); + return ACE_INTERNAL_ERROR; + } + + if ((childpid = fork()) == -1) { + WrtLogE("Fork() ERROR"); + return ACE_ACE_UNKNOWN_ERROR; + } + + if (childpid == 0) { // Child process + WrtLogD("Child"); + + // read data from parent + close(fd_send_to_child[1]); + + // send data to parent + close(fd_send_to_parent[0]); + + std::stringstream pipe_in_buff; + std::stringstream pipe_out_buff; + pipe_in_buff << fd_send_to_parent[1]; + pipe_out_buff << fd_send_to_child[0]; + std::string pipe_in = pipe_in_buff.str(); + std::string pipe_out = pipe_out_buff.str(); + + WrtLogD("Passed file descriptors: %d, %d", + fd_send_to_child[0], + fd_send_to_parent[1]); + + if (execl(POPUP_EXEC, POPUP_EXEC, pipe_out.c_str(), pipe_in.c_str(), + NULL) < 0) + { + WrtLogE("execlp FAILED"); + } + + WrtLogE("This should not happened!!!"); + } // end of child process - from now you can use DEBUG LOGS + else { // Parent process + WrtLogD("Parent"); + + int buff_size = 1024; + char result[buff_size]; + // send data to child + close(fd_send_to_child[0]); + + //writing to child + WrtLogD("Sending message to popup-bin process"); + if (-1 == + TEMP_FAILURE_RETRY(write(fd_send_to_child[1], stream.char_pointer(), + stream.size()))) + { + WrtLogE("Write to pipe failed!"); + return ACE_INTERNAL_ERROR; + } + close(fd_send_to_child[1]); // cleanup + WrtLogD("Message has been sent"); + + // read data from child + close(fd_send_to_parent[1]); + + int status; + wait(&status); + WrtLogD("STATUS EXIT ON POPUP (CHILD): %d", status); + switch (status) { + case ACE_OK: + WrtLogD("ACE_OK"); + break; + + case ACE_INVALID_ARGUMENTS: + WrtLogD("ACE_INVALID_ARGUMENTS"); + close(fd_send_to_parent[0]); + return static_cast <ace_return_t>(status); + break; + + case ACE_INTERNAL_ERROR: + WrtLogD("ACE_INTERNAL_ERROR"); + close(fd_send_to_parent[0]); + return static_cast <ace_return_t>(status); + break; + + case ACE_ACE_UNKNOWN_ERROR: + WrtLogD("ACE_ACE_UNKNOWN_ERROR"); + close(fd_send_to_parent[0]); + return static_cast <ace_return_t>(status); + break; + + default: + WrtLogD("UNKNOWN_ERROR"); + close(fd_send_to_parent[0]); + status = (int) ACE_ACE_UNKNOWN_ERROR; + return static_cast <ace_return_t>(status); + break; + } + + int count; + count = TEMP_FAILURE_RETRY(read(fd_send_to_parent[0], result, buff_size)); + close(fd_send_to_parent[0]); // cleanup + + + if (0 < count) { + BinaryStream stream_in; + int validation_result_int; + stream_in.Write(count, result); + WrtLogD("RESULT FROM POPUP (CHILD) : [ %d ]", count); + DPL::Deserialization::Deserialize(stream_in, validation_result_int); + *validation_result = static_cast <ace_bool_t>(validation_result_int); + + WrtLogD("validation_result :"); + switch (*validation_result) { + case ACE_FALSE: + WrtLogD("ACE_FALSE"); + break; + case ACE_TRUE: + WrtLogD("ACE_TRUE"); + break; + default: + WrtLogD("UNKNOWN - DEFAULT"); + break; + } + } else { + WrtLogD("count = %d", count); + WrtLogD("UNKNOWN_ERROR"); + return ACE_ACE_UNKNOWN_ERROR; + } + + WrtLogD("popup-runner: EXIT"); + return (ace_return_t) status; + } + + WrtLogE("This should not happend!!!"); + return ACE_ACE_UNKNOWN_ERROR; +} +} // Popup +} // Wrt diff --git a/src/wrt-popup/ace/popup-runner/popup-runner.h b/src/wrt-popup/ace/popup-runner/popup-runner.h new file mode 100644 index 0000000..d136fb1 --- /dev/null +++ b/src/wrt-popup/ace/popup-runner/popup-runner.h @@ -0,0 +1,55 @@ +/* + * 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 popup-runner.h + * @author Janusz Kozerski (j.kozerski@samsung.com) + * @version 1.0 + */ + +#include <ace_api_client.h> +#include <vector> + +#include <dpl/serialization.h> + +namespace Wrt { +namespace Popup { +class BinaryStream : public DPL::IStream +{ + public: + void Read (size_t num, void * bytes); + void Write(size_t num, const void * bytes); + + BinaryStream(); + ~BinaryStream(); + + const unsigned char* char_pointer() const; + size_t size() const; + + private: + std::vector<unsigned char> m_data; + size_t m_readPosition; +}; + +ace_return_t run_popup( + ace_popup_t popup_type, + const ace_resource_t resource_name, + const ace_session_id_t session_id, + const ace_param_list_t* ace_param_list, + ace_widget_handle_t handle, + ace_bool_t* validation_result + ); +} // Popup +} // Wrt diff --git a/src/wrt-popup/wrt/CMakeLists.txt b/src/wrt-popup/wrt/CMakeLists.txt new file mode 100755 index 0000000..0d89bfd --- /dev/null +++ b/src/wrt-popup/wrt/CMakeLists.txt @@ -0,0 +1,9 @@ + +SET(WRT_POPUP_COMMON_DIR ${PROJECT_SOURCE_DIR}/src/wrt-popup/wrt) + +SET(WRT_POPUP_COMMON_SRCS + ${WRT_POPUP_COMMON_DIR}/PopupSerializer.cpp +) + +ADD_SUBDIRECTORY(popup-bin) +ADD_SUBDIRECTORY(popup-runner) diff --git a/src/wrt-popup/wrt/PopupEnum.h b/src/wrt-popup/wrt/PopupEnum.h new file mode 100644 index 0000000..3200ef4 --- /dev/null +++ b/src/wrt-popup/wrt/PopupEnum.h @@ -0,0 +1,29 @@ +/* + * 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 WRT_POPUP_ENUM_H +#define WRT_POPUP_ENUM_H + +namespace Wrt { +enum PopupType { + INFO_PROMPT = 1, + YES_NO_PROMPT, + YES_NO_CHECK_PROMPT +}; +} + +#endif + diff --git a/src/wrt-popup/wrt/PopupSerializer.cpp b/src/wrt-popup/wrt/PopupSerializer.cpp new file mode 100644 index 0000000..e9dd99f --- /dev/null +++ b/src/wrt-popup/wrt/PopupSerializer.cpp @@ -0,0 +1,57 @@ +/* + * 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 "PopupSerializer.h" + +#include <memory> + +namespace Wrt { +namespace PopupSerializer { +void appendArg(int arg, DPL::BinaryQueue &buffer) +{ + size_t argSize = sizeof(arg); + buffer.AppendCopy(&argSize, sizeof(argSize)); + buffer.AppendCopy(&arg, sizeof(arg)); +} + +void appendArg(const std::string &arg, DPL::BinaryQueue &buffer) +{ + size_t argSize = arg.size(); + buffer.AppendCopy(&argSize, sizeof(argSize)); + buffer.AppendCopy(arg.c_str(), argSize); +} + +int getIntArg(DPL::BinaryQueue &buffer) +{ + int result; + size_t argSize; + buffer.FlattenConsume(&argSize, sizeof(argSize)); + buffer.FlattenConsume(&result, argSize); + //TODO: what if argSize != sizeof(int) + //This should not be problem if this is run on the same machine. + return result; +} + +std::string getStringArg(DPL::BinaryQueue &buffer) +{ + std::string::size_type size; + buffer.FlattenConsume(&size, sizeof(size)); + std::unique_ptr<char[]> str(new char[size]); + buffer.FlattenConsume(str.get(), size); + return std::string(str.get(), str.get() + size); +} +} +} // Wrt diff --git a/src/wrt-popup/wrt/PopupSerializer.h b/src/wrt-popup/wrt/PopupSerializer.h new file mode 100644 index 0000000..70407ec --- /dev/null +++ b/src/wrt-popup/wrt/PopupSerializer.h @@ -0,0 +1,33 @@ +/* + * 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 WRT_POPUP_SERIALIZER_H +#define WRT_POPUP_SERIALIZER_H + +#include <string> +#include <dpl/binary_queue.h> + +namespace Wrt { +namespace PopupSerializer { +void appendArg(int arg, DPL::BinaryQueue &buffer); +void appendArg(const std::string &arg, DPL::BinaryQueue &buffer); + +int getIntArg(DPL::BinaryQueue &buffer); +std::string getStringArg(DPL::BinaryQueue &buffer); +} +} // Wrt + +#endif
\ No newline at end of file diff --git a/src/wrt-popup/wrt/popup-bin/CMakeLists.txt b/src/wrt-popup/wrt/popup-bin/CMakeLists.txt new file mode 100644 index 0000000..ff393d1 --- /dev/null +++ b/src/wrt-popup/wrt/popup-bin/CMakeLists.txt @@ -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. +# + +PKG_CHECK_MODULES(WRT_POPUP_DEPS + ecore-x + dpl-efl + dpl-event-efl + REQUIRED +) + +INCLUDE_DIRECTORIES( + ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_CURRENT_SOURCE_DIR}/renderer + ${WRT_POPUP_DEPS_INCLUDE_DIRS} + ${WRT_POPUP_COMMON_DIR} +) + +SET(WRT_POPUP_SRCS + ${WRT_POPUP_COMMON_SRCS} + wrt-popup.cpp + YesNoCheckPopup.cpp + InfoPopup.cpp + renderer/evas_object.cpp + renderer/popup_controller.cpp + renderer/popup_manager.cpp + renderer/popup_renderer.cpp +) + +ADD_EXECUTABLE(${TARGET_POPUP_WRT} + ${WRT_POPUP_SRCS} +) + +TARGET_LINK_LIBRARIES(${TARGET_POPUP_WRT} + ${WRT_POPUP_DEPS_LIBRARIES} +) + +SET_TARGET_PROPERTIES(${TARGET_POPUP_WRT} PROPERTIES + COMPILE_DEFINITIONS LOG_TAG="${LOG_TAG}") + +SET_TARGET_PROPERTIES(${TARGET_POPUP_WRT} PROPERTIES + LINK_FLAGS "-Wl,--as-needed -Wl,--hash-style=both" + BUILD_WITH_INSTALL_RPATH ON + INSTALL_RPATH_USE_LINK_PATH ON +) + +INSTALL(TARGETS ${TARGET_POPUP_WRT} DESTINATION bin) diff --git a/src/wrt-popup/wrt/popup-bin/InfoPopup.cpp b/src/wrt-popup/wrt/popup-bin/InfoPopup.cpp new file mode 100644 index 0000000..489c320 --- /dev/null +++ b/src/wrt-popup/wrt/popup-bin/InfoPopup.cpp @@ -0,0 +1,77 @@ +/* + * 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 InfoPopup.cpp + * @author Lukasz Marek(l.marek@samsung.com) + * @version 1.0 + * @brief Popup that displays information. Inplementation + */ + +#include "InfoPopup.h" +#include <memory> +#include <string.h> +#include "popup_manager.h" +#include "popup.h" +#include "PopupSerializer.h" + +namespace Wrt { +namespace Popup { +InfoPopup::InfoPopup() : + m_parent(NULL) +{} + +void InfoPopup::show(DPL::BinaryQueueAutoPtr data, WrtPopup* parent) +{ + WrtLogD("Entered"); + std::string title = PopupSerializer::getStringArg(*data); + std::string message = PopupSerializer::getStringArg(*data); + std::string button = PopupSerializer::getStringArg(*data); + Assert(data->Empty()); + WrtLogD("title: %s message: %s", title.c_str(), message.c_str()); + + m_parent = parent; + + Renderer::CtrlPopupPtr popup = + Renderer::PopupControllerSingleton::Instance().CreatePopup(); + + popup->SetTitle(title); + popup->Append(new Renderer::PopupObject::Label(message)); + + popup->Append(new Renderer::PopupObject::Button(button, 0)); + + ListenForAnswer(popup); + + Renderer::ShowPopupEventShort event(popup, + MakeAnswerCallback( + this, + &InfoPopup::responseCallback)); + + CONTROLLER_POST_EVENT(Renderer::PopupController, + event); + + WrtLogD("Exited"); + return; +} + +void InfoPopup::responseCallback(const Renderer::AnswerCallbackData &answer) +{ + DPL::BinaryQueue retValue; + PopupSerializer::appendArg(true, retValue); + PopupSerializer::appendArg(answer.buttonAnswer, retValue); + m_parent->response(retValue); +} +} // Popup +} // Wrt diff --git a/src/wrt-popup/wrt/popup-bin/InfoPopup.h b/src/wrt-popup/wrt/popup-bin/InfoPopup.h new file mode 100644 index 0000000..3a29fc0 --- /dev/null +++ b/src/wrt-popup/wrt/popup-bin/InfoPopup.h @@ -0,0 +1,45 @@ +/* + * 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 InfoPopup.h + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 1.0 + * @brief Popup that contains 'Yes' and 'No' buttons + */ + +#ifndef WRT_INFO_POPUP_H +#define WRT_INFO_POPUP_H + +#include "wrt-popup.h" + +namespace Wrt { +namespace Popup { +class InfoPopup : public IPopup +{ + public: + InfoPopup(); + virtual void show(DPL::BinaryQueueAutoPtr data, WrtPopup* parent); + + private: + + void responseCallback(const Renderer::AnswerCallbackData &answer); + WrtPopup* m_parent; +}; +} // Popup +} // Wrt + +#endif /* WRT_INFO_POPUP_H */ + diff --git a/src/wrt-popup/wrt/popup-bin/YesNoCheckPopup.cpp b/src/wrt-popup/wrt/popup-bin/YesNoCheckPopup.cpp new file mode 100644 index 0000000..fa6619d --- /dev/null +++ b/src/wrt-popup/wrt/popup-bin/YesNoCheckPopup.cpp @@ -0,0 +1,71 @@ +/* + * File: YesNoCheckPopup.cpp + * Author: pciezkowski + * + * Created on December 12, 2012, 9:23 AM + */ + +#include "YesNoCheckPopup.h" +#include <memory> +#include <string.h> +#include "popup_manager.h" +#include "PopupSerializer.h" + +namespace Wrt { +namespace Popup { +YesNoCheckPopup::~YesNoCheckPopup() +{} + +void YesNoCheckPopup::show(DPL::BinaryQueueAutoPtr data, WrtPopup* parent) +{ + WrtLogD("Entered"); + m_parent = parent; + Renderer::CtrlPopupPtr popup = createPopup(data); + ListenForAnswer(popup); + + Renderer::ShowPopupEventShort event(popup, + MakeAnswerCallback( + this, + &YesNoCheckPopup::responseCallback)); + + CONTROLLER_POST_EVENT(Renderer::PopupController, + event); + + WrtLogD("Exited"); + return; +} + +Renderer::CtrlPopupPtr YesNoCheckPopup::createPopup( + DPL::BinaryQueueAutoPtr data) +{ + std::string title = PopupSerializer::getStringArg(*data); + std::string message = PopupSerializer::getStringArg(*data); + std::string checkboxLabel = PopupSerializer::getStringArg(*data); + Assert(data->Empty()); + WrtLogD("title: %s message: %s, checkbox: %s", + title.c_str(), message.c_str(), checkboxLabel.c_str()); + Renderer::CtrlPopupPtr popup = + Renderer::PopupControllerSingleton::Instance().CreatePopup(); + + popup->SetTitle(title); + popup->Append(new Renderer::PopupObject::Label(message)); + popup->Append(new Renderer::PopupObject::Check(checkboxLabel)); + popup->Append(new Renderer::PopupObject::Button(YES_LABEL, POPUP_YES_VALUE)); + popup->Append(new Renderer::PopupObject::Button(NO_LABEL, POPUP_NO_VALUE)); + return popup; +} + +void YesNoCheckPopup::responseCallback( + const Renderer::AnswerCallbackData &answer) +{ + WrtLogD("Entered"); + bool result = (POPUP_YES_VALUE == answer.buttonAnswer); + DPL::BinaryQueue retValue; + PopupSerializer::appendArg(true, retValue); + PopupSerializer::appendArg(result, retValue); + WrtLogD("Check state: %d", answer.chackState); + PopupSerializer::appendArg(answer.chackState, retValue); + m_parent->response(retValue); +} +} // Popup +} // Wrt diff --git a/src/wrt-popup/wrt/popup-bin/YesNoCheckPopup.h b/src/wrt-popup/wrt/popup-bin/YesNoCheckPopup.h new file mode 100644 index 0000000..635518a --- /dev/null +++ b/src/wrt-popup/wrt/popup-bin/YesNoCheckPopup.h @@ -0,0 +1,52 @@ +/* + * 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 YesNoCheckPopup.cpp + * @author Przmeyslaw Ciezkowsko (p.ciezkowski@samsung.com) + * @version 1.0 + * @brief Popup that contains 'Yes' and 'No' buttons and checkbox. + * Inplementation + */ + +#include "wrt-popup.h" + +#ifndef WRT_YES_NO_CHECK_POPUP_H +#define WRT_YES_NO_CHECK_POPUP_H + +namespace Wrt { +namespace Popup { + +const char YES_LABEL[] = "Yes"; +const char NO_LABEL[] = "No"; +const int POPUP_YES_VALUE = 1; +const int POPUP_NO_VALUE = 2; + +class YesNoCheckPopup : public IPopup +{ + public: + virtual void show(DPL::BinaryQueueAutoPtr data, WrtPopup* parent); + virtual ~YesNoCheckPopup(); + + protected: + virtual Renderer::CtrlPopupPtr createPopup(DPL::BinaryQueueAutoPtr data); + virtual void responseCallback(const Renderer::AnswerCallbackData &answer); + WrtPopup* m_parent; +}; +} // Popup +} // Wrt + +#endif /* WRT_YES_NO_CHECK_POPUP_H */ + diff --git a/src/wrt-popup/wrt/popup-bin/renderer/evas_object.cpp b/src/wrt-popup/wrt/popup-bin/renderer/evas_object.cpp new file mode 100644 index 0000000..13b38c1 --- /dev/null +++ b/src/wrt-popup/wrt/popup-bin/renderer/evas_object.cpp @@ -0,0 +1,234 @@ +/* + * 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 evas_object.cpp + * @author Lukasz Wrzosek (l.wrzosel@samsung.com) + * @version 1.0 + * @brief This file is the implementation for Evas_Object wrapper from + * Efl. + */ + +#include "evas_object.h" +#include <stddef.h> +#include <dpl/foreach.h> + +namespace Wrt { +namespace Popup { +namespace Renderer { +Evas_Object* EvasObject::IConnection::GetEvasObject() +{ + return m_object->GetObject(); +} + +void EvasObject::IConnection::Disconnect() +{ + m_object->DisconnectCallback(this); +} + +EvasObject::IConnection::IConnection(EvasObject::EvasObjectShared* object) : + m_object(object) +{} + +void EvasObject::IConnection::SmartCallbackWrapper(void* data, + Evas_Object* /*object*/, + void* event_info) +{ + Assert(data); + IConnection* Calle = static_cast<IConnection*>(data); + Calle->Call(event_info); +} + +void EvasObject::IConnection::EvasCallbackWrapper(void* data, + Evas* /*evas*/, + Evas_Object* /*object*/, + void* event_info) +{ + Assert(data); + IConnection* Calle = static_cast<IConnection*>(data); + Calle->Call(event_info); +} + +Evas_Object* EvasObject::EvasObjectShared::GetObject() +{ + return m_object; +} + +EvasObject::EvasObjectShared::SmartConnectionBase::SmartConnectionBase( + const std::string& name, + EvasObject::EvasObjectShared* object) : + IConnection(object), + m_callbackName(name) +{} + +void EvasObject::EvasObjectShared::SmartConnectionBase::ConnectPrv() +{ + evas_object_smart_callback_add(GetEvasObject(), + m_callbackName.c_str(), + &IConnection::SmartCallbackWrapper, this); +} + +void EvasObject::EvasObjectShared::SmartConnectionBase::DisconnectPrv() +{ + evas_object_smart_callback_del(GetEvasObject(), + m_callbackName.c_str(), + &IConnection::SmartCallbackWrapper); +} + +EvasObject::EvasObjectShared::EvasConnectionBase::EvasConnectionBase( + Evas_Callback_Type type, + EvasObject::EvasObjectShared* object) : + IConnection(object), + m_callbackType(type) +{} + +void EvasObject::EvasObjectShared::EvasConnectionBase::ConnectPrv() +{ + evas_object_event_callback_add( + GetEvasObject(), m_callbackType, &IConnection::EvasCallbackWrapper, + this); +} + +void EvasObject::EvasObjectShared::EvasConnectionBase::DisconnectPrv() +{ + evas_object_event_callback_del_full( + GetEvasObject(), m_callbackType, &IConnection::EvasCallbackWrapper, + this); +} + +EvasObject::EvasObjectShared::EvasObjectShared() : + m_object(NULL) +{} + +EvasObject::EvasObjectShared::EvasObjectShared(Evas_Object* object) : + m_object(object) +{ + Assert(m_object); + evas_object_event_callback_add(m_object, + EVAS_CALLBACK_DEL, + &StaticOnDelEvent, + this); +} + +void EvasObject::EvasObjectShared::SetObject(Evas_Object* object) +{ + Assert(m_object == NULL); + Assert(object != NULL); + m_object = object; + evas_object_event_callback_add(m_object, + EVAS_CALLBACK_DEL, + &StaticOnDelEvent, + this); +} + +EvasObject::EvasObjectShared::~EvasObjectShared() +{ + if (m_object) { + DisconnectAll(); + evas_object_event_callback_del(m_object, + EVAS_CALLBACK_DEL, + &StaticOnDelEvent); + m_object = NULL; + } +} + +bool EvasObject::EvasObjectShared::DisconnectCallback(IConnection* connection) +{ + IConnectionsSet::iterator it = m_connections.find(connection); + if (it != m_connections.end()) { + (*it)->DisconnectPrv(); + delete connection; + m_connections.erase(it); + return true; + } + return false; +} + +void EvasObject::EvasObjectShared::DisconnectAll() +{ + FOREACH(it, m_connections) + { + (*it)->DisconnectPrv(); + delete *it; + } + m_connections.clear(); +} + +void EvasObject::EvasObjectShared::StaticOnDelEvent(void* data, + Evas* /*e*/, + Evas_Object* /*o*/, + void* /*ev*/) +{ + Assert(data); + EvasObjectShared* This = static_cast<EvasObjectShared*>(data); + if (This->m_object) { + evas_object_event_callback_del(This->m_object, + EVAS_CALLBACK_DEL, + &StaticOnDelEvent); + This->DisconnectAll(); + This->m_object = NULL; + } +} + +EvasObject::EvasObject() : + m_object(new EvasObjectShared()) +{} + +EvasObject::EvasObject(Evas_Object* object) : + m_object(new EvasObjectShared(object)) +{} + +EvasObject::EvasObject(const EvasObject& other) : + m_object(other.m_object) +{} + +//this destructor must be here to let pimpl with shared_ptr work without warning +EvasObject::~EvasObject() +{} + +EvasObject& EvasObject::operator=(const EvasObject& other) +{ + Assert(m_object); + m_object = other.m_object; + return *this; +} + +EvasObject* EvasObject::operator=(Evas_Object* object) +{ + Assert(m_object); + m_object->SetObject(object); + return this; +} + +bool EvasObject::DisconnectCallback(IConnection* connection) +{ + Assert(m_object); + return m_object->DisconnectCallback(connection); +} + +void EvasObject::DisconnectAll() +{ + Assert(m_object); + m_object->DisconnectAll(); +} + +EvasObject::operator Evas_Object *() +{ + Assert(m_object); + return m_object->GetObject(); +} +} +} // namespace DPL +} // namespace Popup diff --git a/src/wrt-popup/wrt/popup-bin/renderer/evas_object.h b/src/wrt-popup/wrt/popup-bin/renderer/evas_object.h new file mode 100644 index 0000000..2758fa1 --- /dev/null +++ b/src/wrt-popup/wrt/popup-bin/renderer/evas_object.h @@ -0,0 +1,654 @@ +/* + * 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 evas_object.h + * @author Lukasz Wrzosek (l.wrzosel@samsung.com) + * @version 1.0 + * @brief This file is the header for Evas_Object wrapper from Efl. + */ + +#ifndef WRT_SRC_DOMAIN_EFL_EVAS_OBJECT_H +#define WRT_SRC_DOMAIN_EFL_EVAS_OBJECT_H + +#include <Evas.h> +#include <dpl/noncopyable.h> +#include <dpl/framework_efl.h> +#include <dpl/assert.h> +#include <dpl/foreach.h> +#include <dpl/apply.h> +#include <set> +#include <string> +#include <tuple> +#include <utility> +#include <memory> + +namespace Wrt { +namespace Popup { +namespace Renderer { +class EvasObject +{ + class EvasObjectShared; + typedef std::shared_ptr<EvasObjectShared> EvasObjectSharedPtr; + + public: + class IConnection + { + public: + Evas_Object* GetEvasObject(); + void Disconnect(); + + private: + IConnection(EvasObjectShared* object); + virtual ~IConnection() + {} + virtual void Call(void* /*event_info*/) = 0; + + static void SmartCallbackWrapper(void* data, + Evas_Object* /*object*/, + void* event_info); + static void EvasCallbackWrapper(void* data, + Evas* /*evas*/, + Evas_Object* /*object*/, + void* event_info); + + virtual void ConnectPrv() = 0; + virtual void DisconnectPrv() = 0; + + friend class EvasObjectShared; + + EvasObjectShared* m_object; + }; + + private: + class EvasObjectShared : DPL::Noncopyable + { + public: + friend class IConnection; + Evas_Object* GetObject(); + + typedef std::set<IConnection*> IConnectionsSet; + + class SmartConnectionBase : public IConnection + { + public: + SmartConnectionBase(const std::string& name, + EvasObjectShared* object); + + virtual void ConnectPrv(); + virtual void DisconnectPrv(); + std::string m_callbackName; + }; + + template<typename ... Args> + class SmartConnection : public SmartConnectionBase + { + public: + typedef void (*CbType)(IConnection* connection, + void* event_info, + Args ... args); + + SmartConnection(const std::string& name, + CbType callback, + EvasObjectShared* object, + Args ... args) : + SmartConnectionBase(name, object), + m_callback(callback), + m_args(args ...) + {} + + virtual ~SmartConnection() + {} + + virtual void Call(void* event_info) + { + DPL::Apply<void, + DPL::ExtraArgsInsertPolicy::Prepend>(m_callback, + m_args, + this, + event_info); + } + + private: + CbType m_callback; + std::tuple<Args ...> m_args; + }; + + template <class ThisType, class ArgType1> + class SmartMemberConnection1 : public SmartConnectionBase + { + public: + typedef void (ThisType::*CbType)(IConnection* connection, + void* event_info, ArgType1 *arg1); + + SmartMemberConnection1(const std::string& name, + CbType callback, + ThisType* callee, + ArgType1* arg1, + EvasObjectShared* object) : + SmartConnectionBase(name, object), + m_callback(callback), + m_callee(callee), + m_arg1(arg1) + {} + + virtual ~SmartMemberConnection1() + {} + + virtual void Call(void* event_info) + { + (m_callee->*m_callback)(this, event_info, m_arg1); + } + + private: + CbType m_callback; + ThisType* m_callee; + ArgType1* m_arg1; + }; + + template <class ThisType, class ArgType1, class ArgType2> + class SmartMemberConnection2 : public SmartConnectionBase + { + public: + typedef void (ThisType::*CbType)(IConnection* connection, + void* event_info, ArgType1 *arg1, + ArgType2* arg2); + + SmartMemberConnection2(const std::string& name, + CbType callback, + ThisType* callee, + ArgType1* arg1, + ArgType2* arg2, + EvasObjectShared* object) : + SmartConnectionBase(name, object), + m_callback(callback), + m_callee(callee), + m_arg1(arg1), + m_arg2(arg2) + {} + + virtual ~SmartMemberConnection2() + {} + + virtual void Call(void* event_info) + { + (m_callee->*m_callback)(this, event_info, m_arg1, m_arg2); + } + + private: + CbType m_callback; + ThisType* m_callee; + ArgType1* m_arg1; + ArgType2* m_arg2; + }; + + class EvasConnectionBase : public IConnection + { + public: + EvasConnectionBase(Evas_Callback_Type type, + EvasObjectShared* object); + + virtual void ConnectPrv(); + virtual void DisconnectPrv(); + + Evas_Callback_Type m_callbackType; + }; + + template <class ArgType1> + class EvasConnection1 : public EvasConnectionBase + { + public: + typedef void (*CbType)(IConnection* connection, void* event_info, + ArgType1 *arg1); + + EvasConnection1(Evas_Callback_Type type, + CbType callback, + ArgType1* arg1, + EvasObjectShared* object) : + EvasConnectionBase(type, object), + m_callback(callback), + m_arg1(arg1) + {} + + virtual ~EvasConnection1() + {} + + virtual void Call(void* event_info) + { + m_callback(this, event_info, m_arg1); + } + + private: + CbType m_callback; + ArgType1* m_arg1; + }; + + template <class ArgType1, class ArgType2> + class EvasConnection2 : public EvasConnectionBase + { + public: + typedef void (*CbType)(IConnection* connection, void* event_info, + ArgType1 *arg1, ArgType2 *arg2); + + EvasConnection2(Evas_Callback_Type type, + CbType callback, + ArgType1* arg1, + ArgType2* arg2, + EvasObjectShared* object) : + EvasConnectionBase(type, object), + m_callback(callback), + m_arg1(arg1), + m_arg2(arg2) + {} + + virtual ~EvasConnection2() + {} + + virtual void Call(void* event_info) + { + m_callback(this, event_info, m_arg1, m_arg2); + } + + private: + CbType m_callback; + ArgType1* m_arg1; + ArgType2* m_arg2; + }; + + template <class ThisType, class ArgType1> + class EvasMemberConnection1 : public EvasConnectionBase + { + public: + typedef void (ThisType::*CbType)(IConnection* connection, + void* event_info, ArgType1 *arg1); + + EvasMemberConnection1(Evas_Callback_Type type, + CbType callback, + ThisType* callee, + ArgType1* arg1, + EvasObjectShared* object) : + EvasConnectionBase(type, object), + m_callback(callback), + m_callee(callee), + m_arg1(arg1) + {} + + virtual ~EvasMemberConnection1() + {} + + virtual void Call(void* event_info) + { + (m_callee->*m_callback)(this, event_info, m_arg1); + } + + private: + CbType m_callback; + ThisType* m_callee; + ArgType1* m_arg1; + }; + + template <class ThisType, class ArgType1, class ArgType2> + class EvasMemberConnection2 : public EvasConnectionBase + { + public: + typedef void (ThisType::*CbType)(IConnection* connection, + void* event_info, ArgType1* arg1, + ArgType2* arg2); + + EvasMemberConnection2(Evas_Callback_Type type, + CbType callback, + ThisType* callee, + ArgType1* arg1, + ArgType2* arg2, + EvasObjectShared* object) : + EvasConnectionBase(type, object), + m_callback(callback), + m_callee(callee), + m_arg1(arg1), + m_arg2(arg2) + {} + + virtual ~EvasMemberConnection2() + {} + + virtual void Call(void* event_info) + { + (m_callee->*m_callback)(this, event_info, m_arg1, m_arg2); + } + + private: + CbType m_callback; + ThisType* m_callee; + ArgType1* m_arg1; + ArgType2* m_arg2; + }; + + EvasObjectShared(); + explicit EvasObjectShared(Evas_Object* object); + void SetObject(Evas_Object* object); + ~EvasObjectShared(); + + template<typename ... Args> + IConnection* ConnectSmartCallback( + const char* callbackName, + typename SmartConnection<Args ...>:: + CbType callback, + Args ... args) + { + Assert(m_object); + Assert(callbackName); + Assert(callback); + IConnection* connection = new SmartConnection<Args ...>( + callbackName, + callback, + this, + args ...); + m_connections.insert(connection); + connection->ConnectPrv(); + return connection; + } + + template <class ThisType, class ArgType1, class ArgType2> + IConnection* ConnectMemberSmartCallback( + const char* callbackName, + typename SmartMemberConnection2<ThisType, ArgType1, + ArgType2>::CbType callback, + ThisType* callee, + ArgType1* arg1, + ArgType2* arg2) + { + Assert(m_object); + Assert(callee); + Assert(callbackName); + Assert(callback); + IConnection* connection = + new SmartMemberConnection2<ThisType, ArgType1, ArgType2>( + callbackName, + callback, + callee, + arg1, + arg2, + this); + m_connections.insert(connection); + connection->ConnectPrv(); + return connection; + } + + template <class ThisType, class ArgType1> + IConnection* ConnectMemberSmartCallback( + const char* callbackName, + typename SmartMemberConnection1<ThisType, + ArgType1>::CbType callback, + ThisType* callee, + ArgType1* arg1) + { + Assert(m_object); + Assert(callee); + Assert(callbackName); + Assert(callback); + IConnection* connection = + new SmartMemberConnection1<ThisType, ArgType1>(callbackName, + callback, + callee, + arg1, + this); + m_connections.insert(connection); + connection->ConnectPrv(); + return connection; + } + + template <class ArgType1, class ArgType2> + IConnection* ConnectEvasCallback(Evas_Callback_Type callbackType, + typename EvasConnection2<ArgType1, + ArgType2>:: + CbType callback, + ArgType1* arg1, + ArgType2* arg2) + { + Assert(m_object); + Assert(callbackType); + Assert(callback); + IConnection* connection = new EvasConnection2<ArgType1, ArgType2>( + callbackType, + callback, + arg1, + arg2, + this); + m_connections.insert(connection); + connection->ConnectPrv(); + return connection; + } + + template <class ArgType1> + IConnection* ConnectEvasCallback( + Evas_Callback_Type callbackType, + typename EvasConnection1<ArgType1>:: + CbType callback, + ArgType1* arg1) + { + Assert(m_object); + Assert(callbackType); + Assert(callback); + IConnection* connection = new EvasConnection1<ArgType1>( + callbackType, + callback, + arg1, + this); + m_connections.insert(connection); + connection->ConnectPrv(); + return connection; + } + + template <class ThisType, class ArgType1, class ArgType2> + IConnection* ConnectMemberEvasCallback( + Evas_Callback_Type callbackType, + typename EvasMemberConnection2<ThisType, ArgType1, + ArgType2>::CbType callback, + ThisType* callee, + ArgType1* arg1, + ArgType2* arg2) + { + Assert(m_object); + Assert(callee); + Assert(callbackType); + Assert(callback); + IConnection* connection = + new EvasMemberConnection2<ThisType, ArgType1, ArgType2>( + callbackType, + callback, + callee, + arg1, + arg2, + this); + m_connections.insert(connection); + connection->ConnectPrv(); + return connection; + } + + template <class ThisType, class ArgType1> + IConnection* ConnectMemberEvasCallback( + Evas_Callback_Type callbackType, + typename EvasMemberConnection1<ThisType, + ArgType1>::CbType callback, + ThisType* callee, + ArgType1* arg1) + { + Assert(m_object); + Assert(callee); + Assert(callbackType); + Assert(callback); + IConnection* connection = + new EvasMemberConnection1<ThisType, ArgType1>(callbackType, + callback, + callee, + arg1, + this); + m_connections.insert(connection); + connection->ConnectPrv(); + return connection; + } + + bool DisconnectCallback(IConnection* connection); + void DisconnectAll(); + + static void StaticOnDelEvent(void* data, + Evas* /*e*/, + Evas_Object* /*o*/, + void* /*ev*/); + + IConnectionsSet m_connections; + Evas_Object* m_object; + }; + + public: + EvasObject(); + explicit EvasObject(Evas_Object* object); + EvasObject(const EvasObject& other); + ~EvasObject(); + + EvasObject& operator=(const EvasObject& other); + EvasObject* operator=(Evas_Object* object); + + operator Evas_Object *(); + + bool IsValid() const + { + Assert(m_object); + return m_object->GetObject() != NULL; + } + + bool DisconnectCallback(IConnection* connection); + void DisconnectAll(); + + template <class ... Args> + IConnection* ConnectSmartCallback( + const char* callbackName, + typename EvasObjectShared::SmartConnection<Args ...>::CbType + callback, + Args ... args) + { + Assert(m_object); + return m_object->ConnectSmartCallback(callbackName, callback, args ...); + } + + template <class ThisType, class ArgType1, class ArgType2> + IConnection* ConnectMemberSmartCallback( + const char* callbackName, + typename EvasObjectShared::SmartMemberConnection2<ThisType, + ArgType1, + ArgType2>::CbType + callback, + ThisType* callee, + ArgType1* arg1, + ArgType2* arg2) + { + Assert(m_object); + Assert(callee); + Assert(callback); + return m_object->ConnectMemberSmartCallback(callbackName, + callback, + callee, + arg1, + arg2); + } + + template <class ThisType, class ArgType1> + IConnection* ConnectMemberSmartCallback( + const char* callbackName, + typename EvasObjectShared::SmartMemberConnection1<ThisType, + ArgType1>::CbType + callback, + ThisType* callee, + ArgType1* arg1) + { + Assert(m_object); + Assert(callee); + Assert(callback); + return m_object->ConnectMemberSmartCallback(callbackName, + callback, + callee, + arg1); + } + + template <class ArgType1, class ArgType2> + IConnection* ConnectEvasCallback( + Evas_Callback_Type callbackType, + typename EvasObjectShared::EvasConnection1<ArgType1>::CbType + callback, + ArgType1* arg1, + ArgType2* arg2) + { + Assert(m_object); + return m_object->ConnectEvasCallback(callbackType, callback, arg1, arg2); + } + + template <class ArgType1> + IConnection* ConnectEvasCallback( + Evas_Callback_Type callbackType, + typename EvasObjectShared::EvasConnection1<ArgType1>::CbType + callback, + ArgType1* arg1) + { + Assert(m_object); + return m_object->ConnectEvasCallback(callbackType, callback, arg1); + } + + template <class ThisType, class ArgType1> + IConnection* ConnectMemberEvasCallback( + Evas_Callback_Type callbackType, + typename EvasObjectShared::EvasMemberConnection1<ThisType, + ArgType1>::CbType + callback, + ThisType* callee, + ArgType1* arg1) + { + Assert(m_object); + Assert(callee); + Assert(callback); + return m_object->ConnectMemberEvasCallback(callbackType, + callback, + callee, + arg1); + } + + template <class ThisType, class ArgType1, class ArgType2> + IConnection* ConnectMemberEvasCallback( + Evas_Callback_Type callbackType, + typename EvasObjectShared::EvasMemberConnection2<ThisType, ArgType1, + ArgType2>::CbType + callback, + ThisType* callee, + ArgType1* arg1, + ArgType2* arg2) + { + Assert(m_object); + Assert(callee); + Assert(callback); + return m_object->ConnectMemberEvasCallback(callbackType, + callback, + callee, + arg1, + arg2); + } + + private: + EvasObjectSharedPtr m_object; +}; +} +} //namespace +} //namespace + +#endif //WRT_SRC_DOMAIN_EFL_EVAS_OBJECT_H + diff --git a/src/wrt-popup/wrt/popup-bin/renderer/popup.h b/src/wrt-popup/wrt/popup-bin/renderer/popup.h new file mode 100644 index 0000000..c9e75b0 --- /dev/null +++ b/src/wrt-popup/wrt/popup-bin/renderer/popup.h @@ -0,0 +1,70 @@ +/* + * 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 popup.h + * @author Lukasz Wrzosek (l.wrzosek@samsung.com) + * @version 1.0 + * @brief This is popup inteface declaration + */ + +#ifndef WRT_SRC_POPUP_POPUP_H_ +#define WRT_SRC_POPUP_POPUP_H_ + +#include <memory> +#include <dpl/assert.h> +#include <dpl/log/wrt_log.h> +#include <string> +#include <dpl/optional_typedefs.h> +#include "popup_object.h" + +namespace Wrt { +namespace Popup { +namespace Renderer { +struct AnswerCallbackData +{ + int buttonAnswer; + DPL::OptionalStdString password; + bool chackState; +}; + +class PopupManager; +class IPopup; +typedef std::shared_ptr<IPopup> IPopupPtr; + +class IPopup : public std::enable_shared_from_this<IPopup> +{ + public: + virtual void SetTitle(const std::string &title) = 0; + /*The object is deleted automatically after rendered */ + virtual void Append(PopupObject::IPopupObject *object) = 0; + + protected: + typedef void (*PopupCallbackType)(const AnswerCallbackData& answer, + void *data); + virtual void Show(PopupCallbackType callback, + void* data) = 0; + virtual ~IPopup() + {} + + private: + friend class PopupManager; + friend class std::shared_ptr<IPopup>; +}; +} +} // namespace Popup +} // namespace Wrt + +#endif //WRT_SRC_POPUP_POPUP_H_ diff --git a/src/wrt-popup/wrt/popup-bin/renderer/popup_controller.cpp b/src/wrt-popup/wrt/popup-bin/renderer/popup_controller.cpp new file mode 100644 index 0000000..6cc404f --- /dev/null +++ b/src/wrt-popup/wrt/popup-bin/renderer/popup_controller.cpp @@ -0,0 +1,111 @@ +/* + * 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 popup_controller.cpp + * @author Lukasz Wrzosek (l.wrzosek@samsung.com) + * @version 1.0 + * @bref Implementation file for popup controller + */ + +#include "popup_controller.h" +#include <stddef.h> +#include <dpl/assert.h> +#include <dpl/log/wrt_log.h> +#include <dpl/singleton_impl.h> + +IMPLEMENT_SINGLETON(Wrt::Popup::Renderer::PopupController) + +namespace Wrt { +namespace Popup { +namespace Renderer { +void CtrlPopup::SetTitle(const std::string &title) +{ + Assert(m_popup); + m_popup->SetTitle(title); +} + +void CtrlPopup::Append(PopupObject::IPopupObject *object) +{ + Assert(m_popup); + m_popup->Append(object); +} + +CtrlPopup::CtrlPopup(IPopupPtr popup) : + m_popup(popup), + m_callback() +{ + Assert(m_popup); +} + +CtrlPopup::~CtrlPopup() +{} + +void CtrlPopup::EmitAnswer(const AnswerCallbackData & answer) +{ + AnswerCallbackData l_answer = answer; + PopupAnswerEvent event(shared_from_this(), m_callback, l_answer); + DPL::Event::EventSupport<PopupAnswerEvent>::EmitEvent(event); +} + +PopupController::PopupController() : m_canvas(NULL) +{} + +CtrlPopupPtr PopupController::CreatePopup() const +{ + return CtrlPopupPtr( + new CtrlPopup(PopupManagerSingleton::Instance().CreatePopup())); +} + +void PopupController::OnEventReceived(const ShowPopupEventShort& event) +{ + CtrlPopupPtr popup = event.GetArg0(); + popup->m_callback = event.GetArg1(); + + //pass canvas from controller to manager + //canvas is not passed earlier because value wasn't set properly + PopupManagerSingleton::Instance().setExternalCanvas(getExternalCanvas()); + + PopupManagerSingleton::Instance().RunAsyncWithArgType( + popup->m_popup, + &PopupController::StaticOnAnswerReceived, + new CtrlPopupPtr(popup)); +} + +void PopupController::StaticOnAnswerReceived(const AnswerCallbackData & answer, + CtrlPopupPtr* popup) +{ + Assert(popup != NULL); + (*popup)->EmitAnswer(answer); + delete popup; // Just SharedPtr is destroyed, not the popup itself +} + +void PopupControllerUser::OnEventReceived(const PopupAnswerEvent& event) +{ + //Here we are in a proper context to call the callback + PopupAnswerCallback answerCall = event.GetArg1(); + AnswerCallbackData answer = event.GetArg2(); + answerCall.Call(answer); + event.GetArg0()->DPL::Event::EventSupport<PopupAnswerEvent>::RemoveListener( + this); +} + +void PopupControllerUser::ListenForAnswer(CtrlPopupPtr popup) +{ + popup->DPL::Event::EventSupport<PopupAnswerEvent>::AddListener(this); +} +} +} //namespace Popup +} //namespace Wrt diff --git a/src/wrt-popup/wrt/popup-bin/renderer/popup_controller.h b/src/wrt-popup/wrt/popup-bin/renderer/popup_controller.h new file mode 100644 index 0000000..0d81695 --- /dev/null +++ b/src/wrt-popup/wrt/popup-bin/renderer/popup_controller.h @@ -0,0 +1,216 @@ +/* + * 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 popup_controller.h + * @author Lukasz Wrzosek (l.wrzosek@samsung.com) + * @version 1.0 + * @bref Header file for popup controller + */ + +/** + * To display a popup from a given class: + * + * class ABC + * { + * void AskUser() + * { + * } + * + * void DoSomeLogicWithAnswer() + * { + * } + * }; + * + * ... update the class to something simmilar: + * + * class ABC : Popup::PopupControllerUser + * { + * void AskUser() { + * using namespace Popup; + * CtrlPopupPtr popup = + * PopupControllerSingletion::Instance().CreatePopup(); + * popup->SetTitle("Title"); + * popup->SetContent("Content"); + * popup->AddButton("name1", 1); + * popup->AddButton("name2", 2); + * ListenForAnswer(popup); + * ShowPopupEvent event(popup, + * MakeAnswerCallback(this, + * &ABC::DoSomeLogicWithAnswer)); + * CONTROLLER_POST_EVENT(PopupController, event); + * } + * + * void DoSomeLogicWithAnswer(Popup::LabelId answer) { + * if (answer == 1) + * ;//name1 pressed + * else if (answer == 2) + * ;//name2 pressed + * } + * }; + **/ + +#ifndef WRT_SRC_POPUP_CONTROLLER_POPUP_CONTROLLER_H_ +#define WRT_SRC_POPUP_CONTROLLER_POPUP_CONTROLLER_H_ + +#include <memory> +#include <dpl/singleton.h> +#include <dpl/event/controller.h> +#include <dpl/event/event_listener.h> +#include <dpl/generic_event.h> +#include <dpl/mutex.h> +#include <dpl/exception.h> +#include <dpl/noncopyable.h> +#include <dpl/log/wrt_log.h> +#include "popup_manager.h" + +namespace Wrt { +namespace Popup { +namespace Renderer { +typedef int LabelId; + +struct PopupAnswerCallback +{ + typedef void (PopupAnswerCallback::*MemberPtr)(); + + void* callee; + MemberPtr member; + void (*callTranslator)(PopupAnswerCallback* callData, + const AnswerCallbackData& answer); + + void Call(const AnswerCallbackData& answer) + { + callTranslator(this, answer); + } +}; + +class PopupController; +class CtrlPopup; + +typedef std::shared_ptr<CtrlPopup> CtrlPopupPtr; + +DECLARE_GENERIC_EVENT_3(PopupAnswerEvent, + CtrlPopupPtr, + PopupAnswerCallback, + AnswerCallbackData) + +DECLARE_GENERIC_EVENT_2(ShowPopupEventShort, + CtrlPopupPtr, + PopupAnswerCallback) + +class CtrlPopup : public DPL::Event::EventSupport<PopupAnswerEvent>, + public std::enable_shared_from_this<CtrlPopup> +{ + public: + void SetTitle(const std::string &title); + void Append(PopupObject::IPopupObject *object); + + ~CtrlPopup(); + + private: + friend class PopupController; + friend class std::shared_ptr<CtrlPopup>; + + explicit CtrlPopup(IPopupPtr popup); + void EmitAnswer(const AnswerCallbackData& answer); + + IPopupPtr m_popup; + PopupAnswerCallback m_callback; +}; + +class PopupController : + public DPL::Event::Controller<DPL::TypeListDecl<ShowPopupEventShort>::Type> +{ + public: + CtrlPopupPtr CreatePopup() const; + + void setExternalCanvas(void* canvas) + { + m_canvas = canvas; + } + void* getExternalCanvas() const + { + return m_canvas; + } + void* m_canvas; + + protected: + virtual void OnEventReceived(const ShowPopupEventShort& event); + PopupController(); + + private: + static void StaticOnAnswerReceived(const AnswerCallbackData& answer, + CtrlPopupPtr* popup); +}; + +class PopupControllerUser : DPL::Event::EventListener<PopupAnswerEvent> +{ + template <class Type> + struct PopupAnswerCallbackCreator + { + typedef void (Type::*MemberPtr)(const AnswerCallbackData& answer); + union Caster + { + MemberPtr specific; + PopupAnswerCallback::MemberPtr generic; + }; + + static PopupAnswerCallback Create(Type* callee, + MemberPtr callback) + { + PopupAnswerCallback callData; + + callData.callee = callee; + + Caster caster; + caster.specific = callback; + callData.member = caster.generic; + + callData.callTranslator = + &PopupAnswerCallbackCreator::MemberCallbackTranslator; + + return callData; + } + + static void MemberCallbackTranslator(PopupAnswerCallback* callData, + const AnswerCallbackData& answer) + { + Type* typedThis = static_cast<Type*>(callData->callee); + Caster caster; + caster.generic = callData->member; + MemberPtr typedCallback = caster.specific; + (typedThis->*typedCallback)(answer); + } + }; + + protected: + virtual void OnEventReceived(const PopupAnswerEvent& event); + void ListenForAnswer(CtrlPopupPtr popup); + + template <class Type> + PopupAnswerCallback MakeAnswerCallback(Type* This, + void (Type::*callback) + (const AnswerCallbackData &)) + { + return PopupAnswerCallbackCreator<Type>::Create(This, callback); + } +}; + +typedef DPL::Singleton<PopupController> PopupControllerSingleton; +} +} //namespace Popup +} //namespace Wrt + +#endif //WRT_SRC_POPUP_CONTROLLER_POPUP_CONTROLLER_H_ diff --git a/src/wrt-popup/wrt/popup-bin/renderer/popup_manager.cpp b/src/wrt-popup/wrt/popup-bin/renderer/popup_manager.cpp new file mode 100644 index 0000000..8bbb380 --- /dev/null +++ b/src/wrt-popup/wrt/popup-bin/renderer/popup_manager.cpp @@ -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. + */ +/* + * @file popup_manager.cpp + * @author Lukasz Wrzosek (l.wrzosek@samsung.com) + * @version 1.0 + * @brief This is popup_manager implementation file + */ + +#include "popup_manager.h" +#include <stddef.h> +#include <dpl/log/wrt_log.h> +#include <dpl/assert.h> +#include <dpl/singleton_impl.h> +#include "popup.h" + +IMPLEMENT_SINGLETON(Wrt::Popup::Renderer::PopupManager) + +namespace Wrt { +namespace Popup { +namespace Renderer { +void PopupManager::Initialize(PopupRendererPtr renderer) +{ + Assert(!m_initialized); + m_popupRenderer = renderer; + m_popupRenderer->Initialize(); + m_initialized = true; +} + +void PopupManager::Deinitialize() +{ + m_popupRenderer->Deinitialize(); + Assert(m_initialized); + m_popupRenderer.reset(); + m_initialized = false; +} + +IPopupPtr PopupManager::CreatePopup() +{ + Assert(m_initialized); + return m_popupRenderer->CreatePopup(); +} +} +} // namespace Popup +} // namespace Wrt diff --git a/src/wrt-popup/wrt/popup-bin/renderer/popup_manager.h b/src/wrt-popup/wrt/popup-bin/renderer/popup_manager.h new file mode 100644 index 0000000..a254d5c --- /dev/null +++ b/src/wrt-popup/wrt/popup-bin/renderer/popup_manager.h @@ -0,0 +1,117 @@ +/* + * 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 popup_manager.h + * @author Lukasz Wrzosek (l.wrzosek@samsung.com) + * @version 1.0 + * @brief This is popup_manager declaration file + */ + +#ifndef WRT_SRC_POPUP_POPUP_MANAGER_H_ +#define WRT_SRC_POPUP_POPUP_MANAGER_H_ + +#include <memory> +#include <dpl/assert.h> +#include <dpl/noncopyable.h> +#include <dpl/singleton.h> +#include <dpl/log/wrt_log.h> +#include "popup.h" +#include "popup_renderer.h" + +namespace Wrt { +namespace Popup { +namespace Renderer { +class PopupManager : DPL::Noncopyable +{ + template <class ArgType> + struct TemplatedPopupCallback + { + typedef void (*Type)(const AnswerCallbackData& answer, ArgType* data); + }; + + public: + PopupManager() : m_initialized(false) {} + ~PopupManager() + { + if (m_initialized) { + WrtLogE("Destroyed without Deinitialize"); + } + } + void Initialize (PopupRendererPtr creator); + void Deinitialize(); + void SetPopupRenderer (PopupRendererPtr creator); + IPopupPtr CreatePopup(); + + template <class ArgType> + void RunAsyncWithArgType( + IPopupPtr popup, + typename TemplatedPopupCallback<ArgType>::Type + callback, + ArgType* argument) + { + Assert(callback); + WrapCbAndArg<ArgType>* wrapped = + new WrapCbAndArg<ArgType>(callback, argument); + popup->Show(&CallbackArgTypeTranslator<ArgType>, wrapped); + } + + void Show(IPopupPtr popup, + IPopup::PopupCallbackType callback, + void* userdata) + { + popup->Show(callback, userdata); + } + + void setExternalCanvas(void* externalCanvas) + { + AssertMsg(m_initialized, "Manger should be initialized"); + m_popupRenderer->setExternalCanvas(externalCanvas); + } + + private: + template <class ArgType> + struct WrapCbAndArg + { + WrapCbAndArg(typename TemplatedPopupCallback<ArgType>::Type cb, + ArgType* arg) : + callback(cb), + argument(arg) + {} + + typename TemplatedPopupCallback<ArgType>::Type callback; + ArgType* argument; + }; + + template <class ArgType> + static void CallbackArgTypeTranslator(const AnswerCallbackData & answer, + void* data) + { + WrapCbAndArg<ArgType>* wrapped = + static_cast< WrapCbAndArg<ArgType>* >(data); + wrapped->callback(answer, wrapped->argument); + delete wrapped; + } + + bool m_initialized; + PopupRendererPtr m_popupRenderer; +}; + +typedef DPL::Singleton<PopupManager> PopupManagerSingleton; +} +} // namespace Popup +} // namespace Wrt + +#endif //WRT_SRC_POPUP_POPUP_MANAGER_H_ diff --git a/src/wrt-popup/wrt/popup-bin/renderer/popup_object.h b/src/wrt-popup/wrt/popup-bin/renderer/popup_object.h new file mode 100644 index 0000000..86f7484 --- /dev/null +++ b/src/wrt-popup/wrt/popup-bin/renderer/popup_object.h @@ -0,0 +1,170 @@ +/* + * 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 popup_object.h + * @author Justyna Mejzner (j.mejzner@samsung.com) + * @version 1.0 + * @brief This is declaration file of PopupObject + */ + +#ifndef WRT_SRC_POPUP_POPUPOBJECT_H_ +#define WRT_SRC_POPUP_POPUPOBJECT_H_ + +#include <dpl/foreach.h> + +#include <list> +#include <string> + +namespace Wrt { +namespace Popup { +namespace Renderer { +namespace PopupObject { +class IPopupObject; +class PopupObjectBase; +class Button; +class Label; +class Check; + +typedef std::list<IPopupObject*> PopupObjects; + +enum PopupType +{ + BUTTON, + LABEL, + CHECK +}; + +class IPopupObject +{ + public: + virtual Button* asButton() = 0; + virtual Label* asLabel() = 0; + virtual Check* asCheck() = 0; + virtual PopupType getType() const = 0; + virtual ~IPopupObject() + {} +}; + +class PopupObjectBase : public IPopupObject +{ + public: + virtual Button* asButton() + { + Assert("wrong type"); + return NULL; + } + virtual Label* asLabel() + { + Assert("wrong type"); + return NULL; + } + virtual Check* asCheck() + { + Assert("wrong type"); + return NULL; + } + + PopupType getType() const + { + return m_type; + } + + protected: + PopupObjectBase(PopupType type) : m_type(type) + {} + + PopupType m_type; +}; + +class Button : public PopupObjectBase +{ + public: + Button(const std::string& label, + int labelId) : + PopupObjectBase(BUTTON), + m_label(label), + m_labelId(labelId) + {} + + Button* asButton() + { + return this; + } + + const std::string& getLabel() const + { + return m_label; + } + + int getLabelId() const + { + return m_labelId; + } + + private: + std::string m_label; + int m_labelId; +}; + +class Label : public PopupObjectBase +{ + public: + Label(const std::string &label) : + PopupObjectBase(LABEL), + m_label(label) + {} + + Label* asLabel() + { + return this; + } + + const std::string& getLabel() const + { + return m_label; + } + + private: + std::string m_label; +}; + +class Check : public PopupObjectBase +{ + public: + Check(const std::string &label) : + PopupObjectBase(CHECK), + m_checkLabel(label) + {} + + Check* asCheck() + { + return this; + } + + const std::string& getCheckLabel() const + { + return m_checkLabel; + } + + private: + std::string m_checkLabel; +}; +} /*PopupObject*/ +} +} //namespace Popup +} //namespace Wrt + +#endif //WRT_SRC_POPUP_POPUPOBJECT_H_ diff --git a/src/wrt-popup/wrt/popup-bin/renderer/popup_renderer.cpp b/src/wrt-popup/wrt/popup-bin/renderer/popup_renderer.cpp new file mode 100644 index 0000000..609d3c1 --- /dev/null +++ b/src/wrt-popup/wrt/popup-bin/renderer/popup_renderer.cpp @@ -0,0 +1,423 @@ +/* + * 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 popup_renderer.cpp + * @author Lukasz Wrzosek (l.wrzosek@samsung.com) + * @version 1.0 + * @brief This is efl specific implementation for PopupRenderer + */ + +#include "popup_renderer.h" +#include <stddef.h> +#include <dpl/assert.h> +#include <dpl/log/wrt_log.h> +#include <dpl/foreach.h> +#include <dpl/framework_efl.h> +#include <dpl/lexical_cast.h> +#include <queue> +#include "popup_manager.h" +#include "popup_manager.h" +#include "evas_object.h" + +namespace Wrt { +namespace { +using namespace Popup; +const char* EDJ_NAME = "/usr/share/edje/ace/generic_popup.edj"; +const char* POPUP_LAYOUT1 = "popup_layout1"; +const char* POPUP_LAYOUT2 = "popup_layout2"; +const char* POPUP_PART_TITLE = "title,text"; +const char* POPUP_PART_BUTTON1 = "button1"; +const char* POPUP_PART_BUTTON2 = "button2"; +const char* POPUP_PART_BUTTON3 = "button3"; +const char* BUTTON_CLICKED_CALLBACK_NAME = "clicked"; +const char* CHANGED_CALLBACK_NAME = "changed"; +const unsigned int MAX_NUMBER_OF_VERTICAL = 2; + +Evas_Object* create_layout_main(Evas_Object* parent, int totalV) +{ + Evas_Object *layout = elm_layout_add(parent); + + if (totalV == 1) { + elm_layout_file_set(layout, EDJ_NAME, POPUP_LAYOUT1); + } else if (totalV == 2) { + elm_layout_file_set(layout, EDJ_NAME, POPUP_LAYOUT2); + } else { + Assert(!"popup needs define new group in the edc"); + } + + evas_object_size_hint_weight_set(layout, EVAS_HINT_EXPAND, + EVAS_HINT_EXPAND); + return layout; +} +} //namespace + +namespace Popup { +namespace Renderer { +class PopupRenderer::Impl +{ + public: + Impl() : + m_popupsToRender(), + m_current(), + m_initialized(false), + m_checkState(false), + m_themeIndexV(0), + m_externalCanvas(NULL) + {} + + ~Impl() + { + if (m_initialized) { + WrtLogE("Destroyed without Deinitialize"); + } + } + + void Initialize() + { + Assert(!m_initialized); + m_initialized = true; + } + + void Deinitialize() + { + Assert(m_initialized); + m_current.reset(); + while (!m_popupsToRender.empty()) { + m_popupsToRender.pop(); + } + m_initialized = false; + } + + void ButtonCallback(EvasObject::IConnection* /*connection*/, + void* /*event_info*/, + void* data) + { + WrtLogD("ButtonCallback"); + Assert(m_initialized); + AnswerCallbackData answerData; + + answerData.buttonAnswer = reinterpret_cast<int>(data); + answerData.chackState = m_checkState; + answerData.password = m_password; + m_current->ForwardAnswer(answerData); + m_current.reset(); + + FOREACH(it, m_createdObjects) + { + if (it->IsValid()) { + evas_object_del(*it); + } + } + m_createdObjects.clear(); + m_checkState = false; + DoRender(); + } + + void CheckCallback(EvasObject::IConnection* connection, + void* /*event_info*/, + void* /* unused */) + { + m_checkState = + elm_check_state_get(connection->GetEvasObject()); + } + + void Render (PopupPtr popup) + { + Assert(m_initialized); + m_popupsToRender.push(popup); + DoRender(); + } + + void DoRender(const PopupObject::Label& object, + EvasObject& parent, + EvasObject& layout, + int themeIndex) + { + EvasObject label(elm_label_add(parent)); + + elm_object_style_set(label, "popup_description/default"); + elm_label_line_wrap_set(label, ELM_WRAP_WORD); + elm_object_text_set(label, object.getLabel().c_str()); + evas_object_size_hint_weight_set(label, EVAS_HINT_EXPAND, 0.0); + evas_object_size_hint_align_set(label, EVAS_HINT_FILL, EVAS_HINT_FILL); + evas_object_show(label); + + elm_object_part_content_set( + layout, + DPL::lexical_cast<std::string>(themeIndex).c_str(), + label); + m_createdObjects.push_back(label); + } + + void DoRender(const PopupObject::Check& object, + EvasObject& parent, + EvasObject& layout, + int themeIndex) + { + EvasObject check(elm_check_add(parent)); + + evas_object_size_hint_align_set(check, EVAS_HINT_FILL, EVAS_HINT_FILL); + evas_object_size_hint_weight_set(check, EVAS_HINT_EXPAND, 0.0); + elm_object_text_set(check, + object.getCheckLabel().c_str()); + elm_object_part_content_set( + layout, + DPL::lexical_cast<std::string>(themeIndex).c_str(), + check); + + check.ConnectMemberSmartCallback(CHANGED_CALLBACK_NAME, + &Impl::CheckCallback, + this, + static_cast<void*>(NULL)); + evas_object_show(check); + m_createdObjects.push_back(check); + } + + void DoRender(const PopupObject::Button& object, + EvasObject &parent) + { + EvasObject btn(elm_button_add(parent)); + + elm_object_style_set(btn, "popup"); + elm_object_text_set(btn, object.getLabel().c_str()); + elm_object_part_content_set(parent, POPUP_PART_BUTTON1, btn); + btn.ConnectMemberSmartCallback(BUTTON_CLICKED_CALLBACK_NAME, + &Impl::ButtonCallback, + this, + reinterpret_cast<void*>(object. + getLabelId())); + m_createdObjects.push_back(btn); + } + + void DoRender(const PopupObject::Button& object1, + const PopupObject::Button& object2, + EvasObject &parent) + { + DoRender(object1, parent); + + EvasObject btn2(elm_button_add(parent)); + + elm_object_style_set(btn2, "popup"); + elm_object_text_set(btn2, object2.getLabel().c_str()); + elm_object_part_content_set(parent, POPUP_PART_BUTTON2, btn2); + btn2.ConnectMemberSmartCallback(BUTTON_CLICKED_CALLBACK_NAME, + &Impl::ButtonCallback, + this, + reinterpret_cast<void*>(object2. + getLabelId())); + m_createdObjects.push_back(btn2); + } + + void DoRender(const PopupObject::Button& object1, + const PopupObject::Button& object2, + const PopupObject::Button& object3, + EvasObject &parent) + { + DoRender(object1, object2, parent); + + EvasObject btn3(elm_button_add(parent)); + + elm_object_style_set(btn3, "popup"); + elm_object_text_set(btn3, object3.getLabel().c_str()); + elm_object_part_content_set(parent, POPUP_PART_BUTTON3, btn3); + btn3.ConnectMemberSmartCallback(BUTTON_CLICKED_CALLBACK_NAME, + &Impl::ButtonCallback, + this, + reinterpret_cast<void*>(object3. + getLabelId())); + m_createdObjects.push_back(btn3); + } + + EvasObject getBaseObject() + { + if (getExternalCanvas() == NULL) { + WrtLogD("Create old style popup"); + EvasObject win(elm_win_add(NULL, "Popup", ELM_WIN_DIALOG_BASIC)); + elm_win_borderless_set(win, EINA_TRUE); + elm_win_alpha_set(win, EINA_TRUE); + elm_win_raise(win); + { + int w, h, x, y; + ecore_x_window_geometry_get(ecore_x_window_root_first_get(), + &x, + &y, + &w, + &h); + evas_object_resize(win, w, h); + evas_object_move(win, x, y); + } + m_createdObjects.push_back(win); + evas_object_show(win); + return win; + } else { + WrtLogD("Create new style popup"); + EvasObject win(getExternalCanvas()); + evas_object_show(win); + return win; + } + } + + void DoRender() + { + if (!m_current && !m_popupsToRender.empty()) { + m_current = m_popupsToRender.front(); + m_popupsToRender.pop(); + + m_themeIndexV = 0; + + // preprocessing + std::vector<int> countPopupObjects = { 0 /* PopupObject::BUTTON */, + 0 /* PopupObject::LABEL */, + 0 /* PopupObject::CHECK */ }; + FOREACH(it, m_current->GetPopupObjects()) { + AssertMsg((*it)->getType() < countPopupObjects.size(), + "Wrong PopupObject assigned"); + countPopupObjects[(*it)->getType()]++; + } + int needsIndexV = countPopupObjects[PopupObject::LABEL] + + countPopupObjects[PopupObject::CHECK]; + + EvasObject win = getBaseObject(); + EvasObject main(elm_popup_add(win)); + + evas_object_size_hint_weight_set(main, + EVAS_HINT_EXPAND, + EVAS_HINT_EXPAND); + elm_object_part_text_set(main, + POPUP_PART_TITLE, + m_current->GetTitle().c_str()); + + m_createdObjects.push_back(main); + std::vector<PopupObject::Button> buttonObjectList; + EvasObject layout(create_layout_main(main, needsIndexV)); + m_createdObjects.push_back(layout); + + FOREACH(it, m_current->GetPopupObjects()) { + switch ((*it)->getType()) { + case PopupObject::BUTTON: + buttonObjectList.push_back(*(*it)->asButton()); + break; + case PopupObject::LABEL: + DoRender(*(*it)->asLabel(), + main, + layout, + m_themeIndexV++); + break; + case PopupObject::CHECK: + DoRender(*(*it)->asCheck(), + main, + layout, + m_themeIndexV++); + break; + default: + Assert(!"incorrect type"); + } + Assert(m_themeIndexV <= MAX_NUMBER_OF_VERTICAL); + } + elm_object_content_set(main, + layout); + + // show buution + switch (buttonObjectList.size()) { + case 0: + WrtLogD("no button"); + break; + case 1: + DoRender(buttonObjectList.at(0), + main); + break; + case 2: + DoRender(buttonObjectList.at(0), + buttonObjectList.at(1), + main); + break; + case 3: + DoRender(buttonObjectList.at(0), + buttonObjectList.at(1), + buttonObjectList.at(2), + main); + break; + default: + Assert(!"incorrect button number"); + break; + } + + evas_object_show(main); + } + } + + void setExternalCanvas(void* externalCanvas) + { + m_externalCanvas = static_cast<Evas_Object*>(externalCanvas); + } + + Evas_Object* getExternalCanvas() const + { + return m_externalCanvas; + } + + std::queue<PopupPtr> m_popupsToRender; + std::list<EvasObject> m_createdObjects; + PopupPtr m_current; + bool m_initialized; + bool m_checkState; + DPL::OptionalStdString m_password; + unsigned int m_themeIndexV; + + private: + Evas_Object* m_externalCanvas; +}; + +PopupRenderer::PopupRenderer() +{ + m_impl = new PopupRenderer::Impl(); +} + +PopupRenderer::~PopupRenderer() +{ + delete m_impl; +} + +void PopupRenderer::Initialize() +{ + Assert(m_impl); + m_impl->Initialize(); +} + +void PopupRenderer::Deinitialize() +{ + Assert(m_impl); + m_impl->Deinitialize(); +} + +IPopupPtr PopupRenderer::CreatePopup() +{ + return std::static_pointer_cast<IPopup>(IPopupPtr + (new Popup(shared_from_this()))); +} + +void PopupRenderer::Render(PopupPtr popup) +{ + m_impl->Render(popup); +} + +void PopupRenderer::setExternalCanvas(void* externalCanvas) +{ + m_impl->setExternalCanvas(externalCanvas); +} +} +} // namespace Popup +} // namespace Wrt diff --git a/src/wrt-popup/wrt/popup-bin/renderer/popup_renderer.h b/src/wrt-popup/wrt/popup-bin/renderer/popup_renderer.h new file mode 100644 index 0000000..98eeb05 --- /dev/null +++ b/src/wrt-popup/wrt/popup-bin/renderer/popup_renderer.h @@ -0,0 +1,127 @@ +/* + * 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 popup_renderer.h + * @author Lukasz Wrzosek (l.wrzosek@samsung.com) + * @version 1.0 + * @brief This is declaration file of PopupRenderer + */ + +#ifndef WRT_SRC_POPUP_POPUP_RENDERER_H_ +#define WRT_SRC_POPUP_POPUP_RENDERER_H_ + +#include <map> +#include <string> +#include <memory> + +#include <dpl/noncopyable.h> +#include <dpl/log/wrt_log.h> +#include <dpl/assert.h> +#include <dpl/foreach.h> +#include "popup.h" + +namespace Wrt { +namespace Popup { +namespace Renderer { +class PopupRenderer : public std::enable_shared_from_this<PopupRenderer> +{ + public: + PopupRenderer(); + ~PopupRenderer(); + void Initialize(); + void Deinitialize(); + IPopupPtr CreatePopup(); + virtual void setExternalCanvas(void* externalCanvas); + + protected: + class Popup; + typedef std::shared_ptr<Popup> PopupPtr; + + class Popup : public IPopup + { + public: + typedef std::map<int, std::string> ButtonMap; + virtual void SetTitle(const std::string &title) + { + WrtLogD("%s", title.c_str()); + Assert(m_title.empty()); + m_title = title; + } + + virtual void Append(PopupObject::IPopupObject *object) + { + m_popupObjectList.push_back(object); + } + + virtual void Show(IPopup::PopupCallbackType callback, + void* data) + { + Assert(callback); + m_data = data; + m_callback = callback; + m_renderer->Render(std::static_pointer_cast<Popup>(shared_from_this())); + } + + const std::string& GetTitle() const + { + return m_title; + } + + PopupObject::PopupObjects& GetPopupObjects() + { + return m_popupObjectList; + } + + virtual ~Popup() + { + FOREACH(it, m_popupObjectList) { + delete *it; + } + } + + private: + friend class PopupRenderer; + friend class std::shared_ptr<Popup>; + friend class PopupObjectTheme; + + Popup(std::shared_ptr<PopupRenderer> renderer) : m_renderer(renderer) + {} + + void ForwardAnswer(const AnswerCallbackData & answer) const + { + m_callback(answer, m_data); + } + + std::string m_title; + void* m_data; + IPopup::PopupCallbackType m_callback; + PopupObject::PopupObjects m_popupObjectList; + std::shared_ptr<PopupRenderer> m_renderer; + }; + + private: + void Render (PopupPtr popup); + + class Impl; + Impl* m_impl; +}; + +typedef std::shared_ptr<PopupRenderer> PopupRendererPtr; +} +} // namespace Popup +} // namespace Wrt + +#endif //WRT_SRC_POPUP_POPUP_RENDERER_H_ diff --git a/src/wrt-popup/wrt/popup-bin/wrt-popup.cpp b/src/wrt-popup/wrt/popup-bin/wrt-popup.cpp new file mode 100644 index 0000000..330da9c --- /dev/null +++ b/src/wrt-popup/wrt/popup-bin/wrt-popup.cpp @@ -0,0 +1,189 @@ +/* + * 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 "wrt-popup.h" +#include <limits> +#include <memory> + +#include <aul.h> +#include <dpl/log/wrt_log.h> +#include <dpl/exception.h> +#include <dpl/assert.h> + +#include "PopupEnum.h" +#include "PopupSerializer.h" +#include "InfoPopup.h" +#include "YesNoCheckPopup.h" + +namespace Wrt { +namespace Popup { +bool WrtPopup::openPipes() +{ + Try + { + if (m_argc != 3) { + WrtLogE("Wrong arguments!"); + return false; + } + m_input.Open(m_argv[1]); + //open output pipe + m_output.Open(m_argv[2]); + + DPL::WaitableHandleWatchSupport::InheritedContext()-> + AddWaitableHandleWatch(this, + m_input.WaitableReadHandle(), + DPL::WaitMode::Read); + m_pipesOpened = true; + return true; + } + Catch(DPL::Exception) + { + WrtLogE("cannot open pipes"); + } + return false; +} + +void WrtPopup::closePipes() +{ + Try + { + if (m_pipesOpened) { + DPL::WaitableHandleWatchSupport::InheritedContext()-> + RemoveWaitableHandleWatch(this, + m_input.WaitableReadHandle(), + DPL::WaitMode::Read); + m_input.Close(); + m_output.Close(); + m_pipesOpened = false; + } + } + Catch(DPL::Exception) + { + WrtLogE("cannot close pipes"); + } +} + +void WrtPopup::OnEventReceived(const QuitEvent & /* event */) +{ + WrtLogD("Quiting"); + closePipes(); + Quit(); +} + +void WrtPopup::OnWaitableHandleEvent(DPL::WaitableHandle waitableHandle, + DPL::WaitMode::Type /*mode*/) +{ + if (waitableHandle == m_input.WaitableReadHandle()) { + readInputData(); + } +} + +void WrtPopup::readInputData() +{ + DPL::BinaryQueueAutoPtr data = + m_input.Read(std::numeric_limits<std::size_t>::max()); + int popupType = PopupSerializer::getIntArg(*data); + WrtLogD("popup type %d", popupType); + switch (popupType) { + case INFO_PROMPT: + m_popup.reset(new InfoPopup()); + m_popup->show(data, this); + break; + case YES_NO_CHECK_PROMPT: + m_popup.reset(new YesNoCheckPopup()); + m_popup->show(data, this); + break; + default: + Assert(false); + } +} + +void WrtPopup::response(DPL::BinaryQueue result) +{ + m_output.Write(result, result.Size()); + PostEvent(QuitEvent()); +} + +void WrtPopup::OnStop() +{ + WrtLogD("On Stop"); +} + +void WrtPopup::OnCreate() +{ + if (!openPipes()) { + PostEvent(QuitEvent()); + } + WrtLogD("On Create"); +} + +void WrtPopup::OnResume() +{ + WrtLogD("OnResume"); +} + +void WrtPopup::OnPause() +{ + WrtLogD("OnPause"); +} + +void WrtPopup::OnReset(bundle * /*b*/) +{ + WrtLogD("OnReset"); +} + +void WrtPopup::OnTerminate() +{ + WrtLogD("Wrt Shutdown now"); +} + +WrtPopup::WrtPopup(int argc, char **argv) : + Application(argc, argv, "wrt-popup", false), + m_pipesOpened(false) +{ + Touch(); + Renderer::PopupControllerSingleton::Instance().Touch(); + Renderer::PopupManagerSingleton::Instance().Initialize( + Renderer::PopupRendererPtr(new Renderer::PopupRenderer)); + WrtLogD("App Created"); +} + +WrtPopup::~WrtPopup() +{ + Renderer::PopupManagerSingleton::Instance().Deinitialize(); + WrtLogD("App Finished"); +} +} +} + +int main(int argc, char *argv[]) +{ + UNHANDLED_EXCEPTION_HANDLER_BEGIN + { + // Output on stdout will be flushed after every newline character, + // even if it is redirected to a pipe. This is useful for running + // from a script and parsing output. + // (Standard behavior of stdlib is to use full buffering when + // redirected to a pipe, which means even after an end of line + // the output may not be flushed). + setlinebuf(stdout); + + Wrt::Popup::WrtPopup app(argc, argv); + int ret = app.Exec(); + WrtLogD("App returned: %d", ret); + return ret; + } + UNHANDLED_EXCEPTION_HANDLER_END +} diff --git a/src/wrt-popup/wrt/popup-bin/wrt-popup.h b/src/wrt-popup/wrt/popup-bin/wrt-popup.h new file mode 100644 index 0000000..ab9c519 --- /dev/null +++ b/src/wrt-popup/wrt/popup-bin/wrt-popup.h @@ -0,0 +1,87 @@ +/* + * 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 WRT_POPUP_H +#define WRT_POPUP_H + +#include <memory> +#include <dpl/application.h> +#include <dpl/generic_event.h> +#include <dpl/event/controller.h> +#include <dpl/type_list.h> +#include <dpl/named_input_pipe.h> +#include <dpl/named_output_pipe.h> +#include <dpl/waitable_handle_watch_support.h> +#include <dpl/binary_queue.h> +#include "popup_controller.h" + +namespace Wrt { +namespace Popup { +DECLARE_GENERIC_EVENT_0(QuitEvent) +class WrtPopup; + +class IPopup : public Renderer::PopupControllerUser +{ + public: + virtual void show(DPL::BinaryQueueAutoPtr data, WrtPopup* parent) = 0; + virtual ~IPopup() {} +}; + +typedef std::unique_ptr<IPopup> IPopupPtr; + +class WrtPopup : + public DPL::WaitableHandleWatchSupport::WaitableHandleListener, + public DPL::Application, + private DPL::Event::Controller<DPL::TypeListDecl<QuitEvent>::Type> +{ + public: + WrtPopup(int argc, char **argv); + virtual ~WrtPopup(); + + void response(DPL::BinaryQueue result); + + protected: + //DPL::Application functions + virtual void OnStop(); + virtual void OnCreate(); + virtual void OnResume(); + virtual void OnPause(); + virtual void OnReset(bundle *b); + virtual void OnTerminate(); + virtual void OnEventReceived(const QuitEvent &event); + virtual void OnWaitableHandleEvent(DPL::WaitableHandle waitableHandle, + DPL::WaitMode::Type mode); + + private: + + void showAcePrompt(DPL::BinaryQueueAutoPtr data); + void communicationBoxResponse(int buttonAnswer, + bool checkState, + void* userdata); + bool m_pipesOpened; + IPopupPtr m_popup; + + bool openPipes(); + void closePipes(); + void readInputData(); + + DPL::NamedInputPipe m_input; + DPL::NamedOutputPipe m_output; +}; +} +} + +#endif // WRT_POPUP_H diff --git a/src/wrt-popup/wrt/popup-runner/CMakeLists.txt b/src/wrt-popup/wrt/popup-runner/CMakeLists.txt new file mode 100644 index 0000000..24970e1 --- /dev/null +++ b/src/wrt-popup/wrt/popup-runner/CMakeLists.txt @@ -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. +# +# +# @file CMakeLists.txt +# @author Lukasz Marek (l.marek@samsung.com) +# +# @version 1.0 +# + +PKG_CHECK_MODULES(WRT_POPUP_RUNNER_LIB_DEP + dpl-efl + REQUIRED +) + +SET(WRT_POPUP_RUNNER_LIB_SRC_DIR ${PROJECT_SOURCE_DIR}/src/wrt-popup/wrt/popup-runner) + +SET(WRT_POPUP_RUNNER_LIB_SOURCES + ${WRT_POPUP_COMMON_SRCS} + ${WRT_POPUP_RUNNER_LIB_SRC_DIR}/PopupInvoker.cpp +) + +ADD_DEFINITIONS(${WRT_POPUP_RUNNER_LIB_DEP_CFLAGS}) + +INCLUDE_DIRECTORIES( + ${WRT_POPUP_RUNNER_LIB_SRC_DIR} + ${WRT_POPUP_RUNNER_LIB_DEP_INCLUDE_DIRS} + ${WRT_POPUP_COMMON_DIR} +) + +ADD_LIBRARY(${TARGET_POPUP_WRT_RUNNER_LIB} SHARED + ${WRT_POPUP_RUNNER_LIB_SOURCES} +) + +SET_TARGET_PROPERTIES(${TARGET_POPUP_WRT_RUNNER_LIB} PROPERTIES + COMPILE_DEFINITIONS LOG_TAG="${LOG_TAG}") + +SET_TARGET_PROPERTIES(${TARGET_POPUP_WRT_RUNNER_LIB} PROPERTIES + COMPILE_FLAGS -fPIC +) + +SET_TARGET_PROPERTIES(${TARGET_POPUP_WRT_RUNNER_LIB} PROPERTIES + SOVERSION ${CMAKE_PROJECT_API_VERSION} + VERSION ${CMAKE_PROJECT_VERSION} +) + +TARGET_LINK_LIBRARIES(${TARGET_POPUP_WRT_RUNNER_LIB} + ${WRT_POPUP_RUNNER_LIB_DEP_LIBRARIES} + ${WRT_POPUP_RUNNER_LIB_DEP_LDFLAGS} +) + +INSTALL(TARGETS ${TARGET_POPUP_WRT_RUNNER_LIB} + DESTINATION lib +) + +INSTALL(FILES ${WRT_POPUP_RUNNER_LIB_SRC_DIR}/PopupInvoker.h + DESTINATION ${DESTINATION_HEADERS_WRT_POPUP_RUNNER} +) diff --git a/src/wrt-popup/wrt/popup-runner/PopupInvoker.cpp b/src/wrt-popup/wrt/popup-runner/PopupInvoker.cpp new file mode 100644 index 0000000..01996ef --- /dev/null +++ b/src/wrt-popup/wrt/popup-runner/PopupInvoker.cpp @@ -0,0 +1,203 @@ +/* + * 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 "PopupInvoker.h" +#include <sstream> +#include <limits> +#include <unistd.h> +#include <stdio.h> +#include <dpl/log/wrt_log.h> +#include <dpl/assert.h> +#include <dpl/waitable_handle.h> +#include <dpl/binary_queue.h> +#include <dpl/serialization.h> +#include <dpl/exception.h> +#include <unistd.h> +#include <stdlib.h> +#include "PopupEnum.h" +#include "PopupSerializer.h" + +namespace { +const char *POPUP_EXEC = "/usr/bin/wrt-popup-wrt-runtime"; +} + +namespace Wrt { +namespace Popup { +PopupInvoker::PopupInvoker() +{ + char tmp[L_tmpnam + 1]; + if (NULL == tmpnam(tmp)) + ThrowMsg(DPL::Exception, "Failed to get pipe name"); + m_inputName = tmp; + + if (NULL == tmpnam(tmp)) + ThrowMsg(DPL::Exception, "Failed to get pipe name"); + m_outputName = tmp; + + m_input.Create(m_inputName); + m_output.Create(m_outputName); + WrtLogD("Pipes created"); +} + +PopupInvoker::~PopupInvoker() +{ + Try + { + m_input.Destroy(m_inputName); + m_output.Destroy(m_outputName); + WrtLogD("Pipes destroyed"); + } + Catch(DPL::Exception) + { + WrtLogE("Cannot destroy pipes"); + } +} + +void PopupInvoker::showInfo(const std::string& title, + const std::string& message, + const std::string& buttonLabel) +{ + WrtLogD("Entered"); + Try + { + DPL::BinaryQueue data; + PopupSerializer::appendArg(INFO_PROMPT, data); + PopupSerializer::appendArg(title, data); + PopupSerializer::appendArg(message, data); + PopupSerializer::appendArg(buttonLabel, data); + DPL::NamedInputPipe tmp; + tmp.Open(m_outputName); + m_output.Open(m_outputName); + m_input.Open(m_inputName); + m_output.Write(data, data.Size()); + + executePopup(); + DPL::BinaryQueueAutoPtr resultData = + m_input.Read(std::numeric_limits<std::size_t>::max()); + const int success = PopupSerializer::getIntArg(*resultData); + if (!success) { + WrtLogW("Failed to show popup."); + } + //ignore result + + tmp.Close(); + m_input.Close(); + m_output.Close(); + } + Catch(DPL::Exception) + { + WrtLogE("error occured"); + } +} + +PopupResponse PopupInvoker::askYesNoCheckbox(const std::string& title, + const std::string& message, + const std::string& checkboxLabel) +{ + Try + { + DPL::BinaryQueue data; + PopupSerializer::appendArg(YES_NO_CHECK_PROMPT, data); + PopupSerializer::appendArg(title, data); + PopupSerializer::appendArg(message, data); + PopupSerializer::appendArg(checkboxLabel, data); + DPL::NamedInputPipe tmp; + tmp.Open(m_outputName); + m_output.Open(m_outputName); + m_input.Open(m_inputName); + m_output.Write(data, data.Size()); + + executePopup(); + + //Result from popup application is available. Read it. + DPL::BinaryQueueAutoPtr resultData = + m_input.Read(std::numeric_limits<std::size_t>::max()); + const int success = PopupSerializer::getIntArg(*resultData); + if (success) { + const int result = PopupSerializer::getIntArg(*resultData); + const int rememberResult = PopupSerializer::getIntArg(*resultData); + + WrtLogD("Popup result is: %d remeber: %d", result, rememberResult); + + Assert(resultData->Empty()); + tmp.Close(); + m_input.Close(); + m_output.Close(); + + if (1 == result) { + if (rememberResult == 1) { + return YES_DO_REMEMBER; + } else { + return YES_DONT_REMEMBER; + } + } else { + if (rememberResult == 1) { + return NO_DO_REMEMBER; + } else { + return NO_DONT_REMEMBER; + } + } + } else { + WrtLogW("Popup failed to execute."); + tmp.Close(); + m_input.Close(); + m_output.Close(); + return NO_DONT_REMEMBER; + } + } + Catch(DPL::Exception) + { + WrtLogE("error occured"); + } + return NO_DONT_REMEMBER; +} + +void PopupInvoker::executePopup() +{ + WrtLogD("entered"); + pid_t pid = fork(); + if (pid == -1) { + //error occured + WrtLogE("Failed to create popup process."); + Assert(false); + } + if (pid == 0) { + //child process + int ret = execl(POPUP_EXEC, + POPUP_EXEC, + m_outputName.c_str(), + m_inputName.c_str(), + NULL); + if (ret == -1) { + //execl returns -1 on error + WrtLogE("Failed to set popup binary"); + //write something to pipe to unblock caller process + DPL::NamedOutputPipe errOut; + errOut.Open(m_inputName); + DPL::BinaryQueue data; + PopupSerializer::appendArg(false, data); + errOut.Write(data, data.Size()); + errOut.Close(); + + Assert(false); + } + } + + DPL::WaitableHandle handle = m_input.WaitableReadHandle(); + DPL::WaitForSingleHandle(handle); +} +} // Popup +} // Wrt diff --git a/src/wrt-popup/wrt/popup-runner/PopupInvoker.h b/src/wrt-popup/wrt/popup-runner/PopupInvoker.h new file mode 100644 index 0000000..d7662a1 --- /dev/null +++ b/src/wrt-popup/wrt/popup-runner/PopupInvoker.h @@ -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. + */ + +#ifndef WRT_POPUP_INVOKER_H +#define WRT_POPUP_INVOKER_H + +#include <string> + +#include <dpl/named_input_pipe.h> +#include <dpl/named_output_pipe.h> + +/* + * + * Example usage: + * + * bool result = PopupInvoker().askYesNoCheckbox("title", "message", "lable for checkbox"); + * + */ + +namespace Wrt { +namespace Popup { +enum PopupResponse { + NO_DO_REMEMBER, + NO_DONT_REMEMBER, + YES_DONT_REMEMBER, + YES_DO_REMEMBER +}; + +class PopupInvoker +{ + public: + class Exception + { + public: + DECLARE_EXCEPTION_TYPE(DPL::Exception, Base) + DECLARE_EXCEPTION_TYPE(Base, PopupInvokerException) + }; + + PopupInvoker(); + ~PopupInvoker(); + + void showInfo(const std::string &title, + const std::string &message, + const std::string &buttonLabel = std::string("OK")); + PopupResponse askYesNoCheckbox(const std::string& title, + const std::string& message, + const std::string& checkboxLabel); + + private: + + void executePopup(); + + DPL::NamedInputPipe m_input; + DPL::NamedOutputPipe m_output; + std::string m_inputName; + std::string m_outputName; +}; +} // Popup +} // Wrt + +#endif diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt new file mode 100644 index 0000000..fb83283 --- /dev/null +++ b/tests/CMakeLists.txt @@ -0,0 +1,22 @@ +# Copyright (c) 2012 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 CMakeLists.txt +# @author Lukasz Marek (l.marek@samsung.com) +# + +INCLUDE(CMakeUtils.txt) + +ADD_SUBDIRECTORY(dao) +ADD_SUBDIRECTORY(Commons)
\ No newline at end of file diff --git a/tests/CMakeUtils.txt b/tests/CMakeUtils.txt new file mode 100644 index 0000000..028c4bc --- /dev/null +++ b/tests/CMakeUtils.txt @@ -0,0 +1,71 @@ +# @file CMakeUtils.txt +# @author Zbigniew Kostrzewa (z.kostrzewa@samsung.com) +# @author Pawel Sikorski (p.sikorski@samsung.com) +# @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com) +# @version 1.0 +# @brief +# + +# +# Replacement functions for standard (w/o "WRT_" prefix) CMake functions. +# They store supplied arguments in global properties to assign them to tests. +FUNCTION(WRT_INCLUDE_DIRECTORIES) + SET_PROPERTY(GLOBAL APPEND PROPERTY TESTS_INCLUDE_DIRS ${ARGV}) +ENDFUNCTION(WRT_INCLUDE_DIRECTORIES) + +FUNCTION(WRT_LINK_DIRECTORIES) + SET_PROPERTY(GLOBAL APPEND PROPERTY TESTS_LIBRARY_DIRS ${ARGV}) +ENDFUNCTION(WRT_LINK_DIRECTORIES) + +FUNCTION(WRT_TARGET_LINK_LIBRARIES) + SET_PROPERTY(GLOBAL APPEND PROPERTY TESTS_LIBRARIES ${ARGV}) +ENDFUNCTION(WRT_TARGET_LINK_LIBRARIES) + +FUNCTION(WRT_TEST_LIBRARY) + SET_PROPERTY(GLOBAL APPEND PROPERTY COMMON_TESTS_LIBRARY ${ARGV}) +ENDFUNCTION(WRT_TEST_LIBRARY) + +# Functions used to build test targets (proper sources, includes, libs are +# added automatically) +FUNCTION(WRT_TEST_BUILD TARGET_NAME) + SET(SOURCES "${ARGN}") + ADD_EXECUTABLE("${TARGET_NAME}" + ${SOURCES} + ) + # get include dirs global property + GET_PROPERTY(INCLUDE_DIRS GLOBAL PROPERTY TESTS_INCLUDE_DIRS) + INCLUDE_DIRECTORIES( + ${INCLUDE_DIRS} + ) + # get library dirs global property + GET_PROPERTY(LIBRARY_DIRS GLOBAL PROPERTY TESTS_LIBRARY_DIRS) + LINK_DIRECTORIES( + ${LIBRARY_DIRS} + ) + # get link libraries global property + GET_PROPERTY(LINK_LIBRARIES GLOBAL PROPERTY TESTS_LIBRARIES) + GET_PROPERTY(TEST_LIBRARY GLOBAL PROPERTY COMMON_TESTS_LIBRARY) + TARGET_LINK_LIBRARIES("${TARGET_NAME}" + ${TEST_LIBRARY} + ${LINK_LIBRARIES} + ) + SET_TARGET_PROPERTIES(${TARGET_NAME} PROPERTIES + COMPILE_DEFINITIONS LOG_TAG="${LOG_TAG}") +ENDFUNCTION(WRT_TEST_BUILD) + +FUNCTION(WRT_TEST_INSTALL) + SET_TARGET_PROPERTIES(${ARGV} PROPERTIES + BUILD_WITH_INSTALL_RPATH ON + INSTALL_RPATH_USE_LINK_PATH ON + ) + INSTALL(TARGETS ${ARGV} + DESTINATION bin + PERMISSIONS OWNER_READ + OWNER_WRITE + OWNER_EXECUTE + GROUP_READ + GROUP_EXECUTE + WORLD_READ + WORLD_EXECUTE + ) +ENDFUNCTION(WRT_TEST_INSTALL) diff --git a/tests/Commons/Base64_test.cpp b/tests/Commons/Base64_test.cpp new file mode 100644 index 0000000..afa1a1c --- /dev/null +++ b/tests/Commons/Base64_test.cpp @@ -0,0 +1,249 @@ +/* + * Copyright (c) 2014 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 Base64_test.cpp + * @author Grzegorz Rynkowski (g.rynkowski@samsung.com) + * @brief This file contains tests for Base64 + */ + +#include <Commons/Base64.h> +#include <Commons/Exception.h> +#include <dpl/log/secure_log.h> +#include <dpl/test/test_runner.h> +#include <cstring> +#include <memory> +#include <random> +#include <set> +#include <string> +#include <type_traits> + +using namespace WrtDeviceApis::Commons; + +namespace { +struct TextPair { + TextPair(std::string&& decoded_, std::string&& encoded_) + { + std::swap(decoded_, decoded); + std::swap(encoded_, encoded); + } + std::string decoded, encoded; + + static const std::vector<TextPair>& examples() + { + static std::vector<TextPair> vec = { + TextPair( + "Man is distinguished, not only by his reason, but by this sing" + "ular passion from other animals, which is a lust of the mind, " + "that by a perseverance of delight in the continued and indefat" + "igable generation of knowledge, exceeds the short vehemence of" + " any carnal pleasure.", + "TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIG" + "J1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxz" + "LCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZX" + "ZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0" + "aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG" + "9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4="), + TextPair("f", "Zg=="), + TextPair("fo" , "Zm8="), + TextPair("foo" , "Zm9v"), + TextPair("foob" , "Zm9vYg=="), + TextPair("fooba" , "Zm9vYmE=") + }; + return vec; + } +}; + +template<typename T> +std::unique_ptr<T[]> convertStringToPtr(const std::string& str) +{ + static_assert(std::is_same<unsigned char, T>::value + || std::is_same<char, T>::value, + "std::string is able convert into char[] or unsigned char[]"); + std::unique_ptr<T[]> textCopy(new T[str.length() + 1]); + std::memcpy(textCopy.get(), str.c_str(), str.length() + 1); + return std::move(textCopy); +} + +#define CheckEncodeMsg(original_, encoded_, msg) { \ + std::string original(original_), encoded(encoded_); \ + std::string methodResult = Base64::encode( \ + convertStringToPtr<unsigned char>(original).get(), \ + original.length()); \ + if (!(methodResult == encoded)) { \ + WrtLogD("Encoded text = \"%s\"", encoded.c_str()); \ + WrtLogD("Base64::encode() = \"%s\"", methodResult.c_str()); \ + RUNNER_ASSERT(false); \ + } \ +} +#define CheckEncode(original, encoded) CheckEncodeMsg(original, encoded, "") + +#define CheckDecodeMsg(encoded_, decoded_, msg) { \ + std::string encoded(encoded_), decoded(decoded_); \ + std::string methodResult = Base64::decode(encoded); \ + if (!(methodResult == decoded)) { \ + WrtLogD("Decoded text = \"%s\"", decoded.c_str()); \ + WrtLogD("Base64::decode() = \"%s\"", methodResult.c_str()); \ + RUNNER_ASSERT(methodResult == decoded); \ + } \ +} +#define CheckDecode(original, decoded) CheckDecodeMsg(original, decoded, "") + +const std::set<char> base64chars = { + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', + 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', + 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', + 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'}; + +} // unnamed namespace + + +RUNNER_TEST_GROUP_INIT(Base64) + +/* +Name: base64_test_encode +Description: Tests encoding of examples +Expected: Base64::encode should encode examples correctly. +*/ +RUNNER_TEST(base64_test_encode) +{ + for (auto& i : TextPair::examples()) + CheckEncode(i.decoded, i.encoded); +} + +/* +Name: base64_test_encode_empty +Description: Tests encoding of empty string +Expected: Base64::encode should return empty string too +*/ +RUNNER_TEST(base64_test_encode_empty) +{ + CheckEncodeMsg("", "", "Encoded of empty string should be empty too."); +} + +/* +Name: base64_test_decode +Description: Tests decoding of examples +Expected: Base64::encode should decode examples correctly. +*/ +RUNNER_TEST(base64_test_decode) +{ + for (auto& i : TextPair::examples()) + CheckDecode(i.encoded, i.decoded); +} + +/* +Name: base64_test_decode_empty +Description: Tests decoding of empty string +Expected: Base64::decode should return empty string too +*/ +RUNNER_TEST(base64_test_decode_empty) +{ + CheckDecodeMsg("", "", "Decoded of empty string should be empty too."); +} + +/* +Name: base64_test_decode_only_pads +Description: Tests decoding of string with only pads +Expected: Base64::decode should return empty string +*/ +RUNNER_TEST(base64_test_decode_only_pads) +{ + CheckDecodeMsg("====", "", + "Decoded string with only pads should produce empty string"); +} + +/* +Name: base64_test_decode_invalid_length +Description: Tests decoding of string with invalid length +Expected: Base64::decode should throw exception +*/ +RUNNER_TEST(base64_test_decode_invalid_length) +{ + for (auto& example : TextPair::examples()) { + for (int i = 1; i <= 3; ++i) { + std::string encodedWithInvalideLength = + example.encoded.substr(0, example.encoded.size() - i); + Try { + Base64::decode(encodedWithInvalideLength); + RUNNER_ASSERT_MSG(false, + "For invalid length method should throw exception."); + } Catch (InvalidArgumentException) { + // Test pass - nothing to do + } Catch (DPL::Exception) { + RUNNER_ASSERT_MSG(false, "Unknown exception."); + } + } + } +} + +/* +Name: base64_test_decode_invalid_valid_char +Description: Tests decoding of string with all ASCII characters +Expected: Base64::decode should throw exception for characters that aren't + in alphabet of Base64. +*/ +RUNNER_TEST(base64_test_decode_invalid_valid_char) +{ + std::random_device rd; + std::mt19937 gen(rd()); + + for (const TextPair& ex : TextPair::examples()) + { + for (char character = 1; character != 0; ++character) + { + if('=' == character) + continue; + + std::string encodedWithNewChar( + [&]()->std::string // return string with invalide character + { + std::size_t lastPosition = ex.encoded.find('='); + lastPosition = (std::string::npos == lastPosition) + ? ex.encoded.length()-1 : lastPosition - 1; + std::uniform_int_distribution<> dis(0, lastPosition); + + int randomPosition = dis(gen); + std::unique_ptr<char[]> tmp = + convertStringToPtr<char>(ex.encoded); + tmp.get()[randomPosition] = character; + return std::string(tmp.get()); + }()); + + bool found = (base64chars.find(character) != base64chars.end()); + Try { + Base64::decode(encodedWithNewChar); + if (!found) { + WrtLogD("Before = \"%s\"", ex.encoded.c_str()); + WrtLogD("After = \"%s\"", encodedWithNewChar.c_str()); + } + RUNNER_ASSERT_MSG(found, "For invalid character(" + << static_cast<int>(character) << "|'" << character + << "') method should throw exception."); + } Catch (InvalidArgumentException) { + if (found) { + WrtLogD("Before = \"%s\"", ex.encoded.c_str()); + WrtLogD("After = \"%s\"", encodedWithNewChar.c_str()); + } + RUNNER_ASSERT_MSG(!found, "For valid character(" + << static_cast<int>(character) << "|'" << character + << "') the exception shouldn't be threw."); + } Catch (DPL::Exception) { + RUNNER_ASSERT_MSG(false, "Unknown exception."); + } + } + } +} diff --git a/tests/Commons/CMakeLists.txt b/tests/Commons/CMakeLists.txt new file mode 100644 index 0000000..c5ba7fc --- /dev/null +++ b/tests/Commons/CMakeLists.txt @@ -0,0 +1,42 @@ +# Copyright (c) 2014 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 CMakeLists.txt +# @author Grzegorz Rynkowski (g.rynkowski@sasmung.com) +# @brief +# + +# names of tested targets +SET(TARGET_COMMONS "wrt-plugins-commons") # name of tested target +SET(TARGET_COMMONS_TEST "wrt-plugins-common-tests-Commons") # name of target + + +PKG_SEARCH_MODULE(dpl REQUIRED dpl-efl) +PKG_SEARCH_MODULE(dpl-test REQUIRED dpl-test-efl) + +INCLUDE_DIRECTORIES(${dpl_INCLUDE_DIRS} + ${dpl-test_INCLUDE_DIRS}) + +# Set tests sources +SET(SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/TestInit.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/Base64_test.cpp") + +WRT_TEST_BUILD(${TARGET_COMMONS_TEST} ${SOURCES}) +WRT_TEST_INSTALL(${TARGET_COMMONS_TEST}) + +TARGET_LINK_LIBRARIES(${TARGET_COMMONS_TEST} + ${TARGET_COMMONS} + ${dpl_LIBRARIES} + ${dpl-test_LIBRARIES} +)
\ No newline at end of file diff --git a/tests/Commons/TestInit.cpp b/tests/Commons/TestInit.cpp new file mode 100644 index 0000000..9cd1884 --- /dev/null +++ b/tests/Commons/TestInit.cpp @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2014 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 main.cpp + * @author Grzegorz Rynkowski (g.rynkowski@samsung.com) + * @version 1.0 + * @brief This file is the implementation file of main. + */ + +#include <dpl/test/test_runner.h> +#include <dpl/log/secure_log.h> + +int main(int argc, char *argv[]) +{ + WrtLogD("Starting tests"); + return DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, argv); +} diff --git a/tests/dao/CMakeLists.txt b/tests/dao/CMakeLists.txt new file mode 100644 index 0000000..7f4e50a --- /dev/null +++ b/tests/dao/CMakeLists.txt @@ -0,0 +1,47 @@ +# 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 CMakeLists.txt +# @author Andrzej Surdej (a.surdej@sasmung.com) +# @version 1.0 +# @brief +# + +SET(TARGET_WIDGETDB_TEST "wrt-plugins-common-tests-widgetdb") + +PKG_SEARCH_MODULE(dpl REQUIRED dpl-efl) +PKG_SEARCH_MODULE(dpl-test REQUIRED dpl-test-efl) + +INCLUDE_DIRECTORIES( + ${dpl_INCLUDE_DIRS} + ${dpl-test_INCLUDE_DIRS} +) + +# Set widgetdb tests sources +SET(WIDGETDB_TESTS_SOURCES "${CMAKE_CURRENT_SOURCE_DIR}/TestInit.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/WidgetDBTest.cpp") + +WRT_TEST_BUILD(${TARGET_WIDGETDB_TEST} ${WIDGETDB_TESTS_SOURCES}) +WRT_TEST_INSTALL(${TARGET_WIDGETDB_TEST}) + +TARGET_LINK_LIBRARIES(${TARGET_WIDGETDB_TEST} + "wrt-plugins-widgetdb" + ${dpl_LIBRARIES} + ${dpl-test_LIBRARIES} +) + +INSTALL(PROGRAMS + ${CMAKE_CURRENT_SOURCE_DIR}/widgetdb_tests_prepare_db.sh + DESTINATION bin + ) diff --git a/tests/dao/README b/tests/dao/README new file mode 100644 index 0000000..a618eb1 --- /dev/null +++ b/tests/dao/README @@ -0,0 +1,12 @@ +Plugins DAO +System tests. Tests widget's private database data access object. +Binary file: plugins-tests-widgetdb. Uses our test framework. Allows to use +different types of output. Text output shows results on console - green passed. +To run: +1. Install wrt-extra on target +2. Run plugins-tests-widgetdb --output=text + +Automatic: YES +Included in Daily Build: YES (http://build01.sprc.samsung.pl/browse/LINUXNGWAP-INT) +Included in Gerrit Builds: YES (http://build01.sprc.samsung.pl/browse/LINUXNGWAP-GERRIT) +Number of test cases: 22
\ No newline at end of file diff --git a/tests/dao/TestInit.cpp b/tests/dao/TestInit.cpp new file mode 100644 index 0000000..7b42bf3 --- /dev/null +++ b/tests/dao/TestInit.cpp @@ -0,0 +1,61 @@ +/* + * 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 TestInit.cpp + * @author Pawel Sikorski (p.sikorski@samsung.com) + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 1.0 + * @brief Init widgetDB module test + */ + +#include <sys/wait.h> +#include <dpl/test/test_runner.h> +#include <dpl/log/wrt_log.h> +#include <dpl/wrt-dao-ro/WrtDatabase.h> + +int main (int argc, char *argv[]) +{ + int ret = system("/usr/bin/widgetdb_tests_prepare_db.sh start"); + + if (!WIFEXITED(ret)) { //unexpected terminate + WrtLogD("Fail while preparing database. Restoring"); + ret = system("/usr/bin/widgetdb_tests_prepare_db.sh stop"); + if (ret != 0) + WrtLogE("Finalization script has return error: %d", ret); + + return -1; + } else if (WEXITSTATUS(ret)) { //wrong script command, nothing done + WrtLogE("Preparation script has return error: %d. Quitting", ret); + return -1; + } + + WrtLogD("Starting tests"); + + WrtDB::WrtDatabase::attachToThreadRW(); + + int status = + DPL::Test::TestRunnerSingleton::Instance().ExecTestRunner(argc, argv); + + WrtDB::WrtDatabase::detachFromThread(); + + ret = system("/usr/bin/widgetdb_tests_prepare_db.sh stop"); + if (ret != 0) { + WrtLogE("Finalization script has return error: %d", ret); + return -1; + } + + return status; +} diff --git a/tests/dao/WidgetDBTest.cpp b/tests/dao/WidgetDBTest.cpp new file mode 100644 index 0000000..c977f7a --- /dev/null +++ b/tests/dao/WidgetDBTest.cpp @@ -0,0 +1,421 @@ +/* + * 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 WidgetDBTest.cpp + * @author Andrzej Surdej (a.surdej@samsung.com) + * @version 1.0 + * @brief This file contains tests for widgetDB commons module + */ + +#include <dpl/test/test_runner.h> +#include <dpl/foreach.h> +#include <dpl/log/wrt_log.h> +#include <WidgetDB/IWidgetDB.h> +#include <WidgetDB/WidgetDBMgr.h> +#include <Commons/Exception.h> + +using namespace WrtDeviceApis::WidgetDB::Api; + +#define RUNNER_ASSERT_WHAT_EQUALS(in, test) \ + do { \ + std::string temp(in); \ + RUNNER_ASSERT_MSG(temp == (test), "Equals: [" << temp << "]"); \ + } \ + while (0) + +RUNNER_TEST_GROUP_INIT(WidgetDB) + +/* + * Name: widgetDB_test_get_language1 + * Description: check default widget language + * Expected: default should be "en" + */ +RUNNER_TEST(widgetDB_test_get_language1) +{ + try { + IWidgetDBPtr widget = getWidgetDB(2000); + std::string lang = widget->getLanguage(); + + WrtLogD("language is: %s", lang.c_str()); + RUNNER_ASSERT_WHAT_EQUALS(lang, "en"); + } catch (const WrtDeviceApis::Commons::SecurityException &e) { + WrtLogE("Exception thrown %s", e.DumpToString().c_str()); + RUNNER_ASSERT(false); + } +} + +/* + * Name: widgetDB_test_get_language2 + * Description: check language returned by WidgetDB if widget does nto exists + * Expected: result should be "" + */ +RUNNER_TEST(widgetDB_test_get_language2) +{ + try { + IWidgetDBPtr widget = getWidgetDB(1000); //widget not exist + std::string lang = widget->getLanguage(); + + WrtLogD("language is: %s", lang.c_str()); + RUNNER_ASSERT_WHAT_EQUALS(lang, ""); + } catch (const WrtDeviceApis::Commons::SecurityException &e) { + WrtLogE("Exception thrown %s", e.DumpToString().c_str()); + RUNNER_ASSERT(false); + } +} + +/* + * Name: widgetDB_test_get_config_value_id + * Description: check GUID returned by WidgetDB + * Expected: GUID should match this, which was inserted into widget database + */ +RUNNER_TEST(widgetDB_test_get_config_value_id) +{ + try { + IWidgetDBPtr widget = getWidgetDB(2000); + std::string tmp = widget->getConfigValue(ConfigAttribute::ID); + + WrtLogD("id is: %s", tmp.c_str()); + RUNNER_ASSERT_WHAT_EQUALS(tmp, "w_id_2000"); + } catch (const WrtDeviceApis::Commons::SecurityException &e) { + WrtLogE("Exception thrown %s", e.DumpToString().c_str()); + RUNNER_ASSERT(false); + } +} + +/* + * Name: widgetDB_test_get_config_value_version + * Description: check version returned by WidgetDB + * Expected: version should match this, which was inserted into widget database + */ +RUNNER_TEST(widgetDB_test_get_config_value_version) +{ + try { + IWidgetDBPtr widget = getWidgetDB(2000); + std::string tmp = widget->getConfigValue(ConfigAttribute::VERSION); + + WrtLogD("version is: %s", tmp.c_str()); + RUNNER_ASSERT_WHAT_EQUALS(tmp, "1.0.0"); + } catch (const WrtDeviceApis::Commons::SecurityException &e) { + WrtLogE("Exception thrown %s", e.DumpToString().c_str()); + RUNNER_ASSERT(false); + } +} + +/* + * Name: widgetDB_test_get_config_value_description + * Description: check description returned by WidgetDB + * Expected: description should match this, which was inserted into widget + * database + */ +RUNNER_TEST(widgetDB_test_get_config_value_description) +{ + try { + IWidgetDBPtr widget = getWidgetDB(2000); + std::string tmp = widget->getConfigValue(ConfigAttribute::DESCRIPTION); + + WrtLogD("description is: %s", tmp.c_str()); + RUNNER_ASSERT_WHAT_EQUALS(tmp, "w_desc_2000_en"); + } catch (const WrtDeviceApis::Commons::SecurityException &e) { + WrtLogE("Exception thrown %s", e.DumpToString().c_str()); + RUNNER_ASSERT(false); + } +} + +/* + * Name: widgetDB_test_get_config_value_license + * Description: check license returned by WidgetDB + * Expected: license should match this, which was inserted into widget database + */ +RUNNER_TEST(widgetDB_test_get_config_value_license) +{ + try { + IWidgetDBPtr widget = getWidgetDB(2000); + std::string tmp = widget->getConfigValue(ConfigAttribute::LICENSE); + + WrtLogD("licence is: %s", tmp.c_str()); + RUNNER_ASSERT_WHAT_EQUALS(tmp, "w_lic_2000_en"); + } catch (const WrtDeviceApis::Commons::SecurityException &e) { + WrtLogE("Exception thrown %s", e.DumpToString().c_str()); + RUNNER_ASSERT(false); + } +} + +/* + * Name: widgetDB_test_get_config_value_license_href + * Description: check license href returned by WidgetDB + * Expected: license href should match this, which was inserted into widget + * database + */ +RUNNER_TEST(widgetDB_test_get_config_value_license_href) +{ + try { + IWidgetDBPtr widget = getWidgetDB(2000); + std::string tmp = widget->getConfigValue(ConfigAttribute::LICENSE_HREF); + + WrtLogD("license href is: %s", tmp.c_str()); + RUNNER_ASSERT_WHAT_EQUALS(tmp, "w_lic_href_2000_en"); + } catch (const WrtDeviceApis::Commons::SecurityException &e) { + WrtLogE("Exception thrown %s", e.DumpToString().c_str()); + RUNNER_ASSERT(false); + } +} + +/* + * Name: widgetDB_test_get_config_value_author_name + * Description: check author name href returned by WidgetDB + * Expected: author name should match this, which was inserted into widget + * database + */ +RUNNER_TEST(widgetDB_test_get_config_value_author_name) +{ + try { + IWidgetDBPtr widget = getWidgetDB(2000); + std::string tmp = widget->getConfigValue(ConfigAttribute::AUTHOR_NAME); + + WrtLogD("author name is: %s", tmp.c_str()); + RUNNER_ASSERT_WHAT_EQUALS(tmp, "a_name_2000"); + } catch (const WrtDeviceApis::Commons::SecurityException &e) { + WrtLogE("Exception thrown %s", e.DumpToString().c_str()); + RUNNER_ASSERT(false); + } +} + +/* + * Name: widgetDB_test_get_config_value_author_href + * Description: check author href returned by WidgetDB + * Expected: author href should match this, which was inserted into widget + * database + */ +RUNNER_TEST(widgetDB_test_get_config_value_author_href) +{ + try { + IWidgetDBPtr widget = getWidgetDB(2000); + std::string tmp = widget->getConfigValue(ConfigAttribute::AUTHOR_HREF); + + WrtLogD("author href is: %s", tmp.c_str()); + RUNNER_ASSERT_WHAT_EQUALS(tmp, "a_href_2000"); + } catch (const WrtDeviceApis::Commons::SecurityException &e) { + WrtLogE("Exception thrown %s", e.DumpToString().c_str()); + RUNNER_ASSERT(false); + } +} + +/* + * Name: widgetDB_test_get_config_value_author_email + * Description: check author email returned by WidgetDB + * Expected: author email should match this, which was inserted into widget + * database + */ +RUNNER_TEST(widgetDB_test_get_config_value_author_email) +{ + try { + IWidgetDBPtr widget = getWidgetDB(2000); + std::string tmp = widget->getConfigValue(ConfigAttribute::AUTHOR_EMAIL); + + WrtLogD("author email is: %s", tmp.c_str()); + RUNNER_ASSERT_WHAT_EQUALS(tmp, "a_email_2000"); + } catch (const WrtDeviceApis::Commons::SecurityException &e) { + WrtLogE("Exception thrown %s", e.DumpToString().c_str()); + RUNNER_ASSERT(false); + } +} + +/* + * Name: widgetDB_test_get_config_value_name + * Description: check localized widget name returned by WidgetDB + * Expected: localized widget name should match this, which was inserted into + * widget database + */ +RUNNER_TEST(widgetDB_test_get_config_value_name) +{ + try { + IWidgetDBPtr widget = getWidgetDB(2000); + std::string tmp = widget->getConfigValue(ConfigAttribute::NAME); + + WrtLogD("name is: %s", tmp.c_str()); + RUNNER_ASSERT_WHAT_EQUALS(tmp, "w_name_2000_en"); + } catch (const WrtDeviceApis::Commons::SecurityException &e) { + WrtLogE("Exception thrown %s", e.DumpToString().c_str()); + RUNNER_ASSERT(false); + } +} + +/* + * Name: widgetDB_test_get_config_value_short_name + * Description: check localized widget short name returned by WidgetDB + * Expected: localized widget short name should match this, which was inserted + * into widget database + */ +RUNNER_TEST(widgetDB_test_get_config_value_short_name) +{ + try { + IWidgetDBPtr widget = getWidgetDB(2000); + std::string tmp = widget->getConfigValue(ConfigAttribute::SHORT_NAME); + + WrtLogD("short name is: %s", tmp.c_str()); + RUNNER_ASSERT_WHAT_EQUALS(tmp, "w_shortname_2000_en"); + } catch (const WrtDeviceApis::Commons::SecurityException &e) { + WrtLogE("Exception thrown %s", e.DumpToString().c_str()); + RUNNER_ASSERT(false); + } +} + +/* + * Name: widgetDB_test_get_config_value_width + * Description: check widget prefered width returned by WidgetDB + * Expected: widget prefered width should match this, which was inserted into + * widget database + */ +RUNNER_TEST(widgetDB_test_get_config_value_width) +{ + try { + IWidgetDBPtr widget = getWidgetDB(2000); + std::string tmp = widget->getConfigValue(ConfigAttribute::WIDTH); + + WrtLogD("width is: %s", tmp.c_str()); + RUNNER_ASSERT_WHAT_EQUALS(tmp, "100"); + } catch (const WrtDeviceApis::Commons::SecurityException &e) { + WrtLogE("Exception thrown %s", e.DumpToString().c_str()); + RUNNER_ASSERT(false); + } +} + +/* + * Name: widgetDB_test_get_config_value_height + * Description: check widget prefered height returned by WidgetDB + * Expected: widget prefered height should match this, which was inserted into + * widget database + */ +RUNNER_TEST(widgetDB_test_get_config_value_height) +{ + try { + IWidgetDBPtr widget = getWidgetDB(2000); + std::string tmp = widget->getConfigValue(ConfigAttribute::HEIGHT); + + WrtLogD("height is: %s", tmp.c_str()); + RUNNER_ASSERT_WHAT_EQUALS(tmp, "200"); + } catch (const WrtDeviceApis::Commons::SecurityException &e) { + WrtLogE("Exception thrown %s", e.DumpToString().c_str()); + RUNNER_ASSERT(false); + } +} + +/* + * Name: widgetDB_test_get_config_value_paths + * Description: check widget installation path returned by WidgetDB + * Expected: widget installation path should match this, which was inserted into + * widget database + */ +RUNNER_TEST(widgetDB_test_get_config_value_paths) +{ + try { + IWidgetDBPtr widget = getWidgetDB(2000); + std::string tmp = widget->getConfigValue(ConfigAttribute::INSTALL_PATH); + + WrtLogD("install path is: %s", tmp.c_str()); + + tmp = widget->getConfigValue( + ConfigAttribute::PUBLIC_STORAGE_PATH); + + WrtLogD("public storage path is: %s", tmp.c_str()); + } catch (const WrtDeviceApis::Commons::SecurityException &e) { + WrtLogD("Exception thrown %s", e.DumpToString().c_str()); + RUNNER_ASSERT(false); + } +} + +/* + * Name: widgetDB_test_get_config_value_empty + * Description: check if requesting GUID from WidgetDB throw excpetion if widget + * does not exists + * Expected: accessing GUID should throw + * WrtDeviceApis::Commons::SecurityException + */ +RUNNER_TEST(widgetDB_test_get_config_value_empty) +{ + try { + IWidgetDBPtr widget = getWidgetDB(2005); + widget->getConfigValue(ConfigAttribute::ID); + + //exception should be thrown + RUNNER_ASSERT(false); + } catch (const WrtDeviceApis::Commons::SecurityException &e) { + WrtLogD("OK. Exception thrown %s", e.DumpToString().c_str()); + } +} + +/* + * Name: widgetDB_test_check_installation_status_installed + * Description: check if widget is installed by WidgetDB + * Expected: plugin should be notified that widget is installed + */ +RUNNER_TEST(widgetDB_test_check_installation_status_installed) +{ + try { + IWidgetDBPtr widget = getWidgetDB(2000); + InstallationStatus tmp = widget->checkInstallationStatus( + "w_id_2000", "w_name_2000_en", "2.0.0"); + + RUNNER_ASSERT(tmp == InstallationStatus::STATUS_INSTALLED); + } catch (const WrtDeviceApis::Commons::SecurityException &e) { + WrtLogE("Exception thrown %s", e.DumpToString().c_str()); + RUNNER_ASSERT(false); + } +} + +/* + * Name: widgetDB_test_check_installation_status_uninstalled + * Description: check if widget is not installed by WidgetDB + * Expected: plugin should be notified that widget is not installed + */ +RUNNER_TEST(widgetDB_test_check_installation_status_uninstalled) +{ + try { + IWidgetDBPtr widget = getWidgetDB(2000); + InstallationStatus tmp = widget->checkInstallationStatus( + "w_id_2011", "w_name_2000_en", "2.0.0"); + + RUNNER_ASSERT(tmp == InstallationStatus::STATUS_UNINSTALLED); + } catch (const WrtDeviceApis::Commons::SecurityException &e) { + WrtLogE("Exception thrown %s", e.DumpToString().c_str()); + RUNNER_ASSERT(false); + } +} + +/* + * Name: widgetDB_test_check_installation_status_latest + * Description: check if widget installation information is taken from latest + * version + * Expected: plugin installation status should be same is both calls of WidgetDB + */ +RUNNER_TEST(widgetDB_test_check_installation_status_latest) +{ + try { + IWidgetDBPtr widget = getWidgetDB(2000); + InstallationStatus tmp1 = widget->checkInstallationStatus( + "w_id_2000", "w_name_2000_en", "0.1.0"); + InstallationStatus tmp2 = widget->checkInstallationStatus( + "w_id_2000", "w_name_2000_en", "1.0.0"); + + RUNNER_ASSERT(tmp1 == InstallationStatus::STATUS_LATEST); + RUNNER_ASSERT(tmp2 == InstallationStatus::STATUS_LATEST); + } catch (const WrtDeviceApis::Commons::SecurityException &e) { + WrtLogE("Exception thrown %s", e.DumpToString().c_str()); + RUNNER_ASSERT(false); + } +} + +#undef RUNNER_ASSERT_WHAT_EQUALS diff --git a/tests/dao/widgetdb_tests_prepare_db.sh b/tests/dao/widgetdb_tests_prepare_db.sh new file mode 100755 index 0000000..f367b02 --- /dev/null +++ b/tests/dao/widgetdb_tests_prepare_db.sh @@ -0,0 +1,122 @@ +#!/bin/sh +# +# 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. +# +# + +WRT_DB=/opt/dbspace/.wrt.db +WRT_DB_BCK=/tmp/wrt.db_backup + +if [ "x$1" == "xstart" ]; then + echo start; + cp $WRT_DB $WRT_DB_BCK + wrt_commons_create_clean_db.sh; + + #simple plugins + INS_MIN_PLUGINPROP="insert into PluginProperties(PluginPropertiesId, InstallationState, PluginLibraryName" + INS_ALL_PLUGINPROP="insert into PluginProperties(PluginPropertiesId, InstallationState, PluginLibraryName, PluginLibraryPath)" + + sqlite3 $WRT_DB "${INS_MIN_PLUGINPROP}) VALUES(1, 1, 'plugin1')"; + sqlite3 $WRT_DB "${INS_MIN_PLUGINPROP}, PluginLibraryPath) VALUES(2, 1, 'plugin2', 'path_to_plugin2')"; + sqlite3 $WRT_DB "${INS_MIN_PLUGINPROP}) VALUES(3, 1, 'plugin3')"; + sqlite3 $WRT_DB "${INS_ALL_PLUGINPROP} VALUES(4, 1, 'p4', 'path_to_p4')"; + sqlite3 $WRT_DB "${INS_ALL_PLUGINPROP} VALUES(5, 1, 'p5', 'path_to_p5')"; + + #simple features + INS_ALL_FEATURESLIST="insert into FeaturesList(FeatureUUID, FeatureName, PluginPropertiesId)" + sqlite3 $WRT_DB "${INS_ALL_FEATURESLIST} VALUES(1, 'feature1', 1)"; + sqlite3 $WRT_DB "${INS_ALL_FEATURESLIST} VALUES(2, 'feature2', 4)"; + sqlite3 $WRT_DB "${INS_ALL_FEATURESLIST} VALUES(3, 'feature3', 4)"; + sqlite3 $WRT_DB "${INS_ALL_FEATURESLIST} VALUES(4, 'feature4', 4)"; + + #Device capab + #TODO + + #Widgets + INS_ALL_WIDGETEXT="insert into WidgetExtendedInfo(app_id)" + INS_ALL_WIDGET="insert into WidgetInfo(app_id, widget_id, widget_version, widget_width, widget_height, author_name, author_email, author_href, min_version, back_supported, defaultlocale, tizen_appid)" + INS_ALL_WIDGET_LOC="insert into LocalizedWidgetInfo(app_id, widget_locale, widget_name, widget_shortname, widget_description, widget_license, widget_license_file, widget_license_href)" + INS_ALL_WIDGET_ICONS="insert into WidgetIcon(app_id, icon_src, icon_width, icon_height)" + INS_ALL_WIDGET_LOC_ICONS="insert into WidgetLocalizedIcon(app_id, icon_id, widget_locale)" + INS_ALL_WIDGET_STARTFILE="insert into WidgetStartFile(app_id, src)" + INS_ALL_WIDGET_LOC_STARTFILE="insert into WidgetLocalizedStartFile(app_id, start_file_id, widget_locale, type, encoding)" + INS_ALL_WIDGET_DEFPREF="insert into WidgetDefaultPreference(app_id, key_name, key_value, readonly)" + INS_ALL_WIDGET_PREF="insert into WidgetPreference(app_id, tizen_appid, key_name, key_value, readonly)" + INS_ALL_WIDGET_FEATURE="insert into WidgetFeature(widget_feature_id, app_id, name, rejected)" + INS_ALL_WIDGET_WINMODES="insert into WidgetWindowModes(app_id, window_mode)" + INS_ALL_WIDGET_WARP="insert into WidgetWARPInfo(app_id, iri, subdomain_access)" + INS_ALL_WIDGET_CERT="insert into WidgetCertificateFingerprint(app_id, owner, chainid, type, md5_fingerprint, sha1_fingerprint, common_name)" + INS_ALL_WIDGET_POWDERLEV="insert into PowderLevels(app_id, category, level)" + INS_ALL_WIDGET_POWDERLEV_CONT="insert into PowderLevelContexts(levelid, context)" + + + sqlite3 $WRT_DB "${INS_ALL_WIDGET} VALUES(2000, 'w_id_2000', '1.0.0', 100, 200, 'a_name_2000', 'a_email_2000', 'a_href_2000', '1.0', 0, 'en', 'tid2000')"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET} VALUES(2001, 'w_id_2001', '2.0.0', 100, 200, 'a_name_2001', 'a_email_2001', 'a_href_2001', '0.5', 0, 'en', 'tid2001')"; + sqlite3 $WRT_DB "insert into WidgetInfo(app_id, back_supported, tizen_appid) VALUES(2002, 0, 'tid2002')"; + sqlite3 $WRT_DB "insert into WidgetInfo(app_id, back_supported, tizen_appid) VALUES(2003, 0, 'NOTUSEDPKGNAME3')"; # for properties tests + + sqlite3 $WRT_DB "${INS_ALL_WIDGETEXT} VALUES(2000)"; + sqlite3 $WRT_DB "${INS_ALL_WIDGETEXT} VALUES(2001)"; + sqlite3 $WRT_DB "insert into WidgetExtendedInfo(app_id) VALUES(2002)"; + sqlite3 $WRT_DB "insert into WidgetExtendedInfo(app_id) VALUES(2003)"; + + sqlite3 $WRT_DB "${INS_ALL_WIDGET_LOC} VALUES(2000, 'en', 'w_name_2000_en', 'w_shortname_2000_en', 'w_desc_2000_en', 'w_lic_2000_en', 'w_licf_2000_en', 'w_lic_href_2000_en')"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_LOC} VALUES(2000, 'pl', 'w_name_2000_pl', 'w_shortname_2000_pl', 'w_desc_2000_pl', 'w_lic_2000_pl', 'w_licf_2000_pl', 'w_lic_href_2000_pl')"; + sqlite3 $WRT_DB "insert into LocalizedWidgetInfo(app_id, widget_locale) VALUES(2002, 'en')"; + sqlite3 $WRT_DB "insert into LocalizedWidgetInfo(app_id, widget_locale) VALUES(2003, 'en')"; + +#Widget features + sqlite3 $WRT_DB "${INS_ALL_WIDGET_FEATURE} VALUES(1,2000, 'first_2000', 0)"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_FEATURE} VALUES(2,2000, 'second_2000', 0)"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_FEATURE} VALUES(3,2000, 'third_2000', 0)"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_FEATURE} VALUES(8,2000, 'fourth_2000', 0)"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_FEATURE} VALUES(9,2000, 'fifth_2000', 0)"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_FEATURE} VALUES(4,2001, 'first_2001', 0)"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_FEATURE} VALUES(5,2001, 'second_2001', 0)"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_FEATURE} VALUES(6,2001, 'third_2001', 0)"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_FEATURE} VALUES(7,2001, 'fourth_2001', 0)"; + + sqlite3 $WRT_DB "${INS_ALL_WIDGET_ICONS} VALUES(2000, 'icon_src_2000', 50, 50)"; + sqlite3 $WRT_DB "insert into WidgetIcon(app_id, icon_src) VALUES(2002, 'icon_src_2002')"; + + sqlite3 $WRT_DB "${INS_ALL_WIDGET_LOC_ICONS} VALUES(2000, 1, 'en')"; + + sqlite3 $WRT_DB "${INS_ALL_WIDGET_STARTFILE} VALUES(2000, 'start_file_2000')"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_STARTFILE} VALUES(2001, 'start_file_2001')"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_STARTFILE} VALUES(2002, 'start_file_2002')"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_STARTFILE} VALUES(2003, 'start_file_2003')"; + + sqlite3 $WRT_DB "${INS_ALL_WIDGET_LOC_STARTFILE} VALUES(2000, 1, 'en', '', '')"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_LOC_STARTFILE} VALUES(2001, 2, 'en', '', '')"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_LOC_STARTFILE} VALUES(2002, 3, 'en', '', '')"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_LOC_STARTFILE} VALUES(2003, 4, 'en', '', '')"; + + #widget properties + sqlite3 $WRT_DB "${INS_ALL_WIDGET_PREF} VALUES(2000, 'tid2000', 'key1_for_2000', 'value_for_key1_2000', 0)"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_PREF} VALUES(2000, 'tid2000', 'key2_for_2000', 'value_for_key2_2000', 0)"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_PREF} VALUES(2001, 'tid2001', 'key1_for_2001', 'value1_for_key_2001', 1)"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_PREF} VALUES(2002, 'tid2002', 'key1_for_2002', 'value1_for_key_2002', 0)"; + sqlite3 $WRT_DB "${INS_ALL_WIDGET_PREF} VALUES(2002, 'tid2002', 'key2_for_2002', 'value2_for_key_2002', 1)"; + + + exit $? + +elif [ "x$1" == "xstop" ]; then + echo stop; + cp $WRT_DB_BCK $WRT_DB + exit $? +else + exit 1 +fi diff --git a/uncrustify.cfg b/uncrustify.cfg new file mode 100644 index 0000000..2bf1d96 --- /dev/null +++ b/uncrustify.cfg @@ -0,0 +1,170 @@ +indent_align_string=true
+indent_braces=false
+indent_braces_no_func=false
+indent_brace_parent=false
+indent_namespace=false
+indent_extern=false
+indent_class=true
+indent_class_colon=false
+indent_else_if=false
+indent_func_call_param=false
+indent_func_def_param=false
+indent_func_proto_param=false
+indent_func_class_param=false
+indent_func_ctor_var_param=false
+indent_template_param=false
+indent_func_param_double=false
+indent_relative_single_line_comments=false
+indent_col1_comment=true
+indent_access_spec_body=false
+indent_paren_nl=false
+indent_comma_paren=false
+indent_bool_paren=false
+indent_square_nl=false
+indent_preserve_sql=false
+indent_align_assign=false
+sp_balance_nested_parens=false
+align_keep_tabs=false
+align_with_tabs=false
+align_on_tabstop=false
+align_number_left=false
+align_func_params=false
+align_same_func_call_params=false
+align_var_def_colon=false
+align_var_def_attribute=false
+align_var_def_inline=false
+align_right_cmt_mix=false
+align_on_operator=false
+align_mix_var_proto=false
+align_single_line_func=false
+align_single_line_brace=false
+align_nl_cont=false
+align_left_shift=true
+nl_collapse_empty_body=true
+nl_assign_leave_one_liners=false
+nl_class_leave_one_liners=false
+nl_enum_leave_one_liners=false
+nl_getset_leave_one_liners=false
+nl_func_leave_one_liners=false
+nl_if_leave_one_liners=false
+nl_multi_line_cond=true
+nl_multi_line_define=false
+nl_before_case=false
+nl_after_case=false
+nl_after_return=false
+nl_after_semicolon=true
+nl_after_brace_open=false
+nl_after_brace_open_cmt=false
+nl_after_vbrace_open=false
+nl_after_brace_close=false
+nl_define_macro=false
+nl_squeeze_ifdef=false
+nl_ds_struct_enum_cmt=false
+nl_ds_struct_enum_close_brace=false
+nl_create_if_one_liner=false
+nl_create_for_one_liner=false
+nl_create_while_one_liner=false
+ls_for_split_full=true
+ls_func_split_full=true
+nl_after_multiline_comment=false
+eat_blanks_after_open_brace=true
+eat_blanks_before_close_brace=true
+mod_pawn_semicolon=false
+mod_full_paren_if_bool=false
+mod_remove_extra_semicolon=true
+mod_sort_import=false
+mod_sort_using=false
+mod_sort_include=false
+mod_move_case_break=false
+mod_remove_empty_return=false
+cmt_indent_multi=true
+cmt_c_group=false
+cmt_c_nl_start=false
+cmt_c_nl_end=false
+cmt_cpp_group=false
+cmt_cpp_nl_start=false
+cmt_cpp_nl_end=false
+cmt_cpp_to_c=false
+cmt_star_cont=true
+cmt_multi_check_last=true
+cmt_insert_before_preproc=false
+pp_indent_at_level=false
+pp_region_indent_code=false
+pp_if_indent_code=false
+pp_define_at_level=false
+indent_columns=4
+indent_member=4
+indent_access_spec=-2
+code_width=80
+nl_max=2
+nl_before_access_spec=2
+cmt_width=80
+indent_with_tabs=0
+sp_arith=force
+sp_assign=force
+sp_enum_assign=force
+sp_pp_concat=remove
+sp_pp_stringify=remove
+sp_bool=force
+sp_compare=force
+sp_paren_brace=force
+sp_angle_paren=remove
+sp_before_sparen=force
+sp_inside_sparen=remove
+sp_after_sparen=force
+sp_sparen_brace=force
+sp_before_semi=remove
+sp_after_semi_for_empty=remove
+sp_before_square=remove
+sp_before_squares=remove
+sp_inside_square=remove
+sp_after_comma=force
+sp_before_comma=remove
+sp_after_class_colon=force
+sp_before_class_colon=force
+sp_before_case_colon=remove
+sp_inside_braces=add
+sp_inside_fparens=remove
+sp_inside_fparen=remove
+sp_func_call_paren=remove
+sp_func_class_paren=remove
+sp_else_brace=force
+sp_brace_else=force
+sp_catch_brace=force
+sp_brace_catch=force
+sp_try_brace=force
+sp_before_dc=remove
+sp_after_dc=remove
+sp_not=remove
+sp_inv=remove
+sp_addr=remove
+sp_member=remove
+sp_deref=remove
+sp_sign=remove
+sp_incdec=remove
+sp_cond_colon=force
+sp_cond_question=force
+sp_case_label=force
+nl_assign_brace=remove
+nl_if_brace=remove
+nl_brace_else=remove
+nl_elseif_brace=remove
+nl_else_brace=remove
+nl_else_if=remove
+nl_try_brace=remove
+nl_for_brace=remove
+nl_catch_brace=remove
+nl_brace_catch=remove
+nl_while_brace=remove
+nl_do_brace=remove
+nl_brace_while=remove
+nl_switch_brace=remove
+nl_namespace_brace=remove
+nl_class_brace=force
+nl_fdef_brace=force
+pos_class_comma=trail
+pos_class_colon=trail
+mod_full_brace_do=add
+mod_full_brace_for=add
+mod_full_brace_if=add
+mod_full_brace_while=add
diff --git a/uncrustify.sh b/uncrustify.sh new file mode 100755 index 0000000..49ad3cf --- /dev/null +++ b/uncrustify.sh @@ -0,0 +1 @@ +uncrustify -c uncrustify.cfg --no-backup `find . -regex "\(.*\.cpp\|.*\.h\|.*\.c\|.*\.cc\)" | grep -v "orm.h\|orm_generator.h\|3rdparty\|examples"` diff --git a/wrt-plugins-common.manifest b/wrt-plugins-common.manifest new file mode 100644 index 0000000..4ae6e9b --- /dev/null +++ b/wrt-plugins-common.manifest @@ -0,0 +1,13 @@ +<manifest> + <define> + <domain name="wrt-plugins-common"/> + </define> + <assign> + <filesystem path="/usr/bin/wrt-popup-ace-runtime" label="wrt-popup-ace-runtime" exec_label="wrt-popup-ace-runtime"/> + <filesystem path="/usr/bin/wrt-popup-wrt-runtime" label="wrt-popup-wrt-runtime" exec_label="wrt-popup-wrt-runtime"/> + <filesystem path="/usr/bin/wrt-plugins-installer" label="_" exec_label="none"/> + </assign> + <request> + <domain name="_"/> + </request> +</manifest> diff --git a/wrt-plugins-common.map b/wrt-plugins-common.map new file mode 100644 index 0000000..29c429e --- /dev/null +++ b/wrt-plugins-common.map @@ -0,0 +1,6 @@ +{ + global: *; + local: *; +}; + + diff --git a/wrt-popup-ace-runtime.rule b/wrt-popup-ace-runtime.rule new file mode 100644 index 0000000..af50ad6 --- /dev/null +++ b/wrt-popup-ace-runtime.rule @@ -0,0 +1,14 @@ +wrt-popup-ace-runtime system::homedir rwx +wrt-popup-ace-runtime device::app_logging w +wrt-popup-ace-runtime ail::db rw +wrt-popup-ace-runtime xorg rwx +wrt-popup-ace-runtime isf rx +wrt-popup-ace-runtime system::vconf rwx +wrt-popup-ace-runtime sound_server rw +wrt-popup-ace-runtime e17 rw +e17 wrt-popup-ace-runtime rw +wrt-popup-ace-runtime system::share rwx +wrt-popup-ace-runtime pulseaudio rwx +wrt-popup-ace-runtime mobileprint x +wrt-popup-ace-runtime dbus r + diff --git a/wrt-popup-wrt-runtime.rule b/wrt-popup-wrt-runtime.rule new file mode 100644 index 0000000..1ad6fbc --- /dev/null +++ b/wrt-popup-wrt-runtime.rule @@ -0,0 +1,14 @@ +wrt-popup-wrt-runtime system::homedir rwx +wrt-popup-wrt-runtime device::app_logging w +wrt-popup-wrt-runtime ail::db rw +wrt-popup-wrt-runtime xorg rwx +wrt-popup-wrt-runtime isf rx +wrt-popup-wrt-runtime system::vconf rwx +wrt-popup-wrt-runtime sound_server rw +wrt-popup-wrt-runtime e17 rw +e17 wrt-popup-wrt-runtime rw +wrt-popup-wrt-runtime system::share rwx +wrt-popup-wrt-runtime pulseaudio rwx +wrt-popup-wrt-runtime mobileprint x +wrt-popup-wrt-runtime dbus r + |