diff options
author | Sehong Na <sehong.na@samsung.com> | 2014-05-31 13:20:25 +0900 |
---|---|---|
committer | Sehong Na <sehong.na@samsung.com> | 2014-05-31 13:20:25 +0900 |
commit | 59c401dcb6127a3ca74995bd3b3a7864a95fc418 (patch) | |
tree | 1d621db3eb1506f2fa42f1c38e143b90e1c3984f /wearable_src | |
download | wrt-plugins-tizen-tizen_2.3.tar.gz wrt-plugins-tizen-tizen_2.3.tar.bz2 wrt-plugins-tizen-tizen_2.3.zip |
Initialize Tizen 2.3submit/tizen_2.3/20140531.1146262.3a_releasetizen_2.3
Diffstat (limited to 'wearable_src')
471 files changed, 70816 insertions, 0 deletions
diff --git a/wearable_src/Alarm/AlarmAbsolute.cpp b/wearable_src/Alarm/AlarmAbsolute.cpp new file mode 100644 index 0000000..7dadf3b --- /dev/null +++ b/wearable_src/Alarm/AlarmAbsolute.cpp @@ -0,0 +1,130 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 "AlarmAbsolute.h" +#include "alarm_common.h" +#include <stdio.h> +#include <string.h> +#include <stdlib.h> +#include <Logger.h> + +namespace DeviceAPI { +namespace Alarm { + +AlarmAbsolute::AlarmAbsolute() +{ + m_isRecurrence = false; + service_create(&m_service_handle); + service_add_extra_data(m_service_handle, ALARM_TYPE_KEY, ALARM_TYPE_ABSOLUTE_VALUE); + service_add_extra_data(m_service_handle, ALARM_ALSOLUTE_RECURRENCE_TYPE_KEY, ALARM_ALSOLUTE_RECURRENCE_TYPE_NONE); + m_recurrenceType = AbsoluteRecurrence::NoRecurrence; + m_id = -1; + m_interval = -1; + is_registered = false; +} + +AlarmAbsolute::AlarmAbsolute(service_h handle) +{ + service_clone(&m_service_handle, handle); + m_id = -1; + m_interval = -1; + is_registered = false; +} + +AlarmAbsolute::~AlarmAbsolute() +{ + service_destroy(m_service_handle); +} + +int AlarmAbsolute::getId() const +{ + return m_id; +} + +void AlarmAbsolute::setId(const int id) +{ + m_id = id; + is_registered = true; +} + +bool AlarmAbsolute::isRecurrence() +{ + return m_isRecurrence; +} + +void AlarmAbsolute::setIsRecurrence(bool value) +{ + m_isRecurrence = value; +} + +void AlarmAbsolute::setDate(struct tm date) +{ + char strDate[19]; + m_date = date; + + snprintf(strDate, sizeof(strDate), "%d %d %d %d %d %d",m_date.tm_year, m_date.tm_mon, + m_date.tm_mday, m_date.tm_hour, m_date.tm_min, m_date.tm_sec); + + service_add_extra_data(m_service_handle, ALARM_ALSOLUTE_DATE_KEY, strDate); + + LoggerI("AlarmAbsolute Date = " << " Sec: " << m_date.tm_sec << ", Min: "<< m_date.tm_min + << ", Hour:" << m_date.tm_hour << ", Day: " << m_date.tm_mday << ", MON: " << m_date.tm_mon + << ", Year: " << m_date.tm_year); +} + +struct tm AlarmAbsolute::getDate() +{ + return m_date; +} + +void AlarmAbsolute::setInterval(int interval) +{ + m_interval = interval; + m_recurrenceType = AbsoluteRecurrence::Interval; + service_add_extra_data(m_service_handle, ALARM_ALSOLUTE_RECURRENCE_TYPE_KEY, ALARM_ALSOLUTE_RECURRENCE_TYPE_INTERVAL); +} + +int AlarmAbsolute::getInterval() +{ + return m_interval; +} + +void AlarmAbsolute::setByDayRecurrence(std::vector<std::string> &daysOfTheWeek) +{ + m_recurrenceType = AbsoluteRecurrence::ByDayValue; + m_daysOfTheWeek = daysOfTheWeek; + service_add_extra_data(m_service_handle, ALARM_ALSOLUTE_RECURRENCE_TYPE_KEY, ALARM_ALSOLUTE_RECURRENCE_TYPE_BYDAYVALUE); +} + +std::vector<std::string> AlarmAbsolute::getByDayRecurrence() +{ + return m_daysOfTheWeek; +} + +AbsoluteRecurrence::Type AlarmAbsolute::getRecurrenceType() +{ + return m_recurrenceType; +} + +service_h AlarmAbsolute::getService() { + return m_service_handle; +} + +} +} + diff --git a/wearable_src/Alarm/AlarmAbsolute.h b/wearable_src/Alarm/AlarmAbsolute.h new file mode 100755 index 0000000..fec12cd --- /dev/null +++ b/wearable_src/Alarm/AlarmAbsolute.h @@ -0,0 +1,72 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_API_ALARMABSOLUTE_H_ +#define TIZENAPIS_API_ALARMABSOLUTE_H_ + +#include <string> +#include <vector> +#include <dpl/shared_ptr.h> +#include <time.h> +#include <app.h> +#include "alarm_common.h" + +namespace DeviceAPI { +namespace Alarm { + +class AlarmAbsolute; +typedef DPL::SharedPtr<AlarmAbsolute> AlarmAbsolutePtr; +typedef std::vector<AlarmAbsolutePtr> AlarmAbsoluteArrayPtr; + +class AlarmAbsolute +{ + public: + AlarmAbsolute(); + AlarmAbsolute(service_h handle); + ~AlarmAbsolute(); + int getId() const; + void setId(const int id); + void setDate(struct tm date); + struct tm getDate(); + void setInterval(int interval); + int getInterval(); + bool isRecurrence(); + void setIsRecurrence(bool value); + void setByDayRecurrence(std::vector<std::string> &daysOfTheWeek); + std::vector<std::string> getByDayRecurrence(); + AbsoluteRecurrence::Type getRecurrenceType(); + service_h getService(); + + public: + bool is_registered; + + private: + int m_id; + struct tm m_date; + bool m_isRecurrence; + int m_interval; + service_h m_service_handle; + std::vector<std::string> m_daysOfTheWeek; + AbsoluteRecurrence::Type m_recurrenceType; + +}; + +} +} + +#endif diff --git a/wearable_src/Alarm/AlarmConverter.cpp b/wearable_src/Alarm/AlarmConverter.cpp new file mode 100644 index 0000000..53c93b4 --- /dev/null +++ b/wearable_src/Alarm/AlarmConverter.cpp @@ -0,0 +1,256 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 <vector> +#include <app.h> +#include <time.h> +#include <CommonsJavaScript/Converter.h> +#include <CommonsJavaScript/Validator.h> +#include <CommonsJavaScript/JSUtils.h> +#include <CommonsJavaScript/JSDOMExceptionFactory.h> +#include "AlarmConverter.h" +#include "JSAlarmAbsolute.h" +#include "AlarmAbsolute.h" +#include "JSAlarmRelative.h" +#include "AlarmRelative.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Alarm { + +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +AlarmConverter::AlarmConverter(JSContextRef context) : WrtDeviceApis::CommonsJavaScript::Converter(context) +{ + +} + +AlarmConverter::~AlarmConverter() +{ + +} + +int AlarmConverter::toNativeAlarmValue(std::vector<std::string> daysOfTheWeek) +{ + int nativeValue = 0; + + for( unsigned int i=0; i<daysOfTheWeek.size(); i++ ) + { + if( daysOfTheWeek[i]=="SU" ) + nativeValue = nativeValue | ALARM_WEEK_FLAG_SUNDAY; + else if( daysOfTheWeek[i]=="MO" ) + nativeValue = nativeValue | ALARM_WEEK_FLAG_MONDAY ; + else if( daysOfTheWeek[i]=="TU" ) + nativeValue = nativeValue | ALARM_WEEK_FLAG_TUESDAY ; + else if( daysOfTheWeek[i]=="WE" ) + nativeValue = nativeValue | ALARM_WEEK_FLAG_WEDNESDAY; + else if( daysOfTheWeek[i]=="TH" ) + nativeValue = nativeValue | ALARM_WEEK_FLAG_THURSDAY ; + else if( daysOfTheWeek[i]=="FR" ) + nativeValue = nativeValue | ALARM_WEEK_FLAG_FRIDAY ; + else if( daysOfTheWeek[i]=="SA" ) + nativeValue = nativeValue | ALARM_WEEK_FLAG_SATURDAY ; + } + return nativeValue; +} + +std::vector<std::string> AlarmConverter::convertFlagToDaysOfTheWeek(int byDayValue) +{ + std::vector<std::string> daysOfTheWeek; + + if(byDayValue & ALARM_WEEK_FLAG_SUNDAY) + daysOfTheWeek.push_back("SU"); + if(byDayValue & ALARM_WEEK_FLAG_MONDAY) + daysOfTheWeek.push_back("MO"); + if(byDayValue & ALARM_WEEK_FLAG_TUESDAY) + daysOfTheWeek.push_back("TU"); + if(byDayValue & ALARM_WEEK_FLAG_WEDNESDAY) + daysOfTheWeek.push_back("WE"); + if(byDayValue & ALARM_WEEK_FLAG_THURSDAY) + daysOfTheWeek.push_back("TH"); + if(byDayValue & ALARM_WEEK_FLAG_FRIDAY) + daysOfTheWeek.push_back("FR"); + if(byDayValue & ALARM_WEEK_FLAG_SATURDAY) + daysOfTheWeek.push_back("SA"); + + return daysOfTheWeek; +} + +service_h AlarmConverter::toService(std::string id) +{ + service_h service; + service_create(&service); + + service_set_operation(service, SERVICE_OPERATION_DEFAULT); + service_set_package(service, id.c_str()); + return service; +} +service_h AlarmConverter::toService(std::string id, std::string page) +{ + service_h service; + service_create(&service); + + service_set_operation(service, SERVICE_OPERATION_DEFAULT); + service_set_package(service, id.c_str()); + return service; +} + +bool AlarmConverter::toAlarmAbsolutePtr(int id, service_h handle, AlarmAbsolutePtr privateData) +{ + char* dateString; + char* alarmType; + struct tm date; + memset(&date, 0, sizeof(tm)); + int error = ALARM_ERROR_NONE; + + error = service_get_extra_data(handle, ALARM_ALSOLUTE_DATE_KEY, &dateString); + + LoggerI("Date Strng = " << dateString); + if(error != SERVICE_ERROR_NONE) + { + LoggerE("Fail to get AlarmDelay"); + return false; + } + sscanf(dateString, "%d %d %d %d %d %d", &date.tm_year, &date.tm_mon, + &date.tm_mday, &date.tm_hour, &date.tm_min, &date.tm_sec); + mktime(&date); + + LoggerI("Converter AlarmAbsolute Date = " << " Sec: " << date.tm_sec << ", Min: "<< date.tm_min + << ", Hour: " << date.tm_hour << ", Day: " << date.tm_mday << ", MON: " << date.tm_mon + << ", Year: " << date.tm_year); + + service_get_extra_data(handle, ALARM_ALSOLUTE_RECURRENCE_TYPE_KEY, &alarmType); + + if(!strcmp(alarmType, ALARM_ALSOLUTE_RECURRENCE_TYPE_INTERVAL)) { + int interval = 0; + alarm_get_scheduled_period(id, &interval); + LoggerI("interval type alarm: "<<interval); + privateData->setInterval(interval); + } else if(!strcmp(alarmType, ALARM_ALSOLUTE_RECURRENCE_TYPE_BYDAYVALUE)) { + int byDayValue =0; + error = alarm_get_scheduled_recurrence_week_flag(id, &byDayValue); + LoggerI("daysOfWeek type alarm: "<<byDayValue<<", error: "<<error); + if(error==ALARM_ERROR_NONE && byDayValue>0) { + std::vector<std::string> result; + result = convertFlagToDaysOfTheWeek(byDayValue); + privateData->setByDayRecurrence(result); + } else { + LoggerE("Can't get the recurrence week flag."); + } + } + + privateData->setId(id); + privateData->setDate(date); + + return true; +} + +bool AlarmConverter::toAlarmRelativePtr(int id, service_h handle, AlarmRelativePtr privateData) +{ + int interval = 0; + char* delayString; + int delay; + + int error = ALARM_ERROR_NONE; + error = alarm_get_scheduled_period(id, &interval); + if(error != ALARM_ERROR_NONE) { + interval = 0; + } + + error = service_get_extra_data(handle, ALARM_RELATIVE_DELAY_KEY, &delayString); + if(error != SERVICE_ERROR_NONE) + { + LoggerE("Fail to get AlarmDelay"); + return false; + } + delay = atoi(delayString); + free(delayString); + + privateData->setId(id); + privateData->setDelay(delay); + privateData->setPeriod(interval); + + return true; +} + +int AlarmConverter::toNativeInterval(std::string freq, std::string interval) +{ + int freqInSecond = 0; + int intervalValue = toInt(interval); + + if (!freq.compare(ALARM_PROPERTY_MINUTELY_RECURRENCE)) + freqInSecond = 60; + else if (!freq.compare(ALARM_PROPERTY_HOURLY_RECURRENCE)) + freqInSecond = 3600; + else if (!freq.compare(ALARM_PROPERTY_DAILY_RECURRENCE)) + freqInSecond = 3600*24; + else if (!freq.compare(ALARM_PROPERTY_WEEKLY_RECURRENCE)) + freqInSecond = 3600 * 24 * 7; + + return freqInSecond * intervalValue; +} + +bool AlarmConverter::toAlarmService(service_h service, DeviceAPI::Application::ApplicationControlPtr appservice) + { + if (appservice->getOperation().compare("") != 0) { + service_set_operation(service, appservice->getOperation().c_str() ); + } else { + LoggerD("Error. operation is madatory field. cannot be null"); + return false; + } + + if (appservice->getUri().compare("") != 0) { + service_set_uri(service, appservice->getUri().c_str() ); + } + + if (appservice->getMime().compare("") != 0) { + service_set_mime(service, appservice->getMime().c_str() ); + } + + std::vector<DeviceAPI::Application::ApplicationControlDataPtr> appControlDataArray = appservice->getAppControlDataArray(); + + if (!appControlDataArray.empty()) { + std::string key; + const char** arr = NULL; + + for (size_t i = 0; i < appControlDataArray.size(); ++i) { + key = appControlDataArray.at(i)->getKey(); + if (key.empty()) { + return false; + } + std::vector<std::string> valueArray = appControlDataArray.at(i)->getValue(); + size_t size = valueArray.size(); + + arr = (const char**)calloc(sizeof(char*), size); + + for (size_t j = 0; j < size; j++) { + arr[j] = valueArray.at(j).c_str(); + } + + service_add_extra_data_array(service, key.c_str(), arr, size); + + if (arr) + free(arr); + } + } + return true; +} + +} +} + diff --git a/wearable_src/Alarm/AlarmConverter.h b/wearable_src/Alarm/AlarmConverter.h new file mode 100755 index 0000000..cf9ada5 --- /dev/null +++ b/wearable_src/Alarm/AlarmConverter.h @@ -0,0 +1,65 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 _JS_TIZEN_ALARM_CONVERTER_H_ +#define _JS_TIZEN_ALARM_CONVERTER_H_ + +#include <vector> +#include <string> +#include <app.h> +#include <CommonsJavaScript/Converter.h> +#include <CommonsJavaScript/ScopedJSStringRef.h> +#include <JSApplicationControl.h> +#include <ApplicationControl.h> +#include <ApplicationConverter.h> +#include "JSAlarmAbsolute.h" +#include "AlarmAbsolute.h" +#include "JSAlarmRelative.h" +#include "AlarmRelative.h" + +namespace DeviceAPI { +namespace Alarm { + +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +class AlarmConverter : public WrtDeviceApis::CommonsJavaScript::Converter +{ +public: + using Converter::toJSValueRef; + explicit AlarmConverter(JSContextRef context); + virtual ~AlarmConverter(); + + int toNativeAlarmValue(std::vector<std::string> daysOfTheWeek); + std::vector<std::string> convertFlagToDaysOfTheWeek(int byDayValue); + int toNativeValue(int interval); + std::vector<std::string> toPrivateValue(int byDayValue); + service_h toService(std::string id); + service_h toService(std::string id, std::string page); + bool toAlarmAbsolutePtr(int id, service_h handle, AlarmAbsolutePtr ptr); + bool toAlarmRelativePtr(int id, service_h handle, AlarmRelativePtr ptr); + int toNativeInterval(std::string freq, std::string interval); + bool toAlarmService(service_h alarm_service, DeviceAPI::Application::ApplicationControlPtr ptr); +}; + +typedef ConverterFactory<AlarmConverter> AlarmConverterFactory; + +} +} + +#endif /* _JS_TIZEN_ALARM_CONVERTER_H_ */ diff --git a/wearable_src/Alarm/AlarmRelative.cpp b/wearable_src/Alarm/AlarmRelative.cpp new file mode 100644 index 0000000..f58366d --- /dev/null +++ b/wearable_src/Alarm/AlarmRelative.cpp @@ -0,0 +1,101 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 "AlarmRelative.h" +#include "alarm_common.h" +#include <JSTimeDuration.h> +#include <app.h> + +namespace DeviceAPI { +namespace Alarm { + +AlarmRelative::AlarmRelative() +{ + m_isRecurrence = false; + service_create(&m_service_handle); + service_add_extra_data(m_service_handle, ALARM_TYPE_KEY, ALARM_TYPE_RELATIVE_VALUE); + m_Period = -1; + m_id = -1; + is_registered = false; +} + +AlarmRelative::AlarmRelative(service_h handle) +{ + service_clone(&m_service_handle, handle); + m_Period = -1; + m_id = -1; + is_registered = false; +} + +AlarmRelative::~AlarmRelative() +{ + service_destroy(m_service_handle); +} + +int AlarmRelative::getId() const +{ + return m_id; +} + +void AlarmRelative::setId(const int id) +{ + m_id = id; + is_registered = true; +} + +bool AlarmRelative::isRecurrence() +{ + return m_isRecurrence; +} + +void AlarmRelative::setIsRecurrence(bool value) +{ + m_isRecurrence = value; +} + +void AlarmRelative::setDelay(int delay) +{ + char result[12]; + snprintf(result, sizeof(result), "%d", delay); + service_add_extra_data(m_service_handle, ALARM_RELATIVE_DELAY_KEY, result); + m_delay = delay; +} + +int AlarmRelative::getDelay() +{ + return m_delay; +} + +void AlarmRelative::setPeriod(int value) +{ + m_Period = value; +} + +int AlarmRelative::getPeriod() +{ + return m_Period; +} + +service_h AlarmRelative::getService() +{ + return m_service_handle; +} + +} +} + diff --git a/wearable_src/Alarm/AlarmRelative.h b/wearable_src/Alarm/AlarmRelative.h new file mode 100755 index 0000000..e8a4839 --- /dev/null +++ b/wearable_src/Alarm/AlarmRelative.h @@ -0,0 +1,73 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_API_ALARMRELATIVE_H_ +#define TIZENAPIS_API_ALARMRELATIVE_H_ + +#include <string> +#include <vector> +#include <dpl/shared_ptr.h> +#include <time.h> +#include <app.h> +#include "alarm_common.h" + +namespace DeviceAPI { +namespace Alarm { + +class AlarmRelative; +typedef DPL::SharedPtr<AlarmRelative> AlarmRelativePtr; +typedef std::vector<AlarmRelativePtr> AlarmRelativeArrayPtr; + +class AlarmRelative +{ + public: + typedef enum { + ALARM_TYPE_DELAY, + ALARM_TYPE_DATE, + ALARM_TYPE_INVALID, + } alarm_type_e; + + AlarmRelative(); + AlarmRelative(service_h handle); + ~AlarmRelative(); + void setIsRecurrence(bool value); + int getId() const; + void setId(const int id); + void setDelay(int delay); + int getDelay(); + bool isRecurrence(); + void setPeriod(int value); + int getPeriod(); + service_h getService(); + + public: + bool is_registered; + + private: + int m_id; + int m_delay; + bool m_isRecurrence; + int m_Period; + service_h m_service_handle; + +}; + +} +} + +#endif diff --git a/wearable_src/Alarm/CMakeLists.txt b/wearable_src/Alarm/CMakeLists.txt new file mode 100644 index 0000000..e3ce625 --- /dev/null +++ b/wearable_src/Alarm/CMakeLists.txt @@ -0,0 +1,60 @@ +SET(TARGET_NAME ${alarm_target}) +SET(DESTINATION_NAME ${alarm_dest}) +SET(TARGET_IMPL_NAME ${alarm_impl}) + +PKG_CHECK_MODULES(platform_pkgs_alarm REQUIRED capi-appfw-application) + +ADD_DEFINITIONS("-fvisibility=hidden") + +INCLUDE_DIRECTORIES( + ${platform_pkgs_alarm_INCLUDE_DIRS} + ${INCLUDE_COMMON} + ${TOP}/Application + ${TOP}/TimeUtil +) + +SET(CMAKE_INSTALL_RPATH + ${CMAKE_INSTALL_RPATH} + ${CMAKE_INSTALL_PREFIX}/${DESTINATION_LIB_PREFIX}/${tizen_dest} + ${CMAKE_INSTALL_PREFIX}/${DESTINATION_LIB_PREFIX}/${timeutil_dest} + ${CMAKE_INSTALL_PREFIX}/${DESTINATION_LIB_PREFIX}/${application_dest} + ${CMAKE_INSTALL_PREFIX}/${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME} +) + +SET(SRCS_IMPL + AlarmAbsolute.cpp + AlarmConverter.cpp + AlarmRelative.cpp + JSAlarmAbsolute.cpp + JSAlarmManager.cpp + JSAlarmRelative.cpp +) + +ADD_LIBRARY(${TARGET_IMPL_NAME} SHARED ${SRCS_IMPL}) + +TARGET_LINK_LIBRARIES(${TARGET_IMPL_NAME} + ${LIBS_COMMON} + ${platform_pkgs_alarm_LIBRARIES} + ${tizen_impl} + ${application_impl} + ${timeutil_impl} +) + +SET(SRCS + plugin_config.cpp + plugin_initializer.cpp +) + +ADD_LIBRARY(${TARGET_NAME} SHARED ${SRCS}) + +TARGET_LINK_LIBRARIES(${TARGET_NAME} + ${TARGET_IMPL_NAME} + "-Wl,--no-as-needed" ${application_config} +) + +INSTALL(TARGETS ${TARGET_NAME} ${TARGET_IMPL_NAME} LIBRARY DESTINATION ${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME}) +INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/config.xml DESTINATION ${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME}) +INSTALL( + DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/ DESTINATION ${DESTINATION_HEADER_PREFIX}/alarm + FILES_MATCHING PATTERN "*.h" PATTERN "CMakeFiles" EXCLUDE +) diff --git a/wearable_src/Alarm/JSAlarmAbsolute.cpp b/wearable_src/Alarm/JSAlarmAbsolute.cpp new file mode 100644 index 0000000..e0f8507 --- /dev/null +++ b/wearable_src/Alarm/JSAlarmAbsolute.cpp @@ -0,0 +1,363 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 <CommonsJavaScript/JSUtils.h> +#include <CommonsJavaScript/Converter.h> +#include <CommonsJavaScript/Validator.h> +#include <CommonsJavaScript/JSDOMExceptionFactory.h> + +#include <ArgumentValidator.h> + +#include <Commons/Exception.h> +#include <JSWebAPIErrorFactory.h> +#include <SecurityExceptions.h> + +#include "AlarmAbsolute.h" +#include "AlarmConverter.h" +#include <app.h> +#include <time.h> +#include <JSUtil.h> + +#include <TimeTracer.h> +#include "plugin_config.h" +#include "JSAlarmAbsolute.h" +#include "JSAlarmManager.h" +#include <Export.h> +#include <Logger.h> + +namespace DeviceAPI { +namespace Alarm { + +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace DeviceAPI::Common; + +JSClassRef JSAlarmAbsolute::m_jsClassRef = NULL; + +JSClassDefinition JSAlarmAbsolute::m_jsClassInfo = { + 0, + kJSClassAttributeNone, + TIZEN_ALARM_ABSOLUTE_INTERFACE, + NULL, + m_property, + m_function, + initialize, + finalize, + NULL, //hasProperty, + NULL, //getProperty, + NULL, //setProperty, + NULL, //deleteProperty,Geolocation + NULL, //getPropertyNames, + NULL, + NULL, // constructor + NULL, + NULL +}; + +JSStaticFunction JSAlarmAbsolute::m_function[] = { + { ALARM_FUNCTION_API_GET_NEXT_SCHEDULED_DATE, JSAlarmAbsolute::getNextScheduledDate, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +JSStaticValue JSAlarmAbsolute::m_property[] = { + { TIZEN_ALARM_ABSOLUTE_ATTRIBUTE_ID, getId, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_ALARM_ABSOLUTE_ATTRIBUTE_DATE, getDate, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_ALARM_ABSOLUTE_ATTRIBUTE_PERIOD, getInterval, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_ALARM_ABSOLUTE_ATTRIBUTE_DAYSOFTHEWEEK, getDaysOfTheWeek, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +const JSClassRef DLL_EXPORT JSAlarmAbsolute::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_jsClassInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSAlarmAbsolute::getClassInfo() +{ + return &m_jsClassInfo; +} + +void JSAlarmAbsolute::initialize(JSContextRef context, JSObjectRef object) +{ +} +void JSAlarmAbsolute::finalize(JSObjectRef object) +{ + JSAlarmAbsolutePriv *priv = static_cast<JSAlarmAbsolutePriv*>(JSObjectGetPrivate(object)); + if (!priv) { + LoggerE("Private object is null"); + } + delete priv; + +} + + +JSObjectRef DLL_EXPORT JSAlarmAbsolute::constructor(JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) +{ + ArgumentValidator validator(ctx, argumentCount, arguments); + + AlarmAbsolutePtr priv = AlarmAbsolutePtr(new AlarmAbsolute()); + + try { + time_t date = validator.toTimeT(0); + struct tm *startDate = localtime(&date); + mktime(startDate); + + priv->setDate(*startDate); + + if (argumentCount >= 2) { + if (JSIsArrayValue(ctx, arguments[1])) { + std::vector<std::string> daysOfTheWeek = validator.toStringVector(1); + + for (size_t i = 0; i < daysOfTheWeek.size(); i++ ) { + if ( (daysOfTheWeek[i]!="SU") && (daysOfTheWeek[i]!="MO") && + (daysOfTheWeek[i]!="TU") && (daysOfTheWeek[i]!="WE") && + (daysOfTheWeek[i]!="TH") && (daysOfTheWeek[i]!="FR") && + (daysOfTheWeek[i]!="SA") ) { + // remove unacceptable data from vector + daysOfTheWeek.erase(std::remove(daysOfTheWeek.begin(), daysOfTheWeek.end(), daysOfTheWeek[i]), daysOfTheWeek.end()); + } + } + + if(daysOfTheWeek.size() > 0) { + priv->setByDayRecurrence(daysOfTheWeek); + } + } else { + long interval = validator.toLong(1); + if (interval < 0) { + throw InvalidValuesException("period can not be negative value"); + } + + priv->setInterval(interval); + } + } + } catch (const BasePlatformException& err) { + LoggerE("Exception occured while creating constructor : " << err.getMessage()); + } + + JSAlarmAbsolutePriv *jspriv = new JSAlarmAbsolutePriv(ctx, priv); + JSObjectRef obj = JSObjectMake(ctx, getClassRef(), jspriv); + + JSStringRef ctorName = JSStringCreateWithUTF8CString("constructor"); + JSObjectSetProperty(ctx, obj, ctorName, constructor, + kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete | kJSPropertyAttributeDontEnum, NULL); + JSStringRelease(ctorName); + + return obj; +} + +AlarmAbsolutePtr JSAlarmAbsolute::getPrivData(JSObjectRef object) +{ + JSAlarmAbsolutePriv *priv = static_cast<JSAlarmAbsolutePriv*>(JSObjectGetPrivate(object)); + if (!priv) { + throw TypeMismatchException("Private object is null"); + } + AlarmAbsolutePtr result = priv->getObject(); + if (!result) { + throw TypeMismatchException("Private object is null"); + } + return result; +} + + +JSValueRef JSAlarmAbsolute::createJSObject(JSContextRef context, AlarmAbsolutePtr privateData) +{ + JSAlarmAbsolutePriv *priv = new JSAlarmAbsolutePriv(context, privateData); + if (!priv) { + throw TypeMismatchException("Private object is null"); + } + return JSObjectMake(context, getClassRef(), static_cast<void*>(priv)); +} + +JSValueRef JSAlarmAbsolute::getNextScheduledDate( JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + try { + struct tm date; + Converter converter(ctx); + + AlarmAbsolutePtr privateData = getPrivData(thisObject); + if (!privateData) { + throw TypeMismatchException("Private object is null"); + } + + if(!privateData->is_registered) { + return JSValueMakeNull(ctx); + } + + int id = privateData->getId(); + TIME_TRACER_ITEM_BEGIN("(getNextScheduledDate)alarm_get_scheduled_date", 0); + int err = alarm_get_scheduled_date(id, &date); + TIME_TRACER_ITEM_END("(getNextScheduledDate)alarm_get_scheduled_date", 0); + if(err != ALARM_ERROR_NONE) { + return JSValueMakeNull(ctx); + } + + // check wheter the alarm is expired or not + struct tm curr_date; + TIME_TRACER_ITEM_BEGIN("(getNextScheduledDate)alarm_get_current_time", 0); + err = alarm_get_current_time(&curr_date); + TIME_TRACER_ITEM_END("(getNextScheduledDate)alarm_get_current_time", 0); + if(err != ALARM_ERROR_NONE) { + return JSValueMakeNull(ctx); + } + + if (mktime(&date) < mktime(&curr_date)) { + return JSValueMakeNull(ctx); + } + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + + return converter.toJSValueRef(date); + + } catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(ctx, exception, err); + } catch (...) { + DeviceAPI::Common::UnknownException err("Unknown Error in ApplicationManager.getAppSharedURI()."); + return JSWebAPIErrorFactory::postException(ctx, exception, err); + } +} + +JSValueRef JSAlarmAbsolute::getDate(JSContextRef ctx, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Converter converter(ctx); + struct tm date; + + try { + AlarmAbsolutePtr privateData = getPrivData(object); + if (!privateData) { + throw TypeMismatchException("Private object is null"); + } + + date = privateData->getDate(); + LoggerI("JSAlarmAbsolute Date = " << " Sec : " << date.tm_sec << " Min : "<< date.tm_min + << " Hour" << date.tm_hour << "Day : " << date.tm_mday << " MON : " << date.tm_mon + << " Year : " << date.tm_year); + + JSValueRef args[6]; + args[0] = JSValueMakeNumber(ctx, date.tm_year + 1900); + args[1] = JSValueMakeNumber(ctx, date.tm_mon); + args[2] = JSValueMakeNumber(ctx, date.tm_mday); + args[3] = JSValueMakeNumber(ctx, date.tm_hour); + args[4] = JSValueMakeNumber(ctx, date.tm_min); + args[5] = JSValueMakeNumber(ctx, date.tm_sec); + + JSObjectRef result = JSObjectMakeDate(ctx, 6, args, exception); + return result; + } catch (...) { + LoggerE("Exception: occured"); + } + + return JSValueMakeUndefined(ctx); +} + +JSValueRef JSAlarmAbsolute::getId(JSContextRef ctx, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + try { + AlarmAbsolutePtr privateData = getPrivData(object); + if (!privateData) { + throw TypeMismatchException("Private object is null"); + } + + Converter converter(ctx); + if (privateData->is_registered) { + std::string strId = converter.toString(privateData->getId()); + return converter.toJSValueRef(strId); + } else { + return JSValueMakeNull(ctx); + } + } catch (...) { + LoggerE("Exception: occured"); + } + + return JSValueMakeUndefined(ctx); +} + +JSValueRef JSAlarmAbsolute::getInterval(JSContextRef ctx, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + try { + AlarmAbsolutePtr privateData = getPrivData(object); + AbsoluteRecurrence::Type alarmType = privateData->getRecurrenceType(); + + if(alarmType == AbsoluteRecurrence::Interval) { + long interval = privateData->getInterval(); + if (interval == -1 ) { + return JSValueMakeNull(ctx); + } else { + return DeviceAPI::Common::JSUtil::toJSValueRef(ctx, interval); + } + } else { + return JSValueMakeNull(ctx); + } + } catch (...) { + LoggerI("Exception: occured"); + } + + return JSValueMakeUndefined(ctx); +} + +JSValueRef JSAlarmAbsolute::getDaysOfTheWeek(JSContextRef ctx, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Converter converter(ctx); + + try { + AlarmAbsolutePtr privateData = getPrivData(object); + if (!privateData) { + throw TypeMismatchException("Private object is null"); + } + + JSObjectRef jsResult = JSCreateArrayObject(ctx, 0, NULL); + if (jsResult == NULL) { + throw UnknownException("Could not create js array object"); + } + + std::vector<std::string> daysOfTheWeek = privateData->getByDayRecurrence(); + + if(daysOfTheWeek.size() > 0) { + for(size_t i = 0; i<daysOfTheWeek.size(); i++) { + JSValueRef val = converter.toJSValueRef(daysOfTheWeek.at(i)); + if(!JSSetArrayElement(ctx, jsResult, i, val)) { + throw UnknownException("Could not insert value into js array"); + } + } + } + + return jsResult; + } catch (...) { + LoggerI("Exception: occured"); + } + + return JSValueMakeUndefined(ctx); +} + +} // Alarm +} // TizenApis + + diff --git a/wearable_src/Alarm/JSAlarmAbsolute.h b/wearable_src/Alarm/JSAlarmAbsolute.h new file mode 100755 index 0000000..b9ee64f --- /dev/null +++ b/wearable_src/Alarm/JSAlarmAbsolute.h @@ -0,0 +1,84 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 _JS_TIZEN_JSALARMABSOLUTE +#define _JS_TIZEN_JSALARMABSOLUTE + +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/PrivateObject.h> +#include <IApplicationManager.h> +#include "AlarmAbsolute.h" + +namespace DeviceAPI { +namespace Alarm { + +#define TIZEN_ALARM_ABSOLUTE_INTERFACE "AlarmAbsolute" + +#define TIZEN_ALARM_ABSOLUTE_ATTRIBUTE_ID "id" +#define TIZEN_ALARM_ABSOLUTE_ATTRIBUTE_DATE "date" +#define TIZEN_ALARM_ABSOLUTE_ATTRIBUTE_PERIOD "period" +#define TIZEN_ALARM_ABSOLUTE_ATTRIBUTE_DAYSOFTHEWEEK "daysOfTheWeek" + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject<AlarmAbsolutePtr, WrtDeviceApis::CommonsJavaScript::NoOwnership> JSAlarmAbsolutePriv; + +class JSAlarmAbsolute { +public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSObjectRef constructor(JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + static JSValueRef createJSObject(JSContextRef context, AlarmAbsolutePtr privateData); + +protected: + static void initialize(JSContextRef context, JSObjectRef object); + static void finalize(JSObjectRef object); + static JSValueRef getNextScheduledDate(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + +private: + static AlarmAbsolutePtr getPrivData(JSObjectRef object); + + static JSValueRef getDate(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getId(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getInterval(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getDaysOfTheWeek(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + + static JSClassDefinition m_jsClassInfo; + static JSClassRef m_jsClassRef; + static JSStaticFunction m_function[]; + static JSStaticValue m_property[]; +}; + +}// Alarm +} // TizenApis + +#endif diff --git a/wearable_src/Alarm/JSAlarmManager.cpp b/wearable_src/Alarm/JSAlarmManager.cpp new file mode 100644 index 0000000..e572cc4 --- /dev/null +++ b/wearable_src/Alarm/JSAlarmManager.cpp @@ -0,0 +1,516 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 <vector> +#include <app.h> +#include <time.h> +#include <string> + +#include <CommonsJavaScript/Converter.h> +#include <CommonsJavaScript/Validator.h> +#include <CommonsJavaScript/JSUtils.h> +#include <CommonsJavaScript/JSDOMExceptionFactory.h> + +#include <ArgumentValidator.h> +#include <JSUtil.h> + +#include <SecurityExceptions.h> +#include <Commons/Exception.h> +#include <Commons/Regex.h> +#include <JSWebAPIErrorFactory.h> +#include <JSApplicationControl.h> +#include <ApplicationControl.h> +#include <ApplicationConverter.h> + +#include <ail.h> + +#include "plugin_config.h" +#include "AlarmConverter.h" +#include "JSAlarmAbsolute.h" +#include "AlarmAbsolute.h" +#include "JSAlarmRelative.h" +#include "AlarmRelative.h" +#include "JSAlarmManager.h" + +#include <TimeTracer.h> +#include <Export.h> +#include <Logger.h> + +namespace DeviceAPI { +namespace Alarm { + +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace DeviceAPI::Common; + +static bool alarm_iterate_callback(int alarm_id, void *user_data) +{ + std::vector<int> *alarmIds = reinterpret_cast<std::vector<int>*>(user_data); + + alarmIds->push_back(alarm_id); + return true; +} + +JSClassRef JSAlarmManager::m_jsClassRef = NULL; + +JSClassDefinition JSAlarmManager::m_jsClassInfo = { + 0, + kJSClassAttributeNone, + TIZEN_ALARM_INTERFACE, + NULL, + m_property, + m_function, + initialize, + finalize, + NULL, //hasProperty, + NULL, //getProperty, + NULL, //setProperty, + NULL, //deleteProperty,Geolocation + NULL, //getPropertyNames, + NULL, + NULL, // constructor + NULL, + NULL +}; + +JSStaticFunction JSAlarmManager::m_function[] = { + { ALARM_FUNCTION_API_ADD, JSAlarmManager::add,kJSPropertyAttributeNone }, + { ALARM_FUNCTION_API_REMOVE, JSAlarmManager::remove,kJSPropertyAttributeNone }, + { ALARM_FUNCTION_API_REMOVE_ALL, JSAlarmManager::removeAll,kJSPropertyAttributeNone }, + { ALARM_FUNCTION_API_GET_ALL, JSAlarmManager::getAll,kJSPropertyAttributeNone }, + { ALARM_FUNCTION_API_GET, JSAlarmManager::get,kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +JSStaticValue JSAlarmManager::m_property[] = { + { TIZEN_ALARM_CONSTANT_PERIOD_MINUTE, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_ALARM_CONSTANT_PERIOD_HOUR, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_ALARM_CONSTANT_PERIOD_DAY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_ALARM_CONSTANT_PERIOD_WEEK, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +const JSClassRef DLL_EXPORT JSAlarmManager::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_jsClassInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSAlarmManager::getClassInfo() +{ + return &m_jsClassInfo; +} + +JSContextRef JSAlarmManager::gContext = NULL; + +void JSAlarmManager::initialize(JSContextRef ctx, JSObjectRef object) +{ + gContext = ctx; +} + +void JSAlarmManager::finalize(JSObjectRef object) +{ +} + +JSValueRef JSAlarmManager::add(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + service_h service; + struct tm startDate; + int delay = 0; + int alarm_id; + std::string applicationId; + std::string page; + + TIME_TRACER_ITEM_BEGIN("(add)ace_check", 0); + AceSecurityStatus status = ALARM_CHECK_ACCESS(ALARM_FUNCTION_API_ADD); + TIZEN_SYNC_ACCESS_HANDLER(status, ctx, exception); + TIME_TRACER_ITEM_END("(add)ace_check", 0); + + try { + ArgumentValidator validator(ctx, argumentCount, arguments); + AlarmConverter converter(ctx); + + // applicationId + std::string appId = validator.toString(1); + + // alarm + JSObjectRef alarmObj = validator.toObject(0); + if (JSValueIsObjectOfClass(ctx, alarmObj, JSAlarmAbsolute::getClassRef())) { + + JSAlarmAbsolutePriv *priv = static_cast<JSAlarmAbsolutePriv*>(JSObjectGetPrivate(alarmObj)); + if (!priv) { + throw TypeMismatchException("Object is null."); + } + AlarmAbsolutePtr alarmPtr = priv->getObject(); + if (!alarmPtr) { + throw TypeMismatchException("Private object is null."); + } + + startDate = alarmPtr->getDate(); + service = alarmPtr->getService(); + service_set_app_id(service, appId.c_str()); + + // appControl + JSObjectRef appControlObj = validator.toObject(2, true); + if (appControlObj) { + if(!JSValueIsObjectOfClass(ctx, appControlObj, DeviceAPI::Application::JSApplicationControl::getClassRef())) { + throw TypeMismatchException("Third parameter is not a ApplicationControl object"); + } + DeviceAPI::Application::ApplicationConverter applicationConverter(ctx); + DeviceAPI::Application::ApplicationControlPtr appService = applicationConverter.toApplicationControl(appControlObj); + if(converter.toAlarmService(service, appService) == false) { + throw TypeMismatchException("Third parameter is not a ApplicationControl object"); + } + } else { + service_set_operation(service, SERVICE_OPERATION_DEFAULT); + } + + AbsoluteRecurrence::Type alarmType = alarmPtr->getRecurrenceType(); + + int err = ALARM_ERROR_NONE; + if(alarmType == AbsoluteRecurrence::ByDayValue) { + int bydayValue = converter.toNativeAlarmValue(alarmPtr->getByDayRecurrence()); + LoggerI("Native bydayValue = " << bydayValue); + TIME_TRACER_ITEM_BEGIN("(add)alarm_schedule_with_recurrence_week_flag", 0); + err = alarm_schedule_with_recurrence_week_flag(service, &startDate, bydayValue, &alarm_id); + TIME_TRACER_ITEM_END("(add)alarm_schedule_with_recurrence_week_flag", 0); + + } else if(alarmType == AbsoluteRecurrence::Interval) { + int interval = alarmPtr->getInterval(); + TIME_TRACER_ITEM_BEGIN("(add)alarm_schedule_at_date", 0); + err = alarm_schedule_at_date(service, &startDate, interval, &alarm_id); + TIME_TRACER_ITEM_END("(add)alarm_schedule_at_date", 0); + } else { + TIME_TRACER_ITEM_BEGIN("(add)alarm_schedule_at_date", 0); + err = alarm_schedule_at_date(service, &startDate, 0, &alarm_id); + TIME_TRACER_ITEM_END("(add)alarm_schedule_at_date", 0); + } + + if(err == ALARM_ERROR_NONE) { + alarmPtr->setId(alarm_id); + } else { + throw UnknownException("Alarm scheduling failed."); + } + + } else if (JSValueIsObjectOfClass(ctx, alarmObj, JSAlarmRelative::getClassRef())) { + + JSAlarmRelativePriv *priv = static_cast<JSAlarmRelativePriv*>(JSObjectGetPrivate(alarmObj)); + if (!priv) { + throw TypeMismatchException("Object is null."); + } + AlarmRelativePtr alarmPtr = priv->getObject(); + if (!alarmPtr) { + throw TypeMismatchException("Private object is null."); + } + + delay = alarmPtr->getDelay(); + if (delay < 0) { + throw InvalidValuesException("Alarm scheduling failed : delay cannot be negative value."); + } + + long interval = alarmPtr->getPeriod(); + service = alarmPtr->getService(); + service_set_app_id(service, appId.c_str()); + + // appControl + JSObjectRef appControlObj = validator.toObject(2, true); + if (appControlObj) { + if(!JSValueIsObjectOfClass(ctx, appControlObj, DeviceAPI::Application::JSApplicationControl::getClassRef())) { + throw TypeMismatchException("Third parameter is not a ApplicationControl object"); + } + DeviceAPI::Application::ApplicationConverter applicationConverter(ctx); + DeviceAPI::Application::ApplicationControlPtr appService = applicationConverter.toApplicationControl(appControlObj); + if(converter.toAlarmService(service, appService) == false) { + throw TypeMismatchException("Third parameter is not a ApplicationControl object"); + } + } else { + service_set_operation(service, SERVICE_OPERATION_DEFAULT); + } + + TIME_TRACER_ITEM_BEGIN("(add)alarm_schedule_after_delay", 0); + int err = alarm_schedule_after_delay(service, delay, interval, &alarm_id); + TIME_TRACER_ITEM_END("(add)alarm_schedule_after_delay", 0); + + if(err == ALARM_ERROR_NONE) { + alarmPtr->setId(alarm_id); + } else { + throw UnknownException("Alarm scheduling failed."); + } + + } else { + LoggerE("First parameter is not a Alarm object"); + throw TypeMismatchException("First parameter is not a Alarm object"); + } + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(ctx); + + } catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(ctx, exception, err); + } catch (...) { + DeviceAPI::Common::UnknownException err("Unknown Error in ApplicationManager.getAppSharedURI()."); + return JSWebAPIErrorFactory::postException(ctx, exception, err); + } +} + +JSValueRef JSAlarmManager::remove(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + TIME_TRACER_ITEM_BEGIN("(add)ace_check", 0); + AceSecurityStatus status = ALARM_CHECK_ACCESS(ALARM_FUNCTION_API_REMOVE); + TIZEN_SYNC_ACCESS_HANDLER(status, ctx, exception); + TIME_TRACER_ITEM_END("(add)ace_check", 0); + + try { + ArgumentValidator validator(ctx, argumentCount, arguments); + + // id + std::string id = validator.toString(0); + + int alarmId = 0; + std::stringstream(id) >> alarmId; + + if (alarmId <= 0) { + throw InvalidValuesException("Invalid ID"); + } + + TIME_TRACER_ITEM_BEGIN("(remove)alarm_cancel", 0); + int ret = alarm_cancel(alarmId); + TIME_TRACER_ITEM_END("(remove)alarm_cancel", 0); + + if (ret != ALARM_ERROR_NONE) { + throw NotFoundException("Alarm not found"); + } + + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(ctx); + } catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(ctx, exception, err); + } catch (...) { + DeviceAPI::Common::UnknownException err("Unknown Error in ApplicationManager.getAppSharedURI()."); + return JSWebAPIErrorFactory::postException(ctx, exception, err); + } +} + +JSValueRef JSAlarmManager::removeAll(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + TIME_TRACER_ITEM_BEGIN("(add)ace_check", 0); + AceSecurityStatus status = ALARM_CHECK_ACCESS(ALARM_FUNCTION_API_REMOVE_ALL); + TIZEN_SYNC_ACCESS_HANDLER(status, ctx, exception); + TIME_TRACER_ITEM_END("(add)ace_check", 0); + + TIME_TRACER_ITEM_BEGIN("(removeAll)alarm_cancel_all", 0); + int returnVal = alarm_cancel_all(); + TIME_TRACER_ITEM_END("(removeAll)alarm_cancel_all", 0); + + if (ALARM_ERROR_NONE != returnVal) { + LoggerE("Error while removing all alarms: "<< returnVal); + } + + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(ctx); +} + +JSValueRef JSAlarmManager::get(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + try { + service_h service = NULL; + char* alarmType = NULL; + JSValueRef result = NULL; + + ArgumentValidator validator(ctx, argumentCount, arguments); + AlarmConverter converter(ctx); + + // id + std::string id = validator.toString(0); + int alarmId = 0; + std::stringstream(id) >> alarmId; + + if (alarmId <= 0) { + LoggerE("Wrong Alarm ID"); + throw InvalidValuesException("Invalid ID"); + } + + TIME_TRACER_ITEM_BEGIN("(get)alarm_get_service", 0); + int ret = alarm_get_service(alarmId, &service); + + if (ret != ALARM_ERROR_NONE) { + throw NotFoundException("Alarm not found"); + } + + ret = service_get_extra_data(service, ALARM_TYPE_KEY, &alarmType); + if (ret != SERVICE_ERROR_NONE) { + LoggerE("Getting data failed: " << ret); + service_destroy(service); + throw UnknownException("Unknown error occurred."); + } + TIME_TRACER_ITEM_END("(get)alarm_get_service", 0); + + if (strcmp(alarmType, ALARM_TYPE_ABSOLUTE_VALUE) == 0) { + AlarmAbsolutePtr privateData = AlarmAbsolutePtr(new AlarmAbsolute(service)); + + if(!converter.toAlarmAbsolutePtr(alarmId, service, privateData)) { + service_destroy(service); + throw TypeMismatchException("Alarm not found"); + } + + result = JSAlarmAbsolute::createJSObject(ctx, privateData); + + } else if(strcmp(alarmType, ALARM_TYPE_RELATIVE_VALUE) == 0) { + AlarmRelativePtr privateData = AlarmRelativePtr(new AlarmRelative(service)); + + if(!converter.toAlarmRelativePtr(alarmId, service, privateData)) { + service_destroy(service); + throw TypeMismatchException("Alarm not found"); + } + + result = JSAlarmRelative::createJSObject(ctx, privateData); + } else { + service_destroy(service); + throw UnknownException("Unknown error occurred."); + } + + service_destroy(service); + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return result; + } catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(ctx, exception, err); + } catch (...) { + DeviceAPI::Common::UnknownException err("Unknown Error in ApplicationManager.getAppSharedURI()."); + return JSWebAPIErrorFactory::postException(ctx, exception, err); + } +} + + +JSValueRef JSAlarmManager::getAll(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + try { + AlarmConverter converter(ctx); + std::vector<int> alarmIds; + + TIME_TRACER_ITEM_BEGIN("(getAll)alarm_foreach_registered_alarm", 0); + int error = alarm_foreach_registered_alarm(alarm_iterate_callback, &alarmIds); + TIME_TRACER_ITEM_END("(getAll)alarm_foreach_registered_alarm", 0); + if (error == ALARM_ERROR_CONNECTION_FAIL) { + LoggerE("Alarm system may not be ready yet."); + alarmIds.clear(); + } else if(error != ALARM_ERROR_NONE) { + LoggerE("Error occurred while getting all alarms : " << error); + throw UnknownException("Unknown error occurred."); + } + + JSObjectRef jsResult = JSCreateArrayObject(ctx, 0, NULL); + if (jsResult == NULL) { + throw TypeMismatchException("Could not create js array object."); + } + + for (size_t i = 0 ; i < alarmIds.size(); i++) { + + service_h handle = NULL; + char* alarmType = NULL; + + TIME_TRACER_ITEM_BEGIN("(getAll)alarm_get_service", 0); + error = alarm_get_service(alarmIds.at(i), &handle); + TIME_TRACER_ITEM_END("(getAll)alarm_get_service", 0); + if(error != ALARM_ERROR_NONE) { + LoggerE("Getting service failed: " << error); + throw NotFoundException("Alarm not found"); + } + + TIME_TRACER_ITEM_BEGIN("(getAll)service_get_extra_data", 0); + error = service_get_extra_data(handle, ALARM_TYPE_KEY, &alarmType); + TIME_TRACER_ITEM_END("(getAll)service_get_extra_data", 0); + if(error != SERVICE_ERROR_NONE) { + LoggerI("Getting data failed: " << error); + service_destroy(handle); + throw UnknownException("Unknown error occurred."); + } + + JSValueRef obj = NULL; + if (strcmp(alarmType, ALARM_TYPE_ABSOLUTE_VALUE) == 0) { + AlarmAbsolutePtr privateData = AlarmAbsolutePtr(new AlarmAbsolute(handle)); + + if(!converter.toAlarmAbsolutePtr(alarmIds.at(i), handle, privateData)) { + service_destroy(handle); + throw TypeMismatchException("Absolute alarm conversion failed."); + } + + obj = JSAlarmAbsolute::createJSObject(ctx, privateData); + + } else if( !strcmp(alarmType, ALARM_TYPE_RELATIVE_VALUE)) { + AlarmRelativePtr privateData = AlarmRelativePtr(new AlarmRelative(handle)); + + if(!converter.toAlarmRelativePtr(alarmIds.at(i), handle, privateData)) { + service_destroy(handle); + throw TypeMismatchException("Relative alarm conversion failed."); + } + obj = JSAlarmRelative::createJSObject(ctx, privateData); + + } else { + service_destroy(handle); + throw UnknownException("Unknown error occurred."); + } + + service_destroy(handle); + + if(!JSSetArrayElement(ctx, jsResult, i, obj)) { + service_destroy(handle); + throw UnknownException("JS array creation failed."); + } + } + + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return jsResult; + } catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(ctx, exception, err); + } catch (...) { + DeviceAPI::Common::UnknownException err("Unknown Error in ApplicationManager.getAppSharedURI()."); + return JSWebAPIErrorFactory::postException(ctx, exception, err); + } +} + +JSValueRef JSAlarmManager::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + try { + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_ALARM_CONSTANT_PERIOD_MINUTE)) { + return JSUtil::toJSValueRef(context, (long)60); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_ALARM_CONSTANT_PERIOD_HOUR)) { + return JSUtil::toJSValueRef(context, (long)3600); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_ALARM_CONSTANT_PERIOD_DAY)) { + return JSUtil::toJSValueRef(context, (long)86400); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_ALARM_CONSTANT_PERIOD_WEEK)) { + return JSUtil::toJSValueRef(context, (long)604800); + } + } catch (const BasePlatformException &err) { + LoggerE("Getting property is failed. %s", err.getMessage().c_str()); + } + + return NULL; +} + +} // Alarm +} // TizenApis + diff --git a/wearable_src/Alarm/JSAlarmManager.h b/wearable_src/Alarm/JSAlarmManager.h new file mode 100755 index 0000000..7100030 --- /dev/null +++ b/wearable_src/Alarm/JSAlarmManager.h @@ -0,0 +1,66 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 _JS_TIZEN_ALARM_MANAGER +#define _JS_TIZEN_ALARM_MANAGER + +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/PrivateObject.h> + +namespace DeviceAPI { +namespace Alarm { + +#define TIZEN_ALARM_INTERFACE "AlarmManager" + +#define TIZEN_ALARM_CONSTANT_PERIOD_MINUTE "PERIOD_MINUTE" +#define TIZEN_ALARM_CONSTANT_PERIOD_HOUR "PERIOD_HOUR" +#define TIZEN_ALARM_CONSTANT_PERIOD_DAY "PERIOD_DAY" +#define TIZEN_ALARM_CONSTANT_PERIOD_WEEK "PERIOD_WEEK" + +class JSAlarmManager { +public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSContextRef gContext; + +protected: + static void initialize(JSContextRef context, JSObjectRef object); + static void finalize(JSObjectRef object); + static JSValueRef add(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + static JSValueRef remove(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + static JSValueRef removeAll(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + static JSValueRef get(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + static JSValueRef getAll(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + +private: + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSClassDefinition m_jsClassInfo; + static JSClassRef m_jsClassRef; + static JSStaticFunction m_function[]; + static JSStaticValue m_property[]; + +}; + +} +} // TizenApis + +#endif diff --git a/wearable_src/Alarm/JSAlarmRelative.cpp b/wearable_src/Alarm/JSAlarmRelative.cpp new file mode 100644 index 0000000..9fd962c --- /dev/null +++ b/wearable_src/Alarm/JSAlarmRelative.cpp @@ -0,0 +1,314 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 <CommonsJavaScript/JSUtils.h> +#include <CommonsJavaScript/Converter.h> +#include <CommonsJavaScript/Validator.h> +#include <CommonsJavaScript/JSDOMExceptionFactory.h> + +#include <ArgumentValidator.h> + +#include <Commons/Exception.h> +#include <JSWebAPIErrorFactory.h> +#include <SecurityExceptions.h> + +#include "plugin_config.h" + +#include "AlarmRelative.h" +#include "AlarmConverter.h" +#include "JSAlarmRelative.h" +#include "JSAlarmManager.h" + +#include <JSUtil.h> + +#include <TimeTracer.h> +#include <app.h> +#include <time.h> +#include <Export.h> +#include <Logger.h> + +namespace DeviceAPI { +namespace Alarm { + +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace DeviceAPI::Common; + +JSClassRef JSAlarmRelative::m_jsClassRef = NULL; + +JSClassDefinition JSAlarmRelative::m_jsClassInfo = { + 0, + kJSClassAttributeNone, + TIZEN_ALARM_RELATIVE_INTERFACE, + NULL, + m_property, + m_function, + initialize, + finalize, + NULL, //hasProperty, + NULL, //getProperty, + NULL, //setProperty, + NULL, //deleteProperty,Geolocation + NULL, //getPropertyNames, + NULL, + NULL, // constructor + NULL, + NULL +}; + +JSStaticFunction JSAlarmRelative::m_function[] = { + { ALARM_FUNCTION_API_GET_REMAINING_SECONDS, JSAlarmRelative::getRemainingSeconds, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +JSStaticValue JSAlarmRelative::m_property[] = { + { TIZEN_ALARM_RELATIVE_ATTRIBUTE_ID, getId, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_ALARM_RELATIVE_ATTRIBUTE_DELAY, getDelay, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_ALARM_RELATIVE_ATTRIBUTE_PERIOD, getPeriod, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +const JSClassRef DLL_EXPORT JSAlarmRelative::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_jsClassInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSAlarmRelative::getClassInfo() +{ + return &m_jsClassInfo; +} + +void JSAlarmRelative::initialize(JSContextRef context, JSObjectRef object) +{ +} +void JSAlarmRelative::finalize(JSObjectRef object) +{ + JSAlarmRelativePriv *priv = static_cast<JSAlarmRelativePriv*>(JSObjectGetPrivate(object)); + if (!priv) { + LoggerE("Private object is null"); + } + delete priv; +} + + +JSObjectRef DLL_EXPORT JSAlarmRelative::constructor(JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) +{ + ArgumentValidator validator(ctx, argumentCount, arguments); + + AlarmRelativePtr privateData = AlarmRelativePtr(new AlarmRelative()); + + try { + long delay = validator.toLong(0); + privateData->setDelay(delay); + + long period = validator.toLong(1, true, -1); + privateData->setPeriod(period); + + } catch (const BasePlatformException& err) { + LoggerE("Exception occured while creating constructor : " << err.getMessage()); + } + + JSAlarmRelativePriv *priv = new JSAlarmRelativePriv(ctx, privateData); + JSObjectRef obj = JSObjectMake(ctx, getClassRef(), priv); + + JSStringRef ctorName = JSStringCreateWithUTF8CString("constructor"); + JSObjectSetProperty(ctx, obj, ctorName, constructor, + kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete | kJSPropertyAttributeDontEnum, NULL); + JSStringRelease(ctorName); + + return obj; +} + +AlarmRelativePtr JSAlarmRelative::getPrivData(JSObjectRef object) +{ + JSAlarmRelativePriv *priv = static_cast<JSAlarmRelativePriv*>(JSObjectGetPrivate(object)); + if (!priv) { + throw TypeMismatchException("Private object is null"); + } + AlarmRelativePtr result = priv->getObject(); + if (!result) { + throw TypeMismatchException("Private object is null"); + } + return result; +} + +JSValueRef JSAlarmRelative::createJSObject(JSContextRef context, AlarmRelativePtr privateData) +{ + JSAlarmRelativePriv *priv = new JSAlarmRelativePriv(context, privateData); + if (!priv) { + throw TypeMismatchException("Private object is null"); + } + return JSObjectMake(context, getClassRef(), static_cast<void*>(priv)); +} + + +JSValueRef JSAlarmRelative::createJSObject(JSContextRef context, int delay, int interval) +{ + AlarmRelativePtr privateData = AlarmRelativePtr(new AlarmRelative()); + privateData->setDelay(delay); + privateData->setPeriod(interval); + + JSAlarmRelativePriv *priv = new JSAlarmRelativePriv(context, privateData); + if (!priv) { + throw TypeMismatchException("Private object is null"); + } + return JSObjectMake(context, getClassRef(), static_cast<void*>(priv)); +} + +JSValueRef JSAlarmRelative::getRemainingSeconds(JSContextRef ctx, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) +{ + struct tm date; + struct tm current; + time_t currentTime; + time_t nextTime; + int id; + + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + + try { + AlarmRelativePtr privateData = getPrivData(thisObject); + + if(!privateData->is_registered) { + return JSValueMakeNull(ctx); + } + + id = privateData->getId(); + + TIME_TRACER_ITEM_BEGIN("(getRemainingSeconds)alarm_get_scheduled_date", 0); + int err = alarm_get_scheduled_date(id, &date); + TIME_TRACER_ITEM_END("(getRemainingSeconds)alarm_get_scheduled_date", 0); + if(err != ALARM_ERROR_NONE) + { + LoggerI("alarm_get_scheduled_date error =" << err); + if(err == ALARM_ERROR_INVALID_PARAMETER || err== ALARM_ERROR_CONNECTION_FAIL) { + return JSValueMakeNull(ctx); + } else { + throw UnknownException("Unknown exception occurred. fail to get scheduled date"); + } + } + + TIME_TRACER_ITEM_BEGIN("(getRemainingSeconds)alarm_get_current_time", 0); + alarm_get_current_time(¤t); + + nextTime = mktime(&date); + currentTime = mktime(¤t); + TIME_TRACER_ITEM_END("(getRemainingSeconds)alarm_get_current_time", 0); + + long result = nextTime - currentTime; + + LoggerI("nextTime: "<<nextTime<<", currentTime: "<<currentTime<<", result: "<<result); + + if(result < 0) { + return JSValueMakeNull(ctx); + } + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + + return DeviceAPI::Common::JSUtil::toJSValueRef(ctx, result); + } catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(ctx, exception, err); + } catch (...) { + DeviceAPI::Common::UnknownException err("Unknown Error in ApplicationManager.getAppSharedURI()."); + return JSWebAPIErrorFactory::postException(ctx, exception, err); + } +} + +JSValueRef JSAlarmRelative::getId(JSContextRef ctx, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Converter converter(ctx); + + try { + AlarmRelativePtr privateData = getPrivData(object); + if (!privateData) { + throw TypeMismatchException("Private object is null"); + } + + if(privateData->is_registered) { + std::string strId = converter.toString(privateData->getId()); + return converter.toJSValueRef(strId); + } else { + return JSValueMakeNull(ctx); + } + } catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(ctx, exception, err); + } catch (...) { + DeviceAPI::Common::TypeMismatchException err("TypeMismatchException occured"); + return JSWebAPIErrorFactory::postException(ctx, exception, err); + } +} + +JSValueRef JSAlarmRelative::getDelay(JSContextRef ctx, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + long delay; + + try { + AlarmRelativePtr privateData = getPrivData(object); + if (!privateData) { + throw TypeMismatchException("Private object is null"); + } + + delay = privateData->getDelay(); + LoggerI("JSAlarmRelative delay = " << delay); + return DeviceAPI::Common::JSUtil::toJSValueRef(ctx, delay); + } catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(ctx, exception, err); + } catch (...) { + DeviceAPI::Common::TypeMismatchException err("TypeMismatchException occured"); + return JSWebAPIErrorFactory::postException(ctx, exception, err); + } +} + +JSValueRef JSAlarmRelative::getPeriod(JSContextRef ctx, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + long period =0; + + try { + AlarmRelativePtr privateData = getPrivData(object); + if (!privateData) { + throw TypeMismatchException("Private object is null"); + } + + period = privateData->getPeriod(); + LoggerI("JSAlarmRelative interval = " << period); + if(period == -1) { + return JSValueMakeNull(ctx); + } else { + return DeviceAPI::Common::JSUtil::toJSValueRef(ctx, period); + } + } catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(ctx, exception, err); + } catch (...) { + DeviceAPI::Common::TypeMismatchException err("TypeMismatchException occured"); + return JSWebAPIErrorFactory::postException(ctx, exception, err); + } +} + +} // Alarm +} // TizenApis + + diff --git a/wearable_src/Alarm/JSAlarmRelative.h b/wearable_src/Alarm/JSAlarmRelative.h new file mode 100755 index 0000000..fee01ff --- /dev/null +++ b/wearable_src/Alarm/JSAlarmRelative.h @@ -0,0 +1,78 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 _JS_TIZEN_ALARMRELATIVE +#define _JS_TIZEN_ALARMRELATIVE + +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/PrivateObject.h> +#include <IApplicationManager.h> +#include "AlarmRelative.h" + +namespace DeviceAPI { +namespace Alarm { + +#define TIZEN_ALARM_RELATIVE_INTERFACE "AlarmRelative" + +#define TIZEN_ALARM_RELATIVE_ATTRIBUTE_ID "id" +#define TIZEN_ALARM_RELATIVE_ATTRIBUTE_DELAY "delay" +#define TIZEN_ALARM_RELATIVE_ATTRIBUTE_PERIOD "period" + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject<AlarmRelativePtr, WrtDeviceApis::CommonsJavaScript::NoOwnership> JSAlarmRelativePriv; + +class JSAlarmRelative { +public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSValueRef createJSObject(JSContextRef context, AlarmRelativePtr privateData); + static JSValueRef createJSObject(JSContextRef context, int delay, int interval); + static JSObjectRef constructor(JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + +protected: + static void initialize(JSContextRef context, JSObjectRef object); + static void finalize(JSObjectRef object); + static JSValueRef getRemainingSeconds(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + +private: + static AlarmRelativePtr getPrivData(JSObjectRef object); + + static JSValueRef getId(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getDelay(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getPeriod(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSClassDefinition m_jsClassInfo; + static JSClassRef m_jsClassRef; + static JSStaticFunction m_function[]; + static JSStaticValue m_property[]; +}; + +}// Alarm +} // TizenApis + +#endif diff --git a/wearable_src/Alarm/alarm_common.h b/wearable_src/Alarm/alarm_common.h new file mode 100755 index 0000000..bd38edf --- /dev/null +++ b/wearable_src/Alarm/alarm_common.h @@ -0,0 +1,61 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_API_ALARM_COMMON_H_ +#define TIZENAPIS_API_ALARM_COMMON_H_ + +namespace DeviceAPI { +namespace Alarm { + +// Alarm Type +#define ALARM_TYPE_KEY "TYPE" +#define ALARM_TYPE_ABSOLUTE_VALUE "ABSOLUTE" +#define ALARM_TYPE_RELATIVE_VALUE "RELATIVE" + +// Absolute Alarm Recurrence +#define ALARM_ALSOLUTE_RECURRENCE_TYPE_KEY "RECURRENCE" +#define ALARM_ALSOLUTE_RECURRENCE_TYPE_INTERVAL "INTERVAL" +#define ALARM_ALSOLUTE_RECURRENCE_TYPE_BYDAYVALUE "BYDAYVALUE" +#define ALARM_ALSOLUTE_RECURRENCE_TYPE_NONE "NONE" +#define ALARM_ABSOLUTE_FREQUENCY_KEY "FREQUENCY" +#define ALARM_ABSOLUTE_FREQUENCY_INTERVAL "FREQUENCY_INTERVAL" +#define ALARM_ALSOLUTE_DATE_KEY "DATE" + +// Relative Alarm Delay +#define ALARM_RELATIVE_DELAY_KEY "RELATIVE_DELAY" + +// Frequency +#define ALARM_PROPERTY_MINUTELY_RECURRENCE "MINUTELY" +#define ALARM_PROPERTY_HOURLY_RECURRENCE "HOURLY" +#define ALARM_PROPERTY_DAILY_RECURRENCE "DAILY" +#define ALARM_PROPERTY_WEEKLY_RECURRENCE "WEEKLY" +#define ALARM_PROPERTY_MONTHLY_RECURRENCE "MONTHLY" +#define ALARM_PROPERTY_YEARLY_RECURRENCE "YEARLY" + +namespace AbsoluteRecurrence +{ + typedef enum + { + NoRecurrence, + ByDayValue, + Interval, + }Type; +} + +} +} +#endif diff --git a/wearable_src/Alarm/config.xml b/wearable_src/Alarm/config.xml new file mode 100755 index 0000000..05f5f62 --- /dev/null +++ b/wearable_src/Alarm/config.xml @@ -0,0 +1,11 @@ +<?xml version="1.0" ?> +<!DOCTYPE plugin-properties SYSTEM "/usr/etc/tizen-apis/config.dtd"> +<plugin-properties> + <library-name>libwrt-plugins-tizen-alarm.so</library-name> + <feature-install-uri>alarm.install.uri</feature-install-uri> + <api-feature> + <name>http://tizen.org/privilege/alarm</name> + <device-capability>alarm</device-capability> + </api-feature> + +</plugin-properties> diff --git a/wearable_src/Alarm/plugin_config.cpp b/wearable_src/Alarm/plugin_config.cpp new file mode 100755 index 0000000..856b58a --- /dev/null +++ b/wearable_src/Alarm/plugin_config.cpp @@ -0,0 +1,109 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 <Commons/FunctionDefinition.h> +#include <Commons/FunctionDeclaration.h> +#include <iostream> +#include <Commons/Exception.h> +#include <dpl/exception.h> +#include <map> + +#include "plugin_config.h" + +#define ALARM_FEATURE_API "http://tizen.org/privilege/alarm" + +#define ALARM_DEVICE_CAP "alarm" + +using namespace WrtDeviceApis::Commons; + +namespace DeviceAPI { +namespace Alarm { + +static FunctionMapping createAlarmFunctions(); + +static FunctionMapping AlarmFunctions = + createAlarmFunctions(); + +#pragma GCC visibility push(default) + +DEFINE_FUNCTION_GETTER(Alarm, AlarmFunctions); + +#pragma GCC visibility pop + +static FunctionMapping createAlarmFunctions() +{ + /** + * Device capabilities + */ + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_ALARM, ALARM_DEVICE_CAP); + + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_ALARM); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_ALARM, DEVICE_CAP_ALARM); + + /** + * Api Features + */ + ACE_CREATE_FEATURE(FEATURE_ALARM, ALARM_FEATURE_API); + + ACE_CREATE_FEATURE_LIST(ALARM_FEATURES); + ACE_ADD_API_FEATURE(ALARM_FEATURES, FEATURE_ALARM); + + /** + * Functions + */ + FunctionMapping alarmMapping; + + // add + AceFunction addFunc = ACE_CREATE_FUNCTION( + FUNCTION_ADD, + ALARM_FUNCTION_API_ADD, + ALARM_FEATURES, + DEVICE_LIST_ALARM); + + alarmMapping.insert(std::make_pair( + ALARM_FUNCTION_API_ADD, + addFunc)); + + // remove + AceFunction removeFunc = ACE_CREATE_FUNCTION( + FUNCTION_REMOVE, + ALARM_FUNCTION_API_REMOVE, + ALARM_FEATURES, + DEVICE_LIST_ALARM); + + alarmMapping.insert(std::make_pair( + ALARM_FUNCTION_API_REMOVE, + removeFunc)); + + + // removeAll + AceFunction removeAllFunc = ACE_CREATE_FUNCTION( + FUNCTION_REMOVE_ALL, + ALARM_FUNCTION_API_REMOVE_ALL, + ALARM_FEATURES, + DEVICE_LIST_ALARM); + + alarmMapping.insert(std::make_pair( + ALARM_FUNCTION_API_REMOVE_ALL, + removeAllFunc)); + + return alarmMapping; +} + +} +} diff --git a/wearable_src/Alarm/plugin_config.h b/wearable_src/Alarm/plugin_config.h new file mode 100755 index 0000000..796e37b --- /dev/null +++ b/wearable_src/Alarm/plugin_config.h @@ -0,0 +1,44 @@ +//
+// Tizen Web Device API
+// Copyright (c) 2012 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an AS IS BASIS,
+// WITHOUT 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 _ALARM_PLUGIN_CONFIG_H_
+#define _ALARM_PLUGIN_CONFIG_H_
+
+#include <string>
+#include <Commons/FunctionDeclaration.h>
+
+#define ALARM_FUNCTION_API_GET_ALL "getAll"
+#define ALARM_FUNCTION_API_GET "get"
+#define ALARM_FUNCTION_API_ADD "add"
+#define ALARM_FUNCTION_API_REMOVE "remove"
+#define ALARM_FUNCTION_API_REMOVE_ALL "removeAll"
+#define ALARM_FUNCTION_API_GET_NEXT_SCHEDULED_DATE "getNextScheduledDate"
+#define ALARM_FUNCTION_API_GET_REMAINING_SECONDS "getRemainingSeconds"
+
+namespace DeviceAPI {
+namespace Alarm {
+
+DECLARE_FUNCTION_GETTER(Alarm);
+
+#define ALARM_CHECK_ACCESS(functionName) \
+ aceCheckAccess<AceFunctionGetter, DefaultArgsVerifier<> >( \
+ getAlarmFunctionData, \
+ functionName)
+}
+}
+#endif
+
diff --git a/wearable_src/Alarm/plugin_initializer.cpp b/wearable_src/Alarm/plugin_initializer.cpp new file mode 100644 index 0000000..2951641 --- /dev/null +++ b/wearable_src/Alarm/plugin_initializer.cpp @@ -0,0 +1,100 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 <Commons/plugin_initializer_def.h> +#include <Commons/WrtAccess/WrtAccess.h> +#include <Commons/Exception.h> +#include <TimeTracer.h> +#include "JSAlarmManager.h" +#include "JSAlarmAbsolute.h" +#include "JSAlarmRelative.h" +#include <Logger.h> + +#define WRT_JS_EXTENSION_OBJECT_TIZEN "tizen" + +namespace DeviceAPI { +namespace Alarm { + +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +class_definition_options_t ConstructorClassOptions = +{ + JS_INTERFACE, + CREATE_INSTANCE, + NONE_NOTICE, + USE_OVERLAYED, //ignored + NULL, + NULL, + NULL +}; + +void on_widget_start_callback(int widgetId) +{ + LoggerI("[Tizen\\AlarmManager ] on_widget_start_callback (" << widgetId << ")"); + Try + { + TIME_TRACER_INIT(); + WrtAccessSingleton::Instance().initialize(widgetId); + } + Catch(Commons::Exception) + { + LoggerE("WrtAccess initialization failed"); + } +} + +void on_widget_stop_callback(int widgetId) +{ + LoggerI("[Tizen\\AlarmManager ] on_widget_stop_callback (" << widgetId << ")"); + Try + { + TIME_TRACER_EXPORT_REPORT_TO(TIME_TRACER_EXPORT_FILE,"Alarm"); + TIME_TRACER_RELEASE(); + WrtAccessSingleton::Instance().deinitialize(widgetId); + } + Catch(Commons::Exception) + { + LoggerE("WrtAccess deinitialization failed"); + } +} + +PLUGIN_ON_WIDGET_START(on_widget_start_callback) +PLUGIN_ON_WIDGET_STOP(on_widget_stop_callback) + +PLUGIN_CLASS_MAP_BEGIN +PLUGIN_CLASS_MAP_ADD_CLASS( + WRT_JS_EXTENSION_OBJECT_TIZEN, + "alarm", + (js_class_template_getter)DeviceAPI::Alarm::JSAlarmManager::getClassRef, + NULL) +PLUGIN_CLASS_MAP_ADD_INTERFACE( + WRT_JS_EXTENSION_OBJECT_TIZEN, + TIZEN_ALARM_ABSOLUTE_INTERFACE, + (js_class_template_getter)DeviceAPI::Alarm::JSAlarmAbsolute::getClassRef, + reinterpret_cast<js_class_constructor_cb_t>(DeviceAPI::Alarm::JSAlarmAbsolute::constructor), + &ConstructorClassOptions) +PLUGIN_CLASS_MAP_ADD_INTERFACE( + WRT_JS_EXTENSION_OBJECT_TIZEN, + TIZEN_ALARM_RELATIVE_INTERFACE, + (js_class_template_getter)DeviceAPI::Alarm::JSAlarmRelative::getClassRef, + reinterpret_cast<js_class_constructor_cb_t>(DeviceAPI::Alarm::JSAlarmRelative::constructor), + &ConstructorClassOptions) +PLUGIN_CLASS_MAP_END + +} // Alarm +} // DeviceAPI diff --git a/wearable_src/Application/AppManagerWrapper.cpp b/wearable_src/Application/AppManagerWrapper.cpp new file mode 100644 index 0000000..48146fa --- /dev/null +++ b/wearable_src/Application/AppManagerWrapper.cpp @@ -0,0 +1,329 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 "AppManagerWrapper.h" +#include <Commons/Exception.h> +#include <Commons/Regex.h> + +// To get package id from appId +#include <package_manager.h> +#include <TimeTracer.h> + +#include <Logger.h> + +namespace DeviceAPI { +namespace Application { + +using namespace std; +using namespace WrtDeviceApis::Commons; + + +AppManagerWrapper::AppManagerWrapper() : + m_manager_handle(NULL), + m_watchIdAcc(0) +{ +} + +AppManagerWrapper::~AppManagerWrapper() +{ + if(m_manager_handle != NULL) + { + unregisterAppListChangedCallbacks(); + } +} + +void AppManagerWrapper::setCurrentAppId(std::string appId) +{ + m_curr_app_id = appId; +} + +std::string AppManagerWrapper::getCurrentAppId() const +{ + return m_curr_app_id; +} + + +void AppManagerWrapper::registerAppListChangedCallbacks(IAppManagerAppListChangedCallbacks *callbacks) +{ + if(callbacks == NULL) + { + LoggerE("callback cannot be set to NULL."); + return; + } + + if(!m_manager_handle) + { + registerAppListChangedCallbacks(); + } + + m_callbacks.insert(callbacks); +} + +void AppManagerWrapper::unregisterAppListChangedCallbacks(IAppManagerAppListChangedCallbacks *callbacks) +{ + if(callbacks == NULL) + { + LoggerE("callback cannot be set to NULL."); + return; + } + + if(m_callbacks.size() == 0) + { + LoggerE("No callbacks are registered."); + return; + } + + AppListChangedCallbacksSet::iterator iter = m_callbacks.find(callbacks); + if(iter == m_callbacks.end()) + { + LoggerE("Callback " << callbacks << " is not registered."); + return; + } + + m_callbacks.erase(iter); + + if(m_callbacks.size() == 0) + { + unregisterAppListChangedCallbacks(); + } +} + + +long AppManagerWrapper::getWatchIdAndInc() +{ + return ++m_watchIdAcc; +} + + +bool AppManagerWrapper::app_callback(package_info_app_component_type_e comp_type, const char *app_id, void *user_data) +{ + if(app_id == NULL) { + LoggerE("Callback is called. but no package name is passed. skip this request"); + return true; + } + + if(user_data == NULL) { + LoggerE("user data is not exist. skip this request"); + return true; + } + + AppManagerWrapper *appManager = (AppManagerWrapper *)user_data; + appManager->applist.push_back(app_id); + + return true; +} + +void AppManagerWrapper::appListChangedCallback(app_manger_event_type_e event_type, const char *pkgId, void *user_data) +{ + if(user_data == NULL) { + LoggerE("user data is not exist. skip this request"); + return; + } + + AppManagerWrapper *appManager = (AppManagerWrapper *)user_data; + + if (event_type == APP_MANAGER_EVENT_UNINSTALLED) { + for (size_t i = 0; i < appManager->applist.size(); i++) { + appListAppUninstalled(appManager->applist.at(i).c_str()); + } + } else { + package_info_h package_info; + + int ret = package_manager_get_package_info(pkgId, &package_info); + if (ret != PACKAGE_MANAGER_ERROR_NONE) { + LoggerE("Cannot create package info"); + return; + } + + ret = package_info_foreach_app_from_package(package_info, PACKAGE_INFO_ALLAPP, app_callback, user_data); + if (ret != PACKAGE_MANAGER_ERROR_NONE) { + LoggerE("failed while getting appids"); + package_info_destroy(package_info); + return; + } + + ret = package_info_destroy(package_info); + if (ret != PACKAGE_MANAGER_ERROR_NONE) { + LoggerE("Cannot destroy package info"); + } + + for (size_t i = 0; i < appManager->applist.size(); i++) { + switch(event_type) + { + case APP_MANAGER_EVENT_INSTALLED: + appListAppInstalled(appManager->applist.at(i).c_str()); + break; + case APP_MANAGER_EVENT_UPDATED: + appListAppUpdated(appManager->applist.at(i).c_str()); + break; + default: + LoggerE("app_manager listener gave wrong event_type : " << event_type); + break; + } + } + } + + // clean-up applist + appManager->applist.clear(); +} + + +void AppManagerWrapper::appListAppInstalled(const char *appId) +{ + AppListChangedCallbacksSet::iterator iter = m_callbacks.begin(); + for(; iter != m_callbacks.end(); iter++) + { + (*iter)->onAppManagerEventInstalled(appId); + } +} + +void AppManagerWrapper::appListAppUninstalled(const char *appId) +{ + AppListChangedCallbacksSet::iterator iter = m_callbacks.begin(); + for(; iter != m_callbacks.end(); iter++) + { + (*iter)->onAppManagerEventUninstalled(appId); + } +} + +void AppManagerWrapper::appListAppUpdated(const char *appId) +{ + AppListChangedCallbacksSet::iterator iter = m_callbacks.begin(); + for(; iter != m_callbacks.end(); iter++) + { + (*iter)->onAppManagerEventUpdated(appId); + } +} + + +int AppManagerWrapper::app_list_changed_cb_broker(int id, const char *type, const char *package, const char *key, const char *val, const void *msg, void *data) +{ + static app_manger_event_type_e event_type; + + if (!strcasecmp(key, "start")) { + if (!strcasecmp(val, "install")) { + event_type = APP_MANAGER_EVENT_INSTALLED; + } else if (!strcasecmp(val, "uninstall")) { + // After uninstallation, we cannot get app ids from package name. + // So, we have to store app ids which is included to target package. + package_info_h package_info; + + int ret = package_manager_get_package_info(package, &package_info); + if (ret != PACKAGE_MANAGER_ERROR_NONE) { + LoggerE("Cannot create package info"); + } + + ret = package_info_foreach_app_from_package(package_info, PACKAGE_INFO_ALLAPP, app_callback, data); + if (ret != PACKAGE_MANAGER_ERROR_NONE) { + LoggerE("failed while getting appids"); + } + + ret = package_info_destroy(package_info); + if (ret != PACKAGE_MANAGER_ERROR_NONE) { + LoggerE("Cannot destroy package info"); + } + event_type = APP_MANAGER_EVENT_UNINSTALLED; + } else if (!strcasecmp(val, "update")) { + event_type = APP_MANAGER_EVENT_UPDATED; + } + } else if (!strcasecmp(key, "end") && !strcasecmp(val, "ok")) { + if (event_type >= 0) { + if (data != NULL) { + AppManagerWrapper *appManager = (AppManagerWrapper *)data; + appManager->appListChangedCallback(event_type, package, data); + } + } + } + + return APP_MANAGER_ERROR_NONE; +} + + +void AppManagerWrapper::registerAppListChangedCallbacks() +{ + if (m_manager_handle != NULL) { + LoggerW("Callback is already registered."); + return; + } + + TIME_TRACER_ITEM_BEGIN("(addAppInfoEventListener)pkgmgr_client_new", 0); + m_manager_handle = pkgmgr_client_new(PC_LISTENING); + TIME_TRACER_ITEM_END("(addAppInfoEventListener)pkgmgr_client_new", 0); + if (m_manager_handle == NULL) { + ThrowMsg(InvalidArgumentException, "Error while registering listener to app_manager"); + } + + TIME_TRACER_ITEM_BEGIN("(addAppInfoEventListener)pkgmgr_client_listen_status", 0); + pkgmgr_client_listen_status(m_manager_handle, app_list_changed_cb_broker, this); + TIME_TRACER_ITEM_END("(addAppInfoEventListener)pkgmgr_client_listen_status", 0); +} + +void AppManagerWrapper::unregisterAppListChangedCallbacks() +{ + if (m_manager_handle == NULL) { + LoggerE("No callback is registered"); + return; + } + + TIME_TRACER_ITEM_BEGIN("(removeAppInfoEventListener)pkgmgr_client_free", 0); + pkgmgr_client_free(m_manager_handle); + TIME_TRACER_ITEM_END("(removeAppInfoEventListener)pkgmgr_client_free", 0); + m_manager_handle = NULL; +} + +bool AppManagerWrapper::initializeAppInfo(ApplicationInformationPtr &appInfo) +{ + LoggerD("Enter"); + + char* packageId = NULL; + int ret = 0; + + ret = package_manager_get_package_id_by_app_id(appInfo->getAppId().c_str(), &packageId); + if ((ret != PACKAGE_MANAGER_ERROR_NONE) || (packageId == NULL)) { + LoggerE("Fail to get package id"); + } else { + // get installed size from package server (to solve smack issue) + pkgmgr_client *pc = pkgmgr_client_new(PC_REQUEST); + if (pc == NULL) { + LoggerE("Fail to create pkgmgr client"); + } else { + ret = pkgmgr_client_request_service(PM_REQUEST_GET_SIZE, PM_GET_TOTAL_SIZE, pc, NULL, packageId, NULL, NULL, NULL); + if (ret < 0) { + LoggerE("Fail to get installed size"); + } else { + appInfo->setInstallSize(ret); + } + + pkgmgr_client_free(pc); + pc = NULL; + } + + if (packageId) { + free(packageId); + } + } + + // if error occured, retry? or not? + appInfo->setInitialize(); + + return true; +} + +SINGLETON_IMPLEMENTATION(AppManagerWrapper) + +} // Application +} // DeviceAPI diff --git a/wearable_src/Application/AppManagerWrapper.h b/wearable_src/Application/AppManagerWrapper.h new file mode 100644 index 0000000..cb0ea83 --- /dev/null +++ b/wearable_src/Application/AppManagerWrapper.h @@ -0,0 +1,108 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_PLATFORM_APPLICATION_APP_MANAGER_WRAPPER_H_ +#define TIZENAPIS_PLATFORM_APPLICATION_APP_MANAGER_WRAPPER_H_ + +#include <string> +#include <map> +#include <set> +#include <dpl/shared_ptr.h> + +#include <app_manager.h> +#include <package-manager.h> +#include <package_manager.h> +#include <package_info.h> + +#include "ApplicationInformation.h" + +// To get app size and installed time +#include <pkgmgr-info.h> + +#include <Singleton.h> + +namespace DeviceAPI { +namespace Application { + + +class IAppManagerAppListChangedCallbacks +{ +public: + friend class AppManagerWrapper; + + IAppManagerAppListChangedCallbacks() {} + ~IAppManagerAppListChangedCallbacks() {} + +protected: + virtual void onAppManagerEventInstalled(const char *appId) = 0; + virtual void onAppManagerEventUninstalled(const char *appId) = 0; + virtual void onAppManagerEventUpdated(const char *appId) = 0; +}; + +class DLL_EXPORT AppManagerWrapper +{ +public: + AppManagerWrapper(); + virtual ~AppManagerWrapper(); + + // Can throw InvalidArgumentException or PlatformException + void registerAppListChangedCallbacks(IAppManagerAppListChangedCallbacks *callbacks); + + // No throws + void unregisterAppListChangedCallbacks(IAppManagerAppListChangedCallbacks *callbacks); + + long getWatchIdAndInc(); + + bool initializeAppInfo(ApplicationInformationPtr &appInfo); + + // get the current application id from WRT + void setCurrentAppId(std::string appId); + std::string getCurrentAppId() const; + +private: + + static bool app_callback(package_info_app_component_type_e comp_type, const char *app_id, void *user_data); + void appListChangedCallback(app_manger_event_type_e event_type, const char *pkgId, void *user_data); + static int app_list_changed_cb_broker(int id, const char *type, const char *package, const char *key, const char *val, const void *msg, void *data); + + void appListAppInstalled(const char *appId); + void appListAppUninstalled(const char *appId); + void appListAppUpdated(const char *appId); + + void registerAppListChangedCallbacks(); + void unregisterAppListChangedCallbacks(); + + typedef std::set<IAppManagerAppListChangedCallbacks *> AppListChangedCallbacksSet; + AppListChangedCallbacksSet m_callbacks; + pkgmgr_client *m_manager_handle; + long m_watchIdAcc; + std::string m_curr_app_id; + +public: + std::vector<std::string> applist; + +public: + friend class AppManagerWrapperSingleton; +}; + +SINGLETON_DEFINITION(AppManagerWrapper) + + +} // Application +} // DeviceAPI + +#endif // TIZENAPIS_PLATFORM_APPLICATION_APP_MANAGER_WRAPPER_H_ diff --git a/wearable_src/Application/Application.cpp b/wearable_src/Application/Application.cpp new file mode 100644 index 0000000..4c9f479 --- /dev/null +++ b/wearable_src/Application/Application.cpp @@ -0,0 +1,159 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 "Application.h" + +#include <bundle.h> +#include <app.h> +#include <app_service.h> + +#include "ApplicationControlData.h" +#include "ApplicationControl.h" +#include "ApplicationManager.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Application { + +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; + +extern "C" int service_create_event(bundle *data, struct service_s **service); + +Application::Application() +{ +} + +Application::~Application() +{ +} + +std::string Application::getContextId() const +{ + return m_contextId; +} + +void Application::setContextId(const std::string &id) +{ + m_contextId = id; +} + +ApplicationInformationPtr Application::getAppInfo() const +{ + return m_appInfo; +} + +void Application::setAppInfo(ApplicationInformationPtr& appInfo) +{ + m_appInfo = appInfo; +} + +void Application::getRequestedAppControl(const EventApplicationGetRequestedAppControlPtr& event) +{ + Try + { + int ret = 0; + + std::string bundle_str = event->getEncodedBundle(); + + service_h service = NULL; + char* tmpStr = NULL; + + bundle *request_bundle = bundle_decode((bundle_raw*)bundle_str.c_str(), bundle_str.length()); + ret = service_create_event(request_bundle, &service); + if(ret != SERVICE_ERROR_NONE) + { + LoggerE("Fail to create event"); + event->setExceptionCode(Commons::ExceptionCodes::UnknownException); + bundle_free(request_bundle); + return; + } + bundle_free(request_bundle); + + ApplicationControlPtr appControl(new ApplicationControl()); + appControl->setService_h(service); + + ret = service_get_operation(service, &tmpStr); + if(ret == SERVICE_ERROR_NONE && tmpStr != NULL) + { + appControl->setOperation(tmpStr); + free(tmpStr); + tmpStr = NULL; + } + + ret = service_get_uri(service, &tmpStr); + if(ret == SERVICE_ERROR_NONE && tmpStr != NULL) + { + appControl->setUri(tmpStr); + free(tmpStr); + tmpStr = NULL; + } + + ret = service_get_mime(service, &tmpStr); + if(ret == SERVICE_ERROR_NONE && tmpStr != NULL) + { + appControl->setMime(tmpStr); + free(tmpStr); + tmpStr = NULL; + } + + ret = service_get_category(service, &tmpStr); + if(ret == SERVICE_ERROR_NONE && tmpStr != NULL) + { + appControl->setCategory(tmpStr); + free(tmpStr); + tmpStr = NULL; + } + + std::vector<ApplicationControlDataPtr> appControlDataArray; + ret = service_foreach_extra_data(service, ApplicationManager::service_extra_data_callback, &appControlDataArray); + if (ret != SERVICE_ERROR_NONE) + { + LoggerE("service_foreach_extra_data fail"); + event->setExceptionCode(Commons::ExceptionCodes::UnknownException); + } + else + { + appControl->setAppControlDataArray(appControlDataArray); + } + + RequestedApplicationControlPtr appCtrMgr(new RequestedApplicationControl()); + appCtrMgr->setAppControl(appControl); + + // add caller id + ret = service_get_caller(service, &tmpStr); + if(ret == SERVICE_ERROR_NONE && tmpStr != NULL) + { + appCtrMgr->setCallerAppId(tmpStr); + free(tmpStr); + tmpStr = NULL; + } else { + LoggerE("fail to get caller application ID"); + event->setExceptionCode(Commons::ExceptionCodes::PlatformException); + } + event->setRequestedAppControl(appCtrMgr); + + } + Catch (WrtDeviceApis::Commons::Exception) + { + LoggerE("Error on getAppControl : " << _rethrown_exception.GetMessage()); + event->setExceptionCode(Commons::ExceptionCodes::PlatformException); + } +} + +} +} diff --git a/wearable_src/Application/Application.h b/wearable_src/Application/Application.h new file mode 100644 index 0000000..ef53a35 --- /dev/null +++ b/wearable_src/Application/Application.h @@ -0,0 +1,54 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_API_APPLICATION_H_ +#define TIZENAPIS_API_APPLICATION_H_ + +#include <string> +#include <vector> +#include <dpl/shared_ptr.h> +#include "ApplicationInformation.h" +#include "EventApplicationGetRequestedAppControl.h" + +namespace DeviceAPI { +namespace Application { + +class Application; +typedef DPL::SharedPtr<Application> ApplicationPtr; + +class Application +{ + public: + Application(); + ~Application(); + + std::string getContextId() const; + void setContextId(const std::string &id); + ApplicationInformationPtr getAppInfo() const; + void setAppInfo(ApplicationInformationPtr &appInfo); + + void getRequestedAppControl(const EventApplicationGetRequestedAppControlPtr& event); + + private: + ApplicationInformationPtr m_appInfo; + std::string m_contextId; +}; + +} +} + +#endif diff --git a/wearable_src/Application/ApplicationAsyncCallbackManager.cpp b/wearable_src/Application/ApplicationAsyncCallbackManager.cpp new file mode 100755 index 0000000..f48124a --- /dev/null +++ b/wearable_src/Application/ApplicationAsyncCallbackManager.cpp @@ -0,0 +1,27 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 "ApplicationAsyncCallbackManager.h" + +namespace DeviceAPI { +namespace Application { + +SINGLETON_IMPLEMENTATION(ApplicationAsyncCallbackManager) + +} // Application +} // DeviceAPI diff --git a/wearable_src/Application/ApplicationAsyncCallbackManager.h b/wearable_src/Application/ApplicationAsyncCallbackManager.h new file mode 100644 index 0000000..6e69991 --- /dev/null +++ b/wearable_src/Application/ApplicationAsyncCallbackManager.h @@ -0,0 +1,46 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 _TIZEN_APPLICATION_ASYNC_CALLBACK_MANAGER_H_ +#define _TIZEN_APPLICATION_ASYNC_CALLBACK_MANAGER_H_ + +#include <AsyncCallbackManager.h> + +namespace DeviceAPI { +namespace Application { + +class ApplicationAsyncCallbackManager : public DeviceAPI::Common::AsyncCallbackManager +{ +private: + ApplicationAsyncCallbackManager() + { + } + +public: + virtual ~ApplicationAsyncCallbackManager() + { + } + + friend class ApplicationAsyncCallbackManagerSingleton; +}; + +SINGLETON_DEFINITION(ApplicationAsyncCallbackManager) + +} // Application +} // DeviceAPI + +#endif // _TIZEN_APPLICATION_ASYNC_CALLBACK_MANAGER_H_ diff --git a/wearable_src/Application/ApplicationCert.cpp b/wearable_src/Application/ApplicationCert.cpp new file mode 100644 index 0000000..a68af99 --- /dev/null +++ b/wearable_src/Application/ApplicationCert.cpp @@ -0,0 +1,51 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 "ApplicationCert.h" + +namespace DeviceAPI { +namespace Application { +ApplicationCert::ApplicationCert() +{ +} + +ApplicationCert::~ApplicationCert() +{ +} + +std::string ApplicationCert::getType() const +{ + return m_type; +} + +void ApplicationCert::setType(const std::string &type) +{ + m_type = type; +} + +std::string ApplicationCert::getValue() const +{ + return m_value; +} + +void ApplicationCert::setValue(const std::string &value) +{ + m_value = value; +} + +} +} diff --git a/wearable_src/Application/ApplicationCert.h b/wearable_src/Application/ApplicationCert.h new file mode 100644 index 0000000..54c5028 --- /dev/null +++ b/wearable_src/Application/ApplicationCert.h @@ -0,0 +1,52 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_API_APPLICATION_CERT_H_ +#define TIZENAPIS_API_APPLICATION_CERT_H_ + +#include <string> +#include <vector> +#include <dpl/shared_ptr.h> + +namespace DeviceAPI { +namespace Application { + +class ApplicationCert; +typedef DPL::SharedPtr<ApplicationCert> ApplicationCertPtr; + +typedef std::vector<ApplicationCertPtr> ApplicationCertArray; +typedef DPL::SharedPtr<ApplicationCertArray> ApplicationCertArrayPtr; + + +class ApplicationCert +{ + public: + ApplicationCert(); + ~ApplicationCert(); + + std::string getType() const; + void setType(const std::string &type); + std::string getValue() const; + void setValue(const std::string &value); + + private: + std::string m_type; + std::string m_value; +}; +} +} +#endif diff --git a/wearable_src/Application/ApplicationContext.cpp b/wearable_src/Application/ApplicationContext.cpp new file mode 100755 index 0000000..8671a1a --- /dev/null +++ b/wearable_src/Application/ApplicationContext.cpp @@ -0,0 +1,50 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 "ApplicationContext.h" + +namespace DeviceAPI { +namespace Application { +ApplicationContext::ApplicationContext() +{ +} + +ApplicationContext::~ApplicationContext() +{ +} + +std::string ApplicationContext::getAppId() const +{ + return m_appId; +} +void ApplicationContext::setAppId(const std::string &appId) +{ + m_appId = appId; +} + +std::string ApplicationContext::getContextId() const +{ + return m_contextId; +} +void ApplicationContext::setContextId(const std::string &contextId) +{ + m_contextId = contextId; +} + + +} +} diff --git a/wearable_src/Application/ApplicationContext.h b/wearable_src/Application/ApplicationContext.h new file mode 100755 index 0000000..13cb362 --- /dev/null +++ b/wearable_src/Application/ApplicationContext.h @@ -0,0 +1,53 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_API_APPLICATION_CONTEXT_H_ +#define TIZENAPIS_API_APPLICATION_CONTEXT_H_ + +#include <string> +#include <vector> +#include <dpl/shared_ptr.h> + +namespace DeviceAPI { +namespace Application { + +class ApplicationContext; +typedef DPL::SharedPtr<ApplicationContext> ApplicationContextPtr; + +typedef std::vector<ApplicationContextPtr> ApplicationContextArray; +typedef DPL::SharedPtr<ApplicationContextArray> ApplicationContextArrayPtr; + +class ApplicationContext +{ + public: + ApplicationContext(); + ~ApplicationContext(); + + std::string getAppId() const; + void setAppId(const std::string &appId); + std::string getContextId() const; + void setContextId(const std::string &contextId); + + + private: + std::string m_appId; + std::string m_contextId; + +}; +} +} +#endif diff --git a/wearable_src/Application/ApplicationControl.cpp b/wearable_src/Application/ApplicationControl.cpp new file mode 100644 index 0000000..23ca359 --- /dev/null +++ b/wearable_src/Application/ApplicationControl.cpp @@ -0,0 +1,169 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 ApplicationControl.cpp + * @author Youngkyeong Yun (yk.yun@samsung.com) + * @version 0.1 + */ + +#include "ApplicationControl.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Application { + +ApplicationControl::ApplicationControl() : + m_appControl(NULL) +{ +} + +ApplicationControl::ApplicationControl(const std::string &op, const std::string &uri, + const std::string &mime, const std::string &category, + std::vector<ApplicationControlDataPtr> &dataArray) : + m_appControl(NULL) +{ + m_operation = op; + m_uri = uri; + m_mime = mime; + m_category = category; + m_appControlDataArray = dataArray; +} + +ApplicationControl::~ApplicationControl() +{ +} + +std::string ApplicationControl::getOperation() const +{ + return m_operation; +} + +void ApplicationControl::setOperation(const std::string &operation) +{ + m_operation = operation; +} + +std::string ApplicationControl::getUri() const +{ + return m_uri; +} + +void ApplicationControl::setUri(const std::string &uri) +{ + m_uri = uri; +} + +std::string ApplicationControl::getMime() const +{ + return m_mime; +} + +void ApplicationControl::setMime(const std::string &mime) +{ + m_mime = mime; +} + +std::string ApplicationControl::getCategory() const +{ + return m_category; +} + +void ApplicationControl::setCategory(const std::string &category) +{ + m_category = category; +} + +std::vector<ApplicationControlDataPtr> ApplicationControl::getAppControlDataArray() const +{ + return m_appControlDataArray; +} + +void ApplicationControl::setAppControlDataArray(const std::vector<ApplicationControlDataPtr> &dataArray) +{ + m_appControlDataArray = dataArray; +} + +void ApplicationControl::addAppControlData(const ApplicationControlDataPtr &data) +{ + m_appControlDataArray.push_back(data); + +} + +service_h ApplicationControl::getService_h() const +{ + return m_appControl; +} + +void ApplicationControl::setService_h(const service_h service) +{ + m_appControl = service; +} + + +#if 0 +void ApplicationControl::replyResult(std::vector<ApplicationControlDataPtr> &appControlDataArray) +{ + service_h reply; + service_create(&reply); + + const char* key = NULL; + const char** arr = NULL; + + if (!appControlDataArray.empty()) + { + LoggerD("appControlDataArray.size() : "<<appControlDataArray.size()); + for (size_t i = 0; i < appControlDataArray.size(); ++i) { + key = appControlDataArray.at(i)->getKey().c_str(); + std::vector<std::string> valueArray = appControlDataArray.at(i)->getValue(); + + arr = (const char**) calloc (sizeof(char*), valueArray.size()); + + for (size_t j = 0; j < valueArray.size(); j++) { + arr[j] = valueArray.at(j).c_str(); + } + service_add_extra_data_array(reply, key, arr, valueArray.size()); + } + } else { + LoggerE("appControlDataArray is empty"); + } + + service_reply_to_launch_request(reply, m_appControl, SERVICE_RESULT_SUCCEEDED); + + service_destroy(reply); + + if (arr) { + free (arr); + } + +} + +void ApplicationControl::replyFailure() +{ + service_h reply; + service_create(&reply); + + LoggerE("==[replyFailure] enter ApplicationControl::replyFailure"); + service_reply_to_launch_request(reply, m_appControl, SERVICE_RESULT_FAILED); + + service_destroy(reply); +} +#endif + +} +} diff --git a/wearable_src/Application/ApplicationControl.h b/wearable_src/Application/ApplicationControl.h new file mode 100755 index 0000000..54d3e34 --- /dev/null +++ b/wearable_src/Application/ApplicationControl.h @@ -0,0 +1,77 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_API_APPLICATION_CONTROL_H_ +#define TIZENAPIS_API_APPLICATION_CONTROL_H_ + +#include <string> +#include <vector> +#include <dpl/shared_ptr.h> +#include <app_service.h> +#include "ApplicationControlData.h" +#include <Export.h> + +namespace DeviceAPI { +namespace Application { + +class ApplicationControl; +typedef DPL::SharedPtr<ApplicationControl> ApplicationControlPtr; + +/* This object represents a single extra data for service request and reply */ +class DLL_EXPORT ApplicationControl +{ + public: + ApplicationControl(); + ApplicationControl(const std::string &op, const std::string &uri, const std::string &mime, + const std::string &category, std::vector<ApplicationControlDataPtr> &dataArray) ; + ~ApplicationControl(); + + std::string getOperation() const; + void setOperation(const std::string &operation); + + std::string getUri() const; + void setUri(const std::string &uri); + + std::string getMime() const; + void setMime(const std::string &uri); + + std::string getCategory() const; + void setCategory(const std::string &category); + + std::vector<ApplicationControlDataPtr> getAppControlDataArray() const; + void setAppControlDataArray(const std::vector<ApplicationControlDataPtr> &dataArray); + void addAppControlData(const ApplicationControlDataPtr &data); + + service_h getService_h() const; + void setService_h(const service_h service); + +#if 0 + void replyResult(std::vector<ApplicationControlDataPtr> &appControlDataArray); + void replyFailure(); +#endif + + private: + std::string m_operation; + std::string m_uri; + std::string m_mime; + std::string m_category; + std::vector<ApplicationControlDataPtr> m_appControlDataArray; + service_h m_appControl; +}; +} +} +#endif diff --git a/wearable_src/Application/ApplicationControlData.cpp b/wearable_src/Application/ApplicationControlData.cpp new file mode 100644 index 0000000..6ed7ae3 --- /dev/null +++ b/wearable_src/Application/ApplicationControlData.cpp @@ -0,0 +1,52 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 "ApplicationControlData.h" + +namespace DeviceAPI { +namespace Application { + +ApplicationControlData::ApplicationControlData() +{ +} + +ApplicationControlData::~ApplicationControlData() +{ + //nothing to do in destructor +} + +std::string ApplicationControlData::getKey() const +{ + return m_key; +} + +void ApplicationControlData::setKey(const std::string &key) +{ + m_key = key; +} + +std::vector<std::string> ApplicationControlData::getValue() const +{ + return m_value; +} +void ApplicationControlData::setValue(const std::vector<std::string> &value) +{ + m_value = value; +} + +} +} diff --git a/wearable_src/Application/ApplicationControlData.h b/wearable_src/Application/ApplicationControlData.h new file mode 100755 index 0000000..a91d024 --- /dev/null +++ b/wearable_src/Application/ApplicationControlData.h @@ -0,0 +1,54 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_API_APPLICATION_CONTROL_DATA_H_ +#define TIZENAPIS_API_APPLICATION_CONTROL_DATA_H_ + +#include <string> +#include <vector> +#include <dpl/shared_ptr.h> +#include <Export.h> + +namespace DeviceAPI { +namespace Application { + +class ApplicationControlData; +typedef DPL::SharedPtr<ApplicationControlData> ApplicationControlDataPtr; + +typedef std::vector<ApplicationControlDataPtr> ApplicationControlDataArray; +typedef DPL::SharedPtr<ApplicationControlDataArray> ApplicationControlDataArrayPtr; + +/* This object represents a single extra data for app control request and reply */ +class DLL_EXPORT ApplicationControlData +{ + public: + ApplicationControlData(); + ~ApplicationControlData(); + + std::string getKey() const; + void setKey(const std::string &key); + + std::vector<std::string> getValue() const; + void setValue(const std::vector<std::string> &value); + + private: + std::string m_key; + std::vector<std::string> m_value; +}; +} +} +#endif diff --git a/wearable_src/Application/ApplicationController.cpp b/wearable_src/Application/ApplicationController.cpp new file mode 100644 index 0000000..07a72e3 --- /dev/null +++ b/wearable_src/Application/ApplicationController.cpp @@ -0,0 +1,543 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 <CommonsJavaScript/JSCallbackManager.h> +#include <JSWebAPIErrorFactory.h> +#include <TimeTracer.h> +#include "ApplicationController.h" +#include "ApplicationConverter.h" +#include "JSApplicationEventCallbackManager.h" +#include "ApplicationAsyncCallbackManager.h" +#include "ApplicationInformationEventPrivateData.h" + +// to unset event callback for kill() API +#include <app_manager.h> + +#include <Logger.h> + +namespace DeviceAPI { +namespace Application { + +using namespace DeviceAPI::Common; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +ApplicationController::ApplicationController(JSContextRef context, IApplicationManagerPtr application) : + EventApplicationLaunchEventAnswerReceiver(ThreadEnum::NULL_THREAD), + EventApplicationKillEventAnswerReceiver(ThreadEnum::NULL_THREAD), + EventApplicationLaunchAppControlEventAnswerReceiver(ThreadEnum::NULL_THREAD), + EventApplicationLaunchAppControlReplyEventAnswerReceiver(ThreadEnum::NULL_THREAD), + EventApplicationFindAppControlEventAnswerReceiver(ThreadEnum::NULL_THREAD), + EventApplicationGetAppsContextEventAnswerReceiver(ThreadEnum::NULL_THREAD), + EventApplicationGetAppsInfoEventAnswerReceiver(ThreadEnum::NULL_THREAD), + EventApplicationAppInfoEventListenerListener(ThreadEnum::NULL_THREAD), + ApplicationPrivObject(context, application) +{ + if (!application) { + LoggerE("controller has no application object"); + } +} + +ApplicationController::~ApplicationController() +{ +} + +void ApplicationController::OnAnswerReceived(const EventApplicationLaunchPtr &event) +{ + ApplicationAsyncAnswerHandler::launch(event); + TIME_TRACER_ITEM_END("launch(async)", 0); +} + +void ApplicationController::OnAnswerReceived(const EventApplicationKillPtr &event) +{ + ApplicationAsyncAnswerHandler::kill(event); + //TIME_TRACER_ITEM_END("kill(async)", 0); +} + +void ApplicationController::OnAnswerReceived(const EventApplicationLaunchAppControlPtr &event) +{ + ApplicationAsyncAnswerHandler::launchAppControl(event); + TIME_TRACER_ITEM_END("launchAppControl(async)", 0); +} + +void ApplicationController::OnAnswerReceived(const EventApplicationLaunchAppControlReplyPtr &event) +{ + ApplicationAsyncAnswerHandler::launchAppControlReply(event); + TIME_TRACER_ITEM_END("launchAppControlReply(async)", 0); +} + +void ApplicationController::OnAnswerReceived(const EventApplicationFindAppControlPtr &event) +{ + ApplicationAsyncAnswerHandler::findAppControl(event); + TIME_TRACER_ITEM_END("findAppControl(async)", 0); +} + +void ApplicationController::OnAnswerReceived(const EventApplicationGetAppsContextPtr &event) +{ + ApplicationAsyncAnswerHandler::getAppsContext(event); + TIME_TRACER_ITEM_END("getAppsContext(async)", 0); +} + +void ApplicationController::OnAnswerReceived(const EventApplicationGetAppsInfoPtr &event) +{ + ApplicationAsyncAnswerHandler::getAppsInfo(event); + TIME_TRACER_ITEM_END("getAppsInfo(async)", 0); +} + +void ApplicationController::onAnswerReceived(const EventApplicationAppInfoEventListenerPtr &event) +{ + ApplicationAsyncAnswerHandler::eventListener(event); +} + +void ApplicationAsyncAnswerHandler::launch(const EventApplicationLaunchPtr &event) +{ + JSCallbackManagerPtr callbackManager = + DPL::StaticPointerCast<JSCallbackManager>(event->getPrivateData()); + if (!callbackManager) { + LoggerE("no callback manager"); + return; + } + + ApplicationAsyncCallbackManagerSingleton::Instance().unregisterCallbackManager(callbackManager); + + if(event->checkCancelled()) { + LoggerD("Operation cancelled"); + return; + } + + JSContextRef gContext = callbackManager->getContext(); + + JSValueRef error = NULL; + if (ExceptionCodes::None != event->getExceptionCode()) + { + switch (event->getExceptionCode()) + { + case ExceptionCodes::InvalidArgumentException: + case ExceptionCodes::NotFoundException: + error = JSWebAPIErrorFactory::makeErrorObject(gContext, JSWebAPIErrorFactory::NOT_FOUND_ERROR, "given app id is not found"); + break; + case ExceptionCodes::PlatformException: + error = JSWebAPIErrorFactory::makeErrorObject(gContext, JSWebAPIErrorFactory::UNKNOWN_ERROR, "platform exception"); + break; + default: + error = JSWebAPIErrorFactory::makeErrorObject(gContext, JSWebAPIErrorFactory::UNKNOWN_ERROR,"unknown error"); + break; + } + + callbackManager->callOnError(error); + return; + } + + Try { + callbackManager->callOnSuccess(); + return; + } Catch(Exception) { + LoggerE("error during processing answer" << _rethrown_exception.GetMessage()); + error = JSWebAPIErrorFactory::makeErrorObject(gContext, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Internal error"); + + callbackManager->callOnError(error); + return; + } +} + +void ApplicationAsyncAnswerHandler::kill(const EventApplicationKillPtr &event) +{ + JSCallbackManagerPtr callbackManager = + DPL::StaticPointerCast<JSCallbackManager>(event->getPrivateData()); + if (!callbackManager) { + LoggerE("no callback manager"); + return; + } + + ApplicationAsyncCallbackManagerSingleton::Instance().unregisterCallbackManager(callbackManager); + + if(event->checkCancelled()) { + LoggerD("Operation cancelled"); + return; + } + + JSContextRef gContext = callbackManager->getContext(); + + JSValueRef error = NULL; + if (ExceptionCodes::None != event->getExceptionCode()) + { + switch (event->getExceptionCode()) + { + case ExceptionCodes::NotFoundException: + error = JSWebAPIErrorFactory::makeErrorObject(gContext, JSWebAPIErrorFactory::NOT_FOUND_ERROR,"given package is not found"); + break; + case ExceptionCodes::PlatformException: + error = JSWebAPIErrorFactory::makeErrorObject(gContext, JSWebAPIErrorFactory::UNKNOWN_ERROR,"platform exception"); + break; + case ExceptionCodes::InvalidArgumentException: + error = JSWebAPIErrorFactory::makeErrorObject(gContext, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, "invalid value"); + break; + default: + error = JSWebAPIErrorFactory::makeErrorObject(gContext, JSWebAPIErrorFactory::UNKNOWN_ERROR,"unknown error"); + break; + } + + callbackManager->callOnError(error); + return; + } + + Try { + callbackManager->callOnSuccess(); + return; + } Catch(Exception) { + LoggerE("error during processing answer" << _rethrown_exception.GetMessage()); + error = JSWebAPIErrorFactory::makeErrorObject(gContext, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Internal error"); + + callbackManager->callOnError(error); + return; + } +} + +void ApplicationAsyncAnswerHandler::launchAppControl(const EventApplicationLaunchAppControlPtr &event) +{ + JSCallbackManagerPtr callbackManager = + DPL::StaticPointerCast<JSCallbackManager>(event->getPrivateData()); + if (!callbackManager) { + LoggerE("no callback manager"); + return; + } + + ApplicationAsyncCallbackManagerSingleton::Instance().unregisterCallbackManager(callbackManager); + + if(event->checkCancelled()) { + LoggerD("Operation cancelled"); + return; + } + + JSContextRef gContext = callbackManager->getContext(); + + JSValueRef error = NULL; + if (ExceptionCodes::None != event->getExceptionCode()) + { + switch (event->getExceptionCode()) + { + case ExceptionCodes::InvalidArgumentException: + error = JSWebAPIErrorFactory::makeErrorObject(gContext, JSWebAPIErrorFactory::INVALID_VALUES_ERROR,"Argument is not valid"); + break; + case ExceptionCodes::NotFoundException: + error = JSWebAPIErrorFactory::makeErrorObject(gContext, JSWebAPIErrorFactory::NOT_FOUND_ERROR,"given package is not found"); + break; + case ExceptionCodes::PlatformException: + error = JSWebAPIErrorFactory::makeErrorObject(gContext, JSWebAPIErrorFactory::UNKNOWN_ERROR,"platform exception"); + break; + default: + error = JSWebAPIErrorFactory::makeErrorObject(gContext, JSWebAPIErrorFactory::UNKNOWN_ERROR,"unknown error"); + break; + } + + callbackManager->callOnError(error); + return; + } + + Try { + callbackManager->callOnSuccess(); + return; + } Catch(Exception) { + LoggerE("error during processing answer" << _rethrown_exception.GetMessage()); + error = JSWebAPIErrorFactory::makeErrorObject(gContext, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Internal error"); + + callbackManager->callOnError(error); + return; + } +} + +void ApplicationAsyncAnswerHandler::launchAppControlReply(const EventApplicationLaunchAppControlReplyPtr &event) +{ + JSCallbackManagerPtr callbackManager = + DPL::StaticPointerCast<JSCallbackManager>(event->getPrivateData()); + if (!callbackManager) { + LoggerE("no callback manager"); + return; + } + + ApplicationAsyncCallbackManagerSingleton::Instance().unregisterCallbackManager(callbackManager); + + if(event->checkCancelled()) { + LoggerD("Operation cancelled"); + return; + } + + JSContextRef gContext = callbackManager->getContext(); + + if (ExceptionCodes::None != event->getExceptionCode()) + { + callbackManager->callOnError(); + return; + } + + Try { + ApplicationControlDataArrayPtr appControlDataArray = event->getAppControlDataArray(); + if(appControlDataArray == NULL) + { + ThrowMsg(WrtDeviceApis::Commons::UnknownException, "No reply"); + } + + ApplicationConverterFactory::ConverterType converter = + ApplicationConverterFactory::getConverter(gContext); + JSValueRef result = converter->toJSValueRef(*appControlDataArray); + + callbackManager->callOnSuccess(result); + return; + } Catch(Exception) { + callbackManager->callOnError(); + return; + } +} + +void ApplicationAsyncAnswerHandler::findAppControl(const EventApplicationFindAppControlPtr &event) +{ + JSCallbackManagerPtr callbackManager = + DPL::StaticPointerCast<JSCallbackManager>(event->getPrivateData()); + if (!callbackManager) { + LoggerE("no callback manager"); + return; + } + + ApplicationAsyncCallbackManagerSingleton::Instance().unregisterCallbackManager(callbackManager); + + if(event->checkCancelled()) { + LoggerD("Operation cancelled"); + return; + } + + JSContextRef gContext = callbackManager->getContext(); + + JSValueRef error = NULL; + if (ExceptionCodes::None != event->getExceptionCode()) + { + switch (event->getExceptionCode()) + { + case ExceptionCodes::NotFoundException: + error = JSWebAPIErrorFactory::makeErrorObject(gContext, JSWebAPIErrorFactory::NOT_FOUND_ERROR,"given package is not found"); + break; + case ExceptionCodes::PlatformException: + error = JSWebAPIErrorFactory::makeErrorObject(gContext, JSWebAPIErrorFactory::UNKNOWN_ERROR,"platform exception"); + break; + default: + error = JSWebAPIErrorFactory::makeErrorObject(gContext, JSWebAPIErrorFactory::UNKNOWN_ERROR,"unknown error"); + break; + } + + callbackManager->callOnError(error); + return; + } + + Try { + ApplicationInformationArrayPtr appInfos = event->getAppInfos(); + ApplicationControlPtr appControl = event->getAppControl(); + + ApplicationConverterFactory::ConverterType converter = + ApplicationConverterFactory::getConverter(gContext); + + JSValueRef result[2]; + result[0] = converter->toJSValueRef(appInfos); + result[1] = converter->toJSValueRef(appControl); + + callbackManager->callOnSuccess(result, 2); + return; + } Catch(Exception) { + LoggerE("error during processing answer" << _rethrown_exception.GetMessage()); + error = JSWebAPIErrorFactory::makeErrorObject(gContext, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Internal error"); + + callbackManager->callOnError(error); + return; + } +} + +void ApplicationAsyncAnswerHandler::getAppsContext(const EventApplicationGetAppsContextPtr &event) +{ + JSCallbackManagerPtr callbackManager = + DPL::StaticPointerCast<JSCallbackManager>(event->getPrivateData()); + if (!callbackManager) { + LoggerE("no callback manager"); + return; + } + + ApplicationAsyncCallbackManagerSingleton::Instance().unregisterCallbackManager(callbackManager); + + if(event->checkCancelled()) { + LoggerD("Operation cancelled"); + return; + } + + JSContextRef gContext = callbackManager->getContext(); + + JSValueRef error = NULL; + if (ExceptionCodes::None != event->getExceptionCode()) + { + switch (event->getExceptionCode()) + { + case ExceptionCodes::NotFoundException: + error = JSWebAPIErrorFactory::makeErrorObject(gContext, JSWebAPIErrorFactory::NOT_FOUND_ERROR,"given package is not found"); + break; + case ExceptionCodes::PlatformException: + error = JSWebAPIErrorFactory::makeErrorObject(gContext, JSWebAPIErrorFactory::UNKNOWN_ERROR,"platform exception"); + break; + default: + error = JSWebAPIErrorFactory::makeErrorObject(gContext, JSWebAPIErrorFactory::UNKNOWN_ERROR,"unknown error"); + break; + } + + callbackManager->callOnError(error); + return; + } + + Try { + ApplicationContextArrayPtr appContextArray = event->getAppContextArray(); + + ApplicationConverterFactory::ConverterType converter = + ApplicationConverterFactory::getConverter(gContext); + + JSValueRef result = converter->toJSValueRef(appContextArray); + + callbackManager->callOnSuccess(result); + return; + } Catch(Exception) { + LoggerE("error during processing answer" << _rethrown_exception.GetMessage()); + error = JSWebAPIErrorFactory::makeErrorObject(gContext, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Internal error"); + + callbackManager->callOnError(error); + return; + } +} + +void ApplicationAsyncAnswerHandler::getAppsInfo(const EventApplicationGetAppsInfoPtr &event) +{ + JSCallbackManagerPtr callbackManager = + DPL::StaticPointerCast<JSCallbackManager>(event->getPrivateData()); + if (!callbackManager) { + LoggerE("no callback manager"); + return; + } + + ApplicationAsyncCallbackManagerSingleton::Instance().unregisterCallbackManager(callbackManager); + + if(event->checkCancelled()) { + LoggerD("Operation cancelled"); + return; + } + + JSContextRef gContext = callbackManager->getContext(); + + JSValueRef error = NULL; + if (ExceptionCodes::None != event->getExceptionCode()) + { + switch (event->getExceptionCode()) + { + case ExceptionCodes::NotFoundException: + error = JSWebAPIErrorFactory::makeErrorObject(gContext, JSWebAPIErrorFactory::NOT_FOUND_ERROR,"given package is not found"); + break; + case ExceptionCodes::PlatformException: + error = JSWebAPIErrorFactory::makeErrorObject(gContext, JSWebAPIErrorFactory::UNKNOWN_ERROR,"platform exception"); + break; + default: + error = JSWebAPIErrorFactory::makeErrorObject(gContext, JSWebAPIErrorFactory::UNKNOWN_ERROR,"unknown error"); + break; + } + + callbackManager->callOnError(error); + return; + } + + Try { + ApplicationInformationArrayPtr appInfoArray = event->getAppInfoArray(); + + ApplicationConverterFactory::ConverterType converter = + ApplicationConverterFactory::getConverter(gContext); + + JSValueRef result = converter->toJSValueRef(appInfoArray); + + callbackManager->callOnSuccess(result); + return; + } Catch(Exception) { + LoggerE("error during processing answer" << _rethrown_exception.GetMessage()); + error = JSWebAPIErrorFactory::makeErrorObject(gContext, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Internal error"); + + callbackManager->callOnError(error); + return; + } +} + + +void ApplicationAsyncAnswerHandler::eventListener(const EventApplicationAppInfoEventListenerPtr &event) +{ + JSApplicationEventCallbackManagerPtr callbackManager = + DPL::StaticPointerCast<JSApplicationEventCallbackManager>(event->getPrivateData()); + if (!callbackManager) + { + LoggerE("no callback manager"); + return; + } + + JSContextRef gContext = callbackManager->getContext(); + + ApplicationConverterFactory::ConverterType converter = + ApplicationConverterFactory::getConverter(gContext); + + Try { + if(event->getType() == EventApplicationAppInfoEventListener::OnInstalled) + { + ApplicationInformationPtr appInfo = event->getAppInfo(); + if(appInfo == NULL) + { + LoggerE("AppInfo is not set."); + return; + } + JSValueRef result = converter->toJSValueRefFromApplicationInformation(appInfo); + callbackManager->callOnInstalled(result); + } + else if(event->getType() == EventApplicationAppInfoEventListener::OnUpdated) + { + ApplicationInformationPtr appInfo = event->getAppInfo(); + if(appInfo == NULL) + { + LoggerE("AppInfo is not set."); + return; + } + JSValueRef result = converter->toJSValueRefFromApplicationInformation(appInfo); + callbackManager->callOnUpdated(result); + } + else if(event->getType() == EventApplicationAppInfoEventListener::OnUninstalled) + { + ApplicationInformationPtr appInfo = event->getAppInfo(); + std::string appId = appInfo->getAppId(); + if(appId == "") + { + LoggerE("AppId is not set."); + return; + } + JSValueRef result = converter->toJSValueRef(appId); + callbackManager->callOnUninstalled(result); + } + else + { + LoggerE("Event callback type is wrong."); + return; + } + } Catch (Exception) { + LoggerE("Conversion error"); + return; + } +} + +} // Application +} // DeviceAPI diff --git a/wearable_src/Application/ApplicationController.h b/wearable_src/Application/ApplicationController.h new file mode 100755 index 0000000..32bccb6 --- /dev/null +++ b/wearable_src/Application/ApplicationController.h @@ -0,0 +1,97 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 _TIZEN_APPLICATION_APPLICATION_CONTROLLER_H_ +#define _TIZEN_APPLICATION_APPLICATION_CONTROLLER_H_ + +#include <dpl/shared_ptr.h> +#include <Commons/EventReceiver.h> +#include <Commons/EventListener.h> +#include <CommonsJavaScript/PrivateObject.h> +#include <CommonsJavaScript/JSPendingOperationPrivateObject.h> +#include <CommonsJavaScript/JSPendingOperation.h> +#include "IApplicationManager.h" + +namespace DeviceAPI { +namespace Application { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject<IApplicationManagerPtr, + WrtDeviceApis::CommonsJavaScript::NoOwnership> ApplicationPrivObject; + +typedef WrtDeviceApis::Commons::EventAnswerReceiver<EventApplicationLaunch> + EventApplicationLaunchEventAnswerReceiver; +typedef WrtDeviceApis::Commons::EventAnswerReceiver<EventApplicationKill> + EventApplicationKillEventAnswerReceiver; +typedef WrtDeviceApis::Commons::EventAnswerReceiver<EventApplicationLaunchAppControl> + EventApplicationLaunchAppControlEventAnswerReceiver; +typedef WrtDeviceApis::Commons::EventAnswerReceiver<EventApplicationLaunchAppControlReply> + EventApplicationLaunchAppControlReplyEventAnswerReceiver; +typedef WrtDeviceApis::Commons::EventAnswerReceiver<EventApplicationFindAppControl> + EventApplicationFindAppControlEventAnswerReceiver; +typedef WrtDeviceApis::Commons::EventAnswerReceiver<EventApplicationGetAppsContext> + EventApplicationGetAppsContextEventAnswerReceiver; +typedef WrtDeviceApis::Commons::EventAnswerReceiver<EventApplicationGetAppsInfo> + EventApplicationGetAppsInfoEventAnswerReceiver; +typedef WrtDeviceApis::Commons::EventListener<EventApplicationAppInfoEventListener> + EventApplicationAppInfoEventListenerListener; + +class ApplicationController : + public EventApplicationLaunchEventAnswerReceiver, + public EventApplicationKillEventAnswerReceiver, + public EventApplicationLaunchAppControlEventAnswerReceiver, + public EventApplicationLaunchAppControlReplyEventAnswerReceiver, + public EventApplicationFindAppControlEventAnswerReceiver, + public EventApplicationGetAppsContextEventAnswerReceiver, + public EventApplicationGetAppsInfoEventAnswerReceiver, + public EventApplicationAppInfoEventListenerListener, + public ApplicationPrivObject +{ +public: + ApplicationController(JSContextRef context, + IApplicationManagerPtr application); + virtual ~ApplicationController(); +protected: + void OnAnswerReceived(const EventApplicationLaunchPtr &event); + void OnAnswerReceived(const EventApplicationKillPtr &event); + void OnAnswerReceived(const EventApplicationLaunchAppControlPtr &event); + void OnAnswerReceived(const EventApplicationLaunchAppControlReplyPtr &event); + void OnAnswerReceived(const EventApplicationFindAppControlPtr &event); + void OnAnswerReceived(const EventApplicationGetAppsContextPtr &event); + void OnAnswerReceived(const EventApplicationGetAppsInfoPtr &event); + void onAnswerReceived(const EventApplicationAppInfoEventListenerPtr &event); +}; + +typedef DPL::SharedPtr<ApplicationController> ApplicationControllerPtr; + +//common part +class ApplicationAsyncAnswerHandler +{ +public: + static void launch(const EventApplicationLaunchPtr &event); + static void kill(const EventApplicationKillPtr &event); + static void launchAppControl(const EventApplicationLaunchAppControlPtr &event); + static void launchAppControlReply(const EventApplicationLaunchAppControlReplyPtr &event); + static void findAppControl(const EventApplicationFindAppControlPtr &event); + static void getAppsContext(const EventApplicationGetAppsContextPtr &event); + static void getAppsInfo(const EventApplicationGetAppsInfoPtr &event); + static void eventListener(const EventApplicationAppInfoEventListenerPtr &event); +}; + +} // Application +} // DeviceAPI + +#endif // _TIZEN_APPLICATION_APPLICATION_CONTROLLER_H_ diff --git a/wearable_src/Application/ApplicationConverter.cpp b/wearable_src/Application/ApplicationConverter.cpp new file mode 100644 index 0000000..4620a02 --- /dev/null +++ b/wearable_src/Application/ApplicationConverter.cpp @@ -0,0 +1,409 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 <CommonsJavaScript/JSUtils.h> +#include <CommonsJavaScript/Validator.h> +#include <CommonsJavaScript/ScopedJSStringRef.h> +#include <Commons/RegexUtils.h> +#include <Commons/Exception.h> +#include <JSWebAPIErrorFactory.h> + +#include "ApplicationConverter.h" +#include "JSApplication.h" +#include "JSApplicationInformation.h" +#include "JSApplicationContext.h" +#include "JSApplicationControlData.h" +#include "JSApplicationControlData.h" +#include "JSApplicationControl.h" +#include "JSRequestedApplicationControl.h" +#include "JSApplicationMetaData.h" +#include "JSApplicationCert.h" + +namespace DeviceAPI { +namespace Application { + +using namespace DeviceAPI::Common; +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::CommonsJavaScript; + +ApplicationConverter::ApplicationConverter(JSContextRef context) : Converter(context) +{ +} + +ApplicationConverter::~ApplicationConverter() +{ +} + + +JSValueRef ApplicationConverter::toJSValueRefFromApplication(const ApplicationPtr &arg) +{ + if(arg == NULL) { + Throw(Commons::ConversionException); + } + return CommonsJavaScript::JSUtils::makeObject(m_context, JSApplication::getClassRef(), arg); +} + + +JSValueRef ApplicationConverter::toJSValueRefFromApplicationCert(const ApplicationCertPtr &arg) +{ + if(arg == NULL) { + Throw(Commons::ConversionException); + } + return CommonsJavaScript::JSUtils::makeObject(m_context, JSApplicationCert::getClassRef(), arg); +} + + +JSValueRef ApplicationConverter::toJSValueRefFromApplicationCerts(const ApplicationCertArrayPtr &arg) +{ + if(arg == NULL) { + Throw(Commons::InvalidArgumentException); + } + return toJSValueRef_(*arg, &ApplicationConverter::toJSValueRefFromApplicationCert, this); +} + + +JSValueRef ApplicationConverter::toJSValueRefFromApplicationMetaData(const ApplicationMetaDataPtr &arg) +{ + if(arg == NULL) { + Throw(Commons::ConversionException); + } + return CommonsJavaScript::JSUtils::makeObject(m_context, JSApplicationMetaData::getClassRef(), arg); +} + + +JSValueRef ApplicationConverter::toJSValueRefFromApplicationMetaDataArray(const ApplicationMetaDataArrayPtr &arg) +{ + if(arg == NULL) { + Throw(Commons::InvalidArgumentException); + } + return toJSValueRef_(*arg, &ApplicationConverter::toJSValueRefFromApplicationMetaData, this); +} + + +JSValueRef ApplicationConverter::toJSValueRefFromApplicationInformation(const ApplicationInformationPtr &arg) +{ + if(arg == NULL) { + Throw(Commons::ConversionException); + } + return CommonsJavaScript::JSUtils::makeObject(m_context, JSApplicationInformation::getClassRef(), arg); +} + +ApplicationInformationPtr ApplicationConverter::toApplicationInformation(const JSValueRef &jsValue) +{ + if(JSApplicationInformation::isObjectOfClass(m_context, jsValue)) + return JSApplicationInformation::getApplicationInformation(m_context, jsValue); + + const ScopedJSStringRef nameStr(JSStringCreateWithUTF8CString(TIZEN_APPLICATION_INFORMATION_NAME)); + const ScopedJSStringRef appIdStr(JSStringCreateWithUTF8CString(TIZEN_APPLICATION_INFORMATION_ID)); + const ScopedJSStringRef iconPathStr(JSStringCreateWithUTF8CString(TIZEN_APPLICATION_INFORMATION_ICONPATH)); + const ScopedJSStringRef versionStr(JSStringCreateWithUTF8CString(TIZEN_APPLICATION_INFORMATION_VERSION)); + const ScopedJSStringRef showStr(JSStringCreateWithUTF8CString(TIZEN_APPLICATION_INFORMATION_SHOW)); + const ScopedJSStringRef categoriesStr(JSStringCreateWithUTF8CString(TIZEN_APPLICATION_INFORMATION_CATEGORIES)); + const ScopedJSStringRef installDateStr(JSStringCreateWithUTF8CString(TIZEN_APPLICATION_INFORMATION_INSTALL_DATE)); + const ScopedJSStringRef installSizeStr(JSStringCreateWithUTF8CString(TIZEN_APPLICATION_INFORMATION_INSTALL_SIZE)); + const ScopedJSStringRef packageIdStr(JSStringCreateWithUTF8CString(TIZEN_APPLICATION_INFORMATION_PACKAGE_ID)); + + JSObjectRef jsObject = toJSObjectRef(jsValue); + + JSValueRef nameData = JSObjectGetProperty(m_context, jsObject, nameStr.get(), NULL); + JSValueRef appIdStrData = JSObjectGetProperty(m_context, jsObject, appIdStr.get(), NULL); + JSValueRef iconPathData = JSObjectGetProperty(m_context, jsObject, iconPathStr.get(), NULL); + JSValueRef versionData = JSObjectGetProperty(m_context, jsObject, versionStr.get(), NULL); + JSValueRef showData = JSObjectGetProperty(m_context, jsObject, showStr.get(), NULL); + JSValueRef categoriesData = JSObjectGetProperty(m_context, jsObject, categoriesStr.get(), NULL); + JSValueRef installDateData = JSObjectGetProperty(m_context, jsObject, installDateStr.get(), NULL); + JSValueRef installSizeData = JSObjectGetProperty(m_context, jsObject, installSizeStr.get(), NULL); + JSValueRef pkgIdStrData = JSObjectGetProperty(m_context, jsObject, packageIdStr.get(), NULL); + + std::string name; + std::string appid; + std::string iconPath; + std::string version; + bool show; + std::vector <std::string> categories; + time_t installDate; + long installSize; + std::string pkgid; + + ApplicationInformationPtr result(new ApplicationInformation()); + if (!result) { + Throw(Commons::ConversionException); + } + + if (!JSValueIsUndefined(m_context, nameData)) { + name = toString(nameData); + result->setName(name); + } + if (!JSValueIsUndefined(m_context, appIdStrData)) { + appid = toString(appIdStrData); + result->setAppId(appid); + } + if (!JSValueIsUndefined(m_context, iconPathData)) { + iconPath = toString(iconPathData); + result->setIconPath(iconPath); + } + if (!JSValueIsUndefined(m_context, versionData)) { + version = toString(versionData); + result->setVersion(version); + } + if (!JSValueIsUndefined(m_context, showData)) { + show = toBool(showData); + result->setShow(show); + } + if (!JSValueIsUndefined(m_context, categoriesData)) { + categories = toVectorOfStrings(categoriesData); + result->setCategories(categories); + } + if (!JSValueIsUndefined(m_context, installDateData)) { + installDate = toDateTimeT(installDateData); + result->setInstallDate(installDate); + } + if (!JSValueIsUndefined(m_context, installSizeData)) { + installSize = toDateTimeT(installSizeData); + result->setInstallSize(installSize); + } + if (!JSValueIsUndefined(m_context, pkgIdStrData)) { + pkgid = toString(pkgIdStrData); + result->setPackageId(pkgid); + } + return result; +} + +JSValueRef ApplicationConverter::toJSValueRef(const ApplicationInformationArrayPtr &arg) +{ + if(arg == NULL) { + Throw(Commons::InvalidArgumentException); + } + return toJSValueRef_(*arg, &ApplicationConverter::toJSValueRefFromApplicationInformation, this); +} + +ApplicationInformationArrayPtr ApplicationConverter::toApplicationInformationArray(const JSValueRef &jsValue) +{ + ApplicationInformationArrayPtr result(new ApplicationInformationArray()); + + JSObjectRef jsObject = toJSObjectRef(jsValue); + for (std::size_t i = 0; i < JSGetArrayLength(m_context, jsObject); ++i) { + JSValueRef element = JSGetArrayElement(m_context, jsObject, i); + result->push_back(toApplicationInformation(element)); + } + return result; +} + +JSValueRef ApplicationConverter::toJSValueRefFromApplicationContext(const ApplicationContextPtr &arg) +{ + if(arg == NULL) { + Throw(Commons::InvalidArgumentException); + } + return CommonsJavaScript::JSUtils::makeObject(m_context, JSApplicationContext::getClassRef(), arg); +} + +ApplicationContextPtr ApplicationConverter::toApplicationContext(const JSValueRef &jsValue) +{ + if(JSApplicationContext::isObjectOfClass(m_context, jsValue)) + return JSApplicationContext::getApplicationContext(m_context, jsValue); + + const ScopedJSStringRef appIdStr(JSStringCreateWithUTF8CString(TIZEN_APPLICATION_CONTEXT_APP_ID)); + const ScopedJSStringRef contextIdStr(JSStringCreateWithUTF8CString(TIZEN_APPLICATION_CONTEXT_ID)); + + JSObjectRef jsObject = toJSObjectRef(jsValue); + + JSValueRef appIdStrData = JSObjectGetProperty(m_context, jsObject, appIdStr.get(), NULL); + JSValueRef contextIdStrData = JSObjectGetProperty(m_context, jsObject, contextIdStr.get(), NULL); + + std::string appid; + std::string contextid; + + ApplicationContextPtr result(new ApplicationContext()); + if (!result) { + Throw(Commons::ConversionException); + } + + if (!JSValueIsUndefined(m_context, appIdStrData)) { + appid = toString(appIdStrData); + result->setAppId(appid); + } + if (!JSValueIsUndefined(m_context, contextIdStrData)) { + contextid = toString(contextIdStrData); + result->setContextId(contextid); + } + + return result; +} + +JSValueRef ApplicationConverter::toJSValueRef(const ApplicationContextArrayPtr &arg) +{ + if(arg == NULL) { + Throw(Commons::ConversionException); + } + return toJSValueRef_(*arg, &ApplicationConverter::toJSValueRefFromApplicationContext, this); +} + +ApplicationContextArrayPtr ApplicationConverter::toApplicationContextArray(const JSValueRef &jsValue) +{ + ApplicationContextArrayPtr result(new ApplicationContextArray()); + + JSObjectRef jsObject = toJSObjectRef(jsValue); + for (std::size_t i = 0; i < JSGetArrayLength(m_context, jsObject); ++i) { + JSValueRef element = JSGetArrayElement(m_context, jsObject, i); + result->push_back(toApplicationContext(element)); + } + return result; +} + + +JSValueRef ApplicationConverter::toJSValueRef(const RequestedApplicationControlPtr &arg) +{ + if(arg == NULL) { + Throw(Commons::InvalidArgumentException); + } + return CommonsJavaScript::JSUtils::makeObject(m_context, JSRequestedApplicationControl::getClassRef(), arg); +} + +RequestedApplicationControlPtr ApplicationConverter::toRequestedApplicationControl(const JSValueRef &jsValue) +{ + if(JSRequestedApplicationControl::isObjectOfClass(m_context, jsValue)) { + return JSRequestedApplicationControl::getRequestedApplicationControl(m_context, jsValue); + } else { + ThrowMsg(Commons::ConversionException, "Wrong parameter type."); + } +} + + +JSValueRef ApplicationConverter::toJSValueRef(const ApplicationControlPtr &arg) +{ + if(arg == NULL) { + Throw(Commons::InvalidArgumentException); + } + + JSValueRef jsValueData = toJSValueRef(arg->getAppControlDataArray()); + + return JSApplicationControl::createJSObject(m_context, arg, jsValueData); +} + +ApplicationControlPtr ApplicationConverter::toApplicationControl(const JSValueRef &jsValue) +{ + if(JSApplicationControl::isObjectOfClass(m_context, jsValue)) { + ApplicationControlPtr result = JSApplicationControl::getApplicationControl(m_context, jsValue); + + JSObjectRef jsObject = toJSObjectRef(jsValue); + + const ScopedJSStringRef appControlDataStr(JSStringCreateWithUTF8CString(TIZEN_APPLICATION_CONTROL_DATA_INTERNAL)); + JSValueRef appControlDataData = JSObjectGetProperty(m_context, jsObject, appControlDataStr.get(), NULL); + + std::vector<ApplicationControlDataPtr> appControlDataArray; + try { + appControlDataArray = toApplicationControlDataArray(appControlDataData); + } catch(const Commons::ConversionException &err) { + LoggerD("ApplicationControlDataArray is wrong."); + } + + result->setAppControlDataArray(appControlDataArray); + + return result; + } else { + throw TypeMismatchException("not a object of class ApplicationControl"); + } +} + +JSValueRef ApplicationConverter::toJSValueRef(const ApplicationControlDataPtr &arg) +{ + JSValueRef jsValueValue = toJSValueRef(arg->getValue()); + + return JSApplicationControlData::createJSObject(m_context, arg, jsValueValue); +} + +ApplicationControlDataPtr ApplicationConverter::toApplicationControlData(const JSValueRef &jsValue) +{ + if(JSApplicationControlData::isObjectOfClass(m_context, jsValue)) + { + ApplicationControlDataPtr result = JSApplicationControlData::getApplicationControlData(m_context, jsValue); + + JSObjectRef jsObject = toJSObjectRef(jsValue); + + const ScopedJSStringRef appControlDataValueStr(JSStringCreateWithUTF8CString(TIZEN_APPLICATION_CONTROL_DATA_VALUE_INTERNAL)); + JSValueRef appControlDataValueData = JSObjectGetProperty(m_context, jsObject, appControlDataValueStr.get(), NULL); + + if (!JSValueIsUndefined(m_context, appControlDataValueData)) { + result->setValue(toVectorOfStrings(appControlDataValueData)); + } + return result; + } + else + { + const ScopedJSStringRef appControlDataKeyStr(JSStringCreateWithUTF8CString(TIZEN_APPLICATION_CONTROL_DATA_KEY)); + const ScopedJSStringRef appControlDataValueStr(JSStringCreateWithUTF8CString(TIZEN_APPLICATION_CONTROL_DATA_VALUE_INTERNAL)); + + JSObjectRef jsObject = toJSObjectRef(jsValue); + + JSValueRef appControlDataKeyData = JSObjectGetProperty(m_context, jsObject, appControlDataKeyStr.get(), NULL); + JSValueRef appControlDataValueData = JSObjectGetProperty(m_context, jsObject, appControlDataValueStr.get(), NULL); + + ApplicationControlDataPtr result(new ApplicationControlData()); + if (!result) { + Throw(Commons::ConversionException); + } + + if (!JSValueIsUndefined(m_context, appControlDataKeyData)) { + result->setKey(toString(appControlDataKeyData)); + } + + if (!JSValueIsUndefined(m_context, appControlDataValueData)) { + result->setValue(toVectorOfStrings(appControlDataValueData)); + } + return result; + } +} + +JSValueRef ApplicationConverter::toJSValueRef(const std::vector<ApplicationControlDataPtr> &arg) +{ + JSObjectRef jsResult = JSCreateArrayObject(m_context, 0, NULL); + + if (jsResult == NULL) { + ThrowMsg(Commons::ConversionException, "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(Commons::ConversionException, "Could not insert value into js array"); + } + } + + return jsResult; +} + +std::vector<ApplicationControlDataPtr> ApplicationConverter::toApplicationControlDataArray(const JSValueRef &jsValue) +{ + if (JSValueIsNull(m_context, jsValue) || JSValueIsUndefined(m_context, jsValue)) { + return std::vector<ApplicationControlDataPtr>(); + } + + if (!JSIsArrayValue(m_context, jsValue)) { + ThrowMsg(Commons::ConversionException, "Argument is not an JS array."); + } + + std::vector<ApplicationControlDataPtr> result; + JSObjectRef objArg = toJSObjectRef(jsValue); + for (std::size_t i = 0; i < JSGetArrayLength(m_context, objArg); ++i) { + JSValueRef element = JSGetArrayElement(m_context, objArg, i); + result.push_back(toApplicationControlData(element)); + } + return result; +} + +} +} diff --git a/wearable_src/Application/ApplicationConverter.h b/wearable_src/Application/ApplicationConverter.h new file mode 100755 index 0000000..a62bde0 --- /dev/null +++ b/wearable_src/Application/ApplicationConverter.h @@ -0,0 +1,69 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_TIZEN_APPLICATION_CONVERTER_H_ +#define TIZENAPIS_TIZEN_APPLICATION_CONVERTER_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/Converter.h> +#include "IApplicationManager.h" +#include "ApplicationInformation.h" +#include "ApplicationContext.h" +#include "ApplicationControlData.h" +#include "ApplicationControl.h" +#include "ApplicationCert.h" +#include "ApplicationMetaData.h" +#include "Application.h" +#include <Export.h> + +namespace DeviceAPI { +namespace Application { +class DLL_EXPORT ApplicationConverter : public WrtDeviceApis::CommonsJavaScript::Converter +{ +public: + using WrtDeviceApis::CommonsJavaScript::Converter::toJSValueRef; +public: + explicit ApplicationConverter(JSContextRef context); + virtual ~ApplicationConverter(); + JSValueRef toJSValueRefFromApplication(const ApplicationPtr &arg); + JSValueRef toJSValueRefFromApplicationInformation(const ApplicationInformationPtr &arg); + JSValueRef toJSValueRefFromApplicationCert(const ApplicationCertPtr &arg); + JSValueRef toJSValueRefFromApplicationCerts(const ApplicationCertArrayPtr &arg); + JSValueRef toJSValueRefFromApplicationMetaData(const ApplicationMetaDataPtr &arg); + JSValueRef toJSValueRefFromApplicationMetaDataArray(const ApplicationMetaDataArrayPtr &arg); + ApplicationInformationPtr toApplicationInformation(const JSValueRef &jsValue); + JSValueRef toJSValueRef(const ApplicationInformationArrayPtr &arg); + ApplicationInformationArrayPtr toApplicationInformationArray(const JSValueRef &jsValue); + JSValueRef toJSValueRefFromApplicationContext(const ApplicationContextPtr &arg); + ApplicationContextPtr toApplicationContext(const JSValueRef &jsValue); + JSValueRef toJSValueRef(const ApplicationContextArrayPtr &arg); + ApplicationContextArrayPtr toApplicationContextArray(const JSValueRef &jsValue); + JSValueRef toJSValueRef(const RequestedApplicationControlPtr &arg); + RequestedApplicationControlPtr toRequestedApplicationControl(const JSValueRef &jsValue); + JSValueRef toJSValueRef(const ApplicationControlPtr &arg); + ApplicationControlPtr toApplicationControl(const JSValueRef &jsValue); + JSValueRef toJSValueRef(const ApplicationControlDataPtr &arg); + ApplicationControlDataPtr toApplicationControlData(const JSValueRef &jsValue); + JSValueRef toJSValueRef(const std::vector<ApplicationControlDataPtr> &arg); + std::vector<ApplicationControlDataPtr> toApplicationControlDataArray(const JSValueRef &jsValue); +}; + +typedef WrtDeviceApis::CommonsJavaScript::ConverterFactory<ApplicationConverter> ApplicationConverterFactory; +} +} +#endif diff --git a/wearable_src/Application/ApplicationFactory.cpp b/wearable_src/Application/ApplicationFactory.cpp new file mode 100755 index 0000000..968ad68 --- /dev/null +++ b/wearable_src/Application/ApplicationFactory.cpp @@ -0,0 +1,38 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 "ApplicationManager.h" +#include "ApplicationFactory.h" + +namespace DeviceAPI { +namespace Application { + +IApplicationManagerPtr ApplicationFactory::createApplication() { + return IApplicationManagerPtr(new ApplicationManager()); +} + +ApplicationFactory& ApplicationFactory::getInstance() { + static ApplicationFactory theInstance; + return theInstance; +} + +ApplicationFactory::ApplicationFactory() { +} + +} +} diff --git a/wearable_src/Application/ApplicationFactory.h b/wearable_src/Application/ApplicationFactory.h new file mode 100755 index 0000000..857295f --- /dev/null +++ b/wearable_src/Application/ApplicationFactory.h @@ -0,0 +1,40 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_API_APPLICATION_FACTORY_H_ +#define TIZENAPIS_API_APPLICATION_FACTORY_H_ + +#include <dpl/noncopyable.h> +#include "IApplicationManager.h" + +namespace DeviceAPI { +namespace Application { + +class ApplicationFactory: DPL::Noncopyable { +public: + IApplicationManagerPtr createApplication(); + static ApplicationFactory& getInstance(); + +protected: + ApplicationFactory(); +}; + +} +} + +#endif diff --git a/wearable_src/Application/ApplicationInformation.cpp b/wearable_src/Application/ApplicationInformation.cpp new file mode 100755 index 0000000..48e8a7b --- /dev/null +++ b/wearable_src/Application/ApplicationInformation.cpp @@ -0,0 +1,178 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 "ApplicationInformation.h" + +namespace DeviceAPI { +namespace Application { +ApplicationInformation::ApplicationInformation(const std::string &appId) +{ + m_show = false; + m_installDate = 0; + m_installSize = 0; + m_isInitialized = false; + m_appId = appId; + m_categoriesJSValue = NULL; + m_installDateJSValue = NULL; +} + +ApplicationInformation::ApplicationInformation() +{ + m_show = false; + m_installDate = 0; + m_installSize = 0; + m_isInitialized = false; + m_categoriesJSValue = NULL; + m_installDateJSValue = NULL; +} + +ApplicationInformation::~ApplicationInformation() +{ + m_categoriesJSValue = NULL; + m_installDateJSValue = NULL; +} + +std::string ApplicationInformation::getName() const +{ + return m_name; +} + +void ApplicationInformation::setName(const std::string &name) +{ + m_name = name; +} + +std::string ApplicationInformation::getAppId() const +{ + return m_appId; +} + +void ApplicationInformation::setAppId(const std::string &appId) +{ + m_appId = appId; +} + +std::string ApplicationInformation::getIconPath() const +{ + return m_iconPath; +} + +void ApplicationInformation::setIconPath(const std::string &iconPath) +{ + m_iconPath = iconPath; +} + +std::string ApplicationInformation::getVersion() const +{ + return m_version; +} + +void ApplicationInformation::setVersion(const std::string &version) +{ + m_version = version; +} + +bool ApplicationInformation::getShow() const +{ + return m_show; +} + +void ApplicationInformation::setShow(const bool &show) +{ + m_show = show; +} + +std::vector<std::string> ApplicationInformation::getCategories() const +{ + return m_categories; +} + +void ApplicationInformation::setCategories(const std::vector<std::string> &categories) +{ + m_categories = categories; +} + +void ApplicationInformation::addCategories(const std::string &category) +{ + m_categories.push_back(category); +} + +time_t ApplicationInformation::getInstallDate() const +{ + return m_installDate; +} + +void ApplicationInformation::setInstallDate(const time_t &date) +{ + m_installDate = date; +} + +long ApplicationInformation::getInstallSize() const +{ + return m_installSize; +} + +void ApplicationInformation::setInstallSize(const long &size) +{ + m_installSize = size; +} + +std::string ApplicationInformation::getPackageId() const +{ + return m_pkgId; +} + +void ApplicationInformation::setPackageId(const std::string &pkgId) +{ + m_pkgId = pkgId; +} + +void ApplicationInformation::setCategoriesJSValue(const void *jsvalue) +{ + m_categoriesJSValue = jsvalue; +} + +const void * ApplicationInformation::getCategoriesJSValue() const +{ + return m_categoriesJSValue; +} + +void ApplicationInformation::setInstallDateJSValue(const void *jsvalue) +{ + m_installDateJSValue = jsvalue; +} + +const void * ApplicationInformation::getInstallDateJSValue() const +{ + return m_installDateJSValue; +} + +// Temporal code. if package manager issue is solved, disable below code. +#if 1 +bool ApplicationInformation::isInitialized() const +{ + return m_isInitialized; +} + +void ApplicationInformation::setInitialize() +{ + m_isInitialized = true; +} +#endif + +} +} diff --git a/wearable_src/Application/ApplicationInformation.h b/wearable_src/Application/ApplicationInformation.h new file mode 100755 index 0000000..2ba8636 --- /dev/null +++ b/wearable_src/Application/ApplicationInformation.h @@ -0,0 +1,91 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_API_APPLICATION_INFORMATION_H_ +#define TIZENAPIS_API_APPLICATION_INFORMATION_H_ + +#include <string> +#include <vector> +#include <dpl/shared_ptr.h> + +namespace DeviceAPI { +namespace Application { + +class ApplicationInformation; +typedef DPL::SharedPtr<ApplicationInformation> ApplicationInformationPtr; + +typedef std::vector<ApplicationInformationPtr> ApplicationInformationArray; +typedef DPL::SharedPtr<ApplicationInformationArray> ApplicationInformationArrayPtr; + +class ApplicationInformation +{ + public: + ApplicationInformation(const std::string &appId); + ApplicationInformation(); + ~ApplicationInformation(); + + std::string getName() const; + void setName(const std::string &name); + std::string getAppId() const; + void setAppId(const std::string &appId); + std::string getIconPath() const; + void setIconPath(const std::string &iconPath); + std::string getVersion() const; + void setVersion(const std::string &version); + bool getShow() const; + void setShow(const bool &show); + std::vector<std::string> getCategories() const; + void setCategories(const std::vector<std::string> &categories); + void addCategories(const std::string &category); + time_t getInstallDate() const; + void setInstallDate(const time_t &date); + long getInstallSize() const; + void setInstallSize(const long &size); + std::string getPackageId() const; + void setPackageId(const std::string &pkgId); + // temporal code. if package manager issue is solved, disable below code. +#if 1 + bool isInitialized() const; + void setInitialize(); +#endif + + private: + std::string m_name; + std::string m_appId; + std::string m_iconPath; + std::string m_version; + bool m_show; + time_t m_installDate; + long m_installSize; + std::string m_pkgId; + // temporal code. if package manager issue is solved, disable below code. + bool m_isInitialized; + std::vector<std::string> m_categories; + + public: + void setCategoriesJSValue(const void *jsvalue); + const void * getCategoriesJSValue() const; + void setInstallDateJSValue(const void *jsvalue); + const void * getInstallDateJSValue() const; + + private: + const void *m_categoriesJSValue; + const void *m_installDateJSValue; +}; +} +} +#endif diff --git a/wearable_src/Application/ApplicationInformationEventPrivateData.h b/wearable_src/Application/ApplicationInformationEventPrivateData.h new file mode 100755 index 0000000..e3f9acf --- /dev/null +++ b/wearable_src/Application/ApplicationInformationEventPrivateData.h @@ -0,0 +1,65 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_TIZEN_APPLICATION_INFORMATION_EVENT_PRIVATE_DATA_H_ +#define TIZENAPIS_TIZEN_APPLICATION_INFORMATION_EVENT_PRIVATE_DATA_H_ + +#include <dpl/shared_ptr.h> +#include <Commons/IEvent.h> +#include <CommonsJavaScript/JSCallbackManager.h> + +namespace DeviceAPI { +namespace Application { + +using namespace WrtDeviceApis::CommonsJavaScript; + +class ApplicationInformationEventPrivateData : public WrtDeviceApis::Commons::IEventPrivateData +{ + public: + ApplicationInformationEventPrivateData(const JSCallbackManagerPtr& onInstalled, + const JSCallbackManagerPtr& onUpdated, + const JSCallbackManagerPtr& onUninstalled): + m_onInstalled(onInstalled), + m_onUpdated(onUpdated), + m_onUninstalled(onUninstalled) + { + } + + JSCallbackManagerPtr getOnInstalled() const + { + return m_onInstalled; + } + JSCallbackManagerPtr getOnUpdated() const + { + return m_onUpdated; + } + JSCallbackManagerPtr getOnUninstalled() const + { + return m_onUninstalled; + } + +private: + JSCallbackManagerPtr m_onInstalled; + JSCallbackManagerPtr m_onUpdated; + JSCallbackManagerPtr m_onUninstalled; +}; + +typedef DPL::SharedPtr<ApplicationInformationEventPrivateData> ApplicationInformationEventPrivateDataPtr; +} +} +#endif diff --git a/wearable_src/Application/ApplicationListenerManager.cpp b/wearable_src/Application/ApplicationListenerManager.cpp new file mode 100755 index 0000000..6f703a0 --- /dev/null +++ b/wearable_src/Application/ApplicationListenerManager.cpp @@ -0,0 +1,26 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 "ApplicationListenerManager.h" + +namespace DeviceAPI { +namespace Application { + +SINGLETON_IMPLEMENTATION(ApplicationListenerManager) + +} // Application +} // DeviceAPI diff --git a/wearable_src/Application/ApplicationListenerManager.h b/wearable_src/Application/ApplicationListenerManager.h new file mode 100644 index 0000000..fe71371 --- /dev/null +++ b/wearable_src/Application/ApplicationListenerManager.h @@ -0,0 +1,100 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 _TIZEN_APPLICATION_LISTENER_MANAGER_H_ +#define _TIZEN_APPLICATION_LISTENER_MANAGER_H_ + +#include <map> +#include <JavaScriptCore/JavaScript.h> +#include <dpl/shared_ptr.h> +#include <IListenerManager.h> +#include "JSApplicationManager.h" +#include "ApplicationController.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Application { + +class ApplicationListenerManager : public DeviceAPI::Common::IListenerController +{ +private: + ApplicationListenerManager() + { + } + +public: + virtual ~ApplicationListenerManager() + { + } + + friend class ApplicationListenerManagerSingleton; +}; + +SINGLETON_DEFINITION(ApplicationListenerManager) + +class ApplicationListenerCanceller : public DeviceAPI::Common::IListenerItem +{ +public: + ApplicationListenerCanceller(JSContextRef context, JSObjectRef object, long watchId) : + DeviceAPI::Common::IListenerItem(context, object, watchId) + { + } + + virtual ~ApplicationListenerCanceller() + { + } + + virtual void cancelListener() + { + ApplicationController *priv = static_cast<ApplicationController*>(JSObjectGetPrivate(m_object)); + + if(!priv) + { + LoggerE("Object has no private object."); + return; + } + + IApplicationManagerPtr application(priv->getObject()); + + Try + { + LoggerD("Remove a listener"); + EventApplicationRemoveAppInfoEventListenerPtr event( + new EventApplicationRemoveAppInfoEventListener()); + + event->setWatchId(m_watchId); + event->setForSynchronousCall(); + + Try { + LoggerD("Remove change listener"); + application->removeAppInfoEventListener(event); + } Catch(WrtDeviceApis::Commons::Exception) { + LoggerE("Error on platform : " << _rethrown_exception.GetMessage()); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LoggerE("Error on platform : " << _rethrown_exception.GetMessage()); + } + } +}; +typedef DPL::SharedPtr<ApplicationListenerCanceller> ApplicationListenerCancellerPtr; + +} // Application +} // DeviceAPI + +#endif // _TIZEN_APPLICATION_LISTENER_MANAGER_H_ diff --git a/wearable_src/Application/ApplicationManager.cpp b/wearable_src/Application/ApplicationManager.cpp new file mode 100644 index 0000000..8de9985 --- /dev/null +++ b/wearable_src/Application/ApplicationManager.cpp @@ -0,0 +1,1607 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 "ApplicationManager.h" + +#include <cassert> +#include <sstream> +#include <pcrecpp.h> +#include <Commons/Exception.h> +#include <Commons/EventReceiver.h> +#include <Commons/Regex.h> +#include <plugins-ipc-message/ipc_message_support.h> + +#include "ApplicationInformation.h" +#include "ApplicationContext.h" +#include "ApplicationControlData.h" +#include "ApplicationControl.h" +#include "Application.h" + +#include <app.h> + +// to launch app by aul +#include <aul.h> + +// to get package name by appid +#include <app_info.h> +#include <app_manager.h> + +// To get cert information from package +#include <package_manager.h> +#include <package_info.h> + +// To get app size and installed time +#include <pkgmgr-info.h> + +// To get ppid +#include <unistd.h> + +#include <TimeTracer.h> + +#include <Logger.h> + +namespace DeviceAPI { +namespace Application { + + +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; + +namespace { + + typedef KeyMultiMap<ApplicationManager*, LaunchAppControlPendingEvent> LaunchAppControlPendingEventMap; + static LaunchAppControlPendingEventMap gLaunchAppControlPendingEventMap; + + // Callback from 'app_manager_set_app_context_event_cb' + // Used by 'kill' + static void app_manager_app_context_event_callback(app_context_h app_context, + app_context_event_e event, void *user_data) + { + int ret = 0; + + if(event != APP_CONTEXT_EVENT_TERMINATED) + return; + + int pid = 0; + + ret = app_context_get_pid(app_context, &pid); + if(ret != APP_MANAGER_ERROR_NONE) + { + LoggerE("Fail to get pid of terminated app (" << ret << ")"); + return; + } + + ApplicationManager* appManager = (ApplicationManager*)(user_data); + appManager->invokeManualAnswerKill(pid); + } + + // get package name by id + static char* getPackageByAppId(const char* appId) + { + app_info_h handle; + char* pkgName; + int ret = 0; + + ret = app_manager_get_app_info(appId, &handle); + if (ret < 0) + { + LoggerE("Fail to get appinfo"); + return NULL; + } + + ret = app_info_get_package(handle, &pkgName); + if (ret < 0) + { + LoggerE("Fail to get pkgName"); + pkgName = NULL; + } + + ret = app_info_destroy(handle); + if (ret < 0) + { + LoggerE("Fail to get destory appinfo"); + return NULL; + } + + return pkgName; + } + + + // Callback of 'app_manager_foreach_app_context' + // Used by 'getAppsContext' + static bool app_manager_app_context_callback(app_context_h app_context, void *user_data) + { + int ret = 0; + + char *app_id = NULL; + int pid; + + std::string contextId; + + if (user_data == NULL) + { + return false; + } + + ret = app_context_get_app_id(app_context, &app_id); + if((ret != APP_MANAGER_ERROR_NONE) || (app_id == NULL)) + { + LoggerE("Fail to get app id from context (" << ret << ")"); + return false; + } + + ret = app_context_get_pid(app_context, &pid); + if(ret != APP_MANAGER_ERROR_NONE) + { + LoggerE("Fail to get pid from context (" << ret << ")"); + if (app_id) + free(app_id); + return false; + } + + std::stringstream sstream; + sstream << pid; + contextId = sstream.str(); + + ApplicationContextPtr appContext(new ApplicationContext()); + appContext->setAppId(app_id); + appContext->setContextId(contextId); + + ApplicationContextArray* appContextArray = (ApplicationContextArray*)user_data; + + appContextArray->push_back(appContext); + + if (app_id) + free(app_id); + + return true; + } + + // Callback of 'service_send_launch_request' + // Used by 'launchAppControl' + static void service_reply_callback(service_h request, service_h reply, + service_result_e result, void *user_data) + { + LaunchAppControlPendingEventMap::DataKeyType key = + (LaunchAppControlPendingEventMap::DataKeyType)user_data; + + LaunchAppControlPendingEvent *pendingEvent = gLaunchAppControlPendingEventMap.getData(key); + if(pendingEvent != NULL) + { + ApplicationManager *application = (ApplicationManager *)pendingEvent->getThisObject(); + EventApplicationLaunchAppControlReplyPtr event = pendingEvent->getEvent(); + application->invokeManualAnswerLaunchAppControl(request, reply, result, event); + + delete pendingEvent; + pendingEvent = NULL; + user_data = NULL; + + gLaunchAppControlPendingEventMap.eraseData(key); + } + } + + static bool package_cert_cb(package_info_h handle, package_cert_type_e cert_type, const char *cert_value, void *user_data) + { + ApplicationCertPtr cert(new ApplicationCert()); + const char* certName = NULL; + + switch(cert_type) { + case PACKAGE_INFO_AUTHOR_ROOT_CERT: + certName = "AUTHOR_ROOT"; + break; + case PACKAGE_INFO_AUTHOR_INTERMEDIATE_CERT: + certName = "AUTHOR_INTERMEDIATE"; + break; + case PACKAGE_INFO_AUTHOR_SIGNER_CERT: + certName = "AUTHOR_SIGNER"; + break; + case PACKAGE_INFO_DISTRIBUTOR_ROOT_CERT: + certName = "DISTRIBUTOR_ROOT"; + break; + case PACKAGE_INFO_DISTRIBUTOR_INTERMEDIATE_CERT: + certName = "DISTRIBUTOR_INTERMEDIATE"; + break; + case PACKAGE_INFO_DISTRIBUTOR_SIGNER_CERT: + certName = "DISTRIBUTOR_SIGNER"; + break; + case PACKAGE_INFO_DISTRIBUTOR2_ROOT_CERT: + certName = "DISTRIBUTOR2_ROOT"; + break; + case PACKAGE_INFO_DISTRIBUTOR2_INTERMEDIATE_CERT: + certName = "DISTRIBUTOR2_INTERMEDIATE"; + break; + case PACKAGE_INFO_DISTRIBUTOR2_SIGNER_CERT: + certName = "DISTRIBUTOR2_SIGNER"; + break; + default: + LoggerE("Unknow Cert type!!!"); + break; + } + + cert->setType(certName); + cert->setValue(cert_value); + + ApplicationCertArray *certs = (ApplicationCertArray *)user_data; + certs->push_back(cert); + + return true; + } + + static std::string get_current_app_id() + { + std::string appId = AppManagerWrapperSingleton::Instance().getCurrentAppId(); + return appId; + } + + static int category_cb(const char *category, void *user_data) + { + if (category == NULL) + return true; + + ApplicationInformation* appInfo = (ApplicationInformation*)user_data; + appInfo->addCategories(category); + return true; + } + + static ApplicationInformationPtr create_app_info(pkgmgrinfo_appinfo_h handle) + { + char* appId = NULL; + char* name = NULL; + char* iconPath = NULL; + bool noDisplay = false; + char* pkgId = NULL; + int ret = 0; + + ApplicationInformationPtr appInfo(new ApplicationInformation()); + ret = pkgmgrinfo_appinfo_get_appid(handle, &appId); + if (ret != PMINFO_R_OK) { + LoggerD("Fail to get name"); + } else { + appInfo->setAppId(appId); + } + + ret = pkgmgrinfo_appinfo_get_label(handle, &name); + if ((ret != PMINFO_R_OK) || (name == NULL)) { + LoggerD("Fail to get name"); + } else { + appInfo->setName(name); + } + + ret = pkgmgrinfo_appinfo_get_icon(handle, &iconPath); + if ((ret != PMINFO_R_OK) || (iconPath == NULL)) { + LoggerD("Fail to get icon"); + } else { + appInfo->setIconPath(iconPath); + } + + ret = pkgmgrinfo_appinfo_is_nodisplay(handle, &noDisplay); + if (ret != PMINFO_R_OK) { + LoggerD("Fail to get nodisplay"); + } else { + appInfo->setShow(!noDisplay); + } + + ret = pkgmgrinfo_appinfo_foreach_category(handle, category_cb, (void*)appInfo.Get()); + if (ret != PMINFO_R_OK) { + LoggerD("Fail to get categories"); + } + + ret = pkgmgrinfo_appinfo_get_pkgid(handle, &pkgId); + if ((ret != PMINFO_R_OK) || (pkgId == NULL)) { + LoggerD("Fail to get pkg Id"); + } else { + appInfo->setPackageId(pkgId); + } + + char *version = NULL; + int installed_time = 0; + pkgmgrinfo_pkginfo_h pkginfo_h; + + ret = pkgmgrinfo_pkginfo_get_pkginfo(pkgId, &pkginfo_h); + if (ret != PMINFO_R_OK) { + LoggerE("Fail to get package info"); + } else { + ret = pkgmgrinfo_pkginfo_get_version(pkginfo_h, &version); + if (ret != PMINFO_R_OK) { + LoggerE("Fail to get version"); + } else { + appInfo->setVersion(version); + } + + ret = pkgmgrinfo_pkginfo_get_installed_time(pkginfo_h, &installed_time); + if (ret != PMINFO_R_OK) { + LoggerE("Fail to get installed date"); + } else { + appInfo->setInstallDate(installed_time); + } + + pkgmgrinfo_pkginfo_destroy_pkginfo(pkginfo_h); + } + + // remark : attribute "total size" is set at first attribute access time for performance. + return appInfo; + } + + + static int installed_app_info_cb(pkgmgrinfo_appinfo_h handle, void *user_data) + { + ApplicationInformationPtr appInfo = create_app_info(handle); + ApplicationInformationArray *appInfoArray = (ApplicationInformationArray*)user_data; + appInfoArray->push_back(appInfo); + return 0; + } + + // Callback from 'service_foreach_app_matched' + // Used by 'findAppControl' + static bool service_app_matched_callback(service_h service, const char *appid, void *user_data) + { + if(appid == NULL) + { + LoggerD("appid is NULL"); + return false; + } + //ApplicationInformationPtr appInfo(new ApplicationInformation(appid)); + pkgmgrinfo_appinfo_h handle; + int ret = pkgmgrinfo_appinfo_get_appinfo(appid, &handle); + if (ret != PMINFO_R_OK) { + LoggerD("Fail to get appInfo from appId : " << appid); + } else { + ApplicationInformationPtr appInfo = create_app_info(handle); + pkgmgrinfo_appinfo_destroy_appinfo(handle); + + ApplicationInformationArray *appInfos = (ApplicationInformationArray *)user_data; + appInfos->push_back(appInfo); + } + + return true; + } + + static int app_meta_data_cb(const char *meta_key, const char *meta_value, void *user_data) + { + if ((meta_key == NULL) || (meta_value == NULL)) { + LoggerE("meta_key or meta_value is null"); + return 0; + } + + ApplicationMetaDataPtr metaData(new ApplicationMetaData()); + + metaData->setKey(meta_key); + metaData->setValue(meta_value); + + ApplicationMetaDataArray *metaDataArray = (ApplicationMetaDataArray *)user_data; + metaDataArray->push_back(metaData); + + return 0; + } +} + +ApplicationManager::ApplicationManager() : + m_initialized(false) +{ + +} + +ApplicationManager::~ApplicationManager() +{ + if(m_installedApplicationsEmitters.size() != 0) + { + AppManagerWrapperSingleton::Instance().unregisterAppListChangedCallbacks(this); + WatchIdMap::iterator iter = m_watchIdMap.begin(); + for(; iter != m_watchIdMap.end(); iter++) + { + m_installedApplicationsEmitters.detach(iter->second); + } + } + + LaunchAppControlPendingEventMap::DataPtrListType dataPtrList = + gLaunchAppControlPendingEventMap.getDataPtrList(this); + + LaunchAppControlPendingEventMap::DataPtrListType::iterator iter = dataPtrList.begin(); + for(; iter != dataPtrList.end(); iter++) + { + delete *iter; + } + + gLaunchAppControlPendingEventMap.eraseKey(this); + + // unset context event callback which is registered by kill(). + app_manager_unset_app_context_event_cb(); +} + +void ApplicationManager::launch(const EventApplicationLaunchPtr& event) +{ + if (m_initialized == false) { + initialize(); + } + + EventRequestReceiver<EventApplicationLaunch>::PostRequest(event); +} + +void ApplicationManager::kill(const EventApplicationKillPtr& event) +{ + if (m_initialized == false) { + initialize(); + } + + EventRequestReceiver<EventApplicationKill>::PostRequest(event); +} + +void ApplicationManager::launchAppControl(const EventApplicationLaunchAppControlPtr& event) +{ + if (m_initialized == false) { + initialize(); + } + + EventApplicationLaunchAppControlReplyPtr eventReply = event->getEventReply(); + if(eventReply != NULL) + EventRequestReceiver<EventApplicationLaunchAppControlReply>::PostRequest(eventReply); + + EventRequestReceiver<EventApplicationLaunchAppControl>::PostRequest(event); +} + +void ApplicationManager::findAppControl(const EventApplicationFindAppControlPtr& event) +{ + if (m_initialized == false) { + initialize(); + } + + EventRequestReceiver<EventApplicationFindAppControl>::PostRequest(event); +} + +void ApplicationManager::getAppsContext(const EventApplicationGetAppsContextPtr& event) +{ + if (m_initialized == false) { + initialize(); + } + + EventRequestReceiver<EventApplicationGetAppsContext>::PostRequest(event); +} + + +void ApplicationManager::getAppsInfo(const EventApplicationGetAppsInfoPtr& event) +{ + if (m_initialized == false) { + initialize(); + } + + EventRequestReceiver<EventApplicationGetAppsInfo>::PostRequest(event); +} + + +void ApplicationManager::addAppInfoEventListener(const EventApplicationAddAppInfoEventListenerPtr& event) +{ + if (m_initialized == false) { + initialize(); + } + + EventRequestReceiver<EventApplicationAddAppInfoEventListener>::PostRequest(event); +} + +void ApplicationManager::removeAppInfoEventListener(const EventApplicationRemoveAppInfoEventListenerPtr& event) +{ + if (m_initialized == false) { + initialize(); + } + + EventRequestReceiver<EventApplicationRemoveAppInfoEventListener>::PostRequest(event); +} + + +void ApplicationManager::invokeManualAnswerLaunchAppControl(service_h request, service_h reply, + service_result_e result, + EventApplicationLaunchAppControlReplyPtr &event) +{ + if (event == NULL) { + return; + } + + if(result == SERVICE_RESULT_SUCCEEDED) + { + // create new service object to store result. + ApplicationControlDataArrayPtr appControlDataArray(new ApplicationControlDataArray()); + + int result = service_foreach_extra_data(reply, service_extra_data_callback, appControlDataArray.Get()); + if( result == SERVICE_ERROR_NONE) + { + event->setAppControlDataArray(appControlDataArray); + } + else + { + event->setExceptionCode(Commons::ExceptionCodes::NotFoundException); + } + } + else if(result == SERVICE_RESULT_FAILED || result == SERVICE_RESULT_CANCELED) + { + event->setExceptionCode(Commons::ExceptionCodes::NotFoundException); + } + + EventRequestReceiver<EventApplicationLaunchAppControlReply>::ManualAnswer(event); +} + +void ApplicationManager::invokeManualAnswerKill(int pid) +{ + DPL::Mutex::ScopedLock lock(&m_killMapLock); + + std::map<int, EventApplicationKillPtr>::iterator it = m_killEventMap.find(pid); + if (it == m_killEventMap.end()) { + return; + } + + EventApplicationKillPtr event = it->second; + m_killEventMap.erase(it); + + EventRequestReceiver<EventApplicationKill>::ManualAnswer(event); +} + + +bool ApplicationManager::service_extra_data_callback(service_h service, const char *key, void* user_data) +{ + int ret = 0; + + ApplicationControlDataArray* appControlDataArray = (ApplicationControlDataArray*)user_data; + + bool isArray = false; + ret = service_is_extra_data_array(service, key, &isArray); + if (ret != SERVICE_ERROR_NONE) + { + LoggerE("service_is_extra_data_array passes error"); + // fail to checking. go to next extra data. + return true; + } + + std::string keyStr(key); + + if(isArray) + { + int length = 0; + char **value = NULL; + + ret = service_get_extra_data_array(service, key, &value, &length); + switch(ret) + { + case SERVICE_ERROR_NONE: { + std::vector<std::string> valArray; + LoggerI("value length : " << length); + for (int i = 0; i < length; i++) + { + if(value[i]) + { + valArray.push_back(value[i]); + } + } + + ApplicationControlDataPtr appControlData(new ApplicationControlData()); + appControlData->setKey(keyStr); + appControlData->setValue(valArray); + appControlDataArray->push_back(appControlData); + + for (int i = 0; i < length; i++) + { + if (value[i]) + free(value[i]); + } + if (value) + free(value); + break; + } + case SERVICE_ERROR_INVALID_PARAMETER: + LoggerE("service_get_extra_data retuns SERVICE_ERROR_INVALID_PARAMETER"); + break; + case SERVICE_ERROR_KEY_NOT_FOUND: + LoggerE("service_get_extra_data retuns SERVICE_ERROR_KEY_NOT_FOUND"); + break; + case SERVICE_ERROR_OUT_OF_MEMORY: + LoggerE("service_get_extra_data retuns SERVICE_ERROR_OUT_OF_MEMORY"); + break; + default: + LoggerE("service_get_extra_data retuns Error"); + break; + } + } + else // (!isArray) + { + char *value = NULL; + + ret = service_get_extra_data(service, key, &value); + switch (ret) + { + case SERVICE_ERROR_NONE: + { + if(value == NULL) + { + LoggerE("service_get_extra_data returns NULL"); + break; + } + + std::vector<std::string> valArray; + valArray.push_back(value); + + ApplicationControlDataPtr appControlData(new ApplicationControlData()); + appControlData->setKey(keyStr); + appControlData->setValue(valArray); + appControlDataArray->push_back(appControlData); + + if (value) + free(value); + + break; + } + case SERVICE_ERROR_INVALID_PARAMETER: + LoggerE("service_get_extra_data retuns SERVICE_ERROR_INVALID_PARAMETER"); + break; + case SERVICE_ERROR_KEY_NOT_FOUND: + LoggerE("service_get_extra_data retuns SERVICE_ERROR_KEY_NOT_FOUND"); + break; + case SERVICE_ERROR_OUT_OF_MEMORY: + LoggerE("service_get_extra_data retuns SERVICE_ERROR_OUT_OF_MEMORY"); + break; + default: + LoggerE("service_get_extra_data retuns Error"); + break; + } + } + + return true; +} + + +ApplicationPtr ApplicationManager::getCurrentApplication() +{ + std::string appId = get_current_app_id(); + + //ApplicationInformationPtr appinfo(new ApplicationInformation(appId)); + pkgmgrinfo_appinfo_h handle; + TIME_TRACER_ITEM_BEGIN("(getCurrentApplication)pkgmgrinfo_appinfo_get_appinfo", 0); + int ret = pkgmgrinfo_appinfo_get_appinfo(appId.c_str(), &handle); + TIME_TRACER_ITEM_END("(getCurrentApplication)pkgmgrinfo_appinfo_get_appinfo", 0); + if (ret != PMINFO_R_OK) { + LoggerE("Fail to get appInfo"); + ThrowMsg(UnknownException, "pkgmgrinfo_appinfo_get_appinfo error : unknown error"); + } + ApplicationInformationPtr appInfo = create_app_info(handle); + pkgmgrinfo_appinfo_destroy_appinfo(handle); + + + ApplicationPtr app(new Application()); + app->setAppInfo(appInfo); + + LoggerD("set appinfo to application"); + { + //int pid = getpid(); + int pid = getppid(); + std::stringstream sstr; + sstr << pid; + app->setContextId(sstr.str()); + } + + return app; +} + + +ApplicationContextPtr ApplicationManager::getAppContext(const std::string id) +{ + int ret = 0; + + std::string contextId = id; + std::string appId; + + int selfpid = getppid(); + + if(contextId.empty()) + { + std::stringstream sstr; + sstr << selfpid; + contextId = sstr.str(); + + appId = get_current_app_id(); + } + else + { + int pid = 0; + std::stringstream(contextId) >> pid; + if (pid <= 0) + { + LoggerE("Given contextId is wrong"); + ThrowMsg(NotFoundException, "Given contextId is wrong"); + } + + if(pid == selfpid) + { + std::stringstream sstr; + sstr << selfpid; + contextId = sstr.str(); + + appId = get_current_app_id(); + } + else + { + char *app_id = NULL; + + TIME_TRACER_ITEM_BEGIN("(getAppContext)app_manager_get_app_id", 0); + ret = app_manager_get_app_id(pid, &app_id); + TIME_TRACER_ITEM_END("(getAppContext)app_manager_get_app_id", 0); + if(ret != APP_MANAGER_ERROR_NONE) + { + if(app_id) + free(app_id); + + switch(ret) + { + case APP_MANAGER_ERROR_NO_SUCH_APP: + case APP_MANAGER_ERROR_INVALID_PARAMETER: + LoggerE("app_manager_get_app_id error : no such app"); + ThrowMsg(NotFoundException, "app_manager_get_app_id error : no such app"); + break; + default: + LoggerE("app_manager_get_app_id error (" << ret << ")"); + ThrowMsg(UnknownException, "app_manager_get_app_id error : unknown error"); + break; + } + } + + appId.assign(app_id, strlen(app_id)); + + if(app_id) + free(app_id); + } + } + + ApplicationContextPtr appContext(new ApplicationContext()); + appContext->setAppId(appId); + appContext->setContextId(contextId); + + return appContext; +} + + +ApplicationInformationPtr ApplicationManager::getAppInfo(const std::string id) +{ + std::string appId = id; + // in case of no argument, get application information of current. + if (appId.empty()) + { + appId = get_current_app_id(); + } + + pkgmgrinfo_appinfo_h handle; + TIME_TRACER_ITEM_BEGIN("(getAppInfo)pkgmgrinfo_appinfo_get_appinfo", 0); + int ret = pkgmgrinfo_appinfo_get_appinfo(appId.c_str(), &handle); + TIME_TRACER_ITEM_END("(getAppInfo)pkgmgrinfo_appinfo_get_appinfo", 0); + if (ret != PMINFO_R_OK) { + ThrowMsg(NotFoundException, "Can not get appinfo"); + } + + ApplicationInformationPtr appInfo = create_app_info(handle); + + pkgmgrinfo_appinfo_destroy_appinfo(handle); + + return appInfo; +} + + +ApplicationCertArrayPtr ApplicationManager::getAppCerts(const std::string id) +{ + std::string appId = id; + + // in case of no argument, get application information of current. + if (appId.empty()) + { + appId = get_current_app_id(); + } + + TIME_TRACER_ITEM_BEGIN("(getAppCerts)getPackageByAppId", 0); + char* package = getPackageByAppId(appId.c_str()); + TIME_TRACER_ITEM_END("(getAppCerts)getPackageByAppId", 0); + if (package == NULL) + { + LoggerE("Can not get package"); + ThrowMsg(NotFoundException, "Can not get package"); + } + + package_info_h pkg_info; + int result = 0; + + TIME_TRACER_ITEM_BEGIN("(getAppCerts)package_manager_get_package_info", 0); + result = package_manager_get_package_info(package, &pkg_info); + TIME_TRACER_ITEM_END("(getAppCerts)package_manager_get_package_info", 0); + if (result != PACKAGE_MANAGER_ERROR_NONE) + { + ThrowMsg(UnknownException, "Can not get package info"); + } + + ApplicationCertArrayPtr certArray(new ApplicationCertArray()); + + TIME_TRACER_ITEM_BEGIN("(getAppCerts)package_info_foreach_cert_info", 0); + result = package_info_foreach_cert_info(pkg_info, package_cert_cb, (void*)certArray.Get()); + TIME_TRACER_ITEM_END("(getAppCerts)package_info_foreach_cert_info", 0); + if ((result != PACKAGE_MANAGER_ERROR_NONE) && (result != PACKAGE_MANAGER_ERROR_IO_ERROR)) + { + package_info_destroy(pkg_info); + ThrowMsg(UnknownException, "Can not get package cert info"); + } + + result = package_info_destroy(pkg_info); + if (result != PACKAGE_MANAGER_ERROR_NONE) { + LoggerE("Cannot destroy package info"); + } + + return certArray; +} + +std::string ApplicationManager::getAppSharedURI(const std::string id) +{ +#define TIZENAPIS_APP_FILE_SCHEME "file://" +#define TIZENAPIS_APP_SLASH "/" +#define TIZENAPIS_APP_SHARED "shared" + + std::string appId; + + if (id.empty()) { + appId = get_current_app_id(); + } else { + appId = id; + } + + app_info_h handle; + char* pkg_name = NULL; + TIME_TRACER_ITEM_BEGIN("(getAppSharedURI)app_manager_get_app_info", 0); + int ret = app_manager_get_app_info(appId.c_str(), &handle); + TIME_TRACER_ITEM_END("(getAppSharedURI)app_manager_get_app_info", 0); + if (ret != APP_ERROR_NONE) { + LoggerD("Fail to get appinfo"); + //throw NotFoundException("Fail to get appinfo"); + ThrowMsg(NotFoundException, "Fail to get appinfo"); + } + + TIME_TRACER_ITEM_BEGIN("(getAppSharedURI)app_info_get_package", 0); + ret = app_info_get_package(handle, &pkg_name); + TIME_TRACER_ITEM_END("(getAppSharedURI)app_info_get_package", 0); + if ((ret != APP_ERROR_NONE) || (pkg_name == NULL)) { + LoggerD("Fail to get pkg_name"); + //throw NotFoundException("Fail to get pkg_name"); + ThrowMsg(NotFoundException, "Fail to get pkg_name"); + } + + app_info_destroy(handle); + + pkgmgrinfo_pkginfo_h pkginfo_h; + char* root_path = NULL; + + TIME_TRACER_ITEM_BEGIN("(getAppSharedURI)pkgmgrinfo_pkginfo_get_pkginfo", 0); + ret = pkgmgrinfo_pkginfo_get_pkginfo(pkg_name, &pkginfo_h); + TIME_TRACER_ITEM_END("(getAppSharedURI)pkgmgrinfo_pkginfo_get_pkginfo", 0); + if (ret != PMINFO_R_OK) { + free(pkg_name); + //throw UnknownException("Fail to get pkginfo"); + ThrowMsg(UnknownException, "Fail to get pkginfo"); + } + + TIME_TRACER_ITEM_BEGIN("(getAppSharedURI)pkgmgrinfo_pkginfo_get_root_path", 0); + ret = pkgmgrinfo_pkginfo_get_root_path(pkginfo_h, &root_path); + TIME_TRACER_ITEM_END("(getAppSharedURI)pkgmgrinfo_pkginfo_get_root_path", 0); + if ((ret != PMINFO_R_OK) || (root_path == NULL)) { + LoggerE("Fail to get root path"); + free(pkg_name); + //throw UnknownException("Fail to get rotpath"); + ThrowMsg(UnknownException, "Fail to get rotpath"); + } + + std::string sharedURI = TIZENAPIS_APP_FILE_SCHEME + std::string(root_path) + TIZENAPIS_APP_SLASH + TIZENAPIS_APP_SHARED + TIZENAPIS_APP_SLASH; + free(pkg_name); + + pkgmgrinfo_pkginfo_destroy_pkginfo(pkginfo_h); + + return sharedURI; +} + +ApplicationMetaDataArrayPtr ApplicationManager::getAppMetaData(const std::string id) +{ + std::string appId = id; + + // in case of no argument, get application information of current. + if (appId.empty()) + { + appId = get_current_app_id(); + } + + int ret = 0; + pkgmgrinfo_appinfo_h handle; + + TIME_TRACER_ITEM_BEGIN("(getAppMetaData)pkgmgrinfo_appinfo_get_appinfo", 0); + ret = pkgmgrinfo_appinfo_get_appinfo(appId.c_str(), &handle); + TIME_TRACER_ITEM_END("(getAppMetaData)pkgmgrinfo_appinfo_get_appinfo", 0); + + if (ret != PMINFO_R_OK) { + ThrowMsg(NotFoundException, "Cannot found application with given appId"); + } + + ApplicationMetaDataArrayPtr metaDataArray(new ApplicationMetaDataArray()); + + TIME_TRACER_ITEM_BEGIN("(getAppMetaData)pkgmgrinfo_appinfo_foreach_metadata", 0); + ret = pkgmgrinfo_appinfo_foreach_metadata(handle, app_meta_data_cb, (void*)metaDataArray.Get()); + TIME_TRACER_ITEM_END("(getAppMetaData)pkgmgrinfo_appinfo_foreach_metadata", 0); + + if (ret != PMINFO_R_OK) { + LoggerE("pkgmgrinfo_appinfo_metadata_filter_foreach() failed"); + pkgmgrinfo_appinfo_destroy_appinfo(handle); + ThrowMsg(UnknownException, "fail to get custom tag"); + } + + pkgmgrinfo_appinfo_destroy_appinfo(handle); + + return metaDataArray; +} + +void ApplicationManager::OnRequestReceived(const EventApplicationLaunchPtr& event) +{ + Try + { + int ret; + int retry = 0; + + std::string appId = event->getAppId(); + if(appId.empty()) + { + LoggerE("App id is mandatory field."); + event->setExceptionCode(Commons::ExceptionCodes::InvalidArgumentException); + return; + } + + // if the application is running, send raise event to the app instead of reset the application. + // give a second chance to launch application to avoid platform issue. + // this retry code will be removed after platform code change. + while (retry < 3) { + ret = aul_open_app(appId.c_str()); + if (ret >= 0) { + break; + } + // delay 300ms for each retry + usleep(300 * 1000); + retry++; + LoggerD("retry launch request : " << retry); + } + + if (ret < 0) { + switch (ret) + { + case AUL_R_EINVAL: + case AUL_R_ERROR: + LoggerE("returns Not Found error"); + event->setExceptionCode(Commons::ExceptionCodes::NotFoundException); + break; + case AUL_R_ECOMM: + LoggerE("returns internal IPC error"); + event->setExceptionCode(Commons::ExceptionCodes::PlatformException); + break; + default: + LoggerE("returns Unknown error"); + event->setExceptionCode(Commons::ExceptionCodes::UnknownException); + break; + } + } else { + LoggerD("Success to launch."); + } + } + Catch (WrtDeviceApis::Commons::Exception) + { + LoggerE("Error on launch : " << _rethrown_exception.GetMessage()); + event->setExceptionCode(Commons::ExceptionCodes::PlatformException); + } +} + +// Because of platform issue, some termination event is not come to app_manager_set_app_context_event_cb(). +// To prevent blocking issue by wating callback function, add termination checking code. +// this function check whether callback is called or not after 3 sec. if callback is not called, +// calls callback function forcibily. +// After fixing platform issue, below code should be removed + +typedef struct { + ApplicationManager* appManager; + int pid; + EventApplicationKillPtr event; +} KILL_DATA_T; + +gboolean check_terminate_callback (gpointer user_data) +{ + //EventApplicationKillPtr event = (EventApplicationKillPtr)data; + KILL_DATA_T* data = (KILL_DATA_T*)user_data; + + char * appId = NULL; + if (app_manager_get_app_id(data->pid, &appId) == APP_MANAGER_ERROR_NONE) { + // if context is still alive, error callback should be called. + data->event->setExceptionCode(Commons::ExceptionCodes::PlatformException); + } + + data->appManager->invokeManualAnswerKill(data->pid); + + return false; +} + + +void ApplicationManager::OnRequestReceived(const EventApplicationKillPtr& event) +{ + Try + { + int ret; + std::string contextId = event->getContextId(); + + if(contextId.empty()) + { + LoggerE("Context id is mandatory"); + event->setExceptionCode(Commons::ExceptionCodes::InvalidArgumentException); + return; + } + + int pid; + std::stringstream(contextId) >> pid; + if(pid <= 0) + { + LoggerE("Given context id is wrong"); + event->setExceptionCode(Commons::ExceptionCodes::NotFoundException); + return; + } + + // if kill request is come for current context, throw InvalidValueException by spec + if (pid == getppid()) + { + event->setExceptionCode(Commons::ExceptionCodes::InvalidArgumentException); + return; + } + + char *appIdCStr = NULL; + ret = app_manager_get_app_id(pid, &appIdCStr); + if (ret != APP_MANAGER_ERROR_NONE) + { + LoggerE("Error while getting app id (" << ret << ")"); + event->setExceptionCode(Commons::ExceptionCodes::NotFoundException); + return; + } + + std::string appId = appIdCStr; + free(appIdCStr); + + app_context_h appContext; + ret = app_manager_get_app_context (appId.c_str(), &appContext); + if (ret != APP_MANAGER_ERROR_NONE) + { + LoggerE("Error while getting app context (" << ret << ")"); + event->setExceptionCode(Commons::ExceptionCodes::NotFoundException); + return; + } + + // TODO thread + ret = app_manager_set_app_context_event_cb(app_manager_app_context_event_callback, this); + if (ret != APP_MANAGER_ERROR_NONE) + { + LoggerE("Error while registering app context event (" << ret << ")"); + event->setExceptionCode(Commons::ExceptionCodes::UnknownException); + return; + } + + ret = app_manager_terminate_app(appContext); + if (ret != APP_MANAGER_ERROR_NONE) + { + LoggerE("Error while terminating app (" << ret << ")"); + event->setExceptionCode(Commons::ExceptionCodes::UnknownException); + return; + } + + // Because of platform issue, some termination event is not come to app_manager_set_app_context_event_cb(). + // To prevent blocking issue by wating callback function, add termination checking code. + // this function check whether callback is called or not after 3 sec. if callback is not called, + // calls callback function forcibily. + // After fixing platform issue, below code should be removed + { + KILL_DATA_T *data = new KILL_DATA_T; + data->pid = pid; + data->appManager = this; + data->event = event; + g_timeout_add(3000, check_terminate_callback, (void*)data); + } + + DPL::Mutex::ScopedLock lock(&m_killMapLock); + m_killEventMap[pid] = event; + event->switchToManualAnswer(); + } + Catch (WrtDeviceApis::Commons::Exception) + { + LoggerE("Error on kill : " << _rethrown_exception.GetMessage()); + event->setExceptionCode(Commons::ExceptionCodes::PlatformException); + } +} + +void ApplicationManager::OnRequestReceived(const EventApplicationLaunchAppControlPtr& event) +{ + Try + { + int ret = 0; + int retry = 0; + + ApplicationControlPtr appControl = event->getAppControl(); + if(appControl == NULL) + { + LoggerE("appControl is mandatory"); + event->setExceptionCode(Commons::ExceptionCodes::InvalidArgumentException); + return; + } + + std::string operation = appControl->getOperation(); + if(operation.empty()) + { + LoggerE("operation is madatory"); + event->setExceptionCode(Commons::ExceptionCodes::InvalidArgumentException); + return; + } + + std::string mime = appControl->getMime(); + pcrecpp::RE re("^(([a-z0-9\\.\\+\\-]+\\/([a-z0-9\\.\\+\\-]+|\\*))|\\*|\\*/\\*)$"); + if(!mime.empty() && !re.PartialMatch(mime)) + { + LoggerE("mime is invalid : \"" << mime << "\""); + event->setExceptionCode(Commons::ExceptionCodes::InvalidArgumentException); + return; + } + + std::string appId = event->getAppId(); + + service_h service; + service_create(&service); + + if (!appId.empty()) + { + service_set_app_id(service, appId.c_str()); + + // get resolved app id for aliased app id cannot be used to app_manager_get_app_info() + char* resolved_app_id = NULL; + service_get_app_id(service, &resolved_app_id); + + // Application exist checking. if specific application is not exist, return Not Found Exception. + app_info_h info_h; + if (app_manager_get_app_info(resolved_app_id, &info_h) != APP_MANAGER_ERROR_NONE) { + event->setExceptionCode(Commons::ExceptionCodes::NotFoundException); + if (resolved_app_id) { + free(resolved_app_id); + } + service_destroy(service); + return; + } + + app_info_destroy(info_h); + if (resolved_app_id) { + free(resolved_app_id); + } + } + + const char* windowId = IPCMessageSupport::sendMessageToUiProcess("tizen://getWindowHandle", NULL); + if (windowId != NULL) + { + service_set_window(service, atoi(windowId)); + } + free((void*)windowId); + + service_set_operation(service, operation.c_str() ); + + std::string uri = appControl->getUri(); + if (!uri.empty()) + { + service_set_uri(service, uri.c_str() ); + } + + if (!mime.empty()) + { + service_set_mime(service, mime.c_str() ); + } + + std::string category = appControl->getCategory(); + if (!category.empty()) + { + service_set_category(service, category.c_str() ); + } + + std::vector<ApplicationControlDataPtr> appControlDataArray = appControl->getAppControlDataArray(); + + if(!appControlDataArray.empty()) + { + LoggerI(" data size : " << appControlDataArray.size()); + + ApplicationControlDataArray::iterator iter; + for(iter = appControlDataArray.begin(); iter != appControlDataArray.end(); iter++) + { + ApplicationControlDataPtr appControlData = *iter; + + std::string key = appControlData->getKey(); + + if(key.empty()) + { + event->setExceptionCode(Commons::ExceptionCodes::InvalidArgumentException); + continue; + } + + std::vector<std::string> valueArray = appControlData->getValue(); + size_t size = valueArray.size(); + + const char **arr = (const char**)calloc(sizeof(char*), size); + + for (size_t j = 0; j < size; j++) + { + arr[j] = valueArray.at(j).c_str(); + } + + // @20121207-wscho: roll-back to return extra-data instead of extra-data array when the value size is one. + const char *keyCStr = key.c_str(); + if (size == 1) { + service_add_extra_data(service, keyCStr, arr[0]); + } else { + service_add_extra_data_array(service, keyCStr, arr, size); + } + + if (arr) + free(arr); + } + } + + LaunchAppControlPendingEvent *pendingEvent = NULL; + LaunchAppControlPendingEventMap::DataKeyType key = 0; + + EventApplicationLaunchAppControlReplyPtr eventReply = event->getEventReply(); + if(eventReply) + { + pendingEvent = new LaunchAppControlPendingEvent((void*)this, eventReply); + key = gLaunchAppControlPendingEventMap.insert(this, pendingEvent); + } + + // give a second chance to launch application to avoid platform issue. + // this retry code will be removed after platform code change. + while (retry < 3) { + ret = service_send_launch_request(service, service_reply_callback, (void *)key); + if (ret != SERVICE_ERROR_LAUNCH_REJECTED) { + break; + } + // delay 300ms for each retry + usleep(300 * 1000); + retry++; + LoggerD("retry launch request : " << retry); + } + + service_destroy(service); + + if(ret != SERVICE_ERROR_NONE) + { + switch (ret) + { + case SERVICE_ERROR_INVALID_PARAMETER: + LoggerE("service_send_launch_request returns SERVICE_ERROR_INVALID_PARAMETER"); + event->setExceptionCode(Commons::ExceptionCodes::InvalidArgumentException); + break; + case SERVICE_ERROR_OUT_OF_MEMORY: + LoggerE("service_send_launch_request returns SERVICE_ERROR_OUT_OF_MEMORY"); + event->setExceptionCode(Commons::ExceptionCodes::PlatformException); + break; + case SERVICE_ERROR_LAUNCH_REJECTED: + LoggerE("service_send_launch_request returns SERVICE_ERROR_LAUNCH_REJECTED!!!"); + event->setExceptionCode(Commons::ExceptionCodes::PlatformException); + break; + case SERVICE_ERROR_APP_NOT_FOUND: + LoggerE("service_send_launch_request returns SERVICE_ERROR_APP_NOT_FOUND"); + event->setExceptionCode(Commons::ExceptionCodes::NotFoundException); + break; + default: + LoggerE("service_send_launch_request returns UNKNOWN ERROR!!!"); + event->setExceptionCode(Commons::ExceptionCodes::UnknownException); + break; + } + + if(pendingEvent) + { + gLaunchAppControlPendingEventMap.eraseData(key); + + delete pendingEvent; + pendingEvent = NULL; + + eventReply->cancelRequest(); + EventRequestReceiver<EventApplicationLaunchAppControlReply>::ManualAnswer(eventReply); + } + } + } + Catch (WrtDeviceApis::Commons::Exception) + { + LoggerE("Error on launchAppControl : " << _rethrown_exception.GetMessage()); + event->setExceptionCode(Commons::ExceptionCodes::PlatformException); + } +} + +void ApplicationManager::OnRequestReceived(const EventApplicationLaunchAppControlReplyPtr& event) +{ + event->switchToManualAnswer(); +} + +void ApplicationManager::OnRequestReceived(const EventApplicationFindAppControlPtr& event) +{ + Try + { + ApplicationControlPtr appControl = event->getAppControl(); + if(appControl == NULL) + { + LoggerE("appControl is NULL"); + event->setExceptionCode(Commons::ExceptionCodes::InvalidArgumentException); + return; + } + + std::string operation = appControl->getOperation(); + if(operation.empty()) + { + LoggerE("operation is madatory"); + event->setExceptionCode(Commons::ExceptionCodes::InvalidArgumentException); + return; + } + + service_h service; + service_create(&service); + + service_set_operation(service, operation.c_str() ); + + std::string uri = appControl->getUri(); + if (!uri.empty()) + { + service_set_uri(service, uri.c_str() ); + } + + std::string mime = appControl->getMime(); + if (!mime.empty()) + { + service_set_mime(service, mime.c_str() ); + } + + std::string category = appControl->getCategory(); + if (!category.empty()) + { + service_set_category(service, category.c_str() ); + } + + std::vector<ApplicationControlDataPtr> appControlDataArray = appControl->getAppControlDataArray(); + + if(!appControlDataArray.empty()) + { + LoggerD(" data size : " << appControlDataArray.size()); + + ApplicationControlDataArray::iterator iter; + for(iter = appControlDataArray.begin(); iter != appControlDataArray.end(); iter++) + { + ApplicationControlDataPtr appControlData = *iter; + + std::string key = appControlData->getKey(); + + if(key.empty()) + { + event->setExceptionCode(Commons::ExceptionCodes::InvalidArgumentException); + continue; + } + + std::vector<std::string> valueArray = appControlData->getValue(); + size_t size = valueArray.size(); + + const char **arr = (const char**)calloc(sizeof(char*), size); + + for (size_t j = 0; j < size; j++) + { + arr[j] = valueArray.at(j).c_str(); + } + + // @20121207-wscho: roll-back to return extra-data instead of extra-data array when the value size is one. + const char *keyCStr = key.c_str(); + if (size == 1) { + service_add_extra_data(service, keyCStr, arr[0]); + } else { + service_add_extra_data_array(service, keyCStr, arr, size); + } + + if (arr) + free(arr); + } + } + + ApplicationInformationArrayPtr appInfos(new ApplicationInformationArray()); + + int result = service_foreach_app_matched(service, service_app_matched_callback, (void *)appInfos.Get()); + if (result != SERVICE_ERROR_NONE) + { + LoggerE("service_foreach_app_matched error (" << result << ")"); + event->setExceptionCode(Commons::ExceptionCodes::PlatformException); + service_destroy(service); + return; + } + + service_destroy(service); + + event->setAppInfos(appInfos); + } + Catch (WrtDeviceApis::Commons::Exception) + { + LoggerE("Error on findAppControl : " << _rethrown_exception.GetMessage()); + event->setExceptionCode(Commons::ExceptionCodes::PlatformException); + } +} + + +void ApplicationManager::OnRequestReceived(const EventApplicationGetAppsContextPtr& event) +{ + Try + { + int ret = 0; + + ApplicationContextArrayPtr appContextArray = event->getAppContextArray(); + ret = app_manager_foreach_app_context(app_manager_app_context_callback, appContextArray.Get()); + if(ret != APP_MANAGER_ERROR_NONE) + { + LoggerE("app_manager_foreach_app_context error (" << ret << ")"); + event->setExceptionCode(Commons::ExceptionCodes::PlatformException); + } + } + Catch (WrtDeviceApis::Commons::Exception) + { + LoggerE("Error on : " << _rethrown_exception.GetMessage()); + event->setExceptionCode(Commons::ExceptionCodes::PlatformException); + } +} + + + +void ApplicationManager::OnRequestReceived(const EventApplicationGetAppsInfoPtr& event) +{ + Try + { + int ret = 0; + ApplicationInformationArrayPtr appInfoArray = event->getAppInfoArray(); + ret = pkgmgrinfo_appinfo_get_installed_list(installed_app_info_cb, (void*)appInfoArray.Get()); + if (ret != PMINFO_R_OK) { + LoggerE("Error on getAppsInfo : "); + event->setExceptionCode(Commons::ExceptionCodes::PlatformException); + } + } + Catch (WrtDeviceApis::Commons::Exception) + { + LoggerE("Error on getAppsInfo : " << _rethrown_exception.GetMessage()); + event->setExceptionCode(Commons::ExceptionCodes::PlatformException); + } +} + + +void ApplicationManager::OnRequestReceived(const EventApplicationAddAppInfoEventListenerPtr& event) +{ + Try + { + EventApplicationAppInfoEventListenerEmitterPtr emitter = event->getEmitter(); + + if(m_installedApplicationsEmitters.size() == 0) + { + LoggerD("First time registering event listener to this application object."); + + // Below can throw Exception + AppManagerWrapperSingleton::Instance().registerAppListChangedCallbacks(this); + } + + m_installedApplicationsEmitters.attach(emitter); + + long watchId = AppManagerWrapperSingleton::Instance().getWatchIdAndInc(); + + m_watchIdMap[watchId] = emitter->getId(); + + event->setWatchId(watchId); + } + Catch (WrtDeviceApis::Commons::Exception) + { + LoggerE("Error on addAppInfoEventListener : " << _rethrown_exception.GetMessage()); + event->setExceptionCode(Commons::ExceptionCodes::PlatformException); + } +} + +void ApplicationManager::OnRequestReceived(const EventApplicationRemoveAppInfoEventListenerPtr& event) +{ + Try + { + long watchId = event->getWatchId(); + + if(m_watchIdMap.find(watchId) == m_watchIdMap.end()) { + ThrowMsg(NotFoundException, "No watchId : " << watchId); + } + + EventApplicationAppInfoEventListenerEmitter::IdType emitterId = m_watchIdMap[watchId]; + + bool success = m_installedApplicationsEmitters.detach(emitterId); + if(!success) + ThrowMsg(NotFoundException, "No watchId : " << watchId); + + if(m_installedApplicationsEmitters.size() == 0) + { + LoggerD("No more event listener on this application object."); + + AppManagerWrapperSingleton::Instance().unregisterAppListChangedCallbacks(this); + } + } + Catch (WrtDeviceApis::Commons::NotFoundException) + { + LoggerE("Not found : " << _rethrown_exception.GetMessage()); + event->setExceptionCode(Commons::ExceptionCodes::NotFoundException); + } + Catch (WrtDeviceApis::Commons::Exception) + { + LoggerE("Error on removeAppInfoEventListener : " << _rethrown_exception.GetMessage()); + event->setExceptionCode(Commons::ExceptionCodes::PlatformException); + } +} + + + +void ApplicationManager::onAppManagerEventInstalled(const char *appId) +{ + EventApplicationAppInfoEventListenerPtr event(new EventApplicationAppInfoEventListener()); + + pkgmgrinfo_appinfo_h handle; + int ret = pkgmgrinfo_appinfo_get_appinfo(appId, &handle); + if (ret != PMINFO_R_OK) { + event->setExceptionCode(Commons::ExceptionCodes::NotFoundException); + } else { + ApplicationInformationPtr appInfo = create_app_info(handle); + event->setAppInfo(appInfo); + pkgmgrinfo_appinfo_destroy_appinfo(handle); + } + + event->setType(EventApplicationAppInfoEventListener::OnInstalled); + m_installedApplicationsEmitters.emit(event); +} + +void ApplicationManager::onAppManagerEventUninstalled(const char *appId) +{ + EventApplicationAppInfoEventListenerPtr event(new EventApplicationAppInfoEventListener()); + + ApplicationInformationPtr appInfo(new ApplicationInformation(appId)); + + event->setType(EventApplicationAppInfoEventListener::OnUninstalled); + event->setAppInfo(appInfo); + m_installedApplicationsEmitters.emit(event); +} + +void ApplicationManager::onAppManagerEventUpdated(const char *appId) +{ + EventApplicationAppInfoEventListenerPtr event(new EventApplicationAppInfoEventListener()); + + pkgmgrinfo_appinfo_h handle; + int ret = pkgmgrinfo_appinfo_get_appinfo(appId, &handle); + if (ret != PMINFO_R_OK) { + event->setExceptionCode(Commons::ExceptionCodes::NotFoundException); + } else { + ApplicationInformationPtr appInfo = create_app_info(handle); + event->setAppInfo(appInfo); + pkgmgrinfo_appinfo_destroy_appinfo(handle); + } + + event->setType(EventApplicationAppInfoEventListener::OnUpdated); + m_installedApplicationsEmitters.emit(event); +} + +void ApplicationManager::initialize() +{ + if (!m_initialized) { + DPL::Mutex::ScopedLock lock(&m_initializationMutex); + if (!m_initialized) { + + } + } +} + +} +} diff --git a/wearable_src/Application/ApplicationManager.h b/wearable_src/Application/ApplicationManager.h new file mode 100644 index 0000000..b50125a --- /dev/null +++ b/wearable_src/Application/ApplicationManager.h @@ -0,0 +1,268 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_PLATFORM_APPLICATION_H_ +#define TIZENAPIS_PLATFORM_APPLICATION_H_ + +#include <map> +#include <set> +#include <list> +#include <Commons/Emitters.h> +#include "IApplicationManager.h" +#include "ApplicationFactory.h" + +#include "Application.h" +#include "ApplicationContext.h" +#include "ApplicationInformation.h" +#include "ApplicationCert.h" +#include "ApplicationMetaData.h" + +//#include <app_manager.h> +#include <app_service.h> + +#include "AppManagerWrapper.h" + +namespace DeviceAPI { +namespace Application { + +class ApplicationManager: public IApplicationManager, public IAppManagerAppListChangedCallbacks { + friend class ApplicationFactory; + +public: + ApplicationManager(); + virtual ~ApplicationManager(); + virtual void launch(const EventApplicationLaunchPtr& event); + virtual void kill(const EventApplicationKillPtr& event); + virtual void launchAppControl(const EventApplicationLaunchAppControlPtr& event); + virtual void findAppControl(const EventApplicationFindAppControlPtr& event); + virtual void getAppsContext(const EventApplicationGetAppsContextPtr& event); + virtual void getAppsInfo(const EventApplicationGetAppsInfoPtr& event); + virtual void addAppInfoEventListener(const EventApplicationAddAppInfoEventListenerPtr& event); + virtual void removeAppInfoEventListener(const EventApplicationRemoveAppInfoEventListenerPtr& event); + + void invokeManualAnswerLaunchAppControl(service_h request, service_h reply, service_result_e result, + EventApplicationLaunchAppControlReplyPtr &event); + void invokeManualAnswerKill(int pid); + + static bool service_extra_data_callback(service_h service, const char *key, void* user_data); + + static ApplicationPtr getCurrentApplication(); + static ApplicationContextPtr getAppContext(const std::string id); + static ApplicationInformationPtr getAppInfo(const std::string id); + static ApplicationCertArrayPtr getAppCerts(const std::string id); + static std::string getAppSharedURI(const std::string appId); + static ApplicationMetaDataArrayPtr getAppMetaData(const std::string id); + +protected: + virtual void OnRequestReceived(const EventApplicationLaunchPtr& event); + virtual void OnRequestReceived(const EventApplicationKillPtr& event); + virtual void OnRequestReceived(const EventApplicationLaunchAppControlPtr& event); + virtual void OnRequestReceived(const EventApplicationLaunchAppControlReplyPtr& event); + virtual void OnRequestReceived(const EventApplicationFindAppControlPtr& event); + virtual void OnRequestReceived(const EventApplicationGetAppsContextPtr& event); + virtual void OnRequestReceived(const EventApplicationGetAppsInfoPtr& event); + virtual void OnRequestReceived(const EventApplicationAddAppInfoEventListenerPtr& event); + virtual void OnRequestReceived(const EventApplicationRemoveAppInfoEventListenerPtr& event); + + // inherited from IAppManagerAppListChangedCallbacks + virtual void onAppManagerEventInstalled(const char *appId); + virtual void onAppManagerEventUninstalled(const char *appId); + virtual void onAppManagerEventUpdated(const char *appId); + +private: + void initialize(); + + DPL::Mutex m_initializationMutex; + bool m_initialized; + + std::map<int, EventApplicationKillPtr> m_killEventMap; + mutable DPL::Mutex m_killMapLock; + + typedef WrtDeviceApis::Commons::Emitters<EventApplicationAppInfoEventListenerEmitter> EventApplicationAppInfoEventListenerEmitters; + typedef std::map<long, EventApplicationAppInfoEventListenerEmitter::IdType> WatchIdMap; + + EventApplicationAppInfoEventListenerEmitters m_installedApplicationsEmitters; + WatchIdMap m_watchIdMap; + +}; + +class LaunchAppControlPendingEvent +{ +public: + LaunchAppControlPendingEvent(void *thisObject, const EventApplicationLaunchAppControlReplyPtr &event) : + m_thisObject(thisObject), + m_event(event) + { + } + + virtual ~LaunchAppControlPendingEvent() + { + } + + void* getThisObject() const { return m_thisObject; } + EventApplicationLaunchAppControlReplyPtr getEvent() const { return m_event; } + +private: + void *m_thisObject; + EventApplicationLaunchAppControlReplyPtr m_event; +}; + + +template <class KeyType, class DataType> +class KeyMultiMap +{ +public: + typedef unsigned int DataKeyType; + typedef DataType * DataPtrType; + typedef std::pair<KeyType, DataPtrType> KeyDataPairType; + typedef std::map<DataKeyType, KeyDataPairType> DataMapType; + typedef std::set<DataKeyType> DataKeySetType; + typedef std::map<KeyType, DataKeySetType> KeyMapType; + typedef std::list<DataPtrType> DataPtrListType; + + KeyMultiMap() : + m_keyAcc(0) + { + } + + DataKeyType insert(const KeyType &key, const DataPtrType &dataPtr) + { + DataKeyType dataKey = ++m_keyAcc; + + KeyDataPairType pair(key, dataPtr); + m_dataMap.insert(std::pair<DataKeyType, KeyDataPairType>(dataKey, pair)); + + typename KeyMapType::iterator keyMapIter = m_keyMap.find(key); + if(keyMapIter == m_keyMap.end()) + { + DataKeySetType newKeySet; + m_keyMap.insert(std::pair<KeyType, DataKeySetType>(key, newKeySet)); + keyMapIter = m_keyMap.find(key); + } + + DataKeySetType &dataKeySet = keyMapIter->second; + + dataKeySet.insert(dataKey); + + return dataKey; + } + + DataPtrType getData(const DataKeyType &dataKey) const + { + typename DataMapType::const_iterator dataMapIter = m_dataMap.find(dataKey); + + if(dataMapIter == m_dataMap.end()) + return static_cast<DataPtrType>(NULL); + + return dataMapIter->second.second; + } + + DataPtrListType getDataPtrList(const KeyType &key) + { + DataPtrListType dataPtrList; + + typename KeyMapType::const_iterator keyMapIter = m_keyMap.find(key); + if(keyMapIter == m_keyMap.end()) + return dataPtrList; + + DataKeySetType keySet = keyMapIter->second; + DataKeySetType::iterator keySetIter = keySet.begin(); + for(; keySetIter != keySet.end(); keySetIter++) + { + DataPtrType dataPtr = getData(*keySetIter); + if(dataPtr == NULL) + { + LoggerD("No data for " << *keySetIter); + break; + } + + dataPtrList.push_back(dataPtr); + } + + return dataPtrList; + } + + void eraseData(const DataKeyType &dataKey) + { + typename DataMapType::iterator dataKeyIter = m_dataMap.find(dataKey); + + if(dataKeyIter == m_dataMap.end()) + { + LoggerD("No data for " << dataKey); + return; + } + + KeyType key = dataKeyIter->second.first; + + m_dataMap.erase(dataKeyIter); + + typename KeyMapType::iterator keyMapIter = m_keyMap.find(key); + if(keyMapIter == m_keyMap.end()) + { + LoggerD("No data for Key"); + return; + } + + DataKeySetType &keySet = keyMapIter->second; + DataKeySetType::iterator keySetIter = keySet.find(dataKey); + if(keySetIter == keySet.end()) + { + LoggerD("No data for " << dataKey); + return; + } + + keySet.erase(keySetIter); + } + + void eraseKey(const KeyType &key) + { + typename KeyMapType::iterator keyMapIter = m_keyMap.find(key); + if(keyMapIter == m_keyMap.end()) + { + LoggerD("No data to erase."); + return; + } + + DataKeySetType &keySet = keyMapIter->second; + DataKeySetType::iterator keySetIter = keySet.begin(); + for(; keySetIter != keySet.end(); keySetIter++) + { + typename DataMapType::iterator dataKeyIter = m_dataMap.find(*keySetIter); + if(dataKeyIter == m_dataMap.end()) + { + LoggerD("No data to erase."); + break; + } + + m_dataMap.erase(dataKeyIter); + } + + m_keyMap.erase(keyMapIter); + } + +private: + DataKeyType m_keyAcc; + + DataMapType m_dataMap; + KeyMapType m_keyMap; +}; + +} +} + +#endif diff --git a/wearable_src/Application/ApplicationMetaData.cpp b/wearable_src/Application/ApplicationMetaData.cpp new file mode 100644 index 0000000..2711e8d --- /dev/null +++ b/wearable_src/Application/ApplicationMetaData.cpp @@ -0,0 +1,51 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 "ApplicationMetaData.h" + +namespace DeviceAPI { +namespace Application { +ApplicationMetaData::ApplicationMetaData() +{ +} + +ApplicationMetaData::~ApplicationMetaData() +{ +} + +std::string ApplicationMetaData::getKey() const +{ + return m_key; +} + +void ApplicationMetaData::setKey(const std::string &key) +{ + m_key = key; +} + +std::string ApplicationMetaData::getValue() const +{ + return m_value; +} + +void ApplicationMetaData::setValue(const std::string &value) +{ + m_value = value; +} + +} +} diff --git a/wearable_src/Application/ApplicationMetaData.h b/wearable_src/Application/ApplicationMetaData.h new file mode 100644 index 0000000..60e3b29 --- /dev/null +++ b/wearable_src/Application/ApplicationMetaData.h @@ -0,0 +1,52 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_API_APPLICATION_META_DATA_H_ +#define TIZENAPIS_API_APPLICATION_META_DATA_H_ + +#include <string> +#include <vector> +#include <dpl/shared_ptr.h> + +namespace DeviceAPI { +namespace Application { + +class ApplicationMetaData; +typedef DPL::SharedPtr<ApplicationMetaData> ApplicationMetaDataPtr; + +typedef std::vector<ApplicationMetaDataPtr> ApplicationMetaDataArray; +typedef DPL::SharedPtr<ApplicationMetaDataArray> ApplicationMetaDataArrayPtr; + + +class ApplicationMetaData +{ + public: + ApplicationMetaData(); + ~ApplicationMetaData(); + + std::string getKey() const; + void setKey(const std::string &key); + std::string getValue() const; + void setValue(const std::string &value); + + private: + std::string m_key; + std::string m_value; +}; +} +} +#endif diff --git a/wearable_src/Application/ApplicationUtil.cpp b/wearable_src/Application/ApplicationUtil.cpp new file mode 100755 index 0000000..a753c0f --- /dev/null +++ b/wearable_src/Application/ApplicationUtil.cpp @@ -0,0 +1,134 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 "ApplicationUtil.h" +#include <dpl/assert.h> + +namespace DeviceAPI { +namespace Application { + +using namespace WrtDeviceApis::CommonsJavaScript; + +ApplicationUtil::ApplicationUtil(JSContextRef context, + JSValueRef* exception) : + m_context(context), + m_exception(exception) +{ + Assert(NULL != m_context && "Context cannot be NULL."); +} + +ApplicationUtil::~ApplicationUtil() +{ +} + +bool ApplicationUtil::isObject(const JSValueRef& arg) +{ + return !JSValueIsNull(m_context, arg) && + !JSValueIsUndefined(m_context, arg) && + JSValueIsObject(m_context, arg); +} + +bool ApplicationUtil::isString(const JSValueRef& arg) +{ + return !JSValueIsNull(m_context, arg) && + !JSValueIsUndefined(m_context, arg) && + JSValueIsString(m_context, arg); +} + +bool ApplicationUtil::isFunction(const JSValueRef& arg) +{ + Converter converter(m_context); + return !JSValueIsNull(m_context, arg) && + !JSValueIsUndefined(m_context, arg) && + JSObjectIsFunction(m_context, converter.toJSObjectRef(arg)); +} + +bool ApplicationUtil::isArray(const JSValueRef& arg) +{ + Converter converter(m_context); + return !JSValueIsNull(m_context, arg) && + !JSValueIsUndefined(m_context, arg) && + JSIsArrayValue(m_context, arg); +} + +bool ApplicationUtil::isNullOrString(const JSValueRef& arg) +{ + return !JSValueIsUndefined(m_context, arg) && + (JSValueIsNull(m_context, arg) || + JSValueIsString(m_context, arg)); +} + +bool ApplicationUtil::isNullOrObject(const JSValueRef& arg) +{ + return !JSValueIsUndefined(m_context, arg) && + (JSValueIsNull(m_context, arg) || + JSValueIsObject(m_context, arg)); +} + +bool ApplicationUtil::isNullOrFunction(const JSValueRef& arg) +{ + Converter converter(m_context); + return !JSValueIsUndefined(m_context, arg) && + (JSValueIsNull(m_context, arg) || + JSObjectIsFunction(m_context, converter.toJSObjectRef(arg))); +} + +bool ApplicationUtil::isNullOrArray(const JSValueRef& arg) +{ + Converter converter(m_context); + return !JSValueIsUndefined(m_context, arg) && + (JSValueIsNull(m_context, arg) || + JSIsArrayValue(m_context, arg)); +} + +bool ApplicationUtil::isNullOrUndefined(const JSValueRef& arg) +{ + return (JSValueIsNull(m_context, arg) || + JSValueIsUndefined(m_context, arg)); +} + +bool ApplicationUtil::isNullOrUndefinedOrString(const JSValueRef& arg) +{ + return (JSValueIsNull(m_context, arg) || + JSValueIsUndefined(m_context, arg) || + JSValueIsString(m_context, arg)); +} + +bool ApplicationUtil::isNullOrUndefinedOrObject(const JSValueRef& arg) +{ + return (JSValueIsNull(m_context, arg) || + JSValueIsUndefined(m_context, arg) || + JSValueIsObject(m_context, arg)); +} + +bool ApplicationUtil::isNullOrUndefinedOrFunction(const JSValueRef& arg) +{ + Converter converter(m_context); + return (JSValueIsNull(m_context, arg) || + JSValueIsUndefined(m_context, arg) || + JSObjectIsFunction(m_context, converter.toJSObjectRef(arg))); +} + +bool ApplicationUtil::isNullOrUndefinedOrArray(const JSValueRef& arg) +{ + Converter converter(m_context); + return (JSValueIsNull(m_context, arg) || + JSValueIsUndefined(m_context, arg) || + JSIsArrayValue(m_context, arg)); +} + +}
} diff --git a/wearable_src/Application/ApplicationUtil.h b/wearable_src/Application/ApplicationUtil.h new file mode 100755 index 0000000..8a6d693 --- /dev/null +++ b/wearable_src/Application/ApplicationUtil.h @@ -0,0 +1,55 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_PLATFORM_APPLICATION_UTIL_H_ +#define TIZENAPIS_PLATFORM_APPLICATION_UTIL_H_ + +#include <CommonsJavaScript/Converter.h> + +namespace DeviceAPI { +namespace Application { +class ApplicationUtil +{ + public: + explicit ApplicationUtil(JSContextRef context, + JSValueRef* exception = NULL); + virtual ~ApplicationUtil(); + + bool isObject(const JSValueRef& arg); + bool isString(const JSValueRef& arg); + bool isFunction(const JSValueRef& arg); + bool isArray(const JSValueRef& arg); + bool isNullOrString(const JSValueRef& arg); + bool isNullOrObject(const JSValueRef& arg); + bool isNullOrFunction(const JSValueRef& arg); + bool isNullOrArray(const JSValueRef& arg); + bool isNullOrUndefined(const JSValueRef& arg); + bool isNullOrUndefinedOrString(const JSValueRef& arg); + bool isNullOrUndefinedOrObject(const JSValueRef& arg); + bool isNullOrUndefinedOrFunction(const JSValueRef& arg); + bool isNullOrUndefinedOrArray(const JSValueRef& arg); + + protected: + JSContextRef m_context; + JSValueRef* m_exception; +}; + +} +} // + +#endif + diff --git a/wearable_src/Application/CMakeLists.txt b/wearable_src/Application/CMakeLists.txt new file mode 100644 index 0000000..add416f --- /dev/null +++ b/wearable_src/Application/CMakeLists.txt @@ -0,0 +1,94 @@ +SET(TARGET_NAME ${application_target}) +SET(DESTINATION_NAME ${application_dest}) +SET(TARGET_IMPL_NAME ${application_impl}) +SET(TARGET_CONFIG_NAME ${application_config}) + +PKG_CHECK_MODULES(platform_pkgs_application REQUIRED + capi-appfw-app-manager + capi-appfw-application + capi-appfw-package-manager + pkgmgr + pkgmgr-info + wrt-plugins-ipc-message + libpcrecpp +) + +ADD_DEFINITIONS("-fvisibility=hidden") + +INCLUDE_DIRECTORIES( + ${INCLUDE_COMMON} + ${TOP}/Application + ${platform_pkgs_application_INCLUDE_DIRS} +) + +SET(CMAKE_INSTALL_RPATH + ${CMAKE_INSTALL_RPATH} + ${CMAKE_INSTALL_PREFIX}/${DESTINATION_LIB_PREFIX}/${tizen_dest} + ${CMAKE_INSTALL_PREFIX}/${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME} +) + +SET(SRCS_IMPL + ApplicationContext.cpp + ApplicationControl.cpp + ApplicationControlData.cpp + RequestedApplicationControl.cpp + ApplicationFactory.cpp + ApplicationInformation.cpp + ApplicationCert.cpp + ApplicationMetaData.cpp + IApplicationManager.cpp + ApplicationManager.cpp + AppManagerWrapper.cpp + Application.cpp + ApplicationAsyncCallbackManager.cpp + ApplicationController.cpp + ApplicationConverter.cpp + ApplicationListenerManager.cpp + ApplicationUtil.cpp + JSApplication.cpp + JSApplicationManager.cpp + JSApplicationContext.cpp + JSApplicationControl.cpp + JSApplicationControlData.cpp + JSRequestedApplicationControl.cpp + JSApplicationEventCallbackManager.cpp + JSApplicationInformation.cpp + JSApplicationCert.cpp + JSApplicationMetaData.cpp +) + +ADD_LIBRARY(${TARGET_IMPL_NAME} SHARED ${SRCS_IMPL}) + +TARGET_LINK_LIBRARIES(${TARGET_IMPL_NAME} + ${LIBS_COMMON} + ${tizen_impl} + ${platform_pkgs_application_LIBRARIES} +) + +SET(SRCS_CONFIG + plugin_config.cpp +) + +ADD_LIBRARY(${TARGET_CONFIG_NAME} SHARED ${SRCS_CONFIG}) + +TARGET_LINK_LIBRARIES(${TARGET_CONFIG_NAME} + ${LIBS_COMMON} +) + +SET(SRCS + plugin_initializer.cpp +) + +ADD_LIBRARY(${TARGET_NAME} SHARED ${SRCS}) + +TARGET_LINK_LIBRARIES(${TARGET_NAME} + ${TARGET_IMPL_NAME} + ${TARGET_CONFIG_NAME} +) + +INSTALL(TARGETS ${TARGET_NAME} ${TARGET_CONFIG_NAME} ${TARGET_IMPL_NAME} LIBRARY DESTINATION ${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME}) +INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/config.xml DESTINATION ${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME}) +INSTALL( + DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/ DESTINATION ${DESTINATION_HEADER_PREFIX}/application + FILES_MATCHING PATTERN "*.h" PATTERN "CMakeFiles" EXCLUDE +) diff --git a/wearable_src/Application/EventApplicationAddAppInfoEventListener.h b/wearable_src/Application/EventApplicationAddAppInfoEventListener.h new file mode 100755 index 0000000..2e23357 --- /dev/null +++ b/wearable_src/Application/EventApplicationAddAppInfoEventListener.h @@ -0,0 +1,65 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_API_APPLICATION_EVENT_APPLICATION_ADD_APP_INFO_EVENT_LISTENER_H_ +#define TIZENAPIS_API_APPLICATION_EVENT_APPLICATION_ADD_APP_INFO_EVENT_LISTENER_H_ + +#include <Commons/IEvent.h> +#include <dpl/shared_ptr.h> +#include "EventApplicationAppInfoEventListener.h" + +namespace DeviceAPI { +namespace Application { + +class EventApplicationAddAppInfoEventListener : public WrtDeviceApis::Commons::IEvent<EventApplicationAddAppInfoEventListener> +{ +private: + /* parameter */ + EventApplicationAppInfoEventListenerEmitterPtr m_emitter; + + /* result */ + long m_watchId; + +public: + void setEmitter(EventApplicationAppInfoEventListenerEmitterPtr &value) + { + m_emitter = value; + } + + EventApplicationAppInfoEventListenerEmitterPtr getEmitter() const + { + return m_emitter; + } + + void setWatchId(long watchId) + { + m_watchId = watchId; + } + + long getWatchId() const + { + return m_watchId; + } +}; + +typedef DPL::SharedPtr<EventApplicationAddAppInfoEventListener> EventApplicationAddAppInfoEventListenerPtr; + +} // Application +} // DeviceAPI + +#endif // TIZENAPIS_API_APPLICATION_EVENT_APPLICATION_ADD_APP_INFO_EVENT_LISTENER_H_ diff --git a/wearable_src/Application/EventApplicationAppInfoEventListener.h b/wearable_src/Application/EventApplicationAppInfoEventListener.h new file mode 100755 index 0000000..7da147a --- /dev/null +++ b/wearable_src/Application/EventApplicationAppInfoEventListener.h @@ -0,0 +1,94 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_API_APPLICATION_EVENT_APPLICATION_APP_INFO_EVENT_LISTENER_H_ +#define TIZENAPIS_API_APPLICATION_EVENT_APPLICATION_APP_INFO_EVENT_LISTENER_H_ + +#include <Commons/IEvent.h> +#include <dpl/shared_ptr.h> +#include <Commons/ListenerEvent.h> +#include <Commons/ListenerEventEmitter.h> +#include <Commons/Emitters.h> +#include "ApplicationInformation.h" + +namespace DeviceAPI { +namespace Application { + +class EventApplicationAppInfoEventListener : public WrtDeviceApis::Commons::ListenerEvent<EventApplicationAppInfoEventListener> +{ +public: + enum CallbackType + { + OnError, + OnInstalled, + OnUpdated, + OnUninstalled + }; + +private: + CallbackType m_type; + + std::string m_appId; + ApplicationInformationPtr m_appInfo; + +public: + void setAppId(const std::string &appId) + { + m_appId = appId; + } + + std::string getAppId() const + { + return m_appId; + } + + void setAppInfo(const ApplicationInformationPtr &appInfo) + { + m_appInfo = appInfo; + } + + ApplicationInformationPtr getAppInfo() const + { + return m_appInfo; + } + + void setType(CallbackType type) + { + m_type = type; + } + + int getType() const + { + return m_type; + } + + EventApplicationAppInfoEventListener() : + m_type(OnError), + m_appInfo(NULL) + { + } +}; + +typedef DPL::SharedPtr<EventApplicationAppInfoEventListener> EventApplicationAppInfoEventListenerPtr; +typedef WrtDeviceApis::Commons::ListenerEventEmitter<EventApplicationAppInfoEventListener> EventApplicationAppInfoEventListenerEmitter; +typedef DPL::SharedPtr<EventApplicationAppInfoEventListenerEmitter> EventApplicationAppInfoEventListenerEmitterPtr; +typedef WrtDeviceApis::Commons::Emitters<EventApplicationAppInfoEventListenerEmitter> EventApplicationAppInfoEventListenerEmitters; + +} // Application +} // DeviceAPI + +#endif // TIZENAPIS_API_APPLICATION_EVENT_APPLICATION_APP_INFO_EVENT_LISTENER_H_ diff --git a/wearable_src/Application/EventApplicationFindAppControl.h b/wearable_src/Application/EventApplicationFindAppControl.h new file mode 100755 index 0000000..ddd3abf --- /dev/null +++ b/wearable_src/Application/EventApplicationFindAppControl.h @@ -0,0 +1,72 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_API_APPLICATION_EVENT_FIND_APP_CONTROL_H_ +#define TIZENAPIS_API_APPLICATION_EVENT_FIND_APP_CONTROL_H_ + +#include <Commons/IEvent.h> +#include <dpl/shared_ptr.h> +#include "ApplicationInformation.h" +#include "ApplicationControl.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Application { + +class EventApplicationFindAppControl : public WrtDeviceApis::Commons::IEvent<EventApplicationFindAppControl> +{ +private: + /* parameter */ + ApplicationControlPtr m_appControl; + + /* result */ + ApplicationInformationArrayPtr m_appInfoArray; + +public: + void setAppControl(ApplicationControlPtr &appControl) + { + m_appControl = appControl; + } + + ApplicationControlPtr getAppControl() const + { + return m_appControl; + } + + void setAppInfos(ApplicationInformationArrayPtr &appInfos) + { + m_appInfoArray = appInfos; + } + + ApplicationInformationArrayPtr getAppInfos() const + { + return m_appInfoArray; + } + + EventApplicationFindAppControl() : + m_appControl(NULL), + m_appInfoArray(NULL) + { + } +}; + +typedef DPL::SharedPtr<EventApplicationFindAppControl> EventApplicationFindAppControlPtr; + +} // Application +} // DeviceAPI + +#endif // TIZENAPIS_API_APPLICATION_EVENT_FIND_APP_CONTROL_H_ diff --git a/wearable_src/Application/EventApplicationGetAppCerts.h b/wearable_src/Application/EventApplicationGetAppCerts.h new file mode 100644 index 0000000..f1f701e --- /dev/null +++ b/wearable_src/Application/EventApplicationGetAppCerts.h @@ -0,0 +1,72 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_API_APPLICATION_EVENT_GET_APP_CERTS_H_ +#define TIZENAPIS_API_APPLICATION_EVENT_GET_APP_CERTS_H_ + + +#include <Commons/IEvent.h> +#include <dpl/shared_ptr.h> +#include "ApplicationCert.h" + +namespace DeviceAPI { +namespace Application { + +class EventApplicationGetAppCerts : public WrtDeviceApis::Commons::IEvent<EventApplicationGetAppCerts> +{ +private: + std::string m_appId; + ApplicationCertArrayPtr m_certs; + +public: + void setAppId(std::string appId) + { + m_appId = appId; + } + + std::string getAppId() + { + return m_appId; + } + + void setAppCerts(ApplicationCertArrayPtr &certs) + { + m_certs = certs; + } + + ApplicationCertArrayPtr getAppCerts() const + { + return m_certs; + } + + void addAppCert(ApplicationCertPtr cert) + { + m_certs->push_back(cert); + } + + EventApplicationGetAppCerts() : + m_certs(new ApplicationCertArray()) + { + } +}; + +typedef DPL::SharedPtr<EventApplicationGetAppCerts> EventApplicationGetAppCertsPtr; + +} // Application +} // DeviceAPI + +#endif // TIZENAPIS_API_APPLICATION_EVENT_GET_APP_CERTS_H_
\ No newline at end of file diff --git a/wearable_src/Application/EventApplicationGetAppContext.h b/wearable_src/Application/EventApplicationGetAppContext.h new file mode 100755 index 0000000..48aa441 --- /dev/null +++ b/wearable_src/Application/EventApplicationGetAppContext.h @@ -0,0 +1,70 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_API_APPLICATION_EVENT_GET_APP_CONTEXT_H_ +#define TIZENAPIS_API_APPLICATION_EVENT_GET_APP_CONTEXT_H_ + + +#include <Commons/IEvent.h> +#include <dpl/shared_ptr.h> +#include "ApplicationContext.h" + +namespace DeviceAPI { +namespace Application { + +class EventApplicationGetAppContext : public WrtDeviceApis::Commons::IEvent<EventApplicationGetAppContext> +{ +private: + /* parameter */ + std::string m_appContextId; + + /* result */ + ApplicationContextPtr m_appContext; + +public: + void setAppContextId(std::string appContextId) + { + m_appContextId = appContextId; + } + + std::string getAppContextId() const + { + return m_appContextId; + } + + void setAppContext(const ApplicationContextPtr appContext) + { + m_appContext = appContext; + } + + ApplicationContextPtr getAppContext() const + { + return m_appContext; + } + + EventApplicationGetAppContext() : + m_appContext(NULL) + { + } +}; + +typedef DPL::SharedPtr<EventApplicationGetAppContext> EventApplicationGetAppContextPtr; + +} // Application +} // DeviceAPI + +#endif // TIZENAPIS_API_APPLICATION_EVENT_GET_APP_CONTEXT_H_ diff --git a/wearable_src/Application/EventApplicationGetAppInfo.h b/wearable_src/Application/EventApplicationGetAppInfo.h new file mode 100755 index 0000000..4fa59c5 --- /dev/null +++ b/wearable_src/Application/EventApplicationGetAppInfo.h @@ -0,0 +1,70 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_API_APPLICATION_EVENT_GET_APP_INFO_H_ +#define TIZENAPIS_API_APPLICATION_EVENT_GET_APP_INFO_H_ + + +#include <Commons/IEvent.h> +#include <dpl/shared_ptr.h> +#include "ApplicationInformation.h" + +namespace DeviceAPI { +namespace Application { + +class EventApplicationGetAppInfo : public WrtDeviceApis::Commons::IEvent<EventApplicationGetAppInfo> +{ +private: + /* parameter */ + std::string m_appId; + + /* result */ + ApplicationInformationPtr m_appInfo; + +public: + void setAppId(std::string appId) + { + m_appId = appId; + } + + std::string getAppId() const + { + return m_appId; + } + + void setAppInfo(const ApplicationInformationPtr appInfo) + { + m_appInfo = appInfo; + } + + ApplicationInformationPtr getAppInfo() const + { + return m_appInfo; + } + + EventApplicationGetAppInfo() : + m_appInfo(NULL) + { + } +}; + +typedef DPL::SharedPtr<EventApplicationGetAppInfo> EventApplicationGetAppInfoPtr; + +} // Application +} // DeviceAPI + +#endif // TIZENAPIS_API_APPLICATION_EVENT_GET_APP_INFO_H_ diff --git a/wearable_src/Application/EventApplicationGetAppSharedURI.h b/wearable_src/Application/EventApplicationGetAppSharedURI.h new file mode 100644 index 0000000..840ed59 --- /dev/null +++ b/wearable_src/Application/EventApplicationGetAppSharedURI.h @@ -0,0 +1,65 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_API_APPLICATION_EVENT_GET_APP_SHARED_URI_H_ +#define TIZENAPIS_API_APPLICATION_EVENT_GET_APP_SHARED_URI_H_ + + +#include <Commons/IEvent.h> +#include <dpl/shared_ptr.h> + +namespace DeviceAPI { +namespace Application { + +class EventApplicationGetAppSharedURI : public WrtDeviceApis::Commons::IEvent<EventApplicationGetAppSharedURI> +{ +private: + std::string m_appId; + std::string m_sharedURI; + +public: + void setAppId(std::string appId) + { + m_appId = appId; + } + + std::string getAppId() + { + return m_appId; + } + + void setSharedURI(std::string &sharedURI) + { + m_sharedURI = sharedURI; + } + + std::string getSharedURI() const + { + return m_sharedURI; + } + + EventApplicationGetAppSharedURI() + { + } +}; + +typedef DPL::SharedPtr<EventApplicationGetAppSharedURI> EventApplicationGetAppSharedURIPtr; + +} // Application +} // DeviceAPI + +#endif // TIZENAPIS_API_APPLICATION_EVENT_GET_APP_SHARED_URI_H_
\ No newline at end of file diff --git a/wearable_src/Application/EventApplicationGetAppsContext.h b/wearable_src/Application/EventApplicationGetAppsContext.h new file mode 100755 index 0000000..bc89df9 --- /dev/null +++ b/wearable_src/Application/EventApplicationGetAppsContext.h @@ -0,0 +1,61 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_API_APPLICATION_EVENT_GET_APPS_CONTEXT_H_ +#define TIZENAPIS_API_APPLICATION_EVENT_GET_APPS_CONTEXT_H_ + +#include <Commons/IEvent.h> +#include <dpl/shared_ptr.h> +#include "ApplicationContext.h" + +namespace DeviceAPI { +namespace Application { + +class EventApplicationGetAppsContext : public WrtDeviceApis::Commons::IEvent<EventApplicationGetAppsContext> +{ +private: + /* result */ + ApplicationContextArrayPtr m_appContextArray; + +public: + void addAppContext(const ApplicationContextPtr appContext) + { + m_appContextArray->push_back(appContext); + } + + const ApplicationContextArrayPtr getAppContextArray() const + { + return m_appContextArray; + } + + void setAppContextArray(ApplicationContextArrayPtr appContextArray) + { + m_appContextArray = appContextArray; + } + + EventApplicationGetAppsContext() : + m_appContextArray(new ApplicationContextArray()) + { + } +}; + +typedef DPL::SharedPtr<EventApplicationGetAppsContext> EventApplicationGetAppsContextPtr; + +} // Application +} // DeviceAPI + +#endif // TIZENAPIS_API_APPLICATION_EVENT_GET_APPS_CONTEXT_H_ diff --git a/wearable_src/Application/EventApplicationGetAppsInfo.h b/wearable_src/Application/EventApplicationGetAppsInfo.h new file mode 100755 index 0000000..0216eef --- /dev/null +++ b/wearable_src/Application/EventApplicationGetAppsInfo.h @@ -0,0 +1,61 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_API_APPLICATION_EVENT_GET_APPS_INFO_H_ +#define TIZENAPIS_API_APPLICATION_EVENT_GET_APPS_INFO_H_ + +#include <Commons/IEvent.h> +#include <dpl/shared_ptr.h> +#include "ApplicationInformation.h" + +namespace DeviceAPI { +namespace Application { + +class EventApplicationGetAppsInfo : public WrtDeviceApis::Commons::IEvent<EventApplicationGetAppsInfo> +{ +private: + /* result */ + ApplicationInformationArrayPtr m_appInfoArray; + +public: + void addAppInfo(const ApplicationInformationPtr appInfo) + { + m_appInfoArray->push_back(appInfo); + } + + const ApplicationInformationArrayPtr getAppInfoArray() const + { + return m_appInfoArray; + } + + void setAppInfoArray(ApplicationInformationArrayPtr appInfoArray) + { + m_appInfoArray = appInfoArray; + } + + EventApplicationGetAppsInfo() : + m_appInfoArray(new ApplicationInformationArray()) + { + } +}; + +typedef DPL::SharedPtr<EventApplicationGetAppsInfo> EventApplicationGetAppsInfoPtr; + +} // Application +} // DeviceAPI + +#endif // TIZENAPIS_API_APPLICATION_EVENT_GET_APPS_INFO_H_ diff --git a/wearable_src/Application/EventApplicationGetCurrApp.h b/wearable_src/Application/EventApplicationGetCurrApp.h new file mode 100644 index 0000000..abedf93 --- /dev/null +++ b/wearable_src/Application/EventApplicationGetCurrApp.h @@ -0,0 +1,57 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_API_APPLICATION_EVENT_GET_CURR_APP_H_ +#define TIZENAPIS_API_APPLICATION_EVENT_GET_CURR_APP_H_ + + +#include <Commons/IEvent.h> +#include <dpl/shared_ptr.h> +#include "Application.h" + +namespace DeviceAPI { +namespace Application { + +class EventApplicationGetCurrApp : public WrtDeviceApis::Commons::IEvent<EventApplicationGetCurrApp> +{ +private: + /* result */ + ApplicationPtr m_app; + +public: + void setApp(const ApplicationPtr app) + { + m_app = app; + } + + ApplicationPtr getApp() const + { + return m_app; + } + + EventApplicationGetCurrApp() : + m_app(NULL) + { + } +}; + +typedef DPL::SharedPtr<EventApplicationGetCurrApp> EventApplicationGetCurrAppPtr; + +} // Application +} // DeviceAPI + +#endif // TIZENAPIS_API_APPLICATION_EVENT_GET_CURR_APP_H_
\ No newline at end of file diff --git a/wearable_src/Application/EventApplicationGetRequestedAppControl.h b/wearable_src/Application/EventApplicationGetRequestedAppControl.h new file mode 100644 index 0000000..d187f4b --- /dev/null +++ b/wearable_src/Application/EventApplicationGetRequestedAppControl.h @@ -0,0 +1,69 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_API_APPLICATION_EVENT_APPLICATION_GET_REQUESTED_APP_CONTROL_H_ +#define TIZENAPIS_API_APPLICATION_EVENT_APPLICATION_GET_REQUESTED_APP_CONTROL_H_ + +#include <Commons/IEvent.h> +#include <dpl/shared_ptr.h> +#include "RequestedApplicationControl.h" + +namespace DeviceAPI { +namespace Application { + +class EventApplicationGetRequestedAppControl : public WrtDeviceApis::Commons::IEvent<EventApplicationGetRequestedAppControl> +{ +private: + /* result */ + RequestedApplicationControlPtr m_reqAppControl; + + std::string m_encodedBundle; + +public: + void setRequestedAppControl(RequestedApplicationControlPtr &reqAppControl) + { + m_reqAppControl = reqAppControl; + } + + RequestedApplicationControlPtr getRequestedAppControl() const + { + return m_reqAppControl; + } + + void setEncodedBundle(std::string encodedBundle) + { + m_encodedBundle = encodedBundle; + } + + std::string getEncodedBundle() const + { + return m_encodedBundle; + } + + EventApplicationGetRequestedAppControl() : + m_reqAppControl(NULL) + { + } +}; + +typedef DPL::SharedPtr<EventApplicationGetRequestedAppControl> EventApplicationGetRequestedAppControlPtr; + +} // Application +} // DeviceAPI + +#endif // TIZENAPIS_API_APPLICATION_EVENT_APPLICATION_GET_REQUESTED_APP_CONTROL_H_
\ No newline at end of file diff --git a/wearable_src/Application/EventApplicationKill.h b/wearable_src/Application/EventApplicationKill.h new file mode 100755 index 0000000..5f8f0aa --- /dev/null +++ b/wearable_src/Application/EventApplicationKill.h @@ -0,0 +1,54 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_API_APPLICATION_EVENT_APPLICATION_KILL_H_ +#define TIZENAPIS_API_APPLICATION_EVENT_APPLICATION_KILL_H_ + +#include <Commons/IEvent.h> +#include <dpl/shared_ptr.h> + +namespace DeviceAPI { +namespace Application { + +class EventApplicationKill : public WrtDeviceApis::Commons::IEvent<EventApplicationKill> +{ +private: + /* parameter */ + std::string m_contextId; + +public: + void setContextId(std::string contextId) + { + m_contextId = contextId; + } + + std::string getContextId() const + { + return m_contextId; + } + + EventApplicationKill() + { + } +}; + +typedef DPL::SharedPtr<EventApplicationKill> EventApplicationKillPtr; + +} // Application +} // DeviceAPI + +#endif // TIZENAPIS_API_APPLICATION_EVENT_APPLICATION_KILL_H_ diff --git a/wearable_src/Application/EventApplicationLaunch.h b/wearable_src/Application/EventApplicationLaunch.h new file mode 100755 index 0000000..9666f92 --- /dev/null +++ b/wearable_src/Application/EventApplicationLaunch.h @@ -0,0 +1,51 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_API_APPLICATION_EVENT_APPLICATION_LAUNCH_H_ +#define TIZENAPIS_API_APPLICATION_EVENT_APPLICATION_LAUNCH_H_ + +#include <Commons/IEvent.h> +#include <dpl/shared_ptr.h> + +namespace DeviceAPI { +namespace Application { + +class EventApplicationLaunch : public WrtDeviceApis::Commons::IEvent<EventApplicationLaunch> +{ +private: + /* parameter */ + std::string m_appId; + +public: + void setAppId(std::string appId) + { + m_appId = appId; + } + + std::string getAppId() const + { + return m_appId; + } +}; + +typedef DPL::SharedPtr<EventApplicationLaunch> EventApplicationLaunchPtr; + +} // Application +} // DeviceAPI + +#endif // TIZENAPIS_API_APPLICATION_EVENT_APPLICATION_LAUNCH_H_ diff --git a/wearable_src/Application/EventApplicationLaunchAppControl.h b/wearable_src/Application/EventApplicationLaunchAppControl.h new file mode 100755 index 0000000..735f804 --- /dev/null +++ b/wearable_src/Application/EventApplicationLaunchAppControl.h @@ -0,0 +1,116 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_API_APPLICATION_EVENT_APPLICATION_LAUNCH_APP_CONTROL_H_ +#define TIZENAPIS_API_APPLICATION_EVENT_APPLICATION_LAUNCH_APP_CONTROL_H_ + +#include <Commons/IEvent.h> +#include <dpl/shared_ptr.h> +#include "ApplicationControl.h" +#include "ApplicationControlData.h" + +namespace DeviceAPI { +namespace Application { + +class EventApplicationLaunchAppControlReply; +typedef DPL::SharedPtr<EventApplicationLaunchAppControlReply> EventApplicationLaunchAppControlReplyPtr; + +class EventApplicationLaunchAppControl : public WrtDeviceApis::Commons::IEvent<EventApplicationLaunchAppControl> +{ +private: + /* parameters */ + ApplicationControlPtr m_appControl; + std::string m_appId; + + EventApplicationLaunchAppControlReplyPtr m_eventReply; + +public: + void setAppControl(ApplicationControlPtr &appControl) + { + m_appControl = appControl; + } + + ApplicationControlPtr getAppControl() const + { + return m_appControl; + } + + void setAppId(std::string appId) + { + m_appId = appId; + } + + std::string getAppId() + { + return m_appId; + } + + void setEventReply(EventApplicationLaunchAppControlReplyPtr &eventReply) + { + m_eventReply = eventReply; + } + + EventApplicationLaunchAppControlReplyPtr getEventReply() const + { + return m_eventReply; + } + + EventApplicationLaunchAppControl() : + m_appControl(NULL), + m_eventReply(NULL) + { + } +}; + +typedef DPL::SharedPtr<EventApplicationLaunchAppControl> EventApplicationLaunchAppControlPtr; + +class EventApplicationLaunchAppControlReply : public WrtDeviceApis::Commons::IEvent<EventApplicationLaunchAppControlReply> +{ +private: + ApplicationControlDataArrayPtr m_appControlDataArray; + +public: + void addAppControlData(std::string &key, std::vector<std::string> &value) + { + ApplicationControlDataPtr appControlData(new ApplicationControlData()); + appControlData->setKey(key); + appControlData->setValue(value); + + m_appControlDataArray->push_back(appControlData); + } + + void setAppControlDataArray(ApplicationControlDataArrayPtr &appControlDataArray) + { + m_appControlDataArray = appControlDataArray; + } + + ApplicationControlDataArrayPtr getAppControlDataArray() const + { + return m_appControlDataArray; + } + + EventApplicationLaunchAppControlReply() : + m_appControlDataArray(new ApplicationControlDataArray()) + { + } +}; + +} // Application +} // DeviceAPI + +#endif // TIZENAPIS_API_APPLICATION_EVENT_APPLICATION_LAUNCH_APP_CONTROL_H_ diff --git a/wearable_src/Application/EventApplicationRemoveAppInfoEventListener.h b/wearable_src/Application/EventApplicationRemoveAppInfoEventListener.h new file mode 100755 index 0000000..a7dc2a4 --- /dev/null +++ b/wearable_src/Application/EventApplicationRemoveAppInfoEventListener.h @@ -0,0 +1,51 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_API_APPLICATION_EVENT_APPLICATION_REMOVE_APP_INFO_EVENT_LISTENER_H_ +#define TIZENAPIS_API_APPLICATION_EVENT_APPLICATION_REMOVE_APP_INFO_EVENT_LISTENER_H_ + +#include <Commons/IEvent.h> +#include <dpl/shared_ptr.h> + +namespace DeviceAPI { +namespace Application { + +class EventApplicationRemoveAppInfoEventListener : public WrtDeviceApis::Commons::IEvent<EventApplicationRemoveAppInfoEventListener> +{ +private: + /* result */ + long m_watchId; + +public: + void setWatchId(long watchId) + { + m_watchId = watchId; + } + + long getWatchId() const + { + return m_watchId; + } +}; + +typedef DPL::SharedPtr<EventApplicationRemoveAppInfoEventListener> EventApplicationRemoveAppInfoEventListenerPtr; + +} // Application +} // DeviceAPI + +#endif // TIZENAPIS_API_APPLICATION_EVENT_APPLICATION_ADD_APP_INFO_EVENT_LISTENER_H_ diff --git a/wearable_src/Application/IApplicationManager.cpp b/wearable_src/Application/IApplicationManager.cpp new file mode 100644 index 0000000..a522a50 --- /dev/null +++ b/wearable_src/Application/IApplicationManager.cpp @@ -0,0 +1,43 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 "IApplicationManager.h" + +namespace DeviceAPI { +namespace Application{ + +using namespace WrtDeviceApis::Commons; + +IApplicationManager::IApplicationManager() : + EventRequestReceiver<EventApplicationLaunch>(ThreadEnum::APPLICATION_THREAD), + EventRequestReceiver<EventApplicationKill>(ThreadEnum::APPLICATION_THREAD), + EventRequestReceiver<EventApplicationLaunchAppControl>(ThreadEnum::APPLICATION_THREAD), + EventRequestReceiver<EventApplicationLaunchAppControlReply>(ThreadEnum::APPLICATION_THREAD), + EventRequestReceiver<EventApplicationFindAppControl>(ThreadEnum::APPLICATION_THREAD), + EventRequestReceiver<EventApplicationGetAppsContext>(ThreadEnum::APPLICATION_THREAD), + EventRequestReceiver<EventApplicationGetAppsInfo>(ThreadEnum::APPLICATION_THREAD), + EventRequestReceiver<EventApplicationAddAppInfoEventListener>(ThreadEnum::APPLICATION_THREAD), + EventRequestReceiver<EventApplicationRemoveAppInfoEventListener>(ThreadEnum::APPLICATION_THREAD) +{ +} + +IApplicationManager::~IApplicationManager() +{ +} + +} // Application +} // DeviceAPI diff --git a/wearable_src/Application/IApplicationManager.h b/wearable_src/Application/IApplicationManager.h new file mode 100644 index 0000000..4cc0523 --- /dev/null +++ b/wearable_src/Application/IApplicationManager.h @@ -0,0 +1,76 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_API_APPLICATION_IAPPLICATION_MANAGER_H_ +#define TIZENAPIS_API_APPLICATION_IAPPLICATION_MANAGER_H_ + +#include <dpl/shared_ptr.h> +#include <Commons/ThreadPool.h> +#include "EventApplicationLaunch.h" +#include "EventApplicationKill.h" +#include "EventApplicationLaunchAppControl.h" +#include "EventApplicationFindAppControl.h" +#include "EventApplicationGetAppsContext.h" +#include "EventApplicationGetAppsInfo.h" +#include "EventApplicationAddAppInfoEventListener.h" +#include "EventApplicationRemoveAppInfoEventListener.h" + +namespace DeviceAPI { +namespace Application { + +class IApplicationManager : + public WrtDeviceApis::Commons::EventRequestReceiver<EventApplicationLaunch>, + public WrtDeviceApis::Commons::EventRequestReceiver<EventApplicationKill>, + public WrtDeviceApis::Commons::EventRequestReceiver<EventApplicationLaunchAppControl>, + public WrtDeviceApis::Commons::EventRequestReceiver<EventApplicationLaunchAppControlReply>, + public WrtDeviceApis::Commons::EventRequestReceiver<EventApplicationFindAppControl>, + public WrtDeviceApis::Commons::EventRequestReceiver<EventApplicationGetAppsContext>, + public WrtDeviceApis::Commons::EventRequestReceiver<EventApplicationGetAppsInfo>, + public WrtDeviceApis::Commons::EventRequestReceiver<EventApplicationAddAppInfoEventListener>, + public WrtDeviceApis::Commons::EventRequestReceiver<EventApplicationRemoveAppInfoEventListener> +{ +public: + virtual ~IApplicationManager(); + virtual void launch(const EventApplicationLaunchPtr& event) = 0; + virtual void kill(const EventApplicationKillPtr& event) = 0; + virtual void launchAppControl(const EventApplicationLaunchAppControlPtr& event) = 0; + virtual void findAppControl(const EventApplicationFindAppControlPtr& event) = 0; + virtual void getAppsContext(const EventApplicationGetAppsContextPtr& event) = 0; + virtual void getAppsInfo(const EventApplicationGetAppsInfoPtr& event) = 0; + virtual void addAppInfoEventListener(const EventApplicationAddAppInfoEventListenerPtr& event) = 0; + virtual void removeAppInfoEventListener(const EventApplicationRemoveAppInfoEventListenerPtr& event) = 0; + +protected: + IApplicationManager(); + + virtual void OnRequestReceived(const EventApplicationLaunchPtr& event) = 0; + virtual void OnRequestReceived(const EventApplicationKillPtr& event) = 0; + virtual void OnRequestReceived(const EventApplicationLaunchAppControlPtr& event) = 0; + virtual void OnRequestReceived(const EventApplicationLaunchAppControlReplyPtr& event) = 0; + virtual void OnRequestReceived(const EventApplicationFindAppControlPtr& event) = 0; + virtual void OnRequestReceived(const EventApplicationGetAppsContextPtr& event) = 0; + virtual void OnRequestReceived(const EventApplicationGetAppsInfoPtr& event) = 0; + virtual void OnRequestReceived(const EventApplicationAddAppInfoEventListenerPtr& event) = 0; + virtual void OnRequestReceived(const EventApplicationRemoveAppInfoEventListenerPtr& event) = 0; + }; + +typedef DPL::SharedPtr<IApplicationManager> IApplicationManagerPtr; + +} // Application +} // DeviceAPI + +#endif // TIZENAPIS_API_APPLICATION_IAPPLICATION_MANAGER_H_
\ No newline at end of file diff --git a/wearable_src/Application/JSApplication.cpp b/wearable_src/Application/JSApplication.cpp new file mode 100644 index 0000000..141b250 --- /dev/null +++ b/wearable_src/Application/JSApplication.cpp @@ -0,0 +1,211 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 <cassert> +#include <memory> +#include <CommonsJavaScript/JSUtils.h> +#include <CommonsJavaScript/Converter.h> +#include <Commons/Exception.h> +#include <CommonsJavaScript/ScopedJSStringRef.h> + +#include <ArgumentValidator.h> +#include <JSUtil.h> + +#include <JSWebAPIErrorFactory.h> + +#include "ApplicationController.h" +#include "ApplicationConverter.h" +#include "plugin_config.h" +#include "JSApplication.h" + +#include <TimeTracer.h> +#include <Export.h> +#include <Logger.h> + +#include <plugins-ipc-message/ipc_message_support.h> + +namespace DeviceAPI { +namespace Application { + +using namespace DeviceAPI::Common; + +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +JSClassRef JSApplication::m_classRef = NULL; + +JSClassDefinition JSApplication::m_classInfo = { + 0, + kJSClassAttributeNone, + TIZEN_INTERFACE_APPLICATION, + 0, + NULL, + m_function, + initialize, + finalize, + NULL, //HasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, + NULL, //ConvertToType +}; + +JSStaticFunction JSApplication::m_function[] = { + { APPLICATION_FUNCTION_API_EXIT, JSApplication::exit, kJSPropertyAttributeNone }, + { APPLICATION_FUNCTION_API_HIDE, JSApplication::hide, kJSPropertyAttributeNone }, + { APPLICATION_FUNCTION_API_GET_REQUESTED_APP_CONTROL, JSApplication::getRequestedAppControl, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + + +JSClassRef DLL_EXPORT JSApplication::getClassRef() { + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +void JSApplication::initialize(JSContextRef context, JSObjectRef object) +{ +} + +void JSApplication::finalize(JSObjectRef object) +{ + JSApplicationPriv* priv = static_cast<JSApplicationPriv*>(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + LoggerI("Deleting JSApplication object"); + delete priv; +} + +JSValueRef JSApplication::makeObject(JSContextRef ctx, const ApplicationPtr value) +{ + if(value == NULL) { + throw TypeMismatchException("Private object is NULL."); + } + + JSApplicationPriv* priv = new JSApplicationPriv(ctx, value); + JSObjectRef target = JSObjectMake(ctx, getClassRef(), priv); + + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(ctx); + JSUtil::setProperty(ctx, target, TIZEN_APPLICATION_APP_INFO, converter->toJSValueRefFromApplicationInformation(value->getAppInfo()), + kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete ); + JSUtil::setProperty(ctx, target, TIZEN_APPLICATION_APP_CONTEXT_ID, converter->toJSValueRef(value->getContextId()), + kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete ); + return target; +} + +JSValueRef JSApplication::exit(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + + try { + IPCMessageSupport::sendAsyncMessageToUiProcess(IPCMessageSupport::TIZEN_EXIT, NULL, NULL, NULL); + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); + + } catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(context, exception, err); + } catch (...) { + DeviceAPI::Common::UnknownException err("Unknown Error in ApplicationManager.getAppSharedURI()."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } +} + +JSValueRef JSApplication::hide(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + + try { + IPCMessageSupport::sendAsyncMessageToUiProcess(IPCMessageSupport::TIZEN_HIDE, NULL, NULL, NULL); + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); + + } catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(context, exception, err); + } catch (...) { + DeviceAPI::Common::UnknownException err("Unknown Error in ApplicationManager.getAppSharedURI()."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } +} + + +JSValueRef JSApplication::getRequestedAppControl(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + + JSApplicationPriv *priv = static_cast<JSApplicationPriv*>(JSObjectGetPrivate(thisObject)); + + + try { + if (!priv) { + throw TypeMismatchException("No private object."); + } + + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + EventApplicationGetRequestedAppControlPtr event(new EventApplicationGetRequestedAppControl()); + ApplicationPtr app = priv->getObject(); + + JSObjectRef windowObject = JSContextGetGlobalObject(context); + JSValueRef encodedBundle = JSObjectGetProperty(context, + windowObject, + ScopedJSStringRef(JSStringCreateWithUTF8CString("__bundle")).get(), + exception); + if (JSValueIsUndefined(context, encodedBundle) || JSValueIsNull(context, encodedBundle)) { + return JSValueMakeNull(context); + } + + event->setEncodedBundle(converter->toString(encodedBundle)); + app->getRequestedAppControl(event); + + if (event->getExceptionCode() == WrtDeviceApis::Commons::ExceptionCodes::NotFoundException) { + throw NotFoundException("No application control request found."); + } else if (event->getExceptionCode() == WrtDeviceApis::Commons::ExceptionCodes::UnknownException) { + return JSValueMakeNull(context); + } + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return converter->toJSValueRef(event->getRequestedAppControl()); + + } catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(context, exception, err); + } catch (...) { + DeviceAPI::Common::UnknownException err("Unknown Error in ApplicationManager.getAppSharedURI()."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } +} + +} +} diff --git a/wearable_src/Application/JSApplication.h b/wearable_src/Application/JSApplication.h new file mode 100644 index 0000000..1df90b9 --- /dev/null +++ b/wearable_src/Application/JSApplication.h @@ -0,0 +1,103 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_TIZEN_JS_APPLICATION_H_ +#define TIZENAPIS_TIZEN_JS_APPLICATION_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/PrivateObject.h> +#include <dpl/shared_ptr.h> +#include "Application.h" + +namespace DeviceAPI { +namespace Application { + +#define TIZEN_INTERFACE_APPLICATION "Application" + +#define TIZEN_APPLICATION_APP_INFO "appInfo" +#define TIZEN_APPLICATION_APP_CONTEXT_ID "contextId" + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject<ApplicationPtr, WrtDeviceApis::CommonsJavaScript::NoOwnership> JSApplicationPriv; + +class JSApplication { +public: + /* + * This initializes this JS class in the JS Engine. + */ + static JSClassRef getClassRef(); + + static JSValueRef makeObject(JSContextRef ctx, const ApplicationPtr value); + + + /** + * hide the application based on application context. + */ + static JSValueRef hide(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + /** + * exit current application + */ + static JSValueRef exit(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + /** + * get request application control + */ + static JSValueRef getRequestedAppControl(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, 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 contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_functions[]; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + static JSClassRef m_classRef; + +}; + +} +} +#endif //TIZENAPIS_TIZEN_JS_APPLICATION_H_ diff --git a/wearable_src/Application/JSApplicationCert.cpp b/wearable_src/Application/JSApplicationCert.cpp new file mode 100644 index 0000000..7b9f2c4 --- /dev/null +++ b/wearable_src/Application/JSApplicationCert.cpp @@ -0,0 +1,131 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 <cassert> +#include <memory> +#include <CommonsJavaScript/JSUtils.h> +#include <CommonsJavaScript/Converter.h> + +//#include <Commons/Exception.h> +#include <JSWebAPIErrorFactory.h> + +#include "ApplicationCert.h" +#include "JSApplicationCert.h" +#include <Export.h> +#include <Logger.h> + +namespace DeviceAPI { +namespace Application { + +using namespace WrtDeviceApis; +using namespace DeviceAPI::Common; + + +JSClassRef JSApplicationCert::m_classRef = NULL; + +JSClassDefinition JSApplicationCert::m_classInfo = { + 0, + kJSClassAttributeNone, + TIZEN_INTERFACE_APPLICATION_CERT, + 0, + m_property, + 0, + initialize, + finalize, + NULL, //HasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, + NULL, //ConvertToType +}; + +JSStaticValue JSApplicationCert::m_property[] = { + { TIZEN_APPLICATION_CERT_TYPE, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_APPLICATION_CERT_VALUE, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSClassRef DLL_EXPORT JSApplicationCert::getClassRef() { + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + + +void JSApplicationCert::initialize(JSContextRef context, JSObjectRef object) +{ +} + +void JSApplicationCert::finalize(JSObjectRef object) +{ + JSApplicationCertPriv* priv = static_cast<JSApplicationCertPriv*>(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + delete priv; +} + +bool JSApplicationCert::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +ApplicationCertPtr JSApplicationCert::getPrivData(JSObjectRef object) +{ + JSApplicationCertPriv *priv = static_cast<JSApplicationCertPriv*>(JSObjectGetPrivate(object)); + if (!priv) { + throw TypeMismatchException("Private object is null"); + } + ApplicationCertPtr result = priv->getObject(); + if (!result) { + throw TypeMismatchException("Private object is null"); + } + return result; +} + + +JSValueRef JSApplicationCert::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + try { + CommonsJavaScript::Converter converter(context); + ApplicationCertPtr privateData = getPrivData(object); + + LoggerD("JSApplicationCert::getProperty = " << propertyName); + + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_APPLICATION_CERT_TYPE)) { + return converter.toJSValueRef(privateData->getType()); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_APPLICATION_CERT_VALUE)) { + return converter.toJSValueRef(privateData->getValue()); + } + } catch (...) { + LoggerE("Exception occured while get property"); + return JSValueMakeUndefined(context); + } + + /* do not return undefined object to find method */ + return NULL; +} + +} +} diff --git a/wearable_src/Application/JSApplicationCert.h b/wearable_src/Application/JSApplicationCert.h new file mode 100644 index 0000000..f838bd2 --- /dev/null +++ b/wearable_src/Application/JSApplicationCert.h @@ -0,0 +1,81 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_TIZEN_JS_APPLICATION_CERT_H_ +#define TIZENAPIS_TIZEN_JS_APPLICATION_CERT_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/PrivateObject.h> +#include <dpl/shared_ptr.h> + +namespace DeviceAPI { +namespace Application { + +#define TIZEN_INTERFACE_APPLICATION_CERT "ApplicationCert" + +#define TIZEN_APPLICATION_CERT_TYPE "type" +#define TIZEN_APPLICATION_CERT_VALUE "value" + + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject<ApplicationCertPtr, WrtDeviceApis::CommonsJavaScript::NoOwnership> JSApplicationCertPriv; + +class JSApplicationCert { +public: + /* + * This initializes this JS class in the JS Engine. + */ + static JSClassRef getClassRef(); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + +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 member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; + + static JSClassRef m_classRef; + + static ApplicationCertPtr getPrivData(JSObjectRef object); + + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + +}; + +} +} +#endif diff --git a/wearable_src/Application/JSApplicationContext.cpp b/wearable_src/Application/JSApplicationContext.cpp new file mode 100644 index 0000000..8802dbf --- /dev/null +++ b/wearable_src/Application/JSApplicationContext.cpp @@ -0,0 +1,164 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 <cassert> +#include <memory> +#include <CommonsJavaScript/JSUtils.h> +#include <CommonsJavaScript/Converter.h> +#include "ApplicationContext.h" +#include <JSWebAPIErrorFactory.h> +#include "JSApplicationContext.h" +#include <Export.h> +#include <Logger.h> + +namespace DeviceAPI { +namespace Application { + +using namespace WrtDeviceApis; +using namespace DeviceAPI::Common; + +JSClassRef JSApplicationContext::m_classRef = NULL; + +JSClassDefinition JSApplicationContext::m_classInfo = { + 0, + kJSClassAttributeNone, + TIZEN_INTERFACE_APPLICATION_CONTEXT, + 0, + m_property, + 0, + initialize, + finalize, + NULL, //HasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, + NULL, //ConvertToType +}; + +JSStaticValue JSApplicationContext::m_property[] = { + { TIZEN_APPLICATION_CONTEXT_ID, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_APPLICATION_CONTEXT_APP_ID, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSClassRef DLL_EXPORT JSApplicationContext::getClassRef() { + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +JSValueRef JSApplicationContext::createJSObject(JSContextRef context, + const std::string &appId, + const std::string &contextId) +{ + ApplicationContextPtr privateData = ApplicationContextPtr(new ApplicationContext()); + privateData->setAppId(appId); + privateData->setContextId(contextId); + + JSApplicationContextPriv *priv = new JSApplicationContextPriv(context, privateData); + + JSObjectRef jsValueRef = JSObjectMake(context, getClassRef(), static_cast<void*>(priv)); + if (NULL == jsValueRef) { + LoggerE("object creation error"); + return JSValueMakeUndefined(context); + } + + return jsValueRef; +} + +void JSApplicationContext::initialize(JSContextRef context, JSObjectRef object) +{ +} + +void JSApplicationContext::finalize(JSObjectRef object) +{ + JSApplicationContextPriv* priv = static_cast<JSApplicationContextPriv*>(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + delete priv; +} + +bool JSApplicationContext::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +ApplicationContextPtr JSApplicationContext::getPrivData(JSContextRef context, JSObjectRef object) +{ + JSApplicationContextPriv *priv = static_cast<JSApplicationContextPriv*>(JSObjectGetPrivate(object)); + if (!priv) { + throw TypeMismatchException("Private object is null"); + } + + ApplicationContextPtr result = priv->getObject(); + if (!result) { + throw TypeMismatchException("Private object is null"); + } + + return result; +} + +ApplicationContextPtr JSApplicationContext::getApplicationContext(JSContextRef context, JSValueRef value) +{ + if (!isObjectOfClass(context, value)) { + throw TypeMismatchException("is not a object class"); + } + + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) { + throw TypeMismatchException("Private object is null"); + } + + JSApplicationContextPriv *priv = static_cast<JSApplicationContextPriv*>(JSObjectGetPrivate(object)); + if (!priv) { + throw TypeMismatchException("Private object is null"); + } + + return priv->getObject(); +} + + +JSValueRef JSApplicationContext::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + try { + CommonsJavaScript::Converter converter(context); + ApplicationContextPtr privateData = getPrivData(context, object); + + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_APPLICATION_CONTEXT_APP_ID)) { + return converter.toJSValueRef(privateData->getAppId()); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_APPLICATION_CONTEXT_ID)) { + return converter.toJSValueRef(privateData->getContextId()); + } + } catch (...) { + LoggerE("Exception occured while get property"); + return JSValueMakeUndefined(context); + } + + /* do not return undefined object to find method */ + return NULL; +} + + +} +} diff --git a/wearable_src/Application/JSApplicationContext.h b/wearable_src/Application/JSApplicationContext.h new file mode 100755 index 0000000..24f7034 --- /dev/null +++ b/wearable_src/Application/JSApplicationContext.h @@ -0,0 +1,91 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_TIZEN_JS_APPLICATION_CONTEXT_H_ +#define TIZENAPIS_TIZEN_JS_APPLICATION_CONTEXT_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/PrivateObject.h> +#include <dpl/shared_ptr.h> +#include "ApplicationContext.h" + +namespace DeviceAPI { +namespace Application { + +#define TIZEN_INTERFACE_APPLICATION_CONTEXT "ApplicationContext" + +#define TIZEN_APPLICATION_CONTEXT_ID "id" +#define TIZEN_APPLICATION_CONTEXT_APP_ID "appId" + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject<ApplicationContextPtr, WrtDeviceApis::CommonsJavaScript::NoOwnership> JSApplicationContextPriv; + +class JSApplicationContext { +public: + /* + * This initializes this JS class in the JS Engine. + */ + static JSClassRef getClassRef(); + + static JSValueRef createJSObject(JSContextRef context, + const std::string &appId, + const std::string &contextId); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + static ApplicationContextPtr getApplicationContext(JSContextRef context, JSValueRef value); + +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 property. + */ + static JSStaticFunction m_functions[]; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; + + static JSClassRef m_classRef; + + static ApplicationContextPtr getPrivData(JSContextRef context, JSObjectRef object); + + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + +}; + +} +} +#endif diff --git a/wearable_src/Application/JSApplicationControl.cpp b/wearable_src/Application/JSApplicationControl.cpp new file mode 100644 index 0000000..870828d --- /dev/null +++ b/wearable_src/Application/JSApplicationControl.cpp @@ -0,0 +1,299 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 <cassert> +#include <memory> +#include <CommonsJavaScript/Converter.h> +#include <CommonsJavaScript/JSDOMExceptionFactory.h> +#include <CommonsJavaScript/PrivateObject.h> +#include <CommonsJavaScript/JSUtils.h> +#include <CommonsJavaScript/ScopedJSStringRef.h> +#include <SecurityExceptions.h> +#include <ArgumentValidator.h> +#include <Export.h> + +//#include <Commons/Exception.h> +#include <JSWebAPIErrorFactory.h> + +#include "plugin_config.h" + +#include "ApplicationConverter.h" +#include "ApplicationUtil.h" +#include "JSApplicationControl.h" + +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace DeviceAPI::Common; + +namespace DeviceAPI { +namespace Application { + +JSClassRef JSApplicationControl::m_jsClassRef = NULL; + +JSClassDefinition JSApplicationControl::m_classInfo = { + 0, + kJSClassAttributeNone, + TIZEN_INTERFACE_APPLICATION_CONTROL, + 0, + m_property, + NULL, + initialize, + finalize, + NULL, //HasProperty, + NULL, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, + NULL, //ConvertToType +}; + +JSStaticValue JSApplicationControl::m_property[] = { + { TIZEN_APPLICATION_CONTROL_OPERATION, getProperty, setProperty, kJSPropertyAttributeNone }, + { TIZEN_APPLICATION_CONTROL_URI, getProperty, setProperty, kJSPropertyAttributeNone }, + { TIZEN_APPLICATION_CONTROL_MIME, getProperty, setProperty, kJSPropertyAttributeNone }, + { TIZEN_APPLICATION_CONTROL_CATEGORY, getProperty, setProperty, kJSPropertyAttributeNone }, + { TIZEN_APPLICATION_CONTROL_DATA, getProperty, setProperty, kJSPropertyAttributeNone }, + { 0, 0, 0, 0 } +}; + +const JSClassDefinition* JSApplicationControl::getClassInfo() +{ + return &m_classInfo; +} + +const JSClassRef DLL_EXPORT JSApplicationControl::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + + return m_jsClassRef; +} + +JSObjectRef JSApplicationControl::createJSObject(JSContextRef context, + const ApplicationControlPtr &appsvc, + JSValueRef jsValueData) +{ + JSApplicationControlPriv *priv = new JSApplicationControlPriv(context, appsvc); + if (!priv) { + LoggerE("Failed to alloc memory"); + return NULL; + } + + JSObjectRef jsObjectRef = JSObjectMake(context, getClassRef(), static_cast<void*>(priv)); + if (NULL == jsObjectRef) + { + LoggerE("object creation error"); + return NULL; + } + + const ScopedJSStringRef jsStrData(JSStringCreateWithUTF8CString(TIZEN_APPLICATION_CONTROL_DATA_INTERNAL)); + + JSObjectSetProperty(context, jsObjectRef, jsStrData.get(), jsValueData, + kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete | kJSPropertyAttributeDontEnum, NULL); + + return jsObjectRef; +} + + +ApplicationControlPtr DLL_EXPORT JSApplicationControl::getApplicationControl(JSContextRef context, JSValueRef value) +{ + if (!isObjectOfClass(context, value)) { + throw TypeMismatchException("is not a object class"); + } + + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) { + throw TypeMismatchException("Private object is null"); + } + + JSApplicationControlPriv *priv = static_cast<JSApplicationControlPriv*>(JSObjectGetPrivate(object)); + if (!priv) { + throw TypeMismatchException("Private object is null"); + } + return priv->getObject(); +} + +void JSApplicationControl::initialize(JSContextRef context,JSObjectRef object) +{ +} + +void JSApplicationControl::finalize(JSObjectRef object) +{ + JSApplicationControlPriv* priv = static_cast<JSApplicationControlPriv*>(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + delete priv; +} + +JSObjectRef DLL_EXPORT JSApplicationControl::constructor(JSContextRef context, + JSObjectRef constructor, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + ArgumentValidator validator(context, argumentCount, arguments); + + ApplicationControlPtr appsvc = ApplicationControlPtr(new ApplicationControl()); + + JSValueRef jsValueData = NULL; + + try { + appsvc->setOperation(validator.toString(0)); + appsvc->setUri(validator.toString(1, true, "")); + appsvc->setMime(validator.toString(2, true, "")); + appsvc->setCategory(validator.toString(3, true, "")); + + JSObjectRef dataArray = validator.toArrayObject(4, true); + if (dataArray) { + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + std::vector<ApplicationControlDataPtr> appControlDataArray = converter->toApplicationControlDataArray(dataArray); + appsvc->setAppControlDataArray(appControlDataArray); + jsValueData = dataArray; + } + } catch (const BasePlatformException& err) { + LoggerD("Exception occured while creating constructor : " << err.getMessage()); + } catch (const ConversionException& err) { + LoggerD("Exception occured while creating constructor : " << err.GetMessage()); + } + + if(jsValueData == NULL) + { + jsValueData = JSCreateArrayObject(context, 0, NULL); + } + + JSObjectRef obj = createJSObject(context, appsvc, jsValueData); + if(obj == NULL) + return NULL; + + JSStringRef ctorName = JSStringCreateWithUTF8CString("constructor"); + JSObjectSetProperty(context, obj, ctorName, constructor, + kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete | kJSPropertyAttributeDontEnum, NULL); + JSStringRelease(ctorName); + + return obj; +} + + +bool JSApplicationControl::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +ApplicationControlPtr JSApplicationControl::getPrivData(JSContextRef context, JSObjectRef object) +{ + JSApplicationControlPriv *priv = static_cast<JSApplicationControlPriv*>(JSObjectGetPrivate(object)); + if (!priv) { + throw TypeMismatchException("Private object is null"); + } + ApplicationControlPtr result = priv->getObject(); + if (!result) { + throw TypeMismatchException("Private object is null"); + } + return result; +} + + +JSValueRef JSApplicationControl::getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception) +{ + JSApplicationControlPriv *priv = static_cast<JSApplicationControlPriv*>(JSObjectGetPrivate(object)); + if (!priv) { + DeviceAPI::Common::TypeMismatchException err("TypeMismatchException occured"); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + + try { + ApplicationControlPtr appsvc = priv->getObject(); + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_APPLICATION_CONTROL_OPERATION)) { + return converter->toJSValueRef(appsvc->getOperation()); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_APPLICATION_CONTROL_URI)) { + std::string uri = appsvc->getUri(); + if (uri.empty()) { + return JSValueMakeNull(context); + } else { + return converter->toJSValueRef(uri); + } + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_APPLICATION_CONTROL_MIME)) { + std::string mime = appsvc->getMime(); + if (mime.empty()) { + return JSValueMakeNull(context); + } else { + return converter->toJSValueRef(mime); + } + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_APPLICATION_CONTROL_CATEGORY)) { + std::string category = appsvc->getCategory(); + if (category.empty()) { + return JSValueMakeNull(context); + } else { + return converter->toJSValueRef(category); + } + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_APPLICATION_CONTROL_DATA)) { + const ScopedJSStringRef jsStrData(JSStringCreateWithUTF8CString(TIZEN_APPLICATION_CONTROL_DATA_INTERNAL)); + return JSObjectGetProperty(context, object, jsStrData.get(), NULL); + } + + } catch (...) { + LoggerE("Exception occured while get property"); + return JSValueMakeUndefined(context); + } + + /* do not return undefined object to find method */ + return NULL; +} + +bool JSApplicationControl::setProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + try { + ApplicationControlPtr privateData = getPrivData(context, object); + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_APPLICATION_CONTROL_OPERATION)) { + privateData->setOperation(converter->toString(value)); + return true; + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_APPLICATION_CONTROL_URI)) { + privateData->setUri(converter->toString(value)); + return true; + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_APPLICATION_CONTROL_MIME)) { + privateData->setMime(converter->toString(value)); + return true; + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_APPLICATION_CONTROL_CATEGORY)) { + privateData->setCategory(converter->toString(value)); + return true; + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_APPLICATION_CONTROL_DATA)) { + if(!JSIsArrayValue(context, value)) + return true; + + const ScopedJSStringRef jsStrData(JSStringCreateWithUTF8CString(TIZEN_APPLICATION_CONTROL_DATA_INTERNAL)); + JSObjectSetProperty(context, object, jsStrData.get(), value, + kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete | kJSPropertyAttributeDontEnum, NULL); + + return true; + } + + } catch (...) { + LoggerE("Exception occured while set property"); + } + + return false; +} + +} +} diff --git a/wearable_src/Application/JSApplicationControl.h b/wearable_src/Application/JSApplicationControl.h new file mode 100755 index 0000000..51ffc17 --- /dev/null +++ b/wearable_src/Application/JSApplicationControl.h @@ -0,0 +1,123 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_TIZEN_JS_APPLICATION_CONTROL_H_ +#define TIZENAPIS_TIZEN_JS_APPLICATION_CONTROL_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/PrivateObject.h> +#include "ApplicationControl.h" +#include "JSApplicationControlData.h" + +namespace DeviceAPI { +namespace Application { + +#define TIZEN_INTERFACE_APPLICATION_CONTROL "ApplicationControl" + +#define TIZEN_APPLICATION_CONTROL_OPERATION "operation" +#define TIZEN_APPLICATION_CONTROL_URI "uri" +#define TIZEN_APPLICATION_CONTROL_MIME "mime" +#define TIZEN_APPLICATION_CONTROL_CATEGORY "category" +#define TIZEN_APPLICATION_CONTROL_DATA "data" +#define TIZEN_APPLICATION_CONTROL_DATA_INTERNAL "__tizen_data" + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT<ApplicationControlPtr>::Type JSApplicationControlPriv; + +class JSApplicationControl { +public: + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + + /** + * create an JSObject for callback function(onAnswerReceived). + */ + static JSObjectRef createJSObject(JSContextRef context, + const ApplicationControlPtr &appsvc, + JSValueRef jsValueData); + + /** + * The Constructor of ApplicationControl + */ + static JSObjectRef constructor(JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + static ApplicationControlPtr getApplicationControl(JSContextRef context, JSValueRef value); + /** + * return private data + */ + //static ApplicationControlPtr getPrivateData(JSObjectRef object); + + +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); + + static ApplicationControlPtr getPrivData(JSContextRef context, JSObjectRef object); + + /** + * The callback invoked when getting a property's value. + */ + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + /** + * The callback invoked when setting a property's value. + */ + + static bool setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + 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_property[]; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + + static JSClassRef m_jsClassRef; + +}; + +} // +} //TizenApis + +#endif diff --git a/wearable_src/Application/JSApplicationControlData.cpp b/wearable_src/Application/JSApplicationControlData.cpp new file mode 100644 index 0000000..f85b69b --- /dev/null +++ b/wearable_src/Application/JSApplicationControlData.cpp @@ -0,0 +1,249 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 <dpl/shared_ptr.h> +#include <CommonsJavaScript/Converter.h> +#include <CommonsJavaScript/JSDOMExceptionFactory.h> +#include <CommonsJavaScript/ScopedJSStringRef.h> + +#include <ArgumentValidator.h> +#include <JSWebAPIErrorFactory.h> +#include <JSUtil.h> +#include <Export.h> +#include "JSApplicationControlData.h" +#include "ApplicationConverter.h" +#include "ApplicationUtil.h" + +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace DeviceAPI::Common; + +namespace DeviceAPI { +namespace Application { + +JSClassRef JSApplicationControlData::m_classRef = NULL; + +JSClassDefinition JSApplicationControlData::m_classInfo = +{ + 0, + kJSClassAttributeNone, + TIZEN_INTERFACE_APPLICATION_CONTROL_DATA, + NULL, + m_property, + m_functions, + initialize, + finalize, + NULL, //hasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //getPropertyNames, + NULL, + NULL, + NULL, + NULL, //ConvertToType, +}; + +JSStaticValue JSApplicationControlData::m_property[] = { + { TIZEN_APPLICATION_CONTROL_DATA_KEY, getProperty, setProperty, kJSPropertyAttributeNone }, + { TIZEN_APPLICATION_CONTROL_DATA_VALUE, getProperty, setProperty, kJSPropertyAttributeNone }, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSApplicationControlData::m_functions[] = +{ + { 0, 0, 0 } +}; + +JSClassRef DLL_EXPORT JSApplicationControlData::getClassRef() { + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +JSObjectRef JSApplicationControlData::createJSObject(JSContextRef context, + const ApplicationControlDataPtr &appdata, + JSValueRef jsValueValue) +{ + JSApplicationControlDataPriv *priv = new JSApplicationControlDataPriv(context, appdata); + + if (!priv) { + LoggerE("Failed to alloc memory"); + return NULL; + } + + JSObjectRef jsObjectRef = JSObjectMake(context, getClassRef(), static_cast<void*>(priv)); + if (NULL == jsObjectRef) + { + LoggerE("object creation error"); + return NULL; + } + + const ScopedJSStringRef jsStrValue(JSStringCreateWithUTF8CString(TIZEN_APPLICATION_CONTROL_DATA_VALUE_INTERNAL)); + + JSObjectSetProperty(context, jsObjectRef, jsStrValue.get(), jsValueValue, kJSPropertyAttributeNone, NULL); + + return jsObjectRef; +} + +JSObjectRef DLL_EXPORT JSApplicationControlData::constructor(JSContextRef context, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) +{ + ArgumentValidator validator(context, argumentCount, arguments); + + ApplicationControlDataPtr appdata(new ApplicationControlData()); + + JSValueRef jsValueValue = NULL; + + try { + appdata->setKey(validator.toString(0)); + JSObjectRef jsObjectArray = validator.toArrayObject(1); + if (jsObjectArray) { + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + std::vector<std::string> valueArray = converter->toVectorOfStrings(jsObjectArray); + appdata->setValue(valueArray); + jsValueValue = jsObjectArray; + } + + } catch (BasePlatformException &err) { + LoggerE("Exception occured while creating constructor : " << err.getMessage()); + } catch (const ConversionException& err) { + LoggerD("Exception occured while creating constructor : " << err.GetMessage()); + } + + if(jsValueValue == NULL) + { + jsValueValue = JSCreateArrayObject(context, 0, NULL); + } + + JSObjectRef obj = createJSObject(context, appdata, jsValueValue); + if(obj == NULL) + return NULL; + + JSStringRef ctorName = JSStringCreateWithUTF8CString("constructor"); + JSObjectSetProperty(context, obj, ctorName, constructor, + kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete | kJSPropertyAttributeDontEnum, NULL); + JSStringRelease(ctorName); + + return obj; +} + +void JSApplicationControlData::initialize(JSContextRef context, JSObjectRef object) +{ +} + +void JSApplicationControlData::finalize(JSObjectRef object) +{ + JSApplicationControlDataPriv* priv = static_cast<JSApplicationControlDataPriv*>(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + delete priv; +} + +bool JSApplicationControlData::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +ApplicationControlDataPtr JSApplicationControlData::getPrivData(JSObjectRef object) +{ + JSApplicationControlDataPriv *priv = static_cast<JSApplicationControlDataPriv*>(JSObjectGetPrivate(object)); + if (!priv) { + throw TypeMismatchException("Private object is null"); + } + ApplicationControlDataPtr result = priv->getObject(); + if (!result) { + throw TypeMismatchException("Private object is null"); + } + return result; +} + +ApplicationControlDataPtr JSApplicationControlData::getApplicationControlData(JSContextRef context, JSValueRef value) +{ + if (!isObjectOfClass(context, value)) { + throw TypeMismatchException("is not a object class"); + } + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) { + throw TypeMismatchException("Fail to get object"); + } + JSApplicationControlDataPriv *priv = static_cast<JSApplicationControlDataPriv*>(JSObjectGetPrivate(object)); + if (!priv) { + throw TypeMismatchException("Private object is null"); + } + return priv->getObject(); +} + + +JSValueRef JSApplicationControlData::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + try { + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + ApplicationControlDataPtr privateData = getPrivData(object); + + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_APPLICATION_CONTROL_DATA_KEY)) { + return converter.toJSValueRef(privateData->getKey()); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_APPLICATION_CONTROL_DATA_VALUE)) { + const ScopedJSStringRef jsStrData(JSStringCreateWithUTF8CString(TIZEN_APPLICATION_CONTROL_DATA_VALUE_INTERNAL)); + return JSObjectGetProperty(context, object, jsStrData.get(), NULL); + } + } catch (...) { + LoggerE("Exception occured while get property"); + return JSValueMakeUndefined(context); + } + + /* do not return undefined object to find method */ + return NULL; +} + + +bool JSApplicationControlData::setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + const JSValueRef arguments[1] = {value}; + ArgumentValidator validator(context, 1, arguments); + + try { + ApplicationControlDataPtr privateData = getPrivData(object); + + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_APPLICATION_CONTROL_DATA_KEY)) { + privateData->setKey(JSUtil::JSValueToString(context, value)); + return true; + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_APPLICATION_CONTROL_DATA_VALUE)) { + if(!JSIsArrayValue(context, value)) + return true; + + const ScopedJSStringRef jsStrData(JSStringCreateWithUTF8CString(TIZEN_APPLICATION_CONTROL_DATA_VALUE_INTERNAL)); + JSObjectSetProperty(context, object, jsStrData.get(), value, + kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete | kJSPropertyAttributeDontEnum, NULL); + + return true; + } + } catch (const BasePlatformException &err) { + LoggerE("Setting property is failed." << err.getMessage()); + } + + return false; +} + +} +} diff --git a/wearable_src/Application/JSApplicationControlData.h b/wearable_src/Application/JSApplicationControlData.h new file mode 100755 index 0000000..9f64389 --- /dev/null +++ b/wearable_src/Application/JSApplicationControlData.h @@ -0,0 +1,107 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_TIZEN_JS_APPLICATION_CONTROL_DATA_H_ +#define TIZENAPIS_TIZEN_JS_APPLICATION_CONTROL_DATA_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <dpl/shared_ptr.h> +#include <CommonsJavaScript/PrivateObject.h> +#include <Commons/IEvent.h> +#include "ApplicationControlData.h" + +namespace DeviceAPI { +namespace Application { + +#define TIZEN_INTERFACE_APPLICATION_CONTROL_DATA "ApplicationControlData" + +#define TIZEN_APPLICATION_CONTROL_DATA_KEY "key" +#define TIZEN_APPLICATION_CONTROL_DATA_VALUE "value" +#define TIZEN_APPLICATION_CONTROL_DATA_VALUE_INTERNAL "__tizen_value" + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject<ApplicationControlDataPtr, WrtDeviceApis::CommonsJavaScript::NoOwnership> JSApplicationControlDataPriv; + +class JSApplicationControlData { +public: + /* + * This initializes this JS class in the JS Engine. + */ + static JSClassRef getClassRef(); + + static JSObjectRef createJSObject(JSContextRef context, + const ApplicationControlDataPtr &appdata, + JSValueRef jsValueValue); + + static JSObjectRef constructor(JSContextRef ctx, + JSObjectRef constructor, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + static ApplicationControlDataPtr + getApplicationControlData(JSContextRef context, JSValueRef value); + +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 property. + */ + static JSStaticFunction m_functions[]; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; + + static JSClassRef m_classRef; + + static ApplicationControlDataPtr getPrivData(JSObjectRef object); + + 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/wearable_src/Application/JSApplicationEventCallbackManager.cpp b/wearable_src/Application/JSApplicationEventCallbackManager.cpp new file mode 100644 index 0000000..1c47280 --- /dev/null +++ b/wearable_src/Application/JSApplicationEventCallbackManager.cpp @@ -0,0 +1,241 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 "JSApplicationEventCallbackManager.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Application { + +JSApplicationEventCallbackManagerPtr JSApplicationEventCallbackManager::createObject(JSContextRef context) +{ + return JSApplicationEventCallbackManagerPtr( new JSApplicationEventCallbackManager(context) ); +} + +JSApplicationEventCallbackManager::JSApplicationEventCallbackManager(JSContextRef context, + JSObjectRef onInstalled, + JSObjectRef onUpdated, + JSObjectRef onUninstalled, + JSObjectRef onError ) : + m_onInstalled(NULL), + m_onUpdated(NULL), + m_onUninstalled(NULL), + m_onError(NULL), + m_context(context), + m_object(NULL) +{ + setOnInstalled(onInstalled); + setOnUpdated(onUpdated); + setOnUninstalled(onUninstalled); + setOnError(onError); +} + +JSApplicationEventCallbackManager::~JSApplicationEventCallbackManager() +{ + if(m_onInstalled) + { + JSValueUnprotect(m_context, m_onInstalled); + } + + if(m_onUpdated) + { + JSValueUnprotect(m_context, m_onUpdated); + } + + if(m_onUninstalled) + { + JSValueUnprotect(m_context, m_onUninstalled); + } + + if(m_onError) + { + JSValueUnprotect(m_context, m_onError); + } +} + +void JSApplicationEventCallbackManager::setOnInstalled( JSValueRef onInstalled ) +{ + if (onInstalled) + { + if (m_onInstalled != NULL) + { + JSValueUnprotect(m_context, m_onInstalled); + } + + m_onInstalled = JSValueToObject( m_context, onInstalled, NULL ); + + if (m_onInstalled != NULL) + { + JSValueProtect(m_context, m_onInstalled); + } + } +} + +JSValueRef JSApplicationEventCallbackManager::getOnInstalled() const +{ + return m_onInstalled; +} + +void JSApplicationEventCallbackManager::setOnUpdated( JSValueRef onUpdated ) +{ + if (onUpdated) + { + if (m_onUpdated != NULL) + { + JSValueUnprotect(m_context, m_onUpdated); + } + + m_onUpdated = JSValueToObject( m_context, onUpdated, NULL ); + + if (m_onUpdated != NULL) + { + JSValueProtect(m_context, m_onUpdated); + } + } +} + +JSValueRef JSApplicationEventCallbackManager::getOnUpdated() const +{ + return m_onUpdated; +} + +void JSApplicationEventCallbackManager::setOnUninstalled( JSValueRef onUninstalled ) +{ + if (onUninstalled) + { + if (m_onUninstalled != NULL) + { + JSValueUnprotect(m_context, m_onUninstalled); + } + + m_onUninstalled = JSValueToObject( m_context, onUninstalled, NULL ); + + if (m_onUninstalled != NULL) + { + JSValueProtect(m_context, m_onUninstalled); + } + } +} + +JSValueRef JSApplicationEventCallbackManager::getOnUninstalled() const +{ + return m_onUninstalled; +} + +void JSApplicationEventCallbackManager::setOnError( JSValueRef onError ) +{ + if (onError) + { + if (m_onError != NULL) + { + JSValueUnprotect(m_context, m_onError); + } + + m_onError = JSValueToObject( m_context, onError, NULL ); + + if (m_onError != NULL) + { + JSValueProtect(m_context, m_onError); + } + } +} + +JSValueRef JSApplicationEventCallbackManager::getOnError() const +{ + return m_onError; +} + +void JSApplicationEventCallbackManager::setContext( JSContextRef context ) +{ + m_context = context; +} + +void JSApplicationEventCallbackManager::setObject( JSObjectRef object ) +{ + m_object = object; +} + +JSObjectRef JSApplicationEventCallbackManager::getObject() const +{ + return m_object; +} + +void JSApplicationEventCallbackManager::callOnInstalled( JSValueRef appInfo ) +{ + if ( m_onInstalled == NULL ) + { + return; + } + JSValueRef objParam[1] = { appInfo }; + makeCallback( m_context, NULL, m_onInstalled, "oninstalled", objParam, 1 ); +} + +void JSApplicationEventCallbackManager::callOnUpdated( JSValueRef appInfo ) +{ + if ( m_onUpdated == NULL ) + { + return; + } + JSValueRef objParam[1] = { appInfo }; + makeCallback( m_context, NULL, m_onUpdated, "onupdated", objParam, 1 ); +} + +void JSApplicationEventCallbackManager::callOnUninstalled( JSValueRef appId ) +{ + if ( m_onUninstalled == NULL ) + { + return; + } + JSValueRef objParam[1] = { appId }; + makeCallback( m_context, NULL, m_onUninstalled, "onuninstalled", objParam, 1 ); +} + +void JSApplicationEventCallbackManager::callOnError( JSValueRef error ) +{ + if ( m_onError == NULL ) + { + return; + } + JSValueRef objParam[1] = { error }; + makeCallback( m_context, NULL, m_onError, "onerror", objParam, 1 ); +} + +void JSApplicationEventCallbackManager::makeCallback(JSContextRef context, JSObjectRef object, JSObjectRef callback, const char *szName, JSValueRef argv[], unsigned argc) +{ + + if (callback == NULL) + { + LoggerE("callback cannot be NULL"); + return; + } + + if (JSObjectIsFunction(context, callback)) + { + if (argc == 0) + { + JSObjectCallAsFunction(context, callback, object, 0, NULL, NULL); + } + else + { + JSObjectCallAsFunction(context, callback, object, argc, argv, NULL); + } + return; + } +} + +} // Application +} // DeviceAPI diff --git a/wearable_src/Application/JSApplicationEventCallbackManager.h b/wearable_src/Application/JSApplicationEventCallbackManager.h new file mode 100755 index 0000000..823608a --- /dev/null +++ b/wearable_src/Application/JSApplicationEventCallbackManager.h @@ -0,0 +1,84 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 _TIZEN_APPLICATION_JS_APPLICATION_EVENT_CALLBACK_MANAGER_H_ +#define _TIZEN_APPLICATION_JS_APPLICATION_EVENT_CALLBACK_MANAGER_H_ + +#include <dpl/shared_ptr.h> +#include <Commons/IEvent.h> +#include <JavaScriptCore/JavaScript.h> + +namespace DeviceAPI { +namespace Application { + +class JSApplicationEventCallbackManager; +typedef DPL::SharedPtr<JSApplicationEventCallbackManager> JSApplicationEventCallbackManagerPtr; + +class JSApplicationEventCallbackManager : public WrtDeviceApis::Commons::IEventPrivateData +{ +private: + JSApplicationEventCallbackManager() {} + JSApplicationEventCallbackManager( JSContextRef context, + JSObjectRef onInstalled = NULL, + JSObjectRef onUpdated = NULL, + JSObjectRef onUninstalled = NULL, + JSObjectRef onError = NULL ); + +public: + static JSApplicationEventCallbackManagerPtr createObject(JSContextRef context); + + virtual ~JSApplicationEventCallbackManager(); + + void setContext( JSContextRef context ); + JSContextRef getContext() const { return m_context; } + + void setOnInstalled( JSValueRef onInstalled ); + JSValueRef getOnInstalled() const; + void setOnUpdated( JSValueRef onUpdated ); + JSValueRef getOnUpdated() const; + void setOnUninstalled( JSValueRef onUninstalled ); + JSValueRef getOnUninstalled() const; + void setOnError( JSValueRef onError ); + JSValueRef getOnError() const; + void setObject( JSObjectRef object ); + JSObjectRef getObject() const; + + void callOnInstalled( JSValueRef contacts ); + void callOnUpdated( JSValueRef contacts ); + void callOnUninstalled( JSValueRef contactIds ); + void callOnError( JSValueRef error ); + +private: + void makeCallback(JSContextRef context, + JSObjectRef object, + JSObjectRef callback, + const char *szName, + JSValueRef argv[], + unsigned argc); + + JSObjectRef m_onInstalled; + JSObjectRef m_onUpdated; + JSObjectRef m_onUninstalled; + JSObjectRef m_onError; + JSContextRef m_context; + JSObjectRef m_object; +}; + +} // Application +} // DeviceAPI + +#endif // _TIZEN_APPLICATION_JS_APPLICATION_EVENT_CALLBACK_MANAGER_H_ diff --git a/wearable_src/Application/JSApplicationInformation.cpp b/wearable_src/Application/JSApplicationInformation.cpp new file mode 100755 index 0000000..cc92877 --- /dev/null +++ b/wearable_src/Application/JSApplicationInformation.cpp @@ -0,0 +1,263 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 <cassert> +#include <memory> +#include <CommonsJavaScript/JSUtils.h> +#include <CommonsJavaScript/Converter.h> +#include <Commons/Exception.h> + +#include <SecurityExceptions.h> +#include <JSWebAPIErrorFactory.h> + +#include "JSApplicationInformation.h" +#include "plugin_config.h" +#include "AppManagerWrapper.h" +#include <Export.h> +#include <Logger.h> + +namespace DeviceAPI { +namespace Application { + +using namespace WrtDeviceApis; +using namespace DeviceAPI::Common; + +using namespace WrtDeviceApis::Commons; + +JSClassRef JSApplicationInformation::m_classRef = NULL; + +JSClassDefinition JSApplicationInformation::m_classInfo = { + 0, + kJSClassAttributeNone, + TIZEN_INTERFACE_APPLICATION_INFORMATION, + 0, + m_property, + 0, + initialize, + finalize, + NULL, //HasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, + NULL, //ConvertToType +}; + +JSStaticValue JSApplicationInformation::m_property[] = { + { TIZEN_APPLICATION_INFORMATION_ID, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_APPLICATION_INFORMATION_NAME, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_APPLICATION_INFORMATION_ICONPATH, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_APPLICATION_INFORMATION_VERSION, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_APPLICATION_INFORMATION_SHOW, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_APPLICATION_INFORMATION_CATEGORIES, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_APPLICATION_INFORMATION_INSTALL_DATE, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_APPLICATION_INFORMATION_INSTALL_SIZE, getPropertySize, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_APPLICATION_INFORMATION_PACKAGE_ID, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSClassRef DLL_EXPORT JSApplicationInformation::getClassRef() { + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +JSValueRef JSApplicationInformation::createJSObject(JSContextRef context, + const std::string &name, + const std::string &appId, + const std::string &iconPath, + const std::string &version, + const bool &show, + const std::vector<std::string> &categories, + const time_t &installDate, + const long &installSize, + const std::string &pkgId) +{ + ApplicationInformationPtr privateData = ApplicationInformationPtr(new ApplicationInformation()); + privateData->setName(name); + privateData->setAppId(appId); + privateData->setIconPath(iconPath); + privateData->setVersion(version); + privateData->setShow(show); + privateData->setCategories(categories); + privateData->setInstallDate(installDate); + privateData->setInstallSize(installSize); + privateData->setPackageId(pkgId); + + JSApplicationInformationPriv *priv = new JSApplicationInformationPriv(context, privateData); + + JSObjectRef jsValueRef = JSObjectMake(context, getClassRef(), static_cast<void*>(priv)); + if (NULL == jsValueRef) { + LoggerE("object creation error"); + return JSValueMakeUndefined(context); + } + + return jsValueRef; +} + +void JSApplicationInformation::initialize(JSContextRef context, JSObjectRef object) +{ +} + +void JSApplicationInformation::finalize(JSObjectRef object) +{ + JSApplicationInformationPriv* priv = static_cast<JSApplicationInformationPriv*>(JSObjectGetPrivate(object)); + if(priv == NULL) + return; + + ApplicationInformationPtr privateData = priv->getObject(); + + JSValueRef installDateJSValue = static_cast<JSValueRef>(privateData->getInstallDateJSValue()); + if(installDateJSValue != NULL) + JSValueUnprotect(priv->getContext(), installDateJSValue); + + JSValueRef categoriesJSValue = static_cast<JSValueRef>(privateData->getCategoriesJSValue()); + if(categoriesJSValue != NULL) + JSValueUnprotect(priv->getContext(), categoriesJSValue); + + JSObjectSetPrivate(object, NULL); + delete priv; +} + +bool JSApplicationInformation::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +ApplicationInformationPtr JSApplicationInformation::getPrivData(JSContextRef context, JSObjectRef object) +{ + JSApplicationInformationPriv *priv = static_cast<JSApplicationInformationPriv*>(JSObjectGetPrivate(object)); + if (!priv) { + throw TypeMismatchException("Private object is null"); + } + ApplicationInformationPtr result = priv->getObject(); + if (!result) { + throw TypeMismatchException("Private object is null"); + } + return result; +} + +ApplicationInformationPtr JSApplicationInformation::getApplicationInformation(JSContextRef context, JSValueRef value) +{ + if (!isObjectOfClass(context, value)) { + throw TypeMismatchException("is not a object class"); + } + + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) { + throw TypeMismatchException("Fail to get object"); + } + + JSApplicationInformationPriv *priv = static_cast<JSApplicationInformationPriv*>(JSObjectGetPrivate(object)); + if (!priv) { + throw TypeMismatchException("Private object is null"); + } + + return priv->getObject(); +} + +JSValueRef JSApplicationInformation::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + try { + CommonsJavaScript::Converter converter(context); + ApplicationInformationPtr privateData = getPrivData(context, object); + JSContextRef gContext = static_cast<JSApplicationInformationPriv*>(JSObjectGetPrivate(object))->getContext(); + + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_APPLICATION_INFORMATION_ID)) { + return converter.toJSValueRef(privateData->getAppId()); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_APPLICATION_INFORMATION_NAME)) { + return converter.toJSValueRef(privateData->getName()); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_APPLICATION_INFORMATION_ICONPATH)) { + return converter.toJSValueRef(privateData->getIconPath()); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_APPLICATION_INFORMATION_SHOW)) { + return converter.toJSValueRef(privateData->getShow()); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_APPLICATION_INFORMATION_CATEGORIES)) { + JSValueRef categoriesJSValue = static_cast<JSValueRef>(privateData->getCategoriesJSValue()); + if(categoriesJSValue == NULL) { + categoriesJSValue = converter.toJSValueRef(privateData->getCategories()); + JSValueProtect(gContext, categoriesJSValue); + privateData->setCategoriesJSValue(static_cast<const void *>(categoriesJSValue)); + } + return categoriesJSValue; + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_APPLICATION_INFORMATION_PACKAGE_ID)) { + return converter.toJSValueRef(privateData->getPackageId()); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_APPLICATION_INFORMATION_VERSION)) { + return converter.toJSValueRef(privateData->getVersion()); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_APPLICATION_INFORMATION_INSTALL_DATE)) { + JSValueRef installDateJSValue = static_cast<JSValueRef>(privateData->getInstallDateJSValue()); + if(installDateJSValue == NULL) { + installDateJSValue = converter.toJSValueRef(privateData->getInstallDate()); + JSValueProtect(gContext, installDateJSValue); + privateData->setInstallDateJSValue(static_cast<const void *>(installDateJSValue)); + } + return installDateJSValue; + } + } catch (...) { + LoggerE("Exception occured while get property"); + return JSValueMakeUndefined(context); + } + + /* do not return undefined object to find method */ + return NULL; +} + +JSValueRef JSApplicationInformation::getPropertySize(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LoggerD("getPropertySize called"); + +// TIZEN_CHECK_ACCESS(context, exception, priv, APPLICATION_FUNCTION_API_SIZE); + AceSecurityStatus status = APPLICATION_CHECK_ACCESS(TIZEN_APPLICATION_INFORMATION_INSTALL_SIZE); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + ApplicationInformationPtr privateData = getPrivData(context, object); + if (!privateData) { + LoggerE("Private object is wrong"); + return JSValueMakeUndefined(context); + } + + try { + CommonsJavaScript::Converter converter(context); + + if (!privateData->isInitialized()) { + AppManagerWrapperSingleton::Instance().initializeAppInfo(privateData); + } + + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_APPLICATION_INFORMATION_INSTALL_SIZE)) { + return converter.toJSValueRefLong(privateData->getInstallSize()); + } + + } catch (...) { + LoggerE("Exception occured while get property"); + return JSValueMakeUndefined(context); + } + + /* do not return undefined object to find method */ + return NULL; +} + +} +} diff --git a/wearable_src/Application/JSApplicationInformation.h b/wearable_src/Application/JSApplicationInformation.h new file mode 100755 index 0000000..fb6f960 --- /dev/null +++ b/wearable_src/Application/JSApplicationInformation.h @@ -0,0 +1,111 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_TIZEN_JS_APPLICATION_INFORMATION_H_ +#define TIZENAPIS_TIZEN_JS_APPLICATION_INFORMATION_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/PrivateObject.h> +#include <dpl/shared_ptr.h> +#include "ApplicationInformation.h" + +namespace DeviceAPI { +namespace Application { + +#define TIZEN_INTERFACE_APPLICATION_INFORMATION "ApplicationInformation" + +#define TIZEN_APPLICATION_INFORMATION_ID "id" +#define TIZEN_APPLICATION_INFORMATION_NAME "name" +#define TIZEN_APPLICATION_INFORMATION_ICONPATH "iconPath" +#define TIZEN_APPLICATION_INFORMATION_VERSION "version" +#define TIZEN_APPLICATION_INFORMATION_SHOW "show" +#define TIZEN_APPLICATION_INFORMATION_CATEGORIES "categories" +#define TIZEN_APPLICATION_INFORMATION_INSTALL_DATE "installDate" +#define TIZEN_APPLICATION_INFORMATION_INSTALL_SIZE "size" +#define TIZEN_APPLICATION_INFORMATION_PACKAGE_ID "packageId" + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject<ApplicationInformationPtr, WrtDeviceApis::CommonsJavaScript::NoOwnership> JSApplicationInformationPriv; + +class JSApplicationInformation { +public: + /* + * This initializes this JS class in the JS Engine. + */ + static JSClassRef getClassRef(); + + static JSValueRef createJSObject(JSContextRef context, + const std::string &name, + const std::string &package, + const std::string &iconPath, + const std::string &version, + const bool &show, + const std::vector<std::string> &categories, + const time_t &installDate, + const long &installSize, + const std::string &pkgId); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + static ApplicationInformationPtr + getApplicationInformation(JSContextRef context, JSValueRef value); + +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 property. + */ + static JSStaticFunction m_functions[]; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; + + static JSClassRef m_classRef; + + static ApplicationInformationPtr getPrivData(JSContextRef context, JSObjectRef object); + + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getPropertySize(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); +}; + +} +} +#endif diff --git a/wearable_src/Application/JSApplicationManager.cpp b/wearable_src/Application/JSApplicationManager.cpp new file mode 100644 index 0000000..943c343 --- /dev/null +++ b/wearable_src/Application/JSApplicationManager.cpp @@ -0,0 +1,939 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 <memory> + +#include <CommonsJavaScript/Converter.h> + +//#include <CommonsJavaScript/Validator.h> +#include <CommonsJavaScript/JSUtils.h> + +#include <CommonsJavaScript/JSCallbackManager.h> +#include <CommonsJavaScript/Utils.h> +#include <CommonsJavaScript/ScopedJSStringRef.h> + +#include <ArgumentValidator.h> +#include <JSUtil.h> + +#include <SecurityExceptions.h> +//#include <Commons/Exception.h> +#include <JSWebAPIErrorFactory.h> + +#include "ApplicationFactory.h" +#include "plugin_config.h" +#include "ApplicationController.h" +#include "JSApplicationManager.h" +#include "ApplicationConverter.h" +#include "ApplicationUtil.h" +#include "JSApplicationControl.h" +#include "ApplicationAsyncCallbackManager.h" +#include "ApplicationListenerManager.h" +#include "ApplicationInformationEventPrivateData.h" +#include "JSApplicationEventCallbackManager.h" +#include "JSApplication.h" +#include "ApplicationManager.h" + +#include <TimeTracer.h> +#include <Export.h> +#include <Logger.h> + +#include <plugins-ipc-message/ipc_message_support.h> + +namespace DeviceAPI { +namespace Application { + +using namespace DeviceAPI::Common; + +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +JSClassRef JSApplicationManager::m_jsClassRef = NULL; + +JSClassDefinition JSApplicationManager::m_classInfo = { + 0, + kJSClassAttributeNone, + TIZEN_INTERFACE_APPLICATION_MANAGER, + NULL, + NULL, + m_function, + initialize, + finalize, + NULL, //hasProperty, + NULL, //getProperty, + NULL, //setProperty, + NULL, //deleteProperty, + NULL, //getPropertyNames, + NULL, + NULL, + NULL, + NULL +}; + +JSStaticFunction JSApplicationManager::m_function[] = { + { APPLICATION_FUNCTION_API_GET_CURRENT_APP, JSApplicationManager::getCurrentApplication, kJSPropertyAttributeNone }, + { APPLICATION_FUNCTION_API_LAUNCH, JSApplicationManager::launch, kJSPropertyAttributeNone }, + { APPLICATION_FUNCTION_API_KILL, JSApplicationManager::kill, kJSPropertyAttributeNone }, + { APPLICATION_FUNCTION_API_SET_USER_AGENT, JSApplicationManager::setUserAgent, kJSPropertyAttributeNone }, + { APPLICATION_FUNCTION_API_GET_APPS_INFO, JSApplicationManager::getAppsInfo, kJSPropertyAttributeNone }, + { APPLICATION_FUNCTION_API_GET_APPS_CONTEXT, JSApplicationManager::getAppsContext, kJSPropertyAttributeNone }, + { APPLICATION_FUNCTION_API_GET_APP_INFO, JSApplicationManager::getAppInfo, kJSPropertyAttributeNone }, + { APPLICATION_FUNCTION_API_GET_APP_CONTEXT, JSApplicationManager::getAppContext, kJSPropertyAttributeNone }, + { APPLICATION_FUNCTION_API_ADD_APP_INFO_EVENT_LISTENER, JSApplicationManager::addAppInfoEventListener, kJSPropertyAttributeNone }, + { APPLICATION_FUNCTION_API_REMOVE_APP_INFO_EVENT_LISTENER, JSApplicationManager::removeAppInfoEventListener, kJSPropertyAttributeNone }, + { APPLICATION_FUNCTION_API_LAUNCH_APP_CONTROL, JSApplicationManager::launchAppControl, kJSPropertyAttributeNone }, + { APPLICATION_FUNCTION_API_FIND_APP_CONTROL, JSApplicationManager::findAppControl, kJSPropertyAttributeNone }, + { APPLICATION_FUNCTION_API_GET_APP_CERTS, JSApplicationManager::getAppCerts, kJSPropertyAttributeNone }, + { APPLICATION_FUNCTION_API_GET_APP_SHARED_URI, JSApplicationManager::getAppSharedURI, kJSPropertyAttributeNone }, + { APPLICATION_FUNCTION_API_GET_APP_META_DATA, JSApplicationManager::getAppMetaData, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +const JSClassRef DLL_EXPORT JSApplicationManager::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + + return m_jsClassRef; +} + +const JSClassDefinition* JSApplicationManager::getClassInfo() +{ + return &m_classInfo; +} + +void JSApplicationManager::initialize(JSContextRef context, JSObjectRef object) +{ + ApplicationController* priv = static_cast<ApplicationController*>(JSObjectGetPrivate(object)); + + if (!priv) { + IApplicationManagerPtr applications(ApplicationFactory::getInstance().createApplication()); + priv = new ApplicationController(context, applications); + + if (!JSObjectSetPrivate(object, static_cast<void*>(priv))) { + delete priv; + } + } else { + LoggerD("private date is already exist"); + } +} + +void JSApplicationManager::finalize(JSObjectRef object) +{ + ApplicationController* priv = static_cast<ApplicationController*> (JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + delete priv; +} + +JSValueRef JSApplicationManager::getCurrentApplication(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + + try { + ApplicationController *controller = static_cast<ApplicationController*>(JSObjectGetPrivate(thisObject)); + if (!controller) { + throw TypeMismatchException("No private object."); + } + JSContextRef gContext = controller->getContext(); + + ApplicationPtr result = ApplicationManager::getCurrentApplication(); + + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSApplication::makeObject(gContext, result); + + } catch (...) { + DeviceAPI::Common::UnknownException err("Unknown Error in ApplicationManager.getCurrentApplication()."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } +} + + +JSValueRef JSApplicationManager::launch(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + TIME_TRACER_ITEM_BEGIN("launch(async)", 0); + + TIME_TRACER_ITEM_BEGIN("launch(ACE)", 0); + AceSecurityStatus status = APPLICATION_CHECK_ACCESS(APPLICATION_FUNCTION_API_LAUNCH); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + TIME_TRACER_ITEM_END("launch(ACE)", 0); + + try { + IApplicationManagerPtr appmgr; + JSContextRef gContext; + ApplicationController *controller; + + controller = static_cast<ApplicationController*>(JSObjectGetPrivate(thisObject)); + if (!controller) { + throw TypeMismatchException("No private object."); + } + appmgr = controller->getObject(); + gContext = controller->getContext(); + + EventApplicationLaunchPtr event(new EventApplicationLaunch()); + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(gContext); + + ArgumentValidator validator(context, argumentCount, arguments); + + // id + std::string id = validator.toString(0); + event->setAppId(id); + + // successCallback + JSObjectRef successCallback = validator.toFunction(1, true); + if (successCallback) + callbackManager->setOnSuccess(successCallback); + + // errorCallback + JSObjectRef errorCallback = validator.toFunction(2, true); + if (errorCallback) + callbackManager->setOnError(errorCallback); + + callbackManager->setObject(thisObject); + ApplicationAsyncCallbackManagerSingleton::Instance().registerCallbackManager(callbackManager, gContext); + + event->setPrivateData(DPL::StaticPointerCast<IEventPrivateData>(callbackManager)); + event->setForAsynchronousCall(controller); + + appmgr->launch(event); + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); + + } catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(context, exception, err); + } catch (...) { + DeviceAPI::Common::UnknownException err("Unknown Error in ApplicationManager.launch()."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } +} + +JSValueRef JSApplicationManager::kill(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + TIME_TRACER_ITEM_BEGIN("kill(async)", 0); + + TIME_TRACER_ITEM_BEGIN("kill(ACE)", 0); + AceSecurityStatus status = APPLICATION_CHECK_ACCESS(APPLICATION_FUNCTION_API_KILL); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + TIME_TRACER_ITEM_END("kill(ACE)", 0); + + try { + IApplicationManagerPtr appmgr; + JSContextRef gContext; + ApplicationController *controller; + + controller = static_cast<ApplicationController*>(JSObjectGetPrivate(thisObject)); + if (!controller) { + throw TypeMismatchException("No private object."); + } + appmgr = controller->getObject(); + gContext = controller->getContext(); + + EventApplicationKillPtr event(new EventApplicationKill()); + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(gContext); + ArgumentValidator validator(context, argumentCount, arguments); + + // contextId + std::string contextId = validator.toString(0); + event->setContextId(contextId); + + // successCallback + JSObjectRef successCallback = validator.toFunction(1, true); + if (successCallback) + callbackManager->setOnSuccess(successCallback); + + // errorCallback + JSObjectRef errorCallback = validator.toFunction(2, true); + if (errorCallback) + callbackManager->setOnError(errorCallback); + + callbackManager->setObject(thisObject); + ApplicationAsyncCallbackManagerSingleton::Instance().registerCallbackManager(callbackManager, gContext); + + event->setPrivateData(DPL::StaticPointerCast<IEventPrivateData>(callbackManager)); + event->setForAsynchronousCall(controller); + + appmgr->kill(event); + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); + + } catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(context, exception, err); + } catch (...) { + DeviceAPI::Common::UnknownException err("Unknown Error in ApplicationManager.kill()."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } +} + + +JSValueRef JSApplicationManager::setUserAgent(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + + try { + ArgumentValidator validator(context, argumentCount, arguments); + + // UserAgent + std::string userAgent = validator.toString(0); + + // perform + IPCMessageSupport::sendAsyncMessageToUiProcess(IPCMessageSupport::TIZEN_CHANGE_USERAGENT, userAgent.c_str(), NULL, NULL); + + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); + + } catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(context, exception, err); + } catch (...) { + DeviceAPI::Common::UnknownException err("Unknown Error in ApplicationManager.removeAppInfoEventListener()."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } +} + + +JSValueRef JSApplicationManager::launchAppControl(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + TIME_TRACER_ITEM_BEGIN("launchAppControlReply", 0); + TIME_TRACER_ITEM_BEGIN("launchAppControl(async)", 0); + TIME_TRACER_ITEM_BEGIN("launchAppControlReply(async)", 0); + + TIME_TRACER_ITEM_BEGIN("launchAppControl(ACE)", 0); + AceSecurityStatus status = APPLICATION_CHECK_ACCESS(APPLICATION_FUNCTION_API_LAUNCH_APP_CONTROL); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + TIME_TRACER_ITEM_END("launchAppControl(ACE)", 0); + + try { + IApplicationManagerPtr appmgr; + JSContextRef gContext; + ApplicationController *controller; + + controller = static_cast<ApplicationController*>(JSObjectGetPrivate(thisObject)); + if (!controller) { + throw TypeMismatchException("No private object."); + } + appmgr = controller->getObject(); + gContext = controller->getContext(); + + + EventApplicationLaunchAppControlPtr event(new EventApplicationLaunchAppControl()); + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(gContext); + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + + ArgumentValidator validator(context, argumentCount, arguments); + + // appControl + JSObjectRef appControlObj = validator.toObject(0); + ApplicationControlPtr appControl = converter->toApplicationControl(appControlObj); + if (!appControl) { + throw TypeMismatchException("ApplicationControl's private object is NULL."); + } + event->setAppControl(appControl); + + // id + std::string id = validator.toString(1, true, ""); + event->setAppId(id); + + // successCallback + JSObjectRef successCallback = validator.toFunction(2, true); + if (successCallback) + callbackManager->setOnSuccess(successCallback); + + // errorCallback + JSObjectRef errorCallback = validator.toFunction(3, true); + if (errorCallback) + callbackManager->setOnError(errorCallback); + + callbackManager->setObject(thisObject); + ApplicationAsyncCallbackManagerSingleton::Instance().registerCallbackManager(callbackManager, gContext); + + // replyCallback + JSCallbackManagerPtr callbackManagerReply; + JSObjectRef replyCallbackObj = validator.toCallbackObject(4, true, "onsuccess", "onfailure", NULL); + + if (replyCallbackObj) { + callbackManagerReply = JSCallbackManager::createObject(gContext); + + // onsuccess + JSValueRef onsuccess = JSUtil::getProperty(context, replyCallbackObj, "onsuccess", exception); + if (!JSValueIsUndefined(context, onsuccess)) { + callbackManagerReply->setOnSuccess(onsuccess); + } + + // onfailure + JSValueRef onfailure = JSUtil::getProperty(context, replyCallbackObj, "onfailure", exception); + if (!JSValueIsUndefined(context, onfailure)) { + callbackManagerReply->setOnError(onfailure); + } + + callbackManagerReply->setObject(thisObject); + ApplicationAsyncCallbackManagerSingleton::Instance().registerCallbackManager(callbackManagerReply, gContext); + + EventApplicationLaunchAppControlReplyPtr eventReply(new EventApplicationLaunchAppControlReply()); + eventReply->setPrivateData(DPL::StaticPointerCast<IEventPrivateData>(callbackManagerReply)); + eventReply->setForAsynchronousCall(controller); + + event->setEventReply(eventReply); + } + + event->setPrivateData(DPL::StaticPointerCast<IEventPrivateData>(callbackManager)); + event->setForAsynchronousCall(controller); + + appmgr->launchAppControl(event); + + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + TIME_TRACER_ITEM_END("launchAppControlReply", 0); + return JSValueMakeUndefined(context); + } catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(context, exception, err); + } catch (...) { + DeviceAPI::Common::UnknownException err("Unknown Error in ApplicationManager.launchAppControl()."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + +} + + +JSValueRef JSApplicationManager::findAppControl(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + TIME_TRACER_ITEM_BEGIN("findAppControl(async)", 0); + try { + + IApplicationManagerPtr appmgr; + JSContextRef gContext; + ApplicationController *controller; + + controller = static_cast<ApplicationController*>(JSObjectGetPrivate(thisObject)); + if (!controller) { + throw TypeMismatchException("No private object."); + } + appmgr = controller->getObject(); + gContext = controller->getContext(); + + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + EventApplicationFindAppControlPtr event(new EventApplicationFindAppControl()); + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(gContext); + + ArgumentValidator validator(context, argumentCount, arguments); + + // appControl + JSObjectRef appControlObj = validator.toObject(0); + + ApplicationControlPtr appControl = converter->toApplicationControl(appControlObj); + if (!appControl) { + throw TypeMismatchException("ApplicationControl's private object is NULL."); + } + event->setAppControl(appControl); + + // successCallback + JSObjectRef successCallbackObj = validator.toFunction(1); + if (successCallbackObj) { + callbackManager->setOnSuccess(successCallbackObj); + } + + // errorCallback + JSObjectRef errorCallback = validator.toFunction(2, true); + if (errorCallback) { + callbackManager->setOnError(errorCallback); + } + + callbackManager->setObject(thisObject); + ApplicationAsyncCallbackManagerSingleton::Instance().registerCallbackManager(callbackManager, gContext); + + event->setPrivateData(DPL::StaticPointerCast<IEventPrivateData>(callbackManager)); + event->setForAsynchronousCall(controller); + + appmgr->findAppControl(event); + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); + + } catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(context, exception, err); + } catch (...) { + DeviceAPI::Common::UnknownException err("Unknown Error in ApplicationManager.findAppControl()."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } +} + + +JSValueRef JSApplicationManager::getAppsContext(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + TIME_TRACER_ITEM_BEGIN("getAppsContext(async)", 0); + + try { + IApplicationManagerPtr appmgr; + JSContextRef gContext; + ApplicationController *controller; + + controller = static_cast<ApplicationController*>(JSObjectGetPrivate(thisObject)); + if (!controller) { + throw TypeMismatchException("No private object."); + } + appmgr = controller->getObject(); + gContext = controller->getContext(); + + EventApplicationGetAppsContextPtr event(new EventApplicationGetAppsContext()); + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(gContext); + + ArgumentValidator validator(context, argumentCount, arguments); + + // successCallback + JSObjectRef successCallbackObj = validator.toFunction(0); + callbackManager->setOnSuccess(successCallbackObj); + + // errorCallback + JSObjectRef errorCallbackObj = validator.toFunction(1, true); + if (errorCallbackObj) + callbackManager->setOnError(errorCallbackObj); + + callbackManager->setObject(thisObject); + ApplicationAsyncCallbackManagerSingleton::Instance().registerCallbackManager(callbackManager, gContext); + + event->setPrivateData(DPL::StaticPointerCast<IEventPrivateData>(callbackManager)); + event->setForAsynchronousCall(controller); + + appmgr->getAppsContext(event); + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); + + } catch (const BasePlatformException &err) { + LoggerE("BasePlatformException"); + return JSWebAPIErrorFactory::postException(context, exception, err); + } catch (...) { + LoggerE("etc..."); + DeviceAPI::Common::UnknownException err("Unknown Error in ApplicationManager.getAppsContext()."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } +} + + +JSValueRef JSApplicationManager::getAppContext(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + + try { + ArgumentValidator validator(context, argumentCount, arguments); + + ApplicationContextPtr result = ApplicationManager::getAppContext(validator.toString(0, true, "")); + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return converter->toJSValueRefFromApplicationContext(result); + + } catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(context, exception, err); + } catch (const WrtDeviceApis::Commons::NotFoundException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_FOUND_ERROR, ex.GetMessage()); + } catch (...) { + DeviceAPI::Common::UnknownException err("Unknown Error in ApplicationManager.getAppContext()."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } +} + + +JSValueRef JSApplicationManager::getAppsInfo(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + TIME_TRACER_ITEM_BEGIN("getAppsInfo(async)", 0); + + try { + IApplicationManagerPtr appmgr; + JSContextRef gContext; + ApplicationController *controller; + + controller = static_cast<ApplicationController*>(JSObjectGetPrivate(thisObject)); + if (!controller) { + throw TypeMismatchException("No private object."); + } + appmgr = controller->getObject(); + gContext = controller->getContext(); + + EventApplicationGetAppsInfoPtr event(new EventApplicationGetAppsInfo()); + JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(gContext); + + ArgumentValidator validator(context, argumentCount, arguments); + + // successCallback + JSObjectRef successCallbackObj = validator.toFunction(0); + callbackManager->setOnSuccess(successCallbackObj); + + // errorCallback + JSObjectRef errorCallbackObj = validator.toFunction(1, true); + if (errorCallbackObj) { + callbackManager->setOnError(errorCallbackObj); + } + + callbackManager->setObject(thisObject); + ApplicationAsyncCallbackManagerSingleton::Instance().registerCallbackManager(callbackManager, gContext); + + event->setPrivateData(DPL::StaticPointerCast<IEventPrivateData>(callbackManager)); + event->setForAsynchronousCall(controller); + + appmgr->getAppsInfo(event); + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); + + } catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(context, exception, err); + } catch (...) { + DeviceAPI::Common::UnknownException err("Unknown Error in ApplicationManager.getAppsInfo()."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } +} + + +JSValueRef JSApplicationManager::getAppInfo(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + + try { + ApplicationController *controller = static_cast<ApplicationController*>(JSObjectGetPrivate(thisObject)); + if (!controller) { + throw TypeMismatchException("No private object."); + } + JSContextRef gContext = controller->getContext(); + + ArgumentValidator validator(context, argumentCount, arguments); + + ApplicationInformationPtr result = ApplicationManager::getAppInfo(validator.toString(0, true, "")); + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(gContext); + + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return converter->toJSValueRefFromApplicationInformation(result); + + } catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(context, exception, err); + } catch (const WrtDeviceApis::Commons::NotFoundException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_FOUND_ERROR, ex.GetMessage()); + } catch (...) { + DeviceAPI::Common::UnknownException err("Unknown Error in ApplicationManager.getAppInfo()."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } +} + +JSValueRef JSApplicationManager::addAppInfoEventListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + + try { + IApplicationManagerPtr appmgr; + JSContextRef gContext; + ApplicationController *controller; + + controller = static_cast<ApplicationController*>(JSObjectGetPrivate(thisObject)); + if (!controller) { + throw TypeMismatchException("No private object."); + } + appmgr = controller->getObject(); + gContext = controller->getContext(); + + EventApplicationAddAppInfoEventListenerPtr event(new EventApplicationAddAppInfoEventListener()); + + ArgumentValidator validator(context, argumentCount, arguments); + + // eventCallback + JSObjectRef eventCBObj = validator.toCallbackObject(0, false, "oninstalled", "onupdated", "onuninstalled", NULL); + JSApplicationEventCallbackManagerPtr callbackManager = JSApplicationEventCallbackManager::createObject(gContext); + + JSValueRef oninstalled = JSUtil::getProperty(context, eventCBObj, "oninstalled", exception); + if (!JSValueIsUndefined(context, oninstalled)) { + callbackManager->setOnInstalled(oninstalled); + } + + JSValueRef onupdated = JSUtil::getProperty(context, eventCBObj, "onupdated", exception); + if (!JSValueIsUndefined(context, onupdated)) { + callbackManager->setOnUpdated(onupdated); + } + + JSValueRef onuninstalled = JSUtil::getProperty(context, eventCBObj, "onuninstalled", exception); + if (!JSValueIsUndefined(context, onuninstalled)) { + callbackManager->setOnUninstalled(onuninstalled); + } + + EventApplicationAppInfoEventListenerEmitterPtr emitter(new EventApplicationAppInfoEventListenerEmitter()); + + emitter->setEventPrivateData(DPL::StaticPointerCast<IEventPrivateData>(callbackManager)); + emitter->setListener(controller); + + event->setEmitter(emitter); + event->setForSynchronousCall(); + + appmgr->addAppInfoEventListener(event); + + if (event->getExceptionCode() != ExceptionCodes::None) { + throw UnknownException("Unknown Exception Occured"); + } + + unsigned long id = event->getWatchId(); + + ApplicationListenerCancellerPtr canceller = ApplicationListenerCancellerPtr(new ApplicationListenerCanceller(gContext, thisObject, id)); + DeviceAPI::Common::IListenerItemPtr listenerItem = DPL::StaticPointerCast<DeviceAPI::Common::IListenerItem>(canceller); + ApplicationListenerManagerSingleton::Instance().registerListener(listenerItem, gContext); + + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return converter->toJSValueRef(id); + + } catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(context, exception, err); + } catch (...) { + DeviceAPI::Common::UnknownException err("Unknown Error in ApplicationManager.addAppInfoEventListener()."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } +} + +JSValueRef JSApplicationManager::removeAppInfoEventListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + + try { + IApplicationManagerPtr appmgr; + JSContextRef gContext; + ApplicationController *controller; + + controller = static_cast<ApplicationController*>(JSObjectGetPrivate(thisObject)); + if (!controller) { + throw TypeMismatchException("No private object."); + } + appmgr = controller->getObject(); + gContext = controller->getContext(); + + EventApplicationRemoveAppInfoEventListenerPtr event(new EventApplicationRemoveAppInfoEventListener()); + + ArgumentValidator validator(context, argumentCount, arguments); + + // watchId + long watchId = validator.toLong(0); + event->setWatchId(watchId); + + event->setForSynchronousCall(); + + appmgr->removeAppInfoEventListener(event); + + ApplicationListenerCancellerPtr canceller = ApplicationListenerCancellerPtr(new ApplicationListenerCanceller(gContext, thisObject, watchId)); + DeviceAPI::Common::IListenerItemPtr listenerItem = DPL::StaticPointerCast<DeviceAPI::Common::IListenerItem>(canceller); + ApplicationListenerManagerSingleton::Instance().unregisterListener(listenerItem); + + if (event->getExceptionCode() == ExceptionCodes::NotFoundException) { + throw NotFoundException("Watch id not found"); + } + else if (event->getExceptionCode() != ExceptionCodes::None) { + throw UnknownException("UnknownException Occured"); + } + + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); + + } catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(context, exception, err); + } catch (...) { + DeviceAPI::Common::UnknownException err("Unknown Error in ApplicationManager.removeAppInfoEventListener()."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } +} + + +JSValueRef JSApplicationManager::getAppCerts(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + + TIME_TRACER_ITEM_BEGIN("(getAppCerts)ACE", 0); + AceSecurityStatus status = APPLICATION_CHECK_ACCESS(APPLICATION_FUNCTION_API_GET_APP_CERTS); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + TIME_TRACER_ITEM_END("(getAppCerts)ACE", 0); + + try { + ArgumentValidator validator(context, argumentCount, arguments); + + ApplicationCertArrayPtr result = ApplicationManager::getAppCerts(validator.toString(0, true, "")); + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return converter->toJSValueRefFromApplicationCerts(result); + + } catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(context, exception, err); + } catch (const WrtDeviceApis::Commons::NotFoundException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_FOUND_ERROR, ex.GetMessage()); + } catch (...) { + DeviceAPI::Common::UnknownException err("Unknown Error in ApplicationManager.getAppCerts()."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } +} + + +JSValueRef JSApplicationManager::getAppSharedURI(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + + try { + ArgumentValidator validator(context, argumentCount, arguments); + + std::string result = ApplicationManager::getAppSharedURI(validator.toString(0, true, "")); + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return converter->toJSValueRef(result); + + } catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(context, exception, err); + } catch (const WrtDeviceApis::Commons::NotFoundException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_FOUND_ERROR, ex.GetMessage()); + } catch (...) { + DeviceAPI::Common::UnknownException err("Unknown Error in ApplicationManager.getAppSharedURI()."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } +} + +JSValueRef JSApplicationManager::getAppMetaData(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + + TIME_TRACER_ITEM_BEGIN("(getAppMetaData)ACE", 0); + AceSecurityStatus status = APPLICATION_CHECK_ACCESS(APPLICATION_FUNCTION_API_GET_APP_META_DATA); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + TIME_TRACER_ITEM_END("(getAppMetaData)ACE", 0); + + try { + ArgumentValidator validator(context, argumentCount, arguments); + + ApplicationMetaDataArrayPtr result = ApplicationManager::getAppMetaData(validator.toString(0, true, "")); + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return converter->toJSValueRefFromApplicationMetaDataArray(result); + + } catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(context, exception, err); + } catch (const WrtDeviceApis::Commons::NotFoundException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_FOUND_ERROR, ex.GetMessage()); + } catch (...) { + DeviceAPI::Common::UnknownException err("Unknown Error in ApplicationManager.getAppCerts()."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } +} + + +/* scheme-callback using title is not working on iframe. So, use IPC API instead of below API. +void JSApplicationManager::setTitleProperty(JSContextRef context, std::string propertyValue){ + + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + // get window object + JSObjectRef windowObject = JSContextGetGlobalObject(context); + + // get title object + JSObjectRef documentObject = converter.toJSObjectRef(JSObjectGetProperty(context, + windowObject, + ScopedJSStringRef(JSStringCreateWithUTF8CString("document")).get(), + NULL)); + + JSObjectSetProperty(context, + documentObject, + ScopedJSStringRef(JSStringCreateWithUTF8CString("title")).get(), + JSValueMakeString(context, JSStringCreateWithUTF8CString("tizen://dummy#$#@##")), + kJSPropertyAttributeNone, + NULL); + + JSObjectSetProperty(context, + documentObject, + ScopedJSStringRef(JSStringCreateWithUTF8CString("title")).get(), + JSValueMakeString(context, JSStringCreateWithUTF8CString(propertyValue.c_str())), + kJSPropertyAttributeNone, + NULL); +} +*/ + +} +} diff --git a/wearable_src/Application/JSApplicationManager.h b/wearable_src/Application/JSApplicationManager.h new file mode 100644 index 0000000..873be7c --- /dev/null +++ b/wearable_src/Application/JSApplicationManager.h @@ -0,0 +1,158 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_TIZEN_JS_APPLICATION_MANAGER_H_ +#define TIZENAPIS_TIZEN_JS_APPLICATION_MANAGER_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/PrivateObject.h> +#include "IApplicationManager.h" + +namespace DeviceAPI { +namespace Application { + +#define TIZEN_INTERFACE_APPLICATION_MANAGER "ApplicationManager" + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject + <IApplicationManagerPtr, WrtDeviceApis::CommonsJavaScript::NoOwnership> JSApplicationManagerPriv; + +class JSApplicationManager { +public: + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + + //static void setTitleProperty(JSContextRef context, std::string propertyValue); + +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); + + /** + * Gets a current application + */ + static JSValueRef getCurrentApplication(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + /** + * Launches a application with given application id + */ + static JSValueRef launch(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + /** + * Kills the application based on application context. + */ + static JSValueRef kill(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + + /** + * exit current application + */ + static JSValueRef setUserAgent(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + /** + * Gets the list of installed packages. + */ + static JSValueRef getAppsInfo(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + /** + * Gets the list of running packages. + */ + static JSValueRef getAppsContext(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + /** + * Gets the application information of based on the package name. + */ + static JSValueRef getAppInfo(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + /** + * Gets the current application Context + */ + static JSValueRef getAppContext(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + /** + * Watch for changes on installed applicaiton. + */ + static JSValueRef addAppInfoEventListener(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + /** + * Unset installed Applications listener + */ + static JSValueRef removeAppInfoEventListener(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + /** + * Launch a application control + */ + static JSValueRef launchAppControl(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + /** + * Find application info list with application control + */ + static JSValueRef findAppControl(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + /** + * Get certificate information of given application + */ + static JSValueRef getAppCerts(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + /** + * Get shared directory URI of specific application + */ + static JSValueRef getAppSharedURI(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + /** + * Get meta data of specific application + */ + static JSValueRef getAppMetaData(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + static JSClassRef m_jsClassRef; +}; + +} +} +#endif diff --git a/wearable_src/Application/JSApplicationMetaData.cpp b/wearable_src/Application/JSApplicationMetaData.cpp new file mode 100644 index 0000000..ec45d73 --- /dev/null +++ b/wearable_src/Application/JSApplicationMetaData.cpp @@ -0,0 +1,136 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 <cassert> +#include <memory> +#include <CommonsJavaScript/JSUtils.h> +#include <CommonsJavaScript/Converter.h> + +//#include <Commons/Exception.h> +#include <JSWebAPIErrorFactory.h> + +#include "ApplicationMetaData.h" +#include "JSApplicationMetaData.h" +#include <Export.h> +#include <Logger.h> + +namespace DeviceAPI { +namespace Application { + +using namespace WrtDeviceApis; +using namespace DeviceAPI::Common; + + +JSClassRef JSApplicationMetaData::m_classRef = NULL; + +JSClassDefinition JSApplicationMetaData::m_classInfo = { + 0, + kJSClassAttributeNone, + TIZEN_INTERFACE_APPLICATION_META_DATA, + 0, + m_property, + 0, + initialize, + finalize, + NULL, //HasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, + NULL, //ConvertToType +}; + +JSStaticValue JSApplicationMetaData::m_property[] = { + { TIZEN_APPLICATION_META_DATA_KEY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_APPLICATION_META_DATA_VALUE, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSClassRef DLL_EXPORT JSApplicationMetaData::getClassRef() { + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + + +void JSApplicationMetaData::initialize(JSContextRef context, JSObjectRef object) +{ +} + +void JSApplicationMetaData::finalize(JSObjectRef object) +{ + JSApplicationMetaDataPriv* priv = static_cast<JSApplicationMetaDataPriv*>(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + delete priv; +} + +bool JSApplicationMetaData::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +ApplicationMetaDataPtr JSApplicationMetaData::getPrivData(JSObjectRef object) +{ + JSApplicationMetaDataPriv *priv = static_cast<JSApplicationMetaDataPriv*>(JSObjectGetPrivate(object)); + if (!priv) { + throw TypeMismatchException("Private object is null"); + } + ApplicationMetaDataPtr result = priv->getObject(); + if (!result) { + throw TypeMismatchException("Private object is null"); + } + return result; +} + + +JSValueRef JSApplicationMetaData::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + try { + CommonsJavaScript::Converter converter(context); + ApplicationMetaDataPtr privateData = getPrivData(object); + + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_APPLICATION_META_DATA_KEY)) { + return converter.toJSValueRef(privateData->getKey()); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_APPLICATION_META_DATA_VALUE)) { + std::string value = privateData->getValue(); + + // if value does not have value, return empty string. + if (value.compare("(null)") == 0) { + value.clear(); + } + + return converter.toJSValueRef(value); + } + } catch (...) { + LoggerE("Exception occured while get property"); + return JSValueMakeUndefined(context); + } + + /* do not return undefined object to find method */ + return NULL; +} + +} +} diff --git a/wearable_src/Application/JSApplicationMetaData.h b/wearable_src/Application/JSApplicationMetaData.h new file mode 100644 index 0000000..e58aa36 --- /dev/null +++ b/wearable_src/Application/JSApplicationMetaData.h @@ -0,0 +1,81 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_TIZEN_JS_APPLICATION_META_DATA_H_ +#define TIZENAPIS_TIZEN_JS_APPLICATION_META_DATA_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/PrivateObject.h> +#include <dpl/shared_ptr.h> + +namespace DeviceAPI { +namespace Application { + +#define TIZEN_INTERFACE_APPLICATION_META_DATA "ApplicationMetaData" + +#define TIZEN_APPLICATION_META_DATA_KEY "key" +#define TIZEN_APPLICATION_META_DATA_VALUE "value" + + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject<ApplicationMetaDataPtr, WrtDeviceApis::CommonsJavaScript::NoOwnership> JSApplicationMetaDataPriv; + +class JSApplicationMetaData{ +public: + /* + * This initializes this JS class in the JS Engine. + */ + static JSClassRef getClassRef(); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + +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 member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; + + static JSClassRef m_classRef; + + static ApplicationMetaDataPtr getPrivData(JSObjectRef object); + + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + +}; + +} +} +#endif diff --git a/wearable_src/Application/JSRequestedApplicationControl.cpp b/wearable_src/Application/JSRequestedApplicationControl.cpp new file mode 100644 index 0000000..53aeed1 --- /dev/null +++ b/wearable_src/Application/JSRequestedApplicationControl.cpp @@ -0,0 +1,256 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 <cassert> +#include <memory> + +#include <SecurityExceptions.h> +#include <JSWebAPIError.h> +#include <ArgumentValidator.h> + +#include "plugin_config.h" +#include "ApplicationConverter.h" +#include "ApplicationUtil.h" +#include "JSRequestedApplicationControl.h" +#include <Export.h> + +#include <TimeTracer.h> + +#include <Logger.h> + +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace DeviceAPI::Common; + +namespace DeviceAPI { +namespace Application { + +using WrtDeviceApis::Commons::NotFoundException; + +JSClassRef JSRequestedApplicationControl::m_jsClassRef = NULL; + +JSClassDefinition JSRequestedApplicationControl::m_classInfo = { + 0, + kJSClassAttributeNone, + TIZEN_INTERFACE_REQUESTED_APPLICATION_CONTROL, + 0, + m_property, + m_function, + initialize, + finalize, + NULL, //HasProperty, + NULL, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, + NULL, //ConvertToType +}; + +JSStaticValue JSRequestedApplicationControl::m_property[] = { + { TIZEN_APPLICATION_CONTROL, getProperty, NULL, kJSPropertyAttributeNone }, + { TIZEN_CALLER_APP_ID, getProperty, NULL, kJSPropertyAttributeNone }, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSRequestedApplicationControl::m_function[] = { + { APPLICATION_FUNCTION_API_REPLY_RESULT, JSRequestedApplicationControl::replyResult, kJSPropertyAttributeNone }, + { APPLICATION_FUNCTION_API_REPLY_FAILURE, JSRequestedApplicationControl::replyFailure,kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +const JSClassDefinition* JSRequestedApplicationControl::getClassInfo() +{ + return &m_classInfo; +} + +JSClassRef DLL_EXPORT JSRequestedApplicationControl::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + + return m_jsClassRef; +} + +JSObjectRef JSRequestedApplicationControl::createJSObject(JSContextRef context, const RequestedApplicationControlPtr &appsvc) +{ + JSRequestedApplicationControlPriv *priv = new JSRequestedApplicationControlPriv(context, appsvc); + + if (!priv) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Can not new an object"); + } + + return JSObjectMake(context, getClassRef(), priv); +} + + + +void JSRequestedApplicationControl::initialize(JSContextRef context,JSObjectRef object) +{ +} + +void JSRequestedApplicationControl::finalize(JSObjectRef object) +{ + JSRequestedApplicationControlPriv* priv = static_cast<JSRequestedApplicationControlPriv*>(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + delete priv; +} + + +bool JSRequestedApplicationControl::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +RequestedApplicationControlPtr JSRequestedApplicationControl::getRequestedApplicationControl(JSContextRef context, JSValueRef value) +{ + if (!isObjectOfClass(context, value)) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + + JSRequestedApplicationControlPriv *priv = static_cast<JSRequestedApplicationControlPriv*>(JSObjectGetPrivate(object)); + if (!priv) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + return priv->getObject(); +} + + +RequestedApplicationControlPtr JSRequestedApplicationControl::getPrivData(JSObjectRef object) +{ + JSRequestedApplicationControlPriv *priv = static_cast<JSRequestedApplicationControlPriv*>(JSObjectGetPrivate(object)); + if (!priv) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Private object is null"); + } + RequestedApplicationControlPtr result = priv->getObject(); + if (!result) { + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Private object is null"); + } + return result; +} + +JSValueRef JSRequestedApplicationControl::getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception) +{ + JSRequestedApplicationControlPriv *priv = static_cast<JSRequestedApplicationControlPriv*>(JSObjectGetPrivate(object)); + if (!priv) { + LoggerE("Exception occured while get property"); + return JSValueMakeUndefined(context); + } + + try { + RequestedApplicationControlPtr providerMgr = priv->getObject(); + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_APPLICATION_CONTROL)) { + return converter->toJSValueRef(providerMgr->getAppControl()); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_CALLER_APP_ID)) { + return converter->toJSValueRef(providerMgr->getCallerAppId()); + } + } catch (...) { + LoggerE("Exception occured while get property"); + return JSValueMakeUndefined(context); + } + + /* do not return undefined object to find method */ + return NULL; +} + + +JSValueRef JSRequestedApplicationControl::replyResult(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + JSRequestedApplicationControlPriv *priv = static_cast<JSRequestedApplicationControlPriv*>(JSObjectGetPrivate(thisObject)); + + try { + if (!priv) { + ThrowMsg(ConversionException, "Object is null."); + } + + ArgumentValidator validator(context, argumentCount, arguments); + + JSObjectRef dataArrayObj = validator.toArrayObject(0, true); + std::vector<ApplicationControlDataPtr> dataArray; + if (dataArrayObj) { + ApplicationConverterFactory::ConverterType converter = ApplicationConverterFactory::getConverter(context); + dataArray = converter->toApplicationControlDataArray(arguments[0]); + } + RequestedApplicationControlPtr providerMgr = priv->getObject(); + providerMgr->replyResult(dataArray); + + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + + return JSValueMakeUndefined(context); + + } catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(context, exception, err); + } catch(const ConversionException& err) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, ""); + } catch (const NotFoundException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_FOUND_ERROR, ex.GetMessage()); + } catch (...) { + DeviceAPI::Common::UnknownException err("Unknown Error in RequestedApplicationControl.replyResult()."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } +} + +JSValueRef JSRequestedApplicationControl::replyFailure(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + JSRequestedApplicationControlPriv *priv = static_cast<JSRequestedApplicationControlPriv*>(JSObjectGetPrivate(thisObject)); + + try { + if (!priv) { + ThrowMsg(ConversionException, "Object is null."); + } + + RequestedApplicationControlPtr providerMgr = priv->getObject(); + providerMgr->replyFailure(); + + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + + return JSValueMakeUndefined(context); + + } catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(context, exception, err); + } catch (const NotFoundException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_FOUND_ERROR, ex.GetMessage()); + } catch (...) { + DeviceAPI::Common::UnknownException err("Unknown Error in RequestedApplicationControl.replyFailure()."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } +} + +} +} diff --git a/wearable_src/Application/JSRequestedApplicationControl.h b/wearable_src/Application/JSRequestedApplicationControl.h new file mode 100644 index 0000000..cc5021a --- /dev/null +++ b/wearable_src/Application/JSRequestedApplicationControl.h @@ -0,0 +1,124 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_TIZEN_JS_REQUESTED_APPLICATION_CONTROL_H_ +#define TIZENAPIS_TIZEN_JS_REQUESTED_APPLICATION_CONTROL_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/PrivateObject.h> +#include "ApplicationControl.h" +#include "RequestedApplicationControl.h" +#include "JSApplicationControl.h" +#include "JSApplicationControlData.h" + +namespace DeviceAPI { +namespace Application { + +#define TIZEN_INTERFACE_REQUESTED_APPLICATION_CONTROL "RequestedApplicationControl" +#define TIZEN_APPLICATION_CONTROL "appControl" +#define TIZEN_CALLER_APP_ID "callerAppId" + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT<RequestedApplicationControlPtr>::Type JSRequestedApplicationControlPriv; + +class JSRequestedApplicationControl { +public: + static const JSClassDefinition* getClassInfo(); + + static JSClassRef getClassRef(); + + /** + * create an JSObject for callback function(onAnswerReceived). + */ + static JSObjectRef createJSObject(JSContextRef context, + const RequestedApplicationControlPtr &appsvc); + + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + /** + * Send Success Result + */ + static JSValueRef replyResult(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + /** + * Send Failure Result + */ + static JSValueRef replyFailure(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + static RequestedApplicationControlPtr getRequestedApplicationControl(JSContextRef context, JSValueRef value); + + +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); + + static RequestedApplicationControlPtr getPrivData(JSObjectRef object); + + + /** + * The callback invoked when getting a property's value. + */ + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + /** + * The callback invoked when setting a property's value. + */ + + static bool setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + 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_property[]; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + + static JSClassRef m_jsClassRef; + +}; + +} // +} //TizenApis + +#endif diff --git a/wearable_src/Application/RequestedApplicationControl.cpp b/wearable_src/Application/RequestedApplicationControl.cpp new file mode 100644 index 0000000..5c3c3c9 --- /dev/null +++ b/wearable_src/Application/RequestedApplicationControl.cpp @@ -0,0 +1,148 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 <Commons/Exception.h> +#include <app_service.h> +#include <app_manager.h> +#include "RequestedApplicationControl.h" + +#include <TimeTracer.h> + +#include <Logger.h> + +namespace DeviceAPI { +namespace Application { + +using namespace WrtDeviceApis::Commons; + +RequestedApplicationControl::RequestedApplicationControl() : + m_appControl(NULL), + m_appService(NULL) +{ +} + + +RequestedApplicationControl::~RequestedApplicationControl() +{ +} + +ApplicationControlPtr RequestedApplicationControl::getAppControl() const +{ + return m_appControl; +} + + +// TODO: Should I add & or not? +void RequestedApplicationControl::setAppControl(ApplicationControlPtr &appControl) +{ + m_appControl = appControl; +} + +std::string RequestedApplicationControl::getCallerAppId() const +{ + return m_callerAppId; +} + +void RequestedApplicationControl::setCallerAppId(const std::string &id) +{ + m_callerAppId = id; +} + +void RequestedApplicationControl::replyResult(std::vector<ApplicationControlDataPtr> &appControlDataArray) +{ + service_h reply; + service_create(&reply); + + if (!appControlDataArray.empty()) + { + const char** arr = NULL; + + LoggerD("appControlDataArray.size() : "<<appControlDataArray.size()); + for (size_t i = 0; i < appControlDataArray.size(); ++i) { + std::vector<std::string> valueArray = appControlDataArray.at(i)->getValue(); + + arr = (const char**) calloc (sizeof(char*), valueArray.size()); + + if (arr != NULL) { + for (size_t j = 0; j < valueArray.size(); j++) { + arr[j] = valueArray.at(j).c_str(); + } + } + service_add_extra_data_array(reply, appControlDataArray.at(i)->getKey().c_str(), arr, valueArray.size()); + if (arr) { + free (arr); + } + } + } else { + LoggerE("[replyResult] appControlDataArray is empty"); + } + + // temporal code to check caller liveness + if (m_callerAppId.empty()) { + LoggerE("m_callerAppId is empty. means caller is dead"); + ThrowMsg(NotFoundException, "Cannot find caller"); + } else { + bool running = false; + TIME_TRACER_ITEM_BEGIN("(replyResult)app_manager_is_running", 0); + int ret = app_manager_is_running(m_callerAppId.c_str(), &running); + TIME_TRACER_ITEM_END("(replyResult)app_manager_is_running", 0); + if ((ret != APP_MANAGER_ERROR_NONE) || !running) { + LoggerE("caller is not running"); + ThrowMsg(NotFoundException, "Cannot find caller"); + } + } + + TIME_TRACER_ITEM_BEGIN("(replyResult)service_reply_to_launch_request", 0); + if (service_reply_to_launch_request(reply, m_appControl->getService_h(), SERVICE_RESULT_SUCCEEDED) != SERVICE_ERROR_NONE) { + ThrowMsg(NotFoundException, "Cannot find caller"); + } + TIME_TRACER_ITEM_END("(replyResult)service_reply_to_launch_request", 0); + + service_destroy(reply); +} + +void RequestedApplicationControl::replyFailure() +{ + service_h reply; + service_create(&reply); + + // temporal code to check caller liveness + if (m_callerAppId.empty()) { + LoggerE("m_callerAppId is empty. means caller is dead"); + ThrowMsg(NotFoundException, "Cannot find caller"); + } else { + bool running = false; + TIME_TRACER_ITEM_BEGIN("(replyFailure)app_manager_is_running", 0); + int ret = app_manager_is_running(m_callerAppId.c_str(), &running); + TIME_TRACER_ITEM_END("(replyFailure)app_manager_is_running", 0); + if ((ret != APP_MANAGER_ERROR_NONE) || !running) { + LoggerE("caller is not running"); + ThrowMsg(NotFoundException, "Cannot find caller"); + } + } + + TIME_TRACER_ITEM_BEGIN("(replyFailure)service_reply_to_launch_request", 0); + if (service_reply_to_launch_request(reply, m_appControl->getService_h(), SERVICE_RESULT_FAILED) != SERVICE_ERROR_NONE) { + ThrowMsg(NotFoundException, "Cannot find caller"); + } + TIME_TRACER_ITEM_END("(replyFailure)service_reply_to_launch_request", 0); + + service_destroy(reply); +} + +} +} diff --git a/wearable_src/Application/RequestedApplicationControl.h b/wearable_src/Application/RequestedApplicationControl.h new file mode 100644 index 0000000..f838a8f --- /dev/null +++ b/wearable_src/Application/RequestedApplicationControl.h @@ -0,0 +1,58 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 TIZENAPIS_API_REQUESTED_APPLICATION_CONTROL_H_ +#define TIZENAPIS_API_REQUESTED_APPLICATION_CONTROL_H_ + +#include <string> +#include <vector> +#include <dpl/shared_ptr.h> + +#include "ApplicationControl.h" +#include "ApplicationControlData.h" + +namespace DeviceAPI { +namespace Application { + +class RequestedApplicationControl; +typedef DPL::SharedPtr<RequestedApplicationControl> RequestedApplicationControlPtr; + +/* This object represents a single extra data for service request and reply */ +class RequestedApplicationControl +{ + public: + RequestedApplicationControl(); + ~RequestedApplicationControl(); + + ApplicationControlPtr getAppControl() const; + void setAppControl(ApplicationControlPtr &appControl); + + std::string getCallerAppId() const; + void setCallerAppId(const std::string &id); + + void replyResult(std::vector<ApplicationControlDataPtr> &appControlDataArray); + void replyFailure(); + + private: + ApplicationControlPtr m_appControl; + service_h m_appService; + std::string m_callerAppId; +}; +} +} +#endif + diff --git a/wearable_src/Application/config.xml b/wearable_src/Application/config.xml new file mode 100755 index 0000000..df09164 --- /dev/null +++ b/wearable_src/Application/config.xml @@ -0,0 +1,37 @@ +<?xml version="1.0" ?> +<!DOCTYPE plugin-properties SYSTEM "/usr/etc/tizen-apis/config.dtd"> +<plugin-properties> + <library-name>libwrt-plugins-tizen-application.so</library-name> + <feature-install-uri>application.install.uri</feature-install-uri> + + <api-feature> + <name>http://tizen.org/privilege/application.launch</name> + <device-capability>application.launch</device-capability> + </api-feature> + + <api-feature> + <name>http://tizen.org/privilege/application.kill</name> + <device-capability>appmanager.kill</device-capability> + </api-feature> + + <api-feature> + <name>http://tizen.org/privilege/appmanager.kill</name> + <device-capability>appmanager.kill</device-capability> + </api-feature> + + <api-feature> + <name>http://tizen.org/privilege/appmanager.certificate</name> + <device-capability>appmanager.certificate</device-capability> + </api-feature> + + <api-feature> + <name>http://tizen.org/privilege/application.read</name> + <device-capability>appmanager.certificate</device-capability> + </api-feature> + + <api-feature> + <name>http://tizen.org/privilege/application.info</name> + <device-capability>application.info</device-capability> + </api-feature> + +</plugin-properties> diff --git a/wearable_src/Application/plugin_config.cpp b/wearable_src/Application/plugin_config.cpp new file mode 100755 index 0000000..aa6ecf4 --- /dev/null +++ b/wearable_src/Application/plugin_config.cpp @@ -0,0 +1,327 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 <Commons/FunctionDefinition.h> +#include <Commons/FunctionDeclaration.h> +#include <iostream> +#include <Commons/Exception.h> +#include <dpl/exception.h> +#include <map> + +#include "plugin_config.h" + +#define APPLICATION_FEATURE_API_LAUNCH "http://tizen.org/privilege/application.launch" +#define APPLICATION_FEATURE_API_KILL "http://tizen.org/privilege/application.kill" +#define APPLICATION_FEATURE_API_KILL2 "http://tizen.org/privilege/appmanager.kill" +#define APPLICATION_FEATURE_API_CERT "http://tizen.org/privilege/appmanager.certificate" +#define APPLICATION_FEATURE_API_INFO "http://tizen.org/privilege/application.info" + + +// for backword compatibility +#define APPLICATION_FEATURE_API_READ "http://tizen.org/privilege/application.read" +//#define APPLICATION_FEATURE_API_INSTALL "http://tizen.org/privilege/application.install" + +#define APPLICATION_DEVICE_CAP_LAUNCH "application.launch" +#define APPLICATION_DEVICE_CAP_KILL "appmanager.kill" +#define APPLICATION_DEVICE_CAP_CERT "appmanager.certificate" +#define APPLICATION_DEVICE_CAP_INFO "application.info" + +//#define APPLICATION_DEVICE_CAP_READ "application.read" +//#define APPLICATION_DEVICE_CAP_INSTALL "application.install" + +using namespace WrtDeviceApis::Commons; + +namespace DeviceAPI { +namespace Application { + +static FunctionMapping createApplicationFunctions(); + +static FunctionMapping ApplicationFunctions = + createApplicationFunctions(); + +#pragma GCC visibility push(default) + +DEFINE_FUNCTION_GETTER(Application, ApplicationFunctions); + +#pragma GCC visibility pop + +static FunctionMapping createApplicationFunctions() +{ + /** + * Device capabilities + */ + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_APPLICATION_LAUNCH, APPLICATION_DEVICE_CAP_LAUNCH); + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_APPLICATION_KILL, APPLICATION_DEVICE_CAP_KILL); + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_APPLICATION_CERT, APPLICATION_DEVICE_CAP_CERT); + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_APPLICATION_INFO, APPLICATION_DEVICE_CAP_INFO); + + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_APPLICATION_LAUNCH); + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_APPLICATION_KILL); + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_APPLICATION_CERT); + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_APPLICATION_INFO); + + ACE_ADD_DEVICE_CAP(DEVICE_LIST_APPLICATION_LAUNCH, DEVICE_CAP_APPLICATION_LAUNCH); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_APPLICATION_KILL, DEVICE_CAP_APPLICATION_KILL); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_APPLICATION_CERT, DEVICE_CAP_APPLICATION_CERT); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_APPLICATION_INFO, DEVICE_CAP_APPLICATION_INFO); + +#if 0 + ACE_CREATE_DEVICE_CAPS_LIST(EMPTY_DEVICE_LIST); + + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_APPLICATION_READ, APPLICATION_DEVICE_CAP_READ); + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_APPLICATION_INSTALL, APPLICATION_DEVICE_CAP_INSTALL); + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_APPLICATION_READ); + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_APPLICATION_INSTALL); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_APPLICATION_READ, DEVICE_CAP_APPLICATION_READ); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_APPLICATION_INSTALL, DEVICE_CAP_APPLICATION_INSTALL); +#endif + + /** + * Api Features + */ + ACE_CREATE_FEATURE(FEATURE_APPLICATION_LAUNCH, APPLICATION_FEATURE_API_LAUNCH); + ACE_CREATE_FEATURE(FEATURE_APPLICATION_KILL, APPLICATION_FEATURE_API_KILL); + ACE_CREATE_FEATURE(FEATURE_APPLICATION_KILL2, APPLICATION_FEATURE_API_KILL2); + ACE_CREATE_FEATURE(FEATURE_APPLICATION_CERT, APPLICATION_FEATURE_API_CERT); + ACE_CREATE_FEATURE(FEATURE_APPLICATION_READ, APPLICATION_FEATURE_API_READ); + ACE_CREATE_FEATURE(FEATURE_APPLICATION_INFO, APPLICATION_FEATURE_API_INFO); + + + ACE_CREATE_FEATURE_LIST(APPLICATION_FEATURES_APPLICATION_LAUNCH); + ACE_ADD_API_FEATURE(APPLICATION_FEATURES_APPLICATION_LAUNCH, FEATURE_APPLICATION_LAUNCH); + + ACE_CREATE_FEATURE_LIST(APPLICATION_FEATURES_APPLICATION_KILL); + ACE_ADD_API_FEATURE(APPLICATION_FEATURES_APPLICATION_KILL, FEATURE_APPLICATION_KILL); + ACE_ADD_API_FEATURE(APPLICATION_FEATURES_APPLICATION_KILL, FEATURE_APPLICATION_KILL2); + + ACE_CREATE_FEATURE_LIST(APPLICATION_FEATURES_APPLICATION_CERT); + ACE_ADD_API_FEATURE(APPLICATION_FEATURES_APPLICATION_CERT, FEATURE_APPLICATION_CERT); + ACE_ADD_API_FEATURE(APPLICATION_FEATURES_APPLICATION_CERT, FEATURE_APPLICATION_READ); + + ACE_CREATE_FEATURE_LIST(APPLICATION_FEATURES_APPLICATION_INFO); + ACE_ADD_API_FEATURE(APPLICATION_FEATURES_APPLICATION_INFO, FEATURE_APPLICATION_INFO); + + +#if 0 + ACE_CREATE_FEATURE(FEATURE_APPLICATION_READ, APPLICATION_FEATURE_API_READ); + ACE_CREATE_FEATURE(FEATURE_APPLICATION_INSTALL, APPLICATION_FEATURE_API_INSTALL); + + ACE_CREATE_FEATURE_LIST(APPLICATION_FEATURES_APPLICATION_READ); + ACE_ADD_API_FEATURE(APPLICATION_FEATURES_APPLICATION_READ, FEATURE_APPLICATION_READ); + + ACE_CREATE_FEATURE_LIST(APPLICATION_FEATURES_APPLICATION_INSTALL); + ACE_ADD_API_FEATURE(APPLICATION_FEATURES_APPLICATION_INSTALL, FEATURE_APPLICATION_INSTALL); +#endif + + /** + * Functions + */ + FunctionMapping applicationMapping; + + // launch + AceFunction launchFunc = ACE_CREATE_FUNCTION( + FUNCTION_LAUNCH, + APPLICATION_FUNCTION_API_LAUNCH, + APPLICATION_FEATURES_APPLICATION_LAUNCH, + DEVICE_LIST_APPLICATION_LAUNCH); + + applicationMapping.insert(std::make_pair( + APPLICATION_FUNCTION_API_LAUNCH, + launchFunc)); + + // launchAppControl + AceFunction launchAppControlFunc = ACE_CREATE_FUNCTION( + FUNCTION_LAUNCH_APP_CONTROL, + APPLICATION_FUNCTION_API_LAUNCH_APP_CONTROL, + APPLICATION_FEATURES_APPLICATION_LAUNCH, + DEVICE_LIST_APPLICATION_LAUNCH); + + applicationMapping.insert(std::make_pair( + APPLICATION_FUNCTION_API_LAUNCH_APP_CONTROL, + launchAppControlFunc)); + + // kill + AceFunction killFunc = ACE_CREATE_FUNCTION( + FUNCTION_KILL, + APPLICATION_FUNCTION_API_KILL, + APPLICATION_FEATURES_APPLICATION_KILL, + DEVICE_LIST_APPLICATION_KILL); + + applicationMapping.insert(std::make_pair( + APPLICATION_FUNCTION_API_KILL, + killFunc)); + + + // getAppCerts + AceFunction getAppCertsFunc = ACE_CREATE_FUNCTION( + FUNCTION_GET_APP_CERTS, + APPLICATION_FUNCTION_API_GET_APP_CERTS, + APPLICATION_FEATURES_APPLICATION_CERT, + DEVICE_LIST_APPLICATION_CERT); + + applicationMapping.insert(std::make_pair( + APPLICATION_FUNCTION_API_GET_APP_CERTS, + getAppCertsFunc)); + + // getAppMetaData + AceFunction getAppMetaDataFunc = ACE_CREATE_FUNCTION( + FUNCTION_GET_APP_META_DATA, + APPLICATION_FUNCTION_API_GET_APP_META_DATA, + APPLICATION_FEATURES_APPLICATION_INFO, + DEVICE_LIST_APPLICATION_INFO); + + applicationMapping.insert(std::make_pair( + APPLICATION_FUNCTION_API_GET_APP_META_DATA, + getAppMetaDataFunc)); + +#if 0 + + // setUserAgent + AceFunction setUserAgentFunc = ACE_CREATE_FUNCTION( + FUNCTION_SET_USER_AGENT, + APPLICATION_FUNCTION_API_SET_USER_AGENT, + APPLICATION_FEATURES_APPLICATION_READ, + EMPTY_DEVICE_LIST); + + applicationMapping.insert(std::make_pair( + APPLICATION_FUNCTION_API_SET_USER_AGENT, + setUserAgentFunc)); + + // getAppsInfo + AceFunction getAppsInfoFunc = ACE_CREATE_FUNCTION( + FUNCTION_GET_APPLICATION_INFORMATIONS, + APPLICATION_FUNCTION_API_GET_APPS_INFO, + APPLICATION_FEATURES_APPLICATION_READ, + DEVICE_LIST_APPLICATION_READ); + + applicationMapping.insert(std::make_pair( + APPLICATION_FUNCTION_API_GET_APPS_INFO, + getAppsInfoFunc)); + + // getAppInfo + AceFunction getAppInfoFunc = ACE_CREATE_FUNCTION( + FUNCTION_GET_APPLICATION_INFORMATION, + APPLICATION_FUNCTION_API_GET_APP_INFO, + APPLICATION_FEATURES_APPLICATION_READ, + DEVICE_LIST_APPLICATION_READ); + + applicationMapping.insert(std::make_pair( + APPLICATION_FUNCTION_API_GET_APP_INFO, + getAppInfoFunc)); + + // getAppsContext + AceFunction getAppsContextFunc = ACE_CREATE_FUNCTION( + FUNCTION_GET_RUNNING_APPLICATION_CONTEXTS, + APPLICATION_FUNCTION_API_GET_APPS_CONTEXT, + APPLICATION_FEATURES_APPLICATION_READ, + DEVICE_LIST_APPLICATION_READ); + + applicationMapping.insert(std::make_pair( + APPLICATION_FUNCTION_API_GET_APPS_CONTEXT, + getAppsContextFunc)); + + // getAppContext + AceFunction getAppContextFunc = ACE_CREATE_FUNCTION( + FUNCTION_GET_CURRENT_APPLICATION_CONTEXT, + APPLICATION_FUNCTION_API_GET_APP_CONTEXT, + APPLICATION_FEATURES_APPLICATION_READ, + DEVICE_LIST_APPLICATION_READ); + + applicationMapping.insert(std::make_pair( + APPLICATION_FUNCTION_API_GET_APP_CONTEXT, + getAppContextFunc)); + + // getAppsContext + AceFunction findAppControlFunc = ACE_CREATE_FUNCTION( + FUNCTION_GET_RUNNING_APPLICATION_CONTEXTS, + APPLICATION_FUNCTION_API_FIND_APP_CONTROL, + APPLICATION_FEATURES_APPLICATION_READ, + DEVICE_LIST_APPLICATION_READ); + + applicationMapping.insert(std::make_pair( + APPLICATION_FUNCTION_API_FIND_APP_CONTROL, + findAppControlFunc)); + + // addAppInfoEventListener + AceFunction addAppInfoEventListenerFunc = ACE_CREATE_FUNCTION( + FUNCTION_ADD_APPLICATION_INFORMATION_EVENT_LISTENER, + APPLICATION_FUNCTION_API_ADD_APP_INFO_EVENT_LISTENER, + APPLICATION_FEATURES_APPLICATION_READ, + DEVICE_LIST_APPLICATION_READ); + + applicationMapping.insert(std::make_pair( + APPLICATION_FUNCTION_API_ADD_APP_INFO_EVENT_LISTENER, + addAppInfoEventListenerFunc)); + + // removeAppInfoEventListener + AceFunction removeAppInfoEventListenerFunc = ACE_CREATE_FUNCTION( + FUNCTION_REMOVE_APPLICATION_INFORMATION_EVENT_LISTENER, + APPLICATION_FUNCTION_API_REMOVE_APP_INFO_EVENT_LISTENER, + APPLICATION_FEATURES_APPLICATION_READ, + DEVICE_LIST_APPLICATION_READ); + + applicationMapping.insert(std::make_pair( + APPLICATION_FUNCTION_API_REMOVE_APP_INFO_EVENT_LISTENER, + removeAppInfoEventListenerFunc)); + + // install + AceFunction installFunc = ACE_CREATE_FUNCTION( + FUNCTION_INSTALL_APP, + APPLICATION_FUNCTION_API_INSTALL_APP, + APPLICATION_FEATURES_APPLICATION_INSTALL, + DEVICE_LIST_APPLICATION_INSTALL); + applicationMapping.insert(std::make_pair( + APPLICATION_FUNCTION_API_INSTALL_APP, + installFunc)); + + // uninstall + AceFunction uninstallFunc = ACE_CREATE_FUNCTION( + FUNCTION_UNINSTALL_APP, + APPLICATION_FUNCTION_API_UNINSTALL_APP, + APPLICATION_FEATURES_APPLICATION_INSTALL, + DEVICE_LIST_APPLICATION_INSTALL); + applicationMapping.insert(std::make_pair( + APPLICATION_FUNCTION_API_UNINSTALL_APP, + uninstallFunc)); + + // update + AceFunction updateFunc = ACE_CREATE_FUNCTION( + FUNCTION_UPDATE_APP, + APPLICATION_FUNCTION_API_UPDATE_APP, + APPLICATION_FEATURES_APPLICATION_INSTALL, + DEVICE_LIST_APPLICATION_INSTALL); + applicationMapping.insert(std::make_pair( + APPLICATION_FUNCTION_API_UPDATE_APP, + updateFunc)); +#endif + // size + AceFunction sizeAttr = ACE_CREATE_FUNCTION( + ATTRIBUTE_SIZE, + APPLICATION_FUNCTION_API_SIZE, + APPLICATION_FEATURES_APPLICATION_INFO, + DEVICE_LIST_APPLICATION_INFO); + + applicationMapping.insert(std::make_pair( + APPLICATION_FUNCTION_API_SIZE, + sizeAttr)); + + return applicationMapping; +} + +} +} diff --git a/wearable_src/Application/plugin_config.h b/wearable_src/Application/plugin_config.h new file mode 100755 index 0000000..ed69a0c --- /dev/null +++ b/wearable_src/Application/plugin_config.h @@ -0,0 +1,67 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 _APPLICATOIN_PLUGIN_CONFIG_H_ +#define _APPLICATOIN_PLUGIN_CONFIG_H_ + +#include <string> +#include <Commons/FunctionDeclaration.h> + +// feature : launch +#define APPLICATION_FUNCTION_API_LAUNCH "launch" +#define APPLICATION_FUNCTION_API_LAUNCH_APP_CONTROL "launchAppControl" + +// feature : kill - public candidate +#define APPLICATION_FUNCTION_API_KILL "kill" + +// feature : certificate - public candidate +#define APPLICATION_FUNCTION_API_GET_APP_CERTS "getAppCerts" + +// no feature required +#define APPLICATION_FUNCTION_API_GET_APPS_INFO "getAppsInfo" +#define APPLICATION_FUNCTION_API_GET_APP_INFO "getAppInfo" +#define APPLICATION_FUNCTION_API_GET_APPS_CONTEXT "getAppsContext" +#define APPLICATION_FUNCTION_API_GET_APP_CONTEXT "getAppContext" +#define APPLICATION_FUNCTION_API_FIND_APP_CONTROL "findAppControl" +#define APPLICATION_FUNCTION_API_ADD_APP_INFO_EVENT_LISTENER "addAppInfoEventListener" +#define APPLICATION_FUNCTION_API_REMOVE_APP_INFO_EVENT_LISTENER "removeAppInfoEventListener" +#define APPLICATION_FUNCTION_API_GET_CURRENT_APP "getCurrentApplication" +#define APPLICATION_FUNCTION_API_GET_REQUESTED_APP_CONTROL "getRequestedAppControl" +#define APPLICATION_FUNCTION_API_EXIT "exit" +#define APPLICATION_FUNCTION_API_HIDE "hide" +#define APPLICATION_FUNCTION_API_REPLY_RESULT "replyResult" +#define APPLICATION_FUNCTION_API_REPLY_FAILURE "replyFailure" +#define APPLICATION_FUNCTION_API_GET_APP_SHARED_URI "getAppSharedURI" +#define APPLICATION_FUNCTION_API_GET_APP_META_DATA "getAppMetaData" +#define APPLICATION_FUNCTION_API_SET_USER_AGENT "setUserAgent" +#define APPLICATION_FUNCTION_API_SIZE "size" + +namespace DeviceAPI { +namespace Application { + +DECLARE_FUNCTION_GETTER(Application); + +#define APPLICATION_CHECK_ACCESS(functionName) \ + aceCheckAccess<AceFunctionGetter, DefaultArgsVerifier<> >( \ + getApplicationFunctionData, \ + functionName) + +} +} +#endif + diff --git a/wearable_src/Application/plugin_initializer.cpp b/wearable_src/Application/plugin_initializer.cpp new file mode 100644 index 0000000..49c7a2f --- /dev/null +++ b/wearable_src/Application/plugin_initializer.cpp @@ -0,0 +1,121 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 <dpl/wrt-dao-ro/widget_dao_read_only.h> +#include <dpl/string.h> + +#include <Commons/plugin_initializer_def.h> +#include <Commons/WrtAccess/WrtAccess.h> +#include <sys/types.h> +#include <unistd.h> +#include <TimeTracer.h> + +#include "JSApplicationManager.h" +#include "JSApplicationControl.h" +#include "ApplicationAsyncCallbackManager.h" +#include "ApplicationListenerManager.h" +#include "AppManagerWrapper.h" +#include <Logger.h> + +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; + +namespace DeviceAPI { +namespace Application { + +class_definition_options_t ApplicationOptions = +{ + JS_INTERFACE, + CREATE_INSTANCE, + NONE_NOTICE, + USE_OVERLAYED, //ignored + NULL, + NULL, + NULL +}; + +void on_widget_start_callback(int widgetId) { + LoggerD("[Tizen1_0\\Application] on_widget_start_callback ("<<widgetId<<")"); + Try { + WrtDB::WidgetDAOReadOnly dao(widgetId); + std::string tzAppId = DPL::ToUTF8String(dao.getTzAppId()); + AppManagerWrapperSingleton::Instance().setCurrentAppId(tzAppId); + + TIME_TRACER_INIT(); + WrtAccessSingleton::Instance().initialize(widgetId); + } Catch(WrtDeviceApis::Commons::Exception) { + LoggerE("WrtAccess initialization failed"); + } +} + +void on_widget_stop_callback(int widgetId) { + LoggerD("[Tizen1_0\\Application] on_widget_stop_callback ("<<widgetId<<")"); + Try { + char buf[30]; + sprintf(buf,"Application.%d",getpid()); + TIME_TRACER_EXPORT_REPORT_TO(TIME_TRACER_EXPORT_FILE,buf); + TIME_TRACER_RELEASE(); + WrtAccessSingleton::Instance().deinitialize(widgetId); + } Catch(WrtDeviceApis::Commons::Exception) { + LoggerE("WrtAccess deinitialization failed"); + } +} + +void on_frame_load_callback(const void * context) +{ + LoggerD("[Tizen\\application] on_frame_load_callback (" << context << ")"); +} + +void on_frame_unload_callback(const void * context) +{ + LoggerD("[Tizen\\application] on_frame_unload_callback (" << context << ")"); + + DeviceAPI::Application::ApplicationAsyncCallbackManagerSingleton::Instance().unregisterContext(static_cast<JSContextRef>(context)); + DeviceAPI::Application::ApplicationListenerManagerSingleton::Instance().unregisterContext(static_cast<JSContextRef>(context)); +} + +PLUGIN_ON_WIDGET_START(on_widget_start_callback) +PLUGIN_ON_WIDGET_STOP(on_widget_stop_callback) +PLUGIN_ON_FRAME_LOAD(on_frame_load_callback) +PLUGIN_ON_FRAME_UNLOAD(on_frame_unload_callback) + +PLUGIN_CLASS_MAP_BEGIN + PLUGIN_CLASS_MAP_ADD_CLASS( + WRT_JS_EXTENSION_OBJECT_TIZEN, + "application", + (js_class_template_getter)DeviceAPI::Application::JSApplicationManager::getClassRef, + NULL) + + PLUGIN_CLASS_MAP_ADD_INTERFACE( + WRT_JS_EXTENSION_OBJECT_TIZEN, + TIZEN_INTERFACE_APPLICATION_CONTROL, + (js_class_template_getter)DeviceAPI::Application::JSApplicationControl::getClassRef, + reinterpret_cast<js_class_constructor_cb_t>(JSApplicationControl::constructor), + &ApplicationOptions) + + PLUGIN_CLASS_MAP_ADD_INTERFACE( + WRT_JS_EXTENSION_OBJECT_TIZEN, + TIZEN_INTERFACE_APPLICATION_CONTROL_DATA, + (js_class_template_getter)DeviceAPI::Application::JSApplicationControlData::getClassRef, + reinterpret_cast<js_class_constructor_cb_t>(JSApplicationControlData::constructor), + &ApplicationOptions) + +PLUGIN_CLASS_MAP_END + +} //Application +} //DeviceAPI + diff --git a/wearable_src/CMakeLists.txt b/wearable_src/CMakeLists.txt new file mode 100755 index 0000000..2a7992b --- /dev/null +++ b/wearable_src/CMakeLists.txt @@ -0,0 +1,51 @@ +# ----------------------------------------------------------------------------- +# Common Module +# ----------------------------------------------------------------------------- +SET(COMMON_TARGET_NAME "wrt-plugins-tizen-common") +SET(COMMON_DESTINATION_NAME "tizen-tizen") + +SET(CMAKE_INSTALL_RPATH + ${CMAKE_INSTALL_RPATH} + ${CMAKE_INSTALL_PREFIX}/${DESTINATION_LIB_PREFIX}/${COMMON_DESTINATION_NAME} +) + +configure_and_install_pkg(wrt-plugins-tizen-common.pc) +add_subdir(Common) + +SET(LIBS_COMMON + ${LIBS_COMMON} + ${COMMON_TARGET_NAME} +) + +IF(ENABLE_TIME_TRACER) +add_subdir(Common/TimeTracer) + +SET(LIBS_COMMON + ${LIBS_COMMON} + "timetracer" +) + +ENDIF(ENABLE_TIME_TRACER) + +SET(LIBS_TEST + ${LIBS_COMMON} + "standaloneconsole" +) + +# ----------------------------------------------------------------------------- +# Plugin Modules +# ----------------------------------------------------------------------------- + +add_plugin( + Tizen + Alarm + Application + Content + Filesystem + Package + Power + Systeminfo + TimeUtil + Sensor + HumanActivityMonitor +) diff --git a/wearable_src/Common/ArgumentValidator.cpp b/wearable_src/Common/ArgumentValidator.cpp new file mode 100755 index 0000000..62c5e20 --- /dev/null +++ b/wearable_src/Common/ArgumentValidator.cpp @@ -0,0 +1,317 @@ +// +// Tizen Web Device API +// Copyright (c) 2013 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "ArgumentValidator.h" +#include "PlatformException.h" +#include "JSUtil.h" +#include <CommonsJavaScript/Converter.h> + +#include <limits> +#include <dlog.h> +#include <math.h> +#include <stdarg.h> + +using namespace std; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::Commons; + + +namespace DeviceAPI { +namespace Common{ + +ArgumentValidator::ArgumentValidator(JSContextRef ctx, int argc, const JSValueRef* argv):mContext(ctx),mArgc(argc), mArgv(argv){ +} + +ArgumentValidator::~ArgumentValidator(){ +} + +JSValueRef ArgumentValidator::getArgument(int index, bool nullable) const{ + if( index < mArgc ){ + return mArgv[index]; + } + + JSValueRef value = NULL; + if( nullable ) + value = JSValueMakeNull(mContext); + else + value = JSValueMakeUndefined(mContext); + return value; +} + +bool ArgumentValidator::isOmitted(int index){ + if( index < mArgc) + return false; + return true; +} +bool ArgumentValidator::isNull(int index){ + if( !isOmitted(index) && JSValueIsNull(mContext, mArgv[index]) ){ + return true; + } + return false; +} +bool ArgumentValidator::isUndefined(int index){ + if( !isOmitted(index) && JSValueIsUndefined(mContext, mArgv[index]) ){ + return true; + } + return false; +} + +double ArgumentValidator::toNumber(int index, bool nullable, double defaultvalue) const{ + JSValueRef value = getArgument(index, nullable); + if( JSValueIsNull(mContext, value) && nullable){ + return defaultvalue; + } + return JSUtil::JSValueToNumber(mContext, value); +} + +short ArgumentValidator::toShort(int index, bool nullable, short defaultvalue) const{ + return static_cast<short>(toLong(index,nullable,defaultvalue)); +} + +long ArgumentValidator::toLong(int index, bool nullable, long defaultvalue) const{ + return static_cast<long>(toLongLong(index,nullable,defaultvalue)); +} + +signed char ArgumentValidator::toByte(int index, bool nullable, signed char defaultvalue) const{ + return static_cast<signed char>(toLong(index,nullable,defaultvalue)); +} + +unsigned char ArgumentValidator::toOctet(int index, bool nullable, unsigned char defaultvalue) const{ + return static_cast<unsigned char>(toULong(index,nullable,defaultvalue)); +} + +unsigned short ArgumentValidator::toUShort(int index, bool nullable, unsigned short defaultvalue) const{ + return static_cast<unsigned short>(toULong(index,nullable,defaultvalue)); +} + +unsigned long ArgumentValidator::toULong(int index, bool nullable, unsigned long defaultvalue) const{ + return static_cast<unsigned long>(toLongLong(index,nullable,defaultvalue)); +} + +long long ArgumentValidator::toLongLong(int index, bool nullable, long long defaultvalue) const{ + return static_cast<long long>(toNumber(index,nullable,defaultvalue)); +} + +unsigned long long ArgumentValidator::toULongLong(int index, bool nullable, unsigned long long defaultvalue) const{ + return static_cast<unsigned long long>(toLongLong(index,nullable,defaultvalue)); +} + +double ArgumentValidator::toDouble(int index, bool nullable, double defaultvalue) const{ + JSValueRef value = getArgument(index, nullable); + if( JSValueIsNull(mContext, value) && nullable){ + return defaultvalue; + } + return JSUtil::JSValueToDouble(mContext, value); +} + +std::string ArgumentValidator::toString(int index, bool nullable, const string & defaultvalue) const{ + JSValueRef value = getArgument(index, nullable); + if( JSValueIsNull(mContext, value) && nullable){ + return defaultvalue; + } + + std::string result; + + JSValueRef exception = NULL; + JSStringRef str = JSValueToStringCopy(mContext, value, &exception); + if (exception != NULL) { + throw TypeMismatchException(mContext, exception); + } + size_t jsSize = JSStringGetMaximumUTF8CStringSize(str); + { + char buffer[jsSize]; + JSStringGetUTF8CString(str, buffer, jsSize); + result = buffer; + } + JSStringRelease(str); + return result; +} + +bool ArgumentValidator::toBool(int index, bool nullable, bool defaultvalue) const{ + JSValueRef value = getArgument(index, nullable); + if( JSValueIsNull(mContext, value) && nullable){ + return defaultvalue; + } + bool boolvalue = JSValueToBoolean(mContext, value); + return boolvalue; +} + +time_t ArgumentValidator::toTimeT(int index, bool nullable, time_t defaultvalue) const{ + JSValueRef value = getArgument(index, nullable); + if( JSValueIsNull(mContext, value) && nullable){ + return defaultvalue; + } + return JSUtil::JSValueToTimeT(mContext, value); +} + +JSObjectRef ArgumentValidator::toObject(int index, bool nullable) const{ + JSValueRef value = getArgument(index, nullable); + if( JSValueIsNull(mContext, value) && nullable){ + return NULL; + } + if( !JSValueIsObject(mContext, value) ){ + throw TypeMismatchException("Value is not Object"); + } + + JSValueRef exception = NULL; + JSObjectRef object = JSValueToObject(mContext, value, &exception); + if( exception ){ + throw TypeMismatchException(mContext, exception); + } + return object; +} + +JSObjectRef ArgumentValidator::toObject(int index, JSClassRef info, bool nullable) const{ + JSObjectRef obj = toObject(index, nullable); + if( obj == NULL ) + return NULL; + if( !JSValueIsObjectOfClass( mContext, obj, info) ){ + throw TypeMismatchException("Value is not correct type"); + } + return obj; +} + +JSValueRef ArgumentValidator::toJSValueRef(int index, bool nullable) const{ + return getArgument(index, nullable); +} + +JSObjectRef ArgumentValidator::toFunction(int index, bool nullable) const{ + JSObjectRef obj = toObject(index, nullable); + if( obj == NULL && nullable){ + return NULL; + } + if( !JSObjectIsFunction( mContext, obj )){ + throw TypeMismatchException("Value is not function"); + } + return obj; +} + +JSObjectRef ArgumentValidator::toArrayObject(int index, bool nullable) const{ + JSValueRef value = getArgument(index, nullable); + if( JSValueIsNull(mContext, value) && nullable){ + return NULL; + } + + if( !JSIsArrayValue(mContext, value)){ + throw TypeMismatchException("Type is not Array"); + } + + JSValueRef exception = NULL; + JSObjectRef obj = JSValueToObject(mContext, value, &exception); + if( exception != NULL ) + throw TypeMismatchException(mContext, exception); + return obj; +} + + +std::vector<std::string> ArgumentValidator::toStringVector(int index, bool nullable) const{ + JSObjectRef value = toArrayObject(index, nullable); + if( value == NULL || JSValueIsNull(mContext, value) ){ + return std::vector<std::string>(); + } + return JSUtil::JSArrayToStringVector(mContext, value); +} + +std::vector<long> ArgumentValidator::toLongVector(int index, bool nullable) const{ + JSObjectRef value = toArrayObject(index, nullable); + if( value == NULL || JSValueIsNull(mContext, value) ){ + return std::vector<long>(); + } + return JSUtil::JSArrayToLongVector(mContext, value); +} + + +std::vector<double> ArgumentValidator::toDoubleVector(int index, bool nullable) const{ + JSObjectRef value = toArrayObject(index, nullable); + if( value == NULL || JSValueIsNull(mContext, value) ){ + return std::vector<double>(); + } + return JSUtil::JSArrayToDoubleVector(mContext, value); +} + +std::vector<time_t> ArgumentValidator::toTimeTVector(int index, bool nullable) const{ + JSObjectRef value = toArrayObject(index, nullable); + if( value == NULL || JSValueIsNull(mContext, value) ){ + return std::vector<time_t>(); + } + return JSUtil::JSArrayToTimeTVector(mContext, value); +} + +std::vector<bool> ArgumentValidator::toBoolVector(int index, bool nullable) const{ + JSObjectRef value = toArrayObject(index, nullable); + if( value == NULL || JSValueIsNull(mContext, value) ){ + return std::vector<bool>(); + } + return JSUtil::JSArrayToBoolVector(mContext, value); +} + +std::vector<JSValueRef> ArgumentValidator::toJSValueRefVector(int index, bool nullable) const{ + JSObjectRef value = toArrayObject(index, nullable); + if( value == NULL || JSValueIsNull(mContext, value) ){ + return std::vector<JSValueRef>(); + } + + std::vector<JSValueRef> result; + for (std::size_t i = 0; i < JSGetArrayLength(mContext, value); ++i) { + JSValueRef element = JSGetArrayElement(mContext, value, i); + result.push_back(element); + } + return result; +} + +std::map<std::string, std::string> ArgumentValidator::toStringMap(int index, bool nullable) const{ + JSObjectRef value = toObject(index, nullable); + if( value == NULL || JSValueIsNull(mContext, value) ){ + return std::map<std::string, std::string>(); + } + + return JSUtil::JSValueToStringMap(mContext, value); +} + +JSObjectRef ArgumentValidator::toCallbackObject(int index, bool nullable, const char *callback, ...) const{ + JSObjectRef obj = toObject(index, nullable); + if( obj == NULL ){ + if( nullable ){ + return NULL; + } + throw TypeMismatchException("Value is not Object"); + } + va_list var_args; + va_start (var_args, callback); + const char * check = callback; + while( check != NULL ){ + JSStringRef propertyName = JSStringCreateWithUTF8CString(check); + bool has = JSObjectHasProperty(mContext, obj, propertyName); + JSStringRelease(propertyName); + if( has ){ + JSObjectRef o = JSUtil::JSValueToObject(mContext, JSUtil::getProperty(mContext, obj, check)); + if( !JSObjectIsFunction(mContext, o) ){ + va_end(var_args); + throw TypeMismatchException("Property is not function object"); + } + } + check = static_cast<const char *>(va_arg(var_args, const char *)); + } + va_end(var_args); + return obj; +} + + + +} +} diff --git a/wearable_src/Common/ArgumentValidator.h b/wearable_src/Common/ArgumentValidator.h new file mode 100755 index 0000000..33ed114 --- /dev/null +++ b/wearable_src/Common/ArgumentValidator.h @@ -0,0 +1,82 @@ +// +// Tizen Web Device API +// Copyright (c) 2013 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _ARGUMENT_VALIDATOR_H_ +#define _ARGUMENT_VALIDATOR_H_ + +#include <string> +#include <vector> +#include <map> +#include <JavaScriptCore/JavaScript.h> +#include <ctime> + +namespace DeviceAPI { +namespace Common{ + +class ArgumentValidator{ +public: + ArgumentValidator(JSContextRef ctx, int argc, const JSValueRef* argv); + ~ArgumentValidator(); + + double toNumber(int index, bool nullable = false, double defaultvalue = 0.0) const; + short toShort(int index, bool nullable = false, short defaultvalue = 0) const; + unsigned short toUShort(int index, bool nullable = false, unsigned short defaultvalue = 0) const; + long toLong(int index, bool nullable = false, long defaultvalue = 0) const; + unsigned long toULong(int index, bool nullable = false, unsigned long defaultvalue = 0) const; + long long toLongLong(int index, bool nullable = false, long long defaultvalue = 0) const; + unsigned long long toULongLong(int index, bool nullable = false, unsigned long long defaultvalue = 0) const; + double toDouble(int index, bool nullable = false, double defaultvalue = 0.0) const; + signed char toByte(int index, bool nullable = false, signed char defaultvalue = 0) const; + unsigned char toOctet(int index, bool nullable = false, unsigned char defaultvalue = 0) const; + std::string toString(int index, bool nullable = false, const std::string& defaultvalue = "") const; + bool toBool(int index, bool nullable = false, bool defaultvalue = false) const; + time_t toTimeT(int index, bool nullable = false, time_t defaultvalue = 0) const; + JSObjectRef toObject(int index, bool nullable = false) const; + JSObjectRef toObject(int index, JSClassRef info, bool nullable = false) const; + JSObjectRef toFunction(int index, bool nullable = false) const; + JSObjectRef toArrayObject(int index, bool nullable = false) const; + JSValueRef toJSValueRef(int index, bool nullable = false) const; + + bool isOmitted(int index); + bool isNull(int index); + bool isUndefined(int index); + + JSObjectRef toCallbackObject(int index, bool nullable, const char *callback, ...) const; + + std::vector<std::string> toStringVector(int index, bool nullable = false) const; + std::vector<long> toLongVector(int index, bool nullable = false) const; + std::vector<double> toDoubleVector(int index, bool nullable = false) const; + std::vector<time_t> toTimeTVector(int index, bool nullable = false) const; + std::vector<bool> toBoolVector(int index, bool nullable = false) const; + std::vector<JSValueRef> toJSValueRefVector(int index, bool nullable= false) const; + + std::map<std::string, std::string> toStringMap(int index, bool nullable = false) const; + +private: + JSValueRef getArgument(int index, bool nullable) const; + JSContextRef mContext; + int mArgc; + const JSValueRef* mArgv; + +}; + +} +} + +#endif //_ARGUMENT_VALIDATOR_H_ + + diff --git a/wearable_src/Common/AsyncCallbackManager.h b/wearable_src/Common/AsyncCallbackManager.h new file mode 100644 index 0000000..e2427f5 --- /dev/null +++ b/wearable_src/Common/AsyncCallbackManager.h @@ -0,0 +1,98 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 AsyncCallbackManager.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _TIZEN_COMMONS_ASYNC_CALLBACK_MANAGER_H_ +#define _TIZEN_COMMONS_ASYNC_CALLBACK_MANAGER_H_ + +#include <dpl/shared_ptr.h> +#include <dpl/type_list.h> +#include <CommonsJavaScript/JSCallbackManager.h> +#include "Singleton.h" +#include "Export.h" +#include "Logger.h" + +namespace DeviceAPI { +namespace Common { + +class AsyncCallbackManager +{ +public: + typedef std::map<WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr, JSContextRef> JSCallbackManagerMap; + typedef typename JSCallbackManagerMap::iterator JSCallbackManagerMapIter; + typedef std::pair<WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr,JSContextRef> JSCallbackManagerPair; + + AsyncCallbackManager() + { + }; + + virtual ~AsyncCallbackManager() + { + m_map.clear(); + }; + + virtual void registerCallbackManager(WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr &cbm, const JSContextRef context) + { + LoggerD("Registering an callback manager on context:" << context); + m_map.insert(JSCallbackManagerPair(cbm, context)); + } + + virtual void unregisterContext(const JSContextRef context) + { + LoggerD("Unregistering all callback managers on context:" << context); + for(JSCallbackManagerMapIter i=m_map.begin(); i!=m_map.end(); i++) + { + if(i->second == context) + { + LoggerD("unregister a callback manager"); + i->first->setOnSuccess(NULL); + i->first->setOnError(NULL); + // This function does not remove cbm from multimap. + // It only prohibit plugin invoke javascript callback. + } + } + } + + virtual void unregisterCallbackManager(const WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr &cbm) + { + LoggerD("Unregistering an callback manager"); + JSCallbackManagerMapIter i = m_map.find(cbm); + + if(i == m_map.end()) + { + LoggerW("nothing to unregister"); + // Something wrong + return; + } + + m_map.erase(i); + } + +private: + JSCallbackManagerMap m_map; +}; + +} // Common +} // DeviceAPI + +#endif // _TIZEN_COMMONS_ASYNC_CALLBACK_MANAGER_H_ diff --git a/wearable_src/Common/CMakeLists.txt b/wearable_src/Common/CMakeLists.txt new file mode 100755 index 0000000..e0d7704 --- /dev/null +++ b/wearable_src/Common/CMakeLists.txt @@ -0,0 +1,29 @@ +SET(SRCS + CallbackUserData.cpp + GlobalContextManager.cpp + ArgumentValidator.cpp + JSUtil.cpp + PlatformException.cpp + MultiCallbackUserData.cpp + JSFunctionWrapper.cpp + JSObjectRefWrapper.cpp + JSStringRefWrapper.cpp + JSWebAPIErrorFactory.cpp + JSWebAPIError.cpp + JSWebAPIException.cpp + WebAPIError.cpp + PropertyBag.cpp + JSArray.cpp +) + +ADD_LIBRARY(${COMMON_TARGET_NAME} SHARED ${SRCS}) + +TARGET_LINK_LIBRARIES(${COMMON_TARGET_NAME} + ${LIBS_COMMON} +) + +INSTALL(TARGETS ${COMMON_TARGET_NAME} LIBRARY DESTINATION ${DESTINATION_LIB_PREFIX}/${COMMON_DESTINATION_NAME}) +INSTALL( + DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/ DESTINATION ${DESTINATION_HEADER_PREFIX}/common + FILES_MATCHING PATTERN "*.h" PATTERN "CMakeFiles" EXCLUDE +) diff --git a/wearable_src/Common/CallbackUserData.cpp b/wearable_src/Common/CallbackUserData.cpp new file mode 100755 index 0000000..7fc818f --- /dev/null +++ b/wearable_src/Common/CallbackUserData.cpp @@ -0,0 +1,96 @@ +// +// Tizen Web Device API +// Copyright (c) 2013 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "CallbackUserData.h" +#include "MultiCallbackUserData.h" +#include <stdarg.h> + +using namespace std; + +namespace DeviceAPI { +namespace Common { + +CallbackUserData::CallbackUserData(JSContextRef globalCtx): mContext(globalCtx), mImpl(NULL){ + mImpl = new MultiCallbackUserData(globalCtx); +} + +CallbackUserData::~CallbackUserData(){ + MultiCallbackUserData * impl = static_cast<MultiCallbackUserData*>(mImpl); + if( impl ) + delete impl; + mImpl = NULL; +} + +void CallbackUserData::setSuccessCallback(JSValueRef onSuccess){ + MultiCallbackUserData * impl = static_cast<MultiCallbackUserData*>(mImpl); + + if( onSuccess && JSValueIsObject(mContext, onSuccess) ){ + JSObjectRef success = JSValueToObject(mContext, onSuccess, NULL); + impl->setCallback("success", success); + } +} + +void CallbackUserData::setErrorCallback(JSValueRef onError){ + MultiCallbackUserData * impl = static_cast<MultiCallbackUserData*>(mImpl); + + if( onError && JSValueIsObject(mContext, onError) ){ + JSObjectRef error = JSValueToObject(mContext, onError, NULL); + impl->setCallback("error", error); + } +} + +void CallbackUserData::callSuccessCallback(int count, JSValueRef obj [ ]){ + MultiCallbackUserData * impl = static_cast<MultiCallbackUserData*>(mImpl); + impl->invokeCallback("success", count, obj); +} + +void CallbackUserData::callSuccessCallback(JSValueRef obj){ + JSValueRef args[1] = {obj}; + callSuccessCallback(1, args); +} + +void CallbackUserData::callSuccessCallback(){ + callSuccessCallback(0, NULL); +} + +void CallbackUserData::callErrorCallback(int count, JSValueRef obj [ ]){ + MultiCallbackUserData * impl = static_cast<MultiCallbackUserData*>(mImpl); + impl->invokeCallback("error", count, obj); +} + +void CallbackUserData::callErrorCallback(JSValueRef obj){ + JSValueRef args[1] = {obj}; + callErrorCallback(1, args); +} + +void CallbackUserData::callErrorCallback(){ + callErrorCallback(0, NULL); +} + +void CallbackUserData::cleanContext(){ + MultiCallbackUserData * impl = static_cast<MultiCallbackUserData*>(mImpl); + mContext = NULL; + impl->cleanContext(); +} + + +JSContextRef CallbackUserData::getContext(){ + return mContext; +} + +} +} diff --git a/wearable_src/Common/CallbackUserData.h b/wearable_src/Common/CallbackUserData.h new file mode 100755 index 0000000..8d73e47 --- /dev/null +++ b/wearable_src/Common/CallbackUserData.h @@ -0,0 +1,55 @@ +// +// Tizen Web Device API +// Copyright (c) 2013 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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_TIZEN_CALLBACKUSERDATA_ +#define _WRTPLUGINS_TIZEN_CALLBACKUSERDATA_ + +#include <JavaScriptCore/JavaScript.h> + +namespace DeviceAPI { +namespace Common{ + +class CallbackUserData{ + public: + CallbackUserData(JSContextRef globalCtx); + virtual ~CallbackUserData(); + JSContextRef getContext(); + void setSuccessCallback(JSValueRef onSuccess); + void setErrorCallback(JSValueRef onError); + + void callSuccessCallback(); + void callSuccessCallback(JSValueRef obj); + void callSuccessCallback(int count, JSValueRef obj[]); + + void callErrorCallback(); + void callErrorCallback(JSValueRef obj); + void callErrorCallback(int count, JSValueRef obj[]); + + void cleanContext(); + + private: + JSContextRef mContext; + void *mImpl; + +}; + + +} +} + +#endif //_TIZEN_COMMON_CALLBACKUSERDATA_ + diff --git a/wearable_src/Common/Export.h b/wearable_src/Common/Export.h new file mode 100644 index 0000000..44afafc --- /dev/null +++ b/wearable_src/Common/Export.h @@ -0,0 +1,29 @@ +// +// Tizen Web Device API +// Copyright (c) 2013 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 __TIZEN_EXPORT_H__ +#define __TIZEN_EXPORT_H__ + +#if defined(__GNUC__) && __GNUC__ >= 4 + #define DLL_EXPORT __attribute__((visibility("default"))) + #define DLL_LOCAL __attribute__((visibility("hidden"))) +#else + #define DLL_EXPORT + #define DLL_LOCAL +#endif + +#endif // __TIZEN_EXPORT_H__ diff --git a/wearable_src/Common/GlobalContextManager.cpp b/wearable_src/Common/GlobalContextManager.cpp new file mode 100644 index 0000000..e949d14 --- /dev/null +++ b/wearable_src/Common/GlobalContextManager.cpp @@ -0,0 +1,88 @@ +// +// Tizen Web Device API +// Copyright (c) 2013 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "GlobalContextManager.h" +#include "Logger.h" + +using namespace std; + +namespace DeviceAPI { +namespace Common{ + +GlobalContextManager::GlobalContextManager(){ +} + +GlobalContextManager* GlobalContextManager::getInstance(){ + static GlobalContextManager instance; + return &instance; +} + +JSContextRef GlobalContextManager::getGlobalContext(JSContextRef ctx){ + if( ctx == NULL ){ + LoggerE("local context is NULL"); + return NULL; + } + JSObjectRef global = JSContextGetGlobalObject(ctx); + ContextMapT::iterator itr; + itr = mContexts.find(global); + if( itr == mContexts.end() ){ + LoggerE("Can not found global Context"); + return NULL; + } + return itr->second; +} + +bool GlobalContextManager::isAliveGlobalContext(JSContextRef ctx){ + if( ctx == NULL ) + return false; + + JSContextRef context = getGlobalContext(ctx); + + if( context == ctx ) + return true; + else + return false; +} + +void GlobalContextManager::addGlobalContext(JSContextRef ctx){ + ContextMapT::iterator itr; + JSObjectRef global = JSContextGetGlobalObject(ctx); + itr = mContexts.find(global); + if( itr != mContexts.end() ){ + LoggerD("already added global context"); + return; + } + mContexts[global] = ctx; +} + +void GlobalContextManager::removeGlobalContext(JSContextRef ctx){ + ContextMapT::iterator itr; + JSObjectRef global = JSContextGetGlobalObject(ctx); + itr = mContexts.find(global); + if( itr == mContexts.end() ){ + LoggerD("does not exist context"); + return; + } + if( itr->second == ctx ) + mContexts.erase(itr); + else + LoggerE("passed context is not global context"); +} + +} +} + diff --git a/wearable_src/Common/GlobalContextManager.h b/wearable_src/Common/GlobalContextManager.h new file mode 100644 index 0000000..40f8f8e --- /dev/null +++ b/wearable_src/Common/GlobalContextManager.h @@ -0,0 +1,78 @@ +// +// Tizen Web Device API +// Copyright (c) 2013 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _TIZEN_COMMON_GLOBALCONTEXTMANAGER_ +#define _TIZEN_COMMON_GLOBALCONTEXTMANAGER_ + +#include <JavaScriptCore/JavaScript.h> +#include <map> + +namespace DeviceAPI { +namespace Common{ + + +/** + * @brief Manage and tracking global context handle + */ +class GlobalContextManager{ + public : + /** + * @breif Gets global context from local context + * + * @param ctx local context + * @return The global context reference or NULL if function has failed + */ + JSContextRef getGlobalContext(JSContextRef ctx); + + /** + * @breif Add global context in manager + * + * @param ctx The global context to add + */ + void addGlobalContext(JSContextRef ctx); + + /** + * @breif Remove global context in manager + * + * @param ctx The global context to remove + */ + void removeGlobalContext(JSContextRef ctx); + + /** + * @breif Check the validation of global context + * + * @param ctx The global context to check + * @return true : the global context is alive, false : the global context was released + */ + bool isAliveGlobalContext(JSContextRef ctx); + + /** + * @breif Gets singletone handle + * + * @return GlobalContextManager handle + */ + static GlobalContextManager* getInstance(); + + private: + GlobalContextManager(); + typedef std::map<JSObjectRef, JSContextRef> ContextMapT; + std::map<JSObjectRef, JSContextRef> mContexts; +}; + +} +} +#endif //_TIZEN_COMMON_GLOBALCONTEXTMANAGER_ diff --git a/wearable_src/Common/IListenerManager.h b/wearable_src/Common/IListenerManager.h new file mode 100644 index 0000000..bf8aad6 --- /dev/null +++ b/wearable_src/Common/IListenerManager.h @@ -0,0 +1,157 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 IListenerManager.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _TIZEN_COMMONS_ILISTENER_MANAGER_H_ +#define _TIZEN_COMMONS_ILISTENER_MANAGER_H_ + +#include <map> +#include <JavaScriptCore/JavaScript.h> +#include <dpl/shared_ptr.h> +#include "Singleton.h" +#include "Export.h" +#include "Logger.h" + +namespace DeviceAPI { +namespace Common { + +class IListenerItem; +typedef DPL::SharedPtr<IListenerItem> IListenerItemPtr; + +class IListenerItem +{ +public: + IListenerItem(JSContextRef context, JSObjectRef object, long watchId) : + m_context(context), + m_object(object), + m_watchId(watchId) + { + } + + virtual ~IListenerItem() + { + } + + virtual void protectObject() + { + LoggerD("Protect object:" << m_object); + + JSValueProtect(m_context, m_object); + } + + virtual void unprotectObject() + { + LoggerD("Unprotect object:" << m_object); + + JSValueUnprotect(m_context, m_object); + } + + virtual void cancelListener() + { + LoggerW("IListenerItem MUST be used as an inherited shape."); + LoggerW("If this log has been printed, it must be used with wrong usage."); + } + + virtual bool equal(const DeviceAPI::Common::IListenerItemPtr &other) const + { + if(!other) + return false; + + if(m_object == other->m_object && m_watchId == other->m_watchId) + return true; + + return false; + } + +protected: + JSContextRef m_context; + JSObjectRef m_object; + long m_watchId; +}; + +class IListenerController +{ +public: + typedef std::multimap<JSContextRef, IListenerItemPtr> ListenerMap; + typedef typename ListenerMap::iterator ListenerMapIter; + typedef std::pair<JSContextRef, IListenerItemPtr> ListenerPair; + typedef std::pair<ListenerMapIter, ListenerMapIter> ListenerMapIterPair; + + IListenerController() + { + } + + virtual ~IListenerController() + { + } + + virtual void registerListener(IListenerItemPtr &canceller, const JSContextRef context) + { + LoggerD("Registering a listener on context:" << context); + + canceller->protectObject(); + m_map.insert(ListenerPair(context, canceller)); + } + + virtual void unregisterContext(const JSContextRef context) + { + LoggerD("Unregistering all listeners on context:" << context); + + ListenerMapIterPair iterPair = m_map.equal_range(context); + + for(ListenerMapIter i=iterPair.first; i!=iterPair.second; i++) + { + LoggerD("Unregistering a listener"); + i->second->cancelListener(); + i->second->unprotectObject(); + } + + m_map.erase(context); + } + + virtual void unregisterListener(const IListenerItemPtr &canceller) + { + LoggerD("Unregistering a listener"); + + for(ListenerMapIter i=m_map.begin(); i!=m_map.end(); i++) + { + if(i->second->equal(canceller)) + { + LoggerD("Found object"); + i->second->unprotectObject(); + + m_map.erase(i); + + break; + } + } + } + +private: + ListenerMap m_map; +}; + +} // Common +} // DeviceAPI + +#endif // _TIZEN_COMMONS_ILISTENER_MANAGER_H_ diff --git a/wearable_src/Common/JSArray.cpp b/wearable_src/Common/JSArray.cpp new file mode 100755 index 0000000..cd386da --- /dev/null +++ b/wearable_src/Common/JSArray.cpp @@ -0,0 +1,48 @@ +#include "JSArray.h" +#include "PlatformException.h" + +namespace DeviceAPI { +namespace Common { + +JSArrayBase::JSArrayBase( JSContextRef context, JSObjectRef array ):mContext(context), mArray(array){ + if(!JSIsArrayValue(context, array)){ + throw TypeMismatchException("The type is not array"); + } + JSValueProtect(context, array); +} + +JSArrayBase::JSArrayBase( JSContextRef context):mContext(context){ + JSValueRef exception = NULL; + mArray = JSObjectMakeArray( context, 0, NULL, &exception); + if(exception != NULL){ + throw UnknownException(context, exception); + } +} + +JSArrayBase::~JSArrayBase(){ + JSValueUnprotect(mContext, mArray); +} + +size_t JSArrayBase::size() const { + return JSGetArrayLength(mContext, mArray); +} + +void JSArrayBase::resize(size_t size){ + JSUtil::setProperty(mContext, mArray, "length", JSUtil::toJSValueRef(mContext, static_cast<double>(size)), kJSPropertyAttributeNone, NULL); +} + +JSValueRef JSArrayBase::get(int index) const{ + return JSGetArrayElement(mContext, mArray, index); +} + +bool JSArrayBase::set( int index, JSValueRef value){ + bool t = JSSetArrayElement(mContext, mArray, index, value); + return t; +} + +bool JSArrayBase::append( JSValueRef value ){ + return set( size(), value); +} + +}//Common +}//DeviceAPI diff --git a/wearable_src/Common/JSArray.h b/wearable_src/Common/JSArray.h new file mode 100755 index 0000000..c27ca21 --- /dev/null +++ b/wearable_src/Common/JSArray.h @@ -0,0 +1,171 @@ +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 __TIZEN_COMMON_JSARRAY_H__ +#define __TIZEN_COMMON_JSARRAY_H__ +#include <JavaScriptCore/JavaScript.h> +#include <vector> +#include "JSUtil.h" + +namespace DeviceAPI { +namespace Common { + +class JSArrayBase{ +public: + JSArrayBase( JSContextRef context, JSObjectRef array ); + JSArrayBase( JSContextRef context ); + + virtual ~JSArrayBase(); + size_t size() const; + void resize(size_t size); + JSValueRef get(int index) const; + bool set(int index, JSValueRef value); + bool append(JSValueRef value); + +protected: + JSContextRef mContext; + JSObjectRef mArray; +}; + + +template <typename T> +class JSArray : protected JSArrayBase{ + friend class ItemProxy; +public: + typedef JSValueRef (*ToJSFunction)(JSContextRef, T); + typedef T (*ToNativeFunction)(JSContextRef, JSValueRef ); + + + JSArray( JSContextRef context, JSObjectRef array, ToNativeFunction nativefun, ToJSFunction jsfun) + :JSArrayBase(context,array),mToNative(nativefun), mToJs(jsfun) { + } + JSArray( JSContextRef context, ToNativeFunction nativefun, ToJSFunction jsfun) + :JSArrayBase(context),mToNative(nativefun), mToJs(jsfun) { + } + + ~JSArray(){ + } + + class ItemProxy { + JSArray<T> *mArray; + int mIndex; + public: + ItemProxy(JSArray<T>* array, int index):mArray(array), mIndex(index){ + } + operator T(){ + return mArray->mToNative(mArray->mContext, mArray->get(mIndex)); + } + ItemProxy& operator=( const T native){ + JSValueRef v = mArray->mToJs(mArray->mContext, native); + mArray->set(mIndex, v); + return *this; + } + ItemProxy& operator=( const ItemProxy& other){ + JSValueRef v = other.mArray->get(other.mIndex); + mArray->set(mIndex, v); + return *this; + } + + }; + size_t size() const{ + return JSArrayBase::size(); + } + + void resize(size_t size){ + JSArrayBase::resize(size); + } + + bool append( T v){ + return JSArrayBase::set( size(), mToJs(mContext, v)); + } + + ItemProxy operator[]( int index ){ + return ItemProxy(this, index); + } + + operator JSObjectRef(){ + return mArray; + } + + operator std::vector<T>(){ + std::vector<T> v; + size_t length = size(); + for( unsigned int i = 0 ; i < length ; i++){ + JSValueRef t = get(i); + T tmp = mToNative(mContext, t); + v.push_back(tmp); + } + return v; + } + + void operator=( const std::vector<T>& list ){ + overwrite(list); + } + + void operator=( const JSArray<T>& rhs){ + resize(rhs.size()); + for(unsigned int i = 0 ; i < rhs.size(); i++){ + set(i, rhs.get(i)); + } + } + +protected: + void overwrite( const std::vector<T>& list ){ + unsigned int i; + unsigned int listSize = list.size(); + resize(listSize); + for( i = 0 ; i < listSize ; i++){ + JSValueRef v = mToJs(mContext, list[i]); + set(i, v); + } + } + + + + +private: + ToNativeFunction mToNative; + ToJSFunction mToJs; +}; + + +class JSStringArray : public JSArray<std::string>{ + static JSValueRef makeJSValue(JSContextRef ctx, std::string v){ + return JSUtil::toJSValueRef(ctx, v); + } + public: + JSStringArray(JSContextRef ctx, JSObjectRef array): JSArray<std::string>(ctx, array, JSUtil::JSValueToString, makeJSValue){} + JSStringArray(JSContextRef ctx): JSArray<std::string>(ctx, JSUtil::JSValueToString, makeJSValue){} + void operator=( const std::vector<std::string>& list ){overwrite(list);} +}; + + +class JSLongArray : public JSArray<long>{ + static JSValueRef makeJSValue(JSContextRef ctx, long v){ + return JSUtil::toJSValueRef(ctx, v); + } + public: + JSLongArray(JSContextRef ctx, JSObjectRef array): JSArray<long>(ctx, array, JSUtil::JSValueToLong, makeJSValue){} + JSLongArray(JSContextRef ctx): JSArray<long>(ctx, JSUtil::JSValueToLong, makeJSValue){} + void operator=( const std::vector<long>& list ){overwrite(list);} + +}; + + + + +} +} +#endif //__TIZEN_COMMON_JSARRAY_H__ + diff --git a/wearable_src/Common/JSFunctionWrapper.cpp b/wearable_src/Common/JSFunctionWrapper.cpp new file mode 100644 index 0000000..7c68bcd --- /dev/null +++ b/wearable_src/Common/JSFunctionWrapper.cpp @@ -0,0 +1,136 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "JSFunctionWrapper.h" + +#include "Logger.h" + +namespace DeviceAPI { +namespace Common { + +JSFunctionWrapper::JSFunctionWrapper(JSContextRef context, JSValueRef function, JSObjectRef thisObject) : + m_context(context), + m_function(function), + m_thisObject(thisObject) +{ + if(m_function) + JSValueProtect(m_context, m_function); +} + +JSFunctionWrapper::~JSFunctionWrapper() +{ + if(m_function) + JSValueUnprotect(m_context, m_function); +} + +void JSFunctionWrapper::setFunction(const JSValueRef value) +{ + if(m_function) + JSValueUnprotect(m_context, m_function); + + m_function = value; + + if(m_function) + JSValueProtect(m_context, m_function); +} + +JSValueRef JSFunctionWrapper::getFunction() const +{ + return m_function; +} + +void JSFunctionWrapper::setThisObject(const JSObjectRef thisObject) +{ + m_thisObject = thisObject; +} + +JSObjectRef JSFunctionWrapper::getThisObject() const +{ + return m_thisObject; +} + +bool JSFunctionWrapper::invokable() const +{ + if(m_function == NULL) + return false; + + JSValueRef exception = NULL; + + JSObjectRef function = JSValueToObject(m_context, m_function, &exception); + if(exception != NULL) + return false; + + if(!JSObjectIsFunction(m_context, function)) + return false; + + return true; +} + +JSValueRef JSFunctionWrapper::invoke(JSValueRef argv[], unsigned argc) +{ + if(!invokable()) + return NULL; + + JSObjectRef function = JSValueToObject(m_context, m_function, NULL); + + JSValueRef exception = NULL; + + JSValueRef result = JSObjectCallAsFunction(m_context, function, m_thisObject, argc, argv, &exception); + + if(exception != NULL) + return NULL; + + return result; +} + +JSValueRef JSFunctionWrapper::invoke(JSValueRef arg) +{ + if(!invokable()) + return NULL; + + JSObjectRef function = JSValueToObject(m_context, m_function, NULL); + + JSValueRef exception = NULL; + + JSValueRef argv[1] = { arg }; + JSValueRef result = JSObjectCallAsFunction(m_context, function, m_thisObject, 1, argv, &exception); + + if(exception != NULL) + return NULL; + + return result; +} + +JSValueRef JSFunctionWrapper::invoke() +{ + if(!invokable()) + return NULL; + + JSObjectRef function = JSValueToObject(m_context, m_function, NULL); + + JSValueRef exception = NULL; + + JSValueRef result = JSObjectCallAsFunction(m_context, function, m_thisObject, 0, NULL, &exception); + + if(exception != NULL) + return NULL; + + return result; +} + +} // Common +} // DeviceAPI diff --git a/wearable_src/Common/JSFunctionWrapper.h b/wearable_src/Common/JSFunctionWrapper.h new file mode 100644 index 0000000..e60f4bf --- /dev/null +++ b/wearable_src/Common/JSFunctionWrapper.h @@ -0,0 +1,62 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 JSFunctionWrapper.h + * @version 0.1 + * @brief + */ + +#ifndef _JS_FUNCTION_WRAPPER_H_ +#define _JS_FUNCTION_WRAPPER_H_ + +#include <JavaScriptCore/JavaScript.h> + +#include <boost/shared_ptr.hpp> + +namespace DeviceAPI { +namespace Common { + +class JSFunctionWrapper +{ +public: + JSFunctionWrapper(JSContextRef context, JSValueRef function, JSObjectRef thisObject); + virtual ~JSFunctionWrapper(); + + void setFunction(const JSValueRef function); + JSValueRef getFunction() const; + + void setThisObject(const JSObjectRef thisObject); + JSObjectRef getThisObject() const; + + bool invokable() const; + + JSValueRef invoke(JSValueRef argv[], unsigned argc); + JSValueRef invoke(JSValueRef arg); + JSValueRef invoke(); + +private: + JSContextRef m_context; + JSValueRef m_function; + JSObjectRef m_thisObject; // it does not protect thisObject +}; +typedef boost::shared_ptr<JSFunctionWrapper> JSFunctionWrapperPtr; + +} // Common +} // DeviceAPI + +#endif // _JS_FUNCTION_WRAPPER_H_ diff --git a/wearable_src/Common/JSObjectRefWrapper.cpp b/wearable_src/Common/JSObjectRefWrapper.cpp new file mode 100644 index 0000000..705090e --- /dev/null +++ b/wearable_src/Common/JSObjectRefWrapper.cpp @@ -0,0 +1,131 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "JSObjectRefWrapper.h" + +#include <string> +#include <algorithm> + +#include "Logger.h" +#include "PlatformException.h" +#include "JSStringRefWrapper.h" + +namespace DeviceAPI { +namespace Common { + +JSObjectRefWrapper::JSObjectRefWrapper(JSContextRef context, JSObjectRef object) : + m_context(context), + m_object(object), + m_protectCount(0) +{ +} + +JSObjectRefWrapper::~JSObjectRefWrapper() +{ + while(m_protectCount) + unprotect(); +} + +void JSObjectRefWrapper::protect() +{ + JSValueRef jsValue = static_cast<JSValueRef>(m_object); + JSValueProtect(m_context, jsValue); + m_protectCount++; +} + +void JSObjectRefWrapper::unprotect() +{ + if(m_protectCount) + { + JSValueRef jsValue = static_cast<JSValueRef>(m_object); + JSValueUnprotect(m_context, jsValue); + m_protectCount--; + } +} + +JSContextRef JSObjectRefWrapper::getContext() const +{ + return m_context; +} + +JSObjectRef JSObjectRefWrapper::getObject() const +{ + return m_object; +} + +JSValueRef JSObjectRefWrapper::getProperty(const std::string propertyName) const +{ + JSValueRef exception = NULL; + + JSStringRefWrapper jsStrWrapName(propertyName); + JSValueRef jsValueProp = JSObjectGetProperty(m_context, m_object, jsStrWrapName.get(), &exception); + if(exception != NULL) + { + LoggerD("Error occured while getting property '" << propertyName << "' from object."); + throw TypeMismatchException(m_context, exception); + } + + return jsValueProp; +} + +JSObjectRef JSObjectRefWrapper::getPropertyObject(const std::string propertyName) const +{ + JSValueRef exception = NULL; + + JSValueRef jsValueProp = getProperty(propertyName); + + JSObjectRef result = JSValueToObject(m_context, jsValueProp, &exception); + if(exception != NULL) + { + LoggerD("Error occured while converting property '" << propertyName << "' to object."); + throw TypeMismatchException(m_context, exception); + } + + return result; +} + +std::string JSObjectRefWrapper::getPropertyString(const std::string propertyName) const +{ + JSValueRef exception = NULL; + + JSValueRef jsValueProp = getProperty(propertyName); + + JSStringRef jsStrProp = JSValueToStringCopy(m_context, jsValueProp, &exception); + if(exception != NULL) + { + LoggerD("Error occured while converting property '" << propertyName << "' to string."); + throw TypeMismatchException(m_context, exception); + } + + size_t jsStrLenPropId = JSStringGetLength(jsStrProp); + + size_t bufferSize = jsStrLenPropId * 4 + 1; + char * buffer = new char[bufferSize]; + + std::fill(buffer, buffer+bufferSize, 0); + + JSStringGetUTF8CString(jsStrProp, buffer, bufferSize); + + std::string result(buffer); + + delete []buffer; + + return result; +} + +} // Common +} // DeviceAPI diff --git a/wearable_src/Common/JSObjectRefWrapper.h b/wearable_src/Common/JSObjectRefWrapper.h new file mode 100644 index 0000000..d06cb09 --- /dev/null +++ b/wearable_src/Common/JSObjectRefWrapper.h @@ -0,0 +1,64 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 JSObjectRefWrapper.h + * @version 0.1 + * @brief + */ + +#ifndef _JS_OBJECT_REF_WRAPPER_H_ +#define _JS_OBJECT_REF_WRAPPER_H_ + +#include <JavaScriptCore/JavaScript.h> + +#include <string> + +namespace DeviceAPI { +namespace Common { + +class JSObjectRefWrapper +{ +public: + JSObjectRefWrapper(JSContextRef context, JSObjectRef object); + virtual ~JSObjectRefWrapper(); + + JSContextRef getContext() const; + JSObjectRef getObject() const; + +protected: + void protect(); + void unprotect(); + + JSValueRef getProperty(const std::string propertyName) const; + + JSObjectRef getPropertyObject(const std::string propertyName) const; + + std::string getPropertyString(const std::string propertyName) const; + +protected: + JSContextRef m_context; + JSObjectRef m_object; + +private: + int m_protectCount; +}; + +} // Common +} // DeviceAPI + +#endif // _JS_OBJECT_REF_WRAPPER_H_ diff --git a/wearable_src/Common/JSStringRefWrapper.cpp b/wearable_src/Common/JSStringRefWrapper.cpp new file mode 100644 index 0000000..b0aa69c --- /dev/null +++ b/wearable_src/Common/JSStringRefWrapper.cpp @@ -0,0 +1,83 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "JSStringRefWrapper.h" + +namespace DeviceAPI { +namespace Common { + +JSStringRefWrapper::JSStringRefWrapper(JSStringRefWrapper &obj) : m_ref(NULL) +{ + JSStringRef ref = obj.m_ref; + if(ref) + { + const JSChar* chars = JSStringGetCharactersPtr(ref); + size_t numChars = JSStringGetLength(ref); + + m_ref = JSStringCreateWithCharacters(chars, numChars); + } +} + +JSStringRefWrapper::JSStringRefWrapper(JSStringRef ref) : m_ref(ref) +{ +} + +JSStringRefWrapper::JSStringRefWrapper(const std::string str) +{ + m_ref = JSStringCreateWithUTF8CString(str.c_str()); +} + +JSStringRefWrapper::JSStringRefWrapper(const char * str) +{ + m_ref = JSStringCreateWithUTF8CString(str); +} + +JSStringRefWrapper::~JSStringRefWrapper() +{ + if (m_ref != NULL) + JSStringRelease(m_ref); +} + +JSStringRefWrapper & JSStringRefWrapper::operator=(const JSStringRefWrapper &obj) +{ + JSStringRef ref = obj.m_ref; + + if (m_ref != NULL) + JSStringRelease(m_ref); + + if(ref) + { + const JSChar* chars = JSStringGetCharactersPtr(ref); + size_t numChars = JSStringGetLength(ref); + + m_ref = JSStringCreateWithCharacters(chars, numChars); + } + else + { + m_ref = NULL; + } + + return *this; +} + +JSStringRef JSStringRefWrapper::get() const +{ + return m_ref; +} + +} // Common +} // DeviceAPI diff --git a/wearable_src/Common/JSStringRefWrapper.h b/wearable_src/Common/JSStringRefWrapper.h new file mode 100644 index 0000000..f9e9dd5 --- /dev/null +++ b/wearable_src/Common/JSStringRefWrapper.h @@ -0,0 +1,47 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _JS_STRING_REF_WRAPPER_H_ +#define _JS_STRING_REF_WRAPPER_H_ + +#include <string> +#include <JavaScriptCore/JavaScript.h> + +namespace DeviceAPI { +namespace Common { + +class JSStringRefWrapper +{ +public: + JSStringRefWrapper(JSStringRefWrapper &obj); + JSStringRefWrapper(JSStringRef ref); + JSStringRefWrapper(const std::string str); + JSStringRefWrapper(const char * str); + virtual ~JSStringRefWrapper(); + + JSStringRefWrapper & operator=(const JSStringRefWrapper &obj); + + JSStringRef get() const; + +private: + JSStringRef m_ref; +}; + +} // Common +} // DeviceAPI + +#endif // _JS_STRING_REF_WRAPPER_H_ diff --git a/wearable_src/Common/JSUtil.cpp b/wearable_src/Common/JSUtil.cpp new file mode 100755 index 0000000..1404b7c --- /dev/null +++ b/wearable_src/Common/JSUtil.cpp @@ -0,0 +1,349 @@ +// +// Tizen Web Device API +// Copyright (c) 2013 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "JSUtil.h" +#include "PlatformException.h" +#include <cmath> +#include <limits> + + +using namespace std; + +namespace DeviceAPI { +namespace Common{ + +JSValueRef JSUtil::getProperty(JSContextRef ctx , JSObjectRef object, const char *name, JSValueRef *exception){ + JSValueRef value; + JSStringRef propertyName = JSStringCreateWithUTF8CString(name); + JSValueRef localException = NULL; + value = JSObjectGetProperty(ctx, object, propertyName, &localException); + JSStringRelease(propertyName); + + if( localException != NULL ){ + if( exception != NULL ) + *exception = localException; + else + throw TypeMismatchException(ctx,localException); + } + return value; +} + +void JSUtil::setProperty(JSContextRef ctx , JSObjectRef object, const char *name, JSValueRef value, JSPropertyAttributes attributes, JSValueRef *exception){ + JSStringRef propertyName = JSStringCreateWithUTF8CString(name); + JSValueRef localException = NULL; + JSObjectSetProperty(ctx, object, propertyName, value,attributes, &localException); + JSStringRelease(propertyName); + if( localException != NULL ){ + if( exception != NULL ) + *exception = localException; + else + throw TypeMismatchException(ctx,localException); + } +} + +string JSUtil::JSStringToString(JSContextRef ctx, JSStringRef str){ + std::string result; + size_t jsSize = JSStringGetMaximumUTF8CStringSize(str); + { + char buffer[jsSize]; + JSStringGetUTF8CString(str, buffer, jsSize); + result = buffer; + } + return result; +} + +string JSUtil::JSValueToString(JSContextRef ctx, JSValueRef value){ + std::string result; + JSValueRef exception = NULL; + JSStringRef str = JSValueToStringCopy(ctx, value, &exception); + if (exception != NULL) { + throw TypeMismatchException(ctx, exception); + } + size_t jsSize = JSStringGetMaximumUTF8CStringSize(str); + { + char buffer[jsSize]; + JSStringGetUTF8CString(str, buffer, jsSize); + result = buffer; + } + JSStringRelease(str); + return result; +} + +long JSUtil::JSValueToLong(JSContextRef ctx, JSValueRef value){ + return static_cast<long>(JSValueToLongLong(ctx,value)); +} + +unsigned long JSUtil::JSValueToULong(JSContextRef ctx, JSValueRef value){ + return static_cast<unsigned long>(JSValueToLongLong(ctx,value)); +} + +long long JSUtil::JSValueToLongLong(JSContextRef ctx, JSValueRef value){ + return static_cast<long long>(JSValueToNumber(ctx, value)); +} + +unsigned long long JSUtil::JSValueToULongLong(JSContextRef ctx, JSValueRef value){ + return static_cast<unsigned long long>(JSValueToLongLong(ctx,value)); +} + +double JSUtil::JSValueToDouble(JSContextRef ctx, JSValueRef value){ + JSValueRef exception = NULL; + + double doublevalue = ::JSValueToNumber(ctx, value, &exception); + if(exception != NULL){ + throw TypeMismatchException(ctx, exception); + } + if( doublevalue == std::numeric_limits<double>::infinity() ) + throw TypeMismatchException("Value is POSITIVE_INFINITY"); + if( doublevalue == -std::numeric_limits<double>::infinity() ) + throw TypeMismatchException("Value is NEGATIVE_INFINITY"); + if( std::isnan(doublevalue)){ + throw TypeMismatchException("Value is not number"); + } + return doublevalue; +} + +double JSUtil::JSValueToNumber(JSContextRef ctx, JSValueRef value){ + JSValueRef exception = NULL; + + double doublevalue = ::JSValueToNumber(ctx, value, &exception); + if(exception != NULL){ + throw TypeMismatchException(ctx, exception); + } + if( doublevalue == std::numeric_limits<double>::infinity() ) + doublevalue = 0.0; + + if( doublevalue == -std::numeric_limits<double>::infinity() ) + doublevalue = 0.0; + + return doublevalue; +} + +signed char JSUtil::JSValueToByte(JSContextRef ctx, JSValueRef value){ + return static_cast<signed char>(JSValueToNumber(ctx,value)); +} + +unsigned char JSUtil::JSValueToOctet(JSContextRef ctx, JSValueRef value){ + return static_cast<unsigned char>(JSValueToNumber(ctx,value)); +} + +bool JSUtil::JSValueToBoolean(JSContextRef ctx, JSValueRef value){ + return ::JSValueToBoolean(ctx, value); +} + +time_t JSUtil::JSValueToTimeT(JSContextRef ctx, JSValueRef value){ + if(!JSValueIsDateObject(ctx, value)) + throw TypeMismatchException("Value is not Date Object"); + + JSObjectRef timeobj = NULL; + timeobj = JSUtil::JSValueToObject(ctx, value); + JSValueRef exception = NULL; + JSObjectRef getTime = NULL; + try{ + getTime = JSUtil::JSValueToObject(ctx, getProperty(ctx, timeobj, "getTime")); + }catch( const TypeMismatchException& err){ + throw TypeMismatchException("Value is not Date Object"); + } + + JSValueRef timevalue = JSObjectCallAsFunction(ctx, getTime, timeobj, 0, NULL, &exception); + if( exception != NULL ) + throw TypeMismatchException("Value is not Date Object"); + + double millisecond = JSValueToDouble(ctx, timevalue); + time_t second = millisecond/1000; + return second; +} + +tm JSUtil::JSValueToDateTm(JSContextRef ctx, JSValueRef value){ + tm result = {0}; + + time_t second = JSUtil::JSValueToTimeT(ctx, value); + + if(localtime_r(&second, &result) == NULL) + throw TypeMismatchException("Value is not Date Object"); + + return result; +} + +tm JSUtil::JSValueToDateTmUTC(JSContextRef ctx, JSValueRef value){ + tm result = {0}; + + time_t second = JSUtil::JSValueToTimeT(ctx, value); + + if(gmtime_r(&second, &result) == NULL) + throw TypeMismatchException("Value is not Date Object"); + + return result; +} + +JSObjectRef JSUtil::JSValueToObject(JSContextRef ctx, JSValueRef value){ + JSValueRef exception = NULL; + JSObjectRef obj = ::JSValueToObject(ctx, value,&exception); + if( exception != NULL){ + throw TypeMismatchException(ctx, exception); + } + return obj; +} + +std::map<std::string, std::string> JSUtil::JSValueToStringMap(JSContextRef ctx, JSValueRef value){ + std::map<std::string, std::string> result; + JSObjectRef obj = JSUtil::JSValueToObject(ctx, value); + JSPropertyNameArrayRef jsPropNames = JSObjectCopyPropertyNames(ctx, obj); + for (std::size_t i = 0; i < JSPropertyNameArrayGetCount(jsPropNames); ++i) { + std::string propName = JSUtil::JSStringToString(ctx, JSPropertyNameArrayGetNameAtIndex(jsPropNames, i)); + std::string propValue = JSUtil::JSValueToString(ctx, JSUtil::getProperty(ctx, obj, propName.c_str(), NULL)); + result.insert(std::make_pair(propName, propValue)); + } + JSPropertyNameArrayRelease(jsPropNames); + return result; +} + +JSObjectRef JSUtil::makeDateObject(JSContextRef ctx, const time_t value){ + JSValueRef exception = NULL; + JSValueRef args[1]; + double millisecond = value*1000.0; + args[0] = toJSValueRef(ctx, millisecond); + JSObjectRef result = JSObjectMakeDate(ctx, 1, args, &exception); + if( exception != NULL){ + throw TypeMismatchException("Can't create Date object"); + } + return result; +} + + +JSValueRef JSUtil::toJSValueRef(JSContextRef ctx, const string& str){ + JSValueRef result = NULL; + JSStringRef jsString = JSStringCreateWithUTF8CString(str.c_str()); + result = JSValueMakeString(ctx, jsString); + JSStringRelease(jsString); + return result; +} + +JSValueRef JSUtil::toJSValueRef(JSContextRef ctx, const unsigned short value){ + return JSValueMakeNumber(ctx, value); +} + +JSValueRef JSUtil::toJSValueRef(JSContextRef ctx, const short value){ + return JSValueMakeNumber(ctx, value); +} + +JSValueRef JSUtil::toJSValueRef(JSContextRef ctx, const unsigned long value){ + return JSValueMakeNumber(ctx, value); +} + +JSValueRef JSUtil::toJSValueRef(JSContextRef ctx, const long value){ + return JSValueMakeNumber(ctx, value); +} + +JSValueRef JSUtil::toJSValueRef(JSContextRef ctx, const unsigned long long value) { + return JSValueMakeNumber(ctx, value); +} + +JSValueRef JSUtil::toJSValueRef(JSContextRef ctx, const long long value) { + return JSValueMakeNumber(ctx, value); +} + +JSValueRef JSUtil::toJSValueRef(JSContextRef ctx, const double value){ + return JSValueMakeNumber(ctx, value); +} + +JSValueRef JSUtil::toJSValueRef(JSContextRef ctx, const signed char value){ + return JSValueMakeNumber(ctx, value); +} + +JSValueRef JSUtil::toJSValueRef(JSContextRef ctx, const unsigned char value){ + return JSValueMakeNumber(ctx, value); +} + + +JSValueRef JSUtil::toJSValueRef(JSContextRef ctx, const bool value){ + return JSValueMakeBoolean(ctx, value); +} + +JSValueRef JSUtil::toJSValueRef(JSContextRef ctx, const std::vector<std::string>& value){ + return toJSValueRef_(ctx, value); +} + +JSValueRef JSUtil::toJSValueRef(JSContextRef ctx, const std::vector<unsigned short>& value){ + return toJSValueRef_(ctx, value); +} + +JSValueRef JSUtil::toJSValueRef(JSContextRef ctx, const std::vector<short>& value){ + return toJSValueRef_(ctx, value); +} + +JSValueRef JSUtil::toJSValueRef(JSContextRef ctx, const std::vector<long>& value){ + return toJSValueRef_(ctx, value); +} + +JSValueRef JSUtil::toJSValueRef(JSContextRef ctx, const std::vector<double>& value){ + return toJSValueRef_(ctx, value); +} + +JSValueRef JSUtil::toJSValueRef(JSContextRef ctx, const std::vector<bool>& value){ + return toJSValueRef_(ctx, value); +} + +JSValueRef JSUtil::toJSValueRef(JSContextRef ctx, const std::map<std::string, std::string>& value){ + JSObjectRef obj = JSObjectMake(ctx, NULL, NULL); + + std::map<std::string, std::string>::const_iterator iter; + for (iter = value.begin(); iter != value.end(); ++iter) { + std::string propName = iter->first; + JSUtil::setProperty(ctx, obj, propName.c_str(), JSUtil::toJSValueRef(ctx, iter->second), kJSPropertyAttributeNone); + } + + return obj; +} + +vector<string> JSUtil::JSArrayToStringVector(JSContextRef ctx, JSValueRef value){ + return JSArrayToType_<string>(ctx, value, JSUtil::JSValueToString); +} +vector<double> JSUtil::JSArrayToDoubleVector(JSContextRef ctx, JSValueRef value){ + return JSArrayToType_<double>(ctx, value, JSUtil::JSValueToDouble); +} +vector<long> JSUtil::JSArrayToLongVector(JSContextRef ctx, JSValueRef value){ + return JSArrayToType_<long>(ctx, value, JSUtil::JSValueToLong); +} +vector<time_t> JSUtil::JSArrayToTimeTVector(JSContextRef ctx, JSValueRef value){ + return JSArrayToType_<time_t>(ctx, value, JSUtil::JSValueToTimeT); +} +vector<bool> JSUtil::JSArrayToBoolVector(JSContextRef ctx, JSValueRef value){ + return JSArrayToType_<bool>(ctx, value, JSUtil::JSValueToBoolean); +} + +bool JSUtil::JSValueIsDateObject(JSContextRef ctx, JSValueRef jsValue) { + JSValueRef exception = NULL; + + JSObjectRef globalObj = JSContextGetGlobalObject(ctx); + + JSValueRef jsDate = getProperty(ctx, globalObj, "Date", &exception); + if(exception) + return false; + + JSObjectRef jsDateObj = ::JSValueToObject(ctx, jsDate, &exception); + if(exception) + return false; + + bool result = JSValueIsInstanceOfConstructor(ctx, jsValue, jsDateObj, &exception); + if(exception) + return false; + + return result; +} + +} +} diff --git a/wearable_src/Common/JSUtil.h b/wearable_src/Common/JSUtil.h new file mode 100755 index 0000000..733761e --- /dev/null +++ b/wearable_src/Common/JSUtil.h @@ -0,0 +1,621 @@ +// +// Tizen Web Device API +// Copyright (c) 2013 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _JSUTIL_H_ +#define _JSUTIL_H_ +#include <JavaScriptCore/JavaScript.h> +#include <string> +#include <map> +#include <vector> +#include "PlatformException.h" +#include <ctime> + + +namespace DeviceAPI { +namespace Common{ + +class JSUtil{ +public: + /** + * @brief Gets a property from an object. + * + * @remarks + * if pass NULL in exception, when occurred error, it throw C++ exception(TypeMismatchException). + * + * @param[in] ctx The execution context to use. + * @param[in] object The JSObject whose property you want to get. + * @param[in] name The name of property + * @param[out] exception A pointer to a JSValueRef in which to store an exception, if any. + * + * @exception TypeMismatchException + */ + static JSValueRef getProperty(JSContextRef ctx , JSObjectRef object, const char *name, JSValueRef *exception=NULL); + + /** + * @brief Sets a property on an object. + * + * @remarks + * if pass NULL in exception, when occurred error, it throw C++ exception(TypeMismatchException). + * + * @param[in] ctx The execution context to use. + * @param[in] object The JSObject whose property you want to set. + * @param[in] name The name of property + * @param[in] attributes A logically ORed set of JSPropertyAttributes to give to the property. + * @param[out] exception A pointer to a JSValueRef in which to store an exception, if any. + * + * @exception TypeMismatchException + */ + static void setProperty(JSContextRef ctx , JSObjectRef object, const char *name, JSValueRef value, JSPropertyAttributes attributes, JSValueRef *exception=NULL); + + /** + * @brief Converts a JavaScript string to STL string + * + * @param[in] ctx The execution context to use. + * @param[in] value The JSString to convert. + * + * @return A STL string with the result of conversion + */ + static std::string JSStringToString(JSContextRef ctx, JSStringRef str); + + /** + * @brief Converts a JavaScript value to STL string + * + * @param[in] ctx The execution context to use. + * @param[in] value The JSValue to convert. + * + * @return A STL string with the result of conversion + * + * @exception TypeMismatchException + */ + static std::string JSValueToString(JSContextRef ctx, JSValueRef value); + + /** + * @brief Converts a JavaScript value to long number and returns the resulting long number. + * + * @param[in] ctx The execution context to use. + * @param[in] value The JSValue to convert. + * + * @return The result of conversion + * + * @exception TypeMismatchException + */ + static long JSValueToLong(JSContextRef ctx, JSValueRef value); + + /** + * @brief Converts a JavaScript value to unsigned long number and returns the resulting unsigned long number. + * + * @param[in] ctx The execution context to use. + * @param[in] value The JSValue to convert. + * + * @return The result of conversion + * + * @exception TypeMismatchException + */ + static unsigned long JSValueToULong(JSContextRef ctx, JSValueRef value); + + + /** + * @brief Converts a JavaScript value to long long number and returns the resulting long long number. + * + * @param[in] ctx The execution context to use. + * @param[in] value The JSValue to convert. + * + * @return The result of conversion + * + * @exception TypeMismatchException + */ + static long long JSValueToLongLong(JSContextRef ctx, JSValueRef value); + + /** + * @brief Converts a JavaScript value to unsigned long long number and returns the resulting unsigned long long number. + * + * @param[in] ctx The execution context to use. + * @param[in] value The JSValue to convert. + * + * @return The result of conversion + * + * @exception TypeMismatchException + */ + static unsigned long long JSValueToULongLong(JSContextRef ctx, JSValueRef value); + + + /** + * @brief Converts a JavaScript value to double number and returns the resulting double number. + * + * @remarks TypeMismatchException is thrown when the result of conversion was NaN(Not a Number). + * + * @param[in] ctx The execution context to use. + * @param[in] value The JSValue to convert. + * + * @return The result of conversion + * + * @exception TypeMismatchException + */ + static double JSValueToDouble(JSContextRef ctx, JSValueRef value); + + /** + * @brief Converts a JavaScript value to number and returns the resulting number. + * + * @param[in] ctx The execution context to use. + * @param[in] value The JSValue to convert. + * + * @return The result of conversion + * + * @exception TypeMismatchException + */ + static double JSValueToNumber(JSContextRef ctx, JSValueRef value); + + + /** + * @brief Converts a JavaScript value to byte(signed) number and returns the resulting byte(signed) number. + * + * @param[in] ctx The execution context to use. + * @param[in] value The JSValue to convert. + * + * @return The result of conversion + * + * @exception TypeMismatchException + */ + static signed char JSValueToByte(JSContextRef ctx, JSValueRef value); + + /** + * @brief Converts a JavaScript value to Octet(unsigned) number and returns the resulting Octet(unsigned) number. + * + * @param[in] ctx The execution context to use. + * @param[in] value The JSValue to convert. + * + * @return The result of conversion + * + * @exception TypeMismatchException + */ + static unsigned char JSValueToOctet(JSContextRef ctx, JSValueRef value); + + + /** + * @brief Converts a JavaScript value to boolean and returns the resulting bollean + * + * + * @param[in] ctx The execution context to use. + * @param[in] value The JSValue to convert. + * + * @return The result of conversion + */ + static bool JSValueToBoolean(JSContextRef ctx, JSValueRef value); + + /** + * @brief Converts a JavaScript value to time_t and returns the resulting time_t. + * + * @remarks TypeMismatchException is thrown when the value was not Date type. + * + * @param[in] ctx The execution context to use. + * @param[in] value The JSValue to convert. + * + * @return The result of conversion + * + * @exception TypeMismatchException + */ + static time_t JSValueToTimeT(JSContextRef ctx, JSValueRef value); + + /** + * @brief Converts a JavaScript value to tm and returns the resulting tm. + * + * @remarks TypeMismatchException is thrown when the value was not Date type. + * + * @param[in] ctx The execution context to use. + * @param[in] value The JSValue to convert. + * + * @return The result of conversion + * + * @exception TypeMismatchException + */ + static std::tm JSValueToDateTm(JSContextRef ctx, JSValueRef value); + + /** + * @brief Converts a JavaScript value to tm as UTC time and returns the resulting tm. + * + * @remarks TypeMismatchException is thrown when the value was not Date type. + * + * @param[in] ctx The execution context to use. + * @param[in] value The JSValue to convert. + * + * @return The result of conversion + * + * @exception TypeMismatchException + */ + static std::tm JSValueToDateTmUTC(JSContextRef ctx, JSValueRef value); + + /** + * @brief Converts a JavaScript value to object and returns the resulting object. + * + * @remarks TypeMismatchException is thrown when the value was not Object type. + * + * @param[in] ctx The execution context to use. + * @param[in] value The JSValue to convert. + * + * @return The JSObject result of conversion + * + * @exception TypeMismatchException + */ + static JSObjectRef JSValueToObject(JSContextRef ctx, JSValueRef value); + + /** + * @brief Converts a JavaScript value to STL string vector and returns the resulting STL string vector + * + * @remarks TypeMismatchException is thrown when the array element could not converts to string.\n + * If the value is not Array object, Will return empty vector + * + * + * @param[in] ctx The execution context to use. + * @param[in] value The JSValue to convert. + * + * @return A STL string vector + * + * @exception TypeMismatchException + */ + static std::vector<std::string> JSArrayToStringVector(JSContextRef ctx, JSValueRef value); + + /** + * @brief Converts a JavaScript value to double number vector and returns the resulting double number vector + * + * @remarks TypeMismatchException is thrown when the array element could not converts to double.\n + * If the value is not Array object, Will return empty vector + * + * + * @param[in] ctx The execution context to use. + * @param[in] value The JSValue to convert. + * + * @return A double number vector + * + * @exception TypeMismatchException + */ + static std::vector<double> JSArrayToDoubleVector(JSContextRef ctx, JSValueRef value); + + /** + * @brief Converts a JavaScript value to long number vector and returns the resulting long number vector + * + * @remarks TypeMismatchException is thrown when the array element could not converts to long.\n + * If the value is not Array object, Will return empty vector + * + * + * @param[in] ctx The execution context to use. + * @param[in] value The JSValue to convert. + * + * @return A long number vector + * + * @exception TypeMismatchException + */ + static std::vector<long> JSArrayToLongVector(JSContextRef ctx, JSValueRef value); + + /** + * @brief Converts a JavaScript value to time_t vector and returns the resulting time_t vector + * + * @remarks TypeMismatchException is thrown when the array element could not converts to time_t.\n + * If the value is not Array object, Will return empty vector + * + * + * @param[in] ctx The execution context to use. + * @param[in] value The JSValue to convert. + * + * @return A time_t vector + * + * @exception TypeMismatchException + */ + static std::vector<time_t> JSArrayToTimeTVector(JSContextRef ctx, JSValueRef value); + + /** + * @brief Converts a JavaScript value to boolean vector and returns the resulting boolean vector + * + * @remarks If the value is not Array object, Will return empty vector + * + * + * @param[in] ctx The execution context to use. + * @param[in] value The JSValue to convert. + * + * @return A boolean vector + */ + static std::vector<bool> JSArrayToBoolVector(JSContextRef ctx, JSValueRef value); + + /** + * @brief Converts a JavaScript value to map<string,string> and returns the resulting object. + * + * @remarks TypeMismatchException is thrown when the value was not Object type. + * + * @param[in] ctx The execution context to use. + * @param[in] value The JSValue to convert. + * + * @return The JSObject result of conversion + * + * @exception TypeMismatchException + */ + static std::map<std::string, std::string> JSValueToStringMap(JSContextRef ctx, JSValueRef value); + + /** + * @brief Creates a JavaScript value of the string type. + * + * @param[in] ctx The execution context to use. + * @param[in] str The STL string to assign to the newly created JSValue. The newly created JSValue retains string, and releases it upon garbage collection. + * + * @return A JSValue of the string type, representing the value of string. + */ + static JSValueRef toJSValueRef(JSContextRef ctx, const std::string& str); + + /** + * @brief Creates a JavaScript value of the number type. + * + * @param[in] ctx The execution context to use. + * @param[in] value The short to assign to the newly created JSValue. + * + * @return A JSValue of the number type, representing the value of number. + */ + static JSValueRef toJSValueRef(JSContextRef ctx, const short value); + + /** + * @brief Creates a JavaScript value of the number type. + * + * @param[in] ctx The execution context to use. + * @param[in] value The unsigned short to assign to the newly created JSValue. + * + * @return A JSValue of the number type, representing the value of number. + */ + static JSValueRef toJSValueRef(JSContextRef ctx, const unsigned short value); + + /** + * @brief Creates a JavaScript value of the number type. + * + * @param[in] ctx The execution context to use. + * @param[in] value The long to assign to the newly created JSValue. + * + * @return A JSValue of the number type, representing the value of number. + */ + static JSValueRef toJSValueRef(JSContextRef ctx, const long value); + + /** + * @brief Creates a JavaScript value of the number type. + * + * @param[in] ctx The execution context to use. + * @param[in] value The unsigned long to assign to the newly created JSValue. + * + * @return A JSValue of the number type, representing the value of number. + */ + static JSValueRef toJSValueRef(JSContextRef ctx, const unsigned long value); + + /** + * @brief Creates a JavaScript value of the number type. + * + * @param[in] ctx The execution context to use. + * @param[in] value The long long to assign to the newly created JSValue. + * + * @return A JSValue of the number type, representing the value of number. + */ + static JSValueRef toJSValueRef(JSContextRef ctx, const long long value); + + /** + * @brief Creates a JavaScript value of the number type. + * + * @param[in] ctx The execution context to use. + * @param[in] value The unsigned long long to assign to the newly created JSValue. + * + * @return A JSValue of the number type, representing the value of number. + */ + static JSValueRef toJSValueRef(JSContextRef ctx, const unsigned long long value); + /** + * @brief Creates a JavaScript value of the number type. + * + * @param[in] ctx The execution context to use. + * @param[in] value The double to assign to the newly created JSValue. + * + * @return A JSValue of the number type, representing the value of number. + */ + static JSValueRef toJSValueRef(JSContextRef ctx, const double value); + + /** + * @brief Creates a JavaScript value of the boolean type. + * + * @param[in] ctx The execution context to use. + * @param[in] value The bool to assign to the newly created JSValue. + * + * @return A JSValue of the boolean type, representing the value of boolean. + */ + static JSValueRef toJSValueRef(JSContextRef ctx, const bool value); + + /** + * @brief Creates a JavaScript value of the number type. + * + * @param[in] ctx The execution context to use. + * @param[in] value The signed char to assign to the newly created JSValue. + * + * @return A JSValue of the number type, representing the value of number. + */ + static JSValueRef toJSValueRef(JSContextRef ctx, const signed char value); + + /** + * @brief Creates a JavaScript value of the number type. + * + * @param[in] ctx The execution context to use. + * @param[in] value The signed char to assign to the newly created JSValue. + * + * @return A JSValue of the number type, representing the value of number. + */ + static JSValueRef toJSValueRef(JSContextRef ctx, const unsigned char value); + + + + /** + * @brief Creates a JavaScript value of the string Array type. + * + * @remarks UnknownException is thrown when could not create Array object.\n + * + * @param[in] ctx The execution context to use. + * @param[in] value The STL string vector to assign to the newly created JSArray + * + * @return A JSArray of the string type + * + * @exception UnknownException + */ + static JSValueRef toJSValueRef(JSContextRef ctx, const std::vector<std::string>& value); + + + /** + * @brief Creates a JavaScript value of the number Array type. + * + * @remarks UnknownException is thrown when could not create Array object.\n + * + * @param[in] ctx The execution context to use. + * @param[in] value The unsigned short vector to assign to the newly created JSArray + * + * @return A JSArray of the number type + * + * @exception UnknownException + */ + static JSValueRef toJSValueRef(JSContextRef ctx, const std::vector<unsigned short>& value); + + + /** + * @brief Creates a JavaScript value of the number Array type. + * + * @remarks UnknownException is thrown when could not create Array object.\n + * + * @param[in] ctx The execution context to use. + * @param[in] value The long vector to assign to the newly created JSArray + * + * @return A JSArray of the number type + * + * @exception UnknownException + */ + static JSValueRef toJSValueRef(JSContextRef ctx, const std::vector<short>& value); + + + /** + * @brief Creates a JavaScript value of the number Array type. + * + * @remarks UnknownException is thrown when could not create Array object.\n + * + * @param[in] ctx The execution context to use. + * @param[in] value The long vector to assign to the newly created JSArray + * + * @return A JSArray of the number type + * + * @exception UnknownException + */ + static JSValueRef toJSValueRef(JSContextRef ctx, const std::vector<long>& value); + + /** + * @brief Creates a JavaScript value of the number Array type. + * + * @remarks UnknownException is thrown when could not create Array object.\n + * + * @param[in] ctx The execution context to use. + * @param[in] value The double vector to assign to the newly created JSArray + * + * @return A JSArray of the number type + * + * @exception UnknownException + */ + static JSValueRef toJSValueRef(JSContextRef ctx, const std::vector<double>& value); + + + /** + * @brief Creates a JavaScript value of the boolean Array type. + * + * @remarks UnknownException is thrown when could not create Array object.\n + * + * @param[in] ctx The execution context to use. + * @param[in] value The boolean vector to assign to the newly created JSArray + * + * @return A JSArray of the boolean type + * + * @exception UnknownException + */ + static JSValueRef toJSValueRef(JSContextRef ctx, const std::vector<bool>& value); + + /** + * @brief Creates a JavaScript value of the string map type. + * + * @remarks UnknownException is thrown when could not create Array object.\n + * + * @param[in] ctx The execution context to use. + * @param[in] value The string map to assign to the newly created JSValue + * + * @return A JSValue of the string map type + * + * @exception UnknownException + */ + static JSValueRef toJSValueRef(JSContextRef ctx, const std::map<std::string, std::string>& value); + + /** + * @brief Creates a JavaScript Date object with time_t value + * + * @remarks TypeMismatchException is thrown when could not create Date object.\n + * + * @param[in] ctx The execution context to use. + * @param[in] value The time_t value to create + * + * @return A JSObject that is a Date. + * + * @exception TypeMismatchException + */ + static JSObjectRef makeDateObject(JSContextRef ctx, const time_t value); + + + template<class T> + static std::vector<T> JSArrayToType_(JSContextRef ctx, JSValueRef value, T (*convert)(JSContextRef, JSValueRef)){ + std::vector<T> result; + if( !JSIsArrayValue(ctx, value)){ + return result; + } + JSObjectRef arrayobj = JSUtil::JSValueToObject(ctx, value); + + for (std::size_t i = 0; i < JSGetArrayLength(ctx, arrayobj); ++i) { + JSValueRef element = JSGetArrayElement(ctx, arrayobj, i); + T v = convert(ctx, element); + result.push_back(v); + } + return result; + } + + template<class T> + static JSValueRef toJSValueRef_(JSContextRef ctx, const std::vector<T>& value){ + JSValueRef *valueArray = new JSValueRef[value.size()]; + for( unsigned int i = 0 ; i < value.size(); i++){ + valueArray[i] = toJSValueRef(ctx,value[i]); + if(valueArray[i] == NULL){ + if(valueArray != NULL) + delete [] valueArray; + throw UnknownException("Element of array is invalid"); + } + } + JSValueRef exception = NULL; + JSObjectRef jsResult = JSObjectMakeArray(ctx, value.size(), valueArray, &exception); + if (exception != NULL) { + if(valueArray != NULL) + delete [] valueArray; + throw UnknownException(ctx, exception); + } + if(valueArray != NULL) + delete [] valueArray; + return jsResult; + }; + +private: + static bool JSValueIsDateObject(JSContextRef ctx, JSValueRef jsValue); +}; + +}} + +#endif //_JSUTIL_H_ + + diff --git a/wearable_src/Common/JSWebAPIError.cpp b/wearable_src/Common/JSWebAPIError.cpp new file mode 100644 index 0000000..6380462 --- /dev/null +++ b/wearable_src/Common/JSWebAPIError.cpp @@ -0,0 +1,197 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "JSWebAPIError.h" + +#include <string> +#include <map> +#include "JSUtil.h" +#include "Logger.h" + +namespace DeviceAPI { +namespace Common { + +#define CLASS_NAME "WebAPIError" +#define PROPERTY_CODE "code" +#define PROPERTY_NAME "name" +#define PROPERTY_TYPE "type" +#define PROPERTY_MESSAGE "message" + +JSClassRef JSWebAPIError::m_classRef = NULL; + +JSClassDefinition JSWebAPIError::m_classInfo = +{ + 0, + kJSClassAttributeNone, + CLASS_NAME, + 0, + m_properties, + m_function, + initialize, + finalize, + NULL, // hasProperty, + NULL, // getProperty, + NULL, // setProperty, + NULL, // deleteProperty, + NULL, // getPropertyNames, + NULL, // callAsFunction, + NULL, // callAsConstructor, + NULL, // hasInstance, + NULL, // convertToType, +}; + +JSStaticFunction JSWebAPIError::m_function[] = +{ + { "toString", toString, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +JSStaticValue JSWebAPIError::m_properties[] = { + { PROPERTY_CODE, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_NAME, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_TYPE, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_MESSAGE, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +const JSClassDefinition* JSWebAPIError::getClassInfo() +{ + return &m_classInfo; +} + +JSClassRef JSWebAPIError::getClassRef() +{ + if (!m_classRef) + { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +bool JSWebAPIError::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +JSObjectRef JSWebAPIError::createJSObject(JSContextRef context, WebAPIError* webapiError) +{ + JSObjectRef jsObjectRef = JSObjectMake(context, getClassRef(), static_cast<void*>(webapiError)); + if (NULL == jsObjectRef) { + LoggerE("object creation error"); + return NULL; + } + return jsObjectRef; +} + +WebAPIError* JSWebAPIError::getPriv(JSContextRef context, JSObjectRef object) +{ + if(!JSValueIsObjectOfClass(context, object, getClassRef())) + return NULL; + + return static_cast<WebAPIError*>(JSObjectGetPrivate(object)); +} + +JSObjectRef JSWebAPIError::constructor(JSContextRef context, + JSObjectRef constructor, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + return JSWebAPIErrorFactory::postException(context, exception, + JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, + "Illegal constructor"); +} + +void JSWebAPIError::initialize(JSContextRef /*context*/, JSObjectRef /*object*/) +{ +} + +void JSWebAPIError::finalize(JSObjectRef object) +{ + WebAPIError* webapiErrObj = static_cast<WebAPIError*>(JSObjectGetPrivate(object)); + if(webapiErrObj) + { + JSObjectSetPrivate(object, NULL); + delete webapiErrObj; + } +} + +JSValueRef JSWebAPIError::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* /*exception*/) +{ + WebAPIError* webapiErrObj = getPriv(context, object); + if(!webapiErrObj) + { + LoggerE("Private object is not set."); + return JSValueMakeUndefined(context); + } + + try + { + std::string propertyNameStr = JSUtil::JSStringToString(context, propertyName); + + if (propertyNameStr == PROPERTY_CODE) + { + return JSUtil::toJSValueRef(context, static_cast<long>(webapiErrObj->getCode())); + } + else if (propertyNameStr == PROPERTY_NAME) + { + return JSUtil::toJSValueRef(context, webapiErrObj->getName()); + } + else if (propertyNameStr == PROPERTY_TYPE) + { + return JSUtil::toJSValueRef(context, webapiErrObj->getName()); + } + else if (propertyNameStr == PROPERTY_MESSAGE) + { + return JSUtil::toJSValueRef(context, webapiErrObj->getMessage()); + } + } + catch(const BasePlatformException & err) + { + LoggerE("Exception: " << err.getMessage()); + } + + return JSValueMakeUndefined(context); +} + +JSValueRef JSWebAPIError::toString(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + WebAPIError* webapiErrObj = getPriv(context, thisObject); + if(!webapiErrObj) + { + LoggerE("Private object is not set."); + return NULL; + } + + std::string name = webapiErrObj->getName(); + std::string message = webapiErrObj->getMessage(); + + std::string result = name + ": " + message; + + return JSUtil::toJSValueRef(context, result); +} + +} // Common +} // DeviceAPI diff --git a/wearable_src/Common/JSWebAPIError.h b/wearable_src/Common/JSWebAPIError.h new file mode 100644 index 0000000..3596a9d --- /dev/null +++ b/wearable_src/Common/JSWebAPIError.h @@ -0,0 +1,81 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _JS_WEBAPI_ERROR_H_ +#define _JS_WEBAPI_ERROR_H_ + +#include <JavaScriptCore/JavaScript.h> +#include "JSWebAPIErrorFactory.h" + +#include "WebAPIError.h" + +namespace DeviceAPI { +namespace Common { + +class JSWebAPIErrorFactory; + +class JSWebAPIError +{ +public: + static JSClassRef getClassRef(); + + static const JSClassDefinition* getClassInfo(); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + static JSObjectRef constructor(JSContextRef context, + JSObjectRef constructor, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + +private: + static JSObjectRef createJSObject(JSContextRef context, WebAPIError* webapiError); + + static WebAPIError* getPriv(JSContextRef context, JSObjectRef object); + + static void initialize(JSContextRef context, JSObjectRef object); + + static void finalize(JSObjectRef object); + + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef toString(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSClassDefinition m_classInfo; + + static JSStaticValue m_properties[]; + + static JSClassRef m_classRef; + + static JSStaticFunction m_function[]; + + friend class JSWebAPIErrorFactory; +}; + +} // Common +} // DeviceAPI + +#endif // _JS_WEBAPI_ERROR_H_ diff --git a/wearable_src/Common/JSWebAPIErrorFactory.cpp b/wearable_src/Common/JSWebAPIErrorFactory.cpp new file mode 100644 index 0000000..e6d0270 --- /dev/null +++ b/wearable_src/Common/JSWebAPIErrorFactory.cpp @@ -0,0 +1,264 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "JSWebAPIErrorFactory.h" + +#include <map> + +#include "JSStringRefWrapper.h" +#include "JSWebAPIException.h" +#include "JSWebAPIError.h" +#include "Logger.h" + +#define INDEX_SIZE_ERROR_NAME_STR "IndexSizeError" +#define DOMSTRING_SIZE_ERROR_NAME_STR "DOMStringSizeError" +#define HIERARCHY_REQUEST_ERROR_NAME_STR "HierarchyRequestError" +#define WRONG_DOCUMENT_ERROR_NAME_STR "WrongDocumentError" +#define INVALID_CHARACTER_ERROR_NAME_STR "InvalidCharacterError" +#define NO_DATA_ALLOWED_ERROR_NAME_STR "NoDataAllowedError" +#define NO_MODIFICATION_ALLOWED_ERROR_NAME_STR "NoModificationAllowedError" +#define NOT_FOUND_ERROR_NAME_STR "NotFoundError" +#define NOT_SUPPORTED_ERROR_NAME_STR "NotSupportedError" +#define INUSE_ATTRIBUTE_ERROR_NAME_STR "InuseAttributeError" +#define INVALID_STATE_ERROR_NAME_STR "InvalidStateError" +#define SYNTAX_ERROR_NAME_STR "SyntaxError" +#define INVALID_MODIFICATION_ERROR_NAME_STR "InvalidModificationError" +#define NAMESPACE_ERROR_NAME_STR "NamespaceError" +#define INVALID_ACCESS_ERROR_NAME_STR "InvalidAccessError" +#define VALIDATION_ERROR_NAME_STR "ValidationError" +#define TYPE_MISMATCH_ERROR_NAME_STR "TypeMismatchError" +#define SECURITY_ERROR_NAME_STR "SecurityError" +#define NETWORK_ERROR_NAME_STR "NetworkError" +#define ABORT_ERROR_NAME_STR "AbortError" +#define URL_MISMATCH_ERROR_NAME_STR "URLMismatchError" +#define QUOTA_EXCEEDED_ERROR_NAME_STR "QuotaExceededError" +#define TIMEOUT_ERROR_NAME_STR "TimeoutError" +#define INVALID_NODE_TYPE_ERROR_NAME_STR "InvalidNodeTypeError" +#define DATA_CLONE_ERROR_NAME_STR "DataCloneError" +#define ENCODING_ERROR_NAME_STR "EncodingError" + +#define UNKNOWN_ERROR_NAME_STR "UnknownError" +#define INVALID_VALUES_ERROR_NAME_STR "InvalidValuesError" +#define IO_ERROR_NAME_STR "IOError" +#define PERMISSION_DENIED_ERROR_NAME_STR "PermissionDeniedError" +#define SERVICE_NOT_AVAILABLE_ERROR_NAME_STR "ServiceNotAvailableError" + +#define ECMA_ERROR_NAME_STR "Error" +#define ECMA_EVAL_ERROR_NAME_STR "EvalError" +#define ECMA_RANGE_ERROR_NAME_STR "RangeError" +#define ECMA_REFERENCE_ERROR_NAME_STR "ReferenceError" +#define ECMA_SYNTAX_ERROR_NAME_STR "SyntaxError" +#define ECMA_TYPE_ERROR_NAME_STR "TypeError" +#define ECMA_URI_ERROR_NAME_STR "URIError" + +#define CUSTOM_ERROR_NAME_STR "CustomError" + +namespace DeviceAPI { +namespace Common { + +enum ErrorClass +{ + ERROR_TYPE_DOM, + ERROR_TYPE_TIZEN, + ERROR_TYPE_ECMA, + ERROR_TYPE_CUSTOM +}; + +struct DeviceAPIErrorProperties +{ + const ErrorClass type; + const unsigned int code; + const char* name; +}; +typedef std::map<std::string, DeviceAPIErrorProperties> DeviceAPIErrorPropertiesMap; + +static DeviceAPIErrorPropertiesMap s_errorProperties = { + { INDEX_SIZE_ERROR_NAME_STR, { ERROR_TYPE_DOM, 1, INDEX_SIZE_ERROR_NAME_STR } }, + { DOMSTRING_SIZE_ERROR_NAME_STR, { ERROR_TYPE_DOM, 2, DOMSTRING_SIZE_ERROR_NAME_STR } }, + { HIERARCHY_REQUEST_ERROR_NAME_STR, { ERROR_TYPE_DOM, 3, HIERARCHY_REQUEST_ERROR_NAME_STR } }, + { WRONG_DOCUMENT_ERROR_NAME_STR, { ERROR_TYPE_DOM, 4, WRONG_DOCUMENT_ERROR_NAME_STR } }, + { INVALID_CHARACTER_ERROR_NAME_STR, { ERROR_TYPE_DOM, 5, INVALID_CHARACTER_ERROR_NAME_STR } }, + { NO_DATA_ALLOWED_ERROR_NAME_STR, { ERROR_TYPE_DOM, 6, NO_DATA_ALLOWED_ERROR_NAME_STR } }, + { NO_MODIFICATION_ALLOWED_ERROR_NAME_STR, { ERROR_TYPE_DOM, 7, NO_MODIFICATION_ALLOWED_ERROR_NAME_STR } }, + { NOT_FOUND_ERROR_NAME_STR, { ERROR_TYPE_DOM, 8, NOT_FOUND_ERROR_NAME_STR } }, + { NOT_SUPPORTED_ERROR_NAME_STR, { ERROR_TYPE_DOM, 9, NOT_SUPPORTED_ERROR_NAME_STR } }, + { INUSE_ATTRIBUTE_ERROR_NAME_STR, { ERROR_TYPE_DOM, 10, INUSE_ATTRIBUTE_ERROR_NAME_STR } }, + { INVALID_STATE_ERROR_NAME_STR, { ERROR_TYPE_DOM, 11, INVALID_STATE_ERROR_NAME_STR } }, + { SYNTAX_ERROR_NAME_STR, { ERROR_TYPE_DOM, 12, SYNTAX_ERROR_NAME_STR } }, + { INVALID_MODIFICATION_ERROR_NAME_STR, { ERROR_TYPE_DOM, 13, INVALID_MODIFICATION_ERROR_NAME_STR } }, + { NAMESPACE_ERROR_NAME_STR, { ERROR_TYPE_DOM, 14, NAMESPACE_ERROR_NAME_STR } }, + { INVALID_ACCESS_ERROR_NAME_STR, { ERROR_TYPE_DOM, 15, INVALID_ACCESS_ERROR_NAME_STR } }, + { VALIDATION_ERROR_NAME_STR, { ERROR_TYPE_DOM, 16, VALIDATION_ERROR_NAME_STR } }, + { TYPE_MISMATCH_ERROR_NAME_STR, { ERROR_TYPE_DOM, 17, TYPE_MISMATCH_ERROR_NAME_STR } }, + { SECURITY_ERROR_NAME_STR, { ERROR_TYPE_DOM, 18, SECURITY_ERROR_NAME_STR } }, + { NETWORK_ERROR_NAME_STR, { ERROR_TYPE_DOM, 19, NETWORK_ERROR_NAME_STR } }, + { ABORT_ERROR_NAME_STR, { ERROR_TYPE_DOM, 20, ABORT_ERROR_NAME_STR } }, + { URL_MISMATCH_ERROR_NAME_STR, { ERROR_TYPE_DOM, 21, URL_MISMATCH_ERROR_NAME_STR } }, + { QUOTA_EXCEEDED_ERROR_NAME_STR, { ERROR_TYPE_DOM, 22, QUOTA_EXCEEDED_ERROR_NAME_STR } }, + { TIMEOUT_ERROR_NAME_STR, { ERROR_TYPE_DOM, 23, TIMEOUT_ERROR_NAME_STR } }, + { INVALID_NODE_TYPE_ERROR_NAME_STR, { ERROR_TYPE_DOM, 24, INVALID_NODE_TYPE_ERROR_NAME_STR } }, + { DATA_CLONE_ERROR_NAME_STR, { ERROR_TYPE_DOM, 25, DATA_CLONE_ERROR_NAME_STR } }, + { ENCODING_ERROR_NAME_STR, { ERROR_TYPE_DOM, 0, ENCODING_ERROR_NAME_STR } }, + { UNKNOWN_ERROR_NAME_STR, { ERROR_TYPE_TIZEN, 0, UNKNOWN_ERROR_NAME_STR } }, + { INVALID_VALUES_ERROR_NAME_STR, { ERROR_TYPE_TIZEN, 0, INVALID_VALUES_ERROR_NAME_STR } }, + { IO_ERROR_NAME_STR, { ERROR_TYPE_TIZEN, 0, IO_ERROR_NAME_STR } }, + { PERMISSION_DENIED_ERROR_NAME_STR, { ERROR_TYPE_TIZEN, 0, PERMISSION_DENIED_ERROR_NAME_STR } }, + { SERVICE_NOT_AVAILABLE_ERROR_NAME_STR, { ERROR_TYPE_TIZEN, 0, SERVICE_NOT_AVAILABLE_ERROR_NAME_STR } }, +}; + +static DeviceAPIErrorProperties s_customErrorProperties = { ERROR_TYPE_CUSTOM, 0, CUSTOM_ERROR_NAME_STR }; + +const std::string JSWebAPIErrorFactory::INDEX_SIZE_ERROR = INDEX_SIZE_ERROR_NAME_STR; +const std::string JSWebAPIErrorFactory::DOMSTRING_SIZE_ERROR = DOMSTRING_SIZE_ERROR_NAME_STR; +const std::string JSWebAPIErrorFactory::HIERARCHY_REQUEST_ERROR = HIERARCHY_REQUEST_ERROR_NAME_STR; +const std::string JSWebAPIErrorFactory::WRONG_DOCUMENT_ERROR = WRONG_DOCUMENT_ERROR_NAME_STR; +const std::string JSWebAPIErrorFactory::INVALID_CHARACTER_ERROR = INVALID_CHARACTER_ERROR_NAME_STR; +const std::string JSWebAPIErrorFactory::NO_DATA_ALLOWED_ERROR = NO_DATA_ALLOWED_ERROR_NAME_STR; +const std::string JSWebAPIErrorFactory::NO_MODIFICATION_ALLOWED_ERROR = NO_MODIFICATION_ALLOWED_ERROR_NAME_STR; +const std::string JSWebAPIErrorFactory::NOT_FOUND_ERROR = NOT_FOUND_ERROR_NAME_STR; +const std::string JSWebAPIErrorFactory::NOT_SUPPORTED_ERROR = NOT_SUPPORTED_ERROR_NAME_STR; +const std::string JSWebAPIErrorFactory::INUSE_ATTRIBUTE_ERROR = INUSE_ATTRIBUTE_ERROR_NAME_STR; +const std::string JSWebAPIErrorFactory::INVALID_STATE_ERROR = INVALID_STATE_ERROR_NAME_STR; +const std::string JSWebAPIErrorFactory::SYNTAX_ERROR = SYNTAX_ERROR_NAME_STR; +const std::string JSWebAPIErrorFactory::INVALID_MODIFICATION_ERROR = INVALID_MODIFICATION_ERROR_NAME_STR; +const std::string JSWebAPIErrorFactory::NAMESPACE_ERROR = NAMESPACE_ERROR_NAME_STR; +const std::string JSWebAPIErrorFactory::INVALID_ACCESS_ERROR = INVALID_ACCESS_ERROR_NAME_STR; +const std::string JSWebAPIErrorFactory::VALIDATION_ERROR = VALIDATION_ERROR_NAME_STR; +const std::string JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR = TYPE_MISMATCH_ERROR_NAME_STR; +const std::string JSWebAPIErrorFactory::SECURITY_ERROR = SECURITY_ERROR_NAME_STR; +const std::string JSWebAPIErrorFactory::NETWORK_ERROR = NETWORK_ERROR_NAME_STR; +const std::string JSWebAPIErrorFactory::ABORT_ERROR = ABORT_ERROR_NAME_STR; +const std::string JSWebAPIErrorFactory::URL_MISMATCH_ERROR = URL_MISMATCH_ERROR_NAME_STR; +const std::string JSWebAPIErrorFactory::QUOTA_EXCEEDED_ERROR = QUOTA_EXCEEDED_ERROR_NAME_STR; +const std::string JSWebAPIErrorFactory::TIMEOUT_ERROR = TIMEOUT_ERROR_NAME_STR; +const std::string JSWebAPIErrorFactory::INVALID_NODE_TYPE_ERROR = INVALID_NODE_TYPE_ERROR_NAME_STR; +const std::string JSWebAPIErrorFactory::DATA_CLONE_ERROR = DATA_CLONE_ERROR_NAME_STR; +const std::string JSWebAPIErrorFactory::ENCODING_ERROR = ENCODING_ERROR_NAME_STR; + +const std::string JSWebAPIErrorFactory::UNKNOWN_ERROR = UNKNOWN_ERROR_NAME_STR; +const std::string JSWebAPIErrorFactory::INVALID_VALUES_ERROR = INVALID_VALUES_ERROR_NAME_STR; +const std::string JSWebAPIErrorFactory::IO_ERROR = IO_ERROR_NAME_STR; +const std::string JSWebAPIErrorFactory::PERMISSION_DENIED_ERROR = PERMISSION_DENIED_ERROR_NAME_STR; +const std::string JSWebAPIErrorFactory::SERVICE_NOT_AVAILABLE_ERROR = SERVICE_NOT_AVAILABLE_ERROR_NAME_STR; + +JSWebAPIErrorFactory::JSWebAPIErrorFactory() +{ +} + +JSWebAPIErrorFactory::~JSWebAPIErrorFactory() +{ +} + +JSObjectRef JSWebAPIErrorFactory::makeErrorObject(JSContextRef context, + const std::string& name, + const std::string& message) +{ + return createErrorObject(context, name, message, false); +} + +JSObjectRef JSWebAPIErrorFactory::makeErrorObject(JSContextRef context, + const BasePlatformException& error) +{ + return createErrorObject(context, error.getName(), error.getMessage(), false); +} + +JSObjectRef JSWebAPIErrorFactory::postException(JSContextRef context, + JSValueRef* exception, + const std::string& name, + const std::string& message) +{ + if(exception == NULL) + { + LoggerE("exception ptr is NULL."); + return NULL; + } + + JSObjectRef exceptionObj = createErrorObject(context, name, message, true); + + *exception = exceptionObj; + + return exceptionObj; +} + +JSObjectRef JSWebAPIErrorFactory::postException(JSContextRef context, + JSValueRef* exception, + const BasePlatformException& error) +{ + return postException(context, exception, error.getName(), error.getMessage()); +} + +JSObjectRef JSWebAPIErrorFactory::createErrorObject(JSContextRef context, + const std::string& name, + const std::string& message, + const bool isException) +{ + JSObjectRef jsErrorObject = NULL; + + DeviceAPIErrorProperties *properties; + + DeviceAPIErrorPropertiesMap::iterator iter = s_errorProperties.find(name); + if(iter != s_errorProperties.end()) + properties = &(iter->second); + else + properties = &s_customErrorProperties; + + if(properties->type == ERROR_TYPE_ECMA) + return createECMAErrorObject(context, properties->name, message); + + WebAPIError *errorObject = NULL; + switch(properties->type) + { + case ERROR_TYPE_DOM: + case ERROR_TYPE_TIZEN: + errorObject = new WebAPIError(properties->code, properties->name, message); + break; + case ERROR_TYPE_CUSTOM: + errorObject = new WebAPIError(0, name, message); + break; + case ERROR_TYPE_ECMA: // Cannot happen + default: + errorObject = new WebAPIError(0, "Error", message); + break; + } + + if(isException) + jsErrorObject = JSWebAPIException::createJSObject(context, errorObject); + else + jsErrorObject = JSWebAPIError::createJSObject(context, errorObject); + + return jsErrorObject; +} + +JSObjectRef JSWebAPIErrorFactory::createECMAErrorObject(JSContextRef context, + const std::string& name, + const std::string& message) +{ + std::string jsCodeStr; + jsCodeStr = "new " + name + "("; + if(!message.empty()) + jsCodeStr += "\"" + message + "\""; + jsCodeStr += ");"; + + JSStringRefWrapper jsCode(jsCodeStr); + + JSValueRef errValue = JSEvaluateScript(context, jsCode.get(), NULL, NULL, 0, NULL); + + return JSValueToObject(context, errValue, NULL); +} + +} // Common +} // DeviceAPI diff --git a/wearable_src/Common/JSWebAPIErrorFactory.h b/wearable_src/Common/JSWebAPIErrorFactory.h new file mode 100644 index 0000000..6dfc55b --- /dev/null +++ b/wearable_src/Common/JSWebAPIErrorFactory.h @@ -0,0 +1,97 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _JS_WEBAPI_ERROR_FACTORY_H_ +#define _JS_WEBAPI_ERROR_FACTORY_H_ + +#include <string> +#include <JavaScriptCore/JavaScript.h> +#include "PlatformException.h" + +namespace DeviceAPI { +namespace Common { + +class JSWebAPIErrorFactory +{ +public: + JSWebAPIErrorFactory(); + virtual ~JSWebAPIErrorFactory(); + + static JSObjectRef makeErrorObject(JSContextRef context, + const std::string& name, + const std::string& message = std::string()); + + static JSObjectRef makeErrorObject(JSContextRef context, + const BasePlatformException& error); + + static JSObjectRef postException(JSContextRef context, + JSValueRef* exception, + const std::string& name, + const std::string& message = std::string()); + + static JSObjectRef postException(JSContextRef context, + JSValueRef* exception, + const BasePlatformException& error); + + static const std::string INDEX_SIZE_ERROR; + static const std::string DOMSTRING_SIZE_ERROR; + static const std::string HIERARCHY_REQUEST_ERROR; + static const std::string WRONG_DOCUMENT_ERROR; + static const std::string INVALID_CHARACTER_ERROR; + static const std::string NO_DATA_ALLOWED_ERROR; + static const std::string NO_MODIFICATION_ALLOWED_ERROR; + static const std::string NOT_FOUND_ERROR; + static const std::string NOT_SUPPORTED_ERROR; + static const std::string INUSE_ATTRIBUTE_ERROR; + static const std::string INVALID_STATE_ERROR; + static const std::string SYNTAX_ERROR; + static const std::string INVALID_MODIFICATION_ERROR; + static const std::string NAMESPACE_ERROR; + static const std::string INVALID_ACCESS_ERROR; + static const std::string VALIDATION_ERROR; + static const std::string TYPE_MISMATCH_ERROR; + static const std::string SECURITY_ERROR; + static const std::string NETWORK_ERROR; + static const std::string ABORT_ERROR; + static const std::string URL_MISMATCH_ERROR; + static const std::string QUOTA_EXCEEDED_ERROR; + static const std::string TIMEOUT_ERROR; + static const std::string INVALID_NODE_TYPE_ERROR; + static const std::string DATA_CLONE_ERROR; + static const std::string ENCODING_ERROR; + + static const std::string UNKNOWN_ERROR; + static const std::string INVALID_VALUES_ERROR; + static const std::string IO_ERROR; + static const std::string PERMISSION_DENIED_ERROR; + static const std::string SERVICE_NOT_AVAILABLE_ERROR; + +private: + static JSObjectRef createErrorObject(JSContextRef context, + const std::string& name, + const std::string& message, + const bool isException); + + static JSObjectRef createECMAErrorObject(JSContextRef context, + const std::string& name, + const std::string& message); +}; + +} // Common +} // DeviceAPI + +#endif // _JS_WEBAPI_ERROR_FACTORY_H_ diff --git a/wearable_src/Common/JSWebAPIException.cpp b/wearable_src/Common/JSWebAPIException.cpp new file mode 100644 index 0000000..0aac394 --- /dev/null +++ b/wearable_src/Common/JSWebAPIException.cpp @@ -0,0 +1,304 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "JSWebAPIException.h" +#include <string> +#include <map> +#include "JSUtil.h" +#include "JSStringRefWrapper.h" +#include "Logger.h" + +namespace DeviceAPI { +namespace Common { + +#define CLASS_NAME "WebAPIException" + +#define PROPERTY_CODE "code" +#define PROPERTY_NAME "name" +#define PROPERTY_TYPE "type" +#define PROPERTY_MESSAGE "message" + +#define PROPERTY_INDEX_SIZE_ERR "INDEX_SIZE_ERR" +#define PROPERTY_DOMSTRING_SIZE_ERR "DOMSTRING_SIZE_ERR" +#define PROPERTY_HIERARCHY_REQUEST_ERR "HIERARCHY_REQUEST_ERR" +#define PROPERTY_WRONG_DOCUMENT_ERR "WRONG_DOCUMENT_ERR" +#define PROPERTY_INVALID_CHARACTER_ERR "INVALID_CHARACTER_ERR" +#define PROPERTY_NO_DATA_ALLOWED_ERR "NO_DATA_ALLOWED_ERR" +#define PROPERTY_NO_MODIFICATION_ALLOWED_ERR "NO_MODIFICATION_ALLOWED_ERR" +#define PROPERTY_NOT_FOUND_ERR "NOT_FOUND_ERR" +#define PROPERTY_NOT_SUPPORTED_ERR "NOT_SUPPORTED_ERR" +#define PROPERTY_INUSE_ATTRIBUTE_ERR "INUSE_ATTRIBUTE_ERR" +#define PROPERTY_INVALID_STATE_ERR "INVALID_STATE_ERR" +#define PROPERTY_SYNTAX_ERR "SYNTAX_ERR" +#define PROPERTY_INVALID_MODIFICATION_ERR "INVALID_MODIFICATION_ERR" +#define PROPERTY_NAMESPACE_ERR "NAMESPACE_ERR" +#define PROPERTY_INVALID_ACCESS_ERR "INVALID_ACCESS_ERR" +#define PROPERTY_VALIDATION_ERR "VALIDATION_ERR" +#define PROPERTY_TYPE_MISMATCH_ERR "TYPE_MISMATCH_ERR" +#define PROPERTY_SECURITY_ERR "SECURITY_ERR" +#define PROPERTY_NETWORK_ERR "NETWORK_ERR" +#define PROPERTY_ABORT_ERR "ABORT_ERR" +#define PROPERTY_URL_MISMATCH_ERR "URL_MISMATCH_ERR" +#define PROPERTY_QUOTA_EXCEEDED_ERR "QUOTA_EXCEEDED_ERR" +#define PROPERTY_TIMEOUT_ERR "TIMEOUT_ERR" +#define PROPERTY_INVALID_NODE_TYPE_ERR "INVALID_NODE_TYPE_ERR" +#define PROPERTY_DATA_CLONE_ERR "DATA_CLONE_ERR" + +typedef std::map<std::string, int> DeviceAPIErrorCodeMap; + +static DeviceAPIErrorCodeMap errorCodes = { + { PROPERTY_INDEX_SIZE_ERR, 1 }, + { PROPERTY_DOMSTRING_SIZE_ERR, 2 }, + { PROPERTY_HIERARCHY_REQUEST_ERR, 3 }, + { PROPERTY_WRONG_DOCUMENT_ERR, 4 }, + { PROPERTY_INVALID_CHARACTER_ERR, 5 }, + { PROPERTY_NO_DATA_ALLOWED_ERR, 6 }, + { PROPERTY_NO_MODIFICATION_ALLOWED_ERR, 7 }, + { PROPERTY_NOT_FOUND_ERR, 8 }, + { PROPERTY_NOT_SUPPORTED_ERR, 9 }, + { PROPERTY_INUSE_ATTRIBUTE_ERR, 10 }, + { PROPERTY_INVALID_STATE_ERR, 11 }, + { PROPERTY_SYNTAX_ERR, 12 }, + { PROPERTY_INVALID_MODIFICATION_ERR, 13 }, + { PROPERTY_NAMESPACE_ERR, 14 }, + { PROPERTY_INVALID_ACCESS_ERR, 15 }, + { PROPERTY_VALIDATION_ERR, 16 }, + { PROPERTY_TYPE_MISMATCH_ERR, 17 }, + { PROPERTY_SECURITY_ERR, 18 }, + { PROPERTY_NETWORK_ERR, 19 }, + { PROPERTY_ABORT_ERR, 20 }, + { PROPERTY_URL_MISMATCH_ERR, 21 }, + { PROPERTY_QUOTA_EXCEEDED_ERR, 22 }, + { PROPERTY_TIMEOUT_ERR, 23 }, + { PROPERTY_INVALID_NODE_TYPE_ERR, 24 }, + { PROPERTY_DATA_CLONE_ERR, 25 } +}; + +JSClassRef JSWebAPIException::m_classRef = NULL; + +JSClassDefinition JSWebAPIException::m_classInfo = +{ + 0, + kJSClassAttributeNone, + CLASS_NAME, + 0, + m_properties, + m_function, + initialize, + finalize, + NULL, // hasProperty, + NULL, // getProperty, + NULL, // setProperty, + NULL, // deleteProperty, + NULL, // getPropertyNames, + NULL, // callAsFunction, + NULL, // callAsConstructor, + NULL, // hasInstance, + NULL, // convertToType, +}; + +JSStaticFunction JSWebAPIException::m_function[] = +{ + { "toString", toString, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +JSStaticValue JSWebAPIException::m_properties[] = { + { PROPERTY_CODE, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_NAME, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_TYPE, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_MESSAGE, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_INDEX_SIZE_ERR, getStaticProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_DOMSTRING_SIZE_ERR, getStaticProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_HIERARCHY_REQUEST_ERR, getStaticProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_WRONG_DOCUMENT_ERR, getStaticProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_INVALID_CHARACTER_ERR, getStaticProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_NO_DATA_ALLOWED_ERR, getStaticProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_NO_MODIFICATION_ALLOWED_ERR, getStaticProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_NOT_FOUND_ERR, getStaticProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_NOT_SUPPORTED_ERR, getStaticProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_INUSE_ATTRIBUTE_ERR, getStaticProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_INVALID_STATE_ERR, getStaticProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_SYNTAX_ERR, getStaticProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_INVALID_MODIFICATION_ERR, getStaticProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_NAMESPACE_ERR, getStaticProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_INVALID_ACCESS_ERR, getStaticProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_VALIDATION_ERR, getStaticProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_TYPE_MISMATCH_ERR, getStaticProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_SECURITY_ERR, getStaticProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_NETWORK_ERR, getStaticProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_ABORT_ERR, getStaticProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_URL_MISMATCH_ERR, getStaticProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_QUOTA_EXCEEDED_ERR, getStaticProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_TIMEOUT_ERR, getStaticProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_INVALID_NODE_TYPE_ERR, getStaticProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_DATA_CLONE_ERR, getStaticProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +const JSClassDefinition* JSWebAPIException::getClassInfo() +{ + return &m_classInfo; +} + +JSClassRef JSWebAPIException::getClassRef() +{ + if (!m_classRef) + { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +bool JSWebAPIException::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +JSObjectRef JSWebAPIException::createJSObject(JSContextRef context, WebAPIError* webapiError) +{ + JSObjectRef jsObjectRef = JSObjectMake(context, getClassRef(), static_cast<void*>(webapiError)); + if (NULL == jsObjectRef) { + LoggerE("object creation error"); + return NULL; + } + return jsObjectRef; +} + +WebAPIError* JSWebAPIException::getPriv(JSContextRef context, JSObjectRef object) +{ + if(!JSValueIsObjectOfClass(context, object, getClassRef())) + return NULL; + + return static_cast<WebAPIError*>(JSObjectGetPrivate(object)); +} + +JSObjectRef JSWebAPIException::constructor(JSContextRef context, + JSObjectRef constructor, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + return JSWebAPIErrorFactory::postException(context, exception, + JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, + "Illegal constructor"); +} + +void JSWebAPIException::initializeConstructor(JSContextRef context, JSObjectRef constructor) +{ + for(DeviceAPIErrorCodeMap::iterator iter = errorCodes.begin(); iter != errorCodes.end(); iter++) + { + JSStringRefWrapper name(iter->first); + JSValueRef value = JSValueMakeNumber(context, static_cast<double>(iter->second)); + JSObjectSetProperty(context, constructor, name.get(), value, kJSPropertyAttributeReadOnly, NULL); + } +} + +void JSWebAPIException::initialize(JSContextRef /*context*/, JSObjectRef /*object*/) +{ +} + +void JSWebAPIException::finalize(JSObjectRef /*object*/) +{ +} + +JSValueRef JSWebAPIException::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* /*exception*/) +{ + WebAPIError* webapiErrObj = getPriv(context, object); + if(!webapiErrObj) + { + LoggerE("Private object is not set."); + return JSValueMakeUndefined(context); + } + + try + { + std::string propertyNameStr = JSUtil::JSStringToString(context, propertyName); + + if (propertyNameStr == PROPERTY_CODE) + { + return JSUtil::toJSValueRef(context, static_cast<long>(webapiErrObj->getCode())); + } + else if (propertyNameStr == PROPERTY_NAME) + { + return JSUtil::toJSValueRef(context, webapiErrObj->getName()); + } + else if (propertyNameStr == PROPERTY_TYPE) + { + return JSUtil::toJSValueRef(context, webapiErrObj->getName()); + } + else if (propertyNameStr == PROPERTY_MESSAGE) + { + return JSUtil::toJSValueRef(context, webapiErrObj->getMessage()); + } + } + catch(const BasePlatformException & err) + { + LoggerE("Exception: " << err.getMessage()); + } + + return JSValueMakeUndefined(context); +} + +JSValueRef JSWebAPIException::getStaticProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* /*exception*/) +{ + try + { + std::string propertyNameStr = JSUtil::JSStringToString(context, propertyName); + + DeviceAPIErrorCodeMap::iterator iter = errorCodes.find(propertyNameStr); + if(iter != errorCodes.end()) + return JSUtil::toJSValueRef(context, static_cast<long>(iter->second)); + } + catch(const BasePlatformException & err) + { + LoggerE("Exception: " << err.getMessage()); + } + + return JSValueMakeUndefined(context); +} + +JSValueRef JSWebAPIException::toString(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + WebAPIError* webapiErrObj = getPriv(context, thisObject); + if(!webapiErrObj) + { + LoggerE("Private object is not set."); + return NULL; + } + + std::string name = webapiErrObj->getName(); + std::string message = webapiErrObj->getMessage(); + + std::string result = name + ": " + message; + + return JSUtil::toJSValueRef(context, result); +} + +} // Common +} // DeviceAPI diff --git a/wearable_src/Common/JSWebAPIException.h b/wearable_src/Common/JSWebAPIException.h new file mode 100644 index 0000000..cc726e5 --- /dev/null +++ b/wearable_src/Common/JSWebAPIException.h @@ -0,0 +1,88 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _JS_WEBAPI_EXCEPTION_H_ +#define _JS_WEBAPI_EXCEPTION_H_ + +#include <JavaScriptCore/JavaScript.h> +#include "JSWebAPIErrorFactory.h" + +#include "WebAPIError.h" + +namespace DeviceAPI { +namespace Common { + +class JSWebAPIErrorFactory; + +class JSWebAPIException +{ +public: + static JSClassRef getClassRef(); + + static const JSClassDefinition* getClassInfo(); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + static JSObjectRef constructor(JSContextRef context, + JSObjectRef constructor, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static void initializeConstructor(JSContextRef context, JSObjectRef constructor); + +private: + static JSObjectRef createJSObject(JSContextRef context, WebAPIError* webapiError); + + static WebAPIError* getPriv(JSContextRef context, JSObjectRef object); + + static void initialize(JSContextRef context, JSObjectRef object); + + static void finalize(JSObjectRef object); + + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getStaticProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef toString(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSClassDefinition m_classInfo; + + static JSStaticValue m_properties[]; + + static JSClassRef m_classRef; + + static JSStaticFunction m_function[]; + + friend class JSWebAPIErrorFactory; +}; + +} // Common +} // DeviceAPI + +#endif // _JS_WEBAPI_EXCEPTION_H_ diff --git a/wearable_src/Common/Logger.h b/wearable_src/Common/Logger.h new file mode 100644 index 0000000..5b3aba5 --- /dev/null +++ b/wearable_src/Common/Logger.h @@ -0,0 +1,63 @@ +// +// Tizen Web Device API +// Copyright (c) 2013 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 __TIZEN_COMMON_LOGGER_H__ +#define __TIZEN_COMMON_LOGGER_H__ + +#include <dlog.h> +#include <sstream> + +#undef LOG_TAG +#define LOG_TAG "WRT_PLUGINS/TIZEN" + +#define _LOGGER(prio, fmt, args...) \ + do { \ + std::ostringstream platformLog; \ + platformLog << "%s: %s(%d) > "; \ + platformLog << fmt; \ + print_log(prio, LOG_TAG, platformLog.str().c_str(), __MODULE__, __func__, __LINE__, ##args); \ + } while(0) + +#ifdef TIZEN_ENGINEER_MODE + #define LoggerD(fmt, args...) _LOGGER(DLOG_DEBUG, fmt, ##args) +#else + #define LoggerD(fmt, args...) do { } while(0) +#endif + +#define LoggerI(fmt, args...) _LOGGER(DLOG_INFO, fmt, ##args) +#define LoggerW(fmt, args...) _LOGGER(DLOG_WARN, fmt, ##args) +#define LoggerE(fmt, args...) _LOGGER(DLOG_ERROR, fmt, ##args) + + +#ifdef TIZEN_ENGINEER_MODE +#define _SLOGGER(prio, fmt, args...) \ + do { \ + std::ostringstream platformLog; \ + platformLog << "%s: %s(%d) > [SECURE_LOG] "; \ + platformLog << fmt; \ + print_log(prio, LOG_TAG, platformLog.str().c_str(), __MODULE__, __func__, __LINE__, ##args); \ + } while(0) +#else +#define _SLOGGER(prio,fmt,args...) do { } while(0) +#endif + +#define SLoggerD(fmt, args...) _SLOGGER(DLOG_DEBUG, fmt, ##args) +#define SLoggerI(fmt, args...) _SLOGGER(DLOG_INFO, fmt, ##args) +#define SLoggerW(fmt, args...) _SLOGGER(DLOG_WARN, fmt, ##args) +#define SLoggerE(fmt, args...) _SLOGGER(DLOG_ERROR, fmt, ##args) + +#endif // __TIZEN_COMMON_LOGGER_H__ diff --git a/wearable_src/Common/MultiCallbackUserData.cpp b/wearable_src/Common/MultiCallbackUserData.cpp new file mode 100755 index 0000000..449a61a --- /dev/null +++ b/wearable_src/Common/MultiCallbackUserData.cpp @@ -0,0 +1,151 @@ +// +// Tizen Web Device API +// Copyright (c) 2013 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "MultiCallbackUserData.h" +#include "GlobalContextManager.h" +#include "PlatformException.h" +#include "JSUtil.h" +#include "Logger.h" + +using namespace std; + +namespace DeviceAPI { +namespace Common { + +MultiCallbackUserData::MultiCallbackUserData(JSContextRef globalCtx): mContext(globalCtx), mObject(NULL){ +} + +MultiCallbackUserData::MultiCallbackUserData(JSContextRef globalCtx, JSObjectRef object): mContext(globalCtx), mObject(object){ + if( mObject ) + JSValueProtect(mContext, mObject); +} + +MultiCallbackUserData::~MultiCallbackUserData(){ + if( !GlobalContextManager::getInstance()->isAliveGlobalContext(mContext)){ + //Remove Callback functions in Native Map + CallbackMapT::iterator itr; + for( itr = mCallbacks.begin() ; itr != mCallbacks.end() ; ++itr){ + JSObjectRef t = itr->second; + if( t != NULL ) + JSValueUnprotect(mContext, t); + } + + //Remove Callback Object + if( mObject ){ + JSValueUnprotect(mContext, mObject); + mObject = NULL; + } + } +} + +void MultiCallbackUserData::setCallback(const string &key, JSObjectRef callback){ + + // Callback Object Case + if( mObject ){ + JSUtil::setProperty(mContext, mObject, key.c_str(), callback, kJSPropertyAttributeNone); + return; + } + + // Callback function Case + CallbackMapT::iterator itr; + itr = mCallbacks.find(key); + if( itr != mCallbacks.end() && itr->second != NULL){ + JSValueUnprotect(mContext, itr->second); + } + + if( callback != NULL ){ + JSValueProtect(mContext, callback); + } + + mCallbacks[key] = callback; +} + + +void MultiCallbackUserData::invokeCallback(const std::string &key, int count, JSValueRef obj [ ]){ + if( !GlobalContextManager::getInstance()->isAliveGlobalContext(mContext)){ + LOGE("context was closed"); + return; + } + + // Callback Object case + if( mObject ){ + try{ + // Getting callback value + JSValueRef callbackValue = JSUtil::getProperty(mContext, mObject, key.c_str()); + + // Testing existing + if( JSValueIsUndefined(mContext, callbackValue) ){ + LOGE("There is no such callback[%s]", key.c_str()); + return; + } + + JSObjectRef callbackObject = JSUtil::JSValueToObject(mContext, callbackValue); + + // Testing type validation + if( !JSObjectIsFunction( mContext, callbackObject) ){ + LOGE("%s is not function", key.c_str()); + return; + } + + JSValueRef exception = NULL; + JSObjectCallAsFunction(mContext, callbackObject, NULL, count, obj, &exception); + + // check Exception in function call + if( exception != NULL ){ + throw UnknownException(mContext, exception); + } + }catch( const BasePlatformException& err){ + LOGE("Error in Callback invoke - %s:%s", err.getName().c_str(), err.getMessage().c_str()); + } + return; + } + + // Callback function case + CallbackMapT::iterator itr; + itr = mCallbacks.find(key); + if( itr == mCallbacks.end()){ + LOGE("There is no such callback[%s]", key.c_str()); + return; + } + + if( itr->second ){ + JSObjectCallAsFunction(mContext, itr->second , NULL, count, obj, NULL); + }else{ + LOGE("The callback[%s] is NULL", key.c_str()); + } +} + +void MultiCallbackUserData::invokeCallback(const std::string &key, JSValueRef obj){ + JSValueRef args[1] = {obj}; + invokeCallback(key, 1, args); +} + +void MultiCallbackUserData::invokeCallback(const std::string &key){ + invokeCallback(key, 0, NULL); +} + +JSContextRef MultiCallbackUserData::getContext(){ + return mContext; +} + +void MultiCallbackUserData::cleanContext(){ + mContext = NULL; +} + +} +} + diff --git a/wearable_src/Common/MultiCallbackUserData.h b/wearable_src/Common/MultiCallbackUserData.h new file mode 100755 index 0000000..29ba5b0 --- /dev/null +++ b/wearable_src/Common/MultiCallbackUserData.h @@ -0,0 +1,58 @@ +// +// Tizen Web Device API +// Copyright (c) 2013 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _TIZEN_COMMON_MULTICALLBACKUSERDATA_ +#define _TIZEN_COMMON_MULTICALLBACKUSERDATA_ + +#include <JavaScriptCore/JavaScript.h> +#include <string> +#include <map> +#include <boost/shared_ptr.hpp> + +namespace DeviceAPI { +namespace Common{ + +class MultiCallbackUserData{ + public: + MultiCallbackUserData(JSContextRef globalCtx); + MultiCallbackUserData(JSContextRef globalCtx, JSObjectRef object); + virtual ~MultiCallbackUserData(); + JSContextRef getContext(); + void setCallback(const std::string &key, JSObjectRef callback); + + void invokeCallback(const std::string &key); + void invokeCallback(const std::string &key, JSValueRef obj); + void invokeCallback(const std::string &key, int count, JSValueRef obj[]); + + void cleanContext(); + + private: + JSContextRef mContext; + JSObjectRef mObject; + typedef std::map<const std::string, JSObjectRef> CallbackMapT; + std::map<const std::string, JSObjectRef> mCallbacks; +}; + +typedef boost::shared_ptr<MultiCallbackUserData> MultiCallbackUserDataPtr; + + +} +} + +#endif //_TIZEN_COMMON_MULTICALLBACKUSERDATA_ + + diff --git a/wearable_src/Common/PlatformException.cpp b/wearable_src/Common/PlatformException.cpp new file mode 100644 index 0000000..168664d --- /dev/null +++ b/wearable_src/Common/PlatformException.cpp @@ -0,0 +1,130 @@ +// +// Tizen Web Device API +// Copyright (c) 2013 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "PlatformException.h" +#include "JSUtil.h" +#include "JSWebAPIErrorFactory.h" +#include <CommonsJavaScript/Converter.h> + +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::Commons; + + + +namespace DeviceAPI { +namespace Common{ + +BasePlatformException::BasePlatformException(const char* name, const char* message):mName(name),mMessage(message){ +} + +BasePlatformException::BasePlatformException(JSContextRef context, JSValueRef value){ + JSObjectRef object = JSValueToObject(context, value, NULL); + if( object == NULL ) + return; + + JSValueRef message = JSUtil::getProperty(context, object, "message"); + JSValueRef name = JSUtil::getProperty(context, object, "name"); + + try{ + Converter convert(context); + if( !JSValueIsUndefined(context, message )) + mMessage = convert.toString(message); + if( !JSValueIsUndefined(context, name )) + mName = convert.toString(name); + }catch( const ConversionException& err){ + } +} + +BasePlatformException::~BasePlatformException() { +} + +std::string BasePlatformException::getName() const{ + return mName; +} + +std::string BasePlatformException::getMessage() const{ + return mMessage; +} + + +TypeMismatchException::TypeMismatchException(const char* message):BasePlatformException("TypeMismatchError", message){ +} +TypeMismatchException::TypeMismatchException(JSContextRef ctx, JSValueRef exception):BasePlatformException(ctx,exception){ + mName = "TypeMismatchError"; +} + +InvalidValuesException::InvalidValuesException(const char* message):BasePlatformException("InvalidValuesError", message){ +} +InvalidValuesException::InvalidValuesException(JSContextRef ctx, JSValueRef exception):BasePlatformException(ctx,exception){ + mName = "InvalidValuesError"; +} + +IOException::IOException(const char* message):BasePlatformException("IOError", message){ +} +IOException::IOException(JSContextRef ctx, JSValueRef exception):BasePlatformException(ctx,exception){ + mName = "IOError"; +} + + +UnknownException::UnknownException(const char* message):BasePlatformException("UnknownError", message){ +} +UnknownException::UnknownException(JSContextRef ctx, JSValueRef exception):BasePlatformException(ctx,exception){ + mName = "UnknownError"; +} + +ServiceNotAvailableException::ServiceNotAvailableException(const char* message):BasePlatformException("ServiceNotAvailableError", message){ +} +ServiceNotAvailableException::ServiceNotAvailableException(JSContextRef ctx, JSValueRef exception):BasePlatformException(ctx,exception){ + mName = "ServiceNotAvailableError"; +} + +SecurityException::SecurityException(const char* message):BasePlatformException("SecurityError", message){ +} +SecurityException::SecurityException(JSContextRef ctx, JSValueRef exception):BasePlatformException(ctx,exception){ + mName = "SecurityError"; +} + +NotSupportedException::NotSupportedException(const char* message):BasePlatformException("NotSupportedError", message){ +} +NotSupportedException::NotSupportedException(JSContextRef ctx, JSValueRef exception):BasePlatformException(ctx,exception){ + mName = "NotSupportedError"; +} + +NotFoundException::NotFoundException(const char* message):BasePlatformException("NotFoundError", message){ +} +NotFoundException::NotFoundException(JSContextRef ctx, JSValueRef exception):BasePlatformException(ctx,exception){ + mName = "NotFoundError"; +} + +InvalidAccessException::InvalidAccessException(const char* message):BasePlatformException("InvalidAccessError", message){ +} +InvalidAccessException::InvalidAccessException(JSContextRef ctx, JSValueRef exception):BasePlatformException(ctx,exception){ + mName = "InvalidAccessError"; +} + +QuotaExceededException::QuotaExceededException(const char* message):BasePlatformException("QuotaExceededError", message){ +} +QuotaExceededException::QuotaExceededException(JSContextRef ctx, JSValueRef exception):BasePlatformException(ctx,exception){ + mName = "QuotaExceededError"; +} + + + + +} +} diff --git a/wearable_src/Common/PlatformException.h b/wearable_src/Common/PlatformException.h new file mode 100644 index 0000000..cc73da9 --- /dev/null +++ b/wearable_src/Common/PlatformException.h @@ -0,0 +1,113 @@ +// +// Tizen Web Device API +// Copyright (c) 2013 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _PLATFORM_EXCEPTION_H_ +#define _PLATFORM_EXCEPTION_H_ + +#include <string> +#include <JavaScriptCore/JavaScript.h> + + +namespace DeviceAPI { +namespace Common{ + +class BasePlatformException{ +public: + BasePlatformException(const char* name, const char* message); + BasePlatformException(JSContextRef ctx, JSValueRef exception); + virtual ~BasePlatformException(); + + virtual std::string getName() const; + virtual std::string getMessage() const; + +protected: + std::string mName; + std::string mMessage; +}; + +class TypeMismatchException : public BasePlatformException{ +public: + TypeMismatchException(const char* message); + TypeMismatchException(JSContextRef ctx, JSValueRef exception); +}; + + +class InvalidValuesException : public BasePlatformException{ +public: + InvalidValuesException(const char* message); + InvalidValuesException(JSContextRef ctx, JSValueRef exception); +}; + + +class IOException : public BasePlatformException{ +public: + IOException(const char* message); + IOException(JSContextRef ctx, JSValueRef exception); +}; + + +class UnknownException : public BasePlatformException{ +public: + UnknownException(const char* message); + UnknownException(JSContextRef ctx, JSValueRef exception); +}; + +class ServiceNotAvailableException : public BasePlatformException{ +public: + ServiceNotAvailableException(const char* message); + ServiceNotAvailableException(JSContextRef ctx, JSValueRef exception); +}; + +class SecurityException : public BasePlatformException{ +public: + SecurityException(const char* message); + SecurityException(JSContextRef ctx, JSValueRef exception); +}; + +class NotSupportedException : public BasePlatformException{ +public: + NotSupportedException(const char* message); + NotSupportedException(JSContextRef ctx, JSValueRef exception); +}; + +class NotFoundException : public BasePlatformException{ +public: + NotFoundException(const char* message); + NotFoundException(JSContextRef ctx, JSValueRef exception); +}; + +class InvalidAccessException : public BasePlatformException{ +public: + InvalidAccessException(const char* message); + InvalidAccessException(JSContextRef ctx, JSValueRef exception); +}; + +class QuotaExceededException : public BasePlatformException{ +public: + QuotaExceededException(const char* message); + QuotaExceededException(JSContextRef ctx, JSValueRef exception); +}; + + + + +}} + + +#endif //_PLATFORM_EXCEPTION_H_ + diff --git a/wearable_src/Common/PropertyBag.cpp b/wearable_src/Common/PropertyBag.cpp new file mode 100755 index 0000000..2572745 --- /dev/null +++ b/wearable_src/Common/PropertyBag.cpp @@ -0,0 +1,261 @@ +// +// Tizen Web Device API +// Copyright (c) 2013 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "PropertyBag.h" +#include "Logger.h" +#include "JSUtil.h" +#include "GlobalContextManager.h" +#include "PlatformException.h" +#include <cmath> + +using namespace std; + +namespace DeviceAPI { +namespace Common { + +PropertyBag::PropertyBag(){ +} + +PropertyBag::~PropertyBag(){ + contextMapT::iterator contextItr; + for( contextItr = mContextMap.begin() ; contextItr != mContextMap.end() ; ++contextItr){ + propertyBagT::iterator propertyItr; + propertyBagT * bag = contextItr->second; + for( propertyItr = bag->begin(); propertyItr != bag->end(); ++propertyItr){ + JSValueRef v = propertyItr->second; + if( v != NULL ) + JSValueUnprotect(contextItr->first, v); + } + delete bag; + } +} + +std::map<const std::string, JSValueRef> * PropertyBag::getBag(JSContextRef globalCtx){ + //find property bag for the context + contextMapT::iterator itr; + itr = mContextMap.find(globalCtx); + propertyBagT *bag = NULL; + + if( itr == mContextMap.end() ){ + bag = new propertyBagT(); + mContextMap[globalCtx] = bag; + }else{ + bag = mContextMap[globalCtx]; + } + return bag; +} + +void PropertyBag::removeItem(JSContextRef globalCtx, propertyBagT *bag, const std::string& propertyName){ + if( bag == NULL ) + return; + propertyBagT::iterator item = bag->find(propertyName); + if( item != bag->end() && item->second != NULL){ + JSValueUnprotect(globalCtx, item->second); + bag->erase(item); + } +} + +void PropertyBag::deleteProperty(JSContextRef ctx, const std::string& propertyName){ + JSContextRef globalCtx = GlobalContextManager::getInstance()->getGlobalContext(ctx); + if( globalCtx == NULL ){ + LOGE("Cannot found global context!"); + return; + } + propertyBagT *bag = getBag(globalCtx); + removeItem(globalCtx, bag, propertyName); +} +void PropertyBag::deleteProperty(JSContextRef ctx, JSStringRef propertyName){ + deleteProperty(ctx, JSUtil::JSStringToString(ctx, propertyName)); +} + + +bool PropertyBag::setProperty(JSContextRef ctx, const std::string& propertyName, JSValueRef value){ + JSContextRef globalCtx = GlobalContextManager::getInstance()->getGlobalContext(ctx); + if( globalCtx == NULL ){ + LOGE("Cannot found global context!"); + return false; + } + propertyBagT *bag = getBag(globalCtx); + if( bag == NULL) + return false; + removeItem(globalCtx, bag, propertyName); + if( value != NULL ) + JSValueProtect(globalCtx, value); + (*bag)[propertyName] = value; + return true; +} + +bool PropertyBag::setProperty(JSContextRef ctx, const std::string& propertyName, double number){ + JSValueRef value = JSUtil::toJSValueRef(ctx, number); + return setProperty(ctx, propertyName, value); +} + +bool PropertyBag::setProperty(JSContextRef ctx, const std::string& propertyName, std::string& str){ + JSValueRef value = JSUtil::toJSValueRef(ctx, str); + return setProperty(ctx, propertyName, value); +} + +bool PropertyBag::setProperty(JSContextRef ctx, const std::string& propertyName, const char *str){ + string strvalue = string(str); + JSValueRef value = JSUtil::toJSValueRef(ctx, strvalue); + return setProperty(ctx, propertyName, value); +} + +bool PropertyBag::setProperty(JSContextRef ctx, const std::string& propertyName, bool boolean){ + JSValueRef value = JSUtil::toJSValueRef(ctx, boolean); + return setProperty(ctx, propertyName, value); +} + + +bool PropertyBag::setProperty(JSContextRef ctx, const std::string& propertyName, JSValueRef value, JSClassRef classRef){ + if( !JSValueIsObjectOfClass( ctx, value, classRef) ){ + LOGE("The value is incorrect type"); + return true; //ignore set property + } + return setProperty(ctx, propertyName, value); +} + + +bool PropertyBag::setFunctionProperty(JSContextRef ctx, const std::string& propertyName, JSValueRef function){ + JSObjectRef obj = JSUtil::JSValueToObject(ctx, function); + if( !JSObjectIsFunction( ctx, obj) ){ + LOGE("The value is incorrect type"); + return true; //ignore set property + } + return setProperty(ctx, propertyName, function); +} + +bool PropertyBag::setArrayProperty(JSContextRef ctx, const std::string& propertyName, JSValueRef array){ + if( !JSIsArrayValue(ctx, array)){ + LOGE("The value is not Array type"); + return true; //ignore set property + } + return setProperty(ctx, propertyName, array); +} + + +bool PropertyBag::setProperty(JSContextRef ctx, JSStringRef propertyName, JSValueRef value){ + return setProperty(ctx, JSUtil::JSStringToString(ctx, propertyName), value); +} +bool PropertyBag::setProperty(JSContextRef ctx, JSStringRef propertyName, double number){ + return setProperty(ctx, JSUtil::JSStringToString(ctx, propertyName), number); +} +bool PropertyBag::setProperty(JSContextRef ctx, JSStringRef propertyName, std::string& str){ + return setProperty(ctx, JSUtil::JSStringToString(ctx, propertyName), str); +} +bool PropertyBag::setProperty(JSContextRef ctx, JSStringRef propertyName, const char * str){ + return setProperty(ctx, JSUtil::JSStringToString(ctx, propertyName), str); +} +bool PropertyBag::setProperty(JSContextRef ctx, JSStringRef propertyName, bool boolean){ + return setProperty(ctx, JSUtil::JSStringToString(ctx, propertyName), boolean); +} +bool PropertyBag::setProperty(JSContextRef ctx, JSStringRef propertyName, JSValueRef value, JSClassRef classRef){ + return setProperty(ctx, JSUtil::JSStringToString(ctx, propertyName),value, classRef); +} +bool PropertyBag::setFunctionProperty(JSContextRef ctx, JSStringRef propertyName, JSValueRef function){ + return setFunctionProperty(ctx, JSUtil::JSStringToString(ctx, propertyName),function); +} +bool PropertyBag::setArrayProperty(JSContextRef ctx, JSStringRef propertyName, JSValueRef array){ + return setArrayProperty(ctx, JSUtil::JSStringToString(ctx, propertyName),array); +} + + + +JSValueRef PropertyBag::getProperty(JSContextRef ctx, const std::string& propertyName){ + JSContextRef globalCtx = GlobalContextManager::getInstance()->getGlobalContext(ctx); + if( globalCtx == NULL ){ + LOGE("Cannot found global context!"); + return NULL; + } + + propertyBagT *bag = getBag(globalCtx); + if( bag == NULL) + return NULL; + + propertyBagT::iterator item = bag->find(propertyName); + if( item == bag->end()){ + LOGE("Cannot found item"); + return NULL; + } + return item->second; +} + +double PropertyBag::getNumberProperty(JSContextRef ctx, const std::string& propertyName){ + JSValueRef value = getProperty(ctx, propertyName); + if( value == NULL ) + return 0.0; + try{ + return JSUtil::JSValueToDouble(ctx, value); + }catch(const BasePlatformException& err){ + LOGE("Cannot convert to number"); + } + return std::nan("not number"); +} + +double PropertyBag::getDoubleProperty(JSContextRef ctx, const std::string& propertyName){ + JSValueRef value = getProperty(ctx, propertyName); + if( value == NULL ) + return 0; + return JSUtil::JSValueToDouble(ctx, value); +} + +bool PropertyBag::getBooleanProperty(JSContextRef ctx, const std::string& propertyName){ + JSValueRef value = getProperty(ctx, propertyName); + if( value == NULL ) + return false; + return JSUtil::JSValueToBoolean(ctx, value); +} + +std::string PropertyBag::getStringProperty(JSContextRef ctx, const std::string& propertyName){ + JSValueRef value = getProperty(ctx, propertyName); + if( value == NULL ) + return "undefined"; + return JSUtil::JSValueToString(ctx, value); +} + +JSObjectRef PropertyBag::getObjectProperty(JSContextRef ctx, const std::string& propertyName){ + JSValueRef value = getProperty(ctx, propertyName); + if( value == NULL ) + return NULL; + if( !JSValueIsObject(ctx, value) ) + return NULL; + return JSUtil::JSValueToObject(ctx, value); +} + +double PropertyBag::getNumberProperty(JSContextRef ctx, JSStringRef propertyName){ + return getNumberProperty(ctx, JSUtil::JSStringToString(ctx, propertyName)); +} +double PropertyBag::getDoubleProperty(JSContextRef ctx, JSStringRef propertyName){ + return getDoubleProperty(ctx, JSUtil::JSStringToString(ctx, propertyName)); +} +bool PropertyBag::getBooleanProperty(JSContextRef ctx, JSStringRef propertyName){ + return getBooleanProperty(ctx, JSUtil::JSStringToString(ctx, propertyName)); +} +std::string PropertyBag::getStringProperty(JSContextRef ctx, JSStringRef propertyName){ + return getStringProperty(ctx, JSUtil::JSStringToString(ctx, propertyName)); +} +JSObjectRef PropertyBag::getObjectProperty(JSContextRef ctx, JSStringRef propertyName){ + return getObjectProperty(ctx, JSUtil::JSStringToString(ctx, propertyName)); +} +JSValueRef PropertyBag::getProperty(JSContextRef ctx, JSStringRef propertyName){ + return getProperty(ctx, JSUtil::JSStringToString(ctx,propertyName)); +} + + + +} //Common +} //DeviceAPI diff --git a/wearable_src/Common/PropertyBag.h b/wearable_src/Common/PropertyBag.h new file mode 100755 index 0000000..71709da --- /dev/null +++ b/wearable_src/Common/PropertyBag.h @@ -0,0 +1,94 @@ +// +// Tizen Web Device API +// Copyright (c) 2013 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 __TIZEN_COMMON_PROPERTY_BAG_H__ +#define __TIZEN_COMMON_PROPERTY_BAG_H__ + +#include <JavaScriptCore/JavaScript.h> +#include <string> +#include <map> + +namespace DeviceAPI { +namespace Common{ + +class PropertyBag{ +public: + PropertyBag(); + virtual ~PropertyBag(); + + void deleteProperty(JSContextRef ctx, const std::string& propertyName); + void deleteProperty(JSContextRef ctx, JSStringRef propertyName); + + + bool setProperty(JSContextRef ctx, const std::string& propertyName, JSValueRef value); + bool setProperty(JSContextRef ctx, JSStringRef propertyName, JSValueRef value); + + bool setProperty(JSContextRef ctx, const std::string& propertyName, double number); + bool setProperty(JSContextRef ctx, JSStringRef propertyName, double number); + + bool setProperty(JSContextRef ctx, const std::string& propertyName, std::string& str); + bool setProperty(JSContextRef ctx, JSStringRef propertyName, std::string& str); + + bool setProperty(JSContextRef ctx, const std::string& propertyName, const char *str); + bool setProperty(JSContextRef ctx, JSStringRef propertyName, const char * str); + + bool setProperty(JSContextRef ctx, const std::string& propertyName, bool boolean); + bool setProperty(JSContextRef ctx, JSStringRef propertyName, bool boolean); + + bool setProperty(JSContextRef ctx, const std::string& propertyName, JSValueRef value, JSClassRef classRef); + bool setProperty(JSContextRef ctx, JSStringRef propertyName, JSValueRef value, JSClassRef classRef); + + bool setFunctionProperty(JSContextRef ctx, const std::string& propertyName, JSValueRef function); + bool setFunctionProperty(JSContextRef ctx, JSStringRef propertyName, JSValueRef function); + + bool setArrayProperty(JSContextRef ctx, const std::string& propertyName, JSValueRef array); + bool setArrayProperty(JSContextRef ctx, JSStringRef propertyName, JSValueRef array); + + JSValueRef getProperty(JSContextRef ctx, const std::string& propertyName); + JSValueRef getProperty(JSContextRef ctx, JSStringRef propertyName); + + double getNumberProperty(JSContextRef ctx, const std::string& propertyName); + double getNumberProperty(JSContextRef ctx, JSStringRef propertyName); + + double getDoubleProperty(JSContextRef ctx, const std::string& propertyName); + double getDoubleProperty(JSContextRef ctx, JSStringRef propertyName); + + bool getBooleanProperty(JSContextRef ctx, const std::string& propertyName); + bool getBooleanProperty(JSContextRef ctx, JSStringRef propertyName); + + std::string getStringProperty(JSContextRef ctx, const std::string& propertyName); + std::string getStringProperty(JSContextRef ctx, JSStringRef propertyName); + + JSObjectRef getObjectProperty(JSContextRef ctx, const std::string& propertyName); + JSObjectRef getObjectProperty(JSContextRef ctx, JSStringRef propertyName); + +private: + typedef std::map<const std::string, JSValueRef> propertyBagT; + typedef std::map<JSContextRef, propertyBagT*> contextMapT; + std::map<JSContextRef, propertyBagT*> mContextMap; + + std::map<const std::string, JSValueRef> * getBag(JSContextRef globalCtx); + void removeItem(JSContextRef globalCtx, propertyBagT *bag, const std::string& propertyName); + +}; + + +} //Common +} //DeviceAPI + + +#endif //__TIZEN_COMMON_PROPERTY_BAG_H__ diff --git a/wearable_src/Common/SecurityExceptions.h b/wearable_src/Common/SecurityExceptions.h new file mode 100644 index 0000000..7ce0402 --- /dev/null +++ b/wearable_src/Common/SecurityExceptions.h @@ -0,0 +1,78 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 TIZENAPIS_COMMONS_JS_SECURITYEXCEPTIONS_H_ +#define TIZENAPIS_COMMONS_JS_SECURITYEXCEPTIONS_H_ + +#include <JavaScriptCore/JavaScript.h> +#include "JSWebAPIErrorFactory.h" + +namespace DeviceAPI { +namespace Common { + +/** + * synchronously checks access status and throws JS Security exception if + * necessary + */ + #define TIZEN_SYNC_ACCESS_HANDLER(status, context, exception) \ + do { \ + switch (status) { \ + case AceSecurityStatus::InternalError: \ + return JSWebAPIErrorFactory::postException(context, exception, \ + JSWebAPIErrorFactory::UNKNOWN_ERROR, "Internal error"); \ + break; \ + case AceSecurityStatus::PrivacyDenied: \ + return JSWebAPIErrorFactory::postException(context, exception, \ + JSWebAPIErrorFactory::SECURITY_ERROR, "The user blocks an application from calling this method."); \ + break; \ + case AceSecurityStatus::AccessDenied: \ + return JSWebAPIErrorFactory::postException(context, exception, \ + JSWebAPIErrorFactory::SECURITY_ERROR, "The application does not have the privilege to call this method."); \ + break; \ + default: \ + break; \ + } \ + } while (0) + +/** + * checks access status and returns an error through JSCallbackManager if + * necessary + */ +#define TIZEN_ASYNC_CBM_ACCESS_HANDLER(status, context, cbm) \ + do { \ + switch (status) { \ + case AceSecurityStatus::InternalError: \ + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, \ + JSWebAPIErrorFactory::UNKNOWN_ERROR, "Internal error")); \ + return JSValueMakeNull(context); \ + case AceSecurityStatus::PrivacyDenied: \ + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, \ + JSWebAPIErrorFactory::SECURITY_ERROR, "The user blocks an application from calling this method.")); \ + return JSValueMakeNull(context); \ + case AceSecurityStatus::AccessDenied: \ + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, \ + JSWebAPIErrorFactory::SECURITY_ERROR, "The application does not have the privilege to call this method.")); \ + return JSValueMakeNull(context); \ + default: \ + break; \ + } \ + } while (0) + +}// Common +}// DeviceAPI +#endif /*TIZENAPIS_COMMONS_JS_SECURITYEXCEPTIONS_H_ */ + diff --git a/wearable_src/Common/Singleton.h b/wearable_src/Common/Singleton.h new file mode 100644 index 0000000..89d65b4 --- /dev/null +++ b/wearable_src/Common/Singleton.h @@ -0,0 +1,50 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 Singleton.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include <Export.h> + +#ifndef _TIZEN_COMMONS_SINGLETON_H_ +#define _TIZEN_COMMONS_SINGLETON_H_ + +#define SINGLETON_DEFINITION(CLASSNAME) \ + class DLL_EXPORT CLASSNAME##Singleton : private CLASSNAME { \ + private: \ + CLASSNAME##Singleton() {} \ + static CLASSNAME##Singleton &InternalInstance(); \ + public: \ + virtual ~CLASSNAME##Singleton() {} \ + static CLASSNAME &Instance(); \ + }; + +#define SINGLETON_IMPLEMENTATION(CLASSNAME) \ + CLASSNAME##Singleton& CLASSNAME##Singleton::InternalInstance() { \ + static CLASSNAME##Singleton instance; \ + return instance; \ + } \ + CLASSNAME& CLASSNAME##Singleton::Instance() { \ + CLASSNAME##Singleton& instance = CLASSNAME##Singleton::InternalInstance(); \ + return instance; \ + } + +#endif // _TIZEN_COMMONS_SINGLETON_H_ diff --git a/wearable_src/Common/StandaloneConsole/CMakeLists.txt b/wearable_src/Common/StandaloneConsole/CMakeLists.txt new file mode 100644 index 0000000..a539bb5 --- /dev/null +++ b/wearable_src/Common/StandaloneConsole/CMakeLists.txt @@ -0,0 +1,24 @@ +SET(TARGET "standaloneconsole")
+
+SET(SRCS
+ JSConsole.cpp
+ StandaloneConsole.cpp
+)
+
+INCLUDE_DIRECTORIES( + ${TOP}/Common
+) +
+ +ADD_LIBRARY(${TARGET} SHARED ${SRCS})
+ +TARGET_LINK_LIBRARIES(${TARGET}
+ ${LIBS_COMMON}
+) + +INSTALL(TARGETS ${TARGET} LIBRARY DESTINATION ${DESTINATION_LIB_PREFIX}/${COMMON_DESTINATION_NAME})
+INSTALL( + DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/ DESTINATION ${DESTINATION_HEADER_PREFIX}/common + FILES_MATCHING PATTERN "*.h" PATTERN "CMakeFiles" EXCLUDE +) +
diff --git a/wearable_src/Common/StandaloneConsole/JSConsole.cpp b/wearable_src/Common/StandaloneConsole/JSConsole.cpp new file mode 100755 index 0000000..42fe5ad --- /dev/null +++ b/wearable_src/Common/StandaloneConsole/JSConsole.cpp @@ -0,0 +1,134 @@ +// +// Tizen Web Device API +// Copyright (c) 2013 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "JSConsole.h" +#include <CommonsJavaScript/Converter.h> +#include <stdio.h> +#include <dlog.h> +#include <sys/time.h> +#include <ctime> +#include <sys/time.h> + + +#undef LOG_TAG +#define LOG_TAG "TIZEN_DEVICEAPI" + +using namespace std; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::Commons; + + +namespace DeviceAPI { +namespace Test { + +JSClassRef JSConsole::m_jsClassRef = NULL; + +JSClassDefinition JSConsole::m_jsClassInfo = { + 0, // current (and only) version is 0 + kJSClassAttributeNone, //attributes + "console", //class name + NULL, // parent class + NULL, //static values + JSConsole::m_function, // static functions + JSConsole::initialize, // initialize + JSConsole::finalize, //finalize + NULL, //hasProperty + NULL, //getProperty + NULL, //setProperty + NULL, //deleteProperty + NULL, //getPropertyNames + NULL, // callAsConstructor + NULL, // constructor + JSConsole::hasInstance, + NULL // convertToType +}; + + +JSStaticFunction JSConsole::m_function[] = { + { "log", JSConsole::log, kJSPropertyAttributeNone }, + { "debug", JSConsole::log, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +const JSClassRef JSConsole::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_jsClassInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSConsole::getClassInfo() +{ + return &m_jsClassInfo; +} + + +JSObjectRef JSConsole::createJSObject( JSContextRef ctx ){ + return JSObjectMake(ctx, getClassRef(), NULL); +} + + +void JSConsole::initialize(JSContextRef ctx, JSObjectRef object) +{ +} + +void JSConsole::finalize(JSObjectRef object) +{ +} + +bool JSConsole::hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception) { + return JSValueIsObjectOfClass(context, possibleInstance, getClassRef()); +} + +#define timersub(a, b, result) \ +do { \ + (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \ + (result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \ + if ((result)->tv_usec < 0) { \ + --(result)->tv_sec; \ + (result)->tv_usec += 1000000; \ + } \ +} while (0) + +JSValueRef JSConsole::log(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception){ + static struct timeval prev = {0}; + struct timeval current = {0}; + struct timeval diff = {0}; + gettimeofday(¤t, NULL); + if( prev.tv_sec == 0 && prev.tv_usec == 0) + prev = current; + + timersub(¤t, &prev, &diff); + prev = current; + + Converter convert(ctx); + if( argumentCount == 0 ) + return JSValueMakeUndefined(ctx); + + try{ + string result = convert.toString(arguments[0]); + printf("<log[%d.%06d]>%s\n",(int)diff.tv_sec,(int)diff.tv_usec,result.c_str()); + LOGD("%s", result.c_str()); + }catch(const ConversionException& err){ + } + return JSValueMakeUndefined(ctx); +} + +} // Filesystem +} // TizenApis + diff --git a/wearable_src/Common/StandaloneConsole/JSConsole.h b/wearable_src/Common/StandaloneConsole/JSConsole.h new file mode 100644 index 0000000..5c6d08b --- /dev/null +++ b/wearable_src/Common/StandaloneConsole/JSConsole.h @@ -0,0 +1,53 @@ +// +// Tizen Web Device API +// Copyright (c) 2013 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _TIZEN_COMMON_JS_CONSOLE_ +#define _TIZEN_COMMON_JS_CONSOLE_ + +#include <JavaScriptCore/JavaScript.h> + +namespace DeviceAPI { +namespace Test{ + +class JSConsole{ +public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + + static JSObjectRef createJSObject(JSContextRef context); + +protected: + static void initialize(JSContextRef context, JSObjectRef object); + static void finalize(JSObjectRef object); + static bool hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception); + + static JSValueRef log(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + static JSValueRef assert(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + +private: + static JSClassDefinition m_jsClassInfo; + static JSClassRef m_jsClassRef; + static JSStaticFunction m_function[]; + +}; + +} // Test +} // TizenApis + +#endif //_TIZEN_COMMON_JS_CONSOLE_ + + diff --git a/wearable_src/Common/StandaloneConsole/StandaloneConsole.cpp b/wearable_src/Common/StandaloneConsole/StandaloneConsole.cpp new file mode 100755 index 0000000..3aba307 --- /dev/null +++ b/wearable_src/Common/StandaloneConsole/StandaloneConsole.cpp @@ -0,0 +1,582 @@ +// +// Tizen Web Device API +// Copyright (c) 2013 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <stdio.h> +#include <dlog.h> +#include <JavaScriptCore/JavaScript.h> +#include "StandaloneConsole.h" +#include "JSConsole.h" +#include <Ecore.h> +#include <GlobalContextManager.h> +#include <string> +#include <vector> +#include <iostream> +#include <termios.h> +#include <JSUtil.h> + +#undef LOG_TAG +#define LOG_TAG "TIZEN_DEVICEAPI" + +using namespace std; +using namespace DeviceAPI::Common; + +namespace DeviceAPI { +namespace Test { + +struct _Command{ + char * mLine; + StandaloneConsole *mConsole; + pthread_mutex_t *mLock; + _Command(const char * cmd, StandaloneConsole *console, pthread_mutex_t* lock){ + mLine = strdup(cmd); + mConsole = console; + mLock = lock; + } + ~_Command(){ + free(mLine); + } + void run(){ + mConsole->RunLine(mLine); + pthread_mutex_unlock(mLock); + } +}; + +struct CallbackData{ + JSObjectRef callback; + int id; + StandaloneConsole *console; +}; + +static Eina_Bool tick(void *data){ + return true; +} + +static Eina_Bool commandDispath(void *data){ + _Command *cmd = (_Command*)data; + cmd->run(); + delete cmd; + return false; +} + +Eina_Bool StandaloneConsole::timerCb(void *data){ + CallbackData *callback = (CallbackData*)data; + StandaloneConsole *console = callback->console; + map<int,int>::iterator itr; + itr = console->mTimerMap.find(callback->id); + if( itr == console->mTimerMap.end() ){ + JSValueUnprotect(console->getGlobalContext(), callback->callback); + delete callback; + return false; + } + if( itr->second == 0){ + console->mTimerMap.erase(itr); + JSValueUnprotect(console->getGlobalContext(), callback->callback); + delete callback; + return false; + } + if( callback->callback != NULL){ + JSObjectCallAsFunction(console->getGlobalContext(), callback->callback, NULL, 0, 0, NULL); + } + + if( itr->second == 2 ){ + console->mTimerMap.erase(itr); + JSValueUnprotect(console->getGlobalContext(), callback->callback); + delete callback; + return false; + } + + return true; +} + + +JSValueRef StandaloneConsole::alert(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception){ + if( argumentCount < 1 ) + return JSValueMakeUndefined(ctx); + + + //JSContextRef globalCtx = GlobalContextManager::getInstance()->getGlobalContext(ctx); + //printf(" local : %p, global : %p \n", ctx, globalCtx); + + JSStringRef str = JSValueToStringCopy(ctx, arguments[0], NULL); + if(str == NULL){ + return JSValueMakeUndefined(ctx); + } + int n = JSStringGetLength(str); + { + char cstr[n+1]; + JSStringGetUTF8CString(str, cstr,n+1); + printf("<alert>%s\n", cstr); + } + return JSValueMakeUndefined(ctx); +} + +JSValueRef StandaloneConsole::setInterval(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception){ + static int id = 0; + StandaloneConsole *console = static_cast<StandaloneConsole*>(JSObjectGetPrivate(thisObject)); + if( argumentCount < 2 ){ + if( exception != NULL){ + + } + return JSValueMakeUndefined(ctx); + } + int handleid = id++; + double interval = JSValueToNumber(ctx, arguments[1], NULL); + interval = interval/1000; + + console->mTimerMap.insert(pair<int,int>(handleid, 1)); + CallbackData *data = new CallbackData(); + JSValueProtect(console->getGlobalContext(), arguments[0]); + data->callback = JSValueToObject(ctx, arguments[0], NULL); + data->id = handleid; + data->console = console; + + ecore_timer_add( interval, StandaloneConsole::timerCb , data); + return JSValueMakeNumber(ctx, handleid); + +} + +JSValueRef StandaloneConsole::setTimeout(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception){ + static int id = 0; + StandaloneConsole *console = static_cast<StandaloneConsole*>(JSObjectGetPrivate(thisObject)); + + if( argumentCount < 2 ){ + if( exception != NULL){ + + } + return JSValueMakeUndefined(ctx); + } + int handleid = id++; + double interval = JSValueToNumber(ctx, arguments[1], NULL); + interval = interval/1000; + + console->mTimerMap.insert(pair<int,int>(handleid, 2)); + CallbackData *data = new CallbackData(); + JSValueProtect(console->getGlobalContext(), arguments[0]); + data->callback = JSValueToObject(ctx, arguments[0], NULL); + data->id = handleid; + data->console = console; + + ecore_timer_add( interval, StandaloneConsole::timerCb , data); + return JSValueMakeNumber(ctx, handleid); + +} + + +JSValueRef StandaloneConsole::clearInterval(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception){ + StandaloneConsole *console = static_cast<StandaloneConsole*>(JSObjectGetPrivate(thisObject)); + if(console == NULL) return JSValueMakeUndefined(ctx); + if( argumentCount < 1 ){ + printf("error clearInterval\n"); + if( exception != NULL){ + + } + return JSValueMakeUndefined(ctx); + } + + int handleid = JSValueToNumber(ctx, arguments[0], NULL); + map<int,int>::iterator it; + it = console->mTimerMap.find(handleid); + if( it != console->mTimerMap.end()) + console->mTimerMap[handleid] = 0; + return JSValueMakeUndefined(ctx); +} + + +static JSValueRef test(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception){ + return JSValueMakeUndefined(ctx); +} + + +static void setProperty(JSContextRef ctx , JSObjectRef object, const char *name, JSValueRef value, JSPropertyAttributes attributes) +{ + JSStringRef propertyName = JSStringCreateWithUTF8CString(name); + JSObjectSetProperty(ctx, object, propertyName, value,attributes, NULL ); + JSStringRelease(propertyName); +} + +static JSValueRef getProperty(JSContextRef ctx , JSObjectRef object, const char *name){ + JSValueRef value; + JSStringRef propertyName = JSStringCreateWithUTF8CString(name); + value = JSObjectGetProperty(ctx, object, propertyName, NULL); + JSStringRelease(propertyName); + return value; +} + +static char * toString(JSContextRef ctx , JSValueRef jsV){ + JSValueRef exception = NULL; + JSStringRef jsStr = JSValueToStringCopy(ctx, jsV, &exception); + if( exception != NULL ) + return NULL; + int n = JSStringGetMaximumUTF8CStringSize(jsStr); + char *buf = new char[n+1]; + JSStringGetUTF8CString(jsStr, buf, n+1); + JSStringRelease(jsStr); + return buf; +} + +StandaloneConsole::StandaloneConsole():mGlobalContext(NULL),mGlobalObject(NULL){ +} + +StandaloneConsole::~StandaloneConsole(){ +} + +void StandaloneConsole::initialize(){ + // Function table + JSStaticFunction functions[] = { + { "alert", StandaloneConsole::alert , kJSPropertyAttributeNone }, + { "setInterval", StandaloneConsole::setInterval , kJSPropertyAttributeNone }, + { "setTimeout", StandaloneConsole::setTimeout , kJSPropertyAttributeNone }, + { "clearInterval", StandaloneConsole::clearInterval , kJSPropertyAttributeNone }, + { "clearTimeout", StandaloneConsole::clearInterval , kJSPropertyAttributeNone }, + { "test", test, kJSPropertyAttributeNone }, + { 0, 0, 0 } + }; + + // Global class + JSClassDefinition def = { + 0, // current (and only) version is 0 + kJSClassAttributeNone, //attributes + "global", //class name + NULL, // parent class + NULL, //static values + functions, // static functions + NULL, // initialize + NULL, //finalize + NULL, //hasProperty + NULL, //getProperty + NULL, //setProperty + NULL, //deleteProperty + NULL, //getPropertyNames + NULL, // callAsConstructor + NULL, // constructor + NULL, + NULL // convertToType + }; + + JSClassRef globalClass = JSClassCreate(&def); + + mGlobalContext = JSGlobalContextCreate(globalClass); + mGlobalObject = JSContextGetGlobalObject(mGlobalContext); + JSObjectSetPrivate(mGlobalObject, this); + JSObjectRef console = JSConsole::createJSObject(mGlobalContext); + setProperty(mGlobalContext, mGlobalObject, "console", console, kJSPropertyAttributeReadOnly); + + + //is it ecore bug? event was not invoke, it was added in another thread + ecore_timer_add(0.001, tick, NULL); +} + + +JSObjectRef StandaloneConsole::getGlobalObject(){ + return mGlobalObject; +} + +JSContextRef StandaloneConsole::getGlobalContext(){ + return mGlobalContext; +} + + +JSValueRef StandaloneConsole::RunLineEx(const char* line, JSValueRef *exception){ + JSStringRef jsScript = JSStringCreateWithUTF8CString(line); + int size = strlen(line); + if( size != static_cast <int>(JSStringGetLength(jsScript))){ + cout <<"error - fail to converting JSStringRef"<<endl; + } + JSValueRef ret = JSEvaluateScript(mGlobalContext, jsScript, NULL, NULL, 0, exception); + JSStringRelease(jsScript); + return ret; +} + +JSValueRef StandaloneConsole::RunScriptEx(const char* path, JSValueRef *exception){ + + FILE* f = fopen(path, "r"); + if( f == NULL ){ + return NULL; + } + + fseek(f, 0, SEEK_END); + int length = ftell(f); + fseek(f, 0, SEEK_SET); + + if( length > 0 ) + { + char buff[length+1]; + memset(buff, 0, length+1); + int r = fread(buff, 1, length, f); + fclose(f); + + if( r != length ){ + printf("error read\n"); + return JSValueMakeUndefined(mGlobalContext); + } + return RunLineEx(buff, exception); + } + fclose(f); + return JSValueMakeUndefined(mGlobalContext); +} + +void StandaloneConsole::RunLine(const char * line){ + JSValueRef exception = NULL; + JSValueRef v = RunLineEx(line, &exception); + reportingResult(v,exception); +} + +void StandaloneConsole::RunScript(const char * path){ + JSValueRef exception = NULL; + JSValueRef v = RunScriptEx(path, &exception); + reportingResult(v,exception); +} + +void StandaloneConsole::GarbageCollect(){ + printf("GarbageCollect\n"); + JSGarbageCollect(mGlobalContext); +} +void StandaloneConsole::reportingResult(JSValueRef v, JSValueRef exception){ + if( exception != NULL ){ + char *errStr = toString(mGlobalContext, exception); + if( errStr != NULL ){ + printf("< error - %s\n", errStr); + delete[] errStr; + } + JSObjectRef errObj = JSValueToObject(mGlobalContext, exception, NULL); + if( errObj != NULL ){ + JSValueRef stack = getProperty(mGlobalContext, errObj, "stack"); + char *stackStr = NULL; + if( !JSValueIsUndefined(mGlobalContext, stack) && (stackStr = toString(mGlobalContext, stack )) != NULL){ + printf("stack:%s\n", stackStr); + delete[] stackStr; + } + } + }else{ + char *resultStr = toString(mGlobalContext, v); + if( resultStr != NULL ){ + printf("< %s\n", resultStr); + delete[] resultStr; + } + } +} + +JSObjectRef StandaloneConsole::registModule(const char * name, JSClassRef module, void * priv){ + JSObjectRef obj = JSObjectMake(mGlobalContext, module, priv); + setProperty(mGlobalContext, mGlobalObject, name, obj, kJSPropertyAttributeReadOnly); + return obj; +} + +void StandaloneConsole::appendModule(const char * name, JSObjectRef module){ + setProperty(mGlobalContext, mGlobalObject, name, module, kJSPropertyAttributeReadOnly); +} + + +int getch(void) +{ + int ch; + struct termios buf; + struct termios save; + + tcgetattr(0, &save); + buf = save; + buf.c_lflag &= ~(ICANON|ECHO); + buf.c_cc[VMIN] = 1; + buf.c_cc[VTIME] = 0; + tcsetattr(0, TCSAFLUSH, &buf); + ch = getchar(); + tcsetattr(0, TCSAFLUSH, &save); + return ch; +} + +struct termios gSave; + +void onExit(void) +{ + tcsetattr(0, TCSAFLUSH, &gSave); +} + +class LineBuffer{ + vector<string> mHistory; + string mLine; + int mHistoryIndex; + unsigned int mCurrentPos; + unsigned int mCurrentPosTmp; + int mLineLength; +public: + LineBuffer():mHistoryIndex(0), mCurrentPos(0){ + tcgetattr(0, &gSave); + atexit(onExit); + } + ~LineBuffer(){ + tcsetattr(0, TCSAFLUSH, &gSave); + } + + void backSpace( int length ){ + for( int i =0 ; i < length ; i++){ + putchar('\b'); + putchar(' '); + putchar('\b'); + } + } + + void cleanLine(){ + int diff = mLineLength - mCurrentPosTmp; + while( diff-- > 0 ){ + moveCursor(false); + } + backSpace(mLineLength); + } + + void applyHistory( unsigned int index ){ + if( mHistory.size() > index ){ + mLine = mHistory[index]; + mCurrentPos = mLine.size(); + } + } + + void moveCursor( bool Left ){ + putchar(27);putchar(91); + if( Left ) + putchar(68); + else + putchar(67); + } + + void moveCurrentCursorPosition(){ + int diff = mLine.size() - mCurrentPos; + + while( diff-- > 0 ){ + moveCursor(true); + } + } + + bool checkSpecialKeys(int a){ + if( a == 8 ){ + if( mLine.size() != 0 && mCurrentPos != 0){ + mCurrentPos--; + mLine.erase(mCurrentPos,1); + } + return true; + } + if( a == 27 ){ + a = getch(); // 91 + a = getch(); + switch( a ){ + case 65: + //UP + if( mHistoryIndex > 0 ){ + applyHistory(--mHistoryIndex); + } + break; + case 66: + //DOWN + if( (unsigned)mHistoryIndex < mHistory.size() ){ + applyHistory(++mHistoryIndex); + } + break; + case 67: + //RIGHT + if( mCurrentPos < mLine.size()) + mCurrentPos++; + break; + case 68: + //LEFT + if( mCurrentPos > 0 ) + mCurrentPos--; + break; + case 51: + //delete + getch(); + if( mCurrentPos < mLine.size()) + mLine.erase(mCurrentPos,1); + break; + case 52: + //end + getch(); + mCurrentPos = mLine.size(); + break; + case 49: + //home + mCurrentPos = 0; + a = getch(); + break; + default: + a = getch(); + } + + return true; + } + return false; + } + + string Prompt(const char * prompt){ + printf("%s", prompt); + mCurrentPos = 0; + mLine.clear(); + mLineLength = mLine.size(); + mCurrentPosTmp = mCurrentPos; + while(1){ + int a = getch(); + cleanLine(); + if( a == 10 ) + break; + + if(!checkSpecialKeys(a)){ + mLine.insert(mCurrentPos,1, a); + mCurrentPos++; + } + cout << mLine; + moveCurrentCursorPosition(); + mLineLength = mLine.size(); + mCurrentPosTmp = mCurrentPos; + } + cout << mLine; + if( mLine.size() > 0 ){ + mHistory.push_back(mLine); + mHistoryIndex = mHistory.size(); + } + return mLine; + } + +}; + + + +void StandaloneConsole::commandline(StandaloneConsole* console){ + pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; + pthread_mutex_lock(&lock); + printf("command line mode ( \"quit\" for exit )\n"); + LineBuffer linebuff; + while(1){ + string line = linebuff.Prompt(">"); + printf("\n"); + + if( line == "quit" ) + break; + if( line == "gc" ){ + console->GarbageCollect(); + continue; + } + if( line.size() == 0 ) + continue; + _Command *cmd = new _Command(line.c_str(), console, &lock); + // for thread safety + ecore_idler_add(commandDispath, cmd); + pthread_mutex_lock(&lock); + } +} + + +} +} + diff --git a/wearable_src/Common/StandaloneConsole/StandaloneConsole.h b/wearable_src/Common/StandaloneConsole/StandaloneConsole.h new file mode 100644 index 0000000..b125f8e --- /dev/null +++ b/wearable_src/Common/StandaloneConsole/StandaloneConsole.h @@ -0,0 +1,68 @@ +// +// Tizen Web Device API +// Copyright (c) 2013 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _TIZEN_COMMON_STANDALONECONSOLE_ +#define _TIZEN_COMMON_STANDALONECONSOLE_ + +#include <Ecore.h> +#include <map> +#include <JavaScriptCore/JavaScript.h> + +namespace DeviceAPI { +namespace Test{ + +class StandaloneConsole{ + public : + StandaloneConsole(); + virtual ~StandaloneConsole(); + void initialize(); + JSObjectRef getGlobalObject(); + JSContextRef getGlobalContext(); + + void RunLine(const char *line); + void RunScript(const char * path); + + void GarbageCollect(); + + + JSValueRef RunLineEx( const char *line , JSValueRef *exception); + JSValueRef RunScriptEx( const char *path , JSValueRef *exception); + + JSObjectRef registModule( const char *name, JSClassRef module, void *priv); + void appendModule( const char* name, JSObjectRef module ); + + static JSValueRef alert(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + static JSValueRef setInterval(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + static JSValueRef clearInterval(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + + static JSValueRef setTimeout(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + + static void commandline(StandaloneConsole *console); + + private: + static Eina_Bool timerCb(void *data); + void reportingResult(JSValueRef v, JSValueRef exception); + + JSContextRef mGlobalContext; + JSObjectRef mGlobalObject; + std::map<int,int> mTimerMap; +}; + +} +} + +#endif //_TIZEN_COMMON_STANDALONECONSOLE_ diff --git a/wearable_src/Common/TimeTracer/CMakeLists.txt b/wearable_src/Common/TimeTracer/CMakeLists.txt new file mode 100644 index 0000000..3dddade --- /dev/null +++ b/wearable_src/Common/TimeTracer/CMakeLists.txt @@ -0,0 +1,24 @@ +SET(TARGET "timetracer") + +SET(SRCS + TimeTracer.c +) + +INCLUDE_DIRECTORIES( + ${TOP}/Common +) + +ADD_DEFINITIONS("-DTIME_TRACER_UNIT_MSEC") + +ADD_LIBRARY(${TARGET} SHARED ${SRCS}) + +TARGET_LINK_LIBRARIES(${TARGET} + ${LIBS_COMMON} +) + +INSTALL(TARGETS ${TARGET} LIBRARY DESTINATION ${DESTINATION_LIB_PREFIX}/${COMMON_DESTINATION_NAME}) +INSTALL( + DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/ DESTINATION ${DESTINATION_HEADER_PREFIX}/common + FILES_MATCHING PATTERN "*.h" PATTERN "CMakeFiles" EXCLUDE +) + diff --git a/wearable_src/Common/TimeTracer/TimeTracer.c b/wearable_src/Common/TimeTracer/TimeTracer.c new file mode 100644 index 0000000..62432d7 --- /dev/null +++ b/wearable_src/Common/TimeTracer/TimeTracer.c @@ -0,0 +1,374 @@ +// +// Tizen Web Device API +// Copyright (c) 2013 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +#undef LOG_TAG +#define LOG_TAG "TIME_TRACER" + +#include <stdio.h> +#include <dlog.h> +#include <stdio.h> +#include <malloc.h> +#include <string.h> +#include <assert.h> +#include <sys/time.h> +#include <sys/utsname.h> +#include <sys/resource.h> +#include <sys/stat.h> +#include <sys/types.h> +#include <unistd.h> +#include <stdarg.h> +#include <stdlib.h> +#include <time.h> +#include "TimeTracer.h" + +/* +* Global Variables +*/ +#define TIME_TRACER_ITEM_MAX 500 +#define OUTPUT_DIR "/tmp/wrt-plugins-tizen-time-trace-result" + +time_tracer_item ** g_items = NULL; //Time tracer item list +static int g_index = 0; +static int g_max_item_name_length = 0; +static unsigned long g_first_time = 0xFFFFFFFF; + +/* +* Internal Implementation +*/ +static void __time_tracer_item_free(void) +{ + int i = 0; + if (!g_items) + return; + + for(i=0;i<g_index;i++) + { + if(g_items[i]) + { + if (g_items[i]->name) + free(g_items[i]->name); + free(g_items[i]); + g_items[i] = NULL; + } + } + + g_index = 0; + g_max_item_name_length = 0; + g_first_time = 0xFFFFFFFF; + free(g_items); + g_items = NULL; +} + +static int __get_time_tracer_item_index(char* name) +{ + int i; + assert(name); + if(!g_items) + return -1; + + for ( i = 0; i < g_index; i++ ) + { + if(!g_items[i]) + return -1; + if (strcmp(name, g_items[i]->name)==0) + return i; + } + return -1; +} + + +/* +* Implementation +*/ +int time_tracer_init(void) +{ + if (g_items) { + LOGW("[%s] Ignored. Already Initialized.", __FUNCTION__); + return 0; + } + g_items = (time_tracer_item **) malloc(TIME_TRACER_ITEM_MAX * sizeof(time_tracer_item *)); + if(!g_items) + { + LOGE("[%s] Failed to create global tracer item",__FUNCTION__); + return -1; + } + g_first_time = 0xFFFFFFFF; + LOGE("TIME TRACER INITIALIZED"); + return 0; +} + +int time_tracer_release(void) +{ + if (!g_items) + return 0; + LOGE("TIME TRACER DESTROYED"); + __time_tracer_item_free(); + return 0; +} + +int time_tracer_item_begin(const char* name, int show, const char* filename, int line) +{ + time_tracer_item *item = NULL; + int index = 0; + int name_len = 0; + struct timeval t; + + if (!g_items) + return 0; + + if (g_index == TIME_TRACER_ITEM_MAX) + { + LOGE("[%s] Do not exceed tracer item max value (max : %d, index : %d)",__FUNCTION__,TIME_TRACER_ITEM_MAX, g_index); + return -1; + } + + if (!name) + { + LOGE("[%s] Item name is NULL.",__FUNCTION__); + return -1; + } + + name_len = strlen(name); + if(name_len==0) + { + LOGE("[%s] Item name is Empty.",__FUNCTION__); + return -1; + } + + //1. Creates of gets the item + //1-1. Creates new item if 'name' is not exists. + if ((index = __get_time_tracer_item_index(name)) == -1) + { + item = (time_tracer_item *)malloc(sizeof(time_tracer_item)); + if ( !item ) + { + LOGE("[%s] Failed to create tracer item", __FUNCTION__); + return -1; + } + + //Clean-up + memset( item, 0, sizeof (time_tracer_item) ); + item->min_elapsed_time = 0xFFFFFFFF; + + item->name = strdup(name); + if (!item->name) + { + LOGE("[%s] Failed to strdup", __FUNCTION__); + free(item); + return -1; + } + + //Add to the global item array + g_items[g_index] = item; + g_index++; + + if ( g_max_item_name_length < name_len ) + g_max_item_name_length = name_len; + } + else // 1-2. Returns existing item + { + item = g_items[index]; + } + + + // 2. Gets the timestamp + gettimeofday( &t, NULL ); + item->timestamp = t.tv_sec*1000000L + t.tv_usec; +#ifdef TIME_TRACER_UNIT_MSEC + item->timestamp = ( item->timestamp >= 1000) ? item->timestamp/1000 : 0; +#endif + + + if (item->first_timestamp == 0) // in case of first + { + //set first timestamp + item->first_timestamp = item->timestamp; + if (g_first_time > item->first_timestamp) + g_first_time = item->first_timestamp; + } + + // 3. Verify pairs of begin, end + if (item->on_tracing) + { + LOGE("[%s] (Name : %s) is not 'end'ed!",__FUNCTION__, item->name); + item->mismatch_count ++; + return -1; + } + + //set tracing on + item->on_tracing = 1; + + if (show) + { + LOGE("[%s][BEGIN] %s (at %s:%d)", __FUNCTION__,name, filename, line ); + printf("[%s][BEGIN] %s (at %s:%d)\n", LOG_TAG,name, filename, line ); + } + //Add invoke count for given item + item->invoke_count++; + return 0; +} + +int time_tracer_item_end(const char* name, int show, const char* filename, int line) +{ + time_tracer_item * item = NULL; + unsigned int tval = 0; + int index = 0; + struct timeval t; + + if (!g_items) + return 0; + + // 1. Gets current timestamp first for more accuracy. + gettimeofday( &t, NULL ); + + if (g_index == TIME_TRACER_ITEM_MAX) + { + LOGE("[%s] Do not exceed tracer item max value (max : %d, index : %d)",__FUNCTION__,TIME_TRACER_ITEM_MAX, g_index); + return -1; + } + + if (!name) + { + LOGE("[%s] Item name is NULL.",__FUNCTION__); + return -1; + } + + if(strlen(name)==0) + { + LOGE("[%s] Item name is Empty.",__FUNCTION__); + return -1; + } + + //2. Gets the item + if ((index = __get_time_tracer_item_index(name)) == -1) + { + LOGE("[%s] (Name : %s) is not exist.",__FUNCTION__, name); + return -1; + } + item = g_items[index]; + + // 3. Verify pairs of begin, end + if (!item->on_tracing) + { + LOGE("[%s] (Name : %s) is not 'begin' yet",__FUNCTION__, item->name); + item->mismatch_count ++; + return -1; + } + + tval = t.tv_sec*1000000L + t.tv_usec; +#ifdef TIME_TRACER_UNIT_MSEC + tval = (tval>=1000) ? tval/1000 : 0; +#endif + + //set last timestamp as current time + item->last_timestamp = tval; + + //calculates the time gap(elapsed time) between current timestamp and item's timestamp. + tval = tval - item->timestamp; + + //set max_elapsed_time if current elapsed time is larger than item's max elasped time. + item->max_elapsed_time = tval > item->max_elapsed_time ? tval : item->max_elapsed_time; + //set min_elapsed_time if current elapsed time is less than item's min elasped time. + item->min_elapsed_time = tval < item->min_elapsed_time ? tval : item->min_elapsed_time; + + //Accumulates the item's total elapse time + item->total_elapsed_time += tval; + //set tracing off + item->on_tracing = 0; + + if (show) + { + LOGE("[%s][END] %s - total elapsed time(acc): %ld, current elased time : %d (at %s:%d)",__FUNCTION__, name, item->total_elapsed_time, tval, filename, line ); + printf("[%s][END] %s - total elapsed time(acc): %ld, current elased time : %d (at %s:%d)\n",LOG_TAG,name, item->total_elapsed_time, tval, filename, line ); + } + return 0; +} + +void time_tracer_export_report(int direction, char* name) +{ + int i = 0; + char format[256]; + FILE* fp = stderr; + + if (!g_items) + return; + + switch (direction) + { + case TIME_TRACER_EXPORT_STDOUT: + fp = stdout; + break; + case TIME_TRACER_EXPORT_STDERR: + fp = stderr; + break; + case TIME_TRACER_EXPORT_FILE: + if(mkdir(OUTPUT_DIR,0755)!=0) + { + LOGE("[%s] Failed to mkdir()",__FUNCTION__); + } + char f_name[256]; + if(name==NULL || strlen(name)==0) + sprintf(f_name,"%s/%s",OUTPUT_DIR,"default.log"); + else + sprintf(f_name,"%s/%s.%s",OUTPUT_DIR,name,"log"); + fp = fopen(f_name, "wt"); + if (!fp) + { + LOGE("[%s] Failed to fopen().",__FUNCTION__); + return; + } + break; + default: + LOGE("[%s] Invalid output direction.",__FUNCTION__); + return; + } + +#ifdef TIME_TRACER_UNIT_MSEC + sprintf(format, "[%%3d] %%-%ds|\tTotal:%%4ld,\tCnt:%%3ld,\tAvg:%%4ld,\tMin:%%4ld,\tMax:%%4ld,\tStart:%%4lu,\tEnd:%%4lu,\tMismatch:%%3ld\n", g_max_item_name_length); + fprintf(fp, "TIME TRACER REPORT [BEGIN]=========================== [# of Item:%d, unit(msec)]\n", g_index); + LOGE("TIME TRACER REPORT [BEGIN]=========================== [# of Item:%d, unit(msec)]", g_index); +#else + snprintf(format, sizeof(format)-1, "[%%3d] %%-%ds |\tTotal:%%ld,\tCnt:%%ld,\tAvg:%%ld,\tMin:%%ld,\tMax:%%ld,\tStart:%%lu,\tEnd:%%lu,\tMismatch:%%ld\n", g_max_item_name_length); + fprintf(fp, "TIME TRACER REPORT [BEGIN]=========================== [# of Item:%d, unit(usec)]\n", g_index); + LOGE("TIME TRACER REPORT [BEGIN]=========================== [# of Item:%d, unit(usec)]", g_index); +#endif + + for ( i = 0; i < g_index; i++ ) + { + if (g_items[i]->invoke_count == 0) + g_items[i]->invoke_count = 1; + + fprintf(fp,format,i, + g_items[i]->name, // item name + g_items[i]->total_elapsed_time, // total elasped time + g_items[i]->invoke_count, // # of call + (g_items[i]->total_elapsed_time == 0)?0:(int)(g_items[i]->total_elapsed_time / g_items[i]->invoke_count), // calculates the average elapsed time + g_items[i]->min_elapsed_time, // mininum elpased time + g_items[i]->max_elapsed_time,// maximum elpased time + g_items[i]->first_timestamp - g_first_time, //begin timestamp + g_items[i]->last_timestamp - g_first_time, //end timestamp + g_items[i]->mismatch_count ); // # of mismatch (begin - end mismatch) + + print_log(DLOG_ERROR, LOG_TAG, format,i,g_items[i]->name, g_items[i]->total_elapsed_time, g_items[i]->invoke_count, (g_items[i]->total_elapsed_time == 0)?0:(int)(g_items[i]->total_elapsed_time / g_items[i]->invoke_count), g_items[i]->min_elapsed_time, g_items[i]->max_elapsed_time, g_items[i]->first_timestamp - g_first_time, g_items[i]->last_timestamp - g_first_time, g_items[i]->mismatch_count ); + + } + fprintf(fp, "TIME TRACER REPORT [END] ============================\n"); + LOGE("TIME TRACER REPORT [END] ============================"); + + if ( direction == TIME_TRACER_EXPORT_FILE ) + fclose(fp); +} diff --git a/wearable_src/Common/TimeTracer/TimeTracer.h b/wearable_src/Common/TimeTracer/TimeTracer.h new file mode 100644 index 0000000..f203c91 --- /dev/null +++ b/wearable_src/Common/TimeTracer/TimeTracer.h @@ -0,0 +1,76 @@ +// +// Tizen Web Device API +// Copyright (c) 2013 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 __TIZEN_COMMON_TIME_TRACER__ +#define __TIZEN_COMMON_TIME_TRACER__ + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct _time_tracer_item +{ + char* name; + unsigned long total_elapsed_time; + unsigned long min_elapsed_time; + unsigned long max_elapsed_time; + unsigned long first_timestamp; + unsigned long last_timestamp; + unsigned long timestamp; + int on_tracing; + int invoke_count; + int mismatch_count; +} time_tracer_item; + +/* COMMON */ +int time_tracer_init(void); +int time_tracer_release(void); +void time_tracer_export_report(int direction, char* name); +int time_tracer_item_begin(const char* name, int show,const char* filename, int line); +int time_tracer_item_end(const char* name, int show, const char* filename, int line); + +#define TIME_TRACER_EXPORT_STDOUT 0 +#define TIME_TRACER_EXPORT_STDERR 1 +#define TIME_TRACER_EXPORT_FILE 2 + +#ifdef ENABLE_TIME_TRACER +//Initialize the time tracer +#define TIME_TRACER_INIT() (time_tracer_init()) +//Release the time tracer +#define TIME_TRACER_RELEASE() (time_tracer_release()) +//Export tracing report to stdout +#define TIME_TRACER_EXPORT_REPORT() (time_tracer_export_report(TIME_TRACER_EXPORT_STDOUT,NULL)) +//Export tracing report to user specific direction (stdout, stderr, file) +#define TIME_TRACER_EXPORT_REPORT_TO(x,y) (time_tracer_export_report(x,y)) +//Set tracing point to begin +#define TIME_TRACER_ITEM_BEGIN(name,show) (time_tracer_item_begin(name,show,__FILE__,__LINE__)) +//Set tracing point to end +#define TIME_TRACER_ITEM_END(name,show) (time_tracer_item_end(name,show,__FILE__,__LINE__) ) +#else +#define TIME_TRACER_INIT() +#define TIME_TRACER_RELEASE() +#define TIME_TRACER_EXPORT_REPORT() +#define TIME_TRACER_EXPORT_REPORT_TO(x,y) +#define TIME_TRACER_ITEM_BEGIN(name,show) +#define TIME_TRACER_ITEM_END(name,show) +#endif + +#ifdef __cplusplus +} +#endif + +#endif //__TIZEN_COMMON_TIME_TRACER__ diff --git a/wearable_src/Common/WebAPIError.cpp b/wearable_src/Common/WebAPIError.cpp new file mode 100644 index 0000000..e8e1909 --- /dev/null +++ b/wearable_src/Common/WebAPIError.cpp @@ -0,0 +1,49 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "WebAPIError.h" + +namespace DeviceAPI { +namespace Common { + +WebAPIError::WebAPIError(const int code, const std::string& name, const std::string& message) : + m_code(code), + m_name(name), + m_message(message) +{ +} + +WebAPIError::~WebAPIError() +{ +} + +int WebAPIError::getCode() const +{ + return m_code; +} + +std::string WebAPIError::getName() const +{ + return m_name; +} + +std::string WebAPIError::getMessage() const +{ + return m_message; +} + +} // Common +} // DeviceAPI diff --git a/wearable_src/Common/WebAPIError.h b/wearable_src/Common/WebAPIError.h new file mode 100644 index 0000000..323fb81 --- /dev/null +++ b/wearable_src/Common/WebAPIError.h @@ -0,0 +1,46 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _WEBAPI_ERROR_H_ +#define _WEBAPI_ERROR_H_ + +#include <string> +#include <dpl/shared_ptr.h> + +namespace DeviceAPI { +namespace Common { + +class WebAPIError +{ +public: + WebAPIError(const int code, const std::string& name, const std::string& message = std::string()); + virtual ~WebAPIError(); + + int getCode() const; + std::string getName() const; + std::string getMessage() const; + +private: + int m_code; + std::string m_name; + std::string m_message; +}; + +} // Common +} // DeviceAPI + +#endif // _WEBAPI_ERROR_H_ diff --git a/wearable_src/Content/AudioLyrics.cpp b/wearable_src/Content/AudioLyrics.cpp new file mode 100755 index 0000000..abb30fd --- /dev/null +++ b/wearable_src/Content/AudioLyrics.cpp @@ -0,0 +1,66 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <Commons/Exception.h> +#include "AudioLyrics.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Content { + +MediacontentLyrics::MediacontentLyrics() +{ +} + +MediacontentLyrics::~MediacontentLyrics() +{ +} + + +string MediacontentLyrics::getMediaLyricsType() const +{ + return m_lyricsType; +} + +void MediacontentLyrics::setMediaLyricsType(string value) +{ + m_lyricsType = value; +} + +vector<unsigned long> MediacontentLyrics::getMediaLyricsTimeStamps() const +{ + return m_timeStamps; +} + +void MediacontentLyrics::addMediaLyricsTimeStamp(unsigned long value) +{ + m_timeStamps.push_back(value); +} + +vector<string> MediacontentLyrics::getMediaLyricsTexts() const +{ + return m_texts; +} + +void MediacontentLyrics::addMediaLyricsText(string value) +{ + m_texts.push_back(value); +} + + +} +} diff --git a/wearable_src/Content/AudioLyrics.h b/wearable_src/Content/AudioLyrics.h new file mode 100755 index 0000000..469029f --- /dev/null +++ b/wearable_src/Content/AudioLyrics.h @@ -0,0 +1,65 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _ABSTRACT_LAYER_CONTENT_LYRICS_H_ +#define _ABSTRACT_LAYER_CONTENT_LYRICS_H_ + +#include <ctime> +#include <string> +#include <vector> +#include <dpl/optional.h> +#include <dpl/shared_ptr.h> + +using namespace std; + +namespace DeviceAPI { +namespace Content { + + +class MediacontentLyrics +{ + + public: + + MediacontentLyrics(); + virtual ~MediacontentLyrics(); + + string getMediaLyricsType() const; + vector<string> getMediaLyricsTexts() const; + vector<unsigned long> getMediaLyricsTimeStamps() const; + + void setMediaLyricsType(string value); + void addMediaLyricsText(string value); + void addMediaLyricsTimeStamp(unsigned long value); + + private: + string m_lyricsType; + vector<unsigned long> m_timeStamps; + vector<string> m_texts; + +}; + + +typedef DPL::SharedPtr<MediacontentLyrics> MediacontentLyricsPtr; + + +} +} + +#endif /* _ABSTRACT_LAYER_CONTENT_LYRICS_H_ */ + diff --git a/wearable_src/Content/AudioLyricsUtil.cpp b/wearable_src/Content/AudioLyricsUtil.cpp new file mode 100755 index 0000000..be7b2be --- /dev/null +++ b/wearable_src/Content/AudioLyricsUtil.cpp @@ -0,0 +1,141 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "AudioLyricsUtil.h" +#include <dpl/singleton_impl.h> +#include <metadata_extractor.h> +#include <Logger.h> + + + +IMPLEMENT_SINGLETON(DeviceAPI::Content::MediaLyricsUtil) + +namespace DeviceAPI { +namespace Content { + +metadata_extractor_h m_extractor = NULL; +MediaLyricsUtil::MediaLyricsUtil() +{ + if ( METADATA_EXTRACTOR_ERROR_NONE != metadata_extractor_create(&m_extractor)) + { + LoggerD("MetaData Extractor create Fail..."); + } +} + +MediaLyricsUtil::~MediaLyricsUtil() +{ + if ( m_extractor && METADATA_EXTRACTOR_ERROR_NONE != metadata_extractor_destroy(m_extractor)) + { + LoggerD("Metadata extractor destory Fail..."); + } +} + +MediacontentLyricsPtr MediaLyricsUtil::fetchLyrics(string filepath) +{ + MediacontentLyricsPtr result; + //MediacontentLyricsPtr lyricsPtr(new MediacontentLyrics()); + //set path. + + if (m_extractor) + { + if ( METADATA_EXTRACTOR_ERROR_NONE == metadata_extractor_set_path(m_extractor, filepath.c_str()) ) + { + char* strSyncTextNum=NULL; + metadata_extractor_attr_e attr = METADATA_SYNCLYRICS_NUM; + if ( METADATA_EXTRACTOR_ERROR_NONE == metadata_extractor_get_metadata(m_extractor, attr, &strSyncTextNum) + && strSyncTextNum ) + { + int nSyncTextNum = 0; + istringstream(strSyncTextNum) >> nSyncTextNum; + free(strSyncTextNum); + strSyncTextNum = NULL; + if ( nSyncTextNum > 0) + { + MediacontentLyricsPtr lyricsPtr(new MediacontentLyrics()); + lyricsPtr->setMediaLyricsType("SYNCHRONIZED"); + for(int i=0; i < nSyncTextNum; i++) + { + unsigned long time_info = 0; + char * lyrics = NULL; + if ( METADATA_EXTRACTOR_ERROR_NONE == + metadata_extractor_get_synclyrics(m_extractor, i, &time_info, &lyrics)) + { + lyricsPtr->addMediaLyricsTimeStamp(time_info); + if(lyrics != NULL) + { + lyricsPtr->addMediaLyricsText(lyrics); + //LoggerI( "[" << time_info << "]"<< "lyrics : " << lyrics); + } + else + { + lyricsPtr->addMediaLyricsText(""); + } + } + if(lyrics != NULL) + { + free(lyrics); + } + } + result = lyricsPtr; + } + else + { + char* unSyncText = NULL; + attr = METADATA_UNSYNCLYRICS; + + if ( METADATA_EXTRACTOR_ERROR_NONE == metadata_extractor_get_metadata(m_extractor, attr, &unSyncText) ) + { + if (unSyncText) + { + MediacontentLyricsPtr lyricsPtr(new MediacontentLyrics()); + lyricsPtr->setMediaLyricsType("UNSYNCHRONIZED"); + lyricsPtr->addMediaLyricsTimeStamp(0); + lyricsPtr->addMediaLyricsText(unSyncText); + + result = lyricsPtr; + + free(unSyncText); + unSyncText = NULL; + } + } + + } + + } + else + { + LoggerD("extractor Error!!!"); + } + + } + + } + else + { + LoggerD(" extractor is invaild "); + } + + return result; +} + +} +} + + + + + diff --git a/wearable_src/Content/AudioLyricsUtil.h b/wearable_src/Content/AudioLyricsUtil.h new file mode 100755 index 0000000..17b7afe --- /dev/null +++ b/wearable_src/Content/AudioLyricsUtil.h @@ -0,0 +1,44 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _TIZEN_MEDIA_LYRICS_UTIL_H_ +#define _TIZEN_MEDIA_LYRICS_UTIL_H_ + +#include <dpl/singleton.h> +#include "AudioLyrics.h" + +namespace DeviceAPI { +namespace Content { + + class MediaLyricsUtil + { + public: + MediaLyricsUtil(); + virtual ~MediaLyricsUtil(); + + MediacontentLyricsPtr fetchLyrics(string filepath); + + friend class DPL::Singleton<MediaLyricsUtil>; + }; + + typedef DPL::Singleton<MediaLyricsUtil> MediaLyricsUtilSingleton; + +} +} +#endif // _TIZEN_MEDIA_LYRICS_UTIL_H_ + diff --git a/wearable_src/Content/CMakeLists.txt b/wearable_src/Content/CMakeLists.txt new file mode 100755 index 0000000..be79b64 --- /dev/null +++ b/wearable_src/Content/CMakeLists.txt @@ -0,0 +1,71 @@ +SET(TARGET_NAME ${content_target}) +SET(DESTINATION_NAME ${content_dest}) +SET(TARGET_IMPL_NAME ${content_impl}) + +PKG_CHECK_MODULES(platform_pkgs_content REQUIRED capi-content-media-content capi-media-metadata-extractor) + +INCLUDE_DIRECTORIES( + ${INCLUDE_COMMON} + ${TOP}/Tizen + ${platform_pkgs_content_INCLUDE_DIRS} +) + +SET(CMAKE_INSTALL_RPATH + ${CMAKE_INSTALL_RPATH} + ${CMAKE_INSTALL_PREFIX}/${DESTINATION_LIB_PREFIX}/${tizen_dest} + ${CMAKE_INSTALL_PREFIX}/${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME} +) + +SET(SRCS_IMPL + AudioLyrics.cpp + AudioLyricsUtil.cpp + ContentAsyncCallbackManager.cpp + ContentAudio.cpp + ContentController.cpp + ContentConverter.cpp + ContentFactory.cpp + ContentFilterValidator.cpp + ContentFilterConverter.cpp + ContentFolder.cpp + ContentImage.cpp + ContentManager.cpp + ContentMedia.cpp + ContentSearchVisitor.cpp + ContentVideo.cpp + IContentManager.cpp + JSAudio.cpp + JSAudioLyrics.cpp + JSContent.cpp + JSContentManager.cpp + JSFolder.cpp + JSImage.cpp + JSVideo.cpp + ContentListener.cpp + ContentUtility.cpp +) + +ADD_LIBRARY(${TARGET_IMPL_NAME} SHARED ${SRCS_IMPL}) + +TARGET_LINK_LIBRARIES(${TARGET_IMPL_NAME} + ${LIBS_COMMON} + ${tizen_impl} + ${platform_pkgs_content_LIBRARIES} +) + +SET(SRCS + plugin_config.cpp + plugin_initializer.cpp +) + +ADD_LIBRARY(${TARGET_NAME} SHARED ${SRCS}) + +TARGET_LINK_LIBRARIES(${TARGET_NAME} + ${TARGET_IMPL_NAME} +) + +INSTALL(TARGETS ${TARGET_NAME} ${TARGET_IMPL_NAME} LIBRARY DESTINATION ${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME}) +INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/config.xml DESTINATION ${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME}) +INSTALL( + DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/ DESTINATION ${DESTINATION_HEADER_PREFIX}/content + FILES_MATCHING PATTERN "*.h" PATTERN "CMakeFiles" EXCLUDE +) diff --git a/wearable_src/Content/ContentAsyncCallbackManager.cpp b/wearable_src/Content/ContentAsyncCallbackManager.cpp new file mode 100755 index 0000000..fcb37eb --- /dev/null +++ b/wearable_src/Content/ContentAsyncCallbackManager.cpp @@ -0,0 +1,29 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "ContentAsyncCallbackManager.h" +#include <dpl/singleton_impl.h> + + + +IMPLEMENT_SINGLETON(DeviceAPI::Content::MediaContentAsyncCallbackManager) + +namespace DeviceAPI { +namespace Content { + +} +} diff --git a/wearable_src/Content/ContentAsyncCallbackManager.h b/wearable_src/Content/ContentAsyncCallbackManager.h new file mode 100755 index 0000000..e24a829 --- /dev/null +++ b/wearable_src/Content/ContentAsyncCallbackManager.h @@ -0,0 +1,51 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _TIZEN_CONTENT_ASYNC_CALLBACK_MANAGER_H_ +#define _TIZEN_CONTENT_ASYNC_CALLBACK_MANAGER_H_ + +#include <dpl/singleton.h> +#include <AsyncCallbackManager.h> + + namespace DeviceAPI { + namespace Content { + + class MediaContentAsyncCallbackManager : public DeviceAPI::Common::AsyncCallbackManager + { + public: + MediaContentAsyncCallbackManager() + { + } + + virtual ~MediaContentAsyncCallbackManager() + { + } + + friend class DPL::Singleton<MediaContentAsyncCallbackManager>; + }; + + typedef DPL::Singleton<MediaContentAsyncCallbackManager> MediaContentAsyncCallbackManagerSingleton; + +} +} + +#endif // _TIZEN_CONTENT_ASYNC_CALLBACK_MANAGER_H_ + + + + diff --git a/wearable_src/Content/ContentAudio.cpp b/wearable_src/Content/ContentAudio.cpp new file mode 100755 index 0000000..24e6ce5 --- /dev/null +++ b/wearable_src/Content/ContentAudio.cpp @@ -0,0 +1,197 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <Commons/Exception.h> +#include "ContentAudio.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Content { + + +MediacontentAudio::MediacontentAudio() +{ + m_lyricsState = CONTENT_LYRIC_UNKNOWN; +} + +MediacontentAudio::~MediacontentAudio() +{ +} + + +string MediacontentAudio::getAudioAlbum() const +{ + return m_audioAlbum; +} +vector<std::string> MediacontentAudio::getAudioArtist() const +{ + return m_audioArtist; +} + +vector<std::string> MediacontentAudio::getAudioGenre() const +{ + return m_audioGenre; +} +vector<std::string> MediacontentAudio::getAudioComposer() const +{ + return m_audioAuthor; +} + +string MediacontentAudio::getAudioCopyright() const +{ + return m_audioCopyright; +} + +int MediacontentAudio::getAudioBitrate() const +{ + return m_audioBitrate; +} + + +int MediacontentAudio::getAudioTrackNum() const +{ + return m_audioTrackNum; +} + +int MediacontentAudio::getAudioDuration() const +{ + return m_audioDuration; +} + +unsigned long long MediacontentAudio::getAudioSize() const +{ + return m_audioSize; +} + +MediacontentLyricsPtr MediacontentAudio::getAudioLyrics() const +{ + return m_lyrics; +} + +void MediacontentAudio::setAudioAlbum(const string &value, bool isChanged) +{ + m_audioAlbum = value; + m_isChangedAudioAlbum = isChanged; +} + +void MediacontentAudio::setAudioArtist(const vector<std::string> &value, bool isChanged) +{ + m_audioArtist = value; + m_isChangedAudioArtist = isChanged; +} + +void MediacontentAudio::setAudioGenre(const vector<std::string> &value, bool isChanged) +{ + m_audioGenre = value; + m_isChangedAudioGenre = isChanged; +} + +void MediacontentAudio::setAudioComposer(const vector<std::string> &value, bool isChanged) +{ + m_audioAuthor = value; + m_isChangedAudioComposer = isChanged; +} + +void MediacontentAudio::setAudioCopyright(const string &value) +{ + m_audioCopyright = value; +} + +void MediacontentAudio::setAudioBitrate(const int &value) +{ + m_audioBitrate = value; +} + +void MediacontentAudio::setAudioTrackNum(const int &value, bool isChanged) +{ + m_audioTrackNum = value; + m_isChangedAudioTrackNumber = isChanged; +} + +void MediacontentAudio::setAudioDuration(const int &value) +{ + m_audioDuration = value; +} + +void MediacontentAudio::setAudioSize(const unsigned long long &value) +{ + m_audioSize = value; +} + +void MediacontentAudio::setAudioLyrics(MediacontentLyricsPtr value) +{ + m_lyrics = value; + m_lyricsState = CONTENT_LYRIC_EXISTENT; +} + + +bool MediacontentAudio::isChangedAudioAlbum() +{ + return m_isChangedAudioAlbum; +} + +bool MediacontentAudio::isChangedAudioArtist() +{ + return m_isChangedAudioArtist; +} +bool MediacontentAudio::isChangedAudioGenre() +{ + return m_isChangedAudioGenre; +} + +bool MediacontentAudio::isChangedAudioComposer() +{ + return m_isChangedAudioComposer; +} + +bool MediacontentAudio::isChangedAudioTrackNumber() +{ + return m_isChangedAudioTrackNumber; +} + +mediacontent_lyric_state MediacontentAudio::getLyricsState() +{ + return m_lyricsState; +} + +vector<std::string> MediacontentAudio::getEditableAttr() const +{ + return m_editableAttrList; +} + +void MediacontentAudio::appendAudioArtist(const string &value) +{ + m_audioArtist.push_back(value); +} + +void MediacontentAudio::appendAudioGenre(const string &value) +{ + m_audioGenre.push_back(value); +} + +void MediacontentAudio::appendAudioComposer(const string &value) +{ + m_audioAuthor.push_back(value); +} + +void MediacontentAudio::setAudioLyricNonExistent() +{ + m_lyricsState = CONTENT_LYRIC_NON_EXISTENT; +} + +} +} diff --git a/wearable_src/Content/ContentAudio.h b/wearable_src/Content/ContentAudio.h new file mode 100755 index 0000000..87181fa --- /dev/null +++ b/wearable_src/Content/ContentAudio.h @@ -0,0 +1,118 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _ABSTRACT_LAYER_CONTENT_AUDIO_H_ +#define _ABSTRACT_LAYER_CONTENT_AUDIO_H_ + +#include <ctime> +#include <string> +#include <vector> +#include <dpl/optional.h> +#include <dpl/shared_ptr.h> +#include "ContentMedia.h" +#include "AudioLyrics.h" + +using namespace std; + +namespace DeviceAPI { +namespace Content { + +typedef enum +{ + CONTENT_LYRIC_UNKNOWN = 0, + CONTENT_LYRIC_EXISTENT, + CONTENT_LYRIC_NON_EXISTENT, +}mediacontent_lyric_state; + +class MediacontentAudio : public MediacontentMedia +{ + public: + + MediacontentAudio(); + virtual ~MediacontentAudio(); + + string getAudioAlbum() const; + vector<std::string> getAudioArtist() const; + vector<std::string> getAudioGenre() const; + vector<std::string> getAudioComposer() const; + string getAudioCopyright() const; + int getAudioBitrate() const; + int getAudioTrackNum() const; + int getAudioDuration() const; + int getAudioRating() const; + unsigned long long getAudioSize() const; + + MediacontentLyricsPtr getAudioLyrics() const; + + void setAudioAlbum(const string &value, bool isChanged=false); + void setAudioArtist(const vector<std::string> &value, bool isChanged=false); + void setAudioGenre(const vector<std::string> &value, bool isChanged=false); + void setAudioComposer(const vector<std::string> &value, bool isChanged=false); + + void appendAudioArtist(const string &value); + void appendAudioGenre(const string &value); + void appendAudioComposer(const string &value); + + void setAudioCopyright(const string &value); + void setAudioBitrate(const int &value); + void setAudioTrackNum(const int &value, bool isChanged=false); + void setAudioDuration(const int &value); + void setAudioSize(const unsigned long long &value); + + void setAudioLyrics(MediacontentLyricsPtr value); + void setAudioLyricNonExistent(); + //void setLyricsState(mediacontent_lyric_state value); + + bool isChangedAudioAlbum(); + bool isChangedAudioArtist(); + bool isChangedAudioGenre(); + bool isChangedAudioComposer(); + bool isChangedAudioTrackNumber(); + mediacontent_lyric_state getLyricsState(); + + virtual vector<std::string> getEditableAttr() const; + + protected: + string m_audioAlbum; + vector<std::string> m_audioArtist; + vector<std::string> m_audioGenre; + vector<std::string> m_audioAuthor; + string m_audioCopyright; + int m_audioTrackNum; + int m_audioDuration; + int m_audioBitrate; + unsigned long long m_audioSize; + bool m_isChangedAudioAlbum; + bool m_isChangedAudioArtist; + bool m_isChangedAudioGenre; + bool m_isChangedAudioComposer; + bool m_isChangedAudioTrackNumber; + mediacontent_lyric_state m_lyricsState; + + MediacontentLyricsPtr m_lyrics; + +}; + +typedef DPL::SharedPtr<MediacontentAudio> MediacontentAudioPtr; + + +} +} + +#endif /* _ABSTRACT_LAYER_CONTENT_AUDIO_H_ */ + diff --git a/wearable_src/Content/ContentController.cpp b/wearable_src/Content/ContentController.cpp new file mode 100755 index 0000000..0291398 --- /dev/null +++ b/wearable_src/Content/ContentController.cpp @@ -0,0 +1,163 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <CommonsJavaScript/JSCallbackManager.h> +#include <JSWebAPIErrorFactory.h> +#include "ContentController.h" +#include "ContentConverter.h" +#include "ContentAsyncCallbackManager.h" +#include <Logger.h> + +using namespace DeviceAPI::Common; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace DeviceAPI { +namespace Content { + +MediacontentManagerController& MediacontentManagerController::getInstance() +{ + static MediacontentManagerController instance; + return instance; +} + +MediacontentManagerController::MediacontentManagerController(): + EventBrowseFolderAnswerReceiver(ThreadEnum::NULL_THREAD), + EventUpdateMediaItemsAnswerReceiver(ThreadEnum::NULL_THREAD), + EventFindFolderAnswerReceiver(ThreadEnum::NULL_THREAD) +{ +} + +MediacontentManagerController::~MediacontentManagerController() +{ +} + + +void MediacontentManagerController::OnAnswerReceived(const IEventUpdateMediaItemsPtr &event) +{ + + JSCallbackManagerPtr cbm = DPL::StaticPointerCast<JSCallbackManager>(event->getPrivateData()); + if(!cbm) + { + LoggerE("no callback manager"); + return; + } + Try + { + MediaContentAsyncCallbackManagerSingleton::Instance().unregisterCallbackManager(cbm); + if (event->getResult()) + { + cbm->callOnSuccess(); + } + else + { + JSValueRef errorObject = DeviceAPI::Common::JSWebAPIErrorFactory::makeErrorObject( + cbm->getContext(), DeviceAPI::Common::JSWebAPIErrorFactory::UNKNOWN_ERROR); + cbm->callOnError(errorObject); + } + return; + } + Catch(Exception) + { + LoggerE("error during processing answer"); + } +} + + +void MediacontentManagerController::OnAnswerReceived(const IEventBrowseFolderPtr &event) +{ + JSCallbackManagerPtr cbm = DPL::StaticPointerCast<JSCallbackManager>(event->getPrivateData()); + if (!cbm) + { + LoggerE("no callback manager"); + return; + } + Try + { + MediaContentAsyncCallbackManagerSingleton::Instance().unregisterCallbackManager(cbm); + if (event->getResult()) + { + MediaConverterFactory::ConverterType converter = MediaConverterFactory::getConverter(cbm->getContext()); + const std::vector<MediacontentMediaPtr> &results = event->getMedia(); + JSValueRef result = converter->toJSValueRef(results); + cbm->callOnSuccess(result); + } + else + { + JSValueRef error = NULL; + if (ExceptionCodes::None != event->getExceptionCode()) + { + switch (event->getExceptionCode()) + { + case ExceptionCodes::InvalidArgumentException: + error = JSWebAPIErrorFactory::makeErrorObject(cbm->getContext(), JSWebAPIErrorFactory::INVALID_VALUES_ERROR, "The value is not valid"); + break; + default: + error = JSWebAPIErrorFactory::makeErrorObject(cbm->getContext(), JSWebAPIErrorFactory::UNKNOWN_ERROR,"unknown error"); + break; + } + cbm->callOnError(error); + return; + } + } + return; + } + Catch(Exception) + { + LoggerE("error during processing answer"); + } +} + + + +void MediacontentManagerController::OnAnswerReceived(const IEventFindFolderPtr &event) +{ + JSCallbackManagerPtr cbm = DPL::StaticPointerCast<JSCallbackManager>(event->getPrivateData()); + if (!cbm) + { + LoggerE("no callback manager"); + return; + } + Try + { + MediaContentAsyncCallbackManagerSingleton::Instance().unregisterCallbackManager(cbm); + if (event->getResult()) + { + MediaConverterFactory::ConverterType converter = MediaConverterFactory::getConverter(cbm->getContext()); + const std::vector<MediacontentFolderPtr> &results = event->getFolder(); + JSValueRef result = converter->toJSValueRef(results); + cbm->callOnSuccess(result); + } + else + { + JSValueRef errorObject = DeviceAPI::Common::JSWebAPIErrorFactory::makeErrorObject( + cbm->getContext(), DeviceAPI::Common::JSWebAPIErrorFactory::UNKNOWN_ERROR); + cbm->callOnError(errorObject); + } + return; + } + Catch(Exception) + { + LoggerE("error during processing answer"); + } + +} + + +} +} + diff --git a/wearable_src/Content/ContentController.h b/wearable_src/Content/ContentController.h new file mode 100755 index 0000000..1661816 --- /dev/null +++ b/wearable_src/Content/ContentController.h @@ -0,0 +1,57 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _TIZEN_CONTROLLER_H_ +#define _TIZEN_CONTROLLER_H_ + +#include "IEventGetDirectories.h" +#include "IEventFind.h" +#include "IEventUpdateBatch.h" + +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace DeviceAPI { +namespace Content { + +typedef EventAnswerReceiver<IEventFindFolder> EventFindFolderAnswerReceiver; +typedef EventAnswerReceiver<IEventBrowseFolder> EventBrowseFolderAnswerReceiver; +typedef EventAnswerReceiver<IEventUpdateMediaItems> EventUpdateMediaItemsAnswerReceiver; + +class MediacontentManagerController : + public EventBrowseFolderAnswerReceiver, + public EventUpdateMediaItemsAnswerReceiver, + public EventFindFolderAnswerReceiver +{ + public: + static MediacontentManagerController& getInstance(); + + protected: + void OnAnswerReceived(const IEventFindFolderPtr &event); + void OnAnswerReceived(const IEventBrowseFolderPtr &event); + void OnAnswerReceived(const IEventUpdateMediaItemsPtr &event); + + private: + MediacontentManagerController(); + virtual ~MediacontentManagerController(); + +}; + +} +} + +#endif //_TIZEN_CONTROLLER_H_
\ No newline at end of file diff --git a/wearable_src/Content/ContentConverter.cpp b/wearable_src/Content/ContentConverter.cpp new file mode 100755 index 0000000..9e4287c --- /dev/null +++ b/wearable_src/Content/ContentConverter.cpp @@ -0,0 +1,190 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <CommonsJavaScript/JSUtils.h> +#include <CommonsJavaScript/Validator.h> +#include <CommonsJavaScript/ScopedJSStringRef.h> +#include <JSUtil.h> + +#include "ContentConverter.h" +#include "JSContent.h" +#include "JSImage.h" +#include "JSVideo.h" +#include "JSAudio.h" +#include "JSFolder.h" +#include "JSAudioLyrics.h" +#include "ContentUtility.h" +#include <Logger.h> + +using namespace DeviceAPI::Common; + +namespace DeviceAPI { +namespace Content { + +MediaConverter::MediaConverter(JSContextRef context) : Converter(context) +{ +} + +JSValueRef MediaConverter::toFunctionOrNull(const JSValueRef& arg) +{ + if (Validator(m_context).isCallback(arg)) + { + return arg; + } else if (!JSValueIsNull(m_context,arg) && !JSValueIsUndefined(m_context, arg)) + { + ThrowMsg(ConversionException, "Not a function nor JS null."); + } + return NULL; +} + +JSValueRef MediaConverter::toFunction(const JSValueRef& arg) +{ + if (Validator(m_context).isCallback(arg)) + { + return arg; + } else if (JSValueIsNull(m_context,arg) || JSValueIsUndefined(m_context, arg)) + { + ThrowMsg(InvalidArgumentException, "JS null passed as function."); + } + ThrowMsg(ConversionException, "Not a function nor JS null."); +} + +/* +JSValueRef MediaConverter::toJSValueRefMediacontent(const IMediacontentPtr& arg) +{ + MediacontentPrivObject *priv = new MediacontentPrivObject(m_context, arg); + return JSObjectMake(m_context, JSMediacontent::getClassRef(), priv); +} +*/ + +JSValueRef MediaConverter::toJSValueRefMedia(const MediacontentMediaPtr& arg) +{ + if(arg->getMediaType() == "IMAGE") + { + return JSUtils::makeObject(m_context, JSImage::getClassRef(), arg); + } + if(arg->getMediaType() == "VIDEO") + { + return JSUtils::makeObject(m_context, JSVideo::getClassRef(), arg); + } + if(arg->getMediaType() == "AUDIO") + { + return JSUtils::makeObject(m_context, JSAudio::getClassRef(), arg); + } + return JSUtils::makeObject(m_context, JSMedia::getClassRef(), arg); +} + +JSValueRef MediaConverter::toJSValueRefFolder(const MediacontentFolderPtr& arg) +{ + return JSUtils::makeObject(m_context, JSFolder::getClassRef(), arg); +} + +JSValueRef MediaConverter::toJSValueRef(const std::vector<MediacontentMediaPtr> &arg) +{ + return toJSValueRef_(arg, &MediaConverter::toJSValueRefMedia, this); +} + +JSValueRef MediaConverter::toJSValueRef(const std::vector<MediacontentFolderPtr> &arg) +{ + return toJSValueRef_(arg, &MediaConverter::toJSValueRefFolder, this); +} + +JSValueRef MediaConverter::toJSValueRef(const MediacontentLyricsPtr &arg) +{ + return JSUtils::makeObject(m_context, JSMediaLyrics::getClassRef(), arg); +} + + + +MediacontentMediaListPtr MediaConverter::toVectorOfMediaItem(JSValueRef events) +{ + MediacontentMediaListPtr result(new MediacontentMediaList()); + + std::vector<MediacontentMediaPtr> resultVector; + JSObjectRef objArg = toJSObjectRef(events); + + for (std::size_t i = 0; i < JSGetArrayLength(m_context, objArg); i++) { + JSValueRef element = JSGetArrayElement(m_context, objArg, i); + JSObjectRef arg = JSValueToObject(m_context, element, NULL); + + if (!JSValueIsObjectOfClass(m_context, element, JSMedia::getClassRef()) && + !JSValueIsObjectOfClass(m_context, element, JSImage::getClassRef()) && + !JSValueIsObjectOfClass(m_context, element, JSAudio::getClassRef()) && + !JSValueIsObjectOfClass(m_context, element, JSVideo::getClassRef())) { + throw TypeMismatchException("content type mismatched."); + } + + if(JSValueIsObjectOfClass(m_context, element, JSImage::getClassRef())){ + MediacontentImagePtr imgPtr = JSImage::getImageObject(arg); + JSValueRef geoValRef = JSUtil::getProperty(m_context , JSUtil::JSValueToObject(m_context, element), "geolocation"); + if(!(JSValueIsNull(m_context, geoValRef) || JSValueIsUndefined(m_context, geoValRef))){ + JSObjectRef geoObjRef = JSUtil::JSValueToObject(m_context, geoValRef); + double latitude = JSUtil::JSValueToDouble(m_context, JSUtil::getProperty(m_context, geoObjRef, "latitude")); + double longitude = JSUtil::JSValueToDouble(m_context,JSUtil::getProperty(m_context, geoObjRef, "longitude")); + if(ContentUtility::checkLocation(latitude, latitude)){ + imgPtr->setImageLatitude(latitude); + imgPtr->setImageLongitude(longitude); + } + else{ + ThrowMsg(WrtDeviceApis::Commons::InvalidArgumentException, "geolocation value is not valid."); + } + } + else + { + imgPtr->setImageLatitude(DEFAULT_GEOLOCATION); + imgPtr->setImageLongitude(DEFAULT_GEOLOCATION); + } + } + if(JSValueIsObjectOfClass(m_context, element, JSVideo::getClassRef())){ + MediacontentVideoPtr vedioPtr = JSVideo::getVideoObject(arg); + JSValueRef geoValRef = JSUtil::getProperty(m_context , JSUtil::JSValueToObject(m_context, element), "geolocation"); + if(!(JSValueIsNull(m_context, geoValRef) || JSValueIsUndefined(m_context, geoValRef))){ + JSObjectRef geoObjRef = JSUtil::JSValueToObject(m_context, geoValRef); + double latitude = JSUtil::JSValueToDouble(m_context, JSUtil::getProperty(m_context, geoObjRef, "latitude")); + double longitude = JSUtil::JSValueToDouble(m_context,JSUtil::getProperty(m_context, geoObjRef, "longitude")); + if(ContentUtility::checkLocation(latitude, latitude)){ + vedioPtr->setVideoLatitude(latitude); + vedioPtr->setVideoLongitude(longitude); + } + else{ + ThrowMsg(WrtDeviceApis::Commons::InvalidArgumentException, "geolocation value is not valid."); + } + } + else + { + vedioPtr->setVideoLatitude(DEFAULT_GEOLOCATION); + vedioPtr->setVideoLongitude(DEFAULT_GEOLOCATION); + } + } + + JSValueRef nameValRef = JSUtil::getProperty(m_context , JSUtil::JSValueToObject(m_context, element), "name"); + if((JSValueIsNull(m_context, nameValRef) || JSValueIsUndefined(m_context, nameValRef)) || + JSUtil::JSValueToString(m_context, nameValRef) == ""){ + ThrowMsg(WrtDeviceApis::Commons::InvalidArgumentException, "name is not valid."); + } + + resultVector.push_back(JSMedia::getMediaObject(arg)); + } + *result = resultVector; + return result; +} + + + + +} +} diff --git a/wearable_src/Content/ContentConverter.h b/wearable_src/Content/ContentConverter.h new file mode 100755 index 0000000..88d7019 --- /dev/null +++ b/wearable_src/Content/ContentConverter.h @@ -0,0 +1,73 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _TIZEN_CONTENT_CONVERTER_H_ +#define _TIZEN_CONTENT_CONVERTER_H_ + +#include <vector> +#include <string> +#include <CommonsJavaScript/Converter.h> +#include "ContentMedia.h" +#include "ContentFolder.h" +#include "AudioLyrics.h" + +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + + +namespace DeviceAPI { +namespace Content { + + +class MediaConverter : public Converter +{ + public: + using Converter::toJSValueRef; + + public: + explicit MediaConverter(JSContextRef context); + + //JSValueRef toJSValueRefMediacontent(const IMediacontentPtr& arg); + + /** + * @throw InvalidArgumentException If not a callback nor JS null. + */ + JSValueRef toFunctionOrNull(const JSValueRef& arg); + + /** + * @throw ConversionException If JS null. + * @throw InvalidArgumentException If not a callback nor JS null. + */ + JSValueRef toFunction(const JSValueRef& arg); + JSValueRef toJSValueRefMedia(const MediacontentMediaPtr& arg); + JSValueRef toJSValueRefFolder(const MediacontentFolderPtr& arg); + JSValueRef toJSValueRef(const std::vector<MediacontentMediaPtr> &arg); + JSValueRef toJSValueRef(const std::vector<MediacontentFolderPtr> &arg); + JSValueRef toJSValueRef(const MediacontentLyricsPtr &arg); + + MediacontentMediaListPtr toVectorOfMediaItem(JSValueRef events); + + +}; + +typedef ConverterFactory<MediaConverter> MediaConverterFactory; + + +} +} + +#endif // _TIZEN_CONTENT_CONVERTER_H_
\ No newline at end of file diff --git a/wearable_src/Content/ContentFactory.cpp b/wearable_src/Content/ContentFactory.cpp new file mode 100755 index 0000000..6ece840 --- /dev/null +++ b/wearable_src/Content/ContentFactory.cpp @@ -0,0 +1,40 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "ContentFactory.h" +#include "ContentManager.h" + + +namespace DeviceAPI { +namespace Content { + +IMediacontentManagerPtr MediacontentFactory::createMediacontentManagerObject() +{ + IMediacontentManagerPtr result(new MediacontentManager()); + return result; +} + +MediacontentFactory& MediacontentFactory::getInstance() +{ + static MediacontentFactory theInstance; + return theInstance; +} + +} +} diff --git a/wearable_src/Content/ContentFactory.h b/wearable_src/Content/ContentFactory.h new file mode 100755 index 0000000..58c7897 --- /dev/null +++ b/wearable_src/Content/ContentFactory.h @@ -0,0 +1,41 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _ABSTRACT_LAYER_CONTENT_FACTORY_H_ +#define _ABSTRACT_LAYER_CONTENT_FACTORY_H_ + +#include "IContentManager.h" +#include <dpl/shared_ptr.h> + +namespace DeviceAPI { +namespace Content { + +class MediacontentFactory : private DPL::Noncopyable +{ + private: + MediacontentFactory(){} + + public: + static MediacontentFactory& getInstance(); + IMediacontentManagerPtr createMediacontentManagerObject(); + +}; + +} +} + +#endif /* WRTPLUGINSCAMERAFACTORY_H_ */
\ No newline at end of file diff --git a/wearable_src/Content/ContentFilterConverter.cpp b/wearable_src/Content/ContentFilterConverter.cpp new file mode 100755 index 0000000..fa539ed --- /dev/null +++ b/wearable_src/Content/ContentFilterConverter.cpp @@ -0,0 +1,87 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 ContentFilterConverter.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @description Reference from CalendarConverter.cpp + */ + +#include "ContentFilterConverter.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Content { + +using namespace std; +using namespace DeviceAPI::Tizen; + +static PropertyStructArray folderProperties = +{ + { "id", PrimitiveType_String }, + { "directoryURI", PrimitiveType_String }, + { "storageType", PrimitiveType_String }, + { "title", PrimitiveType_String }, + { "modifiedDate", PrimitiveType_Time }, + { 0, PrimitiveType_NoType} +}; + +static PropertyStructArray mediaProperties = +{ + { "id", PrimitiveType_String }, + { "type", PrimitiveType_String }, + { "mimeType", PrimitiveType_String }, + { "name", PrimitiveType_String }, + { "title", PrimitiveType_String }, + { "contentURI", PrimitiveType_String }, + { "thumbnailURIs", PrimitiveType_String }, + { "description", PrimitiveType_String }, + { "rating", PrimitiveType_Long }, + { "releaseDate", PrimitiveType_Time }, + { "modifiedDate", PrimitiveType_Time }, + { "geolocation.latitude", PrimitiveType_Double }, + { "geolocation.longitude", PrimitiveType_Double }, + { "album", PrimitiveType_String }, + { "artists", PrimitiveType_String }, + { "width", PrimitiveType_String }, + { "height", PrimitiveType_String }, + { "genres", PrimitiveType_String }, + { 0, PrimitiveType_NoType} +}; + +FolderContentFilterConverter::FolderContentFilterConverter(JSContextRef context) : + FilterConverter(context, folderProperties, false) +{ +} + +FolderContentFilterConverter::~FolderContentFilterConverter() +{ +} + +MediaContentFilterConverter::MediaContentFilterConverter(JSContextRef context) : + FilterConverter(context, mediaProperties, false) +{ +} + +MediaContentFilterConverter::~MediaContentFilterConverter() +{ +} + +} // Content +} // DeviceAPI + diff --git a/wearable_src/Content/ContentFilterConverter.h b/wearable_src/Content/ContentFilterConverter.h new file mode 100644 index 0000000..ca5f65d --- /dev/null +++ b/wearable_src/Content/ContentFilterConverter.h @@ -0,0 +1,54 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 ContentFilterConverter.h + * @version 0.1 + * @description Reference from CalendarConverter.h + */ + +#ifndef _TIZEN_CONTENT_FILTER_CONVERTER_H_ +#define _TIZEN_CONTENT_FILTER_CONVERTER_H_ + +#include <set> +#include <string> +#include <FilterConverter.h> + +namespace DeviceAPI { +namespace Content { + +class FolderContentFilterConverter : public DeviceAPI::Tizen::FilterConverter +{ +public: + explicit FolderContentFilterConverter(JSContextRef context); + virtual ~FolderContentFilterConverter(); +}; +typedef WrtDeviceApis::CommonsJavaScript::ConverterFactory<FolderContentFilterConverter> FolderContentFilterConverterFactory; + +class MediaContentFilterConverter : public DeviceAPI::Tizen::FilterConverter +{ +public: + explicit MediaContentFilterConverter(JSContextRef context); + virtual ~MediaContentFilterConverter(); +}; +typedef WrtDeviceApis::CommonsJavaScript::ConverterFactory<MediaContentFilterConverter> MediaContentFilterConverterFactory; + +} // Content +} // DeviceAPI + +#endif // _TIZEN_CONTENT_FILTER_CONVERTER_H_ + diff --git a/wearable_src/Content/ContentFilterValidator.cpp b/wearable_src/Content/ContentFilterValidator.cpp new file mode 100755 index 0000000..8a3ea4e --- /dev/null +++ b/wearable_src/Content/ContentFilterValidator.cpp @@ -0,0 +1,75 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "ContentFilterValidator.h" +#include <Logger.h> + +namespace DeviceAPI { + +namespace Content{ + +static PropertyStructArray folderProperties = +{ + {"id", PrimitiveType_String}, + {"directoryURI", PrimitiveType_String}, + {"storageType", PrimitiveType_String}, + {"title", PrimitiveType_String}, + {"modifiedDate", PrimitiveType_Time}, + {0, PrimitiveType_NoType} +}; + +static PropertyStructArray mediaProperties = +{ + {"id", PrimitiveType_String}, + {"type", PrimitiveType_String}, + {"mimeType", PrimitiveType_String}, + {"name", PrimitiveType_String}, + {"title", PrimitiveType_String}, + {"contentURI", PrimitiveType_String}, + {"thumbnailURIs", PrimitiveType_String}, + {"description", PrimitiveType_String}, + {"rating", PrimitiveType_Long}, + {"releaseDate", PrimitiveType_Time}, + {"modifiedDate", PrimitiveType_Time}, + {"geolocation.latitude", PrimitiveType_Double}, + {"geolocation.longitude", PrimitiveType_Double}, + {"album", PrimitiveType_String}, + {"artists", PrimitiveType_String}, + {"width", PrimitiveType_String}, + {"height", PrimitiveType_String}, + {"genres", PrimitiveType_String}, + {0, PrimitiveType_NoType} + +}; + + +FilterValidatorPtr MediaFilterValidatorFactory::getMediaFilterValidator(QueryType value) +{ + static FilterValidatorPtr theValidatorInstance; + if(value == QUERY_FOLDER) + { + theValidatorInstance = FilterValidatorPtr(new FilterValidator(folderProperties)); + } + else if(value == QUERY_MEDIA) + { + theValidatorInstance = FilterValidatorPtr(new FilterValidator(mediaProperties)); + } + return theValidatorInstance; + } + +} +} diff --git a/wearable_src/Content/ContentFilterValidator.h b/wearable_src/Content/ContentFilterValidator.h new file mode 100755 index 0000000..f392f57 --- /dev/null +++ b/wearable_src/Content/ContentFilterValidator.h @@ -0,0 +1,52 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _PLATFORM_MEDIA_CONTENT_FILTER_VALIDATOR_H_ +#define _PLATFORM_MEDIA_CONTENT_FILTER_VALIDATOR_H_ + +#include <FilterValidator.h> + + +using namespace DeviceAPI::Tizen; + +namespace DeviceAPI { +namespace Content { + + +class MediaFilterValidatorFactory : private DPL::Noncopyable +{ + public: + typedef enum _QueryType + { + QUERY_FOLDER, + QUERY_MEDIA + }QueryType; + +private: + MediaFilterValidatorFactory() + { + } + +public: + static FilterValidatorPtr getMediaFilterValidator(QueryType value); +}; + +} +} + +#endif // _PLATFORM_MEDIA_CONTENT_FILTER_VALIDATOR_H_
\ No newline at end of file diff --git a/wearable_src/Content/ContentFolder.cpp b/wearable_src/Content/ContentFolder.cpp new file mode 100755 index 0000000..891021e --- /dev/null +++ b/wearable_src/Content/ContentFolder.cpp @@ -0,0 +1,133 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <Commons/Exception.h> +#include "ContentFolder.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Content { + + +MediacontentFolder::MediacontentFolder() +{ + m_modifiedDate = NULL; +} + +MediacontentFolder::~MediacontentFolder() +{ + if(m_modifiedDate != NULL) + { + free(m_modifiedDate); + } +} + + +string MediacontentFolder::getFolderUUID() const +{ + return m_folderUUID; +} + +void MediacontentFolder::setFolderUUID(const string &value) +{ + m_folderUUID = value; +} + + +string MediacontentFolder::getFolderName() const +{ + return m_folderName; +} + +void MediacontentFolder::setFolderName(const string &value) +{ + m_folderName = value; +} + +string MediacontentFolder::getFolderPath() const +{ + return m_folderPath; + +} + +void MediacontentFolder::setFolderPath(const string &value) +{ + m_folderPath = value; + +} + +string MediacontentFolder::getFolderStorageType() +{ + return m_storageType; +} + +void MediacontentFolder::setFolderStorageType(const string &value) +{ + m_storageType = value; + +} +tm* MediacontentFolder::getFolderModifiedDate() const +{ + return m_modifiedDate; +} + +MediaIdListPtr MediacontentFolder::getMediaIdList() const +{ + return m_mediaIdArrayPtr; +} + + +void MediacontentFolder::setFolderModifiedDate(tm *value) +{ + m_modifiedDate = value; + +} + +void MediacontentFolder::setMediaIdList(const MediaIdListPtr &value) +{ + m_mediaIdArrayPtr = value; + +} + + +void MediacontentFolder::insertValue(string attrName, string value) +{ + m_folderValue.insert(pair<string, string>(attrName,value)); +} + +string MediacontentFolder::findValue(string attrName) +{ + + string value; + + map<string, string>::iterator pos; + + pos = m_folderValue.find(attrName); + + if(m_folderValue.end() != pos) + { + value = pos->second; + } + else + { + LoggerD("Attribute(" << attrName << ") There is no data."); + } + return value; +} + +} +} diff --git a/wearable_src/Content/ContentFolder.h b/wearable_src/Content/ContentFolder.h new file mode 100755 index 0000000..c467f24 --- /dev/null +++ b/wearable_src/Content/ContentFolder.h @@ -0,0 +1,85 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _ABSTRACT_LAYER_CONTENT_FOLDER_H_ +#define _ABSTRACT_LAYER_CONTENT_FOLDER_H_ + +#include <map> +#include <ctime> +#include <string> +#include <vector> +#include <dpl/optional.h> +#include <dpl/shared_ptr.h> + +using namespace std; + +namespace DeviceAPI { +namespace Content { + + +typedef vector<std::string> MediaIdList; +typedef DPL::SharedPtr<MediaIdList> MediaIdListPtr; + +class MediacontentFolder +{ + public: + + MediacontentFolder(); + virtual ~MediacontentFolder(); + + + string getFolderUUID() const; + string getFolderPath() const; + string getFolderName() const; + string getFolderStorageType(); + tm* getFolderModifiedDate() const; + MediaIdListPtr getMediaIdList() const; + + void setFolderUUID(const string &value); + void setFolderPath(const string &value); + void setFolderName(const string &value); + void setFolderStorageType(const string &value); + void setFolderModifiedDate(tm *value); + void setMediaIdList(const MediaIdListPtr &value); + + void insertValue(string attr, string value); + string findValue(string attr); + + protected: + + string m_folderUUID; + string m_folderPath; + string m_folderName; + string m_storageType; + tm* m_modifiedDate; + MediaIdListPtr m_mediaIdArrayPtr; + + map<string,string> m_folderValue; + +}; + +typedef DPL::SharedPtr<MediacontentFolder> MediacontentFolderPtr; +typedef std::vector<MediacontentFolderPtr> MediacontentFolderList; +typedef DPL::SharedPtr<MediacontentFolderList> MediacontentFolderListPtr; + + +} +} + +#endif /* _ABSTRACT_LAYER_CONTENT_FOLDER_H_ */ + diff --git a/wearable_src/Content/ContentImage.cpp b/wearable_src/Content/ContentImage.cpp new file mode 100755 index 0000000..03f43fe --- /dev/null +++ b/wearable_src/Content/ContentImage.cpp @@ -0,0 +1,112 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <Commons/Exception.h> +#include "ContentImage.h" +#include <Logger.h> + + +namespace DeviceAPI { +namespace Content { + +MediacontentImage::MediacontentImage() +{ + m_editableAttrList.push_back("geolocation"); + m_editableAttrList.push_back("orientation"); + m_imageLongitude = DEFAULT_GEOLOCATION; + m_imageLatitude = DEFAULT_GEOLOCATION; +} + +MediacontentImage::~MediacontentImage() +{ +} + +double MediacontentImage::getImageLatitude() const +{ + return m_imageLatitude; +} + +double MediacontentImage::getImageLongitude() const +{ + return m_imageLongitude; +} + +void MediacontentImage::setImageLatitude(const double &value, bool isChanged) +{ + m_imageLatitude = value; + m_isChangedLatitude = isChanged; +} +void MediacontentImage::setImageLongitude(const double &value, bool isChanged) +{ + m_imageLongitude = value; + m_isChangedLongitude = isChanged; +} + +int MediacontentImage::getImageWidth() const +{ + return m_imageWidth; + +} + +void MediacontentImage::setImageWidth(const int &value) +{ + m_imageWidth = value; + +} + +int MediacontentImage::getImageHeight() const +{ + return m_imageHeight; +} +void MediacontentImage::setImageHeight(const int &value) +{ + m_imageHeight = value; +} + +string MediacontentImage::getImageOrientation() const +{ + return m_imageOrientation; +} + +void MediacontentImage::setImageOrientation(const string &value, bool isChanged) +{ + m_imageOrientation = value; + m_isChangedOrientation=isChanged; +} + +vector<std::string> MediacontentImage::getEditableAttr() const +{ + return m_editableAttrList; +} + +bool MediacontentImage::isChangedOrientaion () const +{ + return m_isChangedOrientation; +} + +bool MediacontentImage::isChangedLatitude () const +{ + return m_isChangedLatitude; +} + +bool MediacontentImage::isChangedLongitude() const +{ + return m_isChangedLongitude; +} + +} +} diff --git a/wearable_src/Content/ContentImage.h b/wearable_src/Content/ContentImage.h new file mode 100755 index 0000000..61c9dc9 --- /dev/null +++ b/wearable_src/Content/ContentImage.h @@ -0,0 +1,80 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _ABSTRACT_LAYER_CONTENT_IMAGE_H_ +#define _ABSTRACT_LAYER_CONTENT_IMAGE_H_ + +#include <ctime> +#include <string> +#include <vector> +#include <dpl/optional.h> +#include <dpl/shared_ptr.h> +#include "ContentMedia.h" + +using namespace std; + +namespace DeviceAPI { +namespace Content { + +class MediacontentImage : public MediacontentMedia +{ + public: + + MediacontentImage(); + virtual ~MediacontentImage(); + + int getImageWidth() const; + int getImageHeight() const; + string getImageOrientation() const; + double getImageLatitude() const; + double getImageLongitude() const; + + + void setImageWidth(const int &value); + void setImageHeight(const int &value); + void setImageOrientation(const string &value, bool isChanged=false); + void setImageLatitude(const double &value, bool isChanged=false); + void setImageLongitude(const double &value, bool isChanged=false); + + bool isChangedOrientaion() const; + bool isChangedLatitude() const; + bool isChangedLongitude() const; + + virtual vector<std::string> getEditableAttr() const; + + protected: + int m_imageWidth; + int m_imageHeight; + string m_imageOrientation; + double m_imageLongitude; + double m_imageLatitude; + + bool m_isChangedOrientation; + bool m_isChangedLatitude; + bool m_isChangedLongitude; + +}; + +typedef DPL::SharedPtr<MediacontentImage> MediacontentImagePtr; + + +} +} + +#endif /* _ABSTRACT_LAYER_CONTENT_MEDIA_H_ */ + diff --git a/wearable_src/Content/ContentListener.cpp b/wearable_src/Content/ContentListener.cpp new file mode 100755 index 0000000..c60c09f --- /dev/null +++ b/wearable_src/Content/ContentListener.cpp @@ -0,0 +1,91 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <pthread.h> +#include <CommonsJavaScript/JSUtils.h> +#include <CommonsJavaScript/Validator.h> +#include <JSWebAPIErrorFactory.h> +#include <JSUtil.h> +#include "ContentListener.h" +#include "ContentConverter.h" +#include <Logger.h> + +using namespace DeviceAPI::Common; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + + +namespace DeviceAPI { +namespace Content { + +ContentListener::ContentListener(JSContextRef globalCtx, JSObjectRef object) +{ + m_callback = new MultiCallbackUserData(globalCtx); + + // onstarted + JSValueRef oncontentadded = JSUtil::getProperty(globalCtx , object, "oncontentadded"); + if(!JSValueIsUndefined(globalCtx,oncontentadded)) { + m_callback->setCallback("oncontentadded", JSUtil::JSValueToObject(globalCtx, oncontentadded)); + } + JSValueRef oncontentupdated = JSUtil::getProperty(globalCtx , object, "oncontentupdated"); + if(!JSValueIsUndefined(globalCtx,oncontentupdated)) { + m_callback->setCallback("oncontentupdated", JSUtil::JSValueToObject(globalCtx, oncontentupdated)); + } + JSValueRef oncontentremoved = JSUtil::getProperty(globalCtx , object, "oncontentremoved"); + if(!JSValueIsUndefined(globalCtx,oncontentremoved)) { + m_callback->setCallback("oncontentremoved", JSUtil::JSValueToObject(globalCtx, oncontentremoved)); + } + +} + +ContentListener::~ContentListener() { + if(m_callback != NULL){ + delete m_callback; + m_callback = NULL; + } +} + +void ContentListener::oncontentadded(MediacontentMediaPtr content) +{ + JSContextRef context = m_callback->getContext(); + + MediaConverterFactory::ConverterType converter = MediaConverterFactory::getConverter(context); + JSValueRef result = converter->toJSValueRefMedia(content); + m_callback->invokeCallback("oncontentadded", result); +} + +void ContentListener::oncontentupdated(MediacontentMediaPtr content) +{ + JSContextRef context = m_callback->getContext(); + + MediaConverterFactory::ConverterType converter = MediaConverterFactory::getConverter(context); + JSValueRef result = converter->toJSValueRefMedia(content); + m_callback->invokeCallback("oncontentupdated", result); + +} + +void ContentListener::oncontentremoved(std::string id) +{ + JSContextRef context = m_callback->getContext(); + + MediaConverterFactory::ConverterType converter = MediaConverterFactory::getConverter(context); + m_callback->invokeCallback("oncontentremoved", converter->toJSValueRef(id)); +} + + +} // Download +} // DeviceAPI diff --git a/wearable_src/Content/ContentListener.h b/wearable_src/Content/ContentListener.h new file mode 100755 index 0000000..e0462b3 --- /dev/null +++ b/wearable_src/Content/ContentListener.h @@ -0,0 +1,47 @@ +//
+// Tizen Web Device API
+// Copyright (c) 2012 Samsung Electronics Co., Ltd.
+//
+// Licensed under the Apache License, Version 2.0 (the License);
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT 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 __TIZEN_CONTENT_LISTENER__
+#define __TIZEN_CONTENT_LISTENER__
+
+#include <JavaScriptCore/JavaScript.h>
+#include <MultiCallbackUserData.h>
+#include "ContentMedia.h"
+
+using namespace DeviceAPI::Common;
+
+namespace DeviceAPI {
+namespace Content {
+
+class ContentListener {
+public:
+ ContentListener(JSContextRef globalCtx, JSObjectRef object);
+ virtual ~ContentListener();
+
+ void oncontentadded(MediacontentMediaPtr content);
+ void oncontentupdated(MediacontentMediaPtr content);
+ void oncontentremoved(std::string id);
+
+private:
+ MultiCallbackUserData *m_callback;
+};
+
+}
+}
+
+
+#endif // __TIZEN_CONTENT_LISTENER__
diff --git a/wearable_src/Content/ContentManager.cpp b/wearable_src/Content/ContentManager.cpp new file mode 100755 index 0000000..58eca60 --- /dev/null +++ b/wearable_src/Content/ContentManager.cpp @@ -0,0 +1,1145 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <vector> +#include <string> +#include <algorithm> +#include <media_content.h> +#include <Commons/Regex.h> +#include <Commons/StringUtils.h> +#include <CommonsJavaScript/Converter.h> + +#include "ContentManager.h" +#include "ContentFilterValidator.h" +#include "ContentUtility.h" +#include <Logger.h> + +using namespace WrtDeviceApis::Commons; + + +namespace DeviceAPI { +namespace Content { + + +int MediacontentManager::m_instanceCount = 0; + +MediacontentManager::MediacontentManager() +{ + //protect for pararel execution + DPL::Mutex::ScopedLock mx(&m_constructorMutex); + if (m_instanceCount == 0) + { + //when it is first instance then connect to media content service. + if( MEDIA_CONTENT_ERROR_NONE != media_content_connect()) + { + LoggerD("Media Content Service Connect Fail..."); + return; + } + } + //increase counter of instances + m_instanceCount++; +} + +MediacontentManager::~MediacontentManager() +{ + DPL::Mutex::ScopedLock mx(&m_constructorMutex); + //decrease counter of instances + m_instanceCount--; + if (m_instanceCount == 0) + { + //when it is last instance then clse connection to database + if ( MEDIA_CONTENT_ERROR_NONE != media_content_disconnect()) + { + LoggerD("Media Content Service Disconnect Fail..."); + } + } +} + +tm* MediacontentManager::toDateTm(time_t date) +{ + tm *tm_date = (struct tm *)calloc(1, sizeof(struct tm)); + + localtime_r(&date, tm_date); + + return tm_date; +} + +media_content_orientation_e MediacontentManager::convertToOrientation(string orientation) +{ + media_content_orientation_e ret = MEDIA_CONTENT_ORIENTATION_NOT_AVAILABLE; + + if ( orientation.compare("NORMAL")==0) + { + ret = MEDIA_CONTENT_ORIENTATION_NORMAL; + } + else if (orientation.compare("FLIP_HORIZONTAL")==0) + { + ret = MEDIA_CONTENT_ORIENTATION_HFLIP; + } + else if (orientation.compare("ROTATE_180")==0) + { + ret = MEDIA_CONTENT_ORIENTATION_ROT_180; + } + else if (orientation.compare("FLIP_VERTICAL")==0) + { + ret = MEDIA_CONTENT_ORIENTATION_VFLIP; + } + else if (orientation.compare("TRANSPOSE")==0) + { + ret = MEDIA_CONTENT_ORIENTATION_TRANSPOSE; + } + else if (orientation.compare("ROTATE_90")==0) + { + ret = MEDIA_CONTENT_ORIENTATION_ROT_90; + } + else if (orientation.compare("TRANSVERSE")==0) + { + ret =MEDIA_CONTENT_ORIENTATION_TRANSVERSE; + } + else if (orientation.compare("ROTATE_270")==0) + { + ret =MEDIA_CONTENT_ORIENTATION_ROT_270; + } + else + { + LoggerD("wrong value."); + ret = MEDIA_CONTENT_ORIENTATION_NOT_AVAILABLE; + } + + return ret; +} + +void MediacontentManager::convertToPlatformFolder(media_folder_h media_folder, MediacontentFolderPtr& newFolder) +{ + char* tmpStr = NULL; + time_t date; + media_content_storage_e storageType; + + if (MEDIA_CONTENT_ERROR_NONE == media_folder_get_folder_id(media_folder, &tmpStr)) + { + if ( tmpStr ) + { + newFolder->setFolderUUID(tmpStr); + free(tmpStr); + tmpStr = NULL; + } + } + + if (MEDIA_CONTENT_ERROR_NONE == media_folder_get_path(media_folder, &tmpStr)) + { + if ( tmpStr ) + { + newFolder->setFolderPath(ContentUtility::convertPathToUri(tmpStr)); + free(tmpStr); + tmpStr = NULL; + } + } + + if (MEDIA_CONTENT_ERROR_NONE == media_folder_get_name(media_folder, &tmpStr)) + { + if ( tmpStr ) + { + newFolder->setFolderName(tmpStr); + free(tmpStr); + tmpStr = NULL; + } + } + + if (MEDIA_CONTENT_ERROR_NONE == media_folder_get_modified_time(media_folder, &date)) + { + newFolder->setFolderModifiedDate(toDateTm(date)); + } + + if (MEDIA_CONTENT_ERROR_NONE == media_folder_get_storage_type(media_folder, &storageType)) + { + string type; + if(storageType == MEDIA_CONTENT_STORAGE_INTERNAL ) + { + type = "INTERNAL"; + } + else if( storageType == MEDIA_CONTENT_STORAGE_EXTERNAL) + { + type = "EXTERNAL"; + } + else + { + type = "UNKNOWN"; + } + newFolder->setFolderStorageType(type); + } + + +} + +void MediacontentManager::readCommonDataFromMediaInfo(media_info_h info, MediacontentMedia* newMedia) +{ + + char* tmpStr = NULL; + time_t tmpDate; + int tmpInt = 0; + unsigned long long tmpLongLong = 0; + bool tmpBool= false; + + if ( MEDIA_CONTENT_ERROR_NONE == media_info_get_media_id(info, &tmpStr) ) + { + if (tmpStr) + { + newMedia->setMediaUUID(tmpStr); + free(tmpStr); + tmpStr = NULL; + } + } + + if ( MEDIA_CONTENT_ERROR_NONE == media_info_get_mime_type(info, &tmpStr) ) + { + if (tmpStr) + { + newMedia->setMimeType(tmpStr); + free(tmpStr); + tmpStr = NULL; + } + } + + if (MEDIA_CONTENT_ERROR_NONE == media_info_get_display_name(info, &tmpStr) ) + { + if (tmpStr) + { + newMedia->setDisplayName(tmpStr); + free(tmpStr); + tmpStr = NULL; + } + } + + if (MEDIA_CONTENT_ERROR_NONE == media_info_get_title(info, &tmpStr) ) + { + if (tmpStr) + { + newMedia->setTitle(tmpStr); + free(tmpStr); + tmpStr = NULL; + } + } + + if ( MEDIA_CONTENT_ERROR_NONE == media_info_get_file_path(info, &tmpStr) ) + { + if (tmpStr) + { + newMedia->setFilePath(ContentUtility::convertPathToUri(tmpStr)); + free(tmpStr); + tmpStr = NULL; + } + } + + if ( MEDIA_CONTENT_ERROR_NONE == media_info_get_thumbnail_path (info, &tmpStr) ) + { + if (tmpStr) + { + newMedia->setThumbnailPath(ContentUtility::convertPathToUri(tmpStr)); + free(tmpStr); + tmpStr = NULL; + } + } + + if ( MEDIA_CONTENT_ERROR_NONE == media_info_get_description(info, &tmpStr) ) + { + if (tmpStr) + { + newMedia->setDescription(tmpStr); + free(tmpStr); + tmpStr = NULL; + } + } + + //newImage->setReleasedDate(toDateTm(sqlite3_column_int(pStmt,7))); + if ( MEDIA_CONTENT_ERROR_NONE == media_info_get_modified_time (info, &tmpDate) ) + { + if(tmpDate) + { + newMedia->setModifiedDate(toDateTm(tmpDate)); + } + } + + if ( MEDIA_CONTENT_ERROR_NONE == media_info_get_favorite (info, &tmpBool) ) + { + newMedia->setFavorite(tmpBool); + } + + if ( MEDIA_CONTENT_ERROR_NONE == media_info_get_rating (info, &tmpInt) ) + { + newMedia->setRating(tmpInt); + } + + if ( MEDIA_CONTENT_ERROR_NONE == media_info_get_size(info, &tmpLongLong) ) + { + newMedia->setSize(tmpLongLong); + } + +} + +void MediacontentManager::readImageFromMediaInfo( media_info_h info, MediacontentImage* newImage) +{ + char* tmpStr = NULL; + double tmpDouble; + int tmpInt = 0; + + if ( info) + { + newImage->setMediaType("IMAGE"); + + readCommonDataFromMediaInfo(info, newImage); + + image_meta_h img; + + if ( MEDIA_CONTENT_ERROR_NONE == media_info_get_image(info, &img)) + { + //created time + if ( MEDIA_CONTENT_ERROR_NONE == image_meta_get_date_taken (img, &tmpStr) ) + { + if ( tmpStr ) + { + struct tm *result = (struct tm *)calloc(1, sizeof(struct tm)); + if (strptime(tmpStr, "%Y:%m:%d %H:%M:%S", result) == NULL) { + LoggerE( "Couldn't convert supplied date."); + } + + newImage->setReleasedDate(result); + free(tmpStr); + tmpStr = NULL; + } + } + if ( MEDIA_CONTENT_ERROR_NONE == image_meta_get_width(img, &tmpInt) ) + { + newImage->setImageWidth(tmpInt); + } + + if ( MEDIA_CONTENT_ERROR_NONE == image_meta_get_height(img, &tmpInt) ) + { + newImage->setImageHeight(tmpInt); + } + + if ( MEDIA_CONTENT_ERROR_NONE == media_info_get_latitude(info, &tmpDouble) ) + { + newImage->setImageLatitude(tmpDouble); + } + + if ( MEDIA_CONTENT_ERROR_NONE == media_info_get_longitude(info, &tmpDouble) ) + { + newImage->setImageLongitude(tmpDouble); + } + + media_content_orientation_e orientation; + + if ( MEDIA_CONTENT_ERROR_NONE == image_meta_get_orientation(img, &orientation) ) + { + + string orientationStr; + switch(orientation) + { + case 0: + case 1: + orientationStr = "NORMAL"; + break; + case 2: + orientationStr = "FLIP_HORIZONTAL"; + break; + case 3: + orientationStr = "ROTATE_180"; + break; + case 4: + orientationStr = "FLIP_VERTICAL"; + break; + case 5: + orientationStr = "TRANSPOSE"; + break; + case 6: + orientationStr = "ROTATE_90"; + break; + case 7: + orientationStr = "TRANSVERSE"; + break; + case 8: + orientationStr = "ROTATE_270"; + break; + } + + newImage->setImageOrientation(orientationStr); + + } + + + if ( METADATA_EXTRACTOR_ERROR_NONE != image_meta_destroy(img)) + { + LoggerD(" image_meta_destroy is fail... "); + } + + } + else { + LoggerD("fetch Image Info failed.."); + } + + } + else + { + LoggerD("media info is NULL"); + } +} + +void MediacontentManager::readVideoFromMediaInfo( media_info_h info, MediacontentVideo* newVideo) +{ + char* tmpStr; + int tmpInt = 0; + double tmpDouble; + + if ( info) + { + newVideo->setMediaType("VIDEO"); + + readCommonDataFromMediaInfo(info, newVideo); //set common media infomation + + video_meta_h video; + + if ( MEDIA_CONTENT_ERROR_NONE == media_info_get_video(info, &video)) + { + + if ( MEDIA_CONTENT_ERROR_NONE == video_meta_get_recorded_date(video, &tmpStr) ) + { + if ( tmpStr ) + { + struct tm *result=(struct tm *)calloc(1, sizeof(struct tm)); + if (strptime(tmpStr, "%Y:%m:%d %H:%M:%S", result) == NULL) { + LoggerE( "Couldn't convert supplied date."); + } + newVideo->setReleasedDate(result); + + free(tmpStr); + tmpStr = NULL; + } + } + + if ( MEDIA_CONTENT_ERROR_NONE == video_meta_get_album(video, &tmpStr) ) + { + if( tmpStr ) + { + newVideo->setVideoAlbum(tmpStr); + free(tmpStr); + tmpStr = NULL; + } + } + + if ( MEDIA_CONTENT_ERROR_NONE == video_meta_get_artist(video, &tmpStr) ) + { + if ( tmpStr) + { + std::vector<std::string> artists = String::split(tmpStr, TAG_DELIMETER); + for( unsigned int i=0; i < artists.size(); i++) + { + string artist = artists.at(i); + newVideo->appendVideoArtist(artist); + } + + free(tmpStr); + tmpStr = NULL; + } + } + + + if ( MEDIA_CONTENT_ERROR_NONE == media_info_get_longitude(info, &tmpDouble) ) + { + newVideo->setVideoLongitude(tmpDouble); + } + + if ( MEDIA_CONTENT_ERROR_NONE == media_info_get_latitude(info, &tmpDouble) ) + { + newVideo->setVideoLatitude(tmpDouble); + } + + if ( MEDIA_CONTENT_ERROR_NONE == video_meta_get_width(video, &tmpInt) ) + { + newVideo->setVideoWidth(tmpInt); + } + + if ( MEDIA_CONTENT_ERROR_NONE == video_meta_get_height(video, &tmpInt) ) + { + newVideo->setVideoHeight(tmpInt); + } + + if ( MEDIA_CONTENT_ERROR_NONE == video_meta_get_duration(video, &tmpInt) ) + { + newVideo->setVideoDuration(tmpInt); + } + + if ( METADATA_EXTRACTOR_ERROR_NONE != video_meta_destroy(video)) + { + LoggerD(" video_meta_destroy is fail... "); + } + + } + else + { + LoggerD("fetch Video info fail..."); + } + } + else + { + LoggerD("media info is NULL"); + } +} + + +void MediacontentManager::readMusicFromMediaInfo( media_info_h info, MediacontentAudio* newAudio) +{ + char* tmpStr; + int tmpInt = 0; + unsigned long long tmpLongLong = 0; + + if ( info) + { + newAudio->setMediaType("AUDIO"); + + readCommonDataFromMediaInfo(info, newAudio); //set common media infomation + + audio_meta_h audio; + + if ( MEDIA_CONTENT_ERROR_NONE == media_info_get_audio(info, &audio)) + { + if ( MEDIA_CONTENT_ERROR_NONE == audio_meta_get_recorded_date(audio, &tmpStr) ) + { + if ( tmpStr ) + { + struct tm *result = (struct tm *)calloc(1, sizeof(struct tm)); + if (strptime(tmpStr, "%Y:%m:%d %H:%M:%S", result) == NULL) { + LoggerE( "Couldn't convert supplied date."); + } + newAudio->setReleasedDate(result); + + free(tmpStr); + tmpStr = NULL; + } + } + + if ( MEDIA_CONTENT_ERROR_NONE == audio_meta_get_album(audio, &tmpStr) ) + { + if (tmpStr) + { + newAudio->setAudioAlbum(tmpStr); + free(tmpStr); + tmpStr = NULL; + } + } + + if ( MEDIA_CONTENT_ERROR_NONE == audio_meta_get_artist(audio, &tmpStr) ) + { + if (tmpStr) + { + std::vector<std::string> artists = String::split(tmpStr, TAG_DELIMETER); + for( unsigned int i=0; i < artists.size(); i++) + { + string artist = artists.at(i); + newAudio->appendAudioArtist(artist); + } + + free(tmpStr); + tmpStr = NULL; + } + } + + if ( MEDIA_CONTENT_ERROR_NONE == audio_meta_get_composer(audio, &tmpStr) ) + { + if (tmpStr) + { + std::vector<std::string> composers = String::split(tmpStr, TAG_DELIMETER); + for( unsigned int i=0; i < composers.size(); i++) + { + string composer = composers.at(i); + newAudio->appendAudioComposer(composer); + } + + free(tmpStr); + tmpStr = NULL; + } + } + + if ( MEDIA_CONTENT_ERROR_NONE == audio_meta_get_duration(audio, &tmpInt) ) + { + newAudio->setAudioDuration(tmpInt); + } + + if ( MEDIA_CONTENT_ERROR_NONE == audio_meta_get_copyright(audio, &tmpStr) ) + { + if (tmpStr) + { + newAudio->setAudioCopyright(tmpStr); + free(tmpStr); + tmpStr = NULL; + } + } + + if ( MEDIA_CONTENT_ERROR_NONE == audio_meta_get_track_num(audio, &tmpStr) ) + { + int trackNum = 0; + if (tmpStr) + { + try { + istringstream(tmpStr) >> trackNum; + } catch (...) { + LoggerD("Track Number type is wrong. (track number:" << tmpStr << ")"); + trackNum = 0; + } + newAudio->setAudioTrackNum(trackNum); + free(tmpStr); + tmpStr = NULL; + } + } + + if ( MEDIA_CONTENT_ERROR_NONE == media_info_get_size(info, &tmpLongLong) ) + { + newAudio->setAudioSize(tmpLongLong); + } + + if ( MEDIA_CONTENT_ERROR_NONE == audio_meta_get_bit_rate(audio, &tmpInt) ) + { + newAudio->setAudioBitrate(tmpInt); + } + + if ( MEDIA_CONTENT_ERROR_NONE == audio_meta_get_genre(audio, &tmpStr) ) + { + if (tmpStr) + { + std::vector<std::string> genres = String::split(tmpStr, TAG_DELIMETER); + + for( unsigned int i=0; i < genres.size(); i++) + { + string genre = genres.at(i); + newAudio->appendAudioGenre(genre); + } + + free(tmpStr); + tmpStr = NULL; + } + } + + if ( METADATA_EXTRACTOR_ERROR_NONE != audio_meta_destroy(audio)) + { + LoggerD(" audio_meta_destroy is fail... "); + } + + + } + else + { + LoggerD("fetch Music Info fail..."); + } + + + } + else + { + LoggerD("media info is NULL"); + } +} + + + +//Callback. +bool MediacontentManager::mediaFolderCallback(media_folder_h folder, void *user_data) +{ + if (user_data != NULL){ + IEventFindFolder* event = (IEventFindFolder*)user_data; + if ( folder ) + { + MediacontentFolderPtr newFolder(new MediacontentFolder()); + convertToPlatformFolder(folder, newFolder); + + event->addFolder(newFolder); + } + } + else + { + LoggerD("user data is NULL"); + } + return true; + +} + +bool MediacontentManager::mediaItemCallback(media_info_h info, void* user_data) +{ + if (user_data != NULL){ + IEventBrowseFolder* event = (IEventBrowseFolder*)user_data; + + media_content_type_e type; + + if ( MEDIA_CONTENT_ERROR_NONE == media_info_get_media_type( info, &type) ) + { + if ( type == MEDIA_CONTENT_TYPE_IMAGE) + { + MediacontentImage *newImage(new MediacontentImage()); + readImageFromMediaInfo(info, newImage); + event->addMedia(newImage); + } + else if ( type == MEDIA_CONTENT_TYPE_VIDEO) + { + MediacontentVideo *newVideo(new MediacontentVideo()); + readVideoFromMediaInfo(info, newVideo); + event->addMedia(newVideo); + } + else if ( type == MEDIA_CONTENT_TYPE_MUSIC) + { + MediacontentAudio *newVAudio(new MediacontentAudio()); + readMusicFromMediaInfo(info, newVAudio); + event->addMedia(newVAudio); + } + else if( type == MEDIA_CONTENT_TYPE_OTHERS) + { + MediacontentMedia *newMedia(new MediacontentMedia()); + + newMedia->setMediaType("OTHER"); + readCommonDataFromMediaInfo(info, newMedia); + event->addMedia(newMedia); + } + + } + } + else + { + LoggerD("event is NULL"); + } + + return true; +} + +void MediacontentManager::OnRequestReceived(const IEventFindFolderPtr &eFolder) +{ + filter_h filter = NULL; + //set filter + if ( MEDIA_CONTENT_ERROR_NONE == media_filter_create(&filter)) + { + string condition="(FOLDER_STORAGE_TYPE = 0 OR FOLDER_STORAGE_TYPE = 1)"; + + media_filter_set_condition(filter, condition.c_str(), MEDIA_CONTENT_COLLATE_DEFAULT ); //set condition + if ( MEDIA_CONTENT_ERROR_NONE != + media_folder_foreach_folder_from_db (filter, mediaFolderCallback, eFolder.Get())) + { + LoggerE("A platform error occurs in media_folder_foreach_folder_from_db"); + eFolder->setResult(false); + } + else{ + eFolder->setResult(true); + } + if ( MEDIA_CONTENT_ERROR_NONE != media_filter_destroy(filter)) + { + LoggerE("A platform error occurs in media_filter_destroy"); + } + } +} + +void MediacontentManager::OnRequestReceived(const IEventBrowseFolderPtr &eBrowse) +{ + MediaSearchVisitorPtr visitor(new MediaSearchVisitor()); + visitor->setQueryType(MediaSearchVisitor::QUERY_MEDIA); + + try + { + filter_h filter = NULL; + + //set filter + if ( MEDIA_CONTENT_ERROR_NONE == media_filter_create(&filter)) + { + string condition = "(MEDIA_STORAGE_TYPE = 0 OR MEDIA_STORAGE_TYPE = 1)";; + if (eBrowse->getFilterIsSet()) + { + FilterPtr jsFilter = eBrowse->getFilter(); + FilterValidatorPtr validator = MediaFilterValidatorFactory::getMediaFilterValidator(MediaFilterValidatorFactory::QUERY_MEDIA); + bool success = jsFilter->validate(validator); + + if(!success){ + ThrowMsg(InvalidArgumentException, "Invalid attirbutes."); + } + + IFilterVisitorPtr IVisitor = DPL::StaticPointerCast<IFilterVisitor>(visitor); + jsFilter->travel(IVisitor); + condition += " AND "; + condition += visitor->getResult(); + } + + //LoggerI("condition:" << condition); + + media_filter_set_condition(filter, condition.c_str(), MEDIA_CONTENT_COLLATE_DEFAULT ); //set condition + + if(eBrowse->getSortModesIsSet()) + { + media_content_order_e order; + SortModePtr attr = eBrowse->getSortMode(); + + if ( attr ) + { + string attriName = attr->getAttributeName(); + attriName = visitor->getPlatformAttr(attriName); + + if (attriName.compare("") != 0) + { + if (attr->getOrder() == DeviceAPI::Tizen::ASCENDING_SORT_ORDER) + { + order = MEDIA_CONTENT_ORDER_ASC; + } + else + { + order = MEDIA_CONTENT_ORDER_DESC; + } + + if ( MEDIA_CONTENT_ERROR_NONE != + media_filter_set_order(filter, order, attriName.c_str(), MEDIA_CONTENT_COLLATE_DEFAULT )) //set order + { + LoggerE("A platform error occurs in media_filter_set_order"); + } + } + } + + } + + if (eBrowse->getLimitIsSet() ||eBrowse->getOffsetIsSet() ) + { + int count = -1; + int offset = 0; + + if ( eBrowse->getLimitIsSet() ) + { + count = eBrowse->getLimit(); + } + + if ( eBrowse->getOffsetIsSet() ) + { + offset = eBrowse->getOffset(); + } + + if ( MEDIA_CONTENT_ERROR_NONE != media_filter_set_offset(filter, offset, count)) + { + LoggerE("A platform error occurs in media_filter_set_offset"); + } + } + } + else + { + LoggerE("A platform error occurs in media_filter_create"); + eBrowse->setResult(false); + } + + if ( eBrowse->getFolderIdIsSet()) + { + string folderID = eBrowse->getFolderID(); + + if ( MEDIA_CONTENT_ERROR_NONE != + media_folder_foreach_media_from_db (folderID.c_str(), filter, mediaItemCallback, eBrowse.Get())) + { + LoggerE("A platform error occurs in media_folder_foreach_media_from_db"); + eBrowse->setResult(false); + } + else + { + eBrowse->setResult(true); + } + } + else + { + if ( MEDIA_CONTENT_ERROR_NONE != + media_info_foreach_media_from_db (filter, mediaItemCallback, eBrowse.Get())) + { + LoggerE("A platform error occurs in media_info_foreach_media_from_db"); + eBrowse->setResult(false); + } + else + { + eBrowse->setResult(true); + } + } + + //destory Filter + if(filter) + { + if ( MEDIA_CONTENT_ERROR_NONE != media_filter_destroy(filter)) + { + LoggerE("A platform error occurs in media_filter_destroy"); + } + } + } + catch(const InvalidArgumentException &ex) { + LoggerE("Exception: " << ex.DumpToString()); + eBrowse->setExceptionCode(ExceptionCodes::InvalidArgumentException); + eBrowse->setResult(false); + } + catch(const Exception &ex) + { + LoggerE("Exception: " << ex.DumpToString()); + eBrowse->setExceptionCode(ExceptionCodes::UnknownException); + eBrowse->setResult(false); + } +} + +bool MediacontentManager::updateMediaToDB(MediacontentMediaPtr mediaPtr) +{ + string type = mediaPtr->getMediaType(); //media type. + string mediaId = mediaPtr->getMediaUUID(); + + media_info_h media = NULL; + + bool ret = true; + + if ( MEDIA_CONTENT_ERROR_NONE == media_info_get_media_from_db(mediaId.c_str(), &media)) + { + if ( mediaPtr->isChangedRating()) + { + if ( MEDIA_CONTENT_ERROR_NONE + != media_info_set_rating(media, mediaPtr->getRating())) + { + LoggerD("Error: set rating"); + } + } + if ( mediaPtr->isChangedDescription() ) + { + if ( MEDIA_CONTENT_ERROR_NONE + != media_info_set_description (media, mediaPtr->getDescription().c_str())) + { + LoggerD("Error: set description"); + } + } + if( mediaPtr->isChangedDisplayName()) + { + if ( MEDIA_CONTENT_ERROR_NONE + != media_info_set_display_name (media, mediaPtr->getDisplayName().c_str())) + { + LoggerD("Error: set displayname"); + } + } + + if(type.compare("IMAGE") ==0 ) + { + MediacontentImagePtr imagePtr = DPL::DynamicPointerCast<MediacontentImage>(mediaPtr); + + if(imagePtr) + { + image_meta_h img=NULL; + if ( MEDIA_CONTENT_ERROR_NONE == media_info_get_image(media, &img)) + { + if(imagePtr->isChangedOrientaion()) + { + if ( MEDIA_CONTENT_ERROR_NONE != + image_meta_set_orientation (img, convertToOrientation(imagePtr->getImageOrientation()))) + { + LoggerD("Error: set orientation"); + ret = false; + } + } + + if ( MEDIA_CONTENT_ERROR_NONE != + media_info_set_latitude(media, imagePtr->getImageLatitude()) + ) + { + LoggerD("Error: set Latitude"); + ret = false; + } + + if ( MEDIA_CONTENT_ERROR_NONE != + media_info_set_longitude(media, imagePtr->getImageLongitude()) + ) + { + LoggerD("Error: set Longitude"); + ret = false; + } + + if ( MEDIA_CONTENT_ERROR_NONE != image_meta_update_to_db (img) ) + { + LoggerD("Error: update db"); + ret = false; + } + + if ( MEDIA_CONTENT_ERROR_NONE != image_meta_destroy(img)) + { + LoggerD("Error: destroy media info"); + ret = false; + } + + img = NULL; + + } + else + { + LoggerD("Error: get Image from DB"); + ret = false; + } + } + + } + + if(type.compare("VIDEO") ==0 ) + { + MediacontentVideoPtr videoPtr = DPL::DynamicPointerCast<MediacontentVideo>(mediaPtr); + if (videoPtr) + { + + video_meta_h video = NULL; + if ( MEDIA_CONTENT_ERROR_NONE == media_info_get_video(media, &video)) + { + if ( MEDIA_CONTENT_ERROR_NONE != + media_info_set_latitude(media, videoPtr->getVideoLatitude()) + ) + { + LoggerD("Error: set Latitude"); + ret = false; + } + + if ( MEDIA_CONTENT_ERROR_NONE != + media_info_set_longitude(media, videoPtr->getVideoLongitude()) + ) + { + LoggerD("Error: set Latitude"); + ret = false; + } + + + if ( MEDIA_CONTENT_ERROR_NONE != video_meta_update_to_db (video) ) + { + LoggerD("Error: update db"); + ret = false; + } + + if ( MEDIA_CONTENT_ERROR_NONE != video_meta_destroy(video)) + { + LoggerD("Error: destroy video meta"); + ret = false; + } + + video = NULL; + + } + } + + } //video + + + + if(type.compare("AUDIO") ==0 ) + { + + MediacontentAudioPtr audioPtr = DPL::DynamicPointerCast<MediacontentAudio>(mediaPtr); + if (audioPtr && ( audioPtr->isChangedAudioArtist () || audioPtr->isChangedAudioAlbum() + || audioPtr->isChangedAudioGenre() ||audioPtr->isChangedAudioComposer() + || audioPtr->isChangedAudioTrackNumber()) ) + { + + audio_meta_h audio=NULL; + if ( MEDIA_CONTENT_ERROR_NONE == media_info_get_audio(media, &audio)) + { + if ( MEDIA_CONTENT_ERROR_NONE != audio_meta_update_to_db (audio) ) + { + LoggerD("Error: update db"); + ret = false; + } + + if ( MEDIA_CONTENT_ERROR_NONE != audio_meta_destroy(audio)) + { + LoggerD("Error: destroy audio meta"); + ret = false; + } + audio = NULL; + } + + } + + } + + + //update media info + if ( MEDIA_CONTENT_ERROR_NONE != media_info_update_to_db(media)) + { + LoggerD("Error: update to DB"); + ret = false; + } + } + + if( media != NULL) + { + if ( MEDIA_CONTENT_ERROR_NONE !=media_info_destroy(media)) + { + LoggerD("Error: destroy media info"); + ret = false; + } + } + return ret; + +} + +void MediacontentManager::OnRequestReceived(const IEventUpdateMediaPtr &eMedia) +{ + try + { + MediacontentMediaPtr mediaPtr = eMedia->getMediaItem(); + + if(updateMediaToDB(mediaPtr)) + { + eMedia->setResult(true); + } + else + { + eMedia->setResult(false); + ThrowMsg(PlatformException, "DB operation is failed"); + } + } + catch (const Exception &ex) + { + LoggerE("Exception: " << ex.DumpToString()); + eMedia->setResult(false); + } +} + + +void MediacontentManager::OnRequestReceived(const IEventUpdateMediaItemsPtr &eItems) +{ + try + { + MediacontentMediaListPtr mediaListPtr = eItems->getMediaItems(); + if (mediaListPtr->empty()) + { + LoggerD("Item vector is empty"); + } + else + { + for(unsigned int i=0; i<mediaListPtr->size(); i++) + { + + MediacontentMediaPtr mediaPtr = mediaListPtr->at(i); + if(updateMediaToDB(mediaPtr)) + { + eItems->setResult(true); + LoggerD("update success"); + } + else + { + eItems->setResult(false); + ThrowMsg(PlatformException, "DB operation is failed"); + } + + } + } + } + catch (const Exception &ex) + { + LoggerE("Exception: " << ex.DumpToString()); + eItems->setResult(false); + } +} + +} +} diff --git a/wearable_src/Content/ContentManager.h b/wearable_src/Content/ContentManager.h new file mode 100755 index 0000000..31d3d80 --- /dev/null +++ b/wearable_src/Content/ContentManager.h @@ -0,0 +1,83 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _PLATFORM_MEDIA_CONTENT_MANAGER_H_ +#define _PLATFORM_MEDIA_CONTENT_MANAGER_H_ + +#include <vector> +#include <list> +#include <dpl/mutex.h> +#include "IContentManager.h" + +#include <ctime> +#include "IEventGetDirectories.h" +#include "IEventUpdate.h" +#include "IEventUpdateBatch.h" +#include "ContentSearchVisitor.h" + +#include "ContentImage.h" +#include "ContentVideo.h" +#include "ContentAudio.h" +#include "AudioLyrics.h" + +#include <media_content.h> +#include <metadata_extractor.h> + +#define MEDIA_DEBUG 0 +#define TAG_DELIMETER '/' //After reviewing the ID3v2.3 spec the delimiter is a "/" for multiple entries. + +namespace DeviceAPI { +namespace Content { + +class MediacontentManager : public IMediacontentManager +{ + public: + MediacontentManager(); + virtual ~MediacontentManager(); + + static void readCommonDataFromMediaInfo(media_info_h info, MediacontentMedia* newMedia); + static void readImageFromMediaInfo( media_info_h info, MediacontentImage* newImage); + static void readVideoFromMediaInfo( media_info_h info, MediacontentVideo* newVideo); + static void readMusicFromMediaInfo( media_info_h info, MediacontentAudio* newAudio); + + protected: + virtual void OnRequestReceived(const IEventFindFolderPtr &ptr); + virtual void OnRequestReceived(const IEventUpdateMediaPtr &ptr); + virtual void OnRequestReceived(const IEventBrowseFolderPtr &ptr); + virtual void OnRequestReceived(const IEventUpdateMediaItemsPtr &ptr); + + private: + static bool mediaFolderCallback(media_folder_h folder, void *user_data); + static bool mediaItemCallback(media_info_h info, void* user_data); + static void convertToPlatformFolder(media_folder_h media_folder, MediacontentFolderPtr& newFolder); + bool updateMediaToDB(MediacontentMediaPtr mediaPtr); + string makeQuerySortMode(SortModeArrayPtr attr, MediaSearchVisitor::QueryType value=MediaSearchVisitor::QUERY_FOLDER); + static tm* toDateTm(time_t date); + media_content_orientation_e convertToOrientation(string orientation); + + private: + static int m_instanceCount; + DPL::Mutex m_constructorMutex; + +}; + +} +} + +#endif /* _PLATFORM_MEDIA_CONTENT_MANAGER_H_ */ diff --git a/wearable_src/Content/ContentMedia.cpp b/wearable_src/Content/ContentMedia.cpp new file mode 100755 index 0000000..cabe729 --- /dev/null +++ b/wearable_src/Content/ContentMedia.cpp @@ -0,0 +1,237 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <Commons/Exception.h> +#include "ContentMedia.h" +#include <aul/aul.h> +#include <Logger.h> + +namespace DeviceAPI { +namespace Content { + +MediacontentMedia::MediacontentMedia() +{ + m_isChangedFavorite = false; + m_isChangedDisplayName = false; + m_createdDate = NULL; + m_releasedDate = NULL; + m_modifiedDate = NULL; + + m_size = 0; + m_rating = 0; + m_favorite = false; //unused. + m_editableAttrList.push_back("name"); + m_editableAttrList.push_back("rating"); + m_editableAttrList.push_back("description"); +} + +MediacontentMedia::~MediacontentMedia() +{ + m_editableAttrList.clear(); + if(m_createdDate != NULL) + { + free(m_createdDate); + } + if(m_releasedDate != NULL) + { + free(m_releasedDate); + } + if(m_modifiedDate != NULL) + { + free(m_modifiedDate); + } +} + +string MediacontentMedia::getMediaUUID() const +{ + return m_mediaUUID; +} + +void MediacontentMedia::setMediaUUID(const string &value) +{ + m_mediaUUID = value; +} + +string MediacontentMedia::getMimeType() +{ + return m_mimeType; +} + +string MediacontentMedia::getDisplayName() const +{ + return m_displayName; +} + +void MediacontentMedia::setMimeType(const string &value) +{ + m_mimeType = value; +} + +void MediacontentMedia::setDisplayName(const string &value, bool isChanged) +{ + m_displayName = value; + if (isChanged) + m_isChangedDisplayName = true; +} + +string MediacontentMedia::getTitle() const +{ + return m_title; +} + +void MediacontentMedia::setTitle(const string &value) +{ + m_title = value; +} + +string MediacontentMedia::getFilePath() const +{ + return m_filePath; + +} + +void MediacontentMedia::setFilePath(const string &value) +{ + m_filePath = value; + +} + +string MediacontentMedia::getThumbnailPath() const +{ + return m_thumbnailPath; +} + + +tm* MediacontentMedia::getCreatedDate() const +{ + return m_createdDate; +} + +tm* MediacontentMedia::getReleasedDate() const +{ + return m_releasedDate; +} + +void MediacontentMedia::setThumbnailPath(const string &value) +{ + m_thumbnailPath = value; + +} +tm* MediacontentMedia::getModifiedDate() const +{ + return m_modifiedDate; +} + +void MediacontentMedia::setCreatedDate(tm *value) +{ + m_createdDate = value; + +} + +void MediacontentMedia::setReleasedDate(tm *value) +{ + m_releasedDate = value; + +} + +void MediacontentMedia::setModifiedDate(tm *value) +{ + m_modifiedDate = value; + +} +bool MediacontentMedia::getFavorite() const +{ + return m_favorite; +} +void MediacontentMedia::setFavorite(bool value) +{ + m_favorite = value; + m_isChangedFavorite = true; + +} +string MediacontentMedia::getMediaType() const +{ + return m_mediaType; +} + +void MediacontentMedia::setMediaType(const string &value) +{ + m_mediaType = value; +} + +string MediacontentMedia::getDescription() const +{ + return m_description; +} + +void MediacontentMedia::setDescription(const string &value, bool isChanged) +{ + m_description = value; + if ( isChanged ) + m_isChangedDescription = true; + +} + +bool MediacontentMedia::getIsChangedFavorite() const +{ + return m_isChangedFavorite; +} + +bool MediacontentMedia::isChangedRating() const +{ + return m_isChangedRating; +} + +bool MediacontentMedia::isChangedDisplayName() const +{ + return m_isChangedDisplayName; +} + +bool MediacontentMedia::isChangedDescription() const +{ + return m_isChangedDescription; +} + +vector<std::string> MediacontentMedia::getEditableAttr() const +{ + return m_editableAttrList; +} + +void MediacontentMedia::setSize(unsigned long long value) +{ + m_size = value; +} + +unsigned long long MediacontentMedia::getSize() const +{ + return m_size; +} + +void MediacontentMedia::setRating(int value, bool isChanged) +{ + m_rating = value; + if ( isChanged ) + m_isChangedRating = true; +} + +int MediacontentMedia::getRating() const +{ + return m_rating; +} + +} +} diff --git a/wearable_src/Content/ContentMedia.h b/wearable_src/Content/ContentMedia.h new file mode 100755 index 0000000..1902556 --- /dev/null +++ b/wearable_src/Content/ContentMedia.h @@ -0,0 +1,129 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _ABSTRACT_LAYER_CONTENT_MEDIA_H_ +#define _ABSTRACT_LAYER_CONTENT_MEDIA_H_ + +#include <ctime> +#include <string> +#include <vector> +#include <dpl/optional.h> +#include <dpl/shared_ptr.h> + +using namespace std; + +namespace DeviceAPI { +namespace Content { + +const double DEFAULT_GEOLOCATION = -200; + +typedef enum +{ + MEDIA_TYPE_IMAGE = 1, + MEDIA_TYPE_VIDEO = 2, + MEDIA_TYPE_AUDIO = 3, + MEDIA_TYPE_UNKOWN = 4, +}media_type; + +typedef vector<std::string> EditableAttributeList; +typedef DPL::SharedPtr<EditableAttributeList> EditableAttributeListPtr; + +typedef vector<std::string> StringArray; +typedef DPL::SharedPtr<StringArray> StringArrayPtr; + +class MediacontentMedia +{ + public: + + MediacontentMedia(); + virtual ~MediacontentMedia(); + + virtual string getMediaUUID() const; + virtual string getMediaType() const; + virtual string getMimeType(); + virtual string getDisplayName() const; + virtual string getTitle() const; + virtual string getFilePath() const; + virtual string getThumbnailPath() const; + virtual tm* getCreatedDate() const; + virtual tm* getReleasedDate() const; + virtual tm* getModifiedDate() const; + virtual string getDescription() const; + virtual bool getFavorite() const; + virtual unsigned long long getSize() const; + virtual int getRating() const; + + bool getIsChangedFavorite() const; + bool isChangedRating() const; + bool isChangedDisplayName() const; + bool isChangedDescription() const; + + virtual void setMediaUUID(const string &value); + virtual void setMediaType(const string &value); + virtual void setMimeType(const string &value); + virtual void setDisplayName(const string &value, bool isChanged=false); + virtual void setTitle(const string &value); + virtual void setFilePath(const string &value); + virtual void setThumbnailPath(const string &value); + virtual void setCreatedDate(tm *value); + virtual void setReleasedDate(tm *value); + virtual void setModifiedDate(tm *value); + virtual void setFavorite( bool value); + virtual void setDescription(const string &value, bool isChanged=false); + virtual void setSize(unsigned long long value); + virtual void setRating(int value, bool isChanged=false); + + virtual vector<std::string> getEditableAttr() const; + + private: + string m_mediaUUID; + string m_mediaType; + string m_mimeType; + string m_displayName; + string m_title; + string m_filePath; + string m_thumbnailPath; + string m_description; + tm *m_createdDate; + tm *m_releasedDate; + tm *m_modifiedDate; + unsigned long long m_size; + int m_rating; + bool m_favorite; //unused. + bool m_isChangedFavorite; + bool m_isChangedRating; + bool m_isChangedDisplayName; + bool m_isChangedDescription; + + protected: + vector<std::string> m_editableAttrList; + +}; + + +typedef DPL::SharedPtr<MediacontentMedia> MediacontentMediaPtr; +typedef std::vector<MediacontentMediaPtr> MediacontentMediaList; +typedef DPL::SharedPtr<MediacontentMediaList> MediacontentMediaListPtr; + + +} +} + + +#endif /* _ABSTRACT_LAYER_CONTENT_MEDIA_H_ */ + diff --git a/wearable_src/Content/ContentSearchVisitor.cpp b/wearable_src/Content/ContentSearchVisitor.cpp new file mode 100755 index 0000000..53c61f5 --- /dev/null +++ b/wearable_src/Content/ContentSearchVisitor.cpp @@ -0,0 +1,469 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "time.h" +#include <iomanip> +#include <Commons/Exception.h> +#include "ContentSearchVisitor.h" +#include "ContentUtility.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Content { + +const string STR_LEFT_BRACKET(" ("); +const string STR_RIGHT_BRACKET(") "); +const string STR_AND(" AND "); +const string STR_OR(" OR "); +const string STR_GREATER_THAN (">"); +const string STR_LESS_THAN ("<"); +const string STR_EQUAL ("="); +const string STR_S_QUOTATION ("'"); +const string STR_PERCENT ("%"); +const string STR_MIN_LATITUDE("-90"); +const string STR_MAX_LATITUDE("90"); +const string STR_MIN_LONGITUDE("-180"); +const string STR_MAX_LONGITUDE("180"); + + + +typedef enum +{ + MEDIA_ID = 0, + MEDIA_TITLE, + MEDIA_FILEPATH, + MEDIA_THUMBNAILPATH, + MEDIA_CREATEDDATE, + MEDIA_MODIFIEDDATE, + MEDIA_DESCRIPTION, + MEDIA_RATING, + +}media_attribute_e; + + +map<string, string> MediaSearchVisitor::attrFolderEnumMap = { + {"id", "id"}, + {"directoryURI", "FOLDER_PATH"}, + {"title", "FOLDER_NAME"}, + {"storageType", "FOLDER_STORAGE_TYPE"}, + {"modifiedDate", "FOLDER_MODIFIED_TIME"}, +}; + +map<string, string> MediaSearchVisitor::attrMediaEnumMap = { +//media item attribues. + {"id", "MEDIA_ID"}, + {"type", "MEDIA_TYPE"}, + {"mimeType", "MEDIA_MIME_TYPE"}, + {"name", "MEDIA_DISPLAY_NAME"}, + {"title", "MEDIA_TITLE"}, + {"contentURI", "MEDIA_PATH"}, + {"thumbnailURIs", "MEDIA_THUMBNAIL_PATH"}, + {"description", "MEDIA_DESCRIPTION"}, + {"rating", "MEDIA_RATING"}, + {"createdDate", "MEDIA_ADDED_TIME"}, + {"releaseDate", "MEDIA_DATETAKEN"}, + {"modifiedDate", "MEDIA_MODIFIED_TIME"}, +//media image,video,audio attribues. + {"geolocation.latitude", "MEDIA_LATITUDE"}, + {"geolocation.longitude", "MEDIA_LONGITUDE"}, + {"album", "MEDIA_ALBUM"}, + {"artists", "MEDIA_ARTIST"}, + {"width", "MEDIA_WIDTH"}, + {"height", "MEDIA_HEIGHT"}, + {"genres", "MEDIA_GENRE"}, + {"size", "MEDIA_SIZE"}, + +}; + +MediaSearchVisitor::MediaSearchVisitor() +{ + +} + +MediaSearchVisitor::~MediaSearchVisitor() +{ + +} + +void MediaSearchVisitor::visitPreComposite(FilterType& type, int depth) +{ + m_query.append(STR_LEFT_BRACKET); +} + +void MediaSearchVisitor::visitInComposite(FilterType& type, int depth) +{ + if(type == UNION_FILTER) + m_query.append(STR_OR); + else if(type == INTERSECTION_FILTER) + m_query.append(STR_AND); + else{ + ThrowMsg(InvalidArgumentException, "Filter Type is wrong."); + } +} + +void MediaSearchVisitor::visitPostComposite(FilterType& type, int depth) +{ + m_query.append(STR_RIGHT_BRACKET); +} + + +string MediaSearchVisitor::getPlatformAttr(string attrName) +{ + string platformAttr; + map<string, string>::iterator pos; + + if( queryType == QUERY_FOLDER) + { + pos = attrFolderEnumMap.find(attrName); + + if(attrFolderEnumMap.end() != pos) + { + platformAttr = pos->second; + } + else + { + ThrowMsg(InvalidArgumentException, "Attribute(" << attrName << ") is not supported."); + } + } + else if(queryType == QUERY_MEDIA) + { + pos = attrMediaEnumMap.find(attrName); + + if(attrMediaEnumMap.end() != pos) + { + platformAttr = pos->second; + } + else + { + ThrowMsg(InvalidArgumentException, "Attribute(" << attrName << ") is not supported."); + } + + } + return platformAttr; +} + + +void MediaSearchVisitor::visitAttribute(string& attrName, MatchFlag& matchFlag, AnyPtr& matchValue, int depth) +{ + string attrPlatform = getPlatformAttr(attrName); + if(matchValue == NULL) + { + ThrowMsg(PlatformException, "matchValue is not valid data."); + } + + m_query.append(convertAttribute(attrPlatform, matchValue, matchFlag)); +} + +string MediaSearchVisitor::toDateDbStr(tm &date) const +{ + time_t time; + time = mktime(&date); + stringstream ss; + ss << time; + return ss.str(); +} + +string MediaSearchVisitor::convertAttribute(string &attrName, AnyPtr& matchValue, MatchFlag& matchFlag) +{ + string valueStr; + string valueSubStr; + string operatorStr; + string conditionStr; + + string matchValueStr; + + if(attrName.compare("MEDIA_TYPE")==0) + { + if(matchValue->getString().compare("IMAGE")==0) + matchValueStr = "0"; + else if(matchValue->getString().compare("VIDEO")==0) + matchValueStr = "1"; + else if(matchValue->getString().compare("AUDIO")==0) + matchValueStr = "3"; + else if(matchValue->getString().compare("OTHER")==0) + matchValueStr = "4"; + else + { + ThrowMsg(InvalidArgumentException, "mediaType(" << matchValue->getString() << ") is not supported."); + } + } + else if(attrName.compare("MEDIA_PATH")==0 || attrName.compare("MEDIA_THUMBNAIL_PATH")==0) + { + matchValueStr = ContentUtility::convertUriToPath(matchValue->getString()); + } + else if(attrName.compare("MEDIA_LATITUDE")==0){ + if(matchValue->getDouble() < MIN_LATITUDE || + matchValue->getDouble() > MAX_LATITUDE) + { + ThrowMsg(InvalidArgumentException, "latitude range is -90 ~ 90"); + } + else + { + matchValueStr = matchValue->toString(); + } + } + else if(attrName.compare("MEDIA_LONGITUDE")==0){ + if(matchValue->getDouble() < MIN_LONGITUDE|| + matchValue->getDouble() > MAX_LONGITUDE) + { + ThrowMsg(InvalidArgumentException, "longitude range is -180 ~ 180"); + } + else + { + matchValueStr = matchValue->toString(); + } + } + else + { + matchValueStr = matchValue->toString(); + } + + if(matchValue->isType(PrimitiveType_Time)) + { + tm date = *matchValue->getDateTm(); + if(attrName.compare("MEDIA_DATETAKEN")==0) + { + char buf[512]; + strftime(buf, sizeof(buf), "'%Y:%m:%d %H:%M:%S'", &date); + valueStr = buf; + } + else + { + valueStr = toDateDbStr(date); + } + m_operationKey = EQUAL; + } + else + { + ostringstream os; + + switch (matchFlag) { + + case MATCH_CONTAINS: + m_operationKey = LIKE; + os << STR_S_QUOTATION << STR_PERCENT << matchValueStr << STR_PERCENT << STR_S_QUOTATION; + break; + case MATCH_STARTSWITH: + m_operationKey = LIKE; + os << STR_S_QUOTATION << matchValueStr << STR_PERCENT << STR_S_QUOTATION; + break; + case MATCH_ENDSWITH: + m_operationKey = LIKE; + os << STR_S_QUOTATION << STR_PERCENT << matchValueStr << STR_S_QUOTATION; + break; + case MATCH_FULLSTRING: + m_operationKey = FULLSTRING; + os << STR_S_QUOTATION << matchValueStr << STR_S_QUOTATION << " COLLATE NOCASE "; + break; + case MATCH_EXISTS: + m_operationKey = EXISTS; + break; + case MATCH_EXACTLY: + default: + m_operationKey = EQUAL; + os << STR_S_QUOTATION << matchValueStr << STR_S_QUOTATION; + } + + valueStr = os.str(); + } + + //set operation + operatorStr = operatorKey[m_operationKey]; + + if ( attrName.compare("MEDIA_TYPE")==0 && matchValue->getString().compare("AUDIO")==0 ) //if Audio media type. + { + std::string::size_type offset = 0; + std::string soundTypeString = "2"; + + valueSubStr = valueStr; + + while( true ) + { + offset = valueSubStr.find( matchValueStr, offset ); + + if( std::string::npos == offset ) + break; + else + valueSubStr.replace( offset, matchValueStr.length(), soundTypeString ); + } + + if( m_operationKey != EXISTS) + { + valueSubStr = STR_OR + attrName + operatorStr + valueSubStr; + } + else + { + valueSubStr = STR_OR + attrName + operatorStr; + } + } + + + if( m_operationKey != EXISTS) + { + conditionStr = STR_LEFT_BRACKET + attrName + operatorStr + valueStr + valueSubStr + STR_RIGHT_BRACKET; + } + else + { + conditionStr = STR_LEFT_BRACKET + attrName + operatorStr + valueSubStr + STR_RIGHT_BRACKET; + } + + return conditionStr; +} + +condition_e MediaSearchVisitor::getOperationKey() +{ + return m_operationKey; +} + + +void MediaSearchVisitor::visitAttributeRange(string& attrName,AnyPtr& initialValue,AnyPtr& endValue,int depth) +{ + if(initialValue == NULL || endValue == NULL) + return; + + string str; + string initialValueStr; + string endValueStr; + + string attrPlatform = getPlatformAttr(attrName); + + if(!initialValue->isNullOrUndefined()) + { + if(initialValue->isType(PrimitiveType_Time)) + { + tm date = *initialValue->getDateTm(); + if(attrPlatform.compare("MEDIA_DATETAKEN")==0) + { + char buf[512]; + strftime(buf, sizeof(buf), "'%Y:%m:%d %H:%M:%S'", &date); + initialValueStr = buf; + } + else + { + initialValueStr = toDateDbStr(date); + } + } + else + { + initialValueStr = initialValue->toString(); + } + } + + if (!endValue->isNullOrUndefined()) + { + if(endValue->isType(PrimitiveType_Time)) + { + tm date = *endValue->getDateTm(); + if(attrPlatform.compare("MEDIA_DATETAKEN")==0) + { + char buf[512]; + strftime(buf, sizeof(buf), "'%Y:%m:%d %H:%M:%S'", &date); + endValueStr = buf; + } + else + { + endValueStr = toDateDbStr(date); + } + } + else + { + endValueStr = endValue->toString(); + } + } + + if (!initialValue->isNullOrUndefined() && endValue->isNullOrUndefined()) + { + initialValueStr = initialValue->toString(); + if(attrPlatform.compare("MEDIA_LATITUDE")==0) + { + if(initialValue->getDouble() < MIN_LATITUDE) + { + initialValueStr = STR_MIN_LATITUDE; + } + } + else if(attrPlatform.compare("MEDIA_LONGITUDE")==0) + { + if(initialValue->getDouble() < MIN_LONGITUDE) + { + initialValueStr = STR_MIN_LONGITUDE; + } + } + str = STR_LEFT_BRACKET + attrPlatform + STR_GREATER_THAN + STR_EQUAL + + STR_S_QUOTATION + initialValueStr + STR_S_QUOTATION + STR_RIGHT_BRACKET; + } + else if(initialValue->isNullOrUndefined() && !endValue->isNullOrUndefined()) + { + if(attrPlatform.compare("MEDIA_LATITUDE")==0) + { + initialValueStr = STR_MIN_LATITUDE; + str = STR_LEFT_BRACKET + attrPlatform + STR_GREATER_THAN + STR_EQUAL + STR_S_QUOTATION + + initialValueStr + STR_S_QUOTATION + STR_AND + attrPlatform + STR_LESS_THAN + STR_S_QUOTATION + + endValueStr + STR_S_QUOTATION + STR_RIGHT_BRACKET; + } + else if(attrPlatform.compare("MEDIA_LONGITUDE")==0) + { + initialValueStr = STR_MIN_LONGITUDE; + str = STR_LEFT_BRACKET + attrPlatform + STR_GREATER_THAN + STR_EQUAL + STR_S_QUOTATION + + initialValueStr + STR_S_QUOTATION + STR_AND + attrPlatform + STR_LESS_THAN + STR_S_QUOTATION + + endValueStr + STR_S_QUOTATION + STR_RIGHT_BRACKET; + } + else + { + str = STR_LEFT_BRACKET + attrPlatform + STR_LESS_THAN + STR_S_QUOTATION + + endValueStr + STR_S_QUOTATION + STR_RIGHT_BRACKET; + } + } + else if (!initialValue->isNullOrUndefined() && !endValue->isNullOrUndefined()) + { + if(attrPlatform.compare("MEDIA_LATITUDE")==0) + { + if(initialValue->getDouble() < MIN_LATITUDE) + { + initialValueStr = STR_MIN_LATITUDE; + } + } + else if(attrPlatform.compare("MEDIA_LONGITUDE")==0) + { + if(initialValue->getDouble() < MIN_LONGITUDE) + { + initialValueStr = STR_MIN_LONGITUDE; + } + } + str = STR_LEFT_BRACKET + attrPlatform + STR_GREATER_THAN + STR_EQUAL + STR_S_QUOTATION + + initialValueStr + STR_S_QUOTATION + STR_AND + attrPlatform + STR_LESS_THAN + STR_S_QUOTATION + + endValueStr + STR_S_QUOTATION + STR_RIGHT_BRACKET; + } + + m_query.append(str); + +} + +string MediaSearchVisitor::getResult() const +{ + return m_query; +} + +void MediaSearchVisitor::setQueryType(QueryType value) +{ + queryType = value; +} + + + + +} +} diff --git a/wearable_src/Content/ContentSearchVisitor.h b/wearable_src/Content/ContentSearchVisitor.h new file mode 100755 index 0000000..6c33999 --- /dev/null +++ b/wearable_src/Content/ContentSearchVisitor.h @@ -0,0 +1,108 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _PLATFORM_MEDIA_CONTENT_SEARCH_VISITOR_H_ +#define _PLATFORM_MEDIA_CONTENT_SEARCH_VISITOR_H_ + +#include <map> +#include <string> +#include <dpl/shared_ptr.h> +#include <IFilter.h> +#include <IFilterVisitor.h> +#include <SortMode.h> + + +using namespace DeviceAPI::Tizen; +using namespace WrtDeviceApis::Commons; +using namespace std; + + + +namespace DeviceAPI { +namespace Content { + +typedef enum +{ + EQUAL, + NOT_EQUAL, + GREATER_THAN, + LESS_THAN, + GREATER_THAN_OR_EQUAL, + LESS_THAN_OR_EQUAL, + LIKE, + FULLSTRING, + EXISTS, + CONDITION_MAX +}condition_e; + +static string operatorKey[] = +{ + " = ", //EQUAL + " NOT IN ", //NOT_EQUAL + " > ", //GREATER_THAN + " < ", //LESS_THAN + " >= ", //GREATER_THAN_OR_EQUAL + " <= ", //LESS_THAN_OR_EQUAL + " LIKE ", // like + " = ", //fullstring + " is not null " //EXISTS +}; + +class MediaSearchVisitor : public DeviceAPI::Tizen::IFilterVisitor +{ +public: + typedef enum _QueryType { QUERY_FOLDER, QUERY_MEDIA } QueryType; + + + MediaSearchVisitor(); + virtual ~MediaSearchVisitor(); + + virtual void visitPreComposite(FilterType& type, int depth); + virtual void visitInComposite(FilterType& type, int depth); + virtual void visitPostComposite(FilterType& type, int depth); + virtual void visitAttribute(string& attrName, MatchFlag& matchFlag, AnyPtr& matchValue, int depth); + virtual void visitAttributeRange(string& attrName,AnyPtr& initialValue,AnyPtr& endValue,int depth); + + string getPlatformAttr(string attrName); + string getResult() const; + condition_e getOperationKey(); + + void setQueryType(QueryType value); + +private: + string toDateDbStr(tm &date) const; + string convertAttribute(string &attrname, AnyPtr& matchValue, MatchFlag& matchFlag); + +private: + condition_e m_operationKey; + QueryType queryType; + string m_query; + static map<string, string> attrFolderEnumMap; + static map<string, string> attrMediaEnumMap; + + vector<string> m_condition; + + +}; + +typedef DPL::SharedPtr<MediaSearchVisitor> MediaSearchVisitorPtr; + +} +} + +#endif // _PLATFORM_MEDIA_CONTENT_SEARCH_VISITOR_H_ diff --git a/wearable_src/Content/ContentUtility.cpp b/wearable_src/Content/ContentUtility.cpp new file mode 100755 index 0000000..d469192 --- /dev/null +++ b/wearable_src/Content/ContentUtility.cpp @@ -0,0 +1,103 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "ContentUtility.h" +#include <Commons/Regex.h> + + +namespace DeviceAPI { +namespace Content { + +using namespace std; +using namespace WrtDeviceApis::Commons; + +ContentUtility::ContentUtility() +{ +} + +ContentUtility::~ContentUtility() +{ +} + +string ContentUtility::convertUriToPath(const string str) +{ + string result; + std::string schema ("file://"); + std::string _str = ContentUtility::ltrim(str); + + std::string _schema = _str.substr(0,schema.size()); + + if(_schema == schema) + { + result = _str.substr(schema.size()); + } + else + { + result = _str; + } + return result; +} + +string ContentUtility::convertPathToUri(const string str) +{ + string result; + std::string schema ("file://"); + std::string _str = ContentUtility::ltrim(str); + + std::string _schema = _str.substr(0,schema.size()); + + if(_schema == schema) + { + result = _str; + } + else + { + result = schema + _str; + } + return result; +} + +std::string ContentUtility::ltrim(const std::string s) +{ + std::string str = s; + std::string::iterator i; + for (i = str.begin(); i != str.end(); i++) { + if (!isspace(*i)) { + break; + } + } + if (i == str.end()) { + str.clear(); + } else { + str.erase(str.begin(), i); + } + return str; +} + +bool ContentUtility::checkLocation(double lati, double longi) +{ + bool ret = true; + if(lati < MIN_LATITUDE || lati > MAX_LATITUDE || + longi < MIN_LONGITUDE || longi > MAX_LONGITUDE){ + ret = false; + } + return ret; +} + + +} // Content +} // DeviceAPI diff --git a/wearable_src/Content/ContentUtility.h b/wearable_src/Content/ContentUtility.h new file mode 100755 index 0000000..496769c --- /dev/null +++ b/wearable_src/Content/ContentUtility.h @@ -0,0 +1,49 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _PLATFORM_CONTENT_UTILITY_H_ +#define _PLATFORM_CONTENT_UTILITY_H_ + +#include <string> + +namespace DeviceAPI { +namespace Content { + +const double MAX_LATITUDE = 90; +const double MIN_LATITUDE = -90; +const double MAX_LONGITUDE = 180; +const double MIN_LONGITUDE = -180; + +class ContentUtility +{ +public: + ContentUtility(); + virtual ~ContentUtility(); + + static std::string convertUriToPath(const std::string str); + static std::string convertPathToUri(const std::string str); + static bool checkLocation(double lati, double longi); +private: + static std::string ltrim(const std::string s); + +}; + +} // Content +} // DeviceAPI + +#endif // _PLATFORM_CONTENT_UTILITY_H_ diff --git a/wearable_src/Content/ContentVideo.cpp b/wearable_src/Content/ContentVideo.cpp new file mode 100755 index 0000000..4b4cbca --- /dev/null +++ b/wearable_src/Content/ContentVideo.cpp @@ -0,0 +1,148 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <Commons/Exception.h> +#include "ContentVideo.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Content { + + +MediacontentVideo::MediacontentVideo() +{ + m_editableAttrList.push_back("geolocation"); + m_videoLongitude = DEFAULT_GEOLOCATION; + m_videoLatitude = DEFAULT_GEOLOCATION; +} + +MediacontentVideo::~MediacontentVideo() +{ +} + +int MediacontentVideo::getVideoDuration() const +{ + return m_videoDuration; + +} + +int MediacontentVideo::getVideoWidth() const +{ + return m_videoWidth; + +} + +int MediacontentVideo::getVideoHeight() const +{ + return m_videoHeight; +} + +double MediacontentVideo::getVideoLatitude() const +{ + return m_videoLatitude; +} + +double MediacontentVideo::getVideoLongitude() const +{ + return m_videoLongitude; + +} + +string MediacontentVideo::getVideoAlbum() const +{ + return m_videoAlbum; +} + +vector<std::string> MediacontentVideo::getVideoArtist() const +{ + return m_videoArtist; +} + + +void MediacontentVideo::setVideoDuration(const int &value) +{ + m_videoDuration = value; +} + +void MediacontentVideo::setVideoWidth(const int &value) +{ + m_videoWidth = value; + +} + +void MediacontentVideo::setVideoHeight(const int &value) +{ + m_videoHeight = value; + +} + +void MediacontentVideo::setVideoLatitude(const double &value, bool isChanged) +{ + m_videoLatitude = value; + m_isChangedLatitude =isChanged; +} + +void MediacontentVideo::setVideoLongitude(const double &value, bool isChanged) +{ + m_videoLongitude = value; + m_isChangedLongitude=isChanged; +} + +void MediacontentVideo::setVideoAlbum(const string &value, bool isChanged) +{ + m_videoAlbum = value; + m_isChangedAlbum=isChanged; +} + +void MediacontentVideo::setVideoArtist(const vector<std::string> &value, bool isChanged) +{ + m_videoArtist = value; + m_isChangedArtists=isChanged; +} + +void MediacontentVideo::appendVideoArtist(const string value) +{ + m_videoArtist.push_back(value); +} + +bool MediacontentVideo::isChangedArtists() +{ + return m_isChangedArtists; +} + +bool MediacontentVideo::isChangedAlbum() +{ + return m_isChangedAlbum; +} + +bool MediacontentVideo::isChangedLatitude() +{ + return m_isChangedLatitude; +} + +bool MediacontentVideo::isChangedLongitude() +{ + return m_isChangedLongitude; +} + +vector<std::string> MediacontentVideo::getEditableAttr() const +{ + return m_editableAttrList; +} + +} +} diff --git a/wearable_src/Content/ContentVideo.h b/wearable_src/Content/ContentVideo.h new file mode 100755 index 0000000..e156c26 --- /dev/null +++ b/wearable_src/Content/ContentVideo.h @@ -0,0 +1,86 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _ABSTRACT_LAYER_CONTENT_VIDEO_H_ +#define _ABSTRACT_LAYER_CONTENT_VIDEO_H_ + +#include <ctime> +#include <string> +#include <vector> +#include <dpl/optional.h> +#include <dpl/shared_ptr.h> +#include "ContentMedia.h" + +using namespace std; + +namespace DeviceAPI { +namespace Content { + +class MediacontentVideo : public MediacontentMedia +{ + public: + + MediacontentVideo(); + virtual ~MediacontentVideo(); + + int getVideoDuration() const; + int getVideoWidth() const; + int getVideoHeight() const; + double getVideoLatitude() const; + double getVideoLongitude() const; + string getVideoAlbum() const; + vector<std::string> getVideoArtist() const; + void setVideoDuration(const int &value); + void setVideoWidth(const int &value); + void setVideoHeight(const int &value); + void setVideoLatitude(const double &value, bool isChanged=false); + void setVideoLongitude(const double &value, bool isChanged=false); + void setVideoAlbum(const string &value, bool isChanged=false); + void setVideoArtist(const vector<std::string> &value, bool isChanged=false); + void appendVideoArtist(const string value); + + bool isChangedArtists(); + bool isChangedAlbum(); + bool isChangedLatitude(); + bool isChangedLongitude(); + + virtual vector<std::string> getEditableAttr() const; + + private: + double m_videoLongitude; + double m_videoLatitude; + string m_videoAlbum; + vector<std::string> m_videoArtist; + int m_videoDuration; + int m_videoWidth; + int m_videoHeight; + bool m_isChangedArtists; + bool m_isChangedAlbum; + bool m_isChangedLatitude; + bool m_isChangedLongitude; + +}; + +typedef DPL::SharedPtr<MediacontentVideo> MediacontentVideoPtr; + + +} +} + + +#endif /* _ABSTRACT_LAYER_CONTENT_VIDEO_H_ */ + diff --git a/wearable_src/Content/IContentManager.cpp b/wearable_src/Content/IContentManager.cpp new file mode 100755 index 0000000..5d9a40f --- /dev/null +++ b/wearable_src/Content/IContentManager.cpp @@ -0,0 +1,319 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <Commons/StringUtils.h> +#include <Commons/ThreadPool.h> +#include "IContentManager.h" +#include "ContentListener.h" +#include "ContentImage.h" +#include "ContentMedia.h" +#include "ContentVideo.h" +#include "ContentAudio.h" +#include "ContentManager.h" +#include "ContentUtility.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Content { + + +IMediacontentManager::IMediacontentManager() : + WrtDeviceApis::Commons::EventRequestReceiver<IEventFindFolder>(WrtDeviceApis::Commons::ThreadEnum::MEDIACONTENT_THREAD), + WrtDeviceApis::Commons::EventRequestReceiver<IEventBrowseFolder>(WrtDeviceApis::Commons::ThreadEnum::MEDIACONTENT_THREAD), + WrtDeviceApis::Commons::EventRequestReceiver<IEventUpdateMedia>(WrtDeviceApis::Commons::ThreadEnum::MEDIACONTENT_THREAD), + WrtDeviceApis::Commons::EventRequestReceiver<IEventUpdateMediaItems>(WrtDeviceApis::Commons::ThreadEnum::MEDIACONTENT_THREAD) + +{ +} + +IMediacontentManager::~IMediacontentManager() +{ +} + +void IMediacontentManager::findFolder(IEventFindFolderPtr &ptr) +{ + WrtDeviceApis::Commons::EventRequestReceiver<IEventFindFolder>::PostRequest(ptr); +} + +void IMediacontentManager::updateMedia(IEventUpdateMediaPtr &ptr) +{ + WrtDeviceApis::Commons::EventRequestReceiver<IEventUpdateMedia>::PostRequest(ptr); +} + +void IMediacontentManager::browseFolder(IEventBrowseFolderPtr &ptr) +{ + WrtDeviceApis::Commons::EventRequestReceiver<IEventBrowseFolder>::PostRequest(ptr); +} + +void IMediacontentManager::updateMediaItems(IEventUpdateMediaItemsPtr &ptr) +{ + WrtDeviceApis::Commons::EventRequestReceiver<IEventUpdateMediaItems>::PostRequest(ptr); +} + + +struct scanCallbackData +{ + std::string path; + int result; + scanCompletedCallback callback; + void *user_data; +}; + +static gboolean _scan_file_completed_cb(void *user_data) +{ + + scanCallbackData *data = static_cast<scanCallbackData*>(user_data); + + if(data != NULL) + { + string path = data->path; + void* _user_data = data->user_data; + scanCompletedCallback _callback = data->callback; + + std::string err_msg; + + if( data->result == MEDIA_CONTENT_ERROR_NONE) + { + err_msg = ""; + } + else if( data->result == MEDIA_CONTENT_ERROR_OUT_OF_MEMORY) + { + err_msg = "scanning is failed by out of memory"; + } + else if( data->result == MEDIA_CONTENT_ERROR_INVALID_OPERATION) + { + err_msg = "scanning is failed by invalid operation"; + } + else if( data->result == MEDIA_CONTENT_ERROR_DB_FAILED) + { + err_msg = "scanning is failed because db operation is failed"; + } + else if( data->result == MEDIA_CONTENT_ERROR_DB_BUSY) + { + err_msg = "scanning is failed because db operation is failed"; + } + else + { + err_msg = "scanning is failed by unknown reason"; + } + _callback(err_msg, path, _user_data); + + delete data; + } + return false; +} + + +static void _scan_file_thread(void *user_data, Ecore_Thread *thread){ + scanCallbackData *data = static_cast<scanCallbackData*>(user_data); + data->result = media_content_scan_file(data->path.c_str()); + g_idle_add(_scan_file_completed_cb, data); +} + +bool IMediacontentManager::scanFile(scanCompletedCallback callback, std::string path, void* user_data) +{ + bool ret = false; + if( !path.empty() ) + { + scanCallbackData *data = new scanCallbackData(); + data->path = path; + data->callback = callback; + data->user_data = user_data; + + ecore_thread_run( _scan_file_thread, NULL, NULL, static_cast<void*>(data)); + ret = true; + + } + else + { + ThrowMsg(WrtDeviceApis::Commons::InvalidArgumentException, "URI is not available"); + } + return ret; +} + +static bool mediaItemCallback(media_info_h info, void* user_data) +{ + media_content_type_e type; + + if ( MEDIA_CONTENT_ERROR_NONE == media_info_get_media_type( info, &type) ) + { + if ( type == MEDIA_CONTENT_TYPE_IMAGE) + { + MediacontentManager::readImageFromMediaInfo(info, static_cast<MediacontentImage*>(user_data)); + } + else if ( type == MEDIA_CONTENT_TYPE_VIDEO) + { + MediacontentManager::readVideoFromMediaInfo(info, static_cast<MediacontentVideo*>(user_data)); + } + else if ( type == MEDIA_CONTENT_TYPE_MUSIC || type == MEDIA_CONTENT_TYPE_SOUND) + { + MediacontentManager::readMusicFromMediaInfo(info, static_cast<MediacontentAudio*>(user_data)); + } + else if( type == MEDIA_CONTENT_TYPE_OTHERS) + { + MediacontentManager::readCommonDataFromMediaInfo(info, static_cast<MediacontentMedia*>(user_data)); + } + + } + return false; +} + +static void content_notification_cb( + media_content_error_e error, + int pid, + media_content_db_update_item_type_e update_item, + media_content_db_update_type_e update_type, + media_content_type_e media_type, + char *uuid, + char *path, + char *mime_type, + void *user_data) +{ + + ContentListener *listener = static_cast<ContentListener*>(user_data); + std::string err_msg; + if( error == MEDIA_CONTENT_ERROR_NONE) + { + err_msg = ""; + if( update_item == MEDIA_ITEM_FILE) + { + string condition = "MEDIA_ID=\""; + condition += uuid; + condition += "\""; + + MediacontentMedia *p_content; + if(update_type == MEDIA_CONTENT_INSERT) + { + filter_h filter = NULL; + if ( MEDIA_CONTENT_ERROR_NONE == media_filter_create(&filter)) + { + media_filter_set_condition(filter, condition.c_str(), MEDIA_CONTENT_COLLATE_DEFAULT); + + if(media_type == MEDIA_CONTENT_TYPE_IMAGE) + { + p_content = new MediacontentImage(); + } + else if(media_type == MEDIA_CONTENT_TYPE_VIDEO) + { + p_content = new MediacontentVideo(); + } + else if(media_type == MEDIA_CONTENT_TYPE_SOUND || media_type == MEDIA_CONTENT_TYPE_MUSIC) + { + p_content = new MediacontentAudio(); + } + else + { + p_content = new MediacontentMedia(); + } + + if( MEDIA_CONTENT_ERROR_NONE == media_info_foreach_media_from_db(filter,mediaItemCallback,(void*)p_content)) + { + MediacontentMediaPtr result(p_content); + listener->oncontentadded(result); + } + media_filter_destroy(filter); + } + } + else if(update_type == MEDIA_CONTENT_UPDATE) + { + + filter_h filter = NULL; + if ( MEDIA_CONTENT_ERROR_NONE == media_filter_create(&filter)) + { + media_filter_set_condition(filter, condition.c_str(), MEDIA_CONTENT_COLLATE_DEFAULT); + + if(media_type == MEDIA_CONTENT_TYPE_IMAGE) + { + p_content = new MediacontentImage(); + } + else if(media_type == MEDIA_CONTENT_TYPE_VIDEO) + { + p_content = new MediacontentVideo(); + } + else if(media_type == MEDIA_CONTENT_TYPE_SOUND || media_type == MEDIA_CONTENT_TYPE_MUSIC) + { + p_content = new MediacontentAudio(); + } + else + { + p_content = new MediacontentMedia(); + } + + if( MEDIA_CONTENT_ERROR_NONE == media_info_foreach_media_from_db(filter,mediaItemCallback,(void*)p_content)) + { + MediacontentMediaPtr result(p_content); + listener->oncontentupdated(result); + } + media_filter_destroy(filter); + } + + } + else if(update_type == MEDIA_CONTENT_DELETE) + { + listener->oncontentremoved(uuid); + } + } + } + else if( error == MEDIA_CONTENT_ERROR_OUT_OF_MEMORY) + { + err_msg = "scanning is failed by out of memory"; + } + else if( error == MEDIA_CONTENT_ERROR_INVALID_OPERATION) + { + err_msg = "scanning is failed by invalid operation"; + } + else if( error == MEDIA_CONTENT_ERROR_DB_FAILED) + { + err_msg = "scanning is failed because db operation is failed"; + } + else if( error == MEDIA_CONTENT_ERROR_DB_BUSY) + { + err_msg = "scanning is failed because db operation is failed"; + } + else + { + err_msg = "scanning is failed by unknown reason"; + } +} + +bool IMediacontentManager::setListener( void* user_data) +{ + bool ret = false; + if(media_content_unset_db_updated_cb() == MEDIA_CONTENT_ERROR_NONE) + { + if(media_content_set_db_updated_cb(content_notification_cb,user_data) == MEDIA_CONTENT_ERROR_NONE) + { + ret = true; + } + } + return ret; +} + +bool IMediacontentManager::unsetListener() +{ + bool ret = false; + + if(media_content_unset_db_updated_cb() == MEDIA_CONTENT_ERROR_NONE) + { + ret = true; + } + return ret; +} + + +} +} diff --git a/wearable_src/Content/IContentManager.h b/wearable_src/Content/IContentManager.h new file mode 100755 index 0000000..f5fb059 --- /dev/null +++ b/wearable_src/Content/IContentManager.h @@ -0,0 +1,77 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _ABSTRACT_LAYER_ICONTENT_MANAGER_H_ +#define _ABSTRACT_LAYER_ICONTENT_MANAGER_H_ + +#include <media_content.h> +#include <dpl/shared_ptr.h> +#include <string> +#include <dpl/shared_ptr.h> +#include "IEventGetDirectories.h" +#include "IEventUpdate.h" +#include "IEventUpdateBatch.h" +#include "IEventFind.h" +#include "ContentMedia.h" +#include "ContentImage.h" + +namespace DeviceAPI { +namespace Content { + +typedef void (*scanCompletedCallback)(std::string errorMessage, std::string directory, void *user_data ); + +class IMediacontentManager : + public WrtDeviceApis::Commons::EventRequestReceiver<IEventFindFolder>, + public WrtDeviceApis::Commons::EventRequestReceiver<IEventBrowseFolder>, + public WrtDeviceApis::Commons::EventRequestReceiver<IEventUpdateMedia>, + public WrtDeviceApis::Commons::EventRequestReceiver<IEventUpdateMediaItems> +{ + public: + IMediacontentManager(); + virtual ~IMediacontentManager(); + + typedef enum + { + CONTENT_IMAGE, + CONTENT_VIDEO, + CONTENT_AUDIO + } MediacontentType; + + virtual void findFolder(IEventFindFolderPtr &ptr); + virtual void updateMedia(IEventUpdateMediaPtr &ptr); + virtual void browseFolder(IEventBrowseFolderPtr &ptr); + virtual void updateMediaItems(IEventUpdateMediaItemsPtr &ptr); + virtual bool scanFile(scanCompletedCallback callback, std::string path, void* user_data); + virtual bool setListener(void* user_data); + virtual bool unsetListener(); + + virtual void OnRequestReceived(const IEventFindFolderPtr &value) = 0; + virtual void OnRequestReceived(const IEventUpdateMediaPtr &value) = 0; + virtual void OnRequestReceived(const IEventBrowseFolderPtr &value) = 0; + virtual void OnRequestReceived(const IEventUpdateMediaItemsPtr &value) = 0; + +}; + +typedef DPL::SharedPtr<IMediacontentManager> IMediacontentManagerPtr; + + +} +} + + +#endif /* _ABSTRACT_LAYER_ICONTENT_MANAGER_H_ */ diff --git a/wearable_src/Content/IEventFind.h b/wearable_src/Content/IEventFind.h new file mode 100755 index 0000000..2f301dd --- /dev/null +++ b/wearable_src/Content/IEventFind.h @@ -0,0 +1,193 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _ABSTRACT_LAYER_IEVENT_BROWSE_FOLDER_H_ +#define _ABSTRACT_LAYER_IEVENT_BROWSE_FOLDER_H_ + +#include <vector> +#include <Commons/IEvent.h> +#include <IFilter.h> +#include <SortMode.h> + +#include <dpl/shared_ptr.h> +#include "ContentMedia.h" + +using namespace DeviceAPI::Tizen; + +namespace DeviceAPI { +namespace Content { + +class IEventBrowseFolder : public WrtDeviceApis::Commons::IEvent<IEventBrowseFolder> +{ + + public: + + IEventBrowseFolder() + { + m_result = false; + m_filterIsSet = false; + m_sortModesIsSet = false; + m_limitIsSet = false; + m_offsetIsSet = false; + m_folderIdIsSet = false; + + } + + + virtual ~IEventBrowseFolder(){} + + void addMedia(MediacontentMedia *value) + { + MediacontentMediaPtr mediaItem(value); + m_media.push_back(mediaItem); + } + + vector<MediacontentMediaPtr> getMedia() + { + return m_media; + } + + + void setLimit(const unsigned long value) + { + m_limitIsSet = true; + m_limit = value; + } + void setOffset(const unsigned long value) + { + m_offsetIsSet = true; + m_offset = value; + } + + void setFilter(const DeviceAPI::Tizen::FilterPtr &value) + { + m_filter = value; + m_filterIsSet = true; + } + + void setSortModes(const DeviceAPI::Tizen::SortModeArrayPtr &value) + { + m_sortModes = value; + m_sortModesIsSet = true; + } + + void setSortMode(const DeviceAPI::Tizen::SortModePtr &value) + { + m_sortMode = value; + m_sortModesIsSet = true; + } + + void setFolderID(const string &value) + { + m_folderId = value; + m_folderIdIsSet = true; + } + + string getFolderID() + { + return m_folderId; + } + + + void setResult(bool value) + { + m_result = value; + } + + bool getLimitIsSet() const + { + return m_limitIsSet; + } + + bool getOffsetIsSet() const + { + return m_offsetIsSet; + } + + bool getResult()const + { + return m_result; + } + + bool getFilterIsSet()const + { + return m_filterIsSet; + } + + bool getFolderIdIsSet()const + { + return m_folderIdIsSet; + } + + bool getSortModesIsSet()const + { + return m_sortModesIsSet; + } + + unsigned long getLimit() const + { + return m_limit; + } + + unsigned long getOffset() const + { + return m_offset; + } + + FilterPtr getFilter() const + { + return m_filter; + } + + SortModeArrayPtr getSortModes() const + { + return m_sortModes; + } + + SortModePtr getSortMode() const + { + return m_sortMode; + } + + private: + bool m_filterIsSet; + bool m_sortModesIsSet; + + bool m_result; //OUTPUT: operation result + bool m_limitIsSet; + bool m_offsetIsSet; + bool m_folderIdIsSet; + + unsigned long m_limit; + unsigned long m_offset; + FilterPtr m_filter; + SortModeArrayPtr m_sortModes; + SortModePtr m_sortMode; + + string m_folderId; + + vector<MediacontentMediaPtr> m_media; + +}; + +typedef DPL::SharedPtr<IEventBrowseFolder> IEventBrowseFolderPtr; + +} +} + +#endif /* _ABSTRACT_LAYER_IEVENT_BROWSE_FOLDER_H_ */ diff --git a/wearable_src/Content/IEventFindMedia.h b/wearable_src/Content/IEventFindMedia.h new file mode 100755 index 0000000..a6b3943 --- /dev/null +++ b/wearable_src/Content/IEventFindMedia.h @@ -0,0 +1,162 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _ABSTRACT_LAYER_IEVENT_FIND_MEDIA_H_ +#define _ABSTRACT_LAYER_IEVENT_FIND_MEDIA_H_ + +#include <vector> +#include <Commons/IEvent.h> +#include <IFilter.h> +#include <SortMode.h> + +#include <dpl/shared_ptr.h> +#include "ContentMedia.h" + +using namespace DeviceAPI::Tizen; + +namespace DeviceAPI { +namespace Content { + +class IEventFindMedia : public WrtDeviceApis::Commons::IEvent<IEventFindMedia> +{ + + public: + + IEventFindMedia() + { + m_result = false; + m_filterIsSet = false; + m_sortModesIsSet = false; + m_limitIsSet = false; + m_offsetIsSet = false; + + + } + + + virtual ~IEventFindMedia(){} + + void addMedia(MediacontentMedia *value) + { + MediacontentMediaPtr mediaItem(value); + m_media.push_back(mediaItem); + } + + vector<MediacontentMediaPtr> getMedia() + { + return m_media; + } + + + void setLimit(const unsigned long value) + { + m_limitIsSet = true; + m_limit = value; + } + void setOffset(const unsigned long value) + { + m_offsetIsSet = true; + m_offset = value; + } + + void setFilter(const DeviceAPI::Tizen::FilterPtr &value) + { + m_filter = value; + m_filterIsSet = true; + } + + void setSortModes(const DeviceAPI::Tizen::SortModeArrayPtr &value) + { + m_sortModes = value; + m_sortModesIsSet = true; + } + + void setResult(bool value) + { + m_result = value; + } + + bool getLimitIsSet() const + { + return m_limitIsSet; + } + + bool getOffsetIsSet() const + { + return m_offsetIsSet; + } + + bool getResult()const + { + return m_result; + } + + bool getFilterIsSet()const + { + return m_filterIsSet; + } + + bool getSortModesIsSet()const + { + return m_sortModesIsSet; + } + + unsigned long getLimit() const + { + return m_limit; + } + + unsigned long getOffset() const + { + return m_offset; + } + + FilterPtr getFilter() const + { + return m_filter; + } + + SortModeArrayPtr getSortModes() const + { + return m_sortModes; + } + + + private: + bool m_filterIsSet; + bool m_sortModesIsSet; + + bool m_result; //OUTPUT: operation result + bool m_limitIsSet; + bool m_offsetIsSet; + + unsigned long m_limit; + unsigned long m_offset; + FilterPtr m_filter; + SortModeArrayPtr m_sortModes; + + vector<MediacontentMediaPtr> m_media; + +}; + +typedef DPL::SharedPtr<IEventFindMedia> IEventFindMediaPtr; + +} +} + +#endif /* _ABSTRACT_LAYER_IEVENT_FIND_MEDIA_H_ */ diff --git a/wearable_src/Content/IEventGetDirectories.h b/wearable_src/Content/IEventGetDirectories.h new file mode 100755 index 0000000..bde8e2a --- /dev/null +++ b/wearable_src/Content/IEventGetDirectories.h @@ -0,0 +1,161 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _ABSTRACT_LAYER_IEVENT_FIND_FOLDER_H_ +#define _ABSTRACT_LAYER_IEVENT_FIND_FOLDER_H_ + +#include <vector> +#include <Commons/IEvent.h> +#include <dpl/shared_ptr.h> +#include <IFilter.h> +#include <SortMode.h> +#include "ContentFolder.h" + + +using namespace std; + +namespace DeviceAPI { +namespace Content { + +class IEventFindFolder : public WrtDeviceApis::Commons::IEvent<IEventFindFolder> +{ + public: + IEventFindFolder() + { + m_result = false; + m_filterIsSet = false; + m_sortModesIsSet = false; + m_limitIsSet = false; + m_offsetIsSet = false; + + } + ~IEventFindFolder(){} + + void addFolder(MediacontentFolderPtr value) + { + m_folder.push_back(value); + } + + void setResult(bool value) + { + m_result = value; + } + + vector<MediacontentFolderPtr> getFolder() + { + return m_folder; + } + + void setLimit(const unsigned long value) + { + m_limitIsSet = true; + m_limit = value; + } + void setOffset(const unsigned long value) + { + m_offsetIsSet = true; + m_offset = value; + } + + void setFilter(const DeviceAPI::Tizen::FilterPtr &value) + { + m_filter = value; + m_filterIsSet = true; + } + + void setSortModes(const DeviceAPI::Tizen::SortModeArrayPtr &value) + { + m_sortModes = value; + m_sortModesIsSet = true; + } + + bool getLimitIsSet() const + { + return m_limitIsSet; + } + + bool getOffsetIsSet() const + { + return m_offsetIsSet; + } + + bool getResult()const + { + return m_result; + } + + bool getFilterIsSet()const + { + return m_filterIsSet; + } + + bool getSortModesIsSet()const + { + return m_sortModesIsSet; + } + + unsigned long getLimit() const + { + return m_limit; + } + + unsigned long getOffset() const + { + return m_offset; + } + + DeviceAPI::Tizen::FilterPtr getFilter() const + { + return m_filter; + } + + DeviceAPI::Tizen::SortModeArrayPtr getSortModes() const + { + return m_sortModes; + } + + + + virtual void clearOnCancel(){;} + + + private: + bool m_filterIsSet; + bool m_sortModesIsSet; + + bool m_result; //OUTPUT: operation result + bool m_limitIsSet; + bool m_offsetIsSet; + + + unsigned long m_limit; + unsigned long m_offset; + DeviceAPI::Tizen::FilterPtr m_filter; + DeviceAPI::Tizen::SortModeArrayPtr m_sortModes; + vector<MediacontentFolderPtr> m_folder; //OUTPUT: result list + + + +}; + +typedef DPL::SharedPtr<IEventFindFolder> IEventFindFolderPtr; + +} +} + +#endif /* _ABSTRACT_LAYER_IEVENT_FIND_FOLDER_H_ */ diff --git a/wearable_src/Content/IEventUpdate.h b/wearable_src/Content/IEventUpdate.h new file mode 100755 index 0000000..5355d92 --- /dev/null +++ b/wearable_src/Content/IEventUpdate.h @@ -0,0 +1,71 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _ABSTRACT_LAYER_IEVENT_UPDATE_ITEM_H_ +#define _ABSTRACT_LAYER_IEVENT_UPDATE_ITEM_H_ + +#include <vector> +#include <Commons/IEvent.h> +#include <dpl/shared_ptr.h> +#include "ContentMedia.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Content { + +class IEventUpdateMedia : public WrtDeviceApis::Commons::IEvent<IEventUpdateMedia> +{ + + public: + IEventUpdateMedia():m_result(false), m_media(NULL) + { + } + ~IEventUpdateMedia(){} + + + void setMediaItem(MediacontentMediaPtr value) + { + m_media = value; + } + + MediacontentMediaPtr getMediaItem() + { + return m_media; + } + + + void setResult(bool value) + { + m_result = value; + } + bool getResult() const + { + return m_result; + } + + private: + bool m_result; + MediacontentMediaPtr m_media; //OUTPUT: result list +}; + +typedef DPL::SharedPtr<IEventUpdateMedia> IEventUpdateMediaPtr; + +} +} + +#endif /* _ABSTRACT_LAYER_IEVENT_UPDATE_ITEM_H_ */ diff --git a/wearable_src/Content/IEventUpdateBatch.h b/wearable_src/Content/IEventUpdateBatch.h new file mode 100755 index 0000000..0c9eb55 --- /dev/null +++ b/wearable_src/Content/IEventUpdateBatch.h @@ -0,0 +1,71 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _ABSTRACT_LAYER_IEVENT_UPDATE_ITEMS_H_ +#define _ABSTRACT_LAYER_IEVENT_UPDATE_ITEMS_H_ + +#include <vector> +#include <Commons/IEvent.h> +#include <dpl/shared_ptr.h> +#include "ContentMedia.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Content { + +class IEventUpdateMediaItems : public WrtDeviceApis::Commons::IEvent<IEventUpdateMediaItems> +{ + + public: + IEventUpdateMediaItems():m_result(false) + { + } + virtual ~IEventUpdateMediaItems(){} + + void setResult(bool value) + { + m_result = value; + } + bool getResult() const + { + return m_result; + } + + MediacontentMediaListPtr getMediaItems() const + { + return m_mediaList; + } + + void setMediaItems(MediacontentMediaListPtr value) + { + m_mediaList = value; + } + + + private: + bool m_result; + MediacontentMediaListPtr m_mediaList; +}; + +typedef DPL::SharedPtr<IEventUpdateMediaItems> IEventUpdateMediaItemsPtr; + +} +} + +#endif /* _ABSTRACT_LAYER_IEVENT_UPDATE_ITEMS_H_ */ diff --git a/wearable_src/Content/JSAudio.cpp b/wearable_src/Content/JSAudio.cpp new file mode 100755 index 0000000..b63be9b --- /dev/null +++ b/wearable_src/Content/JSAudio.cpp @@ -0,0 +1,609 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <CommonsJavaScript/PrivateObject.h> +#include <CommonsJavaScript/Converter.h> +#include <CommonsJavaScript/JSUtils.h> +#include <JSWebAPIErrorFactory.h> + +#include "JSAudio.h" +#include "JSAudioLyrics.h" +#include "ContentConverter.h" +#include "AudioLyricsUtil.h" +#include "ContentUtility.h" +#include <Logger.h> + +#define TIZEN_CONTENT_AUDIO_ATTRIBUTENAME "AudioContent" +#define TIZEN_CONTENT_AUDIO_ALBUM "album" +#define TIZEN_CONTENT_AUDIO_GENRE "genres" +#define TIZEN_CONTENT_AUDIO_ARTIST "artists" +#define TIZEN_CONTENT_AUDIO_COMPOSER "composers" +#define TIZEN_CONTENT_AUDIO_LYIRICS "lyrics" +#define TIZEN_CONTENT_AUDIO_COPYRIGHT "copyright" +#define TIZEN_CONTENT_AUDIO_BITRATE "bitrate" +#define TIZEN_CONTENT_AUDIO_TRACKNUM "trackNumber" +#define TIZEN_CONTENT_AUDIO_DURATION "duration" +#define TIZEN_CONTENT_AUDIO_SIZE "size" + +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace DeviceAPI { +namespace Content { + +JSClassDefinition JSAudio::m_classInfo = +{ + 0, + kJSClassAttributeNone, + TIZEN_CONTENT_AUDIO_ATTRIBUTENAME, + JSMedia::getClassRef(), + m_property, + NULL, // m_function, + initialize, + finalize, + NULL, //hasProperty, + NULL, //getProperty, + NULL, //setProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL //ConvertToType +}; + +JSStaticValue JSAudio::m_property[] = +{ + { TIZEN_CONTENT_AUDIO_ALBUM, getPropertyAlbum, NULL, kJSPropertyAttributeReadOnly}, + { TIZEN_CONTENT_AUDIO_ARTIST, getPropertyArtist, NULL, kJSPropertyAttributeReadOnly}, + { TIZEN_CONTENT_AUDIO_GENRE, getPropertyGenre, NULL, kJSPropertyAttributeReadOnly}, + { TIZEN_CONTENT_AUDIO_COMPOSER , getPropertyComposer, NULL, kJSPropertyAttributeReadOnly}, + { TIZEN_CONTENT_AUDIO_COPYRIGHT, getPropertyCopyright, NULL, kJSPropertyAttributeReadOnly}, + { TIZEN_CONTENT_AUDIO_LYIRICS, getPropertyLyrics, NULL, kJSPropertyAttributeReadOnly}, + { TIZEN_CONTENT_AUDIO_BITRATE, getPropertyBitrate, NULL, kJSPropertyAttributeReadOnly}, + { TIZEN_CONTENT_AUDIO_TRACKNUM, getPropertyTrackNum, NULL, kJSPropertyAttributeReadOnly}, + { TIZEN_CONTENT_AUDIO_DURATION, getPropertyDuration, NULL, kJSPropertyAttributeReadOnly}, + { TIZEN_CONTENT_AUDIO_SIZE, getPropertySize, NULL, kJSPropertyAttributeReadOnly}, + { 0, 0, 0, 0 } +}; + +JSClassRef JSAudio::m_jsClassRef = JSClassCreate(JSAudio::getClassInfo()); + +void JSAudio::initialize(JSContextRef context, JSObjectRef object) +{ + AudioPrivObject *priv = static_cast<AudioPrivObject*>( JSObjectGetPrivate( object ) ); + if (!priv) + { + MediacontentAudioPtr privateData(new MediacontentAudio()); + priv = new AudioPrivObject(context, privateData); + JSObjectSetPrivate(object, static_cast<void*>(priv)); + LoggerD("new Private Object is created" ); + } + else { + LoggerD("private object already exists"); + } +} + +void JSAudio::finalize(JSObjectRef object) +{ + AudioPrivObject *priv = static_cast<AudioPrivObject*>( JSObjectGetPrivate( object ) ) ; + if (priv != NULL) + { + delete (priv); + priv = NULL; + JSObjectSetPrivate(object, NULL); + } +} + +const JSClassRef JSAudio::getClassRef() +{ + if (!m_jsClassRef) + { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSAudio::getClassInfo() +{ + return &m_classInfo; +} + + +MediacontentAudioPtr JSAudio::getAudioObject(JSObjectRef object) +{ + AudioPrivObject *priv = static_cast<AudioPrivObject*>(JSObjectGetPrivate(object)); + if(!priv) + { + ThrowMsg(NullPointerException, "Private object is null"); + } + MediacontentAudioPtr result = priv->getObject(); + if (!result) + { + ThrowMsg(NullPointerException, "Private object is null"); + } + return result; +} + +JSValueRef JSAudio::getPropertyAlbum( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentAudioPtr audio = getAudioObject(object); + if(!audio->getAudioAlbum().empty()){ + return converter.toJSValueRef(audio->getAudioAlbum()); + } + } + Catch(Exception) + { + LoggerW("trying to get incorrect value"); + } + return JSValueMakeNull(context); +} + +JSValueRef JSAudio::getPropertyArtist( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentAudioPtr audio = getAudioObject(object); + if(audio->getAudioArtist().size() != 0){ + JSObjectRef jsResult = JSCreateArrayObject(context, 0, NULL); + if (NULL == jsResult){ + ThrowMsg(NullPointerException, "Could not create js array object"); + } + for( unsigned int i=0; i < audio->getAudioArtist().size(); i++){ + string artist = audio->getAudioArtist().at(i); + JSValueRef val = converter.toJSValueRef(artist); + if(!JSSetArrayElement(context, jsResult, i, val)){ + ThrowMsg(UnknownException, "Could not insert value into js array"); + } + } + return jsResult; + } + } + Catch(Exception) + { + LoggerW("trying to get incorrect value"); + } + return JSValueMakeNull(context); +} + + + +JSValueRef JSAudio::getPropertyGenre( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentAudioPtr audio = getAudioObject(object); + if(audio->getAudioGenre().size() != 0){ + JSObjectRef jsResult = JSCreateArrayObject(context, 0 , NULL); + if (NULL == jsResult) + { + ThrowMsg(NullPointerException, "Could not create js array object"); + } + + for( unsigned int i=0; i < audio->getAudioGenre().size(); i++){ + string genre = audio->getAudioGenre().at(i); + JSValueRef val = converter.toJSValueRef(genre); + if(!JSSetArrayElement(context, jsResult, i, val)){ + ThrowMsg(UnknownException, "Could not insert value into js array"); + } + } + return jsResult; + } + } + Catch(Exception) + { + LoggerW("trying to get incorrect value"); + } + return JSValueMakeNull(context); +} + + +JSValueRef JSAudio::getPropertyComposer( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentAudioPtr audio = getAudioObject(object); + if(audio->getAudioComposer().size() != 0){ + JSObjectRef jsResult = JSCreateArrayObject(context, 0, NULL); + if (NULL == jsResult){ + ThrowMsg(NullPointerException, "Could not create js array object"); + } + for( unsigned int i=0; i < audio->getAudioComposer().size(); i++){ + string composer = audio->getAudioComposer().at(i); + JSValueRef val = converter.toJSValueRef(composer); + if(!JSSetArrayElement(context, jsResult, i, val)){ + ThrowMsg(UnknownException, "Could not insert value into js array"); + } + } + return jsResult; + } + } + Catch(Exception) + { + LoggerW("trying to get incorrect value"); + } + return JSValueMakeNull(context); +} + +JSValueRef JSAudio::getPropertyCopyright( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentAudioPtr audio = getAudioObject(object); + if(!audio->getAudioCopyright().empty()){ + return converter.toJSValueRef(audio->getAudioCopyright()); + } + } + Catch(Exception) + { + LoggerW("trying to get incorrect value"); + } + return JSValueMakeNull(context); +} + +JSValueRef JSAudio::getPropertyLyrics( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + MediaConverterFactory::ConverterType converter = MediaConverterFactory::getConverter(context); + + AudioPrivObject *priv = static_cast<AudioPrivObject*>(JSObjectGetPrivate(object)); + if(!priv) + { + ThrowMsg(NullPointerException, "Private object is null"); + } + MediacontentAudioPtr audio = priv->getObject(); + if (!audio) + { + ThrowMsg(NullPointerException, "Private object is null"); + } + + JSContextRef globalContext = priv->getContext(); + + if ( CONTENT_LYRIC_UNKNOWN == audio->getLyricsState() || + CONTENT_LYRIC_EXISTENT == audio->getLyricsState() ) + { + + MediacontentLyricsPtr mediaContent; + + if ( audio->getLyricsState() == CONTENT_LYRIC_UNKNOWN ) + { + mediaContent = MediaLyricsUtilSingleton::Instance().fetchLyrics(ContentUtility::convertUriToPath(audio->getFilePath())); + if ( mediaContent ) + audio->setAudioLyrics(mediaContent); + else + audio->setAudioLyricNonExistent(); + } + else + { + mediaContent = audio->getAudioLyrics(); + } + + if (mediaContent && (audio->getLyricsState() != CONTENT_LYRIC_NON_EXISTENT)) + { + JSObjectRef jsobject; + jsobject = JSMediaLyrics::createJSObject(globalContext, mediaContent); + return jsobject; + } + else + { + audio->setAudioLyricNonExistent(); + } + } + + } + Catch(Exception) + { + LoggerW("trying to get incorrect value"); + } + + return JSValueMakeNull(context); +} + +JSValueRef JSAudio::getPropertyBitrate( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentAudioPtr audio = getAudioObject(object); + return converter.toJSValueRef(audio->getAudioBitrate()); + } + Catch(Exception) + { + LoggerW("trying to get incorrect value"); + } + return JSValueMakeNull(context); +} + +JSValueRef JSAudio::getPropertyTrackNum( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentAudioPtr audio = getAudioObject(object); + return converter.toJSValueRef(audio->getAudioTrackNum()); + } + Catch(Exception) + { + LoggerW("trying to get incorrect value"); + } + return JSValueMakeNull(context); +} + +JSValueRef JSAudio::getPropertyDuration( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentAudioPtr audio = getAudioObject(object); + return converter.toJSValueRef(audio->getAudioDuration()); + } + Catch(Exception) + { + LoggerW("trying to get incorrect value"); + } + return JSValueMakeNull(context); +} + +JSValueRef JSAudio::getPropertySize( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentAudioPtr audio = getAudioObject(object); + double audioSize = (double)audio->getAudioSize(); + return converter.toJSValueRef(audioSize); + } + Catch(Exception) + { + LoggerW("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSAudio::setPropertyAlbum( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + + MediacontentAudioPtr audio = getAudioObject(object); + string album = converter.toString(value); + audio->setAudioAlbum(album, true); + return true; + } + Catch(Exception) + { + LoggerW("trying to set incorrect value"); + DeviceAPI::Common::JSWebAPIErrorFactory::postException(context, exception, DeviceAPI::Common::JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR); + } + + return false; + +} + +bool JSAudio::setPropertyArtist( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentAudioPtr audio = getAudioObject(object); + + vector<std::string> artists; + if (!JSValueIsNull(context, value)) { + if (JSIsArrayValue(context, value)) + { + JSObjectRef jsObject = converter.toJSObjectRef(value); + + for (std::size_t i = 0; i < JSGetArrayLength(context, jsObject); ++i) { + JSValueRef element = JSGetArrayElement(context, jsObject, i); + artists.push_back(converter.toString(element)); + } + } + else + { + DeviceAPI::Common::JSWebAPIErrorFactory::postException(context, exception, DeviceAPI::Common::JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR); + return false; + } + } + else + { + artists.push_back(converter.toString(value)); + } + + audio->setAudioArtist(artists, true); + return true; + } + Catch(Exception) + { + LoggerW("trying to set incorrect value"); + return DeviceAPI::Common::JSWebAPIErrorFactory::postException(context, exception, DeviceAPI::Common::JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR); + } + + return false; +} + + +bool JSAudio::setPropertyComposer( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentAudioPtr audio = getAudioObject(object); + + vector<std::string> composers; + if (!JSValueIsNull(context, value) ) + { + if (JSIsArrayValue(context, value)) + { + JSObjectRef jsObject = converter.toJSObjectRef(value); + + for (std::size_t i = 0; i < JSGetArrayLength(context, jsObject); ++i) { + JSValueRef element = JSGetArrayElement(context, jsObject, i); + composers.push_back(converter.toString(element)); + } + } + } + else + { + composers.push_back(converter.toString(value)); + } + + audio->setAudioComposer(composers, true); + return true; + } + Catch(Exception) + { + return DeviceAPI::Common::JSWebAPIErrorFactory::postException(context, exception, DeviceAPI::Common::JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR); + } + + return false; +} + +bool JSAudio::setPropertyGenre( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentAudioPtr audio = getAudioObject(object); + + vector<std::string> genres; + if (!JSValueIsNull(context, value) ) + { + if (JSIsArrayValue(context, value)) + { + JSObjectRef jsObject = converter.toJSObjectRef(value); + + for (std::size_t i = 0; i < JSGetArrayLength(context, jsObject); ++i) { + JSValueRef element = JSGetArrayElement(context, jsObject, i); + genres.push_back(converter.toString(element)); + } + + } + } + else + { + genres.push_back(converter.toString(value)); + } + + audio->setAudioGenre(genres, true); + return true; + } + Catch(Exception) + { + LoggerW("trying to set incorrect value"); + return DeviceAPI::Common::JSWebAPIErrorFactory::postException(context, exception, DeviceAPI::Common::JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR); + } + + return false; +} + +bool JSAudio::setPropertyTrackNumber( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + + MediacontentAudioPtr audio = getAudioObject(object); + int trackNum = converter.toInt(value); + audio->setAudioTrackNum(trackNum, true); + return true; + } + Catch(Exception) + { + LoggerW("trying to set incorrect value"); + DeviceAPI::Common::JSWebAPIErrorFactory::postException(context, exception, DeviceAPI::Common::JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR); + } + + return false; +} + +} +} + diff --git a/wearable_src/Content/JSAudio.h b/wearable_src/Content/JSAudio.h new file mode 100755 index 0000000..e298fb0 --- /dev/null +++ b/wearable_src/Content/JSAudio.h @@ -0,0 +1,199 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _JS_TIZEN_AUDIO_H_ +#define _JS_TIZEN_AUDIO_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/PrivateObject.h> +#include "ContentMedia.h" +#include "ContentAudio.h" +#include "JSContent.h" + +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace DeviceAPI { +namespace Content { + +typedef PrivateObject<MediacontentAudioPtr, NoOwnership> AudioPrivObject; + +class JSAudio +{ +public: + + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + + static MediacontentAudioPtr getAudioObject(JSObjectRef object); + +private: + /** + * This member variable contains the values which has to be passed when + * the this class is embedded into JS Engine. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This member variable contains the initialization values for the + * properties of this class. The values are given according to the + * data structure JSPropertySpec. + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; + + /** + * 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); + + + + /** + * Getters and setters for properties + */ + + static JSValueRef getPropertyAlbum( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getPropertyArtist( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getPropertyGenre( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getPropertyComposer( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getPropertyLyrics( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getPropertyCopyright( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getPropertyBitrate( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getPropertyTrackNum( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getPropertyDuration( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + + static JSValueRef getPropertySize( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setPropertyPlayedTime( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static bool setPropertyPlayCount( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static bool setPropertyAlbum( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static bool setPropertyArtist( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static bool setPropertyComposer( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static bool setPropertyGenre( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static bool setPropertyTrackNumber( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + +}; + +} +} + + +#endif /* _JS_TIZEN_AUDIO_H_ */ diff --git a/wearable_src/Content/JSAudioLyrics.cpp b/wearable_src/Content/JSAudioLyrics.cpp new file mode 100755 index 0000000..f481698 --- /dev/null +++ b/wearable_src/Content/JSAudioLyrics.cpp @@ -0,0 +1,236 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <CommonsJavaScript/PrivateObject.h> +#include <CommonsJavaScript/Converter.h> +#include <CommonsJavaScript/JSUtils.h> +#include <CommonsJavaScript/JSDOMExceptionFactory.h> + +#include "JSAudioLyrics.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Content { + +#define TIZEN_CONTENT_MEDIA_LYRICS "AudioContentLyrics" +#define TIZEN_CONTENT_LYRICS_TYPE "type" +#define TIZEN_CONTENT_LYRICS_TIMESTAMP "timestamps" +#define TIZEN_CONTENT_LYRICS_TEXT "texts" + +JSClassDefinition JSMediaLyrics::m_classInfo = +{ + 0, + kJSClassAttributeNone, + TIZEN_CONTENT_MEDIA_LYRICS, + 0, + m_property, + NULL, // m_function, + initialize, + finalize, + NULL, //hasProperty, + NULL, //getProperty, + NULL, //setProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL //ConvertToType +}; + +JSStaticValue JSMediaLyrics::m_property[] = +{ + //EventProperties + { TIZEN_CONTENT_LYRICS_TYPE, getPropertyLyricsType, NULL, kJSPropertyAttributeReadOnly}, + { TIZEN_CONTENT_LYRICS_TIMESTAMP, getPropertyTimeStamps, NULL, kJSPropertyAttributeReadOnly}, + { TIZEN_CONTENT_LYRICS_TEXT, getPropertyTexts, NULL, kJSPropertyAttributeReadOnly}, + { 0, 0, 0, 0 } +}; + + +JSClassRef JSMediaLyrics::m_jsClassRef = JSClassCreate(JSMediaLyrics::getClassInfo()); + +void JSMediaLyrics::initialize(JSContextRef context, JSObjectRef object) +{ + LyricsPrivObject *priv = static_cast<LyricsPrivObject*>( JSObjectGetPrivate( object ) ); + if (!priv) + { + MediacontentLyricsPtr privateData(new MediacontentLyrics()); + priv = new LyricsPrivObject(context, privateData); + JSObjectSetPrivate(object, static_cast<void*>(priv)); + } + else + { + LoggerD("private object already exists"); + } +} + +void JSMediaLyrics::finalize(JSObjectRef object) +{ + LyricsPrivObject *priv = static_cast<LyricsPrivObject*>( JSObjectGetPrivate( object ) ) ; + delete priv; +} + +const JSClassRef JSMediaLyrics::getClassRef() +{ + if (!m_jsClassRef) + { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSMediaLyrics::getClassInfo() +{ + return &m_classInfo; +} + +MediacontentLyricsPtr JSMediaLyrics::getLyricsObject(JSObjectRef object) +{ + LyricsPrivObject *priv = static_cast<LyricsPrivObject*>(JSObjectGetPrivate(object)); + if(!priv) + { + ThrowMsg(NullPointerException, "Private object is null"); + } + MediacontentLyricsPtr result = priv->getObject(); + if (!result) + { + ThrowMsg(NullPointerException, "Private object is null"); + } + return result; +} + + +JSValueRef JSMediaLyrics::getPropertyLyricsType( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentLyricsPtr lyrics = getLyricsObject(object); + + return converter.toJSValueRef(lyrics->getMediaLyricsType()); + } + Catch(Exception) + { + LoggerW("trying to get incorrect value"); + } + + return JSValueMakeUndefined(context); + +} + +JSValueRef JSMediaLyrics::getPropertyTimeStamps( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentLyricsPtr lyrics = getLyricsObject(object); + + if ( 0 == (lyrics->getMediaLyricsType()).compare("SYNCHRONIZED") ) + { + + JSObjectRef jsResult = JSCreateArrayObject(context, 0, NULL); + vector<unsigned long> timeStamps = lyrics->getMediaLyricsTimeStamps(); + if(timeStamps.size() > 0) + { + if (NULL == jsResult) + { + ThrowMsg(NullPointerException, "Could not create js array object"); + } + for(unsigned int i=0; i<timeStamps.size(); i++) + { + JSValueRef val = converter.toJSValueRef(timeStamps.at(i)); + if(!JSSetArrayElement(context, jsResult, i, val)) + { + ThrowMsg(UnknownException, "Could not insert value into js array"); + } + } + return jsResult; + } + } + } + Catch(Exception) + { + LoggerW("trying to get incorrect value"); + } + + return JSValueMakeUndefined(context); + +} + +JSValueRef JSMediaLyrics::getPropertyTexts( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentLyricsPtr lyrics = getLyricsObject(object); + JSObjectRef jsResult = JSCreateArrayObject(context, 0, NULL); + vector<string> texts = lyrics->getMediaLyricsTexts(); + if(texts.size() >0) + { + if (NULL == jsResult) + { + ThrowMsg(NullPointerException, "Could not create js array object"); + } + for(unsigned int i=0; i<texts.size(); i++) + { + JSValueRef val = converter.toJSValueRef(texts.at(i)); + if(!JSSetArrayElement(context, jsResult, i, val)) + { + ThrowMsg(UnknownException, "Could not insert value into js array"); + } + } + } + return jsResult; + } + Catch(Exception) + { + LoggerW("trying to get incorrect value"); + } + + return JSValueMakeUndefined(context); + +} + +JSObjectRef JSMediaLyrics::createJSObject(JSContextRef context, + const MediacontentLyricsPtr mediaContent) +{ + LyricsPrivObject *priv = new LyricsPrivObject(context, mediaContent); + JSObjectRef jsObjectRef = JSObjectMake(context, getClassRef(), static_cast<void*>(priv)); + if (NULL == jsObjectRef) { + LoggerE("object creation error"); + return NULL; + } + return jsObjectRef; +} + + +} +} + diff --git a/wearable_src/Content/JSAudioLyrics.h b/wearable_src/Content/JSAudioLyrics.h new file mode 100755 index 0000000..f1fe7b6 --- /dev/null +++ b/wearable_src/Content/JSAudioLyrics.h @@ -0,0 +1,111 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _JS_TIZEN_MEDIA_LYRICS_H_ +#define _JS_TIZEN_MEDIA_LYRICS_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/PrivateObject.h> +#include "AudioLyrics.h" + + +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace DeviceAPI { +namespace Content { + +typedef PrivateObject<MediacontentLyricsPtr, NoOwnership> LyricsPrivObject; + +class JSMediaLyrics +{ + public: + + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + + static MediacontentLyricsPtr getLyricsObject(JSObjectRef object); + + static JSObjectRef createJSObject(JSContextRef context, + const MediacontentLyricsPtr mediacontentLyrics); + + + private: + /** + * This member variable contains the values which has to be passed when + * the this class is embedded into JS Engine. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This member variable contains the initialization values for the + * properties of this class. The values are given according to the + * data structure JSPropertySpec. + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; + + /** + * 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); + + + + /** + * Getters and setters for properties + */ + + static JSValueRef getPropertyLyricsType( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getPropertyTimeStamps( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getPropertyTexts( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + + +}; + +} +} + +#endif /* _JS_TIZEN_MEDIA_LYRICS_H_ */ diff --git a/wearable_src/Content/JSContent.cpp b/wearable_src/Content/JSContent.cpp new file mode 100755 index 0000000..35cf614 --- /dev/null +++ b/wearable_src/Content/JSContent.cpp @@ -0,0 +1,527 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <CommonsJavaScript/PrivateObject.h> +#include <CommonsJavaScript/Converter.h> +#include <CommonsJavaScript/JSUtils.h> +#include <JSWebAPIErrorFactory.h> +#include "JSContent.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Content { + +#define TIZEN_CONTENT_MEDIA_ATTRIBUTENAME "Content" +#define TIZEN_CONTENT_MEDIA_UID "id" +#define TIZEN_CONTENT_MEDIA_TYPE "type" +#define TIZEN_CONTENT_MEDIA_MIME_TYPE "mimeType" +#define TIZEN_CONTENT_MEDIA_NAME "name" +#define TIZEN_CONTENT_MEDIA_TITLE "title" +#define TIZEN_CONTENT_MEDIA_FILE_URL "contentURI" +#define TIZEN_CONTENT_MEDIA_THUMBNAILPATH "thumbnailURIs" +#define TIZEN_CONTENT_MEDIA_RELEASEDDATE "releaseDate" +#define TIZEN_CONTENT_MEDIA_MODIFIEDDATE "modifiedDate" +#define TIZEN_CONTENT_MEDIA_DESCRIPTION "description" +#define TIZEN_CONTENT_MEDIA_RATING "rating" +#define TIZEN_CONTENT_MEDIA_SIZE "size" +#define TIZEN_CONTENT_MEDIA_EDIABLEATTR "editableAttributes" + + +JSClassDefinition JSMedia::m_classInfo = +{ + 0, + kJSClassAttributeNone, + TIZEN_CONTENT_MEDIA_ATTRIBUTENAME, + 0, + m_property, + NULL, // m_function, + initialize, + finalize, + NULL, //hasProperty, + NULL, //getProperty, + NULL, //setProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL //ConvertToType +}; + + +JSStaticValue JSMedia::m_property[] = +{ + //EventProperties + { TIZEN_CONTENT_MEDIA_UID, getPropertyId, NULL, kJSPropertyAttributeReadOnly}, + { TIZEN_CONTENT_MEDIA_TYPE, getPropertyType , NULL, kJSPropertyAttributeReadOnly}, + { TIZEN_CONTENT_MEDIA_MIME_TYPE, getPropertyMimeType , NULL, kJSPropertyAttributeReadOnly}, + { TIZEN_CONTENT_MEDIA_NAME, getPropertyDisplayName, setPropertyDisplayName, kJSPropertyAttributeNone}, + { TIZEN_CONTENT_MEDIA_TITLE, getPropertyTitle, NULL, kJSPropertyAttributeReadOnly}, + { TIZEN_CONTENT_MEDIA_FILE_URL, getPropertyFilePath, NULL, kJSPropertyAttributeReadOnly}, + { TIZEN_CONTENT_MEDIA_THUMBNAILPATH, getPropertyThumbnailPath, NULL, kJSPropertyAttributeReadOnly}, + { TIZEN_CONTENT_MEDIA_RELEASEDDATE, getPropertyReleasedDate, NULL, kJSPropertyAttributeReadOnly}, + { TIZEN_CONTENT_MEDIA_MODIFIEDDATE, getPropertyModifiedDate, NULL, kJSPropertyAttributeReadOnly}, + { TIZEN_CONTENT_MEDIA_DESCRIPTION, getPropertyDescription, setPropertyDescription, kJSPropertyAttributeNone}, + { TIZEN_CONTENT_MEDIA_SIZE, getPropertySize, NULL, kJSPropertyAttributeReadOnly}, + { TIZEN_CONTENT_MEDIA_EDIABLEATTR, getPropertyEditableAttr, NULL, kJSPropertyAttributeReadOnly}, + { TIZEN_CONTENT_MEDIA_RATING, getPropertyRating, setPropertyRating, kJSPropertyAttributeNone}, + { 0, 0, 0, 0 } +}; + + +JSClassRef JSMedia::m_jsClassRef = JSClassCreate(JSMedia::getClassInfo()); + +void JSMedia::initialize(JSContextRef context, JSObjectRef object) +{ + MediaPrivObject *priv = static_cast<MediaPrivObject*>( JSObjectGetPrivate( object ) ); + if (!priv) + { + MediacontentMediaPtr privateData(new MediacontentMedia()); + priv = new MediaPrivObject(context, privateData); + JSObjectSetPrivate(object, static_cast<void*>(priv)); + } + else + { + LoggerD("private object already exists"); + } +} + +void JSMedia::finalize(JSObjectRef object) +{ + MediaPrivObject *priv = static_cast<MediaPrivObject*>( JSObjectGetPrivate( object ) ) ; + if (priv != NULL) + { + delete (priv); + priv = NULL; + JSObjectSetPrivate(object, NULL); + } +} + +const JSClassRef JSMedia::getClassRef() +{ + if (!m_jsClassRef) + { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSMedia::getClassInfo() +{ + return &m_classInfo; +} + +MediacontentMediaPtr JSMedia::getMediaObject(JSObjectRef object) +{ + MediaPrivObject *priv = static_cast<MediaPrivObject*>(JSObjectGetPrivate(object)); + if(!priv) + { + ThrowMsg(NullPointerException, "Private object is null"); + } + MediacontentMediaPtr result = priv->getObject(); + if (!result) + { + ThrowMsg(NullPointerException, "Private object is null"); + } + return result; +} + +JSValueRef JSMedia::getPropertyId( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentMediaPtr media = getMediaObject(object); + return converter.toJSValueRef(media->getMediaUUID()); + } + Catch(Exception) + { + LoggerW("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); + +} + +JSValueRef JSMedia::getPropertyMimeType( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentMediaPtr media = getMediaObject(object); + return converter.toJSValueRef(media->getMimeType()); + } + Catch(Exception) + { + LoggerW("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); + +} + + +JSValueRef JSMedia::getPropertyDisplayName( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentMediaPtr media = getMediaObject(object); + return converter.toJSValueRef(media->getDisplayName()); + } + Catch(Exception) + { + LoggerW("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSMedia::getPropertyTitle( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentMediaPtr media = getMediaObject(object); + return converter.toJSValueRef(media->getTitle()); + } + Catch(Exception) + { + LoggerW("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + + +JSValueRef JSMedia::getPropertyFilePath( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentMediaPtr media = getMediaObject(object); + return converter.toJSValueRef(media->getFilePath()); + } + Catch(Exception) + { + LoggerW("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + + +JSValueRef JSMedia::getPropertyThumbnailPath( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentMediaPtr media = getMediaObject(object); + JSObjectRef jsResult = JSCreateArrayObject(context, 0, NULL); + if (NULL == jsResult){ + ThrowMsg(NullPointerException, "Could not create js array object"); + } + + if(!(media->getThumbnailPath().empty())){ + JSValueRef val = converter.toJSValueRef(media->getThumbnailPath()); + if(!JSSetArrayElement(context, jsResult, 0, val)){ + ThrowMsg(UnknownException, "Could not insert value into js array"); + } + return jsResult; + } + } + Catch(Exception) + { + LoggerW("trying to get incorrect value"); + } + return JSValueMakeNull(context); +} + +JSValueRef JSMedia::getPropertyDescription( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentMediaPtr media = getMediaObject(object); +// if(!(media->getDescription().empty())) + { + return converter.toJSValueRef(media->getDescription()); + } + } + Catch(Exception) + { + LoggerW("trying to get incorrect value"); + } + return JSValueMakeNull(context); +} + + +JSValueRef JSMedia::getPropertyModifiedDate( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentMediaPtr media = getMediaObject(object); + if(media->getModifiedDate() != NULL) + { + return converter.toJSValueRef(*(media->getModifiedDate())); + } + } + Catch(Exception) + { + LoggerW("trying to get incorrect value"); + } + return JSValueMakeNull(context); +} + +JSValueRef JSMedia::getPropertyReleasedDate( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentMediaPtr media = getMediaObject(object); + if(media->getReleasedDate() != NULL) + { + return converter.toJSValueRef(*(media->getReleasedDate())); + } + } + Catch(Exception) + { + LoggerW("trying to get incorrect value"); + } + return JSValueMakeNull(context); + +} + + +JSValueRef JSMedia::getPropertyRating( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentMediaPtr objMedia = getMediaObject(object); + return converter.toJSValueRef(objMedia->getRating()); + } + Catch(Exception) + { + LoggerW("trying to get incorrect value"); + } + return JSValueMakeNull(context); +} + +JSValueRef JSMedia::getPropertyType( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentMediaPtr media = getMediaObject(object); + return converter.toJSValueRef(media->getMediaType()); + } + Catch(Exception) + { + LoggerW("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + + +JSValueRef JSMedia::getPropertySize( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentMediaPtr media = getMediaObject(object); + double var = (double)media->getSize(); + return converter.toJSValueRef(var); + } + Catch(Exception) + { + LoggerW("trying to get incorrect value"); + } + + return JSValueMakeNull(context); +} + + +JSValueRef JSMedia::getPropertyEditableAttr( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentMediaPtr media = getMediaObject(object); + vector<std::string> editableAttrList = media->getEditableAttr(); + JSObjectRef jsResult = JSCreateArrayObject(context, 0, NULL); + + if (NULL == jsResult) + { + ThrowMsg(NullPointerException, "Could not create js array object"); + } + for(unsigned int i=0; i<editableAttrList.size(); i++) + { + JSValueRef val = converter.toJSValueRef(editableAttrList.at(i)); + if(!JSSetArrayElement(context, jsResult, i, val)) + { + ThrowMsg(UnknownException, "Could not insert value into js array"); + } + } + return jsResult; + } + Catch(Exception) + { + LoggerW("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); + +} + + +bool JSMedia::setPropertyRating( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentMediaPtr objMedia = getMediaObject(object); + int rating = converter.toInt(value); + + if(rating < 0 || rating > 10) + { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } + if ( objMedia->getRating() != rating) + { + objMedia->setRating(rating, true); + } + return true; + } + Catch(Exception) + { + LoggerW("trying to set incorrect value"); + } + + return false; + +} + +bool JSMedia::setPropertyDisplayName( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentMediaPtr objMedia = getMediaObject(object); + string displayName = converter.toString(value); + + if ((objMedia->getDisplayName()).compare(displayName) != 0) + { + objMedia->setDisplayName(displayName, true); + } + + return true; + } + Catch(Exception) + { + LoggerW("trying to set incorrect value"); + } + + return false; +} + +bool JSMedia::setPropertyDescription( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentMediaPtr objMedia = getMediaObject(object); + string description = converter.toString(value); + + if ( (objMedia->getDescription()).compare(description) != 0 ) + { + objMedia->setDescription(description, true); + } + + return true; + } + Catch(Exception) + { + LoggerW("trying to set incorrect value"); + } + return false; +} + +} +} diff --git a/wearable_src/Content/JSContent.h b/wearable_src/Content/JSContent.h new file mode 100755 index 0000000..9f29a6b --- /dev/null +++ b/wearable_src/Content/JSContent.h @@ -0,0 +1,188 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _JS_TIZEN_MEDIA_H_ +#define _JS_TIZEN_MEDIA_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/PrivateObject.h> +#include "ContentMedia.h" + + +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace DeviceAPI { +namespace Content { + +typedef PrivateObject<MediacontentMediaPtr, NoOwnership> MediaPrivObject; + +class JSMedia +{ + public: + + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + + static MediacontentMediaPtr getMediaObject(JSObjectRef object); + + private: + /** + * This member variable contains the values which has to be passed when + * the this class is embedded into JS Engine. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This member variable contains the initialization values for the + * properties of this class. The values are given according to the + * data structure JSPropertySpec. + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; + + /** + * 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); + + + + /** + * Getters and setters for properties + */ + static JSValueRef getPropertyId( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getPropertyType( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getPropertyMimeType( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getPropertyDisplayName( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getPropertyFilePath( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getPropertyTitle( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getPropertyDescription( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getPropertyThumbnailPath( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getPropertyReleasedDate( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getPropertyModifiedDate( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getPropertyRating( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getPropertySize( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + + static JSValueRef getPropertyEditableAttr( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setPropertyRating( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static bool setPropertyDisplayName( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static bool setPropertyDescription( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + +}; + +} +} + + +#endif /* _JS_TIZEN_MEDIA_H_ */ diff --git a/wearable_src/Content/JSContentManager.cpp b/wearable_src/Content/JSContentManager.cpp new file mode 100755 index 0000000..a5d864b --- /dev/null +++ b/wearable_src/Content/JSContentManager.cpp @@ -0,0 +1,816 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <cassert> +#include <memory> +#include <CommonsJavaScript/Utils.h> +#include <CommonsJavaScript/Validator.h> +#include <CommonsJavaScript/Converter.h> +#include <CommonsJavaScript/JSCallbackManager.h> +#include <CommonsJavaScript/JSUtils.h> +#include <CommonsJavaScript/JSPendingOperation.h> +#include <CommonsJavaScript/PrivateObject.h> +#include <CommonsJavaScript/ScopedJSStringRef.h> +#include <SecurityExceptions.h> +#include <CallbackUserData.h> +#include <MultiCallbackUserData.h> +#include <GlobalContextManager.h> +#include <FilterConverter.h> +#include <JSWebAPIErrorFactory.h> +#include <ArgumentValidator.h> +#include <TimeTracer.h> + +#include "JSUtil.h" +#include "ContentFactory.h" +#include "ContentController.h" +#include "JSContentManager.h" +#include "JSContent.h" +#include "JSImage.h" +#include "JSVideo.h" +#include "JSAudio.h" +#include "ContentConverter.h" +#include "plugin_config.h" +#include "ContentAsyncCallbackManager.h" +#include "ContentListener.h" +#include "ContentVideo.h" +#include "ContentImage.h" +#include "ContentFilterConverter.h" +#include "ContentUtility.h" +#include <Logger.h> + +using namespace DeviceAPI::Common; +using namespace DeviceAPI::Tizen; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +#define TIZEN_CONTENT_MANAGER_ATTRIBUTENAME "content" + +namespace DeviceAPI { +namespace Content { + +JSStaticValue JSMediacontentManager::m_property[] = +{ + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSMediacontentManager::m_function[] = +{ + { CONTENT_FUNCTION_API_FIND_ITEMS, findItems, kJSPropertyAttributeNone }, + { CONTENT_FUNCTION_API_GET_FOLDERS, getFolders, kJSPropertyAttributeNone }, + { CONTENT_FUNCTION_API_UPDATE_ITEM, updateItem, kJSPropertyAttributeNone }, + { CONTENT_FUNCTION_API_UPDATE_ITEMS_BATCH, updateItemsBatch, kJSPropertyAttributeNone }, + { CONTENT_FUNCTION_API_SCAN_FILE, scanFile, kJSPropertyAttributeNone }, + { CONTENT_FUNCTION_API_SET_CHANGE_LISTENER, setChangeListener, kJSPropertyAttributeNone }, + { CONTENT_FUNCTION_API_UNSET_CHANGE_LISTENER, unsetChangeListener,kJSPropertyAttributeNone}, + { 0, 0, 0 } +}; + + +JSClassRef JSMediacontentManager::m_jsClassRef = NULL; + +JSClassDefinition JSMediacontentManager::m_classInfo = +{ + 0, + kJSClassAttributeNone, + TIZEN_CONTENT_MANAGER_ATTRIBUTENAME, + 0, + m_property, + m_function, + initialize, + finalize, + NULL, //hasProperty, + NULL, //getProperty, + NULL, //setProperty, + NULL, //deleteProperty, + NULL, //getPropertyNames, + NULL, //callAsFunction, + NULL, //callAsConstructor, + NULL, + NULL, //convertToType +}; + +JSValueRef JSMediacontentManager::getFolders( + JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception ) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + + MediacontentManagerPrivObject *privateObject; + privateObject = static_cast<MediacontentManagerPrivObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + DeviceAPI::Common::UnknownException err("Content's private object is NULL."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + + JSContextRef globalContext = GlobalContextManager::getInstance()->getGlobalContext(context); + + JSCallbackManagerPtr cbm(NULL); + cbm = JSCallbackManager::createObject(globalContext); + + try{ + ArgumentValidator argValidator(context, argumentCount, arguments); + JSObjectRef successCallbackObj = argValidator.toFunction(0); + if(successCallbackObj){ + cbm->setOnSuccess(successCallbackObj); + } + else{ + throw TypeMismatchException("SuccessCallback type mismatched."); + } + + JSObjectRef errorCallbackObj = argValidator.toFunction(1,true); + if(errorCallbackObj){ + cbm->setOnError(errorCallbackObj); + } + }catch(const BasePlatformException &err){ + return JSWebAPIErrorFactory::postException(context,exception,err); + } + catch(...){ + DeviceAPI::Common::UnknownException err("Unknown Error in ContentManager.getDirectories()."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + + Try + { + IMediacontentManagerPtr contentMgr = privateObject->getObject(); + + IEventFindFolderPtr dplEvent(new IEventFindFolder()); + dplEvent->setPrivateData( DPL::StaticPointerCast<IEventPrivateData> (cbm)); + dplEvent->setForAsynchronousCall(&MediacontentManagerController::getInstance()); + + contentMgr->findFolder(dplEvent); + + MediaContentAsyncCallbackManagerSingleton::Instance().registerCallbackManager(cbm, globalContext); + } + Catch(WrtDeviceApis::Commons::UnsupportedException) + { + LoggerW("Exception: "<<_rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_SUPPORTED_ERROR, _rethrown_exception.GetMessage()); + } + Catch(WrtDeviceApis::Commons::InvalidArgumentException) + { + LoggerW("Exception: "<<_rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, _rethrown_exception.GetMessage()); + } + Catch(WrtDeviceApis::Commons::ConversionException) + { + LoggerW("Exception: "<<_rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, _rethrown_exception.GetMessage()); + } + Catch(WrtDeviceApis::Commons::NotFoundException) + { + LoggerW("Exception: "<<_rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_FOUND_ERROR, _rethrown_exception.GetMessage()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LoggerW("Exception: "<<_rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, _rethrown_exception.GetMessage()); + } + + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); + +} + + + +JSValueRef JSMediacontentManager::findItems( + JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception ) +{ + + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + + MediacontentManagerPrivObject *privateObject; + privateObject = static_cast<MediacontentManagerPrivObject*>(JSObjectGetPrivate(thisObject)); + if(!privateObject) { + DeviceAPI::Common::UnknownException err("Content's private object is NULL."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + + AceSecurityStatus status = CONTENT_CHECK_ACCESS(CONTENT_FUNCTION_API_FIND_ITEMS); + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + JSContextRef globalContext = GlobalContextManager::getInstance()->getGlobalContext(context); + + JSCallbackManagerPtr cbm(NULL); + MediaContentFilterConverterFactory::ConverterType fConverter = MediaContentFilterConverterFactory::getConverter(context); + MediaConverterFactory::ConverterType converter = MediaConverterFactory::getConverter(context); + + cbm = JSCallbackManager::createObject(globalContext); + + string folderId; + Tizen::FilterPtr filter; + Tizen::SortModePtr sortPtr; + JSObjectRef filterObj; + JSObjectRef sortModeObj; + IEventBrowseFolderPtr dplEvent(new IEventBrowseFolder()); + try{ + ArgumentValidator argValidator(context, argumentCount, arguments); + JSObjectRef successCallbackObj = argValidator.toFunction(0); + if(successCallbackObj){ + cbm->setOnSuccess(successCallbackObj); + } + else{ + throw TypeMismatchException("SuccessCallback type mismatched."); + } + + JSObjectRef errorCallbackObj = argValidator.toFunction(1,true); + if(errorCallbackObj){ + cbm->setOnError(errorCallbackObj); + } + + folderId = argValidator.toString(2, true); + if(!folderId.empty()){ + if(folderId != "null" ){ + dplEvent->setFolderID(folderId); + } + else if(folderId == "undefined"){ + throw InvalidValuesException("folderId is not valid."); + } + } + + //filter + filterObj = argValidator.toObject(3,true); + + //sortMode + sortModeObj= argValidator.toObject(4,true); + + // count + if(argumentCount >= 6){ + if(!JSValueIsNull(context, arguments[5])){ + long count = argValidator.toLong(5, true, 0); + if( count >= 0L ){ + dplEvent->setLimit(count); + } + else{ + throw InvalidValuesException( "count should be positive."); + } + } + } + if(argumentCount >= 7){ + // offset + long offset = argValidator.toLong(6, true); + if( offset >= 0L ){ + dplEvent->setOffset(offset); + } + else{ + throw InvalidValuesException("offset should be positive."); + } + } + }catch(const BasePlatformException &err){ + return JSWebAPIErrorFactory::postException(context,exception,err); + } + catch(...){ + DeviceAPI::Common::UnknownException err("Unknown Error in find()."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + + Try + { + if(filterObj){ + dplEvent->setFilter(fConverter->toFilter(filterObj)); + } + if(sortModeObj){ + dplEvent->setSortMode(fConverter->toSortMode(sortModeObj)); + } + IMediacontentManagerPtr contentMgr = privateObject->getObject(); + + dplEvent->setPrivateData( DPL::StaticPointerCast<IEventPrivateData> (cbm)); + dplEvent->setForAsynchronousCall(&MediacontentManagerController::getInstance()); + contentMgr->browseFolder(dplEvent); + MediaContentAsyncCallbackManagerSingleton::Instance().registerCallbackManager(cbm, globalContext); + } + Catch(WrtDeviceApis::Commons::UnsupportedException) + { + LoggerW("Exception: "<<_rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_SUPPORTED_ERROR, _rethrown_exception.GetMessage()); + } + Catch(WrtDeviceApis::Commons::InvalidArgumentException) + { + LoggerW("Exception: "<<_rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, _rethrown_exception.GetMessage()); + } + Catch(WrtDeviceApis::Commons::ConversionException) + { + LoggerW("Exception: "<<_rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, _rethrown_exception.GetMessage()); + } + Catch(WrtDeviceApis::Commons::NotFoundException) + { + LoggerW("Exception: "<<_rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_FOUND_ERROR, _rethrown_exception.GetMessage()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LoggerW("Exception: "<<_rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, _rethrown_exception.GetMessage()); + } + + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); +} + + + +JSValueRef JSMediacontentManager::updateItemsBatch(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + MediacontentManagerPrivObject *privateObject; + privateObject = static_cast<MediacontentManagerPrivObject*>(JSObjectGetPrivate(thisObject)); + if(!privateObject) { + DeviceAPI::Common::UnknownException err("Content's private object is NULL."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + + JSContextRef globalContext = GlobalContextManager::getInstance()->getGlobalContext(context); + AceSecurityStatus status = CONTENT_CHECK_ACCESS(CONTENT_FUNCTION_API_UPDATE_ITEMS_BATCH); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + JSCallbackManagerPtr cbm(NULL); + MediaConverterFactory::ConverterType converter = MediaConverterFactory::getConverter(context); + + cbm = JSCallbackManager::createObject(globalContext); + + MediacontentMediaListPtr contents; + try{ + ArgumentValidator argValidator(context, argumentCount, arguments); + + if((argumentCount >= 1) && (JSIsArrayValue(context, arguments[0]))){ + contents = converter->toVectorOfMediaItem(arguments[0]); + if(!contents) + { + throw TypeMismatchException( "content type mismatched."); + } + } + else{ + throw TypeMismatchException("content type mismatched."); + } + + JSObjectRef successCallbackObj = argValidator.toFunction(1,true); + if(successCallbackObj){ + cbm->setOnSuccess(successCallbackObj); + } + + JSObjectRef errorCallbackObj = argValidator.toFunction(2,true); + if(errorCallbackObj){ + cbm->setOnError(errorCallbackObj); + } + }catch(const BasePlatformException &err){ + return JSWebAPIErrorFactory::postException(context,exception,err); + } + catch(...){ + DeviceAPI::Common::UnknownException err("Unknown Error in updateBatch()."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + + Try + { + IMediacontentManagerPtr contentMgr = privateObject->getObject(); + + IEventUpdateMediaItemsPtr dplEvent(new IEventUpdateMediaItems()); + dplEvent->setMediaItems(contents); + dplEvent->setPrivateData(DPL::StaticPointerCast<IEventPrivateData>(cbm)); + + dplEvent->setForAsynchronousCall(&MediacontentManagerController::getInstance()); + contentMgr->updateMediaItems(dplEvent); + + MediaContentAsyncCallbackManagerSingleton::Instance().registerCallbackManager(cbm, globalContext); + } + Catch(WrtDeviceApis::Commons::UnsupportedException) + { + LoggerW("Exception: "<<_rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_SUPPORTED_ERROR, _rethrown_exception.GetMessage()); + } + Catch(WrtDeviceApis::Commons::InvalidArgumentException) + { + LoggerW("Exception: "<<_rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, _rethrown_exception.GetMessage()); + } + Catch(WrtDeviceApis::Commons::ConversionException) + { + LoggerW("Exception: "<<_rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, _rethrown_exception.GetMessage()); + } + Catch(WrtDeviceApis::Commons::NotFoundException) + { + LoggerW("Exception: "<<_rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_FOUND_ERROR, _rethrown_exception.GetMessage()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LoggerW("Exception: "<<_rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, _rethrown_exception.GetMessage()); + } + + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); +} + + + +JSValueRef JSMediacontentManager::updateItem( + JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + + MediacontentManagerPrivObject *privateObject; + privateObject = static_cast<MediacontentManagerPrivObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + DeviceAPI::Common::UnknownException err("Content's private object is NULL."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + + AceSecurityStatus status = CONTENT_CHECK_ACCESS(CONTENT_FUNCTION_API_UPDATE_ITEM); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + Try + { + IMediacontentManagerPtr contentMgr = privateObject->getObject(); + + //parameter : MediaItem item + + JSObjectRef arg; + if(argumentCount >= 1) + { + if (!JSValueIsObjectOfClass(context, arguments[0], JSMedia::getClassRef()) && + !JSValueIsObjectOfClass(context, arguments[0], JSImage::getClassRef()) && + !JSValueIsObjectOfClass(context, arguments[0], JSAudio::getClassRef()) && + !JSValueIsObjectOfClass(context, arguments[0], JSVideo::getClassRef())) { + ThrowMsg(ConversionException, "Content type mismatched."); + } + arg = JSValueToObject(context, arguments[0], exception); + } + else + { + ThrowMsg(ConversionException, "Content type mismatched."); + } + + MediacontentMediaPtr event; + IEventUpdateMediaPtr dplEvent(new IEventUpdateMedia()); + + if(JSValueIsObjectOfClass(context, arguments[0], JSImage::getClassRef())){ + MediacontentImagePtr imgPtr = JSImage::getImageObject(arg); + JSValueRef geoValRef = JSUtil::getProperty(context , JSUtil::JSValueToObject(context, arguments[0]), "geolocation"); + if(!(JSValueIsNull(context, geoValRef) || JSValueIsUndefined(context, geoValRef))){ + JSObjectRef geoObjRef = JSUtil::JSValueToObject(context, geoValRef); + double latitude = JSUtil::JSValueToDouble(context, JSUtil::getProperty(context, geoObjRef, "latitude")); + double longitude = JSUtil::JSValueToDouble(context, JSUtil::getProperty(context, geoObjRef, "longitude")); + if(ContentUtility::checkLocation(latitude, latitude)){ + imgPtr->setImageLatitude(latitude); + imgPtr->setImageLongitude(longitude); + } + else{ + ThrowMsg(WrtDeviceApis::Commons::InvalidArgumentException, "geolocation value is not valid."); + } + } + else + { + imgPtr->setImageLatitude(DEFAULT_GEOLOCATION); + imgPtr->setImageLongitude(DEFAULT_GEOLOCATION); + } + } + else if(JSValueIsObjectOfClass(context, arguments[0], JSVideo::getClassRef())){ + MediacontentVideoPtr vedioPtr = JSVideo::getVideoObject(arg); + JSValueRef geoValRef = JSUtil::getProperty(context , JSUtil::JSValueToObject(context, arguments[0]), "geolocation"); + if(!(JSValueIsNull(context, geoValRef) || JSValueIsUndefined(context, geoValRef))){ + JSObjectRef geoObjRef = JSUtil::JSValueToObject(context, geoValRef); + double latitude = JSUtil::JSValueToDouble(context, JSUtil::getProperty(context, geoObjRef, "latitude")); + double longitude = JSUtil::JSValueToDouble(context, JSUtil::getProperty(context, geoObjRef, "longitude")); + if(ContentUtility::checkLocation(latitude, latitude)){ + vedioPtr->setVideoLatitude(latitude); + vedioPtr->setVideoLongitude(longitude); + } + else{ + ThrowMsg(WrtDeviceApis::Commons::InvalidArgumentException, "geolocation value is not valid."); + } + } + else + { + vedioPtr->setVideoLatitude(DEFAULT_GEOLOCATION); + vedioPtr->setVideoLongitude(DEFAULT_GEOLOCATION); + } + } + + JSValueRef nameValRef = JSUtil::getProperty(context , JSUtil::JSValueToObject(context, arguments[0]), "name"); + if((JSValueIsNull(context, nameValRef) || JSValueIsUndefined(context, nameValRef)) || + JSUtil::JSValueToString(context, nameValRef) == ""){ + ThrowMsg(WrtDeviceApis::Commons::InvalidArgumentException, "name is not valid."); + } + event = JSMedia::getMediaObject(arg); + dplEvent->setMediaItem(event); + + dplEvent->setForSynchronousCall(); + contentMgr->updateMedia(dplEvent); + + if (!(dplEvent->getResult())) { + ThrowMsg(WrtDeviceApis::Commons::Exception, "updating failed by unknown reason."); + } + } + Catch(WrtDeviceApis::Commons::UnsupportedException) + { + LoggerW("Exception: "<<_rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_SUPPORTED_ERROR, _rethrown_exception.GetMessage()); + } + Catch(WrtDeviceApis::Commons::InvalidArgumentException) + { + LoggerW("Exception: "<<_rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, _rethrown_exception.GetMessage()); + } + Catch(WrtDeviceApis::Commons::ConversionException) + { + LoggerW("Exception: "<<_rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, _rethrown_exception.GetMessage()); + } + Catch(WrtDeviceApis::Commons::NotFoundException) + { + LoggerW("Exception: "<<_rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_FOUND_ERROR, _rethrown_exception.GetMessage()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LoggerW("Exception: "<<_rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, _rethrown_exception.GetMessage()); + } + + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); + +} + +static void _scanCompletedCallback(std::string err_msg, std::string path, void *user_data){ + CallbackUserData *cb = static_cast<CallbackUserData*>(user_data); + if(cb != NULL){ + if(err_msg.empty() ){ + Converter converter(cb->getContext()); + JSValueRef jsPath = converter.toJSValueRef(ContentUtility::convertPathToUri(path)); + cb->callSuccessCallback(jsPath); + } + else{ + DeviceAPI::Common::UnknownException err(err_msg.c_str()); + JSObjectRef errorObject = JSWebAPIErrorFactory::makeErrorObject(cb->getContext(),err); + cb->callErrorCallback(errorObject); + } + delete cb; + } +} + +JSValueRef JSMediacontentManager::scanFile( + JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + + MediacontentManagerPrivObject *privateObject; + privateObject = static_cast<MediacontentManagerPrivObject*>(JSObjectGetPrivate(thisObject)); + if(!privateObject) { + DeviceAPI::Common::UnknownException err("Content's private object is NULL."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + + AceSecurityStatus status = CONTENT_CHECK_ACCESS(CONTENT_FUNCTION_API_SCAN_FILE); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + string path; + CallbackUserData *callback = NULL; + try{ + callback = new CallbackUserData(GlobalContextManager::getInstance()->getGlobalContext(context)); + ArgumentValidator argValidator(context, argumentCount, arguments); + path = argValidator.toString(0); + if(path.empty()){ + throw TypeMismatchException("File path type mismatched."); + } + else if(path == "null" || path == "undefined"){ + throw InvalidValuesException("File path is not valid."); + } + path = ContentUtility::convertUriToPath(path); + + JSObjectRef successCallbackObj = argValidator.toFunction(1,true); + if(successCallbackObj){ + callback->setSuccessCallback(successCallbackObj); + } + + JSObjectRef errorCallbackObj = argValidator.toFunction(2,true); + if(errorCallbackObj){ + callback->setErrorCallback(errorCallbackObj); + } + }catch(const BasePlatformException &err){ + return JSWebAPIErrorFactory::postException(context,exception,err); + } + catch(...){ + DeviceAPI::Common::UnknownException err("Unknown Error in scanFile()."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + + Try + { + IMediacontentManagerPtr contentMgr = privateObject->getObject(); + contentMgr->scanFile(_scanCompletedCallback,path,(void*)callback); + } + Catch(WrtDeviceApis::Commons::UnsupportedException) + { + LoggerW("Exception: "<<_rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_SUPPORTED_ERROR, _rethrown_exception.GetMessage()); + } + Catch(WrtDeviceApis::Commons::InvalidArgumentException) + { + LoggerW("Exception: "<<_rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, _rethrown_exception.GetMessage()); + } + Catch(WrtDeviceApis::Commons::ConversionException) + { + LoggerW("Exception: "<<_rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, _rethrown_exception.GetMessage()); + } + Catch(WrtDeviceApis::Commons::NotFoundException) + { + LoggerW("Exception: "<<_rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_FOUND_ERROR, _rethrown_exception.GetMessage()); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LoggerW("Exception: "<<_rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, _rethrown_exception.GetMessage()); + } + + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); +} + + +JSValueRef JSMediacontentManager::setChangeListener( + JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + + MediacontentManagerPrivObject *privateObject; + privateObject = static_cast<MediacontentManagerPrivObject*>(JSObjectGetPrivate(thisObject)); + if(!privateObject) { + DeviceAPI::Common::UnknownException err("Content's private object is NULL."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + + AceSecurityStatus status = CONTENT_CHECK_ACCESS(CONTENT_FUNCTION_API_SET_CHANGE_LISTENER); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + try{ + ArgumentValidator argValidator(context, argumentCount, arguments); + JSContextRef globalCtx = GlobalContextManager::getInstance()->getGlobalContext(context); + JSObjectRef callbackObj = argValidator.toCallbackObject(0,false,"oncontentadded","oncontentupdated","oncontentremoved",NULL); + ContentListener *listener = new ContentListener(globalCtx, callbackObj); + IMediacontentManagerPtr contentMgr = privateObject->getObject(); + if(!(contentMgr->setListener(listener))) + { + throw DeviceAPI::Common::UnknownException( "Unknown exception is occured by platfrom"); + } + }catch(const BasePlatformException &err){ + return JSWebAPIErrorFactory::postException(context,exception,err); + } + catch(...){ + DeviceAPI::Common::UnknownException err("Unknown Error in setChangeListener()."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); +} + +JSValueRef JSMediacontentManager::unsetChangeListener( + JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + MediacontentManagerPrivObject *privateObject; + privateObject = static_cast<MediacontentManagerPrivObject*>(JSObjectGetPrivate(thisObject)); + if(!privateObject) { + DeviceAPI::Common::UnknownException err("Content's private object is NULL."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + + AceSecurityStatus status = CONTENT_CHECK_ACCESS(CONTENT_FUNCTION_API_SET_CHANGE_LISTENER); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + try{ + // perform + IMediacontentManagerPtr contentMgr = privateObject->getObject(); + if(!(contentMgr->unsetListener())) + { + throw DeviceAPI::Common::UnknownException( "Unknown exception is occured by platfrom"); + } + }catch(const BasePlatformException &err){ + return JSWebAPIErrorFactory::postException(context,exception,err); + } + catch(...){ + DeviceAPI::Common::UnknownException err("Unknown Error in unsetChangeListener()."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); +} + +const JSClassRef JSMediacontentManager::getClassRef() { + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + + +const JSClassDefinition* JSMediacontentManager::getClassInfo() +{ + return &m_classInfo; +} + +void JSMediacontentManager::initialize(JSContextRef context, JSObjectRef object) +{ + MediacontentManagerPrivObject *privateObject = static_cast<MediacontentManagerPrivObject*>(JSObjectGetPrivate(object)); + if (NULL == privateObject) + { + IMediacontentManagerPtr contentManager = MediacontentFactory::getInstance().createMediacontentManagerObject(); + privateObject = new MediacontentManagerPrivObject(context, contentManager); + if (!JSObjectSetPrivate(object, static_cast<void*>(privateObject))) + { + delete privateObject; + } + } + +} + +void JSMediacontentManager::finalize(JSObjectRef object) +{ + MediacontentManagerPrivObject* priv = static_cast<MediacontentManagerPrivObject*> (JSObjectGetPrivate(object)); + if(priv != NULL) + { + delete priv; + JSObjectSetPrivate(object, NULL); + priv = NULL; + } + +} + +IMediacontentManagerPtr JSMediacontentManager::getContentManagerPrivObject( + JSContextRef ctx, + const JSObjectRef object, + JSValueRef* exception) +{ + MediacontentManagerPrivObject *priv = static_cast<MediacontentManagerPrivObject*>(JSObjectGetPrivate(object)); + if (priv) + { + return priv->getObject(); + } + ThrowMsg(ConversionException, "Private object is NULL."); +} + + +} +} + + diff --git a/wearable_src/Content/JSContentManager.h b/wearable_src/Content/JSContentManager.h new file mode 100755 index 0000000..73599a8 --- /dev/null +++ b/wearable_src/Content/JSContentManager.h @@ -0,0 +1,166 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _JS_TIZEN_CONTENTMANAGER_H_ +#define _JS_TIZEN_CONTENTMANAGER_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/PrivateObject.h> +#include <CommonsJavaScript/JSCallbackManager.h> +#include "IContentManager.h" + +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + + +namespace DeviceAPI { +namespace Content { + +typedef PrivateObject<IMediacontentManagerPtr, NoOwnership> MediacontentManagerPrivObject; + +class JSMediacontentManager +{ +public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + +private: + +/* +static JSValueRef getMediacontent( + JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); +*/ + static IMediacontentManagerPtr getContentManagerPrivObject( + JSContextRef ctx, + const JSObjectRef object, + JSValueRef* exception); + + + /** + * 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 JSValueRef getProperty( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + /** + * 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); + + + static JSValueRef getFolders( + JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef updateItem( + JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef updateItemsBatch( + JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + + static JSValueRef findItems( + JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef scanFile( + JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef setChangeListener( + JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef unsetChangeListener( + JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + static JSStaticFunction m_function[]; + + /** + * This structure describes a statically declared value property. + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; +}; + +} +} + +#endif //_JS_TIZEN_CONTENTMANAGER_H_ + diff --git a/wearable_src/Content/JSFolder.cpp b/wearable_src/Content/JSFolder.cpp new file mode 100755 index 0000000..800b101 --- /dev/null +++ b/wearable_src/Content/JSFolder.cpp @@ -0,0 +1,282 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <CommonsJavaScript/PrivateObject.h> +#include <CommonsJavaScript/Converter.h> +#include <CommonsJavaScript/JSUtils.h> +#include <CommonsJavaScript/JSDOMExceptionFactory.h> +#include "ContentFactory.h" +#include "ContentController.h" +#include "JSFolder.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Content { + +#define TIZEN_CONTENT_FOLDER_ATTRIBUTENAME "ContentDirectory" +#define TIZEN_CONTENT_FOLDER_UID "id" +#define TIZEN_CONTENT_FOLDER_NAME "title" +#define TIZEN_CONTENT_FOLDER_PATH "directoryURI" +#define TIZEN_CONTENT_FOLDER_STORAGE_TYPE "storageType" +#define TIZEN_CONTENT_FOLDER_MODIFIEDDATE "modifiedDate" + + +JSClassDefinition JSFolder::m_classInfo = +{ + 0, + kJSClassAttributeNone, + TIZEN_CONTENT_FOLDER_ATTRIBUTENAME, + 0, + m_property, + m_function, // m_function, + initialize, + finalize, + NULL, //hasProperty, + NULL, //getProperty, + NULL, //setProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL //ConvertToType +}; + +JSStaticValue JSFolder::m_property[] = +{ + //FolderProperties + { TIZEN_CONTENT_FOLDER_UID, getPropertyId, NULL, kJSPropertyAttributeReadOnly}, + { TIZEN_CONTENT_FOLDER_NAME, getPropertyName, NULL, kJSPropertyAttributeReadOnly}, + { TIZEN_CONTENT_FOLDER_PATH, getPropertyPath, NULL, kJSPropertyAttributeReadOnly}, + { TIZEN_CONTENT_FOLDER_STORAGE_TYPE, getPropertyStorageType, NULL, kJSPropertyAttributeReadOnly}, + { TIZEN_CONTENT_FOLDER_MODIFIEDDATE, getPropertyModifiedDate, NULL, kJSPropertyAttributeReadOnly}, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSFolder::m_function[] = +{ + { 0, 0, 0 } +}; + + +JSClassRef JSFolder::m_jsClassRef = JSClassCreate(JSFolder::getClassInfo()); + +void JSFolder::initialize(JSContextRef context, JSObjectRef object) +{ + FolderPrivObject *priv = static_cast<FolderPrivObject*>( JSObjectGetPrivate( object ) ); + if (!priv) + { + MediacontentFolderPtr privateData(new MediacontentFolder()); + priv = new FolderPrivObject(context, privateData); + JSObjectSetPrivate(object, static_cast<void*>(priv)); + } + else + { + LoggerD("private object already exists"); + } +} + + +void JSFolder::finalize(JSObjectRef object) +{ + FolderPrivObject *priv = static_cast<FolderPrivObject*>( JSObjectGetPrivate( object ) ) ; + if (priv != NULL) + { + delete (priv); + priv = NULL; + JSObjectSetPrivate(object, NULL); + } +} + + + +const JSClassRef JSFolder::getClassRef() +{ + if (!m_jsClassRef) + { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSFolder::getClassInfo() +{ + return &m_classInfo; +} + + +MediacontentFolderPtr JSFolder::getFolderObject(JSObjectRef object) +{ + FolderPrivObject *priv = static_cast<FolderPrivObject*>(JSObjectGetPrivate(object)); + if(!priv) { + ThrowMsg(NullPointerException, "Private object is null"); + } + MediacontentFolderPtr result = priv->getObject(); + if (!result) { + ThrowMsg(NullPointerException, "Private object is null"); + } + return result; +} + + + +JSValueRef JSFolder::getPropertyId( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentFolderPtr folder = getFolderObject(object); + return converter.toJSValueRef(folder->getFolderUUID()); + } + Catch(Exception) + { + LoggerW("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); + +} + +JSValueRef JSFolder::getPropertyName( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentFolderPtr folder = getFolderObject(object); + return converter.toJSValueRef(folder->getFolderName()); + } + Catch(Exception) + { + LoggerW("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + + +JSValueRef JSFolder::getPropertyPath( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentFolderPtr folder = getFolderObject(object); + return converter.toJSValueRef(folder->getFolderPath()); + } + Catch(Exception) + { + LoggerW("trying to get incorrect value"); + } + return JSValueMakeNull(context); +} + + +JSValueRef JSFolder::getPropertyStorageType( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentFolderPtr folder = getFolderObject(object); + return converter.toJSValueRef(folder->getFolderStorageType()); + } + Catch(Exception) + { + LoggerW("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + + +JSValueRef JSFolder::getPropertyModifiedDate( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentFolderPtr folder = getFolderObject(object); + if(folder->getFolderModifiedDate() != NULL) + { + return converter.toJSValueRef(*(folder->getFolderModifiedDate())); + } + } + Catch(Exception) + { + LoggerW("trying to get incorrect value"); + } + return JSValueMakeNull(context); +} + + +JSValueRef JSFolder::getPropertyMediaId( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentFolderPtr folder = getFolderObject(object); + MediaIdListPtr mediaIdLstPtr = folder->getMediaIdList(); + JSObjectRef jsResult = JSCreateArrayObject(context, 0, NULL); + + if(mediaIdLstPtr) + { + if (NULL == jsResult) + { + ThrowMsg(NullPointerException, "Could not create js array object"); + } + for(unsigned int i=0; i<mediaIdLstPtr->size(); i++) + { + JSValueRef val = converter.toJSValueRef(mediaIdLstPtr->at(i)); + if(!JSSetArrayElement(context, jsResult, i, val)) + { + ThrowMsg(UnknownException, "Could not insert value into js array"); + } + } + } + return jsResult; + } + Catch(Exception) + { + LoggerW("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); + +} + + + +} +} + diff --git a/wearable_src/Content/JSFolder.h b/wearable_src/Content/JSFolder.h new file mode 100755 index 0000000..b40bee0 --- /dev/null +++ b/wearable_src/Content/JSFolder.h @@ -0,0 +1,128 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _JS_TIZEN_FOLDER_H_ +#define _JS_TIZEN_FOLDER_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/PrivateObject.h> +#include "ContentFolder.h" + +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + + +namespace DeviceAPI { +namespace Content { + + +typedef PrivateObject<MediacontentFolderPtr, NoOwnership> FolderPrivObject; + +class JSFolder +{ + public: + + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + + static MediacontentFolderPtr getFolderObject(JSObjectRef object); + + private: + /** + * This member variable contains the values which has to be passed when + * the this class is embedded into JS Engine. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This member variable contains the initialization values for the + * properties of this class. The values are given according to the + * data structure JSPropertySpec. + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; + + /** + * 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); + + /** + * Getters and setters for properties + */ + static JSValueRef getPropertyId( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getPropertyPath( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getPropertyName( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getPropertyStorageType( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getPropertyModifiedDate( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getPropertyMediaId( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getPropertyEditableAttr( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + +}; + +} +} + + +#endif /* _JS_TIZEN_FOLDER_H_ */ diff --git a/wearable_src/Content/JSImage.cpp b/wearable_src/Content/JSImage.cpp new file mode 100755 index 0000000..0644672 --- /dev/null +++ b/wearable_src/Content/JSImage.cpp @@ -0,0 +1,258 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <CommonsJavaScript/PrivateObject.h> +#include <CommonsJavaScript/Converter.h> +#include <CommonsJavaScript/JSUtils.h> +#include <CommonsJavaScript/JSDOMExceptionFactory.h> +#include <JSSimpleCoordinates.h> + +#include <JSWebAPIErrorFactory.h> +#include <SecurityExceptions.h> + +#include "JSUtil.h" +#include "JSImage.h" +#include <Logger.h> + +#define TIZEN_CONTENT_IMAGE_ATTRIBUTENAME "ImageContent" +#define TIZEN_CONTENT_IMAGE_GEOLOCATION "geolocation" +#define TIZEN_CONTENT_IMAGE_WIDTH "width" +#define TIZEN_CONTENT_IMAGE_HEIGHT "height" +#define TIZEN_CONTENT_IMAGE_ORIENTATION "orientation" + +using namespace DeviceAPI::Tizen; +using namespace DeviceAPI::Common; +using namespace WrtDeviceApis::Commons; +using namespace DeviceAPI::Tizen; + +namespace DeviceAPI { +namespace Content { + + +JSClassDefinition JSImage::m_classInfo = +{ + 0, + kJSClassAttributeNone, + TIZEN_CONTENT_IMAGE_ATTRIBUTENAME, + JSMedia::getClassRef(), + m_property, + NULL, // m_function, + initialize, + finalize, + NULL, //hasProperty, + NULL, //getProperty, + setProperty, //setProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL //ConvertToType +}; + +JSStaticValue JSImage::m_property[] = +{ + { TIZEN_CONTENT_IMAGE_WIDTH, getPropertyWidth, NULL, kJSPropertyAttributeReadOnly}, + { TIZEN_CONTENT_IMAGE_HEIGHT, getPropertyHeight, NULL, kJSPropertyAttributeReadOnly}, + { TIZEN_CONTENT_IMAGE_ORIENTATION, getPropertyOrientation, setPropertyOrientation, kJSPropertyAttributeNone}, + { 0, 0, 0, 0 } +}; + + +JSClassRef JSImage::m_jsClassRef = JSClassCreate(JSImage::getClassInfo()); + +void JSImage::initialize(JSContextRef context, JSObjectRef object) +{ + + ImagePrivObject *priv = static_cast<ImagePrivObject*>( JSObjectGetPrivate( object ) ); + + if (!priv) { + MediacontentImagePtr privateData(new MediacontentImage()); + priv = new ImagePrivObject(context, privateData); + JSObjectSetPrivate(object, static_cast<void*>(priv)); + } + else { + MediacontentImagePtr image = getImageObject(object); + if(image->getImageLatitude() != DEFAULT_GEOLOCATION && + image->getImageLongitude() != DEFAULT_GEOLOCATION){ + DeviceAPI::Tizen::SimpleCoordinatesPtr geoPtr(new SimpleCoordinates(image->getImageLatitude(),image->getImageLongitude())); + JSUtil::setProperty(context, object, TIZEN_CONTENT_IMAGE_GEOLOCATION, + JSSimpleCoordinates::createJSObject(context,geoPtr), + kJSPropertyAttributeNone); + } + else + { + JSUtil::setProperty(context, object, TIZEN_CONTENT_IMAGE_GEOLOCATION, + JSValueMakeNull(context),kJSPropertyAttributeNone); + } + } +} + +void JSImage::finalize(JSObjectRef object) +{ + ImagePrivObject *priv = static_cast<ImagePrivObject*>( JSObjectGetPrivate( object ) ) ; + if (priv != NULL) + { + delete (priv); + priv = NULL; + JSObjectSetPrivate(object, NULL); + } +} + +const JSClassRef JSImage::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSImage::getClassInfo() +{ + return &m_classInfo; +} + +MediacontentImagePtr JSImage::getImageObject(JSObjectRef object) +{ + ImagePrivObject *priv = static_cast<ImagePrivObject*>(JSObjectGetPrivate(object)); + if(!priv) { + ThrowMsg(NullPointerException, "Private object is null"); + } + MediacontentImagePtr result = priv->getObject(); + if (!result) { + ThrowMsg(NullPointerException, "Private object is null"); + } + return result; +} + +JSValueRef JSImage::getPropertyWidth( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentImagePtr image = getImageObject(object); + return converter.toJSValueRef(image->getImageWidth()); + } + Catch(Exception) + { + LoggerW("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + + +JSValueRef JSImage::getPropertyHeight( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentImagePtr image = getImageObject(object); + return converter.toJSValueRef(image->getImageHeight()); + } + Catch(Exception) + { + LoggerW("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSImage::getPropertyOrientation( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentImagePtr image = getImageObject(object); + if(!(image->getImageOrientation().empty())){ + return converter.toJSValueRef(image->getImageOrientation()); + } + } + Catch(Exception) + { + LoggerW("trying to get incorrect value"); + } + return JSValueMakeNull(context); +} + +bool JSImage::setPropertyOrientation( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + try + { + Converter converter(context); + MediacontentImagePtr objImg = getImageObject(object); + + string orientation = converter.toString(value); + if (orientation != "NORMAL" && orientation != "FLIP_HORIZONTAL" && + orientation != "ROTATE_180" && orientation != "FLIP_VERTICAL" && + orientation != "TRANSPOSE" && orientation != "ROTATE_90" && + orientation != "TRANSVERSE" && orientation != "ROTATE_270"){ + throw TypeMismatchException("Invalid orientation type"); + } + + if ((objImg->getImageOrientation()).compare(orientation) !=0 ) + { + objImg->setImageOrientation(orientation, true); + } + + return true; + } + catch(...) + { + LoggerW("trying to get incorrect value"); + } + + return false; +} + + +bool JSImage::setProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + try { + // check geolocation + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_CONTENT_IMAGE_GEOLOCATION)) { + if(JSValueIsUndefined(context, value)){ + throw TypeMismatchException("Invalid geolocation"); + } + } + } catch (const BasePlatformException &err) { + LOGE("setProperty error< %s : %s> " , err.getName().c_str(), err.getMessage().c_str()); + return true; + } + return false; +} + + +} +} + diff --git a/wearable_src/Content/JSImage.h b/wearable_src/Content/JSImage.h new file mode 100755 index 0000000..1ab6c38 --- /dev/null +++ b/wearable_src/Content/JSImage.h @@ -0,0 +1,129 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _JS_TIZEN_IMAGE_H_ +#define _JS_TIZEN_IMAGE_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/PrivateObject.h> +#include <SimpleCoordinates.h> + +#include "JSContent.h" +#include "ContentMedia.h" +#include "ContentImage.h" + + +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + + +namespace DeviceAPI { +namespace Content { + +typedef PrivateObject<MediacontentImagePtr, NoOwnership> ImagePrivObject; + +class JSImage +{ +public: + + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + + static MediacontentImagePtr getImageObject(JSObjectRef object); + + +private: + /** + * This member variable contains the values which has to be passed when + * the this class is embedded into JS Engine. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This member variable contains the initialization values for the + * properties of this class. The values are given according to the + * data structure JSPropertySpec. + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; + + /** + * 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); + + + + /** + * Getters and setters for properties + */ + + static JSValueRef getPropertyWidth( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getPropertyHeight( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + + static JSValueRef getPropertyOrientation( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setPropertyOrientation( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static bool setProperty( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + + +}; + +} +} + + +#endif /* _JS_TIZEN_IMAGE_H_ */ diff --git a/wearable_src/Content/JSVideo.cpp b/wearable_src/Content/JSVideo.cpp new file mode 100755 index 0000000..1b3f9c3 --- /dev/null +++ b/wearable_src/Content/JSVideo.cpp @@ -0,0 +1,349 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <CommonsJavaScript/Converter.h> +#include <CommonsJavaScript/JSUtils.h> +#include <JSWebAPIErrorFactory.h> +#include <JSSimpleCoordinates.h> + +#include "ContentConverter.h" +#include "JSVideo.h" +#include "JSUtil.h" +#include <Logger.h> + +#define TIZEN_CONTENT_VIDEO_ATTRIBUTENAME "VideoContent" +#define TIZEN_CONTENT_VIDEO_GEOLOCATION "geolocation" +#define TIZEN_CONTENT_VIDEO_ALBUM "album" +#define TIZEN_CONTENT_VIDEO_ARTIST "artists" +#define TIZEN_CONTENT_VIDEO_DURATION "duration" +#define TIZEN_CONTENT_VIDEO_WIDTH "width" +#define TIZEN_CONTENT_VIDEO_HEIGHT "height" + +using namespace DeviceAPI::Common; +using namespace DeviceAPI::Tizen; +using namespace WrtDeviceApis::Commons; + +namespace DeviceAPI { +namespace Content { + + +JSClassDefinition JSVideo::m_classInfo = +{ + 0, + kJSClassAttributeNone, + TIZEN_CONTENT_VIDEO_ATTRIBUTENAME, + JSMedia::getClassRef(), + m_property, + NULL, // m_function, + initialize, + finalize, + NULL, //hasProperty, + NULL, //getProperty, + setProperty, //setProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL //ConvertToType +}; + +JSStaticValue JSVideo::m_property[] = +{ + { TIZEN_CONTENT_VIDEO_ALBUM, getPropertyAlbum, NULL, kJSPropertyAttributeReadOnly}, + { TIZEN_CONTENT_VIDEO_ARTIST, getPropertyArtist, NULL, kJSPropertyAttributeReadOnly}, + { TIZEN_CONTENT_VIDEO_DURATION, getPropertyDuration, NULL, kJSPropertyAttributeReadOnly}, + { TIZEN_CONTENT_VIDEO_WIDTH, getPropertyWidth, NULL, kJSPropertyAttributeReadOnly}, + { TIZEN_CONTENT_VIDEO_HEIGHT, getPropertyHeight, NULL, kJSPropertyAttributeReadOnly}, + { 0, 0, 0, 0 } +}; + + +JSClassRef JSVideo::m_jsClassRef = JSClassCreate(JSVideo::getClassInfo()); + +void JSVideo::initialize(JSContextRef context, JSObjectRef object) +{ + VideoPrivObject *priv = static_cast<VideoPrivObject*>( JSObjectGetPrivate( object ) ); + if (!priv) + { + MediacontentVideoPtr privateData(new MediacontentVideo()); + priv = new VideoPrivObject(context, privateData); + JSObjectSetPrivate(object, static_cast<void*>(priv)); + LoggerD("new pravite object is created" ); + } + else { + LoggerD("private object already exists"); + MediacontentVideoPtr video = getVideoObject(object); + if(video->getVideoLatitude() != DEFAULT_GEOLOCATION && + video->getVideoLongitude() != DEFAULT_GEOLOCATION){ + DeviceAPI::Tizen::SimpleCoordinatesPtr geoPtr(new SimpleCoordinates(video->getVideoLatitude(),video->getVideoLongitude())); + JSUtil::setProperty(context, object, TIZEN_CONTENT_VIDEO_GEOLOCATION, + JSSimpleCoordinates::createJSObject(context,geoPtr), + kJSPropertyAttributeNone); + } + else + { + JSUtil::setProperty(context, object, TIZEN_CONTENT_VIDEO_GEOLOCATION, + JSValueMakeNull(context),kJSPropertyAttributeNone); + } + } +} + +void JSVideo::finalize(JSObjectRef object) +{ + VideoPrivObject *priv = static_cast<VideoPrivObject*>( JSObjectGetPrivate( object ) ) ; + if (priv != NULL) + { + delete (priv); + priv = NULL; + JSObjectSetPrivate(object, NULL); + } + priv = NULL; +} + +const JSClassRef JSVideo::getClassRef() +{ + if (!m_jsClassRef) + { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSVideo::getClassInfo() +{ + return &m_classInfo; +} + +MediacontentVideoPtr JSVideo::getVideoObject(JSObjectRef object) +{ + VideoPrivObject *priv = static_cast<VideoPrivObject*>(JSObjectGetPrivate(object)); + if(!priv) + { + ThrowMsg(NullPointerException, "Private object is null"); + } + MediacontentVideoPtr result = priv->getObject(); + if (!result) + { + ThrowMsg(NullPointerException, "Private object is null"); + } + return result; +} + +JSValueRef JSVideo::getPropertyAlbum( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentVideoPtr video = getVideoObject(object); + if(!video->getVideoAlbum().empty()){ + return converter.toJSValueRef(video->getVideoAlbum()); + } + } + Catch(Exception) + { + LoggerW("trying to get incorrect value"); + } + return JSValueMakeNull(context); +} + + +JSValueRef JSVideo::getPropertyArtist( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentVideoPtr video = getVideoObject(object); + JSObjectRef jsResult = JSCreateArrayObject(context, 0, NULL); + if (NULL == jsResult) { + ThrowMsg(NullPointerException, "Could not create js array object"); + } + + for( unsigned int i=0; i < video->getVideoArtist().size(); i++) { + string artist = video->getVideoArtist().at(i); + JSValueRef val = converter.toJSValueRef(artist); + + if(!JSSetArrayElement(context, jsResult, i, val)){ + ThrowMsg(NullPointerException, "Could not insert value into js array"); + } + } + return jsResult; + } + Catch(Exception){ + LoggerW("trying to get incorrect value"); + } + return JSValueMakeNull(context); +} + + +JSValueRef JSVideo::getPropertyDuration( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentVideoPtr video = getVideoObject(object); + if(video){ + return converter.toJSValueRef(video->getVideoDuration()); + } + } + Catch(Exception) + { + LoggerW("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSVideo::getPropertyWidth( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + + Try + { + Converter converter(context); + MediacontentVideoPtr video = getVideoObject(object); + if(video){ + return converter.toJSValueRef(video->getVideoWidth()); + } + } + Catch(Exception) + { + LoggerW("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + + +JSValueRef JSVideo::getPropertyHeight( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentVideoPtr video = getVideoObject(object); + if(video){ + return converter.toJSValueRef(video->getVideoHeight()); + } + } + Catch(Exception) + { + LoggerW("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSVideo::setPropertyArtists( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + MediacontentVideoPtr video = getVideoObject(object); + + vector<std::string> artists; + if (!JSValueIsNull(context, value)) { + + if (JSIsArrayValue(context, value)){ + JSObjectRef jsObject = converter.toJSObjectRef(value); + for (std::size_t i = 0; i < JSGetArrayLength(context, jsObject); ++i) { + JSValueRef element = JSGetArrayElement(context, jsObject, i); + artists.push_back(converter.toString(element)); + } + } + else{ + DeviceAPI::Common::JSWebAPIErrorFactory::postException(context, exception, DeviceAPI::Common::JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR); + } + video->setVideoArtist(artists, true); + return true; + } + } + Catch(Exception) + { + LoggerW("trying to set incorrect value"); + DeviceAPI::Common::JSWebAPIErrorFactory::postException(context, exception, DeviceAPI::Common::JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR); + } + return false; +} + +bool JSVideo::setPropertyAlbum( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + Try + { + Converter converter(context); + + MediacontentVideoPtr video = getVideoObject(object); + string album = converter.toString(value); + if(video){ + video->setVideoAlbum(album, true); + return true; + } + } + Catch(Exception) + { + LoggerW("trying to set incorrect value"); + DeviceAPI::Common::JSWebAPIErrorFactory::postException(context, exception, DeviceAPI::Common::JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR); + } + return false; +} + +bool JSVideo::setProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + try { + // check geolocation + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_CONTENT_VIDEO_GEOLOCATION)) { + if(JSValueIsUndefined(context, value)){ + throw TypeMismatchException("Invalid geolocation"); + } + } + } catch (const BasePlatformException &err) { + LOGE("setProperty error< %s : %s> " , err.getName().c_str(), err.getMessage().c_str()); + return true; + } + return false; +} + + +} +} + diff --git a/wearable_src/Content/JSVideo.h b/wearable_src/Content/JSVideo.h new file mode 100755 index 0000000..1679538 --- /dev/null +++ b/wearable_src/Content/JSVideo.h @@ -0,0 +1,157 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _JS_TIZEN_VIDEO_H_ +#define _JS_TIZEN_VIDEO_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/PrivateObject.h> +#include "ContentMedia.h" +#include "ContentVideo.h" +#include "JSContent.h" + +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace DeviceAPI { +namespace Content { + +typedef PrivateObject<MediacontentVideoPtr, NoOwnership> VideoPrivObject; + +class JSVideo +{ +public: + + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + + static MediacontentVideoPtr getVideoObject(JSObjectRef object); + +private: + /** + * This member variable contains the values which has to be passed when + * the this class is embedded into JS Engine. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This member variable contains the initialization values for the + * properties of this class. The values are given according to the + * data structure JSPropertySpec. + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; + + /** + * 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); + + + + /** + * Getters and setters for properties + */ + + static JSValueRef getPropertyAlbum( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getPropertyArtist( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getPropertyDuration( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + + static JSValueRef getPropertyWidth( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static JSValueRef getPropertyHeight( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setPropertyPlayCount( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + + static bool setPropertyPlayedTime( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static bool setPropertyAlbum( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static bool setPropertyArtists( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static bool setProperty( + JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + +}; + +} +} + + +#endif /* _JS_TIZEN_VIDEO_H_ */ diff --git a/wearable_src/Content/config.xml b/wearable_src/Content/config.xml new file mode 100755 index 0000000..3bff72a --- /dev/null +++ b/wearable_src/Content/config.xml @@ -0,0 +1,17 @@ +<?xml version="1.0" ?> +<!DOCTYPE plugin-properties SYSTEM "/usr/etc/tizen-apis/config.dtd"> +<plugin-properties> + <library-name>libwrt-plugins-tizen-content.so</library-name> + <feature-install-uri>content.install.uri</feature-install-uri> + + <api-feature> + <name>http://tizen.org/privilege/content.read</name> + <device-capability>content.read</device-capability> + </api-feature> + + <api-feature> + <name>http://tizen.org/privilege/content.write</name> + <device-capability>content.write</device-capability> + </api-feature> + +</plugin-properties> diff --git a/wearable_src/Content/plugin_config.cpp b/wearable_src/Content/plugin_config.cpp new file mode 100755 index 0000000..fd7c673 --- /dev/null +++ b/wearable_src/Content/plugin_config.cpp @@ -0,0 +1,170 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <Commons/FunctionDefinition.h> +#include <Commons/FunctionDeclaration.h> +#include <iostream> +#include <Commons/Exception.h> +#include <dpl/exception.h> +#include <map> + +#include "plugin_config.h" + +#define CONTENT_FEATURE_API_READ "http://tizen.org/privilege/content.read" +#define CONTENT_FEATURE_API_WRITE "http://tizen.org/privilege/content.write" + +#define CONTENT_DEVICE_CAP_READ "content.read" +#define CONTENT_DEVICE_CAP_WRITE "content.write" + + +using namespace WrtDeviceApis::Commons; + +namespace DeviceAPI { +namespace Content { + +static FunctionMapping createContentFunctions(); + +static FunctionMapping ContentFunctions = createContentFunctions(); + +#pragma GCC visibility push(default) + +DEFINE_FUNCTION_GETTER(Content, ContentFunctions); + +#pragma GCC visibility pop + +static FunctionMapping createContentFunctions() +{ + /** + * Device capabilities + */ + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_CONTENT_READ, CONTENT_DEVICE_CAP_READ); + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_CONTENT_WRITE, CONTENT_DEVICE_CAP_WRITE); + + ACE_CREATE_DEVICE_CAPS_LIST(EMPTY_DEVICE_LIST); + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_CONTENT_READ); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_CONTENT_READ, DEVICE_CAP_CONTENT_READ); + + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_CONTENT_WRITE); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_CONTENT_WRITE, DEVICE_CAP_CONTENT_WRITE); + + /** + * Api Features + */ + ACE_CREATE_FEATURE(FEATURE_CONTENT_READ, CONTENT_FEATURE_API_READ); + ACE_CREATE_FEATURE(FEATURE_CONTENT_WRITE, CONTENT_FEATURE_API_WRITE); + + ACE_CREATE_FEATURE_LIST(CONTENT_FEATURES_CONTENT_READ_WRITE); + ACE_ADD_API_FEATURE(CONTENT_FEATURES_CONTENT_READ_WRITE, FEATURE_CONTENT_READ); + ACE_ADD_API_FEATURE(CONTENT_FEATURES_CONTENT_READ_WRITE, FEATURE_CONTENT_WRITE); + + ACE_CREATE_FEATURE_LIST(CONTENT_FEATURES_CONTENT_READ); + ACE_ADD_API_FEATURE(CONTENT_FEATURES_CONTENT_READ, FEATURE_CONTENT_READ); + + ACE_CREATE_FEATURE_LIST(CONTENT_FEATURES_CONTENT_WRITE); + ACE_ADD_API_FEATURE(CONTENT_FEATURES_CONTENT_WRITE, FEATURE_CONTENT_WRITE); + + /** + * Functions + */ + FunctionMapping contentMapping; + + //"getLocalMediaSource" + AceFunction getLocalMediaSourceFunc = ACE_CREATE_FUNCTION( + FUNCTION_GET_LOCAL_MEDIA_SOURCE, + CONTENT_FUNCTION_API_GET_LOCAL_MEDIASOURCE, + CONTENT_FEATURES_CONTENT_READ_WRITE, + DEVICE_LIST_CONTENT_READ); + + contentMapping.insert(std::make_pair( + CONTENT_FUNCTION_API_GET_LOCAL_MEDIASOURCE, + getLocalMediaSourceFunc)); + + + //findItems + AceFunction findItemsFunc = ACE_CREATE_FUNCTION( + FUNCTION_FIND_ITEMS, + CONTENT_FUNCTION_API_FIND_ITEMS, + CONTENT_FEATURES_CONTENT_READ, + DEVICE_LIST_CONTENT_READ); + + contentMapping.insert(std::make_pair( + CONTENT_FUNCTION_API_FIND_ITEMS, + findItemsFunc)); + + + //updateItem + AceFunction updateItemFunc = ACE_CREATE_FUNCTION( + FUNCTION_UPDATE_ITEM, + CONTENT_FUNCTION_API_UPDATE_ITEM, + CONTENT_FEATURES_CONTENT_WRITE, + DEVICE_LIST_CONTENT_WRITE); + + contentMapping.insert(std::make_pair( + CONTENT_FUNCTION_API_UPDATE_ITEM, + updateItemFunc)); + + //updateItemsBatch + AceFunction updateItemsBatchFunc = ACE_CREATE_FUNCTION( + FUNCTION_UPDATE_ITEMS_BATCH, + CONTENT_FUNCTION_API_UPDATE_ITEMS_BATCH, + CONTENT_FEATURES_CONTENT_WRITE, + DEVICE_LIST_CONTENT_WRITE); + + contentMapping.insert(std::make_pair( + CONTENT_FUNCTION_API_UPDATE_ITEMS_BATCH, + updateItemsBatchFunc)); + + //scanFile + AceFunction scanFileFunc = ACE_CREATE_FUNCTION( + FUNCTION_SCAN_FILE, + CONTENT_FUNCTION_API_SCAN_FILE, + CONTENT_FEATURES_CONTENT_WRITE, + DEVICE_LIST_CONTENT_WRITE); + + contentMapping.insert(std::make_pair( + CONTENT_FUNCTION_API_SCAN_FILE, + scanFileFunc)); + + //setChangeListener + AceFunction setListenerFunc = ACE_CREATE_FUNCTION( + FUNCTION_SET_CHANGE_LISTENER, + CONTENT_FUNCTION_API_SET_CHANGE_LISTENER, + CONTENT_FEATURES_CONTENT_READ, + DEVICE_LIST_CONTENT_READ); + + contentMapping.insert(std::make_pair( + CONTENT_FUNCTION_API_SET_CHANGE_LISTENER, + setListenerFunc)); + + //unsetChangeListener + AceFunction unsetListenerFunc = ACE_CREATE_FUNCTION( + FUNCTION_UNSET_CHANGE_LISTENER, + CONTENT_FUNCTION_API_UNSET_CHANGE_LISTENER, + CONTENT_FEATURES_CONTENT_READ, + DEVICE_LIST_CONTENT_READ); + + contentMapping.insert(std::make_pair( + CONTENT_FUNCTION_API_UNSET_CHANGE_LISTENER, + unsetListenerFunc)); + + + return contentMapping; +} + +} +} diff --git a/wearable_src/Content/plugin_config.h b/wearable_src/Content/plugin_config.h new file mode 100755 index 0000000..6eb9188 --- /dev/null +++ b/wearable_src/Content/plugin_config.h @@ -0,0 +1,53 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _CONTENT_PLUGIN_CONFIG_H_ +#define _CONTENT_PLUGIN_CONFIG_H_ + +#include <string> +#include <Commons/FunctionDeclaration.h> + +namespace DeviceAPI { +namespace Content { + +// Functions from content manager +#define CONTENT_FUNCTION_API_GET_LOCAL_MEDIASOURCE "getLocalMediaSource" + +// Functions from content +#define CONTENT_FUNCTION_API_FIND_ITEMS "find" +#define CONTENT_FUNCTION_API_GET_FOLDERS "getDirectories" +#define CONTENT_FUNCTION_API_UPDATE_ITEM "update" +#define CONTENT_FUNCTION_API_UPDATE_ITEMS_BATCH "updateBatch" +#define CONTENT_FUNCTION_API_SCAN_FILE "scanFile" +#define CONTENT_FUNCTION_API_SET_CHANGE_LISTENER "setChangeListener" +#define CONTENT_FUNCTION_API_UNSET_CHANGE_LISTENER "unsetChangeListener" + + +DECLARE_FUNCTION_GETTER(Content); + +#define CONTENT_CHECK_ACCESS(functionName) \ + WrtDeviceApis::Commons::aceCheckAccess<AceFunctionGetter, \ + WrtDeviceApis::Commons::DefaultArgsVerifier<> >( \ + getContentFunctionData, \ + functionName) + + +} +} + +#endif // _CONTENT_PLUGIN_CONFIG_H_ diff --git a/wearable_src/Content/plugin_initializer.cpp b/wearable_src/Content/plugin_initializer.cpp new file mode 100755 index 0000000..44ac0e9 --- /dev/null +++ b/wearable_src/Content/plugin_initializer.cpp @@ -0,0 +1,93 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <Commons/plugin_initializer_def.h> +#include <Commons/WrtAccess/WrtAccess.h> +#include <Commons/Exception.h> +#include <GlobalContextManager.h> +#include <TimeTracer.h> + +#include "JSContentManager.h" +#include "ContentAsyncCallbackManager.h" +#include <Logger.h> + +using namespace DeviceAPI::Common; +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace DeviceAPI { +namespace Content { + +void on_frame_load_callback(const void * context) +{ + LoggerD("[Tizen\\content] on_frame_load_callback (" << context << ")"); + GlobalContextManager::getInstance()->addGlobalContext(static_cast<JSContextRef>(context)); +} + +void on_frame_unload_callback(const void * context) +{ + LoggerD("[Tizen\\content] on_frame_unload_callback (" << context << ")"); + GlobalContextManager::getInstance()->removeGlobalContext(static_cast<JSContextRef>(context)); + MediaContentAsyncCallbackManagerSingleton::Instance().unregisterContext(static_cast<JSContextRef>(context)); +} + +void on_widget_start_callback(int widgetId) +{ + LoggerD("[Tizen\\content] on_widget_start_callback (" << widgetId << ")"); + TIME_TRACER_INIT(); + + Try + { + WrtAccessSingleton::Instance().initialize(widgetId); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LoggerE("WrtAccess intialization failed"); + } + +} + +void on_widget_stop_callback(int widgetId) +{ + LoggerD("[Tizen\\content] on_widget_stop_callback (" << widgetId << ")"); + TIME_TRACER_EXPORT_REPORT_TO(TIME_TRACER_EXPORT_FILE,"Content"); + TIME_TRACER_RELEASE(); + Try + { + WrtAccessSingleton::Instance().deinitialize(widgetId); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LoggerE("WrtAccess deinitialization failed"); + } +} + +PLUGIN_ON_WIDGET_START(on_widget_start_callback) +PLUGIN_ON_WIDGET_STOP(on_widget_stop_callback) +PLUGIN_ON_FRAME_LOAD(on_frame_load_callback) +PLUGIN_ON_FRAME_UNLOAD(on_frame_unload_callback) + +PLUGIN_CLASS_MAP_BEGIN +PLUGIN_CLASS_MAP_ADD_CLASS(WRT_JS_EXTENSION_OBJECT_TIZEN, + "content", + (js_class_template_getter)JSMediacontentManager::getClassRef, + NULL) +PLUGIN_CLASS_MAP_END + +} +} diff --git a/wearable_src/Filesystem/CMakeLists.txt b/wearable_src/Filesystem/CMakeLists.txt new file mode 100755 index 0000000..3b67e79 --- /dev/null +++ b/wearable_src/Filesystem/CMakeLists.txt @@ -0,0 +1,95 @@ +SET(TARGET_NAME ${filesystem_target}) +SET(DESTINATION_NAME ${filesystem_dest}) +SET(TARGET_IMPL_NAME ${filesystem_impl}) +SET(TARGET_CONFIG_NAME ${filesystem_config}) + +PKG_CHECK_MODULES(platform_pkgs_filesystem REQUIRED capi-appfw-application libpcrecpp ecore) + +ADD_DEFINITIONS("-fvisibility=hidden") + +INCLUDE_DIRECTORIES( + ${INCLUDE_COMMON} + ${platform_pkgs_filesystem_INCLUDE_DIRS} +) + +SET(CMAKE_INSTALL_RPATH + ${CMAKE_INSTALL_RPATH} + ${CMAKE_INSTALL_PREFIX}/${DESTINATION_LIB_PREFIX}/${tizen_dest} + ${CMAKE_INSTALL_PREFIX}/${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME} +) + +SET(SRCS_IMPL + IManager.cpp + IPath.cpp + IStream.cpp + EventResolve.cpp + EventGetStorage.cpp + EventListStorages.cpp + EventCopy.cpp + EventMove.cpp + EventRemove.cpp + EventFind.cpp + EventListNodes.cpp + EventOpen.cpp + EventReadText.cpp + INode.cpp + NodeFilter.cpp + PathUtils.cpp + StorageProperties.cpp + EventStoragestateChanged.cpp + Manager.cpp + Node.cpp + Path.cpp + Stream.cpp + NodeFilterMatcher.cpp + Utils.cpp + JSFilesystemManager.cpp + JSFile.cpp + JSFilestream.cpp + JSStorage.cpp + Converter.cpp + EventGetNodeData.cpp + Encodings.cpp + StorageStaticController.cpp + FilesystemUtils.cpp + ResponseDispatcher.cpp + FilesystemAsyncCallbackManager.cpp + FilesystemListenerManager.cpp +) + +ADD_LIBRARY(${TARGET_IMPL_NAME} SHARED ${SRCS_IMPL}) + +TARGET_LINK_LIBRARIES(${TARGET_IMPL_NAME} + ${LIBS_COMMON} + ${LIBS_WIDGETDB} + ${tizen_impl} + ${platform_pkgs_filesystem_LIBRARIES} +) + +SET(SRCS_CONFIG + plugin_config.cpp +) + +ADD_LIBRARY(${TARGET_CONFIG_NAME} SHARED ${SRCS_CONFIG}) + +TARGET_LINK_LIBRARIES(${TARGET_CONFIG_NAME} + ${LIBS_COMMON} +) + +SET(SRCS + plugin_initializer.cpp +) + +ADD_LIBRARY(${TARGET_NAME} SHARED ${SRCS}) + +TARGET_LINK_LIBRARIES(${TARGET_NAME} + ${TARGET_IMPL_NAME} + ${TARGET_CONFIG_NAME} +) + +INSTALL(TARGETS ${TARGET_NAME} ${TARGET_CONFIG_NAME} ${TARGET_IMPL_NAME} LIBRARY DESTINATION ${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME}) +INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/config.xml DESTINATION ${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME}) +INSTALL( + DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/ DESTINATION ${DESTINATION_HEADER_PREFIX}/filesystem + FILES_MATCHING PATTERN "*.h" PATTERN "CMakeFiles" EXCLUDE +) diff --git a/wearable_src/Filesystem/Converter.cpp b/wearable_src/Filesystem/Converter.cpp new file mode 100755 index 0000000..d604dcc --- /dev/null +++ b/wearable_src/Filesystem/Converter.cpp @@ -0,0 +1,346 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "IManager.h" +#include "IPath.h" +#include <Commons/Exception.h> +#include <CommonsJavaScript/JSUtils.h> +#include <CommonsJavaScript/ScopedJSStringRef.h> +#include "FilesystemUtils.h" +#include "JSFile.h" +#include "Encodings.h" +#include "JSStorage.h" +#include <Logger.h> + +namespace { +const char* PROPERTY_FILEFILTER_NAME = "name"; +const char* PROPERTY_FILEFILTER_START_CREATED = "startCreated"; +const char* PROPERTY_FILEFILTER_END_CREATED = "endCreated"; +const char* PROPERTY_FILEFILTER_START_MODIFIED = "startModified"; +const char* PROPERTY_FILEFILTER_END_MODIFIED = "endModified"; +const char* ACCESS_MODE_READ = "r"; +const char* ACCESS_MODE_APPEND = "a"; +const char* ACCESS_MODE_WRITE = "w"; +const char* ACCESS_MODE_READ_WRITE = "rw"; +const char* STORAGE_TYPE_STATE_MOUNTED = "MOUNTED"; +const char* STORAGE_TYPE_STATE_REMOVED = "REMOVED"; +const char* STORAGE_TYPE_STATE_UNMOUNTABLE = "REMOVED"; +const char* STORAGE_TYPE_INTERNAL = "INTERNAL"; +const char* STORAGE_TYPE_EXTERNAL = "EXTERNAL"; + + +const char* ENCODINGS[] = { + DeviceAPI::Filesystem::Encodings::UTF8, + DeviceAPI::Filesystem::Encodings::ISO88591, + DeviceAPI::Filesystem::Encodings::SJIS, + NULL +}; +} // namespace + +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace DeviceAPI { +namespace Filesystem{ +Converter::Converter(JSContextRef context) : WrtDeviceApis::CommonsJavaScript::Converter(context) +{ +} + +JSValueRef Converter::toJSValueRef( + const NodeList& arg, + const JSFile::PrivateObjectDef::PermissionList &parentPermissions, + JSContextRef context) +{ + JSObjectRef jsResult = JSCreateArrayObject(m_context, 0, NULL); + if (!jsResult) { + ThrowMsg(Commons::ConversionException, + "Could not create js array object"); + } + + for (std::size_t i = 0; i < arg.size(); ++i) + { + JSFile::PrivateObjectDefPtr privData( + new JSFile::PrivateObjectDef( + arg[i], + parentPermissions)); + JSFile::PrivateObject* privateObject = new JSFile::PrivateObject( + context, + privData); + JSObjectRef jsObject = JSObjectMake(m_context, + JSFile::getClassRef(), + privateObject); + if (!jsObject) { + delete privateObject; + ThrowMsg(Commons::ConversionException, + "Could not create JS object."); + } + if (!JSSetArrayElement(m_context, jsResult, i, jsObject)) { + ThrowMsg(Commons::ConversionException, + "Could not insert value into js array"); + } + } + + return jsResult; +} + + +JSValueRef Converter::toJSValueRef(unsigned char* data, std::size_t num) +{ + JSObjectRef result = JSCreateArrayObject(m_context, 0, NULL); + if (!result) { + ThrowMsg(Commons::ConversionException, "Could not create array object."); + } + + for (std::size_t i = 0; i < num; ++i) { + JSValueRef value = JSValueMakeNumber(m_context, data[i]); + if (!JSSetArrayElement(m_context, result, i, value)) { + ThrowMsg(Commons::ConversionException, "Could not fill array."); + } + } + + return result; +} + +JSValueRef Converter::toJSValueRef(unsigned long long arg) +{ + return JSValueMakeNumber(m_context, arg); +} + + + +IPathPtr Converter::toPath(const JSValueRef& arg) +{ + Try { + std::string path = toString(arg); + if (!Utils::isPathValid(path)) { + ThrowMsg(Commons::InvalidArgumentException, "Invalid path component."); + } + return IPath::create(path); + } Catch (Commons::ConversionException) { + ReThrowMsg(Commons::ConversionException, "Not a valid path."); + } +} +std::string Converter::checkPercentSign(std::string& arg) +{ + size_t pos = 0; + + pos = arg.find("%"); + + if (pos == std::string::npos) + { + return arg; + } + else if (arg[arg.size() - 1] == '%') + { + arg[arg.size() - 1] = ')'; + + if (arg[0] == '%') + { + arg[0] = '('; + } + else + { + arg.insert(0, "^"); + arg.insert(1, "("); + } + + return arg; + } + ThrowMsg(Commons::ConversionException, "Invalid Filter"); +} + +NodeFilterPtr Converter::toNodeFilter(const JSValueRef& arg) +{ + JSObjectRef filter = toJSObjectRef(arg); + + NodeFilterPtr result(new NodeFilter()); + JSValueRef prop = NULL; + + result->setFilterValid(false); + + prop = JSUtils::getJSProperty(m_context, filter, PROPERTY_FILEFILTER_NAME); + if (prop) { + std::string nameFilter = toString(prop); + result->setName(checkPercentSign(nameFilter)); + result->setFilterValid(true); + } + + prop = JSUtils::getJSProperty(m_context, filter, PROPERTY_FILEFILTER_START_CREATED); + if (prop) { + result->setMinCreated(toDateTimeT(prop)); + result->setFilterValid(true); + } + + prop = JSUtils::getJSProperty(m_context, filter, PROPERTY_FILEFILTER_END_CREATED); + if (prop) { + result->setMaxCreated(toDateTimeT(prop)); + result->setFilterValid(true); + } + + prop = JSUtils::getJSProperty(m_context, filter, PROPERTY_FILEFILTER_START_MODIFIED); + if (prop) { + result->setMinModified(toDateTimeT(prop)); + result->setFilterValid(true); + } + + prop = JSUtils::getJSProperty(m_context, filter, PROPERTY_FILEFILTER_END_MODIFIED); + if (prop) { + result->setMaxModified(toDateTimeT(prop)); + result->setFilterValid(true); + } + + return result; +} + +AccessMode Converter::toAccessMode(const JSValueRef& arg) +{ + std::string mode = toString_(arg); + if (ACCESS_MODE_READ == mode) { + return AM_READ; + } else if (ACCESS_MODE_APPEND == mode) { + return AM_APPEND; + } else if (ACCESS_MODE_WRITE == mode) { + return AM_WRITE; + } else if (ACCESS_MODE_READ_WRITE == mode) { + return AM_READ_WRITE; + } + + ThrowMsg(Commons::ConversionException, "Invalid mode."); +} + +std::string Converter::toEncoding(const JSValueRef& arg) +{ + std::string result = toString_(arg); + const char** ptr = ENCODINGS; + while (*ptr) { + if (result == *ptr) { + return result; + } + ++ptr; + } + ThrowMsg(Commons::ConversionException, "Invalid encoding"); +} +JSValueRef Converter::toStorageState(const short type) +{ + switch (type) + { + case JSStorage::STATE_MOUNTED: + return toJSValueRef(STORAGE_TYPE_STATE_MOUNTED); + case JSStorage::STATE_REMOVED: + return toJSValueRef(STORAGE_TYPE_STATE_REMOVED); + case JSStorage::STATE_UNMOUNTABLE: + return toJSValueRef(STORAGE_TYPE_STATE_UNMOUNTABLE); + } + ThrowMsg(Commons::ConversionException, "Invalid storage type"); +} + +JSValueRef Converter::toStorageType(const short state) +{ + switch (state) + { + case StorageProperties::TYPE_INTERNAL: + return toJSValueRef(STORAGE_TYPE_INTERNAL); + case StorageProperties::TYPE_EXTERNAL: + return toJSValueRef(STORAGE_TYPE_EXTERNAL); + } + ThrowMsg(Commons::ConversionException, "Invalid storage state"); +} + +JSValueRef Converter::toJSValueRef( + const StoragePropertiesPtr &arg, + JSContextRef context) +{ + StorageProperties tmpStorage; + + tmpStorage.setLabel(arg->getLabel()); + tmpStorage.setType(arg->getType()); + + switch (arg->getState()) { + case StorageProperties::STATE_MOUNTED : + case StorageProperties::STATE_MOUNTED_READONLY : + tmpStorage.setState(JSStorage::STATE_MOUNTED); + break; + case StorageProperties::STATE_REMOVED: + tmpStorage.setState(JSStorage::STATE_REMOVED); + break; + case StorageProperties::STATE_UNMOUNTABLE: + tmpStorage.setState(JSStorage::STATE_UNMOUNTABLE); + break; + } + + JSObjectRef jsObject = JSStorage::createJSObject(context, tmpStorage); + if (!jsObject) { + ThrowMsg(Commons::ConversionException, "Could not create JS object."); + } + + return toJSValueRef(jsObject); +} + +JSValueRef Converter::toJSValueRef( + const std::vector<StoragePropertiesPtr>& arg, + JSContextRef context) +{ + JSObjectRef jsResult = JSCreateArrayObject(m_context, 0, NULL); + if (!jsResult) { + ThrowMsg(Commons::ConversionException, "Could not create js array object"); + } + + StorageProperties tmpStorage; + + for (size_t i = 0; i < arg.size(); i++) { + tmpStorage.setLabel(arg[i]->getLabel()); + tmpStorage.setType(arg[i]->getType()); + + switch (arg[i]->getState()) { + case StorageProperties::STATE_MOUNTED : + case StorageProperties::STATE_MOUNTED_READONLY : + tmpStorage.setState(JSStorage::STATE_MOUNTED); + break; + case StorageProperties::STATE_REMOVED: + tmpStorage.setState(JSStorage::STATE_REMOVED); + break; + case StorageProperties::STATE_UNMOUNTABLE: + tmpStorage.setState(JSStorage::STATE_UNMOUNTABLE); + break; + } + + JSObjectRef jsObject = JSObjectMake(m_context, NULL, NULL); + const ScopedJSStringRef labelStr(JSStringCreateWithUTF8CString("label")); + const ScopedJSStringRef typeStr(JSStringCreateWithUTF8CString("type")); + const ScopedJSStringRef stateStr(JSStringCreateWithUTF8CString("state")); + + JSObjectSetProperty(m_context, jsObject, labelStr.get(), toJSValueRef(tmpStorage.getLabel()), kJSPropertyAttributeReadOnly, NULL); + JSObjectSetProperty(m_context, jsObject, typeStr.get(), toStorageType(tmpStorage.getType()), kJSPropertyAttributeReadOnly, NULL); + JSObjectSetProperty(m_context, jsObject, stateStr.get(), toStorageState(tmpStorage.getState()), kJSPropertyAttributeReadOnly, NULL); + + if (!jsObject) { + ThrowMsg(Commons::ConversionException, "Could not create JS object."); + } + + if (!JSSetArrayElement(m_context, jsResult, i, jsObject)) { + ThrowMsg(Commons::ConversionException, "Could not insert value into js array"); + } + } + + return jsResult; +} +} +} diff --git a/wearable_src/Filesystem/Converter.h b/wearable_src/Filesystem/Converter.h new file mode 100755 index 0000000..70bd4cb --- /dev/null +++ b/wearable_src/Filesystem/Converter.h @@ -0,0 +1,79 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 TIZENAPIS_TIZEN_FILESYSTEM_CONVERTER_H_ +#define TIZENAPIS_TIZEN_FILESYSTEM_CONVERTER_H_ + +#include <vector> +#include <string> +#include <map> +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/Converter.h> +#include "Enums.h" +#include "IPath.h" +#include "INodeTypes.h" +#include "NodeFilter.h" +#include "StorageProperties.h" +#include "JSFile.h" + +namespace DeviceAPI { +namespace Filesystem { +class Converter : public WrtDeviceApis::CommonsJavaScript::Converter +{ +public: + using WrtDeviceApis::CommonsJavaScript::Converter::toJSValueRef; + +public: + explicit Converter(JSContextRef context); + + + + JSValueRef toJSValueRef( + const NodeList& arg, + const JSFile::PrivateObjectDef::PermissionList &parentPermissions, + JSContextRef context); + JSValueRef toJSValueRef(unsigned char* data, + std::size_t num); + JSValueRef toJSValueRef(unsigned long long arg); + + IPathPtr toPath(const JSValueRef& arg); + + NodeFilterPtr toNodeFilter(const JSValueRef& arg); + + AccessMode toAccessMode(const JSValueRef& arg); + + std::string toEncoding(const JSValueRef& arg); + + JSValueRef toStorageType(const short type); + JSValueRef toStorageState(const short state); + std::string checkPercentSign(std::string& arg); + JSValueRef toJSValueRef( + const StoragePropertiesPtr &arg, + JSContextRef context); + + JSValueRef toJSValueRef( + const std::vector<StoragePropertiesPtr>& arg, + JSContextRef context); +}; + +typedef WrtDeviceApis::CommonsJavaScript::ConverterFactory<Converter> ConverterFactory; +typedef ConverterFactory::ConverterType ConverterPtr; +} +} + +#endif diff --git a/wearable_src/Filesystem/Encodings.cpp b/wearable_src/Filesystem/Encodings.cpp new file mode 100755 index 0000000..ac993d3 --- /dev/null +++ b/wearable_src/Filesystem/Encodings.cpp @@ -0,0 +1,30 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "Encodings.h" + +namespace DeviceAPI { +namespace Filesystem { +namespace Encodings { +const char* UTF8 = "UTF-8"; + +const char* ISO88591 = "ISO-8859-1"; +const char* SJIS = "SJIS"; +} +} +} diff --git a/wearable_src/Filesystem/Encodings.h b/wearable_src/Filesystem/Encodings.h new file mode 100755 index 0000000..4425efa --- /dev/null +++ b/wearable_src/Filesystem/Encodings.h @@ -0,0 +1,33 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 TIZENAPIS_TIZEN_FILESYSTEM_ENCODINGS_H_ +#define TIZENAPIS_TIZEN_FILESYSTEM_ENCODINGS_H_ + +namespace DeviceAPI { +namespace Filesystem { +namespace Encodings { +extern const char* UTF8; + +extern const char* ISO88591; +extern const char* SJIS; +} +} +} + +#endif
\ No newline at end of file diff --git a/wearable_src/Filesystem/Enums.h b/wearable_src/Filesystem/Enums.h new file mode 100755 index 0000000..23351f6 --- /dev/null +++ b/wearable_src/Filesystem/Enums.h @@ -0,0 +1,113 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 TIZENAPIS_FILESYSTEM_ENUMS_H_ +#define TIZENAPIS_FILESYSTEM_ENUMS_H_ + +#include <string> +#include <map> + +namespace DeviceAPI { +namespace Filesystem { +enum LocationType +{ + LT_APPS, + LT_DOCUMENTS, + LT_DOWNLOADS, + LT_GAMES, + LT_IMAGES, + LT_OTHERS, + LT_ROOT, + LT_SDCARD, + LT_USBHOST, + LT_SOUNDS, + LT_TEMP, + LT_VIDEOS, + LT_RINGTONES, + LT_WGTPKG, + LT_WGTPRV, + LT_WGTPRVTMP +}; + +enum NodeType +{ + NT_DIRECTORY, + NT_FILE +}; + +enum AccessMode +{ + AM_READ = 0x0001, + AM_WRITE = 0x0002, + AM_READ_WRITE = 0x0003, + AM_APPEND = 0x0004 + + +}; + +/** + * Used in @see IManager::access(). + */ +enum AccessType +{ + AT_EXISTS = 0x0000, //!< AT_EXISTS - checks for existence + AT_READ = 0x0001, //!< AT_READ - checks for read access + AT_WRITE = 0x0002, //!< AT_WRITE - checks for write access + AT_EXEC = 0x0004 //!< AT_EXEC - checks for execution access +}; + +enum Permissions +{ + PERM_NONE = 0x0000, + PERM_READ = 0x0001, + PERM_WRITE = 0x0002 +}; + +enum PlatformMode +{ + PM_USER_READ = 0x0100, + PM_USER_WRITE = 0x0080, + PM_USER_EXEC = 0x0040, + PM_GROUP_READ = 0x0020, + PM_GROUP_WRITE = 0x0010, + PM_GROUP_EXEC = 0x0008, + PM_OTHER_READ = 0x0004, + PM_OTHER_WRITE = 0x0002, + PM_OTHER_EXEC = 0x0001, + PM_NONE = 0x0000 +}; + +enum Options +{ + OPT_NONE = 0x0000, + OPT_OVERWRITE = 0x0001, + OPT_RECURSIVE = 0x0002 +}; + +enum FindFilter +{ + FF_NAME, + FF_CREATED, + FF_MODIFIED, + FF_SIZE +}; +typedef std::map<FindFilter, std::string> FiltersMap; +} // Filesystem +} // TizenApis + +#endif /* TIZENAPIS_FILESYSTEM_ENUMS_H_ */ diff --git a/wearable_src/Filesystem/EventCopy.cpp b/wearable_src/Filesystem/EventCopy.cpp new file mode 100755 index 0000000..cfe7346 --- /dev/null +++ b/wearable_src/Filesystem/EventCopy.cpp @@ -0,0 +1,62 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "EventCopy.h" + + +namespace DeviceAPI { +namespace Filesystem { +EventCopy::EventCopy(const IPathPtr& src, + const IPathPtr& dest) : + m_src(src), + m_dest(dest), + m_options(OPT_NONE) +{ +} + +IPathPtr EventCopy::getDestination() const +{ + return m_dest; +} + +IPathPtr EventCopy::getSource() const +{ + return m_src; +} + +INodePtr EventCopy::getResult() const +{ + return m_result; +} + +void EventCopy::setResult(const INodePtr& node) +{ + m_result = node; +} + +int EventCopy::getOptions() const +{ + return m_options; +} + +void EventCopy::setOptions(int options) +{ + m_options = options; +} +} // Filesystem +} // TizenApis
\ No newline at end of file diff --git a/wearable_src/Filesystem/EventCopy.h b/wearable_src/Filesystem/EventCopy.h new file mode 100755 index 0000000..bd12cfb --- /dev/null +++ b/wearable_src/Filesystem/EventCopy.h @@ -0,0 +1,88 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 TIZENAPIS_FILESYSTEM_EVENTCOPY_H_ +#define TIZENAPIS_FILESYSTEM_EVENTCOPY_H_ + +#include <dpl/shared_ptr.h> +#include <Commons/IEvent.h> +#include "IPath.h" +#include "INode.h" + +namespace DeviceAPI { +namespace Filesystem { +class EventCopy : public WrtDeviceApis::Commons::IEvent<EventCopy> +{ + public: + /** + * Creates new event object. + * @param src Path to source node. + * @param dest Path to destination node. + * @return New object. + */ + EventCopy(const IPathPtr& src, + const IPathPtr& dest); + + /** + * Gets destination path. + * @return Destination path. + */ + IPathPtr getDestination() const; + + /** + * Gets source path. + * @return Source path. + */ + IPathPtr getSource() const; + + /** + * Gets result node. + * @return Result node. + */ + INodePtr getResult() const; + + /** + * Sets result node. + * @param node Result node. + */ + void setResult(const INodePtr& node); + + /** + * Gets options. + * @return Options. + */ + int getOptions() const; + + /** + * Sets options. + * @param options Options. + */ + void setOptions(int options); + + private: + IPathPtr m_src; ///< Source path. + IPathPtr m_dest; ///< Destination path. + INodePtr m_result; ///< Result node. + int m_options; ///< Options for copy action @see WrtPlugins::Api::Filesystem::Options. +}; + +typedef DPL::SharedPtr<EventCopy> EventCopyPtr; +} // Filesystem +} // TizenApis + +#endif // TIZENAPIS_FILESYSTEM_EVENTCOPY_H_ diff --git a/wearable_src/Filesystem/EventCreate.cpp b/wearable_src/Filesystem/EventCreate.cpp new file mode 100755 index 0000000..343a394 --- /dev/null +++ b/wearable_src/Filesystem/EventCreate.cpp @@ -0,0 +1,52 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "EventCreate.h" + + +namespace DeviceAPI { +namespace Filesystem { +EventCreate::EventCreate(const IPathPtr& path, + NodeType type) : + m_path(path), + m_type(type), + m_options(OPT_NONE) +{ +} + +IPathPtr EventCreate::getPath() const +{ + return m_path; +} + +NodeType EventCreate::getType() const +{ + return m_type; +} + +int EventCreate::getOptions() const +{ + return m_options; +} + +void EventCreate::setOptions(int options) +{ + m_options = options; +} +} // Filesystem +} // TizenApis
\ No newline at end of file diff --git a/wearable_src/Filesystem/EventCreate.h b/wearable_src/Filesystem/EventCreate.h new file mode 100755 index 0000000..9509dba --- /dev/null +++ b/wearable_src/Filesystem/EventCreate.h @@ -0,0 +1,75 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 TIZENAPIS_FILESYSTEM_EVENTCREATE_H_ +#define TIZENAPIS_FILESYSTEM_EVENTCREATE_H_ + +#include <dpl/shared_ptr.h> +#include <Commons/IEvent.h> +#include "IPath.h" +#include "Enums.h" + +namespace DeviceAPI { +namespace Filesystem { +class EventCreate : public WrtDeviceApis::Commons::IEvent<EventCreate> +{ + public: + /** + * Creates new event object. + * @param path Path to node to create. + * @param type Type of node to create. + * @return New object. + */ + EventCreate(const IPathPtr& path, + NodeType type); + + /** + * Gets path to the node. + * @return Path to node. + */ + IPathPtr getPath() const; + + /** + * Gets type of the node. + * @return Type of node. + */ + NodeType getType() const; + + /** + * Gets options. + * @return Options. + */ + int getOptions() const; + + /** + * Sets options. + * @param options Options. + */ + void setOptions(int options); + + private: + IPathPtr m_path; ///< Path to node to create. + NodeType m_type; ///< Type of the node. + int m_options; ///< Options for create action @see WrtPlugins::Api::Filesystem::Options. +}; + +typedef DPL::SharedPtr<EventCreate> EventCreatePtr; +} // Filesystem +} // TizenApis + +#endif // TIZENAPIS_FILESYSTEM_EVENTCREATE_H_
\ No newline at end of file diff --git a/wearable_src/Filesystem/EventFind.cpp b/wearable_src/Filesystem/EventFind.cpp new file mode 100755 index 0000000..eb457e8 --- /dev/null +++ b/wearable_src/Filesystem/EventFind.cpp @@ -0,0 +1,61 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "EventFind.h" + +#include "Path.h" +#include "INode.h" + +namespace DeviceAPI { +namespace Filesystem { +EventFind::EventFind(const IPathPtr& path) : m_path(path) +{ +} + +IPathPtr EventFind::getPath() const +{ + return m_path; +} + +NodeList EventFind::getResult() const +{ + return m_nodes; +} + +void EventFind::addResult(const INodePtr& node) +{ + m_nodes.push_back(node); +} + +void EventFind::setResult(const NodeList& nodes) +{ + m_nodes = nodes; +} + +void EventFind::addFilter(FindFilter name, + const std::string& value) +{ + m_filters.insert(std::pair<FindFilter, std::string>(name, value)); +} + +FiltersMap EventFind::getFilters() const +{ + return m_filters; +} +} // Filesystem +} // TizenApis
\ No newline at end of file diff --git a/wearable_src/Filesystem/EventFind.h b/wearable_src/Filesystem/EventFind.h new file mode 100755 index 0000000..98f2856 --- /dev/null +++ b/wearable_src/Filesystem/EventFind.h @@ -0,0 +1,89 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 TIZENAPIS_IEVENTFILESYSTEMFIND_H_ +#define TIZENAPIS_IEVENTFILESYSTEMFIND_H_ + +#include <list> +#include <dpl/shared_ptr.h> +#include <Commons/IEvent.h> +#include "IPath.h" +#include "INodeTypes.h" +#include "Enums.h" + +namespace DeviceAPI { +namespace Filesystem { +class EventFind : public WrtDeviceApis::Commons::IEvent<EventFind> +{ + public: + /** + * Creates new event object. + * @param path Start path. + * @return New object. + */ + explicit EventFind(const IPathPtr& path); + + /** + * Gets start path. + * @return Path to start searching from. + */ + IPathPtr getPath() const; + + /** + * Gets found nodes. + * @return Nodes. + */ + NodeList getResult() const; + + /** + * Adds found node. + * @param node Found node. + */ + void addResult(const INodePtr& node); + + /** + * Sets found nodes. + * @param nodes Nodes. + */ + void setResult(const NodeList& nodes); + + /** + * Adds find filter. + * @param name Filter name. + * @param value Filter value. + */ + void addFilter(FindFilter name, + const std::string& value); + + /** + * Gets all filters. + * @return Filters. + */ + FiltersMap getFilters() const; + + private: + IPathPtr m_path; ///< Start path. + NodeList m_nodes; ///< Resolved nodes. + FiltersMap m_filters; ///< Search filters. +}; + +typedef DPL::SharedPtr<EventFind> EventFindPtr; +} // Filesystem +} // TizenApis + +#endif /* TIZENAPIS_IEVENTFILESYSTEMFIND_H_ */ diff --git a/wearable_src/Filesystem/EventGetNodeData.cpp b/wearable_src/Filesystem/EventGetNodeData.cpp new file mode 100755 index 0000000..b1580e0 --- /dev/null +++ b/wearable_src/Filesystem/EventGetNodeData.cpp @@ -0,0 +1,41 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "EventGetNodeData.h" + +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace DeviceAPI { +namespace Filesystem { +EventGetNodeData::EventGetNodeData(int perms, JSCallbackManagerPtr callbackManager) : + m_perms(perms), + m_callbackManager(callbackManager) +{ +} + +int EventGetNodeData::getPerms() const +{ + return m_perms; +} + +JSCallbackManagerPtr EventGetNodeData::getCallbackManager() const +{ + return m_callbackManager; +} +} +} diff --git a/wearable_src/Filesystem/EventGetNodeData.h b/wearable_src/Filesystem/EventGetNodeData.h new file mode 100755 index 0000000..3aa0d90 --- /dev/null +++ b/wearable_src/Filesystem/EventGetNodeData.h @@ -0,0 +1,47 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 TIZENAPIS_TIZEN_EVENTGETNODEDATA_H_ +#define TIZENAPIS_TIZEN_EVENTGETNODEDATA_H_ + +#include <dpl/shared_ptr.h> +#include <Commons/IEvent.h> +#include <CommonsJavaScript/JSCallbackManager.h> + +namespace DeviceAPI { +namespace Filesystem { +class EventGetNodeData : public WrtDeviceApis::Commons::IEventPrivateData +{ +public: + EventGetNodeData(int perms, + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr callbackManager); + + int getPerms() const; + + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr getCallbackManager() const; + +private: + int m_perms; + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr m_callbackManager; +}; + +typedef DPL::SharedPtr<EventGetNodeData> EventGetNodeDataPtr; +} +} + +#endif
\ No newline at end of file diff --git a/wearable_src/Filesystem/EventGetStorage.cpp b/wearable_src/Filesystem/EventGetStorage.cpp new file mode 100755 index 0000000..d213b0d --- /dev/null +++ b/wearable_src/Filesystem/EventGetStorage.cpp @@ -0,0 +1,48 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "EventGetStorage.h" + +namespace DeviceAPI { +namespace Filesystem { +EventGetStorage::EventGetStorage() +{ +} + +void EventGetStorage::setLabel(const std::string &Label) +{ + label = Label; +} + +std::string EventGetStorage::getLabel() const +{ + return label; +} + +void EventGetStorage::setResult (const StoragePropertiesPtr &Storages) +{ + storages = Storages; +} + +StoragePropertiesPtr EventGetStorage::getResult() const +{ + return storages; +} + +} // Filesystem +} // TizenApis
\ No newline at end of file diff --git a/wearable_src/Filesystem/EventGetStorage.h b/wearable_src/Filesystem/EventGetStorage.h new file mode 100755 index 0000000..abd8dac --- /dev/null +++ b/wearable_src/Filesystem/EventGetStorage.h @@ -0,0 +1,47 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 TIZENAPIS_API_FILESYSTEM_EVENT_GET_STORAGE_H_ +#define TIZENAPIS_API_FILESYSTEM_EVENT_GET_STORAGE_H_ + +#include <Commons/IEvent.h> +#include <dpl/shared_ptr.h> +#include <string> +#include "StorageProperties.h" + +namespace DeviceAPI { +namespace Filesystem { +class EventGetStorage : public WrtDeviceApis::Commons::IEvent< + EventGetStorage> +{ + private: + std::string label; + StoragePropertiesPtr storages; + public: + void setLabel(const std::string &Label); + std::string getLabel() const; + void setResult (const StoragePropertiesPtr& Storages); + StoragePropertiesPtr getResult() const; + EventGetStorage(); +}; + +typedef DPL::SharedPtr<EventGetStorage> EventGetStoragePtr; +} // Filesystem +} // TizenApis + +#endif //TIZENAPIS_API_FILESYSTEM_EVENT_GET_STORAGE_H_
\ No newline at end of file diff --git a/wearable_src/Filesystem/EventListNodes.cpp b/wearable_src/Filesystem/EventListNodes.cpp new file mode 100755 index 0000000..c169442 --- /dev/null +++ b/wearable_src/Filesystem/EventListNodes.cpp @@ -0,0 +1,61 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "EventListNodes.h" +#include <Commons/Exception.h> +#include "INode.h" +#include "Enums.h" + +namespace DeviceAPI { +namespace Filesystem { +EventListNodes::EventListNodes(const INodePtr& node) : m_node(node) +{ + if (node == NULL) + { + ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Can not new an object"); + } +} + +INodePtr EventListNodes::getNode() const +{ + return m_node; +} + +NodeFilterPtr EventListNodes::getFilter() const +{ + return m_filter; +} + +void EventListNodes::setFilter(const NodeFilterPtr& filter) +{ + m_filter = filter; +} + +NodeList EventListNodes::getResult() const +{ + return m_list; +} + +void EventListNodes::setResult(const NodeList& list) +{ + m_list = list; +} + + +} // Filesystem +} // TizenApis diff --git a/wearable_src/Filesystem/EventListNodes.h b/wearable_src/Filesystem/EventListNodes.h new file mode 100755 index 0000000..383bc1e --- /dev/null +++ b/wearable_src/Filesystem/EventListNodes.h @@ -0,0 +1,79 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 TIZENAPIS_FILESYSTEM_EVENTLISTNODES_H_ +#define TIZENAPIS_FILESYSTEM_EVENTLISTNODES_H_ + +#include <dpl/shared_ptr.h> +#include <Commons/IEvent.h> +#include "INodeTypes.h" +#include "NodeFilter.h" + +namespace DeviceAPI { +namespace Filesystem { +class EventListNodes : public WrtDeviceApis::Commons::IEvent<EventListNodes> +{ + public: + /** + * Creates new event object. + * @param path Node to list children for. + * @return New object. + */ + explicit EventListNodes(const INodePtr& node); + + /** + * Gets parent node. + * @return Parent node. + */ + INodePtr getNode() const; + + /** + * Gets filter. + * @return Filter. + */ + NodeFilterPtr getFilter() const; + + /** + * Sets filter. + * @param filter Filter to list only specific nodes. + */ + void setFilter(const NodeFilterPtr& filter); + + /** + * Gets nodes. + * @return Nodes list. + */ + NodeList getResult() const; + + /** + * Sets nodes list. + * @param list Nodes list. + */ + void setResult(const NodeList& list); + + private: + NodeList m_list; ///< List of child nodes. + INodePtr m_node; ///< Node to list children for. + NodeFilterPtr m_filter; ///< Filter. +}; + +typedef DPL::SharedPtr<EventListNodes> EventListNodesPtr; +} // Filesystem +} // TizenApis + +#endif // TIZENAPIS_FILESYSTEM_EVENTLISTNODES_H_
\ No newline at end of file diff --git a/wearable_src/Filesystem/EventListStorages.cpp b/wearable_src/Filesystem/EventListStorages.cpp new file mode 100755 index 0000000..2de311f --- /dev/null +++ b/wearable_src/Filesystem/EventListStorages.cpp @@ -0,0 +1,38 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "EventListStorages.h" + +namespace DeviceAPI { +namespace Filesystem { +EventListStorages::EventListStorages() +{ +} + +void EventListStorages::setResult (const std::vector<StoragePropertiesPtr>& Storages) +{ + storages = Storages; +} + +std::vector<StoragePropertiesPtr> EventListStorages::getResult() const +{ + return storages; +} + +} // Filesystem +} // TizenApis diff --git a/wearable_src/Filesystem/EventListStorages.h b/wearable_src/Filesystem/EventListStorages.h new file mode 100755 index 0000000..8fd5bf9 --- /dev/null +++ b/wearable_src/Filesystem/EventListStorages.h @@ -0,0 +1,44 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 TIZENAPIS_API_FILESYSTEM_EVENT_LIST_STORAGES_H_ +#define TIZENAPIS_API_FILESYSTEM_EVENT_LIST_STORAGES_H_ + +#include <Commons/IEvent.h> +#include <dpl/shared_ptr.h> +#include <vector> +#include "StorageProperties.h" + +namespace DeviceAPI { +namespace Filesystem { +class EventListStorages : public WrtDeviceApis::Commons::IEvent< + EventListStorages> +{ + private: + std::vector<StoragePropertiesPtr> storages; + public: + void setResult (const std::vector<StoragePropertiesPtr>& Storages); + std::vector<StoragePropertiesPtr> getResult() const; + EventListStorages(); +}; + +typedef DPL::SharedPtr<EventListStorages> EventListStoragesPtr; +} +} + +#endif
\ No newline at end of file diff --git a/wearable_src/Filesystem/EventMove.cpp b/wearable_src/Filesystem/EventMove.cpp new file mode 100755 index 0000000..fd9afcc --- /dev/null +++ b/wearable_src/Filesystem/EventMove.cpp @@ -0,0 +1,62 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "EventMove.h" + +namespace DeviceAPI { +namespace Filesystem { +EventMove::EventMove(const IPathPtr& src, + const IPathPtr& dest) : + m_src(src), + m_dest(dest), + m_options(OPT_NONE) +{ + +} + +IPathPtr EventMove::getDestination() const +{ + return m_dest; +} + +IPathPtr EventMove::getSource() const +{ + return m_src; +} + +INodePtr EventMove::getResult() const +{ + return m_result; +} + +void EventMove::setResult(const INodePtr& node) +{ + m_result = node; +} + +int EventMove::getOptions() const +{ + return m_options; +} + +void EventMove::setOptions(int options) +{ + m_options = options; +} +} // Filesystem +} // TizenApis
\ No newline at end of file diff --git a/wearable_src/Filesystem/EventMove.h b/wearable_src/Filesystem/EventMove.h new file mode 100755 index 0000000..742c7f6 --- /dev/null +++ b/wearable_src/Filesystem/EventMove.h @@ -0,0 +1,88 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 TIZENAPIS_FILESYSTEM_EVENTMOVE_H_ +#define TIZENAPIS_FILESYSTEM_EVENTMOVE_H_ + +#include <dpl/shared_ptr.h> +#include <Commons/IEvent.h> +#include "IPath.h" +#include "INode.h" + +namespace DeviceAPI { +namespace Filesystem { +class EventMove : public WrtDeviceApis::Commons::IEvent<EventMove> +{ + public: + /** + * Creates new event object. + * @param src Source path. + * @param dest Destination path. + * @return New object. + */ + EventMove(const IPathPtr& src, + const IPathPtr& dest); + + /** + * Gets destination path. + * @return Destination path. + */ + IPathPtr getDestination() const; + + /** + * Gets source path. + * @return Source path. + */ + IPathPtr getSource() const; + + /** + * Gets result node. + * @return Result node. + */ + INodePtr getResult() const; + + /** + * Sets result node. + * @param node Result node. + */ + void setResult(const INodePtr& node); + + /** + * Gets options. + * @return Options. + */ + int getOptions() const; + + /** + * Sets options. + * @param options Options. + */ + void setOptions(int options); + + private: + IPathPtr m_src; ///< Source path. + IPathPtr m_dest; ///< Destination path. + INodePtr m_result; ///< Result node. + int m_options; ///< Options for copy action @see WrtPlugins::Api::Filesystem::Options. +}; + +typedef DPL::SharedPtr<EventMove> EventMovePtr; +} // Filesystem +} // TizenApis + +#endif // TIZENAPIS_FILESYSTEM_EVENTMOVE_H_
\ No newline at end of file diff --git a/wearable_src/Filesystem/EventOpen.cpp b/wearable_src/Filesystem/EventOpen.cpp new file mode 100755 index 0000000..d266f90 --- /dev/null +++ b/wearable_src/Filesystem/EventOpen.cpp @@ -0,0 +1,54 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "EventOpen.h" + +namespace DeviceAPI { +namespace Filesystem { +EventOpen::EventOpen(int mode) : m_mode(mode) +{ +} + +int EventOpen::getMode() const +{ + return m_mode; +} + +IStreamPtr EventOpen::getResult() const +{ + return m_stream; +} + +void EventOpen::setResult(const IStreamPtr& stream) +{ + m_stream = stream; +} + + +void EventOpen::setCharSet(const std::string &charSet) +{ + m_charSet = charSet; +} + +std::string EventOpen::getCharSet() const +{ + return m_charSet; +} + +} // Filesystem +} // TizenApis
\ No newline at end of file diff --git a/wearable_src/Filesystem/EventOpen.h b/wearable_src/Filesystem/EventOpen.h new file mode 100755 index 0000000..ad8cc58 --- /dev/null +++ b/wearable_src/Filesystem/EventOpen.h @@ -0,0 +1,68 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 TIZENAPIS_FILESYSTEM_EVENTOPEN_H_ +#define TIZENAPIS_FILESYSTEM_EVENTOPEN_H_ + +#include <dpl/shared_ptr.h> +#include <Commons/IEvent.h> +#include "IStream.h" + +namespace DeviceAPI { +namespace Filesystem { +class EventOpen : public WrtDeviceApis::Commons::IEvent<EventOpen> +{ + public: + /** + * Creates new event object. + * @param mode Mode to open the node in. + * @return New object. + */ + explicit EventOpen(int mode); + + /** + * Gets mode. + * @return Mode. + */ + int getMode() const; + + /** + * Gets result stream. + * @return Result stream. + */ + IStreamPtr getResult() const; + + /** + * Sets result stream. + * @param stream Result stream. + */ + void setResult(const IStreamPtr& stream); + void setCharSet(const std::string &charSet); + std::string getCharSet() const; + + private: + std::string m_charSet; // charSet to open + int m_mode; ///< Mode. + IStreamPtr m_stream; ///< Opened stream. +}; + +typedef DPL::SharedPtr<EventOpen> EventOpenPtr; +} // Filesystem +} // TizenApis + +#endif // TIZENAPIS_FILESYSTEM_EVENTOPEN_H_
\ No newline at end of file diff --git a/wearable_src/Filesystem/EventReadText.cpp b/wearable_src/Filesystem/EventReadText.cpp new file mode 100755 index 0000000..3e5b3c1 --- /dev/null +++ b/wearable_src/Filesystem/EventReadText.cpp @@ -0,0 +1,44 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "EventReadText.h" + +namespace DeviceAPI { +namespace Filesystem { +std::string EventReadText::getResult() const +{ + return m_result; +} + +void EventReadText::setResult(const std::string& result) +{ + m_result = result; +} + +void EventReadText::setCharSet(const std::string &charSet) +{ + m_charSet = charSet; +} + +std::string EventReadText::getCharSet() const +{ + return m_charSet; +} + +} // Filesystem +} // TizenApis
\ No newline at end of file diff --git a/wearable_src/Filesystem/EventReadText.h b/wearable_src/Filesystem/EventReadText.h new file mode 100755 index 0000000..fa70a96 --- /dev/null +++ b/wearable_src/Filesystem/EventReadText.h @@ -0,0 +1,55 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 TIZENAPIS_FILESYSTEM_EVENTREADTEXT_H_ +#define TIZENAPIS_FILESYSTEM_EVENTREADTEXT_H_ + +#include <string> +#include <dpl/shared_ptr.h> +#include <Commons/IEvent.h> +#include "IPath.h" + +namespace DeviceAPI { +namespace Filesystem { +class EventReadText : public WrtDeviceApis::Commons::IEvent<EventReadText> +{ + public: + /** + * Gets read text. + * @return Text. + */ + std::string getResult() const; + + /** + * Sets read text. + * @param result Text. + */ + void setResult(const std::string& result); + void setCharSet(const std::string &charSet); + std::string getCharSet() const; + + private: + std::string m_result; ///< Read text. + std::string m_charSet; +}; + +typedef DPL::SharedPtr<EventReadText> EventReadTextPtr; +} // Filesystem +} // TizenApis + +#endif // TIZENAPIS_FILESYSTEM_EVENTREADTEXT_H_
\ No newline at end of file diff --git a/wearable_src/Filesystem/EventRemove.cpp b/wearable_src/Filesystem/EventRemove.cpp new file mode 100755 index 0000000..2253943 --- /dev/null +++ b/wearable_src/Filesystem/EventRemove.cpp @@ -0,0 +1,44 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "EventRemove.h" + +namespace DeviceAPI { +namespace Filesystem { +EventRemove::EventRemove(const IPathPtr& path) : + m_path(path), + m_options(OPT_NONE) +{ +} + +IPathPtr EventRemove::getPath() const +{ + return m_path; +} + +int EventRemove::getOptions() const +{ + return m_options; +} + +void EventRemove::setOptions(int options) +{ + m_options = options; +} +} // Filesystem +} // TizenApis
\ No newline at end of file diff --git a/wearable_src/Filesystem/EventRemove.h b/wearable_src/Filesystem/EventRemove.h new file mode 100755 index 0000000..b8ccb79 --- /dev/null +++ b/wearable_src/Filesystem/EventRemove.h @@ -0,0 +1,66 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 TIZENAPIS_FILESYSTEM_EVENTREMOVE_H_ +#define TIZENAPIS_FILESYSTEM_EVENTREMOVE_H_ + +#include <dpl/shared_ptr.h> +#include <Commons/IEvent.h> +#include "INode.h" +#include "Enums.h" + +namespace DeviceAPI { +namespace Filesystem { +class EventRemove : public WrtDeviceApis::Commons::IEvent<EventRemove> +{ + public: + /** + * Creates new event object. + * @param path Path to the node to remove. + * @return New object. + */ + explicit EventRemove(const IPathPtr& path); + + /** + * Gets path to the node to remove. + * @return Path. + */ + IPathPtr getPath() const; + + /** + * Gets options. + * @return Options. + */ + int getOptions() const; + + /** + * Sets options. + * @param options Options. + */ + void setOptions(int options); + + private: + IPathPtr m_path; ///< Source path. + int m_options; ///< Options for remove action @see WrtPlugins::Api::Filesystem::Options. +}; + +typedef DPL::SharedPtr<EventRemove> EventRemovePtr; +} // Filesystem +} // TizenApis + +#endif // TIZENAPIS_FILESYSTEM_EVENTREMOVE_H_
\ No newline at end of file diff --git a/wearable_src/Filesystem/EventResolve.cpp b/wearable_src/Filesystem/EventResolve.cpp new file mode 100755 index 0000000..52572b1 --- /dev/null +++ b/wearable_src/Filesystem/EventResolve.cpp @@ -0,0 +1,53 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "EventResolve.h" + +namespace DeviceAPI { +namespace Filesystem { +EventResolve::EventResolve(const IPathPtr& path) : m_path(path) +{ + m_mode = "rw"; +} + +IPathPtr EventResolve::getPath() const +{ + return m_path; +} + +INodePtr EventResolve::getResult() const +{ + return m_node; +} + +void EventResolve::setResult(const INodePtr& node) +{ + m_node = node; +} + +void EventResolve::setMode(const std::string &mode) +{ + m_mode = mode; +} +std::string EventResolve::getMode() +{ + return m_mode; +} + +} // Filesystem +} // TizenApis
\ No newline at end of file diff --git a/wearable_src/Filesystem/EventResolve.h b/wearable_src/Filesystem/EventResolve.h new file mode 100755 index 0000000..0f61331 --- /dev/null +++ b/wearable_src/Filesystem/EventResolve.h @@ -0,0 +1,71 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 TIZENAPIS_FILESYSTEM_EVENTRESOLVE_H_ +#define TIZENAPIS_FILESYSTEM_EVENTRESOLVE_H_ + +#include <dpl/shared_ptr.h> +#include <Commons/IEvent.h> +#include "IPath.h" +#include "INode.h" + +namespace DeviceAPI { +namespace Filesystem { +class EventResolve : public WrtDeviceApis::Commons::IEvent<EventResolve> +{ + public: + /** + * Creates new event object. + * @param path Path to the node to resolve. + * @return New object. + */ + explicit EventResolve(const IPathPtr& path); + + /** + * Gets path of the node to resolve. + * @return Path to resolve. + */ + IPathPtr getPath() const; + + /** + * Gets resolved node. + * NULL if none found. Check exception code. + * @return Resolved node or NULL. + */ + INodePtr getResult() const; + + /** + * Sets resolved node. + * @param node Resolved node. + */ + void setResult(const INodePtr& node); + + void setMode(const std::string &mode); + std::string getMode(); + + private: + IPathPtr m_path; ///< Path to the requested node. + INodePtr m_node; ///< Resolved node. + std::string m_mode; +}; + +typedef DPL::SharedPtr<EventResolve> EventResolvePtr; +} // Filesystem +} // TizenApis + +#endif // WRTPLUGINS_FILESYSTEM_EVENTRESOLVE_H_ diff --git a/wearable_src/Filesystem/EventStorageStateChanged.h b/wearable_src/Filesystem/EventStorageStateChanged.h new file mode 100755 index 0000000..b17a18b --- /dev/null +++ b/wearable_src/Filesystem/EventStorageStateChanged.h @@ -0,0 +1,51 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 TIZENAPIS_API_FILESYSTEM_EVENT_STORAGESTATE_CHANGED_H_ +#define TIZENAPIS_API_FILESYSTEM_EVENT_STORAGESTATE_CHANGED_H_ + +#include <vector> +#include <Commons/IEvent.h> +#include <dpl/shared_ptr.h> +#include <Commons/ListenerEvent.h> +#include <Commons/ListenerEventEmitter.h> +#include "StorageProperties.h" + +namespace DeviceAPI { +namespace Filesystem { + +class EventStorageStateChanged : public WrtDeviceApis::Commons::ListenerEvent<EventStorageStateChanged> +{ +private: + StoragePropertiesPtr storages; + +public: + void setResult (const StoragePropertiesPtr& Storages); + StoragePropertiesPtr getResult() const; + + EventStorageStateChanged(); +}; + +typedef DPL::SharedPtr<EventStorageStateChanged> EventStorageStateChangedPtr; +typedef WrtDeviceApis::Commons::ListenerEventEmitter<EventStorageStateChanged> EventStorageStateChangedEmitter; +typedef DPL::SharedPtr<EventStorageStateChangedEmitter> EventStorageStateChangedEmitterPtr; + +} // Filesystem +} // TizenApis + +#endif //TIZENAPIS_API_FILESYSTEM_EVENT_STORAGESTATE_CHANGED_H_
\ No newline at end of file diff --git a/wearable_src/Filesystem/EventStoragestateChanged.cpp b/wearable_src/Filesystem/EventStoragestateChanged.cpp new file mode 100755 index 0000000..f87755d --- /dev/null +++ b/wearable_src/Filesystem/EventStoragestateChanged.cpp @@ -0,0 +1,38 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "EventStorageStateChanged.h" + +namespace DeviceAPI { +namespace Filesystem { +EventStorageStateChanged::EventStorageStateChanged() +{ +} + +void EventStorageStateChanged::setResult (const StoragePropertiesPtr &Storages) +{ + storages = Storages; +} + +StoragePropertiesPtr EventStorageStateChanged::getResult() const +{ + return storages; +} + +} // Filesystem +} // TizenApis
\ No newline at end of file diff --git a/wearable_src/Filesystem/FilesystemAsyncCallbackManager.cpp b/wearable_src/Filesystem/FilesystemAsyncCallbackManager.cpp new file mode 100755 index 0000000..9df7077 --- /dev/null +++ b/wearable_src/Filesystem/FilesystemAsyncCallbackManager.cpp @@ -0,0 +1,26 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "FilesystemAsyncCallbackManager.h" + +namespace DeviceAPI { +namespace Filesystem { + +SINGLETON_IMPLEMENTATION(FilesystemAsyncCallbackManager) + +} +} diff --git a/wearable_src/Filesystem/FilesystemAsyncCallbackManager.h b/wearable_src/Filesystem/FilesystemAsyncCallbackManager.h new file mode 100755 index 0000000..276cf93 --- /dev/null +++ b/wearable_src/Filesystem/FilesystemAsyncCallbackManager.h @@ -0,0 +1,46 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _TIZEN_FILESYSTEM_ASYNC_CALLBACK_MANAGER_H_ +#define _TIZEN_FILESYSTEM_ASYNC_CALLBACK_MANAGER_H_ + +#include <AsyncCallbackManager.h> + +namespace DeviceAPI { +namespace Filesystem { + +class FilesystemAsyncCallbackManager : public DeviceAPI::Common::AsyncCallbackManager +{ +private: + FilesystemAsyncCallbackManager() + { + } + +public: + virtual ~FilesystemAsyncCallbackManager() + { + } + + friend class FilesystemAsyncCallbackManagerSingleton; +}; + +SINGLETON_DEFINITION(FilesystemAsyncCallbackManager) + +} // Tizen1_0 +} // TizenApis + +#endif // _TIZEN_FILESYSTEM_ASYNC_CALLBACK_MANAGER_H_ diff --git a/wearable_src/Filesystem/FilesystemListenerManager.cpp b/wearable_src/Filesystem/FilesystemListenerManager.cpp new file mode 100755 index 0000000..95e6f03 --- /dev/null +++ b/wearable_src/Filesystem/FilesystemListenerManager.cpp @@ -0,0 +1,26 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "FilesystemListenerManager.h" + +namespace DeviceAPI { +namespace Filesystem { + +SINGLETON_IMPLEMENTATION(FilesystemListenerManager) + +} +} diff --git a/wearable_src/Filesystem/FilesystemListenerManager.h b/wearable_src/Filesystem/FilesystemListenerManager.h new file mode 100644 index 0000000..5a9e76d --- /dev/null +++ b/wearable_src/Filesystem/FilesystemListenerManager.h @@ -0,0 +1,76 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _TIZEN_FILESYSTEM_LISTENER_MANAGER_H_ +#define _TIZEN_FILESYSTEM_LISTENER_MANAGER_H_ + +#include <map> +#include <JavaScriptCore/JavaScript.h> +#include <dpl/shared_ptr.h> +#include <IListenerManager.h> +#include "IManager.h" +#include "StorageStaticController.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Filesystem { + +class FilesystemListenerManager : public DeviceAPI::Common::IListenerController +{ +private: + FilesystemListenerManager() + { + } + +public: + virtual ~FilesystemListenerManager() + { + } + + friend class FilesystemListenerManagerSingleton; +}; + +SINGLETON_DEFINITION(FilesystemListenerManager) + +class FilesystemListenerCanceller : public DeviceAPI::Common::IListenerItem +{ +public: + FilesystemListenerCanceller(JSContextRef context, JSObjectRef object, long watchId) : + DeviceAPI::Common::IListenerItem(context, object, watchId) + { + } + + virtual ~FilesystemListenerCanceller() + { + } + + virtual void cancelListener() + { + Try { + LoggerD("Remove change listener"); + IManager::getInstance().removeStorageStateChangeListener(m_watchId); + } Catch(WrtDeviceApis::Commons::Exception) { + LoggerE("Error on platform : " << _rethrown_exception.GetMessage()); + } + } +}; +typedef DPL::SharedPtr<FilesystemListenerCanceller> FilesystemListenerCancellerPtr; + +} // Tizen1_0 +} // TizenApis + +#endif // _TIZEN_FILESYSTEM_LISTENER_MANAGER_H_ diff --git a/wearable_src/Filesystem/FilesystemUtils.cpp b/wearable_src/Filesystem/FilesystemUtils.cpp new file mode 100644 index 0000000..1c5fdbd --- /dev/null +++ b/wearable_src/Filesystem/FilesystemUtils.cpp @@ -0,0 +1,314 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <map> +#include <string> +#include <Commons/Exception.h> +#include "Enums.h" +#include "IManager.h" +#include <Commons/WrtAccess/WrtAccess.h> +#include <WidgetDB/WidgetDBMgr.h> +#include <iconv.h> +#include "FilesystemUtils.h" +#include <Export.h> +#include <Logger.h> + +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; + +namespace { +const std::string PATH_INVALID_COMPONENT_PARENT_DIR(".."); +const std::string PATH_INVALID_COMPONENT_CURRENT_DIR("."); + +typedef std::map<std::string, std::string> RootToPathMap; +typedef RootToPathMap::const_iterator RootToPathMapIterator; +typedef std::map<std::string, std::string> PathToRootMap; +typedef PathToRootMap::const_iterator PathToRootMapIterator; +} + +namespace DeviceAPI { +namespace Filesystem { +namespace Utils{ +const RootToPathMap DLL_EXPORT & getRootToPathMap() +{ + static RootToPathMap result; + if (result.empty()) { + IManager& manager = IManager::getInstance(); + std::map<std::string, IPathPtr> locations = manager.getStorageList(); + + std::map<std::string, IPathPtr>::const_iterator it; + + for (it = locations.begin(); it != locations.end(); ++it) { + result[it->first] = it->second->getFullPath(); + } + } + return result; +} + +const PathToRootMap DLL_EXPORT & getPathToRootMap() +{ + static PathToRootMap result; + if (result.empty()) { + IManager& manager = IManager::getInstance(); + std::map<std::string, IPathPtr> locations = manager.getStorageList(); + + std::map<std::string, IPathPtr>::const_iterator it; + + for (it = locations.begin(); it != locations.end(); ++it) { + result[it->second->getFullPath()] = it->first; + } + } + return result; +} +void DLL_EXPORT checkCreationName(const std::string arg, bool dir) +{ + if (dir == false && arg.find("/") != std::string::npos) + { + ThrowMsg(InvalidArgumentException, "Invalid path name"); + } + + if (arg.find("\\") != std::string::npos) + { + ThrowMsg(InvalidArgumentException, "Invalid path name"); + } + + if (arg.find("?") != std::string::npos) + { + ThrowMsg(InvalidArgumentException, "Invalid path name"); + } + + if (arg.find("*") != std::string::npos) + { + ThrowMsg(InvalidArgumentException, "Invalid path name"); + } + + if (arg.find(":") != std::string::npos) + { + ThrowMsg(InvalidArgumentException, "Invalid path name"); + } + + if (arg.find("\"") != std::string::npos) + { + ThrowMsg(InvalidArgumentException, "Invalid path name"); + } + + if (arg.find("<") != std::string::npos) + { + ThrowMsg(InvalidArgumentException, "Invalid path name"); + } + + if (arg.find(">") != std::string::npos) + { + ThrowMsg(InvalidArgumentException, "Invalid path name"); + } +} + +IPathPtr DLL_EXPORT fromVirtualPath(JSContextRef context, + const std::string& arg) +{ + LoggerD("arg:[" << arg << "]"); + + // uri path, strip file:// + if (isUriPath(arg)) { + std::string stripPath = arg.substr(strlen("file://")); + LoggerD("uri absolute path" << stripPath); + IPathPtr result = IPath::create(stripPath); + + return result; + } + + if (!isPathValid(arg)) { + LoggerD("virtual path is invalid:[" << arg << "]"); + ThrowMsg(Commons::ConversionException, "Not found path component."); + } + + std::string root; + std::string tail; + std::string::size_type separatorPosition = arg.find(IPath::getSeparator()); + if (separatorPosition != std::string::npos) { + root = arg.substr(0, separatorPosition); + tail = arg.substr(separatorPosition + 1, arg.size() - 1); + } else { + root = arg; + } + + int widgetId = WrtAccessSingleton::Instance().getWidgetId(); + WidgetDB::Api::IWidgetDBPtr widgetDB = WidgetDB::Api::getWidgetDB(widgetId); + + RootToPathMap rootToPath = getRootToPathMap(); + rootToPath["wgt-package"] = widgetDB->getWidgetInstallationPath(); + rootToPath["wgt-private"] = widgetDB->getWidgetPersistentStoragePath(); + rootToPath["wgt-private-tmp"] = widgetDB->getWidgetTemporaryStoragePath(); + RootToPathMapIterator it = rootToPath.find(root); + + if (it == rootToPath.end()) { +// ThrowMsg(Commons::NotFoundException, "Location not found."); + LoggerD("Allow non virtual root path " << arg); + return IPath::create(arg); + } + + IPathPtr result = IPath::create(it->second); + + if (!tail.empty()) { + result->append(tail); + } + + return result; +} + +std::string DLL_EXPORT toVirtualPath(JSContextRef context, const std::string& arg) { + + int widgetId = WrtAccessSingleton::Instance().getWidgetId(); + WidgetDB::Api::IWidgetDBPtr widgetDB = + WidgetDB::Api::getWidgetDB(widgetId); + + PathToRootMap pathToRoot = getPathToRootMap(); + pathToRoot[widgetDB->getWidgetInstallationPath()] = "wgt-package"; + pathToRoot[widgetDB->getWidgetPersistentStoragePath()] = "wgt-private"; + pathToRoot[widgetDB->getWidgetTemporaryStoragePath()] = "wgt-private-tmp"; + + std::string path = arg; + + std::string::size_type pos = path.size(); + while (std::string::npos != (pos = path.rfind(IPath::getSeparator(), pos))) { + PathToRootMapIterator it = pathToRoot.find(path); + if (pathToRoot.end() != it) { + return it->second + arg.substr(path.size()); + } + path.erase(pos, path.size()); + } + LoggerD("Allow non virtual root path"); + + return arg; +// ThrowMsg(Commons::ConversionException, "Path doesn't contain a valid location type."); +} + +bool DLL_EXPORT isVirtualPath(const std::string& path) { + std::string root; + std::string::size_type separatorPosition = path.find(IPath::getSeparator()); + + if (separatorPosition != std::string::npos) { + root = path.substr(0, separatorPosition); + } else { + root = path; + } + + int widgetId = WrtAccessSingleton::Instance().getWidgetId(); + WidgetDB::Api::IWidgetDBPtr widgetDB = WidgetDB::Api::getWidgetDB(widgetId); + + RootToPathMap rootToPath = getRootToPathMap(); + rootToPath["wgt-package"] = widgetDB->getWidgetInstallationPath(); + rootToPath["wgt-private"] = widgetDB->getWidgetPersistentStoragePath(); + rootToPath["wgt-private-tmp"] = widgetDB->getWidgetTemporaryStoragePath(); + RootToPathMapIterator it = rootToPath.find(root); + + + if (it == rootToPath.end()) { + return false; + } + else { + return true; + } +} +bool DLL_EXPORT isUriPath(const std::string& path) { + const char* uriPrefix = "file://"; + const char* stringFromPath = path.c_str(); + + if (!strncmp(uriPrefix, stringFromPath, strlen(uriPrefix)) && path[strlen(uriPrefix)] == '/') { + return true; + } + + return false; +} + +bool DLL_EXPORT isPathValid(const std::string& path) { + static const std::string currentDirBegin(PATH_INVALID_COMPONENT_CURRENT_DIR + IPath::getSeparator()); + static const std::string parentDirBegin(PATH_INVALID_COMPONENT_PARENT_DIR + + IPath::getSeparator()); + static const std::string currentDirMiddle(IPath::getSeparator() + + PATH_INVALID_COMPONENT_CURRENT_DIR +IPath::getSeparator()); + static const std::string parentDirMiddle(IPath::getSeparator() + + PATH_INVALID_COMPONENT_PARENT_DIR +IPath::getSeparator()); + + if (path.find(parentDirBegin) == 0 || + path.find(currentDirBegin) == 0 || + path.find(parentDirMiddle) != std::string::npos || + path.find(currentDirMiddle) != std::string::npos) { + return false; + } + + return true; +} + +void DLL_EXPORT toUTF8String(std::string fromEncoding, const char* from, const size_t fromLength, std::string &outputString) +{ + const char *fromEncodingSet = fromEncoding.c_str(); + char *outputBuf = NULL; + char *buf = NULL; + int ret = 0; + iconv_t cd; + size_t outputLength= 0; + + try { +// LoggerD("from " << fromEncodingSet << " to UTF8 conversion " << fromLength); + + cd = iconv_open("UTF-8", fromEncodingSet); + + if (cd == (iconv_t) -1) + { + LoggerD("charset conversion exception iconv -1"); + ThrowMsg(Commons::PlatformException, "charset conversion exception"); + } + + if (fromLength == 0) + { + LoggerD("from length 0"); + ThrowMsg(Commons::PlatformException, "Couldn't allocate output buffer."); + } + + outputBuf = new char[fromLength * 4 + 1]; + outputLength = fromLength * 4; + memset(outputBuf, 0, outputLength + 1); + buf = outputBuf; + + + ret = iconv(cd, (char**)&from, (size_t*)&fromLength, &buf, &outputLength); + + LoggerD(fromLength << " " << outputLength); + + if (ret < 0) + { + iconv_close(cd); + LoggerD("charset conversion exception ret " << ret); + ThrowMsg(Commons::PlatformException, "charset conversion exception"); + } + + iconv_close(cd); + outputString = outputBuf; + + if (outputBuf) + delete[] outputBuf; + + } + Catch(std::bad_alloc) { + LoggerD("Couldn't allocate output buffer."); + ThrowMsg(Commons::PlatformException, "Couldn't allocate output buffer."); + } +} +} +} +} diff --git a/wearable_src/Filesystem/FilesystemUtils.h b/wearable_src/Filesystem/FilesystemUtils.h new file mode 100755 index 0000000..43d4eac --- /dev/null +++ b/wearable_src/Filesystem/FilesystemUtils.h @@ -0,0 +1,43 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 TIZENAPIS_FILESYSTEM_UTILS_H_ +#define TIZENAPIS_FILESYSTEM_UTILS_H_ + +#include <string> +#include <JavaScriptCore/JavaScript.h> +#include "IPath.h" + +namespace DeviceAPI { +namespace Filesystem { +namespace Utils{ + +IPathPtr fromVirtualPath(JSContextRef context, + const std::string& arg); + +std::string toVirtualPath(JSContextRef context, const std::string& arg); + +bool isPathValid(const std::string& path); +bool isUriPath(const std::string& path); +bool isVirtualPath(const std::string& path); +void checkCreationName(const std::string arg, bool dir); +void toUTF8String(std::string fromEncoding, const char* from, const size_t fromLength, std::string &outputString); +} +} +} + +#endif diff --git a/wearable_src/Filesystem/IManager.cpp b/wearable_src/Filesystem/IManager.cpp new file mode 100755 index 0000000..74b528e --- /dev/null +++ b/wearable_src/Filesystem/IManager.cpp @@ -0,0 +1,49 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "Manager.h" +#include <Commons/ThreadPool.h> +#include "IManager.h" + +using namespace WrtDeviceApis::Commons; + +namespace DeviceAPI { +namespace Filesystem { +IManager& IManager::getInstance() +{ + static Manager instance; + return instance; +} + +IManager::IManager() : + EventRequestReceiver<EventResolve>(ThreadEnum::FILESYSTEM_THREAD), + EventRequestReceiver<EventGetStorage>(ThreadEnum::FILESYSTEM_THREAD), + EventRequestReceiver<EventListStorages>(ThreadEnum::FILESYSTEM_THREAD), + EventRequestReceiver<EventCopy>(ThreadEnum::FILESYSTEM_THREAD), + EventRequestReceiver<EventMove>(ThreadEnum::FILESYSTEM_THREAD), + EventRequestReceiver<EventCreate>(ThreadEnum::FILESYSTEM_THREAD), + EventRequestReceiver<EventRemove>(ThreadEnum::FILESYSTEM_THREAD), + EventRequestReceiver<EventFind>(ThreadEnum::FILESYSTEM_THREAD) +{ +} + +IManager::~IManager() +{ +} +} // Filesystem +} // TizenApis
\ No newline at end of file diff --git a/wearable_src/Filesystem/IManager.h b/wearable_src/Filesystem/IManager.h new file mode 100755 index 0000000..48c55a7 --- /dev/null +++ b/wearable_src/Filesystem/IManager.h @@ -0,0 +1,174 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 TIZENAPIS_FILESYSTEM_IMANAGER_H_ +#define TIZENAPIS_FILESYSTEM_IMANAGER_H_ + +#include <map> +#include <vector> +#include <string> +#include <cstddef> +#include <dpl/noncopyable.h> +#include <Commons/EventReceiver.h> +#include "EventResolve.h" +#include "EventGetStorage.h" +#include "EventListStorages.h" +#include "EventStorageStateChanged.h" +#include "EventCopy.h" +#include "EventMove.h" +#include "EventRemove.h" +#include "EventCreate.h" +#include "EventFind.h" +#include "Enums.h" +#include "INode.h" +#include "IPath.h" + +namespace DeviceAPI { +namespace Filesystem { +typedef std::vector<IPathPtr> LocationPaths; + +typedef std::vector<LocationType> LocationTypes; + +typedef std::map<std::string, IPathPtr> StorageList; + +class IManager : public WrtDeviceApis::Commons::EventRequestReceiver<EventResolve>, + public WrtDeviceApis::Commons::EventRequestReceiver<EventGetStorage>, + public WrtDeviceApis::Commons::EventRequestReceiver<EventListStorages>, + public WrtDeviceApis::Commons::EventRequestReceiver<EventCopy>, + public WrtDeviceApis::Commons::EventRequestReceiver<EventMove>, + public WrtDeviceApis::Commons::EventRequestReceiver<EventCreate>, + public WrtDeviceApis::Commons::EventRequestReceiver<EventRemove>, + public WrtDeviceApis::Commons::EventRequestReceiver<EventFind> +{ + public: + static IManager& getInstance(); + + virtual ~IManager() = 0; + + /** + * Gets base path. + * @return Valid path or empty shared pointer. + */ + virtual IPathPtr getBasePath() const = 0; + + virtual StorageList getStorageList() const = 0; + + /** + * Gets path for specified location type. + * @param type Location type @see WrtPlugins::Api::Filesystem::LocationType. + * @return Valid path or empty shared pointer. + */ + virtual IPathPtr getLocationPath(LocationType type) const = 0; + + /** + * Gets paths to default locations. + * @return Paths to predefined virtual locations. + */ + virtual LocationPaths getLocationPaths() const = 0; + + /** + * Gets locations supported by platform. + * @return Supported locations. + */ + virtual LocationTypes getLocations() const = 0; + + /** + * Gets filesystem node. + * @param event Get node event @see Api::Filesystem::EventGetNode. + * @remarks Asynchronous. + */ + virtual void getNode(const EventResolvePtr& event) = 0; + + /** + * Gets maximum length of filesystem path. + * @return Maximum path length. + */ + virtual std::size_t getMaxPathLength() const = 0; + + /** + * Copies node to specified destination. + * @param event Copy node event @see Api::Filesystem::EventCopy. + * @remarks Asynchronous. + */ + virtual void copy(const EventCopyPtr& event) = 0; + + /** + * Moves node to specified destination. + * @param event Move node event @see Api::Filesystem::EventMove. + * @remarks Asynchronous. + */ + virtual void move(const EventMovePtr& event) = 0; + + /** + * Creates a node. + * @param event Create node event @see Api::Filesystem::EventCreate. + * @remarks Asynchronous. + */ + virtual void create(const EventCreatePtr& event) = 0; + + /** + * Removes node. + * @param event Remove node event @see Api::Filesystem::EventRemove. + * @remarks Asynchronous. + */ + virtual void remove(const EventRemovePtr& event) = 0; + + /** + * Finds nodes. + * @param event Find nodes event @see Api::Filesystem::EventFind. + * @remarks Asynchronous. + */ + virtual void find(const EventFindPtr& event) = 0; + + /** + * Checks if node at specified path has supplied access rights. + * @param path Path to the node. + * @param accessType Access right(s) to check @see AccessType. Multiple values + * can be passed using OR operator. + * @return True if specified node has supplied access rights, false otherwise. + */ +// virtual bool access(const IPathPtr& path, +// int accessType) const = 0; + + virtual void addOpenedNode(const INodePtr& node) = 0; + virtual void removeOpenedNode(const INodePtr& node) = 0; + virtual bool checkIfOpened(const IPathPtr& path) const = 0; + + virtual void getStorage(const EventGetStoragePtr& event) = 0; + virtual void listStorages(const EventListStoragesPtr& event) = 0; + + virtual long addStorageStateChangeListener(const EventStorageStateChangedEmitterPtr& emitter) = 0; + virtual void removeStorageStateChangeListener(EventStorageStateChangedEmitter::IdType id) = 0; + virtual void addWidgetStorage(const std::string &key, const std::string &value) = 0; + + protected: + IManager(); + + virtual void OnRequestReceived(const EventResolvePtr& event) = 0; + virtual void OnRequestReceived(const EventGetStoragePtr& event) = 0; + virtual void OnRequestReceived(const EventListStoragesPtr& event) = 0; + virtual void OnRequestReceived(const EventCopyPtr& event) = 0; + virtual void OnRequestReceived(const EventMovePtr& event) = 0; + virtual void OnRequestReceived(const EventCreatePtr& event) = 0; + virtual void OnRequestReceived(const EventRemovePtr& event) = 0; + virtual void OnRequestReceived(const EventFindPtr& event) = 0; +}; // IManager +} // Filesystem +} // TizenApis + +#endif // TIZENAPIS_FILESYSTEM_IMANAGER_H_
\ No newline at end of file diff --git a/wearable_src/Filesystem/INode.cpp b/wearable_src/Filesystem/INode.cpp new file mode 100755 index 0000000..e5af280 --- /dev/null +++ b/wearable_src/Filesystem/INode.cpp @@ -0,0 +1,37 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "INode.h" +#include <Commons/ThreadPool.h> + +using namespace WrtDeviceApis::Commons; + +namespace DeviceAPI { +namespace Filesystem { +INode::INode() : + EventRequestReceiver<EventListNodes>(ThreadEnum::FILESYSTEM_THREAD), + EventRequestReceiver<EventOpen>(ThreadEnum::FILESYSTEM_THREAD), + EventRequestReceiver<EventReadText>(ThreadEnum::FILESYSTEM_THREAD) +{ +} + +INode::~INode() +{ +} +} // Filesystem +} // TizenApis
\ No newline at end of file diff --git a/wearable_src/Filesystem/INode.h b/wearable_src/Filesystem/INode.h new file mode 100755 index 0000000..163de54 --- /dev/null +++ b/wearable_src/Filesystem/INode.h @@ -0,0 +1,187 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 TIZENAPIS_FILESYSTEM_INODE_H_ +#define TIZENAPIS_FILESYSTEM_INODE_H_ + +#include <string> +#include <vector> +#include <ctime> +#include <dpl/noncopyable.h> +#include <dpl/shared_ptr.h> +#include <Commons/Deprecated.h> +#include <Commons/EventReceiver.h> +#include "EventListNodes.h" +#include "EventOpen.h" +#include "EventReadText.h" +#include "Enums.h" +#include "IPath.h" +#include "IStream.h" +#include "INodeTypes.h" +#include "NodeFilter.h" + +namespace DeviceAPI { +namespace Filesystem { +class INode : public WrtDeviceApis::Commons::EventRequestReceiver<EventListNodes>, + public WrtDeviceApis::Commons::EventRequestReceiver<EventOpen>, + public WrtDeviceApis::Commons::EventRequestReceiver<EventReadText> +{ + public: + typedef std::vector<std::string> NameList; + typedef NameList::iterator NodeListIterator; + + public: + virtual ~INode() = 0; + + /** + * Gets direct child of this node. + * @param path Path to the child node. + * @return Ptr to the child node. + * @remarks Ownership passed to the caller. + */ + virtual INodePtr getChild(const IPathPtr& path) = 0; + + /** + * Gets path of current node. + * @return Node's path. + */ + virtual IPathPtr getPath() const = 0; + + /** + * Gets type of current node. + * @return Node's type. + */ + virtual NodeType getType() const = 0; + + /** + * Gets permissions of the virtual node (not real filesystem node). + * @return Node's permissions. + */ + virtual int getPermissions() const = 0; + + /** + * Sets permissions on the virtual node (not real filesystem node). + * @param perms Node's permissions @see Api::Filesystem::Permissions. + */ + virtual void setPermissions(int perms) = 0; + + /** + * Gets list of names of direct child nodes. + * @return Names of child nodes. + */ + virtual NameList getChildNames() const = 0; + + /** + * Gets list of direct child nodes. + * @return Child nodes. + * @remarks Ownership passed to the caller. + * @deprecated + */ + virtual NodeList getChildNodes(const NodeFilterPtr& filter = + NodeFilterPtr()) const /* WRT_PLUGINS_DEPRECATED */ = 0; + + /** + * Gets list of direct descendant nodes. + * @param event Get child nodes event. + */ + virtual void getChildNodes(const EventListNodesPtr& event) = 0; + + /** + * Gets stream for this node. + * @param mode @see Api::Filesystem::AccessMode. + * @return Stream connected with current node. + * @deprecated Use async version of thi method instead. + */ + virtual IStreamPtr open(int mode) = 0; + + /** + * Gets stream for this node. + * @param mode @see Api::Filesystem::AccessMode. + * @return Stream connected with current node. + */ + virtual void open(const EventOpenPtr& event) = 0; + + /** + * Removes underlying filesystem node. + * @param options Removal options (by default removal is recursive). + * @remarks Synchronous. + * Valid options: + * - OPT_RECURSIVE - remove node recursively. + */ + virtual void remove(int options = OPT_RECURSIVE) = 0; + + /** + * Creates child of current node. + * @param path Path to the node to create. + * @param type Type of the node @see Api::Filesystem::NodeType. + * @param options Additional options see remarks (no options by default). + * @return Ptr to newly created node. + * @remarks + * Valid options: + * - OPT_RECURSIVE - attempt to create all necessary sub-directories + */ + virtual INodePtr createChild(const IPathPtr& path, + NodeType type, + int options = OPT_NONE) = 0; + + /** + * Gets size of this node. + * @return Size. + */ + virtual unsigned long long getSize() const = 0; + + /** + * Gets creation date of this node. + * @return Date. + */ + virtual std::time_t getCreated() const = 0; + + /** + * Gets last modification date of this node. + * @return Date. + */ + virtual std::time_t getModified() const = 0; + + /** + * Gets parent of this node. + * @return Parent node or NULL if no parent (e.g. in case of a root node). + */ + virtual INodePtr getParent() const = 0; + + /** + * Gets platform permissions. + * @return Platform permissions (set of flags from @see Permissions enum). + */ + virtual int getMode() const = 0; + + /** + * Reads whole file as text. + * @param event Read file event. + */ + virtual void read(const EventReadTextPtr& event) = 0; + + virtual std::string toUri(int widgetId) const = 0; + virtual bool checkPermission(const std::string mode) = 0; + + protected: + INode(); +}; +} // Filesystem +} // TizenApis + +#endif /* TIZENAPIS_FILESYSTEM_INODE_H_ */ diff --git a/wearable_src/Filesystem/INodeTypes.h b/wearable_src/Filesystem/INodeTypes.h new file mode 100755 index 0000000..9e4f79f --- /dev/null +++ b/wearable_src/Filesystem/INodeTypes.h @@ -0,0 +1,36 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 TIZENAPIS_FILESYSTEM_INODETYPES_H_ +#define TIZENAPIS_FILESYSTEM_INODETYPES_H_ + +#include <vector> +#include <dpl/shared_ptr.h> + +namespace DeviceAPI { +namespace Filesystem { +class INode; + +typedef DPL::SharedPtr<INode> INodePtr; + +typedef std::vector<INodePtr> NodeList; +typedef NodeList::iterator NodeListIterator; +} // Filesystem +} // TizenApis + +#endif // TIZENAPIS_FILESYSTEM_INODETYPES_H_
\ No newline at end of file diff --git a/wearable_src/Filesystem/IPath.cpp b/wearable_src/Filesystem/IPath.cpp new file mode 100755 index 0000000..37e0173 --- /dev/null +++ b/wearable_src/Filesystem/IPath.cpp @@ -0,0 +1,38 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "Path.h" +#include "IPath.h" + +namespace DeviceAPI { +namespace Filesystem { +IPathPtr IPath::create(const std::string& str) +{ + return Path::create(str); +} + +IPath::SeparatorType IPath::getSeparator() +{ + return Path::getSeparator(); +} + +IPath::~IPath() +{ +} +} // Filesystem +} // TizenApis
\ No newline at end of file diff --git a/wearable_src/Filesystem/IPath.h b/wearable_src/Filesystem/IPath.h new file mode 100755 index 0000000..56ba001 --- /dev/null +++ b/wearable_src/Filesystem/IPath.h @@ -0,0 +1,157 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 TIZENAPIS_FILESYSTEM_IPATH_H_ +#define TIZENAPIS_FILESYSTEM_IPATH_H_ + +#include <string> +#include <dpl/shared_ptr.h> + +namespace DeviceAPI { +namespace Filesystem { +class IPath; +typedef DPL::SharedPtr<IPath> IPathPtr; + +class IPath +{ + public: + typedef char SeparatorType; + + public: + /** + * Creates path object from specified string. + * @param str Path string. + * @return Path. + * @throw InvalidArgumentException If supplied string is not a valid path. + * @throw PlatformException If error in platform occurs. + * @remarks Ownership passed to the caller. + */ + static IPathPtr create(const std::string& str); + + /** + * Gets separator used by current platform. + * @return Path separator. + */ + static SeparatorType getSeparator(); + + public: + virtual ~IPath() = 0; + + /** + * Gets full path. + * @return Full path. + */ + virtual std::string getFullPath() const = 0; + + /** + * Gets base path (full path w/o name). + * @return Base path + */ + virtual std::string getPath() const = 0; + + /** + * Gets the last part of path. + * @return Path's name. + * @return Last part is typically name of a directory or file. + */ + virtual std::string getName() const = 0; + + /** + * Appends path specified as string to current path. + * @param path Path to append. + * @return Current path object. + */ + virtual IPathPtr append(const std::string& path) = 0; + + /** + * Appends path specified as path object to current path. + * @param path Path to append. + * @return Current path object. + */ + virtual IPathPtr append(const IPathPtr& path) = 0; + + /** + * Checks if path is abolute. + * @return True if absolute, false if relative. + */ + virtual bool isAbsolute() const = 0; + + /** + * Clones this object. + * @return Independent copy. + */ + virtual IPathPtr clone() const = 0; +}; + +inline const IPathPtr operator+(const IPath& lhs, + const IPath& rhs) +{ + return IPath::create(lhs.getFullPath())->append(rhs.getFullPath()); +} + +inline const IPathPtr operator+(const IPath& lhs, + const std::string& rhs) +{ + return IPath::create(lhs.getFullPath())->append(rhs); +} + +inline const IPathPtr operator+(const std::string& lhs, + const IPath& rhs) +{ + return IPath::create(lhs)->append(rhs.getFullPath()); +} + +inline const bool operator==(const IPath& lhs, + const IPath& rhs) +{ + return (lhs.getFullPath() == rhs.getFullPath()); +} + +inline const bool operator==(const IPath& lhs, + const std::string& rhs) +{ + return (lhs.getFullPath() == rhs); +} + +inline const bool operator==(const std::string& lhs, + const IPath& rhs) +{ + return (lhs == rhs.getFullPath()); +} + +inline const bool operator!=(const IPath& lhs, + const IPath& rhs) +{ + return (lhs.getFullPath() != rhs.getFullPath()); +} + +inline const bool operator!=(const IPath& lhs, + const std::string& rhs) +{ + return (lhs.getFullPath() != rhs); +} + +inline const bool operator!=(const std::string& lhs, + const IPath& rhs) +{ + return (lhs != rhs.getFullPath()); +} +} // Filesystem +} // TizenApis + +#endif // TIZENAPIS_FILESYSTEM_IPATH_H_
\ No newline at end of file diff --git a/wearable_src/Filesystem/IStream.cpp b/wearable_src/Filesystem/IStream.cpp new file mode 100755 index 0000000..e882608 --- /dev/null +++ b/wearable_src/Filesystem/IStream.cpp @@ -0,0 +1,27 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "IStream.h" + +namespace DeviceAPI { +namespace Filesystem { +IStream::~IStream() +{ +} +} // Filesystem +} // TizenApis
\ No newline at end of file diff --git a/wearable_src/Filesystem/IStream.h b/wearable_src/Filesystem/IStream.h new file mode 100755 index 0000000..3e782f1 --- /dev/null +++ b/wearable_src/Filesystem/IStream.h @@ -0,0 +1,129 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 TIZENAPIS_FILESYSTEM_ISTREAM_H_ +#define TIZENAPIS_FILESYSTEM_ISTREAM_H_ + +#include <cstddef> +#include <string> +#include <dpl/noncopyable.h> +#include <dpl/shared_ptr.h> + +namespace DeviceAPI { +namespace Filesystem { +class IStream; +typedef DPL::SharedPtr<IStream> IStreamPtr; + +class IStream : private DPL::Noncopyable +{ + public: + virtual ~IStream() = 0; + + virtual IStreamPtr write(bool arg) = 0; + virtual IStreamPtr write(unsigned char arg) = 0; + virtual IStreamPtr write(char arg) = 0; + virtual IStreamPtr write(int arg) = 0; + virtual IStreamPtr write(double arg) = 0; + virtual IStreamPtr write(const std::string& arg) = 0; + + virtual IStreamPtr read(bool& arg) = 0; + virtual IStreamPtr read(unsigned char& arg) = 0; + virtual IStreamPtr read(char& arg) = 0; + virtual IStreamPtr read(int& arg) = 0; + virtual IStreamPtr read(double& arg) = 0; + virtual IStreamPtr read(std::string& arg) = 0; + + /** + * Gets characters from stream. + * @param num Number of characters to read. + * @return Pointer to read buffer. + * @throw PlatformException if stream is closed, EOF is set or write-only. + * @remarks Passes ownership to the caller. + */ + virtual char* getChars(std::size_t num) = 0; + + /** + * Gets bytes from stream. + * @param num Number of bytes to read. + * @return Pointer to read buffer. + * @remarks Passes ownership to the caller. + * @throw PlatformException if stream is closed, EOF is set or write-only. + */ + virtual unsigned char* getBytes(std::size_t num) = 0; + + /** + * Gets number of bytes read by last getBytes() or getChars() operation. + * @return Number of read bytes. + * @throw PlatformException if stream is closed or write-only. + */ + virtual std::size_t getCount() const = 0; + + /** + * Reads line of characters from stream (till '\n' character). + * @return Read line. + */ + virtual std::string getLine() = 0; + + /** + * Checks whether stream is open. + * @return True if stream is open, false otherwsie. + */ + virtual bool isOpen() const = 0; + + /** + * Checks whether End-Of-Line character occured. + * @return True if EOF flag was set, false otherwise. + */ + virtual bool isEof() const = 0; + + /** + * Closes stream. + */ + virtual void close() = 0; + + /** + * Gets current position in stream. + * @return Position or -1 if fails. + */ + virtual long getPosition() const = 0; + + /** + * Sets current position in stream. + * @param position Position to set. + */ + virtual void setPosition(long position) = 0; + + /** + * Gets mode stream was opened in. + * @return Mode @see Api::Filesystem::AccessMode. + */ + virtual int getMode() const = 0; + + /** + * Gets stream's size. + * @return Size or -1 if unavailable (e.g. stream is write-only). + */ + virtual unsigned long long getSize() const = 0; + virtual void setCharSet(const std::string &charSet) = 0; + virtual std::string getCharSet() const = 0; + +}; +} // Filesystem +} // TizenApis + +#endif /* TIZENAPIS_FILESYSTEM_ISTREAM_H_ */ diff --git a/wearable_src/Filesystem/JSFile.cpp b/wearable_src/Filesystem/JSFile.cpp new file mode 100755 index 0000000..a566008 --- /dev/null +++ b/wearable_src/Filesystem/JSFile.cpp @@ -0,0 +1,1320 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "JSFile.h" + +#include <string> +#include <ctime> + +#include <Commons/FunctionDeclaration.h> +#include <Commons/Exception.h> +#include <Commons/WrtAccess/WrtAccess.h> +#include "Enums.h" +#include "IManager.h" +#include "EventCopy.h" +#include "EventMove.h" +#include "EventListNodes.h" +#include "EventOpen.h" +#include "EventReadText.h" +#include <CommonsJavaScript/JSCallbackManager.h> +#include <CommonsJavaScript/Validator.h> +#include <CommonsJavaScript/JSUtils.h> +#include <CommonsJavaScript/Utils.h> +#include <JSWebAPIErrorFactory.h> +#include <SecurityExceptions.h> +#include <ArgumentValidator.h> +#include <JSUtil.h> +#include <Export.h> + +#include <TimeTracer.h> +#include "FilesystemUtils.h" +#include "Converter.h" +#include "plugin_config.h" +#include "Encodings.h" +#include "JSFilestream.h" +#include "ResponseDispatcher.h" +#include "FilesystemAsyncCallbackManager.h" +#include <Logger.h> + +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace DeviceAPI::Common; + +namespace { +#define PLUGIN_NAME "File" +#define PROPERTY_PARENT "parent" +#define PROPERTY_READ_ONLY "readOnly" +#define PROPERTY_IS_FILE "isFile" +#define PROPERTY_IS_DIRECTORY "isDirectory" +#define PROPERTY_CREATED "created" +#define PROPERTY_MODIFIED "modified" +#define PROPERTY_PATH "path" +#define PROPERTY_NAME "name" +#define PROPERTY_FULL_PATH "fullPath" +#define PROPERTY_FILE_SIZE "fileSize" +#define PROPERTY_LENGTH "length" +} //namespace + +JSValueRef getFunctionOrNull(JSContextRef ctx, JSValueRef arg) +{ + if (Validator(ctx).isCallback(arg)) { + return arg; + } else if (!JSValueIsNull(ctx, arg) && !JSValueIsUndefined(ctx, arg)) { + ThrowMsg(ConversionException, "Not a function nor JS null."); + } + return NULL; +} + + + +JSValueRef getFunction(JSContextRef ctx, JSValueRef arg) +{ + if (Validator(ctx).isCallback(arg)) { + return arg; + } else{ + ThrowMsg(ConversionException, "Not a function nor JS null."); + } +} + +namespace DeviceAPI { +namespace Filesystem { + +JSClassRef JSFile::m_classRef = 0; + +JSClassDefinition JSFile::m_classInfo = { + 0, + kJSClassAttributeNone, + PLUGIN_NAME, + 0, + m_properties, + m_functions, + initialize, + finalize, + NULL, + NULL, + NULL, + NULL, + getPropertyNames, + NULL, + NULL, + hasInstance, + NULL +}; + +JSStaticValue JSFile::m_properties[] = { + { PROPERTY_PARENT, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_READ_ONLY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_IS_FILE, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_IS_DIRECTORY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_CREATED, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_MODIFIED, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_PATH, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_NAME, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_FULL_PATH, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_FILE_SIZE, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_LENGTH, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSFile::m_functions[] = { + { "toURI", toUri, kJSPropertyAttributeNone }, + { "listFiles", listFiles, kJSPropertyAttributeNone }, + { "openStream", openStream, kJSPropertyAttributeNone }, + { "readAsText", readAsText, kJSPropertyAttributeNone }, + { "copyTo", copyTo, kJSPropertyAttributeNone }, + { "moveTo", moveTo, kJSPropertyAttributeNone }, + { "createDirectory", createDirectory, kJSPropertyAttributeNone }, + { "createFile", createFile, kJSPropertyAttributeNone }, + { "resolve", resolve, kJSPropertyAttributeNone }, + { "deleteDirectory", deleteDirectory, kJSPropertyAttributeNone }, + { "deleteFile", deleteFile, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +void JSFile::initialize(JSContextRef context, + JSObjectRef object) +{ +} + +void JSFile::finalize(JSObjectRef object) +{ + PrivateObject* privateObject = static_cast<PrivateObject*>(JSObjectGetPrivate(object)); + if (privateObject) { + JSObjectSetPrivate(object, NULL); + delete privateObject; + } +} + +const JSClassRef DLL_EXPORT JSFile::getClassRef() +{ + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +const JSClassDefinition* JSFile::getClassInfo() +{ + return &m_classInfo; +} + +JSValueRef JSFile::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + PrivateObject* privateObject = + static_cast<PrivateObject*>(JSObjectGetPrivate(object)); + if (!privateObject) { + LoggerE("Private object is not set."); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type mismatch error"); + } + + JSContextRef globalContext = privateObject->getContext(); + Converter converter(globalContext); + + try { + if (JSStringIsEqualToUTF8CString(propertyName, PROPERTY_PARENT)) + { + INodePtr parent(privateObject->getObject()->getNode()->getParent()); + PrivateObjectDef::PermissionList perms = + privateObject->getObject()->getParentPermissions(); + if (parent && !perms.empty()) + { + parent->setPermissions(perms.back()); + perms.pop_back(); + PrivateObjectDefPtr privData(new PrivateObjectDef(parent, perms)); + + return JSUtils::makeObject(privateObject->getContext(), getClassRef(), privData); + } + return JSValueMakeNull(context); + } + else if (JSStringIsEqualToUTF8CString(propertyName, PROPERTY_READ_ONLY)) + { + bool readOnly = ((privateObject->getObject()->getNode()->getMode() & PM_USER_WRITE) == 0); + return converter.toJSValueRef(readOnly); + } + else if (JSStringIsEqualToUTF8CString(propertyName, PROPERTY_IS_FILE)) + { + bool isFile = (privateObject->getObject()->getNode()->getType() == NT_FILE); + return converter.toJSValueRef(isFile); + } + else if (JSStringIsEqualToUTF8CString(propertyName, + PROPERTY_IS_DIRECTORY)) + { + bool isDirectory = (privateObject->getObject()->getNode()->getType() == NT_DIRECTORY); + return converter.toJSValueRef(isDirectory); + } + else if (JSStringIsEqualToUTF8CString(propertyName, PROPERTY_CREATED)) + { + std::time_t created = privateObject->getObject()->getNode()->getCreated(); + return converter.toJSValueRef(created); + } + else if (JSStringIsEqualToUTF8CString(propertyName, PROPERTY_MODIFIED)) + { + std::time_t modified = privateObject->getObject()->getNode()->getModified(); + return converter.toJSValueRef(modified); + } + else if (JSStringIsEqualToUTF8CString(propertyName, PROPERTY_PATH)) + { + std::string fpath = privateObject->getObject()->getNode()->getPath()->getFullPath(); + std::string vpath = Utils::toVirtualPath(globalContext, fpath); + std::string::size_type pos = vpath.rfind(IPath::getSeparator()); + std::string path = (std::string::npos != pos ? vpath.substr(0, pos + 1) : vpath); + return converter.toJSValueRef(path); + } + else if (JSStringIsEqualToUTF8CString(propertyName, PROPERTY_NAME)) + { + std::string fpath = privateObject->getObject()->getNode()->getPath()->getFullPath(); + std::string vpath = Utils::toVirtualPath(globalContext, fpath); + std::string name; + std::string::size_type pos = vpath.rfind(IPath::getSeparator()); + + if (std::string::npos != pos) { + name = vpath.substr(pos + 1); + } + return converter.toJSValueRef(name); + } + else if (JSStringIsEqualToUTF8CString(propertyName, PROPERTY_FULL_PATH)) + { + std::string path = privateObject->getObject()->getNode()->getPath()->getFullPath(); + return converter.toJSValueRef(Utils::toVirtualPath(globalContext, path)); + } + else if (JSStringIsEqualToUTF8CString(propertyName, PROPERTY_FILE_SIZE)) + { + if (privateObject->getObject()->getNode()->getType() == NT_DIRECTORY) + { + return JSValueMakeUndefined(context); + } + return converter.toJSValueRef(privateObject->getObject()->getNode()->getSize()); + } + else if (JSStringIsEqualToUTF8CString(propertyName, PROPERTY_LENGTH)) + { + if (privateObject->getObject()->getNode()->getType() == NT_FILE) { + return JSValueMakeUndefined(context); + } + // TODO: think about more efficent solution! + NodeList children = privateObject->getObject()->getNode()->getChildNodes(); + return converter.toJSValueRef(children.size()); + } + } + catch (const WrtDeviceApis::Commons::Exception& ex) { + LoggerE("Exception: " << ex.GetMessage()); + } + /* + else if (JSStringIsEqualToUTF8CString(propertyName, PROPERTY_READ_ONLY)) { + bool readOnly = ((privateObject->getObject()->getNode() & PERM_WRITE) == 0); + return converter.toJSValueRef(readOnly); + } else if (JSStringIsEqualToUTF8CString(propertyName, PROPERTY_IS_FILE)) { + bool isFile = (privateObject->getObject()->getNode()->getType() == NT_FILE); + return converter.toJSValueRef(isFile); + } else if (JSStringIsEqualToUTF8CString(propertyName, PROPERTY_IS_DIRECTORY)) { + bool isDirectory =(privateObject->getObject()->getNode()->getType() == NT_DIRECTORY); + return converter.toJSValueRef(isDirectory); + } else if (JSStringIsEqualToUTF8CString(propertyName, PROPERTY_CREATED)) { + std::time_t created = privateObject->getObject()->getNode()->getCreated(); + return converter.toJSValueRef(created); + } else if (JSStringIsEqualToUTF8CString(propertyName, PROPERTY_MODIFIED)) { + std::time_t modified = privateObject->getObject()->getNode()->getModified(); + return converter.toJSValueRef(modified); + } else if (JSStringIsEqualToUTF8CString(propertyName, PROPERTY_PATH)) { + std::string fpath = privateObject->getObject()->getNode()->getPath()->getFullPath(); + std::string vpath = Utils::toVirtualPath(globalContext, fpath); + std::string::size_type pos = vpath.rfind(IPath::getSeparator()); + std::string path = (std::string::npos != pos ? vpath.substr(0, pos + 1) : vpath); + return converter.toJSValueRef(path); + } else if (JSStringIsEqualToUTF8CString(propertyName, PROPERTY_NAME)) { + std::string fpath = privateObject->getObject()->getNode()->getPath()->getFullPath(); + std::string vpath = Utils::toVirtualPath(globalContext, fpath); + std::string name; + std::string::size_type pos = vpath.rfind(IPath::getSeparator()); + if (std::string::npos != pos) { + name = vpath.substr(pos + 1); + } + return converter.toJSValueRef(name); + } else if (JSStringIsEqualToUTF8CString(propertyName, PROPERTY_FULL_PATH)) { + std::string path = privateObject->getObject()->getNode()->getPath()->getFullPath(); + return converter.toJSValueRef(Utils::toVirtualPath(globalContext, path)); + } else if (JSStringIsEqualToUTF8CString(propertyName, PROPERTY_FILE_SIZE)) { + if (privateObject->getObject()->getNode()->getType() == NT_DIRECTORY) { + return JSValueMakeUndefined(context); + } + return converter.toJSValueRef(privateObject->getObject()->getNode()->getSize()); + } else if (JSStringIsEqualToUTF8CString(propertyName, PROPERTY_LENGTH)) { + if (privateObject->getObject()->getNode()->getType() == NT_FILE) { + return JSValueMakeUndefined(context); + } + NodeList children = privateObject->getObject()->getNode()->getChildNodes(); + return converter.toJSValueRef(children.size()); + } + } catch (const WrtDeviceApis::Commons::Exception& ex) { + LoggerW("trying to get incorrect value"); + }*/ + + return JSValueMakeUndefined(context); +} + +void JSFile::getPropertyNames(JSContextRef context, + JSObjectRef object, + JSPropertyNameAccumulatorRef propertyNames) +{ +} + +bool JSFile::hasInstance(JSContextRef context, + JSObjectRef constructor, + JSValueRef possibleInstance, + JSValueRef* exception) +{ + return JSValueIsObjectOfClass(context, possibleInstance, getClassRef()); +} + +JSValueRef JSFile::toUri(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argc, + const JSValueRef argv[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + PrivateObject* privateObject = static_cast<PrivateObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LoggerE("Private object is not set."); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type mismatch error"); + } + + Converter converter(context); + + AceSecurityStatus status = FILESYSTEM_CHECK_ACCESS(FILESYSTEM_FUNCTION_API_TO_URI); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + + try { + int widgetId = WrtAccessSingleton::Instance().getWidgetId(); + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return converter.toJSValueRef(privateObject->getObject()->getNode()->toUri(widgetId)); + } /*catch(const WrtDeviceApis::Commons::ConversionException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, ex.GetMessage()); + }*/ catch (const WrtDeviceApis::Commons::UnsupportedException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_SUPPORTED_ERROR, ex.GetMessage()); + } /*catch(const WrtDeviceApis::Commons::InvalidArgumentException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, ex.GetMessage()); + } */catch(const WrtDeviceApis::Commons::Exception& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, ex.GetMessage()); + } +} + +JSValueRef JSFile::listFiles(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argc, + const JSValueRef argv[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + PrivateObject* privateObject = static_cast<PrivateObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type mismatch error"); + } + + LoggerD("OK"); + + // argument validation with new validator + try { + ArgumentValidator validator(context, argc, argv); + validator.toFunction(0, false); + validator.toFunction(1, true); + validator.toObject(2, true); + } + catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(context, exception, err); + } catch (...) { + DeviceAPI::Common::UnknownException err(""); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + + JSContextRef globalContext = privateObject->getContext(); + size_t index = 0; + JSValueRef reserveArguments[3]; + JSCallbackManagerPtr cbm = JSCallbackManager::createObject(globalContext); + + try { + + AceSecurityStatus status = FILESYSTEM_CHECK_ACCESS(FILESYSTEM_FUNCTION_API_LIST_FILES); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + for (index = 0; index < 3; index++) + { + if (index < argc) + reserveArguments[index] = argv[index]; + else + reserveArguments[index] = JSValueMakeUndefined(context); + } + + JSValueRef onSuccess = getFunction(globalContext, reserveArguments[0]); + JSValueRef onError = NULL; + + + if (argc > 1) { + onError = getFunctionOrNull(globalContext, reserveArguments[1]); + } + + cbm->setOnSuccess(onSuccess); + cbm->setOnError(onError); + cbm->setObject(thisObject); + + Converter converter(globalContext); + + EventListNodesPtr event(new EventListNodes(privateObject->getObject()->getNode())); + if (argc > 2) { + if (JSValueIsNull(context, reserveArguments[2]) == false && + JSValueIsUndefined(context, reserveArguments[2]) == false) { + NodeFilterPtr filter = converter.toNodeFilter(reserveArguments[2]); + + if (filter->isFilterValid()) { + event->setFilter(converter.toNodeFilter(reserveArguments[2])); + } + } + } + PrivateObjectDef::PermissionList perms = + privateObject->getObject()->getParentPermissions(); + perms.push_back(privateObject->getObject()->getNode()->getPermissions()); + + ListFilesPrivateDataPtr privData(new ListFilesPrivateData(cbm, perms)); + + event->setPrivateData(DPL::StaticPointerCast<WrtDeviceApis::Commons::IEventPrivateData>(privData)); + event->setForAsynchronousCall(&ResponseDispatcher::getInstance()); + + privateObject->getObject()->getNode()->getChildNodes(event); + FilesystemAsyncCallbackManagerSingleton::Instance().registerCallbackManager(cbm, globalContext); + + + } catch(const WrtDeviceApis::Commons::ConversionException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, ex.GetMessage()); + } catch (const WrtDeviceApis::Commons::UnsupportedException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_SUPPORTED_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::InvalidArgumentException& ex) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, ex.GetMessage())); + } catch(const WrtDeviceApis::Commons::Exception& ex) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::UNKNOWN_ERROR, ex.GetMessage())); + } + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); +} + +JSValueRef JSFile::openStream(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + PrivateObject* privateObject = static_cast<PrivateObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type mismatch error"); + } + + // argument validation with new validator + try { + ArgumentValidator validator(context, argumentCount, arguments); + validator.toFunction(1, false); + validator.toFunction(2, true); + } + catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(context, exception, err); + } catch (...) { + DeviceAPI::Common::UnknownException err(""); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + + JSContextRef globalContext = privateObject->getContext(); + JSCallbackManagerPtr cbm = JSCallbackManager::createObject(globalContext); + + size_t index = 0; + JSValueRef reserveArguments[4]; + + AceSecurityStatus status = FILESYSTEM_CHECK_ACCESS(FILESYSTEM_FUNCTION_API_OPEN_STREAM); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + + try { + + for (index = 0; index < 4; index++) { + if (index < argumentCount) + reserveArguments[index] = arguments[index]; + else + reserveArguments[index] = JSValueMakeUndefined(context); + + } + + JSValueRef onSuccess = getFunction(globalContext, reserveArguments[1]); + JSValueRef onError = NULL; + + onError = getFunctionOrNull(globalContext, reserveArguments[2]); + + cbm->setOnSuccess(onSuccess); + cbm->setOnError(onError); + cbm->setObject(thisObject); + + + Converter converter(globalContext); + + AccessMode mode = converter.toAccessMode(reserveArguments[0]); + std::string encoding = Encodings::UTF8; + if (argumentCount > 3) { + if(!JSValueIsNull(globalContext, reserveArguments[3]) && !JSValueIsUndefined(globalContext, reserveArguments[3])){ + encoding = converter.toEncoding(reserveArguments[3]); + } + } + + if ((AM_READ != mode) && (PERM_READ == privateObject->getObject()->getNode()->getPermissions())) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, + JSWebAPIErrorFactory::INVALID_VALUES_ERROR, "permission denied error")); + return JSValueMakeUndefined(context); + } + + std::string path = privateObject->getObject()->getNode()->getPath()->getFullPath(); + std::string vpath = Utils::toVirtualPath(globalContext, path); + + AccessModeInfo am = AccessModeInfo(mode, vpath); + status = FILESYSTEM_ACCESSMODE_CHECK_ACCESS(FILESYSTEM_FUNCTION_API_OPEN_STREAM, am); + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + EventOpenPtr event(new EventOpen(mode)); + event->setPrivateData(DPL::StaticPointerCast<WrtDeviceApis::Commons::IEventPrivateData>(cbm)); + event->setCharSet(encoding); + event->setForAsynchronousCall(&ResponseDispatcher::getInstance()); + FilesystemAsyncCallbackManagerSingleton::Instance().registerCallbackManager(cbm, globalContext); + + privateObject->getObject()->getNode()->open(event); + + + } catch(const WrtDeviceApis::Commons::ConversionException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, ex.GetMessage()); + } catch (const WrtDeviceApis::Commons::UnsupportedException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_SUPPORTED_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::InvalidArgumentException& ex) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, ex.GetMessage())); + } catch(const WrtDeviceApis::Commons::Exception& ex) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::UNKNOWN_ERROR, ex.GetMessage())); + } + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); +} + +JSValueRef JSFile::readAsText(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argc, + const JSValueRef argv[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + PrivateObject* privateObject = static_cast<PrivateObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type mismatch error"); + } + + + // argument validation with new validator + try { + ArgumentValidator validator(context, argc, argv); + validator.toFunction(0, false); + validator.toFunction(1, true); + } + catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(context, exception, err); + } catch (...) { + DeviceAPI::Common::UnknownException err(""); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + + + JSContextRef globalContext = privateObject->getContext(); + AceSecurityStatus status = FILESYSTEM_CHECK_ACCESS(FILESYSTEM_FUNCTION_API_READ_AS_TEXT); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + size_t index = 0; + JSValueRef reserveArguments[3]; + JSCallbackManagerPtr cbm = JSCallbackManager::createObject(globalContext); + + try { + + for (index = 0; index < 3; index++) { + if (index < argc) + reserveArguments[index] = argv[index]; + else + reserveArguments[index] = JSValueMakeUndefined(context); + + } + + + JSValueRef onSuccess = getFunction(globalContext, reserveArguments[0]); + JSValueRef onError = NULL; + + if (argc > 1) { + onError = getFunctionOrNull(globalContext, reserveArguments[1]); + } + + cbm->setOnSuccess(onSuccess); + cbm->setOnError(onError); + cbm->setObject(thisObject); + + Converter converter(context); + std::string src = Encodings::UTF8; + if (argc > 2) { + if (!JSValueIsNull(context, reserveArguments[2]) && !JSValueIsUndefined(context, reserveArguments[2])) { + src = converter.toEncoding(reserveArguments[2]); + } + } + + if (NT_FILE != privateObject->getObject()->getNode()->getType()) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::IO_ERROR, "IO error")); + return JSValueMakeUndefined(context); + } + + EventReadTextPtr event(new EventReadText()); + event->setPrivateData(DPL::StaticPointerCast<WrtDeviceApis::Commons::IEventPrivateData,JSCallbackManager>(cbm)); + event->setCharSet(src); + event->setForAsynchronousCall(&ResponseDispatcher::getInstance()); + FilesystemAsyncCallbackManagerSingleton::Instance().registerCallbackManager(cbm, globalContext); + + privateObject->getObject()->getNode()->read(event); + + } catch(const WrtDeviceApis::Commons::ConversionException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, ex.GetMessage()); + } catch (const WrtDeviceApis::Commons::UnsupportedException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_SUPPORTED_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::InvalidArgumentException& ex) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, ex.GetMessage())); + } catch(const WrtDeviceApis::Commons::Exception& ex) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::UNKNOWN_ERROR, ex.GetMessage())); + } + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); +} + +JSValueRef JSFile::copyTo(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argc, + const JSValueRef argv[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + PrivateObject* privateObject = static_cast<PrivateObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type mismatch error"); + } + + JSContextRef globalContext = privateObject->getContext(); + size_t index = 0; + JSValueRef reserveArguments[5]; + JSCallbackManagerPtr cbm = JSCallbackManager::createObject(globalContext); + + AceSecurityStatus status = FILESYSTEM_CHECK_ACCESS(FILESYSTEM_FUNCTION_API_COPY_TO); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + // argument validation with new validator + try { + ArgumentValidator validator(context, argc, argv); + validator.toFunction(3, true); + validator.toFunction(4, true); + } + catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(context, exception, err); + } catch (...) { + DeviceAPI::Common::UnknownException err(""); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + + + try { + + for (index = 0; index < 5; index++) + { + if (index < argc) + reserveArguments[index] = argv[index]; + else + reserveArguments[index] = JSValueMakeUndefined(context); + } + + Converter converter(globalContext); + JSValueRef onSuccess = NULL; + JSValueRef onError = NULL; + + onSuccess = getFunctionOrNull(globalContext, reserveArguments[3]); + onError = getFunctionOrNull(globalContext, reserveArguments[4]); + + cbm->setOnSuccess(onSuccess); + cbm->setOnError(onError); + cbm->setObject(thisObject); + + + //TODO add check validation for src, dest string. + IPathPtr src = Utils::fromVirtualPath(globalContext, converter.toString(reserveArguments[0])); + IPathPtr dest = Utils::fromVirtualPath(globalContext, converter.toString(reserveArguments[1])); + bool overwrite = converter.toBool(reserveArguments[2]);; + + /* if ((privateObject->getObject()->getNode()->getPermissions() & PERM_WRITE) == 0) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, + JSWebAPIErrorFactory::INVALID_VALUES_ERROR, "permission denied error")); + return JSValueMakeUndefined(context); + }*/ + + if (NT_DIRECTORY != privateObject->getObject()->getNode()->getType()) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::IO_ERROR, "IO error")); + return JSValueMakeUndefined(context); + } + + std::string virtualDestPath = Utils::toVirtualPath(globalContext, dest->getFullPath()); + AccessModeInfo amode = AccessModeInfo(AM_WRITE, virtualDestPath); + status = FILESYSTEM_ACCESSMODE_CHECK_ACCESS( + FILESYSTEM_FUNCTION_API_COPY_TO, + amode); + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + EventCopyPtr event(new EventCopy(src, dest)); + + if (overwrite) { + event->setOptions(OPT_OVERWRITE); + } + + event->setPrivateData(DPL::StaticPointerCast<WrtDeviceApis::Commons:: + IEventPrivateData, + JSCallbackManager>( + cbm)); + event->setForAsynchronousCall(&ResponseDispatcher::getInstance()); + FilesystemAsyncCallbackManagerSingleton::Instance().registerCallbackManager(cbm, globalContext); + + IManager::getInstance().copy(event); + } catch(const WrtDeviceApis::Commons::ConversionException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, ex.GetMessage()); + } catch (const WrtDeviceApis::Commons::UnsupportedException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_SUPPORTED_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::NotFoundException &ex) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::NOT_FOUND_ERROR, ex.GetMessage())); + } catch(const WrtDeviceApis::Commons::InvalidArgumentException& ex) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, ex.GetMessage())); + } catch(const WrtDeviceApis::Commons::Exception& ex) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::UNKNOWN_ERROR, ex.GetMessage())); + } + + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); +} + +JSValueRef JSFile::moveTo(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argc, + const JSValueRef argv[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + PrivateObject* privateObject = static_cast<PrivateObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type mismatch error"); + } + + JSContextRef globalContext = privateObject->getContext(); + + LoggerD("OK"); + + // argument validation with new validator + try { + ArgumentValidator validator(context, argc, argv); + validator.toFunction(3, true); + validator.toFunction(4, true); + } + catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(context, exception, err); + } catch (...) { + DeviceAPI::Common::UnknownException err(""); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + + size_t index = 0; + JSValueRef reserveArguments[5]; + JSCallbackManagerPtr cbm = JSCallbackManager::createObject(globalContext); + + AceSecurityStatus status = FILESYSTEM_CHECK_ACCESS(FILESYSTEM_FUNCTION_API_MOVE_TO); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + try { + + for (index = 0; index < 5; index++) { + if (index < argc) + reserveArguments[index] = argv[index]; + else + reserveArguments[index] = JSValueMakeUndefined(context); + } + + Converter converter(context); + JSValueRef onSuccess = NULL; + JSValueRef onError = NULL; + + onSuccess = getFunctionOrNull(globalContext, reserveArguments[3]); + onError = getFunctionOrNull(globalContext, reserveArguments[4]); + cbm->setOnSuccess(onSuccess); + cbm->setOnError(onError); + cbm->setObject(thisObject); + +/* if ((privateObject->getObject()->getNode()->getPermissions() & PERM_WRITE) == 0) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, + JSWebAPIErrorFactory::INVALID_VALUES_ERROR, "permission denied error")); + return JSValueMakeUndefined(context); + }*/ + + if (NT_DIRECTORY != privateObject->getObject()->getNode()->getType()) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::IO_ERROR, "io error")); + return JSValueMakeUndefined(context); + } + + IPathPtr src = Utils::fromVirtualPath(globalContext, converter.toString(reserveArguments[0])); + IPathPtr dest = Utils::fromVirtualPath(globalContext, converter.toString(reserveArguments[1])); + bool overwrite = converter.toBool(reserveArguments[2]); + + std::string virtualDestPath = Utils::toVirtualPath(globalContext, dest->getFullPath()); + + AccessModeInfo amode = AccessModeInfo(AM_WRITE, virtualDestPath); + AceSecurityStatus status = FILESYSTEM_ACCESSMODE_CHECK_ACCESS(FILESYSTEM_FUNCTION_API_MOVE_TO, amode); + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + EventMovePtr event(new EventMove(src, dest)); + if (overwrite) { + event->setOptions(OPT_OVERWRITE); + } + + event->setForAsynchronousCall(&ResponseDispatcher::getInstance()); + event->setPrivateData(DPL::StaticPointerCast<WrtDeviceApis::Commons::IEventPrivateData > (cbm)); + FilesystemAsyncCallbackManagerSingleton::Instance().registerCallbackManager(cbm, globalContext); + + IManager::getInstance().move(event); + + } catch(const WrtDeviceApis::Commons::ConversionException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, ex.GetMessage()); + } catch (const WrtDeviceApis::Commons::UnsupportedException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_SUPPORTED_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::NotFoundException &ex) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::NOT_FOUND_ERROR, ex.GetMessage())); + } + catch(const WrtDeviceApis::Commons::InvalidArgumentException& ex) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, ex.GetMessage())); + } catch(const WrtDeviceApis::Commons::Exception& ex) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::UNKNOWN_ERROR, ex.GetMessage())); + } + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); +} + +JSValueRef JSFile::createDirectory(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argc, + const JSValueRef argv[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + PrivateObject* privateObject = static_cast<PrivateObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type mismatch error"); + } + + AceSecurityStatus status = FILESYSTEM_CHECK_ACCESS(FILESYSTEM_FUNCTION_API_CREATE_DIR); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + + Converter converter(context); + try { + + if (argc < 1) { + ThrowMsg(InvalidArgumentException, "Invalid path name"); + } +/* if ((privateObject->getObject()->getNode()->getPermissions() & PERM_WRITE) == 0) { + ThrowMsg(WrtDeviceApis::Commons::SecurityException, "Permission denied error"); + }*/ + + std::string createName = converter.toString(argv[0]); + DeviceAPI::Filesystem::Utils::checkCreationName(createName, true); + + + IPathPtr path = converter.toPath(argv[0]); + + INodePtr node(privateObject->getObject()->getNode()->createChild(path, NT_DIRECTORY, OPT_RECURSIVE)); + node->setPermissions(privateObject->getObject()->getNode()->getPermissions()); + + PrivateObjectDefPtr privData(new PrivateObjectDef(node, privateObject->getObject()->getParentPermissions())); + privData->pushParentPermissions(privateObject->getObject()->getNode()->getPermissions()); + + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return WrtDeviceApis::CommonsJavaScript::JSUtils::makeObject(privateObject->getContext(), getClassRef(), privData); + } catch (const WrtDeviceApis::Commons::SecurityException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, ex.GetMessage()); + } + catch (const WrtDeviceApis::Commons::PlatformException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::IO_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::ConversionException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, ex.GetMessage()); + } catch (const WrtDeviceApis::Commons::UnsupportedException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_SUPPORTED_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::InvalidArgumentException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::Exception& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, ex.GetMessage()); + } +} + +JSValueRef JSFile::createFile(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argc, + const JSValueRef argv[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + PrivateObject* privateObject = static_cast<PrivateObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type mismatch error"); + } + + AceSecurityStatus status = FILESYSTEM_CHECK_ACCESS(FILESYSTEM_FUNCTION_API_CREATE_FILE); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + + Converter converter(context); + try { + + if (argc < 1) { + ThrowMsg(InvalidArgumentException, "Invalid path name"); + } + +/* if ((privateObject->getObject()->getNode()->getPermissions() & PERM_WRITE) == 0) { + ThrowMsg(WrtDeviceApis::Commons::SecurityException, "Permission denied error"); + }*/ + + std::string createName = converter.toString(argv[0]); + DeviceAPI::Filesystem::Utils::checkCreationName(createName, false); + + IPathPtr path = converter.toPath(argv[0]); + + INodePtr node = privateObject->getObject()->getNode()->createChild(path, NT_FILE); + + PrivateObjectDefPtr privData(new PrivateObjectDef(node, privateObject->getObject()->getParentPermissions())); + privData->pushParentPermissions(privateObject->getObject()->getNode()->getPermissions()); + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return WrtDeviceApis::CommonsJavaScript::JSUtils::makeObject(privateObject->getContext(), getClassRef(), privData); + + } catch (const WrtDeviceApis::Commons::SecurityException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, ex.GetMessage()); + } catch (const WrtDeviceApis::Commons::PlatformException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::IO_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::ConversionException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, ex.GetMessage()); + } catch (const WrtDeviceApis::Commons::UnsupportedException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_SUPPORTED_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::InvalidArgumentException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::Exception& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, ex.GetMessage()); + } + +} + +JSValueRef JSFile::resolve(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argc, + const JSValueRef argv[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + PrivateObject* privateObject = static_cast<PrivateObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type mismatch error"); + } + + AceSecurityStatus status = FILESYSTEM_CHECK_ACCESS(FILESYSTEM_FUNCTION_API_RESOLVE); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + if (privateObject->getObject()->getNode()->getType() != NT_DIRECTORY) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::IO_ERROR, "IO error"); + } + + Converter converter(context); + + try { + if (argc < 1) { + ThrowMsg(InvalidArgumentException, "Invalid path name"); + } + + IPathPtr path = converter.toPath(argv[0]); + INodePtr node = privateObject->getObject()->getNode()->getChild(path); + node->setPermissions(privateObject->getObject()->getNode()->getPermissions()); + PrivateObjectDefPtr privData(new PrivateObjectDef(node, privateObject->getObject()->getParentPermissions())); + privData->pushParentPermissions(privateObject->getObject()->getNode()->getPermissions()); + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return WrtDeviceApis::CommonsJavaScript::JSUtils::makeObject(privateObject->getContext(), getClassRef(), privData); + /* + IPathPtr path = converter.toPath(argv[0]); + INodePtr node = privateObject->getObject()->getNode()->getChild(path); + node->setPermissions(privateObject->getObject()->getNode()->getPermissions()); + return JSUtils::makeObject(privateObject->getContext(), getClassRef(), node); + */ + } catch (const WrtDeviceApis::Commons::PlatformException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::IO_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::ConversionException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, ex.GetMessage()); + } catch (const WrtDeviceApis::Commons::UnsupportedException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_SUPPORTED_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::InvalidArgumentException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::NotFoundException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_FOUND_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::Exception& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, ex.GetMessage()); + } +} + +JSValueRef JSFile::deleteDirectory(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argc, + const JSValueRef argv[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + PrivateObject* privateObject = static_cast<PrivateObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type mismatch error"); + } + + AceSecurityStatus status = FILESYSTEM_CHECK_ACCESS(FILESYSTEM_FUNCTION_API_DELETE_DIR); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + if (argc < 2) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type missmatch error"); + } + + JSContextRef globalContext = privateObject->getContext(); + + LoggerD("OK"); + + // argument validation with new validator + try { + ArgumentValidator validator(context, argc, argv); + validator.toFunction(2, true); + validator.toFunction(3, true); + } + catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(context, exception, err); + } catch (...) { + DeviceAPI::Common::UnknownException err(""); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + + size_t index = 0; + JSValueRef reserveArguments[4]; + JSCallbackManagerPtr cbm = JSCallbackManager::createObject(globalContext); + + try { + for (index = 0; index < 4; index++) { + if (index < argc) + reserveArguments[index] = argv[index]; + else + reserveArguments[index] = JSValueMakeUndefined(context); + } + + + JSValueRef onSuccess = NULL; + JSValueRef onError = NULL; + + onSuccess = getFunctionOrNull(globalContext, reserveArguments[2]); + onError = getFunctionOrNull(globalContext, reserveArguments[3]); + + cbm->setOnSuccess(onSuccess); + cbm->setOnError(onError); + cbm->setObject(thisObject); + +/* if ((privateObject->getObject()->getNode()->getPermissions() & PERM_WRITE) == 0) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, + JSWebAPIErrorFactory::INVALID_VALUES_ERROR, "permission denied error")); + return JSValueMakeUndefined(context); + }*/ + + if (privateObject->getObject()->getNode()->getType() != NT_DIRECTORY) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::IO_ERROR, "IO error")); + return JSValueMakeUndefined(context); + } + + Converter converter(context); + IPathPtr path = Utils::fromVirtualPath(globalContext, converter.toString(reserveArguments[0])); + bool recursive = converter.toBool(reserveArguments[1]); + + /* + if (privateObject->getObject()->getNode()->getPath()->getFullPath() != path->getPath()) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::NOT_FOUND_ERROR, "not found error in current directory")); + return JSValueMakeUndefined(context); + } + */ + + EventResolvePtr eventResolve(new EventResolve(path)); + if (eventResolve->setForSynchronousCall()) { + IManager::getInstance().getNode(eventResolve); + if (!eventResolve->getResult() || (eventResolve->getExceptionCode() != WrtDeviceApis::Commons::ExceptionCodes::None)) { + + if(eventResolve->getExceptionCode() == WrtDeviceApis::Commons::ExceptionCodes::NotFoundException) + ThrowMsg(WrtDeviceApis::Commons::NotFoundException, "Not found error"); + else if(eventResolve->getExceptionCode() == WrtDeviceApis::Commons::ExceptionCodes::SecurityException){ + ThrowMsg(WrtDeviceApis::Commons::SecurityException, "Permission denied error"); + } + else + ThrowMsg(PlatformException, "IO Error"); + } + + if (eventResolve->getResult()->getType() != NT_DIRECTORY) { + ThrowMsg(InvalidArgumentException, "Invalid directory"); + } + + EventRemovePtr eventRemove(new EventRemove(path)); + + if (recursive) { + eventRemove->setOptions(OPT_RECURSIVE); + } + + eventRemove->setForAsynchronousCall(&ResponseDispatcher::getInstance()); + eventRemove->setPrivateData(DPL::StaticPointerCast<WrtDeviceApis::Commons::IEventPrivateData > (cbm)); + FilesystemAsyncCallbackManagerSingleton::Instance().registerCallbackManager(cbm, globalContext); + + IManager::getInstance().remove(eventRemove); + } + } catch (const WrtDeviceApis::Commons::PlatformException& ex) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::IO_ERROR, ex.GetMessage())); + + } catch(const WrtDeviceApis::Commons::ConversionException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, ex.GetMessage()); + } catch (const WrtDeviceApis::Commons::UnsupportedException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_SUPPORTED_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::InvalidArgumentException& ex) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, ex.GetMessage())); + } catch(const WrtDeviceApis::Commons::NotFoundException& ex) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::NOT_FOUND_ERROR, ex.GetMessage())); + } catch(const WrtDeviceApis::Commons::SecurityException& ex) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, ex.GetMessage())); + }catch(const WrtDeviceApis::Commons::Exception& ex) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::UNKNOWN_ERROR, ex.GetMessage())); + } + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); +} + +JSValueRef JSFile::deleteFile(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argc, + const JSValueRef argv[], + JSValueRef* exception) +{ + LoggerD("<<<"); + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + + PrivateObject* privateObject = static_cast<PrivateObject*>(JSObjectGetPrivate(thisObject)); + + if (!privateObject) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type mismatch error"); + } + // argument validation with new validator + try { + ArgumentValidator validator(context, argc, argv); + validator.toFunction(1, true); + validator.toFunction(2, true); + } + catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(context, exception, err); + } catch (...) { + DeviceAPI::Common::UnknownException err(""); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + + JSContextRef globalContext = privateObject->getContext(); + + size_t index = 0; + JSValueRef reserveArguments[3]; + JSCallbackManagerPtr cbm = JSCallbackManager::createObject(globalContext); + + AceSecurityStatus status = FILESYSTEM_CHECK_ACCESS(FILESYSTEM_FUNCTION_API_DELETE_FILE); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + + try { + for (index = 0; index < 3; index++) { + if (index < argc) + reserveArguments[index] = argv[index]; + else + reserveArguments[index] = JSValueMakeUndefined(context); + } + + JSValueRef onSuccess = NULL; + JSValueRef onError = NULL; + + onSuccess = getFunctionOrNull(globalContext, reserveArguments[1]); + onError = getFunctionOrNull(globalContext, reserveArguments[2]); + + cbm->setOnSuccess(onSuccess); + cbm->setOnError(onError); + cbm->setObject(thisObject); + +/* + if ((privateObject->getObject()->getNode()->getPermissions() & PERM_WRITE) == 0) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, + JSWebAPIErrorFactory::INVALID_VALUES_ERROR, "permission denied error")); + return JSValueMakeUndefined(context); + }*/ + + if (privateObject->getObject()->getNode()->getType() != NT_DIRECTORY) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::IO_ERROR, "IO error")); + return JSValueMakeUndefined(context); + } + + + Converter converter(context); + IPathPtr path = Utils::fromVirtualPath(globalContext, converter.toString(reserveArguments[0])); + + /*if (privateObject->getObject()->getNode()->getPath()->getFullPath() != path->getPath()) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::NOT_FOUND_ERROR, "not found error in current directory")); + return JSValueMakeUndefined(context); + }*/ + + + EventResolvePtr eventResolve(new EventResolve(path)); + if (eventResolve->setForSynchronousCall()) { + IManager::getInstance().getNode(eventResolve); + + if (!eventResolve->getResult() ||(eventResolve->getExceptionCode() != WrtDeviceApis::Commons::ExceptionCodes::None)) { + if(eventResolve->getExceptionCode() == WrtDeviceApis::Commons::ExceptionCodes::NotFoundException){ + LoggerD("POST IO NOT_FOUND_ERROR"); + ThrowMsg(WrtDeviceApis::Commons::NotFoundException, "Not found error"); + } + if(eventResolve->getExceptionCode() == WrtDeviceApis::Commons::ExceptionCodes::SecurityException){ + ThrowMsg(WrtDeviceApis::Commons::SecurityException, "Permission denied error"); + } + + LoggerD("POST IO ERROR"); + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::IO_ERROR, "IO error")); + return JSValueMakeUndefined(context); + } + + if (eventResolve->getResult()->getType() != NT_FILE) { + ThrowMsg(InvalidArgumentException, "Invalid directory"); + } + + LoggerD("try to call async event"); + EventRemovePtr eventRemove(new EventRemove(path)); + eventRemove->setForAsynchronousCall(&ResponseDispatcher::getInstance()); + eventRemove->setPrivateData(DPL::StaticPointerCast<WrtDeviceApis::Commons::IEventPrivateData > (cbm)); + FilesystemAsyncCallbackManagerSingleton::Instance().registerCallbackManager(cbm, globalContext); + + IManager::getInstance().remove(eventRemove); + + } + } catch (const WrtDeviceApis::Commons::PlatformException& ex) { + LoggerD("Platform Exception !!!!!!!! post io error"); + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::IO_ERROR, ex.GetMessage())); + } catch(const WrtDeviceApis::Commons::ConversionException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, ex.GetMessage()); + } catch (const WrtDeviceApis::Commons::UnsupportedException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_SUPPORTED_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::InvalidArgumentException& ex) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, ex.GetMessage())); + } catch(const WrtDeviceApis::Commons::NotFoundException& ex) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::NOT_FOUND_ERROR, ex.GetMessage())); + } catch(const WrtDeviceApis::Commons::SecurityException& ex) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, ex.GetMessage())); + } catch(const WrtDeviceApis::Commons::Exception& ex) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::UNKNOWN_ERROR, ex.GetMessage())); + } + + LoggerD(">>>"); + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); +} +} +} diff --git a/wearable_src/Filesystem/JSFile.h b/wearable_src/Filesystem/JSFile.h new file mode 100755 index 0000000..162a7bb --- /dev/null +++ b/wearable_src/Filesystem/JSFile.h @@ -0,0 +1,286 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 TIZENAPIS_TIZEN_JSFILE_H_ +#define TIZENAPIS_TIZEN_JSFILE_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <Commons/IEvent.h> +#include <CommonsJavaScript/PrivateObject.h> +#include <CommonsJavaScript/JSCallbackManager.h> +#include "INode.h" + +namespace DeviceAPI { +namespace Filesystem { +class JSFile +{ +public: + + class PrivateObjectDef + { + public: + + typedef std::vector<int> PermissionList; + + PrivateObjectDef(const INodePtr &node, + const PermissionList &parentPermissions) : + m_node(node), + m_parentPerms(parentPermissions) + { + } + + virtual ~PrivateObjectDef() + { + } + + INodePtr getNode() const + { + return m_node; + } + + PermissionList getParentPermissions() const + { + return m_parentPerms; + } + + void setParentPermissions(const PermissionList &permissions) + { + m_parentPerms = permissions; + } + + void pushParentPermissions(int permissions) + { + m_parentPerms.push_back(permissions); + } + + private: + INodePtr m_node; + PermissionList m_parentPerms; + }; + + class ListFilesPrivateData : public WrtDeviceApis::Commons::IEventPrivateData + { + public: + ListFilesPrivateData( + const WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr &callbackManager, + const PrivateObjectDef::PermissionList parentPermissions) : + m_callbackManager(callbackManager), + m_parentPermissions(parentPermissions) + { + } + + virtual ~ListFilesPrivateData() + { + } + + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr getCallbackManager() const + { + return m_callbackManager; + } + + PrivateObjectDef::PermissionList getParentPermissions() const + { + return m_parentPermissions; + } + + private: + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr m_callbackManager; + PrivateObjectDef::PermissionList m_parentPermissions; + }; + + typedef DPL::SharedPtr<ListFilesPrivateData> ListFilesPrivateDataPtr; + typedef DPL::SharedPtr<PrivateObjectDef> PrivateObjectDefPtr; + typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT<PrivateObjectDefPtr>::Type PrivateObject; + +public: + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + +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 JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + /** + * The callback invoked when collecting the names of an object's properties. + */ + static void getPropertyNames(JSContextRef context, + JSObjectRef object, + JSPropertyNameAccumulatorRef propertyNames); + + /** + * 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); + + /** + * Returns a URI for the file. + */ + static JSValueRef toUri(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * Returns list of all files of this directory. + */ + static JSValueRef listFiles(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * WRT_GeneralError exception + */ + static JSValueRef openStream(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * WRT_GeneralError exception + */ + static JSValueRef readAsText(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * The operation is only for file except for directory. + * Make sure the dest directory already exists. + */ + static JSValueRef copyTo(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * This operation is only for file not directory + * The dest directory should exists in local file system, or the operation fails. + */ + static JSValueRef moveTo(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * create directory even through the parent directories do not exist in local file system. + */ + static JSValueRef createDirectory(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * Creates a new empty file in a specified location. + */ + static JSValueRef createFile(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * Resolves an existing file or directory relative to + * the current directory this operation is performed on; and + * returns a file handle for it. + */ + static JSValueRef resolve(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * Removes all files from specified directory if recursive is true, + * or just remove the directory itself when there is no files or directories underneath it + */ + static JSValueRef deleteDirectory(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * Deletes a specified file. + */ + static JSValueRef deleteFile(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_functions[]; + + /** + * This structure describes a statically declared value property. + */ + static JSStaticValue m_properties[]; + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + static JSClassRef m_classRef; +}; +} +} + +#endif
\ No newline at end of file diff --git a/wearable_src/Filesystem/JSFilestream.cpp b/wearable_src/Filesystem/JSFilestream.cpp new file mode 100644 index 0000000..8e36084 --- /dev/null +++ b/wearable_src/Filesystem/JSFilestream.cpp @@ -0,0 +1,492 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "JSFilestream.h" + +#include <dpl/scoped_array.h> + +#include <Commons/Base64.h> +#include <CommonsJavaScript/JSUtils.h> +#include <JSWebAPIErrorFactory.h> +#include <SecurityExceptions.h> +#include <TimeTracer.h> +#include <Export.h> + +#include "Converter.h" +#include "Encodings.h" +#include "plugin_config.h" +#include "FilesystemUtils.h" +#include <Logger.h> + +namespace { +const char* PLUGIN_NAME = "FileStream"; +const char* PROPERTY_EOF = "eof"; +const char* PROPERTY_POSITION = "position"; +const char* PROPERTY_BYTES_AVAILABLE = "bytesAvailable"; +} + +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace DeviceAPI::Common; + +namespace DeviceAPI { +namespace Filesystem { +JSClassRef JSFilestream::m_classRef = 0; + +JSClassDefinition JSFilestream::m_classInfo = { + 0, + kJSClassAttributeNone, + PLUGIN_NAME, + 0, + m_properties, + m_functions, + initialize, + finalize, + NULL, + NULL, + NULL, + NULL, + getPropertyNames, + NULL, + NULL, + hasInstance, + NULL +}; + +JSStaticValue JSFilestream::m_properties[] = { + { PROPERTY_EOF, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { PROPERTY_POSITION, getProperty, setProperty, kJSPropertyAttributeNone }, + { PROPERTY_BYTES_AVAILABLE, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSFilestream::m_functions[] = { + { "close", close, kJSPropertyAttributeNone }, + { "read", read, kJSPropertyAttributeNone }, + { "readBytes", readBytes, kJSPropertyAttributeNone }, + { "readBase64", readBase64, kJSPropertyAttributeNone }, + { "write", write, kJSPropertyAttributeNone }, + { "writeBytes", writeBytes, kJSPropertyAttributeNone }, + { "writeBase64", writeBase64, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +void JSFilestream::initialize(JSContextRef context, + JSObjectRef object) +{ +} + +void JSFilestream::finalize(JSObjectRef object) +{ + PrivateObject* privateObject = static_cast<PrivateObject*>(JSObjectGetPrivate(object)); + delete privateObject; +} + +const JSClassRef DLL_EXPORT JSFilestream::getClassRef() +{ + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +const JSClassDefinition* JSFilestream::getClassInfo() +{ + return &m_classInfo; +} + +JSValueRef JSFilestream::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + PrivateObject* privateObject = static_cast<PrivateObject*>(JSObjectGetPrivate(object)); + if (!privateObject) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type mismatch error"); + + } + + PrivateObject::ObjectType stream = privateObject->getObject(); + Converter converter(context); + try { + if (JSStringIsEqualToUTF8CString(propertyName, PROPERTY_EOF)) { + return converter.toJSValueRef(stream->isEof()); + } else if (JSStringIsEqualToUTF8CString(propertyName, PROPERTY_POSITION)) { + long pos = stream->getPosition(); + if (pos < 0) { + return JSValueMakeUndefined(context); + } + return converter.toJSValueRef(static_cast<unsigned long>(pos)); + } else if (JSStringIsEqualToUTF8CString(propertyName, PROPERTY_BYTES_AVAILABLE)) { + long position = stream->getPosition(); + long bytes = stream->getSize() - position; + + return converter.toJSValueRefLong(static_cast<long>(bytes)); + } + } catch (const WrtDeviceApis::Commons::ConversionException& ex) { + LoggerW("trying to get incorrect value"); + } + + return JSValueMakeUndefined(context); +} + +bool JSFilestream::setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + PrivateObject* privateObject = static_cast<PrivateObject*>(JSObjectGetPrivate(object)); + if (!privateObject) { + return false; + } + + Converter converter(context); + try { + if (JSStringIsEqualToUTF8CString(propertyName, PROPERTY_POSITION)) { + privateObject->getObject()->setPosition(converter.toLong(value)); + return true; + } + } catch (const WrtDeviceApis::Commons::Exception& ex) { + LoggerW("trying to set incorrect value"); + } + + return false; +} + +void JSFilestream::getPropertyNames(JSContextRef context, + JSObjectRef object, + JSPropertyNameAccumulatorRef propertyNames) +{ +} + +bool JSFilestream::hasInstance(JSContextRef context, + JSObjectRef constructor, + JSValueRef instance, + JSValueRef* exception) +{ + return JSValueIsObjectOfClass(context, instance, JSFilestream::getClassRef()); +} + +JSValueRef JSFilestream::close(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argc, + const JSValueRef argv[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + PrivateObject* privateObject = static_cast<PrivateObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type mismatch error"); + + } + + AceSecurityStatus status = FILESYSTEM_CHECK_ACCESS(FILESYSTEM_FUNCTION_API_CLOSE); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + + Try { + privateObject->getObject()->close(); + } Catch (WrtDeviceApis::Commons::PlatformException) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown error"); + } + + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); +} + +JSValueRef JSFilestream::read(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argc, + const JSValueRef argv[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + TIME_TRACER_ITEM_BEGIN("read(UTF8)", 0); + PrivateObject* privateObject = static_cast<PrivateObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type mismatch error"); + } + + Converter converter(context); + + AceSecurityStatus status = FILESYSTEM_CHECK_ACCESS(FILESYSTEM_FUNCTION_API_READ); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + try { + JSValueRef undefinedValue = JSValueMakeUndefined(context); + unsigned long count = 0; + + if (argc > 0) + count = converter.toULong(argv[0]); + else + count = converter.toULong(undefinedValue); + + if (count <= 0) { + ThrowMsg(InvalidArgumentException, "Invalid argument"); + } + std::string outStr = ""; + std::string currentCharSet = privateObject->getObject()->getCharSet(); + + DPL::ScopedArray<char> text(privateObject->getObject()->getChars(count)); + + // utf8, iso8859-1, skip + if (!strcmp(currentCharSet.c_str(), Encodings::UTF8) || !strcmp(currentCharSet.c_str(), Encodings::ISO88591)) + { + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return converter.toJSValueRef(std::string(text.Get())); + } + else + { + Utils::toUTF8String(currentCharSet, text.Get(), count, outStr); + TIME_TRACER_ITEM_END("read(UTF8)", 0); + return converter.toJSValueRef(outStr); + } + } catch(const WrtDeviceApis::Commons::ConversionException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, ex.GetMessage()); + } catch (const WrtDeviceApis::Commons::UnsupportedException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_SUPPORTED_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::InvalidArgumentException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::PlatformException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::IO_ERROR, ex.GetMessage()); + } + +} + +JSValueRef JSFilestream::readBytes(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argc, + const JSValueRef argv[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + PrivateObject* privateObject = static_cast<PrivateObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type mismatch error"); + } + + AceSecurityStatus status = FILESYSTEM_CHECK_ACCESS(FILESYSTEM_FUNCTION_API_READ_BYTES); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + + Converter converter(context); + Try { + JSValueRef undefinedValue = JSValueMakeUndefined(context); + unsigned long count = 0; + + if (argc > 0) + count = converter.toULong(argv[0]); + else + count = converter.toULong(undefinedValue); + + if (count <= 0) { + ThrowMsg(InvalidArgumentException, "Invalid argument"); + } + + DPL::ScopedArray<unsigned char> data(privateObject->getObject()->getBytes(count)); + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return converter.toJSValueRef(data.Get(), privateObject->getObject()->getCount()); + } catch(const WrtDeviceApis::Commons::ConversionException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, ex.GetMessage()); + } catch (const WrtDeviceApis::Commons::UnsupportedException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_SUPPORTED_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::InvalidArgumentException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::PlatformException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::IO_ERROR, ex.GetMessage()); + } + +} + +JSValueRef JSFilestream::readBase64(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argc, + const JSValueRef argv[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + PrivateObject* privateObject = static_cast<PrivateObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type mismatch error"); + } + + AceSecurityStatus status = FILESYSTEM_CHECK_ACCESS(FILESYSTEM_FUNCTION_API_READ_BASE64); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + Converter converter(context); + try { + JSValueRef undefinedValue = JSValueMakeUndefined(context); + unsigned long count = 0; + + if (argc > 0) + count = converter.toULong(argv[0]); + else + count = converter.toULong(undefinedValue); + + if (count <= 0) { + ThrowMsg(InvalidArgumentException, "Invalid argument"); + } + + DPL::ScopedArray<unsigned char> data(privateObject->getObject()->getBytes(count)); + std::string base64 = WrtDeviceApis::Commons::Base64::encode(data.Get(), privateObject->getObject()->getCount()); + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return converter.toJSValueRef(base64); + } catch(const WrtDeviceApis::Commons::ConversionException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, ex.GetMessage()); + } catch (const WrtDeviceApis::Commons::UnsupportedException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_SUPPORTED_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::InvalidArgumentException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::PlatformException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::IO_ERROR, ex.GetMessage()); + } + +} + +JSValueRef JSFilestream::write(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argc, + const JSValueRef argv[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + PrivateObject* privateObject = static_cast<PrivateObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type mismatch error"); + } + + AceSecurityStatus status = FILESYSTEM_CHECK_ACCESS(FILESYSTEM_FUNCTION_API_WRITE); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + + Converter converter(context); + try { + JSValueRef undefinedValue = JSValueMakeUndefined(context); + + if (argc > 0) + privateObject->getObject()->write(converter.toString(argv[0])); + else + privateObject->getObject()->write(converter.toString(undefinedValue)); + + + } catch(const WrtDeviceApis::Commons::ConversionException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, ex.GetMessage()); + } catch (const WrtDeviceApis::Commons::UnsupportedException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_SUPPORTED_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::InvalidArgumentException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::PlatformException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::IO_ERROR, ex.GetMessage()); + } + + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); +} + +JSValueRef JSFilestream::writeBytes(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argc, + const JSValueRef argv[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + PrivateObject* privateObject = static_cast<PrivateObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type mismatch error"); + } + + AceSecurityStatus status = FILESYSTEM_CHECK_ACCESS(FILESYSTEM_FUNCTION_API_WRITE_BYTES); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + + Converter converter(context); + Try { + if (argc < 1 || !JSIsArrayValue(context, argv[0])) + ThrowMsg(ConversionException, "Type mismatch error"); + + PrivateObject::ObjectType stream = privateObject->getObject(); + std::vector<unsigned char> data = converter.toVectorOfUChars(argv[0]); + std::vector<unsigned char>::const_iterator it = data.begin(); + for (; it != data.end(); ++it) { + stream->write(*it); + } + } catch(const WrtDeviceApis::Commons::ConversionException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, ex.GetMessage()); + } catch (const WrtDeviceApis::Commons::UnsupportedException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_SUPPORTED_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::InvalidArgumentException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::PlatformException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::IO_ERROR, ex.GetMessage()); + } + + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); +} + +JSValueRef JSFilestream::writeBase64(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argc, + const JSValueRef argv[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + PrivateObject* privateObject = static_cast<PrivateObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type mismatch error"); + } + + AceSecurityStatus status = FILESYSTEM_CHECK_ACCESS(FILESYSTEM_FUNCTION_API_WRITE_BASE64); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + Converter converter(context); + try { + LoggerD("OK"); + + JSValueRef undefinedValue = JSValueMakeUndefined(context); + std::string base64; + if (argc > 0) + base64 = WrtDeviceApis::Commons::Base64::decode(converter.toString(argv[0])); + else + base64 = WrtDeviceApis::Commons::Base64::decode(converter.toString(undefinedValue)); + + privateObject->getObject()->write(base64); + } catch(const WrtDeviceApis::Commons::ConversionException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, ex.GetMessage()); + } catch (const WrtDeviceApis::Commons::UnsupportedException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_SUPPORTED_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::InvalidArgumentException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::IO_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::PlatformException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::IO_ERROR, ex.GetMessage()); + } + + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); +} +} // Tizen1_0 +} // TizenApis + diff --git a/wearable_src/Filesystem/JSFilestream.h b/wearable_src/Filesystem/JSFilestream.h new file mode 100755 index 0000000..6fc278e --- /dev/null +++ b/wearable_src/Filesystem/JSFilestream.h @@ -0,0 +1,172 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 TIZENAPIS_TIZEN_JSFILESTREAM_H_ +#define TIZENAPIS_TIZEN_JSFILESTREAM_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/PrivateObject.h> +#include "IStream.h" + +namespace DeviceAPI { +namespace Filesystem { +class JSFilestream +{ +public: + typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT<IStreamPtr>::Type PrivateObject; + +public: + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + +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 JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + /** + * The callback invoked when setting a property's value. + */ + static bool setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + /** + * The callback invoked when collecting the names of an object's properties. + */ + static void getPropertyNames(JSContextRef context, + JSObjectRef object, + JSPropertyNameAccumulatorRef propertyNames); + + /** + * 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); + + /** + * Closes this FileStream. + */ + static JSValueRef close(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * Reads the specified number of characters from this FileStream. + */ + static JSValueRef read(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * Reads the specified number of bytes from this FileStream. + */ + static JSValueRef readBytes(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * Reads the specified number of bytes from this FileStream, encoding the result in base64. + */ + static JSValueRef readBase64(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * Writes the specified DOMString to this FileStream. + */ + static JSValueRef write(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * Writes the specified bytes to this FileStream. + */ + static JSValueRef writeBytes(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * Converts the specified base64 DOMString to bytes and writes the result to this FileStream. + */ + static JSValueRef writeBase64(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_functions[]; + + /** + * This structure describes a statically declared value property. + */ + static JSStaticValue m_properties[]; + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + static JSClassRef m_classRef; +}; +} +} + +#endif
\ No newline at end of file diff --git a/wearable_src/Filesystem/JSFilesystemManager.cpp b/wearable_src/Filesystem/JSFilesystemManager.cpp new file mode 100644 index 0000000..c88b13a --- /dev/null +++ b/wearable_src/Filesystem/JSFilesystemManager.cpp @@ -0,0 +1,631 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "JSFilesystemManager.h" +#include <Commons/Exception.h> +#include "EventResolve.h" +#include "IManager.h" +#include "IPath.h" +#include "EventGetStorage.h" +#include "EventListStorages.h" +#include "EventStorageStateChanged.h" +#include <CommonsJavaScript/JSCallbackManager.h> +#include <CommonsJavaScript/Utils.h> +#include <CommonsJavaScript/JSUtils.h> +#include <CommonsJavaScript/Validator.h> +#include <JSWebAPIErrorFactory.h> +#include <SecurityExceptions.h> +#include <Commons/WrtAccess/WrtAccess.h> +#include <WidgetDB/WidgetDBMgr.h> +#include <WidgetDB/IWidgetDB.h> +#include <TimeTracer.h> +#include <ArgumentValidator.h> +#include <JSWebAPIException.h> +#include <JSUtil.h> +#include <Export.h> +#include "JSFile.h" +#include "FilesystemUtils.h" +#include "Converter.h" +#include "EventGetNodeData.h" +#include "plugin_config.h" +#include "StorageStaticController.h" +#include "ResponseDispatcher.h" +#include "FilesystemAsyncCallbackManager.h" +#include "FilesystemListenerManager.h" +#include <Logger.h> + +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace DeviceAPI::Common; +using namespace WrtDeviceApis; + + + +namespace { +const char* PLUGIN_NAME = "FileSystemManager"; +const char* PROPERTY_MAXPATHLENGTH = "maxPathLength"; + +JSValueRef getFunctionOrNull(JSContextRef ctx, JSValueRef arg) +{ + if (Validator(ctx).isCallback(arg)) { + return arg; + } else if (!JSValueIsNull(ctx, arg) && !JSValueIsUndefined(ctx, arg)) { + ThrowMsg(ConversionException, "Not a function nor JS null."); + } + return NULL; +} + + +JSValueRef getFunction(JSContextRef ctx, JSValueRef arg) +{ + if (Validator(ctx).isCallback(arg)) { + return arg; + }else{ + ThrowMsg(ConversionException, "JS null passed as function."); + } +} + +} + + + +namespace DeviceAPI { +namespace Filesystem { + +JSClassRef JSFilesystemManager::m_classRef = 0; + +JSClassDefinition JSFilesystemManager::m_classInfo = { + 0, + kJSClassAttributeNone, + PLUGIN_NAME, + 0, + m_properties, + m_functions, + initialize, + finalize, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL +}; + +JSStaticValue JSFilesystemManager::m_properties[] = { + { PROPERTY_MAXPATHLENGTH, getMaxPathLength, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSFilesystemManager::m_functions[] = { + { "resolve", JSFilesystemManager::resolve, kJSPropertyAttributeNone }, + { "getStorage", JSFilesystemManager::getStorage, kJSPropertyAttributeNone }, + { "listStorages", JSFilesystemManager::getStorageList, kJSPropertyAttributeNone }, + { "addStorageStateChangeListener", JSFilesystemManager::addStorageStateListener, kJSPropertyAttributeNone }, + { "removeStorageStateChangeListener", JSFilesystemManager::removeStorageStateListener, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +const JSClassRef DLL_EXPORT JSFilesystemManager::getClassRef() +{ + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +const JSClassDefinition* JSFilesystemManager::getClassInfo() +{ + return &m_classInfo; +} + +void JSFilesystemManager::initialize(JSContextRef context, + JSObjectRef object) +{ + PrivateObject* privateObject = new PrivateObject(context); + if (!JSObjectSetPrivate(object, privateObject)) { + delete privateObject; + } + else { + int widgetId = WrtAccessSingleton::Instance().getWidgetId(); + WidgetDB::Api::IWidgetDBPtr widgetDB = WidgetDB::Api::getWidgetDB(widgetId); + + LoggerD(widgetDB->getWidgetInstallationPath()); + std::string wgtpackage = "wgt-package"; + std::string wgtprivate = "wgt-private"; + std::string wgtprivatetemp = "wgt-private-tmp"; + + IManager::getInstance().addWidgetStorage(wgtpackage, widgetDB->getWidgetInstallationPath()); + IManager::getInstance().addWidgetStorage(wgtprivate, widgetDB->getWidgetPersistentStoragePath()); + IManager::getInstance().addWidgetStorage(wgtprivatetemp, widgetDB->getWidgetTemporaryStoragePath()); + + } +} + +void JSFilesystemManager::finalize(JSObjectRef object) +{ + PrivateObject* privateObject = static_cast<PrivateObject*>(JSObjectGetPrivate(object)); + if (privateObject) { + JSObjectSetPrivate(object, NULL); + delete privateObject; + } +} + +JSValueRef JSFilesystemManager::getMaxPathLength(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + ConverterPtr converter = ConverterFactory::getConverter(context); + try { + return converter->toJSValueRef(IManager::getInstance().getMaxPathLength()); + } catch (const WrtDeviceApis::Commons::ConversionException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::IO_ERROR, "IO error"); + } +} + +JSValueRef JSFilesystemManager::getStorage(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argc, + const JSValueRef argv[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + PrivateObject* privateObject = static_cast<PrivateObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + return JSValueMakeUndefined(context); + } + + AceSecurityStatus status = FILESYSTEM_CHECK_ACCESS(FILESYSTEM_FUNCTION_API_GET_STORAGE); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + // argument validation with new validator + try { + ArgumentValidator validator(context, argc, argv); + validator.toString(0, false); + validator.toFunction(1, false); + validator.toFunction(2, true); + } + catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(context, exception, err); + } catch (...) { + DeviceAPI::Common::UnknownException err(""); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + + if (argc < 2) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type missmatch error"); + } + + + + + JSContextRef globalContext = privateObject->getContext(); + ConverterPtr converter = ConverterFactory::getConverter(globalContext); + JSCallbackManagerPtr cbm = JSCallbackManager::createObject(globalContext); + + try { + + JSValueRef onSuccess = getFunction(globalContext, argv[1]); + JSValueRef onError = NULL; + + if (argc>2) { + onError = getFunctionOrNull(globalContext, argv[2]); + } + + cbm->setOnSuccess(onSuccess); + cbm->setOnError(onError); + + EventGetStoragePtr event(new EventGetStorage()); + event->setLabel(converter->toString(argv[0])); + event->setForAsynchronousCall(&ResponseDispatcher::getInstance()); + event->setPrivateData(DPL::StaticPointerCast<WrtDeviceApis::Commons::IEventPrivateData > (cbm)); + FilesystemAsyncCallbackManagerSingleton::Instance().registerCallbackManager(cbm, globalContext); + + IManager::getInstance().getStorage(event); + + } catch(const WrtDeviceApis::Commons::ConversionException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, ex.GetMessage()); + } catch (const WrtDeviceApis::Commons::UnsupportedException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_SUPPORTED_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::InvalidArgumentException& ex) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, ex.GetMessage())); + } catch(const WrtDeviceApis::Commons::Exception& ex) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::UNKNOWN_ERROR, ex.GetMessage())); + } + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); +} + +JSValueRef JSFilesystemManager::getStorageList(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argc, + const JSValueRef argv[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + PrivateObject* privateObject = static_cast<PrivateObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + return JSValueMakeUndefined(context); + } + + AceSecurityStatus status = FILESYSTEM_CHECK_ACCESS(FILESYSTEM_FUNCTION_API_LIST_STORAGE); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + // argument validation with new validator + try { + ArgumentValidator validator(context, argc, argv); + validator.toFunction(0, false); + validator.toFunction(1, true); + } + catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(context, exception, err); + } catch (...) { + DeviceAPI::Common::UnknownException err(""); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + + if (argc < 1) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type missmatch error"); + } + + + JSContextRef globalContext = privateObject->getContext(); + ConverterPtr converter = ConverterFactory::getConverter(globalContext); + JSCallbackManagerPtr cbm = JSCallbackManager::createObject(globalContext); + + try { + + JSValueRef onSuccess = getFunction(globalContext, argv[0]); + JSValueRef onError = NULL; + + if (argc > 1) { + onError = getFunctionOrNull(globalContext, argv[1]); + } + + cbm->setOnSuccess(onSuccess); + cbm->setOnError(onError); + cbm->setObject(thisObject); + + EventListStoragesPtr event(new EventListStorages()); + event->setForAsynchronousCall(&ResponseDispatcher::getInstance()); + event->setPrivateData(DPL::StaticPointerCast<WrtDeviceApis::Commons::IEventPrivateData > (cbm)); + FilesystemAsyncCallbackManagerSingleton::Instance().registerCallbackManager(cbm, globalContext); + + + IManager::getInstance().listStorages(event); + + } catch(const WrtDeviceApis::Commons::ConversionException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, ex.GetMessage()); + } catch (const WrtDeviceApis::Commons::UnsupportedException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_SUPPORTED_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::InvalidArgumentException& ex) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, ex.GetMessage())); + } catch(const WrtDeviceApis::Commons::Exception& ex) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::UNKNOWN_ERROR, ex.GetMessage())); + } + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); +} + +JSValueRef JSFilesystemManager::addStorageStateListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argc, + const JSValueRef argv[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + PrivateObject* privateObject = static_cast<PrivateObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + return JSValueMakeUndefined(context); + } + + AceSecurityStatus status = FILESYSTEM_CHECK_ACCESS(FILESYSTEM_FUNCTION_API_ADD_STORAGE_LISTENER); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + + // argument validation with new validator + try { + ArgumentValidator validator(context, argc, argv); + validator.toFunction(0, false); + validator.toFunction(1, true); + } + catch (const BasePlatformException &err) { + LogDebug("Exception"); + return JSWebAPIErrorFactory::postException(context, exception, err); + } catch (...) { + DeviceAPI::Common::UnknownException err(""); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + + + if (argc < 1) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "TYPE_MISMATCH_ERROR"); + } + + + JSContextRef globalContext = privateObject->getContext(); + JSCallbackManagerPtr cbm = JSCallbackManager::createObject(globalContext); + ConverterPtr converter = ConverterFactory::getConverter(globalContext); + + try { + JSValueRef onSuccess = getFunction(globalContext, argv[0]); + JSValueRef onError = NULL; + if (argc > 1) { + onError = getFunctionOrNull(globalContext, argv[1]); + } + + cbm->setOnSuccess(onSuccess); + cbm->setOnError(onError); + + EventStorageStateChangedEmitterPtr emitter(new EventStorageStateChangedEmitter); + emitter->setListener(&StorageStaticController::getInstance()); + emitter->setEventPrivateData(DPL::StaticPointerCast<EventStorageStateChanged::PrivateDataType>(cbm)); + long id = IManager::getInstance().addStorageStateChangeListener(emitter); + + FilesystemListenerCancellerPtr canceller = FilesystemListenerCancellerPtr(new FilesystemListenerCanceller(globalContext, thisObject, id)); + IListenerItemPtr listenerItem = DPL::StaticPointerCast<IListenerItem>(canceller); + FilesystemListenerManagerSingleton::Instance().registerListener(listenerItem, globalContext); + + return converter->toJSValueRefLong(id); + } catch(const WrtDeviceApis::Commons::ConversionException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, ex.GetMessage()); + } catch (const WrtDeviceApis::Commons::UnsupportedException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_SUPPORTED_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::InvalidArgumentException& ex) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, ex.GetMessage())); + } catch(const WrtDeviceApis::Commons::Exception& ex) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::UNKNOWN_ERROR, ex.GetMessage())); + } + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); +} + +JSValueRef JSFilesystemManager::removeStorageStateListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argc, + const JSValueRef argv[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + PrivateObject* privateObject = static_cast<PrivateObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + return JSValueMakeUndefined(context); + } + + AceSecurityStatus status = FILESYSTEM_CHECK_ACCESS(FILESYSTEM_FUNCTION_API_REMOVE_STORAGE_LISTENER); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + LogDebug("a"); + + // argument validation with new validator + try { + ArgumentValidator validator(context, argc, argv); + validator.toLong(0, false); + } + catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(context, exception, err); + } catch (...) { + DeviceAPI::Common::UnknownException err(""); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + + if (argc < 1) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type missmatch error"); + } + + + + + JSContextRef globalContext = privateObject->getContext(); + ConverterPtr converter = ConverterFactory::getConverter(globalContext); + + try { + long id = static_cast<long>(converter->toLong(argv[0])); + LoggerD("id:" << id); + + if (id >= 0) { + + FilesystemListenerCancellerPtr canceller = FilesystemListenerCancellerPtr(new FilesystemListenerCanceller(globalContext, thisObject, id)); + IListenerItemPtr listenerItem = DPL::StaticPointerCast<IListenerItem>(canceller); + FilesystemListenerManagerSingleton::Instance().unregisterListener(listenerItem); + + IManager::getInstance().removeStorageStateChangeListener(id); + + } + } catch(const WrtDeviceApis::Commons::ConversionException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, ex.GetMessage()); + } catch (const WrtDeviceApis::Commons::UnsupportedException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_SUPPORTED_ERROR, ex.GetMessage()); + } catch (const WrtDeviceApis::Commons::NotFoundException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_FOUND_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::InvalidArgumentException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::Exception& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, ex.GetMessage()); + } + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); +} + +JSValueRef JSFilesystemManager::resolve(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argc, + const JSValueRef argv[], + JSValueRef* exception) +{ + + LoggerD("<<<"); + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + + PrivateObject* privateObject = static_cast<PrivateObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + return JSValueMakeUndefined(context); + + } + + AceSecurityStatus status = FILESYSTEM_CHECK_ACCESS(FILESYSTEM_FUNCTION_API_MGR_RESOLVE_ID); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + // argument validation with new validator + try { + ArgumentValidator validator(context, argc, argv); + validator.toString(0, false); + validator.toFunction(1, false); + validator.toFunction(2, true); + validator.toString(3, true); + } + catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(context, exception, err); + } catch (...) { + DeviceAPI::Common::UnknownException err(""); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + + if (argc < 2) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type missmatch error"); + } + + LogDebug("resolve"); + + + + + JSContextRef globalContext = privateObject->getContext(); + ConverterPtr converter = ConverterFactory::getConverter(globalContext); + + size_t index = 0; + JSCallbackManagerPtr cbm = JSCallbackManager::createObject(globalContext); + JSValueRef reserveArguments[4]; + + try { + for (index = 0; index < 4; index++) { + if (index < argc) + reserveArguments[index] = argv[index]; + else + reserveArguments[index] = JSValueMakeUndefined(context); + } + + JSValueRef onSuccess = getFunction(globalContext, reserveArguments[1]); + JSValueRef onError = NULL; + + onError = getFunctionOrNull(globalContext, reserveArguments[2]); + + cbm->setOnSuccess(onSuccess); + cbm->setOnError(onError); + cbm->setObject(thisObject); + + IPathPtr path; + std::string virtualPath = converter->toString(reserveArguments[0]); + + if (!Utils::isVirtualPath(virtualPath) && !Utils::isUriPath(virtualPath)) { + ThrowMsg(Commons::NotFoundException, "Location not found."); + } + + std::string rootPath; + std::size_t found; + + if ((found = virtualPath.find("/")) == std::string::npos) { + rootPath = virtualPath; + } + else { + rootPath = virtualPath.substr(0, found); + } + + if (virtualPath.find("removable") != std::string::npos) { + LoggerD(rootPath << " : " << virtualPath); + EventGetStoragePtr getStroageEvent(new EventGetStorage()); + getStroageEvent->setLabel(rootPath); + if (getStroageEvent->setForSynchronousCall()) { + + IManager::getInstance().getStorage(getStroageEvent); + StoragePropertiesPtr storage = getStroageEvent->getResult(); + + if (storage->getState() != StorageProperties::STATE_MOUNTED && + storage->getState() != StorageProperties::STATE_MOUNTED_READONLY) + { + ThrowMsg(Commons::NotFoundException, "removable stroage is not available."); + } + } + + } + + path = Utils::fromVirtualPath(globalContext, virtualPath); + + LoggerD("virtualPath:[" << virtualPath << "]"); + int permissions = PERM_READ | PERM_WRITE; + std::string perm = "rw"; + + + + if (argc > 3) { + perm = converter->toString(reserveArguments[3]); + LoggerD("perms:[" << perm << "]"); + if (("r" != perm) && ("rw" != perm) && ("w" != perm) && ("a" != perm)) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Invalid mode"); + } else if ("r" == perm) { + permissions = PERM_READ; + } + } + + if (permissions & PERM_WRITE && ((virtualPath == "wgt-package" ) || (virtualPath == "ringtones" ))) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, + JSWebAPIErrorFactory::INVALID_VALUES_ERROR, "invalid mode, permission denied error")); + return JSValueMakeUndefined(context); + } + + PermissionsAccessInfo perms(permissions, virtualPath); + AceSecurityStatus status = FILESYSTEM_PERMISSION_CHECK_ACCESS( + FILESYSTEM_FUNCTION_API_MGR_RESOLVE_ID, + perms); + + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + EventGetNodeDataPtr data(new EventGetNodeData(permissions, cbm)); + EventResolvePtr event(new EventResolve(path)); + event->setForAsynchronousCall(&ResponseDispatcher::getInstance()); + event->setMode(perm); + event->setPrivateData(DPL::StaticPointerCast<WrtDeviceApis::Commons::IEventPrivateData > (data)); + FilesystemAsyncCallbackManagerSingleton::Instance().registerCallbackManager(cbm, globalContext); + + IManager::getInstance().getNode(event); + + } catch(const WrtDeviceApis::Commons::ConversionException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::NotFoundException& ex) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::NOT_FOUND_ERROR, ex.GetMessage())); + } catch (const WrtDeviceApis::Commons::UnsupportedException& ex) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_SUPPORTED_ERROR, ex.GetMessage()); + } catch(const WrtDeviceApis::Commons::InvalidArgumentException& ex) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, ex.GetMessage())); + } catch(const WrtDeviceApis::Commons::Exception& ex) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::UNKNOWN_ERROR, ex.GetMessage())); + } + + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); +} +} +} diff --git a/wearable_src/Filesystem/JSFilesystemManager.h b/wearable_src/Filesystem/JSFilesystemManager.h new file mode 100755 index 0000000..ba00d49 --- /dev/null +++ b/wearable_src/Filesystem/JSFilesystemManager.h @@ -0,0 +1,124 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 TIZENAPIS_TIZEN_JSFILESYSTEMMANAGER_H_ +#define TIZENAPIS_TIZEN_JSFILESYSTEMMANAGER_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/PrivateObject.h> + +namespace DeviceAPI { +namespace Filesystem { +class JSFilesystemManager +{ + public: + typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT<void>::Type PrivateObject; + + public: + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + + 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 JSValueRef getMaxPathLength(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + /** + * Resolves a location to a File handle. + */ + static JSValueRef resolve(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argc, + const JSValueRef argv[], + JSValueRef* exception); + + /** + * Get information about a storage based on it's label. + */ + static JSValueRef getStorage(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argc, + const JSValueRef argv[], + JSValueRef* exception); + + /** + * List the available storages on the device. + * Get the list of available internal and external storage devices. + */ + static JSValueRef getStorageList(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argc, + const JSValueRef argv[], + JSValueRef* exception); + + static JSValueRef addStorageStateListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argc, + const JSValueRef argv[], + JSValueRef* exception) ; + + static JSValueRef removeStorageStateListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argc, + const JSValueRef argv[], + JSValueRef* exception); + + private: + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_functions[]; + + /** + * This structure describes a statically declared value property. + */ + static JSStaticValue m_properties[]; + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + static JSClassRef m_classRef; +}; +} +} + +#endif
\ No newline at end of file diff --git a/wearable_src/Filesystem/JSStorage.cpp b/wearable_src/Filesystem/JSStorage.cpp new file mode 100644 index 0000000..35f4f01 --- /dev/null +++ b/wearable_src/Filesystem/JSStorage.cpp @@ -0,0 +1,172 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <cassert> +#include <memory> +#include <CommonsJavaScript/JSUtils.h> +//#include <CommonsJavaScript/Converter.h> +#include <CommonsJavaScript/JSDOMExceptionFactory.h> +#include <Export.h> +#include "StorageProperties.h" +#include "JSStorage.h" +#include "Converter.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Filesystem { + +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace { +const char* STR_STORAGE_LABEL = "label"; +const char* STR_STORAGE_TYPE = "type"; +const char* STR_STORAGE_STATE = "state"; +/*const char* STR_TYPE_INTERNAL = "INTERNAL"; +const char* STR_TYPE_EXTERNAL = "EXTERNAL"; +const char* STR_STATE_MOUNTED = "MOUNTED"; +const char* STR_STATE_REMOVED = "REMOVED"; +const char* STR_STATE_UNMOUNTABLE = "UNMOUNTABLE";*/ +} //private namespace + +JSClassDefinition JSStorage::m_classInfo = { + 0, + kJSClassAttributeNone, + "FileSystemStorage", + 0, + m_property, + 0, + initialize, + finalize, + NULL, //HasProperty, + getProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + hasInstance, + NULL, //ConvertToType +}; + +JSStaticValue JSStorage::m_property[] = { + { STR_STORAGE_LABEL, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { STR_STORAGE_TYPE, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { STR_STORAGE_STATE, getProperty, NULL, kJSPropertyAttributeReadOnly }, +/* { STR_TYPE_INTERNAL, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { STR_TYPE_EXTERNAL, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { STR_STATE_MOUNTED, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { STR_STATE_REMOVED, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { STR_STATE_UNMOUNTABLE, getProperty, NULL, kJSPropertyAttributeReadOnly },*/ + { 0, 0, 0, 0 } +}; + +const JSClassRef DLL_EXPORT JSStorage::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSStorage::getClassInfo() +{ + return &m_classInfo; +} + +JSClassRef JSStorage::m_jsClassRef = JSClassCreate( + JSStorage::getClassInfo()); + +JSObjectRef JSStorage::createJSObject(JSContextRef context, + const StorageProperties &storages) +{ + std::auto_ptr<StorageProperties> storageProps(new StorageProperties()); + + storageProps->setLabel(storages.getLabel()); + storageProps->setType(storages.getType()); + storageProps->setState(storages.getState()); + + JSStoragePriv *priv = new JSStoragePriv(context, storageProps.get()); + storageProps.release(); + if (!priv) { + ThrowMsg(Commons::NullPointerException, "Can not new an object"); + } + return JSObjectMake(context, getClassRef(), priv); +} + +void JSStorage::initialize(JSContextRef context, + JSObjectRef object) +{ +} + +void JSStorage::finalize(JSObjectRef object) +{ + JSStoragePriv* priv = static_cast<JSStoragePriv*>(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + delete priv; +} + +JSValueRef JSStorage::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + JSStoragePriv *priv = static_cast<JSStoragePriv*>(JSObjectGetPrivate(object)); + + Try { + if (!priv) { + ThrowMsg(Commons::PlatformException, "Can not new an object"); + } + StorageProperties *storages = priv->getObject(); + Converter convert(context); + + if (JSStringIsEqualToUTF8CString(propertyName, STR_STORAGE_LABEL)) { + return convert.toJSValueRef(storages->getLabel()); + } else if (JSStringIsEqualToUTF8CString(propertyName, STR_STORAGE_TYPE)) { + return convert.toStorageType(storages->getType()); + } else if (JSStringIsEqualToUTF8CString(propertyName, STR_STORAGE_STATE)) { + return convert.toStorageState(storages->getState()); + } + /*else if (JSStringIsEqualToUTF8CString(propertyName, STR_TYPE_INTERNAL)) { + return convert.toJSValueRef(TYPE_INTERNAL); + } else if (JSStringIsEqualToUTF8CString(propertyName, STR_TYPE_EXTERNAL)) { + return convert.toJSValueRef(TYPE_EXTERNAL); + } else if (JSStringIsEqualToUTF8CString(propertyName, STR_STATE_MOUNTED)) { + return convert.toJSValueRef(STATE_MOUNTED); + } else if (JSStringIsEqualToUTF8CString(propertyName, STR_STATE_REMOVED)) { + return convert.toJSValueRef(STATE_REMOVED); + } else if (JSStringIsEqualToUTF8CString(propertyName, STR_STATE_UNMOUNTABLE)) { + return convert.toJSValueRef(STATE_UNMOUNTABLE); + }*/ + } Catch(Commons::Exception) { + LoggerW("trying to get incorrect value"); + } + return JSValueMakeUndefined(context); +} + +bool JSStorage::hasInstance(JSContextRef context, + JSObjectRef constructor, + JSValueRef possibleInstance, + JSValueRef* exception) +{ + return JSValueIsObjectOfClass(context, possibleInstance, getClassRef()); +} +} +} + diff --git a/wearable_src/Filesystem/JSStorage.h b/wearable_src/Filesystem/JSStorage.h new file mode 100755 index 0000000..37c96e0 --- /dev/null +++ b/wearable_src/Filesystem/JSStorage.h @@ -0,0 +1,100 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 TIZENAPIS_TIZEN_JS_STORAGE_H_ +#define TIZENAPIS_TIZEN_JS_STORAGE_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/PrivateObject.h> +#include "StorageProperties.h" + +namespace DeviceAPI { +namespace Filesystem { +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT<StorageProperties*>::Type JSStoragePriv; + +class JSStorage +{ +public: + enum StorageType + { + TYPE_INTERNAL = 0, + TYPE_EXTERNAL, + }; + + enum StorageState + { + STATE_MOUNTED = 0, + STATE_REMOVED, + STATE_UNMOUNTABLE, + }; + + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + + /** + * create an JSObject for callback function(onAnswerReceived). + */ + static JSObjectRef createJSObject(JSContextRef context, + const StorageProperties &storages); + +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 JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + /** + * 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_property[]; + + static JSClassRef m_jsClassRef; +}; +} +} + +#endif + diff --git a/wearable_src/Filesystem/Manager.cpp b/wearable_src/Filesystem/Manager.cpp new file mode 100644 index 0000000..fb89f82 --- /dev/null +++ b/wearable_src/Filesystem/Manager.cpp @@ -0,0 +1,979 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "Manager.h" + +#include <unistd.h> +#include <sys/stat.h> +#include <errno.h> +#include <pcrecpp.h> +#include <ctime> +#include <sstream> +#include <dirent.h> +#include <dpl/scoped_ptr.h> + +#include <Commons/Exception.h> +#include <Commons/Regex.h> +#include "PathUtils.h" +#include "StorageProperties.h" +#include "Node.h" +#include "Utils.h" +#include <app.h> +#include <Logger.h> + +namespace { +const char* PATH_DOWNLOADS = "/opt/usr/media/Downloads"; +const char* PATH_DOCUMENTS = "/opt/usr/media/Documents"; +const char* PATH_SOUNDS = "/opt/usr/media/Sounds"; +const char* PATH_IMAGES = "/opt/usr/media/Images"; +const char* PATH_VIDEOS = "/opt/usr/media/Videos"; +const char* PATH_RINGTONE = "/opt/usr/share/settings/Ringtones"; +} + +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; + +namespace DeviceAPI { +namespace Filesystem { +Manager::Locations Manager::m_locations; +Manager::RootList Manager::m_rootlist; +Manager::SubRootList Manager::m_subrootlist; +const std::size_t Manager::m_maxPathLength = PATH_MAX; + +NodeList Manager::m_openedNodes; +std::vector<Manager::WatcherPtr> Manager::m_watchers; + +bool Manager::fileExists(const std::string &file) +{ + errno = 0; + struct stat info; + memset(&info, 0, sizeof(struct stat)); + int status = lstat(file.c_str(), &info); + if (status == 0) { + return true; + } else if (errno == ENOENT) { + return false; + } + ThrowMsg(Commons::PlatformException, "Cannot stat file."); +} + +bool Manager::getSupportedDeviceCB(int storage, storage_type_e type, storage_state_e state, const char *path, void *user_data) +{ + std::vector<StoragePropertiesPtr>* storageVector = (std::vector<StoragePropertiesPtr>*)user_data; + StoragePropertiesPtr storageItem(new StorageProperties()); + + int size = 12; + char buf[size]; + std::string lable; + std::string fullpath(path); + if (type == STORAGE_TYPE_INTERNAL) { + snprintf(buf, size, "internal%d", storage); + lable.append(buf); + } else if (type == STORAGE_TYPE_EXTERNAL) { + snprintf(buf, size, "removable%d", storage); + lable.append(buf); + } + LoggerD(lable << "state" << state); + + storageItem->setId(storage); + storageItem->setLabel(lable); + storageItem->setType((short)type); + storageItem->setState((short)state); + storageItem->setFullPath(fullpath); + + storageVector->insert(storageVector->end(), storageItem); + + return true; +} + +void Manager::storageStateChangedCB(int storage, storage_state_e state, void *user_data) +{ + if (user_data != NULL) { + watcherList* m_watcherList = (watcherList *)user_data; + watcherList::iterator it = m_watcherList->begin(); + for(; it!= m_watcherList->end(); ++it) { + (*it)->StorageStateHasChanged(storage, state); + } + } +} + +void Manager::addOpenedNode(const INodePtr& node) +{ + NodeListIterator it = m_openedNodes.begin(); + for (; it != m_openedNodes.end(); ++it) { + if (node.Get() == (*it).Get()) { + //node is added already + return; + } + } + m_openedNodes.push_back(node); +} + +void Manager::removeOpenedNode(const INodePtr& node) +{ + NodeListIterator it = m_openedNodes.begin(); + for (; it != m_openedNodes.end(); ++it) { + if ((*it).Get() == node.Get()) { + m_openedNodes.erase(it); + break; + } + } +} + +bool Manager::checkIfOpened(const IPathPtr& path) const +{ + NodeListIterator it = m_openedNodes.begin(); + for (; it != m_openedNodes.end(); ++it) { + if (*path == *(*it)->getPath()) { + return true; + } + } + return false; +} + +Manager::Manager() +{ + static bool initialized = init(); + (void) initialized; +} + +Manager::~Manager() +{ +} + +StorageList Manager::getStorageList() const +{ + return m_locations; +} + +IPathPtr Manager::getBasePath() const +{ + Locations::const_iterator it = m_locations.find(m_subrootlist.find(LT_ROOT)->second); + if (it == m_locations.end()) { + ThrowMsg(Commons::PlatformException, "Base path not available."); + } + return it->second; +} + +IPathPtr Manager::getLocationPath(LocationType type) const +{ + Locations::const_iterator it = m_locations.find(m_subrootlist.find(type)->second); + if (it != m_locations.end()) { + return it->second->clone(); + } + return IPathPtr(); +} + +LocationPaths Manager::getLocationPaths() const +{ + LocationPaths result; + Locations::const_iterator it = m_locations.begin(); + for (; it != m_locations.end(); ++it) { + result.push_back(it->second->clone()); + } + return result; +} + +LocationTypes Manager::getLocations() const +{ + LocationTypes result; + SubRootList::const_iterator it = m_subrootlist.begin(); + for (; it != m_subrootlist.end(); ++it) { + result.push_back(it->first); + } + return result; +} + +void Manager::getNode(const EventResolvePtr& event) +{ + EventRequestReceiver<EventResolve>::PostRequest(event); +} + +void Manager::getStorage(const EventGetStoragePtr& event) +{ + EventRequestReceiver<EventGetStorage>::PostRequest(event); +} + +void Manager::listStorages(const EventListStoragesPtr& event) +{ + EventRequestReceiver<EventListStorages>::PostRequest(event); +} + +std::size_t Manager::getMaxPathLength() const +{ + return m_maxPathLength; +} + +void Manager::copy(const EventCopyPtr& event) +{ + EventRequestReceiver<EventCopy>::PostRequest(event); +} + +void Manager::move(const EventMovePtr& event) +{ + EventRequestReceiver<EventMove>::PostRequest(event); +} + +void Manager::create(const EventCreatePtr& event) +{ + EventRequestReceiver<EventCreate>::PostRequest(event); +} + +void Manager::remove(const EventRemovePtr& event) +{ + EventRequestReceiver<EventRemove>::PostRequest(event); +} + +void Manager::find(const EventFindPtr& event) +{ + EventRequestReceiver<EventFind>::PostRequest(event); +} + +void Manager::find(const IPathPtr& path, + const FiltersMap& filters, + NodeList& result, + const EventFindPtr& event) +{ + Try { + DIR* dir = opendir(path->getFullPath().c_str()); + if (!dir) { + return; + } + + errno = 0; + struct dirent* entry = NULL; + while ((entry = readdir(dir))) { + if (event && event->checkCancelled()) { + break; + } + if (!strcmp(entry->d_name, ".") || !strncmp(entry->d_name, "..", 2)) { + continue; + } + IPathPtr childPath = *path + entry->d_name; + struct stat info; + memset(&info, 0, sizeof(struct stat)); + if (lstat(childPath->getFullPath().c_str(), &info) == 0) { + if (matchFilters(entry->d_name, info, filters)) { + result.push_back(Node::resolve(childPath)); + } + if (S_ISDIR(info.st_mode)) { + find(childPath, filters, result, event); + } + } + } + + if (errno != 0) { + ThrowMsg(Commons::PlatformException, + "Error while reading directory."); + } + + if (closedir(dir) != 0) { + ThrowMsg(Commons::PlatformException, + "Could not close platform node."); + } + } + Catch(WrtDeviceApis::Commons::Exception) { + } +} + +void Manager::copyElement( + const std::string &src, const std::string &dest, bool recursive) const +{ + LoggerD("Copying src: " << src << " to: " << dest); + + //element is a file: + if (EINA_TRUE != ecore_file_is_dir(src.c_str())) { + if (EINA_TRUE != ecore_file_cp(src.c_str(), dest.c_str())) { + ThrowMsg(Commons::PlatformException, "Failed to copy file"); + } + return; + } + //element is a directory -> create it: + if (EINA_TRUE != ecore_file_is_dir(dest.c_str())) { + if (EINA_TRUE != ecore_file_mkdir(dest.c_str())) { + LoggerD("Failed to create destination directory"); + ThrowMsg(Commons::PlatformException, "Failed to copy directory"); + } + } + //copy all elements of directory: + if (recursive) { + Eina_List* list = ecore_file_ls(src.c_str()); + void* data; + EINA_LIST_FREE(list, data) + { + Try + { + copyElement((src + '/' + static_cast<char*>(data)).c_str(), + (dest + '/' + static_cast<char*>(data)).c_str()); + } + + Catch (Commons::Exception) + { + //remove rest of the list + EINA_LIST_FREE(list, data) + { + free(data); + } + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + ReThrowMsg(Commons::PlatformException, "Failed to copy element"); + } + free(data); + } + } + +} + +/*bool Manager::access(const IPathPtr& path, + int accessType) const +{ + int amode = 0; + if (accessType & AT_EXISTS) { amode |= F_OK; } + if (accessType & AT_READ) { amode |= R_OK; } + if (accessType & AT_WRITE) { amode |= W_OK; } + if (accessType & AT_EXEC) { amode |= X_OK; } + return (::access(path->getFullPath().c_str(), amode) == 0); +}*/ + +long Manager::addStorageStateChangeListener( + const EventStorageStateChangedEmitterPtr& emitter) +{ + RootList::const_iterator it = m_rootlist.begin(); + WatcherPtr watcher(new Watcher(emitter)); + Manager::m_watchers.push_back(watcher); + + for (; it != m_rootlist.end(); ++it) { + storage_set_state_changed_cb(it->second, Manager::storageStateChangedCB, (void *)(&m_watchers)); + } + + watcher->getCurrentStoargeStateForWatch(); + return static_cast<long>(emitter->getId()); +} + +void Manager::removeStorageStateChangeListener(EventStorageStateChangedEmitter::IdType id) +{ + watcherList::iterator itWatcher = Manager::m_watchers.begin(); + bool found = false; + for (;itWatcher != Manager::m_watchers.end();) { + if (id == (*itWatcher)->getEmitter()->getId()) { + itWatcher = Manager::m_watchers.erase(itWatcher); + found = true; + continue; + } + ++itWatcher; + } + + if (Manager::m_watchers.size() == 0) { + RootList::const_iterator itRoot; + for (itRoot = m_rootlist.begin(); itRoot != m_rootlist.end(); ++itRoot) { + storage_unset_state_changed_cb(itRoot->second); + } + } + + if (found == false) { +// LoggerD("no exist" << id); + ThrowMsg(Commons::NotFoundException, "The " << id << "is not exist"); + } +} + +bool Manager::matchFilters(const std::string& name, + const struct stat& info, + const FiltersMap& filters) +{ + FiltersMap::const_iterator it = filters.begin(); + for (; it != filters.end(); ++it) { + if (it->first == FF_NAME) { + if (!pcrecpp::RE(it->second).PartialMatch(name)) { return false; } + } else if (it->first == FF_SIZE) { + std::size_t size; + std::stringstream ss(it->second); + ss >> size; + if (!ss || + (size != static_cast<size_t>(info.st_size))) { return false; } + } else if (it->first == FF_CREATED) { + std::time_t created; + std::stringstream ss(it->second); + ss >> created; + if (!ss || (created != info.st_ctime)) { return false; } + } else if (it->first == FF_MODIFIED) { + std::time_t modified; + std::stringstream ss(it->second); + ss >> modified; + if (!ss || (modified != info.st_mtime)) { return false; } + } + } + return true; +} + +void Manager::OnRequestReceived(const EventResolvePtr& event) +{ + try { + INodePtr node = Node::resolve(event->getPath()); + if (node->checkPermission(event->getMode()) == false) + { + ThrowMsg(Commons::SecurityException, "Permission Denied Error"); + } + event->setResult(node); + } + catch (const Commons::Exception& ex) + { + LoggerE("Exception: " << ex.GetMessage()); + event->setExceptionCode(ex.getCode()); + } +} + +void Manager::OnRequestReceived(const EventGetStoragePtr& event) +{ + try { + + StoragePropertiesPtr storage(new StorageProperties()); + + RootList::const_iterator it = m_rootlist.find(event->getLabel()); + if (it == m_rootlist.end()) { + Locations::const_iterator itL = m_locations.find(event->getLabel()); + if (itL == m_locations.end()) { + ThrowMsg(Commons::NotFoundException, "Base path not available."); + } else { + storage->setId(0xff); + storage->setLabel(event->getLabel()); + storage->setType(StorageProperties::TYPE_INTERNAL); + storage->setState(StorageProperties::STATE_MOUNTED); + } + } else { + int id = it->second; + + storage_type_e currentType; + storage_state_e currentState; + + storage_get_type(id, ¤tType); + storage_get_state(id, ¤tState); + + storage->setId(id); + storage->setLabel(event->getLabel()); + storage->setType((short)currentType); + storage->setState((short)currentState); + } + + event->setResult(storage); + } catch (const Commons::Exception& ex) + { + event->setExceptionCode(ex.getCode()); + } +} + +void Manager::OnRequestReceived(const EventListStoragesPtr& event) +{ + try { + std::vector<StoragePropertiesPtr> storageList; + + storage_foreach_device_supported(Manager::getSupportedDeviceCB, &storageList); + + SubRootList::const_iterator it = m_subrootlist.begin(); + for (; it != m_subrootlist.end(); ++it) { + if (it->first == LT_ROOT) + continue; + if (it->first == LT_SDCARD) + continue; + if (it->first == LT_USBHOST) + continue; + + addLocalStorage(it->second, storageList); + } + + + event->setResult(storageList); + } catch (const Commons::Exception& ex) + { + event->setExceptionCode(ex.getCode()); + } +} + +void Manager::OnRequestReceived(const EventCopyPtr& event) +{ + Try { + INodePtr srcNode = Node::resolve(event->getSource()); + LoggerD(std::hex << srcNode->getMode() << " " << std::hex << PM_USER_READ); + if ((srcNode->getMode() & PM_USER_READ/*PERM_READ*/) == 0) { + ThrowMsg(Commons::SecurityException, + "Not enough permissions to read source node."); + } + + IPathPtr src = event->getSource(); + IPathPtr dest = event->getDestination(); + if (!dest->isAbsolute()) { + dest = src->getPath() + *dest; + } + + INodePtr parent; + + Try { + parent = Node::resolve(IPath::create(dest->getPath())); + + if (parent->checkPermission("rw") == false) + { + Throw(Commons::SecurityException); + } + } + Catch(Commons::NotFoundException) + { + event->setExceptionCode(_rethrown_exception.getCode()); + ReThrowMsg(Commons::NotFoundException, "could not find a destination path."); + } + Catch(Commons::SecurityException) + { + event->setExceptionCode(_rethrown_exception.getCode()); + ReThrowMsg(Commons::SecurityException, "no permission on the destination path"); + } + Catch (Commons::Exception) + { + event->setExceptionCode(_rethrown_exception.getCode()); + ReThrowMsg(Commons::PlatformException, + "Could not get destination's parent node."); + } + + if (parent->getType() != NT_DIRECTORY) { + ThrowMsg(Commons::PlatformException, + "Destination's parent node is not directory."); + } + + std::string realSrc = src->getFullPath(); + std::string realDest = dest->getFullPath(); + + if (realSrc == realDest) { + ThrowMsg(Commons::PlatformException, + "Destination is same as source."); + } + else if (src->getPath() == dest->getPath() && dest->getName() == "") { + ThrowMsg(Commons::PlatformException, + "Destination is same as source."); + } + + + + errno = 0; + struct stat info; + memset(&info, 0, sizeof(struct stat)); + int status = lstat(realDest.c_str(), &info); + if ((status != 0) && (errno != ENOENT)) { + ThrowMsg(Commons::PlatformException, + "No access to platform destination node."); + } + + if (S_ISDIR(info.st_mode) && srcNode->getType() == NT_FILE) { + dest->append("/" + src->getName()); + realDest = dest->getFullPath(); + memset(&info, 0, sizeof(struct stat)); + status = lstat(realDest.c_str(), &info); + if ((status != 0) && (errno != ENOENT)) { + ThrowMsg(Commons::PlatformException, + "No access to platform destination node."); + } + } + + if (0 == status) { + //no owerwrite flag setted -> exception + if ((event->getOptions() & OPT_OVERWRITE) == 0) { + ThrowMsg(Commons::PlatformException, "Overwrite is not set."); + } + + if (event->checkCancelled()) { + //file is not copied yet, so we can cancel it now. + event->setCancelAllowed(true); + return; + } + + //destination exist. Need to be removed + Try { + INodePtr node = Node::resolve(dest); + + // only remove if dest is file. + if (node->getType() == NT_FILE) { + node->remove(event->getOptions()); + } + else { + // destination exist and src & dest are directory and dest path ends with '/' + if (srcNode->getType() == NT_DIRECTORY && realDest[realDest.length() - 1] == '/') { + realDest += src->getName(); + } + } + } + catch (const Commons::Exception& ex) + { + LoggerE("Exception: " << ex.GetMessage()); + event->setExceptionCode(ex.getCode()); + } + } + //Destination is not exist. Start copy now. + LoggerD(dest->getFullPath().c_str()); + copyElement(realSrc, realDest); + + event->setResult(Node::resolve(dest)); + } + catch (const Commons::Exception& ex) + { + LoggerE("Exception: " << ex.GetMessage()); + event->setExceptionCode(ex.getCode()); + } + //file is copied already so we don't allow cancelling anymore. + event->setCancelAllowed(false); +} + +void Manager::OnRequestReceived(const EventMovePtr& event) +{ + try { + IPathPtr src = event->getSource(); + IPathPtr dest = event->getDestination(); + + INodePtr srcNode = Node::resolve(src); + LoggerD(std::hex << srcNode->getMode() << " " << std::hex << PM_USER_WRITE); + if ((srcNode->getMode() & PM_USER_WRITE/*PERM_WRITE*/) == 0) + { + ThrowMsg(Commons::SecurityException, + "Not enough permissions to move source node."); + } + + if (!dest->isAbsolute()) { + dest = src->getPath() + *dest; + } + + if (src->getFullPath() == dest->getFullPath()) { + ThrowMsg(Commons::PlatformException, + "Destination is same as source."); + } + else if (src->getPath() == dest->getPath() && dest->getName() == "") { + ThrowMsg(Commons::PlatformException, + "Destination is same as source."); + } + + INodePtr parent; + Try { + parent = Node::resolve(IPath::create(dest->getPath())); + + if (parent->checkPermission("rw") == false) + { + Throw(Commons::SecurityException); + } + } + + Catch(Commons::NotFoundException) + { + event->setExceptionCode(_rethrown_exception.getCode()); + ReThrowMsg(Commons::NotFoundException, "could not find a destination path."); + } + Catch(Commons::SecurityException) + { + event->setExceptionCode(_rethrown_exception.getCode()); + ReThrowMsg(Commons::SecurityException, "no permission on the destination path"); + } + Catch(Commons::Exception) + { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + ReThrowMsg(Commons::PlatformException, + "Could not get destination's parent node."); + } + + if (parent->getType() != NT_DIRECTORY) { + ThrowMsg(Commons::PlatformException, + "Destination's parent node is not directory."); + } + + errno = 0; + struct stat info; + memset(&info, 0, sizeof(info)); + int status = lstat(dest->getFullPath().c_str(), &info); + if ((status != 0) && (errno != ENOENT)) { + ThrowMsg(Commons::PlatformException, + "No access to platform destination node."); + } + + LoggerD(dest->getFullPath().c_str()); + + if (S_ISDIR(info.st_mode) && srcNode->getType() == NT_FILE) { + dest->append("/" + src->getName()); + memset(&info, 0, sizeof(info)); + status = lstat(dest->getFullPath().c_str(), &info); + if ((status != 0) && (errno != ENOENT)) { + ThrowMsg(Commons::PlatformException, + "No access to platform destination node."); + } + } + + if (status == 0 && 0 == (event->getOptions() & OPT_OVERWRITE)) { + ThrowMsg(Commons::PlatformException, "Overwrite is not set."); + } + + if (event->checkCancelled()) { + //file is not moved yet, so we can cancel it now. + event->setCancelAllowed(true); + return; + } + + errno = 0; + + LoggerD(dest->getFullPath().c_str()); + + if (0 != ::rename(src->getFullPath().c_str(), dest->getFullPath().c_str())) + { + int error = errno; + switch (error) + { + case EXDEV: + { + LoggerD(std::hex << srcNode->getMode() << " " << std::hex << PM_USER_READ); + if ((srcNode->getMode() & PM_USER_READ /*PERM_READ*/) == 0) + { + ThrowMsg(Commons::SecurityException, + "Not enough permissions to move source node."); + } + if (0 == status) { + //destination exist. Need to be removed + Try { + INodePtr node = Node::resolve(dest); + node->remove(event->getOptions()); + } + catch (const Commons::Exception& ex) + { + LoggerE("Exception: " << ex.GetMessage()); + event->setExceptionCode(ex.getCode()); + LoggerE("Exception while removing dest directory"); + } + } + + copyElement(src->getFullPath(), + dest->getFullPath()); + //remove source files + Try { + INodePtr node = Node::resolve(event->getSource()); + node->remove(event->getOptions()); + } + Catch(Commons::Exception) { + LoggerE("Exception: " + << _rethrown_exception.GetMessage()); + } + break; + } + default: + // needtofix + ThrowMsg(Commons::PlatformException, + "Error on rename: " /*<< DPL::GetErrnoString(error)*/); + break; + } + } + + event->setResult(Node::resolve(dest)); + } + catch (const Commons::Exception& ex) + { + LoggerE("Exception: " << ex.GetMessage()); + event->setExceptionCode(ex.getCode()); + } + + event->setCancelAllowed(false); +} + +void Manager::OnRequestReceived(const EventCreatePtr& event) +{ + Try { + } + catch (const Commons::Exception& ex) + { + LoggerE("Exception: " << ex.GetMessage()); + event->setExceptionCode(ex.getCode()); + } +} + +void Manager::OnRequestReceived(const EventRemovePtr& event) +{ + if (!event->checkCancelled()) { + Try { + + INodePtr node = Node::resolve(event->getPath()); + + if (node->checkPermission("rw") == false) + { + ThrowMsg(Commons::SecurityException, "no permission on the path"); + } + node->remove(event->getOptions()); + } + catch (const Commons::Exception& ex) + { + LoggerE("Exception: " << ex.GetMessage()); + event->setExceptionCode(ex.getCode()); + } + event->setCancelAllowed(false); + } else { + event->setCancelAllowed(true); + } +} + +void Manager::OnRequestReceived(const EventFindPtr& event) +{ + try { + NodeList result; + find(event->getPath(), event->getFilters(), result, event); + event->setResult(result); + } + catch (const Commons::Exception& ex) { + LoggerE("Exception: " << ex.GetMessage()); + event->setExceptionCode(Commons::ExceptionCodes::PlatformException); + } + event->setCancelAllowed(true); +} + +void Manager::addLocalStorage(std::string label, std::vector<StoragePropertiesPtr> &storageList) +{ + StoragePropertiesPtr storage(new StorageProperties()); + storage->setId(0xff); + storage->setLabel(label); + storage->setType(StorageProperties::TYPE_INTERNAL); + + storage_state_e currentState; + storage_get_state(0, ¤tState); + storage->setState((short)currentState); + + storageList.insert(storageList.end(), storage); +} + +void Manager::addWidgetStorage(const std::string &key, const std::string &value) +{ + setupLocation(key, value.c_str()); + + if (key == "wgt-package") + { + m_subrootlist[LT_WGTPKG] = key; + } + else if (key == "wgt-private") + { + m_subrootlist[LT_WGTPRV] = key; + } + else if (key == "wgt-private-tmp") + { + m_subrootlist[LT_WGTPRVTMP] = key; + } +} + +bool Manager::init() +{ + std::vector<StoragePropertiesPtr> storageList; + storage_foreach_device_supported(Manager::getSupportedDeviceCB, &storageList); + + for (size_t i = 0; i < storageList.size(); i++) { + m_locations[storageList[i]->getLabel()] = IPath::create(storageList[i]->getFullPath()); + m_rootlist[storageList[i]->getLabel()] = storageList[i]->getId(); + } + + /* for Tizen */ + setupLocation("downloads", PATH_DOWNLOADS); + setupLocation("documents", PATH_DOCUMENTS); + setupLocation("music", PATH_SOUNDS); + setupLocation("images", PATH_IMAGES); + setupLocation("videos", PATH_VIDEOS); + setupLocation("ringtones", PATH_RINGTONE); + + m_subrootlist[LT_ROOT] = "internal0"; + m_subrootlist[LT_SDCARD] = "removable1"; + m_subrootlist[LT_USBHOST] = "removable2"; + m_subrootlist[LT_DOWNLOADS] = "downloads"; + m_subrootlist[LT_DOCUMENTS] = "documents"; + m_subrootlist[LT_SOUNDS] = "music"; + m_subrootlist[LT_IMAGES] = "images"; + m_subrootlist[LT_VIDEOS] = "videos"; + m_subrootlist[LT_RINGTONES] = "ringtones"; + return true; + +} + +void Manager::setupLocation(std::string location, const char* path) +{ + if (!nodeExists(path)) { + try { + makePath(path, 0755); + } + catch (const Commons::Exception& ex) + { + LoggerE("Exception: " << ex.GetMessage()); + return; + } + } + m_locations[location] = IPath::create(path); +} + +void Manager::Watcher::getCurrentStoargeStateForWatch() +{ + std::string label(""); + storage_type_e type; + storage_state_e state; + RootList::const_iterator it = m_rootlist.begin(); + for (; it != m_rootlist.end(); ++it) { + label = it->first; + if (label.compare("") != 0) { + StoragePropertiesPtr storageItem(new StorageProperties()); + + if (storage_get_type(it->second, &type) != STORAGE_ERROR_NONE) { + Throw(Commons::PlatformException); + } + if (storage_get_state(it->second, &state) != STORAGE_ERROR_NONE) { + Throw(Commons::PlatformException); + } + + storageItem->setId(it->second); + storageItem->setLabel(it->first); + storageItem->setType(static_cast<short>(type)); + storageItem->setState(static_cast<short>(state)); + + EventStorageStateChangedPtr event(new EventStorageStateChanged()); + + event->setResult(storageItem); + emit(event); + } + } +} + +void Manager::Watcher::StorageStateHasChanged(int storage, storage_state_e state) +{ + StoragePropertiesPtr storageItem(new StorageProperties()); + + std::string label; + storage_type_e type; + + RootList::const_iterator it = m_rootlist.begin(); + for (; it != m_rootlist.end(); ++it) { + if (it->second == storage) { + label = it->first; + break; + } + } + + if (storage_get_type(storage, &type) != STORAGE_ERROR_NONE) { + Throw(Commons::PlatformException); + } + + if (label.compare("") != 0) { + storageItem->setId(storage); + storageItem->setLabel(label); + storageItem->setType(static_cast<short>(type)); + storageItem->setState(static_cast<short>(state)); + + EventStorageStateChangedPtr event(new EventStorageStateChanged()); + + event->setResult(storageItem); + emit(event); + } +} + +} +} diff --git a/wearable_src/Filesystem/Manager.h b/wearable_src/Filesystem/Manager.h new file mode 100755 index 0000000..47b6ea9 --- /dev/null +++ b/wearable_src/Filesystem/Manager.h @@ -0,0 +1,189 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 TIZENAPIS_FILESYSTEMMANAGER_H_ +#define TIZENAPIS_FILESYSTEMMANAGER_H_ + +#include <string> +#include <map> +#include <vector> +#include <cstddef> +#include <dpl/shared_ptr.h> +#include "IManager.h" +#include "IPath.h" +#include <appfw/app_storage.h> +#include "Node.h" +#include "Path.h" + +namespace DeviceAPI { +namespace Filesystem { +class Manager : public IManager +{ + public: + /** + * Checks if file exists. + * @param real file path. + * @return true when file exists, false otherwise. + * @throw PlatformException If unable to validate if file exists. + */ + static bool fileExists(const std::string &file); + static bool getSupportedDeviceCB(int storage, storage_type_e type, storage_state_e state, const char *path, void *user_data); + static void storageStateChangedCB(int storage, storage_state_e state, void *user_data); + + public: + Manager(); + ~Manager(); + + IPathPtr getBasePath() const; + + StorageList getStorageList() const; + + IPathPtr getLocationPath( + LocationType type) const; + + LocationPaths getLocationPaths() const; + + LocationTypes getLocations() const; + + void getNode(const EventResolvePtr& event); + + void getStorage(const EventGetStoragePtr& event); + + void listStorages(const EventListStoragesPtr& event); + + std::size_t getMaxPathLength() const; + + void copy(const EventCopyPtr& event); + + void move(const EventMovePtr& event); + + void create(const EventCreatePtr& event); + + void remove(const EventRemovePtr& event); + + void find(const EventFindPtr& event); + + /** + * Finds files in the filesystem whish match specified filters. + * @param path Starting path. + * @param filter Filters @see FindFilters. + * @param result List with found files. + * @param event DPL event, if set then search process can be cancelled + * @remarks For filter FF_NAME value is treated as perl like regex pattern. + * Use @Regex::escpae() if you want to treat it as normal string. + */ + void find( + const IPathPtr& path, + const FiltersMap& filter, + NodeList& result, + const EventFindPtr& event = + EventFindPtr(NULL)); + + /** + * @warning Operates on specified as it is - it DOES NOT take its real path. + * This is because all filesystem operation will probably change + * their approach to real path and will allow to refer to nodes + * only by virtual roots. + */ +/* bool access(const IPathPtr& path, + int accessType) const;*/ + + void addOpenedNode(const INodePtr& node); + void removeOpenedNode(const INodePtr& node); + bool checkIfOpened(const IPathPtr& path) const; + + long addStorageStateChangeListener(const EventStorageStateChangedEmitterPtr& emitter); + void removeStorageStateChangeListener(EventStorageStateChangedEmitter::IdType id); + +public : + class Watcher + { + private: + EventStorageStateChangedEmitterPtr m_emitter; + + public: + Watcher(const EventStorageStateChangedEmitterPtr& emitter) : + m_emitter(emitter) + { + } + + EventStorageStateChangedEmitterPtr getEmitter() + { + return m_emitter; + } + + void emit(const EventStorageStateChangedPtr& event) + { + m_emitter->emit(event); + } + void getCurrentStoargeStateForWatch(); + void StorageStateHasChanged(int storage, storage_state_e state); + }; + typedef DPL::SharedPtr<Watcher> WatcherPtr; + + protected: + bool matchFilters(const std::string& name, + const struct stat& info, + const FiltersMap& filter); + + void OnRequestReceived(const EventResolvePtr& event); + void OnRequestReceived(const EventGetStoragePtr& event); + void OnRequestReceived(const EventListStoragesPtr& event); + void OnRequestReceived(const EventCopyPtr& event); + void OnRequestReceived(const EventMovePtr& event); + void OnRequestReceived(const EventCreatePtr& event); + void OnRequestReceived(const EventRemovePtr& event); + void OnRequestReceived(const EventFindPtr& event); + + void addLocalStorage(std::string label, std::vector<StoragePropertiesPtr> &storageList); + void addWidgetStorage(const std::string &key, const std::string &value); + private: + typedef std::map<std::string, + IPathPtr> Locations; + + typedef std::map<std::string, int> RootList; + typedef std::map<LocationType, std::string> SubRootList; + private: + /** + * Initializes statics of Manager class. + * Used only internally. + * @return True on success, false otherwsie. + */ + static bool init(); + static void setupLocation(std::string location, const char* path); + + void copyElement(const std::string &src, + const std::string &dest, + bool recursive = true) const; + + + private: + static RootList m_rootlist; + static SubRootList m_subrootlist; + static Locations m_locations; ///< Paths to default locations. + static const std::size_t m_maxPathLength; ///< Maximum path length. + static NodeList m_openedNodes; ///< List of nodes that has opened streams. + +public: + typedef std::vector<WatcherPtr> watcherList; + static watcherList m_watchers; +}; +} // Filesystem +} // TizenApis + +#endif // TIZENAPIS_FILESYSTEMMANAGER_H_
\ No newline at end of file diff --git a/wearable_src/Filesystem/Node.cpp b/wearable_src/Filesystem/Node.cpp new file mode 100644 index 0000000..5a04a1b --- /dev/null +++ b/wearable_src/Filesystem/Node.cpp @@ -0,0 +1,653 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "Node.h" + +#include <algorithm> +#include <memory> +#include <typeinfo> +#include <sys/types.h> +#include <cstdio> +#include <unistd.h> +#include <dirent.h> +#include <errno.h> +#include <pcrecpp.h> +#include <sstream> + +#include <Commons/Exception.h> +#include "PathUtils.h" +#include "Enums.h" +#include "Manager.h" +#include "NodeFilterMatcher.h" +#include <Logger.h> + +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; + + +namespace DeviceAPI { +namespace Filesystem { + +#define MAX_NODE_LENGTH 256 +bool Node::checkPermission(const std::string mode) +{ + switch (m_type) + { + case NT_DIRECTORY: + { + DIR* dir = opendir(m_path->getFullPath().c_str()); + + if (!dir) + ThrowMsg(Commons::SecurityException, "Node has been deleted from platform."); + + if (closedir(dir) != 0) + ThrowMsg(Commons::SecurityException, "Could not close platform node."); + + LoggerD("open/close dir ok"); + + + if (mode == "r") + return true; + + std::stringstream ss; + time_t now; + time(&now); + ss << now; + IPathPtr tempFilePath = IPath::create(m_path->getFullPath()); + tempFilePath->append(ss.str()); + try + { + createAsFileInternal(tempFilePath); + removeAsFile(tempFilePath); + } + catch (const Commons::Exception& ex) + { + LoggerE("Exception: " << ex.GetMessage()); + return false; + } + + if (mode == "rw" || mode == "w" || mode == "a") + return true; + ThrowMsg(Commons::InvalidArgumentException, "invalid mode"); + } + break; + case NT_FILE: + { + std::fstream stream; + std::ios_base::openmode modeBit = std::fstream::binary; + + if (mode == "r") + { + modeBit |= std::fstream::in; + } + else if (mode == "rw" || mode == "w" || mode == "a") + { + modeBit |= std::fstream::app; + } + else + { + ThrowMsg(Commons::InvalidArgumentException, "invalid mode"); + } + + stream.open(m_path->getFullPath().c_str(), modeBit); + + if (stream.is_open()) + { + stream.close(); + return true; + } + return false; + } + break; + } + return false; +} + +INodePtr Node::resolve(const IPathPtr& path) +{ + struct stat info; + struct stat syminfo; + + if (lstat(path->getFullPath().c_str(), &info) != 0) { + LoggerE("File: " << path->getFullPath().c_str() << " error no" <<errno); + + switch (errno) + { + case EACCES: + ThrowMsg(Commons::SecurityException, "Node access denied"); + break; + case ENOENT: + ThrowMsg(Commons::NotFoundException, "Node does not exist"); + break; + default: + ThrowMsg(Commons::PlatformException, "Platform exception fail"); + } + } + + if (!S_ISDIR(info.st_mode) & !S_ISREG(info.st_mode) && !S_ISLNK(info.st_mode)) { + ThrowMsg(Commons::PlatformException, + "Platform node is of unsupported type."); + } + + NodeType type = S_ISDIR(info.st_mode) ? NT_DIRECTORY : NT_FILE; + + if (S_ISLNK(info.st_mode)) { + syminfo = stat(path); + + type = S_ISDIR(syminfo.st_mode) ? NT_DIRECTORY : NT_FILE; + LoggerD(type); + } + + NodePtr result(new Node(path, type)); + + return DPL::StaticPointerCast<INode>(result); +} + +IPathPtr Node::getPath() const +{ + return IPath::create(m_path->getFullPath()); +} + +INodePtr Node::getChild(const IPathPtr& path) +{ + if (m_type != NT_DIRECTORY) { + ThrowMsg(Commons::PlatformException, "Not a directory."); + } + return Node::resolve(*m_path + *path); +} + +NodeType Node::getType() const +{ + return m_type; +} + +int Node::getPermissions() const +{ + return m_perms; +} + +void Node::setPermissions(int perms) +{ + m_perms = perms; +} + +Node::NameList Node::getChildNames() const +{ + if (m_type != NT_DIRECTORY) { + ThrowMsg(Commons::PlatformException, "Node is not directory."); + } + + if ((m_perms & PERM_READ) == 0) { + ThrowMsg(Commons::SecurityException, "No permission."); + } + + DIR* dir = opendir(m_path->getFullPath().c_str()); + if (!dir) { + ThrowMsg(Commons::PlatformException, + "Node has been deleted from platform."); + } + + NameList result; + errno = 0; + struct dirent *entry = NULL; + while ((entry = readdir(dir))) { + if (!strcmp(entry->d_name, ".") || !strncmp(entry->d_name, "..", 2)) { + continue; + } + result.push_back(entry->d_name); + } + if (errno != 0) { + ThrowMsg(Commons::PlatformException, "Error while reading directory."); + } + + if (closedir(dir) != 0) { + ThrowMsg(Commons::PlatformException, "Could not close platform node."); + } + + return result; +} + +NodeList Node::getChildNodes(const NodeFilterPtr& filter) const +{ + if (m_type != NT_DIRECTORY) { + ThrowMsg(Commons::PlatformException, "Node is not directory."); + } + + if ((m_perms & PERM_READ) == 0) { + ThrowMsg(Commons::SecurityException, "No permission."); + } + + DIR* dir = opendir(m_path->getFullPath().c_str()); + if (!dir) { + ThrowMsg(Commons::PlatformException, + "Node has been deleted from platform."); + } + + errno = 0; + NodeList result; + struct dirent *entry = NULL; + while ((entry = readdir(dir))) { + if (!strcmp(entry->d_name, ".") || !strncmp(entry->d_name, "..", 2)) { + continue; + } + + Try { + INodePtr node = Node::resolve(*m_path + entry->d_name); + node->setPermissions(getPermissions()); // inherit access rights + if (NodeFilterMatcher::match(node, filter)) { + result.push_back(node); + } + } + catch (const Commons::Exception& ex) + { + LoggerD("exception"); + } + } + + if (errno != 0) { + ThrowMsg(Commons::PlatformException, "Error while reading directory."); + } + + if (closedir(dir) != 0) { + ThrowMsg(Commons::PlatformException, "Could not close platform node."); + } + + return result; +} + +void Node::getChildNodes(const EventListNodesPtr& event) +{ + LoggerD("ENTER"); + EventRequestReceiver<EventListNodes>::PostRequest(event); +} + +INodePtr Node::createChild( + const IPathPtr& path, + NodeType type, + int options) +{ + if (m_type != NT_DIRECTORY) { + ThrowMsg(Commons::PlatformException, "Parent node is not a directory."); + } + + /* if ((m_perms & PERM_WRITE) == 0) { + ThrowMsg(Commons::SecurityException, "Not enough permissions."); + }*/ + + IPathPtr childPath = *m_path + *path; + if (exists(childPath)) { + ThrowMsg(Commons::PlatformException, "Node already exists."); + } + + NodePtr result; + switch (type) { + case NT_FILE: + result.Reset(createAsFile(childPath, options)); + break; + case NT_DIRECTORY: + result.Reset(createAsDirectory(childPath, options)); + break; + default: + ThrowMsg(Commons::PlatformException, "Unsupported node type."); + } + if (!!result) { + result->m_perms = m_perms; + } else { + ThrowMsg(Commons::PlatformException, "Node creation error"); + } + + return DPL::StaticPointerCast<INode>(result); +} + +IStreamPtr Node::open(int mode) +{ + if (m_type == NT_DIRECTORY) { + ThrowMsg(Commons::PlatformException, + "Cannot attach stream to directory."); + } + + if (((mode & AM_READ) && ((m_perms & PERM_READ) == 0)) || + (((mode & AM_WRITE) || + (mode & AM_APPEND)) && ((m_perms & PERM_WRITE) == 0))) { + ThrowMsg(Commons::SecurityException, "Not enough permissions."); + } + + DPL::Mutex::ScopedLock lock(&m_openStreamsMutex); + StreamPtr stream(new Stream(SharedFromThis(), mode)); + m_openStreams.insert(stream); + IManager::getInstance().addOpenedNode(DPL::StaticPointerCast<INode>( + SharedFromThis())); + return DPL::StaticPointerCast<IStream>(stream); +} + +void Node::open(const EventOpenPtr& event) +{ + LoggerD("ENTER"); + EventRequestReceiver<EventOpen>::PostRequest(event); +} + +void Node::remove(int options) +{ + switch (m_type) { + case NT_FILE: + removeAsFile(m_path); + break; + case NT_DIRECTORY: + removeAsDirectory(m_path, (options & OPT_RECURSIVE)); + break; + } +} + +unsigned long long Node::getSize() const +{ + if (m_type == NT_DIRECTORY) { + ThrowMsg(Commons::PlatformException, + "Getting size for directories is not supported."); + } + + struct stat info = stat(m_path); + if (!S_ISREG(info.st_mode)) { + ThrowMsg(Commons::PlatformException, + "Specified node is not a regular file."); + } + + return info.st_size; +} + +std::time_t Node::getCreated() const +{ + return stat(m_path).st_ctime; +} + +std::time_t Node::getModified() const +{ + return stat(m_path).st_mtime; +} + +// TODO Optimize it, maybe store a flag indicating that node is a root. +INodePtr Node::getParent() const +{ + LocationPaths roots = IManager::getInstance().getLocationPaths(); + for (LocationPaths::iterator it = roots.begin(); it != roots.end(); ++it) { + if (*(*it) == *m_path) { + return INodePtr(); + } + } + return Node::resolve(IPath::create(m_path->getPath())); +} + +int Node::getMode() const +{ + int result = 0; + struct stat info = stat(m_path); + if (info.st_mode & S_IRUSR) { result |= PM_USER_READ; } + if (info.st_mode & S_IWUSR) { result |= PM_USER_WRITE; } + if (info.st_mode & S_IXUSR) { result |= PM_USER_EXEC; } + if (info.st_mode & S_IRGRP) { result |= PM_GROUP_READ; } + if (info.st_mode & S_IWGRP) { result |= PM_GROUP_WRITE; } + if (info.st_mode & S_IXGRP) { result |= PM_GROUP_EXEC; } + if (info.st_mode & S_IROTH) { result |= PM_OTHER_READ; } + if (info.st_mode & S_IWOTH) { result |= PM_OTHER_WRITE; } + if (info.st_mode & S_IXOTH) { result |= PM_OTHER_EXEC; } + return result; +} + +void Node::read(const EventReadTextPtr& event) +{ + LoggerD("ENTER"); + EventRequestReceiver<EventReadText>::PostRequest(event); +} + +void Node::onStreamClose(const StreamPtr& stream) +{ + { + DPL::Mutex::ScopedLock lock(&m_openStreamsMutex); + m_openStreams.erase(stream); + } + if (m_openStreams.empty()) { + IManager::getInstance().removeOpenedNode(DPL::StaticPointerCast<INode>( + SharedFromThis())); + } +} + +bool Node::exists(const IPathPtr& path) +{ + struct stat info; + memset(&info, 0, sizeof(struct stat)); + int status = lstat(path->getFullPath().c_str(), &info); + + if (status == 0) + { + return true; + } + else if (errno == ENAMETOOLONG) + { + ThrowMsg(Commons::PlatformException, "file name is too long"); + } + else if (errno != ENOENT) + { + return true; + } + return false; +} + +struct stat Node::stat(const IPathPtr& path) +{ + struct stat result; + memset(&result, 0, sizeof(struct stat)); + if (::stat(path->getFullPath().c_str(), + &result) != 0) + { + LoggerE("File: " << path->getFullPath().c_str()); + ThrowMsg(Commons::PlatformException, "Node does not exist or no access"); + } + return result; +} + +Node::Node(const IPathPtr& path, + NodeType type) : + m_path(path), + m_type(type), + m_perms(PERM_NONE) +{ +} + +Node* Node::createAsFile(const IPathPtr& path, + int /* options */) +{ + LoggerD("ENTER"); + createAsFileInternal(path); + return new Node(path, NT_FILE); +} + +void Node::createAsFileInternal(const IPathPtr& path) +{ + LoggerD("ENTER"); + FILE* file = std::fopen(path->getFullPath().c_str(), "wb"); + if (!file) { + ThrowMsg(Commons::PlatformException, + "Platform node could not be created."); + } + std::fclose(file); +} + +Node* Node::createAsDirectory(const IPathPtr& path, + int options) +{ + if (options & OPT_RECURSIVE) { + PathUtils::PathList parts = PathUtils::getParts(path); + PathUtils::PathListIterator it = parts.begin(); + for (; it != parts.end(); ++it) { + if (!exists(*it)) { createAsDirectoryInternal(*it); } + } + } + createAsDirectoryInternal(path); + return new Node(path, NT_DIRECTORY); +} + +void Node::createAsDirectoryInternal(const IPathPtr& path) +{ + if (mkdir(path->getFullPath().c_str(), S_IRWXU | S_IRWXG | S_IROTH | + S_IXOTH) != 0) { + ThrowMsg(Commons::PlatformException, + "Platform node could not be created."); + } +} + +void Node::removeAsFile(const IPathPtr& path) +{ + DPL::Mutex::ScopedLock lock(&m_openStreamsMutex); + if (!m_openStreams.empty()) { + ThrowMsg(Commons::PlatformException, "Node is locked for I/O."); + } + if (IManager::getInstance().checkIfOpened(path)) { + ThrowMsg(Commons::PlatformException, "Node is locked for I/O."); + } + + if (unlink(path->getFullPath().c_str()) != 0) { + ThrowMsg(Commons::PlatformException, + "Error while removing platform node."); + } +} + +void Node::removeAsDirectory(const IPathPtr& path, + bool recursive) +{ + if (recursive) { + DIR* dir = opendir(path->getFullPath().c_str()); + if (!dir) { + LoggerE("File: " << path->getFullPath().c_str()); + ThrowMsg(Commons::PlatformException, + "Node does not exist or access denied."); + } + errno = 0; + struct dirent *entry = NULL; + while ((entry = readdir(dir))) { + if (!strcmp(entry->d_name, ".") || !strncmp(entry->d_name, "..", 2)) { + continue; + } + IPathPtr subPath = *path + entry->d_name; + struct stat info; + memset(&info, 0, sizeof(struct stat)); + if (lstat(subPath->getFullPath().c_str(), &info) == 0) { + Try { + if (S_ISDIR(info.st_mode)) { + removeAsDirectory(subPath, true); + } else if (S_ISREG(info.st_mode)) { + removeAsFile(subPath); + } + } + catch (const Commons::Exception& ex) + { + } + // TODO: Not sure if above exception should be swallowed. + } + } + closedir(dir); + } + + errno = 0; + if (rmdir(path->getFullPath().c_str()) != 0) { + if (errno == EEXIST) { + ThrowMsg(Commons::PlatformException, "Node has child nodes."); + } + ThrowMsg(Commons::PlatformException, + "Error while removing platform node."); + } +} + +void Node::OnRequestReceived(const EventListNodesPtr& event) +{ + try { + NodeList list = event->getNode()->getChildNodes(event->getFilter()); + event->setResult(list); + } + catch (const Commons::Exception& ex) + { + LoggerE("Exception: " << ex.GetMessage()); + event->setExceptionCode(ex.getCode()); + } + +} + +void Node::OnRequestReceived(const EventOpenPtr& event) +{ + if (!event->checkCancelled()) { + try { + IStreamPtr result = open(event->getMode()); + result->setCharSet(event->getCharSet()); + event->setResult(result); + } + + catch (const Commons::Exception& ex) + { + LoggerE("Exception: " << ex.GetMessage()); + event->setExceptionCode(ex.getCode()); + } + //event can be cancelled before executing this code. + //when it comes here we doesn't allow it anymore + event->setCancelAllowed(false); + } else { + event->setCancelAllowed(true); + } +} + +void Node::OnRequestReceived(const EventReadTextPtr& event) +{ + Try { + event->setResult(readText()); + LoggerD("LEAVIN GRACEFULLY"); + } + catch (const Commons::Exception& ex) + { + LoggerE("Exception: " << ex.GetMessage()); + event->setExceptionCode(ex.getCode()); + } + //this function doesn't change state of the platform, + //so we can allow to cancel it and discard results. + event->setCancelAllowed(true); +} + +std::string Node::readText() +{ + if (m_type != NT_FILE) { + ThrowMsg(Commons::PlatformException, "Node is not a file."); + } + + if ((m_perms & PERM_READ) == 0) { + ThrowMsg(Commons::SecurityException, "No permission."); + } + + std::stringstream result; + DPL::SharedPtr<Stream> stream(new Stream(SharedFromThis(), AM_READ)); + while (!stream->isEof()) { + result << stream->getLine(); + if(!stream->isEof()) + result << '\n'; + } + stream->close(); + return result.str(); +} + +std::string Node::toUri(int /*widgetId*/) const +{ + // TODO I believe moving this feature to WrtWrapper would make more sense. + return "file://" + m_path->getFullPath(); +} +} +} diff --git a/wearable_src/Filesystem/Node.h b/wearable_src/Filesystem/Node.h new file mode 100755 index 0000000..94bf411 --- /dev/null +++ b/wearable_src/Filesystem/Node.h @@ -0,0 +1,118 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 TIZENAPIS_FILESYSTEM_NODE_H_ +#define TIZENAPIS_FILESYSTEM_NODE_H_ + +#include <ctime> +#include <cstddef> +#include <sys/stat.h> +#include <set> +#include <dpl/shared_ptr.h> +#include <dpl/enable_shared_from_this.h> +#include <dpl/mutex.h> + +#include "Enums.h" +#include "INode.h" +#include "Path.h" +#include "Stream.h" + +namespace DeviceAPI { +namespace Filesystem { +class Node : public INode, + public DPL::EnableSharedFromThis<Node> +{ + public: + static INodePtr resolve( + const IPathPtr& path); + + + public: + bool checkPermission(const std::string mode); + IPathPtr getPath() const; + NodeType getType() const; + int getPermissions() const; + void setPermissions(int perms); + unsigned long long getSize() const; + std::time_t getCreated() const; + std::time_t getModified() const; + INodePtr getParent() const; + int getMode() const; + + INodePtr getChild(const IPathPtr& path); + NameList getChildNames() const; + NodeList getChildNodes( + const NodeFilterPtr& filter = + NodeFilterPtr()) const; + void getChildNodes(const EventListNodesPtr& event); + INodePtr createChild( + const IPathPtr & path, + NodeType, + int options); + IStreamPtr open(int mode); + void open(const EventOpenPtr& event); + void remove(int options); + void read(const EventReadTextPtr& event); + + void onStreamClose(const StreamPtr& stream); + + private: + typedef std::set<StreamPtr> StreamList; + + private: + static bool exists(const IPathPtr& path); + static struct stat stat(const IPathPtr& path); + + private: + Node(const IPathPtr& path, + NodeType type); + + Node* createAsFile(const IPathPtr& path, + int options); + void createAsFileInternal(const IPathPtr& path); + + Node* createAsDirectory(const IPathPtr& path, + int options); + void createAsDirectoryInternal(const IPathPtr& path); + + void removeAsFile(const IPathPtr& path); + void removeAsDirectory(const IPathPtr& path, + bool recursive); + + void OnRequestReceived(const EventListNodesPtr& event); + void OnRequestReceived(const EventOpenPtr& event); + + void OnRequestReceived(const EventReadTextPtr& event); + std::string readText(); + + std::string toUri(int widgetId) const; + + + private: + IPathPtr m_path; + NodeType m_type; + int m_perms; + StreamList m_openStreams; + mutable DPL::Mutex m_openStreamsMutex; +}; + +typedef DPL::SharedPtr<Node> NodePtr; +} // Filesystem +} // TizenApis + +#endif /* TIZENAPIS_FILESYSTEM_NODE_H_ */ diff --git a/wearable_src/Filesystem/NodeFilter.cpp b/wearable_src/Filesystem/NodeFilter.cpp new file mode 100755 index 0000000..2a13157 --- /dev/null +++ b/wearable_src/Filesystem/NodeFilter.cpp @@ -0,0 +1,128 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "NodeFilter.h" + +namespace DeviceAPI { +namespace Filesystem { + +NodeFilter::NodeFilter() +{ + m_valid = false; +} + +NodeFilter::~NodeFilter() +{ +} + +OptionalString NodeFilter::getName() const +{ + return m_name; +} + +void NodeFilter::setFilterValid(bool valid) +{ + m_valid = valid; +} + +bool NodeFilter::isFilterValid() +{ + return m_valid; +} + +void NodeFilter::setName(const OptionalString& name) +{ + m_name = name; +} + +OptionalDate NodeFilter::getMinCreated() const +{ + return m_created.min; +} + +void NodeFilter::setMinCreated(const OptionalDate& date) +{ + m_created.min = date; +} + +OptionalDate NodeFilter::getMaxCreated() const +{ + return m_created.max; +} + +void NodeFilter::setMaxCreated(const OptionalDate& date) +{ + m_created.max = date; +} + +void NodeFilter::setCreated(const OptionalDate& date) +{ + m_created.min = m_created.max = date; +} + +OptionalDate NodeFilter::getMinModified() const +{ + return m_modified.min; +} + +void NodeFilter::setMinModified(const OptionalDate& date) +{ + m_modified.min = date; +} + +OptionalDate NodeFilter::getMaxModified() const +{ + return m_modified.max; +} + +void NodeFilter::setMaxModified(const OptionalDate& date) +{ + m_modified.max = date; +} + +void NodeFilter::setModified(const OptionalDate& date) +{ + m_modified.min = m_modified.max = date; +} + +OptionalSize NodeFilter::getMinSize() const +{ + return m_size.min; +} + +void NodeFilter::setMinSize(const OptionalSize& size) +{ + m_size.min = size; +} + +OptionalSize NodeFilter::getMaxSize() const +{ + return m_size.max; +} + +void NodeFilter::setMaxSize(const OptionalSize& size) +{ + m_size.max = size; +} + +void NodeFilter::setSize(const OptionalSize& size) +{ + m_size.min = m_size.max = size; +} +} // Filesystem +} // TizenApis
\ No newline at end of file diff --git a/wearable_src/Filesystem/NodeFilter.h b/wearable_src/Filesystem/NodeFilter.h new file mode 100755 index 0000000..bd2381a --- /dev/null +++ b/wearable_src/Filesystem/NodeFilter.h @@ -0,0 +1,82 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 TIZENAPIS_FILESYSTEM_NODEFILTER_H_ +#define TIZENAPIS_FILESYSTEM_NODEFILTER_H_ + +#include <ctime> +#include <cstddef> +#include <string> +#include <dpl/optional.h> +#include <dpl/shared_ptr.h> +#include <Commons/Range.h> + +namespace DeviceAPI { +namespace Filesystem { +typedef DPL::Optional<std::string> OptionalString; +typedef DPL::Optional<std::time_t> OptionalDate; +typedef DPL::Optional<unsigned long long> OptionalSize; + +class NodeFilter +{ + public: + NodeFilter(); + virtual ~NodeFilter(); + OptionalString getName() const; + void setName(const OptionalString& name); + + OptionalDate getMinCreated() const; + void setMinCreated(const OptionalDate& date); + + OptionalDate getMaxCreated() const; + void setMaxCreated(const OptionalDate& date); + + void setCreated(const OptionalDate& date); + + OptionalDate getMinModified() const; + void setMinModified(const OptionalDate& date); + + OptionalDate getMaxModified() const; + void setMaxModified(const OptionalDate& date); + + void setModified(const OptionalDate& date); + + OptionalSize getMinSize() const; + void setMinSize(const OptionalSize& size); + + OptionalSize getMaxSize() const; + void setMaxSize(const OptionalSize& size); + + void setSize(const OptionalSize& size); + void setFilterValid(bool valid); + bool isFilterValid(); + private: + bool m_valid; + + OptionalString m_name; + WrtDeviceApis::Commons::Range<OptionalDate> m_created; + WrtDeviceApis::Commons::Range<OptionalDate> m_modified; + WrtDeviceApis::Commons::Range<OptionalSize> m_size; +}; + +typedef DPL::SharedPtr<NodeFilter> NodeFilterPtr; +} // Filesystem +} // TizenApis + +#endif // TIZENAPIS_FILESYSTEM_NODEFILTER_H_
\ No newline at end of file diff --git a/wearable_src/Filesystem/NodeFilterMatcher.cpp b/wearable_src/Filesystem/NodeFilterMatcher.cpp new file mode 100755 index 0000000..f7fc86f --- /dev/null +++ b/wearable_src/Filesystem/NodeFilterMatcher.cpp @@ -0,0 +1,79 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "NodeFilterMatcher.h" + +#include <pcrecpp.h> + +namespace DeviceAPI { +namespace Filesystem { +bool NodeFilterMatcher::match(const INodePtr& value, + const NodeFilterPtr& filter) +{ + if (filter) { + if (!matchString(value->getPath()->getName(), filter->getName())) { + return false; + } + + if (!matchRange(value->getCreated(), + filter->getMinCreated(), + filter->getMaxCreated())) { + return false; + } + + if (!matchRange(value->getModified(), + filter->getMinModified(), + filter->getMaxModified())) { + return false; + } + +/* if (!matchRange(value->getSize(), + filter->getMinSize(), + filter->getMaxSize())) { + return false; + }*/ + } + + return true; +} + + +bool NodeFilterMatcher::matchString(const std::string& value, + const OptionalString& filter) +{ + if (!filter.IsNull()) { + pcrecpp::RE_Options reoption; + reoption.set_caseless(true); + return pcrecpp::RE(*filter, reoption).PartialMatch(value); + } + return true; +} + +template<typename Type> +bool NodeFilterMatcher::matchRange(const Type& value, + const DPL::Optional<Type>& min, + const DPL::Optional<Type>& max) +{ + if ((!min.IsNull() && (value < *min)) || + (!max.IsNull() && (value > *max))) { + return false; + } + return true; +} +} // Filesystem +} // TizenApis
\ No newline at end of file diff --git a/wearable_src/Filesystem/NodeFilterMatcher.h b/wearable_src/Filesystem/NodeFilterMatcher.h new file mode 100755 index 0000000..23c9f54 --- /dev/null +++ b/wearable_src/Filesystem/NodeFilterMatcher.h @@ -0,0 +1,50 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 TIZENAPIS_FILESYSTEM_NODEFILTERMATCHER_H_ +#define TIZENAPIS_FILESYSTEM_NODEFILTERMATCHER_H_ + +#include <string> +#include <dpl/optional.h> +#include "INode.h" +#include "NodeFilter.h" + +namespace DeviceAPI { +namespace Filesystem { +class NodeFilterMatcher +{ + public: + static bool match(const INodePtr& value, + const NodeFilterPtr& filter); + + private: + static bool matchString(const std::string& value, + const OptionalString& filter); + + template<typename Type> + static bool matchRange(const Type& value, + const DPL::Optional<Type>& min, + const DPL::Optional<Type>& max); + + private: + NodeFilterMatcher(); +}; +} // Filesystem +} // TizenApis + +#endif // TIZENAPIS_FILESYSTEM_NODEFILTERMATCHER_H_ diff --git a/wearable_src/Filesystem/Path.cpp b/wearable_src/Filesystem/Path.cpp new file mode 100644 index 0000000..b5018b4 --- /dev/null +++ b/wearable_src/Filesystem/Path.cpp @@ -0,0 +1,118 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <memory> +#include <algorithm> +#include <iterator> +#include <stdlib.h> +#include <limits.h> +#include <Commons/Exception.h> +#include <Commons/StringUtils.h> +#include "Path.h" +#include <Logger.h> + +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; + +namespace DeviceAPI { +namespace Filesystem { +const Path::SeparatorType Path::m_pathSeparator = '/'; + +IPathPtr Path::create(const std::string& path) +{ + DPL::SharedPtr<Path> result(new Path()); + result->reset(path); + return DPL::StaticPointerCast<IPath>(result); +} + +std::string Path::getFullPath() const +{ + return m_fullPath; +} + +std::string Path::getPath() const +{ + return m_path; +} + +std::string Path::getName() const +{ + return m_name; +} + +IPathPtr Path::append(const std::string& path) +{ + reset(m_fullPath + m_pathSeparator + path); + return DPL::StaticPointerCast<IPath>(SharedFromThis()); +} + +IPathPtr Path::append(const IPathPtr& path) +{ + reset(m_fullPath + m_pathSeparator + path->getFullPath()); + return DPL::StaticPointerCast<IPath>(SharedFromThis()); +} + +bool Path::isAbsolute() const +{ + return (!m_fullPath.empty() && (m_fullPath[0] == m_pathSeparator)); +} + +IPath::SeparatorType Path::getSeparator() +{ + return m_pathSeparator; +} + +bool Path::isValid(const std::string& str) +{ + return !str.empty(); +} + +IPathPtr Path::clone() const +{ + return Path::create(m_fullPath); +} + +Path::Path() +{ +} + +void Path::reset(const std::string& str) +{ + if (!isValid(str)) { + LoggerD(str << "empty string"); + ThrowMsg(Commons::NotFoundException, + "Not a valid path: " + str + "."); + } + std::string tmp = Commons::String::unique(/*Commons::String::trim*/( + str), m_pathSeparator); + std::string::size_type pos = tmp.find_last_of(m_pathSeparator); + if (pos == std::string::npos) { + m_fullPath = m_name = tmp; + m_path.clear(); + } else { + if (0 == pos) { + m_fullPath = m_path = m_pathSeparator; + } else { + m_fullPath = m_path = tmp.substr(0, pos); + m_fullPath += m_pathSeparator; + } + m_name = tmp.substr(pos + 1); + m_fullPath += m_name; + } +} +} // Filesystem +} // TizenApis
\ No newline at end of file diff --git a/wearable_src/Filesystem/Path.h b/wearable_src/Filesystem/Path.h new file mode 100755 index 0000000..9a4c520 --- /dev/null +++ b/wearable_src/Filesystem/Path.h @@ -0,0 +1,68 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 TIZENAPIS_FILESYSTEM_PATH_H_ +#define TIZENAPIS_FILESYSTEM_PATH_H_ + +#include <string> +#include <vector> +#include <dpl/enable_shared_from_this.h> +#include "IPath.h" + +namespace DeviceAPI { +namespace Filesystem { +class Path : public IPath, + public DPL::EnableSharedFromThis<Path> +{ + public: + static IPathPtr create(const std::string& path); + static IPath::SeparatorType getSeparator(); + + public: + std::string getFullPath() const; + std::string getPath() const; + std::string getName() const; + IPathPtr append(const std::string& path); + IPathPtr append(const IPathPtr& path); + bool isAbsolute() const; + IPathPtr clone() const; + + private: + /** + * Checks whether specified string is a valid path. + * @param path String to verify. + * @return True when string is a valid path, false otherwise. + */ + static bool isValid(const std::string& str); + + private: + Path(); + void reset(const std::string& str); + + private: + static const SeparatorType m_pathSeparator; ///< Path separator. + + private: + std::string m_fullPath; ///< Full path. + std::string m_path; ///< Base path. + std::string m_name; ///< Last part of the path. +}; +} // Filesystem +} // TizenApis + +#endif /* TIZENAPIS_FILESYSTEM_PATH_H_ */ diff --git a/wearable_src/Filesystem/PathUtils.cpp b/wearable_src/Filesystem/PathUtils.cpp new file mode 100755 index 0000000..b6f47a0 --- /dev/null +++ b/wearable_src/Filesystem/PathUtils.cpp @@ -0,0 +1,38 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "PathUtils.h" +#include <Logger.h> +namespace DeviceAPI { +namespace Filesystem { +namespace PathUtils { +PathList getParts(const IPathPtr& path) +{ + PathList result; + IPath::SeparatorType separator = path->getSeparator(); + std::string fullPath = path->getFullPath(); + std::string::size_type pos = 0; + while ((pos = fullPath.find(separator, pos + 1)) != std::string::npos) { + if (pos == fullPath.length()- 1) + break; + result.push_back(IPath::create(fullPath.substr(0, pos))); + } + return result; +} +} // PathUtils +} // Filesystem +} // TizenApis diff --git a/wearable_src/Filesystem/PathUtils.h b/wearable_src/Filesystem/PathUtils.h new file mode 100755 index 0000000..63e6460 --- /dev/null +++ b/wearable_src/Filesystem/PathUtils.h @@ -0,0 +1,42 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 TIZENAPIS_FILESYSTEM_PATHUTILS_H_ +#define TIZENAPIS_FILESYSTEM_PATHUTILS_H_ + +#include <vector> +#include "IPath.h" + +namespace DeviceAPI { +namespace Filesystem { +namespace PathUtils { +typedef std::vector<IPathPtr> PathList; +typedef PathList::iterator PathListIterator; + +/** + * Gets sub-paths of supplied path. + * The supplied path is not included. + * @param path + * @return List of paths. + */ +PathList getParts(const IPathPtr& path); +} // PathUtils +} // Filesystem +} // TizenApis + +#endif // TIZENAPIS_FILESYSTEM_PATHUTILS_H_
\ No newline at end of file diff --git a/wearable_src/Filesystem/ResponseDispatcher.cpp b/wearable_src/Filesystem/ResponseDispatcher.cpp new file mode 100644 index 0000000..9f98ff2 --- /dev/null +++ b/wearable_src/Filesystem/ResponseDispatcher.cpp @@ -0,0 +1,336 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "ResponseDispatcher.h" + +#include <dpl/assert.h> +#include <Commons/Exception.h> +#include <Commons/IEvent.h> +#include <CommonsJavaScript/JSUtils.h> +#include <JSWebAPIErrorFactory.h> +#include "JSFile.h" +#include "JSFilestream.h" +#include "EventGetNodeData.h" +#include "Converter.h" +#include "FilesystemAsyncCallbackManager.h" +#include "Encodings.h" +#include "FilesystemUtils.h" +#include <Logger.h> + +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace DeviceAPI::Common; + +namespace DeviceAPI { +namespace Filesystem { +ResponseDispatcher& ResponseDispatcher::getInstance() +{ + static ResponseDispatcher dispatcher; + return dispatcher; +} + +ResponseDispatcher::ResponseDispatcher() : + EventAnswerReceiver<EventResolve>(ThreadEnum::NULL_THREAD), + EventAnswerReceiver<EventGetStorage>(ThreadEnum::NULL_THREAD), + EventAnswerReceiver<EventListStorages>(ThreadEnum::NULL_THREAD), + EventAnswerReceiver<EventListNodes>(ThreadEnum::NULL_THREAD), + EventAnswerReceiver<EventOpen>(ThreadEnum::NULL_THREAD), + EventAnswerReceiver<EventCopy>(ThreadEnum::NULL_THREAD), + EventAnswerReceiver<EventMove>(ThreadEnum::NULL_THREAD), + EventAnswerReceiver<EventRemove>(ThreadEnum::NULL_THREAD), + EventAnswerReceiver<EventReadText>(ThreadEnum::NULL_THREAD) +{ +} + +void ResponseDispatcher::OnAnswerReceived(const EventResolvePtr& event) +{ + LoggerD("ENTER"); + EventGetNodeDataPtr data = + DPL::DynamicPointerCast<EventGetNodeData>(event->getPrivateData()); + + FilesystemAsyncCallbackManagerSingleton::Instance().unregisterCallbackManager(data->getCallbackManager()); + + if (event->getExceptionCode() == WrtDeviceApis::Commons::ExceptionCodes::None) { + event->getResult()->setPermissions(data->getPerms()); + JSFile::PrivateObjectDefPtr privData(new JSFile::PrivateObjectDef(event->getResult(), JSFile::PrivateObjectDef::PermissionList())); + try { + INodePtr parent = event->getResult()->getParent(); + + if (parent) + { + privData->pushParentPermissions(data->getPerms()); + } + } + catch (...) + { + LoggerD("no parent"); + } + + JSObjectRef object = JSUtils::makeObject(data->getCallbackManager()->getContext(), JSFile::getClassRef(), privData); + data->getCallbackManager()->callOnSuccess(object); + } else { + JSObjectRef jsException; + if (event->getExceptionCode() == WrtDeviceApis::Commons::ExceptionCodes::NotFoundException) { + jsException = JSWebAPIErrorFactory::makeErrorObject(data->getCallbackManager()->getContext(), JSWebAPIErrorFactory::NOT_FOUND_ERROR, "NotFoundError"); + } + else if (event->getExceptionCode() == WrtDeviceApis::Commons::ExceptionCodes::SecurityException) { + jsException = JSWebAPIErrorFactory::makeErrorObject(data->getCallbackManager()->getContext(), JSWebAPIErrorFactory::INVALID_VALUES_ERROR, "PermissionDeniedError"); + } + else { + jsException = JSWebAPIErrorFactory::makeErrorObject(data->getCallbackManager()->getContext(), JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown error"); + } + data->getCallbackManager()->callOnError(jsException); + } +} + + +void ResponseDispatcher::OnAnswerReceived(const EventListNodesPtr& event) +{ + LoggerD("ENTER"); + JSFile::ListFilesPrivateDataPtr privData = + DPL::DynamicPointerCast<JSFile::ListFilesPrivateData>(event->getPrivateData()); + + JSCallbackManagerPtr data = privData->getCallbackManager(); + + FilesystemAsyncCallbackManagerSingleton::Instance().unregisterCallbackManager(data); + + if (event->getExceptionCode() == WrtDeviceApis::Commons::ExceptionCodes::None) { + Converter converter(data->getContext()); + Try { + JSValueRef result = converter.toJSValueRef(event->getResult(), privData->getParentPermissions(), data->getContext()); + data->callOnSuccess(result); + } + Catch(WrtDeviceApis::Commons::ConversionException) { + data->callOnError(JSWebAPIErrorFactory::makeErrorObject(data->getContext(), JSWebAPIErrorFactory::IO_ERROR, "IO error")); + } + } else { + JSObjectRef jsException = NULL; + jsException = JSWebAPIErrorFactory::makeErrorObject(data->getContext(), JSWebAPIErrorFactory::IO_ERROR, "IO error"); + data->callOnError(jsException); + } +} + +void ResponseDispatcher::OnAnswerReceived(const EventOpenPtr& event) +{ + LoggerD("ENTER"); + DPL::SharedPtr<JSCallbackManager> data = + DPL::DynamicPointerCast<JSCallbackManager>(event->getPrivateData()); + + FilesystemAsyncCallbackManagerSingleton::Instance().unregisterCallbackManager(data); + + if (event->getExceptionCode() == WrtDeviceApis::Commons::ExceptionCodes::None) { + JSObjectRef object = JSUtils::makeObject(data->getContext(), JSFilestream::getClassRef(), event->getResult()); + data->callOnSuccess(object); + } else { + JSObjectRef jsException; + + if (event->getExceptionCode() == WrtDeviceApis::Commons::ExceptionCodes::NotFoundException) { + jsException = JSWebAPIErrorFactory::makeErrorObject(data->getContext(), JSWebAPIErrorFactory::NOT_FOUND_ERROR, "NotFoundError"); + } + else if (event->getExceptionCode() == WrtDeviceApis::Commons::ExceptionCodes::SecurityException) { + jsException = JSWebAPIErrorFactory::makeErrorObject(data->getContext(), JSWebAPIErrorFactory::INVALID_VALUES_ERROR, "Permission Denied Error"); + } + else { + jsException = JSWebAPIErrorFactory::makeErrorObject(data->getContext(), JSWebAPIErrorFactory::IO_ERROR, "IO error"); + } + data->callOnError(jsException); + } +} + +void ResponseDispatcher::OnAnswerReceived(const EventCopyPtr& event) +{ + LoggerD("ENTER"); + DPL::SharedPtr<JSCallbackManager> data = + DPL::DynamicPointerCast<JSCallbackManager>(event->getPrivateData()); + + FilesystemAsyncCallbackManagerSingleton::Instance().unregisterCallbackManager(data); + + if (event->getExceptionCode() == WrtDeviceApis::Commons::ExceptionCodes::None) { + JSFile::PrivateObjectDefPtr privData(new JSFile::PrivateObjectDef( + event->getResult(), + JSFile::PrivateObjectDef::PermissionList())); + + JSObjectRef object = JSUtils::makeObject(data->getContext(), JSFile::getClassRef(), privData); + data->callOnSuccess(object); + } else { + JSObjectRef jsException = NULL; + if (event->getExceptionCode() == WrtDeviceApis::Commons::ExceptionCodes::SecurityException) { + jsException = JSWebAPIErrorFactory::makeErrorObject(data->getContext(), JSWebAPIErrorFactory::INVALID_VALUES_ERROR, "Permission denied error"); + } + else if (event->getExceptionCode() == WrtDeviceApis::Commons::ExceptionCodes::NotFoundException) { + jsException = JSWebAPIErrorFactory::makeErrorObject(data->getContext(), JSWebAPIErrorFactory::NOT_FOUND_ERROR, "NotFoundError"); + } + else { + jsException = JSWebAPIErrorFactory::makeErrorObject(data->getContext(), JSWebAPIErrorFactory::IO_ERROR, "IO error"); + } + data->callOnError(jsException); + } +} + +void ResponseDispatcher::OnAnswerReceived(const EventMovePtr& event) +{ + LoggerD("ENTER"); + DPL::SharedPtr<JSCallbackManager> data = + DPL::DynamicPointerCast<JSCallbackManager>(event->getPrivateData()); + + FilesystemAsyncCallbackManagerSingleton::Instance().unregisterCallbackManager(data); + + if (event->getExceptionCode() == WrtDeviceApis::Commons::ExceptionCodes::None) { + JSFile::PrivateObjectDefPtr privData(new JSFile::PrivateObjectDef( + event->getResult(), + JSFile::PrivateObjectDef::PermissionList())); + JSObjectRef object = JSUtils::makeObject(data->getContext(), + JSFile::getClassRef(), + privData); + data->callOnSuccess(object); + } else { + JSObjectRef jsException = NULL; + if (event->getExceptionCode() == WrtDeviceApis::Commons::ExceptionCodes::SecurityException) { + jsException = JSWebAPIErrorFactory::makeErrorObject(data->getContext(), JSWebAPIErrorFactory::INVALID_VALUES_ERROR, "Permission denied error"); + } + else if (event->getExceptionCode() == WrtDeviceApis::Commons::ExceptionCodes::NotFoundException) { + jsException = JSWebAPIErrorFactory::makeErrorObject(data->getContext(), JSWebAPIErrorFactory::NOT_FOUND_ERROR, "NotFoundError"); + } + else { + jsException = JSWebAPIErrorFactory::makeErrorObject(data->getContext(), JSWebAPIErrorFactory::IO_ERROR, "IO error"); + } + data->callOnError(jsException); + } +} + +void ResponseDispatcher::OnAnswerReceived(const EventRemovePtr& event) +{ + LoggerD("--| ENTER"); + DPL::SharedPtr<JSCallbackManager> data = + DPL::DynamicPointerCast<JSCallbackManager>(event->getPrivateData()); + + FilesystemAsyncCallbackManagerSingleton::Instance().unregisterCallbackManager(data); + + if (event->getExceptionCode() == WrtDeviceApis::Commons::ExceptionCodes::None) { + data->callOnSuccess(); + } else { + JSObjectRef jsException = NULL; + if (event->getExceptionCode() ==WrtDeviceApis::Commons::ExceptionCodes::SecurityException) { + jsException = JSWebAPIErrorFactory::makeErrorObject(data->getContext(), JSWebAPIErrorFactory::INVALID_VALUES_ERROR, "Permission denied error"); + } + else if (event->getExceptionCode() == WrtDeviceApis::Commons::ExceptionCodes::NotFoundException) { + jsException = JSWebAPIErrorFactory::makeErrorObject(data->getContext(), JSWebAPIErrorFactory::NOT_FOUND_ERROR, "NotFoundError"); + } + else { + jsException = JSWebAPIErrorFactory::makeErrorObject(data->getContext(), JSWebAPIErrorFactory::IO_ERROR, "IO error"); + } + data->callOnError(jsException); + } +} + +void ResponseDispatcher::OnAnswerReceived(const EventReadTextPtr& event) +{ + LoggerD("--| ENTER"); + DPL::SharedPtr<JSCallbackManager> data = + DPL::DynamicPointerCast<JSCallbackManager>(event->getPrivateData()); + + FilesystemAsyncCallbackManagerSingleton::Instance().unregisterCallbackManager(data); + + if (event->getExceptionCode() == WrtDeviceApis::Commons::ExceptionCodes::None) { + Converter converter(data->getContext()); + Try { + std::string resultText = event->getResult(); + std::string currentEncoding = event->getCharSet(); + std::string utf8OutStr = ""; + JSValueRef result; + + if (!strcmp(currentEncoding.c_str(), Encodings::UTF8) || !strcmp(currentEncoding.c_str(), Encodings::ISO88591)) + { + result = converter.toJSValueRef(resultText); + data->callOnSuccess(result); + } + else + { + Utils::toUTF8String(currentEncoding, resultText.c_str(), resultText.length(), utf8OutStr); + result = converter.toJSValueRef(utf8OutStr); + data->callOnSuccess(result); + } + } + Catch(WrtDeviceApis::Commons::ConversionException) { + data->callOnError(JSWebAPIErrorFactory::makeErrorObject( + data->getContext(), JSWebAPIErrorFactory::IO_ERROR, "IO error")); + } + } else { + JSObjectRef jsException = NULL; + if (event->getExceptionCode() == WrtDeviceApis::Commons::ExceptionCodes::SecurityException) { + jsException = JSWebAPIErrorFactory::makeErrorObject(data->getContext(), JSWebAPIErrorFactory::INVALID_VALUES_ERROR, "Permission denied error"); + } + else if (event->getExceptionCode() == WrtDeviceApis::Commons::ExceptionCodes::NotFoundException) { + jsException = JSWebAPIErrorFactory::makeErrorObject(data->getContext(), JSWebAPIErrorFactory::NOT_FOUND_ERROR, "NotFoundError"); + } + else { + jsException = JSWebAPIErrorFactory::makeErrorObject(data->getContext(), JSWebAPIErrorFactory::IO_ERROR, "IO error"); + } + data->callOnError(jsException); + } +} + +void ResponseDispatcher::OnAnswerReceived(const EventGetStoragePtr& event) +{ + DPL::SharedPtr<JSCallbackManager> data = DPL::DynamicPointerCast<JSCallbackManager>(event->getPrivateData()); + + FilesystemAsyncCallbackManagerSingleton::Instance().unregisterCallbackManager(data); + + if (event->getExceptionCode() == WrtDeviceApis::Commons::ExceptionCodes::None) { + Converter converter(data->getContext()); + Try { + JSValueRef result = converter.toJSValueRef(event->getResult(), data->getContext()); + data->callOnSuccess(result); + } Catch (WrtDeviceApis::Commons::ConversionException) { + data->callOnError(JSWebAPIErrorFactory::makeErrorObject(data->getContext(), JSWebAPIErrorFactory::IO_ERROR, "IO error")); + } + } else { + JSObjectRef jsException = NULL; + if (event->getExceptionCode() == WrtDeviceApis::Commons::ExceptionCodes::NotFoundException) { + jsException = JSWebAPIErrorFactory::makeErrorObject(data->getContext(), JSWebAPIErrorFactory::NOT_FOUND_ERROR, "Not found error"); + } + else { + jsException = JSWebAPIErrorFactory::makeErrorObject(data->getContext(), JSWebAPIErrorFactory::IO_ERROR, "IO error"); + } + data->callOnError(jsException); + } +} + +void ResponseDispatcher::OnAnswerReceived(const EventListStoragesPtr& event) +{ + DPL::SharedPtr<JSCallbackManager> data = DPL::DynamicPointerCast<JSCallbackManager>(event->getPrivateData()); + + FilesystemAsyncCallbackManagerSingleton::Instance().unregisterCallbackManager(data); + + if (event->getExceptionCode() == WrtDeviceApis::Commons::ExceptionCodes::None) { + Converter converter(data->getContext()); + Try { + JSValueRef result = converter.toJSValueRef(event->getResult(), data->getContext()); + data->callOnSuccess(result); + } Catch (WrtDeviceApis::Commons::ConversionException) { + data->callOnError(JSWebAPIErrorFactory::makeErrorObject(data->getContext(), JSWebAPIErrorFactory::IO_ERROR, "IO error")); + } + } else { + JSObjectRef jsException = NULL; + jsException = JSWebAPIErrorFactory::makeErrorObject(data->getContext(), JSWebAPIErrorFactory::IO_ERROR, "IO error"); + data->callOnError(jsException); + } +} + +} +} diff --git a/wearable_src/Filesystem/ResponseDispatcher.h b/wearable_src/Filesystem/ResponseDispatcher.h new file mode 100755 index 0000000..9a8f759 --- /dev/null +++ b/wearable_src/Filesystem/ResponseDispatcher.h @@ -0,0 +1,67 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 TIZENAPIS_TIZEN_RESPONSEDISPATCHER_H_ +#define TIZENAPIS_TIZEN_RESPONSEDISPATCHER_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <Commons/EventReceiver.h> +#include "EventResolve.h" +#include "EventGetStorage.h" +#include "EventListStorages.h" +#include "EventListNodes.h" +#include "EventOpen.h" +#include "EventCopy.h" +#include "EventMove.h" +#include "EventRemove.h" +#include "EventReadText.h" + +namespace DeviceAPI { +namespace Filesystem { +class ResponseDispatcher : + public WrtDeviceApis::Commons::EventAnswerReceiver<EventResolve>, + public WrtDeviceApis::Commons::EventAnswerReceiver<EventGetStorage>, + public WrtDeviceApis::Commons::EventAnswerReceiver<EventListStorages>, + public WrtDeviceApis::Commons::EventAnswerReceiver<EventListNodes>, + public WrtDeviceApis::Commons::EventAnswerReceiver<EventOpen>, + public WrtDeviceApis::Commons::EventAnswerReceiver<EventCopy>, + public WrtDeviceApis::Commons::EventAnswerReceiver<EventMove>, + public WrtDeviceApis::Commons::EventAnswerReceiver<EventRemove>, + public WrtDeviceApis::Commons::EventAnswerReceiver<EventReadText> +{ +public: + static ResponseDispatcher& getInstance(); + + void OnAnswerReceived(const EventResolvePtr& event); + void OnAnswerReceived(const EventGetStoragePtr& event); + void OnAnswerReceived(const EventListStoragesPtr& event); + void OnAnswerReceived(const EventListNodesPtr& event); + void OnAnswerReceived(const EventOpenPtr& event); + void OnAnswerReceived(const EventCopyPtr& event); + void OnAnswerReceived(const EventMovePtr& event); + void OnAnswerReceived(const EventRemovePtr& event); + void OnAnswerReceived(const EventReadTextPtr& event); + +protected: + ResponseDispatcher(); +}; +} +} + +#endif + diff --git a/wearable_src/Filesystem/StorageProperties.cpp b/wearable_src/Filesystem/StorageProperties.cpp new file mode 100755 index 0000000..22ec041 --- /dev/null +++ b/wearable_src/Filesystem/StorageProperties.cpp @@ -0,0 +1,82 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "StorageProperties.h" + +namespace DeviceAPI { +namespace Filesystem { +StorageProperties::StorageProperties() : + id(0), + label(""), + type(0), + state(0), + fullpath("") +{ +} + +void StorageProperties::setId (const int Id) +{ + id = Id; +} + +void StorageProperties::setLabel (const std::string &Label) +{ + label = Label; +} + +void StorageProperties::setType (const short Type) +{ + type = Type; +} + +void StorageProperties::setState (const short State) +{ + state = State; +} + +void StorageProperties::setFullPath (const std::string &FullPath) +{ + fullpath = FullPath; +} + +int StorageProperties::getId() const +{ + return id; +} + +std::string StorageProperties::getLabel() const +{ + return label; +} + +short StorageProperties::getType() const +{ + return type; +} + +short StorageProperties::getState() const +{ + return state; +} + +std::string StorageProperties::getFullPath() const +{ + return fullpath; +} +} // Filesystem +} // TizenApis diff --git a/wearable_src/Filesystem/StorageProperties.h b/wearable_src/Filesystem/StorageProperties.h new file mode 100755 index 0000000..28802f8 --- /dev/null +++ b/wearable_src/Filesystem/StorageProperties.h @@ -0,0 +1,70 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 TIZENAPIS_API_FILESYSTEM_STORAGE_PROPERTIES_H_ +#define TIZENAPIS_API_FILESYSTEM_STORAGE_PROPERTIES_H_ + +#include <dpl/shared_ptr.h> +#include <string> + +namespace DeviceAPI { +namespace Filesystem { +class StorageProperties; +typedef DPL::SharedPtr<StorageProperties> StoragePropertiesPtr; + +class StorageProperties +{ +private: + int id; + std::string label; + short type; + short state; + std::string fullpath; +public: + enum StorageType + { + TYPE_INTERNAL = 0, + TYPE_EXTERNAL, + }; + + enum StorageState + { + STATE_UNMOUNTABLE = -2, + STATE_REMOVED = -1, + STATE_MOUNTED = 0, + STATE_MOUNTED_READONLY = 1, + }; + + void setId (const int Id); + void setLabel (const std::string &Label); + void setType (const short Type); + void setState (const short State); + void setFullPath (const std::string &FullPath); + + int getId() const; + std::string getLabel() const; + short getType() const; + short getState() const; + std::string getFullPath() const; + + StorageProperties(); +}; +} // Filesystem +} // TizenApis + +#endif //TIZENAPIS_API_FILESYSTEM_STORAGE_PROPERTIES_H_
\ No newline at end of file diff --git a/wearable_src/Filesystem/StorageStaticController.cpp b/wearable_src/Filesystem/StorageStaticController.cpp new file mode 100644 index 0000000..b20ab82 --- /dev/null +++ b/wearable_src/Filesystem/StorageStaticController.cpp @@ -0,0 +1,65 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <JavaScriptCore/JavaScript.h> +#include <dpl/shared_ptr.h> +#include <CommonsJavaScript/PrivateObject.h> +#include <CommonsJavaScript/JSCallbackManager.h> +#include <CommonsJavaScript/Converter.h> +#include <Commons/IEvent.h> +#include <CommonsJavaScript/JSDOMExceptionFactory.h> +#include "EventStorageStateChanged.h" +#include "StorageStaticController.h" +#include "JSStorage.h" +#include "Converter.h" +#include <Logger.h> + +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace DeviceAPI { +namespace Filesystem { +StorageStaticController& StorageStaticController::getInstance() +{ + static StorageStaticController controller; + return controller; +} + +StorageStaticController::StorageStaticController() : + EventListener<EventStorageStateChanged>(ThreadEnum::NULL_THREAD) +{ +} + +void StorageStaticController::onAnswerReceived( + const EventStorageStateChangedPtr& event) +{ + JSCallbackManagerPtr callbackManager = + DPL::DynamicPointerCast<JSCallbackManager>(event->getPrivateData()); + + JSContextRef context = callbackManager->getContext(); + Converter converter(context); + try { + JSValueRef result = converter.toJSValueRef(event->getResult(), context); + callbackManager->callOnSuccess(result); + } catch(Commons::ConversionException) { + LoggerE("Conversion exception while processing EventStorageStateChanged"); + } +} + +} +}
\ No newline at end of file diff --git a/wearable_src/Filesystem/StorageStaticController.h b/wearable_src/Filesystem/StorageStaticController.h new file mode 100755 index 0000000..1ca5723 --- /dev/null +++ b/wearable_src/Filesystem/StorageStaticController.h @@ -0,0 +1,44 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 TIZENAPIS_TIZEN_FILESYSTEM_STORAGE_STATIC_CONTROLLER_H_ +#define TIZENAPIS_TIZEN_FILESYSTEM_STORAGE_STATIC_CONTROLLER_H_ + +#include <Commons/EventReceiver.h> +#include <Commons/EventListener.h> +#include "EventStorageStateChanged.h" + +namespace DeviceAPI { +namespace Filesystem { +class StorageStaticController : + public WrtDeviceApis::Commons::EventListener<EventStorageStateChanged> +{ +public: + static StorageStaticController& getInstance(); + + void onAnswerReceived( + const EventStorageStateChangedPtr& event); + +protected: + StorageStaticController(); +}; +} +} + +#endif + diff --git a/wearable_src/Filesystem/Stream.cpp b/wearable_src/Filesystem/Stream.cpp new file mode 100644 index 0000000..2660193 --- /dev/null +++ b/wearable_src/Filesystem/Stream.cpp @@ -0,0 +1,317 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "Stream.h" + +#include <stdio.h> +#include <new> +#include <dpl/scoped_array.h> + +#include <Commons/Exception.h> +#include "Manager.h" +#include "Node.h" +#include <Logger.h> + +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; + +namespace DeviceAPI { +namespace Filesystem { +Stream::Stream(const NodePtr& parent, + int mode) : + m_parent(parent), + m_mode(mode) +{ + + std::ios_base::openmode mode_ = std::ios_base::binary; + if (mode & AM_READ) { mode_ |= std::ios_base::in; } + if (mode & AM_WRITE) { mode_ |= std::ios_base::out; } + else if (mode & AM_APPEND) { + mode_ |= (std::ios_base::app | std::ios_base::out); + } + + m_stream.open(m_parent->getPath()->getFullPath().c_str(), mode_); + if (!m_stream) { + ThrowMsg(Commons::PlatformException, "Could not open stream."); + } +} + +Stream::~Stream() +{ + close(); +} + +IStreamPtr Stream::write(bool arg) +{ + return write_(arg); +} + +IStreamPtr Stream::write(unsigned char arg) +{ + return write_(arg); +} + +IStreamPtr Stream::write(char arg) +{ + return write_(arg); +} + +IStreamPtr Stream::write(int arg) +{ + return write_(arg); +} + +IStreamPtr Stream::write(double arg) +{ + return write_(arg); +} + +IStreamPtr Stream::write(const std::string& arg) +{ + return write_(arg); +} + +IStreamPtr Stream::read(bool& arg) +{ + return read_(arg); +} + +IStreamPtr Stream::read(unsigned char& arg) +{ + return read_(arg); +} + +IStreamPtr Stream::read(char& arg) +{ + return read_(arg); +} + +IStreamPtr Stream::read(int& arg) +{ + return read_(arg); +} + +IStreamPtr Stream::read(double& arg) +{ + return read_(arg); +} + +IStreamPtr Stream::read(std::string& arg) +{ + return read_(arg); +} + +void Stream::setCharSet(const std::string &charSet) +{ + m_charSet = charSet; +} + +std::string Stream::getCharSet() const +{ + return m_charSet; +} + +char* Stream::getChars(std::size_t num) +{ + checkForReading(); + + std::size_t maxChars = num + 1; + DPL::ScopedArray<char> result; + Try { + result.Reset(new char[maxChars]); + memset(result.Get(), 0, maxChars); + + } + Catch(std::bad_alloc) { + ThrowMsg(Commons::PlatformException, "Couldn't allocate output buffer."); + } +// if (m_stream.get(result.Get(), maxChars).bad()) { + m_stream.read(result.Get(), num); + + if (m_stream.bad()) { + ThrowMsg(Commons::PlatformException, + "Error while reading from the stream."); + } + + return result.Release(); +} + +unsigned char* Stream::getBytes(std::size_t num) +{ + checkForReading(); + + DPL::ScopedArray<char> buffer; + Try { + buffer.Reset(new char[num]); + } + Catch(std::bad_alloc) { + ThrowMsg(Commons::PlatformException, "Couldn't allocate output buffer."); + } + if (m_stream.read(buffer.Get(), num).bad()) { + ThrowMsg(Commons::PlatformException, + "Error while reading from the stream."); + } + + return static_cast<unsigned char*>(static_cast<void*>(buffer.Release())); +} + +std::size_t Stream::getCount() const +{ + if (!isOpen()) { + ThrowMsg(Commons::PlatformException, "Stream is closed."); + } + + if (!isReadable()) { + ThrowMsg(Commons::PlatformException, "Stream is not readable."); + } + + return m_stream.gcount(); +} + +std::string Stream::getLine() +{ + checkForReading(); + + std::string result; + std::getline(m_stream, result); + + return result; +} + +bool Stream::isOpen() const +{ + return m_stream.is_open(); +} + +bool Stream::isEof() const +{ + return m_stream.eof(); +} + +void Stream::close() +{ + if (isOpen()) { + m_stream.close(); + m_parent->onStreamClose(SharedFromThis()); + } +} + +int Stream::getMode() const +{ + return m_mode; +} + +long Stream::getPosition() const +{ + return static_cast<long>(m_stream.tellg()); +} + +void Stream::setPosition(long position) +{ + if (m_stream.rdstate() & std::ios_base::eofbit) { + m_stream.clear(); + } + if (!(m_stream.seekg(position)) || !(m_stream.seekp(position))) { + ThrowMsg(PlatformException, "Could not set position."); + } +} + +unsigned long long Stream::getSize() const +{ + std::fstream::streampos pos = m_stream.tellg(); + if (pos == -1) { + return 0; + } + + if (!m_stream.seekg(0, std::_S_end)) { + return 0; + } + + unsigned long long result = m_stream.tellg(); + m_stream.seekg(pos, std::_S_beg); + + return result + 1; +} + +template<typename T> +IStreamPtr Stream::write_(T arg) +{ + checkForWriting(); + + if (!(m_stream << arg)) { + LoggerE("Error while writing to the stream."); + ThrowMsg(Commons::PlatformException, + "Error while writing to the stream."); + } + m_stream.flush(); + + return DPL::StaticPointerCast<IStream>(SharedFromThis()); +} + +template<typename T> +IStreamPtr Stream::read_(T& arg) +{ + checkForReading(); + + if (!(m_stream >> arg)) { + ThrowMsg(Commons::PlatformException, + "Error while reading from the stream."); + } + + return DPL::StaticPointerCast<IStream>(SharedFromThis()); +} + +bool Stream::isReadable() const +{ + return (m_mode & AM_READ); +} + +bool Stream::isWriteable() const +{ + return ((m_mode & AM_WRITE) || (m_mode & AM_APPEND)); +} + +void Stream::checkForReading() const +{ + if (!isOpen()) { + ThrowMsg(Commons::PlatformException, "Stream is closed."); + } + + if (isEof()) { + ThrowMsg(Commons::PlatformException, "Stream is marked as EOF."); + } + + if (!isReadable()) { + ThrowMsg(Commons::PlatformException, "Stream is not readable."); + } +} + +void Stream::checkForWriting() const +{ + if (!isOpen()) { + LoggerE("Stream is closed."); + ThrowMsg(Commons::PlatformException, "Stream is closed."); + } + + if (!isWriteable()) { + LoggerE("Stream is not writeable."); + ThrowMsg(Commons::PlatformException, "Stream is not writeable."); + } +} +} // Filesystem +} // TizenApis
\ No newline at end of file diff --git a/wearable_src/Filesystem/Stream.h b/wearable_src/Filesystem/Stream.h new file mode 100755 index 0000000..7c40f07 --- /dev/null +++ b/wearable_src/Filesystem/Stream.h @@ -0,0 +1,107 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 TIZENAPIS_FILESYSTEM_STREAM_H_ +#define TIZENAPIS_FILESYSTEM_STREAM_H_ + +#include <cstddef> +#include <fstream> +#include <dpl/shared_ptr.h> +#include <dpl/enable_shared_from_this.h> +#include "IStream.h" +#include "Enums.h" +#include "INode.h" + +namespace DeviceAPI { +namespace Filesystem { +class Node; +typedef DPL::SharedPtr<Node> NodePtr; + +class Stream : public IStream, + public DPL::EnableSharedFromThis<Stream> +{ + friend class Node; + + public: + ~Stream(); + + IStreamPtr write(bool arg); + IStreamPtr write(unsigned char arg); + IStreamPtr write(char arg); + IStreamPtr write(int arg); + IStreamPtr write(double arg); + IStreamPtr write(const std::string& arg); + + IStreamPtr read(bool& arg); + IStreamPtr read(unsigned char& arg); + IStreamPtr read(char& arg); + IStreamPtr read(int& arg); + IStreamPtr read(double& arg); + IStreamPtr read(std::string& arg); + + void setCharSet(const std::string &charSet); + std::string getCharSet() const; + + unsigned char* getBytes(std::size_t num); + + std::size_t getCount() const; + + char* getChars(std::size_t num); + + std::string getLine(); + + bool isOpen() const; + bool isEof() const; + + void close(); + + long getPosition() const; + void setPosition(long position); + + int getMode() const; + + unsigned long long getSize() const; + + private: + template<typename T> + IStreamPtr read_(T& arg); + template<typename T> + IStreamPtr write_(T arg); + + inline bool isReadable() const; + inline bool isWriteable() const; + void checkForReading() const; + void checkForWriting() const; + + private: + Stream(const NodePtr& parent, + int mode); + + private: + NodePtr m_parent; + int m_mode; + mutable std::fstream m_stream; + std::string m_charSet; + +}; + +typedef DPL::SharedPtr<Stream> StreamPtr; +} // Filesystem +} // TizenApis + +#endif /* TIZENAPIS_FILESYSTEM_STREAM_H_ */ diff --git a/wearable_src/Filesystem/Utils.cpp b/wearable_src/Filesystem/Utils.cpp new file mode 100755 index 0000000..1268dab --- /dev/null +++ b/wearable_src/Filesystem/Utils.cpp @@ -0,0 +1,101 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <sys/stat.h> +#include <cerrno> +#include <cstring> +#include <cstdlib> +#include <unistd.h> + +#include <Commons/Exception.h> +#include "Utils.h" + +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; + +namespace { +int try_mkdir(const char* path, + mode_t mode) +{ + struct stat st; + int err = 0; + + if (::stat(path, &st) != 0) { + if (::mkdir(path, mode) != 0) { + err = -1; + } + } else if (!S_ISDIR(st.st_mode)) { + errno = ENOTDIR; + err = -1; + } + + return err; +} + +int mkpath(const char* path, + mode_t mode) +{ + char* copy = ::strdup(path); + if (NULL == copy) { + return -1; + } + + int err = 0; + char* ptr = copy; + char* slash = NULL; + + while ((0 == err) && (NULL != (slash = ::strchr(ptr, '/')))) { + if (slash != ptr) { + *slash = '\0'; + err = try_mkdir(copy, mode); + *slash = '/'; + } + ptr = slash + 1; + } + + if (0 == err) { + err = try_mkdir(path, mode); + } + + ::free(copy); + return err; +} +} + +namespace DeviceAPI { +namespace Filesystem { +bool nodeExists(const std::string& path) +{ + struct stat info; + if (stat(path.c_str(), &info) == 0) { + if (S_ISDIR(info.st_mode)) { + return true; + } + } + return false; +} + +void makePath(const std::string& path, + mode_t mode) +{ + if (mkpath(path.c_str(), mode) == -1) { + ThrowMsg(Commons::PlatformException, "Couldn't create path: " << path); + } +} +} +} diff --git a/wearable_src/Filesystem/Utils.h b/wearable_src/Filesystem/Utils.h new file mode 100755 index 0000000..0f2dd18 --- /dev/null +++ b/wearable_src/Filesystem/Utils.h @@ -0,0 +1,34 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 TIZENAPIS_FILESYSTEM_UTILS_H_ +#define TIZENAPIS_FILESYSTEM_UTILS_H_ + +#include <sys/types.h> +#include <string> + +namespace DeviceAPI { +namespace Filesystem { +bool nodeExists(const std::string& path); + +void makePath(const std::string& path, + mode_t mode); +} +} + +#endif diff --git a/wearable_src/Filesystem/config.xml b/wearable_src/Filesystem/config.xml new file mode 100755 index 0000000..42c4ef2 --- /dev/null +++ b/wearable_src/Filesystem/config.xml @@ -0,0 +1,17 @@ +<?xml version="1.0" ?> +<!DOCTYPE plugin-properties SYSTEM "/usr/etc/tizen-apis/config.dtd"> +<plugin-properties> + <library-name>libwrt-plugins-tizen-filesystem.so</library-name> + <feature-install-uri>filesystem.install.uri</feature-install-uri> + + <api-feature> + <name>http://tizen.org/privilege/filesystem.read</name> + <device-capability>filesystem.read</device-capability> + </api-feature> + + <api-feature> + <name>http://tizen.org/privilege/filesystem.write</name> + <device-capability>filesystem.write</device-capability> + </api-feature> + +</plugin-properties> diff --git a/wearable_src/Filesystem/plugin_config.cpp b/wearable_src/Filesystem/plugin_config.cpp new file mode 100755 index 0000000..e0ca0b2 --- /dev/null +++ b/wearable_src/Filesystem/plugin_config.cpp @@ -0,0 +1,436 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <map> +#include <utility> + +#include <Commons/FunctionDefinition.h> +#include <Commons/FunctionDeclaration.h> +#include <Commons/Exception.h> +#include "Enums.h" + +#define FILESYSTEM_FEATURE_API_READ "http://tizen.org/privilege/filesystem.read" +#define FILESYSTEM_FEATURE_API_WRITE "http://tizen.org/privilege/filesystem.write" + +namespace DeviceAPI { +namespace Filesystem { + +#pragma GCC visibility push(default) + +const char* FILESYSTEM_PARAM_LOCATION = "param:location"; +const char* FILESYSTEM_DEVICE_CAP_READ = "filesystem.read"; +const char* FILESYSTEM_DEVICE_CAP_WRITE = "filesystem.write"; + +const char* FILESYSTEM_FUNCTION_API_MGR_RESOLVE_ID = "manager_resolve"; +const char* FILESYSTEM_FUNCTION_API_MGR_RESOLVE = "resolve"; + +const char* FILESYSTEM_FUNCTION_API_GET_STORAGE = "getStorage"; +const char* FILESYSTEM_FUNCTION_API_LIST_STORAGE = "listStorage"; +const char* FILESYSTEM_FUNCTION_API_ADD_STORAGE_LISTENER = "addStorageStateChangeListener"; +const char* FILESYSTEM_FUNCTION_API_REMOVE_STORAGE_LISTENER = "removeStorageStateChangeListener"; + +const char* FILESYSTEM_FUNCTION_API_RESOLVE = "resolve"; +const char* FILESYSTEM_FUNCTION_API_TO_URI = "toURI"; +const char* FILESYSTEM_FUNCTION_API_LIST_FILES = "listFiles"; +const char* FILESYSTEM_FUNCTION_API_OPEN_STREAM = "openStream"; +const char* FILESYSTEM_FUNCTION_API_READ_AS_TEXT = "readAsText"; +const char* FILESYSTEM_FUNCTION_API_COPY_TO = "copyTo"; +const char* FILESYSTEM_FUNCTION_API_MOVE_TO = "moveTo"; +const char* FILESYSTEM_FUNCTION_API_CREATE_DIR = "createDirectory"; +const char* FILESYSTEM_FUNCTION_API_CREATE_FILE = "createFile"; +const char* FILESYSTEM_FUNCTION_API_DELETE_DIR = "deleteDirectory"; +const char* FILESYSTEM_FUNCTION_API_DELETE_FILE = "deleteFile"; + +const char* FILESYSTEM_FUNCTION_API_CLOSE = "close"; +const char* FILESYSTEM_FUNCTION_API_READ = "read"; +const char* FILESYSTEM_FUNCTION_API_READ_BYTES = "readBytes"; +const char* FILESYSTEM_FUNCTION_API_READ_BASE64 = "readBase64"; +const char* FILESYSTEM_FUNCTION_API_WRITE = "write"; +const char* FILESYSTEM_FUNCTION_API_WRITE_BYTES = "writeBytes"; +const char* FILESYSTEM_FUNCTION_API_WRITE_BASE64 = "writeBase64"; + +static WrtDeviceApis::Commons::FunctionMapping createFilesystemFunctions(); + +static WrtDeviceApis::Commons::FunctionMapping FilesystemFunctions = + createFilesystemFunctions(); + +DEFINE_FUNCTION_GETTER(Filesystem, FilesystemFunctions); + +static WrtDeviceApis::Commons::FunctionMapping createFilesystemFunctions() +{ + using namespace WrtDeviceApis::Commons; + + /** + * Device capabilities + */ + + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_FILESYSTEM_READ, + FILESYSTEM_DEVICE_CAP_READ); + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_FILESYSTEM_WRITE, + FILESYSTEM_DEVICE_CAP_WRITE); + + ACE_CREATE_DEVICE_CAPS_LIST(EMPTY_DEVICE_LIST); + + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_FILESYSTEM_READ); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_FILESYSTEM_READ, DEVICE_CAP_FILESYSTEM_READ); + + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_FILESYSTEM_WRITE); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_FILESYSTEM_WRITE, + DEVICE_CAP_FILESYSTEM_WRITE); + + /** + * Api Features + */ + ACE_CREATE_FEATURE(FEATURE_READ, FILESYSTEM_FEATURE_API_READ); + ACE_CREATE_FEATURE(FEATURE_WRITE, FILESYSTEM_FEATURE_API_WRITE); + + ACE_CREATE_FEATURE_LIST(FILESYSTEM_FEATURES_FILESYSTEM_READ); + + ACE_ADD_API_FEATURE(FILESYSTEM_FEATURES_FILESYSTEM_READ, + FEATURE_READ); + + ACE_CREATE_FEATURE_LIST(FILESYSTEM_FEATURES_FILESYSTEM_WRITE); + + ACE_ADD_API_FEATURE(FILESYSTEM_FEATURES_FILESYSTEM_WRITE, + FEATURE_WRITE); + + /** + * Functions + */ + + FunctionMapping FilesystemMapping; + + AceFunction mgrResolveFunc = ACE_CREATE_FUNCTION( + FUNCTION_MGR_RESOLVE, + FILESYSTEM_FUNCTION_API_MGR_RESOLVE, + FILESYSTEM_FEATURES_FILESYSTEM_READ, + EMPTY_DEVICE_LIST); // check of device-cap will be done inside resolve() + + FilesystemMapping.insert(std::make_pair( + FILESYSTEM_FUNCTION_API_MGR_RESOLVE_ID, + mgrResolveFunc)); + + AceFunction getStorageFunc = ACE_CREATE_FUNCTION( + FUNCTION_GET_STORAGE, + FILESYSTEM_FUNCTION_API_GET_STORAGE, + FILESYSTEM_FEATURES_FILESYSTEM_READ, + EMPTY_DEVICE_LIST); + + FilesystemMapping.insert(std::make_pair( + FILESYSTEM_FUNCTION_API_GET_STORAGE, + getStorageFunc)); + + AceFunction listStorageFunc = ACE_CREATE_FUNCTION( + FUNCTION_LIST_STORAGE, + FILESYSTEM_FUNCTION_API_LIST_STORAGE, + FILESYSTEM_FEATURES_FILESYSTEM_READ, + EMPTY_DEVICE_LIST); + + FilesystemMapping.insert(std::make_pair( + FILESYSTEM_FUNCTION_API_LIST_STORAGE, + listStorageFunc)); + + AceFunction addStorageListenerFunc = ACE_CREATE_FUNCTION( + FUNCTION_ADD_STORAGE_LISTENER, + FILESYSTEM_FUNCTION_API_ADD_STORAGE_LISTENER, + FILESYSTEM_FEATURES_FILESYSTEM_WRITE, + EMPTY_DEVICE_LIST); + + FilesystemMapping.insert(std::make_pair( + FILESYSTEM_FUNCTION_API_ADD_STORAGE_LISTENER, + addStorageListenerFunc)); + + AceFunction removeStorageListenerFunc = ACE_CREATE_FUNCTION( + FUNCTION_REMOVE_STORAGE_LISTENER, + FILESYSTEM_FUNCTION_API_REMOVE_STORAGE_LISTENER, + FILESYSTEM_FEATURES_FILESYSTEM_WRITE, + EMPTY_DEVICE_LIST); + + FilesystemMapping.insert(std::make_pair( + FILESYSTEM_FUNCTION_API_REMOVE_STORAGE_LISTENER, + removeStorageListenerFunc)); + + AceFunction resolveFunc = ACE_CREATE_FUNCTION( + FUNCTION_RESOLVE, + FILESYSTEM_FUNCTION_API_RESOLVE, + FILESYSTEM_FEATURES_FILESYSTEM_READ, + EMPTY_DEVICE_LIST); + + FilesystemMapping.insert(std::make_pair( + FILESYSTEM_FUNCTION_API_RESOLVE, + resolveFunc)); + + AceFunction toUriFunc = ACE_CREATE_FUNCTION( + FUNCTION_TO_URI, + FILESYSTEM_FUNCTION_API_TO_URI, + FILESYSTEM_FEATURES_FILESYSTEM_READ, + EMPTY_DEVICE_LIST); + + FilesystemMapping.insert(std::make_pair( + FILESYSTEM_FUNCTION_API_TO_URI, + toUriFunc)); + + AceFunction listFilesFunc = ACE_CREATE_FUNCTION( + FUNCTION_LIST_FILES, + FILESYSTEM_FUNCTION_API_LIST_FILES, + FILESYSTEM_FEATURES_FILESYSTEM_READ, + EMPTY_DEVICE_LIST); + + FilesystemMapping.insert(std::make_pair( + FILESYSTEM_FUNCTION_API_LIST_FILES, + listFilesFunc)); + + AceFunction openStreamFunc = ACE_CREATE_FUNCTION( + FUNCTION_OPEN_STREAM, + FILESYSTEM_FUNCTION_API_OPEN_STREAM, + FILESYSTEM_FEATURES_FILESYSTEM_READ, + EMPTY_DEVICE_LIST); + + FilesystemMapping.insert(std::make_pair( + FILESYSTEM_FUNCTION_API_OPEN_STREAM, + openStreamFunc)); + + AceFunction readAsTextFunc = ACE_CREATE_FUNCTION( + FUNCTION_READ_AS_TEXT, + FILESYSTEM_FUNCTION_API_READ_AS_TEXT, + FILESYSTEM_FEATURES_FILESYSTEM_READ, + EMPTY_DEVICE_LIST); + + FilesystemMapping.insert(std::make_pair( + FILESYSTEM_FUNCTION_API_READ_AS_TEXT, + readAsTextFunc)); + + + + + AceFunction copyToFunc = ACE_CREATE_FUNCTION( + FUNCTION_COPY_TO, + FILESYSTEM_FUNCTION_API_COPY_TO, + FILESYSTEM_FEATURES_FILESYSTEM_WRITE, + EMPTY_DEVICE_LIST); + + FilesystemMapping.insert(std::make_pair( + FILESYSTEM_FUNCTION_API_COPY_TO, + copyToFunc)); + + AceFunction moveToFunc = ACE_CREATE_FUNCTION( + FUNCTION_MOVE_TO, + FILESYSTEM_FUNCTION_API_MOVE_TO, + FILESYSTEM_FEATURES_FILESYSTEM_WRITE, + EMPTY_DEVICE_LIST); + + FilesystemMapping.insert(std::make_pair( + FILESYSTEM_FUNCTION_API_MOVE_TO, + moveToFunc)); + + AceFunction createDirFunc = ACE_CREATE_FUNCTION( + FUNCTION_CREATE_DIR, + FILESYSTEM_FUNCTION_API_CREATE_DIR, + FILESYSTEM_FEATURES_FILESYSTEM_WRITE, + EMPTY_DEVICE_LIST); + + FilesystemMapping.insert(std::make_pair( + FILESYSTEM_FUNCTION_API_CREATE_DIR, + createDirFunc)); + + AceFunction createFileFunc = ACE_CREATE_FUNCTION( + FUNCTION_CREATE_FILE, + FILESYSTEM_FUNCTION_API_CREATE_FILE, + FILESYSTEM_FEATURES_FILESYSTEM_WRITE, + EMPTY_DEVICE_LIST); + + FilesystemMapping.insert(std::make_pair( + FILESYSTEM_FUNCTION_API_CREATE_FILE, + createFileFunc)); + + AceFunction deleteDirFunc = ACE_CREATE_FUNCTION( + FUNCTION_DELETE_DIR, + FILESYSTEM_FUNCTION_API_DELETE_DIR, + FILESYSTEM_FEATURES_FILESYSTEM_WRITE, + EMPTY_DEVICE_LIST); + + FilesystemMapping.insert(std::make_pair( + FILESYSTEM_FUNCTION_API_DELETE_DIR, + deleteDirFunc)); + + AceFunction deleteFileFunc = ACE_CREATE_FUNCTION( + FUNCTION_DELETE_FILE, + FILESYSTEM_FUNCTION_API_DELETE_FILE, + FILESYSTEM_FEATURES_FILESYSTEM_WRITE, + EMPTY_DEVICE_LIST); + + FilesystemMapping.insert(std::make_pair( + FILESYSTEM_FUNCTION_API_DELETE_FILE, + deleteFileFunc)); + + AceFunction closeFunc = ACE_CREATE_FUNCTION( + FUNCTION_CLOSE, + FILESYSTEM_FUNCTION_API_CLOSE, + FILESYSTEM_FEATURES_FILESYSTEM_READ, + EMPTY_DEVICE_LIST); + + FilesystemMapping.insert(std::make_pair( + FILESYSTEM_FUNCTION_API_CLOSE, + closeFunc)); + + AceFunction readFunc = ACE_CREATE_FUNCTION( + FUNCTION_READ, + FILESYSTEM_FUNCTION_API_READ, + FILESYSTEM_FEATURES_FILESYSTEM_READ, + EMPTY_DEVICE_LIST); + + FilesystemMapping.insert(std::make_pair( + FILESYSTEM_FUNCTION_API_READ, + readFunc)); + + AceFunction readBytesFunc = ACE_CREATE_FUNCTION( + FUNCTION_READ_BYTES, + FILESYSTEM_FUNCTION_API_READ_BYTES, + FILESYSTEM_FEATURES_FILESYSTEM_READ, + EMPTY_DEVICE_LIST); + + FilesystemMapping.insert(std::make_pair( + FILESYSTEM_FUNCTION_API_READ_BYTES, + readBytesFunc)); + + AceFunction readBase64Func = ACE_CREATE_FUNCTION( + FUNCTION_READ_BASE64, + FILESYSTEM_FUNCTION_API_READ_BASE64, + FILESYSTEM_FEATURES_FILESYSTEM_READ, + EMPTY_DEVICE_LIST); + + FilesystemMapping.insert(std::make_pair( + FILESYSTEM_FUNCTION_API_READ_BASE64, + readBase64Func)); + + AceFunction writeFunc = ACE_CREATE_FUNCTION( + FUNCTION_WRITE, + FILESYSTEM_FUNCTION_API_WRITE, + FILESYSTEM_FEATURES_FILESYSTEM_WRITE, + EMPTY_DEVICE_LIST); + + FilesystemMapping.insert(std::make_pair( + FILESYSTEM_FUNCTION_API_WRITE, + writeFunc)); + + AceFunction writeBytesFunc = ACE_CREATE_FUNCTION( + FUNCTION_WRITE_BYTES, + FILESYSTEM_FUNCTION_API_WRITE_BYTES, + FILESYSTEM_FEATURES_FILESYSTEM_WRITE, + EMPTY_DEVICE_LIST); + + FilesystemMapping.insert(std::make_pair( + FILESYSTEM_FUNCTION_API_WRITE_BYTES, + writeBytesFunc)); + + AceFunction writeBase64Func = ACE_CREATE_FUNCTION( + FUNCTION_WRITE_BASE64, + FILESYSTEM_FUNCTION_API_WRITE_BASE64, + FILESYSTEM_FEATURES_FILESYSTEM_WRITE, + EMPTY_DEVICE_LIST); + + FilesystemMapping.insert(std::make_pair( + FILESYSTEM_FUNCTION_API_WRITE_BASE64, + writeBase64Func)); + + return FilesystemMapping; +} + +void setFilesystemPermDevCaps(int permissions, + const std::string& path, + WrtDeviceApis::Commons::AceFunction* outFunction) +{ + using namespace WrtDeviceApis::Commons; + AceDeviceCapParam paramLocation = AceDeviceCapParam( + FILESYSTEM_PARAM_LOCATION, path); + + AceDeviceCaps devCaps; + + if (permissions & Filesystem::PERM_READ) { + AceDeviceCapability devCapRead = AceDeviceCapability( + FILESYSTEM_DEVICE_CAP_READ, + AceDeviceCapParams()); + devCaps.push_back(devCapRead); + + ACE_ADD_DEV_CAP_PARAM( + devCaps, + FILESYSTEM_DEVICE_CAP_READ, + paramLocation); + } + + if (permissions & Filesystem::PERM_WRITE) { + AceDeviceCapability devCapWrite = AceDeviceCapability( + FILESYSTEM_DEVICE_CAP_WRITE, + AceDeviceCapParams()); + + devCaps.push_back(devCapWrite); + + ACE_ADD_DEV_CAP_PARAM( + devCaps, + FILESYSTEM_DEVICE_CAP_WRITE, + paramLocation); + } + + outFunction->deviceCapabilities = devCaps; +} + +void setFilesystemAccessModeDevCaps(int accessMode, + const std::string& path, + WrtDeviceApis::Commons::AceFunction + *outFunction) +{ + using namespace WrtDeviceApis::Commons; + + AceDeviceCapParam paramLocation = AceDeviceCapParam( + FILESYSTEM_PARAM_LOCATION, + path); + AceDeviceCaps devCaps; + + if (accessMode & Filesystem::AM_READ) { + AceDeviceCapability devCapRead = AceDeviceCapability( + FILESYSTEM_DEVICE_CAP_READ, + AceDeviceCapParams()); + + devCaps.push_back(devCapRead); + + ACE_ADD_DEV_CAP_PARAM( + devCaps, + FILESYSTEM_DEVICE_CAP_READ, + paramLocation); + } + + if ((accessMode & Filesystem::AM_WRITE) || + (accessMode & Filesystem::AM_APPEND)) { + AceDeviceCapability devCapWrite = AceDeviceCapability( + FILESYSTEM_DEVICE_CAP_WRITE, + AceDeviceCapParams()); + + devCaps.push_back(devCapWrite); + + ACE_ADD_DEV_CAP_PARAM( + devCaps, + FILESYSTEM_DEVICE_CAP_WRITE, + paramLocation); + } + outFunction->deviceCapabilities = devCaps; +} + +#pragma GCC visibility pop + +} +} diff --git a/wearable_src/Filesystem/plugin_config.h b/wearable_src/Filesystem/plugin_config.h new file mode 100755 index 0000000..756ab0a --- /dev/null +++ b/wearable_src/Filesystem/plugin_config.h @@ -0,0 +1,150 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _FILESYSTEM_PLUGIN_CONFIG_H_ +#define _FILESYSTEM_PLUGIN_CONFIG_H_ + +#include <Commons/FunctionDeclaration.h> + +namespace DeviceAPI { +namespace Filesystem { + +extern const char* FILESYSTEM_FUNCTION_API_MGR_RESOLVE_ID; +extern const char* FILESYSTEM_FUNCTION_API_GET_STORAGE; +extern const char* FILESYSTEM_FUNCTION_API_LIST_STORAGE; +extern const char* FILESYSTEM_FUNCTION_API_ADD_STORAGE_LISTENER; +extern const char* FILESYSTEM_FUNCTION_API_REMOVE_STORAGE_LISTENER; + +extern const char* FILESYSTEM_FUNCTION_API_RESOLVE; +extern const char* FILESYSTEM_FUNCTION_API_TO_URI; +extern const char* FILESYSTEM_FUNCTION_API_LIST_FILES; +extern const char* FILESYSTEM_FUNCTION_API_OPEN_STREAM; +extern const char* FILESYSTEM_FUNCTION_API_READ_AS_TEXT; +extern const char* FILESYSTEM_FUNCTION_API_COPY_TO; +extern const char* FILESYSTEM_FUNCTION_API_MOVE_TO; +extern const char* FILESYSTEM_FUNCTION_API_CREATE_DIR; +extern const char* FILESYSTEM_FUNCTION_API_CREATE_FILE; +extern const char* FILESYSTEM_FUNCTION_API_DELETE_DIR; +extern const char* FILESYSTEM_FUNCTION_API_DELETE_FILE; + +extern const char* FILESYSTEM_FUNCTION_API_CLOSE; +extern const char* FILESYSTEM_FUNCTION_API_READ; +extern const char* FILESYSTEM_FUNCTION_API_READ_BYTES; +extern const char* FILESYSTEM_FUNCTION_API_READ_BASE64; +extern const char* FILESYSTEM_FUNCTION_API_WRITE; +extern const char* FILESYSTEM_FUNCTION_API_WRITE_BYTES; +extern const char* FILESYSTEM_FUNCTION_API_WRITE_BASE64; + +DECLARE_FUNCTION_GETTER(Filesystem); + +void setFilesystemPermDevCaps(int permissions, + const std::string& path, + WrtDeviceApis::Commons::AceFunction* outFunction); + +void setFilesystemAccessModeDevCaps(int accessMode, + const std::string& path, + WrtDeviceApis::Commons::AceFunction* + outFunction); + +struct PermissionsAccessInfo +{ + PermissionsAccessInfo(int perms, + const std::string& fpath) : + permissions(perms), + path(fpath) + { + } + + int permissions; + const std::string path; +}; + +struct AccessModeInfo +{ + AccessModeInfo(int amode, + const std::string& fpath) : + accessMode(amode), + path(fpath) + { + } + + int accessMode; + const std::string path; +}; + +} +} + +namespace WrtDeviceApis { +namespace Commons { + +/** + * template specialization for security access basing on permissions + */ +template <> +class DefaultArgsVerifier <DeviceAPI::Filesystem::PermissionsAccessInfo> +{ + public: + void operator()(AceFunction& aceFunction, + const DeviceAPI::Filesystem::PermissionsAccessInfo& permInfo) const + { + DeviceAPI::Filesystem::setFilesystemPermDevCaps(permInfo.permissions, + permInfo.path, + &aceFunction); + } +}; + +/** + * template specialization for security access basing on access mode + */ +template <> +class DefaultArgsVerifier <DeviceAPI::Filesystem::AccessModeInfo> +{ + public: + void operator()(AceFunction& aceFunction, + const DeviceAPI::Filesystem::AccessModeInfo& accessInfo) const + { + DeviceAPI::Filesystem::setFilesystemAccessModeDevCaps(accessInfo.accessMode, + accessInfo.path, + &aceFunction); + } +}; + +#define FILESYSTEM_CHECK_ACCESS(functionName) \ + WrtDeviceApis::Commons::aceCheckAccess<AceFunctionGetter, \ + WrtDeviceApis::Commons::DefaultArgsVerifier<> >( \ + getFilesystemFunctionData, \ + functionName) + +#define FILESYSTEM_PERMISSION_CHECK_ACCESS(functionName, perm) \ + WrtDeviceApis::Commons::aceCheckAccess<AceFunctionGetter, \ + WrtDeviceApis::Commons::DefaultArgsVerifier <DeviceAPI::Filesystem::PermissionsAccessInfo> >( \ + getFilesystemFunctionData, \ + functionName, \ + perm) + +#define FILESYSTEM_ACCESSMODE_CHECK_ACCESS(functionName, amode) \ + WrtDeviceApis::Commons::aceCheckAccess<AceFunctionGetter, \ + WrtDeviceApis::Commons::DefaultArgsVerifier <DeviceAPI::Filesystem::AccessModeInfo> >( \ + getFilesystemFunctionData, \ + functionName, \ + amode) +} +} + +#endif diff --git a/wearable_src/Filesystem/plugin_initializer.cpp b/wearable_src/Filesystem/plugin_initializer.cpp new file mode 100644 index 0000000..16b2b46 --- /dev/null +++ b/wearable_src/Filesystem/plugin_initializer.cpp @@ -0,0 +1,84 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <Commons/WrtAccess/WrtAccess.h> +#include <Commons/plugin_initializer_def.h> +#include <TimeTracer.h> +#include "JSFilesystemManager.h" +#include "JSFile.h" +#include "JSFilestream.h" +#include "FilesystemAsyncCallbackManager.h" +#include "FilesystemListenerManager.h" +#include <Logger.h> + +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; + +namespace DeviceAPI { +namespace Filesystem { + +void on_widget_start_callback(int widgetId) +{ + TIME_TRACER_INIT(); + Try { + WrtAccessSingleton::Instance().initialize(widgetId); + } Catch (Commons::Exception) { + LoggerE("WrtAccess initialization failed"); + } +} + +void on_widget_stop_callback(int widgetId) +{ + TIME_TRACER_EXPORT_REPORT_TO(TIME_TRACER_EXPORT_FILE,"FileSystem"); + TIME_TRACER_RELEASE(); + Try { + WrtAccessSingleton::Instance().deinitialize(widgetId); + } Catch (Commons::Exception) { + LoggerE("WrtAccess deinitialization failed"); + } +} + +void on_frame_unload_callback(const void * context) +{ + LoggerD("[Tizen\\filesystem] on_frame_unload_callback (" << context << ")"); + DeviceAPI::Filesystem::FilesystemAsyncCallbackManagerSingleton::Instance().unregisterContext(static_cast<JSContextRef>(context)); + DeviceAPI::Filesystem::FilesystemListenerManagerSingleton::Instance().unregisterContext(static_cast<JSContextRef>(context)); +} + +void on_frame_load_callback(const void * context) +{ + LoggerD("[Tizen\\filesystem] on_frame_load_callback (" << context << ")"); +} + +PLUGIN_ON_WIDGET_START(on_widget_start_callback) +PLUGIN_ON_WIDGET_STOP(on_widget_stop_callback) +PLUGIN_ON_FRAME_LOAD(on_frame_load_callback) +PLUGIN_ON_FRAME_UNLOAD(on_frame_unload_callback) + +#define FILESYSTEM ".filesystem" + +PLUGIN_CLASS_MAP_BEGIN +PLUGIN_CLASS_MAP_ADD_CLASS(WRT_JS_EXTENSION_OBJECT_TIZEN, + "filesystem", + (js_class_template_getter)DeviceAPI::Filesystem::JSFilesystemManager::getClassRef, + NULL) +PLUGIN_CLASS_MAP_END + +#undef FILESYSTEM + +} // Filesystem +} // DeviceAPI diff --git a/wearable_src/HumanActivityMonitor/CMakeLists.txt b/wearable_src/HumanActivityMonitor/CMakeLists.txt new file mode 100755 index 0000000..cf3f1e3 --- /dev/null +++ b/wearable_src/HumanActivityMonitor/CMakeLists.txt @@ -0,0 +1,54 @@ +SET(TARGET_NAME ${humanactivitymonitor_target}) +SET(DESTINATION_NAME ${humanactivitymonitor_dest}) +SET(TARGET_IMPL_NAME ${humanactivitymonitor_impl}) + +pkg_check_modules(platform_pkgs_humanactivitymonitor REQUIRED + glib-2.0 + capi-context-manager + capi-system-info +) + +INCLUDE_DIRECTORIES( + ${INCLUDE_COMMON} + ${TOP}/HumanActivityMonitor + ${platform_pkgs_humanactivitymonitor_INCLUDE_DIRS} +) + +SET(CMAKE_INSTALL_RPATH + ${CMAKE_INSTALL_RPATH} + ${CMAKE_INSTALL_PREFIX}/${DESTINATION_LIB_PREFIX}/${tizen_dest} + ${CMAKE_INSTALL_PREFIX}/${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME} +) + +SET(SRCS_IMPL + JSMotionManager.cpp + JSPedometerInfo.cpp + MotionManager.cpp + PedometerInfo.cpp +) + +ADD_LIBRARY(${TARGET_IMPL_NAME} SHARED ${SRCS_IMPL}) + +TARGET_LINK_LIBRARIES(${TARGET_IMPL_NAME} + ${LIBS_COMMON} + ${tizen_impl} + ${platform_pkgs_humanactivitymonitor_LIBRARIES} +) + +SET(SRCS + plugin_config.cpp + plugin_initializer.cpp +) + +ADD_LIBRARY(${TARGET_NAME} SHARED ${SRCS}) + +TARGET_LINK_LIBRARIES(${TARGET_NAME} + ${TARGET_IMPL_NAME} +) + +INSTALL(TARGETS ${TARGET_NAME} ${TARGET_IMPL_NAME} LIBRARY DESTINATION ${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME}) +INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/config.xml DESTINATION ${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME}) +INSTALL( + DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/ DESTINATION ${DESTINATION_HEADER_PREFIX}/humanactivitymonitor + FILES_MATCHING PATTERN "*.h" PATTERN "CMakeFiles" EXCLUDE +) diff --git a/wearable_src/HumanActivityMonitor/ContextTypes.h b/wearable_src/HumanActivityMonitor/ContextTypes.h new file mode 100755 index 0000000..b44410f --- /dev/null +++ b/wearable_src/HumanActivityMonitor/ContextTypes.h @@ -0,0 +1,55 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _PEDOMETER_TYPES_H_ +#define _PEDOMETER_TYPES_H_ + +#include <string> +#include <vector> +#include <map> + +namespace DeviceAPI { +namespace HumanActivityMonitor { + +// Motion Type +#define MOTION_ENUM_TYPE_PEDOMETER "PEDOMETER" +#define MOTION_ENUM_TYPE_WRIST_UP "WRIST_UP" + +// enum PedometerStepStatus +#define TIZEN_PEDOMETER_STEP_STATUS_NOT_MOVING "NOT_MOVING" +#define TIZEN_PEDOMETER_STEP_STATUS_WALKING "WALKING" +#define TIZEN_PEDOMETER_STEP_STATUS_RUNNING "RUNNING" +#define TIZEN_PEDOMETER_STEP_STATUS_UNKOWN "UNKOWN" + +// attributes +#define TIZEN_PEDOMETER_INFO_STEP_STATUS "stepStatus" +#define TIZEN_PEDOMETER_INFO_SPEED "speed" +#define TIZEN_PEDOMETER_INFO_WALKING_FREQUENCY "walkingFrequency" +#define TIZEN_PEDOMETER_INFO_CUMULATIVE_DISTANCE "cumulativeDistance" +#define TIZEN_PEDOMETER_INFO_CUMULATIVE_CALORIE "cumulativeCalorie" +#define TIZEN_PEDOMETER_INFO_CUMULATIVE_TOTAL_STEP_COUNT "cumulativeTotalStepCount" +#define TIZEN_PEDOMETER_INFO_CUMULATIVE_WALK_STEP_COUNT "cumulativeWalkStepCount" +#define TIZEN_PEDOMETER_INFO_CUMULATIVE_RUN_STEP_COUNT "cumulativeRunStepCount" + +// Custom feature +#define TIZEN_TIZEN_FEATURE_PEDOMETER "tizen.org/feature/sensor.pedometer" +#define TIZEN_TIZEN_FEATURE_WRIST_UP "tizen.org/feature/sensor.wrist_up" + +} // Context +} // DeviceAPI + +#endif // _PEDOMETER_TYPES_H_ diff --git a/wearable_src/HumanActivityMonitor/JSMotionManager.cpp b/wearable_src/HumanActivityMonitor/JSMotionManager.cpp new file mode 100755 index 0000000..27544a3 --- /dev/null +++ b/wearable_src/HumanActivityMonitor/JSMotionManager.cpp @@ -0,0 +1,303 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <SecurityExceptions.h> + +#include <JSUtil.h> +#include <JSWebAPIError.h> +#include <ArgumentValidator.h> +#include <GlobalContextManager.h> +#include <MultiCallbackUserData.h> +#include <PlatformException.h> +#include <context-manager/context_manager.h> +#include <cstring> + +#include "plugin_config.h" + +#include "JSMotionManager.h" + +using namespace WrtDeviceApis::Commons; +using namespace DeviceAPI::Common; +using namespace std; + + +namespace DeviceAPI { +namespace HumanActivityMonitor { + +JSClassDefinition JSMotionManager::m_classInfo = { + 0, + kJSClassAttributeNone, + "MotionManager", + NULL, //ParentClass + NULL, //StaticValues + m_function, //StaticFunctions + initialize, //Initialize + finalize, //Finalize + NULL, //HasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL //ConvertToType +}; + +JSStaticFunction JSMotionManager::m_function[] = { + { PEDOMETER_MANAGER_API_GET_CONTEXT_INFO, JSMotionManager::getContextInfo, kJSPropertyAttributeNone }, + { PEDOMETER_MANAGER_API_START, JSMotionManager::setChangeListener, kJSPropertyAttributeNone }, + { PEDOMETER_MANAGER_API_SET_ACCUMULATIVE_PEDOMETER_LISTENER, JSMotionManager::setAccumulativePedometerListener, kJSPropertyAttributeNone }, + { PEDOMETER_MANAGER_API_UNSET_ACCUMULATIVE_PEDOMETER_LISTENER, JSMotionManager::unsetAccumulativePedometerListener, kJSPropertyAttributeNone }, + { PEDOMETER_MANAGER_API_STOP, JSMotionManager::unsetChangeListener, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +JSClassRef JSMotionManager::m_jsClassRef = JSClassCreate(JSMotionManager::getClassInfo()); + +const JSClassRef JSMotionManager::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSMotionManager::getClassInfo() +{ + return &m_classInfo; +} + +void JSMotionManager::initialize(JSContextRef context, JSObjectRef object) +{ + +} + +void JSMotionManager::finalize(JSObjectRef object) +{ + LoggerD("enter"); +} + +JSValueRef JSMotionManager::getContextInfo(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("enter"); + string contextType; + + try { + + AceSecurityStatus status = HUMANACTIVITYMONITOR_CHECK_ACCESS(MOTION_API_GET_CONTEXT_INFO); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + ArgumentValidator validator(context, argumentCount, arguments); + contextType = validator.toString(0); + + if(!strcmp(MOTION_ENUM_TYPE_PEDOMETER,contextType.c_str())){ + // successCallback + JSObjectRef successCB = validator.toFunction(1); + if (successCB) { + PedometerSuccessCallbackPtr pedometerGetCB(new PedometerSuccessCallback(GlobalContextManager::getInstance()->getGlobalContext(context))); + pedometerGetCB->setSuccessCallback(successCB); + pedometerGetCB->setContextType(contextType.c_str()); + + // errorCallback + JSObjectRef errCB = validator.toFunction(2, true); + if(errCB){ + pedometerGetCB->setErrorCallback(errCB); + } + + // perform + MotionManager::getInstance()->getContextInfo(pedometerGetCB); + + }else{ + LoggerD("argument type mismatch"); + throw TypeMismatchException("argument type mismatch"); + } + + }else{ + LoggerD("argument type mismatch"); + throw TypeMismatchException("Type mismatch"); + } + + return JSValueMakeUndefined(context); + + } catch (const TypeMismatchException &err) { + LoggerD("Type Mismatch Exception"); + return JSWebAPIErrorFactory::postException(context, exception, err); + } catch (const BasePlatformException &err) { + LoggerD("argument is wrong."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + +} + +JSValueRef JSMotionManager::setChangeListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + + LoggerD("enter"); + + try { + + string contextType; + ArgumentValidator validator(context, argumentCount, arguments); + JSObjectRef successCB = validator.toFunction(1, true); + + contextType = validator.toString(0); + + if(!strcmp(MOTION_ENUM_TYPE_PEDOMETER,contextType.c_str())){ + AceSecurityStatus status = HUMANACTIVITYMONITOR_CHECK_ACCESS(MOTION_API_START); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + PedometerSuccessCallbackPtr pedometerCB(new PedometerSuccessCallback(GlobalContextManager::getInstance()->getGlobalContext(context))); + pedometerCB->setContextType(contextType.c_str()); + if (successCB) { + pedometerCB->setSuccessCallback(successCB); + } + MotionManager::getInstance()->setChangeListener(pedometerCB); + + }else if(!strcmp(MOTION_ENUM_TYPE_WRIST_UP,contextType.c_str())){ + AceSecurityStatus status = HUMANACTIVITYMONITOR_CHECK_ACCESS(MOTION_API_START); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + WristUpSuccessCallbackPtr wristupCB(new WristUpSuccessCallback(GlobalContextManager::getInstance()->getGlobalContext(context))); + wristupCB->setContextType(contextType.c_str()); + if (successCB) { + wristupCB->setSuccessCallback(successCB); + } + MotionManager::getInstance()->setChangeListener(wristupCB); + + }else{ + throw TypeMismatchException("Type Mismatch"); + } + + return JSValueMakeUndefined(context); + + } catch (const BasePlatformException &err) { + LoggerD("argument is wrong."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + +} + +JSValueRef JSMotionManager::unsetChangeListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + + LoggerD("enter"); + + try { + string contextType; + ArgumentValidator validator(context, argumentCount, arguments); + contextType = validator.toString(0); + + if(!strcmp(MOTION_ENUM_TYPE_PEDOMETER,contextType.c_str()) || !strcmp(MOTION_ENUM_TYPE_WRIST_UP,contextType.c_str())){ + AceSecurityStatus status = HUMANACTIVITYMONITOR_CHECK_ACCESS(MOTION_API_STOP); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + MotionManager::getInstance()->unsetChangeListener(GlobalContextManager::getInstance()->getGlobalContext(context), contextType.c_str()); + }else{ + throw TypeMismatchException("Type Mismatch"); + } + + return JSValueMakeUndefined(context); + + } catch (const BasePlatformException &err) { + LoggerD("argument is wrong."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + +} + + + +JSValueRef JSMotionManager::setAccumulativePedometerListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("enter"); + + + try { + + ArgumentValidator validator(context, argumentCount, arguments); + JSObjectRef successCB = validator.toFunction(0); + + AceSecurityStatus status = HUMANACTIVITYMONITOR_CHECK_ACCESS(MOTION_API_START); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + PedometerSuccessCallbackPtr pedometerCB(new PedometerSuccessCallback(GlobalContextManager::getInstance()->getGlobalContext(context))); + pedometerCB->setContextType("PEDOMETER"); + if (successCB) { + pedometerCB->setSuccessCallback(successCB); + } + MotionManager::getInstance()->setAccumulativePedometerListener(pedometerCB); + + return JSValueMakeUndefined(context); + + } catch (const BasePlatformException &err) { + LoggerD("argument is wrong."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + + +} + + +JSValueRef JSMotionManager::unsetAccumulativePedometerListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("enter"); + + try { + ArgumentValidator validator(context, argumentCount, arguments); + + AceSecurityStatus status = HUMANACTIVITYMONITOR_CHECK_ACCESS(MOTION_API_STOP); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + MotionManager::getInstance()->unsetAccumulativePedometerListener(GlobalContextManager::getInstance()->getGlobalContext(context)); + + return JSValueMakeUndefined(context); + + } catch (const BasePlatformException &err) { + LoggerD("argument is wrong."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + + +} + + +} // Context +} // DeviceAPI diff --git a/wearable_src/HumanActivityMonitor/JSMotionManager.h b/wearable_src/HumanActivityMonitor/JSMotionManager.h new file mode 100755 index 0000000..16bd9a9 --- /dev/null +++ b/wearable_src/HumanActivityMonitor/JSMotionManager.h @@ -0,0 +1,109 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 __TIZEN_JS_PEDOMETER_MANAGER_H__ +#define __TIZEN_JS_PEDOMETER_MANAGER_H__ + +#include <JavaScriptCore/JavaScript.h> + +#include "MotionManager.h" + +namespace DeviceAPI { +namespace HumanActivityMonitor { + +class JSMotionManager +{ +public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); +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); + + static JSValueRef getContextInfo(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef setChangeListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef unsetChangeListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef setAccumulativePedometerListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef unsetAccumulativePedometerListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + + /** + * This member variable contains the values which has to be passed + * when the this class is embedded into JS Engine. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This member variable contains the initialization values for the + * properties of this class. The values are given according to + * the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; +}; + + + +} // Context +} // DeviceAPI + +#endif // __TIZEN_JS_PEDOMETER_MANAGER_H__ + diff --git a/wearable_src/HumanActivityMonitor/JSPedometerInfo.cpp b/wearable_src/HumanActivityMonitor/JSPedometerInfo.cpp new file mode 100755 index 0000000..7dce456 --- /dev/null +++ b/wearable_src/HumanActivityMonitor/JSPedometerInfo.cpp @@ -0,0 +1,247 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <JSUtil.h> +#include <CommonsJavaScript/Converter.h> +#include <ArgumentValidator.h> +#include <GlobalContextManager.h> +#include <MultiCallbackUserData.h> +#include <PlatformException.h> + +#include "plugin_config.h" +#include "JSPedometerInfo.h" + +using namespace DeviceAPI::Common; + +namespace DeviceAPI { +namespace HumanActivityMonitor { + +JSClassDefinition JSPedometerInfo::m_classInfo = { + 0, + kJSClassAttributeNone, + "PedometerInfo", + NULL, //ParentClass + m_property, //StaticValues + NULL, //StaticFunctions + initialize, //Initialize + finalize, //Finalize + NULL, //HasProperty, + NULL, //getProperty, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL //ConvertToType +}; + +JSStaticValue JSPedometerInfo::m_property[] = { + { TIZEN_PEDOMETER_INFO_STEP_STATUS, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_PEDOMETER_INFO_SPEED, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_PEDOMETER_INFO_WALKING_FREQUENCY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_PEDOMETER_INFO_CUMULATIVE_DISTANCE, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_PEDOMETER_INFO_CUMULATIVE_CALORIE, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_PEDOMETER_INFO_CUMULATIVE_TOTAL_STEP_COUNT, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_PEDOMETER_INFO_CUMULATIVE_WALK_STEP_COUNT, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_PEDOMETER_INFO_CUMULATIVE_RUN_STEP_COUNT, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + + + +JSClassRef JSPedometerInfo::m_jsClassRef = JSClassCreate(JSPedometerInfo::getClassInfo()); + +const JSClassRef JSPedometerInfo::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSPedometerInfo::getClassInfo() +{ + return &m_classInfo; +} + + +JSValueRef JSPedometerInfo::createJSObject(JSContextRef context, PedometerInfo* pedometerInfo) +{ + JSObjectRef jsValueRef = JSObjectMake(context, getClassRef(), static_cast<void*>(pedometerInfo)); + if (NULL == jsValueRef) { + LogError("object creation error"); + return JSValueMakeUndefined(context); + } + + return jsValueRef; +} + + +void JSPedometerInfo::initialize(JSContextRef context, JSObjectRef object) +{ + +} + +void JSPedometerInfo::finalize(JSObjectRef object) +{ + PedometerInfo* priv = static_cast<PedometerInfo*>(JSObjectGetPrivate(object)); + if (priv) { + delete priv; + } +} + +JSValueRef JSPedometerInfo::getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception) +{ + PedometerInfo* priv = static_cast<PedometerInfo*>(JSObjectGetPrivate(object)); + if (!priv) { + throw TypeMismatchException("Private object is NULL"); + } + + if (JSStringIsEqualToUTF8CString(propertyName, PEDOMETER_INFO_STEP_STATUS)) { + std::string statusString(""); + statusString.append(priv->getStepStatusString()); + return JSUtil::toJSValueRef(context, statusString); + }else if (JSStringIsEqualToUTF8CString(propertyName, PEDOMETER_INFO_SPEED)) { + return JSUtil::toJSValueRef(context, priv->getSpeed()); + }else if (JSStringIsEqualToUTF8CString(propertyName, PEDOMETER_INFO_WALKING_FREQUENCY)) { + return JSUtil::toJSValueRef(context, priv->getWalkingFrequency()); + }else if (JSStringIsEqualToUTF8CString(propertyName, PEDOMETER_INFO_CUMULATIVE_DISTANCE)) { + return JSUtil::toJSValueRef(context, priv->getCumulativeDistance()); + }else if (JSStringIsEqualToUTF8CString(propertyName, PEDOMETER_INFO_CUMULATIVE_CALORIE)) { + return JSUtil::toJSValueRef(context, priv->getCumulativeCalorie()); + }else if (JSStringIsEqualToUTF8CString(propertyName, PEDOMETER_INFO_CUMULATIVE_TOTAL_STEP_COUNT)) { + return JSUtil::toJSValueRef(context, priv->getCumulativeTotalStepCount()); + }else if (JSStringIsEqualToUTF8CString(propertyName, PEDOMETER_INFO_CUMULATIVE_WALK_STEP_COUNT)) { + return JSUtil::toJSValueRef(context, priv->getCumulativeWalkStepCount()); + }else if (JSStringIsEqualToUTF8CString(propertyName, PEDOMETER_INFO_CUMULATIVE_RUN_STEP_COUNT)) { + return JSUtil::toJSValueRef(context, priv->getCumulativeRunStepCount()); + } + + return JSValueMakeUndefined(context); + +} + +JSClassDefinition JSAccumulativePedometerInfo::m_classInfo = { + 0, + kJSClassAttributeNone, + "PedometerInfo", + NULL, //ParentClass + m_property, //StaticValues + NULL, //StaticFunctions + initialize, //Initialize + finalize, //Finalize + NULL, //HasProperty, + NULL, //getProperty, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL //ConvertToType +}; + +JSStaticValue JSAccumulativePedometerInfo::m_property[] = { + { TIZEN_PEDOMETER_INFO_STEP_STATUS, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_PEDOMETER_INFO_SPEED, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_PEDOMETER_INFO_WALKING_FREQUENCY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { PEDOMETER_INFO_ACCUMULATIVE_DISTANCE, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { PEDOMETER_INFO_ACCUMULATIVE_CALORIE, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { PEDOMETER_INFO_ACCUMULATIVE_TOTAL_STEP_COUNT, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { PEDOMETER_INFO_ACCUMULATIVE_WALK_STEP_COUNT, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { PEDOMETER_INFO_ACCUMULATIVE_RUN_STEP_COUNT, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + + + +JSClassRef JSAccumulativePedometerInfo::m_jsClassRef = JSClassCreate(JSAccumulativePedometerInfo::getClassInfo()); + +const JSClassRef JSAccumulativePedometerInfo::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSAccumulativePedometerInfo::getClassInfo() +{ + return &m_classInfo; +} + + +JSValueRef JSAccumulativePedometerInfo::createJSObject(JSContextRef context, PedometerInfo* pedometerInfo) +{ + JSObjectRef jsValueRef = JSObjectMake(context, getClassRef(), static_cast<void*>(pedometerInfo)); + if (NULL == jsValueRef) { + LogError("object creation error"); + return JSValueMakeUndefined(context); + } + + return jsValueRef; +} + + +void JSAccumulativePedometerInfo::initialize(JSContextRef context, JSObjectRef object) +{ + +} + +void JSAccumulativePedometerInfo::finalize(JSObjectRef object) +{ + PedometerInfo* priv = static_cast<PedometerInfo*>(JSObjectGetPrivate(object)); + if (priv) { + delete priv; + } +} + +JSValueRef JSAccumulativePedometerInfo::getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception) +{ + PedometerInfo* priv = static_cast<PedometerInfo*>(JSObjectGetPrivate(object)); + if (!priv) { + throw TypeMismatchException("Private object is NULL"); + } + + if (JSStringIsEqualToUTF8CString(propertyName, PEDOMETER_INFO_STEP_STATUS)) { + std::string statusString(""); + statusString.append(priv->getStepStatusString()); + return JSUtil::toJSValueRef(context, statusString); + }else if (JSStringIsEqualToUTF8CString(propertyName, PEDOMETER_INFO_SPEED)) { + return JSUtil::toJSValueRef(context, priv->getSpeed()); + }else if (JSStringIsEqualToUTF8CString(propertyName, PEDOMETER_INFO_WALKING_FREQUENCY)) { + return JSUtil::toJSValueRef(context, priv->getWalkingFrequency()); + }else if (JSStringIsEqualToUTF8CString(propertyName, PEDOMETER_INFO_ACCUMULATIVE_DISTANCE)) { + return JSUtil::toJSValueRef(context, priv->getCumulativeDistance()); + }else if (JSStringIsEqualToUTF8CString(propertyName, PEDOMETER_INFO_ACCUMULATIVE_CALORIE)) { + return JSUtil::toJSValueRef(context, priv->getCumulativeCalorie()); + }else if (JSStringIsEqualToUTF8CString(propertyName, PEDOMETER_INFO_ACCUMULATIVE_TOTAL_STEP_COUNT)) { + return JSUtil::toJSValueRef(context, priv->getCumulativeTotalStepCount()); + }else if (JSStringIsEqualToUTF8CString(propertyName, PEDOMETER_INFO_ACCUMULATIVE_WALK_STEP_COUNT)) { + return JSUtil::toJSValueRef(context, priv->getCumulativeWalkStepCount()); + }else if (JSStringIsEqualToUTF8CString(propertyName, PEDOMETER_INFO_ACCUMULATIVE_RUN_STEP_COUNT)) { + return JSUtil::toJSValueRef(context, priv->getCumulativeRunStepCount()); + } + + return JSValueMakeUndefined(context); + +} + + +} // Context +} // DeviceAPI diff --git a/wearable_src/HumanActivityMonitor/JSPedometerInfo.h b/wearable_src/HumanActivityMonitor/JSPedometerInfo.h new file mode 100755 index 0000000..9276c65 --- /dev/null +++ b/wearable_src/HumanActivityMonitor/JSPedometerInfo.h @@ -0,0 +1,107 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 __TIZEN_JS_PEDOMETER_INFO_H__ +#define __TIZEN_JS_PEDOMETER_INFO_H__ + +#include <JavaScriptCore/JavaScript.h> +#include <JSUtil.h> + + +#include "PedometerInfo.h" + +namespace DeviceAPI { +namespace HumanActivityMonitor { + +class JSPedometerInfo +{ +public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSValueRef createJSObject(JSContextRef context, PedometerInfo* pedometerInfo); + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, 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 member variable contains the values which has to be passed + * when the this class is embedded into JS Engine. + */ + static JSClassDefinition m_classInfo; + + + /** + * This member variable contains the initialization values for the + * properties of this class. The values are given according to + * the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; +}; + + +class JSAccumulativePedometerInfo +{ +public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSValueRef createJSObject(JSContextRef context, PedometerInfo* pedometerInfo); + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, 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 member variable contains the values which has to be passed + * when the this class is embedded into JS Engine. + */ + static JSClassDefinition m_classInfo; + + + /** + * This member variable contains the initialization values for the + * properties of this class. The values are given according to + * the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; +}; + + +} // Context +} // DeviceAPI + +#endif // __TIZEN_JS_DOWNLOAD_MANAGER_H__ diff --git a/wearable_src/HumanActivityMonitor/MotionManager.cpp b/wearable_src/HumanActivityMonitor/MotionManager.cpp new file mode 100755 index 0000000..4193aa3 --- /dev/null +++ b/wearable_src/HumanActivityMonitor/MotionManager.cpp @@ -0,0 +1,819 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <PlatformException.h> +#include <Logger.h> + +#include <context_manager.h> +#include <JSWebAPIErrorFactory.h> + +#include <map> +#include <glib.h> + +#include <system_info.h> + +#include "GlobalContextManager.h" +#include "MotionManager.h" +#include "PedometerInfo.h" +#include "JSPedometerInfo.h" + + +namespace DeviceAPI { +namespace HumanActivityMonitor { + + + +MotionManager* MotionManager::getInstance(){ + static MotionManager instance; + return &instance; +} + + +MotionManager::MotionManager() +{ + LoggerD("-- enter --"); + + int ret = 0; + int req_id = -1; + + double dData = 0.0; + int status = CONTEXT_PEDOMETER_STEP_STATUS_STOP; + + mPedometerB = false; + mWristUpB = false; + mHRMB = false; + mSleepMonitorB = false; + + ret = system_info_get_platform_bool(TIZEN_TIZEN_FEATURE_PEDOMETER, &mPedometerB); + if(ret != SYSTEM_INFO_ERROR_NONE){ + LoggerD("custom feature read error"); + } + + ret = system_info_get_platform_bool(TIZEN_TIZEN_FEATURE_WRIST_UP, &mWristUpB); + if(ret != SYSTEM_INFO_ERROR_NONE){ + LoggerD("custom feature read error"); + } + + LoggerD("enter "<<mPedometerB<<" , "<<mWristUpB); + + ret = context_set_changed_callback(CONTEXT_ITEM_PEDOMETER, NULL, MotionManager::pedometer_changed_cb, this, &req_id); + if(ret != CONTEXT_ERROR_NONE){ + LoggerD("changed callback register error"); + } + + ret = context_set_changed_callback(CONTEXT_ITEM_WRIST_UP, NULL, MotionManager::wrist_up_changed_cb, this, &req_id); + if(ret != CONTEXT_ERROR_NONE){ + LoggerD("changed callback register error"); + } + + + mBaseInit = false; + mBasePedometerInfo = new PedometerInfo(); + if(mBasePedometerInfo == NULL){ + LoggerD("base pedometer memory allocation failed"); + }else{ + mBasePedometerInfo->setStepStatus(status); + mBasePedometerInfo->setSpeed(dData); + mBasePedometerInfo->setWalkingFrequency(dData); + mBasePedometerInfo->setCumulativeDistance(dData); + mBasePedometerInfo->setCumulativeCalorie(dData); + mBasePedometerInfo->setCumulativeTotalStepCount(dData); + mBasePedometerInfo->setCumulativeWalkStepCount(dData); + mBasePedometerInfo->setCumulativeRunStepCount(dData); + } + + LoggerD("end"); + +} + +MotionManager::~MotionManager() +{ + LoggerD("enter"); + int ret = context_unset_changed_callback(CONTEXT_ITEM_PEDOMETER); + if(ret != CONTEXT_ERROR_NONE){ + LoggerD("context stop error : "<<ret); + } + + ret = context_unset_changed_callback(CONTEXT_ITEM_WRIST_UP); + if(ret != CONTEXT_ERROR_NONE){ + LoggerD("context stop error : "<<ret); + } + + + if(mBasePedometerInfo != NULL){ + delete mBasePedometerInfo; + } + +} + +gboolean MotionManager::callPedometerSuccessCallback(void* data) +{ + LoggerD("enter"); + PedometerSuccessCallbackHolder* holder = static_cast<PedometerSuccessCallbackHolder*>(data); + holder->ptr->callSuccessCallback(holder->mJSPedometerInfo); + delete holder; + return false; +} + +gboolean MotionManager::callWristUpSuccessCallback(void* data) +{ + LoggerD("enter"); + WristUpSuccessCallbackHolder* holder = static_cast<WristUpSuccessCallbackHolder*>(data); + holder->ptr->callSuccessCallback(JSValueMakeNull(holder->ptr->getContext())); + delete holder; + return false; +} + + +void MotionManager::broadcast_wristup_info() +{ + guint bGIdleRet = 0; + WristUpSuccessCallbackHolder* holder = NULL; + std::map<JSContextRef, WristUpSuccessCallbackPtr>::iterator iter; + + for(iter = mWristupCallbackMap.begin() ; iter != mWristupCallbackMap.end() ; ++iter){ + holder = new WristUpSuccessCallbackHolder(); + holder->ptr = iter->second; + bGIdleRet = g_idle_add(callWristUpSuccessCallback, holder); + if (!bGIdleRet) { + LoggerD("g_idle_add fails"); + } + } + +} + + + +void MotionManager::broadcast_pedometer_info(PedometerInfo* curPedometerInfo) +{ + bool bInit = false; + double dValue = 0.0; + guint bGIdleRet = 0; + int stepStatus = 0; + PedometerInfo* pedometerInfo = NULL; + PedometerInfo* basePedometerInfo = NULL; + PedometerSuccessCallbackHolder* holder = NULL; + std::map<JSContextRef, PedometerSuccessCallbackPtr>::iterator iter; + + if(mBaseInit == false){ + mBasePedometerInfo->setCumulativeDistance(curPedometerInfo->getCumulativeDistance()); + mBasePedometerInfo->setCumulativeCalorie(curPedometerInfo->getCumulativeCalorie()); + mBasePedometerInfo->setCumulativeTotalStepCount(curPedometerInfo->getCumulativeTotalStepCount()); + mBasePedometerInfo->setCumulativeWalkStepCount(curPedometerInfo->getCumulativeWalkStepCount()); + mBasePedometerInfo->setCumulativeRunStepCount(curPedometerInfo->getCumulativeRunStepCount()); + mBaseInit = true; + //LoggerD("global base pedometer init"); + } + + stepStatus = curPedometerInfo->getStepStatus(); + if(stepStatus == CONTEXT_PEDOMETER_STEP_STATUS_UNKNOWN){ + LoggerD("enter "<<stepStatus); + if(curPedometerInfo != NULL){ + delete curPedometerInfo; + } + return; + } + + for(iter = mPedometerCallbackMap.begin() ; iter != mPedometerCallbackMap.end() ; ++iter){ + + PedometerSuccessCallbackPtr callback = iter->second; + bInit = callback->getPedometerInit(); + basePedometerInfo = callback->getPedometerInfo(); + + if(bInit == false){ + basePedometerInfo->setCumulativeDistance(curPedometerInfo->getCumulativeDistance()); + basePedometerInfo->setCumulativeCalorie(curPedometerInfo->getCumulativeCalorie()); + basePedometerInfo->setCumulativeTotalStepCount(curPedometerInfo->getCumulativeTotalStepCount()); + basePedometerInfo->setCumulativeWalkStepCount(curPedometerInfo->getCumulativeWalkStepCount()); + basePedometerInfo->setCumulativeRunStepCount(curPedometerInfo->getCumulativeRunStepCount()); + callback->setPedometerInit(true); + LoggerD("base pedometer init"); + return; + } + + pedometerInfo = new PedometerInfo(); + if(pedometerInfo == NULL){ + LoggerD("PedometerInfo memory allocation fail"); + return; + } + + pedometerInfo->setStepStatus(curPedometerInfo->getStepStatus()); + pedometerInfo->setSpeed(curPedometerInfo->getSpeed()); + pedometerInfo->setWalkingFrequency(curPedometerInfo->getWalkingFrequency()); + + dValue = curPedometerInfo->getCumulativeDistance() - basePedometerInfo->getCumulativeDistance(); + pedometerInfo->setCumulativeDistance(pedometerInfo->convertSimpleDouble(dValue)); + + dValue = curPedometerInfo->getCumulativeCalorie() - basePedometerInfo->getCumulativeCalorie(); + pedometerInfo->setCumulativeCalorie(pedometerInfo->convertSimpleDouble(dValue)); + + dValue = curPedometerInfo->getCumulativeTotalStepCount() - basePedometerInfo->getCumulativeTotalStepCount(); + pedometerInfo->setCumulativeTotalStepCount(pedometerInfo->convertSimpleDouble(dValue)); + //LoggerD("1. Total Step "<<curPedometerInfo->getCumulativeTotalStepCount()); + //LoggerD("2. Total Step "<<basePedometerInfo->getCumulativeTotalStepCount()); + //LoggerD("3. Total Step "<<pedometerInfo->getCumulativeTotalStepCount()); + + dValue = curPedometerInfo->getCumulativeWalkStepCount() - basePedometerInfo->getCumulativeWalkStepCount(); + pedometerInfo->setCumulativeWalkStepCount(pedometerInfo->convertSimpleDouble(dValue)); + + dValue = curPedometerInfo->getCumulativeRunStepCount() - basePedometerInfo->getCumulativeRunStepCount(); + pedometerInfo->setCumulativeRunStepCount(pedometerInfo->convertSimpleDouble(dValue)); + + holder = new PedometerSuccessCallbackHolder(); + holder->ptr = callback; + holder->mJSPedometerInfo = JSPedometerInfo::createJSObject(callback->getContext(), pedometerInfo); + bGIdleRet = g_idle_add(callPedometerSuccessCallback, holder); + if (!bGIdleRet) { + LoggerD("g_idle_add fails"); + } + + } + + for(iter = mAccumulatviePedometerCallbackMap.begin() ; iter != mAccumulatviePedometerCallbackMap.end() ; ++iter){ + + PedometerSuccessCallbackPtr callback = iter->second; + + pedometerInfo = new PedometerInfo(); + if(pedometerInfo == NULL){ + LoggerD("PedometerInfo memory allocation fail"); + return; + } + + pedometerInfo->setStepStatus(curPedometerInfo->getStepStatus()); + pedometerInfo->setSpeed(curPedometerInfo->getSpeed()); + pedometerInfo->setWalkingFrequency(curPedometerInfo->getWalkingFrequency()); + + pedometerInfo->setCumulativeDistance(pedometerInfo->convertSimpleDouble(curPedometerInfo->getCumulativeDistance())); + pedometerInfo->setCumulativeCalorie(pedometerInfo->convertSimpleDouble( curPedometerInfo->getCumulativeCalorie())); + pedometerInfo->setCumulativeTotalStepCount(pedometerInfo->convertSimpleDouble(curPedometerInfo->getCumulativeTotalStepCount())); + pedometerInfo->setCumulativeWalkStepCount(pedometerInfo->convertSimpleDouble(curPedometerInfo->getCumulativeWalkStepCount())); + pedometerInfo->setCumulativeRunStepCount(pedometerInfo->convertSimpleDouble(curPedometerInfo->getCumulativeRunStepCount())); + + holder = new PedometerSuccessCallbackHolder(); + holder->ptr = callback; + holder->mJSPedometerInfo = JSAccumulativePedometerInfo::createJSObject(callback->getContext(), pedometerInfo); + bGIdleRet = g_idle_add(callPedometerSuccessCallback, holder); + if (!bGIdleRet) { + LoggerD("g_idle_add fails"); + } + + } + + + + if(curPedometerInfo != NULL){ + delete curPedometerInfo; + } + LoggerD("enter"); + +} + + + + +void MotionManager::broadcast_get_pedometer_info(PedometerInfo* curPedometerInfo) +{ + bool bInit = false; + double dValue = 0.0; + guint bGIdleRet = 0; + int stepStatus = 0; + PedometerInfo* pedometerInfo = NULL; + PedometerInfo* basePedometerInfo = NULL; + PedometerSuccessCallbackHolder* holder = NULL; + PedometerSuccessCallbackPtr callback = NULL; + PedometerSuccessCallbackPtr startCallback = NULL; + std::map<JSContextRef, PedometerSuccessCallbackPtr>::iterator iter; + std::list<PedometerSuccessCallbackPtr>::iterator iterList = mPedometerGetCallbackList.begin(); + + LoggerD("enter"); + + stepStatus = curPedometerInfo->getStepStatus(); + if(stepStatus == CONTEXT_PEDOMETER_STEP_STATUS_UNKNOWN){ + LoggerD("enter "<<stepStatus); + if(curPedometerInfo != NULL){ + delete curPedometerInfo; + } + return; + } + + + while(iterList != mPedometerGetCallbackList.end()){ + callback = *iterList; + + iter = mPedometerCallbackMap.find(callback->getContext()); + if(iter != mPedometerCallbackMap.end()){ + startCallback = iter->second; + bInit = startCallback->getPedometerInit(); + basePedometerInfo = startCallback->getPedometerInfo(); + + if(bInit == false){ + basePedometerInfo->setCumulativeDistance(curPedometerInfo->getCumulativeDistance()); + basePedometerInfo->setCumulativeCalorie(curPedometerInfo->getCumulativeCalorie()); + basePedometerInfo->setCumulativeTotalStepCount(curPedometerInfo->getCumulativeTotalStepCount()); + basePedometerInfo->setCumulativeWalkStepCount(curPedometerInfo->getCumulativeWalkStepCount()); + basePedometerInfo->setCumulativeRunStepCount(curPedometerInfo->getCumulativeRunStepCount()); + callback->setPedometerInit(true); + } + + pedometerInfo = new PedometerInfo(); + if(pedometerInfo == NULL){ + LoggerD("PedometerInfo memory allocation fail"); + return; + } + + pedometerInfo->setStepStatus(curPedometerInfo->getStepStatus()); + pedometerInfo->setSpeed(curPedometerInfo->getSpeed()); + pedometerInfo->setWalkingFrequency(curPedometerInfo->getWalkingFrequency()); + + dValue = curPedometerInfo->getCumulativeDistance() - basePedometerInfo->getCumulativeDistance(); + pedometerInfo->setCumulativeDistance(pedometerInfo->convertSimpleDouble(dValue)); + + dValue = curPedometerInfo->getCumulativeCalorie() - basePedometerInfo->getCumulativeCalorie(); + pedometerInfo->setCumulativeCalorie(pedometerInfo->convertSimpleDouble(dValue)); + + dValue = curPedometerInfo->getCumulativeTotalStepCount() - basePedometerInfo->getCumulativeTotalStepCount(); + pedometerInfo->setCumulativeTotalStepCount(pedometerInfo->convertSimpleDouble(dValue)); + //LoggerD("Total Step "<<dValue); + + dValue = curPedometerInfo->getCumulativeWalkStepCount() - basePedometerInfo->getCumulativeWalkStepCount(); + pedometerInfo->setCumulativeWalkStepCount(pedometerInfo->convertSimpleDouble(dValue)); + + dValue = curPedometerInfo->getCumulativeRunStepCount() - basePedometerInfo->getCumulativeRunStepCount(); + pedometerInfo->setCumulativeRunStepCount(pedometerInfo->convertSimpleDouble(dValue)); + + holder = new PedometerSuccessCallbackHolder(); + holder->ptr = callback; + holder->mJSPedometerInfo = JSPedometerInfo::createJSObject(callback->getContext(), pedometerInfo); + bGIdleRet = g_idle_add(callPedometerSuccessCallback, holder); + if (!bGIdleRet) { + LoggerD("g_idle_add fails"); + } + + } + ++iterList; + } + + mPedometerGetCallbackList.clear(); + + if(curPedometerInfo != NULL){ + delete curPedometerInfo; + } + LoggerD("enter"); + +} + + + +void MotionManager::wrist_up_changed_cb(int error, context_item_e context, char* context_data, void* user_data, int req_id) +{ + + int action = 0; + MotionManager* contextManager = NULL; + + if ((error != CONTEXT_ERROR_NONE) || (context != CONTEXT_ITEM_WRIST_UP)) { + LoggerD("context manager error"); + return; + } + + contextManager = static_cast<MotionManager*>(user_data); + if(contextManager == NULL){ + LoggerD("context manager null"); + return; + } + + context_context_data_get_int(context_data, CONTEXT_MOTION_ACTION, &action); + + if(action == CONTEXT_WRIST_UP_NORMAL){ + LoggerD("Wrist up"); + contextManager->broadcast_wristup_info(); + }else{ + return; + } + + +} + + +void MotionManager::pedometer_changed_cb(int error, context_item_e context, char* context_data, void* user_data, int req_id) +{ + LoggerD("enter"); + + double dData = 0.0; + int status = CONTEXT_PEDOMETER_STEP_STATUS_STOP; + PedometerInfo* pedometerInfo = NULL; + + if ((error != CONTEXT_ERROR_NONE) || (context != CONTEXT_ITEM_PEDOMETER)) { + LoggerD("context manager error"); + return; + } + + MotionManager* contextManager = static_cast<MotionManager*>(user_data); + if(contextManager == NULL){ + LoggerD("context manager null"); + return; + } + + pedometerInfo = new PedometerInfo(); + if(pedometerInfo == NULL){ + LoggerD("PedometerInfo memory allocation fail"); + return; + } + + context_context_data_get_int(context_data, CONTEXT_PEDOMETER_STEP_STATUS, &status); + pedometerInfo->setStepStatus(status); + + context_context_data_get_double(context_data, CONTEXT_PEDOMETER_SPEED, &dData); + pedometerInfo->setSpeed(dData); + + context_context_data_get_double(context_data, CONTEXT_PEDOMETER_WALKING_FREQUENCY, &dData); + pedometerInfo->setWalkingFrequency(dData); + + context_context_data_get_double(context_data, CONTEXT_PEDOMETER_CUMULATIVE_DISTANCE, &dData); + pedometerInfo->setCumulativeDistance(dData); + + context_context_data_get_double(context_data, CONTEXT_PEDOMETER_CUMULATIVE_CALORIE, &dData); + pedometerInfo->setCumulativeCalorie(dData); + + context_context_data_get_double(context_data, CONTEXT_PEDOMETER_CUMULATIVE_TOTAL_STEP_COUNT, &dData); + pedometerInfo->setCumulativeTotalStepCount(dData); + //LoggerD("Total Step "<<dData); + + context_context_data_get_double(context_data, CONTEXT_PEDOMETER_CUMULATIVE_WALK_STEP_COUNT, &dData); + pedometerInfo->setCumulativeWalkStepCount(dData); + + context_context_data_get_double(context_data, CONTEXT_PEDOMETER_CUMULATIVE_RUN_STEP_COUNT, &dData); + pedometerInfo->setCumulativeRunStepCount(dData); + + contextManager->broadcast_pedometer_info(pedometerInfo); + +} + + +void MotionManager::pedometer_get_info_cb(int error, context_item_e context, char* context_data, void* user_data, int req_id) +{ + LoggerD("enter"); + + double dData = 0.0; + int status = CONTEXT_PEDOMETER_STEP_STATUS_STOP; + PedometerInfo* pedometerInfo = NULL; + + if ((error != CONTEXT_ERROR_NONE) || (context != CONTEXT_ITEM_PEDOMETER)) { + LoggerD("context manager error"); + return; + } + + MotionManager* contextManager = static_cast<MotionManager*>(user_data); + if(contextManager == NULL){ + LoggerD("context manager null"); + return; + } + + pedometerInfo = new PedometerInfo(); + if(pedometerInfo == NULL){ + LoggerD("PedometerInfo memory allocation fail"); + return; + } + + context_context_data_get_int(context_data, CONTEXT_PEDOMETER_STEP_STATUS, &status); + pedometerInfo->setStepStatus(status); + + context_context_data_get_double(context_data, CONTEXT_PEDOMETER_SPEED, &dData); + pedometerInfo->setSpeed(dData); + + context_context_data_get_double(context_data, CONTEXT_PEDOMETER_WALKING_FREQUENCY, &dData); + pedometerInfo->setWalkingFrequency(dData); + + context_context_data_get_double(context_data, CONTEXT_PEDOMETER_CUMULATIVE_DISTANCE, &dData); + pedometerInfo->setCumulativeDistance(dData); + + context_context_data_get_double(context_data, CONTEXT_PEDOMETER_CUMULATIVE_CALORIE, &dData); + pedometerInfo->setCumulativeCalorie(dData); + + context_context_data_get_double(context_data, CONTEXT_PEDOMETER_CUMULATIVE_TOTAL_STEP_COUNT, &dData); + pedometerInfo->setCumulativeTotalStepCount(dData); + //LoggerD("Total Step "<<dData); + + context_context_data_get_double(context_data, CONTEXT_PEDOMETER_CUMULATIVE_WALK_STEP_COUNT, &dData); + pedometerInfo->setCumulativeWalkStepCount(dData); + + context_context_data_get_double(context_data, CONTEXT_PEDOMETER_CUMULATIVE_RUN_STEP_COUNT, &dData); + pedometerInfo->setCumulativeRunStepCount(dData); + + contextManager->broadcast_get_pedometer_info(pedometerInfo); + + +} + + +void MotionManager::getContextInfo(PedometerSuccessCallbackPtr callback) +{ + + int ret = 0; + int req_id = -1; + context_item_e type; + std::map<JSContextRef, PedometerSuccessCallbackPtr>::iterator iter; + + LoggerD("enter"); + + if(mPedometerB == false){ + LoggerD("pedometer not supported"); + throw NotSupportedException("pedometer not supported"); + } + + + if(callback == NULL){ + throw InvalidValuesException("callback function is null"); + } + + iter = mPedometerCallbackMap.find(callback->getContext()); + if(iter == mPedometerCallbackMap.end()){ + LoggerD("Not yet start"); + JSValueRef error = JSWebAPIErrorFactory::makeErrorObject(callback->getContext(), JSWebAPIErrorFactory::SERVICE_NOT_AVAILABLE_ERROR, "service not available"); + callback->callErrorCallback(error); + return; + } + + type = callback->getContextType(); + if(type != CONTEXT_ITEM_PEDOMETER){ + LoggerD("Not supported type : "<<type); + throw InvalidValuesException("Invalid type"); + return; + } + + ret= context_get_context(type, NULL, MotionManager::pedometer_get_info_cb, this, &req_id); + if((ret == CONTEXT_ERROR_NONE) || (ret == CONTEXT_ERROR_CONTEXT_ALREADY_REGISTERED)){ + mPedometerGetCallbackList.push_back(callback); + }else{ + LoggerD("unknown error : "<<ret); + JSValueRef error = JSWebAPIErrorFactory::makeErrorObject(callback->getContext(), JSWebAPIErrorFactory::UNKNOWN_ERROR, "unknown error"); + callback->callErrorCallback(error); + } + + LoggerD("end"); + +} + + +void MotionManager::setChangeListener(PedometerSuccessCallbackPtr callback) +{ + std::map<JSContextRef, PedometerSuccessCallbackPtr>::iterator iter; + + LoggerD("enter"); + if(mPedometerB == false){ + LoggerD("pedometer not supported"); + throw NotSupportedException("pedometer not supported"); + } + + iter = mPedometerCallbackMap.find(callback->getContext()); + if(iter != mPedometerCallbackMap.end()){ + mPedometerCallbackMap.erase(callback->getContext()); + LoggerD("prev callback erase"); + } + + mPedometerCallbackMap[callback->getContext()] = callback; + LoggerD("pedometer start"); + +} + + + +void MotionManager::setChangeListener(WristUpSuccessCallbackPtr callback) +{ + LoggerD("enter"); + std::map<JSContextRef, WristUpSuccessCallbackPtr>::iterator iter; + + if(mWristUpB == false){ + LoggerD("wrist up not supported"); + throw NotSupportedException("wrist up not supported"); + } + + iter = mWristupCallbackMap.find(callback->getContext()); + if(iter != mWristupCallbackMap.end()){ + mWristupCallbackMap.erase(callback->getContext()); + LoggerD("prev callback erase"); + } + mWristupCallbackMap[callback->getContext()] = callback; + LoggerD("wrist up start"); + +} + + + +void MotionManager::setAccumulativePedometerListener(PedometerSuccessCallbackPtr callback) +{ + std::map<JSContextRef, PedometerSuccessCallbackPtr>::iterator iter; + + LoggerD("enter"); + if(mPedometerB == false){ + LoggerD("pedometer not supported"); + throw NotSupportedException("pedometer not supported"); + } + + iter = mAccumulatviePedometerCallbackMap.find(callback->getContext()); + if(iter != mAccumulatviePedometerCallbackMap.end()){ + mAccumulatviePedometerCallbackMap.erase(callback->getContext()); + LoggerD("prev callback erase"); + } + + mAccumulatviePedometerCallbackMap[callback->getContext()] = callback; + LoggerD("pedometer start"); + +} + + +void MotionManager::unsetChangeListener(JSContextRef globalCtx, const char* type) +{ + int total = 0; + int ret = 0; + + LoggerD("enter"); + + if(!strcmp(MOTION_ENUM_TYPE_PEDOMETER, type)){ + if(mPedometerB == false){ + LoggerD("pedometer not supported"); + throw NotSupportedException("pedometer not supported"); + } + mPedometerCallbackMap.erase(globalCtx); + }else if(!strcmp(MOTION_ENUM_TYPE_WRIST_UP, type)){ + if(mWristUpB == false){ + LoggerD("wrist up not supported"); + throw NotSupportedException("wrist up not supported"); + } + mWristupCallbackMap.erase(globalCtx); + }else{ + LoggerD("Type Mismatch : "<<type); + throw TypeMismatchException("Type Mismatch"); + } + +} + + + +void MotionManager::unsetAccumulativePedometerListener(JSContextRef globalCtx) +{ + LoggerD("enter"); + + if(mPedometerB == false){ + LoggerD("pedometer not supported"); + throw NotSupportedException("pedometer not supported"); + } + mAccumulatviePedometerCallbackMap.erase(globalCtx); +} + + +void MotionManager::removeCallback(JSContextRef globalCtx) +{ + + LoggerD("enter"); + + mPedometerCallbackMap.erase(globalCtx); + mWristupCallbackMap.erase(globalCtx); + + LoggerD("enter : "<<globalCtx<<" [ "<<mPedometerCallbackMap.size()<<" , "<<mWristupCallbackMap.size()<<" ] "); + +} + + +PedometerSuccessCallback::PedometerSuccessCallback(JSContextRef globalCtx) + :CallbackUserData(globalCtx) +{ + double dData = 0.0; + int status = CONTEXT_PEDOMETER_STEP_STATUS_STOP; + + mContextType = (context_item_e)0; + mPedometerInit = false; + + mPedometerInfo = new PedometerInfo(); + mPedometerInfo->setStepStatus(status); + mPedometerInfo->setSpeed(dData); + mPedometerInfo->setWalkingFrequency(dData); + mPedometerInfo->setCumulativeDistance(dData); + mPedometerInfo->setCumulativeCalorie(dData); + mPedometerInfo->setCumulativeTotalStepCount(dData); + mPedometerInfo->setCumulativeWalkStepCount(dData); + mPedometerInfo->setCumulativeRunStepCount(dData); + +} + +PedometerSuccessCallback::~PedometerSuccessCallback() +{ + LoggerD("enter"); + if(mPedometerInfo != NULL){ + delete mPedometerInfo; + } + +} + + +void PedometerSuccessCallback::setPedometerInit(const bool init) +{ + mPedometerInit = init; +} + +bool PedometerSuccessCallback::getPedometerInit() const +{ + return mPedometerInit; +} + + +void PedometerSuccessCallback::setContextType(const char* type) +{ + if(!strcmp(MOTION_ENUM_TYPE_PEDOMETER,type)){ + mContextType = CONTEXT_ITEM_PEDOMETER; + }else{ + throw TypeMismatchException("Not context type"); + } +} + +context_item_e PedometerSuccessCallback::getContextType() const +{ + return mContextType; +} + + +void PedometerSuccessCallback::setPedometerInfo(PedometerInfo* pedometerInfo) +{ + if(pedometerInfo == NULL){ + return; + } + + if(mPedometerInfo != NULL){ + delete mPedometerInfo; + } + + mPedometerInfo = pedometerInfo; +} + +void PedometerSuccessCallback::copyPedometerInfo(PedometerInfo* pedometerInfo) +{ + if(pedometerInfo == NULL){ + return; + } + + if(mPedometerInfo != NULL){ + delete mPedometerInfo; + } + + mPedometerInfo = new PedometerInfo(); + mPedometerInfo->setStepStatus(pedometerInfo->getStepStatus()); + mPedometerInfo->setSpeed(pedometerInfo->getSpeed()); + mPedometerInfo->setWalkingFrequency(pedometerInfo->getWalkingFrequency()); + mPedometerInfo->setCumulativeDistance(pedometerInfo->getCumulativeDistance()); + mPedometerInfo->setCumulativeCalorie(pedometerInfo->getCumulativeCalorie()); + mPedometerInfo->setCumulativeTotalStepCount(pedometerInfo->getCumulativeTotalStepCount()); + mPedometerInfo->setCumulativeWalkStepCount(pedometerInfo->getCumulativeWalkStepCount()); + mPedometerInfo->setCumulativeRunStepCount(pedometerInfo->getCumulativeRunStepCount()); + +} + + +PedometerInfo* PedometerSuccessCallback::getPedometerInfo() +{ + return mPedometerInfo; +} + + +WristUpSuccessCallback::WristUpSuccessCallback(JSContextRef globalCtx) + :CallbackUserData(globalCtx) +{ + mContextType = (context_item_e)0; +} + +WristUpSuccessCallback::~WristUpSuccessCallback() +{ + LoggerD("enter"); + +} + +void WristUpSuccessCallback::setContextType(const char* type) +{ + if(!strcmp(MOTION_ENUM_TYPE_WRIST_UP,type)){ + mContextType = CONTEXT_ITEM_WRIST_UP; + }else{ + throw TypeMismatchException("Not context type"); + } +} + +context_item_e WristUpSuccessCallback::getContextType() const +{ + return mContextType; +} + + + +} // Context +} // DeviceAPI diff --git a/wearable_src/HumanActivityMonitor/MotionManager.h b/wearable_src/HumanActivityMonitor/MotionManager.h new file mode 100755 index 0000000..dec7e80 --- /dev/null +++ b/wearable_src/HumanActivityMonitor/MotionManager.h @@ -0,0 +1,141 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 __TIZEN_PEDOMETER_MANAGER_H__ +#define __TIZEN_PEDOMETER_MANAGER_H__ + +#include <map> +#include <list> +#include <glib.h> +#include <boost/shared_ptr.hpp> +#include <CallbackUserData.h> + +#include "context_manager_types.h" + +#include "PedometerInfo.h" +#include "ContextTypes.h" + +using namespace DeviceAPI::Common; + +namespace DeviceAPI { +namespace HumanActivityMonitor { + +class PedometerSuccessCallback; +typedef std::shared_ptr<PedometerSuccessCallback> PedometerSuccessCallbackPtr; +class WristUpSuccessCallback; +typedef std::shared_ptr<WristUpSuccessCallback> WristUpSuccessCallbackPtr; +class HRMSuccessCallback; +typedef std::shared_ptr<HRMSuccessCallback> HRMSuccessCallbackPtr; +class SleepMonitorSuccessCallback; +typedef std::shared_ptr<SleepMonitorSuccessCallback> SleepMonitorSuccessCallbackPtr; + + +struct PedometerSuccessCallbackHolder { + PedometerSuccessCallbackPtr ptr; + JSValueRef mJSPedometerInfo; + bool mInit; +}; + +struct WristUpSuccessCallbackHolder { + WristUpSuccessCallbackPtr ptr; +}; + +struct HRMSuccessCallbackHolder { + HRMSuccessCallbackPtr ptr; + JSValueRef mJSHRMInfo; +}; + +struct SleepMonitorSuccessCallbackHolder { + SleepMonitorSuccessCallbackPtr ptr; + JSValueRef mJSSleepStatusArray; +}; + +class WristUpSuccessCallback : public Common::CallbackUserData +{ +public: + WristUpSuccessCallback(JSContextRef globalCtx); + virtual ~WristUpSuccessCallback(); + void setContextType(const char* type); + context_item_e getContextType() const; + +private: + context_item_e mContextType; + +}; + +class PedometerSuccessCallback : public Common::CallbackUserData +{ +public: + PedometerSuccessCallback(JSContextRef globalCtx); + virtual ~PedometerSuccessCallback(); + void setPedometerInit(const bool init); + bool getPedometerInit() const; + void setContextType(const char* type); + context_item_e getContextType() const; + void setPedometerInfo(PedometerInfo* pedometerInfo); + void copyPedometerInfo(PedometerInfo* pedometerInfo); + PedometerInfo* getPedometerInfo(); + +private: + context_item_e mContextType; + PedometerInfo* mPedometerInfo; + bool mPedometerInit; +}; + +class MotionManager +{ +public: + MotionManager(); + virtual ~MotionManager(); + void getContextInfo(PedometerSuccessCallbackPtr callback); + void setChangeListener(PedometerSuccessCallbackPtr callback); + void setChangeListener(WristUpSuccessCallbackPtr callback); + void unsetChangeListener(JSContextRef globalCtx, const char* type); + void setAccumulativePedometerListener(PedometerSuccessCallbackPtr callback); + void unsetAccumulativePedometerListener(JSContextRef globalCtx); + void broadcast_wristup_info(); + void broadcast_pedometer_info(PedometerInfo* curPedometerInfo); + void broadcast_get_pedometer_info(PedometerInfo* curPedometerInfo); + static gboolean callPedometerSuccessCallback(void* data); + static gboolean callWristUpSuccessCallback(void* data); + static void wrist_up_changed_cb(int error, context_item_e context, char* context_data, void* user_data, int req_id); + static void pedometer_changed_cb(int error, context_item_e context, char* context_data, void* user_data, int req_id); + static void pedometer_get_info_cb(int error, context_item_e context, char* context_data, void* user_data, int req_id); + static MotionManager* getInstance(); + void removeCallback(JSContextRef globalCtx); + +private: + std::map<JSContextRef, PedometerSuccessCallbackPtr> mPedometerCallbackMap; + std::map<JSContextRef, WristUpSuccessCallbackPtr> mWristupCallbackMap; + std::map<JSContextRef, PedometerSuccessCallbackPtr> mAccumulatviePedometerCallbackMap; + std::list<PedometerSuccessCallbackPtr> mPedometerGetCallbackList; + + PedometerInfo* mBasePedometerInfo; + bool mBaseInit; + + bool mPedometerB; + bool mWristUpB; + bool mHRMB; + bool mSleepMonitorB; + +}; + + +} // Context +} // DeviceAPI + +#endif // __TIZEN_PEDOMETER_MANAGER_H__ diff --git a/wearable_src/HumanActivityMonitor/PedometerInfo.cpp b/wearable_src/HumanActivityMonitor/PedometerInfo.cpp new file mode 100755 index 0000000..afae779 --- /dev/null +++ b/wearable_src/HumanActivityMonitor/PedometerInfo.cpp @@ -0,0 +1,161 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <PlatformException.h> +#include <Logger.h> +#include <math.h> + +#include "PedometerInfo.h" + +namespace DeviceAPI { +namespace HumanActivityMonitor { + +PedometerInfo::PedometerInfo(): + m_stepStatus(-1), + m_speed(0.0), + m_walkingFrequency(0.0), + m_cumulativeDistance(0.0), + m_cumulativeCalorie(0.0), + m_cumulativeTotalStepCount(0.0), + m_cumulativeWalkStepCount(0.0), + m_cumulativeRunStepCount(0.0) +{ +} + +PedometerInfo::~PedometerInfo() +{ +} + +char* PedometerInfo::getStepStatusString() const +{ + //LoggerD("enter "<<m_stepStatus); + if(m_stepStatus == CONTEXT_PEDOMETER_STEP_STATUS_STOP){ + return (char*)"NOT_MOVING"; + }else if(m_stepStatus == CONTEXT_PEDOMETER_STEP_STATUS_MARK){ + return (char*)"NOT_MOVING"; + }else if(m_stepStatus == CONTEXT_PEDOMETER_STEP_STATUS_STROLL){ + return (char*)"NOT_MOVING"; + }else if(m_stepStatus == CONTEXT_PEDOMETER_STEP_STATUS_WALK){ + return (char*)"WALKING"; + }else if(m_stepStatus == CONTEXT_PEDOMETER_STEP_STATUS_RUN){ + return (char*)"RUNNING"; + }else if(m_stepStatus == CONTEXT_PEDOMETER_STEP_STATUS_RUSH){ + return (char*)"RUNNING"; + }else if(m_stepStatus == CONTEXT_PEDOMETER_STEP_STATUS_WALK_UP){ + return (char*)"WALKING"; + }else if(m_stepStatus == CONTEXT_PEDOMETER_STEP_STATUS_WALK_DOWN){ + return (char*)"WALKING"; + }else if(m_stepStatus == CONTEXT_PEDOMETER_STEP_STATUS_RUN_UP){ + return (char*)"RUNNING"; + }else if(m_stepStatus == CONTEXT_PEDOMETER_STEP_STATUS_RUN_DOWN){ + return (char*)"RUNNING"; + }else { + LoggerD("enter "<<m_stepStatus); + return (char*)"NOT_MOVING"; + } + +} + +int PedometerInfo::getStepStatus() const +{ + //LoggerD("enter "<<m_stepStatus); + return m_stepStatus; +} + +void PedometerInfo::setStepStatus(int stepStatus) +{ + m_stepStatus = stepStatus; +} + +double PedometerInfo::getSpeed() const +{ + return m_speed; +} + +void PedometerInfo::setSpeed(double speed) +{ + m_speed = speed; +} + +double PedometerInfo::getWalkingFrequency() const +{ + return m_walkingFrequency; +} + +void PedometerInfo::setWalkingFrequency(double walkingFrequency) +{ + m_walkingFrequency = walkingFrequency; +} + +double PedometerInfo::getCumulativeDistance() const +{ + return m_cumulativeDistance; +} + +void PedometerInfo::setCumulativeDistance(double cumulativeDistance) +{ + m_cumulativeDistance = cumulativeDistance; +} + +double PedometerInfo::getCumulativeCalorie() const +{ + return m_cumulativeCalorie; +} + +void PedometerInfo::setCumulativeCalorie(double cumulativeCalorie) +{ + m_cumulativeCalorie = cumulativeCalorie; +} + +double PedometerInfo::getCumulativeTotalStepCount() const +{ + return m_cumulativeTotalStepCount; +} + +void PedometerInfo::setCumulativeTotalStepCount(double cumulativeTotalStepCount) +{ + m_cumulativeTotalStepCount = cumulativeTotalStepCount; +} + +double PedometerInfo::getCumulativeWalkStepCount() const +{ + return m_cumulativeWalkStepCount; +} + +void PedometerInfo::setCumulativeWalkStepCount(double cumulativeWalkStepCount) +{ + m_cumulativeWalkStepCount = cumulativeWalkStepCount; +} + +double PedometerInfo::getCumulativeRunStepCount() const +{ + return m_cumulativeRunStepCount; +} + +void PedometerInfo::setCumulativeRunStepCount(double cumulativeRunStepCount) +{ + m_cumulativeRunStepCount = cumulativeRunStepCount; +} + +double PedometerInfo::convertSimpleDouble(double origin) +{ + return ((int)(origin*pow(10.0,2)))/pow(10.0,2); +} + + +} // Context +} // DeviceAPI diff --git a/wearable_src/HumanActivityMonitor/PedometerInfo.h b/wearable_src/HumanActivityMonitor/PedometerInfo.h new file mode 100755 index 0000000..1591543 --- /dev/null +++ b/wearable_src/HumanActivityMonitor/PedometerInfo.h @@ -0,0 +1,79 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 __TIZEN_PEDOMETER_INFO_H__ +#define __TIZEN_PEDOMETER_INFO_H__ + +#include <context_manager.h> +#include <MultiCallbackUserData.h> + +#include "ContextTypes.h" + +using namespace DeviceAPI::Common; + +namespace DeviceAPI { +namespace HumanActivityMonitor { + +class PedometerInfo +{ +public: + PedometerInfo(); + virtual ~PedometerInfo(); + + int getStepStatus() const; + char* getStepStatusString() const; + void setStepStatus(int stepStatus); + + double getSpeed() const; + void setSpeed(double speed); + + double getWalkingFrequency() const; + void setWalkingFrequency(double walkingFrequency); + + double getCumulativeDistance() const; + void setCumulativeDistance(double cumulativeDistance); + + double getCumulativeCalorie() const; + void setCumulativeCalorie(double cumulativeCalorie); + + double getCumulativeTotalStepCount() const; + void setCumulativeTotalStepCount(double cumulativeTotalStepCount); + + double getCumulativeWalkStepCount() const; + void setCumulativeWalkStepCount(double cumulativeWalkStepCount); + + double getCumulativeRunStepCount() const; + void setCumulativeRunStepCount(double cumulativeRunStepCount); + + double convertSimpleDouble(double origin); + +private: + int m_stepStatus; + double m_speed; + double m_walkingFrequency; + double m_cumulativeDistance; + double m_cumulativeCalorie; + double m_cumulativeTotalStepCount; + double m_cumulativeWalkStepCount; + double m_cumulativeRunStepCount; +}; + + +} // Pedometer +} // DeviceAPI + +#endif // __TIZEN_PEDOMETER_INFO_H__ diff --git a/wearable_src/HumanActivityMonitor/config.xml b/wearable_src/HumanActivityMonitor/config.xml new file mode 100755 index 0000000..d1cbf84 --- /dev/null +++ b/wearable_src/HumanActivityMonitor/config.xml @@ -0,0 +1,10 @@ +<?xml version="1.0" ?> +<!DOCTYPE plugin-properties SYSTEM "/usr/etc/tizen-apis/config.dtd"> +<plugin-properties> + <library-name>libwrt-plugins-tizen-humanactivitymonitor.so</library-name> + <feature-install-uri>humanactivitymonitor.install.uri</feature-install-uri> + <api-feature> + <name>http://tizen.org/privilege/healthinfo</name> + <device-capability>healthinfo</device-capability> + </api-feature> +</plugin-properties> diff --git a/wearable_src/HumanActivityMonitor/plugin_config.cpp b/wearable_src/HumanActivityMonitor/plugin_config.cpp new file mode 100755 index 0000000..423f211 --- /dev/null +++ b/wearable_src/HumanActivityMonitor/plugin_config.cpp @@ -0,0 +1,104 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <Commons/FunctionDefinition.h> +#include <Commons/FunctionDeclaration.h> +#include <Commons/Exception.h> +#include <map> + +#include "plugin_config.h" + +#define MOTION_FEATURE_API_HEALTHINFO "http://tizen.org/privilege/healthinfo" +#define MOTION_DEVICE_CAP_HEALTHINFO "healthinfo" + + +using namespace WrtDeviceApis::Commons; + +namespace DeviceAPI { +namespace HumanActivityMonitor { + +static FunctionMapping createHumanActivityMonitorFunctions(); +static FunctionMapping HumanActivityMonitorFunctions = createHumanActivityMonitorFunctions(); + +DEFINE_FUNCTION_GETTER(HumanActivityMonitor, HumanActivityMonitorFunctions); + +static FunctionMapping createHumanActivityMonitorFunctions() +{ + /** + * Device capabilities : healthinfo + */ + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_MOTION_HEALTHINFO, MOTION_DEVICE_CAP_HEALTHINFO); + + ACE_CREATE_DEVICE_CAPS_LIST(EMPTY_DEVICE_LIST); + + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_MOTION_HEALTHINFO); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_MOTION_HEALTHINFO, DEVICE_CAP_MOTION_HEALTHINFO); + + /** + * Api Features + */ + ACE_CREATE_FEATURE(FEATURE_MOTION_HEALTHINFO, MOTION_FEATURE_API_HEALTHINFO); + + ACE_CREATE_FEATURE_LIST(MOTION_FEATURES_MOTION_HEALTHINFO); + ACE_ADD_API_FEATURE(MOTION_FEATURES_MOTION_HEALTHINFO, FEATURE_MOTION_HEALTHINFO); + + + /** + * Functions + */ + FunctionMapping motionMapping; + + + //start + AceFunction MotionStartFunc = ACE_CREATE_FUNCTION( + FUNCTION_MOTION_START, + MOTION_API_START, + MOTION_FEATURES_MOTION_HEALTHINFO, + DEVICE_LIST_MOTION_HEALTHINFO); + + motionMapping.insert(std::make_pair( + MOTION_API_START, + MotionStartFunc)); + + //stop + AceFunction MotionStopFunc = ACE_CREATE_FUNCTION( + FUNCTION_MOTION_STOP, + MOTION_API_STOP, + MOTION_FEATURES_MOTION_HEALTHINFO, + DEVICE_LIST_MOTION_HEALTHINFO); + + motionMapping.insert(std::make_pair( + MOTION_API_STOP, + MotionStopFunc)); + + + //getMotionInfo + AceFunction MotionGetMotionInfoFunc = ACE_CREATE_FUNCTION( + FUNCTION_MOTION_GET_MOTION_INFO, + MOTION_API_GET_CONTEXT_INFO, + MOTION_FEATURES_MOTION_HEALTHINFO, + DEVICE_LIST_MOTION_HEALTHINFO); + + motionMapping.insert(std::make_pair( + MOTION_API_GET_CONTEXT_INFO, + MotionGetMotionInfoFunc)); + + return motionMapping; +} + +} // Context +} // DeviceAPI diff --git a/wearable_src/HumanActivityMonitor/plugin_config.h b/wearable_src/HumanActivityMonitor/plugin_config.h new file mode 100755 index 0000000..491475e --- /dev/null +++ b/wearable_src/HumanActivityMonitor/plugin_config.h @@ -0,0 +1,69 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _PEDOMETER_PLUGIN_CONFIG_H_ +#define _PEDOMETER_PLUGIN_CONFIG_H_ + +#include <string> +#include <Commons/FunctionDeclaration.h> + +#include <Logger.h> + +namespace DeviceAPI { +namespace HumanActivityMonitor { + +#define MOTION_API_GET_CONTEXT_INFO "getHumanActivityData" +#define MOTION_API_START "start" +#define MOTION_API_STOP "stop" + + +// attributes +#define PEDOMETER_INFO_STEP_STATUS "stepStatus" +#define PEDOMETER_INFO_SPEED "speed" +#define PEDOMETER_INFO_WALKING_FREQUENCY "walkingFrequency" +// +#define PEDOMETER_INFO_CUMULATIVE_DISTANCE "cumulativeDistance" +#define PEDOMETER_INFO_CUMULATIVE_CALORIE "cumulativeCalorie" +#define PEDOMETER_INFO_CUMULATIVE_TOTAL_STEP_COUNT "cumulativeTotalStepCount" +#define PEDOMETER_INFO_CUMULATIVE_WALK_STEP_COUNT "cumulativeWalkStepCount" +#define PEDOMETER_INFO_CUMULATIVE_RUN_STEP_COUNT "cumulativeRunStepCount" +// +#define PEDOMETER_INFO_ACCUMULATIVE_DISTANCE "accumulativeDistance" +#define PEDOMETER_INFO_ACCUMULATIVE_CALORIE "accumulativeCalorie" +#define PEDOMETER_INFO_ACCUMULATIVE_TOTAL_STEP_COUNT "accumulativeTotalStepCount" +#define PEDOMETER_INFO_ACCUMULATIVE_WALK_STEP_COUNT "accumulativeWalkStepCount" +#define PEDOMETER_INFO_ACCUMULATIVE_RUN_STEP_COUNT "accumulativeRunStepCount" + + +// functions +#define PEDOMETER_MANAGER_API_GET_CONTEXT_INFO "getHumanActivityData" +#define PEDOMETER_MANAGER_API_START "start" +#define PEDOMETER_MANAGER_API_STOP "stop" +#define PEDOMETER_MANAGER_API_SET_ACCUMULATIVE_PEDOMETER_LISTENER "setAccumulativePedometerListener" +#define PEDOMETER_MANAGER_API_UNSET_ACCUMULATIVE_PEDOMETER_LISTENER "unsetAccumulativePedometerListener" + +DECLARE_FUNCTION_GETTER(HumanActivityMonitor); + +#define HUMANACTIVITYMONITOR_CHECK_ACCESS(functionName) \ + aceCheckAccess<AceFunctionGetter, DefaultArgsVerifier<> >( \ + getHumanActivityMonitorFunctionData, \ + functionName) + +} +} + +#endif // _PEDOMETER_PLUGIN_CONFIG_H_ diff --git a/wearable_src/HumanActivityMonitor/plugin_initializer.cpp b/wearable_src/HumanActivityMonitor/plugin_initializer.cpp new file mode 100755 index 0000000..311439e --- /dev/null +++ b/wearable_src/HumanActivityMonitor/plugin_initializer.cpp @@ -0,0 +1,90 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 + * @brief + */ + + +#include <Commons/plugin_initializer_def.h> +#include <Commons/WrtAccess/WrtAccess.h> + +#include <GlobalContextManager.h> + +#include "JSMotionManager.h" + +#include <Logger.h> + +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; +using namespace DeviceAPI::Common; + +#define WRT_JS_EXTENSION_OBJECT_WEBAPIS "webapis" +#define WRT_JS_EXTENSION_OBJECT_TIZEN "tizen" + +namespace DeviceAPI { +namespace HumanActivityMonitor { + +void on_widget_start_callback(int widgetId) +{ + LOGD("[Tizen\\HumanActivityMonitor] on_widget_start_callback (%d)", widgetId); + try { + WrtAccessSingleton::Instance().initialize(widgetId); + } catch (...) { + LOGE("WrtAccess initialization failed"); + } +} + +void on_widget_stop_callback(int widgetId) +{ + LOGD("[Tizen\\HumanActivityMonitor] on_widget_stop_callback (%d)", widgetId); + try { + WrtAccessSingleton::Instance().deinitialize(widgetId); + } catch (...) { + LOGE("WrtAccess deinitialization failed"); + } +} + +void on_frame_load_callback(const void * context) +{ + LOGD("[Tizen\\HumanActivityMonitor] on_frame_load_callback (%p)", context); + GlobalContextManager::getInstance()->addGlobalContext(static_cast<JSContextRef>(context)); +} + +void on_frame_unload_callback(const void * context) +{ + LOGD("[Tizen\\HumanActivityMonitor] on_frame_unload_callback (%p)", context); + GlobalContextManager::getInstance()->removeGlobalContext(static_cast<JSContextRef>(context)); + MotionManager::getInstance()->removeCallback(static_cast<JSContextRef>(context)); + +} + +PLUGIN_ON_WIDGET_START(on_widget_start_callback) +PLUGIN_ON_WIDGET_STOP(on_widget_stop_callback) +PLUGIN_ON_FRAME_LOAD(on_frame_load_callback) +PLUGIN_ON_FRAME_UNLOAD(on_frame_unload_callback) + +PLUGIN_CLASS_MAP_BEGIN +PLUGIN_CLASS_MAP_ADD_CLASS(WRT_JS_EXTENSION_OBJECT_TIZEN, + "humanactivitymonitor", + (js_class_template_getter)DeviceAPI::HumanActivityMonitor::JSMotionManager::getClassRef, + NULL) +PLUGIN_CLASS_MAP_END + +} // Context +} // DeviceAPI diff --git a/wearable_src/Package/CMakeLists.txt b/wearable_src/Package/CMakeLists.txt new file mode 100644 index 0000000..ede4af6 --- /dev/null +++ b/wearable_src/Package/CMakeLists.txt @@ -0,0 +1,55 @@ +SET(TARGET_NAME ${package_target}) +SET(DESTINATION_NAME ${package_dest}) +SET(TARGET_IMPL_NAME ${package_impl}) + +PKG_CHECK_MODULES(platform_pkgs_package REQUIRED + capi-appfw-app-manager + capi-appfw-package-manager + pkgmgr + pkgmgr-info +) + +INCLUDE_DIRECTORIES( + ${INCLUDE_COMMON} + ${TOP}/Package + ${platform_pkgs_package_INCLUDE_DIRS} +) + +SET(CMAKE_INSTALL_RPATH + ${CMAKE_INSTALL_RPATH} + ${CMAKE_INSTALL_PREFIX}/${DESTINATION_LIB_PREFIX}/${tizen_dest} + ${CMAKE_INSTALL_PREFIX}/${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME} +) + +SET(SRCS_IMPL + JSPackageInformation.cpp + JSPackageManager.cpp + PackageInformation.cpp + PackageManager.cpp +) + +ADD_LIBRARY(${TARGET_IMPL_NAME} SHARED ${SRCS_IMPL}) + +TARGET_LINK_LIBRARIES(${TARGET_IMPL_NAME} + ${LIBS_COMMON} + ${tizen_impl} + ${platform_pkgs_package_LIBRARIES} +) + +SET(SRCS + plugin_config.cpp + plugin_initializer.cpp +) + +ADD_LIBRARY(${TARGET_NAME} SHARED ${SRCS}) + +TARGET_LINK_LIBRARIES(${TARGET_NAME} + ${TARGET_IMPL_NAME} +) + +INSTALL(TARGETS ${TARGET_NAME} ${TARGET_IMPL_NAME} LIBRARY DESTINATION ${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME}) +INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/config.xml DESTINATION ${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME}) +INSTALL( + DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/ DESTINATION ${DESTINATION_HEADER_PREFIX}/package + FILES_MATCHING PATTERN "*.h" PATTERN "CMakeFiles" EXCLUDE +) diff --git a/wearable_src/Package/JSPackageInformation.cpp b/wearable_src/Package/JSPackageInformation.cpp new file mode 100644 index 0000000..c30ee65 --- /dev/null +++ b/wearable_src/Package/JSPackageInformation.cpp @@ -0,0 +1,168 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 <CommonsJavaScript/Converter.h> +#include <CommonsJavaScript/JSUtils.h> +#include <CommonsJavaScript/Utils.h> +#include <JSUtil.h> +#include <JSWebAPIErrorFactory.h> +#include "JSPackageInformation.h" +#include "PackageInformation.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Package { + +using namespace std; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace DeviceAPI::Common; + +JSClassRef JSPackageInformation::m_classRef = NULL; + +JSClassDefinition JSPackageInformation::m_classInfo = { + 0, // current (and only) version is 0 + kJSClassAttributeNone, // attributes + TIZEN_INTERFACE_PACKAGE_INFORMATION, // class name + NULL, // parent class + m_property, // static values + NULL, // static functions + initialize, // initialize + finalize, // finalize + NULL, // hasProperty + NULL, // getProperty + NULL, // setProperty + NULL, // deleteProperty + NULL, // getPropertyNames + NULL, // callAsConstructor + NULL, // callAsConstructor + NULL, // hasInstance + NULL // convertToType +}; + +JSStaticValue JSPackageInformation::m_property[] = { + { TIZEN_PACKAGE_INFORMATION_ID, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_PACKAGE_INFORMATION_NAME, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_PACKAGE_INFORMATION_ICONPATH, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_PACKAGE_INFORMATION_VERSION, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_PACKAGE_INFORMATION_TOTAL_SIZE, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_PACKAGE_INFORMATION_DATA_SIZE, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_PACKAGE_INFORMATION_LAST_MODIFIED, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_PACKAGE_INFORMATION_AUTHOR, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_PACKAGE_INFORMATION_DESCRIPTION, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_PACKAGE_INFORMATION_APP_IDS, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +// type is defined to partner feature on native +//{ TIZEN_PACKAGE_INFORMATION_TYPE, getProperty, setProperty, kJSPropertyAttributeReadOnly }, + +JSClassRef JSPackageInformation::getClassRef() { + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + + +JSValueRef JSPackageInformation::createJSObject(JSContextRef context, PackageInformation *pkgInfo) +{ + JSObjectRef jsValueRef = JSObjectMake(context, getClassRef(), static_cast<void*>(pkgInfo)); + if (NULL == jsValueRef) { + LoggerE("object creation error"); + return JSValueMakeUndefined(context); + } + + return jsValueRef; +} + + +void JSPackageInformation::initialize(JSContextRef context, JSObjectRef object) +{ +} + +void JSPackageInformation::finalize(JSObjectRef object) +{ +} + +bool JSPackageInformation::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +PackageInformation* JSPackageInformation::getPrivData(JSObjectRef object) +{ + PackageInformation *priv = static_cast<PackageInformation*>(JSObjectGetPrivate(object)); + if (!priv) { + throw TypeMismatchException("Private object is null"); + } + + return priv; +} + +JSValueRef JSPackageInformation::getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + try { + //WrtDeviceApis::CommonsJavaScript::Converter converter(context); + PackageInformation* privateData = getPrivData(object); + if (!privateData) { + throw TypeMismatchException("Private object is NULL"); + } + + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_PACKAGE_INFORMATION_ID)) { + return JSUtil::toJSValueRef(context, privateData->m_id); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_PACKAGE_INFORMATION_NAME)) { + return JSUtil::toJSValueRef(context, privateData->m_name); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_PACKAGE_INFORMATION_ICONPATH)) { + return JSUtil::toJSValueRef(context, privateData->m_iconPath); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_PACKAGE_INFORMATION_VERSION)) { + return JSUtil::toJSValueRef(context, privateData->m_version); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_PACKAGE_INFORMATION_LAST_MODIFIED)) { + return JSUtil::makeDateObject(context, privateData->m_lastModified); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_PACKAGE_INFORMATION_AUTHOR)) { + return JSUtil::toJSValueRef(context, privateData->m_author); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_PACKAGE_INFORMATION_DESCRIPTION)) { + return JSUtil::toJSValueRef(context, privateData->m_description); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_PACKAGE_INFORMATION_APP_IDS)) { + return JSUtil::toJSValueRef(context, privateData->m_appIds); + } else { + // Operation to get size need long time (IPC Delay). + if (!privateData->m_isInitialized) { + privateData->initializePackageInfo(); + } + + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_PACKAGE_INFORMATION_TOTAL_SIZE)) { + return JSUtil::toJSValueRef(context, privateData->m_totalSize); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_PACKAGE_INFORMATION_DATA_SIZE)) { + return JSUtil::toJSValueRef(context, privateData->m_dataSize); + } + } + } catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(context, exception, err); + } catch (...) { + DeviceAPI::Common::TypeMismatchException err("TypeMismatchException occured"); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + + return JSValueMakeUndefined(context); +} + +} +} diff --git a/wearable_src/Package/JSPackageInformation.h b/wearable_src/Package/JSPackageInformation.h new file mode 100644 index 0000000..1869d28 --- /dev/null +++ b/wearable_src/Package/JSPackageInformation.h @@ -0,0 +1,111 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 _TIZEN_JS_PACKAGE_INFORMATION_H_ +#define _TIZEN_JS_PACKAGE_INFORMATION_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/PrivateObject.h> +#include "PackageInformation.h" + +namespace DeviceAPI { +namespace Package { + +#define TIZEN_INTERFACE_PACKAGE_INFORMATION "PackageInformation" + +// Fields +#define TIZEN_PACKAGE_INFORMATION_ID "id" +#define TIZEN_PACKAGE_INFORMATION_NAME "name" +#define TIZEN_PACKAGE_INFORMATION_ICONPATH "iconPath" +#define TIZEN_PACKAGE_INFORMATION_VERSION "version" +#define TIZEN_PACKAGE_INFORMATION_TOTAL_SIZE "totalSize" +#define TIZEN_PACKAGE_INFORMATION_DATA_SIZE "dataSize" +#define TIZEN_PACKAGE_INFORMATION_LAST_MODIFIED "lastModified" +#define TIZEN_PACKAGE_INFORMATION_AUTHOR "author" +#define TIZEN_PACKAGE_INFORMATION_TYPE "type" +#define TIZEN_PACKAGE_INFORMATION_DESCRIPTION "description" +#define TIZEN_PACKAGE_INFORMATION_APP_IDS "appIds" + +#if 0 +#define TIZEN_PACKAGE_INFORMATION_IS_DOWNLOADED "isDownloaded" +#define TIZEN_PACKAGE_INFORMATION_IS_MOVABLE "isMovable" +#define TIZEN_PACKAGE_INFORMATION_IS_UNINSTALLABLE "isUninstallable" +#define TIZEN_PACKAGE_INFORMATION_INSTALLED_STORAGE "installedStorage" +#endif + +class JSPackageInformation { +public: + /* + * This initializes this JS class in the JS Engine. + */ + static JSClassRef getClassRef(); + +#if 0 + static JSValueRef createJSObject(JSContextRef context, + const string &id, + const string &name, + const string &iconPath, + const string &version, + const long &totalSize, + const long &dataSize, + const time_t &lastModified, + const string &description, + const string &author, + const vector<string> &appId); +#endif + + static JSValueRef createJSObject(JSContextRef context, PackageInformation *pkgInfo); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + +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 member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; + + static JSClassRef m_classRef; + + static PackageInformation* getPrivData(JSObjectRef object); + + static JSValueRef getProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + +}; + +} +} +#endif diff --git a/wearable_src/Package/JSPackageManager.cpp b/wearable_src/Package/JSPackageManager.cpp new file mode 100644 index 0000000..6b7c359 --- /dev/null +++ b/wearable_src/Package/JSPackageManager.cpp @@ -0,0 +1,511 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 <JSWebAPIErrorFactory.h> +#include <SecurityExceptions.h> + +#include <ArgumentValidator.h> +#include <PlatformException.h> + +#include <CommonsJavaScript/Converter.h> +//#include <CommonsJavaScript/JSUtils.h> +//#include <CommonsJavaScript/Utils.h> + +#include <JSUtil.h> +#include <GlobalContextManager.h> +#include <TimeTracer.h> + +#include "JSPackageManager.h" +#include "JSPackageInformation.h" + +#include "PackageManager.h" +#include "PackageInformation.h" +#include "plugin_config.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Package { + +using namespace std; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace DeviceAPI::Common; + +JSClassRef JSPackageManager::m_jsClassRef = NULL; + +JSClassDefinition JSPackageManager::m_classInfo = { + 0, // current (and only) version is 0 + kJSClassAttributeNone, // attributes + TIZEN_INTERFACE_PACKAGE_MANAGER, // class name + NULL, // parent class + NULL, // static values + m_function, // static functions + initialize, // initialize + finalize, // finalize + NULL, // hasProperty + NULL, // getProperty + NULL, // setProperty + NULL, // deleteProperty + NULL, // getPropertyNames + NULL, // callAsConstructor + NULL, // callAsConstructor + NULL, // hasInstance + NULL // convertToType +}; + +JSStaticFunction JSPackageManager::m_function[] = { + { PACKAGE_FUNCTION_API_INSTALL, JSPackageManager::install, kJSPropertyAttributeNone }, + { PACKAGE_FUNCTION_API_UNINSTALL, JSPackageManager::uninstall, kJSPropertyAttributeNone }, + { PACKAGE_FUNCTION_API_GET_PACKAGE_INFO, JSPackageManager::getPackageInfo, kJSPropertyAttributeNone }, + { PACKAGE_FUNCTION_API_GET_PACKAGES_INFO, JSPackageManager::getPackagesInfo, kJSPropertyAttributeNone }, + { PACKAGE_FUNCTION_API_SET_PACKAGE_INFO_EVENT_LISTENER, JSPackageManager::setPackageInfoEventListener, kJSPropertyAttributeNone }, + { PACKAGE_FUNCTION_API_UNSET_PACKAGE_INFO_EVENT_LISTENER, JSPackageManager::unsetPackageInfoEventListener, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +const JSClassRef JSPackageManager::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + + return m_jsClassRef; +} + +const JSClassDefinition* JSPackageManager::getClassInfo() +{ + return &m_classInfo; +} + +void JSPackageManager::initialize(JSContextRef context, JSObjectRef object) +{ + // Do Nothing. +} + +void JSPackageManager::finalize(JSObjectRef object) +{ + CallbackUserData *callback = static_cast<CallbackUserData*>(JSObjectGetPrivate(object)); + if( callback != NULL ){ + JSObjectSetPrivate(object, NULL); + delete callback; + } +} + +JSValueRef JSPackageManager::install(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + + TIME_TRACER_ITEM_BEGIN("install(ACE)", 0); + AceSecurityStatus status = PACKAGE_CHECK_ACCESS(PACKAGE_FUNCTION_API_INSTALL); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + TIME_TRACER_ITEM_END("install(ACE)", 0); + + try { + ArgumentValidator validator(context, argumentCount, arguments); + + string path = validator.toString(0); + + JSObjectRef eventCBObj = validator.toCallbackObject(1, false, "onprogress", "oncomplete", NULL); + JSObjectRef errCB = validator.toFunction(2, true); + + CallbackUserData *onprogressCb = NULL; + CallbackUserData *oncompleteCb = NULL; + CallbackUserData *onerrorCb = NULL; + + JSValueRef onprogress = JSUtil::getProperty(context, eventCBObj, "onprogress", exception); + if (!JSValueIsUndefined(context, onprogress)) { + onprogressCb = new CallbackUserData(GlobalContextManager::getInstance()->getGlobalContext(context)); + onprogressCb->setSuccessCallback(onprogress); + } + + JSValueRef oncomplete = JSUtil::getProperty(context, eventCBObj, "oncomplete", exception); + if (!JSValueIsUndefined(context, oncomplete)) { + oncompleteCb = new CallbackUserData(GlobalContextManager::getInstance()->getGlobalContext(context)); + oncompleteCb->setSuccessCallback(oncomplete); + } + + if (errCB) { + onerrorCb = new CallbackUserData(GlobalContextManager::getInstance()->getGlobalContext(context)); + onerrorCb->setSuccessCallback(errCB); + } + + PackageInstallEventCallback *pkgInstallEventCB = new PackageInstallEventCallback(GlobalContextManager::getInstance()->getGlobalContext(context), onprogressCb, oncompleteCb, onerrorCb); + + PackageManager::getInstance()->install(path, pkgInstallEventCB); + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); + + } catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(context, exception, err); + } catch (...) { + DeviceAPI::Common::UnknownException err("Unknown Error in ApplicationManager.getAppSharedURI()."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } +} + + +JSValueRef JSPackageManager::uninstall(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + + TIME_TRACER_ITEM_BEGIN("uninstall(ACE)", 0); + AceSecurityStatus status = PACKAGE_CHECK_ACCESS(PACKAGE_FUNCTION_API_INSTALL); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + TIME_TRACER_ITEM_END("uninstall(ACE)", 0); + + try { + ArgumentValidator validator(context, argumentCount, arguments); + + string id = validator.toString(0); + //JSObjectRef eventCBObj = validator.toObject(1, true); + JSObjectRef eventCBObj = validator.toCallbackObject(1, false, "onprogress", "oncomplete", NULL); + JSObjectRef errCB = validator.toFunction(2, true); + + CallbackUserData *onprogressCb = NULL; + CallbackUserData *oncompleteCb = NULL; + CallbackUserData *onerrorCb = NULL; + + JSValueRef onprogress = JSUtil::getProperty(context, eventCBObj, "onprogress", exception); + if (!JSValueIsUndefined(context, onprogress)) { + onprogressCb = new CallbackUserData(GlobalContextManager::getInstance()->getGlobalContext(context)); + onprogressCb->setSuccessCallback(onprogress); + } + + JSValueRef oncomplete = JSUtil::getProperty(context, eventCBObj, "oncomplete", exception); + if (!JSValueIsUndefined(context, oncomplete)) { + oncompleteCb = new CallbackUserData(GlobalContextManager::getInstance()->getGlobalContext(context)); + oncompleteCb->setSuccessCallback(oncomplete); + } + + if (errCB) { + onerrorCb = new CallbackUserData(GlobalContextManager::getInstance()->getGlobalContext(context)); + onerrorCb->setSuccessCallback(errCB); + } + + PackageInstallEventCallback *pkgInstallEventCB = new PackageInstallEventCallback(GlobalContextManager::getInstance()->getGlobalContext(context), onprogressCb, oncompleteCb, onerrorCb); + + PackageManager::getInstance()->uninstall(id, pkgInstallEventCB); + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); + + } catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(context, exception, err); + } catch (...) { + DeviceAPI::Common::UnknownException err("Unknown Error in ApplicationManager.getAppSharedURI()."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } +} + + +JSValueRef JSPackageManager::getPackagesInfo(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + + TIME_TRACER_ITEM_BEGIN("getPackagesInfo(ACE)", 0); + AceSecurityStatus status = PACKAGE_CHECK_ACCESS(PACKAGE_FUNCTION_API_GET_PACKAGES_INFO); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + TIME_TRACER_ITEM_END("getPackagesInfo(ACE)", 0); + + try { + ArgumentValidator validator(context, argumentCount, arguments); + JSObjectRef successCBObj = validator.toFunction(0); + JSObjectRef errCB = validator.toFunction(1, true); + + PackageInfoCallbackData *callback = new PackageInfoCallbackData(GlobalContextManager::getInstance()->getGlobalContext(context)); + callback->setSuccessCallback(successCBObj); + if (argumentCount > 1) { + callback->setErrorCallback(errCB); + } + + PackageManager::getInstance()->getPackagesInfo(callback); + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); + + } catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(context, exception, err); + } catch (...) { + DeviceAPI::Common::UnknownException err("Unknown Error in ApplicationManager.getAppSharedURI()."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } +} + +JSValueRef JSPackageManager::getPackageInfo(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + + TIME_TRACER_ITEM_BEGIN("(getPackageInfo) ACE", 0); + AceSecurityStatus status = PACKAGE_CHECK_ACCESS(PACKAGE_FUNCTION_API_GET_PACKAGE_INFO); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + TIME_TRACER_ITEM_END("(getPackageInfo) ACE", 0); + + try { + ArgumentValidator validator(context, argumentCount, arguments); + string id = validator.toString(0, true); + + PackageInformation* pkgInfo = PackageManager::getInstance()->getPackageInfo(id); + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSPackageInformation::createJSObject(context, pkgInfo); + + } catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(context, exception, err); + } catch (...) { + DeviceAPI::Common::UnknownException err("Unknown Error in ApplicationManager.getAppSharedURI()."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } +} + + +JSValueRef JSPackageManager::setPackageInfoEventListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + + TIME_TRACER_ITEM_BEGIN("(setPackageInfoEventListener) ACE", 0); + AceSecurityStatus status = PACKAGE_CHECK_ACCESS(PACKAGE_FUNCTION_API_SET_PACKAGE_INFO_EVENT_LISTENER); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + TIME_TRACER_ITEM_END("(setPackageInfoEventListener) ACE", 0); + + try { + ArgumentValidator validator(context, argumentCount, arguments); + + JSObjectRef eventCBObj = validator.toCallbackObject(0, false, "oninstalled", "onupdated", "onuninstalled", NULL); + + CallbackUserData *oninstalledCb = NULL; + CallbackUserData *onupdatedCb = NULL; + CallbackUserData *onuninstalledCb = NULL; + + JSValueRef oninstalled = JSUtil::getProperty(context, eventCBObj, "oninstalled", exception); + if (!JSValueIsUndefined(context, oninstalled)) { + oninstalledCb = new CallbackUserData(GlobalContextManager::getInstance()->getGlobalContext(context)); + oninstalledCb->setSuccessCallback(oninstalled); + } + + JSValueRef onupdated = JSUtil::getProperty(context, eventCBObj, "onupdated", exception); + if (!JSValueIsUndefined(context, onupdated)) { + onupdatedCb = new CallbackUserData(GlobalContextManager::getInstance()->getGlobalContext(context)); + onupdatedCb->setSuccessCallback(onupdated); + } + + JSValueRef onuninstalled = JSUtil::getProperty(context, eventCBObj, "onuninstalled", exception); + if (!JSValueIsUndefined(context, onuninstalled)) { + onuninstalledCb = new CallbackUserData(GlobalContextManager::getInstance()->getGlobalContext(context)); + onuninstalledCb->setSuccessCallback(onuninstalled); + } + + PackageInfoEventCallback *pkginfoEventCB = new PackageInfoEventCallback(oninstalledCb, onupdatedCb, onuninstalledCb); + + PackageManager::getInstance()->setPackageInfoEventListener(pkginfoEventCB); + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); + + } catch (const BasePlatformException &err) { + return JSWebAPIErrorFactory::postException(context, exception, err); + } catch (...) { + DeviceAPI::Common::UnknownException err("Unknown Error in ApplicationManager.getAppSharedURI()."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } +} + +JSValueRef JSPackageManager::unsetPackageInfoEventListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + + TIME_TRACER_ITEM_BEGIN("(unsetPackageInfoEventListener) ACE", 0); + AceSecurityStatus status = PACKAGE_CHECK_ACCESS(PACKAGE_FUNCTION_API_UNSET_PACKAGE_INFO_EVENT_LISTENER); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + TIME_TRACER_ITEM_END("(unsetPackageInfoEventListener) ACE", 0); + + try { + PackageManager::getInstance()->unsetPackageInfoEventListener(); + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); + + } catch(const BasePlatformException& err) { + return JSWebAPIErrorFactory::postException(context, exception, err); + } +} + + +#if 0 +JSValueRef JSPackageManager::move(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + + //AceSecurityStatus status = PACKAGE_CHECK_ACCESS(PACKAGE_FUNCTION_API_MOVE); + //TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + Try { + Converter converter(context); + JSValueRef checkedArguments[4]; + + ArgumentValidationChecker::check(context, argumentCount, arguments, 4, checkedArguments, + ArgumentValidationChecker::MANDATORY, ArgumentValidationChecker::String, + ArgumentValidationChecker::MANDATORY, ArgumentValidationChecker::String, + ArgumentValidationChecker::MANDATORY | ArgumentValidationChecker::NULLABLE, ArgumentValidationChecker::Object, + ArgumentValidationChecker::OPTIONAL | ArgumentValidationChecker::NULLABLE, ArgumentValidationChecker::Function, + ArgumentValidationChecker::END); + + string id = converter.toString(checkedArguments[0]); + string storage = converter.toString(checkedArguments[1]); + if ((storage.compare("EXTERNAL") != 0) && (storage.compare("INTERNAL") != 0)) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Wrong second parameter type"); + } + + JSObjectRef eventCBObj = converter.toJSObjectRef(arguments[2]); + JSValueRef onprogress = JSUtils::getJSPropertyOrUndefined(context, eventCBObj, "onprogress"); + JSValueRef oncomplete = JSUtils::getJSPropertyOrUndefined(context, eventCBObj, "oncomplete"); + + if (!JSObjectIsFunction(context, converter.toJSObjectRef(onprogress)) || + !JSObjectIsFunction(context, converter.toJSObjectRef(oncomplete))) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Wrong third parameter type"); + } + + CallbackUserData *onprogressCb = new CallbackUserData(GlobalContextManager::getInstance()->getGlobalContext(context)); + onprogressCb->setSuccessCallback(onprogress); + + CallbackUserData *oncompleteCb = new CallbackUserData(GlobalContextManager::getInstance()->getGlobalContext(context)); + oncompleteCb->setSuccessCallback(oncomplete); + + if (argumentCount > 2) { + oncompleteCb->setErrorCallback(checkedArguments[3]); + } + + PackageInstallEventCallback *pkgInstallEventCB = new PackageInstallEventCallback(onprogressCb, oncompleteCb); + + PackageManager::getInstance()->move(id, storage, pkgInstallEventCB); + + } Catch (NotFoundException) { + LoggerE("Exception: "<<_rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_FOUND_ERROR, _rethrown_exception.GetMessage()); + } Catch (ConversionException) { + LoggerE("Exception: "<<_rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, _rethrown_exception.GetMessage()); + } Catch (Exception) { + LoggerE("Exception: "<<_rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, _rethrown_exception.GetMessage()); + } + + return JSValueMakeUndefined(context); +} + + +JSValueRef JSPackageManager::isInstalled(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //AceSecurityStatus status = PACKAGE_CHECK_ACCESS(PACKAGE_FUNCTION_API_IS_INSTALLED); + //TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + // Should I change first parameter to "undefined" or throw exception??? + if (argumentCount < 1) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "wrong parameter"); + } + + Try { + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + string id = converter.toString(arguments[0]); + + return converter.toJSValueRef(PackageManager::getInstance()->isInstalled(id)); + } Catch (NotFoundException) { + LoggerE("Exception: "<<_rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_FOUND_ERROR, _rethrown_exception.GetMessage()); + } Catch (ConversionException) { + LoggerE("Exception: "<<_rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, _rethrown_exception.GetMessage()); + } Catch (Exception) { + LoggerE("Exception: "<<_rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, _rethrown_exception.GetMessage()); + } + + return false; +} + +JSValueRef JSPackageManager::getPackageIdFromAppId(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + //AceSecurityStatus status = PACKAGE_CHECK_ACCESS(PACKAGE_FUNCTION_API_GET_PACKAGE_ID_FROM_APP_ID); + //TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + Try { + WrtDeviceApis::CommonsJavaScript::Converter converter(context); + string id; + if (argumentCount > 0) { + id = converter.toString(arguments[0]); + } else { + id = "undefined"; + } + + return converter.toJSValueRef(PackageManager::getInstance()->getPackageIdFromAppId(id)); + } Catch (NotFoundException) { + LoggerE("Exception: "<<_rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_FOUND_ERROR, _rethrown_exception.GetMessage()); + } Catch (ConversionException) { + LoggerE("Exception: "<<_rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, _rethrown_exception.GetMessage()); + } Catch (Exception) { + LoggerE("Exception: "<<_rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, _rethrown_exception.GetMessage()); + } + + return JSValueMakeUndefined(context); +} + +#endif + + +} +} diff --git a/wearable_src/Package/JSPackageManager.h b/wearable_src/Package/JSPackageManager.h new file mode 100644 index 0000000..0c40ed7 --- /dev/null +++ b/wearable_src/Package/JSPackageManager.h @@ -0,0 +1,123 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 _TIZEN_JS_PACKAGE_MANAGER_H_ +#define _TIZEN_JS_PACKAGE_MANAGER_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/PrivateObject.h> + +namespace DeviceAPI { +namespace Package { + +#define TIZEN_INTERFACE_PACKAGE_MANAGER "PackageManager" + +class JSPackageManager { +public: + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + + //static void setTitleProperty(JSContextRef context, std::string propertyValue); + +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); + + /** + * Install an package + */ + static JSValueRef install(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + /** + * Uninstall an package + */ + static JSValueRef uninstall(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + + /** + * Gets the list of installed packages. + */ + static JSValueRef getPackagesInfo(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + /** + * Gets the package information of based on the package ID. + */ + static JSValueRef getPackageInfo(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + + /** + * Watch for package installation & uninstallation. + */ + static JSValueRef setPackageInfoEventListener(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + /** + * Unset watch for installation & uninstallation + */ + static JSValueRef unsetPackageInfoEventListener(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + +#if 0 + /** + * move an package + */ + static JSValueRef move(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + + /** + * Check whether It is installed or not + */ + static JSValueRef isInstalled(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); + + + /** + * Gets the package ID from application ID + */ + static JSValueRef getPackageIdFromAppId(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], JSValueRef* exception); +#endif + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + static JSClassRef m_jsClassRef; +}; + +} +} +#endif diff --git a/wearable_src/Package/PackageInformation.cpp b/wearable_src/Package/PackageInformation.cpp new file mode 100644 index 0000000..e343e1a --- /dev/null +++ b/wearable_src/Package/PackageInformation.cpp @@ -0,0 +1,67 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 <package-manager.h> + +#include "PackageInformation.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Package { + +PackageInformation::PackageInformation() : + m_isInitialized(false) +{ +} + +PackageInformation::~PackageInformation() +{ +} + +void PackageInformation::initializePackageInfo() +{ + LoggerD("Enter : " << m_id); + + pkgmgr_client *pc = pkgmgr_client_new(PC_REQUEST); + if (pc == NULL) { + LoggerE("Fail to create pkgmgr client"); + } else { + int ret = pkgmgr_client_request_service(PM_REQUEST_GET_SIZE, PM_GET_TOTAL_SIZE, pc, NULL, m_id.c_str(), NULL, NULL, NULL); + if (ret < 0) { + LoggerE("Fail to get total size"); + } else { + m_totalSize = ret; + } + + ret = pkgmgr_client_request_service(PM_REQUEST_GET_SIZE, PM_GET_DATA_SIZE, pc, NULL, m_id.c_str(), NULL, NULL, NULL); + if (ret < 0) { + LoggerE("Fail to get data size"); + } else { + m_dataSize = ret; + } + + LoggerD("Before pkgmgr_client_free"); + pkgmgr_client_free(pc); + LoggerD("After pkgmgr_client_free"); + pc = NULL; + } + + m_isInitialized = true; +} + +} +} diff --git a/wearable_src/Package/PackageInformation.h b/wearable_src/Package/PackageInformation.h new file mode 100644 index 0000000..37613e6 --- /dev/null +++ b/wearable_src/Package/PackageInformation.h @@ -0,0 +1,53 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 _TIZEN_PACKAGE_INFORMATION_H_ +#define _TIZEN_PACKAGE_INFORMATION_H_ + +#include <string> +#include <vector> + +namespace DeviceAPI { +namespace Package { + +using namespace std; + +class PackageInformation +{ +public: + PackageInformation(); + ~PackageInformation(); + void initializePackageInfo(); + +public: + string m_id; + string m_name; + string m_iconPath; + string m_version; + time_t m_lastModified; + long m_totalSize; + long m_dataSize;; + string m_author; + string m_type; + string m_description; + vector<string> m_appIds; + bool m_isInitialized; +}; + +} +} +#endif diff --git a/wearable_src/Package/PackageManager.cpp b/wearable_src/Package/PackageManager.cpp new file mode 100644 index 0000000..a90141a --- /dev/null +++ b/wearable_src/Package/PackageManager.cpp @@ -0,0 +1,885 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 <glib.h> + +#include <JSWebAPIErrorFactory.h> +#include <GlobalContextManager.h> +#include <PlatformException.h> + +// to get package name by appid +#include <app_manager.h> + +// To get cert information from package +#include <package_manager.h> +#include <package_info.h> + +// To get app size and installed time +#include <pkgmgr-info.h> + +// To use ecore_thread +#include <Ecore.h> + +#include "PackageManager.h" +#include "PackageInformation.h" +#include "JSPackageInformation.h" + +#include <TimeTracer.h> + +#include <Logger.h> + +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace DeviceAPI::Common; + +using namespace std; + +#ifdef __cplusplus +extern "C" { +int package_manager_client_destroy(package_manager_request_h request); +} +#endif + +namespace DeviceAPI { +namespace Package { + +PackageInfoCallbackData::PackageInfoCallbackData(JSContextRef globalCtx): + CallbackUserData(globalCtx) +{ + m_exceptionCode = WrtDeviceApis::Commons::ExceptionCodes::None; +} + +PackageInfoCallbackData::~PackageInfoCallbackData() +{ + // TODO: Should I clear pkgInfos? +} + +vector<PackageInformation> PackageInfoCallbackData::getPackageInfoList() +{ + return m_pkgInfos; +} + + +void PackageInfoCallbackData::addPackageInfo(PackageInformation pkgInfo) +{ + m_pkgInfos.push_back(pkgInfo); +} + + +void PackageInfoCallbackData::setExceptionCode(ExceptionCodes::Enumeration exceptionCode) +{ + m_exceptionCode = exceptionCode; +} + +ExceptionCodes::Enumeration PackageInfoCallbackData::getExceptionCode() const +{ + return m_exceptionCode; +} + +PackageInfoEventCallback::PackageInfoEventCallback(CallbackUserData* oninstalled, CallbackUserData* onupdated, CallbackUserData* onuninstalled) +{ + m_oninstalled = oninstalled; + m_onupdated = onupdated; + m_onuninstalled = onuninstalled; + m_handle_p = NULL; +} + +PackageInfoEventCallback::~PackageInfoEventCallback() +{ + if (m_oninstalled) + delete m_oninstalled; + + if (m_onupdated) + delete m_onupdated; + + if (m_onuninstalled) + delete m_onuninstalled; +} + +CallbackUserData* PackageInfoEventCallback::getOnInstalled() +{ + return m_oninstalled; +} + +CallbackUserData* PackageInfoEventCallback::getOnUpdated() +{ + return m_onupdated; +} + +CallbackUserData* PackageInfoEventCallback::getOnUninstalled() +{ + return m_onuninstalled; +} + +pkgmgr_client** PackageInfoEventCallback::getEventHandler() +{ + return m_handle_p; +} + +void PackageInfoEventCallback::setEventHandler(pkgmgr_client **handler) +{ + m_handle_p = handler; +} + +PackageInstallEventCallback::PackageInstallEventCallback(JSContextRef globalCtx, CallbackUserData* onprogress, CallbackUserData* oncomplete, CallbackUserData* onerror) +{ + m_context = globalCtx; + m_onprogress = onprogress; + m_oncomplete = oncomplete; + m_onerror = onerror; + + m_request_handle = NULL; +} + +PackageInstallEventCallback::~PackageInstallEventCallback() +{ + if (m_request_handle != NULL) { + //package_manager_request_destroy(m_request_handle); + package_manager_client_destroy(m_request_handle); + } + + if (m_onprogress) + delete m_onprogress; + + if (m_oncomplete) + delete m_oncomplete; + + if (m_onerror) + delete m_onerror; +} + +CallbackUserData* PackageInstallEventCallback::getOnProgress() +{ + return m_onprogress; +} + +CallbackUserData* PackageInstallEventCallback::getOnComplete() +{ + return m_oncomplete; +} + +CallbackUserData* PackageInstallEventCallback::getOnError() +{ + return m_onerror; +} + +JSContextRef PackageInstallEventCallback::getContext() +{ + return m_context; +} + +void PackageInstallEventCallback::setHandle(package_manager_request_h handle) +{ + m_request_handle = handle; +} + +package_manager_request_h PackageInstallEventCallback::getHandle() +{ + return m_request_handle; +} + +static int get_current_pkg_id(char** pkg_id) +{ + app_info_h handle; + + string appId = PackageManager::getInstance()->getCurrentAppId(); + + int ret = app_manager_get_app_info(appId.c_str(), &handle); + if (ret != APP_MANAGER_ERROR_NONE) { + LoggerE("Fail to get appinfo"); + return ret; + } + + ret = app_info_get_package(handle, pkg_id); + if ((ret != APP_MANAGER_ERROR_NONE) || (*pkg_id == NULL)) { + LoggerE("Fail to get pkg_id"); + app_info_destroy(handle); + return ret; + } + + ret = app_info_destroy(handle); + if (ret != APP_MANAGER_ERROR_NONE) { + LoggerE("Fail to get destory appinfo"); + return ret; + } + + return ret; +} + +static bool app_callback(package_info_app_component_type_e comp_type, const char *app_id, void *user_data) +{ + PackageInformation* pkgInfo = (PackageInformation*)user_data; + pkgInfo->m_appIds.push_back(app_id); + return true; +} + +static PackageInformation* create_pkg_info(pkgmgrinfo_pkginfo_h handle) +{ + PackageInformation *pkgInfo = new PackageInformation(); + + char* id = NULL; + char* name = NULL; + char* iconPath = NULL; + char* version = NULL; + int lastModified = 0; + char* type = NULL; + char* author = NULL; + char* description = NULL; + vector<string> appIds; + int ret = 0; + + ret = pkgmgrinfo_pkginfo_get_pkgid(handle, &id); + if ((ret != PMINFO_R_OK) || (id == NULL)) { + LoggerE("Fail to get id. return NULL."); + delete pkgInfo; + return NULL; + } else { + pkgInfo->m_id = id; + } + + ret = pkgmgrinfo_pkginfo_get_label(handle, &name); + if ((ret != PMINFO_R_OK) || (name == NULL)) { + LoggerE("Fail to get labe"); + } else { + pkgInfo->m_name = name; + } + + ret = pkgmgrinfo_pkginfo_get_icon(handle, &iconPath); + if ((ret != PMINFO_R_OK) || (iconPath == NULL)) { + LoggerE("Fail to get iconPath"); + } else { + pkgInfo->m_iconPath = iconPath; + } + + ret = pkgmgrinfo_pkginfo_get_version(handle, &version); + if ((ret != PMINFO_R_OK) || (version == NULL)) { + LoggerE("Fail to get version"); + } else { + pkgInfo->m_version = version; + } + + ret = pkgmgrinfo_pkginfo_get_installed_time(handle, &lastModified); + if (ret != PMINFO_R_OK) { + LoggerE("Fail to get lastModified"); + } else { + pkgInfo->m_lastModified = lastModified; + } + + ret = pkgmgrinfo_pkginfo_get_type(handle, &type); + if ((ret != PMINFO_R_OK) || (type == NULL)) { + LoggerE("Fail to get type"); + } else { + pkgInfo->m_type = type; + } + + ret = pkgmgrinfo_pkginfo_get_author_name(handle, &author); + if ((ret != PMINFO_R_OK) || (author == NULL)) { + LoggerE("Fail to get author"); + } else { + pkgInfo->m_author = author; + } + + ret = pkgmgrinfo_pkginfo_get_description(handle, &description); + if ((ret != PMINFO_R_OK) || (description == NULL)) { + LoggerE("Fail to get description"); + } else { + pkgInfo->m_description = description; + } + + package_info_h package_info; + + ret = package_manager_get_package_info(id, &package_info); + if (ret != PACKAGE_MANAGER_ERROR_NONE) { + LoggerE("Cannot create package info"); + delete pkgInfo; + return NULL; + } + + ret = package_info_foreach_app_from_package(package_info, PACKAGE_INFO_ALLAPP, app_callback, (void*)pkgInfo); + if (ret != PACKAGE_MANAGER_ERROR_NONE) { + LoggerE("failed while getting appids"); + } + + ret = package_info_destroy(package_info); + if (ret != PACKAGE_MANAGER_ERROR_NONE) { + LoggerE("Cannot destroy package info"); + } + + // REMARK: data size and total size is set at first access time + + // REMARK: do not destroy handle. because handle is comes from outside!! + return pkgInfo; +} + +static gboolean getCompleteCB(void *data) +{ + PackageInfoCallbackData *callback = (PackageInfoCallbackData *)data; + JSContextRef context = callback->getContext(); + + if (callback->getExceptionCode() == WrtDeviceApis::Commons::ExceptionCodes::None) { + vector<PackageInformation> pkgInfoList = callback->getPackageInfoList(); + + JSObjectRef jsResult = JSCreateArrayObject(context, 0, NULL); + if (jsResult == NULL) { + JSValueRef error = JSWebAPIErrorFactory::makeErrorObject(callback->getContext(), JSWebAPIErrorFactory::UNKNOWN_ERROR, "platform exception"); + callback->callErrorCallback(error); + return false; + } + + for (size_t i = 0; i < pkgInfoList.size(); ++i) { + JSValueRef tmpVal = JSPackageInformation::createJSObject(context, &pkgInfoList[i]); + if (!JSSetArrayElement(context, jsResult, i, tmpVal)) { + JSValueRef error = JSWebAPIErrorFactory::makeErrorObject(callback->getContext(), JSWebAPIErrorFactory::UNKNOWN_ERROR, "platform exception"); + callback->callErrorCallback(error); + return false; + } + } + + callback->callSuccessCallback(jsResult); + } else { + JSValueRef error = JSWebAPIErrorFactory::makeErrorObject(callback->getContext(), JSWebAPIErrorFactory::UNKNOWN_ERROR, "platform exception"); + callback->callErrorCallback(error); + } + + delete callback; + + return false; +} + +static int get_package_list_cb(pkgmgrinfo_pkginfo_h handle, void *user_data) +{ + PackageInfoCallbackData *callback = (PackageInfoCallbackData *)user_data; + PackageInformation* pkgInfo = create_pkg_info(handle); + if (pkgInfo != NULL) { + callback->addPackageInfo(*pkgInfo); + delete pkgInfo; + } else { + LoggerE("Fail to get pkgInfo"); + } + return 0; +} + +static void getThreadCB(void *data, Ecore_Thread *thread) +{ + PackageInfoCallbackData *callback = (PackageInfoCallbackData *)data; + + int ret = pkgmgrinfo_pkginfo_get_list(get_package_list_cb, data); + if (ret != PMINFO_R_OK) { + LoggerE("Fail to get package info"); + callback->setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::PlatformException); + } + + // the operation of ecore_thread_run() is not normal. (the finish callback is not called from main thread.) + // so, add complete callback to gmainloop explicitly. + g_idle_add(getCompleteCB, data); +} + + +static void package_event_cb(app_manger_event_type_e event_type, const char *package, void *user_data) +{ + PackageInfoEventCallback *eventCB = (PackageInfoEventCallback *)user_data; + + switch(event_type) { + case APP_MANAGER_EVENT_INSTALLED: { + pkgmgrinfo_pkginfo_h handle; + int ret = pkgmgrinfo_pkginfo_get_pkginfo(package, &handle); + if (ret != PMINFO_R_OK) { + LoggerE("fail to find pkg info with given pkg"); + // Do not throw exception. No one can handle exception because this code is called from async callback. + //throw NotFoundException("Can't find given package"); + break; + } + + PackageInformation* pkgInfo = create_pkg_info(handle); + pkgmgrinfo_appinfo_destroy_appinfo(handle); + + if (pkgInfo == NULL) { + LoggerE("Fail to get pkg info. skip callback call"); + } else { + CallbackUserData *callback = eventCB->getOnInstalled(); + if (callback) { + callback->callSuccessCallback(JSPackageInformation::createJSObject(callback->getContext(), pkgInfo)); + } + } + break; + } + case APP_MANAGER_EVENT_UNINSTALLED: { + CallbackUserData *callback = eventCB->getOnUninstalled(); + if (callback) { + Converter converter(callback->getContext()); + callback->callSuccessCallback(converter.toJSValueRef(package)); + } + break; + } + case APP_MANAGER_EVENT_UPDATED: { + pkgmgrinfo_pkginfo_h handle; + int ret = pkgmgrinfo_pkginfo_get_pkginfo(package, &handle); + if (ret != PMINFO_R_OK) { + // Do not throw exception. No one can handle exception because this code is called from async callback. + //throw NotFoundException("Can't find given package"); + break; + } + + PackageInformation* pkgInfo = create_pkg_info(handle); + pkgmgrinfo_appinfo_destroy_appinfo(handle); + + if (pkgInfo == NULL) { + LoggerE("Fail to get pkg info. skip callback call"); + } else { + CallbackUserData *callback = eventCB->getOnUpdated(); + if (callback) { + callback->callSuccessCallback(JSPackageInformation::createJSObject(callback->getContext(), pkgInfo)); + } + } + break; + } + default: + LoggerE("Fail!! Unknown event type is entered : " << event_type); + break; + } + + +} + +static int app_list_changed_cb_broker(int id, const char *type, const char *package, const char *key, const char *val, const void *msg, void *data) +{ + static app_manger_event_type_e event_type; + + if (!strcasecmp(key, "start")) + { + LoggerD("start "); + if (!strcasecmp(val, "install")) + { + event_type = APP_MANAGER_EVENT_INSTALLED; + } + else if (!strcasecmp(val, "uninstall")) + { + event_type = APP_MANAGER_EVENT_UNINSTALLED; + } + else if (!strcasecmp(val, "update")) + { + event_type = APP_MANAGER_EVENT_UPDATED; + } + } + else if (!strcasecmp(key, "end") && !strcasecmp(val, "ok")) + { + LoggerD("end "); + if (event_type >= 0) + { + package_event_cb(event_type, package, data); + + // Check whether handler is freed in the callback function or not. + // if freed, return error code to avoid iteration of callback function. (core platform side) + PackageInfoEventCallback * callback = (PackageInfoEventCallback *)data; + pkgmgr_client ** handler_p = callback->getEventHandler(); + if (*handler_p == NULL) { + LoggerE("handler is NULL"); + return -1; + } + LoggerE("handler is not NULL"); + } + } + + return 0; +} + + +void install_request_cb(int id, const char *type, const char *package, + package_manager_event_type_e event_type, + package_manager_event_state_e event_state, + int progress, + package_manager_error_e error, + void *user_data) +{ + PackageInstallEventCallback *callback = (PackageInstallEventCallback *)user_data; + JSContextRef context = callback->getContext();; + + switch (event_state) { + case PACAKGE_MANAGER_EVENT_STATE_COMPLETED: { + if (callback->getOnComplete()) { + Converter converter(context); + callback->getOnComplete()->callSuccessCallback(converter.toJSValueRef(package)); + } + + LoggerD("destroy client handle"); + // this api is not supported from platform. + //package_manager_request_destroy(callback->getHandle()); + package_manager_client_destroy(callback->getHandle()); + callback->setHandle(NULL); + + //clean-up callback object + delete callback; + + break; + } + case PACAKGE_MANAGER_EVENT_STATE_FAILED: { + JSValueRef jsError = NULL; + if (error == PACKAGE_MANAGER_ERROR_NO_SUCH_PACKAGE) { + jsError = JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::NOT_FOUND_ERROR,"given package is not found"); + } else { + jsError = JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::UNKNOWN_ERROR,"platform exception"); + } + + if (callback->getOnError()) { + callback->getOnError()->callSuccessCallback(jsError); + } + + LoggerD("destroy client handle"); + // this api is not supported from platform. + //package_manager_request_destroy(callback->getHandle()); + package_manager_client_destroy(callback->getHandle()); + callback->setHandle(NULL); + + //clean-up callback object + delete callback; + + break; + } + case PACAKGE_MANAGER_EVENT_STATE_STARTED: + case PACAKGE_MANAGER_EVENT_STATE_PROCESSING: { + if (callback->getOnProgress() && package && package[0]!='\0') { + Converter converter(context); + JSValueRef args[2] = {converter.toJSValueRef(package), converter.toJSValueRef(progress)}; + callback->getOnProgress()->callSuccessCallback(2, args); + } + break; + } + default: + JSValueRef error = JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::UNKNOWN_ERROR,"platform exception"); + if (callback->getOnError()) { + callback->getOnError()->callSuccessCallback(error); + } + LoggerD("destroy client handle"); + // this api is not supported from platform. + //package_manager_request_destroy(callback->getHandle()); + package_manager_client_destroy(callback->getHandle()); + callback->setHandle(NULL); + + //clean-up callback object + delete callback; + + break; + } + +} + +static string ltrim(const string s) +{ + string str = s; + string::iterator i; + for (i = str.begin(); i != str.end(); i++) { + if (!isspace(*i)) { + break; + } + } + if (i == str.end()) { + str.clear(); + } else { + str.erase(str.begin(), i); + } + return str; +} + + +static string convertUriToPath(const string str) +{ + string result; + string schema ("file://"); + string _str = ltrim(str); + + string _schema = _str.substr(0,schema.size()); + if(_schema == schema) { + result = _str.substr(schema.size()); + } else { + result = _str; + } + return result; +} + + +void PackageManager::install(string pkgPath, PackageInstallEventCallback* callback) +{ + int ret = 0; + int id = 0; + package_manager_request_h request_h; + JSContextRef globalCtx = callback->getContext(); + CallbackUserData* errCallback = callback->getOnError(); + + ret = package_manager_request_create(&request_h); + if (ret != PACKAGE_MANAGER_ERROR_NONE) { + if (errCallback) { + JSValueRef error = + JSWebAPIErrorFactory::makeErrorObject(globalCtx, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Platform Error"); + errCallback->callSuccessCallback(error); + } + delete callback; + return; + } + + ret = package_manager_request_install(request_h, convertUriToPath(pkgPath).c_str(), &id); + if (ret != PACKAGE_MANAGER_ERROR_NONE) { + if (errCallback) { + JSValueRef error = + JSWebAPIErrorFactory::makeErrorObject(globalCtx, JSWebAPIErrorFactory::NOT_FOUND_ERROR, "Not proper file"); + errCallback->callSuccessCallback(error); + } + delete callback; + return; + } + + callback->setHandle(request_h); + + ret = package_manager_request_set_event_cb(request_h, install_request_cb, callback); + if (ret != PACKAGE_MANAGER_ERROR_NONE) { + if (errCallback) { + JSValueRef error = + JSWebAPIErrorFactory::makeErrorObject(globalCtx, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Platform Error"); + errCallback->callSuccessCallback(error); + } + delete callback; + return; + } +} + +void PackageManager::uninstall(string pkgPath, PackageInstallEventCallback* callback) +{ + int ret = 0; + int id = 0; + package_manager_request_h request_h; + JSContextRef globalCtx = callback->getContext(); + CallbackUserData* errCallback = callback->getOnError(); + + ret = package_manager_request_create(&request_h); + if (ret != PACKAGE_MANAGER_ERROR_NONE) { + if (errCallback) { + JSValueRef error = + JSWebAPIErrorFactory::makeErrorObject(globalCtx, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Platform Error"); + errCallback->callSuccessCallback(error); + } + //clean-up callback object + delete callback; + return; + } + + ret = package_manager_request_uninstall(request_h, pkgPath.c_str(), &id); + if (ret != PACKAGE_MANAGER_ERROR_NONE) { + if (errCallback) { + JSValueRef error = + JSWebAPIErrorFactory::makeErrorObject(globalCtx, JSWebAPIErrorFactory::NOT_FOUND_ERROR, "Not proper file"); + // TODO: how can I handle about uninstallable package??? + errCallback->callSuccessCallback(error); + } + //clean-up callback object + delete callback; + return; + } + + callback->setHandle(request_h); + + ret = package_manager_request_set_event_cb(request_h, install_request_cb, callback); + if (ret != PACKAGE_MANAGER_ERROR_NONE) { + if (errCallback) { + JSValueRef error = + JSWebAPIErrorFactory::makeErrorObject(globalCtx, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Platform Error"); + errCallback->callSuccessCallback(error); + } + //clean-up callback object + delete callback; + return; + } +} + + +PackageInformation* PackageManager::getPackageInfo(string pkgId) +{ + if (pkgId.empty() || !pkgId.compare("null")) { + char *pkg_id = NULL; + + TIME_TRACER_ITEM_BEGIN("(getPackageInfo) get_current_pkg_id", 0); + int ret = get_current_pkg_id(&pkg_id); + TIME_TRACER_ITEM_END("(getPackageInfo) get_current_pkg_id", 0); + if((ret != APP_MANAGER_ERROR_NONE) || (pkg_id == NULL)) { + LoggerE("Can not get app id from current pid"); + throw NotFoundException("Can't find given package"); + } + pkgId = pkg_id; + free(pkg_id); + } + + pkgmgrinfo_pkginfo_h handle; + TIME_TRACER_ITEM_BEGIN("(getPackageInfo) pkgmgrinfo_pkginfo_get_pkginfo", 0); + int ret = pkgmgrinfo_pkginfo_get_pkginfo(pkgId.c_str(), &handle); + TIME_TRACER_ITEM_END("(getPackageInfo) pkgmgrinfo_pkginfo_get_pkginfo", 0); + if (ret != PMINFO_R_OK) { + throw NotFoundException("Can't find given package"); + } + + TIME_TRACER_ITEM_BEGIN("(getPackageInfo) create_pkg_info", 0); + PackageInformation* pkgInfo = create_pkg_info(handle); + TIME_TRACER_ITEM_END("(getPackageInfo) create_pkg_info", 0); + pkgmgrinfo_appinfo_destroy_appinfo(handle); + + if (pkgInfo == NULL) { + throw UnknownException("Can't get pkg info from given package"); + } + + return pkgInfo; +} + + +void PackageManager::getPackagesInfo(PackageInfoCallbackData *user_data) +{ + // getting info of all package from other thread. the result callback will be called on main thread + ecore_thread_run(getThreadCB, NULL, NULL, user_data); +} + + +void PackageManager::setPackageInfoEventListener(PackageInfoEventCallback * eventCB) +{ + if (m_manager_handle == NULL) { + TIME_TRACER_ITEM_BEGIN("(setPackageInfoEventListener) pkgmgr_client_new", 0); + m_manager_handle = pkgmgr_client_new(PC_LISTENING); + TIME_TRACER_ITEM_END("(setPackageInfoEventListener) pkgmgr_client_new", 0); + if (m_manager_handle == NULL) { + throw UnknownException("Fail to create package manager handle"); + } + } + + eventCB->setEventHandler(&m_manager_handle); + + TIME_TRACER_ITEM_BEGIN("(setPackageInfoEventListener) pkgmgr_client_listen_status", 0); + pkgmgr_client_listen_status(m_manager_handle, app_list_changed_cb_broker, eventCB); + TIME_TRACER_ITEM_END("(setPackageInfoEventListener) pkgmgr_client_listen_status", 0); +} + +void PackageManager::unsetPackageInfoEventListener() +{ + if (m_manager_handle == NULL) { + LoggerE("no package manager handle registered"); + return; + } + + TIME_TRACER_ITEM_BEGIN("(unsetPackageInfoEventListener) pkgmgr_client_free", 0); + pkgmgr_client_free(m_manager_handle); + TIME_TRACER_ITEM_END("(unsetPackageInfoEventListener) pkgmgr_client_free", 0); + m_manager_handle = NULL; +} + +PackageManager* PackageManager::getInstance() +{ + static PackageManager instance; + return &instance; +} + +void PackageManager::setCurrentAppId(string appId) +{ + m_curr_app_id = appId; +} + +string PackageManager::getCurrentAppId() const +{ + return m_curr_app_id; +} + +PackageManager::PackageManager() +{ +} + +PackageManager::~PackageManager() +{ + if (m_manager_handle != NULL) { + pkgmgr_client_free(m_manager_handle); + m_manager_handle = NULL; + } + +} + + +// candidate apis +#if 0 +void PackageManager::move(string pkgPath, string target, PackageInstallEventCallback* callback) +{ + int ret = 0; + package_manager_move_type_e type = PACAKGE_MANAGER_REQUEST_MOVE_TO_INTERNAL; + + if (target.compare("INTERNAL") == 0) { + type = PACAKGE_MANAGER_REQUEST_MOVE_TO_INTERNAL; + } else { + type = PACAKGE_MANAGER_REQUEST_MOVE_TO_EXTERNAL; + } + // compare current storage and target storage + + package_manager_request_h request_h; + + ret = package_manager_request_create(&request_h); + if (ret != PACKAGE_MANAGER_ERROR_NONE) { + ThrowMsg(PlatformException, "Unknow exception is occured!!"); + } + + ret = package_manager_request_move(request_h, pkgPath.c_str(), type); + if (ret != PACKAGE_MANAGER_ERROR_NONE) { + ThrowMsg(PlatformException, "Unknow exception is occured!!"); + } + + callback->setHandle(request_h); + + ret = package_manager_request_set_event_cb(request_h, install_request_cb, callback); + if (ret != PACKAGE_MANAGER_ERROR_NONE) { + ThrowMsg(PlatformException, "Unknow exception is occured!!"); + } +} + +bool PackageManager::isInstalled(string pkgId) +{ + package_info_h handle; + int ret = 0; + + ret = package_manager_get_package_info(pkgId.c_str(), &handle); + if (ret == PACKAGE_MANAGER_ERROR_NO_SUCH_PACKAGE) { + return false; + } else if (ret == PACKAGE_MANAGER_ERROR_NONE) { + // TODO: Should I exception handling while destory handle? what should I do for that time? + package_info_destroy(handle); + return true; + } else { + ThrowMsg(PlatformException, "Unknow exception is occured!!"); + } +} + +string PackageManager::getPackageIdFromAppId(string appId) +{ + char *pkg_id = NULL; + string pkgId; + int ret = 0; + + ret = package_manager_get_package_id_by_app_id(appId.c_str(), &pkg_id); + if (ret != PACKAGE_MANAGER_ERROR_NONE) { + ThrowMsg(NotFoundException, "Not found pkg"); + } + + pkgId = pkg_id; + if (pkg_id) + free(pkg_id); + + return pkgId; + +} +#endif + + +} +} diff --git a/wearable_src/Package/PackageManager.h b/wearable_src/Package/PackageManager.h new file mode 100644 index 0000000..b78e1bb --- /dev/null +++ b/wearable_src/Package/PackageManager.h @@ -0,0 +1,136 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 _TIZEN_PACKAGE_MANAGER_H_ +#define _TIZEN_PACKAGE_MANAGER_H_ + +#include <string> +#include <list> +#include <CallbackUserData.h> +#include <CommonsJavaScript/Converter.h> +#include <JavaScriptCore/JavaScript.h> +#include <Commons/Exception.h> + +#include <package_manager.h> +#include <package-manager.h> + +#include "PackageInformation.h" + +namespace DeviceAPI { +namespace Package { + +using namespace WrtDeviceApis::Commons; +using namespace DeviceAPI::Common; +using namespace std; + +class PackageInfoCallbackData : public CallbackUserData +{ +public: + PackageInfoCallbackData(JSContextRef globalCtx); + ~PackageInfoCallbackData(); + + vector<PackageInformation> getPackageInfoList(); + void addPackageInfo(PackageInformation pkgInfo); + + void setExceptionCode(ExceptionCodes::Enumeration exceptionCode); + ExceptionCodes::Enumeration getExceptionCode() const; + +public: + pkgmgr_client *pc; + +private: + vector<PackageInformation> m_pkgInfos; + ExceptionCodes::Enumeration m_exceptionCode; +}; + + +class PackageInfoEventCallback +{ +public: + PackageInfoEventCallback(CallbackUserData* oninstalled, CallbackUserData* onupdated, CallbackUserData* onuninstalled); + ~PackageInfoEventCallback(); + CallbackUserData* getOnInstalled(); + CallbackUserData* getOnUpdated(); + CallbackUserData* getOnUninstalled(); + pkgmgr_client ** getEventHandler(); + void setEventHandler(pkgmgr_client **handle_p); + +private: + CallbackUserData* m_oninstalled; + CallbackUserData* m_onupdated; + CallbackUserData* m_onuninstalled; + pkgmgr_client **m_handle_p; +}; + +class PackageInstallEventCallback +{ +public: + PackageInstallEventCallback(JSContextRef globalCtx, CallbackUserData* onprogress, CallbackUserData* oncomplete, CallbackUserData* onerror); + ~PackageInstallEventCallback(); + CallbackUserData* getOnProgress(); + CallbackUserData* getOnComplete(); + CallbackUserData* getOnError(); + JSContextRef getContext(); + void setHandle(package_manager_request_h handle); + package_manager_request_h getHandle(); + +private: + CallbackUserData* m_onprogress; + CallbackUserData* m_oncomplete; + CallbackUserData* m_onerror; + package_manager_request_h m_request_handle; + JSContextRef m_context; +}; + + +class PackageManager +{ +public: + enum InstalledStorageType + { + INTERNAL, + EXTERNAL + }; + + void install(string pkgPath, PackageInstallEventCallback* callback); + void uninstall(string pkgPath, PackageInstallEventCallback* callback); + void move(string pkgPath, string type, PackageInstallEventCallback* callback); + + bool isInstalled(string pkgId); + PackageInformation* getPackageInfo(string pkgId); + void getPackagesInfo(PackageInfoCallbackData *user_data); + string getPackageIdFromAppId(string appId); + void setPackageInfoEventListener(PackageInfoEventCallback * eventCB); + void unsetPackageInfoEventListener(); + + // get the current application id from WRT + void setCurrentAppId(string appId); + string getCurrentAppId() const; + + static PackageManager* getInstance(); + +private: + PackageManager(); + ~PackageManager(); + pkgmgr_client *m_manager_handle; + string m_curr_app_id; + +}; + +} // Package +} // DeviceAPI +#endif diff --git a/wearable_src/Package/config.xml b/wearable_src/Package/config.xml new file mode 100755 index 0000000..170e884 --- /dev/null +++ b/wearable_src/Package/config.xml @@ -0,0 +1,17 @@ +<?xml version="1.0" ?> +<!DOCTYPE plugin-properties SYSTEM "/usr/etc/tizen-apis/config.dtd"> +<plugin-properties> + <library-name>libwrt-plugins-tizen-package.so</library-name> + <feature-install-uri>package.install.uri</feature-install-uri> + + <api-feature> + <name>http://tizen.org/privilege/packagemanager.install</name> + <device-capability>packagemanager.install</device-capability> + </api-feature> + + <api-feature> + <name>http://tizen.org/privilege/package.info</name> + <device-capability>package.info</device-capability> + </api-feature> + +</plugin-properties> diff --git a/wearable_src/Package/plugin_config.cpp b/wearable_src/Package/plugin_config.cpp new file mode 100644 index 0000000..d240fad --- /dev/null +++ b/wearable_src/Package/plugin_config.cpp @@ -0,0 +1,187 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 <Commons/FunctionDefinition.h> +#include <Commons/FunctionDeclaration.h> +#include <iostream> +#include <Commons/Exception.h> +#include <dpl/exception.h> +#include <map> + +#include "plugin_config.h" + +#define PACKAGE_FEATURE_API_INSTALL "http://tizen.org/privilege/packagemanager.install" +#define PACKAGE_FEATURE_API_INFO "http://tizen.org/privilege/package.info" + +#define PACKAGE_DEVICE_CAP_INSTALL "packagemanager.install" +#define PACKAGE_DEVICE_CAP_INFO "package.info" + +using namespace WrtDeviceApis::Commons; + +namespace DeviceAPI { +namespace Package { + +static FunctionMapping createPackageFunctions(); + +static FunctionMapping PackageFunctions = + createPackageFunctions(); + +#pragma GCC visibility push(default) + +DEFINE_FUNCTION_GETTER(Package, PackageFunctions); + +#pragma GCC visibility pop + +static FunctionMapping createPackageFunctions() +{ + /** + * Device capabilities + */ + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_PACKAGE_INSTALL, PACKAGE_DEVICE_CAP_INSTALL); + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_PACKAGE_INFO, PACKAGE_DEVICE_CAP_INFO); + + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_PACKAGE_INSTALL); + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_PACKAGE_INFO); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_PACKAGE_INSTALL, DEVICE_CAP_PACKAGE_INSTALL); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_PACKAGE_INFO, DEVICE_CAP_PACKAGE_INFO); + + /** + * Api Features + */ + ACE_CREATE_FEATURE(FEATURE_PACKAGE_INSTALL, PACKAGE_FEATURE_API_INSTALL); + ACE_CREATE_FEATURE(FEATURE_PACKAGE_INFO, PACKAGE_FEATURE_API_INFO); + + ACE_CREATE_FEATURE_LIST(PACKAGE_FEATURES_PACKAGE_INSTALL); + ACE_ADD_API_FEATURE(PACKAGE_FEATURES_PACKAGE_INSTALL, FEATURE_PACKAGE_INSTALL); + + ACE_CREATE_FEATURE_LIST(PACKAGE_FEATURES_PACKAGE_INFO); + ACE_ADD_API_FEATURE(PACKAGE_FEATURES_PACKAGE_INFO, FEATURE_PACKAGE_INFO); + + /** + * Functions + */ + FunctionMapping packageMapping; + + // install + AceFunction installFunc = ACE_CREATE_FUNCTION( + FUNCTION_INSTALL, + PACKAGE_FUNCTION_API_INSTALL, + PACKAGE_FEATURES_PACKAGE_INSTALL, + DEVICE_LIST_PACKAGE_INSTALL); + + packageMapping.insert(std::make_pair( + PACKAGE_FUNCTION_API_INSTALL, + installFunc)); + + // uninstall + AceFunction uninstallFunc = ACE_CREATE_FUNCTION( + FUNCTION_UNINSTALL, + PACKAGE_FUNCTION_API_UNINSTALL, + PACKAGE_FEATURES_PACKAGE_INSTALL, + DEVICE_LIST_PACKAGE_INSTALL); + + packageMapping.insert(std::make_pair( + PACKAGE_FUNCTION_API_UNINSTALL, + uninstallFunc)); + + // getPackageInfo + AceFunction getPackageInfoFunc = ACE_CREATE_FUNCTION( + FUNCTION_GET_PACKAGE_INFO, + PACKAGE_FUNCTION_API_GET_PACKAGE_INFO, + PACKAGE_FEATURES_PACKAGE_INFO, + DEVICE_LIST_PACKAGE_INFO); + + packageMapping.insert(std::make_pair( + PACKAGE_FUNCTION_API_GET_PACKAGE_INFO, + getPackageInfoFunc)); + + // getPackagesInfo + AceFunction getPackagesInfoFunc = ACE_CREATE_FUNCTION( + FUNCTION_GET_PACKAGES_INFO, + PACKAGE_FUNCTION_API_GET_PACKAGES_INFO, + PACKAGE_FEATURES_PACKAGE_INFO, + DEVICE_LIST_PACKAGE_INFO); + + packageMapping.insert(std::make_pair( + PACKAGE_FUNCTION_API_GET_PACKAGES_INFO, + getPackagesInfoFunc)); + + // setPackageInfoEventListener + AceFunction setPackageInfoEventListenerFunc = ACE_CREATE_FUNCTION( + FUNCTION_SET_PACKAGE_INFO_EVENT_LISTENER, + PACKAGE_FUNCTION_API_SET_PACKAGE_INFO_EVENT_LISTENER, + PACKAGE_FEATURES_PACKAGE_INFO, + DEVICE_LIST_PACKAGE_INFO); + + packageMapping.insert(std::make_pair( + PACKAGE_FUNCTION_API_SET_PACKAGE_INFO_EVENT_LISTENER, + setPackageInfoEventListenerFunc)); + + // unsetPackageInfoEventListener + AceFunction unsetPackageInfoEventListenerFunc = ACE_CREATE_FUNCTION( + FUNCTION_UNSET_PACKAGE_INFO_EVENT_LISTENER, + PACKAGE_FUNCTION_API_UNSET_PACKAGE_INFO_EVENT_LISTENER, + PACKAGE_FEATURES_PACKAGE_INFO, + DEVICE_LIST_PACKAGE_INFO); + + packageMapping.insert(std::make_pair( + PACKAGE_FUNCTION_API_UNSET_PACKAGE_INFO_EVENT_LISTENER, + unsetPackageInfoEventListenerFunc)); + +// candidated APIs +#if 0 + // move + AceFunction moveFunc = ACE_CREATE_FUNCTION( + FUNCTION_MOVE, + PACKAGE_FUNCTION_API_MOVE, + PACKAGE_FEATURES_PACKAGE_INSTALL, + EMPTY_DEVICE_LIST); + + packageMapping.insert(std::make_pair( + PACKAGE_FUNCTION_API_MOVE, + moveFunc)); + + // isInstalled + AceFunction isInstalledFunc = ACE_CREATE_FUNCTION( + FUNCTION_IS_INSTALLED, + PACKAGE_FUNCTION_API_IS_INSTALLED, + PACKAGE_FEATURES_PACKAGE_INFO, + EMPTY_DEVICE_LIST); + + packageMapping.insert(std::make_pair( + PACKAGE_FUNCTION_API_IS_INSTALLED, + isInstalledFunc)); + + // getPackageIdFromAppId + AceFunction getPackageIdFromAppIdFunc = ACE_CREATE_FUNCTION( + FUNCTION_GET_PACKAGE_ID_FROM_APP_ID, + PACKAGE_FUNCTION_API_GET_PACKAGE_ID_FROM_APP_ID, + PACKAGE_FEATURES_PACKAGE_INFO, + EMPTY_DEVICE_LIST); + + packageMapping.insert(std::make_pair( + PACKAGE_FUNCTION_API_GET_PACKAGE_ID_FROM_APP_ID, + getPackageIdFromAppIdFunc)); + +#endif + + + return packageMapping; +} + +} +} diff --git a/wearable_src/Package/plugin_config.h b/wearable_src/Package/plugin_config.h new file mode 100644 index 0000000..95cc4ac --- /dev/null +++ b/wearable_src/Package/plugin_config.h @@ -0,0 +1,54 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 _PACKAGE_PLUGIN_CONFIG_H_
+#define _PACKAGE_PLUGIN_CONFIG_H_
+
+#include <string>
+#include <Commons/FunctionDeclaration.h>
+
+// feature : install
+#define PACKAGE_FUNCTION_API_INSTALL "install"
+#define PACKAGE_FUNCTION_API_UNINSTALL "uninstall"
+
+// feature : read
+#define PACKAGE_FUNCTION_API_GET_PACKAGES_INFO "getPackagesInfo"
+#define PACKAGE_FUNCTION_API_GET_PACKAGE_INFO "getPackageInfo"
+#define PACKAGE_FUNCTION_API_SET_PACKAGE_INFO_EVENT_LISTENER "setPackageInfoEventListener"
+#define PACKAGE_FUNCTION_API_UNSET_PACKAGE_INFO_EVENT_LISTENER "unsetPackageInfoEventListener"
+
+// candidate apis
+#if 0
+#define PACKAGE_FUNCTION_API_MOVE "move"
+#define PACKAGE_FUNCTION_API_IS_INSTALLED "isInstalled"
+#define PACKAGE_FUNCTION_API_GET_PACKAGE_ID_FROM_APP_ID "getPackageIdFromAppId"
+#endif
+
+namespace DeviceAPI {
+namespace Package {
+
+DECLARE_FUNCTION_GETTER(Package);
+
+#define PACKAGE_CHECK_ACCESS(functionName) \
+ aceCheckAccess<AceFunctionGetter, DefaultArgsVerifier<> >( \
+ getPackageFunctionData, \
+ functionName)
+
+}
+}
+#endif
+
diff --git a/wearable_src/Package/plugin_initializer.cpp b/wearable_src/Package/plugin_initializer.cpp new file mode 100644 index 0000000..e8993c2 --- /dev/null +++ b/wearable_src/Package/plugin_initializer.cpp @@ -0,0 +1,90 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an AS IS BASIS, +// WITHOUT 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 <dpl/wrt-dao-ro/widget_dao_read_only.h> +#include <dpl/string.h> + +#include <Commons/plugin_initializer_def.h> +#include <Commons/WrtAccess/WrtAccess.h> +#include <GlobalContextManager.h> +#include <TimeTracer.h> +#include "JSPackageManager.h" +#include "PackageManager.h" +#include <Logger.h> + +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; +using namespace DeviceAPI::Common; + +namespace DeviceAPI { +namespace Package { + +void on_widget_start_callback(int widgetId) { + LoggerD("[Tizen2_1\\Package] on_widget_start_callback ("<<widgetId<<")"); + TIME_TRACER_INIT(); + Try { + WrtDB::WidgetDAOReadOnly dao(widgetId); + std::string tzAppId = DPL::ToUTF8String(dao.getTzAppId()); + PackageManager::getInstance()->setCurrentAppId(tzAppId); + + WrtAccessSingleton::Instance().initialize(widgetId); + } Catch(WrtDeviceApis::Commons::Exception) { + LoggerE("WrtAccess initialization failed"); + } +} + +void on_widget_stop_callback(int widgetId) { + LoggerD("[Tizen2_1\\Package] on_widget_stop_callback ("<<widgetId<<")"); + TIME_TRACER_EXPORT_REPORT_TO(TIME_TRACER_EXPORT_FILE,"Package"); + TIME_TRACER_RELEASE(); + Try { + WrtAccessSingleton::Instance().deinitialize(widgetId); + } Catch(WrtDeviceApis::Commons::Exception) { + LoggerE("WrtAccess deinitialization failed"); + } +} + +void on_frame_load_callback(const void * context) +{ + LoggerD("[Tizen\\Package] on_frame_load_callback (" << context << ")"); + GlobalContextManager::getInstance()->addGlobalContext(static_cast<JSContextRef>(context)); +} + +void on_frame_unload_callback(const void * context) +{ + LoggerD("[Tizen\\Package] on_frame_unload_callback (" << context << ")"); + GlobalContextManager::getInstance()->removeGlobalContext(static_cast<JSContextRef>(context)); +} + +PLUGIN_ON_WIDGET_START(on_widget_start_callback) +PLUGIN_ON_WIDGET_STOP(on_widget_stop_callback) + +PLUGIN_ON_FRAME_LOAD(on_frame_load_callback) +PLUGIN_ON_FRAME_UNLOAD(on_frame_unload_callback) + +PLUGIN_CLASS_MAP_BEGIN + PLUGIN_CLASS_MAP_ADD_CLASS( + WRT_JS_EXTENSION_OBJECT_TIZEN, + "package", + (js_class_template_getter)DeviceAPI::Package::JSPackageManager::getClassRef, + NULL) + +PLUGIN_CLASS_MAP_END + +} //Package +} //DeviceAPI + diff --git a/wearable_src/Power/CMakeLists.txt b/wearable_src/Power/CMakeLists.txt new file mode 100755 index 0000000..a6191c1 --- /dev/null +++ b/wearable_src/Power/CMakeLists.txt @@ -0,0 +1,48 @@ +SET(TARGET_NAME ${power_target}) +SET(DESTINATION_NAME ${power_dest}) +SET(TARGET_IMPL_NAME ${power_impl}) + +PKG_CHECK_MODULES(platform_pkgs_power REQUIRED capi-system-power deviced capi-system-device) + +INCLUDE_DIRECTORIES( + ${INCLUDE_COMMON} + ${platform_pkgs_power_INCLUDE_DIRS} +) + +SET(CMAKE_INSTALL_RPATH + ${CMAKE_INSTALL_RPATH} + ${CMAKE_INSTALL_PREFIX}/${DESTINATION_LIB_PREFIX}/${tizen_dest} + ${CMAKE_INSTALL_PREFIX}/${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME} +) + +SET(SRCS_IMPL + JSPowerManager.cpp + PowerManager.cpp +) + +ADD_LIBRARY(${TARGET_IMPL_NAME} SHARED ${SRCS_IMPL}) + +TARGET_LINK_LIBRARIES(${TARGET_IMPL_NAME} + ${LIBS_COMMON} + ${tizen_impl} + ${platform_pkgs_power_LIBRARIES} +) + +SET(SRCS + plugin_config.cpp + plugin_initializer.cpp +) + +ADD_LIBRARY(${TARGET_NAME} SHARED ${SRCS}) + +TARGET_LINK_LIBRARIES(${TARGET_NAME} + ${TARGET_IMPL_NAME} +) + +INSTALL(TARGETS ${TARGET_NAME} ${TARGET_IMPL_NAME} LIBRARY DESTINATION ${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME}) +INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/config.xml DESTINATION ${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME}) +INSTALL( + DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/ DESTINATION ${DESTINATION_HEADER_PREFIX}/power + FILES_MATCHING PATTERN "*.h" PATTERN "CMakeFiles" EXCLUDE +) + diff --git a/wearable_src/Power/JSPowerManager.cpp b/wearable_src/Power/JSPowerManager.cpp new file mode 100644 index 0000000..b5c292b --- /dev/null +++ b/wearable_src/Power/JSPowerManager.cpp @@ -0,0 +1,328 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <SecurityExceptions.h> +#include <CallbackUserData.h> +#include <GlobalContextManager.h> +#include <JSUtil.h> +#include <ArgumentValidator.h> +#include <TimeTracer.h> + +#include "JSPowerManager.h" +#include "plugin_config.h" +#include "PowerManager.h" +#include <Logger.h> + +using namespace WrtDeviceApis::Commons; +using namespace DeviceAPI::Common; +using namespace std; + +namespace DeviceAPI { +namespace Power { + +JSClassDefinition JSPowerManager::m_classInfo = { + 0, + kJSClassAttributeNone, + "PowerManager", + NULL, //ParentClass + NULL, //StaticValues + m_function, + initialize, + finalize, + NULL, //HasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL //ConvertToType +}; + +JSStaticFunction JSPowerManager::m_function[] = { + { POWER_FUNCTION_API_REQUEST, request, kJSPropertyAttributeNone }, + { POWER_FUNCTION_API_RELEASE, release, kJSPropertyAttributeNone }, + { POWER_FUNCTION_API_SET_SCREEN_STATE_CHANGE_LISTENER, setScreenStateChangeListener, kJSPropertyAttributeNone }, + { POWER_FUNCTION_API_UNSET_SCREEN_STATE_CHANGE_LISTENER, unsetScreenStateChangeListener, kJSPropertyAttributeNone }, + { POWER_FUNCTION_API_GET_SCREEN_BRIGHTNESS, getScreenBrightness, kJSPropertyAttributeNone }, + { POWER_FUNCTION_API_SET_SCREEN_BRIGHTNESS, setScreenBrightness, kJSPropertyAttributeNone }, + { POWER_FUNCTION_API_IS_SCREEN_ON, isScreenOn, kJSPropertyAttributeNone }, + { POWER_FUNCTION_API_RESTORE_SCREEN_BRIGHTNESS, restoreScreenBrightness, kJSPropertyAttributeNone }, + { POWER_FUNCTION_API_TURN_SCREEN_ON, turnScreenOn, kJSPropertyAttributeNone }, + { POWER_FUNCTION_API_TURN_SCREEN_OFF, turnScreenOff, kJSPropertyAttributeNone }, + + { 0, 0, 0 } +}; + +JSClassRef JSPowerManager::m_jsClassRef = JSClassCreate(JSPowerManager::getClassInfo()); + +void JSPowerManager::initialize(JSContextRef context, JSObjectRef object) +{ +} + +void JSPowerManager::finalize(JSObjectRef object) +{ + CallbackUserData *callback = static_cast<CallbackUserData*>(JSObjectGetPrivate(object)); + if( callback != NULL ){ + PowerManager::getInstance()->removeScreenStateChangedCallback(callback); + JSObjectSetPrivate(object, NULL); + delete callback; + } +} + +const JSClassRef JSPowerManager::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSPowerManager::getClassInfo() +{ + return &m_classInfo; +} + +JSValueRef JSPowerManager::request(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("entered"); + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + + AceSecurityStatus status = POWER_CHECK_ACCESS(POWER_FUNCTION_API_REQUEST); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + try{ + ArgumentValidator validator(context, argumentCount, arguments); + string resource_str = validator.toString(0); + string state_str = validator.toString(1); + PowerResource resource(resource_str.c_str()); + PowerState state(state_str.c_str()); + PowerManager::getInstance()->request( resource , state ); + }catch(const BasePlatformException& err){ + return JSWebAPIErrorFactory::postException(context, exception, err); + } + + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); +} + +JSValueRef JSPowerManager::release(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("entered"); + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + + try{ + ArgumentValidator validator(context, argumentCount, arguments); + + string resource_str = validator.toString(0); + PowerResource resource(resource_str.c_str()); + PowerManager::getInstance()->release( resource ); + + }catch(const BasePlatformException& err){ + return JSWebAPIErrorFactory::postException(context, exception, err); + } + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); +} + +JSValueRef JSPowerManager::setScreenStateChangeListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("entered"); + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + + try{ + ArgumentValidator validator(context, argumentCount, arguments); + JSObjectRef func = validator.toFunction(0); + CallbackUserData *callback = static_cast<CallbackUserData*>(JSObjectGetPrivate(thisObject)); + if( callback == NULL ){ + callback = new CallbackUserData(GlobalContextManager::getInstance()->getGlobalContext(context)); + JSObjectSetPrivate(thisObject, callback); + } + callback->setSuccessCallback(func); + PowerManager::getInstance()->addScreenStateChangedCallback(callback); + + }catch(const BasePlatformException& err){ + return JSWebAPIErrorFactory::postException(context, exception, err); + }catch( const std::bad_alloc& oom){ + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Out of memory"); + } + + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); +} + +JSValueRef JSPowerManager::unsetScreenStateChangeListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("entered"); + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + + CallbackUserData *callback = static_cast<CallbackUserData*>(JSObjectGetPrivate(thisObject)); + if( callback != NULL ){ + PowerManager::getInstance()->removeScreenStateChangedCallback(callback); + JSObjectSetPrivate(thisObject, NULL); + delete callback; + } + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); +} + +JSValueRef JSPowerManager::getScreenBrightness(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("entered"); + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + + try{ + double brightness = PowerManager::getInstance()->getScreenBrightness(); + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSUtil::toJSValueRef(context, brightness); + }catch(const BasePlatformException& err){ + return JSWebAPIErrorFactory::postException(context, exception, err); + } +} + +JSValueRef JSPowerManager::setScreenBrightness(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("entered"); + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + AceSecurityStatus status = POWER_CHECK_ACCESS(POWER_FUNCTION_API_RELEASE); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + try{ + ArgumentValidator validator(context, argumentCount, arguments); + + double value = validator.toDouble(0); + LOGE(" value = %f", value); + PowerManager::getInstance()->setScreenBrightness(value); + }catch(const BasePlatformException& err){ + return JSWebAPIErrorFactory::postException(context, exception, err); + } + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); + +} + +JSValueRef JSPowerManager::isScreenOn(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("entered"); + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + + try{ + bool state = PowerManager::getInstance()->isScreenOn(); + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSUtil::toJSValueRef(context,state); + }catch(const BasePlatformException& err){ + return JSWebAPIErrorFactory::postException(context, exception, err); + } +} + +JSValueRef JSPowerManager::restoreScreenBrightness(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("entered"); + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + + try{ + PowerManager::getInstance()->restoreScreenBrightness(); + }catch(const BasePlatformException& err){ + return JSWebAPIErrorFactory::postException(context, exception, err); + } + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context);} + +JSValueRef JSPowerManager::turnScreenOn(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("entered"); + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + AceSecurityStatus status = POWER_CHECK_ACCESS(POWER_FUNCTION_API_RELEASE); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + try{ + PowerManager::getInstance()->setScreenState(true); + }catch(const BasePlatformException& err){ + return JSWebAPIErrorFactory::postException(context, exception, err); + } + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); +} + +JSValueRef JSPowerManager::turnScreenOff(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("entered"); + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 0); + AceSecurityStatus status = POWER_CHECK_ACCESS(POWER_FUNCTION_API_RELEASE); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + try{ + PowerManager::getInstance()->setScreenState(false); + }catch(const BasePlatformException& err){ + return JSWebAPIErrorFactory::postException(context, exception, err); + } + TIME_TRACER_ITEM_END(__FUNCTION__, 0); + return JSValueMakeUndefined(context); +} + +} +} diff --git a/wearable_src/Power/JSPowerManager.h b/wearable_src/Power/JSPowerManager.h new file mode 100755 index 0000000..04c2834 --- /dev/null +++ b/wearable_src/Power/JSPowerManager.h @@ -0,0 +1,172 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _JS_TIZEN_POWER_MANAGER_H_ +#define _JS_TIZEN_POWER_MANAGER_H_ + +#include <string> +#include <JavaScriptCore/JavaScript.h> + +namespace DeviceAPI { +namespace Power { + +class JSPowerManager +{ + public: + + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + + private: + + /** + * This member variable contains the values which has to be passed + * when the this class is embedded into JS Engine. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This member variable contains the initialization values for the + * properties of this class. The values are given according to + * the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; + + /** + * 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); + + /** + * Requests a power resource. + */ + static JSValueRef request(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * Releases a previous power request. + */ + static JSValueRef release(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * Sets the screen state change listener. + */ + static JSValueRef setScreenStateChangeListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * Unsets the screen state change listener. + */ + static JSValueRef unsetScreenStateChangeListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * Gets the screen brightness. + */ + static JSValueRef getScreenBrightness(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * Sets the screen brightness. + */ + static JSValueRef setScreenBrightness(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * Returns true if screen is on. + */ + static JSValueRef isScreenOn(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * Restore the screen brightensss to the default setting value. + */ + static JSValueRef restoreScreenBrightness(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * Turns the screen on. + */ + static JSValueRef turnScreenOn(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * Turns the screen off. + */ + static JSValueRef turnScreenOff(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); +}; + +} +} + +#endif /* _JS_TIZEN_POWER_MANAGER_H_ */ + diff --git a/wearable_src/Power/PowerManager.cpp b/wearable_src/Power/PowerManager.cpp new file mode 100755 index 0000000..e04e1c1 --- /dev/null +++ b/wearable_src/Power/PowerManager.cpp @@ -0,0 +1,391 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "PowerManager.h" +#include <cstring> +#include <power.h> +#include <dd-display.h> +#include <device.h> +#include <algorithm> +#include <PlatformException.h> +#include <JSUtil.h> +#include <vconf.h> +#include <Logger.h> +#include <unistd.h> + +using namespace DeviceAPI::Common; +using namespace std; + +namespace DeviceAPI { +namespace Power { + +PowerResource::PowerResource(const char *resource) +{ + if( strcmp(resource,"SCREEN") == 0 ) + mType = SCREEN; + else if( strcmp(resource,"CPU") == 0 ) + mType = CPU; + else + throw TypeMismatchException("value is not PowerResource type"); +}; + +const std::string PowerResource::toString(){ + static const char *table[] = {"SCREEN", "CPU"}; + return std::string(table[mType]); +} + + +PowerState::PowerState(const char *str) +{ + static const char *table[] = { "SCREEN_OFF", "SCREEN_DIM", "SCREEN_NORMAL", "SCREEN_BRIGHT", "CPU_AWAKE"}; + static state state_table[] = { SCREENOFF, SCREENDIM, SCREENNORMAL, SCREENBRIGHT, CPUAWAKE }; + for(unsigned int i =0; i < sizeof(table)/sizeof(char*) ; i++){ + if( strcmp(str, table[i]) == 0 ){ + mState = state_table[i]; + return; + } + } + throw TypeMismatchException("value is not PowerState type"); +}; + +PowerState::PowerState(state in):mState(in){ +} + +const std::string PowerState::toString(){ + static const char *table[] = { "SCREEN_OFF", "SCREEN_DIM", "SCREEN_NORMAL", "SCREEN_BRIGHT", "CPU_AWAKE"}; + return std::string(table[mState]); +} + + +void PowerManager::onPlatformStateChangedCB(power_state_e state, void *user_data){ + PowerManager* object = static_cast<PowerManager*>(user_data); + if(object == NULL){ + LoggerE("User data is NULL"); + return; + } + PowerState current(PowerState::SCREENOFF); + switch( state ){ + case POWER_STATE_NORMAL : + current.mState = object->mBrightStateEnable ? PowerState::SCREENBRIGHT : PowerState::SCREENNORMAL; + break; + case POWER_STATE_SCREEN_DIM : + current.mState = PowerState::SCREENDIM; + break; + case POWER_STATE_SCREEN_OFF : + current.mState = PowerState::SCREENOFF; + break; + } + object->broadcastScreenState(current); +} + + +void PowerManager::request(PowerResource resource, PowerState state){ + if( resource == PowerResource::SCREEN && state == PowerState::CPUAWAKE) + throw InvalidValuesException("invalid PowerState"); + if( resource == PowerResource::CPU && state != PowerState::CPUAWAKE) + throw InvalidValuesException("invalid PowerState"); + + int ret=0; + switch( state ){ + case PowerState::SCREENDIM : + case PowerState::SCREENNORMAL : + case PowerState::CPUAWAKE : + { + int native_state = POWER_STATE_SCREEN_OFF; + if( state == PowerState::SCREENDIM ) + native_state = POWER_STATE_SCREEN_DIM; + else if( state == PowerState::SCREENNORMAL ) + native_state = POWER_STATE_NORMAL; + else + native_state = POWER_STATE_SCREEN_OFF; + + ret = power_lock_state( (power_state_e)native_state , 0); + if( POWER_ERROR_NONE!=ret ){ + LoggerE("power_lock_state(%d) error %d",native_state, ret); + throw UnknownException("power_lock_state error"); + } + break; + } + case PowerState::SCREENBRIGHT : + { + int maxBrightness; + ret = device_get_max_brightness(0, &maxBrightness); + if( DEVICE_ERROR_NONE!=ret) { + LoggerE("Platform error while getting max brightness: %d", ret); + throw UnknownException("Platform error while getting max brightness"); + } + + setPlatformBrightness( maxBrightness ); + + LOGI("Succeeded setting the brightness to a max level: %d", maxBrightness); + ret = power_lock_state(POWER_STATE_NORMAL, 0); + if( POWER_ERROR_NONE!=ret ){ + LoggerE("Platform error while locking state %d", ret); + throw UnknownException("Platform error while locking state"); + } + + mBrightStateEnable = true; + power_state_e platform_state = power_get_state(); + if( platform_state == POWER_STATE_NORMAL) + broadcastScreenState(PowerState::SCREENBRIGHT); + break; + } + case PowerState::SCREENOFF: + LoggerE("SCREEN_OFF state cannot be requested"); + throw InvalidValuesException("SCREEN_OFF state cannot be requested"); + + default : + throw UnknownException("Platform error while locking state"); + } +} + +void PowerManager::release(PowerResource resource){ + int ret; + if( PowerResource::SCREEN == resource ) { + ret = power_unlock_state(POWER_STATE_SCREEN_DIM); + if( POWER_ERROR_NONE!=ret ) + LOGI("Platform return value from dim unlock: %d", ret); + + ret = power_unlock_state(POWER_STATE_NORMAL); + if( POWER_ERROR_NONE!=ret ) + LOGI("Platform return value from dim unlock: %d", ret); + + if( mBrightStateEnable ){ + ret = device_set_brightness_from_settings(0); + if( DEVICE_ERROR_NONE!=ret){ + LoggerE("Platform error while setting restore brightness %d", ret); + throw UnknownException("Platform error while setting restore brightness"); + } + } + + mBrightStateEnable = false; + power_state_e platform_state = power_get_state(); + if( platform_state == POWER_STATE_NORMAL) + broadcastScreenState(PowerState::SCREENNORMAL); + + } else if( PowerResource::CPU == resource ) { + ret = power_unlock_state(POWER_STATE_SCREEN_OFF); + if( POWER_ERROR_NONE!=ret ) + LOGI("Platform return value from off unlock: %d", ret); + } +} + +double PowerManager::getScreenBrightness(){ + int brightness; + brightness = getPlatformBrightness(); + LOGI("Brightness value: %d", brightness); + return brightness/100.0; +} + +void PowerManager::setScreenBrightness(double brightness){ + int ret; + if( brightness > 1 || brightness < 0 ) + throw InvalidValuesException("brightness should be 0 <= brightness <= 1"); + int maxBrightness; + ret = device_get_max_brightness(0, &maxBrightness); + if( ret != 0 ){ + LoggerE("Platform error while setting restore brightness: %d", ret); + throw UnknownException("Platform error while getting max brightness"); + } + int nativeBrightness = (int)(brightness*maxBrightness); + + if (nativeBrightness == 0) + nativeBrightness = 1; + + setPlatformBrightness(nativeBrightness); + LOGI("Set the brightness value: %d", nativeBrightness); +} + +bool PowerManager::isScreenOn(){ + power_state_e state = power_get_state(); + if(POWER_STATE_SCREEN_OFF==state) + return false; + else + return true; +} + +void PowerManager::setScreenState(bool onoff){ + int ret = 0; + if( onoff ) + ret = display_change_state(LCD_NORMAL); + else + ret = display_change_state(LCD_OFF); + + if( ret<0 ){ + LoggerE("Platform error while changing screen state %d", ret); + throw UnknownException("Platform error while changing screen state"); + } + + int timeout=100; + while(timeout--){ + if( isScreenOn() == onoff ) + break; + usleep(100000); + } + +} + +void PowerManager::restoreScreenBrightness(){ + int ret; + ret = device_set_brightness_from_settings(0); + if( DEVICE_ERROR_NONE!=ret){ + LoggerE("Platform error while restoring brightness %d", ret); + throw UnknownException("Platform error while restoring brightness"); + } +} + +PowerManager* PowerManager::getInstance(){ + static PowerManager instance; + return &instance; +} + +void PowerManager::addScreenStateChangedCallback(Common::CallbackUserData * callback){ + list<CallbackUserData*>::iterator itr; + itr = find(mListener.begin(), mListener.end(), callback); + if( itr == mListener.end() ) + mListener.push_back(callback); +} + +void PowerManager::removeScreenStateChangedCallback(Common::CallbackUserData * callback){ + mListener.remove(callback); +} + +void PowerManager::setPlatformBrightness(int brightness){ + + + if( mCurrentState.mState == PowerState::SCREENDIM ){ + mCurrentBrightness = brightness; + LOGI("Current state is not normal state the value is saved in cache: %d", brightness); + mShouldBeReadFromCache = true; + return; + }else + mShouldBeReadFromCache = false; + + int ret = device_set_brightness(0, brightness); + if( ret != 0){ + LoggerE("Platform error while setting %d brightness: %d", brightness, ret); + throw UnknownException("Platform error while setting brightness."); + } + mCurrentBrightness = brightness; +} + +int PowerManager::getPlatformBrightness(){ + int currentPowerState = 1; + int brightness = 0; + int isCustomMode = 0; + int isAutoBrightness = 0; + int ret = 0; + + vconf_get_int(VCONFKEY_PM_STATE, ¤tPowerState); + if( currentPowerState == VCONFKEY_PM_STATE_NORMAL){ + vconf_get_int(VCONFKEY_PM_CURRENT_BRIGHTNESS, &brightness); + LOGD("[PM_STATE_NORMAL] return VCONFKEY_PM_CURRENT_BRIGHTNESS %d", brightness); + return brightness; + } + + vconf_get_int(VCONFKEY_PM_CUSTOM_BRIGHTNESS_STATUS, &isCustomMode); + if( (isCustomMode && mCurrentBrightness != -1) || mShouldBeReadFromCache ){ + LOGD("return custom brightness %d", mCurrentBrightness); + return mCurrentBrightness; + } + + vconf_get_int(VCONFKEY_SETAPPL_BRIGHTNESS_AUTOMATIC_INT, &isAutoBrightness); + if( isAutoBrightness == 1 ){ + ret = vconf_get_int(VCONFKEY_SETAPPL_PREFIX"/automatic_brightness_level" /*prevent RSA build error*/, &brightness); + if( ret != 0 ) //RSA binary has no AUTOMATIC_BRIGHTNESS + vconf_get_int(VCONFKEY_SETAPPL_LCD_BRIGHTNESS, &brightness); + }else{ + vconf_get_int(VCONFKEY_SETAPPL_LCD_BRIGHTNESS, &brightness); + } + LOGD("BRIGHTNESS(%s) %d", isAutoBrightness == 1 ? "auto" : "fix" , brightness); + + return brightness; +} + + +void PowerManager::restoreSettedBrightness(){ + int isCustomMode = 0; + vconf_get_int(VCONFKEY_PM_CUSTOM_BRIGHTNESS_STATUS, &isCustomMode); + if( isCustomMode || mShouldBeReadFromCache ){ + if( mCurrentBrightness == -1 ){ + // brightness was changed in other process + restoreScreenBrightness(); + }else{ + setPlatformBrightness(mCurrentBrightness); + } + } + mShouldBeReadFromCache = false; +} + +void PowerManager::broadcastScreenState(PowerState current){ + if( mCurrentState == current) + return; + + PowerState PreviousState = mCurrentState; + mCurrentState = current; + + if( mCurrentState.mState == PowerState::SCREENNORMAL && PreviousState.mState == PowerState::SCREENDIM ){ + //restore ScreenBrightness + try{ + restoreSettedBrightness(); + } + catch( const BasePlatformException& err){ + LoggerE("Error restore custom brightness %s", err.getMessage().c_str()); + } + } + if( mCurrentState.mState == PowerState::SCREENNORMAL && PreviousState.mState == PowerState::SCREENOFF){ + mShouldBeReadFromCache = false; + } + + list<CallbackUserData*> tmplist(mListener); + list<CallbackUserData*>::iterator itr = tmplist.begin(); + + while( itr != tmplist.end() ){ + CallbackUserData *callback = *itr; + if( callback != NULL ){ + JSValueRef previousState = JSUtil::toJSValueRef(callback->getContext(), PreviousState.toString()); + JSValueRef currentState = JSUtil::toJSValueRef(callback->getContext(), mCurrentState.toString()); + JSValueRef args[2] = { previousState, currentState }; + callback->callSuccessCallback(2, args); + } + ++itr; + } +} + + +PowerManager::PowerManager():mCurrentState(PowerState::SCREENNORMAL),mBrightStateEnable(false),mCurrentBrightness(-1),mShouldBeReadFromCache(false){ + power_state_e platform_state = power_get_state(); + switch( platform_state ){ + case POWER_STATE_NORMAL : + mCurrentState.mState = PowerState::SCREENNORMAL; + break; + case POWER_STATE_SCREEN_DIM : + mCurrentState.mState = PowerState::SCREENDIM; + break; + case POWER_STATE_SCREEN_OFF : + mCurrentState.mState = PowerState::SCREENOFF; + break; + } + power_set_changed_cb(PowerManager::onPlatformStateChangedCB, this); +} +PowerManager::~PowerManager(){ + power_unset_changed_cb(); +} + +} //Power +} //DeviceAPI + diff --git a/wearable_src/Power/PowerManager.h b/wearable_src/Power/PowerManager.h new file mode 100755 index 0000000..e5f6153 --- /dev/null +++ b/wearable_src/Power/PowerManager.h @@ -0,0 +1,86 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _POWER_MANAGER_H_ +#define _POWER_MANAGER_H_ + +#include <string> +#include <list> +#include <CallbackUserData.h> +#include <JavaScriptCore/JavaScript.h> +#include <power.h> + +namespace DeviceAPI { +namespace Power { + +class PowerResource{ +public: + enum type { SCREEN=0, CPU=1 }; + PowerResource( const char * str ); + operator type() const {return mType;} + const std::string toString(); + type mType; +}; + +class PowerState{ +public: + enum state { SCREENOFF, SCREENDIM, SCREENNORMAL, SCREENBRIGHT, CPUAWAKE }; + PowerState( const char * str ); + PowerState( state in); + operator state() const {return mState;} + const std::string toString(); + state mState; +}; + + + +class PowerManager +{ +public: + void request( PowerResource resource, PowerState state ); + void release( PowerResource resource ); + double getScreenBrightness(); + void setScreenBrightness(double brightness); + void restoreScreenBrightness(); + bool isScreenOn(); + void setScreenState( bool onoff ); + + void addScreenStateChangedCallback(Common::CallbackUserData *callback); + void removeScreenStateChangedCallback(Common::CallbackUserData *callback); + + static PowerManager* getInstance(); +private: + int getPlatformBrightness(); + void setPlatformBrightness(int i); + void restoreSettedBrightness(); + static void onPlatformStateChangedCB(power_state_e state, void *user_data); + PowerManager(); + virtual ~PowerManager(); + void broadcastScreenState(PowerState current); + std::list<Common::CallbackUserData*> mListener; + PowerState mCurrentState; + bool mBrightStateEnable; + int mCurrentBrightness; + bool mShouldBeReadFromCache; + +}; + +} +} + +#endif /* _POWER_MANAGER_H_ */ + diff --git a/wearable_src/Power/config.xml b/wearable_src/Power/config.xml new file mode 100755 index 0000000..92b3f63 --- /dev/null +++ b/wearable_src/Power/config.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" ?> +<!DOCTYPE plugin-properties SYSTEM "/usr/etc/tizen-apis/config.dtd"> +<plugin-properties> + <library-name>libwrt-plugins-tizen-power.so</library-name> + <feature-install-uri>power.install.uri</feature-install-uri> + + <api-feature> + <name>http://tizen.org/privilege/power</name> + <device-capability>power</device-capability> + </api-feature> + +</plugin-properties> diff --git a/wearable_src/Power/plugin_config.cpp b/wearable_src/Power/plugin_config.cpp new file mode 100755 index 0000000..fb97251 --- /dev/null +++ b/wearable_src/Power/plugin_config.cpp @@ -0,0 +1,181 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <Commons/FunctionDefinition.h> +#include <Commons/FunctionDeclaration.h> +#include <map> + +#include "plugin_config.h" + +#define POWER_FEATURE_API "http://tizen.org/privilege/power" + +#define POWER_DEVICE_CAP "power" + +using namespace WrtDeviceApis::Commons; + +namespace DeviceAPI { +namespace Power { + +static FunctionMapping createPowerFunctions(); + +static FunctionMapping PowerFunctions = + createPowerFunctions(); + +#pragma GCC visibility push(default) + +DEFINE_FUNCTION_GETTER(Power, PowerFunctions); + +#pragma GCC visibility pop + +static FunctionMapping createPowerFunctions() +{ + /** + * Device capabilities + */ + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_POWER, POWER_DEVICE_CAP); + + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_POWER); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_POWER, DEVICE_CAP_POWER); + + /** + * Api Features + */ + ACE_CREATE_FEATURE(FEATURE_POWER, POWER_FEATURE_API); + + ACE_CREATE_FEATURE_LIST(POWER_FEATURES); + ACE_ADD_API_FEATURE(POWER_FEATURES, FEATURE_POWER); + + /** + * Functions + */ + FunctionMapping powerMapping; + + // request + AceFunction requestFunc = ACE_CREATE_FUNCTION( + FUNCTION_REQUEST, + POWER_FUNCTION_API_REQUEST, + POWER_FEATURES, + DEVICE_LIST_POWER); + + powerMapping.insert(std::make_pair( + POWER_FUNCTION_API_REQUEST, + requestFunc)); + + // release + AceFunction releaseFunc = ACE_CREATE_FUNCTION( + FUNCTION_RELEASE, + POWER_FUNCTION_API_RELEASE, + POWER_FEATURES, + DEVICE_LIST_POWER); + + powerMapping.insert(std::make_pair( + POWER_FUNCTION_API_RELEASE, + releaseFunc)); + + // setScreenStateChangeListener + AceFunction setScreenStateChangeListenerFunc = ACE_CREATE_FUNCTION( + FUNCTION_SET_SCREEN_STATE_CHANGE_LISTENER, + POWER_FUNCTION_API_SET_SCREEN_STATE_CHANGE_LISTENER, + POWER_FEATURES, + DEVICE_LIST_POWER); + + powerMapping.insert(std::make_pair( + POWER_FUNCTION_API_SET_SCREEN_STATE_CHANGE_LISTENER, + setScreenStateChangeListenerFunc)); + + // setScreenStateChangeListenerFunc + AceFunction setScreenStateChangeListenerFuncFunc = ACE_CREATE_FUNCTION( + FUNCTION_UNSET_SCREEN_STATE_CHANGE_LISTENER, + POWER_FUNCTION_API_UNSET_SCREEN_STATE_CHANGE_LISTENER, + POWER_FEATURES, + DEVICE_LIST_POWER); + + powerMapping.insert(std::make_pair( + POWER_FUNCTION_API_UNSET_SCREEN_STATE_CHANGE_LISTENER, + setScreenStateChangeListenerFuncFunc)); + + // getScreenBrightness + AceFunction getScreenBrightnessFunc = ACE_CREATE_FUNCTION( + FUNCTION_GET_SCREEN_BRIGHTNESS, + POWER_FUNCTION_API_GET_SCREEN_BRIGHTNESS, + POWER_FEATURES, + DEVICE_LIST_POWER); + + powerMapping.insert(std::make_pair( + POWER_FUNCTION_API_GET_SCREEN_BRIGHTNESS, + getScreenBrightnessFunc)); + + // setScreenBrightness + AceFunction setScreenBrightnessFunc = ACE_CREATE_FUNCTION( + FUNCTION_SET_SCREEN_BRIGHTNESS, + POWER_FUNCTION_API_SET_SCREEN_BRIGHTNESS, + POWER_FEATURES, + DEVICE_LIST_POWER); + + powerMapping.insert(std::make_pair( + POWER_FUNCTION_API_SET_SCREEN_BRIGHTNESS, + setScreenBrightnessFunc)); + + // isScreenOn + AceFunction isScreenOnFunc = ACE_CREATE_FUNCTION( + FUNCTION_IS_SCREEN_ON, + POWER_FUNCTION_API_IS_SCREEN_ON, + POWER_FEATURES, + DEVICE_LIST_POWER); + + powerMapping.insert(std::make_pair( + POWER_FUNCTION_API_IS_SCREEN_ON, + isScreenOnFunc)); + + // restoreScreenBrightness + AceFunction restoreScreenBrightnessFunc = ACE_CREATE_FUNCTION( + FUNCTION_RESTORE_SCREEN_BRIGHTNESS, + POWER_FUNCTION_API_RESTORE_SCREEN_BRIGHTNESS, + POWER_FEATURES, + DEVICE_LIST_POWER); + + powerMapping.insert(std::make_pair( + POWER_FUNCTION_API_RESTORE_SCREEN_BRIGHTNESS, + restoreScreenBrightnessFunc)); + + // turnScreenOn + AceFunction turnScreenOnFunc = ACE_CREATE_FUNCTION( + FUNCTION_TURN_SCREEN_ON, + POWER_FUNCTION_API_TURN_SCREEN_ON, + POWER_FEATURES, + DEVICE_LIST_POWER); + + powerMapping.insert(std::make_pair( + POWER_FUNCTION_API_TURN_SCREEN_ON, + turnScreenOnFunc)); + + // turnScreenOff + AceFunction turnScreenOffFunc = ACE_CREATE_FUNCTION( + FUNCTION_TURN_SCREEN_OFF, + POWER_FUNCTION_API_TURN_SCREEN_OFF, + POWER_FEATURES, + DEVICE_LIST_POWER); + + powerMapping.insert(std::make_pair( + POWER_FUNCTION_API_TURN_SCREEN_OFF, + turnScreenOffFunc)); + + return powerMapping; +} + +} +} diff --git a/wearable_src/Power/plugin_config.h b/wearable_src/Power/plugin_config.h new file mode 100755 index 0000000..b528cce --- /dev/null +++ b/wearable_src/Power/plugin_config.h @@ -0,0 +1,49 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _POWER_PLUGIN_CONFIG_H_ +#define _POWER_PLUGIN_CONFIG_H_ + +#include <string> +#include <Commons/FunctionDeclaration.h> + +namespace DeviceAPI { +namespace Power { + +// Functions from power manager +#define POWER_FUNCTION_API_REQUEST "request" +#define POWER_FUNCTION_API_RELEASE "release" +#define POWER_FUNCTION_API_SET_SCREEN_STATE_CHANGE_LISTENER "setScreenStateChangeListener" +#define POWER_FUNCTION_API_UNSET_SCREEN_STATE_CHANGE_LISTENER "unsetScreenStateChangeListener" +#define POWER_FUNCTION_API_GET_SCREEN_BRIGHTNESS "getScreenBrightness" +#define POWER_FUNCTION_API_SET_SCREEN_BRIGHTNESS "setScreenBrightness" +#define POWER_FUNCTION_API_IS_SCREEN_ON "isScreenOn" +#define POWER_FUNCTION_API_RESTORE_SCREEN_BRIGHTNESS "restoreScreenBrightness" +#define POWER_FUNCTION_API_TURN_SCREEN_ON "turnScreenOn" +#define POWER_FUNCTION_API_TURN_SCREEN_OFF "turnScreenOff" + +DECLARE_FUNCTION_GETTER(Power); + +#define POWER_CHECK_ACCESS(functionName) \ + aceCheckAccess<AceFunctionGetter, DefaultArgsVerifier<> >( \ + getPowerFunctionData, \ + functionName) + +} +} + +#endif // _POWER_PLUGIN_CONFIG_H_ diff --git a/wearable_src/Power/plugin_initializer.cpp b/wearable_src/Power/plugin_initializer.cpp new file mode 100644 index 0000000..2e9cdb3 --- /dev/null +++ b/wearable_src/Power/plugin_initializer.cpp @@ -0,0 +1,86 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <Logger.h> + +#include <Commons/plugin_initializer_def.h> +#include <Commons/WrtAccess/WrtAccess.h> +#include <Commons/Exception.h> +#include "JSPowerManager.h" +#include <GlobalContextManager.h> +#include <TimeTracer.h> + +namespace DeviceAPI { +namespace Power { + +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; +using namespace DeviceAPI::Common; + +void on_widget_start_callback(int widgetId) +{ + LoggerD("[Tizen\\Power] on_widget_start_callback (" << widgetId << ")"); + TIME_TRACER_INIT(); + + Try { + WrtAccessSingleton::Instance().initialize(widgetId); + } Catch (Exception) { + LoggerE("WrtAccess initialization failed"); + } +} + +void on_widget_stop_callback(int widgetId) +{ + LoggerD("[Tizen\\Power] on_widget_stop_callback (" << widgetId << ")"); + TIME_TRACER_EXPORT_REPORT_TO(TIME_TRACER_EXPORT_FILE,"Power"); + TIME_TRACER_RELEASE(); + + Try { + WrtAccessSingleton::Instance().deinitialize(widgetId); + } Catch (Exception) { + LoggerE("WrtAccess deinitialization failed"); + } +} + +void on_frame_load_callback(const void * context) +{ + LoggerD("[Tizen\\Power] on_frame_load_callback (" << context << ")"); + GlobalContextManager::getInstance()->addGlobalContext(static_cast<JSContextRef>(context)); +} + +void on_frame_unload_callback(const void * context) +{ + LoggerD("[Tizen\\Power] on_frame_unload_callback (" << context << ")"); + GlobalContextManager::getInstance()->removeGlobalContext(static_cast<JSContextRef>(context)); +} + +PLUGIN_ON_WIDGET_START(on_widget_start_callback) +PLUGIN_ON_WIDGET_STOP(on_widget_stop_callback) + +PLUGIN_ON_FRAME_LOAD(on_frame_load_callback) +PLUGIN_ON_FRAME_UNLOAD(on_frame_unload_callback) + +PLUGIN_CLASS_MAP_BEGIN +PLUGIN_CLASS_MAP_ADD_CLASS(WRT_JS_EXTENSION_OBJECT_TIZEN, + "power", + (js_class_template_getter)JSPowerManager::getClassRef, + NULL) +PLUGIN_CLASS_MAP_END + +} +} + diff --git a/wearable_src/RefImpl/CMakeLists.txt b/wearable_src/RefImpl/CMakeLists.txt new file mode 100755 index 0000000..570be8b --- /dev/null +++ b/wearable_src/RefImpl/CMakeLists.txt @@ -0,0 +1,50 @@ +SET(TARGET_NAME ${refimpl_target}) +SET(DESTINATION_NAME ${refimpl_dest}) +SET(TARGET_IMPL_NAME ${refimpl_impl}) + +SET(CMAKE_INSTALL_RPATH + ${CMAKE_INSTALL_RPATH} + ${CMAKE_INSTALL_PREFIX}/${DESTINATION_LIB_PREFIX}/${tizen_dest} + ${CMAKE_INSTALL_PREFIX}/${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME} +) + +SET(SRCS_IMPL + JSRefImplManager.cpp + RefImplManager.cpp + mock.cpp + JSSuper.cpp + JSSub.cpp + Super.cpp + Sub.cpp + NestedValue.cpp + JSNestedValue.cpp +) + +INCLUDE_DIRECTORIES( + ${INCLUDE_COMMON} +) + +ADD_LIBRARY(${TARGET_IMPL_NAME} SHARED ${SRCS_IMPL}) + +TARGET_LINK_LIBRARIES(${TARGET_IMPL_NAME} + ${LIBS_COMMON} +) + +SET(SRCS + plugin_initializer.cpp +) + +ADD_LIBRARY(${TARGET_NAME} SHARED ${SRCS}) + +TARGET_LINK_LIBRARIES(${TARGET_NAME} + ${TARGET_IMPL_NAME} +) + +INSTALL(TARGETS ${TARGET_NAME} ${TARGET_IMPL_NAME} LIBRARY DESTINATION ${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME}) +INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/config.xml DESTINATION ${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME}) +INSTALL( + DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/ DESTINATION ${DESTINATION_HEADER_PREFIX}/power + FILES_MATCHING PATTERN "*.h" PATTERN "CMakeFiles" EXCLUDE +) + +add_subdir(test) diff --git a/wearable_src/RefImpl/JSNestedValue.cpp b/wearable_src/RefImpl/JSNestedValue.cpp new file mode 100755 index 0000000..2f917c7 --- /dev/null +++ b/wearable_src/RefImpl/JSNestedValue.cpp @@ -0,0 +1,174 @@ +// +// Tizen Web Device API +// Copyright (c) 2013 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "JSNestedValue.h" +#include "NestedValue.h" + +#include <ArgumentValidator.h> +#include <PlatformException.h> +#include <JSUtil.h> + +#include <string> + +using namespace DeviceAPI::Common; +using namespace std; + +namespace DeviceAPI { +namespace Reference { + +JSClassRef JSNestedValue::m_jsClassRef = NULL; + +JSClassDefinition JSNestedValue::m_jsClassInfo = { + 0, // current (and only) version is 0 + kJSClassAttributeNone, //attributes + "NestedValue", //class name + NULL, // parent class + JSNestedValue::m_property, //static values + JSNestedValue::m_function, // static functions + JSNestedValue::initialize, // initialize + JSNestedValue::finalize, //finalize + NULL, //hasProperty + NULL, //getProperty + NULL, //setProperty + NULL, //deleteProperty + NULL, //getPropertyNames + NULL, // callAsFunction + NULL, // constructor + NULL, + NULL // convertToType +}; + + +JSStaticValue JSNestedValue::m_property[] = { + { "Number", JSNestedValue::getProperty, JSNestedValue::setProperty, kJSPropertyAttributeNone}, + { "Message", JSNestedValue::getProperty, JSNestedValue::setProperty, kJSPropertyAttributeNone}, + { 0, 0, 0, 0 } +}; + + +JSStaticFunction JSNestedValue::m_function[] = { + { "print", JSNestedValue::print, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + + +const JSClassRef JSNestedValue::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_jsClassInfo); + } + return m_jsClassRef; +} +const JSClassDefinition* JSNestedValue::getClassInfo() +{ + return &m_jsClassInfo; +} + + +boost::shared_ptr<NestedValue> JSNestedValue::getNative(JSContextRef ctx, JSValueRef value){ + JSObjectRef object = JSUtil::JSValueToObject(ctx, value); + NestedValueHolder* priv = static_cast<NestedValueHolder*>(JSObjectGetPrivate(object)); + if( priv == NULL || priv->obj == NULL ) + throw TypeMismatchException("Not NestedValue Type"); + return priv->obj; +} + +JSObjectRef JSNestedValue::makeJSObject(JSContextRef ctx, boost::shared_ptr < NestedValue > native){ + NestedValueHolder *priv = new NestedValueHolder; + priv->obj = native; + JSObjectRef obj = JSObjectMake(ctx, getClassRef(), priv); + return obj; +} + +JSObjectRef JSNestedValue::constructor(JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception){ + try{ + ArgumentValidator validator(ctx, argumentCount, arguments); + + boost::shared_ptr<NestedValue> native( new NestedValue(validator.toLong(0), validator.toString(1).c_str()) ); + JSObjectRef obj = makeJSObject(ctx, native); + JSUtil::setProperty(ctx, obj, "constructor", constructor, kJSPropertyAttributeReadOnly|kJSPropertyAttributeDontDelete|kJSPropertyAttributeDontEnum); + return obj; + }catch( const BasePlatformException &err){ + JSObjectRef error = JSWebAPIErrorFactory::makeErrorObject(ctx, err); + *exception = error; + return error; + } +} + +void JSNestedValue::initialize(JSContextRef ctx, JSObjectRef object) +{ + printf("JSNestedValue::initialize()\n"); +} + +void JSNestedValue::finalize(JSObjectRef object) +{ + printf("JSNestedValue::finalize()\n"); + NestedValueHolder * priv = static_cast<NestedValueHolder*>(JSObjectGetPrivate(object)); + if( priv ){ + JSObjectSetPrivate(object, NULL); + delete priv; + } +} + +JSValueRef JSNestedValue::getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception){ + printf("JSNestedValue::getProperty()\n"); + NestedValueHolder* priv = static_cast<NestedValueHolder*>(JSObjectGetPrivate(object)); + + string name = JSUtil::JSStringToString(context, propertyName); + if( name == "Number" ){ + return JSUtil::toJSValueRef(context, priv->obj->getNumber()); + }else if( name == "Message"){ + return JSUtil::toJSValueRef(context, priv->obj->getMessage()); + } + return NULL; +} + +bool JSNestedValue::setProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef value, JSValueRef* exception){ + printf("JSNestedValue::setProperty()\n"); + NestedValueHolder* priv = static_cast<NestedValueHolder*>(JSObjectGetPrivate(object)); + string name = JSUtil::JSStringToString(context, propertyName); + try{ + JSValueRef values[1] = { value }; + ArgumentValidator validator(context, 1, values); + if( name == "Number" ){ + priv->obj->setNumber( validator.toLong(0)); + return true; + }else if( name == "Message"){ + priv->obj->setMessage( validator.toString(0)); + return true; + } + }catch( const BasePlatformException& err){ + printf("Silently error\n"); + return true; + } + return false; +} + + +JSValueRef JSNestedValue::print(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception){ + printf("JSNestedValue::print()\n"); + NestedValueHolder* priv = static_cast<NestedValueHolder*>(JSObjectGetPrivate(thisObject)); + if( priv && priv->obj){ + printf("Number : %d , Message: %s\n" , priv->obj->getNumber(), priv->obj->getMessage().c_str()); + } + return JSValueMakeUndefined(ctx); +} + + +} // Reference +} // TizenApis + diff --git a/wearable_src/RefImpl/JSNestedValue.h b/wearable_src/RefImpl/JSNestedValue.h new file mode 100755 index 0000000..a9ed474 --- /dev/null +++ b/wearable_src/RefImpl/JSNestedValue.h @@ -0,0 +1,49 @@ +#ifndef _REFIMPL_JS_NESTEDVALUE_H_ +#define _REFIMPL_JS_NESTEDVALUE_H_ + +#include <string> +#include <JavaScriptCore/JavaScript.h> +#include <boost/shared_ptr.hpp> + +namespace DeviceAPI { +namespace Reference { + +class NestedValue; + +struct NestedValueHolder{ + boost::shared_ptr<NestedValue> obj; +}; + +class JSNestedValue +{ + public: + + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + + static JSObjectRef makeJSObject(JSContextRef ctx, boost::shared_ptr<NestedValue> native); + static boost::shared_ptr<NestedValue> getNative(JSContextRef ctx, JSValueRef value); + static JSObjectRef constructor(JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + private: + + static JSClassDefinition m_jsClassInfo; + static JSClassRef m_jsClassRef; + static JSStaticFunction m_function[]; + static JSStaticValue m_property[]; + + + static void initialize(JSContextRef context, JSObjectRef object); + static void finalize(JSObjectRef object); + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + static bool setProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef value, JSValueRef* exception); + + static JSValueRef print(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + +}; + +} +} + +#endif /* _REFIMPL_JS_NESTEDVALUE_H_ */ + + diff --git a/wearable_src/RefImpl/JSRefImplManager.cpp b/wearable_src/RefImpl/JSRefImplManager.cpp new file mode 100755 index 0000000..f465d91 --- /dev/null +++ b/wearable_src/RefImpl/JSRefImplManager.cpp @@ -0,0 +1,596 @@ +/* + * 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 <SecurityExceptions.h> +#include <CommonsJavaScript/Converter.h> +#include <GlobalContextManager.h> +#include <ArgumentValidator.h> +#include <PlatformException.h> +#include <JSWebAPIErrorFactory.h> +#include <JSUtil.h> +#include <Logger.h> +#include <MultiCallbackUserData.h> +#include <boost/shared_ptr.hpp> +#include <string> +#include <vector> +#include <JSArray.h> + +#include "TimeTracer.h" +#include "JSRefImplManager.h" +#include "RefImplManager.h" +#include "JSSub.h" +#include "JSSuper.h" +#include "Sub.h" +#include "NestedValue.h" +#include "JSNestedValue.h" + +using namespace std; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::Commons; +using namespace DeviceAPI::Common; + + +namespace DeviceAPI { +namespace Reference { + +JSClassRef JSRefImplManager::m_jsClassRef = NULL; + +JSClassDefinition JSRefImplManager::m_jsClassInfo = { + 0, // current (and only) version is 0 + kJSClassAttributeNone, //attributes + "RefImplManager", //class name + NULL, // parent class + JSRefImplManager::m_property, //static values + JSRefImplManager::m_function, // static functions + JSRefImplManager::initialize, // initialize + JSRefImplManager::finalize, //finalize + NULL, //hasProperty + JSRefImplManager::getNormalProperty, //getProperty + JSRefImplManager::setNormalProperty, //setProperty + NULL, //deleteProperty + NULL, //getPropertyNames + NULL, // callAsConstructor + NULL, // constructor + NULL, + NULL // convertToType +}; + +JSStaticValue JSRefImplManager::m_property[] = { + { "Number", getReadOnlyNumber, NULL, kJSPropertyAttributeNone|kJSPropertyAttributeReadOnly|kJSPropertyAttributeDontDelete}, + { "Sub", getReadOnlySub, NULL, kJSPropertyAttributeNone|kJSPropertyAttributeReadOnly|kJSPropertyAttributeDontDelete}, + { 0, 0, 0, 0 } +}; + + + +JSStaticFunction JSRefImplManager::m_function[] = { + { "syncToSync", JSRefImplManager::syncToSync, kJSPropertyAttributeNone }, + { "syncToAsync", JSRefImplManager::syncToAsync, kJSPropertyAttributeNone }, + { "asyncToAsync", JSRefImplManager::asyncToAsync, kJSPropertyAttributeNone }, + { "addListener", JSRefImplManager::addListener, kJSPropertyAttributeNone }, + { "removeListener", JSRefImplManager::removeListener, kJSPropertyAttributeNone }, + { "fire", JSRefImplManager::fire, kJSPropertyAttributeNone }, + { "argtest", JSRefImplManager::argtest, kJSPropertyAttributeNone }, + { "arraytest", JSRefImplManager::arraytest, kJSPropertyAttributeNone }, + { "isSuper", JSRefImplManager::isSuper, kJSPropertyAttributeNone }, + { "isSub", JSRefImplManager::isSub, kJSPropertyAttributeNone }, + { "setCallback", JSRefImplManager::setCallback, kJSPropertyAttributeNone }, + { "unsetCallback", JSRefImplManager::unsetCallback, kJSPropertyAttributeNone }, + { "fireCallback", JSRefImplManager::fireCallback, kJSPropertyAttributeNone }, + { "callbackObjectTest", JSRefImplManager::callbackObjectTest, kJSPropertyAttributeNone }, + { "updateNumber", JSRefImplManager::updateNumber, kJSPropertyAttributeNone }, + { "updateSub", JSRefImplManager::updateSub, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +const JSClassRef JSRefImplManager::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_jsClassInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSRefImplManager::getClassInfo() +{ + return &m_jsClassInfo; +} + +void JSRefImplManager::initialize(JSContextRef ctx, JSObjectRef object) +{ + TIME_TRACER_INIT(); +} + +void JSRefImplManager::finalize(JSObjectRef object) +{ + TIME_TRACER_EXPORT_REPORT_TO(TIME_TRACER_EXPORT_FILE,"RefImpl"); + TIME_TRACER_RELEASE(); +} + + +JSValueRef JSRefImplManager::getReadOnlyNumber(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception){ + return RefImplManager::getInstance()->mLocalProperty.getProperty(context,propertyName); +} + +JSValueRef JSRefImplManager::getReadOnlySub(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception){ + return RefImplManager::getInstance()->mLocalProperty.getProperty(context,propertyName); +} + +JSValueRef JSRefImplManager::getNormalProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception){ + string name = JSUtil::JSStringToString(context, propertyName); + if( name == "Number" ) + return NULL; + if( name == "Sub") + return NULL; + return RefImplManager::getInstance()->mLocalProperty.getProperty(context,propertyName); +} + +bool JSRefImplManager::setNormalProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef value, JSValueRef* exception){ + string name = JSUtil::JSStringToString(context, propertyName); + if( name == "Number" ) + return false; + if( name == "Sub") + return false; + return RefImplManager::getInstance()->mLocalProperty.setProperty(context,propertyName, value); +} + +JSValueRef JSRefImplManager::syncToSync(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception){ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 1); + try{ + Converter convert(ctx); + ArgumentValidator validator(ctx, argumentCount, arguments); + + int a = validator.toLong(0); + int b = validator.toLong(1); + int result = RefImplManager::getInstance()->syncToSync(a,b); + TIME_TRACER_ITEM_END(__FUNCTION__, 1); + return convert.toJSValueRef(result); + }catch( const TypeMismatchException& err ){ + return JSWebAPIErrorFactory::postException(ctx, exception, err); + }catch( const BasePlatformException& err){ + return JSWebAPIErrorFactory::postException(ctx, exception, err); + }catch( const ConversionException& err){ + return JSWebAPIErrorFactory::postException(ctx, exception, "TypeMismatchError" , "can't convert to int"); + } + return JSValueMakeUndefined(ctx); +} + +JSValueRef JSRefImplManager::syncToAsync(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception){ + TIME_TRACER_ITEM_BEGIN(__FUNCTION__, 1); + try{ + ArgumentValidator validator(ctx, argumentCount, arguments); + + int a = validator.toLong(0); + int b = validator.toLong(1); + RefCallbackUserData *callback = new RefCallbackUserData(GlobalContextManager::getInstance()->getGlobalContext(ctx),a,b); + callback->setSuccessCallback(validator.toFunction(2)); + callback->setErrorCallback(validator.toFunction(3, true)); + + RefImplManager::getInstance()->syncToAsync(callback); + + }catch( const TypeMismatchException& err ){ + return JSWebAPIErrorFactory::postException(ctx, exception, err); + }catch( const BasePlatformException& err){ + return JSWebAPIErrorFactory::postException(ctx, exception, err); + } + TIME_TRACER_ITEM_END(__FUNCTION__, 1); + TIME_TRACER_EXPORT_REPORT(); + TIME_TRACER_EXPORT_REPORT_TO(TIME_TRACER_EXPORT_FILE,"RefImpl"); + return JSValueMakeUndefined(ctx); + +} + +JSValueRef JSRefImplManager::asyncToAsync(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception){ + try{ + ArgumentValidator validator(ctx, argumentCount, arguments); + int a = validator.toLong(0); + int b = validator.toLong(1); + RefCallbackUserData *callback = new RefCallbackUserData(GlobalContextManager::getInstance()->getGlobalContext(ctx),a,b); + callback->setSuccessCallback(validator.toFunction(2)); + callback->setErrorCallback(validator.toFunction(3, true)); + + RefImplManager::getInstance()->asyncToAsync(callback); + + }catch( const TypeMismatchException& err ){ + return JSWebAPIErrorFactory::postException(ctx, exception, err); + }catch( const BasePlatformException& err){ + return JSWebAPIErrorFactory::postException(ctx, exception, err); + } + + return JSValueMakeUndefined(ctx); + +} + +JSValueRef JSRefImplManager::argtest(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception){ + try{ + ArgumentValidator validator(ctx, argumentCount, arguments); + string tocheck = validator.toString(0); + + if( validator.isOmitted(0) || validator.isNull(0)){ + printf("argument is omitted\n"); + } + + if( tocheck == "Boolean"){ + bool value = validator.toBool(1); + printf("arg[1] = %d\n", value); + return JSUtil::toJSValueRef(ctx, value); + } + else if( tocheck == "Long"){ + long value = validator.toLong(1); + printf("arg[1] = %ld\n", value); + return JSUtil::toJSValueRef(ctx, value); + } + else if( tocheck == "ULong"){ + unsigned long value = validator.toULong(1); + printf("arg[1] = %lu\n", value); + return JSUtil::toJSValueRef(ctx, value); + } + else if( tocheck == "ULongLong"){ + unsigned long long value = validator.toULongLong(1); + printf("arg[1] = %llu\n", value); + return JSUtil::toJSValueRef(ctx, value); + } + else if( tocheck == "Byte"){ + signed char value = (int)validator.toByte(1); + printf("arg[1] = %d\n", value); + return JSUtil::toJSValueRef(ctx, value); + } + else if( tocheck == "Octet"){ + unsigned char value = (int)validator.toOctet(1); + printf("arg[1] = %d\n", value); + return JSUtil::toJSValueRef(ctx, value); + } + else if( tocheck == "String"){ + string value = validator.toString(1); + printf("arg[1] = %s\n", value.c_str()); + return JSUtil::toJSValueRef(ctx, value); + }else if( tocheck == "Object"){ + JSObjectRef value = validator.toObject(1); + printf("arg[1] = %p\n", value); + return value; + }else if( tocheck == "Date"){ + time_t value = validator.toTimeT(1); + printf("arg[1] = %ld\n", value); + return JSUtil::makeDateObject(ctx, value); + }else if( tocheck == "Double" ){ + double value = validator.toDouble(1); + printf("arg[1] = %f\n", value); + return JSUtil::toJSValueRef(ctx, value); + }else if( tocheck == "Function"){ + JSObjectRef value = validator.toFunction(1); + printf("arg[1] = %p\n", value); + return value; + }else if( tocheck == "Array"){ + JSObjectRef value = validator.toArrayObject(1); + printf("arg[1] = %p\n", value); + return value; + }else{ + printf("usage: argtest([Long|String|Object|Date|Double|Function], ...)\n"); + return JSUtil::toJSValueRef(ctx, "usage: argtest([Long|String|Object|Date|Double|Function], ...)"); + } + }catch( const TypeMismatchException& err ){ + printf("TypeMismatch exception %s : %s\n", err.getName().c_str(), err.getMessage().c_str()); + return JSWebAPIErrorFactory::postException(ctx, exception, err); + } + return JSValueMakeUndefined(ctx); +} + +JSValueRef makeJSBool(JSContextRef ctx, bool v){ + return JSUtil::toJSValueRef(ctx, v); +} + +JSValueRef makeNestedValue(JSContextRef ctx, boost::shared_ptr < NestedValue > native){ + return JSNestedValue::makeJSObject(ctx, native); +} + +JSValueRef JSRefImplManager::arraytest(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception){ + try{ + ArgumentValidator validator(ctx, argumentCount, arguments); + string type = validator.toString(0); + JSObjectRef jsArray = validator.toArrayObject(1, true); + if( type == "String" && jsArray != NULL){ + JSStringArray receivedArray(ctx, jsArray); + + // basic getting test + for( unsigned int i = 0 ; i < receivedArray.size() ; i++){ + string element = receivedArray[i]; + printf("received array[%d] = %s\n", i, element.c_str()); + } + + // JSArray to JSArray Copy test + JSStringArray copyTest(ctx); + copyTest = receivedArray; + + for( unsigned int i = 0 ; i < copyTest.size() ; i++){ + string element = copyTest[i]; + printf("copyTest array[%d] = %s\n", i, element.c_str()); + } + + // to Native Vector converting test + vector<string> tmp = receivedArray; + for( unsigned int i = 0 ; i < tmp.size() ; i++){ + printf("to Native Vector [%d] = %s\n", i, tmp[i].c_str()); + } + + //Copy from vector + vector<string> aa; + aa.push_back("one"); + aa.push_back("two"); + aa.push_back("three"); + JSStringArray newArray(ctx); + newArray = aa; + for( unsigned int i = 0 ; i < newArray.size() ; i++){ + string element = newArray[i]; + printf("Copy from Vector[%d] = %s\n", i, element.c_str()); + } + + // Modification test + newArray[newArray.size()] = "last"; + newArray[0] = "zero"; + printf("Modification test\n"); + printf("except:zero,two,three,last\n"); + + return newArray; + } + else if( type == "Long" && jsArray != NULL ){ + JSLongArray receivedArray(ctx, jsArray); + + //Basic getting test + for( unsigned int i = 0 ; i < receivedArray.size() ; i++){ + long v = receivedArray[i]; + printf("received array[%d] = %d\n", i, v ); + } + + // JSArray to JSArray Copy test + JSLongArray copyTest(ctx); + copyTest = receivedArray; + + for( unsigned int i = 0 ; i < copyTest.size() ; i++){ + long v = copyTest[i]; + printf("copyTest array[%d] = %d\n", i, v); + } + + // to Native Vector converting test + vector<long> tmp = receivedArray; + for( unsigned int i = 0 ; i < tmp.size() ; i++){ + printf("to Native Vector [%d] = %d\n", i, tmp[i]); + } + + //Copy from vector + vector<long> aa; + aa.push_back(1); + aa.push_back(2); + aa.push_back(3); + JSLongArray newArray(ctx); + newArray = aa; + for( unsigned int i = 0 ; i < newArray.size() ; i++){ + long v = newArray[i]; + printf("Copy from Vector[%d] = %d\n", i, v); + } + + // Modification test + newArray[newArray.size()] = 99; + newArray[0] = 0; + printf("Modification test\n"); + printf("except:0,2,3,99\n"); + + return newArray; + } + else if( type == "Boolean" && jsArray != NULL ){ + JSArray<bool> receivedArray(ctx, jsArray, JSUtil::JSValueToBoolean, makeJSBool); + + //Basic getting test + for( unsigned int i = 0 ; i < receivedArray.size() ; i++){ + printf("received array[%d] = %s\n", i, receivedArray[i] ? "true" : "false" ); + } + + // JSArray to JSArray Copy test + JSArray<bool> copyTest(ctx, JSUtil::JSValueToBoolean, makeJSBool); + copyTest = receivedArray; + + for( unsigned int i = 0 ; i < copyTest.size() ; i++){ + printf("copyTest array[%d] = %s\n", i, copyTest[i] ? "true" : "false" ); + } + + // to Native Vector converting test + vector<bool> tmp = receivedArray; + for( unsigned int i = 0 ; i < tmp.size() ; i++){ + printf("to Native Vector[%d] = %s\n", i, tmp[i] ? "true" : "false" ); + } + + //Copy from vector + vector<bool> aa; + aa.push_back(true); + aa.push_back(false); + aa.push_back(true); + JSArray<bool> newArray(ctx, JSUtil::JSValueToBoolean, makeJSBool); + newArray = aa; + for( unsigned int i = 0 ; i < newArray.size() ; i++){ + printf("Copy from Vector[%d] = %s\n", i, newArray[i] ? "true" : "false" ); + } + + // Modification test + newArray[newArray.size()] = true; + newArray[0] = false; + printf("Modification test\n"); + printf("except:false,false,true,false\n"); + return newArray; + + } + else if( type == "NestedValue" && jsArray != NULL ){ + JSArray<boost::shared_ptr<NestedValue>> receivedArray(ctx, jsArray, JSNestedValue::getNative, makeNestedValue); + for( unsigned int i = 0 ; i< receivedArray.size() ; i++){ + boost::shared_ptr<NestedValue> ptr = receivedArray[i]; + ptr->print(); + } + JSArray<boost::shared_ptr<NestedValue>> newArray(ctx, JSNestedValue::getNative, makeNestedValue); + newArray = receivedArray; + newArray[0] = boost::shared_ptr<NestedValue>(new NestedValue(0, "newAdded!")); + for( unsigned int i = 0 ; i< newArray.size() ; i++){ + boost::shared_ptr<NestedValue> ptr = newArray[i]; + ptr->print(); + } + return newArray; + } + else{ + printf("usage: arraytest([Long|String|Boolean], array)\n"); + return JSUtil::toJSValueRef(ctx, "usage: arraytest([Long|String|Boolean], array)"); + } + return JSValueMakeUndefined(ctx); + }catch( const TypeMismatchException& err ){ + printf("TypeMismatch exception %s : %s\n", err.getName().c_str(), err.getMessage().c_str()); + return JSWebAPIErrorFactory::postException(ctx, exception, err); + }catch( const BasePlatformException& err){ + printf("exception %s : %s\n", err.getName().c_str(), err.getMessage().c_str()); + return JSWebAPIErrorFactory::postException(ctx, exception, err); + } + return JSValueMakeUndefined(ctx); + +} + +JSValueRef JSRefImplManager::addListener(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception){ + try{ + ArgumentValidator validator(ctx, argumentCount, arguments); + JSObjectRef fun = validator.toFunction(0); + boost::shared_ptr<CallbackUserData> callback(new CallbackUserData(GlobalContextManager::getInstance()->getGlobalContext(ctx))); + callback->setSuccessCallback(fun); + long id = RefImplManager::getInstance()->addListener(callback); + return JSUtil::toJSValueRef(ctx, id); + }catch( const BasePlatformException& err){ + return JSWebAPIErrorFactory::postException(ctx, exception, err); + } + return JSValueMakeUndefined(ctx); +} + +JSValueRef JSRefImplManager::removeListener(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception){ + try{ + ArgumentValidator validator(ctx, argumentCount, arguments); + int id = validator.toLong(0); + RefImplManager::getInstance()->removeListener(id); + }catch( const BasePlatformException& err){ + return JSWebAPIErrorFactory::postException(ctx, exception, err); + } + return JSValueMakeUndefined(ctx); +} + +JSValueRef JSRefImplManager::fire(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception){ + RefImplManager::getInstance()->fireListener(); + return JSValueMakeUndefined(ctx); +} + + + +JSValueRef JSRefImplManager::isSuper(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception){ + try{ + ArgumentValidator validator(ctx, argumentCount, arguments); + JSObjectRef test = validator.toObject(0); + if( JSValueIsObjectOfClass(ctx, test, JSSuper::getClassRef()) ) + return JSUtil::toJSValueRef(ctx, true); + else + return JSUtil::toJSValueRef(ctx, false); + }catch( const BasePlatformException& err){ + printf("exception %s %s\n", err.getName().c_str(), err.getMessage().c_str()); + return JSWebAPIErrorFactory::postException(ctx, exception, err); + } + return JSValueMakeUndefined(ctx); +} + +JSValueRef JSRefImplManager::isSub(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception){ + try{ + ArgumentValidator validator(ctx, argumentCount, arguments); + JSObjectRef test = validator.toObject(0); + if( JSValueIsObjectOfClass(ctx, test, JSSub::getClassRef()) ) + return JSUtil::toJSValueRef(ctx, true); + else + return JSUtil::toJSValueRef(ctx, false); + }catch( const BasePlatformException& err){ + printf("exception %s %s\n", err.getName().c_str(), err.getMessage().c_str()); + return JSWebAPIErrorFactory::postException(ctx, exception, err); + } + return JSValueMakeUndefined(ctx); +} + +JSValueRef JSRefImplManager::setCallback(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception){ + try{ + ArgumentValidator validator(ctx, argumentCount, arguments); + JSObjectRef jsCallbackObj = validator.toObject(0); + boost::shared_ptr<MultiCallbackUserData> callback(new MultiCallbackUserData(GlobalContextManager::getInstance()->getGlobalContext(ctx), jsCallbackObj)); + RefImplManager::getInstance()->setCallbackObject(GlobalContextManager::getInstance()->getGlobalContext(ctx), callback); + }catch( const BasePlatformException& err){ + return JSWebAPIErrorFactory::postException(ctx, exception, err); + } + return JSValueMakeUndefined(ctx); +} +JSValueRef JSRefImplManager::unsetCallback(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception){ + RefImplManager::getInstance()->unsetCallbackObject(GlobalContextManager::getInstance()->getGlobalContext(ctx)); + return JSValueMakeUndefined(ctx); +} +JSValueRef JSRefImplManager::fireCallback(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception){ + try{ + ArgumentValidator validator(ctx, argumentCount, arguments); + string functionName= validator.toString(0); + RefImplManager::getInstance()->namedCallbackFire(GlobalContextManager::getInstance()->getGlobalContext(ctx), functionName.c_str()); + }catch( const BasePlatformException& err){ + return JSWebAPIErrorFactory::postException(ctx, exception, err); + } + return JSValueMakeUndefined(ctx); +} + +JSValueRef JSRefImplManager::callbackObjectTest(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception){ + try{ + printf("validator.toCallbackObject(0, true, \"fun1\", \"fun2\", \"fun3\", NULL);\n"); + ArgumentValidator validator(ctx, argumentCount, arguments); + JSObjectRef obj = validator.toCallbackObject(0, true, "fun1", "fun2", "fun3", NULL); + printf("returnd obj = %p\n", obj); + }catch( const BasePlatformException& err){ + printf("exception %s %s\n", err.getName().c_str(), err.getMessage().c_str()); + } + try{ + printf("validator.toCallbackObject(0, false, \"fun1\", \"fun2\", \"fun3\", NULL);\n"); + ArgumentValidator validator(ctx, argumentCount, arguments); + JSObjectRef obj = validator.toCallbackObject(0, false, "fun1", "fun2", "fun3", NULL); + printf("returnd obj = %p\n", obj); + }catch( const BasePlatformException& err){ + printf("exception %s %s\n", err.getName().c_str(), err.getMessage().c_str()); + } + + return JSValueMakeUndefined(ctx); +} + +JSValueRef JSRefImplManager::updateNumber(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception){ + try{ + ArgumentValidator validator(ctx, argumentCount, arguments); + int readonlyValue= validator.toLong(0); + RefImplManager::getInstance()->mLocalProperty.setProperty(ctx, "Number", (double)readonlyValue); + }catch( const BasePlatformException& err){ + return JSWebAPIErrorFactory::postException(ctx, exception, err); + } + return JSValueMakeUndefined(ctx); +} + +JSValueRef JSRefImplManager::updateSub(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception){ + try{ + ArgumentValidator validator(ctx, argumentCount, arguments); + JSObjectRef o = validator.toObject(0, JSSub::getClassRef()); + RefImplManager::getInstance()->mLocalProperty.setProperty(ctx, "Sub", o); + }catch( const BasePlatformException& err){ + return JSWebAPIErrorFactory::postException(ctx, exception, err); + } + return JSValueMakeUndefined(ctx); +} + +} // Reference +} // TizenApis + diff --git a/wearable_src/RefImpl/JSRefImplManager.h b/wearable_src/RefImpl/JSRefImplManager.h new file mode 100644 index 0000000..97084d0 --- /dev/null +++ b/wearable_src/RefImpl/JSRefImplManager.h @@ -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. + */ + + +#ifndef _JS_REFIMPL_MANAGER_H_ +#define _JS_REFIMPL_MANAGER_H_ + +#include <string> +#include <JavaScriptCore/JavaScript.h> + +namespace DeviceAPI { +namespace Reference { + +class JSRefImplManager +{ + public: + + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + + private: + static JSClassDefinition m_jsClassInfo; + static JSClassRef m_jsClassRef; + + static JSStaticFunction m_function[]; + static JSStaticValue m_property[]; + + + static void initialize(JSContextRef context, JSObjectRef object); + static void finalize(JSObjectRef object); + + static JSValueRef getReadOnlyNumber(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + static JSValueRef getReadOnlySub(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + static JSValueRef getNormalProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + static bool setNormalProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef value, JSValueRef* exception); + + static JSValueRef syncToSync(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + static JSValueRef syncToAsync(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + static JSValueRef asyncToAsync(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + static JSValueRef argtest(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + static JSValueRef arraytest(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + static JSValueRef callbackObjectTest(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + + + + static JSValueRef addListener(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + static JSValueRef removeListener(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + static JSValueRef fire(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + + static JSValueRef isSuper(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + static JSValueRef isSub(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + + static JSValueRef setCallback(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + static JSValueRef unsetCallback(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + static JSValueRef fireCallback(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + + static JSValueRef updateNumber(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + static JSValueRef updateSub(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + + + +}; + +} +} + +#endif /* _JS_REFIMPL_MANAGER_H_ */ + + diff --git a/wearable_src/RefImpl/JSSub.cpp b/wearable_src/RefImpl/JSSub.cpp new file mode 100755 index 0000000..6534769 --- /dev/null +++ b/wearable_src/RefImpl/JSSub.cpp @@ -0,0 +1,101 @@ +#include "JSSuper.h" +#include "JSSub.h" + +#include <ArgumentValidator.h> +#include <PlatformException.h> +#include <JSWebAPIErrorFactory.h> +#include <JSUtil.h> +#include "Sub.h" + +using namespace DeviceAPI::Common; + + +namespace DeviceAPI { +namespace Reference { + +JSClassRef JSSub::m_jsClassRef = NULL; + +JSClassDefinition JSSub::m_jsClassInfo = { + 0, // current (and only) version is 0 + kJSClassAttributeNone, //attributes + "Sub", //class name + JSSuper::getClassRef(), // parent class + NULL, //static values + JSSub::m_function, // static functions + JSSub::initialize, // initialize + JSSub::finalize, //finalize + NULL, //hasProperty + NULL, //getProperty + NULL, //setProperty + NULL, //deleteProperty + NULL, //getPropertyNames + NULL, // callAsFunction + NULL, // constructor + NULL, + NULL // convertToType +}; + + +JSStaticFunction JSSub::m_function[] = { + { "extend", JSSub::extend, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + + +const JSClassRef JSSub::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_jsClassInfo); + } + return m_jsClassRef; +} +const JSClassDefinition* JSSub::getClassInfo() +{ + return &m_jsClassInfo; +} + +JSObjectRef JSSub::constructor(JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception){ + printf("JSSub::constructor()\n"); + ArgumentValidator validator(ctx, argumentCount, arguments); + try{ + int a = validator.toLong(0); + if( a == 2) + throw InvalidValuesException("2 is invalid value"); + }catch(const BasePlatformException& err){ + JSObjectRef error = JSWebAPIErrorFactory::makeErrorObject(ctx, err); + *exception = error; + return error; + } + Sub *priv = new Sub(); + JSObjectRef obj = JSObjectMake(ctx, getClassRef(), priv); + JSUtil::setProperty(ctx, obj, "constructor", constructor, kJSPropertyAttributeReadOnly|kJSPropertyAttributeDontDelete|kJSPropertyAttributeDontEnum); + return obj; +} + +void JSSub::initialize(JSContextRef ctx, JSObjectRef object) +{ + printf("JSSub::initialize()\n"); +} + +void JSSub::finalize(JSObjectRef object) +{ + printf("JSSub::finalize()\n"); + Sub * priv = static_cast<Sub*>(JSObjectGetPrivate(object)); + if( priv ){ + JSObjectSetPrivate(object, NULL); + delete priv; + } +} + +JSValueRef JSSub::extend(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception){ + printf("JSSub::extend()\n"); + Sub * priv = static_cast<Sub*>(JSObjectGetPrivate(thisObject)); + if( priv ) + priv->extend(); + return JSValueMakeUndefined(ctx); +} + + +} // Reference +} // TizenApis + diff --git a/wearable_src/RefImpl/JSSub.h b/wearable_src/RefImpl/JSSub.h new file mode 100755 index 0000000..96e5dd8 --- /dev/null +++ b/wearable_src/RefImpl/JSSub.h @@ -0,0 +1,39 @@ +#ifndef _JS_SUB_H_ +#define _JS_SUB_H_ + +#include <string> +#include <JavaScriptCore/JavaScript.h> + +namespace DeviceAPI { +namespace Reference { + +class JSSub +{ + public: + + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + + static JSObjectRef constructor(JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + + private: + + static JSClassDefinition m_jsClassInfo; + static JSClassRef m_jsClassRef; + static JSStaticFunction m_function[]; + + + static void initialize(JSContextRef context, JSObjectRef object); + static void finalize(JSObjectRef object); + + static JSValueRef extend(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + +}; + +} +} + +#endif /* _JS_SUB_H_ */ + + + diff --git a/wearable_src/RefImpl/JSSuper.cpp b/wearable_src/RefImpl/JSSuper.cpp new file mode 100755 index 0000000..2fe9503 --- /dev/null +++ b/wearable_src/RefImpl/JSSuper.cpp @@ -0,0 +1,97 @@ +#include "JSSuper.h" +#include <JSWebAPIErrorFactory.h> +#include <JSUtil.h> +#include "Super.h" + +using namespace DeviceAPI::Common; + + + +namespace DeviceAPI { +namespace Reference { + +JSClassRef JSSuper::m_jsClassRef = NULL; + +JSClassDefinition JSSuper::m_jsClassInfo = { + 0, // current (and only) version is 0 + kJSClassAttributeNone, //attributes + "Super", //class name + NULL, // parent class + NULL, //static values + JSSuper::m_function, // static functions + JSSuper::initialize, // initialize + JSSuper::finalize, //finalize + NULL, //hasProperty + NULL, //getProperty + NULL, //setProperty + NULL, //deleteProperty + NULL, //getPropertyNames + NULL, // callAsFunction + NULL, // constructor + NULL, //hasInstance + NULL // convertToType +}; + + +JSStaticFunction JSSuper::m_function[] = { + { "base", JSSuper::base, kJSPropertyAttributeNone }, + { "override", JSSuper::override, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +const JSClassRef JSSuper::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_jsClassInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSSuper::getClassInfo() +{ + return &m_jsClassInfo; +} + +void JSSuper::initialize(JSContextRef ctx, JSObjectRef object) +{ + printf("JSSuper::initialize()\n"); +} + +void JSSuper::finalize(JSObjectRef object) +{ + printf("JSSuper::finalize()\n"); + Super * priv = static_cast<Super*>(JSObjectGetPrivate(object)); + if( priv ){ + JSObjectSetPrivate(object, NULL); + delete priv; + } +} + +JSObjectRef JSSuper::constructor(JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception){ + printf("JSSuper::constructor()\n"); + Super * priv = new Super(); + JSObjectRef obj = JSObjectMake(ctx, getClassRef(), priv); + JSUtil::setProperty(ctx, obj, "constructor", constructor, kJSPropertyAttributeReadOnly|kJSPropertyAttributeDontDelete|kJSPropertyAttributeDontEnum); + return obj; +} + +JSValueRef JSSuper::base(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception){ + printf("JSSuper::base()\n"); + Super * priv = static_cast<Super*>(JSObjectGetPrivate(thisObject)); + if( priv ) + priv->base(); + return JSValueMakeUndefined(ctx); +} + +JSValueRef JSSuper::override(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception){ + printf("JSSuper::override()\n"); + Super * priv = static_cast<Super*>(JSObjectGetPrivate(thisObject)); + priv->override(); + return JSValueMakeUndefined(ctx); +} + + + +} // Reference +} // TizenApis + diff --git a/wearable_src/RefImpl/JSSuper.h b/wearable_src/RefImpl/JSSuper.h new file mode 100755 index 0000000..5345b4a --- /dev/null +++ b/wearable_src/RefImpl/JSSuper.h @@ -0,0 +1,38 @@ +#ifndef _JS_SUPER_H_ +#define _JS_SUPER_H_ + +#include <string> +#include <JavaScriptCore/JavaScript.h> + +namespace DeviceAPI { +namespace Reference { + +class JSSuper +{ + public: + + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSObjectRef constructor(JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + + private: + + static JSClassDefinition m_jsClassInfo; + static JSClassRef m_jsClassRef; + static JSStaticFunction m_function[]; + + static void initialize(JSContextRef context, JSObjectRef object); + static void finalize(JSObjectRef object); + static JSValueRef base(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + static JSValueRef override(JSContextRef ctx, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + + +}; + +} +} + +#endif /* _JS_SUPER_H_ */ + + + diff --git a/wearable_src/RefImpl/NestedValue.cpp b/wearable_src/RefImpl/NestedValue.cpp new file mode 100755 index 0000000..24856b2 --- /dev/null +++ b/wearable_src/RefImpl/NestedValue.cpp @@ -0,0 +1,38 @@ +#include "NestedValue.h" + +using namespace std; + +namespace DeviceAPI { +namespace Reference { + +NestedValue::NestedValue():mNumber(0){ +} + +NestedValue::NestedValue(long number, const string &message ):mNumber(number), mMessage(message){ +} + +NestedValue::~NestedValue(){ +} + +long NestedValue::getNumber() const{ + return mNumber; +} + +const string& NestedValue::getMessage() const{ + return mMessage; +} + +void NestedValue::setNumber(long v){ + mNumber = v; +} + +void NestedValue::setMessage(const string & msg){ + mMessage = msg; +} + +void NestedValue::print(){ + printf("%d)%s\n", mNumber, mMessage.c_str()); +} + +} +} diff --git a/wearable_src/RefImpl/NestedValue.h b/wearable_src/RefImpl/NestedValue.h new file mode 100755 index 0000000..3be2be6 --- /dev/null +++ b/wearable_src/RefImpl/NestedValue.h @@ -0,0 +1,30 @@ +#ifndef _REFIMPL_NESTEDVALUE_H_ +#define _REFIMPL_NESTEDVALUE_H_ + +#include <string> + +namespace DeviceAPI { +namespace Reference { + +class NestedValue{ +public: + NestedValue(); + NestedValue(long number, const std::string &message); + virtual ~NestedValue(); + long getNumber() const; + const std::string& getMessage() const; + + void setNumber(long v); + void setMessage(const std::string &msg); + void print(); + +private: + long mNumber; + std::string mMessage; + +}; + +} +} + +#endif //_REFIMPL_NESTEDVALUE_H_ diff --git a/wearable_src/RefImpl/RefImplManager.cpp b/wearable_src/RefImpl/RefImplManager.cpp new file mode 100755 index 0000000..9723a4a --- /dev/null +++ b/wearable_src/RefImpl/RefImplManager.cpp @@ -0,0 +1,190 @@ +/* + * 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. + */ + +#include "RefImplManager.h" +#include "mock.h" +#include <Ecore.h> +#include <CommonsJavaScript/Converter.h> +#include <JSWebAPIErrorFactory.h> +#include <PlatformException.h> + + +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace DeviceAPI::Common; +using namespace std; + +namespace DeviceAPI { +namespace Reference{ + +static void* workerThread(void *data); +//static void workerThread(void *data, Ecore_Thread *thread); +static Eina_Bool jobCompleteCB(void *data); +//static void jobCompleteCB(void *data, Ecore_Thread *thread); +static void platformCB( int result , void *user_data); + +//static void workerThread(void *data, Ecore_Thread *thread){ +static void* workerThread(void *data){ + RefCallbackUserData * callback = static_cast<RefCallbackUserData*>(data); + callback->result = mock_delayed_sync_function(callback->a, callback->b); + ecore_idler_add(jobCompleteCB, data); + return NULL; +} + +//static void jobCompleteCB(void *data, Ecore_Thread *thread){ +static Eina_Bool jobCompleteCB(void *data){ + RefCallbackUserData * callback = static_cast<RefCallbackUserData*>(data); + Converter convert(callback->getContext()); + if( callback->result == 44 ){ + JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(callback->getContext(), JSWebAPIErrorFactory::IO_ERROR, "44 is I/O Error"); + callback->callErrorCallback(errobj); + }else{ + JSValueRef result = convert.toJSValueRef(callback->result); + callback->callSuccessCallback(result); + } + delete callback; + return false; +} + +int RefImplManager::syncToSync(int a, int b){ + if( a == 5 ) + throw InvalidValuesException("5 is not allowed"); + + int ret = mock_sync_function(a,b); + if( ret == 44 ) + throw IOException("44 is I/O error"); + return ret; +} + +void RefImplManager::syncToAsync( RefCallbackUserData * callback ){ + if( callback->a == 5 ) + throw InvalidValuesException("5 is not allowed"); + //Ecore_Thread *tid = ecore_thread_run( workerThread, jobCompleteCB, NULL, callback); + pthread_t thread; + pthread_create(&thread, NULL, workerThread, callback); + pthread_detach(thread); +} + + +static void platformCB( int result , void *user_data){ + RefCallbackUserData * callback = static_cast<RefCallbackUserData*>(user_data); + Converter convert(callback->getContext()); + if( result == 44 ){ + JSObjectRef errobj = JSWebAPIErrorFactory::makeErrorObject(callback->getContext(), JSWebAPIErrorFactory::IO_ERROR, "44 is I/O Error"); + callback->callErrorCallback(errobj); + }else{ + JSValueRef jsresult = convert.toJSValueRef(result); + callback->callSuccessCallback(jsresult); + } + delete callback; +} + +void RefImplManager::asyncToAsync( RefCallbackUserData * callback ){ + if( callback->a == 5 ) + throw InvalidValuesException("5 is not allowed"); + + mock_async_function(callback->a, callback->b, platformCB, callback); +} + + +RefImplManager* RefImplManager::getInstance(){ + static RefImplManager instance; + return &instance; +} + +int RefImplManager::onFire(void* user_data){ + RefImplManager* obj = static_cast<RefImplManager*>(user_data); + obj->broadCast(); + return false; +} + +void RefImplManager::fireListener(){ + g_idle_add(onFire, this); +} + +int RefImplManager::addListener(boost::shared_ptr<CallbackUserData> callback){ + int id = mCounter++; + mListenerList.insert(listenerT(id, callback)); + return id; +} + +void RefImplManager::removeListener(int id){ + map<int, boost::shared_ptr<Common::CallbackUserData>>::iterator itr; + itr = mListenerList.find(id); + if( itr != mListenerList.end() ){ + mListenerList.erase(itr); + } +} + +void RefImplManager::broadCast(){ + map<int, boost::shared_ptr<Common::CallbackUserData>> tmplist(mListenerList); + map<int, boost::shared_ptr<Common::CallbackUserData>>::iterator itr; + itr = tmplist.begin(); + while( itr != tmplist.end() ){ + boost::shared_ptr<Common::CallbackUserData> callback = (*itr).second; + callback->callSuccessCallback(); + ++itr; + } +} + + +void RefImplManager::setCallbackObject( JSContextRef context, boost::shared_ptr<Common::MultiCallbackUserData> callback){ + mCallbackList[context] = callback; +} +void RefImplManager::unsetCallbackObject( JSContextRef context ){ + mCallbackList.erase(context); +} + +struct NamedCallbackData{ + JSContextRef context; + std::string name; + RefImplManager* obj; +}; + +void RefImplManager::namedCallbackFire(JSContextRef context, const char *callbackName){ + struct NamedCallbackData * data = new NamedCallbackData(); + data->context = context; + data->name = callbackName; + data->obj = this; + g_idle_add(onNamedFire, data); +} + +int RefImplManager::onNamedFire(void* user_data){ + struct NamedCallbackData * data = static_cast<NamedCallbackData*>(user_data); + data->obj->namedBroadCast(data->context, data->name.c_str()); + delete data; + return false; +} + +void RefImplManager::namedBroadCast(JSContextRef context, const char *callbackName){ + map<JSContextRef, boost::shared_ptr<Common::MultiCallbackUserData>>::iterator itr; + itr = mCallbackList.find(context); + if( itr != mCallbackList.end() ){ + mCallbackList[context]->invokeCallback(callbackName); + } +} + + +RefImplManager::RefImplManager():mCounter(0){ +} +RefImplManager::~RefImplManager(){ +} + + + +} +} + diff --git a/wearable_src/RefImpl/RefImplManager.h b/wearable_src/RefImpl/RefImplManager.h new file mode 100755 index 0000000..7e4da9a --- /dev/null +++ b/wearable_src/RefImpl/RefImplManager.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. + */ + +#ifndef _REFIMPLMANAGER_ +#define _REFIMPLMANAGER_ + +#include <string> +#include <stdio.h> +#include <CallbackUserData.h> +#include <MultiCallbackUserData.h> +#include <boost/shared_ptr.hpp> +#include <map> +#include <PropertyBag.h> + +namespace DeviceAPI { +namespace Reference{ + +class RefCallbackUserData : public Common::CallbackUserData{ + public: + RefCallbackUserData(JSContextRef globalCtx, int aa, int bb):CallbackUserData(globalCtx), a(aa), b(bb), result(0){} + int a; + int b; + int result; +}; + +class RefImplManager{ + public: + int syncToSync(int a, int b); + void syncToAsync(RefCallbackUserData *callback); + void asyncToAsync(RefCallbackUserData *callback); + + //for multiple callback + int addListener(boost::shared_ptr<Common::CallbackUserData> callback); + void removeListener(int id); + void fireListener(); + + // for single callbcak object per one global context + void setCallbackObject( JSContextRef context, boost::shared_ptr<Common::MultiCallbackUserData> callback); + void unsetCallbackObject( JSContextRef context ); + void namedCallbackFire(JSContextRef context, const char *callbackName); + + static RefImplManager* getInstance(); + Common::PropertyBag mLocalProperty; + + private: + int mCounter; + typedef std::pair<int, boost::shared_ptr<Common::CallbackUserData>> listenerT; + std::map<int, boost::shared_ptr<Common::CallbackUserData>> mListenerList; + typedef std::pair<JSContextRef, boost::shared_ptr<Common::MultiCallbackUserData>> callbackObjectT; + std::map<JSContextRef, boost::shared_ptr<Common::MultiCallbackUserData>> mCallbackList; + + RefImplManager(); + ~RefImplManager(); + static int onFire(void* user_data); + static int onNamedFire(void* user_data); + void broadCast(); + void namedBroadCast(JSContextRef context, const char *callbackName); + +}; + + + +} +} + +#endif //_REFIMPLMANAGER_ + diff --git a/wearable_src/RefImpl/Sub.cpp b/wearable_src/RefImpl/Sub.cpp new file mode 100755 index 0000000..2782941 --- /dev/null +++ b/wearable_src/RefImpl/Sub.cpp @@ -0,0 +1,17 @@ +#include "Sub.h" +#include <stdio.h> +Sub::Sub(){ + printf("Sub C++ constructor\n"); +} + +Sub::~Sub(){ + printf("Sub C++ destroy\n"); +} + +void Sub::extend(){ + printf("Sub::extend()\n"); +} + +void Sub::override(){ + printf("Sub::override()\n"); +} diff --git a/wearable_src/RefImpl/Sub.h b/wearable_src/RefImpl/Sub.h new file mode 100755 index 0000000..d9e39ef --- /dev/null +++ b/wearable_src/RefImpl/Sub.h @@ -0,0 +1,15 @@ +#ifndef _SUB_H_ +#define _SUB_H_ + +#include "Super.h" + +class Sub : public Super { +public: + Sub(); + virtual ~Sub(); + void extend(); + virtual void override(); +}; + +#endif //_SUB_H_ + diff --git a/wearable_src/RefImpl/Super.cpp b/wearable_src/RefImpl/Super.cpp new file mode 100755 index 0000000..81e47ee --- /dev/null +++ b/wearable_src/RefImpl/Super.cpp @@ -0,0 +1,18 @@ +#include "Super.h" +#include <stdio.h> + + +Super::Super(){ + printf("Super c++ constructor\n"); +} +Super::~Super(){ + printf("Super c++ destroy\n"); +} + +void Super::base(){ + printf("Super::base()\n"); +} + +void Super::override(){ + printf("Super::override()\n"); +} diff --git a/wearable_src/RefImpl/Super.h b/wearable_src/RefImpl/Super.h new file mode 100755 index 0000000..21c45e1 --- /dev/null +++ b/wearable_src/RefImpl/Super.h @@ -0,0 +1,12 @@ +#ifndef _SUPER_H_ +#define _SUPER_H_ + +class Super { +public: + Super(); + virtual ~Super(); + void base(); + virtual void override(); +}; + +#endif //_SUPER_H_
\ No newline at end of file diff --git a/wearable_src/RefImpl/config.xml b/wearable_src/RefImpl/config.xml new file mode 100755 index 0000000..f13ba9c --- /dev/null +++ b/wearable_src/RefImpl/config.xml @@ -0,0 +1,12 @@ +<?xml version="1.0" ?> +<!DOCTYPE plugin-properties SYSTEM "/usr/etc/tizen-apis/config.dtd"> +<plugin-properties> + <library-name>libwrt-plugins-tizen-refimpl.so</library-name> + <feature-install-uri>efimpl.install.uri</feature-install-uri> + + <api-feature> + <name>http://tizen.org/privilege/refimpl</name> + <device-capability>refimpl</device-capability> + </api-feature> + +</plugin-properties> diff --git a/wearable_src/RefImpl/mock.cpp b/wearable_src/RefImpl/mock.cpp new file mode 100755 index 0000000..c5854b8 --- /dev/null +++ b/wearable_src/RefImpl/mock.cpp @@ -0,0 +1,61 @@ +#include "mock.h" +#include <Ecore.h> +#include <pthread.h> +#include <unistd.h> +#include <dlog.h> +#include <glib.h> + +#undef LOG_TAG +#define LOG_TAG "TIZEN_DEVICEAPI" + + +struct worker_data{ + int a; + int b; + async_cb callback; + void * user_data; + int result; +}; + +static void* worker_function(void *arg); +static int threadsafe_function(void *arg); + + +int mock_sync_function(int a, int b){ + return a+b; +} +int mock_delayed_sync_function(int a, int b){ + sleep(2); + return a+b; +} + + +int mock_async_function( int a, int b, async_cb callback, void *user_data){ + pthread_t thread; + worker_data *data = new worker_data(); + data->a = a; + data->b = b; + data->callback = callback; + data->user_data = user_data; + pthread_create(&thread, NULL, worker_function, data); + pthread_detach(thread); + return 0; +} + + +static void* worker_function(void *arg){ + static int count = 0; + worker_data *data = (worker_data*)arg; + data->result = mock_delayed_sync_function(data->a, data->b); + g_idle_add(threadsafe_function, data); + return NULL; +} + +static int threadsafe_function(void *arg){ + worker_data *data = (worker_data*)arg; + if( data->callback ) + data->callback(data->result, data->user_data); + delete data; + return false; +} + diff --git a/wearable_src/RefImpl/mock.h b/wearable_src/RefImpl/mock.h new file mode 100755 index 0000000..5711ec0 --- /dev/null +++ b/wearable_src/RefImpl/mock.h @@ -0,0 +1,8 @@ + +typedef void (* async_cb)( int result , void *user_data); + + +int mock_sync_function(int a, int b); +int mock_delayed_sync_function(int a, int b); +int mock_async_function(int a, int b, async_cb callback, void *user_data); + diff --git a/wearable_src/RefImpl/plugin_initializer.cpp b/wearable_src/RefImpl/plugin_initializer.cpp new file mode 100644 index 0000000..12cabd1 --- /dev/null +++ b/wearable_src/RefImpl/plugin_initializer.cpp @@ -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. + */ + +#include <Commons/plugin_initializer_def.h> +#include <Commons/WrtAccess/WrtAccess.h> +#include <Commons/Exception.h> +#include "JSRefImplManager.h" +#include "JSSub.h" +#include "JSSuper.h" +#include "JSNestedValue.h" +#include <GlobalContextManager.h> +#include <Logger.h> + +namespace DeviceAPI { +namespace Reference { + +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; +using namespace DeviceAPI::Common; + +class_definition_options_t TizenInterfaceOptions = { + JS_INTERFACE, + CREATE_INSTANCE, + NONE_NOTICE, + USE_OVERLAYED, //ignored + NULL, // JSWidget::acquireGlobalContext, + NULL, + NULL +}; + +void on_widget_start_callback(int widgetId) +{ + LoggerD("[Tizen\\Power] on_widget_start_callback (" << widgetId << ")"); + + Try { + WrtAccessSingleton::Instance().initialize(widgetId); + } Catch (Exception) { + LoggerE("WrtAccess initialization failed"); + } +} + +void on_widget_stop_callback(int widgetId) +{ + LoggerD("[Tizen\\Power] on_widget_stop_callback (" << widgetId << ")"); + + Try { + WrtAccessSingleton::Instance().deinitialize(widgetId); + } Catch (Exception) { + LoggerE("WrtAccess deinitialization failed"); + } +} + +void on_frame_load_callback(const void * context) +{ + LoggerD("[Tizen\\Power] on_frame_load_callback (" << context << ")"); + GlobalContextManager::getInstance()->addGlobalContext(static_cast<JSContextRef>(context)); +} + +void on_frame_unload_callback(const void * context) +{ + LoggerD("[Tizen\\Power] on_frame_unload_callback (" << context << ")"); + GlobalContextManager::getInstance()->removeGlobalContext(static_cast<JSContextRef>(context)); +} + +PLUGIN_ON_WIDGET_START(on_widget_start_callback) +PLUGIN_ON_WIDGET_STOP(on_widget_stop_callback) + +PLUGIN_ON_FRAME_LOAD(on_frame_load_callback) +PLUGIN_ON_FRAME_UNLOAD(on_frame_unload_callback) + +PLUGIN_CLASS_MAP_BEGIN +PLUGIN_CLASS_MAP_ADD_CLASS(WRT_JS_EXTENSION_OBJECT_TIZEN, + "RefImpl", + (js_class_template_getter)JSRefImplManager::getClassRef, + NULL) +PLUGIN_CLASS_MAP_ADD_INTERFACE(WRT_JS_EXTENSION_OBJECT_TIZEN, + "Sub", + (js_class_template_getter)DeviceAPI::Reference::JSSub::getClassRef, + (js_class_constructor_cb_t)DeviceAPI::Reference::JSSub::constructor, + &TizenInterfaceOptions) +PLUGIN_CLASS_MAP_ADD_INTERFACE(WRT_JS_EXTENSION_OBJECT_TIZEN, + "Super", + (js_class_template_getter)DeviceAPI::Reference::JSSuper::getClassRef, + (js_class_constructor_cb_t)DeviceAPI::Reference::JSSuper::constructor, + &TizenInterfaceOptions) +PLUGIN_CLASS_MAP_ADD_INTERFACE(WRT_JS_EXTENSION_OBJECT_TIZEN, + "NestedValue", + (js_class_template_getter)DeviceAPI::Reference::JSNestedValue::getClassRef, + (js_class_constructor_cb_t)DeviceAPI::Reference::JSNestedValue::constructor, + &TizenInterfaceOptions) +PLUGIN_CLASS_MAP_END + +} +} + diff --git a/wearable_src/RefImpl/test/CMakeLists.txt b/wearable_src/RefImpl/test/CMakeLists.txt new file mode 100755 index 0000000..4cfb2aa --- /dev/null +++ b/wearable_src/RefImpl/test/CMakeLists.txt @@ -0,0 +1,26 @@ +SET(TARGET_NAME ${refimpl_target}_test) + +include_directories( + ${TOP}/Common + ${TOP}/RefImpl + ${TOP}/Common/StandaloneConsole +) + +set(CMAKE_INSTALL_RPATH + ${CMAKE_INSTALL_RPATH} + ${CMAKE_INSTALL_PREFIX}/${DESTINATION_LIB_PREFIX}/${tizen_dest} + ${CMAKE_INSTALL_PREFIX}/${DESTINATION_LIB_PREFIX}/${refimpl_dest} +) + +set(SRCS + main.cpp +) + +ADD_EXECUTABLE(${TARGET_NAME} ${SRCS}) + +target_link_libraries(${TARGET_NAME} + ${refimpl_impl} + ${LIBS_COMMON} + ${LIBS_TEST} +) + diff --git a/wearable_src/RefImpl/test/main.cpp b/wearable_src/RefImpl/test/main.cpp new file mode 100755 index 0000000..6a5d316 --- /dev/null +++ b/wearable_src/RefImpl/test/main.cpp @@ -0,0 +1,80 @@ +#include <stdio.h> +#include <string.h> +#include <JavaScriptCore/JavaScript.h> +#include "StandaloneConsole.h" +#include <Ecore.h> +#include <GlobalContextManager.h> + +#include <Commons/FunctionDefinition.h> +#include <Commons/FunctionDeclaration.h> +#include <pthread.h> +#include <JSRefImplManager.h> +#include <JSSub.h> +#include <JSSuper.h> +#include <JSNestedValue.h> + +using namespace std; +using namespace DeviceAPI::Test; +using namespace DeviceAPI::Common; +using namespace DeviceAPI::Reference; +using namespace WrtDeviceApis::Commons; + + +void fun1(void *data, Ecore_Thread *thread){ + printf("fun1 %p\n", pthread_self()); +} +void fun2(void *data, Ecore_Thread *thread){ + printf("fun2 %p\n", pthread_self()); +} + +static Eina_Bool fun3(void *data){ + ecore_thread_run(fun1, fun2, NULL, NULL); + return false; +} + + +void loopQuit(void *data, Ecore_Thread *thread){ + ecore_main_loop_quit(); +} + +void threadRun(void *data, Ecore_Thread *thread){ + StandaloneConsole *console = (StandaloneConsole*)data; + StandaloneConsole::commandline(console); + +} + +int main(int argc, char** argv){ + + if (!ecore_init()) + { + printf("ERROR: Cannot init Ecore!\n"); + return -1; + } + ecore_main_loop_glib_integrate(); + + DPL::Log::LogSystemSingleton::Instance().SetTag("STANDALONE"); + //DPL::Event::GetMainEventDispatcherInstance().ResetCrossEventCallHandler(); + WrtAccessSingleton::Instance().initialize(0); + + + StandaloneConsole console; + console.initialize(); + GlobalContextManager::getInstance()->addGlobalContext(console.getGlobalContext()); + console.registModule("ref", JSRefImplManager::getClassRef(), NULL); + JSObjectRef Sub = JSObjectMakeConstructor(console.getGlobalContext(), JSSub::getClassRef(), JSSub::constructor); + JSObjectRef Super = JSObjectMakeConstructor(console.getGlobalContext(), JSSuper::getClassRef(), JSSuper::constructor); + JSObjectRef Nested = JSObjectMakeConstructor(console.getGlobalContext(), JSNestedValue::getClassRef(), JSNestedValue::constructor); + console.appendModule("Sub", Sub); + console.appendModule("Super", Super); + console.appendModule("NestedValue", Nested); + + if( argc > 1 ){ + console.RunScript(argv[1]); + } + printf("main thread = %p\n", pthread_self()); + ecore_thread_run(threadRun, loopQuit, NULL, &console); + + ecore_main_loop_begin(); + ecore_shutdown(); + return 0; +} diff --git a/wearable_src/RefImpl/test/test.js b/wearable_src/RefImpl/test/test.js new file mode 100755 index 0000000..1883bea --- /dev/null +++ b/wearable_src/RefImpl/test/test.js @@ -0,0 +1,52 @@ + +if( ref.syncToSync(1,1) == 2 ) + console.log("PASS 1"); +else + console.log("FAIL 1"); + +if( ref.syncToSync(1,2) == 3 ) + console.log("PASS 2"); +else + console.log("FAIL 2"); + + +try{ + ref.syncToSync(5,1); + console.log("FAIL 3"); +}catch(e){ + console.log("PASS 3"); +} + +try{ + ref.syncToSync(4,40); + console.log("FAIL 4"); +}catch(e){ + console.log("PASS 4"); +} + +ref.syncToAsync(1,2 ,function(r){ if(r == 3)console.log("PASS 5");else console.log("FAIL 5");}, function(e){ console.log("FAIL 5");}); +ref.syncToAsync(3,2 ,function(r){ if(r == 5)console.log("PASS 6");else console.log("FAIL 6");}, function(e){ console.log("FAIL 6");}); + +try{ + ref.syncToAsync(5,1, function(r){ console.log("FAIL 7"); }, function(e){ console.log("FAIL 7");}); + console.log("FAIL 7"); +}catch(e){ + console.log("PASS 7"); +} + +ref.syncToAsync(4,40 ,function(r){ console.log("FAIL 8");}, function(e){ console.log("PASS 8");}); + + +ref.asyncToAsync(1,2 ,function(r){ if(r == 3)console.log("PASS 9");else console.log("FAIL 9 "+r);}, function(e){ console.log("FAIL 9(2)");}); +ref.asyncToAsync(3,2 ,function(r){ if(r == 5)console.log("PASS 10");else console.log("FAIL 10 "+r);}, function(e){ console.log("FAIL 10(2)");}); + +try{ + ref.asyncToAsync(5,1, function(r){ console.log("FAIL 11"); }, function(e){ console.log("FAIL 11");}); + console.log("FAIL 11"); +}catch(e){ + console.log("PASS 11"); +} + +ref.asyncToAsync(4,40 ,function(r){ console.log("FAIL 12");}, function(e){ console.log("PASS 12");}); + + diff --git a/wearable_src/Sensor/CMakeLists.txt b/wearable_src/Sensor/CMakeLists.txt new file mode 100755 index 0000000..067cd68 --- /dev/null +++ b/wearable_src/Sensor/CMakeLists.txt @@ -0,0 +1,50 @@ +SET(TARGET_NAME ${sensor_target}) +SET(DESTINATION_NAME ${sensor_dest}) +SET(TARGET_IMPL_NAME ${sensor_impl}) + +PKG_CHECK_MODULES(platform_pkgs_sensor REQUIRED capi-system-sensor) + +INCLUDE_DIRECTORIES( + ${INCLUDE_COMMON} + ${platform_pkgs_sensor_INCLUDE_DIRS} +) + +SET(CMAKE_INSTALL_RPATH + ${CMAKE_INSTALL_RPATH} + ${CMAKE_INSTALL_PREFIX}/${DESTINATION_LIB_PREFIX}/${tizen_dest} + ${CMAKE_INSTALL_PREFIX}/${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME} +) + +SET(SRCS_IMPL + JSSensorService.cpp + SensorService.cpp + JSSensorData.cpp + SensorData.cpp +) + +ADD_LIBRARY(${TARGET_IMPL_NAME} SHARED ${SRCS_IMPL}) + +TARGET_LINK_LIBRARIES(${TARGET_IMPL_NAME} + ${LIBS_COMMON} + ${tizen_impl} + ${platform_pkgs_sensor_LIBRARIES} +) + +SET(SRCS + plugin_config.cpp + plugin_initializer.cpp +) + +ADD_LIBRARY(${TARGET_NAME} SHARED ${SRCS}) + +TARGET_LINK_LIBRARIES(${TARGET_NAME} + ${TARGET_IMPL_NAME} +) + +INSTALL(TARGETS ${TARGET_NAME} ${TARGET_IMPL_NAME} LIBRARY DESTINATION ${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME}) +INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/config.xml DESTINATION ${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME}) +INSTALL( + DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/ DESTINATION ${DESTINATION_HEADER_PREFIX}/power + FILES_MATCHING PATTERN "*.h" PATTERN "CMakeFiles" EXCLUDE +) + diff --git a/wearable_src/Sensor/JSSensorData.cpp b/wearable_src/Sensor/JSSensorData.cpp new file mode 100755 index 0000000..9ca0d94 --- /dev/null +++ b/wearable_src/Sensor/JSSensorData.cpp @@ -0,0 +1,314 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <SecurityExceptions.h> + +#include <JSUtil.h> +#include <JSWebAPIError.h> +#include <ArgumentValidator.h> +#include <GlobalContextManager.h> +#include <MultiCallbackUserData.h> +#include <PlatformException.h> + +#include "plugin_config.h" + +#include "JSSensorData.h" + +using namespace WrtDeviceApis::Commons; +using namespace DeviceAPI::Common; + +namespace DeviceAPI { +namespace Sensor { + +JSClassDefinition JSLightData::m_classInfo = { + 0, + kJSClassAttributeNone, + "LightData", + NULL, //ParentClass + m_property, //StaticValues + NULL, //StaticFunctions + initialize, //Initialize + finalize, //Finalize + NULL, //HasProperty, + NULL, //getProperty, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL //ConvertToType +}; + +JSStaticValue JSLightData::m_property[] = { + { TIZEN_LIGHT_DATA_LIGHT_LEVEL, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSClassRef JSLightData::m_jsClassRef = JSClassCreate(JSLightData::getClassInfo()); + +const JSClassRef JSLightData::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSLightData::getClassInfo() +{ + return &m_classInfo; +} + + +JSValueRef JSLightData::createJSObject(JSContextRef context, LightData* lightData) +{ + JSObjectRef jsValueRef = JSObjectMake(context, getClassRef(), static_cast<void*>(lightData)); + if (NULL == jsValueRef) { + LoggerD("object creation error"); + return JSValueMakeUndefined(context); + } + return jsValueRef; +} + + +void JSLightData::initialize(JSContextRef context, JSObjectRef object) +{ + LoggerD("enter"); + +} + +void JSLightData::finalize(JSObjectRef object) +{ + LoggerD("enter"); + LightData* priv = static_cast<LightData*>(JSObjectGetPrivate(object)); + if (priv) { + delete priv; + } +} + +JSValueRef JSLightData::getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception) +{ + LoggerD("enter"); + double value = 0; + LightData* priv = static_cast<LightData*>(JSObjectGetPrivate(object)); + if (!priv) { + throw TypeMismatchException("Private object is NULL"); + } + + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_LIGHT_DATA_LIGHT_LEVEL)) { + value = priv->getLightLevel(); + return JSUtil::toJSValueRef(context, value); + } + return JSValueMakeUndefined(context); + +} + + +//Proximity +JSClassDefinition JSProximityData::m_classInfo = { + 0, + kJSClassAttributeNone, + "ProximityData", + NULL, //ParentClass + m_property, //StaticValues + NULL, //StaticFunctions + initialize, //Initialize + finalize, //Finalize + NULL, //HasProperty, + NULL, //getProperty, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL //ConvertToType +}; + +JSStaticValue JSProximityData::m_property[] = { + { TIZEN_PROXIMITY_DATA_PROXIMITY_LEVEL, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSClassRef JSProximityData::m_jsClassRef = JSClassCreate(JSProximityData::getClassInfo()); + +const JSClassRef JSProximityData::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSProximityData::getClassInfo() +{ + return &m_classInfo; +} + + +JSValueRef JSProximityData::createJSObject(JSContextRef context, ProximityData* proximityData) +{ + LoggerD("enter ="<<proximityData->getProximityLevel()); + JSObjectRef jsValueRef = JSObjectMake(context, getClassRef(), static_cast<void*>(proximityData)); + if (NULL == jsValueRef) { + LoggerD("object creation error"); + return JSValueMakeUndefined(context); + } + return jsValueRef; +} + + +void JSProximityData::initialize(JSContextRef context, JSObjectRef object) +{ + LoggerD("enter"); + +} + +void JSProximityData::finalize(JSObjectRef object) +{ + ProximityData* priv = static_cast<ProximityData*>(JSObjectGetPrivate(object)); + if (priv) { + delete priv; + } +} + +JSValueRef JSProximityData::getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception) +{ + int value = 0; + std::string proximityLevel(""); + LoggerD("enter"); + + ProximityData* priv = static_cast<ProximityData*>(JSObjectGetPrivate(object)); + if (!priv) { + throw TypeMismatchException("Private object is NULL"); + } + + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_PROXIMITY_DATA_PROXIMITY_LEVEL)) { + value = priv->getProximityLevel(); + if(value<5){ + proximityLevel.append("NEAR"); + }else{ + proximityLevel.append("FAR"); + } + return JSUtil::toJSValueRef(context, proximityLevel); + } + return JSValueMakeUndefined(context); + +} + +// Magnetic +JSClassDefinition JSMagneticData::m_classInfo = { + 0, + kJSClassAttributeNone, + "MagneticData", + NULL, //ParentClass + m_property, //StaticValues + NULL, //StaticFunctions + initialize, //Initialize + finalize, //Finalize + NULL, //HasProperty, + NULL, //getProperty, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL //ConvertToType +}; + +JSStaticValue JSMagneticData::m_property[] = { + { TIZEN_PROXIMITY_DATA_MAGNETIC_X, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_PROXIMITY_DATA_MAGNETIC_Y, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_PROXIMITY_DATA_MAGNETIC_Z, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { TIZEN_PROXIMITY_DATA_MAGNETIC_ACCURACY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +JSClassRef JSMagneticData::m_jsClassRef = JSClassCreate(JSMagneticData::getClassInfo()); + +const JSClassRef JSMagneticData::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSMagneticData::getClassInfo() +{ + return &m_classInfo; +} + + +JSValueRef JSMagneticData::createJSObject(JSContextRef context, MagneticData* magneticData) +{ + JSObjectRef jsValueRef = JSObjectMake(context, getClassRef(), static_cast<void*>(magneticData)); + if (NULL == jsValueRef) { + LoggerD("object creation error"); + return JSValueMakeUndefined(context); + } + return jsValueRef; +} + + +void JSMagneticData::initialize(JSContextRef context, JSObjectRef object) +{ + LoggerD("enter"); + +} + +void JSMagneticData::finalize(JSObjectRef object) +{ + MagneticData* priv = static_cast<MagneticData*>(JSObjectGetPrivate(object)); + if (priv) { + delete priv; + } +} + +JSValueRef JSMagneticData::getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception) +{ + double value = 0; + std::string accuracy(""); + + MagneticData* priv = static_cast<MagneticData*>(JSObjectGetPrivate(object)); + if (!priv) { + throw TypeMismatchException("Private object is NULL"); + } + + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_PROXIMITY_DATA_MAGNETIC_X)) { + value = priv->getMagneticX(); + return JSUtil::toJSValueRef(context, value); + }else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_PROXIMITY_DATA_MAGNETIC_Y)) { + value = priv->getMagneticY(); + return JSUtil::toJSValueRef(context, value); + }else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_PROXIMITY_DATA_MAGNETIC_Z)) { + value = priv->getMagneticZ(); + return JSUtil::toJSValueRef(context, value); + }else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_PROXIMITY_DATA_MAGNETIC_ACCURACY)) { + accuracy.append(priv->getMagneticAccuracy()); + return JSUtil::toJSValueRef(context, accuracy); + } + return JSValueMakeUndefined(context); + +} + + + +} // Sensor +} // DeviceAPI diff --git a/wearable_src/Sensor/JSSensorData.h b/wearable_src/Sensor/JSSensorData.h new file mode 100755 index 0000000..e7a1e34 --- /dev/null +++ b/wearable_src/Sensor/JSSensorData.h @@ -0,0 +1,145 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 __TIZEN_JS_SENSOR_DATA_H__ +#define __TIZEN_JS_SENSOR_DATA_H__ + +#include <JavaScriptCore/JavaScript.h> + +#include "SensorData.h" + +namespace DeviceAPI { +namespace Sensor { + +class JSLightData +{ +public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSValueRef createJSObject(JSContextRef context, LightData* lightData); + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, 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 member variable contains the values which has to be passed + * when the this class is embedded into JS Engine. + */ + static JSClassDefinition m_classInfo; + + + /** + * This member variable contains the initialization values for the + * properties of this class. The values are given according to + * the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; +}; + + + +// +class JSProximityData +{ +public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSValueRef createJSObject(JSContextRef context, ProximityData* proximityData); + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, 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 member variable contains the values which has to be passed + * when the this class is embedded into JS Engine. + */ + static JSClassDefinition m_classInfo; + + + /** + * This member variable contains the initialization values for the + * properties of this class. The values are given according to + * the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; +}; + + +// Magnetic +class JSMagneticData +{ +public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSValueRef createJSObject(JSContextRef context, MagneticData* magneticData); + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, 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 member variable contains the values which has to be passed + * when the this class is embedded into JS Engine. + */ + static JSClassDefinition m_classInfo; + + + /** + * This member variable contains the initialization values for the + * properties of this class. The values are given according to + * the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; +}; + + +} // Sensor +} // DeviceAPI + +#endif // __TIZEN_JS_DOWNLOAD_MANAGER_H__ diff --git a/wearable_src/Sensor/JSSensorService.cpp b/wearable_src/Sensor/JSSensorService.cpp new file mode 100755 index 0000000..3869940 --- /dev/null +++ b/wearable_src/Sensor/JSSensorService.cpp @@ -0,0 +1,887 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <SecurityExceptions.h> + +#include <JSUtil.h> +#include <JSWebAPIError.h> +#include <ArgumentValidator.h> +#include <GlobalContextManager.h> +#include <MultiCallbackUserData.h> +#include <PlatformException.h> +#include <Logger.h> + +#include "plugin_config.h" +#include "JSSensorService.h" +#include "SensorService.h" + +using namespace WrtDeviceApis::Commons; +using namespace DeviceAPI::Common; + +namespace DeviceAPI { +namespace Sensor { + +JSClassDefinition JSSensorService::m_classInfo = { + 0, + kJSClassAttributeNone, + "SensorService", + NULL, //ParentClass + NULL, //StaticValues + m_function, //StaticFunctions + initialize, //Initialize + finalize, //Finalize + NULL, //HasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL //ConvertToType +}; + +JSStaticFunction JSSensorService::m_function[] = { + { SENSOR_SERVICE_API_GET_DEFAULT_SENSOR, getDefaultSensor, kJSPropertyAttributeNone }, + { SENSOR_SERVICE_API_GET_AVAILABLE_SENSORS, getAvailableSensor, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +JSClassRef JSSensorService::m_jsClassRef = JSClassCreate(JSSensorService::getClassInfo()); + +const JSClassRef JSSensorService::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSSensorService::getClassInfo() +{ + return &m_classInfo; +} + +void JSSensorService::initialize(JSContextRef context, JSObjectRef object) +{ + +} + +void JSSensorService::finalize(JSObjectRef object) +{ + +} + +JSValueRef JSSensorService::getDefaultSensor(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + try { + LoggerD("enter"); + + bool supported = false; + ArgumentValidator validator(context, argumentCount, arguments); + std::string sensorType = validator.toString(0); + std::string proximityType = "PROXIMITY"; + std::string lightType = "LIGHT"; + std::string magneticType = "MAGNETIC"; + std::string pressureType = "PRESSURE"; + + // perform + if(proximityType.compare(sensorType) == 0){ + ProximitySensor* proximitySensor = ProximitySensor::getInstance(); + + supported = proximitySensor->isSupported(); + if(false == supported){ + LoggerD("Not supported"); + throw NotSupportedException("Not supported"); + } + + JSValueRef proximityRef = JSProximitySensor::createJSObject(GlobalContextManager::getInstance()->getGlobalContext(context), proximitySensor); + return proximityRef; + }else if(lightType.compare(sensorType) == 0){ + LightSensor* lightSensor = LightSensor::getInstance(); + + supported = lightSensor->isSupported(); + if(false == supported){ + LoggerD("Not supported"); + throw NotSupportedException("Not supported"); + } + + JSValueRef lightRef = JSLightSensor::createJSObject(GlobalContextManager::getInstance()->getGlobalContext(context), lightSensor); + return lightRef; + }else if(magneticType.compare(sensorType) == 0){ + MagneticSensor* magneticSensor = MagneticSensor::getInstance(); + + supported = magneticSensor->isSupported(); + if(false == supported){ + LoggerD("Not supported"); + throw NotSupportedException("Not supported"); + } + + JSValueRef magneticRef = JSMagneticSensor::createJSObject(GlobalContextManager::getInstance()->getGlobalContext(context), magneticSensor); + return magneticRef; + }else if(pressureType.compare(sensorType) == 0){ + throw NotSupportedException("Not supported"); + + }else{ + LoggerD("argument type mismatch"); + throw TypeMismatchException("argument type mismatch"); + } + + } catch (const TypeMismatchException &err) { + LoggerD("Type Mismatch Exception"); + return JSWebAPIErrorFactory::postException(context, exception, err); + } catch (const BasePlatformException &err) { + LoggerD("throw exception"); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + +} + +JSValueRef JSSensorService::getAvailableSensor(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + try { + LoggerD("enter"); + return SensorService::getInstance()->getAvailableSensor(GlobalContextManager::getInstance()->getGlobalContext(context)); + } catch (const TypeMismatchException &err) { + LoggerD("Type Mismatch Exception"); + return JSWebAPIErrorFactory::postException(context, exception, err); + } catch (const BasePlatformException &err) { + LoggerD("argument is wrong."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + +} + +// Proximity +JSClassDefinition JSProximitySensor::m_classInfo = { + 0, + kJSClassAttributeNone, + "ProximitySensor", + NULL, //ParentClass + NULL, //StaticValues + m_function, //StaticFunctions + initialize, //Initialize + finalize, //Finalize + NULL, //HasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL //ConvertToType +}; + +JSStaticFunction JSProximitySensor::m_function[] = { + { SENSOR_API_START, start, kJSPropertyAttributeNone }, + { SENSOR_API_STOP, stop, kJSPropertyAttributeNone }, + { SENSOR_API_SET_CHANGE_LISTENER, setChangeListener, kJSPropertyAttributeNone }, + { SENSOR_API_UNSET_CHANGE_LISTENER, unsetChangeListener, kJSPropertyAttributeNone }, + { SENSOR_API_GET_PROXIMITY_SENSOR_DATA, getSensorData, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +JSClassRef JSProximitySensor::m_jsClassRef = JSClassCreate(JSProximitySensor::getClassInfo()); + +const JSClassRef JSProximitySensor::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSProximitySensor::getClassInfo() +{ + return &m_classInfo; +} + + +JSValueRef JSProximitySensor::createJSObject(JSContextRef context, ProximitySensor* proximitySensor) +{ + JSObjectRef jsValueRef = JSObjectMake(context, getClassRef(), static_cast<void*>(proximitySensor)); + if (NULL == jsValueRef) { + LogError("object creation error"); + return JSValueMakeUndefined(context); + } + + return jsValueRef; +} + + +void JSProximitySensor::initialize(JSContextRef context, JSObjectRef object) +{ + +} + +void JSProximitySensor::finalize(JSObjectRef object) +{ + ProximitySensor *priv = static_cast<ProximitySensor*>(JSObjectGetPrivate(object)); + if (priv) { + JSObjectSetPrivate(object, NULL); + delete priv; + } +} + +JSValueRef JSProximitySensor::start(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("enter"); + + try{ + ArgumentValidator validator(context, argumentCount, arguments); + JSObjectRef successCB = validator.toFunction(0); + + ProximitySuccessCallbackPtr proximityCB(new ProximitySuccessCallback(GlobalContextManager::getInstance()->getGlobalContext(context))); + if (successCB) { + proximityCB->setSuccessCallback(successCB); + } + + JSObjectRef errorCB = validator.toFunction(1, true); + if(errorCB) { + proximityCB->setErrorCallback(errorCB); + } + + ProximitySensor::getInstance()->start(proximityCB); + return JSValueMakeUndefined(context); + + } catch (const BasePlatformException &err) { + LoggerD("argument is wrong."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + +} + +JSValueRef JSProximitySensor::stop(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("enter"); + + try{ + ProximitySensor::getInstance()->stop(GlobalContextManager::getInstance()->getGlobalContext(context)); + return JSValueMakeUndefined(context); + + } catch (const BasePlatformException &err) { + LoggerD("argument is wrong."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + +} + +JSValueRef JSProximitySensor::setChangeListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("enter"); + + try{ + ArgumentValidator validator(context, argumentCount, arguments); + JSObjectRef successCB = validator.toFunction(0); + + ProximitySuccessCallbackPtr proximityCB(new ProximitySuccessCallback(GlobalContextManager::getInstance()->getGlobalContext(context))); + if (successCB) { + proximityCB->setSuccessCallback(successCB); + } + + JSObjectRef errorCB = validator.toFunction(1, true); + if(errorCB) { + proximityCB->setErrorCallback(errorCB); + } + + ProximitySensor::getInstance()->setChangeListener(proximityCB); + return JSValueMakeUndefined(context); + + } catch (const BasePlatformException &err) { + LoggerD("argument is wrong."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + + + +} + +JSValueRef JSProximitySensor::unsetChangeListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("enter"); + + try{ + ProximitySensor::getInstance()->unsetChangeListener(GlobalContextManager::getInstance()->getGlobalContext(context)); + return JSValueMakeUndefined(context); + + } catch (const BasePlatformException &err) { + LoggerD("argument is wrong."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + + +} + +JSValueRef JSProximitySensor::getSensorData(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + + LoggerD("enter"); + + try{ + ArgumentValidator validator(context, argumentCount, arguments); + JSObjectRef successCB = validator.toFunction(0); + + ProximitySuccessCallbackPtr proximityCB(new ProximitySuccessCallback(GlobalContextManager::getInstance()->getGlobalContext(context))); + if (successCB) { + proximityCB->setSuccessCallback(successCB); + } + + JSObjectRef errorCB = validator.toFunction(1, true); + if(errorCB) { + proximityCB->setErrorCallback(errorCB); + } + + ProximitySensor::getInstance()->getSensorData(proximityCB); + return JSValueMakeUndefined(context); + + } catch (const BasePlatformException &err) { + LoggerD("argument is wrong."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + + + + +} + + +// Light +JSClassDefinition JSLightSensor::m_classInfo = { + 0, + kJSClassAttributeNone, + "LightSensor", + NULL, //ParentClass + NULL, //StaticValues + m_function, //StaticFunctions + initialize, //Initialize + finalize, //Finalize + NULL, //HasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL //ConvertToType +}; + +JSStaticFunction JSLightSensor::m_function[] = { + { SENSOR_API_START, start, kJSPropertyAttributeNone }, + { SENSOR_API_STOP, stop, kJSPropertyAttributeNone }, + { SENSOR_API_SET_CHANGE_LISTENER, setChangeListener, kJSPropertyAttributeNone }, + { SENSOR_API_UNSET_CHANGE_LISTENER, unsetChangeListener, kJSPropertyAttributeNone }, + { SENSOR_API_GET_LIGHT_SENSOR_DATA, getSensorData, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +JSClassRef JSLightSensor::m_jsClassRef = JSClassCreate(JSLightSensor::getClassInfo()); + +const JSClassRef JSLightSensor::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSLightSensor::getClassInfo() +{ + return &m_classInfo; +} + + +JSValueRef JSLightSensor::createJSObject(JSContextRef context, LightSensor* sensor) +{ + JSObjectRef jsValueRef = JSObjectMake(context, getClassRef(), static_cast<void*>(sensor)); + if (NULL == jsValueRef) { + LogError("object creation error"); + return JSValueMakeUndefined(context); + } + + return jsValueRef; +} + + +void JSLightSensor::initialize(JSContextRef context, JSObjectRef object) +{ + +} + +void JSLightSensor::finalize(JSObjectRef object) +{ + LightSensor *priv = static_cast<LightSensor*>(JSObjectGetPrivate(object)); + if (priv) { + JSObjectSetPrivate(object, NULL); + delete priv; + } +} + +JSValueRef JSLightSensor::start(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("enter"); + + try{ + ArgumentValidator validator(context, argumentCount, arguments); + JSObjectRef successCB = validator.toFunction(0); + + LightSuccessCallbackPtr lightCB(new LightSuccessCallback(GlobalContextManager::getInstance()->getGlobalContext(context))); + if (successCB) { + lightCB->setSuccessCallback(successCB); + } + + JSObjectRef errorCB = validator.toFunction(1, true); + if(errorCB) { + lightCB->setErrorCallback(errorCB); + } + + LightSensor::getInstance()->start(lightCB); + return JSValueMakeUndefined(context); + + } catch (const BasePlatformException &err) { + LoggerD("argument is wrong."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + +} + +JSValueRef JSLightSensor::stop(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("enter"); + + try{ + LightSensor::getInstance()->stop(GlobalContextManager::getInstance()->getGlobalContext(context)); + return JSValueMakeUndefined(context); + + } catch (const BasePlatformException &err) { + LoggerD("argument is wrong."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + +} + +JSValueRef JSLightSensor::setChangeListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("enter"); + + try{ + ArgumentValidator validator(context, argumentCount, arguments); + JSObjectRef successCB = validator.toFunction(0); + + LightSuccessCallbackPtr lightCB(new LightSuccessCallback(GlobalContextManager::getInstance()->getGlobalContext(context))); + if (successCB) { + lightCB->setSuccessCallback(successCB); + } + + JSObjectRef errorCB = validator.toFunction(1, true); + if(errorCB) { + lightCB->setErrorCallback(errorCB); + } + + LightSensor::getInstance()->setChangeListener(lightCB); + return JSValueMakeUndefined(context); + + } catch (const BasePlatformException &err) { + LoggerD("argument is wrong."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + + + +} + +JSValueRef JSLightSensor::unsetChangeListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("enter"); + + try{ + LightSensor::getInstance()->unsetChangeListener(GlobalContextManager::getInstance()->getGlobalContext(context)); + return JSValueMakeUndefined(context); + + } catch (const BasePlatformException &err) { + LoggerD("argument is wrong."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + + +} + +JSValueRef JSLightSensor::getSensorData(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + + LoggerD("enter"); + + try{ + ArgumentValidator validator(context, argumentCount, arguments); + JSObjectRef successCB = validator.toFunction(0); + + LightSuccessCallbackPtr lightCB(new LightSuccessCallback(GlobalContextManager::getInstance()->getGlobalContext(context))); + if (successCB) { + lightCB->setSuccessCallback(successCB); + } + + JSObjectRef errorCB = validator.toFunction(1, true); + if(errorCB) { + lightCB->setErrorCallback(errorCB); + } + + LightSensor::getInstance()->getSensorData(lightCB); + return JSValueMakeUndefined(context); + + } catch (const BasePlatformException &err) { + LoggerD("argument is wrong."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + +} + +// Magnetic +JSClassDefinition JSMagneticSensor::m_classInfo = { + 0, + kJSClassAttributeNone, + "MagneticSensor", + NULL, //ParentClass + NULL, //StaticValues + m_function, //StaticFunctions + initialize, //Initialize + finalize, //Finalize + NULL, //HasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL //ConvertToType +}; + +JSStaticFunction JSMagneticSensor::m_function[] = { + { SENSOR_API_START, start, kJSPropertyAttributeNone }, + { SENSOR_API_STOP, stop, kJSPropertyAttributeNone }, + { SENSOR_API_SET_CHANGE_LISTENER, setChangeListener, kJSPropertyAttributeNone }, + { SENSOR_API_UNSET_CHANGE_LISTENER, unsetChangeListener, kJSPropertyAttributeNone }, + { SENSOR_API_GET_MAGNETIC_SENSOR_DATA, getSensorData, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +JSClassRef JSMagneticSensor::m_jsClassRef = JSClassCreate(JSMagneticSensor::getClassInfo()); + +const JSClassRef JSMagneticSensor::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSMagneticSensor::getClassInfo() +{ + return &m_classInfo; +} + + +JSValueRef JSMagneticSensor::createJSObject(JSContextRef context, MagneticSensor* sensor) +{ + JSObjectRef jsValueRef = JSObjectMake(context, getClassRef(), static_cast<void*>(sensor)); + if (NULL == jsValueRef) { + LogError("object creation error"); + return JSValueMakeUndefined(context); + } + + return jsValueRef; +} + + +void JSMagneticSensor::initialize(JSContextRef context, JSObjectRef object) +{ + +} + +void JSMagneticSensor::finalize(JSObjectRef object) +{ + MagneticSensor *priv = static_cast<MagneticSensor*>(JSObjectGetPrivate(object)); + if (priv) { + JSObjectSetPrivate(object, NULL); + delete priv; + } +} + +JSValueRef JSMagneticSensor::start(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("enter"); + + try{ + ArgumentValidator validator(context, argumentCount, arguments); + JSObjectRef successCB = validator.toFunction(0); + + MagneticSuccessCallbackPtr magneticCB(new MagneticSuccessCallback(GlobalContextManager::getInstance()->getGlobalContext(context))); + if (successCB) { + magneticCB->setSuccessCallback(successCB); + } + + JSObjectRef errorCB = validator.toFunction(1, true); + if(errorCB) { + magneticCB->setErrorCallback(errorCB); + } + + MagneticSensor::getInstance()->start(magneticCB); + return JSValueMakeUndefined(context); + + } catch (const BasePlatformException &err) { + LoggerD("argument is wrong."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + +} + +JSValueRef JSMagneticSensor::stop(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("enter"); + + try{ + MagneticSensor::getInstance()->stop(GlobalContextManager::getInstance()->getGlobalContext(context)); + return JSValueMakeUndefined(context); + + } catch (const BasePlatformException &err) { + LoggerD("argument is wrong."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + +} + +JSValueRef JSMagneticSensor::setChangeListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("enter"); + + try{ + ArgumentValidator validator(context, argumentCount, arguments); + JSObjectRef successCB = validator.toFunction(0); + + MagneticSuccessCallbackPtr magneticCB(new MagneticSuccessCallback(GlobalContextManager::getInstance()->getGlobalContext(context))); + if (successCB) { + magneticCB->setSuccessCallback(successCB); + } + + JSObjectRef errorCB = validator.toFunction(1, true); + if(errorCB) { + magneticCB->setErrorCallback(errorCB); + } + + MagneticSensor::getInstance()->setChangeListener(magneticCB); + return JSValueMakeUndefined(context); + + } catch (const BasePlatformException &err) { + LoggerD("argument is wrong."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + +} + + + +JSValueRef JSMagneticSensor::unsetChangeListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("enter"); + + try{ + MagneticSensor::getInstance()->unsetChangeListener(GlobalContextManager::getInstance()->getGlobalContext(context)); + return JSValueMakeUndefined(context); + + } catch (const BasePlatformException &err) { + LoggerD("argument is wrong."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + + +} + + +JSValueRef JSMagneticSensor::setCalibrationListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("enter"); + + try{ + ArgumentValidator validator(context, argumentCount, arguments); + JSObjectRef successCB = validator.toFunction(0); + + MagneticSuccessCallbackPtr magneticCB(new MagneticSuccessCallback(GlobalContextManager::getInstance()->getGlobalContext(context))); + if (successCB) { + magneticCB->setSuccessCallback(successCB); + } + + JSObjectRef errorCB = validator.toFunction(1, true); + if(errorCB) { + magneticCB->setErrorCallback(errorCB); + } + + MagneticSensor::getInstance()->setCalibrationListener(magneticCB); + return JSValueMakeUndefined(context); + + } catch (const BasePlatformException &err) { + LoggerD("argument is wrong."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + + + +} + + +JSValueRef JSMagneticSensor::unsetCalibrationListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("enter"); + + try{ + MagneticSensor::getInstance()->unsetCalibrationListener(GlobalContextManager::getInstance()->getGlobalContext(context)); + return JSValueMakeUndefined(context); + + } catch (const BasePlatformException &err) { + LoggerD("argument is wrong."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + +} + +JSValueRef JSMagneticSensor::getSensorData(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + + LoggerD("enter"); + + try{ + ArgumentValidator validator(context, argumentCount, arguments); + JSObjectRef successCB = validator.toFunction(0); + + MagneticSuccessCallbackPtr magneticCB(new MagneticSuccessCallback(GlobalContextManager::getInstance()->getGlobalContext(context))); + if (successCB) { + magneticCB->setSuccessCallback(successCB); + } + + JSObjectRef errorCB = validator.toFunction(1, true); + if(errorCB) { + magneticCB->setErrorCallback(errorCB); + } + + MagneticSensor::getInstance()->getSensorData(magneticCB); + return JSValueMakeUndefined(context); + + } catch (const BasePlatformException &err) { + LoggerD("argument is wrong."); + return JSWebAPIErrorFactory::postException(context, exception, err); + } + + +} + +} // Sensor +} // DeviceAPI diff --git a/wearable_src/Sensor/JSSensorService.h b/wearable_src/Sensor/JSSensorService.h new file mode 100755 index 0000000..97d660e --- /dev/null +++ b/wearable_src/Sensor/JSSensorService.h @@ -0,0 +1,331 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 __TIZEN_JS_SENSOR_SERVICE_H__ +#define __TIZEN_JS_SENSOR_SERVICE_H__ + +#include <JavaScriptCore/JavaScript.h> + +#include "SensorService.h" + +namespace DeviceAPI { +namespace Sensor { + +class JSSensorService +{ +public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + +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); + + static JSValueRef getDefaultSensor(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef getAvailableSensor(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * This member variable contains the values which has to be passed + * when the this class is embedded into JS Engine. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This member variable contains the initialization values for the + * properties of this class. The values are given according to + * the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; +}; + +class JSProximitySensor +{ +public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSValueRef createJSObject(JSContextRef context, ProximitySensor* proximitySensor); + +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); + + static JSValueRef start(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef stop(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef setChangeListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef unsetChangeListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef getSensorData(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * This member variable contains the values which has to be passed + * when the this class is embedded into JS Engine. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This member variable contains the initialization values for the + * properties of this class. The values are given according to + * the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; +}; + + +class JSLightSensor +{ +public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSValueRef createJSObject(JSContextRef context, LightSensor* sensor); + +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); + + static JSValueRef start(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef stop(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef setChangeListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef unsetChangeListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef getSensorData(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * This member variable contains the values which has to be passed + * when the this class is embedded into JS Engine. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This member variable contains the initialization values for the + * properties of this class. The values are given according to + * the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; +}; + + + +class JSMagneticSensor +{ +public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSValueRef createJSObject(JSContextRef context, MagneticSensor* sensor); + +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); + + static JSValueRef start(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef stop(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef setChangeListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef unsetChangeListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef getSensorData(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef setCalibrationListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef unsetCalibrationListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * This member variable contains the values which has to be passed + * when the this class is embedded into JS Engine. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This member variable contains the initialization values for the + * properties of this class. The values are given according to + * the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; + + static JSClassRef m_jsClassRef; +}; + + +} // Sensor +} // DeviceAPI + +#endif // __TIZEN_JS_DOWNLOAD_MANAGER_H__ diff --git a/wearable_src/Sensor/SensorData.cpp b/wearable_src/Sensor/SensorData.cpp new file mode 100755 index 0000000..6c65856 --- /dev/null +++ b/wearable_src/Sensor/SensorData.cpp @@ -0,0 +1,115 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <PlatformException.h> +#include <Logger.h> +#include <math.h> + +#include "SensorData.h" + +namespace DeviceAPI { +namespace Sensor { + +LightData::LightData(double lux) +{ + mLightLevel = lux; +} + +LightData::~LightData() +{ +} + +double LightData::getLightLevel() +{ + return mLightLevel; +} + + +// Proximity + +ProximityData::ProximityData(int proximityLevel) +{ + mProximityLevel = proximityLevel; +} + +ProximityData::~ProximityData() +{ +} + +int ProximityData::getProximityLevel() +{ + return mProximityLevel; +} + +// Magnetic +MagneticData::MagneticData(double x, double y, double z, sensor_data_accuracy_e accuracy) +{ + LoggerD("enter = "<<x<<" "<<y<<" "<<z<<" / "<<accuracy); + + mAccuracy = accuracy; + mMagneticX = convertSimpleDouble(x); + mMagneticY = convertSimpleDouble(y); + mMagneticZ = convertSimpleDouble(z); +} + +MagneticData::~MagneticData() +{ + +} + + +double MagneticData::getMagneticX() +{ + return mMagneticX; +} + +double MagneticData::getMagneticY() +{ + return mMagneticY; +} + +double MagneticData::getMagneticZ() +{ + return mMagneticZ; +} + +char* MagneticData::getMagneticAccuracy() +{ + LoggerD("enter "<<mAccuracy); + if(SENSOR_DATA_ACCURACY_BAD == mAccuracy){ + return "ACCURACY_BAD"; + }else if(SENSOR_DATA_ACCURACY_NORMAL == mAccuracy){ + return "ACCURACY_NORMAL"; + }else if(SENSOR_DATA_ACCURACY_GOOD == mAccuracy){ + return "ACCURACY_GOOD"; + }else if(SENSOR_DATA_ACCURACY_VERYGOOD == mAccuracy){ + return "ACCURACY_VERYGOOD"; + }else{ + return "ACCURACY_UNDEFINED"; + } +} + + +double MagneticData::convertSimpleDouble(double origin) +{ + return ((int)(origin*pow(10.0,2)))/pow(10.0,2); +} + + + +} // Sensor +} // DeviceAPI diff --git a/wearable_src/Sensor/SensorData.h b/wearable_src/Sensor/SensorData.h new file mode 100755 index 0000000..754c771 --- /dev/null +++ b/wearable_src/Sensor/SensorData.h @@ -0,0 +1,80 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 __TIZEN_SENSOR_DATA_H__ +#define __TIZEN_SENSOR_DATA_H__ + +#include <MultiCallbackUserData.h> +#include <sensors.h> + +//#include "SensorTypes.h" + +using namespace DeviceAPI::Common; + +namespace DeviceAPI { +namespace Sensor { + +class LightData{ + +public: + LightData(double lux); + virtual ~LightData(); + double getLightLevel(); + +private: + double mLightLevel; + +}; + + +class ProximityData{ + +public: + ProximityData(int proximityLevel); + virtual ~ProximityData(); + int getProximityLevel(); + +private: + int mProximityLevel; + +}; + + +class MagneticData{ + +public: + MagneticData(double x, double y, double z, sensor_data_accuracy_e accuracy); + virtual ~MagneticData(); + double getMagneticX(); + double getMagneticY(); + double getMagneticZ(); + char* getMagneticAccuracy(); + double convertSimpleDouble(double origin); + +private: + double mMagneticX; + double mMagneticY; + double mMagneticZ; + sensor_data_accuracy_e mAccuracy; + +}; + + +} // Sensor +} // DeviceAPI + +#endif // __TIZEN_SENSOR_DATA_H__ diff --git a/wearable_src/Sensor/SensorService.cpp b/wearable_src/Sensor/SensorService.cpp new file mode 100755 index 0000000..f0500e6 --- /dev/null +++ b/wearable_src/Sensor/SensorService.cpp @@ -0,0 +1,1056 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <PlatformException.h> +#include <JSWebAPIErrorFactory.h> +#include <Logger.h> +#include <JSUtil.h> +#include <sensors.h> +#include <glib.h> + +#include "SensorService.h" +#include "SensorData.h" +#include "JSSensorData.h" + + +namespace DeviceAPI { +namespace Sensor { + +SensorService* SensorService::getInstance(){ + static SensorService instance; + return &instance; +} + + + +SensorService::SensorService() +{ + LoggerD("*** enter ***"); +} + +SensorService::~SensorService() +{ +} + +JSValueRef SensorService::getAvailableSensor(JSContextRef context) +{ + LoggerD("enter"); + int ret = SENSOR_ERROR_NONE; + int index = 0; + bool bLightSupported = false; + bool bMagneticSupported = false; + bool bPressureSupported = false; + bool bProximitySupported = false; + std::string lightType = "LIGHT"; + std::string magneticType = "MAGNETIC"; + std::string pressureType = "PRESSURE"; + std::string proximityType = "PROXIMITY"; + + + ret = sensor_is_supported(SENSOR_LIGHT, &bLightSupported); + if(ret != SENSOR_ERROR_NONE){ + LoggerD("Unknown error"); + throw UnknownException("Unknown error"); + return JSValueMakeUndefined(context); +; + } + + ret = sensor_is_supported(SENSOR_MAGNETIC, &bMagneticSupported); + if(ret != SENSOR_ERROR_NONE){ + LoggerD("Unknown error"); + throw UnknownException("Unknown error"); + return JSValueMakeUndefined(context); + } + + ret = sensor_is_supported(SENSOR_PROXIMITY, &bProximitySupported); + if(ret != SENSOR_ERROR_NONE){ + LoggerD("Unknown error"); + throw UnknownException("Unknown error"); + return JSValueMakeUndefined(context); + } + + JSObjectRef jsArray = JSCreateArrayObject(context, 0, NULL); + if (jsArray == NULL) { + LoggerD("Unknown error"); + throw UnknownException("Unknown error"); + return JSValueMakeUndefined(context); + } + + if(true == bLightSupported){ + JSValueRef jsLightType = JSUtil::toJSValueRef(context, lightType); + if (!JSSetArrayElement(context, jsArray, index, jsLightType)) { + LoggerD("Unknown error"); + throw UnknownException("Unknown error"); + return JSValueMakeUndefined(context); + }else{ + index++; + } + } + + if(true == bMagneticSupported){ + JSValueRef jsMagneticType = JSUtil::toJSValueRef(context, magneticType); + if (!JSSetArrayElement(context, jsArray, index, jsMagneticType)) { + LoggerD("Unknown error"); + throw UnknownException("Unknown error"); + return JSValueMakeUndefined(context); + }else{ + index++; + } + } + + if(true == bPressureSupported){ + JSValueRef jsPressureType = JSUtil::toJSValueRef(context, pressureType); + if (!JSSetArrayElement(context, jsArray, index, jsPressureType)) { + LoggerD("Unknown error"); + throw UnknownException("Unknown error"); + return JSValueMakeUndefined(context); + }else{ + index++; + } + } + + if(true == bProximitySupported){ + JSValueRef jsProximityType = JSUtil::toJSValueRef(context, proximityType); + if (!JSSetArrayElement(context, jsArray, index, jsProximityType)) { + LoggerD("Unknown error"); + throw UnknownException("Unknown error"); + return JSValueMakeUndefined(context); + }else{ + index++; + } + } + + return jsArray; + + +} + +//ProximitySuccessCallback +ProximitySuccessCallback::ProximitySuccessCallback(JSContextRef globalCtx) + :CallbackUserData(globalCtx) +{ + LoggerD("enter"); +} + +ProximitySuccessCallback::~ProximitySuccessCallback() +{ + LoggerD("enter"); + +} + + +//LightSuccessCallback +LightSuccessCallback::LightSuccessCallback(JSContextRef globalCtx) + :CallbackUserData(globalCtx) +{ + LoggerD("enter"); +} + +LightSuccessCallback::~LightSuccessCallback() +{ + LoggerD("enter"); + +} + +//MagneticSuccessCallback +MagneticSuccessCallback::MagneticSuccessCallback(JSContextRef globalCtx) + :CallbackUserData(globalCtx) +{ + LoggerD("enter"); +} + +MagneticSuccessCallback::~MagneticSuccessCallback() +{ + LoggerD("enter"); + +} + + +// ProximitySensor +ProximitySensor* ProximitySensor::getInstance(){ + static ProximitySensor instance; + return &instance; +} + + +ProximitySensor::ProximitySensor() +{ + int ret = SENSOR_ERROR_NONE; + LoggerD("enter"); + + mBStart = false; + mBSupported = false; + + sensor_is_supported(SENSOR_PROXIMITY, &mBSupported); + if(mBSupported == false){ + LoggerD("not supported error"); + throw NotSupportedException("not supported error"); + return; + } + + ret = sensor_create(&mProximityHandle); + if (ret != SENSOR_ERROR_NONE){ + LoggerD("unknown error"); + throw UnknownException("unknown error"); + return; + } + + +} + +ProximitySensor::~ProximitySensor() +{ + int ret = SENSOR_ERROR_NONE; + LoggerD("enter"); + + ret = sensor_destroy(mProximityHandle); + if (ret != SENSOR_ERROR_NONE){ + LoggerD("unknown error"); + throw UnknownException("unknown error"); + return; + } +} + +bool ProximitySensor::isSupported() +{ + return mBSupported; +} + +void ProximitySensor::sensor_proximity_callback(unsigned long long timestamp, float distance, void* user_data) +{ + LoggerD("enter = "<<distance); + ProximitySensor* proximitySensor = (ProximitySensor*)user_data; + proximitySensor->broadcast_proximity(distance); + +} + + +gboolean ProximitySensor::callProximitySuccessCallback(void* data) +{ + LoggerD("enter"); + ProximitySuccessCallbackHolder* holder = static_cast<ProximitySuccessCallbackHolder*>(data); + holder->ptr->callSuccessCallback(holder->mJSProximityData); + delete holder; + return false; +} + +gboolean ProximitySensor::callProximityStartSuccessCB(void* data) +{ + LoggerD("enter"); + ProximitySuccessCallbackHolder* holder = static_cast<ProximitySuccessCallbackHolder*>(data); + holder->ptr->callSuccessCallback(); + delete holder; + return false; +} + + +void ProximitySensor::broadcast_proximity(float proximityLevel) +{ + LoggerD("enter = "<<proximityLevel); + + bool started = false; + guint bGIdleRet = 0; + ProximityData* proximityData = NULL; + ProximitySuccessCallbackHolder* holder = NULL; + std::map<JSContextRef, ProximitySuccessCallbackPtr>::iterator iter; + int total = mProximityCallbackMap.size(); + + if(total <= 0){ + return; + } + + for(iter = mProximityCallbackMap.begin() ; iter != mProximityCallbackMap.end() ; ++iter){ + started = false; + started = mProximityStartMap[iter->second->getContext()]; + if(true == started){ + proximityData = new ProximityData((int)proximityLevel); + holder = new ProximitySuccessCallbackHolder(); + if((proximityData == NULL) || (holder == NULL)){ + return; + } + + holder->ptr = iter->second; + holder->mJSProximityData = JSProximityData::createJSObject(holder->ptr->getContext(), proximityData); + bGIdleRet = g_idle_add(callProximitySuccessCallback, holder); + if (!bGIdleRet) { + LoggerD("g_idle_add fails"); + } + } + } + +} + + + +void ProximitySensor::start(ProximitySuccessCallbackPtr callback) +{ + int ret = 0; + guint bGIdleRet = 0; + ProximitySuccessCallbackHolder* holder = NULL; + int mapTotal = mProximityStartMap.size(); + + LoggerD("enter"); + + if(mapTotal <= 0){ + ret = sensor_start(mProximityHandle, SENSOR_PROXIMITY); + if (ret != SENSOR_ERROR_NONE){ + LoggerD("unknown error"); + throw UnknownException("unknown error"); + return; + } + mBStart = true; + } + + mProximityStartMap[callback->getContext()] = true; + + holder = new ProximitySuccessCallbackHolder(); + if(holder == NULL){ + return; + } + + holder->ptr = callback; + holder->mJSProximityData = NULL; + bGIdleRet = g_idle_add(callProximityStartSuccessCB, holder); + if (!bGIdleRet) { + LoggerD("g_idle_add fails"); + } + +} + +void ProximitySensor::stop(JSContextRef globalCtx) +{ + LoggerD("enter "); + + int ret = 0; + int mapTotal = 0; + + mProximityStartMap.erase(globalCtx); + mapTotal = mProximityStartMap.size(); + + if(mapTotal <= 0){ + ret = sensor_stop(mProximityHandle, SENSOR_PROXIMITY); + if (ret != SENSOR_ERROR_NONE){ + LoggerD("unknown error"); + throw UnknownException("unknown error"); + return; + } + mBStart = false; + } + +} + +void ProximitySensor::setChangeListener(ProximitySuccessCallbackPtr callback) +{ + LoggerD("enter"); + int error = 0; + int mapTotal = mProximityCallbackMap.size(); + std::map<JSContextRef, ProximitySuccessCallbackPtr>::iterator iter; + + iter = mProximityCallbackMap.find(callback->getContext()); + if(iter != mProximityCallbackMap.end()){ + mProximityCallbackMap.erase(callback->getContext()); + LoggerD("prev callback erase"); + } + mProximityCallbackMap[callback->getContext()] = callback; + + if(mapTotal <= 0){ + error = sensor_proximity_set_cb(mProximityHandle, 100, sensor_proximity_callback, this); + if (error != SENSOR_ERROR_NONE){ + LoggerD("unknown error"); + throw UnknownException("unknown error"); + return; + } + } + +} + +void ProximitySensor::unsetChangeListener(JSContextRef globalCtx) +{ + int total = 0, ret = 0; + mProximityCallbackMap.erase(globalCtx); + + total = mProximityCallbackMap.size(); + if(total <= 0){ + ret = sensor_proximity_unset_cb(mProximityHandle); + if (ret != SENSOR_ERROR_NONE){ + LoggerD("unknown error"); + throw UnknownException("unknown error"); + return; + } + + } + +} + +void ProximitySensor::getSensorData(ProximitySuccessCallbackPtr callback) +{ + LoggerD("enter"); + int error = 0; + bool started = false; + float distance = 0.0; + guint bGIdleRet = 0; + ProximityData* proximityData = NULL; + ProximitySuccessCallbackHolder* holder = NULL; + + started = mProximityStartMap[callback->getContext()]; + if(false == started){ + mProximityStartMap.erase(callback->getContext()); + + LoggerD("Not yet start"); + JSValueRef error = JSWebAPIErrorFactory::makeErrorObject(callback->getContext(), JSWebAPIErrorFactory::SERVICE_NOT_AVAILABLE_ERROR, "service not available"); + callback->callErrorCallback(error); + return; + + } + + error = sensor_proximity_read_data(mProximityHandle, &distance); + if (error != SENSOR_ERROR_NONE){ + LoggerD("unknown error"); + throw UnknownException("unknown error"); + return; + } + + proximityData = new ProximityData((int)distance); + holder = new ProximitySuccessCallbackHolder(); + if((proximityData == NULL) || (holder == NULL)){ + return; + } + + holder->ptr = callback; + holder->mJSProximityData = JSProximityData::createJSObject(holder->ptr->getContext(), proximityData); + bGIdleRet = g_idle_add(callProximitySuccessCallback, holder); + if (!bGIdleRet) { + LoggerD("g_idle_add fails"); + } + + +} + + +// LightSensor +LightSensor* LightSensor::getInstance(){ + static LightSensor instance; + return &instance; +} + + +LightSensor::LightSensor() +{ + int ret = SENSOR_ERROR_NONE; + LoggerD("enter"); + + mBStart = false; + mBSupported = false; + + sensor_is_supported(SENSOR_LIGHT, &mBSupported); + if(mBSupported == false){ + LoggerD("not supported error"); + throw NotSupportedException("not supported error"); + return; + } + + ret = sensor_create(&mLightHandle); + if (ret != SENSOR_ERROR_NONE){ + LoggerD("unknown error"); + throw UnknownException("unknown error"); + return; + } + + +} + +LightSensor::~LightSensor() +{ + int ret = SENSOR_ERROR_NONE; + LoggerD("enter"); + + ret = sensor_destroy(mLightHandle); + if (ret != SENSOR_ERROR_NONE){ + LoggerD("unknown error"); + throw UnknownException("unknown error"); + return; + } +} + +bool LightSensor::isSupported() +{ + return mBSupported; +} + + +void LightSensor::sensor_light_callback(unsigned long long timestamp, float lux, void* user_data) +{ + LoggerD("enter = "<<lux); + LightSensor* lightSensor = (LightSensor*)user_data; + lightSensor->broadcast_light(lux); + +} + +gboolean LightSensor::callLightSuccessCallback(void* data) +{ + LoggerD("enter"); + LightSuccessCallbackHolder* holder = static_cast<LightSuccessCallbackHolder*>(data); + holder->ptr->callSuccessCallback(holder->mJSLightData); + delete holder; + return false; +} + +gboolean LightSensor::callLightStartSuccessCallback(void* data) +{ + LoggerD("enter"); + LightSuccessCallbackHolder* holder = static_cast<LightSuccessCallbackHolder*>(data); + holder->ptr->callSuccessCallback(); + delete holder; + return false; +} + +void LightSensor::broadcast_light(float lux) +{ + LoggerD("enter = "<<lux); + + bool started = false; + guint bGIdleRet = 0; + LightData* lightData = NULL; + LightSuccessCallbackHolder* holder = NULL; + std::map<JSContextRef, LightSuccessCallbackPtr>::iterator iter; + int total = mLightCallbackMap.size(); + + if(total <= 0){ + return; + } + + for(iter = mLightCallbackMap.begin() ; iter != mLightCallbackMap.end() ; ++iter){ + started = false; + started = mLightStartMap[iter->second->getContext()]; + if(true == started){ + lightData = new LightData((double)lux); + holder = new LightSuccessCallbackHolder(); + if((lightData == NULL) || (holder == NULL)){ + return; + } + + holder->ptr = iter->second; + holder->mJSLightData = JSLightData::createJSObject(holder->ptr->getContext(), lightData); + bGIdleRet = g_idle_add(callLightSuccessCallback, holder); + if (!bGIdleRet) { + LoggerD("g_idle_add fails"); + } + } + } + + +} + + + +void LightSensor::start(LightSuccessCallbackPtr callback) +{ + int ret = 0; + guint bGIdleRet = 0; + LightSuccessCallbackHolder* holder = NULL; + int mapTotal = mLightStartMap.size(); + + LoggerD("enter"); + + if(mapTotal <= 0){ + ret = sensor_start(mLightHandle, SENSOR_LIGHT); + if (ret != SENSOR_ERROR_NONE){ + LoggerD("unknown error"); + throw UnknownException("unknown error"); + return; + } + mBStart = true; + } + + mLightStartMap[callback->getContext()] = true; + + holder = new LightSuccessCallbackHolder(); + if(holder == NULL){ + return; + } + + holder->ptr = callback; + holder->mJSLightData = NULL; + bGIdleRet = g_idle_add(callLightStartSuccessCallback, holder); + if (!bGIdleRet) { + LoggerD("g_idle_add fails"); + } + +} + +void LightSensor::stop(JSContextRef globalCtx) +{ + LoggerD("enter "); + + int ret = 0; + int mapTotal = 0; + + mLightStartMap.erase(globalCtx); + mapTotal = mLightStartMap.size(); + + if(mapTotal <= 0){ + ret = sensor_stop(mLightHandle, SENSOR_LIGHT); + if (ret != SENSOR_ERROR_NONE){ + LoggerD("unknown error"); + throw UnknownException("unknown error"); + return; + } + mBStart = false; + } + +} + +void LightSensor::setChangeListener(LightSuccessCallbackPtr callback) +{ + LoggerD("enter"); + int error = 0; + int mapTotal = mLightCallbackMap.size(); + std::map<JSContextRef, LightSuccessCallbackPtr>::iterator iter; + + iter = mLightCallbackMap.find(callback->getContext()); + if(iter != mLightCallbackMap.end()){ + mLightCallbackMap.erase(callback->getContext()); + LoggerD("prev callback erase"); + } + mLightCallbackMap[callback->getContext()] = callback; + + if(mapTotal <= 0){ + error = sensor_light_set_cb(mLightHandle, 100, sensor_light_callback, this); + if (error != SENSOR_ERROR_NONE){ + LoggerD("unknown error"); + throw UnknownException("unknown error"); + return; + } + } + +} + +void LightSensor::unsetChangeListener(JSContextRef globalCtx) +{ + int total = 0, ret = 0; + mLightCallbackMap.erase(globalCtx); + + total = mLightCallbackMap.size(); + if(total <= 0){ + ret = sensor_light_unset_cb(mLightHandle); + if (ret != SENSOR_ERROR_NONE){ + LoggerD("unknown error"); + throw UnknownException("unknown error"); + return; + } + + } + +} + +void LightSensor::getSensorData(LightSuccessCallbackPtr callback) +{ + LoggerD("enter"); + int error = 0; + bool started = false; + float lightLevel = 0.0; + guint bGIdleRet = 0; + LightData* lightData = NULL; + LightSuccessCallbackHolder* holder = NULL; + + started = mLightStartMap[callback->getContext()]; + if(false == started){ + mLightStartMap.erase(callback->getContext()); + + LoggerD("Not yet start"); + JSValueRef error = JSWebAPIErrorFactory::makeErrorObject(callback->getContext(), JSWebAPIErrorFactory::SERVICE_NOT_AVAILABLE_ERROR, "service not available"); + callback->callErrorCallback(error); + return; + + } + + error = sensor_light_read_data(mLightHandle, &lightLevel); + if (error != SENSOR_ERROR_NONE){ + LoggerD("unknown error"); + throw UnknownException("unknown error"); + return; + } + + lightData = new LightData((double)lightLevel); + holder = new LightSuccessCallbackHolder(); + if((lightData == NULL) || (holder == NULL)){ + return; + } + + holder->ptr = callback; + holder->mJSLightData = JSLightData::createJSObject(holder->ptr->getContext(), lightData); + bGIdleRet = g_idle_add(callLightSuccessCallback, holder); + if (!bGIdleRet) { + LoggerD("g_idle_add fails"); + } + +} + + +// Magnetic Sensor +MagneticSensor* MagneticSensor::getInstance(){ + static MagneticSensor instance; + return &instance; +} + + +MagneticSensor::MagneticSensor() +{ + int ret = SENSOR_ERROR_NONE; + LoggerD("enter"); + + mBStart = false; + mBSupported = false; + + sensor_is_supported(SENSOR_MAGNETIC, &mBSupported); + if(mBSupported == false){ + LoggerD("not supported error"); + throw NotSupportedException("not supported error"); + return; + } + + ret = sensor_create(&mMagneticHandle); + if (ret != SENSOR_ERROR_NONE){ + LoggerD("unknown error"); + throw UnknownException("unknown error"); + return; + } + + +} + +MagneticSensor::~MagneticSensor() +{ + int ret = SENSOR_ERROR_NONE; + LoggerD("enter"); + + ret = sensor_destroy(mMagneticHandle); + if (ret != SENSOR_ERROR_NONE){ + LoggerD("unknown error"); + throw UnknownException("unknown error"); + return; + } +} + +bool MagneticSensor::isSupported() +{ + return mBSupported; +} + + +void MagneticSensor::sensor_magnetic_callback( unsigned long long timestamp, + sensor_data_accuracy_e accuracy, float x, float y, float z, void *user_data) +{ + LoggerD("enter = "<<x<<" "<<y<<" "<<z<<"//"<<accuracy); + MagneticSensor* magneticSensor = (MagneticSensor*)user_data; + magneticSensor->broadcast_magnetic(x, y, z, accuracy); + +} + +void MagneticSensor::broadcast_magnetic(float x, float y, float z, sensor_data_accuracy_e accuracy) +{ + bool started = false; + guint bGIdleRet = 0; + MagneticData* magneticData = NULL; + MagneticSuccessCallbackHolder* holder = NULL; + std::map<JSContextRef, MagneticSuccessCallbackPtr>::iterator iter; + int total = mMagneticCallbackMap.size(); + + if(total <= 0){ + return; + } + + for(iter = mMagneticCallbackMap.begin() ; iter != mMagneticCallbackMap.end() ; ++iter){ + started = false; + started = mMagneticStartMap[iter->second->getContext()]; + if(true == started){ + magneticData = new MagneticData(x, y, z, accuracy); + holder = new MagneticSuccessCallbackHolder(); + if((magneticData == NULL) || (holder == NULL)){ + return; + } + + holder->ptr = iter->second; + holder->mJSMagneticData = JSMagneticData::createJSObject(holder->ptr->getContext(), magneticData); + bGIdleRet = g_idle_add(callMagneticSuccessCallback, holder); + if (!bGIdleRet) { + LoggerD("g_idle_add fails"); + } + } + } + + +} + + +gboolean MagneticSensor::callMagneticSuccessCallback(void* data) +{ + LoggerD("enter"); + MagneticSuccessCallbackHolder* holder = static_cast<MagneticSuccessCallbackHolder*>(data); + holder->ptr->callSuccessCallback(holder->mJSMagneticData); + delete holder; + return false; +} + +gboolean MagneticSensor::callMagneticStartSuccessCallback(void* data) +{ + LoggerD("enter"); + MagneticSuccessCallbackHolder* holder = static_cast<MagneticSuccessCallbackHolder*>(data); + holder->ptr->callSuccessCallback(); + delete holder; + return false; +} + + + +void MagneticSensor::start(MagneticSuccessCallbackPtr callback) +{ + int ret = 0; + guint bGIdleRet = 0; + MagneticSuccessCallbackHolder* holder = NULL; + int mapTotal = mMagneticStartMap.size(); + + LoggerD("enter"); + + if(mapTotal <= 0){ + ret = sensor_start(mMagneticHandle, SENSOR_MAGNETIC); + if (ret != SENSOR_ERROR_NONE){ + LoggerD("unknown error"); + throw UnknownException("unknown error"); + return; + } + mBStart = true; + } + + mMagneticStartMap[callback->getContext()] = true; + + holder = new MagneticSuccessCallbackHolder(); + if(holder == NULL){ + return; + } + + holder->ptr = callback; + holder->mJSMagneticData = NULL; + bGIdleRet = g_idle_add(callMagneticStartSuccessCallback, holder); + if (!bGIdleRet) { + LoggerD("g_idle_add fails"); + } + +} + +void MagneticSensor::stop(JSContextRef globalCtx) +{ + LoggerD("enter "); + + int ret = 0; + int mapTotal = 0; + + mMagneticStartMap.erase(globalCtx); + mapTotal = mMagneticStartMap.size(); + + if(mapTotal <= 0){ + ret = sensor_stop(mMagneticHandle, SENSOR_MAGNETIC); + if (ret != SENSOR_ERROR_NONE){ + LoggerD("unknown error"); + throw UnknownException("unknown error"); + return; + } + mBStart = false; + + } + +} + +void MagneticSensor::setChangeListener(MagneticSuccessCallbackPtr callback) +{ + LoggerD("enter"); + int error = 0; + int mapTotal = mMagneticCallbackMap.size(); + std::map<JSContextRef, MagneticSuccessCallbackPtr>::iterator iter; + + iter = mMagneticCallbackMap.find(callback->getContext()); + if(iter != mMagneticCallbackMap.end()){ + mMagneticCallbackMap.erase(callback->getContext()); + LoggerD("prev callback erase"); + } + mMagneticCallbackMap[callback->getContext()] = callback; + + if(mapTotal <= 0){ + error = sensor_magnetic_set_cb(mMagneticHandle, 100, sensor_magnetic_callback, this); + if (error != SENSOR_ERROR_NONE){ + LoggerD("unknown error"); + throw UnknownException("unknown error"); + return; + } + } + +} + +void MagneticSensor::unsetChangeListener(JSContextRef globalCtx) +{ + int total = 0, ret = 0; + mMagneticCallbackMap.erase(globalCtx); + + total = mMagneticCallbackMap.size(); + if(total <= 0){ + ret = sensor_magnetic_unset_cb(mMagneticHandle); + if (ret != SENSOR_ERROR_NONE){ + LoggerD("unknown error"); + throw UnknownException("unknown error"); + return; + } + + } + +} + + +void MagneticSensor::getSensorData(MagneticSuccessCallbackPtr callback) +{ + LoggerD("enter"); + int error = 0; + bool started = false; + float x = 0.0, y = 0.0, z = 0.0; + sensor_data_accuracy_e accuracy = SENSOR_DATA_ACCURACY_UNDEFINED; + guint bGIdleRet = 0; + MagneticData* magneticData = NULL; + MagneticSuccessCallbackHolder* holder = NULL; + + started = mMagneticStartMap[callback->getContext()]; + if(false == started){ + mMagneticStartMap.erase(callback->getContext()); + + LoggerD("Not yet start"); + JSValueRef error = JSWebAPIErrorFactory::makeErrorObject(callback->getContext(), JSWebAPIErrorFactory::SERVICE_NOT_AVAILABLE_ERROR, "service not available"); + callback->callErrorCallback(error); + return; + } + + error = sensor_magnetic_read_data(mMagneticHandle, &accuracy, &x, &y, &z); + if (error != SENSOR_ERROR_NONE){ + LoggerD("unknown error"); + throw UnknownException("unknown error"); + return; + } + + magneticData = new MagneticData(x, y, z, accuracy); + holder = new MagneticSuccessCallbackHolder(); + if((magneticData == NULL) || (holder == NULL)){ + return; + } + + holder->ptr = callback; + holder->mJSMagneticData = JSMagneticData::createJSObject(holder->ptr->getContext(), magneticData); + bGIdleRet = g_idle_add(callMagneticSuccessCallback, holder); + if (!bGIdleRet) { + LoggerD("g_idle_add fails"); + } + + +} + + +void MagneticSensor::setCalibrationListener(MagneticSuccessCallbackPtr callback) +{ + LoggerD("enter"); + int error = 0; + int mapTotal = mCalibrationCallbackMap.size(); + std::map<JSContextRef, MagneticSuccessCallbackPtr>::iterator iter; + + iter = mCalibrationCallbackMap.find(callback->getContext()); + if(iter != mCalibrationCallbackMap.end()){ + mCalibrationCallbackMap.erase(callback->getContext()); + LoggerD("prev callback erase"); + } + mCalibrationCallbackMap[callback->getContext()] = callback; + + if(mapTotal <= 0){ + error = sensor_magnetic_set_calibration_cb(mMagneticHandle, sensor_magnetic_calibration_callback, this); + if (error != SENSOR_ERROR_NONE){ + LoggerD("unknown error"); + throw UnknownException("unknown error"); + return; + } + } + +} + +void MagneticSensor::unsetCalibrationListener(JSContextRef globalCtx) +{ + int total = 0, ret = 0; + mCalibrationCallbackMap.erase(globalCtx); + + total = mCalibrationCallbackMap.size(); + if(total <= 0){ + ret = sensor_magnetic_unset_calibration_cb(mMagneticHandle); + if (ret != SENSOR_ERROR_NONE){ + LoggerD("unknown error"); + throw UnknownException("unknown error"); + return; + } + + } + +} + +void MagneticSensor::sensor_magnetic_calibration_callback(void *user_data) +{ + LoggerD("enter"); + MagneticSensor* magneticSensor = (MagneticSensor*)user_data; + magneticSensor->broadcast_calibaratiion(); + +} + +void MagneticSensor::broadcast_calibaratiion() +{ + guint bGIdleRet = 0; + MagneticSuccessCallbackHolder* holder = NULL; + std::map<JSContextRef, MagneticSuccessCallbackPtr>::iterator iter; + int total = mCalibrationCallbackMap.size(); + + if(total <= 0){ + return; + } + + for(iter = mCalibrationCallbackMap.begin() ; iter != mCalibrationCallbackMap.end() ; ++iter){ + holder = new MagneticSuccessCallbackHolder(); + if(holder == NULL){ + return; + } + + holder->ptr = iter->second; + bGIdleRet = g_idle_add(callMagneticCalibarationSuccessCB, holder); + if (!bGIdleRet) { + LoggerD("g_idle_add fails"); + } + } + + +} + +gboolean MagneticSensor::callMagneticCalibarationSuccessCB(void* data) +{ + LoggerD("enter"); + MagneticSuccessCallbackHolder* holder = static_cast<MagneticSuccessCallbackHolder*>(data); + holder->ptr->callSuccessCallback(); + delete holder; + return false; +} + + +} // Sensor +} // DeviceAPI diff --git a/wearable_src/Sensor/SensorService.h b/wearable_src/Sensor/SensorService.h new file mode 100755 index 0000000..bc7bcd1 --- /dev/null +++ b/wearable_src/Sensor/SensorService.h @@ -0,0 +1,191 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 __TIZEN_SENSOR_SERVICE_H__ +#define __TIZEN_SENSOR_SERVICE_H__ + +#include <map> +#include <list> +#include <glib.h> +#include <boost/shared_ptr.hpp> +#include <CallbackUserData.h> +#include <sensors.h> + +//#include "SensorTypes.h" + +using namespace DeviceAPI::Common; + +namespace DeviceAPI { +namespace Sensor { + +class ProximitySuccessCallback; +typedef std::shared_ptr<ProximitySuccessCallback> ProximitySuccessCallbackPtr; +class LightSuccessCallback; +typedef std::shared_ptr<LightSuccessCallback> LightSuccessCallbackPtr; +class MagneticSuccessCallback; +typedef std::shared_ptr<MagneticSuccessCallback> MagneticSuccessCallbackPtr; + +struct ProximitySuccessCallbackHolder { + ProximitySuccessCallbackPtr ptr; + JSValueRef mJSProximityData; +}; + +struct LightSuccessCallbackHolder { + LightSuccessCallbackPtr ptr; + JSValueRef mJSLightData; +}; + +struct MagneticSuccessCallbackHolder { + MagneticSuccessCallbackPtr ptr; + JSValueRef mJSMagneticData; +}; + +class SensorService +{ +public: + SensorService(); + virtual ~SensorService(); + JSValueRef getAvailableSensor(JSContextRef context); + static SensorService* getInstance(); + +private: +}; + +class ProximitySuccessCallback : public Common::CallbackUserData +{ +public: + ProximitySuccessCallback(JSContextRef globalCtx); + virtual ~ProximitySuccessCallback(); + +private: +}; + + +class LightSuccessCallback : public Common::CallbackUserData +{ +public: + LightSuccessCallback(JSContextRef globalCtx); + virtual ~LightSuccessCallback(); + +private: +}; + +class MagneticSuccessCallback : public Common::CallbackUserData +{ +public: + MagneticSuccessCallback(JSContextRef globalCtx); + virtual ~MagneticSuccessCallback(); + +private: +}; + + +class ProximitySensor +{ +public: + ProximitySensor(); + virtual ~ProximitySensor(); + static ProximitySensor* getInstance(); + void start(ProximitySuccessCallbackPtr successCB); + void stop(JSContextRef globalCtx); + void setChangeListener(ProximitySuccessCallbackPtr callback); + void unsetChangeListener(JSContextRef globalCtx); + void getSensorData(ProximitySuccessCallbackPtr callback); + void broadcast_proximity(float proximityLevel); + bool isSupported(); + static void sensor_proximity_callback(unsigned long long timestamp, float distance, void* user_data); + static gboolean callProximitySuccessCallback(void* data); + static gboolean callProximityStartSuccessCB(void* data); + +private: + sensor_h mProximityHandle; + bool mBStart; + bool mBSupported; + std::map<JSContextRef, ProximitySuccessCallbackPtr> mProximityCallbackMap; + std::map<JSContextRef, bool> mProximityStartMap; + +}; + + + +class LightSensor +{ +public: + LightSensor(); + virtual ~LightSensor(); + static LightSensor* getInstance(); + void start(LightSuccessCallbackPtr successCB); + void stop(JSContextRef globalCtx); + void setChangeListener(LightSuccessCallbackPtr callback); + void unsetChangeListener(JSContextRef globalCtx); + void getSensorData(LightSuccessCallbackPtr callback); + void broadcast_light(float lux); + bool isSupported(); + static void sensor_light_callback(unsigned long long timestamp, float lux, void* user_data); + static gboolean callLightSuccessCallback(void* data); + static gboolean callLightStartSuccessCallback(void* data); + +private: + sensor_h mLightHandle; + bool mBStart; + bool mBSupported; + std::map<JSContextRef, LightSuccessCallbackPtr> mLightCallbackMap; + std::map<JSContextRef, bool> mLightStartMap; + +}; + + + + +class MagneticSensor +{ +public: + MagneticSensor(); + virtual ~MagneticSensor(); + static MagneticSensor* getInstance(); + void start(MagneticSuccessCallbackPtr successCB); + void stop(JSContextRef globalCtx); + void setChangeListener(MagneticSuccessCallbackPtr callback); + void unsetChangeListener(JSContextRef globalCtx); + void setCalibrationListener(MagneticSuccessCallbackPtr callback); + void unsetCalibrationListener(JSContextRef globalCtx); + void getSensorData(MagneticSuccessCallbackPtr callback); + void broadcast_magnetic(float x, float y, float z, sensor_data_accuracy_e accuracy); + void broadcast_calibaratiion(); + bool isSupported(); + static void sensor_magnetic_callback(unsigned long long timestamp, sensor_data_accuracy_e accuracy, float x, float y, float z, void *user_data); + static void sensor_magnetic_calibration_callback(void *user_data); + static gboolean callMagneticStartSuccessCallback(void* data); + static gboolean callMagneticSuccessCallback(void* data); + static gboolean callMagneticCalibarationSuccessCB(void* data); + + +private: + sensor_h mMagneticHandle; + bool mBStart; + bool mBSupported; + std::map<JSContextRef, MagneticSuccessCallbackPtr> mMagneticCallbackMap; + std::map<JSContextRef, MagneticSuccessCallbackPtr> mCalibrationCallbackMap; + std::map<JSContextRef, bool> mMagneticStartMap; + +}; + + +} // Sensor +} // DeviceAPI + +#endif // __TIZEN_SENSOR_SERVICE_H__ diff --git a/wearable_src/Sensor/config.xml b/wearable_src/Sensor/config.xml new file mode 100755 index 0000000..8f98b96 --- /dev/null +++ b/wearable_src/Sensor/config.xml @@ -0,0 +1,10 @@ +<?xml version="1.0" ?> +<!DOCTYPE plugin-properties SYSTEM "/usr/etc/tizen-apis/config.dtd"> +<plugin-properties> + <library-name>libwrt-plugins-tizen-sensor.so</library-name> + <feature-install-uri>sensor.install.uri</feature-install-uri> + + <api-feature> + <name>http://tizen.org/privilege/sensor</name> + </api-feature> +</plugin-properties> diff --git a/wearable_src/Sensor/plugin_config.cpp b/wearable_src/Sensor/plugin_config.cpp new file mode 100644 index 0000000..c6e8bf8 --- /dev/null +++ b/wearable_src/Sensor/plugin_config.cpp @@ -0,0 +1,44 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <Commons/FunctionDefinition.h> +#include <Commons/FunctionDeclaration.h> +#include <Commons/Exception.h> +#include <map> + +#include "plugin_config.h" + +using namespace WrtDeviceApis::Commons; + +namespace DeviceAPI { +namespace Sensor { + +static FunctionMapping createSensorFunctions(); +static FunctionMapping SensorFunctions = createSensorFunctions(); + +DEFINE_FUNCTION_GETTER(Sensor, SensorFunctions); + +static FunctionMapping createSensorFunctions() +{ + FunctionMapping sensorMapping; + // TODO: implement here + return sensorMapping; +} + +} // Sensor +} // DeviceAPI diff --git a/wearable_src/Sensor/plugin_config.h b/wearable_src/Sensor/plugin_config.h new file mode 100755 index 0000000..a87c3cc --- /dev/null +++ b/wearable_src/Sensor/plugin_config.h @@ -0,0 +1,72 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _SENSOR_PLUGIN_CONFIG_H_ +#define _SENSOR_PLUGIN_CONFIG_H_ + +#include <string> +#include <Commons/FunctionDeclaration.h> + +#include <Logger.h> + +namespace DeviceAPI { +namespace Sensor { + +// attributes +#define TIZEN_SENSOR_TYPE_LIGHT "LIGHT" +#define TIZEN_SENSOR_TYPE_PROXIMITY "PROXIMITY" +#define TIZEN_SENSOR_TYPE_MAGNETIC "MAGNETIC" +#define TIZEN_SENSOR_TYPE_PRESSURE "PRESSURE" + +#define TIZEN_LIGHT_DATA_LIGHT_LEVEL "lightLevel" +#define TIZEN_PROXIMITY_DATA_PROXIMITY_LEVEL "proximityState" +#define TIZEN_PROXIMITY_DATA_MAGNETIC_X "x" +#define TIZEN_PROXIMITY_DATA_MAGNETIC_Y "y" +#define TIZEN_PROXIMITY_DATA_MAGNETIC_Z "z" +#define TIZEN_PROXIMITY_DATA_MAGNETIC_ACCURACY "accuracy" +#define TIZEN_PRESSURE_DATA_PRESSURE "pressure" + + +// functions +#define SENSOR_SERVICE_API_GET_DEFAULT_SENSOR "getDefaultSensor" +#define SENSOR_SERVICE_API_GET_AVAILABLE_SENSORS "getAvailableSensors" + +#define SENSOR_API_START "start" +#define SENSOR_API_STOP "stop" +#define SENSOR_API_SET_CHANGE_LISTENER "setChangeListener" +#define SENSOR_API_UNSET_CHANGE_LISTENER "unsetChangeListener" + +#define SENSOR_API_GET_PROXIMITY_SENSOR_DATA "getProximitySensorData" +#define SENSOR_API_GET_LIGHT_SENSOR_DATA "getLightSensorData" +#define SENSOR_API_GET_MAGNETIC_SENSOR_DATA "getMagneticSensorData" +#define SENSOR_API_GET_PRESSURE_SENSOR_DATA "getPressureSensorData" + +#define SENSOR_API_MAGNETIC_SENSOR_SET_CALIBRATION_LISTENER "setCalibrationListener" +#define SENSOR_API_MAGNETIC_SENSOR_UNSET_CALIBRATION_LISTENER "unsetCalibrationListener" + +DECLARE_FUNCTION_GETTER(Sensor); + +#define SENSOR_CHECK_ACCESS(functionName) \ + aceCheckAccess<AceFunctionGetter, DefaultArgsVerifier<> >( \ + getSensorFunctionData, \ + functionName) + +} +} + +#endif // _SENSOR_PLUGIN_CONFIG_H_ diff --git a/wearable_src/Sensor/plugin_initializer.cpp b/wearable_src/Sensor/plugin_initializer.cpp new file mode 100644 index 0000000..93f0f30 --- /dev/null +++ b/wearable_src/Sensor/plugin_initializer.cpp @@ -0,0 +1,81 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <Commons/plugin_initializer_def.h> +#include <Commons/WrtAccess/WrtAccess.h> + +#include <GlobalContextManager.h> + +#include "JSSensorService.h" + +#include <Logger.h> + +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; +using namespace DeviceAPI::Common; + +namespace DeviceAPI { +namespace Sensor { + + +void on_widget_start_callback(int widgetId) +{ + LOGD("[Tizen\\Sensor] on_widget_start_callback (%d)", widgetId); + try { + WrtAccessSingleton::Instance().initialize(widgetId); + } catch (...) { + LOGE("WrtAccess initialization failed"); + } +} + +void on_widget_stop_callback(int widgetId) +{ + LOGD("[Tizen\\Sensor] on_widget_stop_callback (%d)", widgetId); + try { + WrtAccessSingleton::Instance().deinitialize(widgetId); + } catch (...) { + LOGE("WrtAccess deinitialization failed"); + } +} + +void on_frame_load_callback(const void * context) +{ + LOGD("[Tizen\\Sensor] on_frame_load_callback (%p)", context); + GlobalContextManager::getInstance()->addGlobalContext(static_cast<JSContextRef>(context)); +} + +void on_frame_unload_callback(const void * context) +{ + LOGD("[Tizen\\Sensor] on_frame_unload_callback (%p)", context); + GlobalContextManager::getInstance()->removeGlobalContext(static_cast<JSContextRef>(context)); +} + +PLUGIN_ON_WIDGET_START(on_widget_start_callback) +PLUGIN_ON_WIDGET_STOP(on_widget_stop_callback) +PLUGIN_ON_FRAME_LOAD(on_frame_load_callback) +PLUGIN_ON_FRAME_UNLOAD(on_frame_unload_callback) + +PLUGIN_CLASS_MAP_BEGIN +PLUGIN_CLASS_MAP_ADD_CLASS(WRT_JS_EXTENSION_OBJECT_TIZEN, + "sensorService", + (js_class_template_getter)JSSensorService::getClassRef, + NULL) +PLUGIN_CLASS_MAP_END + +} // Sensor +} // DeviceAPI diff --git a/wearable_src/Systeminfo/BaseProperties.h b/wearable_src/Systeminfo/BaseProperties.h new file mode 100755 index 0000000..fed0c85 --- /dev/null +++ b/wearable_src/Systeminfo/BaseProperties.h @@ -0,0 +1,82 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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_API_BASE_PROPERTIES_H_ +#define WRTPLUGINS_API_BASE_PROPERTIES_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <dpl/shared_ptr.h> +#include <CommonsJavaScript/PrivateObject.h> +#include <CommonsJavaScript/Converter.h> +#include "JSNetworkInfo.h" +#include "JSWifiNetworkInfo.h" +#include "JSCellularNetworkInfo.h" +#include "JSSIMInfo.h" +#include "JSStorageInfo.h" +#include "JSBatteryInfo.h" +#include "JSDisplayInfo.h" +#include "JSCpuInfo.h" +#include "JSDeviceCapabilitiesInfo.h" +#include "JSDeviceOrientationInfo.h" +#include "JSBuildInfo.h" +#include "JSLocaleInfo.h" +#include "JSPeripheralInfo.h" +#include "SysteminfoPropertyInfo.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Systeminfo { + +struct WatchOption +{ + unsigned long timeout; + double highThreshold; + double lowThreshold; + std::string id; + + WatchOption () : + timeout(0), + highThreshold(0.0), + lowThreshold(0.0), + id("") + { + } +}; + +class BaseProperty +{ + public: + + explicit BaseProperty() + { + } + + virtual ~BaseProperty() + { + } + + virtual JSValueRef getValue(JSContextRef context) const = 0; + virtual const char* getProperty() const = 0; + virtual const int getWatchType() const = 0; +}; + +typedef DPL::SharedPtr<BaseProperty> BasePropertyPtr; + +} +} + +#endif diff --git a/wearable_src/Systeminfo/CMakeLists.txt b/wearable_src/Systeminfo/CMakeLists.txt new file mode 100755 index 0000000..e45e0d9 --- /dev/null +++ b/wearable_src/Systeminfo/CMakeLists.txt @@ -0,0 +1,76 @@ +SET(TARGET_NAME ${systeminfo_target}) +SET(DESTINATION_NAME ${systeminfo_dest}) +SET(TARGET_IMPL_NAME ${systeminfo_impl}) + +PKG_CHECK_MODULES(platform_pkgs_systeminfo REQUIRED +# capi-telephony-sim +# capi-network-connection + capi-system-info + capi-system-runtime-info + capi-system-sensor + sensor +# tapi +) + +ADD_DEFINITIONS("-fvisibility=hidden") + +INCLUDE_DIRECTORIES( + ${INCLUDE_COMMON} + ${platform_pkgs_systeminfo_INCLUDE_DIRS} +) + +SET(CMAKE_INSTALL_RPATH + ${CMAKE_INSTALL_RPATH} + ${CMAKE_INSTALL_PREFIX}/${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME} +) + +SET(SRCS_IMPL + SysteminfoFactory.cpp + EventGetSysteminfo.cpp + EventWatchSysteminfo.cpp + ISysteminfo.cpp + Systeminfo.cpp + JSDisplayInfo.cpp + JSStorageInfo.cpp + JSStorageUnitInfo.cpp + JSCpuInfo.cpp +# JSWifiNetworkInfo.cpp +# JSCellularNetworkInfo.cpp + JSBatteryInfo.cpp +# JSNetworkInfo.cpp +# JSSIMInfo.cpp + JSDeviceOrientationInfo.cpp + JSBuildInfo.cpp + JSLocaleInfo.cpp + JSDeviceCapabilitiesInfo.cpp + JSPeripheralInfo.cpp + JSSysteminfo.cpp + SysteminfoAsyncCallbackManager.cpp + SysteminfoListener.cpp + SysteminfoListenerManager.cpp +) + +ADD_LIBRARY(${TARGET_IMPL_NAME} SHARED ${SRCS_IMPL}) + +TARGET_LINK_LIBRARIES(${TARGET_IMPL_NAME} + ${LIBS_COMMON} + ${platform_pkgs_systeminfo_LIBRARIES} +) + +SET(SRCS + plugin_config.cpp + plugin_initializer.cpp +) + +ADD_LIBRARY(${TARGET_NAME} SHARED ${SRCS}) + +TARGET_LINK_LIBRARIES(${TARGET_NAME} + ${TARGET_IMPL_NAME} +) + +INSTALL(TARGETS ${TARGET_NAME} ${TARGET_IMPL_NAME} LIBRARY DESTINATION ${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME}) +INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/config.xml DESTINATION ${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME}) +INSTALL( + DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/ DESTINATION ${DESTINATION_HEADER_PREFIX}/systeminfo + FILES_MATCHING PATTERN "*.h" PATTERN "CMakeFiles" EXCLUDE +) diff --git a/wearable_src/Systeminfo/EventGetSysteminfo.cpp b/wearable_src/Systeminfo/EventGetSysteminfo.cpp new file mode 100755 index 0000000..2fa3920 --- /dev/null +++ b/wearable_src/Systeminfo/EventGetSysteminfo.cpp @@ -0,0 +1,142 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <Commons/IEvent.h> +#include <dpl/shared_ptr.h> +#include <CommonsJavaScript/Converter.h> +#include <CommonsJavaScript/JSCallbackManager.h> + +#include "EventGetSysteminfo.h" + +namespace DeviceAPI { +namespace Systeminfo { + +EventGetSysteminfo::EventGetSysteminfo() +{ + m_simValueCnt = 0; +} + +EventGetSysteminfo::~EventGetSysteminfo() +{ +} + +void EventGetSysteminfo::setSimState(char* state) +{ + m_simProperty.state = state; +} + +void EventGetSysteminfo::setSimImsi(char* mcc, char* mnc, char* msin) +{ + m_simProperty.mcc = atoi(mcc); + m_simProperty.mnc = atoi(mnc); + m_simProperty.msin = msin; +} + +int EventGetSysteminfo::addSimValueCnt() +{ + return ++m_simValueCnt; +} + +int EventGetSysteminfo::setSimValue(const int attribute, char* value) +{ + switch(attribute) { + case 0 : + m_simProperty.operatorName = value; + break; + case 1 : + m_simProperty.msisdn = value; + break; + case 2 : + m_simProperty.iccid = value; + break; + case 3 : + m_simProperty.spn = value; + break; + } + + return ++m_simValueCnt; +} + +void EventGetSysteminfo::setTapiHandle(void* handle) +{ + m_tapiHandle = handle; +} + +void EventGetSysteminfo::setBasePropertyPtr(const BasePropertyPtr& baseProperty) +{ + m_BaseProperty = baseProperty; +} + +void EventGetSysteminfo::makeSimObject() +{ + LoggerD("enter"); + SIMPropertiesPtr SIM(new SIMProperties()); + + if (!m_BaseProperty) { + LoggerE("property is not set"); + setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::ConversionException); + } else { + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr m_callbackManager = DPL::StaticPointerCast<WrtDeviceApis::CommonsJavaScript::JSCallbackManager >(getPrivateData()); + if (!m_callbackManager) { + LoggerE("property is not set"); + setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::NullPointerException); + } else { + JSContextRef context = m_callbackManager->getContext(); + SIM->state = m_simProperty.state; + SIM->mcc = m_simProperty.mcc; + SIM->mnc = m_simProperty.mnc; + SIM->msin = m_simProperty.msin; + SIM->operatorName = m_simProperty.operatorName; + SIM->msisdn = m_simProperty.msisdn; + SIM->iccid = m_simProperty.iccid; + SIM->spn = m_simProperty.spn; + m_value = JSSIMInfo::createJSObject(context, SIM); + } + } +} + + +JSValueRef EventGetSysteminfo::getValue() const +{ + return m_value; +} + +const char * EventGetSysteminfo::getProperty() const +{ + return m_BaseProperty->getProperty(); +} + +void EventGetSysteminfo::processGetValue() +{ + LoggerD("enter"); + if (!m_BaseProperty) { + LoggerE("property is not set"); + setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::ConversionException); + } else { + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr m_callbackManager = DPL::StaticPointerCast<WrtDeviceApis::CommonsJavaScript::JSCallbackManager >(getPrivateData()); + if (!m_callbackManager) { + LoggerE("property is not set"); + setExceptionCode(WrtDeviceApis::Commons::ExceptionCodes::NullPointerException); + } else { + JSContextRef context = m_callbackManager->getContext(); + m_value = m_BaseProperty->getValue(context); + } + } +} + +} +} diff --git a/wearable_src/Systeminfo/EventGetSysteminfo.h b/wearable_src/Systeminfo/EventGetSysteminfo.h new file mode 100755 index 0000000..64b0ad0 --- /dev/null +++ b/wearable_src/Systeminfo/EventGetSysteminfo.h @@ -0,0 +1,60 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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_API_SYSTEMINFO_EVENT_GET_SYSTEMINFO_H_ +#define WRTPLUGINS_API_SYSTEMINFO_EVENT_GET_SYSTEMINFO_H_ + +#include <Commons/IEvent.h> +#include <dpl/shared_ptr.h> +#include <CommonsJavaScript/Converter.h> +#include <CommonsJavaScript/JSCallbackManager.h> +#include "ISysteminfo.h" + +namespace DeviceAPI { +namespace Systeminfo { +class EventGetSysteminfo; + +class EventGetSysteminfo : public WrtDeviceApis::Commons::IEvent<EventGetSysteminfo> +{ + private : + BasePropertyPtr m_BaseProperty; + JSValueRef m_value; + void* m_tapiHandle; + SIMProperties m_simProperty; + int m_simValueCnt; + + public : + EventGetSysteminfo(); + ~EventGetSysteminfo(); + int addSimValueCnt(); + void setSimState(char* state); + void setSimImsi(char* mcc, char* mnc, char* msin); + int setSimValue(const int attribute, char* value); + void setTapiHandle(void* handle); + void setBasePropertyPtr(const BasePropertyPtr& baseProperty); + void makeSimObject(); + JSValueRef getValue() const; + const char * getProperty() const; + void processGetValue(); +}; + +typedef DPL::SharedPtr<EventGetSysteminfo> EventGetSysteminfoPtr; + +} +} + +#endif
\ No newline at end of file diff --git a/wearable_src/Systeminfo/EventWatchSysteminfo.cpp b/wearable_src/Systeminfo/EventWatchSysteminfo.cpp new file mode 100755 index 0000000..4863c3d --- /dev/null +++ b/wearable_src/Systeminfo/EventWatchSysteminfo.cpp @@ -0,0 +1,366 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <CommonsJavaScript/Converter.h> +#include <Commons/Exception.h> +#include "EventWatchSysteminfo.h" +#include "Systeminfo.h" + +namespace DeviceAPI { +namespace Systeminfo { + +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::Commons; + +namespace { + +static Eina_Bool timeout_timer_cb(void* data) +{ + EventWatchSysteminfo *event = static_cast<EventWatchSysteminfo *> (data); + event->timeoutWatch(); + return ECORE_CALLBACK_RENEW; +} + +} + +#define MAX_STORAGE_CNT 2 +DPL::Atomic EventWatchSysteminfo::m_uniqId = 1; + +EventWatchSysteminfo::EventWatchSysteminfo() : m_id(m_uniqId) +{ + m_initTimer = NULL; + m_canceled = false; + m_storageCnt = 0; + m_tmpStorageCnt = 0; + m_Systeminfo = NULL; + m_setLastValue = false; + ++m_uniqId; +} + +EventWatchSysteminfo::~EventWatchSysteminfo() +{ + LoggerD("destroy event data, id=" << m_id); + removeTimer(); +} + +void EventWatchSysteminfo::setWatchOption(const WatchOption& watchoption) { + m_WatchOption = watchoption; +} + +WatchOption EventWatchSysteminfo::getWatchOption() { + return m_WatchOption; +} + +JSCallbackManagerPtr EventWatchSysteminfo::getCallbackManager() { + return DPL::StaticPointerCast< JSCallbackManager >(getPrivateData()); +} + +BasePropertyPtr EventWatchSysteminfo::getBasePropertyPtr() { + return m_BaseProperty; +} + +void EventWatchSysteminfo::setSysteminfoPtr(void* SysteminfoPtr) { + m_Systeminfo = SysteminfoPtr; +} + +void EventWatchSysteminfo::setBasePropertyPtr(const BasePropertyPtr& baseProperty) { + m_BaseProperty = baseProperty; +} + +const char * EventWatchSysteminfo::getProperty() const { + return m_BaseProperty->getProperty(); +} + +const int EventWatchSysteminfo::getWatchType() const { + return m_BaseProperty->getWatchType(); +} + +void EventWatchSysteminfo::getWatchValue(int cnt) +{ + m_tmpStorageCnt = cnt; + processGetValue(); +} + +unsigned long EventWatchSysteminfo::getId() const +{ + return m_id; +} + +void EventWatchSysteminfo::setId(unsigned long id) +{ + m_id = id; +} + +void EventWatchSysteminfo::processGetValue() +{ + LoggerD("thread=" << DPL::Thread::GetCurrentThread()); + JSValueRef lastValue = NULL; + JSValueRef lastValueList[MAX_STORAGE_CNT]; + JSValueRef tmpValue = NULL; + JSValueRef tmpValueList[MAX_STORAGE_CNT]; + JSStringRef propertyName = NULL; + std::string key; + JSObjectRef object = NULL; + JSValueRef value = NULL; + double level = 0.0, brightness = 0.0, load = 0.0; + bool isCharging = false; + double capacity[MAX_STORAGE_CNT]; + double availableCapacity[MAX_STORAGE_CNT]; + bool isRemovable[MAX_STORAGE_CNT]; + int watchType = m_BaseProperty->getWatchType(); + + if(m_canceled) { + LoggerD("Watch event is cancelled aleardy."); + return; + } + if (m_Systeminfo == NULL) { + LoggerE("systeminfo pointer is not set"); + return; + } + + JSCallbackManagerPtr m_cbm = DPL::StaticPointerCast< JSCallbackManager >(getPrivateData()); + JSContextRef context = m_cbm->getContext(); + + if (!m_setLastValue) { + lastValue = m_BaseProperty->getValue(context); + switch(watchType) { + case WATCH_TYPE_BATTERY : + key = "level"; + object = JSValueToObject(context, lastValue, NULL); + propertyName = JSStringCreateWithUTF8CString(key.c_str()); + m_propertyValue.batterInfo.level = JSValueToNumber(context, JSObjectGetProperty(context, object, propertyName, NULL), NULL); + + key = "isCharging"; + object = JSValueToObject(context, lastValue, NULL); + propertyName = JSStringCreateWithUTF8CString(key.c_str()); + m_propertyValue.batterInfo.isCharging = JSValueToBoolean(context, JSObjectGetProperty(context, object, propertyName, NULL)); + break; + + case WATCH_TYPE_CPU : + key = "load"; + object = JSValueToObject(context, lastValue, NULL); + propertyName = JSStringCreateWithUTF8CString(key.c_str()); + m_propertyValue.cpuInfo.load = JSValueToNumber(context, JSObjectGetProperty(context, object, propertyName, NULL), NULL); + break; + + case WATCH_TYPE_STORAGE: + if (m_tmpStorageCnt > MAX_STORAGE_CNT) { + Throw(WrtDeviceApis::Commons::Exception); + } + + key = "units"; + object = JSValueToObject(context, lastValue, NULL); + propertyName = JSStringCreateWithUTF8CString(key.c_str()); + value = JSObjectGetProperty(context, object, propertyName, NULL); + + for (int i=0; i<m_tmpStorageCnt; i++) { + + lastValueList[i] = JSGetArrayElement(context, JSValueToObject(context, value, NULL), i); + + key = "capacity"; + object = JSValueToObject(context, lastValueList[i], NULL); + propertyName = JSStringCreateWithUTF8CString(key.c_str()); + m_propertyValue.storageInfo[i].capacity = JSValueToNumber(context, JSObjectGetProperty(context, object, propertyName, NULL), NULL); + + key = "availableCapacity"; + object = JSValueToObject(context, lastValueList[i], NULL); + propertyName = JSStringCreateWithUTF8CString(key.c_str()); + m_propertyValue.storageInfo[i].availableCapacity = JSValueToNumber(context, JSObjectGetProperty(context, object, propertyName, NULL), NULL); + + key = "isRemovable"; + object = JSValueToObject(context, lastValueList[i], NULL); + propertyName = JSStringCreateWithUTF8CString(key.c_str()); + m_propertyValue.storageInfo[i].isRemovable = JSValueToBoolean(context, JSObjectGetProperty(context, object, propertyName, NULL)); + } + + m_storageCnt = m_tmpStorageCnt; + break; + + default : + LoggerD("default value"); + break; + } + m_setLastValue = true; + return; + } + + if (watchType == WATCH_TYPE_CPU) { + tmpValue = ((Systeminfo*)m_Systeminfo)->getCpuValue(context); + } else { + tmpValue = m_BaseProperty->getValue(context); + } + + if (!tmpValue) { + return; + } + + LoggerD("watchType : " << watchType); + switch(watchType) { + case WATCH_TYPE_BATTERY : + key = "level"; + object = JSValueToObject(context, tmpValue, NULL); + propertyName = JSStringCreateWithUTF8CString(key.c_str()); + level = JSValueToNumber(context, JSObjectGetProperty(context, object, propertyName, NULL), NULL); + + key = "isCharging"; + object = JSValueToObject(context, tmpValue, NULL); + propertyName = JSStringCreateWithUTF8CString(key.c_str()); + isCharging = JSValueToBoolean(context, JSObjectGetProperty(context, object, propertyName, NULL)); + + if (m_propertyValue.batterInfo.level != level || m_propertyValue.batterInfo.isCharging != isCharging) { + if (((m_WatchOption.highThreshold > 0) && (level > m_WatchOption.highThreshold)) + || ((m_WatchOption.lowThreshold > 0) && (level < m_WatchOption.lowThreshold)) + || ((m_WatchOption.highThreshold == 0) && (m_WatchOption.lowThreshold == 0))) { + LoggerD("make callback"); + m_cbm->callOnSuccess(tmpValue); + setTimer(); + } + } + m_propertyValue.batterInfo.level = level; + m_propertyValue.batterInfo.isCharging = isCharging; + break; + + case WATCH_TYPE_CPU : + key = "load"; + object = JSValueToObject(context, tmpValue, NULL); + propertyName = JSStringCreateWithUTF8CString(key.c_str()); + load = JSValueToNumber(context, JSObjectGetProperty(context, object, propertyName, NULL), NULL); + + if (m_propertyValue.cpuInfo.load != load) { + if (((m_WatchOption.highThreshold > 0) && (load > m_WatchOption.highThreshold)) + || ((m_WatchOption.lowThreshold > 0) && (load < m_WatchOption.lowThreshold)) + || ((m_WatchOption.highThreshold == 0) && (m_WatchOption.lowThreshold == 0))) { + m_cbm->callOnSuccess(tmpValue); + setTimer(); + } + } + m_propertyValue.cpuInfo.load = load; + break; + + case WATCH_TYPE_STORAGE : + if (m_tmpStorageCnt > MAX_STORAGE_CNT) { + Throw(Exception); + } + + key = "units"; + object = JSValueToObject(context, tmpValue, NULL); + propertyName = JSStringCreateWithUTF8CString(key.c_str()); + value = JSObjectGetProperty(context, object, propertyName, NULL); + + for (int i=0; i<m_tmpStorageCnt; i++) { + tmpValueList[i] = JSGetArrayElement(context, JSValueToObject(context, value, NULL), i); + key = "capacity"; + object = JSValueToObject(context, tmpValueList[i], NULL); + propertyName = JSStringCreateWithUTF8CString(key.c_str()); + capacity[i] = JSValueToNumber(context, JSObjectGetProperty(context, object, propertyName, NULL), NULL); + + key = "availableCapacity"; + object = JSValueToObject(context, tmpValueList[i], NULL); + propertyName = JSStringCreateWithUTF8CString(key.c_str()); + availableCapacity[i] = JSValueToNumber(context, JSObjectGetProperty(context, object, propertyName, NULL), NULL); + + key = "isRemovable"; + object = JSValueToObject(context, tmpValueList[i], NULL); + propertyName = JSStringCreateWithUTF8CString(key.c_str()); + isRemovable[i] = JSValueToBoolean(context, JSObjectGetProperty(context, object, propertyName, NULL)); + } + + if (m_tmpStorageCnt == m_storageCnt) { + for (int k=0; k<m_tmpStorageCnt; k++) { + if (m_propertyValue.storageInfo[k].capacity != capacity[k] || m_propertyValue.storageInfo[k].availableCapacity != availableCapacity[k] + || m_propertyValue.storageInfo[k].isRemovable != isRemovable[k]) { + LoggerD("make callback / m_tmpStorageCnt : " << m_tmpStorageCnt); + m_cbm->callOnSuccess(tmpValue); + setTimer(); + break; + } + } + } else { + LoggerD("make callback / m_tmpStorageCnt : " << m_tmpStorageCnt); + m_cbm->callOnSuccess(tmpValue); + setTimer(); + } + + m_storageCnt = m_tmpStorageCnt; + for (int j=0; j<m_tmpStorageCnt; j++) { + m_propertyValue.storageInfo[j].capacity = capacity[j]; + m_propertyValue.storageInfo[j].availableCapacity = availableCapacity[j]; + m_propertyValue.storageInfo[j].isRemovable = isRemovable[j]; + } + break; + + case WATCH_TYPE_DISPLAY : + key = "brightness"; + object = JSValueToObject(context, tmpValue, NULL); + propertyName = JSStringCreateWithUTF8CString(key.c_str()); + brightness = JSValueToNumber(context, JSObjectGetProperty(context, object, propertyName, NULL), NULL); + if (((m_WatchOption.highThreshold > 0) && (brightness > m_WatchOption.highThreshold)) + || ((m_WatchOption.lowThreshold > 0) && (brightness < m_WatchOption.lowThreshold)) + || ((m_WatchOption.highThreshold == 0) && (m_WatchOption.lowThreshold == 0))) { + LoggerD("make callback"); + m_cbm->callOnSuccess(tmpValue); + setTimer(); + } + break; + + case WATCH_TYPE_DEVICE_ORIENTATION : + case WATCH_TYPE_PERIPHERAL : + case WATCH_TYPE_LOCALE : + LoggerD("make callback"); + m_cbm->callOnSuccess(tmpValue); + setTimer(); + break; + } +} + +void EventWatchSysteminfo::setTimer() +{ + if (m_WatchOption.timeout > 0) { + if (m_initTimer) { + ecore_timer_freeze(m_initTimer); + ecore_timer_del(m_initTimer); + m_initTimer = NULL; + } + double value = m_WatchOption.timeout/(double)1000; + m_initTimer = ecore_timer_add(value, timeout_timer_cb, this); + ecore_timer_thaw(m_initTimer); + } +} + +void EventWatchSysteminfo::removeTimer() +{ + if (m_initTimer) { + ecore_timer_freeze(m_initTimer); + ecore_timer_del(m_initTimer); + } + m_initTimer = NULL; +} + +void EventWatchSysteminfo::clearWatch() +{ + m_canceled = true; + removeTimer(); + ((Systeminfo*)m_Systeminfo)->clearWatch(m_id); +} + +void EventWatchSysteminfo::timeoutWatch() +{ + clearWatch(); +} + +} +} diff --git a/wearable_src/Systeminfo/EventWatchSysteminfo.h b/wearable_src/Systeminfo/EventWatchSysteminfo.h new file mode 100755 index 0000000..e0bd0cf --- /dev/null +++ b/wearable_src/Systeminfo/EventWatchSysteminfo.h @@ -0,0 +1,100 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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_API_SYSTEMINFO_EVENT_WATCH_SYSTEMINFO_H_ +#define WRTPLUGINS_API_SYSTEMINFO_EVENT_WATCH_SYSTEMINFO_H_ + +#include <ctime> +#include <string> +#include <dpl/shared_ptr.h> +#include <dpl/noncopyable.h> +#include <Commons/IEvent.h> +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/JSCallbackManager.h> +#include "ISysteminfo.h" + +namespace DeviceAPI { +namespace Systeminfo { +class EventWatchSysteminfo; + +struct BatteryPropertyValue { + double level; + bool isCharging; +}; + +struct CpuPropertyValue { + double load; +}; + +struct StoragePropertyValue { + unsigned long long capacity; + unsigned long long availableCapacity; + bool isRemovable; +}; + +struct PropertyValue { + BatteryPropertyValue batterInfo; + CpuPropertyValue cpuInfo; + StoragePropertyValue storageInfo[2]; +}; + +class EventWatchSysteminfo : public WrtDeviceApis::Commons::IEvent<EventWatchSysteminfo> +{ + private : + static DPL::Atomic m_uniqId; + + BasePropertyPtr m_BaseProperty; + WatchOption m_WatchOption; + void* m_Systeminfo; + + Ecore_Timer *m_initTimer; + unsigned long m_id; + int m_watchType; + bool m_canceled; + DPL::Mutex m_mutex; + int m_storageCnt; + int m_tmpStorageCnt; + PropertyValue m_propertyValue; + bool m_setLastValue; + + public : + EventWatchSysteminfo(); + ~EventWatchSysteminfo(); + + void setWatchOption(const WatchOption& watchoption); + WatchOption getWatchOption(); + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr getCallbackManager(); + BasePropertyPtr getBasePropertyPtr(); + void setSysteminfoPtr(void* SysteminfoPtr); + void setBasePropertyPtr(const BasePropertyPtr& baseProperty); + const char * getProperty() const; + const int getWatchType() const; + void getWatchValue(int cnt = 1); + unsigned long getId() const; + void setId(unsigned long id); + void processGetValue(); + void setTimer(); + void removeTimer(); + void clearWatch(); + void timeoutWatch(); +}; + +typedef DPL::SharedPtr<EventWatchSysteminfo> EventWatchSysteminfoPtr; +} +} + +#endif diff --git a/wearable_src/Systeminfo/ISysteminfo.cpp b/wearable_src/Systeminfo/ISysteminfo.cpp new file mode 100755 index 0000000..11bf8a3 --- /dev/null +++ b/wearable_src/Systeminfo/ISysteminfo.cpp @@ -0,0 +1,36 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "ISysteminfo.h" +#include "EventGetSysteminfo.h" + +namespace DeviceAPI { +namespace Systeminfo { +using namespace WrtDeviceApis::Commons; + +ISysteminfo::ISysteminfo() : + EventRequestReceiver<EventGetSysteminfo>(ThreadEnum::NULL_THREAD), + EventRequestReceiver<EventWatchSysteminfo>(ThreadEnum::NULL_THREAD) +{ +} + +ISysteminfo::~ISysteminfo() +{ +} + +} +} diff --git a/wearable_src/Systeminfo/ISysteminfo.h b/wearable_src/Systeminfo/ISysteminfo.h new file mode 100755 index 0000000..2a1fca6 --- /dev/null +++ b/wearable_src/Systeminfo/ISysteminfo.h @@ -0,0 +1,61 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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_API_ISYSTEMINFO_H_ +#define WRTPLUGINS_API_ISYSTEMINFO_H_ + +#include <dpl/shared_ptr.h> +#include <Commons/ThreadPool.h> + +#include "BaseProperties.h" +#include "EventGetSysteminfo.h" +#include "EventWatchSysteminfo.h" + +namespace DeviceAPI { +namespace Systeminfo { + +class EventGetSysteminfo; +class EventWatchSysteminfo; +typedef DPL::SharedPtr<EventGetSysteminfo> EventGetSysteminfoPtr; +typedef DPL::SharedPtr<EventWatchSysteminfo> EventWatchSysteminfoPtr; + +class ISysteminfo : + public WrtDeviceApis::Commons::EventRequestReceiver<EventGetSysteminfo>, + public WrtDeviceApis::Commons::EventRequestReceiver<EventWatchSysteminfo> +{ + public: + virtual ~ISysteminfo(); + + virtual DeviceCapabilitiesPropertiesPtr getCapabilities() = 0; + virtual void get(const EventGetSysteminfoPtr& event) = 0; + virtual void watch(const EventWatchSysteminfoPtr& event) = 0; + virtual BasePropertyPtr getBasePropertyPtr(JSContextRef context, JSValueRef property) = 0; + virtual void clearWatch(const unsigned long id) = 0; + + protected: + ISysteminfo(); + + virtual void OnRequestReceived(const EventGetSysteminfoPtr& event) = 0; + virtual void OnRequestReceived(const EventWatchSysteminfoPtr& event) = 0; +}; + +typedef DPL::SharedPtr<ISysteminfo> ISysteminfoPtr; + +} +} + +#endif diff --git a/wearable_src/Systeminfo/JSBatteryInfo.cpp b/wearable_src/Systeminfo/JSBatteryInfo.cpp new file mode 100644 index 0000000..d430faf --- /dev/null +++ b/wearable_src/Systeminfo/JSBatteryInfo.cpp @@ -0,0 +1,126 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <memory> +#include "JSBatteryInfo.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Systeminfo { +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::Commons; + +namespace { +const char* BATTERY_LEVEL_PROPERTY = "level"; +const char* BATTERY_ISCHARGING_PROPERTY = "isCharging"; +} + +JSClassRef JSBatteryInfo::m_classRef = NULL; + +JSClassDefinition JSBatteryInfo::m_classInfo = { + 0, + kJSClassAttributeNone, + "batteryinfo", + 0, + m_properties, + NULL, + Initialize, + Finalize, + hasProperty, + getProperty, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL +}; + +JSStaticValue JSBatteryInfo::m_properties[] = { + { BATTERY_LEVEL_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { BATTERY_ISCHARGING_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +const JSClassRef JSBatteryInfo::getClassRef() +{ + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +const JSClassDefinition* JSBatteryInfo::getClassInfo() +{ + return &m_classInfo; +} + +void JSBatteryInfo::Initialize(JSContextRef context, JSObjectRef object) +{ +} + +void JSBatteryInfo::Finalize(JSObjectRef object) +{ + LoggerD("Entered"); + JSBatteryPriv* priv = static_cast<JSBatteryPriv*>(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + LoggerD("Deleting batteryInfo object"); + delete priv; +} + +bool JSBatteryInfo::hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName) +{ + return JSUtils::hasProperty(m_properties, propertyName); +} + +JSObjectRef JSBatteryInfo::createJSObject(JSContextRef context, const BatteryPropertiesPtr batteryInfo) +{ + LoggerD("test"); + JSBatteryPriv *priv = new JSBatteryPriv(context, batteryInfo); + return JSObjectMake(context, getClassRef(), priv); +} + +JSValueRef JSBatteryInfo::getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception) +{ + LoggerD("Enter"); + JSBatteryPriv *priv = static_cast<JSBatteryPriv*>(JSObjectGetPrivate(object)); + if (NULL == priv) { + LoggerE("Private object not set."); + return JSValueMakeUndefined(context); + } + + Try + { + BatteryPropertiesPtr batteryInfo = priv->getObject(); + Converter convert(context); + + if (JSStringIsEqualToUTF8CString(propertyName, BATTERY_LEVEL_PROPERTY)) { + return convert.toJSValueRef(batteryInfo->level); + } else if (JSStringIsEqualToUTF8CString(propertyName, BATTERY_ISCHARGING_PROPERTY)) { + return convert.toJSValueRef(batteryInfo->isCharging); + } + } + Catch(Exception) + { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSValueMakeUndefined(context); +} + +} +} diff --git a/wearable_src/Systeminfo/JSBatteryInfo.h b/wearable_src/Systeminfo/JSBatteryInfo.h new file mode 100755 index 0000000..b9a7bbb --- /dev/null +++ b/wearable_src/Systeminfo/JSBatteryInfo.h @@ -0,0 +1,48 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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_TIZEN1_0_BATTERY_INFO_H_ +#define WRTPLUGINS_TIZEN1_0_BATTERY_INFO_H_ + +#include <JavaScriptCore/JavaScript.h> +#include "SysteminfoPropertyInfo.h" + +namespace DeviceAPI { +namespace Systeminfo { +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT<BatteryPropertiesPtr>::Type JSBatteryPriv; + +class JSBatteryInfo +{ + public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSObjectRef createJSObject(JSContextRef context, const BatteryPropertiesPtr batteryInfo); + + private: + static void Initialize(JSContextRef context, JSObjectRef object); + static void Finalize(JSObjectRef object); + static bool hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName); + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + + static JSStaticValue m_properties[]; + static JSClassRef m_classRef; + static JSClassDefinition m_classInfo; +}; + +} +} +#endif diff --git a/wearable_src/Systeminfo/JSBuildInfo.cpp b/wearable_src/Systeminfo/JSBuildInfo.cpp new file mode 100755 index 0000000..a0d96ac --- /dev/null +++ b/wearable_src/Systeminfo/JSBuildInfo.cpp @@ -0,0 +1,129 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <memory> +#include "JSBuildInfo.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Systeminfo { +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::Commons; + +namespace { +const char* BUILD_MODEL_PROPERTY = "model"; +const char* BUILD_MANUFACTURER_PROPERTY = "manufacturer"; +const char* BUILD_BUILD_PROPERTY = "buildVersion"; + +} + +JSClassRef JSBuildInfo::m_classRef = NULL; + +JSClassDefinition JSBuildInfo::m_classInfo = { + 0, + kJSClassAttributeNone, + "buildinfo", + 0, + m_properties, + NULL, + Initialize, + Finalize, + hasProperty, + getProperty, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL +}; + +JSStaticValue JSBuildInfo::m_properties[] = { + { BUILD_MODEL_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { BUILD_MANUFACTURER_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { BUILD_BUILD_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +const JSClassRef JSBuildInfo::getClassRef() +{ + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +const JSClassDefinition* JSBuildInfo::getClassInfo() +{ + return &m_classInfo; +} + +void JSBuildInfo::Initialize(JSContextRef context, JSObjectRef object) +{ +} + +void JSBuildInfo::Finalize(JSObjectRef object) +{ + LoggerD("Entered"); + JSBuildPriv* priv = static_cast<JSBuildPriv*>(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + LoggerD("Deleting buildInfo object"); + delete priv; +} + +bool JSBuildInfo::hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName) +{ + return JSUtils::hasProperty(m_properties, propertyName); +} + +JSObjectRef JSBuildInfo::createJSObject(JSContextRef context, const BuildPropertiesPtr buildInfo) +{ + JSBuildPriv *priv = new JSBuildPriv(context, buildInfo); + return JSObjectMake(context, getClassRef(), priv); +} + +JSValueRef JSBuildInfo::getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception) +{ + LoggerD("Enter"); + JSBuildPriv *priv = static_cast<JSBuildPriv*>(JSObjectGetPrivate(object)); + if (NULL == priv) { + LoggerE("Private object not set."); + return JSValueMakeUndefined(context); + } + + Try + { + BuildPropertiesPtr buildInfo = priv->getObject(); + Converter convert(context); + + if (JSStringIsEqualToUTF8CString(propertyName, BUILD_MODEL_PROPERTY)) { + return convert.toJSValueRef(buildInfo->model); + } else if (JSStringIsEqualToUTF8CString(propertyName, BUILD_MANUFACTURER_PROPERTY)) { + return convert.toJSValueRef(buildInfo->manufacturer); + } else if (JSStringIsEqualToUTF8CString(propertyName, BUILD_BUILD_PROPERTY)) { + return convert.toJSValueRef(buildInfo->buildVersion); + } + } + Catch(Exception) + { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSValueMakeUndefined(context); +} +} +} diff --git a/wearable_src/Systeminfo/JSBuildInfo.h b/wearable_src/Systeminfo/JSBuildInfo.h new file mode 100755 index 0000000..4e765be --- /dev/null +++ b/wearable_src/Systeminfo/JSBuildInfo.h @@ -0,0 +1,48 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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_TIZEN1_0_BUILD_INFO_H_ +#define WRTPLUGINS_TIZEN1_0_BUILD_INFO_H_ + +#include <JavaScriptCore/JavaScript.h> +#include "SysteminfoPropertyInfo.h" + +namespace DeviceAPI { +namespace Systeminfo { +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT<BuildPropertiesPtr>::Type JSBuildPriv; + +class JSBuildInfo +{ + public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSObjectRef createJSObject(JSContextRef context, const BuildPropertiesPtr buildInfo); + + private: + static void Initialize(JSContextRef context, JSObjectRef object); + static void Finalize(JSObjectRef object); + static bool hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName); + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + + static JSStaticValue m_properties[]; + static JSClassRef m_classRef; + static JSClassDefinition m_classInfo; +}; + +} +} +#endif diff --git a/wearable_src/Systeminfo/JSCellularNetworkInfo.cpp b/wearable_src/Systeminfo/JSCellularNetworkInfo.cpp new file mode 100755 index 0000000..0c84d4d --- /dev/null +++ b/wearable_src/Systeminfo/JSCellularNetworkInfo.cpp @@ -0,0 +1,168 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <memory> +#include <JSWebAPIErrorFactory.h> +#include <SecurityExceptions.h> +#include "JSCellularNetworkInfo.h" +#include "plugin_config.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Systeminfo { +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::Commons; +using namespace DeviceAPI::Common; + +namespace { +const char* CELLULARNETWORK_STATUS_PROPERTY = "status"; +const char* CELLULARNETWORK_APN_PROPERTY = "apn"; +const char* CELLULARNETWORK_IPADDRESS_PROPERTY = "ipAddress"; +const char* CELLULARNETWORK_IPV6ADDRESS_PROPERTY = "ipv6Address"; +const char* CELLULARNETWORK_MCC_PROPERTY = "mcc"; +const char* CELLULARNETWORK_MNC_PROPERTY = "mnc"; +const char* CELLULARNETWORK_CELLID_PROPERTY = "cellId"; +const char* CELLULARNETWORK_LAC_PROPERTY = "lac"; +const char* CELLULARNETWORK_ROAMING_PROPERTY = "isRoaming"; +const char* CELLULARNETWORK_FLIGHT_MODE_PROPERTY = "isFlightMode"; +const char* CELLULARNETWORK_IMEI_PROPERTY = "imei"; +} + +JSClassRef JSCellularNetworkInfo::m_classRef = NULL; + +JSClassDefinition JSCellularNetworkInfo::m_classInfo = { + 0, + kJSClassAttributeNone, + "cellularnetworkinfo", + 0, + m_properties, + NULL, + Initialize, + Finalize, + hasProperty, + getProperty, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL +}; + +JSStaticValue JSCellularNetworkInfo::m_properties[] = { + { CELLULARNETWORK_STATUS_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { CELLULARNETWORK_APN_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { CELLULARNETWORK_IPADDRESS_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { CELLULARNETWORK_IPV6ADDRESS_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { CELLULARNETWORK_MCC_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { CELLULARNETWORK_MNC_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { CELLULARNETWORK_CELLID_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { CELLULARNETWORK_LAC_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { CELLULARNETWORK_ROAMING_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { CELLULARNETWORK_FLIGHT_MODE_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { CELLULARNETWORK_IMEI_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +const JSClassRef JSCellularNetworkInfo::getClassRef() +{ + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +const JSClassDefinition* JSCellularNetworkInfo::getClassInfo() +{ + return &m_classInfo; +} + +void JSCellularNetworkInfo::Initialize(JSContextRef context, JSObjectRef object) +{ +} + +void JSCellularNetworkInfo::Finalize(JSObjectRef object) +{ + LoggerD("Entered"); + JSCellularNetworkPriv* priv = static_cast<JSCellularNetworkPriv*>(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + LoggerD("Deleting CellularNetworkInfo object"); + delete priv; +} + +bool JSCellularNetworkInfo::hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName) +{ + return JSUtils::hasProperty(m_properties, propertyName); +} + +JSObjectRef JSCellularNetworkInfo::createJSObject(JSContextRef context, const CellularNetworkPropertiesPtr cellularNetworkInfo) +{ + LoggerD("Enter"); + JSCellularNetworkPriv *priv = new JSCellularNetworkPriv(context, cellularNetworkInfo); + return JSObjectMake(context, getClassRef(), priv); +} + +JSValueRef JSCellularNetworkInfo::getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception) +{ + LoggerD("Enter"); + JSCellularNetworkPriv *priv = static_cast<JSCellularNetworkPriv*>(JSObjectGetPrivate(object)); + if (NULL == priv) { + LoggerE("Private object not set."); + return JSValueMakeUndefined(context); + } + + Try + { + CellularNetworkPropertiesPtr cellularNetworkInfo = priv->getObject(); + Converter convert(context); + + if (JSStringIsEqualToUTF8CString(propertyName, CELLULARNETWORK_STATUS_PROPERTY)) { + return convert.toJSValueRef(cellularNetworkInfo->status); + } else if (JSStringIsEqualToUTF8CString(propertyName, CELLULARNETWORK_APN_PROPERTY)) { + return convert.toJSValueRef(cellularNetworkInfo->apn); + } else if (JSStringIsEqualToUTF8CString(propertyName, CELLULARNETWORK_IPADDRESS_PROPERTY)) { + return convert.toJSValueRef(cellularNetworkInfo->ipAddress); + } else if (JSStringIsEqualToUTF8CString(propertyName, CELLULARNETWORK_IPV6ADDRESS_PROPERTY)) { + return convert.toJSValueRef(cellularNetworkInfo->ipv6Address); + } else if (JSStringIsEqualToUTF8CString(propertyName, CELLULARNETWORK_MCC_PROPERTY)) { + return convert.toJSValueRef(cellularNetworkInfo->mcc); + } else if (JSStringIsEqualToUTF8CString(propertyName, CELLULARNETWORK_MNC_PROPERTY)) { + return convert.toJSValueRef(cellularNetworkInfo->mnc); + } else if (JSStringIsEqualToUTF8CString(propertyName, CELLULARNETWORK_CELLID_PROPERTY)) { + return convert.toJSValueRef(cellularNetworkInfo->cellId); + } else if (JSStringIsEqualToUTF8CString(propertyName, CELLULARNETWORK_LAC_PROPERTY)) { + return convert.toJSValueRef(cellularNetworkInfo->lac); + } else if (JSStringIsEqualToUTF8CString(propertyName, CELLULARNETWORK_ROAMING_PROPERTY)) { + return convert.toJSValueRef(cellularNetworkInfo->isRoaming); + } else if (JSStringIsEqualToUTF8CString(propertyName, CELLULARNETWORK_FLIGHT_MODE_PROPERTY)) { + return convert.toJSValueRef(cellularNetworkInfo->isFlightMode); + } else if (JSStringIsEqualToUTF8CString(propertyName, CELLULARNETWORK_IMEI_PROPERTY)) { + AceSecurityStatus status = SYSTEMINFO_CHECK_ACCESS(SYSTEMINFO_FUNCTION_API_GET_PROPERTY_PARTNER_VALUE); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + + return convert.toJSValueRef(cellularNetworkInfo->imei); + } + } + Catch(Exception) + { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSValueMakeUndefined(context); +} +} +} diff --git a/wearable_src/Systeminfo/JSCellularNetworkInfo.h b/wearable_src/Systeminfo/JSCellularNetworkInfo.h new file mode 100755 index 0000000..b68a6f9 --- /dev/null +++ b/wearable_src/Systeminfo/JSCellularNetworkInfo.h @@ -0,0 +1,49 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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_TIZEN1_0_CELLULARNETWORK_INFO_H_ +#define WRTPLUGINS_TIZEN1_0_CELLULARNETWORK_INFO_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <SecurityExceptions.h> +#include "SysteminfoPropertyInfo.h" + +namespace DeviceAPI { +namespace Systeminfo { +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT<CellularNetworkPropertiesPtr>::Type JSCellularNetworkPriv; + +class JSCellularNetworkInfo +{ + public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSObjectRef createJSObject(JSContextRef context, const CellularNetworkPropertiesPtr cellularNetworkInfo); + + private: + static void Initialize(JSContextRef context, JSObjectRef object); + static void Finalize(JSObjectRef object); + static bool hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName); + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + + static JSStaticValue m_properties[]; + static JSClassRef m_classRef; + static JSClassDefinition m_classInfo; +}; + +} +} +#endif diff --git a/wearable_src/Systeminfo/JSCpuInfo.cpp b/wearable_src/Systeminfo/JSCpuInfo.cpp new file mode 100644 index 0000000..36cf77d --- /dev/null +++ b/wearable_src/Systeminfo/JSCpuInfo.cpp @@ -0,0 +1,121 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <memory> +#include "JSCpuInfo.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Systeminfo { +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::Commons; + +namespace { +const char* CPU_LOAD_PROPERTY = "load"; +} + +JSClassRef JSCpuInfo::m_classRef = NULL; + +JSClassDefinition JSCpuInfo::m_classInfo = { + 0, + kJSClassAttributeNone, + "cpuinfo", + 0, + m_properties, + NULL, + Initialize, + Finalize, + hasProperty, + getProperty, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL +}; + +JSStaticValue JSCpuInfo::m_properties[] = { + { CPU_LOAD_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +const JSClassRef JSCpuInfo::getClassRef() +{ + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +const JSClassDefinition* JSCpuInfo::getClassInfo() +{ + return &m_classInfo; +} + +void JSCpuInfo::Initialize(JSContextRef context, JSObjectRef object) +{ +} + +void JSCpuInfo::Finalize(JSObjectRef object) +{ + LoggerD("Entered"); + JSCpuPriv* priv = static_cast<JSCpuPriv*>(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + LoggerD("Deleting CpuInfo object"); + delete priv; +} + +bool JSCpuInfo::hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName) +{ + return JSUtils::hasProperty(m_properties, propertyName); +} + +JSObjectRef JSCpuInfo::createJSObject(JSContextRef context, const CpuPropertiesPtr cpuInfo) +{ + LoggerD("Enter"); + JSCpuPriv *priv = new JSCpuPriv(context, cpuInfo); + return JSObjectMake(context, getClassRef(), priv); +} + +JSValueRef JSCpuInfo::getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception) +{ + LoggerD("Enter"); + JSCpuPriv *priv = static_cast<JSCpuPriv*>(JSObjectGetPrivate(object)); + if (NULL == priv) { + LoggerE("Private object not set."); + return JSValueMakeUndefined(context); + } + + Try + { + CpuPropertiesPtr cpuInfo = priv->getObject(); + Converter convert(context); + + if (JSStringIsEqualToUTF8CString(propertyName, CPU_LOAD_PROPERTY)) { + return convert.toJSValueRef(cpuInfo->load); + } + } + Catch(Exception) + { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSValueMakeUndefined(context); +} +} +} diff --git a/wearable_src/Systeminfo/JSCpuInfo.h b/wearable_src/Systeminfo/JSCpuInfo.h new file mode 100755 index 0000000..71fc969 --- /dev/null +++ b/wearable_src/Systeminfo/JSCpuInfo.h @@ -0,0 +1,48 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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_TIZEN1_0_CPU_INFO_H_ +#define WRTPLUGINS_TIZEN1_0_CPU_INFO_H_ + +#include <JavaScriptCore/JavaScript.h> +#include "SysteminfoPropertyInfo.h" + +namespace DeviceAPI { +namespace Systeminfo { +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT<CpuPropertiesPtr>::Type JSCpuPriv; + +class JSCpuInfo +{ + public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSObjectRef createJSObject(JSContextRef context, const CpuPropertiesPtr cpuInfo); + + private: + static void Initialize(JSContextRef context, JSObjectRef object); + static void Finalize(JSObjectRef object); + static bool hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName); + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + + static JSStaticValue m_properties[]; + static JSClassRef m_classRef; + static JSClassDefinition m_classInfo; +}; + +} +} +#endif diff --git a/wearable_src/Systeminfo/JSDeviceCapabilitiesInfo.cpp b/wearable_src/Systeminfo/JSDeviceCapabilitiesInfo.cpp new file mode 100755 index 0000000..b50031c --- /dev/null +++ b/wearable_src/Systeminfo/JSDeviceCapabilitiesInfo.cpp @@ -0,0 +1,1031 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <fstream> +#include <pcrecpp.h> +#include <memory> +#include <dlfcn.h> +#include <unistd.h> +#include <JSWebAPIErrorFactory.h> +#include <SecurityExceptions.h> +#include <sensors.h> +#include <system_info.h> +#include <pkgmgr-info.h> +#include "JSDeviceCapabilitiesInfo.h" +#include "plugin_config.h" +#include <Logger.h> + +#define MAXBUFSIZE 256 +#define DUID_KEY_STRING 28 +#define DUID_BUFFER_SIZE 100 + +namespace DeviceAPI { +namespace Systeminfo { +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::Commons; +using namespace DeviceAPI::Common; + +namespace { +const char* DEVICE_CAPABILITIES_BLUETOOTH = "bluetooth"; +const char* DEVICE_CAPABILITIES_NFC = "nfc"; +const char* DEVICE_CAPABILITIES_NFC_RESERVED_PUSH = "nfcReservedPush"; +const char* DEVICE_CAPABILITIES_MULTITOUCHCOUNT = "multiTouchCount"; +const char* DEVICE_CAPABILITIES_INPUTKEYBOARD = "inputKeyboard"; +const char* DEVICE_CAPABILITIES_INPUTKEYBOARD_LAYOUT = "inputKeyboardLayout"; +const char* DEVICE_CAPABILITIES_WIFI = "wifi"; +const char* DEVICE_CAPABILITIES_WIFIDIRECT = "wifiDirect"; +const char* DEVICE_CAPABILITIES_OPENGLES = "opengles"; +const char* DEVICE_CAPABILITIES_OPENGLES_TEXTURE_FORMAT = "openglestextureFormat"; +const char* DEVICE_CAPABILITIES_OPENGLESVERSION1_1 = "openglesVersion1_1"; +const char* DEVICE_CAPABILITIES_OPENGLESVERSION2_0 = "openglesVersion2_0"; +const char* DEVICE_CAPABILITIES_FMRADIO = "fmRadio"; +const char* DEVICE_CAPABILITIES_PLATFORMVERSION = "platformVersion"; +const char* DEVICE_CAPABILITIES_PLATFORMNAME = "platformName"; +const char* DEVICE_CAPABILITIES_WEBAPIVERSION = "webApiVersion"; +const char* DEVICE_CAPABILITIES_NATIVEAPIVERSION = "nativeApiVersion"; +const char* DEVICE_CAPABILITIES_CAMERA = "camera"; +const char* DEVICE_CAPABILITIES_CAMERAFRONT = "cameraFront"; +const char* DEVICE_CAPABILITIES_CAMERAFRONTFLASH = "cameraFrontFlash"; +const char* DEVICE_CAPABILITIES_CAMERABACK = "cameraBack"; +const char* DEVICE_CAPABILITIES_CAMERABACKFLASH = "cameraBackFlash"; +const char* DEVICE_CAPABILITIES_LOCATION = "location"; +const char* DEVICE_CAPABILITIES_LOCATIONGPS = "locationGps"; +const char* DEVICE_CAPABILITIES_LOCATIONWPS = "locationWps"; +const char* DEVICE_CAPABILITIES_MICROPHONE = "microphone"; +const char* DEVICE_CAPABILITIES_USBHOST = "usbHost"; +const char* DEVICE_CAPABILITIES_USBACCESSORY = "usbAccessory"; +const char* DEVICE_CAPABILITIES_SCREENOUTPUTRCA = "screenOutputRca"; +const char* DEVICE_CAPABILITIES_SCREENOUTPUTHDMI = "screenOutputHdmi"; +const char* DEVICE_CAPABILITIES_PLATFORMCORECPUARCH = "platformCoreCpuArch"; +const char* DEVICE_CAPABILITIES_PLATFORMCOREFPUARCH = "platformCoreFpuArch"; +const char* DEVICE_CAPABILITIES_SIPVOIP = "sipVoip"; +const char* DEVICE_CAPABILITIES_DUID = "duid"; +const char* DEVICE_CAPABILITIES_SPEECH_ROCOGNITION = "speechRecognition"; +const char* DEVICE_CAPABILITIES_SPEECH_SYNTHESIS = "speechSynthesis"; +const char* DEVICE_CAPABILITIES_ACCELEROMETER = "accelerometer"; +const char* DEVICE_CAPABILITIES_ACCELEROMETER_WAKEUP = "accelerometerWakeup"; +const char* DEVICE_CAPABILITIES_BAROMETER = "barometer"; +const char* DEVICE_CAPABILITIES_BAROMETER_WAKEUP = "barometerWakeup"; +const char* DEVICE_CAPABILITIES_GYROSCOPE = "gyroscope"; +const char* DEVICE_CAPABILITIES_GYROSCOPE_WAKEUP = "gyroscopeWakeup"; +const char* DEVICE_CAPABILITIES_MAGNETOMETER = "magnetometer"; +const char* DEVICE_CAPABILITIES_MAGNETOMETER_WAKEUP = "magnetometerWakeup"; +const char* DEVICE_CAPABILITIES_PHOTOMETER = "photometer"; +const char* DEVICE_CAPABILITIES_PHOTOMETER_WAKEUP = "photometerWakeup"; +const char* DEVICE_CAPABILITIES_PROXIMITY = "proximity"; +const char* DEVICE_CAPABILITIES_PROXIMITY_WAKEUP = "proximityWakeup"; +const char* DEVICE_CAPABILITIES_TILTMETER = "tiltmeter"; +const char* DEVICE_CAPABILITIES_TILTMETER_WAKEUP = "tiltmeterWakeup"; +const char* DEVICE_CAPABILITIES_DATA_ENCRYPTION = "dataEncryption"; +const char* DEVICE_CAPABILITIES_GRAPHICS_ACCELERATION = "graphicsAcceleration"; +const char* DEVICE_CAPABILITIES_PUSH = "push"; +const char* DEVICE_CAPABILITIES_TELEPHONY = "telephony"; +const char* DEVICE_CAPABILITIES_TELEPHONY_MMS = "telephonyMms"; +const char* DEVICE_CAPABILITIES_TELEPHONY_SMS = "telephonySms"; +const char* DEVICE_CAPABILITIES_SCREENSIZE_NORMAL = "screenSizeNormal"; +const char* DEVICE_CAPABILITIES_SCREENSIZE_480_800 = "screenSize480_800"; +const char* DEVICE_CAPABILITIES_SCREENSIZE_720_1280 = "screenSize720_1280"; +const char* DEVICE_CAPABILITIES_AUTO_ROTATION = "autoRotation"; +const char* DEVICE_CAPABILITIES_SHELL_APP_WIDGET = "shellAppWidget"; +const char* DEVICE_CAPABILITIES_VISION_IMAGE_RECOGNITION = "visionImageRecognition"; +const char* DEVICE_CAPABILITIES_VISION_QRCODE_GENERATION = "visionQrcodeGeneration"; +const char* DEVICE_CAPABILITIES_VISION_QRCODE_RECOGNITION = "visionQrcodeRecognition"; +const char* DEVICE_CAPABILITIES_VISION_FACE_RECOGNITION = "visionFaceRecognition"; +const char* DEVICE_CAPABILITIES_SECURE_ELEMENT = "secureElement"; +const char* DEVICE_CAPABILITIES_NATIVE_OSP_COMPATIBLE = "nativeOspCompatible"; +const char* DEVICE_CAPABILITIES_PROFILE = "profile"; +} + +JSClassRef JSDeviceCapabilitiesInfo::m_classRef = NULL; + +JSClassDefinition JSDeviceCapabilitiesInfo::m_classInfo = { + 0, + kJSClassAttributeNone, + "devicecapabilitiesinfo", + 0, + m_properties, + NULL, + Initialize, + Finalize, + hasProperty, + getProperty, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL +}; + +JSStaticValue JSDeviceCapabilitiesInfo::m_properties[] = { + { DEVICE_CAPABILITIES_BLUETOOTH, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_NFC, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_NFC_RESERVED_PUSH, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_MULTITOUCHCOUNT, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_INPUTKEYBOARD, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_INPUTKEYBOARD_LAYOUT, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_WIFI, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_WIFIDIRECT, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_OPENGLES, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_OPENGLES_TEXTURE_FORMAT, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_OPENGLESVERSION1_1, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_OPENGLESVERSION2_0, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_FMRADIO, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_PLATFORMVERSION, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_PLATFORMNAME, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_WEBAPIVERSION, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_NATIVEAPIVERSION, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_CAMERA, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_CAMERAFRONT, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_CAMERAFRONTFLASH, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_CAMERABACK, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_CAMERABACKFLASH, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_LOCATION, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_LOCATIONGPS, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_LOCATIONWPS, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_MICROPHONE, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_USBHOST, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_USBACCESSORY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_SCREENOUTPUTRCA, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_SCREENOUTPUTHDMI, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_PLATFORMCORECPUARCH, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_PLATFORMCOREFPUARCH, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_SIPVOIP, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_DUID, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_SPEECH_ROCOGNITION, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_SPEECH_SYNTHESIS, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_ACCELEROMETER, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_ACCELEROMETER_WAKEUP, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_BAROMETER, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_BAROMETER_WAKEUP, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_GYROSCOPE, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_GYROSCOPE_WAKEUP, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_MAGNETOMETER, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_MAGNETOMETER_WAKEUP, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_PHOTOMETER, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_PHOTOMETER_WAKEUP, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_PROXIMITY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_PROXIMITY_WAKEUP, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_TILTMETER, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_TILTMETER_WAKEUP, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_DATA_ENCRYPTION, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_GRAPHICS_ACCELERATION, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_PUSH, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_TELEPHONY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_TELEPHONY_MMS, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_TELEPHONY_SMS, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_SCREENSIZE_NORMAL, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_SCREENSIZE_480_800, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_SCREENSIZE_720_1280, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_AUTO_ROTATION, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_SHELL_APP_WIDGET, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_VISION_IMAGE_RECOGNITION, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_VISION_QRCODE_GENERATION, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_VISION_QRCODE_RECOGNITION, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_VISION_FACE_RECOGNITION, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_SECURE_ELEMENT, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_NATIVE_OSP_COMPATIBLE, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICE_CAPABILITIES_PROFILE, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +const JSClassRef JSDeviceCapabilitiesInfo::getClassRef() +{ + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +const JSClassDefinition* JSDeviceCapabilitiesInfo::getClassInfo() +{ + return &m_classInfo; +} + +void JSDeviceCapabilitiesInfo::Initialize(JSContextRef context, JSObjectRef object) +{ +} + +void JSDeviceCapabilitiesInfo::Finalize(JSObjectRef object) +{ + LoggerD("Entered"); + JSDeviceCapabilitiesPriv* priv = static_cast<JSDeviceCapabilitiesPriv*>(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + LoggerD("Deleting DeviceCapabilitiesInfo object"); + delete priv; +} + +bool JSDeviceCapabilitiesInfo::hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName) +{ + return JSUtils::hasProperty(m_properties, propertyName); +} + +JSObjectRef JSDeviceCapabilitiesInfo::createJSObject(JSContextRef context, const DeviceCapabilitiesPropertiesPtr deviceCapabilitiesInfo) +{ + LoggerD("Enter"); + JSDeviceCapabilitiesPriv *priv = new JSDeviceCapabilitiesPriv(context, deviceCapabilitiesInfo); + return JSObjectMake(context, getClassRef(), priv); +} + +JSValueRef JSDeviceCapabilitiesInfo::getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception) +{ + LoggerD("Enter"); + JSDeviceCapabilitiesPriv *priv = static_cast<JSDeviceCapabilitiesPriv*>(JSObjectGetPrivate(object)); + if (NULL == priv) { + LoggerE("Private object not set."); + return JSValueMakeUndefined(context); + } + + Try + { + DeviceCapabilitiesPropertiesPtr deviceCapabilitiesInfo = priv->getObject(); + Converter convert(context); + + if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_BLUETOOTH)) { + bool bluetooth = false; + if(system_info_get_platform_bool("tizen.org/feature/network.bluetooth", &bluetooth) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->bluetooth = bluetooth; + } else { + LoggerE("get fail bluetooth value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->bluetooth); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_NFC)) { + bool nfc = false; + if(system_info_get_platform_bool("tizen.org/feature/network.nfc", &nfc) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->nfc = nfc; + } else { + LoggerE("get fail nfc value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->nfc); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_NFC_RESERVED_PUSH)) { + bool nfcReservedPush = false; + if(system_info_get_platform_bool("tizen.org/feature/network.nfc.reserved_push", &nfcReservedPush) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->nfcReservedPush = nfcReservedPush; + } else { + LoggerE("get fail nfc reserved push value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->nfcReservedPush); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_MULTITOUCHCOUNT)) { + int multiTouchCount = 0; + if(system_info_get_platform_int("tizen.org/feature/multi_point_touch.point_count", &multiTouchCount) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->multiTouchCount = multiTouchCount; + } else { + LoggerE("get fail multiTouchCount value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->multiTouchCount); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_INPUTKEYBOARD)) { + bool inputKeyboard = false; + if(system_info_get_platform_bool("tizen.org/feature/input.keyboard", &inputKeyboard) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->inputKeyboard = inputKeyboard; + } else { + LoggerE("get fail inputKeyboard value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->inputKeyboard); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_INPUTKEYBOARD_LAYOUT)) { + bool inputKeyboard = false; + if(system_info_get_platform_bool("tizen.org/feature/input.keyboard", &inputKeyboard) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->inputKeyboardLayout = inputKeyboard; + } else { + LoggerE("get fail inputKeyboardLayout value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->inputKeyboardLayout); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_WIFI)) { + bool wifi = false; + if(system_info_get_platform_bool("tizen.org/feature/network.wifi", &wifi) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->wifi = wifi; + } else { + LoggerE("get fail wifi value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->wifi); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_WIFIDIRECT)) { + bool wifiDirect = false; + if(system_info_get_platform_bool("tizen.org/feature/network.wifi.direct", &wifiDirect) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->wifiDirect = wifiDirect; + } else { + LoggerE("get fail wifiDirect value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->wifiDirect); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_OPENGLES)) { + bool opengles = NULL; + if(system_info_get_platform_bool("tizen.org/feature/opengles", &opengles) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->opengles = opengles; + } else { + LoggerE("get fail opengles value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->opengles); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_OPENGLES_TEXTURE_FORMAT)) { + bool texture = false; + bool data = false; + char* textureFormat = NULL; + char textureFormatFull[MAXBUFSIZE]; + textureFormatFull[0] = '\0'; + + if (system_info_get_platform_bool("tizen.org/feature/opengles.texture_format.utc", &texture) == SYSTEM_INFO_ERROR_NONE && texture == true) { + strcat(textureFormatFull, "utc"); + data = true; + } + if (system_info_get_platform_bool("tizen.org/feature/opengles.texture_format.ptc", &texture) == SYSTEM_INFO_ERROR_NONE && texture == true) { + if (data) { + strcat(textureFormatFull, " | "); + } + strcat(textureFormatFull, "ptc"); + data = true; + } + if (system_info_get_platform_bool("tizen.org/feature/opengles.texture_format.etc", &texture) == SYSTEM_INFO_ERROR_NONE && texture == true) { + if (data) { + strcat(textureFormatFull, " | "); + } + strcat(textureFormatFull, "etc"); + data = true; + } + if (system_info_get_platform_bool("tizen.org/feature/opengles.texture_format.3dc", &texture) == SYSTEM_INFO_ERROR_NONE && texture == true) { + if (data) { + strcat(textureFormatFull, " | "); + } + strcat(textureFormatFull, "3dc"); + } + if (system_info_get_platform_bool("tizen.org/feature/opengles.texture_format.atc", &texture) == SYSTEM_INFO_ERROR_NONE && texture == true) { + if (data) { + strcat(textureFormatFull, " | "); + } + strcat(textureFormatFull, "atc"); + data = true; + } + if (system_info_get_platform_bool("tizen.org/feature/opengles.texture_format.pvrtc", &texture) == SYSTEM_INFO_ERROR_NONE && texture == true) { + if (data) { + strcat(textureFormatFull, " | "); + } + strcat(textureFormatFull, "pvrtc"); + } + + textureFormat = strdup(textureFormatFull); + + if (textureFormat == NULL) { + LoggerE("get fail openglestextureFormat value"); + return JSValueMakeUndefined(context); + } + + deviceCapabilitiesInfo->openglestextureFormat = textureFormat; + free(textureFormat); + + return convert.toJSValueRef(deviceCapabilitiesInfo->openglestextureFormat); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_OPENGLESVERSION1_1)) { + bool openglesVersion1_1 = false; + if(system_info_get_platform_bool("tizen.org/feature/opengles.version.1_1", &openglesVersion1_1) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->openglesVersion1_1 = openglesVersion1_1; + } else { + LoggerE("get fail openglesVersion1_1 value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->openglesVersion1_1); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_OPENGLESVERSION2_0)) { + bool openglesVersion2_0 = false; + if(system_info_get_platform_bool("tizen.org/feature/opengles.version.2_0", &openglesVersion2_0) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->openglesVersion2_0 = openglesVersion2_0; + } else { + LoggerE("get fail openglesVersion2_0 value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->openglesVersion2_0); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_FMRADIO)) { + bool fmRadio = false; + if(system_info_get_platform_bool("tizen.org/feature/fmradio", &fmRadio) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->fmRadio = fmRadio; + } else { + LoggerE("get fail fmRadio value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->fmRadio); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_PLATFORMVERSION)) { + AceSecurityStatus status = SYSTEMINFO_CHECK_ACCESS(SYSTEMINFO_FUNCTION_API_GET_CAPABILITIES); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + char* platformVersion = NULL; + if(system_info_get_platform_string("tizen.org/feature/platform.version", &platformVersion) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->platformVersion = platformVersion; + free(platformVersion); + } else { + LoggerE("get fail platformVersion value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->platformVersion); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_PLATFORMNAME)) { + char* platformName = NULL; + if(system_info_get_platform_string("tizen.org/system/platform.name", &platformName) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->platformName = platformName; + free(platformName); + } else { + LoggerE("get fail platformName value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->platformName); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_WEBAPIVERSION)) { + AceSecurityStatus status = SYSTEMINFO_CHECK_ACCESS(SYSTEMINFO_FUNCTION_API_GET_CAPABILITIES); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + char* webApiVersion = NULL; + if(system_info_get_platform_string("tizen.org/feature/platform.web.api.version", &webApiVersion) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->webApiVersion = webApiVersion; + free(webApiVersion); + } else { + LoggerE("get fail webApiVersion value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->webApiVersion); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_NATIVEAPIVERSION)) { + AceSecurityStatus status = SYSTEMINFO_CHECK_ACCESS(SYSTEMINFO_FUNCTION_API_GET_CAPABILITIES); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + char* nativeApiVersion = NULL; + if(system_info_get_platform_string("tizen.org/feature/platform.native.api.version", &nativeApiVersion) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->nativeApiVersion = nativeApiVersion; + free(nativeApiVersion); + } else { + LoggerE("get fail nativeApiVersion value"); + deviceCapabilitiesInfo->nativeApiVersion = ""; + free(nativeApiVersion); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->nativeApiVersion); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_CAMERAFRONT)) { + bool cameraFront = false; + if(system_info_get_platform_bool("tizen.org/feature/camera.front", &cameraFront) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->cameraFront = cameraFront; + } else { + LoggerE("get fail cameraFront value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->cameraFront); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_CAMERA)) { + bool camera = false; + if(system_info_get_platform_bool("tizen.org/feature/camera", &camera) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->camera = camera; + } else { + LoggerE("get fail camera value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->camera); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_CAMERAFRONTFLASH)) { + bool cameraFrontFlash = false; + if(system_info_get_platform_bool("tizen.org/feature/camera.front.flash", &cameraFrontFlash) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->cameraFrontFlash = cameraFrontFlash; + } else { + LoggerE("get fail cameraFrontFlash value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->cameraFrontFlash); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_CAMERABACK)) { + bool cameraBack = false; + if(system_info_get_platform_bool("tizen.org/feature/camera.back", &cameraBack) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->cameraBack = cameraBack; + } else { + LoggerE("get fail cameraBack value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->cameraBack); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_CAMERABACKFLASH)) { + bool cameraBackFlash = false; + if(system_info_get_platform_bool("tizen.org/feature/camera.back.flash", &cameraBackFlash) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->cameraBackFlash = cameraBackFlash; + } else { + LoggerE("get fail cameraBackFlash value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->cameraBackFlash); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_LOCATION)) { + bool location = false; + if(system_info_get_platform_bool("tizen.org/feature/location", &location) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->location = location; + } else { + LoggerE("get fail location value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->location); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_LOCATIONGPS)) { + bool locationGps = false; + if(system_info_get_platform_bool("tizen.org/feature/location.gps", &locationGps) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->locationGps = locationGps; + } else { + LoggerE("get fail locationGps value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->locationGps); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_LOCATIONWPS)) { + bool locationWps = false; + if(system_info_get_platform_bool("tizen.org/feature/location.wps", &locationWps) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->locationWps = locationWps; + } else { + LoggerE("get fail locationWps value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->locationWps); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_MICROPHONE)) { + bool microphone = false; + if(system_info_get_platform_bool("tizen.org/feature/microphone", µphone) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->microphone = microphone; + } else { + LoggerE("get fail microphone value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->microphone); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_USBHOST)) { + bool usbHost = false; + if(system_info_get_platform_bool("tizen.org/feature/usb.host", &usbHost) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->usbHost = usbHost; + } else { + LoggerE("get fail usbHost value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->usbHost); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_USBACCESSORY)) { + bool usbAccessory = false; + if(system_info_get_platform_bool("tizen.org/feature/usb.accessory", &usbAccessory) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->usbAccessory = usbAccessory; + } else { + LoggerE("get fail usbAccessory value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->usbAccessory); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_SCREENOUTPUTRCA)) { + bool screenOutputRca = false; + if(system_info_get_platform_bool("tizen.org/feature/screen.output.rca", &screenOutputRca) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->screenOutputRca = screenOutputRca; + } else { + LoggerE("get fail screenOutputRca value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->screenOutputRca); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_SCREENOUTPUTHDMI)) { + bool screenOutputHdmi = false; + if(system_info_get_platform_bool("tizen.org/feature/screen.output.hdmi", &screenOutputHdmi) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->screenOutputHdmi = screenOutputHdmi; + } else { + LoggerE("get fail screenOutputHdmi value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->screenOutputHdmi); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_PLATFORMCORECPUARCH)) { + bool cpuArch = false; + bool data = false; + char* platformCoreCpuArch = NULL; + char platformCoreCpuArchFull[MAXBUFSIZE]; + platformCoreCpuArchFull[0] = '\0'; + + if (system_info_get_platform_bool("tizen.org/feature/platform.core.cpu.arch.armv6", &cpuArch) == SYSTEM_INFO_ERROR_NONE && cpuArch == true) { + strcat(platformCoreCpuArchFull, "armv6"); + data = true; + } + if (system_info_get_platform_bool("tizen.org/feature/platform.core.cpu.arch.armv7", &cpuArch) == SYSTEM_INFO_ERROR_NONE && cpuArch == true) { + if (data) { + strcat(platformCoreCpuArchFull, " | "); + } + strcat(platformCoreCpuArchFull, "armv7"); + data = true; + } + if (system_info_get_platform_bool("tizen.org/feature/platform.core.cpu.arch.x86", &cpuArch) == SYSTEM_INFO_ERROR_NONE && cpuArch == true) { + if (data) { + strcat(platformCoreCpuArchFull, " | "); + } + strcat(platformCoreCpuArchFull, "x86"); + } + + platformCoreCpuArch = strdup(platformCoreCpuArchFull); + + if (platformCoreCpuArch == NULL) { + LoggerE("get fail platformCoreCpuArch value"); + return JSValueMakeUndefined(context); + } + + deviceCapabilitiesInfo->platformCoreCpuArch = platformCoreCpuArch; + free(platformCoreCpuArch); + + return convert.toJSValueRef(deviceCapabilitiesInfo->platformCoreCpuArch); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_PLATFORMCOREFPUARCH)) { + bool fpuArch = false; + bool data = false; + char* platformCoreFpuArch = NULL; + char platformCoreFpuArchFull[MAXBUFSIZE]; + platformCoreFpuArchFull[0] = '\0'; + + if (system_info_get_platform_bool("tizen.org/feature/platform.core.fpu.arch.sse2", &fpuArch) == SYSTEM_INFO_ERROR_NONE && fpuArch == true) { + data = true; + strcat(platformCoreFpuArchFull, "sse2"); + } + if (system_info_get_platform_bool("tizen.org/feature/platform.core.fpu.arch.sse3", &fpuArch) == SYSTEM_INFO_ERROR_NONE && fpuArch == true) { + if(data) { + strcat(platformCoreFpuArchFull, " | "); + } + strcat(platformCoreFpuArchFull, "sse3"); + data = true; + } + if (system_info_get_platform_bool("tizen.org/feature/platform.core.fpu.arch.ssse3", &fpuArch) == SYSTEM_INFO_ERROR_NONE && fpuArch == true) { + if(data) { + strcat(platformCoreFpuArchFull, " | "); + } + strcat(platformCoreFpuArchFull, "ssse3"); + data = true; + } + if (system_info_get_platform_bool("tizen.org/feature/platform.core.fpu.arch.vfpv2", &fpuArch) == SYSTEM_INFO_ERROR_NONE && fpuArch == true) { + if(data) { + strcat(platformCoreFpuArchFull, " | "); + } + strcat(platformCoreFpuArchFull, "vfpv2"); + data = true; + } + if (system_info_get_platform_bool("tizen.org/feature/platform.core.fpu.arch.vfpv3", &fpuArch) == SYSTEM_INFO_ERROR_NONE && fpuArch == true) { + if(data) { + strcat(platformCoreFpuArchFull, " | "); + } + strcat(platformCoreFpuArchFull, "vfpv3"); + } + platformCoreFpuArch = strdup(platformCoreFpuArchFull); + + if (platformCoreFpuArch == NULL) { + LoggerE("get fail platformCoreFpuArch value"); + return JSValueMakeUndefined(context); + } + + deviceCapabilitiesInfo->platformCoreFpuArch = platformCoreFpuArch; + free(platformCoreFpuArch); + + return convert.toJSValueRef(deviceCapabilitiesInfo->platformCoreFpuArch); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_SIPVOIP)) { + bool sipVoip = false; + if(system_info_get_platform_bool("tizen.org/feature/sip.voip", &sipVoip) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->sipVoip = sipVoip; + } else { + LoggerE("get fail sipVoip value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->sipVoip); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_DUID)) { +// FILE *fp = NULL; +// char duid[DUID_BUFFER_SIZE] = {0,}; +// fp = fopen("/opt/usr/etc/system_info_cache.ini", "r"); +// +// if(fp == NULL) { +// LoggerD("fail file open."); +// return convert.toJSValueRef(deviceCapabilitiesInfo->duid); +// } +// while(fgets(duid, DUID_BUFFER_SIZE-1, fp)) { +// if (strncmp(duid, "http://tizen.org/system/duid", DUID_KEY_STRING) == 0) { +// char* token = NULL; +// char* ptr = NULL; +// token = strtok_r(duid, "=\r\n", &ptr); +// if (token != NULL) { +// token = strtok_r(NULL, "=\r\n", &ptr); +// if (token != NULL) { +// deviceCapabilitiesInfo->duid = token; +// LoggerD("deviceCapabilitiesInfo->duid : " << deviceCapabilitiesInfo->duid); +// } +// } +// break; +// } +// } +// fclose(fp); + deviceCapabilitiesInfo->duid = ""; + return convert.toJSValueRef(deviceCapabilitiesInfo->duid); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_SPEECH_ROCOGNITION)) { + bool speechRecognition = false; + if(system_info_get_platform_bool("tizen.org/feature/speech.recognition", &speechRecognition) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->speechRecognition = speechRecognition; + } else { + LoggerE("get fail speechRecognition value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->speechRecognition); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_SPEECH_SYNTHESIS)) { + bool speechSynthesis = false; + if(system_info_get_platform_bool("tizen.org/feature/speech.synthesis", &speechSynthesis) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->speechSynthesis = speechSynthesis; + } else { + LoggerE("get fail speechSynthesis value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->speechSynthesis); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_ACCELEROMETER)) { + bool accelerometer = false; + if(system_info_get_platform_bool("tizen.org/feature/sensor.accelerometer", &accelerometer) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->accelerometer = accelerometer; + } else { + LoggerE("get fail accelerometer value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->accelerometer); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_ACCELEROMETER_WAKEUP)) { + bool accelerometerWakeup = false; + if(system_info_get_platform_bool("tizen.org/feature/sensor.accelerometer.wakeup", &accelerometerWakeup) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->accelerometerWakeup = accelerometerWakeup; + } else { + LoggerE("get fail accelerometerWakeup value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->accelerometerWakeup); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_BAROMETER)) { + bool barometer = false; + if(system_info_get_platform_bool("tizen.org/feature/sensor.barometer", &barometer) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->barometer = barometer; + } else { + LoggerE("get fail barometer value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->barometer); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_BAROMETER_WAKEUP)) { + bool barometerWakeup = false; + if(system_info_get_platform_bool("tizen.org/feature/sensor.barometer.wakeup", &barometerWakeup) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->barometerWakeup = barometerWakeup; + } else { + LoggerE("get fail barometerWakeup value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->barometerWakeup); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_GYROSCOPE)) { + bool gyroscope = false; + if(system_info_get_platform_bool("tizen.org/feature/sensor.gyroscope", &gyroscope) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->gyroscope = gyroscope; + } else { + LoggerE("get fail gyroscope value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->gyroscope); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_GYROSCOPE_WAKEUP)) { + bool gyroscopeWakeup = false; + if(system_info_get_platform_bool("tizen.org/feature/sensor.gyroscope.wakeup", &gyroscopeWakeup) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->gyroscopeWakeup = gyroscopeWakeup; + } else { + LoggerE("get fail gyroscopeWakeup value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->gyroscopeWakeup); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_MAGNETOMETER)) { + bool magnetometer = false; + if(system_info_get_platform_bool("tizen.org/feature/sensor.magnetometer", &magnetometer) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->magnetometer = magnetometer; + } else { + LoggerE("get fail magnetometer value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->magnetometer); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_MAGNETOMETER_WAKEUP)) { + bool magnetometerWakeup = false; + if(system_info_get_platform_bool("tizen.org/feature/sensor.magnetometer.wakeup", &magnetometerWakeup) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->magnetometerWakeup = magnetometerWakeup; + } else { + LoggerE("get fail magnetometerWakeup value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->magnetometerWakeup); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_PHOTOMETER)) { + bool photometer = false; + if(system_info_get_platform_bool("tizen.org/feature/sensor.photometer", &photometer) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->photometer = photometer; + } else { + LoggerE("get fail photometer value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->photometer); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_PHOTOMETER_WAKEUP)) { + bool photometerWakeup = false; + if(system_info_get_platform_bool("tizen.org/feature/sensor.photometer.wakeup", &photometerWakeup) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->photometerWakeup = photometerWakeup; + } else { + LoggerE("get fail photometerWakeup value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->photometerWakeup); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_PROXIMITY)) { + bool proximity = false; + if(system_info_get_platform_bool("tizen.org/feature/sensor.proximity", &proximity) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->proximity = proximity; + } else { + LoggerE("get fail proximity value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->proximity); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_PROXIMITY_WAKEUP)) { + bool proximityWakeup = false; + if(system_info_get_platform_bool("tizen.org/feature/sensor.proximity.wakeup", &proximityWakeup) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->proximityWakeup = proximityWakeup; + } else { + LoggerE("get fail proximityWakeup value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->proximityWakeup); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_TILTMETER)) { + bool tiltmeter = false; + if(system_info_get_platform_bool("tizen.org/feature/sensor.tiltmeter", &tiltmeter) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->tiltmeter = tiltmeter; + } else { + LoggerE("get fail tiltmeter value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->tiltmeter); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_TILTMETER_WAKEUP)) { + bool tiltmeterWakeup = false; + if(system_info_get_platform_bool("tizen.org/feature/sensor.tiltmeter.wakeup", &tiltmeterWakeup) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->tiltmeterWakeup = tiltmeterWakeup; + } else { + LoggerE("get fail tiltmeterWakeup value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->tiltmeterWakeup); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_DATA_ENCRYPTION)) { + bool dataEncryption = false; + if(system_info_get_platform_bool("tizen.org/feature/database.encryption", &dataEncryption) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->dataEncryption = dataEncryption; + } else { + LoggerE("get fail dataEncryption value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->dataEncryption); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_GRAPHICS_ACCELERATION)) { + bool graphicsAcceleration = false; + if(system_info_get_platform_bool("tizen.org/feature/graphics.acceleration", &graphicsAcceleration) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->graphicsAcceleration = graphicsAcceleration; + } else { + LoggerE("get fail graphicsAcceleration value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->graphicsAcceleration); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_PUSH)) { + bool push = false; + if(system_info_get_platform_bool("tizen.org/feature/network.push", &push) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->push = push; + } else { + LoggerE("get fail push value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->push); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_TELEPHONY)) { + bool telephony = false; + if(system_info_get_platform_bool("tizen.org/feature/network.telephony", &telephony) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->telephony = telephony; + } else { + LoggerE("get fail telephony value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->telephony); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_TELEPHONY_MMS)) { + bool telephonyMms = false; + if(system_info_get_platform_bool("tizen.org/feature/network.telephony.mms", &telephonyMms) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->telephonyMms = telephonyMms; + } else { + LoggerE("get fail telephonyMms value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->telephonyMms); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_TELEPHONY_SMS)) { + bool telephonySms = false; + if(system_info_get_platform_bool("tizen.org/feature/network.telephony.sms", &telephonySms) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->telephonySms = telephonySms; + } else { + LoggerE("get fail telephonySms value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->telephonySms); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_SCREENSIZE_NORMAL)) { + bool screenSizeNormal = false; + if(system_info_get_platform_bool("tizen.org/feature/screen.size.normal", &screenSizeNormal) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->screenSizeNormal = screenSizeNormal; + } else { + LoggerE("get fail screenSizeNormal value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->screenSizeNormal); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_SCREENSIZE_480_800)) { + bool screenSize480_800 = false; + if(system_info_get_platform_bool("tizen.org/feature/screen.size.normal.480.800", &screenSize480_800) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->screenSize480_800 = screenSize480_800; + } else { + LoggerE("get fail screenSize480_800 value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->screenSize480_800); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_SCREENSIZE_720_1280)) { + bool screenSize720_1280 = false; + if(system_info_get_platform_bool("tizen.org/feature/screen.size.normal.720.1280", &screenSize720_1280) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->screenSize720_1280 = screenSize720_1280; + } else { + LoggerE("get fail screenSize720_1280 value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->screenSize720_1280); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_AUTO_ROTATION)) { + bool autoRotation = false; + if(system_info_get_platform_bool("tizen.org/feature/screen.auto_rotation", &autoRotation) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->autoRotation = autoRotation; + } else { + LoggerE("get fail autoRotation value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->autoRotation); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_SHELL_APP_WIDGET)) { + bool shellAppWidget = false; + if(system_info_get_platform_bool("tizen.org/feature/shell.appwidget", &shellAppWidget) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->shellAppWidget = shellAppWidget; + } else { + LoggerE("get fail shellAppWidget value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->shellAppWidget); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_VISION_IMAGE_RECOGNITION)) { + bool visionImageRecognition = false; + if(system_info_get_platform_bool("tizen.org/feature/vision.image_recognition", &visionImageRecognition) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->visionImageRecognition = visionImageRecognition; + } else { + LoggerE("get fail visionImageRecognition value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->visionImageRecognition); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_VISION_QRCODE_GENERATION)) { + bool visionQrcodeGeneration = false; + if(system_info_get_platform_bool("tizen.org/feature/vision.qrcode_generation", &visionQrcodeGeneration) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->visionQrcodeGeneration = visionQrcodeGeneration; + } else { + LoggerE("get fail visionQrcodeGeneration value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->visionQrcodeGeneration); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_VISION_QRCODE_RECOGNITION)) { + bool visionQrcodeRecognition = false; + if(system_info_get_platform_bool("tizen.org/feature/vision.qrcode_recognition", &visionQrcodeRecognition) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->visionQrcodeRecognition = visionQrcodeRecognition; + } else { + LoggerE("get fail visionQrcodeRecognition value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->visionQrcodeRecognition); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_VISION_FACE_RECOGNITION)) { + bool visionFaceRecognition = false; + if(system_info_get_platform_bool("tizen.org/feature/vision.face_recognition", &visionFaceRecognition) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->visionFaceRecognition = visionFaceRecognition; + } else { + LoggerE("get fail visionFaceRecognition value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->visionFaceRecognition); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_SECURE_ELEMENT)) { + bool secureElement = false; + if(system_info_get_platform_bool("tizen.org/feature/network.secure_element", &secureElement) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->secureElement = secureElement; + } else { + LoggerE("get fail secureElement value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->secureElement); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_NATIVE_OSP_COMPATIBLE)) { + bool nativeOspCompatible = false; + if(system_info_get_platform_bool("tizen.org/feature/platform.native.osp_compatible", &nativeOspCompatible) == SYSTEM_INFO_ERROR_NONE) { + deviceCapabilitiesInfo->nativeOspCompatible = nativeOspCompatible; + } else { + LoggerE("get fail nativeOspCompatible value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->nativeOspCompatible); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICE_CAPABILITIES_PROFILE)) { + char* profile = NULL; + if(system_info_get_platform_string("tizen.org/feature/profile", &profile) == SYSTEM_INFO_ERROR_NONE) { + if (!strcmp(profile, "mobile-full")) + deviceCapabilitiesInfo->profile = "MOBILE_FULL"; + else if (!strcmp(profile, "mobile-web")) + deviceCapabilitiesInfo->profile = "MOBILE_WEB"; + else if (!strcmp(profile, "wearable")) + deviceCapabilitiesInfo->profile = "WEARABLE"; + free(profile); + } else { + LoggerE("get fail profile value"); + return JSValueMakeUndefined(context); + } + return convert.toJSValueRef(deviceCapabilitiesInfo->profile); + } + } + Catch(Exception) + { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR); + } + return JSValueMakeUndefined(context); +} + +} +} diff --git a/wearable_src/Systeminfo/JSDeviceCapabilitiesInfo.h b/wearable_src/Systeminfo/JSDeviceCapabilitiesInfo.h new file mode 100755 index 0000000..89053ab --- /dev/null +++ b/wearable_src/Systeminfo/JSDeviceCapabilitiesInfo.h @@ -0,0 +1,48 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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_TIZEN1_0_DEVICE_CAPABILITIES_INFO_H_ +#define WRTPLUGINS_TIZEN1_0_DEVICE_CAPABILITIES_INFO_H_ + +#include <JavaScriptCore/JavaScript.h> +#include "SysteminfoPropertyInfo.h" + +namespace DeviceAPI { +namespace Systeminfo { +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT<DeviceCapabilitiesPropertiesPtr>::Type JSDeviceCapabilitiesPriv; + +class JSDeviceCapabilitiesInfo +{ + public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSObjectRef createJSObject(JSContextRef context, const DeviceCapabilitiesPropertiesPtr deviceCapabilitiesInfo); + + private: + static void Initialize(JSContextRef context, JSObjectRef object); + static void Finalize(JSObjectRef object); + static bool hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName); + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + + static JSStaticValue m_properties[]; + static JSClassRef m_classRef; + static JSClassDefinition m_classInfo; +}; + +} +} +#endif diff --git a/wearable_src/Systeminfo/JSDeviceOrientationInfo.cpp b/wearable_src/Systeminfo/JSDeviceOrientationInfo.cpp new file mode 100755 index 0000000..b6c843a --- /dev/null +++ b/wearable_src/Systeminfo/JSDeviceOrientationInfo.cpp @@ -0,0 +1,124 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <memory> +#include "JSDeviceOrientationInfo.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Systeminfo { +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::Commons; + +namespace { +const char* DEVICEORIENTATION_STATUS_PROPERTY = "status"; +const char* DEVICEORIENTATION_IS_AUTOROTATION_PROPERTY = "isAutoRotation"; +} + +JSClassRef JSDeviceOrientationInfo::m_classRef = NULL; + +JSClassDefinition JSDeviceOrientationInfo::m_classInfo = { + 0, + kJSClassAttributeNone, + "deviceorientationinfo", + 0, + m_properties, + NULL, + Initialize, + Finalize, + hasProperty, + getProperty, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL +}; + +JSStaticValue JSDeviceOrientationInfo::m_properties[] = { + { DEVICEORIENTATION_STATUS_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DEVICEORIENTATION_IS_AUTOROTATION_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +const JSClassRef JSDeviceOrientationInfo::getClassRef() +{ + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +const JSClassDefinition* JSDeviceOrientationInfo::getClassInfo() +{ + return &m_classInfo; +} + +void JSDeviceOrientationInfo::Initialize(JSContextRef context, JSObjectRef object) +{ +} + +void JSDeviceOrientationInfo::Finalize(JSObjectRef object) +{ + LoggerD("Entered"); + JSDeviceOrientationPriv* priv = static_cast<JSDeviceOrientationPriv*>(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + LoggerD("Deleting deviceOrientationInfo object"); + delete priv; +} + +bool JSDeviceOrientationInfo::hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName) +{ + return JSUtils::hasProperty(m_properties, propertyName); +} + +JSObjectRef JSDeviceOrientationInfo::createJSObject(JSContextRef context, const DeviceOrientationPropertiesPtr deviceOrientationInfo) +{ + JSDeviceOrientationPriv *priv = new JSDeviceOrientationPriv(context, deviceOrientationInfo); + return JSObjectMake(context, getClassRef(), priv); +} + +JSValueRef JSDeviceOrientationInfo::getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception) +{ + LoggerD("Enter"); + JSDeviceOrientationPriv *priv = static_cast<JSDeviceOrientationPriv*>(JSObjectGetPrivate(object)); + if (NULL == priv) { + LoggerE("Private object not set."); + return JSValueMakeUndefined(context); + } + + Try + { + DeviceOrientationPropertiesPtr deviceOrientationInfo = priv->getObject(); + Converter convert(context); + + if (JSStringIsEqualToUTF8CString(propertyName, DEVICEORIENTATION_STATUS_PROPERTY)) { + return convert.toJSValueRef(deviceOrientationInfo->status); + } else if (JSStringIsEqualToUTF8CString(propertyName, DEVICEORIENTATION_IS_AUTOROTATION_PROPERTY)) { + return convert.toJSValueRef(deviceOrientationInfo->isAutoRotation); + } + } + Catch(Exception) + { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSValueMakeUndefined(context); +} +} +} diff --git a/wearable_src/Systeminfo/JSDeviceOrientationInfo.h b/wearable_src/Systeminfo/JSDeviceOrientationInfo.h new file mode 100755 index 0000000..4c4555d --- /dev/null +++ b/wearable_src/Systeminfo/JSDeviceOrientationInfo.h @@ -0,0 +1,48 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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_TIZEN1_0_DEVICEORIENTATION_INFO_H_ +#define WRTPLUGINS_TIZEN1_0_DEVICEORIENTATION_INFO_H_ + +#include <JavaScriptCore/JavaScript.h> +#include "SysteminfoPropertyInfo.h" + +namespace DeviceAPI { +namespace Systeminfo { +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT<DeviceOrientationPropertiesPtr>::Type JSDeviceOrientationPriv; + +class JSDeviceOrientationInfo +{ + public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSObjectRef createJSObject(JSContextRef context, const DeviceOrientationPropertiesPtr deviceOrientationInfo); + + private: + static void Initialize(JSContextRef context, JSObjectRef object); + static void Finalize(JSObjectRef object); + static bool hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName); + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + + static JSStaticValue m_properties[]; + static JSClassRef m_classRef; + static JSClassDefinition m_classInfo; +}; + +} +} +#endif diff --git a/wearable_src/Systeminfo/JSDisplayInfo.cpp b/wearable_src/Systeminfo/JSDisplayInfo.cpp new file mode 100755 index 0000000..be533ae --- /dev/null +++ b/wearable_src/Systeminfo/JSDisplayInfo.cpp @@ -0,0 +1,145 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <memory> +#include "JSDisplayInfo.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Systeminfo { +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::Commons; + +namespace { +const char* DISPLAY_RESOLUTIONW_PROPERTY = "resolutionWidth"; +const char* DISPLAY_RESOLUTIONH_PROPERTY = "resolutionHeight"; +const char* DISPLAY_INCHW_PROPERTY = "dotsPerInchWidth"; +const char* DISPLAY_INCHH_PROPERTY = "dotsPerInchHeight"; +const char* DISPLAY_PHYSICALW_PROPERTY = "physicalWidth"; +const char* DISPLAY_PHYSICALH_PROPERTY = "physicalHeight"; +const char* DISPLAY_BRIGHTNESS_PROPERTY = "brightness"; +} + +JSClassRef JSDisplayInfo::m_classRef = NULL; + +JSClassDefinition JSDisplayInfo::m_classInfo = { + 0, + kJSClassAttributeNone, + "displayinfo", + 0, + m_properties, + NULL, + Initialize, + Finalize, + hasProperty, + getProperty, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL +}; + +JSStaticValue JSDisplayInfo::m_properties[] = { + { DISPLAY_RESOLUTIONW_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DISPLAY_RESOLUTIONH_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DISPLAY_INCHW_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DISPLAY_INCHH_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DISPLAY_PHYSICALW_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DISPLAY_PHYSICALH_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { DISPLAY_BRIGHTNESS_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +const JSClassRef JSDisplayInfo::getClassRef() +{ + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +const JSClassDefinition* JSDisplayInfo::getClassInfo() +{ + return &m_classInfo; +} + +void JSDisplayInfo::Initialize(JSContextRef context, JSObjectRef object) +{ +} + +void JSDisplayInfo::Finalize(JSObjectRef object) +{ + LoggerD("Entered"); + JSDisplayPriv* priv = static_cast<JSDisplayPriv*>(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + LoggerD("Deleting DisplayInfo object"); + delete priv; +} + +bool JSDisplayInfo::hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName) +{ + return JSUtils::hasProperty(m_properties, propertyName); +} + +JSObjectRef JSDisplayInfo::createJSObject(JSContextRef context, const DisplayPropertiesPtr displayInfo) +{ + JSDisplayPriv *priv = new JSDisplayPriv(context, displayInfo); + return JSObjectMake(context, getClassRef(), priv); +} + +JSValueRef JSDisplayInfo::getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception) +{ + LoggerD("Enter"); + JSDisplayPriv *priv = static_cast<JSDisplayPriv*>(JSObjectGetPrivate(object)); + if (NULL == priv) { + LoggerE("Private object not set."); + return JSValueMakeUndefined(context); + } + + Try + { + DisplayPropertiesPtr displayInfo = priv->getObject(); + Converter convert(context); + if (JSStringIsEqualToUTF8CString(propertyName, DISPLAY_RESOLUTIONW_PROPERTY)) { + return convert.toJSValueRef(displayInfo->resolutionWidth); + } else if (JSStringIsEqualToUTF8CString(propertyName, DISPLAY_RESOLUTIONH_PROPERTY)) { + return convert.toJSValueRef(displayInfo->resolutionHeight); + } else if (JSStringIsEqualToUTF8CString(propertyName, DISPLAY_INCHW_PROPERTY)) { + return convert.toJSValueRef(displayInfo->dotsPerInchWidth); + } else if (JSStringIsEqualToUTF8CString(propertyName, DISPLAY_INCHH_PROPERTY)) { + return convert.toJSValueRef(displayInfo->dotsPerInchHeight); + } else if (JSStringIsEqualToUTF8CString(propertyName, DISPLAY_PHYSICALW_PROPERTY)) { + LoggerD("width " << displayInfo->physicalWidth); + return convert.toJSValueRef(displayInfo->physicalWidth); + } else if (JSStringIsEqualToUTF8CString(propertyName, DISPLAY_PHYSICALH_PROPERTY)) { + LoggerD("width " << displayInfo->physicalHeight); + return convert.toJSValueRef(displayInfo->physicalHeight); + } else if (JSStringIsEqualToUTF8CString(propertyName, DISPLAY_BRIGHTNESS_PROPERTY)) { + return convert.toJSValueRef(displayInfo->brightness); + } + } + Catch(Exception) + { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSValueMakeUndefined(context); +} +} +} diff --git a/wearable_src/Systeminfo/JSDisplayInfo.h b/wearable_src/Systeminfo/JSDisplayInfo.h new file mode 100755 index 0000000..ec83737 --- /dev/null +++ b/wearable_src/Systeminfo/JSDisplayInfo.h @@ -0,0 +1,48 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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_TIZEN1_0_DISPLAY_INFO_H_ +#define WRTPLUGINS_TIZEN1_0_DISPLAY_INFO_H_ + +#include <JavaScriptCore/JavaScript.h> +#include "SysteminfoPropertyInfo.h" + +namespace DeviceAPI { +namespace Systeminfo { +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT<DisplayPropertiesPtr>::Type JSDisplayPriv; + +class JSDisplayInfo +{ + public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSObjectRef createJSObject(JSContextRef context, const DisplayPropertiesPtr displayInfo); + + private: + static void Initialize(JSContextRef context, JSObjectRef object); + static void Finalize(JSObjectRef object); + static bool hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName); + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + + static JSStaticValue m_properties[]; + static JSClassRef m_classRef; + static JSClassDefinition m_classInfo; +}; + +} +} +#endif diff --git a/wearable_src/Systeminfo/JSLocaleInfo.cpp b/wearable_src/Systeminfo/JSLocaleInfo.cpp new file mode 100644 index 0000000..61310e4 --- /dev/null +++ b/wearable_src/Systeminfo/JSLocaleInfo.cpp @@ -0,0 +1,124 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <memory> +#include "JSLocaleInfo.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Systeminfo { +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::Commons; + +namespace { +const char* LOCALE_LANGUAGE_PROPERTY = "language"; +const char* LOCALE_COUNTRY_PROPERTY = "country"; +} + +JSClassRef JSLocaleInfo::m_classRef = NULL; + +JSClassDefinition JSLocaleInfo::m_classInfo = { + 0, + kJSClassAttributeNone, + "localeinfo", + 0, + m_properties, + NULL, + Initialize, + Finalize, + hasProperty, + getProperty, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL +}; + +JSStaticValue JSLocaleInfo::m_properties[] = { + { LOCALE_LANGUAGE_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { LOCALE_COUNTRY_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +const JSClassRef JSLocaleInfo::getClassRef() +{ + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +const JSClassDefinition* JSLocaleInfo::getClassInfo() +{ + return &m_classInfo; +} + +void JSLocaleInfo::Initialize(JSContextRef context, JSObjectRef object) +{ +} + +void JSLocaleInfo::Finalize(JSObjectRef object) +{ + LoggerD("Entered"); + JSLocalePriv* priv = static_cast<JSLocalePriv*>(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + LoggerD("Deleting localeInfo object"); + delete priv; +} + +bool JSLocaleInfo::hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName) +{ + return JSUtils::hasProperty(m_properties, propertyName); +} + +JSObjectRef JSLocaleInfo::createJSObject(JSContextRef context, const LocalePropertiesPtr localeInfo) +{ + JSLocalePriv *priv = new JSLocalePriv(context, localeInfo); + return JSObjectMake(context, getClassRef(), priv); +} + +JSValueRef JSLocaleInfo::getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception) +{ + LoggerD("Enter"); + JSLocalePriv *priv = static_cast<JSLocalePriv*>(JSObjectGetPrivate(object)); + if (NULL == priv) { + LoggerE("Private object not set."); + return JSValueMakeUndefined(context); + } + + Try + { + LocalePropertiesPtr localeInfo = priv->getObject(); + Converter convert(context); + + if (JSStringIsEqualToUTF8CString(propertyName, LOCALE_LANGUAGE_PROPERTY)) { + return convert.toJSValueRef(localeInfo->language); + } else if (JSStringIsEqualToUTF8CString(propertyName, LOCALE_COUNTRY_PROPERTY)) { + return convert.toJSValueRef(localeInfo->country); + } + } + Catch(Exception) + { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSValueMakeUndefined(context); +} +} +} diff --git a/wearable_src/Systeminfo/JSLocaleInfo.h b/wearable_src/Systeminfo/JSLocaleInfo.h new file mode 100755 index 0000000..95c8174 --- /dev/null +++ b/wearable_src/Systeminfo/JSLocaleInfo.h @@ -0,0 +1,48 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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_TIZEN1_0_LOCALE_INFO_H_ +#define WRTPLUGINS_TIZEN1_0_LOCALE_INFO_H_ + +#include <JavaScriptCore/JavaScript.h> +#include "SysteminfoPropertyInfo.h" + +namespace DeviceAPI { +namespace Systeminfo { +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT<LocalePropertiesPtr>::Type JSLocalePriv; + +class JSLocaleInfo +{ + public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSObjectRef createJSObject(JSContextRef context, const LocalePropertiesPtr localeInfo); + + private: + static void Initialize(JSContextRef context, JSObjectRef object); + static void Finalize(JSObjectRef object); + static bool hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName); + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + + static JSStaticValue m_properties[]; + static JSClassRef m_classRef; + static JSClassDefinition m_classInfo; +}; + +} +} +#endif diff --git a/wearable_src/Systeminfo/JSNetworkInfo.cpp b/wearable_src/Systeminfo/JSNetworkInfo.cpp new file mode 100644 index 0000000..83cf4db --- /dev/null +++ b/wearable_src/Systeminfo/JSNetworkInfo.cpp @@ -0,0 +1,120 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <memory> +#include "JSNetworkInfo.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Systeminfo { +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::Commons; + +namespace { +const char* NETWORK_TYPE_PROPERTY = "networkType"; +} + +JSClassRef JSNetworkInfo::m_classRef = NULL; + +JSClassDefinition JSNetworkInfo::m_classInfo = { + 0, + kJSClassAttributeNone, + "networkinfo", + 0, + m_properties, + NULL, + Initialize, + Finalize, + hasProperty, + getProperty, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL +}; + +JSStaticValue JSNetworkInfo::m_properties[] = { + { NETWORK_TYPE_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +const JSClassRef JSNetworkInfo::getClassRef() +{ + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +const JSClassDefinition* JSNetworkInfo::getClassInfo() +{ + return &m_classInfo; +} + +void JSNetworkInfo::Initialize(JSContextRef context, JSObjectRef object) +{ +} + +void JSNetworkInfo::Finalize(JSObjectRef object) +{ + LoggerD("Entered"); + JSNetworkPriv* priv = static_cast<JSNetworkPriv*>(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + LoggerD("Deleting networkInfo object"); + delete priv; +} + +bool JSNetworkInfo::hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName) +{ + return JSUtils::hasProperty(m_properties, propertyName); +} + +JSObjectRef JSNetworkInfo::createJSObject(JSContextRef context, const NetworkPropertiesPtr networkInfo) +{ + JSNetworkPriv *priv = new JSNetworkPriv(context, networkInfo); + return JSObjectMake(context, getClassRef(), priv); +} + +JSValueRef JSNetworkInfo::getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception) +{ + LoggerD("Enter"); + JSNetworkPriv *priv = static_cast<JSNetworkPriv*>(JSObjectGetPrivate(object)); + if (NULL == priv) { + LoggerE("Private object not set."); + return JSValueMakeUndefined(context); + } + + Try + { + NetworkPropertiesPtr networkInfo = priv->getObject(); + Converter convert(context); + + if (JSStringIsEqualToUTF8CString(propertyName, NETWORK_TYPE_PROPERTY)) { + return convert.toJSValueRef(networkInfo->networkType); + } + } + Catch(Exception) + { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSValueMakeUndefined(context); +} +} +} diff --git a/wearable_src/Systeminfo/JSNetworkInfo.h b/wearable_src/Systeminfo/JSNetworkInfo.h new file mode 100755 index 0000000..21971ed --- /dev/null +++ b/wearable_src/Systeminfo/JSNetworkInfo.h @@ -0,0 +1,48 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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_TIZEN1_0_NETWORK_INFO_H_ +#define WRTPLUGINS_TIZEN1_0_NETWORK_INFO_H_ + +#include <JavaScriptCore/JavaScript.h> +#include "SysteminfoPropertyInfo.h" + +namespace DeviceAPI { +namespace Systeminfo { +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT<NetworkPropertiesPtr>::Type JSNetworkPriv; + +class JSNetworkInfo +{ + public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSObjectRef createJSObject(JSContextRef context, const NetworkPropertiesPtr networkInfo); + + private: + static void Initialize(JSContextRef context, JSObjectRef object); + static void Finalize(JSObjectRef object); + static bool hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName); + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + + static JSStaticValue m_properties[]; + static JSClassRef m_classRef; + static JSClassDefinition m_classInfo; +}; + +} +} +#endif diff --git a/wearable_src/Systeminfo/JSPeripheralInfo.cpp b/wearable_src/Systeminfo/JSPeripheralInfo.cpp new file mode 100644 index 0000000..826cf7b --- /dev/null +++ b/wearable_src/Systeminfo/JSPeripheralInfo.cpp @@ -0,0 +1,120 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <memory> +#include "JSPeripheralInfo.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Systeminfo { +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::Commons; + +namespace { +const char* PERIPHERAL_IS_VIDEO_OUTPUT_ON_PROPERTY = "isVideoOutputOn"; +} + +JSClassRef JSPeripheralInfo::m_classRef = NULL; + +JSClassDefinition JSPeripheralInfo::m_classInfo = { + 0, + kJSClassAttributeNone, + "peripheralinfo", + 0, + m_properties, + NULL, + Initialize, + Finalize, + hasProperty, + getProperty, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL +}; + +JSStaticValue JSPeripheralInfo::m_properties[] = { + { PERIPHERAL_IS_VIDEO_OUTPUT_ON_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +const JSClassRef JSPeripheralInfo::getClassRef() +{ + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +const JSClassDefinition* JSPeripheralInfo::getClassInfo() +{ + return &m_classInfo; +} + +void JSPeripheralInfo::Initialize(JSContextRef context, JSObjectRef object) +{ +} + +void JSPeripheralInfo::Finalize(JSObjectRef object) +{ + LoggerD("Entered"); + JSPeripheralPriv* priv = static_cast<JSPeripheralPriv*>(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + LoggerD("Deleting peripheralInfo object"); + delete priv; +} + +bool JSPeripheralInfo::hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName) +{ + return JSUtils::hasProperty(m_properties, propertyName); +} + +JSObjectRef JSPeripheralInfo::createJSObject(JSContextRef context, const PeripheralPropertiesPtr peripheralInfo) +{ + JSPeripheralPriv *priv = new JSPeripheralPriv(context, peripheralInfo); + return JSObjectMake(context, getClassRef(), priv); +} + +JSValueRef JSPeripheralInfo::getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception) +{ + LoggerD("Enter"); + JSPeripheralPriv *priv = static_cast<JSPeripheralPriv*>(JSObjectGetPrivate(object)); + if (NULL == priv) { + LoggerE("Private object not set."); + return JSValueMakeUndefined(context); + } + + Try + { + PeripheralPropertiesPtr peripheralInfo = priv->getObject(); + Converter convert(context); + + if (JSStringIsEqualToUTF8CString(propertyName, PERIPHERAL_IS_VIDEO_OUTPUT_ON_PROPERTY)) { + return convert.toJSValueRef(peripheralInfo->isVideoOutputOn); + } + } + Catch(Exception) + { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSValueMakeUndefined(context); +} +} +} diff --git a/wearable_src/Systeminfo/JSPeripheralInfo.h b/wearable_src/Systeminfo/JSPeripheralInfo.h new file mode 100755 index 0000000..45aca3d --- /dev/null +++ b/wearable_src/Systeminfo/JSPeripheralInfo.h @@ -0,0 +1,48 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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_TIZEN1_0_PERIPHERAL_INFO_H_ +#define WRTPLUGINS_TIZEN1_0_PERIPHERAL_INFO_H_ + +#include <JavaScriptCore/JavaScript.h> +#include "SysteminfoPropertyInfo.h" + +namespace DeviceAPI { +namespace Systeminfo { +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT<PeripheralPropertiesPtr>::Type JSPeripheralPriv; + +class JSPeripheralInfo +{ + public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSObjectRef createJSObject(JSContextRef context, const PeripheralPropertiesPtr peripheralInfo); + + private: + static void Initialize(JSContextRef context, JSObjectRef object); + static void Finalize(JSObjectRef object); + static bool hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName); + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + + static JSStaticValue m_properties[]; + static JSClassRef m_classRef; + static JSClassDefinition m_classInfo; +}; + +} +} +#endif diff --git a/wearable_src/Systeminfo/JSSIMInfo.cpp b/wearable_src/Systeminfo/JSSIMInfo.cpp new file mode 100755 index 0000000..1613e3f --- /dev/null +++ b/wearable_src/Systeminfo/JSSIMInfo.cpp @@ -0,0 +1,168 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <memory> +#include <JSWebAPIErrorFactory.h> +#include <SecurityExceptions.h> +#include "JSSIMInfo.h" +#include "plugin_config.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Systeminfo { +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::Commons; +using namespace DeviceAPI::Common; + +namespace { +const char* SIM_STATE_PROPERTY = "state"; +const char* SIM_OPERATORNAME_PROPERTY = "operatorName"; +const char* SIM_MSISDN_PROPERTY = "msisdn"; +const char* SIM_ICCID_PROPERTY = "iccid"; +const char* SIM_MCC_PROPERTY = "mcc"; +const char* SIM_MNC_PROPERTY = "mnc"; +const char* SIM_MSIN_PROPERTY = "msin"; +const char* SIM_SPN_PROPERTY = "spn"; +} + +JSClassRef JSSIMInfo::m_classRef = NULL; + +JSClassDefinition JSSIMInfo::m_classInfo = { + 0, + kJSClassAttributeNone, + "siminfo", + 0, + m_properties, + NULL, + Initialize, + Finalize, + hasProperty, + getProperty, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL +}; + +JSStaticValue JSSIMInfo::m_properties[] = { + { SIM_STATE_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { SIM_OPERATORNAME_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { SIM_MSISDN_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { SIM_ICCID_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { SIM_MCC_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { SIM_MNC_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { SIM_MSIN_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { SIM_SPN_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +const JSClassRef JSSIMInfo::getClassRef() +{ + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +const JSClassDefinition* JSSIMInfo::getClassInfo() +{ + return &m_classInfo; +} + +void JSSIMInfo::Initialize(JSContextRef context, JSObjectRef object) +{ +} + +void JSSIMInfo::Finalize(JSObjectRef object) +{ + LoggerD("Entered"); + JSSIMPriv* priv = static_cast<JSSIMPriv*>(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + LoggerD("Deleting SIM Info object"); + delete priv; +} + +bool JSSIMInfo::hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName) +{ + return JSUtils::hasProperty(m_properties, propertyName); +} + +JSObjectRef JSSIMInfo::createJSObject(JSContextRef context, const SIMPropertiesPtr SIMInfo) +{ + LoggerD("Enter"); + JSSIMPriv *priv = new JSSIMPriv(context, SIMInfo); + return JSObjectMake(context, getClassRef(), priv); +} + +JSValueRef JSSIMInfo::getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception) +{ + LoggerD("Enter"); + JSSIMPriv *priv = static_cast<JSSIMPriv*>(JSObjectGetPrivate(object)); + if (NULL == priv) { + LoggerE("Private object not set."); + return JSValueMakeUndefined(context); + } + + Try + { + SIMPropertiesPtr SIMInfo = priv->getObject(); + Converter convert(context); + if (JSStringIsEqualToUTF8CString(propertyName, SIM_STATE_PROPERTY)) { + AceSecurityStatus status = SYSTEMINFO_CHECK_ACCESS(SYSTEMINFO_FUNCTION_API_GET_PROPERTY_SIM_VALUE); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + return convert.toJSValueRef(SIMInfo->state); + } else if (JSStringIsEqualToUTF8CString(propertyName, SIM_OPERATORNAME_PROPERTY)) { + AceSecurityStatus status = SYSTEMINFO_CHECK_ACCESS(SYSTEMINFO_FUNCTION_API_GET_PROPERTY_SIM_VALUE); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + return convert.toJSValueRef(SIMInfo->operatorName); + } else if (JSStringIsEqualToUTF8CString(propertyName, SIM_MSISDN_PROPERTY)) { + AceSecurityStatus status = SYSTEMINFO_CHECK_ACCESS(SYSTEMINFO_FUNCTION_API_GET_PROPERTY_PARTNER_VALUE); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + return convert.toJSValueRef(SIMInfo->msisdn); + } else if (JSStringIsEqualToUTF8CString(propertyName, SIM_ICCID_PROPERTY)) { + AceSecurityStatus status = SYSTEMINFO_CHECK_ACCESS(SYSTEMINFO_FUNCTION_API_GET_PROPERTY_SIM_VALUE); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + return convert.toJSValueRef(SIMInfo->iccid); + } else if (JSStringIsEqualToUTF8CString(propertyName, SIM_MCC_PROPERTY)) { + AceSecurityStatus status = SYSTEMINFO_CHECK_ACCESS(SYSTEMINFO_FUNCTION_API_GET_PROPERTY_SIM_VALUE); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + return convert.toJSValueRef(SIMInfo->mcc); + } else if (JSStringIsEqualToUTF8CString(propertyName, SIM_MNC_PROPERTY)) { + AceSecurityStatus status = SYSTEMINFO_CHECK_ACCESS(SYSTEMINFO_FUNCTION_API_GET_PROPERTY_SIM_VALUE); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + return convert.toJSValueRef(SIMInfo->mnc); + } else if (JSStringIsEqualToUTF8CString(propertyName, SIM_MSIN_PROPERTY)) { + AceSecurityStatus status = SYSTEMINFO_CHECK_ACCESS(SYSTEMINFO_FUNCTION_API_GET_PROPERTY_PARTNER_VALUE); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + return convert.toJSValueRef(SIMInfo->msin); + } else if (JSStringIsEqualToUTF8CString(propertyName, SIM_SPN_PROPERTY)) { + AceSecurityStatus status = SYSTEMINFO_CHECK_ACCESS(SYSTEMINFO_FUNCTION_API_GET_PROPERTY_SIM_VALUE); + TIZEN_SYNC_ACCESS_HANDLER(status, context, exception); + return convert.toJSValueRef(SIMInfo->spn); + } + } + Catch(Exception) + { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSValueMakeUndefined(context); +} +} +} diff --git a/wearable_src/Systeminfo/JSSIMInfo.h b/wearable_src/Systeminfo/JSSIMInfo.h new file mode 100755 index 0000000..7de6d53 --- /dev/null +++ b/wearable_src/Systeminfo/JSSIMInfo.h @@ -0,0 +1,48 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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_TIZEN1_0_SIM_INFO_H_ +#define WRTPLUGINS_TIZEN1_0_SIM_INFO_H_ + +#include <JavaScriptCore/JavaScript.h> +#include "SysteminfoPropertyInfo.h" + +namespace DeviceAPI { +namespace Systeminfo { +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT<SIMPropertiesPtr>::Type JSSIMPriv; + +class JSSIMInfo +{ + public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSObjectRef createJSObject(JSContextRef context, const SIMPropertiesPtr SIMInfo); + + private: + static void Initialize(JSContextRef context, JSObjectRef object); + static void Finalize(JSObjectRef object); + static bool hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName); + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + + static JSStaticValue m_properties[]; + static JSClassRef m_classRef; + static JSClassDefinition m_classInfo; +}; + +} +} +#endif diff --git a/wearable_src/Systeminfo/JSStorageInfo.cpp b/wearable_src/Systeminfo/JSStorageInfo.cpp new file mode 100755 index 0000000..8034487 --- /dev/null +++ b/wearable_src/Systeminfo/JSStorageInfo.cpp @@ -0,0 +1,140 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <memory> +#include "JSStorageUnitInfo.h" +#include "JSStorageInfo.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Systeminfo { +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::Commons; + +namespace { +const char* STORAGE_UNITS_PROPERTY = "units"; +} + +JSClassRef JSStorageInfo::m_classRef = NULL; + +JSClassDefinition JSStorageInfo::m_classInfo = { + 0, + kJSClassAttributeNone, + "storageinfo", + 0, + m_properties, + NULL, + Initialize, + Finalize, + hasProperty, + getProperty, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL +}; + +JSStaticValue JSStorageInfo::m_properties[] = { + { STORAGE_UNITS_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +const JSClassRef JSStorageInfo::getClassRef() +{ + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +const JSClassDefinition* JSStorageInfo::getClassInfo() +{ + return &m_classInfo; +} + +void JSStorageInfo::Initialize(JSContextRef context, JSObjectRef object) +{ +} + +void JSStorageInfo::Finalize(JSObjectRef object) +{ + LoggerD("Entered"); + JSStoragePriv* priv = static_cast<JSStoragePriv*>(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + LoggerD("Deleting StorageInfo object"); + delete priv; +} + +bool JSStorageInfo::hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName) +{ + return JSUtils::hasProperty(m_properties, propertyName); +} + +JSObjectRef JSStorageInfo::createJSObject(JSContextRef context, const StoragePropertiesPtr storageInfo) +{ + JSStoragePriv *priv = new JSStoragePriv(context, storageInfo); + return JSObjectMake(context, getClassRef(), priv); +} + +JSValueRef JSStorageInfo::getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception) +{ + JSStoragePriv *priv = static_cast<JSStoragePriv*>(JSObjectGetPrivate(object)); + if (NULL == priv) { + LoggerE("Private object not set."); + return JSValueMakeUndefined(context); + } + + Try + { + StoragePropertiesPtr storageInfo = priv->getObject(); + Converter convert(context); + std::vector <JSObjectRef> storagelist; + StorageUnitPropertiesPtr internal(new StorageUnitProperties()); + StorageUnitPropertiesPtr sdcard(new StorageUnitProperties()); + + if (storageInfo->cnt > 0) { + internal->type = storageInfo->units[0].type; + internal->capacity = storageInfo->units[0].capacity; + internal->availableCapacity = storageInfo->units[0].availableCapacity; + internal->isRemoveable = storageInfo->units[0].isRemoveable; + internal->isRemovable = storageInfo->units[0].isRemovable; + storagelist.push_back(JSStorageUnitInfo::createJSObject(context, internal)); + } + if (storageInfo->cnt > 1) { + sdcard->type = storageInfo->units[1].type; + sdcard->capacity = storageInfo->units[1].capacity; + sdcard->availableCapacity = storageInfo->units[1].availableCapacity; + sdcard->isRemoveable = storageInfo->units[1].isRemoveable; + sdcard->isRemovable = storageInfo->units[1].isRemovable; + storagelist.push_back(JSStorageUnitInfo::createJSObject(context, sdcard)); + } + + if (JSStringIsEqualToUTF8CString(propertyName, STORAGE_UNITS_PROPERTY)) { + return JSObjectMakeArray(context, storageInfo->cnt, storagelist.data(), NULL); + } + } + Catch(Exception) + { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSValueMakeUndefined(context); +} +} +} diff --git a/wearable_src/Systeminfo/JSStorageInfo.h b/wearable_src/Systeminfo/JSStorageInfo.h new file mode 100755 index 0000000..9161016 --- /dev/null +++ b/wearable_src/Systeminfo/JSStorageInfo.h @@ -0,0 +1,48 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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_TIZEN1_0_STORAGE_INFO_H_ +#define WRTPLUGINS_TIZEN1_0_STORAGE_INFO_H_ + +#include <JavaScriptCore/JavaScript.h> +#include "SysteminfoPropertyInfo.h" + +namespace DeviceAPI { +namespace Systeminfo { +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT<StoragePropertiesPtr>::Type JSStoragePriv; + +class JSStorageInfo +{ + public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSObjectRef createJSObject(JSContextRef context, const StoragePropertiesPtr storageInfo); + + private: + static void Initialize(JSContextRef context, JSObjectRef object); + static void Finalize(JSObjectRef object); + static bool hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName); + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + + static JSStaticValue m_properties[]; + static JSClassRef m_classRef; + static JSClassDefinition m_classInfo; +}; + +} +} +#endif diff --git a/wearable_src/Systeminfo/JSStorageUnitInfo.cpp b/wearable_src/Systeminfo/JSStorageUnitInfo.cpp new file mode 100755 index 0000000..e71cca2 --- /dev/null +++ b/wearable_src/Systeminfo/JSStorageUnitInfo.cpp @@ -0,0 +1,134 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <memory> +#include "JSStorageUnitInfo.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Systeminfo { +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::Commons; + +namespace { +const char* STORAGE_UNIT_TYPE_PROPERTY = "type"; +const char* STORAGE_UNIT_CAPACITY_PROPERTY = "capacity"; +const char* STORAGE_UNIT_AVAILCAPA_PROPERTY = "availableCapacity"; +const char* STORAGE_UNIT_REMOVEABLE_PROPERTY = "isRemoveable"; +const char* STORAGE_UNIT_REMOVABLE_PROPERTY = "isRemovable"; +} + +JSClassRef JSStorageUnitInfo::m_classRef = NULL; + +JSClassDefinition JSStorageUnitInfo::m_classInfo = { + 0, + kJSClassAttributeNone, + "storageunitinfo", + 0, + m_properties, + NULL, + Initialize, + Finalize, + hasProperty, + getProperty, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL +}; + +JSStaticValue JSStorageUnitInfo::m_properties[] = { + { STORAGE_UNIT_TYPE_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { STORAGE_UNIT_CAPACITY_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { STORAGE_UNIT_AVAILCAPA_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { STORAGE_UNIT_REMOVEABLE_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { STORAGE_UNIT_REMOVABLE_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +const JSClassRef JSStorageUnitInfo::getClassRef() +{ + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +const JSClassDefinition* JSStorageUnitInfo::getClassInfo() +{ + return &m_classInfo; +} + +void JSStorageUnitInfo::Initialize(JSContextRef context, JSObjectRef object) +{ +} + +void JSStorageUnitInfo::Finalize(JSObjectRef object) +{ + LoggerD("Entered"); + JSStorageUnitPriv* priv = static_cast<JSStorageUnitPriv*>(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + LoggerD("Deleting StorageUnitInfo object"); + delete priv; +} + +bool JSStorageUnitInfo::hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName) +{ + return JSUtils::hasProperty(m_properties, propertyName); +} + +JSObjectRef JSStorageUnitInfo::createJSObject(JSContextRef context, const StorageUnitPropertiesPtr storageUnitInfo) +{ + JSStorageUnitPriv *priv = new JSStorageUnitPriv(context, storageUnitInfo); + return JSObjectMake(context, getClassRef(), priv); +} + +JSValueRef JSStorageUnitInfo::getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception) +{ + JSStorageUnitPriv *priv = static_cast<JSStorageUnitPriv*>(JSObjectGetPrivate(object)); + if (NULL == priv) { + LoggerE("Private object not set."); + return JSValueMakeUndefined(context); + } + + Try + { + StorageUnitPropertiesPtr storageUnitInfo = priv->getObject(); + Converter convert(context); + if (JSStringIsEqualToUTF8CString(propertyName, STORAGE_UNIT_TYPE_PROPERTY)) { + return convert.toJSValueRef(storageUnitInfo->type); + } else if (JSStringIsEqualToUTF8CString(propertyName, STORAGE_UNIT_CAPACITY_PROPERTY)) { + return JSValueMakeNumber(context, storageUnitInfo->capacity); + } else if (JSStringIsEqualToUTF8CString(propertyName, STORAGE_UNIT_AVAILCAPA_PROPERTY)) { + return JSValueMakeNumber(context, storageUnitInfo->availableCapacity); + } else if (JSStringIsEqualToUTF8CString(propertyName, STORAGE_UNIT_REMOVEABLE_PROPERTY)) { + return convert.toJSValueRef(storageUnitInfo->isRemoveable); + } else if (JSStringIsEqualToUTF8CString(propertyName, STORAGE_UNIT_REMOVABLE_PROPERTY)) { + return convert.toJSValueRef(storageUnitInfo->isRemovable); + } + } + Catch(Exception) + { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSValueMakeUndefined(context); +} +} +} diff --git a/wearable_src/Systeminfo/JSStorageUnitInfo.h b/wearable_src/Systeminfo/JSStorageUnitInfo.h new file mode 100755 index 0000000..f435286 --- /dev/null +++ b/wearable_src/Systeminfo/JSStorageUnitInfo.h @@ -0,0 +1,48 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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_TIZEN1_0_STORAGE_UNIT_INFO_H_ +#define WRTPLUGINS_TIZEN1_0_STORAGE_UNIT_INFO_H_ + +#include <JavaScriptCore/JavaScript.h> +#include "SysteminfoPropertyInfo.h" + +namespace DeviceAPI { +namespace Systeminfo { +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT<StorageUnitPropertiesPtr>::Type JSStorageUnitPriv; + +class JSStorageUnitInfo +{ + public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSObjectRef createJSObject(JSContextRef context, const StorageUnitPropertiesPtr storageUnitInfo); + + private: + static void Initialize(JSContextRef context, JSObjectRef object); + static void Finalize(JSObjectRef object); + static bool hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName); + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + + static JSStaticValue m_properties[]; + static JSClassRef m_classRef; + static JSClassDefinition m_classInfo; +}; + +} +} +#endif diff --git a/wearable_src/Systeminfo/JSSysteminfo.cpp b/wearable_src/Systeminfo/JSSysteminfo.cpp new file mode 100755 index 0000000..04d8d78 --- /dev/null +++ b/wearable_src/Systeminfo/JSSysteminfo.cpp @@ -0,0 +1,319 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <CommonsJavaScript/JSUtils.h> +#include <CommonsJavaScript/Validator.h> +#include <CommonsJavaScript/ScopedJSStringRef.h> +#include <CommonsJavaScript/JSCallbackManager.h> +#include <CommonsJavaScript/Utils.h> +#include <CommonsJavaScript/Converter.h> +#include "SysteminfoFactory.h" +#include "EventGetSysteminfo.h" +#include "EventWatchSysteminfo.h" +#include <JSWebAPIErrorFactory.h> +#include <SecurityExceptions.h> +#include <TimeTracer.h> +#include <Export.h> +#include "SysteminfoListener.h" +#include "SysteminfoAsyncCallbackManager.h" +#include "SysteminfoListenerManager.h" +#include "JSSysteminfo.h" + +namespace DeviceAPI { +namespace Systeminfo { + +using namespace std; + +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::Commons; +using namespace DeviceAPI::Common; + +JSClassDefinition JSSysteminfo::m_classInfo = { + 0, + kJSClassAttributeNone, + "systeminfo", + NULL, + NULL, + m_function, + initialize, + finalize, + NULL, //hasProperty, + NULL, //getProperty, + NULL, //setProperty, + NULL, //deleteProperty, + NULL, //getPropertyNames, + NULL, + NULL, + NULL, + NULL +}; + +JSStaticFunction JSSysteminfo::m_function[] = { + { "getCapabilities", JSSysteminfo::getCapabilities, kJSPropertyAttributeNone }, + { "getPropertyValue", JSSysteminfo::getPropertyValue, kJSPropertyAttributeNone }, + { "addPropertyValueChangeListener", JSSysteminfo::addPropertyValueChangeListener, kJSPropertyAttributeNone }, + { "removePropertyValueChangeListener", JSSysteminfo::removePropertyValueChangeListener, kJSPropertyAttributeNone }, + { 0, 0, 0 } +}; + +const JSClassRef DLL_EXPORT JSSysteminfo::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSSysteminfo::getClassInfo() +{ + return &m_classInfo; +} + +JSClassRef JSSysteminfo::m_jsClassRef = JSClassCreate(JSSysteminfo::getClassInfo()); + +void JSSysteminfo::initialize(JSContextRef context, JSObjectRef object) +{ + if (!JSObjectGetPrivate(object)) { + ISysteminfoPtr Systeminfos(SysteminfoFactory::getInstance().getSysteminfos()); + JSSysteminfoPriv* priv = new JSSysteminfoPriv(context, Systeminfos); + if (!JSObjectSetPrivate(object, static_cast<void*>(priv))) { + LoggerE("Object can't store private data."); + delete priv; + } + + LoggerD("JSSysteminfo::initialize "); + } else { + LoggerD("Private object already set."); + } +} + +void JSSysteminfo::finalize(JSObjectRef object) +{ + JSSysteminfoPriv* priv = static_cast<JSSysteminfoPriv*>(JSObjectGetPrivate(object)); + + JSObjectSetPrivate(object, NULL); + LoggerD("Deleting gallery"); + delete priv; +} + +JSValueRef JSSysteminfo::getCapabilities(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) +{ + JSSysteminfoPriv *priv = static_cast<JSSysteminfoPriv*>(JSObjectGetPrivate(thisObject)); + + Converter converter(context); + Validator check(context, exception); + + if (!priv) { + LoggerE("private object is null"); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type missmatch error"); + } + Try + { + ISysteminfoPtr Systeminfos(priv->getObject()); + + DeviceCapabilitiesPropertiesPtr result(new DeviceCapabilitiesProperties()); + + result = Systeminfos->getCapabilities(); + + return (static_cast<JSValueRef>(JSDeviceCapabilitiesInfo::createJSObject(context, result))); + } + Catch(WrtDeviceApis::Commons::ConversionException) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, "Invalid values error"); + } + Catch(WrtDeviceApis::Commons::InvalidArgumentException){ + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, "Invalid values error"); + } + Catch(WrtDeviceApis::Commons::Exception) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown error"); + } +} + +JSValueRef JSSysteminfo::getPropertyValue(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) +{ + JSSysteminfoPriv *priv = static_cast<JSSysteminfoPriv*>(JSObjectGetPrivate(thisObject)); + + Converter converter(context); + Validator check(context, exception); + std::string property; + + if (!priv) { + LoggerE("private object is null"); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Wrong Object"); + } + if (argumentCount < 2) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type missmatch error"); + } + if (!check.isCallback(arguments[1])) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type missmatch error"); + } + + JSValueRef onSuccessForCbm = NULL, onErrorForCbm = NULL; + onSuccessForCbm = arguments[1]; + if (argumentCount == 3) { + if (check.isCallback(arguments[2])) { + onErrorForCbm = arguments[2]; + } else if (!JSValueIsNull(context, arguments[2])) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type missmatch error"); + } + } + + JSCallbackManagerPtr cbm(JSCallbackManager::createObject(priv->getContext(), onSuccessForCbm, onErrorForCbm, true, true)); + cbm->setObject(thisObject); + + Try { + ISysteminfoPtr Systeminfos(priv->getObject()); + BasePropertyPtr baseProperty = Systeminfos->getBasePropertyPtr(priv->getContext(), arguments[0]); + + EventGetSysteminfoPtr event(new EventGetSysteminfo()); + event->setBasePropertyPtr(baseProperty); + TIME_TRACER_ITEM_BEGIN(event->getProperty(), 0); + event->setPrivateData(DPL::StaticPointerCast<IEventPrivateData>(cbm)); + + SysteminfoListener& listener = SysteminfoListener::getInstance(); + event->setForAsynchronousCall(&listener); + + Systeminfos->get(event); + SysteminfoAsyncCallbackManagerSingleton::Instance().registerCallbackManager(cbm, priv->getContext()); + + return JSValueMakeUndefined(context); + } + + Catch(WrtDeviceApis::Commons::PlatformException) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_SUPPORTED_ERROR, "Not supported error"); + } + Catch(WrtDeviceApis::Commons::ConversionException) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type missmatch error"); + } + Catch(WrtDeviceApis::Commons::Exception) { + cbm->callOnError(JSWebAPIErrorFactory::makeErrorObject(context, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown error")); + } + return JSValueMakeUndefined(context); +} + +JSValueRef JSSysteminfo::addPropertyValueChangeListener(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) +{ + WatchOption option; + JSSysteminfoPriv *priv = static_cast<JSSysteminfoPriv*>(JSObjectGetPrivate(thisObject)); + + Converter converter(context); + Validator check(context, exception); + + if (!priv) { + LoggerE("private object is null"); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Wrong Object"); + } + if (argumentCount < 2) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type missmatch error"); + } + if (!check.isCallback(arguments[1])) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type missmatch error"); + } + + JSValueRef onSuccessForCbm = NULL; + onSuccessForCbm = arguments[1]; + + JSCallbackManagerPtr cbm(JSCallbackManager::createObject(priv->getContext(), onSuccessForCbm, NULL, true, true)); + + Try { + if (argumentCount > 2) { + if (JSValueIsObject(context, arguments[2])) { + option.timeout = converter.toULong(JSUtils::getJSProperty(context, arguments[2], "timeout", exception)); + option.highThreshold = converter.toDouble(JSUtils::getJSProperty(context, arguments[2], "highThreshold", exception)); + option.lowThreshold = converter.toDouble(JSUtils::getJSProperty(context, arguments[2], "lowThreshold", exception)); + } else if (!JSValueIsNull(context, arguments[2])) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type missmatch error"); + } + } + ISysteminfoPtr Systeminfos(priv->getObject()); + BasePropertyPtr baseProperty = Systeminfos->getBasePropertyPtr(priv->getContext(), arguments[0]); + + EventWatchSysteminfoPtr event(new EventWatchSysteminfo); + event->setWatchOption(option); + event->setBasePropertyPtr(baseProperty); + event->setPrivateData(DPL::StaticPointerCast<IEventPrivateData>(cbm)); + + SysteminfoListener& listener = SysteminfoListener::getInstance(); + event->setForAsynchronousCall(&listener); + + Systeminfos->watch(event); + LoggerD("event->getId()" << event->getId()); + + SysteminfoListenerCancellerPtr canceller = SysteminfoListenerCancellerPtr(new SysteminfoListenerCanceller(priv->getContext(), thisObject, event->getId())); + DeviceAPI::Common::IListenerItemPtr listenerItem = DPL::StaticPointerCast<DeviceAPI::Common::IListenerItem>(canceller); + SysteminfoListenerManagerSingleton::Instance().registerListener(listenerItem, priv->getContext()); + + return converter.toJSValueRef(event->getId()); + } + + Catch(WrtDeviceApis::Commons::PlatformException) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::NOT_SUPPORTED_ERROR, "Not supported error"); + } + Catch(WrtDeviceApis::Commons::ConversionException) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type missmatch error"); + } + Catch(WrtDeviceApis::Commons::InvalidArgumentException) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, "Invalid values error"); + } + Catch(WrtDeviceApis::Commons::Exception) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Platform error"); + } +} + +JSValueRef JSSysteminfo::removePropertyValueChangeListener(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) +{ + unsigned long id = 0; + JSSysteminfoPriv *priv = static_cast<JSSysteminfoPriv*>(JSObjectGetPrivate(thisObject)); + + Converter converter(context); + if (!priv) { + LoggerE("private object is null"); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Wrong Object"); + } + if (argumentCount < 1) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type missmatch error"); + } + + Try { + ISysteminfoPtr Systeminfos(priv->getObject()); + id = converter.toULong(arguments[0]); + + LoggerD("clearWatch id = " << id ); + Systeminfos->clearWatch(id); + + SysteminfoListenerCancellerPtr canceller = SysteminfoListenerCancellerPtr(new SysteminfoListenerCanceller(priv->getContext(), thisObject, id)); + DeviceAPI::Common::IListenerItemPtr listenerItem = DPL::StaticPointerCast<DeviceAPI::Common::IListenerItem>(canceller); + SysteminfoListenerManagerSingleton::Instance().unregisterListener(listenerItem); + + return JSValueMakeUndefined(context); + } + Catch(WrtDeviceApis::Commons::ConversionException) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type missmatch error"); + } + Catch(WrtDeviceApis::Commons::InvalidArgumentException) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, "Invalid values error"); + } + Catch(WrtDeviceApis::Commons::Exception) { + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown error"); + } +} + +} +} diff --git a/wearable_src/Systeminfo/JSSysteminfo.h b/wearable_src/Systeminfo/JSSysteminfo.h new file mode 100755 index 0000000..16c0b09 --- /dev/null +++ b/wearable_src/Systeminfo/JSSysteminfo.h @@ -0,0 +1,61 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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_TIZEN1_0_JS_SYSTEMINFO_H_ +#define WRTPLUGINS_TIZEN1_0_JS_SYSTEMINFO_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/PrivateObject.h> +#include "ISysteminfo.h" + +namespace DeviceAPI { +namespace Systeminfo { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT<ISysteminfoPtr>::Type JSSysteminfoPriv; + +class JSSysteminfo +{ + public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + + private: + static void initialize(JSContextRef context, JSObjectRef object); + static void finalize(JSObjectRef object); + + static JSValueRef getCapabilities(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + + static JSValueRef getPropertyValue(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + + static JSValueRef addPropertyValueChangeListener(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + + static JSValueRef removePropertyValueChangeListener(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + + static JSClassDefinition m_classInfo; + static JSStaticFunction m_function[]; + + static JSClassRef m_jsClassRef; +}; + +} +} + +#endif diff --git a/wearable_src/Systeminfo/JSWifiNetworkInfo.cpp b/wearable_src/Systeminfo/JSWifiNetworkInfo.cpp new file mode 100644 index 0000000..aa5c6da --- /dev/null +++ b/wearable_src/Systeminfo/JSWifiNetworkInfo.cpp @@ -0,0 +1,137 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <memory> +#include "JSWifiNetworkInfo.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Systeminfo { +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::Commons; + +namespace { +const char* WIFINETWORK_STATUS_PROPERTY = "status"; +const char* WIFINETWORK_SSID_PROPERTY = "ssid"; +const char* WIFINETWORK_IPADDRESS_PROPERTY = "ipAddress"; +const char* WIFINETWORK_IPV6ADDRESS_PROPERTY = "ipv6Address"; +const char* WIFINETWORK_SIGNALSTRENGTH_PROPERTY = "signalStrength"; +} + +JSClassRef JSWifiNetworkInfo::m_classRef = NULL; + +JSClassDefinition JSWifiNetworkInfo::m_classInfo = { + 0, + kJSClassAttributeNone, + "wifinetworkinfo", + 0, + m_properties, + NULL, + Initialize, + Finalize, + hasProperty, + getProperty, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL, + NULL +}; + +JSStaticValue JSWifiNetworkInfo::m_properties[] = { + { WIFINETWORK_STATUS_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { WIFINETWORK_SSID_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { WIFINETWORK_IPADDRESS_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { WIFINETWORK_IPV6ADDRESS_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { WIFINETWORK_SIGNALSTRENGTH_PROPERTY, getProperty, NULL, kJSPropertyAttributeReadOnly }, + { 0, 0, 0, 0 } +}; + +const JSClassRef JSWifiNetworkInfo::getClassRef() +{ + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +const JSClassDefinition* JSWifiNetworkInfo::getClassInfo() +{ + return &m_classInfo; +} + +void JSWifiNetworkInfo::Initialize(JSContextRef context, JSObjectRef object) +{ +} + +void JSWifiNetworkInfo::Finalize(JSObjectRef object) +{ + LoggerD("Entered"); + JSWifiNetworkPriv* priv = static_cast<JSWifiNetworkPriv*>(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + LoggerD("Deleting WifiNetworkInfo object"); + delete priv; +} + +bool JSWifiNetworkInfo::hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName) +{ + return JSUtils::hasProperty(m_properties, propertyName); +} + +JSObjectRef JSWifiNetworkInfo::createJSObject(JSContextRef context, const WifiNetworkPropertiesPtr wifiNetworkInfo) +{ + LoggerD("Enter"); + JSWifiNetworkPriv *priv = new JSWifiNetworkPriv(context, wifiNetworkInfo); + return JSObjectMake(context, getClassRef(), priv); +} + +JSValueRef JSWifiNetworkInfo::getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception) +{ + LoggerD("Enter"); + JSWifiNetworkPriv *priv = static_cast<JSWifiNetworkPriv*>(JSObjectGetPrivate(object)); + if (NULL == priv) { + LoggerE("Private object not set."); + return JSValueMakeUndefined(context); + } + + Try + { + WifiNetworkPropertiesPtr wifiNetworkInfo = priv->getObject(); + Converter convert(context); + + if (JSStringIsEqualToUTF8CString(propertyName, WIFINETWORK_STATUS_PROPERTY)) { + return convert.toJSValueRef(wifiNetworkInfo->status); + } else if (JSStringIsEqualToUTF8CString(propertyName, WIFINETWORK_SSID_PROPERTY)) { + return convert.toJSValueRef(wifiNetworkInfo->ssid); + } else if (JSStringIsEqualToUTF8CString(propertyName, WIFINETWORK_IPADDRESS_PROPERTY)) { + return convert.toJSValueRef(wifiNetworkInfo->ipAddress); + } else if (JSStringIsEqualToUTF8CString(propertyName, WIFINETWORK_IPV6ADDRESS_PROPERTY)) { + return convert.toJSValueRef(wifiNetworkInfo->ipv6Address); + } else if (JSStringIsEqualToUTF8CString(propertyName, WIFINETWORK_SIGNALSTRENGTH_PROPERTY)) { + return convert.toJSValueRef(wifiNetworkInfo->signalStrength); + } + } + Catch(Exception) + { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSValueMakeUndefined(context); +} +} +} diff --git a/wearable_src/Systeminfo/JSWifiNetworkInfo.h b/wearable_src/Systeminfo/JSWifiNetworkInfo.h new file mode 100755 index 0000000..de658d1 --- /dev/null +++ b/wearable_src/Systeminfo/JSWifiNetworkInfo.h @@ -0,0 +1,48 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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_TIZEN1_0_WIFINETWORK_INFO_H_ +#define WRTPLUGINS_TIZEN1_0_WIFINETWORK_INFO_H_ + +#include <JavaScriptCore/JavaScript.h> +#include "SysteminfoPropertyInfo.h" + +namespace DeviceAPI { +namespace Systeminfo { +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT<WifiNetworkPropertiesPtr>::Type JSWifiNetworkPriv; + +class JSWifiNetworkInfo +{ + public: + static const JSClassDefinition* getClassInfo(); + static const JSClassRef getClassRef(); + static JSObjectRef createJSObject(JSContextRef context, const WifiNetworkPropertiesPtr wifiNetworkInfo); + + private: + static void Initialize(JSContextRef context, JSObjectRef object); + static void Finalize(JSObjectRef object); + static bool hasProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName); + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception); + + static JSStaticValue m_properties[]; + static JSClassRef m_classRef; + static JSClassDefinition m_classInfo; +}; + +} +} +#endif diff --git a/wearable_src/Systeminfo/Systeminfo.cpp b/wearable_src/Systeminfo/Systeminfo.cpp new file mode 100755 index 0000000..602d228 --- /dev/null +++ b/wearable_src/Systeminfo/Systeminfo.cpp @@ -0,0 +1,1091 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <stddef.h> +#include <cassert> +#include <math.h> +#include <Commons/Exception.h> +#include <CommonsJavaScript/Converter.h> +#include <CommonsJavaScript/PrivateObject.h> +#include <TimeTracer.h> +#include "Systeminfo.h" +#include <Logger.h> +#include <string.h> + +using namespace WrtDeviceApis::CommonsJavaScript; +using namespace WrtDeviceApis::Commons; + +namespace DeviceAPI { +namespace Systeminfo { + +namespace { + +void BatteryValueCallback(keynode_t *node, void *event_ptr) +{ + if(event_ptr) { + ((Systeminfo*)event_ptr)->getWatchValue(WATCH_TYPE_BATTERY); + } +} + +void PeripheralValueCallback(keynode_t *node, void *event_ptr) +{ + if(event_ptr) { + ((Systeminfo*)event_ptr)->getWatchValue(WATCH_TYPE_PERIPHERAL); + } +} + +void DisplayValueCallback(keynode_t *node, void* event_ptr) +{ + if(event_ptr) { + ((Systeminfo*)event_ptr)->getWatchValue(WATCH_TYPE_DISPLAY); + } +} + +void OrientationValueVconfCallback(keynode_t *node, void *event_ptr) +{ + LoggerD("enter"); + if(event_ptr) { + ((Systeminfo*)event_ptr)->getWatchValue(WATCH_TYPE_DEVICE_ORIENTATION); + } +} + +void localeChangedCallback(runtime_info_key_e key, void* event_ptr) +{ + if(event_ptr) { + ((Systeminfo*)event_ptr)->getWatchValue(WATCH_TYPE_LOCALE); + } +} + +void StorageValueVconfCallback(keynode_t *node, void *event_ptr) +{ + LoggerD("enter"); + if(event_ptr) { + ((Systeminfo*)event_ptr)->getWatchValue(WATCH_TYPE_STORAGE); + } +} + +static Eina_Bool StorageValueCallback(void* event_ptr) +{ + LoggerD("enter"); + if(event_ptr) { + ((Systeminfo*)event_ptr)->getWatchValue(WATCH_TYPE_STORAGE); + } + return ECORE_CALLBACK_RENEW; +} + +static Eina_Bool CpuValueCallback(void* event_ptr) +{ + if(event_ptr) { + ((Systeminfo*)event_ptr)->getWatchValue(WATCH_TYPE_CPU); + } + return ECORE_CALLBACK_RENEW; +} + +void OrientationValueCallback(unsigned int event_type, sensor_event_data_t *event , void *event_ptr) +{ + if(event_ptr) { + ((Systeminfo*)event_ptr)->getWatchValue(WATCH_TYPE_DEVICE_ORIENTATION); + } +} + +} + +#define STORAGE_INTERNAL_PATH "/opt/usr/media" +#define STORAGE_SDCARD_PATH "/opt/storage/sdcard" +#define STORAGE_USBHOST_PATH "/opt/storage/usb" +#define DISPLAY_BRIGHTNESS_DIVIDE_VALUE 100 +#define CPU_POWER_DEVICE_VALUE 100 + +#define RADIAN_VALUE (57.2957) + +enum { + STORAGE_TYPE_UNKNOWN = 0, + STORAGE_TYPE_INTERNAL = 1, + STORAGE_TYPE_MMC = 2, + STORAGE_TYPE_USBHOST = 3 +}; + +Systeminfo::OptionalProperty Systeminfo::m_Property; + +Systeminfo::Systeminfo() : m_storageTimer(NULL), + m_cpuTimer(NULL), + m_sensorHandle(0) + +{ + int state =-1; + EventMgrPtr eventMgrPtr(new EventMgr()); + m_EventMgrPtr = eventMgrPtr; + if (m_Property.IsNull()) { + mapProperties properties; + properties["BATTERY"] = BasePropertyPtr(new Battery()); + m_Property = properties; + (*m_Property)["CPU"] = BasePropertyPtr(new Cpu()); + (*m_Property)["STORAGE"] = BasePropertyPtr(new Storage()); + (*m_Property)["DISPLAY"] = BasePropertyPtr(new Display()); + (*m_Property)["DEVICE_ORIENTATION"] = BasePropertyPtr(new DeviceOrientation()); + (*m_Property)["BUILD"] = BasePropertyPtr(new Build()); + (*m_Property)["PERIPHERAL"] = BasePropertyPtr(new Peripheral()); + (*m_Property)["LOCALE"] = BasePropertyPtr(new Locale()); + } + + m_sensorHandle = sf_connect(ACCELEROMETER_SENSOR); + if (m_sensorHandle < 0) { + LoggerE ("sensor attach fail"); + } else { + LoggerD("m_sensorHandle : " << m_sensorHandle); + + state = sf_start(m_sensorHandle, 0); + if(state < 0) { + LoggerE("failed"); + } + + state = sf_register_event(m_sensorHandle, ACCELEROMETER_EVENT_ROTATION_CHECK, NULL, OrientationValueCallback, (void *)this); + if (state < 0) { + LoggerD("sensor_register_cb fail to gather data"); + } else if (state == 0) { + LoggerD("sensor_register_cb success to gather data"); + } + } +} + +Systeminfo::~Systeminfo() +{ + int state = -1; + if (m_storageTimer) { + ecore_timer_freeze(m_storageTimer); + ecore_timer_del(m_storageTimer); + m_storageTimer = NULL; + } + if (m_cpuTimer) { + ecore_timer_freeze(m_cpuTimer); + ecore_timer_del(m_cpuTimer); + m_cpuTimer = NULL; + } + m_EventMgrPtr->clearAllEvent(); + + state = sf_unregister_event(m_sensorHandle, ACCELEROMETER_EVENT_ROTATION_CHECK); + if (state < 0) { + LoggerD("sf_unregister_event fail to gather data\n"); + } + + sf_stop(m_sensorHandle); + sf_disconnect(m_sensorHandle); +} + +DeviceCapabilitiesPropertiesPtr Systeminfo::getCapabilities() +{ + LoggerD("enter"); + DeviceCapabilitiesPropertiesPtr deviceCapabilities(new DeviceCapabilitiesProperties()); + return deviceCapabilities; +} + +bool Systeminfo::registCallback(int watchType) +{ + switch(watchType) { + case WATCH_TYPE_BATTERY: + if ((m_EventMgrPtr->getEventBatteryList()).size() == 1) { + vconf_notify_key_changed(VCONFKEY_SYSMAN_BATTERY_CAPACITY, BatteryValueCallback, (void *)this); + vconf_notify_key_changed(VCONFKEY_SYSMAN_BATTERY_CHARGE_NOW, BatteryValueCallback, (void *)this); + } + break; + case WATCH_TYPE_DISPLAY: + if ((m_EventMgrPtr->getEventDisplayList()).size() == 1) { + vconf_notify_key_changed(VCONFKEY_PM_CURRENT_BRIGHTNESS, DisplayValueCallback, (void *)this); + } + break; + case WATCH_TYPE_STORAGE: + if ((m_EventMgrPtr->getEventStorageList()).size() == 1) { + vconf_notify_key_changed(VCONFKEY_SYSMAN_MMC_STATUS, StorageValueVconfCallback, (void *)this); + if (!m_storageTimer) { + m_storageTimer = ecore_timer_add(1, StorageValueCallback, this); + ecore_timer_thaw(m_storageTimer); + } + } + break; + case WATCH_TYPE_CPU: + if ((m_EventMgrPtr->getEventCpuList()).size() == 1) { + if (!m_cpuTimer) { + m_cpuTimer = ecore_timer_add(1, CpuValueCallback, this); + ecore_timer_thaw(m_cpuTimer); + } + } + break; + case WATCH_TYPE_DEVICE_ORIENTATION: + LoggerD("regist sensor"); + if ((m_EventMgrPtr->getEventDeviceOrientationList()).size() == 1) { + vconf_notify_key_changed(VCONFKEY_SETAPPL_AUTO_ROTATE_SCREEN_BOOL, OrientationValueVconfCallback, (void *)this); + } else { + LoggerD("already regist"); + } + break; + case WATCH_TYPE_PERIPHERAL: + if ((m_EventMgrPtr->getEventPeripheralList()).size() == 1) { + vconf_notify_key_changed(VCONFKEY_MIRACAST_WFD_SOURCE_STATUS, PeripheralValueCallback, (void *)this); + vconf_notify_key_changed(VCONFKEY_SYSMAN_HDMI, PeripheralValueCallback, (void *)this); + vconf_notify_key_changed(VCONFKEY_POPSYNC_ACTIVATED_KEY, PeripheralValueCallback, (void *)this); + } + break; + case WATCH_TYPE_LOCALE: + if ((m_EventMgrPtr->getEventLocaleList()).size() == 1) { + if (runtime_info_set_changed_cb(RUNTIME_INFO_KEY_REGION, localeChangedCallback, (void *)this) != RUNTIME_INFO_ERROR_NONE) { + LoggerE("regist failed"); + Throw(WrtDeviceApis::Commons::Exception); + } + if (runtime_info_set_changed_cb(RUNTIME_INFO_KEY_LANGUAGE, localeChangedCallback, (void *)this) != RUNTIME_INFO_ERROR_NONE) { + LoggerE("regist failed"); + Throw(WrtDeviceApis::Commons::Exception); + } + } + break; + } + return false; +} + +void Systeminfo::get(const EventGetSysteminfoPtr& event) +{ + EventRequestReceiver<EventGetSysteminfo>::PostRequest(event); +} + +void Systeminfo::watch(const EventWatchSysteminfoPtr& event) +{ + int watchType = event->getWatchType(); + LoggerD("watch Type : " << watchType); + + if(watchType == WATCH_TYPE_UNKNOWN) { + LoggerD("watch method is not supported"); + event->setId(-1); + return; + } + + event->setSysteminfoPtr(this); + m_EventMgrPtr->addEvent(event, watchType); + registCallback(watchType); + + EventRequestReceiver<EventWatchSysteminfo>::PostRequest(event); +} + +void Systeminfo::clearWatch(const unsigned long id) +{ + if (id < 1) { + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + } else { + int watchType = m_EventMgrPtr->getWatchType(id); + switch(watchType) { + case WATCH_TYPE_BATTERY: + if ((m_EventMgrPtr->getEventBatteryList()).size() == 1) { + vconf_ignore_key_changed(VCONFKEY_SYSMAN_BATTERY_CAPACITY, BatteryValueCallback); + vconf_ignore_key_changed(VCONFKEY_SYSMAN_BATTERY_CHARGE_NOW, BatteryValueCallback); + } + break; + case WATCH_TYPE_DISPLAY: + if ((m_EventMgrPtr->getEventDisplayList()).size() == 1) { + vconf_ignore_key_changed(VCONFKEY_PM_CURRENT_BRIGHTNESS, DisplayValueCallback); + } + break; + case WATCH_TYPE_STORAGE: + if ((m_EventMgrPtr->getEventStorageList()).size() == 1) { + vconf_ignore_key_changed(VCONFKEY_SYSMAN_MMC_STATUS, StorageValueVconfCallback); + if (m_storageTimer) { + ecore_timer_freeze(m_storageTimer); + ecore_timer_del(m_storageTimer); + m_storageTimer = NULL; + } + } + break; + case WATCH_TYPE_CPU: + if ((m_EventMgrPtr->getEventCpuList()).size() == 1) { + if (m_cpuTimer) { + ecore_timer_freeze(m_cpuTimer); + ecore_timer_del(m_cpuTimer); + m_cpuTimer = NULL; + } + } + break; + case WATCH_TYPE_DEVICE_ORIENTATION: + if ((m_EventMgrPtr->getEventDeviceOrientationList()).size() == 1) { + vconf_ignore_key_changed(VCONFKEY_SETAPPL_AUTO_ROTATE_SCREEN_BOOL, OrientationValueVconfCallback); + } + break; + case WATCH_TYPE_PERIPHERAL: + if ((m_EventMgrPtr->getEventPeripheralList()).size() == 1) { + vconf_ignore_key_changed(VCONFKEY_MIRACAST_WFD_SOURCE_STATUS, PeripheralValueCallback); + vconf_ignore_key_changed(VCONFKEY_SYSMAN_HDMI, PeripheralValueCallback); + vconf_ignore_key_changed(VCONFKEY_POPSYNC_ACTIVATED_KEY, PeripheralValueCallback); + } + break; + case WATCH_TYPE_LOCALE: + if ((m_EventMgrPtr->getEventLocaleList()).size() == 1) { + if (runtime_info_unset_changed_cb(RUNTIME_INFO_KEY_LANGUAGE) != RUNTIME_INFO_ERROR_NONE) { + LoggerE("regist failed"); + Throw(WrtDeviceApis::Commons::Exception); + } + if (runtime_info_unset_changed_cb(RUNTIME_INFO_KEY_REGION) != RUNTIME_INFO_ERROR_NONE) { + LoggerE("regist failed"); + Throw(WrtDeviceApis::Commons::Exception); + } + } + break; + case WATCH_TYPE_UNKNOWN: + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + break; + } + m_EventMgrPtr->removeEvent(id, watchType); + } +} + +BasePropertyPtr Systeminfo::getBasePropertyPtr(JSContextRef context, JSValueRef property) +{ + Converter converter(context); + std::string l_property = converter.toString(property); + mapProperties::iterator it = (*m_Property).find(l_property); + if (it == (*m_Property).end()) { + LoggerE("not existing property"); + if (!strcmp(l_property.c_str(), "NETWORK") || !strcmp(l_property.c_str(), "WIFI_NETWORK") + || !strcmp(l_property.c_str(), "CELLULAR_NETWORK") || !strcmp(l_property.c_str(), "SIM")) { + Throw(WrtDeviceApis::Commons::PlatformException); + } else { + Throw(WrtDeviceApis::Commons::ConversionException); + } + + return BasePropertyPtr(NULL); + } + + return it->second; +} + +void Systeminfo::getWatchValue(const int watchType) +{ + LoggerD(" watch type : " << watchType); + + if (watchType == WATCH_TYPE_BATTERY) { + EventBatteryList eventList = m_EventMgrPtr->getEventBatteryList(); + for (EventBatteryList::iterator it = eventList.begin(); it != eventList.end(); it++) { + (*it)->getWatchValue(); + } + } else if (watchType == WATCH_TYPE_DISPLAY) { + EventDisplayList eventList = m_EventMgrPtr->getEventDisplayList(); + for (EventDisplayList::iterator it = eventList.begin(); it != eventList.end(); it++) { + (*it)->getWatchValue(); + } + } else if (watchType == WATCH_TYPE_CPU) { + EventCpuList eventList = m_EventMgrPtr->getEventCpuList(); + for (EventCpuList::iterator it = eventList.begin(); it != eventList.end(); it++) { + (*it)->getWatchValue(); + } + } else if (watchType == WATCH_TYPE_STORAGE) { + EventStorageList eventList = m_EventMgrPtr->getEventStorageList(); + for (EventStorageList::iterator it = eventList.begin(); it != eventList.end(); it++) { + int storageCnt = 1; + int sdcardState = 0; + if(vconf_get_int(VCONFKEY_SYSMAN_MMC_STATUS, &sdcardState) == 0) { + if(sdcardState == VCONFKEY_SYSMAN_MMC_MOUNTED) { + LoggerD("mmc is mounted"); + storageCnt++; + } else { + LoggerD("mmc is unmounted"); + } + } + LoggerD("storage cnt : " << storageCnt); + (*it)->getWatchValue(storageCnt); + } + }else if (watchType == WATCH_TYPE_DEVICE_ORIENTATION) { + EventDeviceOrientationList eventList = m_EventMgrPtr->getEventDeviceOrientationList(); + for (EventDeviceOrientationList::iterator it = eventList.begin(); it != eventList.end(); it++) { + (*it)->getWatchValue(); + } + } else if (watchType == WATCH_TYPE_PERIPHERAL) { + EventPeripheralList eventList = m_EventMgrPtr->getEventPeripheralList(); + for (EventPeripheralList::iterator it = eventList.begin(); it != eventList.end(); it++) { + (*it)->getWatchValue(); + } + } else if (watchType == WATCH_TYPE_LOCALE) { + EventLocaleList eventList = m_EventMgrPtr->getEventLocaleList(); + for (EventLocaleList::iterator it = eventList.begin(); it != eventList.end(); it++) { + (*it)->getWatchValue(); + } + } +} + +JSValueRef Systeminfo::getCpuValue(JSContextRef context) +{ + LoggerD("enter"); + Converter converter(context); + + CpuPropertiesPtr cpuPtr(new CpuProperties()); + FILE *fp = NULL; + long long usr = 0, nice = 0, system = 0, idle = 0, cpuUsage = 0, diffIdle = 0, total = 0; + + fp = fopen("/proc/stat", "r"); + if(fp == NULL) { + return JSValueMakeNull(context); + } + + if (fscanf(fp, "%*s %lld %lld %lld %lld", &usr, &system, &nice, &idle) > 0) { + total = usr + nice + system + idle - m_cpuInfo.usr - m_cpuInfo.nice - m_cpuInfo.system - m_cpuInfo.idle; + diffIdle = idle-m_cpuInfo.idle; + if ((total > 0LL) && (diffIdle > 0LL)) { + cpuUsage = diffIdle * 100LL / total; + cpuPtr->load = (double)cpuUsage / 100.0; + m_cpuInfo.usr = usr; + m_cpuInfo.system = system; + m_cpuInfo.nice = nice; + m_cpuInfo.idle = idle; + LoggerD("cpu load : " << cpuPtr->load); + } + } + + fclose(fp); + return JSCpuInfo::createJSObject(context, cpuPtr); +} + +void Systeminfo::OnRequestReceived(const EventGetSysteminfoPtr& event) +{ + event->processGetValue(); +} + +void Systeminfo::OnRequestReceived(const EventWatchSysteminfoPtr& event) +{ + WatchOption watchOption = event->getWatchOption(); + + event->switchToManualAnswer(); + event->setCancelAllowed(true); + event->processGetValue(); + event->setTimer(); +} + +//////////////////////////////////////////////////////////////////////////////////////// + +Systeminfo::EventMgr::EventMgr() +{ +} + +Systeminfo::EventMgr::~EventMgr() +{ +} + +void Systeminfo::EventMgr::clearAllEvent() +{ + DPL::Mutex::ScopedLock lock(&m_synchro); + + while (!m_eventBatteryList.empty()) { + EventWatchSysteminfoPtr event = m_eventBatteryList.front(); + LoggerD("removing EventId=" << event->getId()); + event->clearWatch(); + m_eventBatteryList.pop_front(); + } + while (!m_eventDisplayList.empty()) { + EventWatchSysteminfoPtr event = m_eventDisplayList.front(); + LoggerD("removing EventId=" << event->getId()); + event->clearWatch(); + m_eventDisplayList.pop_front(); + } + while (!m_eventStorageList.empty()) { + EventWatchSysteminfoPtr event = m_eventStorageList.front(); + LoggerD("removing EventId=" << event->getId()); + event->clearWatch(); + m_eventStorageList.pop_front(); + } + while (!m_eventCpuList.empty()) { + EventWatchSysteminfoPtr event = m_eventCpuList.front(); + LoggerD("removing EventId=" << event->getId()); + event->clearWatch(); + m_eventCpuList.pop_front(); + } + while (!m_eventDeviceOrientationList.empty()) { + EventWatchSysteminfoPtr event = m_eventDeviceOrientationList.front(); + LoggerD("removing EventId=" << event->getId()); + event->clearWatch(); + m_eventDeviceOrientationList.pop_front(); + } + while (!m_eventPeripheralList.empty()) { + EventWatchSysteminfoPtr event = m_eventPeripheralList.front(); + LoggerD("removing EventId=" << event->getId()); + event->clearWatch(); + m_eventPeripheralList.pop_front(); + } + while (!m_eventLocaleList.empty()) { + EventWatchSysteminfoPtr event = m_eventLocaleList.front(); + LoggerD("removing EventId=" << event->getId()); + event->clearWatch(); + m_eventLocaleList.pop_front(); + } +} + +void Systeminfo::EventMgr::addEvent(const EventWatchSysteminfoPtr& arg, const int watchType) +{ + DPL::Mutex::ScopedLock lock(&m_synchro); + + if (watchType == WATCH_TYPE_BATTERY){ + m_eventBatteryList.push_back(arg); + LoggerD("Event Battery list size=" << m_eventBatteryList.size()); + } else if (watchType == WATCH_TYPE_DISPLAY) { + m_eventDisplayList.push_back(arg); + LoggerD("Event display list size=" << m_eventDisplayList.size()); + } else if (watchType == WATCH_TYPE_STORAGE) { + m_eventStorageList.push_back(arg); + LoggerD("Event storage list size=" << m_eventStorageList.size()); + } else if (watchType == WATCH_TYPE_CPU) { + m_eventCpuList.push_back(arg); + LoggerD("Event cpu list size=" << m_eventCpuList.size()); + } else if (watchType == WATCH_TYPE_DEVICE_ORIENTATION) { + m_eventDeviceOrientationList.push_back(arg); + LoggerD("Event device orientation list size=" << m_eventDeviceOrientationList.size()); + } else if (watchType == WATCH_TYPE_PERIPHERAL) { + m_eventPeripheralList.push_back(arg); + LoggerD("Event peripheral list size=" << m_eventPeripheralList.size()); + } else if (watchType == WATCH_TYPE_LOCALE) { + m_eventLocaleList.push_back(arg); + LoggerD("Event Locale list size=" << m_eventLocaleList.size()); + } +} + +void Systeminfo::EventMgr::removeEvent(unsigned long id, const int watchType) +{ + DPL::Mutex::ScopedLock lock(&m_synchro); + LoggerD("Event id : " << id); + + EventWatchSysteminfoPtr event(NULL); + + LoggerD("trying to delete event, id=" << id); + + if (watchType == WATCH_TYPE_BATTERY) { + for (EventBatteryList::iterator it = m_eventBatteryList.begin(); it != m_eventBatteryList.end(); it++) { + if (id == (*it)->getId()) { + event = *it; + break; + } + } + if (!event) { + LoggerE("event id not in the list, nothing to do"); + return; + } + + LoggerD("event Battery list size=" << m_eventBatteryList.size()); + m_eventBatteryList.remove(event); + LoggerD( "event removed, event Battery list size=" << m_eventBatteryList.size()); + } else if (watchType == WATCH_TYPE_DISPLAY) { + for (EventDisplayList::iterator it = m_eventDisplayList.begin(); it != m_eventDisplayList.end(); it++) { + if (id == (*it)->getId()) { + event = *it; + break; + } + } + if (!event) { + LoggerE("event id not in the list, nothing to do"); + return; + } + + LoggerD("event display list size=" << m_eventDisplayList.size()); + m_eventDisplayList.remove(event); + LoggerD( "event removed, event display list size=" << m_eventDisplayList.size()); + } else if (watchType == WATCH_TYPE_STORAGE) { + for (EventStorageList::iterator it = m_eventStorageList.begin(); it != m_eventStorageList.end(); it++) { + if (id == (*it)->getId()) { + event = *it; + break; + } + } + if (!event) { + LoggerE("event id not in the list, nothing to do"); + return; + } + + LoggerD("event storage list size=" << m_eventStorageList.size()); + m_eventStorageList.remove(event); + LoggerD( "event removed, event storage list size=" << m_eventStorageList.size()); + } else if (watchType == WATCH_TYPE_CPU) { + for (EventCpuList::iterator it = m_eventCpuList.begin(); it != m_eventCpuList.end(); it++) { + if (id == (*it)->getId()) { + event = *it; + break; + } + } + if (!event) { + LoggerE("event id not in the list, nothing to do"); + return; + } + + LoggerD("event cpu list size=" << m_eventCpuList.size()); + m_eventCpuList.remove(event); + LoggerD( "event removed, event cpu list size=" << m_eventCpuList.size()); + } else if (watchType == WATCH_TYPE_DEVICE_ORIENTATION) { + for (EventDeviceOrientationList::iterator it = m_eventDeviceOrientationList.begin(); it != m_eventDeviceOrientationList.end(); it++) { + if (id == (*it)->getId()) { + event = *it; + break; + } + } + if (!event) { + LoggerE("event id not in the list, nothing to do"); + return; + } + + LoggerD("event device orientation list size=" << m_eventDeviceOrientationList.size()); + m_eventDeviceOrientationList.remove(event); + LoggerD( "event removed, event device orientation list size=" << m_eventDeviceOrientationList.size()); + } else if (watchType == WATCH_TYPE_PERIPHERAL) { + for (EventPeripheralList::iterator it = m_eventPeripheralList.begin(); it != m_eventPeripheralList.end(); it++) { + if (id == (*it)->getId()) { + event = *it; + break; + } + } + if (!event) { + LoggerE("event id not in the list, nothing to do"); + return; + } + + LoggerD("event peripheral list size=" << m_eventPeripheralList.size()); + m_eventPeripheralList.remove(event); + LoggerD( "event removed, event peripheral list size=" << m_eventPeripheralList.size()); + } else if (watchType == WATCH_TYPE_LOCALE) { + for (EventLocaleList::iterator it = m_eventLocaleList.begin(); it != m_eventLocaleList.end(); it++) { + if (id == (*it)->getId()) { + event = *it; + break; + } + } + if (!event) { + LoggerE("event id not in the list, nothing to do"); + return; + } + + LoggerD("event Locale list size=" << m_eventLocaleList.size()); + m_eventLocaleList.remove(event); + LoggerD( "event removed, event Locale list size=" << m_eventLocaleList.size()); + } +} + +const int Systeminfo::EventMgr::getWatchType(const unsigned long id) +{ + DPL::Mutex::ScopedLock lock(&m_synchro); + + EventWatchSysteminfoPtr event(NULL); + + for (EventBatteryList::iterator it = m_eventBatteryList.begin(); it != m_eventBatteryList.end(); it++) { + if (id == (*it)->getId()) { + event = *it; + break; + } + } + + for (EventDisplayList::iterator it = m_eventDisplayList.begin(); it != m_eventDisplayList.end(); it++) { + if (id == (*it)->getId()) { + event = *it; + break; + } + } + + for (EventStorageList::iterator it = m_eventStorageList.begin(); it != m_eventStorageList.end(); it++) { + if (id == (*it)->getId()) { + event = *it; + break; + } + } + + for (EventCpuList::iterator it = m_eventCpuList.begin(); it != m_eventCpuList.end(); it++) { + if (id == (*it)->getId()) { + event = *it; + break; + } + } + + for (EventDeviceOrientationList::iterator it = m_eventDeviceOrientationList.begin(); it != m_eventDeviceOrientationList.end(); it++) { + if (id == (*it)->getId()) { + event = *it; + break; + } + } + + for (EventPeripheralList::iterator it = m_eventPeripheralList.begin(); it != m_eventPeripheralList.end(); it++) { + if (id == (*it)->getId()) { + event = *it; + break; + } + } + + for (EventLocaleList::iterator it = m_eventLocaleList.begin(); it != m_eventLocaleList.end(); it++) { + if (id == (*it)->getId()) { + event = *it; + break; + } + } + + if (!event) { + LoggerE("event id not in the list, nothing to do"); + return WATCH_TYPE_UNKNOWN; + } + + return event->getWatchType(); +} + +EventBatteryList Systeminfo::EventMgr::getEventBatteryList() +{ + return m_eventBatteryList; +} + +EventDisplayList Systeminfo::EventMgr::getEventDisplayList() +{ + return m_eventDisplayList; +} + +EventStorageList Systeminfo::EventMgr::getEventStorageList() +{ + return m_eventStorageList; +} + +EventCpuList Systeminfo::EventMgr::getEventCpuList() +{ + return m_eventCpuList; +} + +EventDeviceOrientationList Systeminfo::EventMgr::getEventDeviceOrientationList() +{ + return m_eventDeviceOrientationList; +} + +EventPeripheralList Systeminfo::EventMgr::getEventPeripheralList() +{ + return m_eventPeripheralList; +} + +EventLocaleList Systeminfo::EventMgr::getEventLocaleList() +{ + return m_eventLocaleList; +} + +//////////////////////////////////////////////////////////////////////////////////////// + +PROPERTY_GET_SYSTEMINFO_DEFINITION(Battery) { + LoggerD("test"); + BatteryPropertiesPtr BatteryPtr(new BatteryProperties()); + int value=0; + int value2=0; + + if (vconf_get_int(VCONFKEY_SYSMAN_BATTERY_CAPACITY, &value) != 0) { + return JSValueMakeNull(context); + } else { + BatteryPtr->level = (double)(value)/CPU_POWER_DEVICE_VALUE; + } + + if (vconf_get_int(VCONFKEY_SYSMAN_BATTERY_CHARGE_NOW, &value2) != 0) { + return JSValueMakeNull(context); + } else { + BatteryPtr->isCharging = (value2 == 0) ? false : true; + } + + return JSBatteryInfo::createJSObject(context, BatteryPtr); +} + +PROPERTY_GET_SYSTEMINFO_DEFINITION(Cpu) { + LoggerD("test"); + Converter converter(context); + + CpuPropertiesPtr cpuPtr(new CpuProperties()); + FILE *fp = NULL; + long long usr = 0, nice = 0, system = 0, idle = 0, total = 0, cpuUsage = 0; + + fp = fopen("/proc/stat", "r"); + if(fp == NULL) { + return JSValueMakeNull(context); + } + + if (fscanf(fp, "%*s %lld %lld %lld %lld", &usr, &system, &nice, &idle) > 0) { + total = usr + nice + system + idle; + if ((total > 0LL) && (idle > 0LL)) { + cpuUsage = idle * 100LL / total; + cpuPtr->load = (double)cpuUsage / 100.0; + LoggerD("cpu load : " << cpuPtr->load); + } + } + + fclose(fp); + return JSCpuInfo::createJSObject(context, cpuPtr); +} + +PROPERTY_GET_SYSTEMINFO_DEFINITION(Storage) { + Converter converter(context); + int sdcardState=0; + struct statfs fs; + + if (statfs(STORAGE_INTERNAL_PATH, &fs) < 0) { + return JSValueMakeNull(context); + } + StoragePropertiesPtr storagePtr(new StorageProperties()); + storagePtr->units[0].type = "INTERNAL"; + storagePtr->units[0].capacity = (unsigned long long)fs.f_bsize * (unsigned long long)fs.f_blocks; + storagePtr->units[0].availableCapacity = (unsigned long long)fs.f_bsize * (unsigned long long)fs.f_bavail; + storagePtr->units[0].isRemoveable = false; + storagePtr->units[0].isRemovable = false; + storagePtr->cnt = 1; + LoggerD("type : " << storagePtr->units[0].type); + if(vconf_get_int(VCONFKEY_SYSMAN_MMC_STATUS, &sdcardState) == 0) { + if(sdcardState == VCONFKEY_SYSMAN_MMC_MOUNTED){ + if (statfs(STORAGE_SDCARD_PATH, &fs) < 0) { + return JSValueMakeNull(context); + } + storagePtr->units[1].type = "MMC"; + storagePtr->units[1].capacity = (unsigned long long)fs.f_bsize * (unsigned long long)fs.f_blocks; + storagePtr->units[1].availableCapacity = (unsigned long long)fs.f_bsize * (unsigned long long)fs.f_bavail; + storagePtr->units[1].isRemoveable = true; + storagePtr->units[1].isRemovable = true; + storagePtr->cnt = 2; + LoggerD("type : " << storagePtr->units[1].type); + } + } + return JSStorageInfo::createJSObject(context, storagePtr); + +} + +PROPERTY_GET_SYSTEMINFO_DEFINITION(Display) { + Converter converter(context); + DisplayPropertiesPtr display(new DisplayProperties()); + int brightness=0, dotsPerInch=0, physicalW=0, physicalH=0; +// bool screenSizeCheck = false; + + if(vconf_get_int(VCONFKEY_PM_CURRENT_BRIGHTNESS, &brightness) == 0) { + display->brightness = (double)(brightness)/DISPLAY_BRIGHTNESS_DIVIDE_VALUE; + } + /* + char featureList[6][50] = {"tizen.org/feature/screen.size.normal.240.400", + "tizen.org/feature/screen.size.normal.320.320", + "tizen.org/feature/screen.size.normal.480.800", + "tizen.org/feature/screen.size.normal.540.960", + "tizen.org/feature/screen.size.normal.600.1024", + "tizen.org/feature/screen.size.normal.720.1280"}; + + int startIndex = strlen("tizen.org/feature/screen.size.normal."); + + for (int index = 0; index < 6; index++) { + if (system_info_get_platform_bool(featureList[index], &screenSizeCheck) == SYSTEM_INFO_ERROR_NONE) { + if (screenSizeCheck) { + char *wString = &featureList[index][startIndex]; + char *hString = strchr(wString, '.'); + + display->resolutionWidth = atoi(wString); + display->resolutionHeight = atoi(&hString[1]); + break; + } + } + } + */ + if(system_info_get_platform_int("tizen.org/feature/screen.dpi", &dotsPerInch) == SYSTEM_INFO_ERROR_NONE) { + display->dotsPerInchWidth = dotsPerInch; + display->dotsPerInchHeight = dotsPerInch; + } + + if(system_info_get_platform_int("tizen.org/feature/screen.width", &physicalW) == SYSTEM_INFO_ERROR_NONE) { + display->physicalWidth = physicalW; + display->resolutionWidth = physicalW; + } + + if(system_info_get_platform_int("tizen.org/feature/screen.height", &physicalH) == SYSTEM_INFO_ERROR_NONE) { + display->physicalHeight = physicalH; + display->resolutionHeight = physicalH; + } + + return JSDisplayInfo::createJSObject(context, display); +} + +PROPERTY_GET_SYSTEMINFO_DEFINITION(DeviceOrientation) { + LoggerD("enter"); + Converter converter(context); + DeviceOrientationPropertiesPtr deviceOrientation(new DeviceOrientationProperties()); + + unsigned long rotation = 0; +// int handleOrientaion = 0; + int isAutoRotation = 0; + + if (vconf_get_bool(VCONFKEY_SETAPPL_AUTO_ROTATE_SCREEN_BOOL, &isAutoRotation) == 0) { + if (isAutoRotation) { + deviceOrientation->isAutoRotation = true; + } else { + deviceOrientation->isAutoRotation = false; + } + } +/* + handleOrientaion = sf_connect(ACCELEROMETER_SENSOR); + LoggerD("handleOrientaion : " << handleOrientaion); + if (handleOrientaion < 0) { + LoggerD ("sensor attach fail"); + return JSDeviceOrientationInfo::createJSObject(context, deviceOrientation); + } + int state = sf_start(handleOrientaion, 0); + if(state < 0) { + LoggerD("start failed"); + } + + int ret_val = sf_check_rotation(&rotation); + if (ret_val < 0) { + LoggerD("sf_check_rotation fail to gather data\n"); + } + + LoggerD(" rotation value = " << rotation); +*/ + + int ret_val = sf_check_rotation(&rotation); + if(ret_val < 0) + LoggerE("error"); + + switch (rotation) { + case 0: + case ROTATION_EVENT_0: + LoggerD("my_callback_func received data (PORTRAIT_TOP|HEAD_CENTER)\n"); + deviceOrientation->status = "PORTRAIT_PRIMARY"; + break; + case ROTATION_EVENT_90: + LoggerD("my_callback_func received data (LANDSCAPE|HEAD_RIGHT)\n"); + deviceOrientation->status = "LANDSCAPE_PRIMARY"; + break; + case ROTATION_EVENT_180: + LoggerD("my_callback_func received data (PORTRAIT_BTM|HEAD_CENTER)\n"); + deviceOrientation->status = "PORTRAIT_SECONDARY"; + break; + case ROTATION_EVENT_270: + LoggerD("my_callback_func received data (LANDSCAPE|HEAD_LEFT)\n"); + deviceOrientation->status = "LANDSCAPE_SECONDARY"; + break; + default: + LoggerD(" received data unexpected\n"); + break; + } +/* + state = sf_stop(handleOrientaion); + LoggerD("handleOrientaion 1 state = " << state); + + state = sf_disconnect(handleOrientaion); + LoggerD("handleOrientaion state =" << state); +*/ + return JSDeviceOrientationInfo::createJSObject(context, deviceOrientation); +} + +PROPERTY_GET_SYSTEMINFO_DEFINITION(Build) { + LoggerD("enter"); + Converter converter(context); + BuildPropertiesPtr Build(new BuildProperties()); + + char* model = NULL; + char* manufacturer = NULL; + char* buildVersion = NULL; + + if(system_info_get_platform_string("tizen.org/system/model_name", &model) == SYSTEM_INFO_ERROR_NONE) { + if (model != NULL) { + LoggerD("model : " << model); + Build->model = model; + free(model); + } + } + + if (system_info_get_value_string(SYSTEM_INFO_KEY_MANUFACTURER, &manufacturer) == SYSTEM_INFO_ERROR_NONE) { + if (manufacturer != NULL) { + LoggerD("manufacturer : " << manufacturer); + Build->manufacturer = manufacturer; + free(manufacturer); + } + } + + if (system_info_get_value_string(SYSTEM_INFO_KEY_BUILD_STRING, &buildVersion) == SYSTEM_INFO_ERROR_NONE) { + if (buildVersion != NULL) { + LoggerD("buildVersion : " << buildVersion); + Build->buildVersion = buildVersion; + free(buildVersion); + } + } + + return JSBuildInfo::createJSObject(context, Build); +} + +PROPERTY_GET_SYSTEMINFO_DEFINITION(Peripheral) { + Converter converter(context); + PeripheralPropertiesPtr peripheral(new PeripheralProperties()); + int hdmiStatus = 0, wirelessDisplayStatus = 0, popSyncStatus=0 ; + peripheral->isVideoOutputOn = false; + + if (vconf_get_int(VCONFKEY_MIRACAST_WFD_SOURCE_STATUS, &wirelessDisplayStatus) == 0) { + switch(wirelessDisplayStatus) { + case VCONFKEY_MIRACAST_WFD_SOURCE_ON: + peripheral->isVideoOutputOn = true; + break; + default: + LoggerD("VideOutput status is off"); + break; + } + } + + if (vconf_get_int(VCONFKEY_SYSMAN_HDMI, &hdmiStatus) == 0) { + switch(hdmiStatus) { + case VCONFKEY_SYSMAN_HDMI_CONNECTED: + peripheral->isVideoOutputOn = true; + break; + default: + LoggerD("VideOutput status is off"); + break; + } + } + + if (vconf_get_int(VCONFKEY_POPSYNC_ACTIVATED_KEY, &popSyncStatus) == 0) { + switch(popSyncStatus) { + case 1: + peripheral->isVideoOutputOn = true; + break; + default: + LoggerD("VideOutput status is off"); + break; + } + } + + return JSPeripheralInfo::createJSObject(context, peripheral); +} + +PROPERTY_GET_SYSTEMINFO_DEFINITION(Locale) { + LoggerD("enter"); + Converter converter(context); + LocalePropertiesPtr Locale(new LocaleProperties()); + + char* country = NULL; + char* language = NULL; + + if (runtime_info_get_value_string(RUNTIME_INFO_KEY_LANGUAGE, &language) == RUNTIME_INFO_ERROR_NONE) { + if (language != NULL) { + LoggerD("language : " << language); + Locale->language = language; + free(language); + } + } + + if (runtime_info_get_value_string(RUNTIME_INFO_KEY_REGION, &country) == RUNTIME_INFO_ERROR_NONE) { + if (country != NULL) { + LoggerD("country : " << country); + char* token = NULL; + char* countryTemp = NULL; + token = strtok(country, "."); + if (token != NULL) { + countryTemp = strdup(token); + if (countryTemp != NULL) { + Locale->country = countryTemp; + free(countryTemp); + } + } + free(country); + } + } + + return JSLocaleInfo::createJSObject(context, Locale); +} + +} +} diff --git a/wearable_src/Systeminfo/Systeminfo.h b/wearable_src/Systeminfo/Systeminfo.h new file mode 100755 index 0000000..dd622da --- /dev/null +++ b/wearable_src/Systeminfo/Systeminfo.h @@ -0,0 +1,194 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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_PLATFORM_SYSTEMINFO_H_ +#define WRTPLUGINS_PLATFORM_SYSTEMINFO_H_ + +#include <map> +#include <vector> +#include <string> +#include <sys/vfs.h> +#include <vconf.h> +#include <sensor.h> +#include <system_info.h> +#include <runtime_info.h> +#include <JavaScriptCore/JavaScript.h> +#include <dpl/shared_ptr.h> +#include <dpl/noncopyable.h> +#include "ISysteminfo.h" +#include "SysteminfoFactory.h" +#include "EventGetSysteminfo.h" +#include "EventWatchSysteminfo.h" +#include "BaseProperties.h" +#include <Commons/Emitters.h> +#include <CommonsJavaScript/Converter.h> + +namespace DeviceAPI { +namespace Systeminfo { + +enum { + WATCH_TYPE_UNKNOWN = 0, + WATCH_TYPE_BATTERY = 1, + WATCH_TYPE_DISPLAY = 2, + WATCH_TYPE_STORAGE = 3, + WATCH_TYPE_CPU = 4, + WATCH_TYPE_DEVICE_ORIENTATION = 5, + WATCH_TYPE_PERIPHERAL = 6, + WATCH_TYPE_LOCALE = 7 +}; + +struct cpuInfo { + unsigned long long usr; + unsigned long long nice; + unsigned long long system; + unsigned long long idle; + unsigned long long usage; + cpuInfo() : usr(0), nice(0), system(0), idle(0), usage(0) + { + } +}; + +typedef DPL::Atomic::ValueType WatchId; + +#define PROPERTY_DECLARATION(className, propertyName, watchType) \ + class className : public BaseProperty { \ + public: \ + explicit className() : BaseProperty() { \ + } \ + JSValueRef getValue(JSContextRef context) const; \ + const char* getProperty() const \ + { \ + return propertyName; \ + } \ + const int getWatchType() const \ + { \ + return watchType; \ + } \ + }; + +#define PROPERTY_GET_SYSTEMINFO_DEFINITION(className) JSValueRef className::getValue( \ + JSContextRef context) const + +PROPERTY_DECLARATION(Battery, "BATTERY", WATCH_TYPE_BATTERY) +PROPERTY_DECLARATION(Cpu, "CPU", WATCH_TYPE_CPU) +PROPERTY_DECLARATION(Storage, "STORAGE", WATCH_TYPE_STORAGE) +PROPERTY_DECLARATION(Display, "DISPLAY", WATCH_TYPE_DISPLAY) +PROPERTY_DECLARATION(DeviceOrientation, "DEVICE_ORIENTATION", WATCH_TYPE_DEVICE_ORIENTATION) +PROPERTY_DECLARATION(Peripheral, "PERIPHERAL", WATCH_TYPE_PERIPHERAL) +PROPERTY_DECLARATION(Build, "BUILD", WATCH_TYPE_UNKNOWN) +PROPERTY_DECLARATION(Locale, "LOCALE", WATCH_TYPE_LOCALE) + +typedef std::list<EventWatchSysteminfoPtr> EventBatteryList; +typedef std::list<EventWatchSysteminfoPtr> EventDisplayList; +typedef std::list<EventWatchSysteminfoPtr> EventStorageList; +typedef std::list<EventWatchSysteminfoPtr> EventCpuList; +typedef std::list<EventWatchSysteminfoPtr> EventDeviceOrientationList; +typedef std::list<EventWatchSysteminfoPtr> EventPeripheralList; +typedef std::list<EventWatchSysteminfoPtr> EventLocaleList; + +class Systeminfo : public ISysteminfo +{ + friend class SysteminfoFactory; + friend class EventWatchSysteminfo;; + + public: + + virtual ~Systeminfo(); + virtual DeviceCapabilitiesPropertiesPtr getCapabilities(); + virtual void get(const EventGetSysteminfoPtr& event); + virtual void watch(const EventWatchSysteminfoPtr& event); + virtual BasePropertyPtr getBasePropertyPtr(JSContextRef context, JSValueRef property); + virtual void clearWatch(const unsigned long id); + void getWatchValue(const int watchType); + bool registCallback(const int watchType); + JSValueRef getCpuValue(JSContextRef context); + + class EventMgr + { + public: + EventMgr(); + ~EventMgr(); + + void clearAllEvent(); + void addEvent(const EventWatchSysteminfoPtr& arg, const int watchType); + void removeEvent(unsigned long id, const int watchType); + const int getWatchType(const unsigned long id); + EventBatteryList getEventBatteryList(); + EventDisplayList getEventDisplayList(); + EventStorageList getEventStorageList(); + EventCpuList getEventCpuList(); + EventDeviceOrientationList getEventDeviceOrientationList(); + EventPeripheralList getEventPeripheralList(); + EventLocaleList getEventLocaleList(); + + private: + EventBatteryList m_eventBatteryList; + EventDisplayList m_eventDisplayList; + EventStorageList m_eventStorageList; + EventCpuList m_eventCpuList; + EventDeviceOrientationList m_eventDeviceOrientationList; + EventPeripheralList m_eventPeripheralList; + EventLocaleList m_eventLocaleList; + + DPL::Mutex m_synchro; + }; + typedef DPL::SharedPtr<EventMgr> EventMgrPtr; + + protected: + Systeminfo(); + virtual void OnRequestReceived(const EventGetSysteminfoPtr& event); + virtual void OnRequestReceived(const EventWatchSysteminfoPtr& event); + + private: + typedef std::map<std::string, BasePropertyPtr > mapProperties; + typedef DPL::Optional<mapProperties> OptionalProperty; + + static OptionalProperty m_Property; + int m_networkRegist; + DPL::Mutex m_initializationMutex; + EventMgrPtr m_EventMgrPtr; + Ecore_Timer *m_storageTimer; + Ecore_Timer *m_cpuTimer; + int m_sensorHandle; + cpuInfo m_cpuInfo; +}; + +class SysteminfoAsyncPendingEvent +{ + public: + SysteminfoAsyncPendingEvent(void *thisObject, const EventGetSysteminfoPtr &event) : + m_thisObject(thisObject), + m_event(event) + { + } + + virtual ~SysteminfoAsyncPendingEvent() + { + } + + void* getThisObject() const { return m_thisObject; } + EventGetSysteminfoPtr getEvent() const { return m_event; } + + private: + void *m_thisObject; + EventGetSysteminfoPtr m_event; +}; + +} +} + +#endif diff --git a/wearable_src/Systeminfo/SysteminfoAsyncCallbackManager.cpp b/wearable_src/Systeminfo/SysteminfoAsyncCallbackManager.cpp new file mode 100755 index 0000000..6fa6b26 --- /dev/null +++ b/wearable_src/Systeminfo/SysteminfoAsyncCallbackManager.cpp @@ -0,0 +1,26 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "SysteminfoAsyncCallbackManager.h" + +namespace DeviceAPI { +namespace Systeminfo { + +SINGLETON_IMPLEMENTATION(SysteminfoAsyncCallbackManager) + +} // Systeminfo +} // DeviceAPI diff --git a/wearable_src/Systeminfo/SysteminfoAsyncCallbackManager.h b/wearable_src/Systeminfo/SysteminfoAsyncCallbackManager.h new file mode 100755 index 0000000..2393cc7 --- /dev/null +++ b/wearable_src/Systeminfo/SysteminfoAsyncCallbackManager.h @@ -0,0 +1,46 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _TIZEN_SYSTEMINFO_ASYNC_CALLBACK_MANAGER_H_ +#define _TIZEN_SYSTEMINFO_ASYNC_CALLBACK_MANAGER_H_ + +#include <AsyncCallbackManager.h> + +namespace DeviceAPI { +namespace Systeminfo { + +class SysteminfoAsyncCallbackManager : public DeviceAPI::Common::AsyncCallbackManager +{ +private: + SysteminfoAsyncCallbackManager() + { + } + +public: + virtual ~SysteminfoAsyncCallbackManager() + { + } + + friend class SysteminfoAsyncCallbackManagerSingleton; +}; + +SINGLETON_DEFINITION(SysteminfoAsyncCallbackManager) + +} +} + +#endif diff --git a/wearable_src/Systeminfo/SysteminfoFactory.cpp b/wearable_src/Systeminfo/SysteminfoFactory.cpp new file mode 100755 index 0000000..e24374b --- /dev/null +++ b/wearable_src/Systeminfo/SysteminfoFactory.cpp @@ -0,0 +1,41 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "Systeminfo.h" +#include "SysteminfoFactory.h" + +namespace DeviceAPI { +namespace Systeminfo { + +ISysteminfoPtr SysteminfoFactory::getSysteminfos() +{ + static ISysteminfoPtr obj(new Systeminfo()); + return obj; +} + +SysteminfoFactory& SysteminfoFactory::getInstance() +{ + static SysteminfoFactory theInstance; + return theInstance; +} + +SysteminfoFactory::SysteminfoFactory() +{ +} + +} +} diff --git a/wearable_src/Systeminfo/SysteminfoFactory.h b/wearable_src/Systeminfo/SysteminfoFactory.h new file mode 100755 index 0000000..41b7066 --- /dev/null +++ b/wearable_src/Systeminfo/SysteminfoFactory.h @@ -0,0 +1,42 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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_API_SYSTMEINFOFACTORY_H_ +#define WRTPLUGINS_API_SYSTMEINFOFACTORY_H_ + +#include <dpl/noncopyable.h> +#include "ISysteminfo.h" + +namespace DeviceAPI { +namespace Systeminfo { + +class SysteminfoFactory : DPL::Noncopyable +{ + public: + ISysteminfoPtr getSysteminfos(); + + static SysteminfoFactory& getInstance(); + + protected: + SysteminfoFactory(); +}; + +} +} + +#endif + diff --git a/wearable_src/Systeminfo/SysteminfoListener.cpp b/wearable_src/Systeminfo/SysteminfoListener.cpp new file mode 100755 index 0000000..287d13f --- /dev/null +++ b/wearable_src/Systeminfo/SysteminfoListener.cpp @@ -0,0 +1,68 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <CommonsJavaScript/JSCallbackManager.h> +#include "SysteminfoListener.h" +#include <CommonsJavaScript/ScopedJSStringRef.h> +#include "SysteminfoAsyncCallbackManager.h" +#include <TimeTracer.h> +#include <Logger.h> + +using namespace std; + +namespace DeviceAPI { +namespace Systeminfo { + +SysteminfoListener& SysteminfoListener::getInstance() +{ + static SysteminfoListener instance; + return instance; +} + +SysteminfoListener::SysteminfoListener() : + EventGetSysteminfoAnswerReceiver(WrtDeviceApis::Commons::ThreadEnum::NULL_THREAD), + EventWatchSysteminfoAnswerReceiver(WrtDeviceApis::Commons::ThreadEnum::NULL_THREAD) +{ +} + +SysteminfoListener::~SysteminfoListener() +{ +} + +void SysteminfoListener::OnAnswerReceived(const EventGetSysteminfoPtr& event) +{ + LoggerD("Enter"); + WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr callbackManager = DPL::StaticPointerCast<WrtDeviceApis::CommonsJavaScript::JSCallbackManager >(event->getPrivateData()); + LoggerD("thread=" << DPL::Thread::GetCurrentThread()); + + SysteminfoAsyncCallbackManagerSingleton::Instance().unregisterCallbackManager(callbackManager); + + if (!event->checkCancelled()) { + JSValueRef tmpValue = event->getValue(); + if ((WrtDeviceApis::Commons::ExceptionCodes::None == event->getExceptionCode()) && (NULL != tmpValue)) { + callbackManager->callOnSuccess(tmpValue); + TIME_TRACER_ITEM_END(event->getProperty(), 0); + } + } +} + +void SysteminfoListener::OnAnswerReceived(const EventWatchSysteminfoPtr& event) +{ +} + +} +} diff --git a/wearable_src/Systeminfo/SysteminfoListener.h b/wearable_src/Systeminfo/SysteminfoListener.h new file mode 100755 index 0000000..fa85b3b --- /dev/null +++ b/wearable_src/Systeminfo/SysteminfoListener.h @@ -0,0 +1,51 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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_API_SYSTEMINFO_LISTENER_H_ +#define WRTPLUGINS_API_SYSTEMINFO_LISTENER_H_ + +#include <CommonsJavaScript/JSPendingOperation.h> +#include "ISysteminfo.h" + +namespace DeviceAPI { +namespace Systeminfo { + +typedef WrtDeviceApis::Commons::EventAnswerReceiver<EventGetSysteminfo> EventGetSysteminfoAnswerReceiver; +typedef WrtDeviceApis::Commons::EventAnswerReceiver<EventWatchSysteminfo> EventWatchSysteminfoAnswerReceiver; + +class SysteminfoListener : public EventGetSysteminfoAnswerReceiver, public EventWatchSysteminfoAnswerReceiver +{ + private: + explicit SysteminfoListener(); + + public: + static SysteminfoListener& getInstance(); + + virtual ~SysteminfoListener(); + + protected: + virtual void OnAnswerReceived(const EventGetSysteminfoPtr& event); + + virtual void OnAnswerReceived(const EventWatchSysteminfoPtr& event); +}; + +typedef DPL::SharedPtr<SysteminfoListener> SysteminfoListenerPtr; + +} +} + +#endif diff --git a/wearable_src/Systeminfo/SysteminfoListenerManager.cpp b/wearable_src/Systeminfo/SysteminfoListenerManager.cpp new file mode 100755 index 0000000..54cac75 --- /dev/null +++ b/wearable_src/Systeminfo/SysteminfoListenerManager.cpp @@ -0,0 +1,26 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 "SysteminfoListenerManager.h" + +namespace DeviceAPI { +namespace Systeminfo { + +SINGLETON_IMPLEMENTATION(SysteminfoListenerManager) + +} // Systeminfo +} // DeviceAPI diff --git a/wearable_src/Systeminfo/SysteminfoListenerManager.h b/wearable_src/Systeminfo/SysteminfoListenerManager.h new file mode 100755 index 0000000..8f7064b --- /dev/null +++ b/wearable_src/Systeminfo/SysteminfoListenerManager.h @@ -0,0 +1,100 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _TIZEN_SYSTEMINFO_LISTENER_MANAGER_H_ +#define _TIZEN_SYSTEMINFO_LISTENER_MANAGER_H_ + +#include <map> +#include <JavaScriptCore/JavaScript.h> +#include <dpl/shared_ptr.h> +#include <IListenerManager.h> +#include "JSSysteminfo.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Systeminfo { + +class SysteminfoListenerCanceller; +typedef DPL::SharedPtr<SysteminfoListenerCanceller> SysteminfoListenerCancellerPtr; + +class SysteminfoListenerManager : public DeviceAPI::Common::IListenerController +{ +private: + SysteminfoListenerManager() + { + } + +public: + virtual ~SysteminfoListenerManager() + { + } + + friend class SysteminfoListenerManagerSingleton; +}; +SINGLETON_DEFINITION(SysteminfoListenerManager) + +class SysteminfoListenerCanceller : public DeviceAPI::Common::IListenerItem +{ +public: + SysteminfoListenerCanceller(JSContextRef context, JSObjectRef object, unsigned long watchId) : + DeviceAPI::Common::IListenerItem(context, object, 0), + m_ulWatchId(watchId) + { + } + + virtual ~SysteminfoListenerCanceller() + { + } + + virtual void cancelListener() + { + JSSysteminfoPriv *priv = static_cast<JSSysteminfoPriv*>(JSObjectGetPrivate(m_object)); + + if (!priv) { + LoggerW("Object has no private object"); + return; + } + + try { + ISysteminfoPtr Systeminfos(priv->getObject()); + Systeminfos->clearWatch(m_ulWatchId); + } Catch(WrtDeviceApis::Commons::Exception) { + LoggerE("Error on platform : " << _rethrown_exception.GetMessage()); + } + } + + virtual bool equal(const DeviceAPI::Common::IListenerItemPtr &other) const + { + if(!other) + return false; + + SysteminfoListenerCancellerPtr other2 = DPL::DynamicPointerCast<SysteminfoListenerCanceller>(other); + + if(m_object == other2->m_object && m_ulWatchId == other2->m_ulWatchId) + return true; + + return false; + } + +private: + unsigned long m_ulWatchId; +}; + +} +} + +#endif diff --git a/wearable_src/Systeminfo/SysteminfoPropertyInfo.h b/wearable_src/Systeminfo/SysteminfoPropertyInfo.h new file mode 100755 index 0000000..955b0b0 --- /dev/null +++ b/wearable_src/Systeminfo/SysteminfoPropertyInfo.h @@ -0,0 +1,404 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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_API_PROPERTY_INFO_H_ +#define WRTPLUGINS_API_PROPERTY_INFO_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/PrivateObject.h> +#include <CommonsJavaScript/JSUtils.h> +#include <CommonsJavaScript/Converter.h> +#include <string> +#include <dpl/shared_ptr.h> + +namespace DeviceAPI { +namespace Systeminfo { + +enum SystemInfosDeviceOrientationStatus { + PORTRAIT_PRIMARY = 0, + PORTRAIT_SECONDARY = 1, + LANDSCAPE_PRIMARY = 2, + LANDSCAPE_SECONDARY = 3 +}; + +struct DeviceCapabilitiesProperties +{ + bool bluetooth; + bool nfc; + bool nfcReservedPush; + unsigned short multiTouchCount; + bool inputKeyboard; + bool inputKeyboardLayout; + bool wifi; + bool wifiDirect; + bool opengles; + std::string openglestextureFormat; + bool openglesVersion1_1; + bool openglesVersion2_0; + bool fmRadio; + std::string platformVersion; + std::string platformName; + std::string webApiVersion; + std::string nativeApiVersion; + bool camera; + bool cameraFront; + bool cameraFrontFlash; + bool cameraBack; + bool cameraBackFlash; + bool location; + bool locationGps; + bool locationWps; + bool microphone; + bool usbHost; + bool usbAccessory; + bool screenOutputRca; + bool screenOutputHdmi; + std::string platformCoreCpuArch; + std::string platformCoreFpuArch; + bool sipVoip; + std::string duid; + bool speechRecognition; + bool speechSynthesis; + bool accelerometer; + bool accelerometerWakeup; + bool barometer; + bool barometerWakeup; + bool gyroscope; + bool gyroscopeWakeup; + bool magnetometer; + bool magnetometerWakeup; + bool photometer; + bool photometerWakeup; + bool proximity; + bool proximityWakeup; + bool tiltmeter; + bool tiltmeterWakeup; + bool dataEncryption; + bool graphicsAcceleration; + bool push; + bool telephony; + bool telephonyMms; + bool telephonySms; + bool screenSizeNormal; + bool screenSize480_800; + bool screenSize720_1280; + bool autoRotation; + bool shellAppWidget; + bool visionImageRecognition; + bool visionQrcodeGeneration; + bool visionQrcodeRecognition; + bool visionFaceRecognition; + bool secureElement; + bool nativeOspCompatible; + std::string profile; + + DeviceCapabilitiesProperties() : + bluetooth(false), + nfc(false), + nfcReservedPush(false), + multiTouchCount(0), + inputKeyboard(false), + inputKeyboardLayout(false), + wifi(false), + wifiDirect(false), + opengles(false), + openglestextureFormat(""), + openglesVersion1_1(false), + openglesVersion2_0(false), + fmRadio(false), + platformVersion(""), + platformName(""), + webApiVersion(""), + nativeApiVersion(""), + camera(false), + cameraFront(false), + cameraFrontFlash(false), + cameraBack(false), + cameraBackFlash(false), + location(false), + locationGps(false), + locationWps(false), + microphone(false), + usbHost(false), + usbAccessory(false), + screenOutputRca(false), + screenOutputHdmi(false), + platformCoreCpuArch(""), + platformCoreFpuArch(""), + sipVoip(false), + duid(""), + speechRecognition(false), + speechSynthesis(false), + accelerometer(false), + accelerometerWakeup(false), + barometer(false), + barometerWakeup(false), + gyroscope(false), + gyroscopeWakeup(false), + magnetometer(false), + magnetometerWakeup(false), + photometer(false), + photometerWakeup(false), + proximity(false), + proximityWakeup(false), + tiltmeter(false), + tiltmeterWakeup(false), + dataEncryption(false), + graphicsAcceleration(false), + push(false), + telephony(false), + telephonyMms(false), + telephonySms(false), + screenSizeNormal(false), + screenSize480_800(false), + screenSize720_1280(false), + autoRotation(false), + shellAppWidget(false), + visionImageRecognition(false), + visionQrcodeGeneration(false), + visionQrcodeRecognition(false), + visionFaceRecognition(false), + secureElement(false), + nativeOspCompatible(false), + profile("") + { + } +}; + +struct BatteryProperties +{ + double level; + bool isCharging; + + BatteryProperties() : + level(0.0), + isCharging(false) + { + } +}; + +struct CpuProperties +{ + double load; + + CpuProperties() : + load(0.0) + { + } +}; + +struct StorageUnitProperties +{ + std::string type; + unsigned long long capacity; + unsigned long long availableCapacity; + bool isRemoveable; + bool isRemovable; + + StorageUnitProperties(): + type("UNKNOWN"), + capacity(0), + availableCapacity(0), + isRemoveable(false), + isRemovable(false) + { + } +}; + +struct StorageProperties +{ + StorageUnitProperties units[2]; + unsigned long cnt; + + StorageProperties(): + cnt(0) + { + } +}; + + +struct DisplayProperties +{ + unsigned long resolutionWidth; + unsigned long resolutionHeight; + unsigned long dotsPerInchWidth; + unsigned long dotsPerInchHeight; + double physicalWidth; + double physicalHeight; + double brightness; + + DisplayProperties() : + resolutionWidth(0), + resolutionHeight(0), + dotsPerInchWidth(0), + dotsPerInchHeight(0), + physicalWidth(0.0), + physicalHeight(0.0), + brightness(0.0) + { + } +}; + +struct WifiNetworkProperties +{ + std::string status; + std::string ssid; + std::string ipAddress; + std::string ipv6Address; + double signalStrength; + + WifiNetworkProperties() : + status(""), + ssid(""), + ipAddress(""), + ipv6Address(""), + signalStrength(0.0) + { + } +}; + +struct NetworkProperties +{ + std::string networkType; + + NetworkProperties() : + networkType("UNKNOWN") + { + } +}; + +struct CellularNetworkProperties +{ + std::string status; + std::string apn; + std::string ipAddress; + std::string ipv6Address; + unsigned short mcc; + unsigned short mnc; + unsigned short cellId; + unsigned short lac; + bool isRoaming; + bool isFlightMode; + std::string imei; + + CellularNetworkProperties() : + status(""), + apn(""), + ipAddress(""), + ipv6Address(""), + mcc(0), + mnc(0), + cellId(0), + lac(0), + isRoaming(false), + isFlightMode(false), + imei("") + { + } +}; + +struct SIMProperties +{ + std::string state; + std::string operatorName; + std::string msisdn; + std::string iccid; + unsigned short mcc; + unsigned short mnc; + std::string msin; + std::string spn; + + SIMProperties() : + state("UNKNOWN"), + operatorName(""), + msisdn(""), + iccid(""), + mcc(0), + mnc(0), + msin(""), + spn("") + { + } +}; + +struct DeviceOrientationProperties +{ + std::string status; + bool isAutoRotation; + + DeviceOrientationProperties() : + status("PORTRAIT_PRIMARY"), + isAutoRotation(false) + { + } +}; + +struct BuildProperties +{ + std::string model; + std::string manufacturer; + std::string buildVersion; + + BuildProperties() : + model(""), + manufacturer(""), + buildVersion("") + { + } +}; + +struct LocaleProperties +{ + std::string language; + std::string country; + + LocaleProperties() : + language(""), + country("") + { + } +}; + +struct PeripheralProperties +{ + bool isVideoOutputOn; + + PeripheralProperties() : + isVideoOutputOn(false) + { + } +}; + +typedef DPL::SharedPtr<DeviceCapabilitiesProperties> DeviceCapabilitiesPropertiesPtr; +typedef DPL::SharedPtr<BatteryProperties> BatteryPropertiesPtr; +typedef DPL::SharedPtr<CpuProperties> CpuPropertiesPtr; +typedef DPL::SharedPtr<StorageUnitProperties> StorageUnitPropertiesPtr; +typedef DPL::SharedPtr<StorageProperties> StoragePropertiesPtr; +typedef DPL::SharedPtr<DisplayProperties> DisplayPropertiesPtr; +typedef DPL::SharedPtr<WifiNetworkProperties> WifiNetworkPropertiesPtr; +typedef DPL::SharedPtr<NetworkProperties> NetworkPropertiesPtr; +typedef DPL::SharedPtr<CellularNetworkProperties> CellularNetworkPropertiesPtr; +typedef DPL::SharedPtr<SIMProperties> SIMPropertiesPtr; +typedef DPL::SharedPtr<DeviceOrientationProperties> DeviceOrientationPropertiesPtr; +typedef DPL::SharedPtr<BuildProperties> BuildPropertiesPtr; +typedef DPL::SharedPtr<LocaleProperties> LocalePropertiesPtr; +typedef DPL::SharedPtr<PeripheralProperties> PeripheralPropertiesPtr; + +} +} + +#endif diff --git a/wearable_src/Systeminfo/config.xml b/wearable_src/Systeminfo/config.xml new file mode 100755 index 0000000..2956c4e --- /dev/null +++ b/wearable_src/Systeminfo/config.xml @@ -0,0 +1,23 @@ +<?xml version="1.0" ?> +<!DOCTYPE plugin-properties SYSTEM "/usr/etc/tizen-apis/config.dtd"> +<plugin-properties> + <library-name>libwrt-plugins-tizen-systeminfo.so</library-name> + <feature-install-uri>systeminfo.install.uri</feature-install-uri> + + <api-feature> + <name>http://tizen.org/privilege/systeminfo</name> + <device-capability>system.info</device-capability> + <device-capability>systemmanager.info</device-capability> + </api-feature> + + <api-feature> + <name>http://tizen.org/privilege/system</name> + <device-capability>system.info</device-capability> + </api-feature> + + <api-feature> + <name>http://tizen.org/privilege/systemmanager</name> + <device-capability>systemmanager.info</device-capability> + </api-feature> +</plugin-properties> + diff --git a/wearable_src/Systeminfo/plugin_config.cpp b/wearable_src/Systeminfo/plugin_config.cpp new file mode 100755 index 0000000..a444bf8 --- /dev/null +++ b/wearable_src/Systeminfo/plugin_config.cpp @@ -0,0 +1,114 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <map> +#include <utility> +#include <Commons/FunctionDefinition.h> +#include <Commons/FunctionDeclaration.h> +#include <Commons/Exception.h> +#include "plugin_config.h" + +#define SYSTEMINFO_FEATURE_API_MASTER "http://tizen.org/privilege/systeminfo" +#define SYSTEMINFO_FEATURE_API_SYSTEMINFO "http://tizen.org/privilege/system" +#define SYSTEMINFO_FEATURE_API_SYSTEMMANAGER "http://tizen.org/privilege/systemmanager" + +#define SYSTEMINFO_DEVICE_CAP_SYSTEMINFO "system.info" +#define SYSTEMINFO_DEVICE_CAP_SYSTEMMANAGER "system.manager" + +namespace DeviceAPI { +namespace Systeminfo { + +#pragma GCC visibility push(default) + +const char* SYSTEMINFO_FUNCTION_API_GET_CAPABILITIES = "getCapabilities"; +const char* SYSTEMINFO_FUNCTION_API_GET_PROPERTY_PARTNER_VALUE = "getPropertyPartnerValue"; +const char* SYSTEMINFO_FUNCTION_API_GET_PROPERTY_SIM_VALUE = "getPropertySimValue"; + +static WrtDeviceApis::Commons::FunctionMapping createSysteminfoFunctions(); + +static WrtDeviceApis::Commons::FunctionMapping SysteminfoFunctions = + createSysteminfoFunctions(); + +DEFINE_FUNCTION_GETTER(Systeminfo, SysteminfoFunctions); + +#pragma GCC visibility pop + +static WrtDeviceApis::Commons::FunctionMapping createSysteminfoFunctions() +{ + /** + * Device capabilities + */ + using namespace WrtDeviceApis::Commons; + + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_SYSTEMINFO, SYSTEMINFO_DEVICE_CAP_SYSTEMINFO); + ACE_CREATE_DEVICE_CAP(DEVICE_CAP_SYSTEMMANAGER, SYSTEMINFO_DEVICE_CAP_SYSTEMMANAGER); + + ACE_CREATE_DEVICE_CAPS_LIST(EMPTY_DEVICE_LIST); + + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_SYSTEMINFO); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_SYSTEMINFO, DEVICE_CAP_SYSTEMINFO); + + ACE_CREATE_DEVICE_CAPS_LIST(DEVICE_LIST_SYSTEMMANAGER); + ACE_ADD_DEVICE_CAP(DEVICE_LIST_SYSTEMMANAGER, DEVICE_CAP_SYSTEMMANAGER); + + /** + * Api Features + */ + ACE_CREATE_FEATURE(FEATURE_MASTER, SYSTEMINFO_FEATURE_API_MASTER); + ACE_CREATE_FEATURE(FEATURE_SYSTEMINFO, SYSTEMINFO_FEATURE_API_SYSTEMINFO); + ACE_CREATE_FEATURE(FEATURE_SYSTEMMANAGER, SYSTEMINFO_FEATURE_API_SYSTEMMANAGER); + + ACE_CREATE_FEATURE_LIST(SYSTEMINFO_FEATURES_SYSTEMINFO); + ACE_ADD_API_FEATURE(SYSTEMINFO_FEATURES_SYSTEMINFO, FEATURE_MASTER); + ACE_ADD_API_FEATURE(SYSTEMINFO_FEATURES_SYSTEMINFO, FEATURE_SYSTEMINFO); + + ACE_CREATE_FEATURE_LIST(SYSTEMINFO_FEATURES_SYSTEMMANAGER); + ACE_ADD_API_FEATURE(SYSTEMINFO_FEATURES_SYSTEMMANAGER, FEATURE_MASTER); + ACE_ADD_API_FEATURE(SYSTEMINFO_FEATURES_SYSTEMMANAGER, FEATURE_SYSTEMMANAGER); + + /** + * Functions + */ + FunctionMapping SysteminfoFunctions; + + AceFunction getCapabilitiesFunc = ACE_CREATE_FUNCTION( + FUNCTION_GET_CAPABILITIES, + SYSTEMINFO_FUNCTION_API_GET_CAPABILITIES, + SYSTEMINFO_FEATURES_SYSTEMINFO, + DEVICE_LIST_SYSTEMINFO); + SysteminfoFunctions.insert(std::make_pair(SYSTEMINFO_FUNCTION_API_GET_CAPABILITIES, getCapabilitiesFunc)); + + AceFunction getPropertyPartnerValueFunc = ACE_CREATE_FUNCTION( + FUNCTION_GET_PROPERTY_PARTNER_VALUE, + SYSTEMINFO_FUNCTION_API_GET_PROPERTY_PARTNER_VALUE, + SYSTEMINFO_FEATURES_SYSTEMMANAGER, + DEVICE_LIST_SYSTEMINFO); + SysteminfoFunctions.insert(std::make_pair(SYSTEMINFO_FUNCTION_API_GET_PROPERTY_PARTNER_VALUE, getPropertyPartnerValueFunc)); + + AceFunction getPropertySimValueFunc = ACE_CREATE_FUNCTION( + FUNCTION_GET_PROPERTY_SIM_VALUE, + SYSTEMINFO_FUNCTION_API_GET_PROPERTY_SIM_VALUE, + SYSTEMINFO_FEATURES_SYSTEMINFO, + DEVICE_LIST_SYSTEMINFO); + SysteminfoFunctions.insert(std::make_pair(SYSTEMINFO_FUNCTION_API_GET_PROPERTY_SIM_VALUE, getPropertySimValueFunc)); + + return SysteminfoFunctions; +} +} +} + +#undef SYSTEMINFO_FEATURE_API diff --git a/wearable_src/Systeminfo/plugin_config.h b/wearable_src/Systeminfo/plugin_config.h new file mode 100755 index 0000000..bc0884d --- /dev/null +++ b/wearable_src/Systeminfo/plugin_config.h @@ -0,0 +1,39 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _SYSTEMINFO_PLUGIN_CONFIG_H_ +#define _SYSTEMINFO_PLUGIN_CONFIG_H_ + +#include <Commons/FunctionDeclaration.h> + +namespace DeviceAPI { +namespace Systeminfo { + +extern const char* SYSTEMINFO_FUNCTION_API_GET_CAPABILITIES; +extern const char* SYSTEMINFO_FUNCTION_API_GET_PROPERTY_PARTNER_VALUE; +extern const char* SYSTEMINFO_FUNCTION_API_GET_PROPERTY_SIM_VALUE; + +DECLARE_FUNCTION_GETTER(Systeminfo); + +#define SYSTEMINFO_CHECK_ACCESS(functionName) \ + aceCheckAccess<AceFunctionGetter, DefaultArgsVerifier<> >( \ + getSysteminfoFunctionData, \ + functionName) +} +} + +#endif diff --git a/wearable_src/Systeminfo/plugin_initializer.cpp b/wearable_src/Systeminfo/plugin_initializer.cpp new file mode 100644 index 0000000..3c3465e --- /dev/null +++ b/wearable_src/Systeminfo/plugin_initializer.cpp @@ -0,0 +1,87 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <Commons/plugin_initializer_def.h> +#include <Commons/WrtAccess/WrtAccess.h> +#include <TimeTracer.h> +#include "SysteminfoAsyncCallbackManager.h" +#include "SysteminfoListenerManager.h" +#include "JSSysteminfo.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Systeminfo { + +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; + +#define WRT_JS_EXTENSION_OBJECT_TIZEN "tizen" + +void on_widget_start_callback(int widgetId) +{ + LoggerD("[Tizen\\Systeminfo ] on_widget_start_callback (" << widgetId << ")"); + TIME_TRACER_INIT(); + Try + { + WrtAccessSingleton::Instance().initialize(widgetId); + } + Catch(Commons::Exception) + { + LoggerE("WrtAccess initialization failed"); + } +} + +void on_widget_stop_callback(int widgetId) +{ + LoggerD("[Tizen\\Systeminfo ] on_widget_stop_callback (" << widgetId << ")"); + TIME_TRACER_EXPORT_REPORT_TO(TIME_TRACER_EXPORT_FILE,"SystemInfo"); + TIME_TRACER_RELEASE(); + Try + { + WrtAccessSingleton::Instance().deinitialize(widgetId); + } + Catch(Commons::Exception) + { + LoggerE("WrtAccess deinitialization failed"); + } +} + +void on_frame_load_callback(const void * context) +{ + LoggerD("[Tizen\\systeminfo] on_frame_load_callback (" << context << ")"); +} + +void on_frame_unload_callback(const void * context) +{ + LoggerD("[Tizen\\systeminfo] on_frame_unload_callback (" << context << ")"); + + DeviceAPI::Systeminfo::SysteminfoAsyncCallbackManagerSingleton::Instance().unregisterContext(static_cast<JSContextRef>(context)); + DeviceAPI::Systeminfo::SysteminfoListenerManagerSingleton::Instance().unregisterContext(static_cast<JSContextRef>(context)); +} + +PLUGIN_ON_WIDGET_START(on_widget_start_callback) +PLUGIN_ON_WIDGET_STOP(on_widget_stop_callback) +PLUGIN_ON_FRAME_LOAD(on_frame_load_callback) +PLUGIN_ON_FRAME_UNLOAD(on_frame_unload_callback) + +PLUGIN_CLASS_MAP_BEGIN +PLUGIN_CLASS_MAP_ADD_CLASS(WRT_JS_EXTENSION_OBJECT_TIZEN, "systeminfo", (js_class_template_getter)DeviceAPI::Systeminfo::JSSysteminfo::getClassRef, NULL) +PLUGIN_CLASS_MAP_END + +} // Systeminfo +} // DeviceAPI + diff --git a/wearable_src/TimeUtil/CMakeLists.txt b/wearable_src/TimeUtil/CMakeLists.txt new file mode 100755 index 0000000..c41b66c --- /dev/null +++ b/wearable_src/TimeUtil/CMakeLists.txt @@ -0,0 +1,48 @@ +SET(TARGET_NAME ${timeutil_target}) +SET(DESTINATION_NAME ${timeutil_dest}) +SET(TARGET_IMPL_NAME ${timeutil_impl}) + +PKG_CHECK_MODULES(platform_pkgs_time REQUIRED icu-i18n icu-io icu-le icu-lx icu-uc ) + +INCLUDE_DIRECTORIES( + ${TOP}/Common + ${platform_pkgs_time_INCLUDE_DIRS} +) + +SET(CMAKE_INSTALL_RPATH + ${CMAKE_INSTALL_RPATH} + ${CMAKE_INSTALL_PREFIX}/${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME} +) + +SET(SRCS_IMPL + JSTimeUtil.cpp + JSTZDate.cpp + JSTimeDuration.cpp + TimeUtilConverter.cpp + TimeUtil.cpp + TZDate.cpp + TimeUtilTools.cpp +) + +ADD_LIBRARY(${TARGET_IMPL_NAME} SHARED ${SRCS_IMPL}) + +TARGET_LINK_LIBRARIES(${TARGET_IMPL_NAME} + ${LIBS_COMMON} +) + +SET(SRCS + plugin_initializer.cpp +) + +ADD_LIBRARY(${TARGET_NAME} SHARED ${SRCS}) + +TARGET_LINK_LIBRARIES(${TARGET_NAME} + ${TARGET_IMPL_NAME} +) + +INSTALL(TARGETS ${TARGET_NAME} ${TARGET_IMPL_NAME} LIBRARY DESTINATION ${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME}) +INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/config.xml DESTINATION ${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME}) +INSTALL( + DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/ DESTINATION ${DESTINATION_HEADER_PREFIX}/timeutil + FILES_MATCHING PATTERN "*.h" PATTERN "CMakeFiles" EXCLUDE +) diff --git a/wearable_src/TimeUtil/DurationProperties.h b/wearable_src/TimeUtil/DurationProperties.h new file mode 100755 index 0000000..41bb7cc --- /dev/null +++ b/wearable_src/TimeUtil/DurationProperties.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. + */ + + + + +#ifndef WRTPLUGINS_API_TIMEUTIL_DURATION_PROPERTIES_H_ +#define WRTPLUGINS_API_TIMEUTIL_DURATION_PROPERTIES_H_ + +#include <dpl/shared_ptr.h> +#include <string> + +using namespace std; + +namespace DeviceAPI { +namespace Time { + +namespace { + const short MSECS_UNIT= 0; + const short SECONDS_UNIT = 1; + const short MINUTES_UNIT = 2; + const short HOURS_UNIT = 3; + const short DAYS_UNIT = 4; +} + +struct DurationProperties +{ + long long length; + short unit; + DurationProperties() + : length(0), + unit(MSECS_UNIT) + { + } +}; + +typedef DPL::SharedPtr<DurationProperties> DurationPropertiesPtr; + +} // Time +} // DeviceAPI + +#endif //WRTPLUGINS_API_TIMEUTIL_DURATION_PROPERTIES_H_
\ No newline at end of file diff --git a/wearable_src/TimeUtil/JSTZDate.cpp b/wearable_src/TimeUtil/JSTZDate.cpp new file mode 100644 index 0000000..38b00bf --- /dev/null +++ b/wearable_src/TimeUtil/JSTZDate.cpp @@ -0,0 +1,1361 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <ctime> +#include <string> + +#include <CommonsJavaScript/PrivateObject.h> +#include <CommonsJavaScript/JSUtils.h> +#include <Commons/Exception.h> +#include <JSWebAPIErrorFactory.h> +#include <ArgumentValidator.h> +#include <JSUtil.h> +#include "DurationProperties.h" +#include "JSTZDate.h" +#include "TimeUtilConverter.h" +#include <Logger.h> + +using namespace DeviceAPI::Common; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +#define min(a,b) (((a) < (b)) ? (a) : (b)) + +#define TZDATE_ATTRIBUTENAME "TZDate" + +namespace DeviceAPI { +namespace Time { + +JSClassDefinition JSTZDate::m_classInfo = +{ + 0, + kJSClassAttributeNone, + TZDATE_ATTRIBUTENAME, + 0, + NULL,//property, + m_function, + initialize, + finalize, + NULL, //hasProperty, + NULL, //getProperty, + NULL, //setProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL //ConvertToType +}; + +JSStaticFunction JSTZDate::m_function[] = { + {"getDate", JSTZDate::getDate, kJSPropertyAttributeNone}, + {"getDay", JSTZDate::getDay, kJSPropertyAttributeNone}, + {"getFullYear", JSTZDate::getFullYear, kJSPropertyAttributeNone}, + {"getHours", JSTZDate::getHours, kJSPropertyAttributeNone}, + {"getMilliseconds", JSTZDate::getMilliseconds, kJSPropertyAttributeNone}, + {"getMinutes", JSTZDate::getMinutes, kJSPropertyAttributeNone}, + {"getMonth", JSTZDate::getMonth, kJSPropertyAttributeNone}, + {"getSeconds", JSTZDate::getSeconds, kJSPropertyAttributeNone}, + + {"setDate", JSTZDate::setDate, kJSPropertyAttributeNone}, + {"setFullYear", JSTZDate::setFullYear, kJSPropertyAttributeNone}, + {"setHours", JSTZDate::setHours, kJSPropertyAttributeNone}, + {"setMilliseconds", JSTZDate::setMilliseconds, kJSPropertyAttributeNone}, + {"setMinutes", JSTZDate::setMinutes, kJSPropertyAttributeNone}, + {"setMonth", JSTZDate::setMonth, kJSPropertyAttributeNone}, + {"setSeconds", JSTZDate::setSeconds, kJSPropertyAttributeNone}, + + {"getUTCDate", JSTZDate::getUTCDate, kJSPropertyAttributeNone}, + {"getUTCDay", JSTZDate::getUTCDay, kJSPropertyAttributeNone}, + {"getUTCFullYear", JSTZDate::getUTCFullYear, kJSPropertyAttributeNone}, + {"getUTCHours", JSTZDate::getUTCHours, kJSPropertyAttributeNone}, + {"getUTCMilliseconds", JSTZDate::getUTCMilliseconds, kJSPropertyAttributeNone}, + {"getUTCMinutes", JSTZDate::getUTCMinutes, kJSPropertyAttributeNone}, + {"getUTCMonth", JSTZDate::getUTCMonth, kJSPropertyAttributeNone}, + {"getUTCSeconds", JSTZDate::getUTCSeconds, kJSPropertyAttributeNone}, + + {"setUTCDate", JSTZDate::setUTCDate, kJSPropertyAttributeNone}, + {"setUTCFullYear", JSTZDate::setUTCFullYear, kJSPropertyAttributeNone}, + {"setUTCHours", JSTZDate::setUTCHours, kJSPropertyAttributeNone}, + {"setUTCMilliseconds", JSTZDate::setUTCMilliseconds, kJSPropertyAttributeNone}, + {"setUTCMinutes", JSTZDate::setUTCMinutes, kJSPropertyAttributeNone}, + {"setUTCMonth", JSTZDate::setUTCMonth, kJSPropertyAttributeNone}, + {"setUTCSeconds", JSTZDate::setUTCSeconds, kJSPropertyAttributeNone}, + + {"getTimezone", JSTZDate::getTimezone, kJSPropertyAttributeNone}, + {"toTimezone", JSTZDate::toTimezone, kJSPropertyAttributeNone}, + {"toLocalTimezone", JSTZDate::toLocalTimezone, kJSPropertyAttributeNone}, + {"toUTC", JSTZDate::toUTC, kJSPropertyAttributeNone}, + + {"difference", JSTZDate::difference, kJSPropertyAttributeNone}, + {"equalsTo", JSTZDate::equalsTo, kJSPropertyAttributeNone}, + {"earlierThan", JSTZDate::earlierThan, kJSPropertyAttributeNone}, + {"laterThan", JSTZDate::laterThan, kJSPropertyAttributeNone}, + {"addDuration", JSTZDate::addDuration, kJSPropertyAttributeNone}, + + {"toLocaleDateString", JSTZDate::toLocaleDateString, kJSPropertyAttributeNone}, + {"toLocaleTimeString", JSTZDate::toLocaleTimeString, kJSPropertyAttributeNone}, + {"toLocaleString", JSTZDate::toLocaleString, kJSPropertyAttributeNone}, + {"toDateString", JSTZDate::toDateString, kJSPropertyAttributeNone}, + {"toTimeString", JSTZDate::toTimeString, kJSPropertyAttributeNone}, + {"toString", JSTZDate::toString, kJSPropertyAttributeNone}, + + {"getTimezoneAbbreviation", JSTZDate::getTimezoneAbbreviation, kJSPropertyAttributeNone}, + {"secondsFromUTC", JSTZDate::secondsFromUTC, kJSPropertyAttributeNone}, + {"isDST", JSTZDate::isDST, kJSPropertyAttributeNone}, + {"getPreviousDSTTransition", JSTZDate::getPreviousDSTTransition, kJSPropertyAttributeNone}, + {"getNextDSTTransition", JSTZDate::getNextDSTTransition, kJSPropertyAttributeNone}, + { 0, 0, 0} +}; + +JSClassRef JSTZDate::m_jsClassRef = JSClassCreate(JSTZDate::getClassInfo()); + +JSObjectRef JSTZDate::createJSObject(JSContextRef context, TZDatePtr tzDate) { + LoggerD("entered"); + TZDatePrivObject *priv = new TZDatePrivObject(context, tzDate); + if (!priv) { + ThrowMsg(NullPointerException, "Can not new an object"); + } + + return JSObjectMake(context, getClassRef(), priv); +} + + +JSObjectRef JSTZDate::createJSObject(JSContextRef context, const bool isNotNull) { + LoggerD("entered"); + TZDatePtr tzDate(new TZDate(isNotNull)); + return createJSObject(context, tzDate); +} + +JSObjectRef JSTZDate::createJSObject(JSContextRef context, const std::string &timezone) { + LoggerD("entered"); + if (timezone == "") + return createJSObject(context); + + TZDatePtr tzDate(new TZDate(timezone)); + return createJSObject(context, tzDate); +} + +JSObjectRef JSTZDate::createJSObject(JSContextRef context, const double milliseconds, const std::string &timezone) { + LoggerD("entered"); + TZDatePtr tzDate; + if (timezone == "") + tzDate = TZDatePtr(new TZDate()); + else + tzDate = TZDatePtr(new TZDate(timezone)); + + if (!tzDate->setTime(milliseconds)) + ThrowMsg(WrtDeviceApis::Commons::UnknownException, "Can not set UTC Time"); + + return createJSObject(context, tzDate); +} + +JSObjectRef JSTZDate::createJSObject(JSContextRef context, const std::string &dateString, const double milliseconds, const std::string &timezone) { + LoggerD("entered"); + TZDatePtr tzDate = TZDatePtr(new TZDate(dateString, milliseconds, timezone)); + + return createJSObject(context, tzDate); +} + +JSObjectRef JSTZDate::createJSObject(JSContextRef context, const TZDateProperties &properties) { + LoggerD("entered"); + TZDatePtr tzDate(new TZDate(properties)); + + return createJSObject(context, tzDate); +} + +JSObjectRef JSTZDate::createJSObject(JSContextRef context, const long year, const long month, const long day, const long hours, const long minutes, const long seconds, const long milliseconds, const std::string &timezone) { + LoggerD("entered"); + + TZDateProperties props; + props.year = year; + props.month = month; + props.day = day; + props.hours = hours; + props.minutes = minutes; + props.seconds = seconds; + props.milliseconds = milliseconds; + props.timezone = timezone; + + return createJSObject(context, props); + +} + +void JSTZDate::initialize(JSContextRef context, JSObjectRef object) +{ + LoggerD("entered Nothing to do."); +} + +void JSTZDate::finalize(JSObjectRef object) +{ + LoggerD( "entered" ); + TZDatePrivObject *priv = + static_cast<TZDatePrivObject*>(JSObjectGetPrivate(object)); + if (priv) + delete priv; +} + +JSObjectRef JSTZDate::constructor(JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) +{ + LoggerD("entered"); + JSObjectRef tzDate = NULL; + ArgumentValidator validator(ctx, argumentCount, arguments); + Try { + if (argumentCount == 0) + tzDate = createJSObject(ctx); + else if (argumentCount <= 2) { + std::string timezone = ""; + try { + timezone = validator.toString(1, true); + + JSObjectRef dateObj = validator.toObject(0, true); + if (dateObj) { + JSValueRef dateException = NULL; + + JSValueRef toStringFuction = JSUtil::getProperty(ctx, dateObj, "toString", NULL); + JSObjectRef function = JSUtil::JSValueToObject(ctx, toStringFuction); + + JSValueRef result = JSObjectCallAsFunction(ctx, function, dateObj, 0, NULL, &dateException); + if (dateException) + ThrowMsg(ConversionException, "Couldn't get date string"); + + std::string stringDate = JSUtil::JSValueToString(ctx, result); + LoggerD(stringDate); + stringDate.erase(stringDate.find(" GMT")); + + JSValueRef getMiliSecFuction = JSUtil::getProperty(ctx, dateObj, "getMilliseconds", NULL); + function = JSUtil::JSValueToObject(ctx, getMiliSecFuction); + + result = JSObjectCallAsFunction(ctx, function, dateObj, 0, NULL, &dateException); + if (dateException) + ThrowMsg(ConversionException, "Couldn't get milliseconds"); + + long millisec = JSUtil::JSValueToLong(ctx, result); + LoggerD("getMilliseconds = " << millisec); + tzDate = createJSObject(ctx, stringDate, millisec, timezone); + } + } catch (const BasePlatformException& err) { + LoggerE(err.getName() << ":"<<err.getMessage()); + if (tzDate) { + TZDatePrivObject *priv = static_cast<TZDatePrivObject*>(JSObjectGetPrivate(tzDate)); + if (priv) + delete priv; + } + tzDate = NULL; + } catch (const WrtDeviceApis::Commons::Exception& err) { + LoggerE(err.GetClassName() << ":"<<err.GetMessage()); + if (tzDate) { + TZDatePrivObject *priv = static_cast<TZDatePrivObject*>(JSObjectGetPrivate(tzDate)); + if (priv) + delete priv; + } + tzDate = NULL; + } + if (!tzDate) + tzDate = createJSObject(ctx, timezone); + } else { + TZDateProperties prop; + prop.year = validator.toLong(0); + if ((prop.year >= 0) && (prop.year <= 99)) + prop.year += 1900; + prop.month = validator.toLong(1); + prop.day = validator.toLong(2); + prop.hours = validator.toLong(3, true); + prop.minutes = validator.toLong(4, true); + prop.seconds = validator.toLong(5, true); + prop.milliseconds= validator.toLong(6, true); + prop.timezone = validator.toString(7, true); + tzDate = createJSObject(ctx, prop); + } + } Catch(ConversionException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (InvalidArgumentException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + + if (tzDate == NULL) + tzDate = createJSObject(ctx, false); + + JSStringRef ctorName = JSStringCreateWithUTF8CString("constructor"); + JSObjectSetProperty(ctx, tzDate, ctorName, constructor, + kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete | kJSPropertyAttributeDontEnum, NULL); + JSStringRelease(ctorName); + return tzDate; +} +const JSClassRef JSTZDate::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSTZDate::getClassInfo() +{ + return &m_classInfo; +} + +JSValueRef JSTZDate::getTimezone(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LoggerD("entered"); + TimeUtilConverter converter(context); + + Try { + TZDatePrivObject* privateObject = static_cast<TZDatePrivObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LoggerE("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + TZDatePtr tzDate(privateObject->getObject()); + std::string timezone = tzDate->getTimezone(); + + return converter.toJSValueRef(timezone); + } Catch(NullPointerException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch(WrtDeviceApis::Commons::UnknownException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + + return converter.toJSValueRef("Invalid Date"); +} + +JSValueRef JSTZDate::toTimezone(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LoggerD("entered"); + + try { + ArgumentValidator validator(context, argumentCount, arguments); + std::string timezone = validator.toString(0); + + TZDatePrivObject* privateObject = static_cast<TZDatePrivObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LoggerE("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + TZDatePtr tzDate(privateObject->getObject()); + if ((timezone == "") || (!tzDate->isAvailableTimezone(timezone))) + ThrowMsg(InvalidArgumentException, "Unsupported Timezone."); + + return createJSObject(context, tzDate->getTime(), timezone); + } catch(const BasePlatformException& err){ + return JSWebAPIErrorFactory::postException(context, exception, err); + } Catch(NullPointerException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch(WrtDeviceApis::Commons::UnknownException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, _rethrown_exception.GetMessage()); + } Catch (InvalidArgumentException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, _rethrown_exception.GetMessage()); + } Catch(ConversionException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown Error"); +} + +JSValueRef JSTZDate::diffTZDate(JSContextRef context, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception, CompareType type) { + LoggerD("entered"); + + ArgumentValidator validator(context, argumentCount, arguments); + if (!validator.toObject(0, JSTZDate::getClassRef(), false)) + ThrowMsg(ConversionException, "Parameter is not TZDate"); + + TZDatePrivObject* privateObject = static_cast<TZDatePrivObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LoggerE("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + TimeUtilConverter converter(context); + TZDatePtr tzDate(privateObject->getObject()); + long long cmpResult = tzDate->difference(converter.getPropertiesInTZDate(arguments[0])); + + switch (type) { + case EQUALSTO: + { + if (cmpResult == 0) + return converter.toJSValueRef(true); + else + return converter.toJSValueRef(false); + } + case EARLIERTHAN: + { + if (cmpResult < 0) + return converter.toJSValueRef(true); + else + return converter.toJSValueRef(false); + } + case LATERTHAN: + { + if (cmpResult > 0) + return converter.toJSValueRef(true); + else + return converter.toJSValueRef(false); + } + case DIFFERENCE: + default: + return converter.makeMillisecondDurationObject(cmpResult); + } +} + +JSValueRef JSTZDate::difference(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LoggerD("entered"); + + Try { + return diffTZDate(context, thisObject, argumentCount, arguments, exception, DIFFERENCE); + } catch(const BasePlatformException& err){ + return JSWebAPIErrorFactory::postException(context, exception, err); + } Catch(NullPointerException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch(WrtDeviceApis::Commons::UnknownException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, _rethrown_exception.GetMessage()); + } Catch(ConversionException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown Error"); +} + +JSValueRef JSTZDate::equalsTo(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LoggerD("entered"); + + Try { + return diffTZDate(context, thisObject, argumentCount, arguments, exception, EQUALSTO); + } catch(const BasePlatformException& err){ + return JSWebAPIErrorFactory::postException(context, exception, err); + } Catch(NullPointerException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch(WrtDeviceApis::Commons::UnknownException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, _rethrown_exception.GetMessage()); + } Catch(ConversionException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown Error"); +} + +JSValueRef JSTZDate::earlierThan(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LoggerD("earlierThan entered"); + + Try { + return diffTZDate(context, thisObject, argumentCount, arguments, exception, EARLIERTHAN); + } catch(const BasePlatformException& err){ + return JSWebAPIErrorFactory::postException(context, exception, err); + } Catch(NullPointerException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch(WrtDeviceApis::Commons::UnknownException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, _rethrown_exception.GetMessage()); + } Catch(ConversionException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown Error"); + +} + +JSValueRef JSTZDate::laterThan(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + + LoggerD("laterThan entered"); + + Try { + return diffTZDate(context, thisObject, argumentCount, arguments, exception, LATERTHAN); + } catch(const BasePlatformException& err){ + return JSWebAPIErrorFactory::postException(context, exception, err); + } Catch(NullPointerException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch(WrtDeviceApis::Commons::UnknownException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, _rethrown_exception.GetMessage()); + } Catch(ConversionException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown Error"); + +} + +JSValueRef JSTZDate::addDuration(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + + LoggerD("addDuration entered"); + Try { + TimeUtilConverter converter(context); + + DurationProperties duration; + if (argumentCount == 0) + duration= converter.getDurationProperties(JSValueMakeUndefined(context)); + else + duration= converter.getDurationProperties(arguments[0]); + + LoggerD("unit : " << duration.unit << " Length:" << duration.length); + TZDatePrivObject* privateObject = static_cast<TZDatePrivObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LoggerE("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + TZDatePtr tzDate(privateObject->getObject()); + TZDateProperties result = tzDate->addDuration(duration); + + return (static_cast<JSValueRef>(createJSObject(context, result))); + } Catch(NullPointerException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch(WrtDeviceApis::Commons::UnknownException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, _rethrown_exception.GetMessage()); + } Catch(ConversionException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (OutOfRangeException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "The result is beyond the scope that TZDate can handle."); + } + + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown Error"); +} + +JSValueRef JSTZDate::toUTC(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + + LoggerD("toUTC entered"); + Try { + TZDatePrivObject* privateObject = static_cast<TZDatePrivObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LoggerE("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + TZDatePtr tzDate(privateObject->getObject()); + return createJSObject(context, tzDate->getTime(), tzDate->getUTCTimezoneName()); + } Catch(NullPointerException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch(WrtDeviceApis::Commons::UnknownException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, _rethrown_exception.GetMessage()); + } Catch (InvalidArgumentException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::INVALID_VALUES_ERROR, "Invalid Values"); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown Error"); +} + + +JSValueRef JSTZDate::toLocalTimezone(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + + LoggerD("toLocalTimezone entered"); + Try { + TZDatePrivObject* privateObject = static_cast<TZDatePrivObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LoggerE("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + TZDatePtr tzDate(privateObject->getObject()); + return createJSObject(context, tzDate->getTime(), tzDate->getLocalTimezoneName()); + } Catch(NullPointerException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch(WrtDeviceApis::Commons::UnknownException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, _rethrown_exception.GetMessage()); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown Error"); +} + +JSValueRef JSTZDate::toLocaleDateString(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LoggerD("Entered"); + TimeUtilConverter converter(context); + Try { + TZDatePrivObject* privateObject = static_cast<TZDatePrivObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LoggerE("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + TZDatePtr tzDate(privateObject->getObject()); + std::string result = tzDate->toDateString(true); + return converter.toJSValueRef(result); + } Catch(NullPointerException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch(WrtDeviceApis::Commons::UnknownException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + + return converter.toJSValueRef("Invalid Date"); +} + +JSValueRef JSTZDate::toLocaleTimeString(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LoggerD("Entered"); + TimeUtilConverter converter(context); + Try { + TZDatePrivObject* privateObject = static_cast<TZDatePrivObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LoggerE("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + TZDatePtr tzDate(privateObject->getObject()); + std::string result = tzDate->toTimeString(true); + return converter.toJSValueRef(result); + } Catch(NullPointerException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch(WrtDeviceApis::Commons::UnknownException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + + return converter.toJSValueRef("Invalid Date"); +} + +JSValueRef JSTZDate::toLocaleString(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LoggerD("Entered"); + TimeUtilConverter converter(context); + Try { + TZDatePrivObject* privateObject = static_cast<TZDatePrivObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LoggerE("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + TZDatePtr tzDate(privateObject->getObject()); + std::string result = tzDate->toString(true); + return converter.toJSValueRef(result); + } Catch(NullPointerException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch(WrtDeviceApis::Commons::UnknownException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + + return converter.toJSValueRef("Invalid Date"); +} + +JSValueRef JSTZDate::toDateString(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LoggerD("Entered"); + TimeUtilConverter converter(context); + Try { + TZDatePrivObject* privateObject = static_cast<TZDatePrivObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LoggerE("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + TZDatePtr tzDate(privateObject->getObject()); + std::string result = tzDate->toDateString(); + return converter.toJSValueRef(result); + } Catch(NullPointerException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch(WrtDeviceApis::Commons::UnknownException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + + return converter.toJSValueRef("Invalid Date"); +} + +JSValueRef JSTZDate::toTimeString(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LoggerD("Entered"); + TimeUtilConverter converter(context); + Try { + TZDatePrivObject* privateObject = static_cast<TZDatePrivObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LoggerE("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + TZDatePtr tzDate(privateObject->getObject()); + std::string result = tzDate->toTimeString(); + return converter.toJSValueRef(result); + } Catch(NullPointerException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch(WrtDeviceApis::Commons::UnknownException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + + return converter.toJSValueRef("Invalid Date"); +} + + +JSValueRef JSTZDate::toString(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LoggerD("Entered"); + TimeUtilConverter converter(context); + Try { + TZDatePrivObject* privateObject = static_cast<TZDatePrivObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LoggerE("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + TZDatePtr tzDate(privateObject->getObject()); + std::string result = tzDate->toString(); + return converter.toJSValueRef(result); + } Catch(NullPointerException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch(WrtDeviceApis::Commons::UnknownException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + + return converter.toJSValueRef("Invalid Date"); +} + +JSValueRef JSTZDate::getDate(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception) { + LoggerD("<<<"); + + TZDate::TZDateFields dateFields = TZDate::TZDATE_DATE; + return getTZDateValue(context, thisObject, argumentCount, arguments, exception, dateFields); +} //getDate() + +JSValueRef JSTZDate::getDay(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception) { + LoggerD("<<<"); + + TZDate::TZDateFields dateFields = TZDate::TZDATE_DAY_OF_WEEK; + return getTZDateValue(context, thisObject, argumentCount, arguments, exception, dateFields); +} //getDay() + +JSValueRef JSTZDate::getFullYear(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception) { + LoggerD("<<<"); + + TZDate::TZDateFields dateFields = TZDate::TZDATE_YEAR; + return getTZDateValue(context, thisObject, argumentCount, arguments, exception, dateFields); +} //getFullYear() + +JSValueRef JSTZDate::getHours(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception) { + LoggerD("<<<"); + + TZDate::TZDateFields dateFields = TZDate::TZDATE_HOUR_OF_DAY; + return getTZDateValue(context, thisObject, argumentCount, arguments, exception, dateFields); +} //getHours() + +JSValueRef JSTZDate::getMilliseconds(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception) { + LoggerD("<<<"); + + TZDate::TZDateFields dateFields = TZDate::TZDATE_MILLISECOND; + return getTZDateValue(context, thisObject, argumentCount, arguments, exception, dateFields); +} //getMilliseconds() + +JSValueRef JSTZDate::getMinutes(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception) { + LoggerD("<<<"); + + TZDate::TZDateFields dateFields = TZDate::TZDATE_MINUTE; + return getTZDateValue(context, thisObject, argumentCount, arguments, exception, dateFields); +} //getMinutes() + +JSValueRef JSTZDate::getMonth(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception) { + LoggerD("<<<"); + TZDate::TZDateFields dateFields = TZDate::TZDATE_MONTH; + return getTZDateValue(context, thisObject, argumentCount, arguments, exception, dateFields); +} //getMonth() + +JSValueRef JSTZDate::getSeconds(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception) { + LoggerD("<<<"); + + TZDate::TZDateFields dateFields = TZDate::TZDATE_SECOND; + return getTZDateValue(context, thisObject, argumentCount, arguments, exception, dateFields); +} //getSeconds() + +JSValueRef JSTZDate::getTZDateValue(JSContextRef context, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception, + TZDate::TZDateFields dateFields) { + TimeUtilConverter converter(context); + try { + TZDatePrivObject* privateObject = static_cast<TZDatePrivObject*> (JSObjectGetPrivate(thisObject)); + + if (privateObject == NULL) { + LoggerE(">>> NULL Exception"); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + TZDatePtr tzDate(privateObject->getObject()); + long retVal = tzDate->get(dateFields); + + LoggerD(">>> retVal:" << retVal); + return converter.toJSValueRef(static_cast<int> (retVal)); + } Catch(NullPointerException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch(WrtDeviceApis::Commons::UnknownException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + + return converter.toJSValueRef(0); +} + +JSValueRef JSTZDate::setDate(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception) { + LoggerD("<<<"); + + TZDate::TZDateFields dateFields = TZDate::TZDATE_DATE; + + try{ + setTZDateValue(context, thisObject, argumentCount, arguments, exception, dateFields); + } catch(const BasePlatformException& err){ + return JSWebAPIErrorFactory::postException(context, exception, err); + } Catch(NullPointerException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch(WrtDeviceApis::Commons::UnknownException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (InvalidArgumentException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch(ConversionException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + + return JSValueMakeUndefined(context); +} //setDate() + +JSValueRef JSTZDate::setFullYear(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception) { + LoggerD("<<<"); + + TZDate::TZDateFields dateFields = TZDate::TZDATE_YEAR; + + try{ + setTZDateValue(context, thisObject, argumentCount, arguments, exception, dateFields); + } catch(const BasePlatformException& err){ + return JSWebAPIErrorFactory::postException(context, exception, err); + } Catch(NullPointerException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch(WrtDeviceApis::Commons::UnknownException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch(ConversionException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + + return JSValueMakeUndefined(context); +} //setFullYear() + +JSValueRef JSTZDate::setHours(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception) { + LoggerD("<<<"); + + TZDate::TZDateFields dateFields = TZDate::TZDATE_HOUR_OF_DAY; + + Try { + setTZDateValue(context, thisObject, argumentCount, arguments, exception, dateFields); + } catch(const BasePlatformException& err){ + return JSWebAPIErrorFactory::postException(context, exception, err); + }Catch(NullPointerException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch(WrtDeviceApis::Commons::UnknownException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch(ConversionException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + + return JSValueMakeUndefined(context); +} //setHours() + +JSValueRef JSTZDate::setMilliseconds(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception) { + LoggerD("<<<"); + + TZDate::TZDateFields dateFields = TZDate::TZDATE_MILLISECOND; + + Try{ + setTZDateValue(context, thisObject, argumentCount, arguments, exception, dateFields); + } catch(const BasePlatformException& err){ + return JSWebAPIErrorFactory::postException(context, exception, err); + }Catch(NullPointerException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch(WrtDeviceApis::Commons::UnknownException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch(ConversionException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + + return JSValueMakeUndefined(context); +} //setMilliseconds() + +JSValueRef JSTZDate::setMinutes(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception) { + LoggerD("<<<"); + + TZDate::TZDateFields dateFields = TZDate::TZDATE_MINUTE; + + Try { + setTZDateValue(context, thisObject, argumentCount, arguments, exception, dateFields); + } catch(const BasePlatformException& err){ + return JSWebAPIErrorFactory::postException(context, exception, err); + }Catch(NullPointerException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch(WrtDeviceApis::Commons::UnknownException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch(ConversionException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + + return JSValueMakeUndefined(context); +} //setMinutes() + +JSValueRef JSTZDate::setMonth(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception) { + LoggerD("<<<"); + + TZDate::TZDateFields dateFields = TZDate::TZDATE_MONTH; + + Try { + setTZDateValue(context, thisObject, argumentCount, arguments, exception, dateFields); + } catch(const BasePlatformException& err){ + return JSWebAPIErrorFactory::postException(context, exception, err); + }Catch(NullPointerException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch(WrtDeviceApis::Commons::UnknownException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch(ConversionException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + + return JSValueMakeUndefined(context); +} //setMonth() + +JSValueRef JSTZDate::setSeconds(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception) { + LoggerD("<<<"); + + TZDate::TZDateFields dateFields = TZDate::TZDATE_SECOND; + + Try { + setTZDateValue(context, thisObject, argumentCount, arguments, exception, dateFields); + } catch(const BasePlatformException& err){ + return JSWebAPIErrorFactory::postException(context, exception, err); + }Catch(NullPointerException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch(WrtDeviceApis::Commons::UnknownException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch(ConversionException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + + return JSValueMakeUndefined(context); +} //setSeconds() + + +JSValueRef JSTZDate::setTZDateValue(JSContextRef context, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception, TZDate::TZDateFields dateFields) { + ArgumentValidator validator(context, argumentCount, arguments); + long data = validator.toLong(0); + + + TZDatePrivObject* privateObject = static_cast<TZDatePrivObject*> (JSObjectGetPrivate(thisObject)); + + if (privateObject == NULL) { + LoggerE(">>> NULL Exception"); + ThrowMsg(NullPointerException, "privateObject is NULL"); + } + + TZDatePtr tzDate(privateObject->getObject()); + tzDate->set(dateFields,data); + + return JSValueMakeUndefined(context); +} //setTZDateValue + +JSValueRef JSTZDate::getUTCDate(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LoggerD("Entered"); + return getUTCTZDateValue(context, thisObject, argumentCount, TZDate::TZDATE_DATE, exception); +} + +JSValueRef JSTZDate::getUTCDay(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LoggerD("Entered"); + return getUTCTZDateValue(context, thisObject, argumentCount, TZDate::TZDATE_DAY_OF_WEEK, exception); +} + +JSValueRef JSTZDate::getUTCFullYear(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LoggerD("Entered"); + return getUTCTZDateValue(context, thisObject, argumentCount, TZDate::TZDATE_YEAR, exception); +} + +JSValueRef JSTZDate::getUTCHours(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LoggerD("Entered"); + return getUTCTZDateValue(context, thisObject, argumentCount, TZDate::TZDATE_HOUR_OF_DAY, exception); +} + +JSValueRef JSTZDate::getUTCMilliseconds(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LoggerD("Entered"); + return getUTCTZDateValue(context, thisObject, argumentCount, TZDate::TZDATE_MILLISECOND, exception); +} + +JSValueRef JSTZDate::getUTCMinutes(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LoggerD("Entered"); + return getUTCTZDateValue(context, thisObject, argumentCount, TZDate::TZDATE_MINUTE, exception); +} + +JSValueRef JSTZDate::getUTCMonth(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LoggerD("Entered"); + return getUTCTZDateValue(context, thisObject, argumentCount, TZDate::TZDATE_MONTH, exception); +} + +JSValueRef JSTZDate::getUTCSeconds(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LoggerD("Entered"); + return getUTCTZDateValue(context, thisObject, argumentCount, TZDate::TZDATE_SECOND, exception); +} + +JSValueRef JSTZDate::getUTCTZDateValue(JSContextRef context, JSObjectRef thisObject, size_t argumentCount, TZDate::TZDateFields DateFields, JSValueRef * exception) { + LoggerD("Entered"); + TimeUtilConverter converter(context); + Try { + TZDatePrivObject* privateObject = static_cast<TZDatePrivObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LoggerE("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + TZDatePtr tzDate(privateObject->getObject()); + long result = tzDate->getUTC(DateFields); + + return converter.toJSValueRefLong(result); + } Catch(NullPointerException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch(WrtDeviceApis::Commons::UnknownException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (InvalidArgumentException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + + return converter.toJSValueRef(0); +} + +JSValueRef JSTZDate::setUTCDate(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LoggerD("Entered"); + + return setUTCTZDateValue(context, thisObject, argumentCount, arguments, TZDate::TZDATE_DATE, exception); +} + +JSValueRef JSTZDate::setUTCFullYear(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LoggerD("Entered"); + + return setUTCTZDateValue(context, thisObject, argumentCount, arguments, TZDate::TZDATE_YEAR, exception); +} + +JSValueRef JSTZDate::setUTCHours(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LoggerD("Entered"); + + return setUTCTZDateValue(context, thisObject, argumentCount, arguments, TZDate::TZDATE_HOUR_OF_DAY, exception); +} + +JSValueRef JSTZDate::setUTCMilliseconds(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LoggerD("Entered"); + + return setUTCTZDateValue(context, thisObject, argumentCount, arguments, TZDate::TZDATE_MILLISECOND, exception); +} + +JSValueRef JSTZDate::setUTCMinutes(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LoggerD("Entered"); + + return setUTCTZDateValue(context, thisObject, argumentCount, arguments, TZDate::TZDATE_MINUTE, exception); +} + +JSValueRef JSTZDate::setUTCMonth(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LoggerD("Entered"); + + return setUTCTZDateValue(context, thisObject, argumentCount, arguments, TZDate::TZDATE_MONTH, exception); +} + +JSValueRef JSTZDate::setUTCSeconds(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LoggerD("Entered"); + + return setUTCTZDateValue(context, thisObject, argumentCount, arguments, TZDate::TZDATE_SECOND, exception); +} + +JSValueRef JSTZDate::setUTCTZDateValue(JSContextRef context, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], TZDate::TZDateFields dateFields, JSValueRef * exception) { + LoggerD("Entered"); + Try { + TimeUtilConverter converter(context); + + long data = 0; + if (argumentCount == 0) + data = converter.toLong(JSValueMakeUndefined(context)); + else + data = converter.toLong(arguments[0]); + + + TZDatePrivObject* privateObject = static_cast<TZDatePrivObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LoggerE("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + TZDatePtr tzDate(privateObject->getObject()); + tzDate->setUTC(dateFields, data); + } Catch(NullPointerException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch(WrtDeviceApis::Commons::UnknownException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch(ConversionException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + + return JSValueMakeUndefined(context); +} + +JSValueRef JSTZDate::getTimezoneAbbreviation(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LoggerD("entered"); + TimeUtilConverter converter(context); + Try { + TZDatePrivObject* privateObject = static_cast<TZDatePrivObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LoggerE("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + TZDatePtr tzDate(privateObject->getObject()); + + std::string result; + + return converter.toJSValueRef(tzDate->getTimezoneAbbreviation()); + } Catch(NullPointerException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch(WrtDeviceApis::Commons::UnknownException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return converter.toJSValueRef("Invalid Date"); +} + +JSValueRef JSTZDate::secondsFromUTC(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LoggerD("entered"); + + Try { + TZDatePrivObject* privateObject = static_cast<TZDatePrivObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LoggerE("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + TimeUtilConverter converter(context); + + TZDatePtr tzDate(privateObject->getObject()); + + return converter.toJSValueRefLong(tzDate->secondsFromUTC()); + } Catch(NullPointerException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch(WrtDeviceApis::Commons::UnknownException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, _rethrown_exception.GetMessage()); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown Error"); +} +JSValueRef JSTZDate::isDST(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LoggerD("entered"); + Try { + TZDatePrivObject* privateObject = static_cast<TZDatePrivObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LoggerE("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + TimeUtilConverter converter(context); + + TZDatePtr tzDate(privateObject->getObject()); + + return converter.toJSValueRef(tzDate->isDST()); + } Catch(NullPointerException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch(WrtDeviceApis::Commons::UnknownException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, _rethrown_exception.GetMessage()); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown Error"); +} + +JSValueRef JSTZDate::getPreviousDSTTransition(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LoggerD("entered"); + + Try { + TZDatePrivObject* privateObject = static_cast<TZDatePrivObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LoggerE("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + TimeUtilConverter converter(context); + + TZDatePtr tzDate(privateObject->getObject()); + + TZDateProperties resultDate = tzDate->getDSTTransition(TZDate::PREV_TRANSITION); + if (resultDate.timezone == "") + return JSValueMakeNull(context); + + return createJSObject(context, resultDate); + } Catch(NullPointerException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch(WrtDeviceApis::Commons::UnknownException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, _rethrown_exception.GetMessage()); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown Error"); +} + +JSValueRef JSTZDate::getNextDSTTransition(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LoggerD("entered"); + + Try { + TZDatePrivObject* privateObject = static_cast<TZDatePrivObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LoggerE("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + TimeUtilConverter converter(context); + + TZDatePtr tzDate(privateObject->getObject()); + + TZDateProperties resultDate = tzDate->getDSTTransition(TZDate::NEXT_TRANSITION); + if (resultDate.timezone == "") + return JSValueMakeNull(context); + + return createJSObject(context, resultDate); + } Catch(NullPointerException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch(WrtDeviceApis::Commons::UnknownException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, _rethrown_exception.GetMessage()); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown Error"); +} + +} //DeviceAPI +} //Time +#undef min diff --git a/wearable_src/TimeUtil/JSTZDate.h b/wearable_src/TimeUtil/JSTZDate.h new file mode 100755 index 0000000..b8e5065 --- /dev/null +++ b/wearable_src/TimeUtil/JSTZDate.h @@ -0,0 +1,224 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _JS_TIZEN_TZDATE_H_ +#define _JS_TIZEN_TZDATE_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/PrivateObject.h> +#include "TZDate.h" + +namespace DeviceAPI { +namespace Time { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject<TZDatePtr, WrtDeviceApis::CommonsJavaScript::NoOwnership> TZDatePrivObject; + +class JSTZDate +{ +public: + + static const JSClassDefinition* getClassInfo(); + + static const JSClassRef getClassRef(); + static JSObjectRef createJSObject(JSContextRef context, TZDatePtr tzDate); + static JSObjectRef createJSObject(JSContextRef context, const bool isNotNull = true); + static JSObjectRef createJSObject(JSContextRef context, const std::string &timezone); + static JSObjectRef createJSObject(JSContextRef context, const double milliseconds, const std::string &timezone); + static JSObjectRef createJSObject(JSContextRef context, const TZDateProperties &properties); + static JSObjectRef createJSObject(JSContextRef context, const long year, const long month, const long day, const long hours, const long minutes, const long seconds, const long milliseconds, const std::string &timezone); + static JSObjectRef createJSObject(JSContextRef context, const std::string &dateString, const double milliseconds, const std::string &timezone); + + + static JSObjectRef constructor(JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + +private: + enum CompareType { + DIFFERENCE, + EQUALSTO, + EARLIERTHAN, + LATERTHAN + }; + /** + * This member variable contains the values which has to be passed when + * the this class is embedded into JS Engine. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This member variable contains the initialization values for the + * properties of this class. The values are given according to the + * data structure JSPropertySpec. + */ + + static JSClassRef m_jsClassRef; + + /** + * 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); + + static JSValueRef getTimezone(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef toTimezone(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + + static JSValueRef diffTZDate(JSContextRef context, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception, CompareType type); + + static JSValueRef difference(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef equalsTo(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef earlierThan(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef laterThan(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef addDuration(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef toUTC(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef toLocalTimezone(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + + static JSValueRef toLocaleDateString(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef toLocaleTimeString(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef toLocaleString(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef toDateString(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef toTimeString(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef toString(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + + static JSValueRef getDate(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception); + + static JSValueRef getDay(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception); + + static JSValueRef getFullYear(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception); + + static JSValueRef getHours(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception); + + static JSValueRef getMilliseconds(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception); + + static JSValueRef getMinutes(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception); + + static JSValueRef getMonth(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception); + + static JSValueRef getSeconds(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception); + + static JSValueRef setTZDateValue(JSContextRef context, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception, + TZDate::TZDateFields dateFields); + + static JSValueRef getTZDateValue(JSContextRef context, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception, + TZDate::TZDateFields dateFields); + + static JSValueRef setDate(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception); + + static JSValueRef setFullYear(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception); + + static JSValueRef setHours(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception); + + static JSValueRef setMilliseconds(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception); + + static JSValueRef setMinutes(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception); + + static JSValueRef setMonth(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception); + + static JSValueRef setSeconds(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], + JSValueRef * exception); + + static JSValueRef getUTCTZDateValue(JSContextRef context, JSObjectRef thisObject, size_t argumentCount, + TZDate::TZDateFields DateFields, JSValueRef * exception); + static JSValueRef getUTCDate(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef getUTCDay(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef getUTCFullYear(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef getUTCHours(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef getUTCMilliseconds(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef getUTCMinutes(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef getUTCMonth(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef getUTCSeconds(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + + static JSValueRef setUTCTZDateValue(JSContextRef context, JSObjectRef thisObject, size_t argumentCount, + const JSValueRef arguments[], TZDate::TZDateFields dateFields, JSValueRef * exception); + static JSValueRef setUTCDate(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef setUTCFullYear(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef setUTCHours(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef setUTCMilliseconds(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef setUTCMinutes(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef setUTCMonth(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef setUTCSeconds(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + + static JSValueRef getTimezoneAbbreviation(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef secondsFromUTC(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef isDST(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef getPreviousDSTTransition(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef getNextDSTTransition(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, + size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); +}; + +} +} + +#endif /* _JS_TIZEN_DATETIME_H_ */ diff --git a/wearable_src/TimeUtil/JSTimeDuration.cpp b/wearable_src/TimeUtil/JSTimeDuration.cpp new file mode 100755 index 0000000..ebcde92 --- /dev/null +++ b/wearable_src/TimeUtil/JSTimeDuration.cpp @@ -0,0 +1,349 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <string> +#include <memory> +#include <cmath> +#include <Commons/Exception.h> +#include <CommonsJavaScript/Utils.h> +#include <CommonsJavaScript/JSCallbackManager.h> +#include <JSUtil.h> +#include <JSWebAPIErrorFactory.h> +#include "JSTimeDuration.h" +#include "TimeUtilConverter.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Time { + + +using namespace DeviceAPI::Common; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +#define TIZEN_TIMEDURATION_LENGTH "length" +#define TIZEN_TIMEDURATION_UNIT "unit" + +JSClassDefinition JSTimeDuration::m_classInfo = { + 0, + kJSClassAttributeNone, + "TimeDuration", + 0, + m_property, + m_function, + initialize, + finalize, + NULL, //HasProperty, + NULL, //GetProperty, + setProperty, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, + NULL, //ConvertToType +}; + + +JSStaticFunction JSTimeDuration::m_function[] = { + {"difference", JSTimeDuration::difference, kJSPropertyAttributeNone}, + {"equalsTo", JSTimeDuration::equalsTo, kJSPropertyAttributeNone}, + {"lessThan", JSTimeDuration::lessThan, kJSPropertyAttributeNone}, + {"greaterThan", JSTimeDuration::greaterThan, kJSPropertyAttributeNone}, +}; + +JSStaticValue JSTimeDuration::m_property[] = +{ + //TimdDurationProperties + {TIZEN_TIMEDURATION_LENGTH, getProperty, setProperty, kJSPropertyAttributeNone}, + {TIZEN_TIMEDURATION_UNIT, getProperty, setProperty, kJSPropertyAttributeNone}, + { 0, 0, 0, 0 } +}; + +const JSClassRef JSTimeDuration::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSTimeDuration::getClassInfo() +{ + return &m_classInfo; +} + +JSClassRef JSTimeDuration::m_jsClassRef = JSClassCreate(JSTimeDuration::getClassInfo()); + +void JSTimeDuration::initialize(JSContextRef context, JSObjectRef object) +{ + LoggerD("entered Nothing to do."); +} + +void JSTimeDuration::finalize(JSObjectRef object) +{ + TimeDurationPrivObject* priv = static_cast<TimeDurationPrivObject*>(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + LoggerD("Deleting TimeDuration"); + delete priv; +} + +JSValueRef JSTimeDuration::getProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception) +{ + LoggerD("Enter"); + + Try { + TimeUtilConverter convert(context); + + LoggerD("propertyName : " << convert.toString(propertyName)); + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_TIMEDURATION_LENGTH)) { + return convert.toJSValueRef(static_cast<double>(convert.getDurationLength(object))); + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_TIMEDURATION_UNIT)) { + return convert.toJSValueRef(convert.toDurationUnitString(convert.getDurationUnit(object))); + } + } Catch (ConversionException) { + LoggerE("ConversionException: " << _rethrown_exception.GetMessage()); + } Catch (InvalidArgumentException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSValueMakeUndefined(context); +} + +bool JSTimeDuration::setProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + LoggerD("Enter"); + + Try { + TimeDurationPrivObject* privateObject = static_cast<TimeDurationPrivObject*>(JSObjectGetPrivate(object)); + if (!privateObject) { + LoggerE("Private object is not set."); + ThrowMsg(NullPointerException, "Private object not initialized"); + } + + DurationPropertiesPtr duration = privateObject->getObject(); + TimeUtilConverter convert(context); + + if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_TIMEDURATION_LENGTH)) { + duration->length = convert.toLongLong(value); + return true; + } else if (JSStringIsEqualToUTF8CString(propertyName, TIZEN_TIMEDURATION_UNIT)) { + std::string unitStr = convert.toString(value); + short unit = convert.toDurationUnit(unitStr); + if ((unit == MSECS_UNIT) && (unitStr != "MSECS")) + ThrowMsg(InvalidArgumentException, unitStr + "is not one of TimeDurationUnit"); + duration->unit = unit; + return true; + } + } Catch (NullPointerException) { + LoggerE("NullPointerException: " << _rethrown_exception.GetMessage()); + } Catch (ConversionException) { + LoggerE("ConversionException: " << _rethrown_exception.GetMessage()); + } Catch (InvalidArgumentException) { + LoggerE("InvalidArgumentException: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return false; +} + +JSObjectRef JSTimeDuration::createJSObject(JSContextRef context, + const DurationProperties &durations) +{ + DurationPropertiesPtr durationProps(new DurationProperties(durations)); + TimeDurationPrivObject *priv = new TimeDurationPrivObject(context, durationProps); + + if (!priv) { + ThrowMsg(NullPointerException, "Can not new an object"); + } + return JSObjectMake(context, getClassRef(), priv); +} + +JSObjectRef JSTimeDuration::createJSObject(JSContextRef context, + const DurationPropertiesPtr duration) +{ + TimeDurationPrivObject *priv = new TimeDurationPrivObject(context, duration); + if (!priv) { + ThrowMsg(NullPointerException, "Private object is null."); + } + return JSObjectMake(context, getClassRef(), priv); +} + +JSObjectRef JSTimeDuration::constructor(JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception) { + LoggerD("entered"); + TimeUtilConverter convert(ctx); + JSObjectRef timeDuration = NULL; + Try { + DurationProperties duration; + if (argumentCount == 0) + duration.length = convert.toLongLong(JSValueMakeUndefined(ctx)); + else + duration.length = convert.toLongLong(arguments[0]); + + if (argumentCount > 1) { + if (!JSValueIsUndefined(ctx, arguments[1]) && !JSValueIsNull(ctx, arguments[1])) { + duration.unit = convert.toDurationUnit(convert.toString(arguments[1])); + } + } + timeDuration = createJSObject(ctx, duration); + } Catch(NullPointerException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch(WrtDeviceApis::Commons::UnknownException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch(ConversionException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (InvalidArgumentException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerW("Trying to get incorrect value"); + } + if (timeDuration == NULL) + timeDuration = JSObjectMake(ctx, getClassRef(), NULL); + + JSStringRef ctorName = JSStringCreateWithUTF8CString("constructor"); + JSObjectSetProperty(ctx, timeDuration, ctorName, constructor, + kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete | kJSPropertyAttributeDontEnum, NULL); + JSStringRelease(ctorName); + return timeDuration; +} + +JSValueRef JSTimeDuration::diffTimeDuration(JSContextRef context, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception, CompareType type) { + LoggerD("entered"); + + TimeDurationPrivObject* privateObject = static_cast<TimeDurationPrivObject*>(JSObjectGetPrivate(thisObject)); + if (!privateObject) { + LoggerE("Private object is not set."); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + TimeUtilConverter converter(context); + + DurationProperties first = converter.getDurationProperties(thisObject); + DurationProperties second; + if (argumentCount == 0) + second= converter.getDurationProperties(JSValueMakeUndefined(context)); + else + second= converter.getDurationProperties(arguments[0]); + + DurationProperties diff; + if (first.unit > second.unit) { + long long firstLength = converter.convertDurationLength(first, second.unit); + diff.unit = second.unit; + diff.length = firstLength - second.length; + } else { + long long secondLength = converter.convertDurationLength(second, first.unit); + diff.unit = first.unit; + diff.length = first.length - secondLength; + } + + switch (type) { + case EQUALSTO: + { + if (diff.length == 0) + return converter.toJSValueRef(true); + else + return converter.toJSValueRef(false); + } + case LESSTHAN: + { + if (diff.length < 0) + return converter.toJSValueRef(true); + else + return converter.toJSValueRef(false); + } + case GREATERTHAN: + { + if (diff.length > 0) + return converter.toJSValueRef(true); + else + return converter.toJSValueRef(false); + } + case DIFFERENCE: + default: + return converter.makeDurationObject(converter.optimizedTimeDuration(diff)); + } +} + +JSValueRef JSTimeDuration::difference(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LoggerD("Entered"); + Try { + return diffTimeDuration(context, thisObject, argumentCount, arguments, exception, DIFFERENCE); + } Catch(ConversionException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown Error"); +} + +JSValueRef JSTimeDuration::equalsTo(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LoggerD("Entered"); + Try { + return diffTimeDuration(context, thisObject, argumentCount, arguments, exception, EQUALSTO); + } Catch(ConversionException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown Error"); +} + +JSValueRef JSTimeDuration::lessThan(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LoggerD("Entered"); + Try { + return diffTimeDuration(context, thisObject, argumentCount, arguments, exception, LESSTHAN); + } Catch(ConversionException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown Error"); +} + +JSValueRef JSTimeDuration::greaterThan(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LoggerD("Entered"); + Try { + return diffTimeDuration(context, thisObject, argumentCount, arguments, exception, GREATERTHAN); + } Catch(ConversionException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown Error"); +} + +} //Time +} //DeviceAPI diff --git a/wearable_src/TimeUtil/JSTimeDuration.h b/wearable_src/TimeUtil/JSTimeDuration.h new file mode 100755 index 0000000..6d2565c --- /dev/null +++ b/wearable_src/TimeUtil/JSTimeDuration.h @@ -0,0 +1,117 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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_PLUGINS_TIZEN_JS_TIMEDURATION_H_ +#define WRT_PLUGINS_TIZEN_JS_TIMEDURATION_H_ + +#include <dpl/shared_ptr.h> +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/PrivateObject.h> +#include "DurationProperties.h" + +namespace DeviceAPI { +namespace Time { +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT< + DurationPropertiesPtr>:: + Type TimeDurationPrivObject; + +/** + * @class JSTimeDuration + * @brief This class is javascript extension + * + */ +class JSTimeDuration +{ + public: + /** + * Gets object's class description. + */ + static const JSClassDefinition* getClassInfo(); + + /** + * Gets class definition reference. + * @remarks New instance of JSClassRef is created (only once) if none was + * @remarks set before. + * @return Class reference. + */ + static const JSClassRef getClassRef(); + static JSObjectRef createJSObject(JSContextRef context, const DurationProperties &durations); + static JSObjectRef createJSObject(JSContextRef context, const DurationPropertiesPtr duration); + + static JSObjectRef constructor(JSContextRef ctx, JSObjectRef constructor, size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception); + private: + enum CompareType { + DIFFERENCE, + EQUALSTO, + LESSTHAN, + GREATERTHAN + }; + /** + * 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); + + /** + * Getters for properties + */ + static JSValueRef getProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception); + + static bool setProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef value, JSValueRef* exception); + + static JSValueRef diffTimeDuration(JSContextRef context, JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception, CompareType type); + static JSValueRef difference(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef equalsTo(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef lessThan(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + static JSValueRef greaterThan(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception); + + /** + * This structure contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + static JSClassRef m_jsClassRef; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_function[]; + + /** + * This member variable contains the initialization values for the + * properties of this class. The values are given according to the + * data structure JSPropertySpec. + */ + static JSStaticValue m_property[]; +}; +} +} + +#endif //WRT_PLUGINS_TIZEN_JS_TIMEDURATION_H_
\ No newline at end of file diff --git a/wearable_src/TimeUtil/JSTimeUtil.cpp b/wearable_src/TimeUtil/JSTimeUtil.cpp new file mode 100755 index 0000000..bb985ca --- /dev/null +++ b/wearable_src/TimeUtil/JSTimeUtil.cpp @@ -0,0 +1,436 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <string> +#include <ctime> + +#include <Commons/Exception.h> +#include <CommonsJavaScript/Utils.h> +#include <CommonsJavaScript/JSCallbackManager.h> +#include <JSWebAPIErrorFactory.h> +#include <ArgumentValidator.h> +#include <PlatformException.h> +#include <GlobalContextManager.h> +#include <CallbackUserData.h> +#include "JSTimeUtil.h" +#include "JSTZDate.h" +#include "TimeUtilConverter.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Time { + + +using namespace DeviceAPI::Common; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; +JSClassDefinition JSTimeUtil::m_classInfo = { + 0, + kJSClassAttributeNone, + "TimeUtil", + 0, + NULL, + m_function, + initialize, + finalize, + NULL, //HasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //GetPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + hasInstance, + NULL, //ConvertToType +}; + +JSStaticFunction JSTimeUtil::m_function[] = { + { "getCurrentDateTime", JSTimeUtil::getCurrentDateTime, kJSPropertyAttributeNone }, + { "getLocalTimezone", JSTimeUtil::getLocalTimezone, kJSPropertyAttributeNone }, + { "getAvailableTimezones", JSTimeUtil::getAvailableTimezones, kJSPropertyAttributeNone }, + { "getDateFormat", JSTimeUtil::getDateFormat, kJSPropertyAttributeNone }, + { "getTimeFormat", JSTimeUtil::getTimeFormat, kJSPropertyAttributeNone }, + { "isLeapYear", JSTimeUtil::isLeapYear, kJSPropertyAttributeNone}, + { "setDateTimeChangeListener", JSTimeUtil::setDateTimeChangeListener, kJSPropertyAttributeNone }, + { "unsetDateTimeChangeListener", JSTimeUtil::unsetDateTimeChangeListener, kJSPropertyAttributeNone}, + { "setTimezoneChangeListener", JSTimeUtil::setTimezoneChangeListener, kJSPropertyAttributeNone }, + { "unsetTimezoneChangeListener", JSTimeUtil::unsetTimezoneChangeListener, kJSPropertyAttributeNone}, + { 0, 0, 0 } +}; + +const JSClassRef JSTimeUtil::getClassRef() +{ + if (!m_jsClassRef) { + m_jsClassRef = JSClassCreate(&m_classInfo); + } + return m_jsClassRef; +} + +const JSClassDefinition* JSTimeUtil::getClassInfo() +{ + return &m_classInfo; +} + +JSClassRef JSTimeUtil::m_jsClassRef = JSClassCreate(JSTimeUtil::getClassInfo()); + +void JSTimeUtil::initialize(JSContextRef context, JSObjectRef object) +{ + TimeUtilPrivObject* priv = static_cast<TimeUtilPrivObject*>(JSObjectGetPrivate(object)); + if (!priv) { + TimeUtilPtr timeutil(new TimeUtil()); + priv = new TimeUtilPrivObject( context, timeutil); + if(!JSObjectSetPrivate(object, static_cast<void*>(priv))) { + LoggerE("Object can't store private data."); + delete priv; + } + } + + LoggerD("JSTimeUtil::initialize "); +} + +void JSTimeUtil::finalize(JSObjectRef object) +{ + TimeUtilPrivObject* priv = static_cast<TimeUtilPrivObject*>(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + LoggerD("Deleting timeutil"); + if (priv) + delete priv; +} + +bool JSTimeUtil::hasInstance(JSContextRef context, + JSObjectRef constructor, + JSValueRef possibleInstance, + JSValueRef* exception) +{ + return JSValueIsObjectOfClass(context, possibleInstance, getClassRef()); +} + +JSValueRef JSTimeUtil::getCurrentDateTime(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("Entered "); + Try { + TimeUtilPrivObject* privateObject = static_cast<TimeUtilPrivObject*>(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LoggerE("private object is null"); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + return JSTZDate::createJSObject(context); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch(NullPointerException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown Error"); +} + +JSValueRef JSTimeUtil::getLocalTimezone(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("Entered "); + Try { + TimeUtilPrivObject* privateObject = + static_cast<TimeUtilPrivObject*>(JSObjectGetPrivate( + thisObject)); + if (NULL == privateObject) { + ThrowMsg(NullPointerException, "Can not new an object"); + } + + TimeUtilPtr timeutil(privateObject->getObject()); + std::string localTimezone = timeutil->getLocalTimezone(); + + TimeUtilConverter converter(context); + + return converter.toJSValueRef(localTimezone); + } Catch(NullPointerException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown Error"); +} + +JSValueRef JSTimeUtil::getAvailableTimezones(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("entered"); + Try { + TimeUtilPrivObject* privateObject = + static_cast<TimeUtilPrivObject*>(JSObjectGetPrivate( + thisObject)); + if (NULL == privateObject) { + ThrowMsg(NullPointerException, "Can not new an object"); + } + + TimeUtilConverter converter(context); + + TimeUtilPtr timeutil(privateObject->getObject()); + + std::vector<std::string> timezones = timeutil->getAvailableTimezones(); + std::vector<JSValueRef> timezonesArray; + unsigned short timezonesCount = timezones.size(); + for (int i = 0; i < timezonesCount; ++i) { + timezonesArray.push_back(converter.toJSValueRef(timezones[i])); + } + + return converter.toJSValueRef(timezonesArray); + } Catch (NullPointerException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown Error"); +} + +JSValueRef JSTimeUtil::getDateFormat(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("entered"); + try + { + TimeUtilConverter converter(context); + ArgumentValidator validator(context, argumentCount, arguments); + bool value = validator.toBool(0,true,false); + + TimeUtilPrivObject* privateObject = + static_cast<TimeUtilPrivObject*>(JSObjectGetPrivate( + thisObject)); + if (NULL == privateObject) { + ThrowMsg(NullPointerException, "Can not new an object"); + } + + TimeUtilPtr timeutil(privateObject->getObject()); + std::string dateformat = timeutil->getDateFormat(value); + + return converter.toJSValueRef(dateformat); + } catch(const BasePlatformException& err){ + return JSWebAPIErrorFactory::postException(context, exception, err); + } Catch(ConversionException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (NullPointerException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown Error"); +} + +JSValueRef JSTimeUtil::getTimeFormat(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("entered"); + Try { + TimeUtilPrivObject* privateObject = + static_cast<TimeUtilPrivObject*>(JSObjectGetPrivate( + thisObject)); + + if (NULL == privateObject) { + ThrowMsg(NullPointerException, "Can not new an object"); + } + + TimeUtilPtr timeutil(privateObject->getObject()); + std::string timeFormat = timeutil->getTimeFormat(); + TimeUtilConverter converter(context); + + return converter.toJSValueRef(timeFormat); + } Catch (NullPointerException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown Error"); +} + +JSValueRef JSTimeUtil::isLeapYear(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LoggerD("Entered"); + try{ + TimeUtilConverter converter(context); + ArgumentValidator validator(context, argumentCount, arguments); + long year = validator.toLong(0); + + if (year % 4 != 0) + return converter.toJSValueRef(false); + if (year % 400 == 0) + return converter.toJSValueRef(true); + if (year % 100 == 0) + return converter.toJSValueRef(false); + + return converter.toJSValueRef(true); + }catch(const BasePlatformException& err){ + return JSWebAPIErrorFactory::postException(context, exception, err); + } Catch(ConversionException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown Error"); +} + +JSValueRef JSTimeUtil::setDateTimeChangeListener(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LoggerD("Entered"); + try{ + ArgumentValidator validator(context, argumentCount, arguments); + TimeUtilPrivObject* privateObject = static_cast<TimeUtilPrivObject*>(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LoggerE("private object is null"); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + if (!validator.toFunction(0)) + throw TypeMismatchException("Callback is not function."); + CallbackUserData *callback( + new CallbackUserData(GlobalContextManager::getInstance()->getGlobalContext(context))); + if (!callback) + throw UnknownException("Failed Memory allocation"); + callback->setSuccessCallback(arguments[0]); + TimeUtilPtr timeutil(privateObject->getObject()); + timeutil->setDateTimeChangeListener(callback); + return JSValueMakeUndefined(context); + } Catch(TypeMismatchException) { + LoggerE(_rethrown_exception.getName() << ": " << _rethrown_exception.getMessage()); + return JSWebAPIErrorFactory::postException(context, exception, _rethrown_exception); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown Error"); +} + +JSValueRef JSTimeUtil::unsetDateTimeChangeListener(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LoggerD("Entered"); + try{ + TimeUtilPrivObject* privateObject = static_cast<TimeUtilPrivObject*>(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LoggerE("private object is null"); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + TimeUtilPtr timeutil(privateObject->getObject()); + timeutil->unsetDateTimeChangeListener(); + return JSValueMakeUndefined(context); + }catch(const BasePlatformException& err){ + LoggerE(err.getName() << ": " << err.getMessage()); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown Error"); +} + +JSValueRef JSTimeUtil::setTimezoneChangeListener(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LoggerD("Entered"); + try{ + ArgumentValidator validator(context, argumentCount, arguments); + TimeUtilPrivObject* privateObject = static_cast<TimeUtilPrivObject*>(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LoggerE("private object is null"); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + if (!validator.toFunction(0)) + throw TypeMismatchException("Callback is not function."); + CallbackUserData *callback( + new CallbackUserData(GlobalContextManager::getInstance()->getGlobalContext(context))); + if (!callback) + throw UnknownException("Failed Memory allocation"); + callback->setSuccessCallback(arguments[0]); + TimeUtilPtr timeutil(privateObject->getObject()); + timeutil->setTimezoneChangeListener(callback); + return JSValueMakeUndefined(context); + } Catch(TypeMismatchException) { + LoggerE(_rethrown_exception.getName() << ": " << _rethrown_exception.getMessage()); + return JSWebAPIErrorFactory::postException(context, exception, _rethrown_exception); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown Error"); +} + +JSValueRef JSTimeUtil::unsetTimezoneChangeListener(JSContextRef context, JSObjectRef function, + JSObjectRef thisObject, size_t argumentCount, const JSValueRef arguments[], JSValueRef * exception) { + LoggerD("Entered"); + try{ + TimeUtilPrivObject* privateObject = static_cast<TimeUtilPrivObject*>(JSObjectGetPrivate(thisObject)); + if (NULL == privateObject) { + LoggerE("private object is null"); + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::TYPE_MISMATCH_ERROR, "Type Mismatch"); + } + + TimeUtilPtr timeutil(privateObject->getObject()); + timeutil->unsetTimezoneChangeListener(); + return JSValueMakeUndefined(context); + }catch(const BasePlatformException& err){ + LoggerE(err.getName() << ": " << err.getMessage()); + } Catch (PlatformException) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } Catch (WrtDeviceApis::Commons::Exception) { + LoggerE("Exception: " << _rethrown_exception.GetMessage()); + } + return JSWebAPIErrorFactory::postException(context, exception, JSWebAPIErrorFactory::UNKNOWN_ERROR, "Unknown Error"); +} + +} //TimeUtil +} //DeviceAPI diff --git a/wearable_src/TimeUtil/JSTimeUtil.h b/wearable_src/TimeUtil/JSTimeUtil.h new file mode 100755 index 0000000..12dc7da --- /dev/null +++ b/wearable_src/TimeUtil/JSTimeUtil.h @@ -0,0 +1,169 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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_PLUGINS_TIZEN_JS_TIMEUTIL_H_ +#define WRT_PLUGINS_TIZEN_JS_TIMEUTIL_H_ + +#include <dpl/shared_ptr.h> +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/JSPendingOperationPrivateObject.h> +#include <CommonsJavaScript/PrivateObject.h> +#include "TimeUtil.h" + +namespace DeviceAPI { +namespace Time { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject<TimeUtilPtr, WrtDeviceApis::CommonsJavaScript::NoOwnership> TimeUtilPrivObject; + +/** + * @class JSTimeUtil + * @brief This class is javascript extension + * + */ +class JSTimeUtil +{ + public: + /** + * Gets object's class description. + */ + static const JSClassDefinition* getClassInfo(); + + /** + * Gets class definition reference. + * @remarks New instance of JSClassRef is created (only once) if none was + * @remarks set before. + * @return Class reference. + */ + static const JSClassRef getClassRef(); + + 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 an object is used as the target of an 'instanceof' expression. + */ + static bool hasInstance(JSContextRef ctx, + JSObjectRef constructor, + JSValueRef possibleInstance, + JSValueRef* exception); + + /** + * Get current date/time. + */ + static JSValueRef getCurrentDateTime(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + + /** + * Get local system timezone. + */ + static JSValueRef getLocalTimezone(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + /** + * Get asynchronously the timezones supported by the system. + */ + static JSValueRef getAvailableTimezones(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef getDateFormat(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef getTimeFormat(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef isLeapYear(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef * exception); + + static JSValueRef setDateTimeChangeListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef unsetDateTimeChangeListener(JSContextRef context, + JSObjectRef function, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef * exception); + + static JSValueRef setTimezoneChangeListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + + static JSValueRef unsetTimezoneChangeListener(JSContextRef context, + JSObjectRef object, + JSObjectRef thisObject, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception); + /** + * 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 JSClassRef m_jsClassRef; +}; +} +} + +#endif //WRT_PLUGINS_TIZEN_JS_TIMEUTIL_H_
\ No newline at end of file diff --git a/wearable_src/TimeUtil/TZDate.cpp b/wearable_src/TimeUtil/TZDate.cpp new file mode 100755 index 0000000..e2d36b6 --- /dev/null +++ b/wearable_src/TimeUtil/TZDate.cpp @@ -0,0 +1,919 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <Commons/Exception.h> +#include <unicode/timezone.h> +#include <unicode/vtzone.h> +#include <unicode/smpdtfmt.h> +#include "TZDate.h" +#include "TimeUtilTools.h" +#include <vconf.h> +#include <Logger.h> + +using namespace WrtDeviceApis; + +namespace DeviceAPI { +namespace Time { + +TZDate::TZDate(const bool isNotNull) +{ + LoggerD("entered"); + + if (isNotNull == FALSE) { + myCalendar = NULL; + } else { + UErrorCode ec = U_ZERO_ERROR; +#if 0 + TimeUtilTools util; + TimeZone *tz = util.makeTimeZone(timezone); + if (timezone) + free(timezone); + + if (isAvailableTimezone(tz)) + myCalendar = Calendar::createInstance(tz, ec); + else + myCalendar = Calendar::createInstance(ec); + + if (tz) + delete tz; + + if (U_SUCCESS(ec)) { + util.printDate(myCalendar); + } + else { + myCalendar = NULL; + } +#else + myCalendar = Calendar::createInstance(ec); +#endif + } +} + +TZDate::TZDate(const std::string &timezone) +{ + LoggerD("entered"); + + myCalendar = _makeCalendar(timezone); +} + +TZDate::TZDate(const TZDateProperties &properties) +{ + LoggerD("entered"); + + TimeUtilTools util; + myCalendar = _makeCalendar(properties); +} + +TZDate::TZDate(const std::string &dateString, const double milliseconds, const std::string &timezone) { + myCalendar = NULL; + + UErrorCode ec = U_ZERO_ERROR; + Calendar *dateCalender = Calendar::createInstance(ec); + DateFormat *df = NULL; + try { + if (dateCalender == NULL || U_FAILURE(ec)) { + ThrowMsg(Commons::UnknownException, "Can't make calendar"); + } + df = new SimpleDateFormat("EEE MMM d uuuuuu HH:mm:ss", Locale::getEnglish(), ec); + + if (df == NULL || U_FAILURE(ec)) { + ThrowMsg(Commons::UnknownException, "Can't make DateFormat"); + } + ParsePosition pos; + pos.setIndex(0); + TimeUtilTools util; + UnicodeString text(dateString.c_str()); + UDate date = df->parse(text, ec); + + if (U_FAILURE(ec)) { + ThrowMsg(Commons::UnknownException, "parse fail"); + } + + dateCalender->setTime(date, ec); + + if (U_FAILURE(ec)) { + ThrowMsg(Commons::UnknownException, "setTime fail"); + } + + util.printDate(dateCalender); + TZDateProperties properties; + properties.year = _get(TZDATE_YEAR, dateCalender); + properties.month = _get(TZDATE_MONTH, dateCalender); + properties.day = _get(TZDATE_DATE, dateCalender); + properties.hours = _get(TZDATE_HOUR_OF_DAY, dateCalender); + properties.minutes = _get(TZDATE_MINUTE, dateCalender); + properties.seconds = _get(TZDATE_SECOND, dateCalender); + properties.milliseconds = milliseconds; + properties.timezone = timezone; + myCalendar = _makeCalendar(properties); + } catch (const WrtDeviceApis::Commons::Exception& err) { + LoggerE(err.GetClassName() << ":"<<err.GetMessage()); + if (myCalendar) + delete myCalendar; + myCalendar = NULL; + } + + if (dateCalender) + delete dateCalender; + if (df) + delete df; +} + +TZDate::~TZDate() +{ + LoggerD("entered"); + + if (myCalendar != NULL) + delete myCalendar; + + myCalendar = NULL; +} + +bool TZDate::isNull() +{ + if (myCalendar == NULL) + return TRUE; + + return FALSE; +} + +bool TZDate::isAvailableTimezone(const std::string &timezone) { + TimeUtilTools util; + TimeZone *tz = util.makeTimeZone(timezone); + + bool result = isAvailableTimezone(tz); + + if (tz) + delete tz; + return result; +} + +bool TZDate::isAvailableTimezone(TimeZone *tz) { + if (!tz) + return false; + + TimeUtilTools util; + bool result = true; + UnicodeString id; + tz->getID(id); + + if (util.toString(id) == "Etc/Unknown") + result = false; + + return result; +} + +Calendar *TZDate::_makeCalendar(const std::string &timezone) { + UErrorCode ec = U_ZERO_ERROR; + TimeUtilTools util; + Calendar *cal = NULL; + + TimeZone *tz = util.makeTimeZone(timezone); + + if (isAvailableTimezone(tz)) + cal = Calendar::createInstance(tz ,ec); + else { + if (tz) + delete tz; + cal = Calendar::createInstance(ec); + } + + if (U_SUCCESS(ec)) { + util.printDate(cal); + } else { + if (tz) + delete tz; + cal = NULL; + } + return cal; +} + +Calendar *TZDate::_makeCalendar(const TZDateProperties &properties) +{ + LoggerD("entered"); + UErrorCode ec = U_ZERO_ERROR; + TimeUtilTools util; + + Calendar *cal = NULL; + if (!isAvailableTimezone(properties.timezone)) + cal = Calendar::createInstance(ec); + else + cal = Calendar::createInstance(util.makeTimeZone(properties.timezone) ,ec); + + if ((cal != NULL) && U_SUCCESS(ec)) { + try { + cal->set(UCAL_DATE, 10); //set specific date because first date(1) or last date(31) can make changing of month because of timezone + + _set(TZDATE_YEAR, properties.year, cal); + _set(TZDATE_MONTH, properties.month, cal); + _set(TZDATE_DATE, properties.day, cal); + _set(TZDATE_HOUR_OF_DAY, properties.hours, cal); + _set(TZDATE_MINUTE, properties.minutes, cal); + _set(TZDATE_SECOND, properties.seconds, cal); + _set(TZDATE_MILLISECOND, properties.milliseconds, cal); + } catch (const WrtDeviceApis::Commons::Exception& err) { + LoggerE(err.GetClassName() << ":"<<err.GetMessage()); + if (cal) + delete cal; + cal = NULL; + } + return cal; + } + + if (cal) + delete cal; + return NULL; +} + +std::string TZDate::_getTimezoneName(Calendar *cal) +{ + if (cal == NULL) + ThrowMsg(Commons::UnknownException, "Invalid Date"); + + UnicodeString id; + TimeUtilTools util; + + cal->getTimeZone().getID(id); + std::string s_result = util.toString(id); + LoggerD(s_result); + return s_result; +} + +const UCalendarDateFields TZDate::_convertDateField(const TZDateFields field) +{ + switch (field) { + case TZDATE_ERA: + return UCAL_ERA; + break; + case TZDATE_YEAR: + return UCAL_EXTENDED_YEAR; + break; + case TZDATE_MONTH: + return UCAL_MONTH; + break; + case TZDATE_WEEK_OF_YEAR: + return UCAL_WEEK_OF_YEAR; + break; + case TZDATE_WEEK_OF_MONTH: + return UCAL_WEEK_OF_MONTH; + break; + case TZDATE_DATE: + return UCAL_DATE; + break; + case TZDATE_DAY_OF_YEAR: + return UCAL_DAY_OF_YEAR; + break; + case TZDATE_DAY_OF_WEEK: + return UCAL_DAY_OF_WEEK; + break; + case TZDATE_DAY_OF_WEEK_IN_MONTH: + return UCAL_DAY_OF_WEEK_IN_MONTH; + break; + case TZDATE_AM_PM: + return UCAL_AM_PM; + break; + case TZDATE_HOUR: + return UCAL_HOUR; + break; + case TZDATE_HOUR_OF_DAY: + return UCAL_HOUR_OF_DAY; + break; + case TZDATE_MINUTE: + return UCAL_MINUTE; + break; + case TZDATE_SECOND: + return UCAL_SECOND; + break; + case TZDATE_MILLISECOND: + return UCAL_MILLISECOND; + break; + case TZDATE_ZONE_OFFSET: + return UCAL_ZONE_OFFSET; + break; + case TZDATE_DST_OFFSET: + return UCAL_DST_OFFSET; + break; + default: + return UCAL_FIELD_COUNT; + } +} + +TZDateProperties TZDate::_makeProperties(Calendar *cal) +{ + TZDateProperties result; + TimeUtilTools util; + + result.year = _get(TZDATE_YEAR, cal); + result.month = _get(TZDATE_MONTH,cal); + result.day = _get(TZDATE_DATE, cal); + result.hours = _get(TZDATE_HOUR_OF_DAY, cal); + result.minutes = _get(TZDATE_MINUTE, cal); + result.seconds = _get(TZDATE_SECOND, cal); + result.milliseconds = _get(TZDATE_MILLISECOND, cal); + result.timezone= _getTimezoneName(cal); + + return result; +} + +TZDateProperties TZDate::makeProperties() { + return _makeProperties(myCalendar); +} + +std::string TZDate::getTimezone() +{ + return _getTimezoneName(myCalendar); +} + +TZDateProperties TZDate::toTimezone(const std::string timezone) { + if (myCalendar == NULL) + ThrowMsg(Commons::UnknownException, "Invalid Date"); + + TimeUtilTools util; + Calendar *newCalendar = myCalendar->clone(); + if (newCalendar == NULL) + ThrowMsg(Commons::PlatformException, "Can't create new calendar"); + + newCalendar->setTimeZone(*(util.makeTimeZone(timezone))); + + TZDateProperties newProps = _makeProperties(newCalendar); + delete newCalendar; + + return newProps; +} + +long TZDate::_get(const TZDateFields field, Calendar *cal) +{ + LoggerD("<<<"); + + if (cal == NULL) + ThrowMsg(Commons::UnknownException, "Invalid Date"); + + if (_convertDateField(field) == UCAL_FIELD_COUNT){ + LoggerD(">>> UCAL_FIELD_COUNT"); + return -1; + } + + UErrorCode ec = U_ZERO_ERROR; + TimeUtilTools util; + int32_t value = cal->get(_convertDateField(field), ec); + if (U_SUCCESS(ec)) { + long result = util.tolong(value); + + LoggerD(">>> result:" << result); + return result; + } + ThrowMsg(Commons::PlatformException, "Can't get Calendar value"); +} +long TZDate::get(const TZDateFields field) +{ + LoggerD("<<<"); + + long result = _get(field, myCalendar); + if (field == TZDATE_DAY_OF_WEEK) + result--; + return result; +} + +void TZDate::set(const TZDateFields field, const long value) { + try { + _set(field, value, myCalendar); + } catch (Commons::PlatformException& err) { + LoggerE(err.GetMessage()); + if (myCalendar) + delete myCalendar; + myCalendar = NULL; + } + +} + +void TZDate::_set(const TZDateFields field, const long value, Calendar *cal) +{ + if (_convertDateField(field) == UCAL_FIELD_COUNT) + return; + + if (cal == NULL) + ThrowMsg(Commons::UnknownException, "Invalid Date"); + + TimeUtilTools util; + Calendar *originCal = cal->clone(); + cal->set(_convertDateField(field), util.toint32_t(value)); + + LoggerD("Field : " << field << " value : " << value<< " result:" <<_get(field, cal)); + try { + if (field == TZDATE_YEAR) { + if (value != _get(field, cal)) + ThrowMsg(Commons::PlatformException, "Out of range"); + } else if (field == TZDATE_MONTH) { + long yearDiff = value / 12; + long month = value % 12; + if (value < 0) { + yearDiff--; + month += 12; + } + + long originYear = _get(TZDATE_YEAR, originCal); + if (((originYear + yearDiff) != _get(TZDATE_YEAR, cal)) + || (month != _get(TZDATE_MONTH, cal))) { + LoggerD("originYear:"<<originYear<<" yearDiff:"<<yearDiff<<" TZDATE_YEAR:"<< _get(TZDATE_YEAR, cal)); + LoggerD(" month:"<<month<<" TZDATE_MONTH:"<< _get(TZDATE_MONTH, cal)); + ThrowMsg(Commons::PlatformException, "Out of range"); + } + } else { + UErrorCode ec = U_ZERO_ERROR; + double diff = value - _get(field, originCal); + if (field == TZDATE_DATE) + diff *= U_MILLIS_PER_DAY; + else if (field == TZDATE_HOUR_OF_DAY) + diff *= U_MILLIS_PER_HOUR; + else if (field == TZDATE_MINUTE) + diff *= U_MILLIS_PER_MINUTE; + else if (field == TZDATE_SECOND) + diff *= U_MILLIS_PER_SECOND; + + UDate originUDate = originCal->getTime(ec); + if (!U_SUCCESS(ec)) + ThrowMsg(Commons::PlatformException, "ICU Error"); + + LoggerD("originUDate :" << (double)originUDate << " diff : " << diff); + + if ((U_DATE_MAX - originUDate) < diff) + ThrowMsg(Commons::PlatformException, "Out of range"); + } + } catch (Commons::PlatformException& err) { + LoggerE(err.GetMessage()); + if (originCal) + delete originCal; + throw(err); + } + if (originCal) + delete originCal; +} + +long TZDate::getUTC(const TZDateFields field) +{ + if (_convertDateField(field) == UCAL_FIELD_COUNT) + return -1; + + UErrorCode ec = U_ZERO_ERROR; + Calendar *utcCalendar = NULL; + + try { + utcCalendar = Calendar::createInstance(*(TimeZone::getGMT()),ec); + if (!U_SUCCESS(ec) || (utcCalendar == NULL)) + ThrowMsg(Commons::PlatformException, "Can't create utcCalendar"); + + if (myCalendar == NULL) + ThrowMsg(Commons::UnknownException, "Invalid Date"); + + UDate date = myCalendar->getTime(ec); + if (!U_SUCCESS(ec)) + ThrowMsg(Commons::PlatformException, "Can't get time of myCalendar"); + + utcCalendar->setTime(date, ec); + if (!U_SUCCESS(ec)) + ThrowMsg(Commons::PlatformException, "Can't set time of utcCalendar"); + + int32_t value = utcCalendar->get(_convertDateField(field), ec); + + if (!U_SUCCESS(ec)) + ThrowMsg(Commons::PlatformException, "Can't get data of utcCalendar"); + + if (utcCalendar) + delete utcCalendar; + utcCalendar = NULL; + + TimeUtilTools util; + long result = util.tolong(value); + if (field == TZDATE_DAY_OF_WEEK) + result--; + LoggerD("result : " << result); + + return result; + } catch (const Commons::PlatformException& err) { + LoggerE(err.GetMessage()); + } + + if (utcCalendar) + delete utcCalendar; + ThrowMsg(Commons::PlatformException, "Can't get UTC Calendar value"); +} + +void TZDate::setUTC(const TZDateFields field, const long value) +{ + if (_convertDateField(field) == UCAL_FIELD_COUNT) + return; + + TimeUtilTools util; + UErrorCode ec = U_ZERO_ERROR; + + long myValue = get(field); + long utcValue = getUTC(field); + if (field == TZDATE_DAY_OF_WEEK) + utcValue++; + set(field, myValue + value - utcValue); + + if (!U_SUCCESS(ec)) + ThrowMsg(Commons::PlatformException, "Can't set UTC Calendar value"); +} + +long long TZDate::difference(const TZDateProperties &prop) { + LoggerD("entered"); + + TimeUtilTools util; + UErrorCode ec = U_ZERO_ERROR; + + if (myCalendar == NULL) + ThrowMsg(Commons::UnknownException, "Invalid Date"); + + Calendar *otherCalendar = _makeCalendar(prop); + + if (otherCalendar == NULL) + ThrowMsg(Commons::PlatformException, "Other calendar is null"); + + if (!util.compareTimeZoneName(otherCalendar, prop.timezone)) { + delete otherCalendar; + ThrowMsg(Commons::InvalidArgumentException, "Unsupported Timezone."); + } + + UDate myTime = myCalendar->getTime(ec); + + if (U_SUCCESS(ec)) { + UDate otherTime = otherCalendar->getTime(ec); + if (U_SUCCESS(ec)) { + LoggerD("myCalendar"); + util.printDate(myCalendar); + LoggerD("otherCalendar"); + util.printDate(otherCalendar); + delete otherCalendar; + + LoggerD("myTime : " <<myTime); + LoggerD("otherTime : " << otherTime); + + return static_cast<long long>(myTime - otherTime); + } + } + delete otherCalendar; + ThrowMsg(Commons::PlatformException, "Calendar error in difference"); +} + +TZDateProperties TZDate::addDuration(const DurationProperties &duration) { + LoggerD("entered"); + if (myCalendar == NULL) + ThrowMsg(Commons::UnknownException, "Invalid Date"); + + UErrorCode ec = U_ZERO_ERROR; + + TimeUtilTools util; + + Calendar *cal = myCalendar->clone(); + if (cal == NULL) + ThrowMsg(Commons::PlatformException, "Can't clone my calendar"); + + long long length = duration.length; + short unit = duration.unit; + int msec=0, sec=0, min=0, hour=0; + long long day=0; + + if (unit == MSECS_UNIT) { + msec = length % 1000; + length /= 1000; + unit = SECONDS_UNIT; + } + if ((length != 0) && (unit == SECONDS_UNIT)) { + sec = length % 60; + length /= 60; + unit = MINUTES_UNIT; + } + if ((length != 0) && (unit == MINUTES_UNIT)) { + min = length % 60; + length /= 60; + unit = HOURS_UNIT; + } + if ((length != 0) && (unit == HOURS_UNIT)) { + hour = length % 24; + length /= 24; + unit = DAYS_UNIT; + } + day = length; + LoggerD("day:"<<day<<" hour:"<<hour<<" min:"<<min<<" sec:"<<sec<<" msec:"<<msec); + try { + if (msec != 0) { + cal->add(UCAL_MILLISECOND, util.toint32_t(msec), ec); + if (!U_SUCCESS(ec)) + Throw(Commons::PlatformException); + } + if (sec != 0) { + cal->add(UCAL_SECOND, util.toint32_t(sec), ec); + if (!U_SUCCESS(ec)) + Throw(Commons::PlatformException); + } + if (min != 0) { + cal->add(UCAL_MINUTE, util.toint32_t(min), ec); + if (!U_SUCCESS(ec)) + Throw(Commons::PlatformException); + } + if (hour != 0) { + cal->add(UCAL_HOUR_OF_DAY, util.toint32_t(hour), ec); + if (!U_SUCCESS(ec)) + Throw(Commons::PlatformException); + } + + UDate oldValue = cal->getTime(ec); + if (!U_SUCCESS(ec)) + Throw(Commons::PlatformException); + + while (day != 0) { + LoggerD("1st day : " << day); + int amount = 0; + + if (day < INT_MIN) + amount = INT_MIN; + else if (day > INT_MAX) + amount = INT_MAX; + else + amount = day; + + day -= amount; + LoggerD("amount : " << amount); + LoggerD("2nd day : " << day); + cal->add(UCAL_DATE, util.toint32_t(amount), ec); + if (!U_SUCCESS(ec)) + Throw(Commons::PlatformException); + + UDate newValue = cal->getTime(ec); + if (!U_SUCCESS(ec)) + Throw(Commons::PlatformException); + + int diff = static_cast<int>((newValue - oldValue) / 24 / 60 / 60 / 1000); + LoggerD("diff : " << diff); + if (diff != amount) { + Throw(Commons::OutOfRangeException); + } + oldValue = newValue; + } ; + } catch (Commons::PlatformException) { + delete cal; + ThrowMsg(Commons::PlatformException, "Calendar error in addDuration"); + } catch (Commons::OutOfRangeException) { + delete cal; + ThrowMsg(Commons::OutOfRangeException, "The result is beyond the scope that TZDate can handle."); + } + + TZDateProperties result = _makeProperties(cal); + util.printDate(cal); + delete cal; + + if (!U_SUCCESS(ec)) + ThrowMsg(Commons::PlatformException, "Calendar error in addDuration"); + return result; +} + +std::string TZDate::getUTCTimezoneName() { + UnicodeString id; + TimeUtilTools util; + + TimeZone::getGMT()->getID(id); + std::string s_result = util.toString(id); + LoggerD(s_result); + return s_result; +} + +std::string TZDate::getLocalTimezoneName() { + UnicodeString id; + TimeUtilTools util; + + TimeZone::createDefault()->getID(id); + std::string s_result = util.toString(id); + LoggerD(s_result); + return s_result; +} + +double TZDate::getTime() { + LoggerD("entered"); + if (myCalendar == NULL) + ThrowMsg(Commons::UnknownException, "Invalid Date"); + + UErrorCode ec = U_ZERO_ERROR; + + UDate date = myCalendar->getTime(ec); + if (U_SUCCESS(ec)) + return static_cast<double>(date); + + ThrowMsg(Commons::PlatformException, "can't get time"); +} + +bool TZDate::setTime(const double time) { + LoggerD("entered"); + if (myCalendar == NULL) + ThrowMsg(Commons::UnknownException, "Invalid Date"); + + UErrorCode ec = U_ZERO_ERROR; + + myCalendar->setTime(static_cast<UDate>(time), ec); + if (U_SUCCESS(ec)) + return true; + + return false; +} + + std::string TZDate::toDateString(bool bLocale) { + if (myCalendar == NULL) + ThrowMsg(Commons::UnknownException, "Invalid Date"); + + UErrorCode ec = U_ZERO_ERROR; + UnicodeString str; + TimeUtilTools util; + + Locale *defaultLocale = util.getDefaultLocale(); + UnicodeString patten = util.getDateTimeFormat(TimeUtilTools::DATE_FORMAT, bLocale); + patten.findAndReplace("Y", "u"); + patten.findAndReplace("y", "u"); + DateFormat *fmt = new SimpleDateFormat(patten, ((bLocale && defaultLocale) ? *defaultLocale : Locale::getEnglish()), ec); + if (U_SUCCESS(ec)) { + fmt->setCalendar(*myCalendar); + fmt->format(myCalendar->getTime(ec), str); + delete fmt; + + if (U_SUCCESS(ec)) { + std::string result = util.toString(str); + str.remove(); + + LoggerD (result); + return result; + } + } + + ThrowMsg(Commons::PlatformException, "can't make SimpleDateFormat or can't get time"); + } + + std::string TZDate::toTimeString(bool bLocale) { + if (myCalendar == NULL) + ThrowMsg(Commons::UnknownException, "Invalid Date"); + + UErrorCode ec = U_ZERO_ERROR; + UnicodeString str; + TimeUtilTools util; + + Locale *defaultLocale = util.getDefaultLocale(); + DateFormat *fmt = new SimpleDateFormat(util.getDateTimeFormat(TimeUtilTools::TIME_FORMAT, bLocale), ((bLocale && defaultLocale) ? *defaultLocale : Locale::getEnglish()), ec); + if (U_SUCCESS(ec)) { + fmt->setCalendar(*myCalendar); + fmt->format(myCalendar->getTime(ec), str); + delete fmt; + + if (U_SUCCESS(ec)) { + std::string result = util.toString(str); + str.remove(); + LoggerD (result); + return result; + } + } + + ThrowMsg(Commons::PlatformException, "can't make SimpleDateFormat or can't get time"); + } + + std::string TZDate::toString(bool bLocale) { + if (myCalendar == NULL) + ThrowMsg(Commons::UnknownException, "Invalid Date"); + + LoggerD("entered"); + + UErrorCode ec = U_ZERO_ERROR; + UnicodeString str; + TimeUtilTools util; + + Locale *defaultLocale = util.getDefaultLocale(); + UnicodeString patten = util.getDateTimeFormat(TimeUtilTools::DATETIME_FORMAT, bLocale); + patten.findAndReplace("Y", "u"); + patten.findAndReplace("y", "u"); + DateFormat *fmt = new SimpleDateFormat(patten, ((bLocale && defaultLocale) ? *defaultLocale : Locale::getEnglish()), ec); + if (U_SUCCESS(ec)) { + fmt->setCalendar(*myCalendar); + fmt->format(myCalendar->getTime(ec), str); + delete fmt; + + if (U_SUCCESS(ec)) { + std::string result = util.toString(str); + str.remove(); + LoggerD (result); + return result; + } + } + ThrowMsg(Commons::PlatformException, "can't make SimpleDateFormat or can't get time"); +} + +std::string TZDate::getTimezoneAbbreviation() { + LoggerD("entered"); + if (myCalendar == NULL) + ThrowMsg(Commons::UnknownException, "Invalid Date"); + + UnicodeString str; + TimeUtilTools util; + + myCalendar->getTimeZone().getDisplayName(isDST(), TimeZone::SHORT, Locale::getEnglish(), str); + if ((str != "GMT") && (str.length() > 3) && !str.compare(0, 3, "GMT")) + myCalendar->getTimeZone().getDisplayName(isDST(), TimeZone::LONG_GMT, Locale::getEnglish(), str); + std::string result = util.toString(str); + str.remove(); + LoggerD (result); + return result; +} + +long TZDate::secondsFromUTC() { + LoggerD("entered"); + if (myCalendar == NULL) + ThrowMsg(Commons::UnknownException, "Invalid Date"); + + UErrorCode ec = U_ZERO_ERROR; + TimeUtilTools util; + + int32_t zoneOffset = myCalendar->get(UCAL_ZONE_OFFSET, ec); + if (!U_SUCCESS(ec)) + ThrowMsg(Commons::PlatformException, "can't get zone offset"); + + int32_t dstOffset = myCalendar->get(UCAL_DST_OFFSET, ec); + if (!U_SUCCESS(ec)) + ThrowMsg(Commons::PlatformException, "can't get dst offset"); + + long result = -((util.tolong(zoneOffset + dstOffset)) / MILLISTOSEC); + + LoggerD("result : " << result); + return result; +} + +bool TZDate::isDST() { + LoggerD("entered"); + if (myCalendar == NULL) + ThrowMsg(Commons::UnknownException, "Invalid Date"); + + UErrorCode ec = U_ZERO_ERROR; + TimeUtilTools util; + UBool result = myCalendar->inDaylightTime(ec); + + if (!U_SUCCESS(ec)) + ThrowMsg(Commons::PlatformException, "can't inDaylightTime value from ICU"); + + return static_cast<bool>(result); +} + +TZDateProperties TZDate::getDSTTransition(DSTTransition trans) { + LoggerD("entered"); + if (myCalendar == NULL) + ThrowMsg(Commons::UnknownException, "Invalid Date"); + + TimeUtilTools util; + UErrorCode ec = U_ZERO_ERROR; + TZDateProperties props; + UDate dstTransitionDate = myCalendar->getTime(ec); + UBool result = false; + + if (U_SUCCESS(ec)) { + UnicodeString *id = util.toUnicodeString(getTimezone()); + + VTimeZone *vtz = VTimeZone::createVTimeZoneByID(*id); + delete id; + + TimeZoneTransition tzTrans; + if (vtz->useDaylightTime() == TRUE) { + if (trans == NEXT_TRANSITION) + result = vtz->getNextTransition(dstTransitionDate, FALSE, tzTrans); + else + result = vtz->getPreviousTransition(dstTransitionDate, FALSE, tzTrans); + if (result == TRUE) { + LoggerD("result is TRUE"); + dstTransitionDate = tzTrans.getTime(); + } + } + delete vtz; + + if (result == false) + return props; + + Calendar *dstTransCalendar = myCalendar->clone(); + dstTransCalendar->setTime(dstTransitionDate, ec); + if (U_SUCCESS(ec)) { + props = _makeProperties(dstTransCalendar); + delete dstTransCalendar; + return props; + } + delete dstTransCalendar; + } + ThrowMsg(Commons::PlatformException, "can't getDSTTransition value from ICU"); +} + +} +} diff --git a/wearable_src/TimeUtil/TZDate.h b/wearable_src/TimeUtil/TZDate.h new file mode 100755 index 0000000..a7c06eb --- /dev/null +++ b/wearable_src/TimeUtil/TZDate.h @@ -0,0 +1,119 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _TZDATE_H_ +#define _TZDATE_H_ + +#include <string> +#include <ctime> + +#include <unicode/calendar.h> +#include <unicode/timezone.h> + +#include "TZDateProperties.h" +#include "DurationProperties.h" + +namespace DeviceAPI { +namespace Time { + +class TZDate +{ + + public: + enum TZDateFields { + TZDATE_ERA, + TZDATE_YEAR, + TZDATE_MONTH, + TZDATE_WEEK_OF_YEAR, + TZDATE_WEEK_OF_MONTH, + TZDATE_DATE, + TZDATE_DAY_OF_YEAR, + TZDATE_DAY_OF_WEEK, + TZDATE_DAY_OF_WEEK_IN_MONTH, + TZDATE_AM_PM, + TZDATE_HOUR, + TZDATE_HOUR_OF_DAY, + TZDATE_MINUTE, + TZDATE_SECOND, + TZDATE_MILLISECOND, + TZDATE_ZONE_OFFSET, + TZDATE_DST_OFFSET, + + TZDATE_FIELDS_COUNT, + }; + + enum DSTTransition { + PREV_TRANSITION, + NEXT_TRANSITION + }; + + TZDate(const bool isNotNull = true); + TZDate(const std::string &timezone); + TZDate(const TZDateProperties &properties); + TZDate(const std::string &dateString, const double milliseconds, const std::string &timezone); + virtual ~TZDate(); + + bool isNull(); + long get(const TZDateFields field); + std::string getTimezone(); + TZDateProperties toTimezone(const std::string timezone); + void set(const TZDateFields field, const long value); + + long getUTC(const TZDateFields field); + void setUTC(const TZDateFields field, const long value); + + long long difference(const TZDateProperties &prop); + TZDateProperties addDuration(const DurationProperties &duration); + std::string getUTCTimezoneName(); + std::string getLocalTimezoneName(); + TZDateProperties makeProperties(); + + double getTime(); + bool setTime(const double time); + std::string toDateString(bool bLocale = false) ; + std::string toTimeString(bool bLocale = false); + std::string toString(bool bLocale = false); + + std::string getTimezoneAbbreviation(); + long secondsFromUTC(); + bool isDST(); + TZDateProperties getDSTTransition(DSTTransition trans); + bool isAvailableTimezone(const std::string &timezone); + bool isAvailableTimezone(icu::TimeZone *tz); + private: + long _get(const TZDateFields field, icu::Calendar *cal); + void _set(const TZDateFields field, const long value, icu::Calendar *cal); + std::string _getTimezoneName(icu::Calendar *cal); + const UCalendarDateFields _convertDateField(const TZDateFields field); + + icu::Calendar * _makeCalendar(const std::string &timezone); + icu::Calendar * _makeCalendar(const TZDateProperties &properties); + TZDateProperties _makeProperties(icu::Calendar *cal); + + icu::Calendar *myCalendar; + +}; + +typedef DPL::SharedPtr<TZDate> TZDatePtr; + +} +} + +#endif /* _DATETIME_H_ */ diff --git a/wearable_src/TimeUtil/TZDateProperties.h b/wearable_src/TimeUtil/TZDateProperties.h new file mode 100755 index 0000000..f80b2e6 --- /dev/null +++ b/wearable_src/TimeUtil/TZDateProperties.h @@ -0,0 +1,54 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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_API_TIMEUTIL_TZDATE_PROPERTIES_H_ +#define WRTPLUGINS_API_TIMEUTIL_TZDATE_PROPERTIES_H_ + +#include <ctime> +#include <string> +#include <dpl/shared_ptr.h> + +namespace DeviceAPI { +namespace Time { + +struct TZDateProperties +{ + long year; + long month; + long day; + long hours; + long minutes; + long seconds; + long milliseconds; + std::string timezone; + TZDateProperties() + : year(0), month(0), day(0), hours(0), minutes(0), seconds(0), milliseconds(0), + timezone("") + { + } +}; + + +typedef DPL::SharedPtr<TZDateProperties> TZDatePropertiesPtr; + +} // Time +} // DeviceAPI + +#endif //WRTPLUGINS_API_TIMEUTIL_TZDATE_PROPERTIES_H_
\ No newline at end of file diff --git a/wearable_src/TimeUtil/TimeUtil.cpp b/wearable_src/TimeUtil/TimeUtil.cpp new file mode 100755 index 0000000..952dbff --- /dev/null +++ b/wearable_src/TimeUtil/TimeUtil.cpp @@ -0,0 +1,261 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <ctime> +#include <vconf.h> +#include <Commons/Exception.h> +#include <unicode/ustring.h> +#include <unicode/timezone.h> +#include <unicode/calendar.h> +#include <unicode/strenum.h> +#include <unicode/datefmt.h> +#include "TZDateProperties.h" +#include "TimeUtil.h" +#include "TimeUtilTools.h" +#include <Logger.h> + +using namespace WrtDeviceApis; + +namespace DeviceAPI { +namespace Time { + +namespace { + static void changedTimeCallback(keynode_t* node, void* user_data) { + LoggerD("entered KeyName:" << vconf_keynode_get_name(node)); + if (user_data && !strcmp(vconf_keynode_get_name(node), VCONFKEY_SYSTEM_TIME_CHANGED)) { + LoggerD("enter"); + ((TimeUtil*)user_data)->changeDefaultTimezone(); + } + } +}//private namespace + +TimeUtil::TimeUtil() +{ + LoggerD("entered"); + mDateTimeChangeListener = NULL; + mTimezoneChangeListener = NULL; + bRegisteredChangedTime = false; + + if (vconf_notify_key_changed(VCONFKEY_SYSTEM_TIME_CHANGED, changedTimeCallback, (void*)this) == 0) { + LoggerD("Success to register changedTimeCallback"); + bRegisteredChangedTime = true; + } + TimeUtilTools util; + TimeZone* zone = TimeZone::createDefault(); + if (zone) { + UnicodeString id; + zone->getID(id); + delete zone; + localTimezone = util.toString(id); + } + changeDefaultTimezone(); + +} + +TimeUtil::~TimeUtil() +{ + LoggerD("entered"); + if (bRegisteredChangedTime) { + vconf_ignore_key_changed(VCONFKEY_SYSTEM_TIME_CHANGED, changedTimeCallback); + bRegisteredChangedTime = false; + } + unsetDateTimeChangeListener(); +} + +std::string TimeUtil::getLocalTimezone() { + LoggerD("entered"); +#if 0 + UnicodeString idResult; + + TimeZone* zone = TimeZone::createDefault(); + UnicodeString id; + zone->getID(id); + + delete zone; + + try { + TimeUtilTools util; + std::string s_result = util.toString(id); + LoggerD("result : " << s_result); + + return s_result; + } catch (Commons::PlatformException) { + LoggerE("can't get the local timezone's name"); + } + + ThrowMsg(Commons::PlatformException, "Can't get Local Timezone"); +#else + return localTimezone; +#endif +} + + +std::string TimeUtil::getUTCTimezone() { + LoggerD("entered"); + UnicodeString id; + + const TimeZone *utcTimezone = TimeZone::getGMT(); + utcTimezone->getID(id); + + try { + TimeUtilTools util; + std::string s_result = util.toString(id); + + LoggerD("result : " << s_result); + + return s_result; + } catch(Commons::PlatformException) { + LoggerE("can't get the UTC timezone's name"); + } + + ThrowMsg(Commons::PlatformException, "Can't get UTC Timezone"); +} + +std::vector<std::string> TimeUtil::getAvailableTimezones(){ + UErrorCode ec = U_ZERO_ERROR; + StringEnumeration * tzen = TimeZone::createEnumeration(); + const char *str = NULL; + int32_t count = tzen->count(ec); + std::vector<std::string> timezones; + + LoggerD("count: " << count); + + if (U_SUCCESS(ec)) { + int i = 0; + + do { + int32_t resultLen = 0; + + str = tzen->next(&resultLen, ec); + if(U_SUCCESS(ec)) { + std::string timezone = str; + timezones.push_back(timezone); + i++; + } + }while((str!=NULL) && (i < count)); + } else { + ThrowMsg(Commons::PlatformException, "Can't get timezones list"); + } + return timezones;; +} + +std::string TimeUtil::getDateFormat(const bool b_shortFormat) { + LoggerD("entered"); + TimeUtilTools util; + UnicodeString dateFormat = util.getDateTimeFormat((b_shortFormat ? TimeUtilTools::DATE_SHORT_FORMAT : TimeUtilTools::DATE_FORMAT), true); + dateFormat.findAndReplace("Y", "y"); + dateFormat.findAndReplace("U", "y"); + dateFormat.findAndReplace("u", "y"); + dateFormat.findAndReplace("D", "d"); + dateFormat.findAndReplace("E", "D"); + dateFormat.findAndReplace("e", "D"); + + if (dateFormat.indexOf("MMM") > 0) { + if (dateFormat.indexOf("MMMM") > 0) + dateFormat = dateFormat.findAndReplace("MMMM", "M"); + else + dateFormat = dateFormat.findAndReplace("MMM", "M"); + } else { + dateFormat = dateFormat.findAndReplace("M", "m"); + } + + int32_t i = 0; + + while (i < dateFormat.length()) { + if (dateFormat[i] == dateFormat[i+1]) + dateFormat.remove(i, 1); + else + i++; + } + LoggerD("result : " << util.toString(dateFormat)); + return util.toString(dateFormat); +} + +std::string TimeUtil::getTimeFormat(){ + LoggerD("entered"); + TimeUtilTools util; + UnicodeString timeFormat = util.getDateTimeFormat(TimeUtilTools::TIME_FORMAT, true); + timeFormat.findAndReplace("H", "h"); + timeFormat.findAndReplace("K", "h"); + timeFormat.findAndReplace("k", "h"); + timeFormat.findAndReplace("a", "ap"); + + int32_t i = 0; + + while (i < timeFormat.length()) { + if (timeFormat[i] == timeFormat[i+1]) + timeFormat.remove(i, 1); + else + i++; + } + LoggerD("result : " << util.toString(timeFormat)); + return util.toString(timeFormat); +} + + void TimeUtil::changeDefaultTimezone() { + LoggerD("Enter"); + + std::string s_result; + TimeUtilTools util; + std::string defaultTimezone = util.getDefaultTimezone(); + if (localTimezone != defaultTimezone) { + localTimezone = defaultTimezone; + UnicodeString *timezoneId = util.toUnicodeString(defaultTimezone); + if (timezoneId) { + TimeZone* zone = TimeZone::createTimeZone(*timezoneId); + if (zone) { + TimeZone::setDefault(*zone); + delete zone; + } + delete timezoneId; + } + if (mTimezoneChangeListener) { + LoggerD("Timezone changed"); + mTimezoneChangeListener->callSuccessCallback(); + } + } + if (mDateTimeChangeListener) { + LoggerD("Time changed"); + mDateTimeChangeListener->callSuccessCallback(); + } +} +void TimeUtil::setDateTimeChangeListener(Common::CallbackUserData *callback) { + LoggerD("Enter"); + unsetDateTimeChangeListener(); + mDateTimeChangeListener = callback; +} +void TimeUtil::unsetDateTimeChangeListener() { + LoggerD("Enter"); + if (mDateTimeChangeListener) + delete mDateTimeChangeListener; + mDateTimeChangeListener = NULL; +} + +void TimeUtil::setTimezoneChangeListener(Common::CallbackUserData *callback) { + LoggerD("Enter"); + unsetTimezoneChangeListener(); + mTimezoneChangeListener = callback; +} +void TimeUtil::unsetTimezoneChangeListener() { + LoggerD("Enter"); + if (mTimezoneChangeListener) + delete mTimezoneChangeListener; + mTimezoneChangeListener = NULL; +} + +} +} diff --git a/wearable_src/TimeUtil/TimeUtil.h b/wearable_src/TimeUtil/TimeUtil.h new file mode 100755 index 0000000..ed905fc --- /dev/null +++ b/wearable_src/TimeUtil/TimeUtil.h @@ -0,0 +1,62 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _TIMEUTIL_H_ +#define _TIMEUTIL_H_ + +#include <dpl/mutex.h> +#include <dpl/shared_ptr.h> +#include <string> +#include <vector> +#include <CallbackUserData.h> + +#include <unicode/unistr.h> + +namespace DeviceAPI { +namespace Time { + +class TimeUtil +{ + public: + TimeUtil(); + virtual ~TimeUtil(); + virtual std::string getLocalTimezone(); + virtual std::string getUTCTimezone(); + virtual std::vector<std::string> getAvailableTimezones(); + virtual std::string getDateFormat(const bool b_shortFormat); + virtual std::string getTimeFormat(); + virtual void changeDefaultTimezone(); + virtual void setDateTimeChangeListener(Common::CallbackUserData *callback); + virtual void unsetDateTimeChangeListener(); + virtual void setTimezoneChangeListener(Common::CallbackUserData *callback); + virtual void unsetTimezoneChangeListener(); + private: + std::string localTimezone; + bool bRegisteredChangedTime; + Common::CallbackUserData *mDateTimeChangeListener; + Common::CallbackUserData *mTimezoneChangeListener; +}; + +typedef DPL::SharedPtr<TimeUtil> TimeUtilPtr; +} +} + + +#endif /* _TIMEUTIL_H_ */ diff --git a/wearable_src/TimeUtil/TimeUtilConverter.cpp b/wearable_src/TimeUtil/TimeUtilConverter.cpp new file mode 100755 index 0000000..9fbac1c --- /dev/null +++ b/wearable_src/TimeUtil/TimeUtilConverter.cpp @@ -0,0 +1,336 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <Commons/Exception.h> +#include <CommonsJavaScript/ScopedJSStringRef.h> +#include <CommonsJavaScript/PrivateObject.h> +#include <CommonsJavaScript/Validator.h> +#include <CommonsJavaScript/JSUtils.h> +#include <Commons/RegexUtils.h> + +#include "TimeUtilConverter.h" +#include "JSTZDate.h" +#include "JSTimeDuration.h" +#include <Logger.h> + +using namespace WrtDeviceApis; + +namespace DeviceAPI { +namespace Time { + +TimeUtilConverter::TimeUtilConverter(JSContextRef context) +: WrtDeviceApis::CommonsJavaScript::Converter(context) { +} + +TimeUtilConverter::~TimeUtilConverter() { +} + +short TimeUtilConverter::toShort(const JSValueRef& arg) +{ + double tmp = toNumber_(arg); + return (isNan(tmp) ? 0 : static_cast<short>(tmp)); +} + +TZDateProperties TimeUtilConverter::getPropertiesInTZDate(JSValueRef arg) { + if (JSValueIsNull(m_context, arg) || JSValueIsUndefined(m_context, arg) || !JSValueIsObjectOfClass(m_context, arg, JSTZDate::getClassRef())) { + ThrowMsg(Commons::ConversionException, + "Wrong Input Type"); + } + JSObjectRef obj = toJSObjectRef(arg); + return getPropertiesInTZDate(obj); +} + + +TZDateProperties TimeUtilConverter::getPropertiesInTZDate(JSObjectRef arg) { + LoggerD("TZDate object=" << arg); + if (!arg) { + LoggerE("Object is null"); + ThrowMsg(Commons::ConversionException, "Private object not initialized"); + } + TZDatePrivObject* privateObject = static_cast<TZDatePrivObject*>(JSObjectGetPrivate(arg)); + if (!privateObject) { + LoggerE("Private object is not set."); + ThrowMsg(Commons::ConversionException, "Private object not initialized"); + } + + TZDatePtr tzDate = privateObject->getObject(); + TZDateProperties result; + + result.timezone = tzDate->getTimezone(); + result.year = tzDate->get(TZDate::TZDATE_YEAR); + result.month = tzDate->get(TZDate::TZDATE_MONTH); + result.day= tzDate->get(TZDate::TZDATE_DATE); + result.hours= tzDate->get(TZDate::TZDATE_HOUR_OF_DAY); + result.minutes= tzDate->get(TZDate::TZDATE_MINUTE); + result.seconds= tzDate->get(TZDate::TZDATE_SECOND); + result.milliseconds = tzDate->get(TZDate::TZDATE_MILLISECOND); + return result; +} + +JSObjectRef TimeUtilConverter::makeDurationObject(const DurationProperties &duration) { + return JSTimeDuration::createJSObject(m_context, duration); +} + +JSObjectRef TimeUtilConverter::makeMillisecondDurationObject(const long long length) { + DurationProperties duration; + duration.length = length; + duration.unit = MSECS_UNIT; + const long long dayToMsecs = 1000 * 60 * 60 * 24; + if ((length % dayToMsecs) == 0) { + duration.length = length / dayToMsecs; + duration.unit = DAYS_UNIT; + } + + return makeDurationObject(duration); +} + +DurationPropertiesPtr TimeUtilConverter::getDuration(JSValueRef value) { + if (!JSValueIsObjectOfClass(m_context, value, JSTimeDuration::getClassRef())) { + ThrowMsg(Commons::ConversionException, "Wrong input type"); + } + + TimeDurationPrivObject* privateObject = static_cast<TimeDurationPrivObject*>(JSObjectGetPrivate(toJSObjectRef(value))); + DurationPropertiesPtr duration = privateObject->getObject(); + return duration; +} + +DurationProperties TimeUtilConverter::getDurationProperties(JSValueRef value) { + DurationProperties duration; + duration.length = getDurationLength(value); + duration.unit = getDurationUnit(value); + return duration; +} + +long long TimeUtilConverter::getDurationLength(JSValueRef value) { + if (JSValueIsNull(m_context, value) || JSValueIsUndefined(m_context, value) || !JSValueIsObjectOfClass(m_context, value, JSTimeDuration::getClassRef())) { + ThrowMsg(Commons::ConversionException, + "Wrong input type"); + } + JSObjectRef obj = toJSObjectRef(value); + return getDurationLength(obj); +} + +long long TimeUtilConverter::getDurationLength(JSObjectRef object) { + TimeDurationPrivObject* privateObject = static_cast<TimeDurationPrivObject*>(JSObjectGetPrivate(object)); + if (!privateObject) { + LoggerE("Private object is not set."); + ThrowMsg(Commons::ConversionException, "Private object not initialized"); + } + + DurationPropertiesPtr duration = privateObject->getObject(); + + return duration->length; +} + +short TimeUtilConverter::getDurationUnit(JSValueRef value) { + if (JSValueIsNull(m_context, value) || JSValueIsUndefined(m_context, value) || !JSValueIsObjectOfClass(m_context, value, JSTimeDuration::getClassRef())) { + ThrowMsg(Commons::ConversionException, + "Wrong input type"); + } + JSObjectRef obj = toJSObjectRef(value); + return getDurationUnit(obj); +} + +short TimeUtilConverter::getDurationUnit(JSObjectRef object) { + TimeDurationPrivObject* privateObject = static_cast<TimeDurationPrivObject*>(JSObjectGetPrivate(object)); + if (!privateObject) { + LoggerE("Private object is not set."); + ThrowMsg(Commons::ConversionException, "Private object not initialized"); + } + + DurationPropertiesPtr duration = privateObject->getObject(); + + return duration->unit; + +} + +short TimeUtilConverter::toDurationUnit(std::string strUnit) { + if (!strUnit.compare("DAYS")) + return DAYS_UNIT; + else if (!strUnit.compare("SECS")) + return SECONDS_UNIT; + else if (!strUnit.compare("MINS")) + return MINUTES_UNIT; + else if (!strUnit.compare("HOURS")) + return HOURS_UNIT; + else + return MSECS_UNIT; +} + +std::string TimeUtilConverter::toDurationUnitString(short unit) { + switch (unit) { + case DAYS_UNIT: + return "DAYS"; + case SECONDS_UNIT: + return "SECS"; + case MINUTES_UNIT: + return "MINS"; + case HOURS_UNIT: + return "HOURS"; + case MSECS_UNIT: + default: + return "MSECS"; + } +} + +long long TimeUtilConverter::convertDurationLength(DurationProperties duration, short unit) { + if (duration.unit < unit) + ThrowMsg(Commons::ConversionException, "Unit is larger than duration's unit"); + + if (duration.unit == unit) + return duration.length; + + long long result = duration.length; + + switch(unit) { + case MSECS_UNIT: + result = result * 1000; + if (duration.unit == SECONDS_UNIT) + return result; + // intentional fall-through + + case SECONDS_UNIT: + result = result * 60; + if (duration.unit == MINUTES_UNIT) + return result; + // intentional fall-through + + case MINUTES_UNIT: + result = result * 60; + if (duration.unit == HOURS_UNIT) + return result; + // intentional fall-through + + case HOURS_UNIT: + result = result * 24; + return result; + // intentional fall-through + } + return result; +} + +DurationProperties TimeUtilConverter::optimizedTimeDuration(DurationProperties origin) { + DurationProperties result; + result.unit = origin.unit; + result.length = origin.length; + + switch(origin.unit) { + case MSECS_UNIT: + if (result.length % 1000) + return result; + result.unit = SECONDS_UNIT; + result.length /= 1000; + // intentional fall-through + + case SECONDS_UNIT: + if (result.length % 60) + return result; + result.unit = MINUTES_UNIT; + result.length /= 60; + // intentional fall-through + + case MINUTES_UNIT: + if (result.length % 60) + return result; + result.unit = HOURS_UNIT; + result.length /= 60; + // intentional fall-through + + case HOURS_UNIT: + if (result.length % 24) + return result; + result.unit = DAYS_UNIT; + result.length /= 24; + // intentional fall-through + } + return result; +} + +double TimeUtilConverter::getTimeInMilliseconds(JSValueRef arg) { + if (JSValueIsNull(m_context, arg) || JSValueIsUndefined(m_context, arg) || !JSValueIsObjectOfClass(m_context, arg, JSTZDate::getClassRef())) { + ThrowMsg(Commons::ConversionException, + "Wrong input type"); + } + JSObjectRef obj = toJSObjectRef(arg); + + return getTimeInMilliseconds(obj); +} + +double TimeUtilConverter::getTimeInMilliseconds(JSObjectRef arg) { + if (!arg) { + LoggerE("Object is null"); + ThrowMsg(Commons::ConversionException, "Object is null"); + } + + TZDatePrivObject* privateObject = static_cast<TZDatePrivObject*>(JSObjectGetPrivate(arg)); + if (!privateObject) { + LoggerE("Private object is not set."); + ThrowMsg(Commons::ConversionException, "Private object not initialized"); + } + + TZDatePtr tzDate = privateObject->getObject(); + + return tzDate->getTime(); +} + +tm TimeUtilConverter::toTZDateTime(JSValueRef arg) { + if (JSValueIsNull(m_context, arg) || JSValueIsUndefined(m_context, arg) || !JSValueIsObjectOfClass(m_context, arg, JSTZDate::getClassRef())) { + ThrowMsg(Commons::ConversionException, + "Wrong input type"); + } + JSObjectRef obj = toJSObjectRef(arg); + + return toTZDateTime(obj); +} + +tm TimeUtilConverter::toTZDateTime(JSObjectRef arg) { + if (!arg) { + LoggerE("Object is null"); + ThrowMsg(Commons::ConversionException, "Object is null"); + } + + TZDatePrivObject* privateObject = static_cast<TZDatePrivObject*>(JSObjectGetPrivate(arg)); + if (!privateObject) { + LoggerE("Private object is not set."); + ThrowMsg(Commons::ConversionException, "Private object not initialized"); + } + + TZDatePtr tzDate = privateObject->getObject(); + TZDatePtr utcTzDate(new TZDate(tzDate->getUTCTimezoneName())); + if (!utcTzDate->setTime(tzDate->getTime())) + ThrowMsg(Commons::ConversionException, "Can not set Time"); + + TZDateProperties utcProperties = utcTzDate->makeProperties(); + struct tm utcTm; + memset(&utcTm, 0, sizeof(utcTm)); + + utcTm.tm_year = utcProperties.year - 1900; + utcTm.tm_mon = utcProperties.month; + utcTm.tm_mday= utcProperties.day; + utcTm.tm_hour= utcProperties.hours; + utcTm.tm_min=utcProperties.minutes; + utcTm.tm_sec= utcProperties.seconds; + utcTm.tm_isdst = 0; + return utcTm; +} + +JSObjectRef TimeUtilConverter::toJSValueRefTZDate(const double milliseconds, const std::string &timezone) { + return JSTZDate::createJSObject(m_context, milliseconds, timezone); +} + +} +} diff --git a/wearable_src/TimeUtil/TimeUtilConverter.h b/wearable_src/TimeUtil/TimeUtilConverter.h new file mode 100755 index 0000000..e29d558 --- /dev/null +++ b/wearable_src/TimeUtil/TimeUtilConverter.h @@ -0,0 +1,72 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _JS_TIZEN_TIMEUTIL_CONVERTER_H_ +#define _JS_TIZEN_TIMEUTIL_CONVERTER_H_ + +#include <vector> +#include <string> + +#include <CommonsJavaScript/Converter.h> +#include <CommonsJavaScript/ScopedJSStringRef.h> + +#include "TZDate.h" +#include "DurationProperties.h" + +using namespace WrtDeviceApis::CommonsJavaScript; + +namespace DeviceAPI { +namespace Time { + + +class TimeUtilConverter : public Converter +{ + public: + using Converter::toJSValueRef; + public: + explicit TimeUtilConverter(JSContextRef context); + virtual ~TimeUtilConverter(); + short toShort(const JSValueRef& arg); + + TZDateProperties getPropertiesInTZDate(JSValueRef arg); + TZDateProperties getPropertiesInTZDate(JSObjectRef arg); + JSObjectRef makeDurationObject(const DurationProperties &duration); + JSObjectRef makeMillisecondDurationObject(const long long length); + DurationPropertiesPtr getDuration(JSValueRef value); + DurationProperties getDurationProperties(JSValueRef value); + long long getDurationLength(JSValueRef value); + long long getDurationLength(JSObjectRef object); + short getDurationUnit(JSValueRef value); + short getDurationUnit(JSObjectRef object); + short toDurationUnit(std::string strUnit); + std::string toDurationUnitString(short unit); + long long convertDurationLength(DurationProperties duration, short unit); + double getTimeInMilliseconds(JSValueRef arg); + double getTimeInMilliseconds(JSObjectRef arg); + tm toTZDateTime(JSValueRef arg); + tm toTZDateTime(JSObjectRef arg); + JSObjectRef toJSValueRefTZDate(const double milliseconds, const std::string &timezone); + DurationProperties optimizedTimeDuration(DurationProperties origin); +}; + +} +} + +#endif /* _JS_TIZEN_TIMEUTIL_CONVERTER_H_ */ diff --git a/wearable_src/TimeUtil/TimeUtilTools.cpp b/wearable_src/TimeUtil/TimeUtilTools.cpp new file mode 100755 index 0000000..ccb7811 --- /dev/null +++ b/wearable_src/TimeUtil/TimeUtilTools.cpp @@ -0,0 +1,223 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <unicode/ustring.h> +#include <unicode/udat.h> +#include <unicode/dtptngen.h> +#include <string.h> +#include <vconf.h> +#include <Commons/Exception.h> +#include "TimeUtilTools.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Time { + +using namespace WrtDeviceApis; + +long TimeUtilTools::tolong(const int32_t num) +{ + return static_cast<long>(num); +} + +int32_t TimeUtilTools::toint32_t(const long long num) +{ + return static_cast<int32_t>(num); +} + +int32_t TimeUtilTools::toint32_t(const long num) +{ + return static_cast<int32_t>(num); +} + +int32_t TimeUtilTools::toint32_t(const int num) +{ + return static_cast<int32_t>(num); +} + +UnicodeString *TimeUtilTools::toUnicodeString(const std::string str) +{ + UnicodeString *id = new UnicodeString(str.c_str()); + + return id; +} + +std::string TimeUtilTools::toString(UnicodeString uniStr) +{ + int bufferLen = sizeof(UChar)*static_cast<int>(uniStr.length()) + 1; + char *resultBuffer = (char *)malloc(bufferLen); + if (!resultBuffer) + ThrowMsg(Commons::PlatformException, "memory allocation error"); + memset(resultBuffer, 0, bufferLen); + CheckedArrayByteSink sink(resultBuffer, bufferLen); + uniStr.toUTF8(sink); + if (sink.Overflowed()) + ThrowMsg(Commons::PlatformException, "Converting error"); + + std::string str(resultBuffer); + free(resultBuffer); + LoggerD(str); + return str; +} + +TimeZone *TimeUtilTools::makeTimeZone(const std::string &name) +{ + LoggerD("entered timezone name : " << name); + + if (name == "") + return NULL; + + UnicodeString *id = toUnicodeString(name); + + TimeZone *tz = TimeZone::createTimeZone(*id); + delete id; + + return tz; +} + +bool TimeUtilTools::compareTimeZoneName(Calendar *cal, const std::string &name) { + UnicodeString id; + cal->getTimeZone().getID(id); + std::string timezone = toString(id); + + if ((timezone != name) && (timezone == "Etc/Unknown")) + return false; + + return true; +} + +Locale *TimeUtilTools::getDefaultLocale() { + char *tempstr = vconf_get_str(VCONFKEY_REGIONFORMAT); + if (tempstr == NULL) + return NULL; + + Locale *defaultLocale = NULL; + + char *str_region = NULL; + char* p = strchr(tempstr, '.'); + int len = 0; + if (p) { + len = p - tempstr;//strlen(tempstr) - strlen(".UTF-8"); + } else + len = strlen(tempstr); + if ((len > 0) && (len <= strlen(tempstr))) + str_region = strndup(tempstr, len); + LoggerD("region:"<<tempstr); + if (tempstr) + free(tempstr); + if (str_region) { + LoggerD(len<<":"<<str_region); + defaultLocale = new Locale(str_region); + if (str_region) + free(str_region); + } + + if (defaultLocale && defaultLocale->isBogus()) { + delete defaultLocale; + defaultLocale = NULL; + } + return defaultLocale; +} + +UnicodeString TimeUtilTools::getDateTimeFormat(DateTimeFormatType type, bool bLocale) { + UErrorCode ec = U_ZERO_ERROR; + Locale *defaultLocale = getDefaultLocale(); + DateTimePatternGenerator *dateTimepatten = DateTimePatternGenerator::createInstance(((bLocale && defaultLocale) ? *defaultLocale : Locale::getEnglish()), ec); + if (defaultLocale) + delete defaultLocale; + if (U_SUCCESS(ec)) { + UnicodeString patten; + LoggerD("Type : " << type); + if (type == DATE_FORMAT) + patten = dateTimepatten->getBestPattern(UDAT_YEAR_MONTH_WEEKDAY_DAY, ec); + else if (type == DATE_SHORT_FORMAT) + patten = dateTimepatten->getBestPattern(UDAT_YEAR_NUM_MONTH_DAY, ec); + else { + int ret = 0; + int value = 0; + ret = vconf_get_int(VCONFKEY_REGIONFORMAT_TIME1224, &value); + // if failed, set default time format + if (-1 == ret) { + value = VCONFKEY_TIME_FORMAT_12; + } + + std::string skeletone; + if (type != TIME_FORMAT) + skeletone = UDAT_YEAR_MONTH_WEEKDAY_DAY; + if (value == VCONFKEY_TIME_FORMAT_12) + skeletone += "hhmmss"; + else + skeletone += "HHmmss"; + + UnicodeString *skeletoneUniStr = toUnicodeString(skeletone); + patten = dateTimepatten->getBestPattern(*skeletoneUniStr, ec); + delete skeletoneUniStr; + + if (!bLocale) + patten += " 'GMT'Z v'"; + } + LoggerD("pattern : " << toString(patten)); + return patten; + + } + + return ""; +} + +std::string TimeUtilTools::getDefaultTimezone() { + enum { BUFFERSIZE = 1024 }; + char buf[BUFFERSIZE]; + std::string result; + ssize_t len = readlink("/opt/etc/localtime", buf, sizeof(buf)-1); + if (len != -1) { + buf[len] = '\0'; + } + else { + /* handle error condition */ + return result; + } + result = std::string(buf+20); + + LoggerD("tzpath = %s", result.c_str()); + return result; +} + +void TimeUtilTools::printDate(Calendar *cal) +{ + if (cal == NULL) + return; +#ifdef TIZEN_ENGINEER_MODE + UErrorCode ec = U_ZERO_ERROR; + + LoggerD("year : " << tolong(cal->get(UCAL_YEAR, ec))); + LoggerD("month : " << tolong(cal->get(UCAL_MONTH, ec))); + LoggerD("day : " << tolong(cal->get(UCAL_DATE, ec))); + LoggerD("hours : " << tolong(cal->get(UCAL_HOUR, ec))); + LoggerD("hours of day : " << tolong(cal->get(UCAL_HOUR_OF_DAY, ec))); + LoggerD("AM/PM : " << tolong(cal->get(UCAL_AM_PM, ec))); + LoggerD("dayofweek : " << tolong(cal->get(UCAL_DAY_OF_WEEK, ec))); + LoggerD("minues : " << tolong(cal->get(UCAL_MINUTE, ec))); + LoggerD("seconds : " << tolong(cal->get(UCAL_SECOND, ec))); + LoggerD("miliseconds : " << tolong(cal->get(UCAL_MILLISECOND, ec))); + LoggerD("zone offset : " << tolong(cal->get(UCAL_ZONE_OFFSET, ec))); + LoggerD("dst offset : " << tolong(cal->get(UCAL_DST_OFFSET, ec))); + LoggerD("is leap month? : " << tolong(cal->get(UCAL_IS_LEAP_MONTH, ec))); +#endif +} + +} +} diff --git a/wearable_src/TimeUtil/TimeUtilTools.h b/wearable_src/TimeUtil/TimeUtilTools.h new file mode 100755 index 0000000..4635672 --- /dev/null +++ b/wearable_src/TimeUtil/TimeUtilTools.h @@ -0,0 +1,63 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 _TIMEUTILTOOLS_H_ +#define _TIMEUTILTOOLS_H_ + +#include <unicode/unistr.h> +#include <unicode/timezone.h> +#include <unicode/calendar.h> +#include <ctime> + +namespace DeviceAPI { +namespace Time { + +#define MILLISTOSEC 1000 + +class TimeUtilTools +{ + + public: + enum DateTimeFormatType { + TIME_FORMAT, + DATE_FORMAT, + DATE_SHORT_FORMAT, + DATETIME_FORMAT + }; + TimeUtilTools() {} + virtual ~TimeUtilTools() {} + long tolong(const int32_t num); + int32_t toint32_t(const long long num); + int32_t toint32_t(const long num); + int32_t toint32_t(const int num); + UnicodeString *toUnicodeString(const std::string str); + std::string toString(UnicodeString uniStr); + TimeZone *makeTimeZone(const std::string &name); + bool compareTimeZoneName(Calendar *cal, const std::string &name); + void printDate(Calendar *cal); + UnicodeString getDateTimeFormat(DateTimeFormatType type, bool bLocale); + Locale *getDefaultLocale(); + std::string getDefaultTimezone(); +}; + +} +} + +#endif /* _TIMEUTILTOOLS_H_ */ diff --git a/wearable_src/TimeUtil/config.xml b/wearable_src/TimeUtil/config.xml new file mode 100755 index 0000000..a0205c6 --- /dev/null +++ b/wearable_src/TimeUtil/config.xml @@ -0,0 +1,13 @@ +<?xml version="1.0" ?> +<!DOCTYPE plugin-properties SYSTEM "/usr/etc/tizen-apis/config.dtd"> +<plugin-properties> + <library-name>libwrt-plugins-tizen-timeutil.so</library-name> + <feature-install-uri>time.install.uri</feature-install-uri> + + <api-feature> + <name>http://tizen.org/privilege/time</name> + <device-capability>time</device-capability> + </api-feature> + + +</plugin-properties> diff --git a/wearable_src/TimeUtil/plugin_initializer.cpp b/wearable_src/TimeUtil/plugin_initializer.cpp new file mode 100644 index 0000000..baeeb3a --- /dev/null +++ b/wearable_src/TimeUtil/plugin_initializer.cpp @@ -0,0 +1,102 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 <Commons/plugin_initializer_def.h> +#include <Commons/WrtAccess/WrtAccess.h> +#include <GlobalContextManager.h> +#include "JSTimeUtil.h" +#include "JSTZDate.h" +#include "JSTimeDuration.h" +#include <Logger.h> + +namespace DeviceAPI { +namespace Time { + +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; +using namespace DeviceAPI::Common; + +class_definition_options_t ConstructorClassOptions = +{ + JS_INTERFACE, + CREATE_INSTANCE, + NONE_NOTICE, + USE_OVERLAYED, //ignored + NULL, + NULL, + NULL +}; + +void on_widget_start_callback(int widgetId) { + LoggerD("[TIZEN\\TimeUtil] on_widget_start_callback ("<<widgetId<<")"); + Try + { + WrtAccessSingleton::Instance().initialize(widgetId); + } + Catch(Commons::Exception) + { + LoggerE("WrtAccess initialization failed"); + } +} + +void on_widget_stop_callback(int widgetId) { + LoggerD("[TIZEN\\TimeUtil] on_widget_stop_callback ("<<widgetId<<")"); + Try + { + WrtAccessSingleton::Instance().deinitialize(widgetId); + } + Catch(Commons::Exception) + { + LoggerE("WrtAccess deinitialization failed"); + } +} + +void on_frame_load_callback(const void * context) +{ + LoggerD("[TIZEN\\TimeUtil] on_frame_load_callback (" << context << ")"); + GlobalContextManager::getInstance()->addGlobalContext(static_cast<JSContextRef>(context)); +} + +void on_frame_unload_callback(const void * context) +{ + LoggerD("[TIZEN\\TimeUtil] on_frame_unload_callback (" << context << ")"); + GlobalContextManager::getInstance()->removeGlobalContext(static_cast<JSContextRef>(context)); +} +PLUGIN_ON_WIDGET_START(on_widget_start_callback) +PLUGIN_ON_WIDGET_STOP(on_widget_stop_callback) +PLUGIN_ON_FRAME_LOAD(on_frame_load_callback) +PLUGIN_ON_FRAME_UNLOAD(on_frame_unload_callback) + +PLUGIN_CLASS_MAP_BEGIN +PLUGIN_CLASS_MAP_ADD_CLASS(WRT_JS_EXTENSION_OBJECT_TIZEN, + "time", + (js_class_template_getter)JSTimeUtil::getClassRef, + NULL) +PLUGIN_CLASS_MAP_ADD_INTERFACE(WRT_JS_EXTENSION_OBJECT_TIZEN, + "TZDate", + (js_class_template_getter)JSTZDate::getClassRef, + reinterpret_cast<js_class_constructor_cb_t>(JSTZDate::constructor), + &ConstructorClassOptions) +PLUGIN_CLASS_MAP_ADD_INTERFACE(WRT_JS_EXTENSION_OBJECT_TIZEN, + "TimeDuration", + (js_class_template_getter)JSTimeDuration::getClassRef, + reinterpret_cast<js_class_constructor_cb_t>(JSTimeDuration::constructor), + &ConstructorClassOptions) +PLUGIN_CLASS_MAP_END + +} // Time +} // DeviceAPI diff --git a/wearable_src/Tizen/AnyFactory.cpp b/wearable_src/Tizen/AnyFactory.cpp new file mode 100644 index 0000000..6b46eba --- /dev/null +++ b/wearable_src/Tizen/AnyFactory.cpp @@ -0,0 +1,234 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 AnyType.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief Declaration of the JSFilter class + */ + +#include "AnyFactory.h" +#include <string.h> +#include <locale.h> +#include <Commons/Exception.h> +#include <PlatformException.h> +#include <JSUtil.h> +#include <sstream> +#include <Logger.h> + +namespace DeviceAPI { +namespace Tizen { + +using namespace DeviceAPI::Common; + +class PrivateAny : public Any +{ +public: + PrivateAny(); + PrivateAny(JSContextRef context, const JSValueRef value, PrimitiveType type); + virtual ~PrivateAny(); + +private: + bool isDate(JSContextRef jsContext, JSValueRef jsValue) const; + std::string toJSON(JSContextRef jsContext, JSValueRef jsValue) const; + std::string toString(JSContextRef jsContext, JSValueRef jsValue) const; +}; + +PrivateAny::PrivateAny() : Any() +{ + m_isNullOrUndefined = true; + m_type = PrimitiveType_Null; + m_json = "null"; + m_str = "null"; +} + +PrivateAny::PrivateAny(JSContextRef context, const JSValueRef value, PrimitiveType type) : Any() +{ + m_type = type; + + if(type == PrimitiveType_NoType) + throw UnknownException("Cannot create any with NoType"); + + if(JSValueIsUndefined(context, value) || JSValueIsNull(context, value)) + m_isNullOrUndefined = true; + + try + { + if(type == PrimitiveType_Boolean) + m_value.b = JSUtil::JSValueToBoolean(context, value); + else if(type == PrimitiveType_Long) + m_value.l = JSUtil::JSValueToLong(context, value); + else if(type == PrimitiveType_ULong) + m_value.ul = JSUtil::JSValueToULong(context, value); + else if(type == PrimitiveType_LongLong) + m_value.ll = JSUtil::JSValueToLongLong(context, value); + else if(type == PrimitiveType_ULongLong) + m_value.ull = JSUtil::JSValueToULongLong(context, value); + else if(type == PrimitiveType_Double) + m_value.d = JSUtil::JSValueToDouble(context, value); + else if(type == PrimitiveType_String) + { + m_value.str = new std::string(); + *m_value.str = JSUtil::JSValueToString(context, value); + } + else if(type == PrimitiveType_Time) + { + m_value.t = new std::tm; + *m_value.t = JSUtil::JSValueToDateTm(context, value); + } + } + catch(BasePlatformException &e) + { + if(!m_isNullOrUndefined) + { + throw e; + } + + m_type = PrimitiveType_Null; + m_json = "null"; + } + + if(m_json.empty()) + m_json = toJSON(context, value); + + m_str = toString(context, value); +} + +PrivateAny::~PrivateAny() +{ + if(m_type == PrimitiveType_String) + { + if(m_value.str != NULL) + delete m_value.str; + } + else if(m_type == PrimitiveType_Time) + { + if(m_value.t != NULL) + delete m_value.t; + } +} + +bool PrivateAny::isDate(JSContextRef jsContext, JSValueRef jsValue) const +{ + JSObjectRef jsObjectGlobal = JSContextGetGlobalObject(jsContext); + JSStringRef jsStringDate = JSStringCreateWithUTF8CString("Date"); + JSValueRef jsValueDate = JSObjectGetProperty(jsContext, jsObjectGlobal, jsStringDate, NULL); + JSStringRelease(jsStringDate); + + JSObjectRef jsObjectDate = JSValueToObject(jsContext, jsValueDate, NULL); + + return JSValueIsInstanceOfConstructor(jsContext, jsValue, jsObjectDate, NULL); +} + +std::string PrivateAny::toJSON(JSContextRef context, JSValueRef value) const +{ + JSValueRef jsError = NULL; + JSStringRef jsStrJson = JSValueCreateJSONString(context, value, 0, &jsError); + if(jsError != NULL || jsStrJson == NULL) + { + LoggerE("Fail to create JSON string"); + return std::string(""); + } + + std::string result = JSUtil::JSStringToString(context, jsStrJson); + JSStringRelease(jsStrJson); + + return result; +} + +std::string PrivateAny::toString(JSContextRef context, JSValueRef value) const +{ + std::string result; + + if(m_type == PrimitiveType_String) + { + result = *m_value.str; + } + else if(m_type == PrimitiveType_Long || + m_type == PrimitiveType_ULong || + m_type == PrimitiveType_LongLong || + m_type == PrimitiveType_ULongLong) + { + std::stringstream ss; + + if(m_type == PrimitiveType_Long) + ss << m_value.l; + else if(m_type == PrimitiveType_ULong) + ss << m_value.ul; + else if(m_type == PrimitiveType_LongLong) + ss << m_value.ll; + else if(m_type == PrimitiveType_ULongLong) + ss << m_value.ull; + + result = ss.str(); + } + else + { + JSValueRef jsError = NULL; + JSStringRef jsStrJson = JSValueToStringCopy(context, value, &jsError); + if(jsError == NULL && jsStrJson != NULL) + { + result = JSUtil::JSStringToString(context, jsStrJson); + JSStringRelease(jsStrJson); + } + } + + return result; +} + +AnyPtr AnyFactory::createAny(JSContextRef context, JSValueRef value, PrimitiveType type) +{ + AnyPtr any(NULL); + + try + { + any = AnyPtr(new PrivateAny(context, value, type)); + } + catch(TypeMismatchException &e) + { + ThrowMsg(WrtDeviceApis::Commons::ConversionException, "Type error occured while converting JSValueRef"); + } + catch(BasePlatformException &e) + { + ThrowMsg(WrtDeviceApis::Commons::ConversionException, "Unknown error occured while converting JSValueRef"); + } + + return any; +} + +AnyPtr AnyFactory::createAnyNoException(JSContextRef context, JSValueRef value, PrimitiveType type) +{ + try + { + return AnyPtr(new PrivateAny(context, value, type)); + } + catch(BasePlatformException &e) + { + LoggerE("Error while converting (" << e.getName() << ") : " << e.getMessage()); + } + + return AnyPtr(new PrivateAny()); +} + +AnyPtr AnyFactory::createAnyEmpty(JSContextRef context) +{ + return AnyPtr(new PrivateAny()); +} + +} // Tizen +} // DeviceAPI diff --git a/wearable_src/Tizen/AnyFactory.h b/wearable_src/Tizen/AnyFactory.h new file mode 100644 index 0000000..98d2c52 --- /dev/null +++ b/wearable_src/Tizen/AnyFactory.h @@ -0,0 +1,48 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 AnyFactory.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief Declaration of the AnyFactory method + */ + +#ifndef _API_ANY_FACTORY_H_ +#define _API_ANY_FACTORY_H_ + +#include <ctime> +#include <iomanip> +#include <string> +#include <dpl/shared_ptr.h> +#include <JavaScriptCore/JavaScript.h> +#include "AnyType.h" + +namespace DeviceAPI { +namespace Tizen { + +class AnyFactory { +public: + static AnyPtr createAny(JSContextRef context, JSValueRef value, PrimitiveType type); + static AnyPtr createAnyNoException(JSContextRef context, JSValueRef value, PrimitiveType type); + static AnyPtr createAnyEmpty(JSContextRef context); +}; + +} // Tizen +} // DeviceAPI + +#endif // _API_ANYTYPE_H_ diff --git a/wearable_src/Tizen/AnyType.cpp b/wearable_src/Tizen/AnyType.cpp new file mode 100644 index 0000000..3a6ec84 --- /dev/null +++ b/wearable_src/Tizen/AnyType.cpp @@ -0,0 +1,164 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 AnyType.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief Declaration of the JSFilter class + */ + +#include "AnyType.h" + +#include <string.h> +#include <locale.h> +#include <JSUtil.h> + +namespace DeviceAPI { +namespace Tizen { + +using namespace DeviceAPI::Common; + +Any::Any() : + m_isNullOrUndefined(false), + m_priv(NULL), + m_privFinalizerFunc(NULL), + m_type(PrimitiveType_NoType) +{ +} + +Any::~Any() +{ + if(m_priv && m_privFinalizerFunc) + { + m_privFinalizerFunc(m_priv); + } +} + +PrimitiveType Any::getType() const +{ + return m_type; +} + +bool Any::isType(PrimitiveType type) const +{ + return (type == m_type); +} + +bool Any::isNullOrUndefined() const +{ + return m_isNullOrUndefined; +} + +std::string Any::toString() const +{ + return m_str; +} + +bool Any::getBool() const +{ + if(m_type != PrimitiveType_Boolean) + return false; + + return m_value.b; +} + +long Any::getLong() const +{ + if(m_type != PrimitiveType_Long) + return static_cast<long>(0); + + return m_value.l; +} + +unsigned long Any::getULong() const +{ + if(m_type != PrimitiveType_ULong) + return static_cast<unsigned long>(0); + + return m_value.ul; +} + +long long Any::getLongLong() const +{ + if(m_type != PrimitiveType_LongLong) + return static_cast<long long>(0); + + return m_value.ll; +} + +unsigned long long Any::getULongLong() const +{ + if(m_type != PrimitiveType_ULongLong) + return static_cast<unsigned long long>(0); + + return m_value.ull; +} + +double Any::getDouble() const +{ + if(m_type != PrimitiveType_Double) + return static_cast<double>(0.0); + + return m_value.d; +} + +std::string Any::getString() const +{ + if(m_type != PrimitiveType_String || m_value.str == NULL) + return std::string(""); + + return *m_value.str; +} + +std::tm *Any::getDateTm() const +{ + if(m_type != PrimitiveType_Time || m_value.t == NULL) + return NULL; + + return m_value.t; +} + +std::time_t Any::getTimeT() const +{ + if(m_type != PrimitiveType_Time || m_value.t == NULL) + return static_cast<std::time_t>(0); + + return mktime(m_value.t); +} + +std::string Any::getJSON() const +{ + return m_json; +} + +void * Any::getPriv() const +{ + return m_priv; +} + +void Any::setPriv(void * priv, AnyPrivFinalizerFunc privFinalizerFunc) +{ + if(m_priv && m_privFinalizerFunc) + m_privFinalizerFunc(m_priv); + + m_priv = priv; + m_privFinalizerFunc = privFinalizerFunc; +} + +} // Tizen +} // DeviceAPI diff --git a/wearable_src/Tizen/AnyType.h b/wearable_src/Tizen/AnyType.h new file mode 100644 index 0000000..4c8965f --- /dev/null +++ b/wearable_src/Tizen/AnyType.h @@ -0,0 +1,133 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 AnyType.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief Declaration of the Any class + */ + +#ifndef _API_ANYTYPE_H_ +#define _API_ANYTYPE_H_ + +#include <ctime> +#include <string> +#include <dpl/shared_ptr.h> + +namespace DeviceAPI { +namespace Tizen { + +template<class T> +class AnySharedPtrWrapper +{ +public: + typedef T PrivateClass; + typedef DPL::SharedPtr<PrivateClass> PrivSharedPtr; + + AnySharedPtrWrapper(PrivSharedPtr &obj) : m_object(obj) + { + } + + virtual ~AnySharedPtrWrapper() + { + m_object = PrivSharedPtr(NULL); + } + + PrivSharedPtr getObject() + { + return m_object; + } + +private: + PrivSharedPtr m_object; +}; + +enum PrimitiveType { + PrimitiveType_NoType, + PrimitiveType_Null, + PrimitiveType_Boolean, + PrimitiveType_Long, + PrimitiveType_ULong, + PrimitiveType_LongLong, + PrimitiveType_ULongLong, + PrimitiveType_Double, + PrimitiveType_String, + PrimitiveType_Time, + PrimitiveType_Object, + PrimitiveType_PlatformObject +}; + +typedef void (*AnyPrivFinalizerFunc)(void *); + +class Any +{ +public: + Any(); + virtual ~Any(); + + PrimitiveType getType() const; + bool isType(PrimitiveType type) const; + bool isNullOrUndefined() const; + + std::string toString() const; + + bool getBool() const; + long getLong() const; + unsigned long getULong() const; + long long getLongLong() const; + unsigned long long getULongLong() const; + double getDouble() const; + std::string getString() const; + std::tm *getDateTm() const; + std::time_t getTimeT() const; + + std::string getJSON() const; + + void * getPriv() const; + void setPriv(void * priv, AnyPrivFinalizerFunc privFinalizerFunc); + +protected: + union AnyTypeUnion + { + bool b; + long l; + unsigned long ul; + long long ll; + unsigned long long ull; + double d; + std::string* str; + std::tm *t; + }; + + AnyTypeUnion m_value; + bool m_isNullOrUndefined; + + std::string m_json; + std::string m_str; + + void * m_priv; + AnyPrivFinalizerFunc m_privFinalizerFunc; + + PrimitiveType m_type; +}; +typedef DPL::SharedPtr<Any> AnyPtr; + +} // Tizen +} // DeviceAPI + +#endif // _API_ANYTYPE_H_ diff --git a/wearable_src/Tizen/AttributeFilter.cpp b/wearable_src/Tizen/AttributeFilter.cpp new file mode 100644 index 0000000..0b5b374 --- /dev/null +++ b/wearable_src/Tizen/AttributeFilter.cpp @@ -0,0 +1,85 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 AttributeFilter.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include "AttributeFilter.h" + +namespace DeviceAPI {
namespace Tizen { + +using namespace std; + +AttributeFilter::AttributeFilter(const string attributeName, + const MatchFlag& matchFlag, + const AnyPtr& matchValue) : + m_attributeName(attributeName), + m_matchFlag(matchFlag), + m_matchValue(matchValue) +{ +} + +AttributeFilter::~AttributeFilter() +{ +} + +string AttributeFilter::getAttributeName() const +{ + return m_attributeName; +} + +void AttributeFilter::setAttributeName(const string &value) +{ + m_attributeName = value; +} + +bool AttributeFilter::validate(FilterValidatorPtr& validator, int depth) +{ + return validator->validateAttribute(m_attributeName, m_matchFlag, m_matchValue, depth); +} + +void AttributeFilter::travel(IFilterVisitorPtr& visitor, int depth) +{ + visitor->visitAttribute(m_attributeName, m_matchFlag, m_matchValue, depth); +} + +AnyPtr AttributeFilter::getMatchValue() const +{ + return m_matchValue; +} + +void AttributeFilter::setMatchValue(const AnyPtr &value) +{ + m_matchValue = value; +} + +MatchFlag AttributeFilter::getMatchFlag() const +{ + return m_matchFlag; +} + +void AttributeFilter::setMatchFlag(const MatchFlag& value) +{ + m_matchFlag = value; +} + +} // Tizen +} // DeviceAPI diff --git a/wearable_src/Tizen/AttributeFilter.h b/wearable_src/Tizen/AttributeFilter.h new file mode 100644 index 0000000..2d1fce7 --- /dev/null +++ b/wearable_src/Tizen/AttributeFilter.h @@ -0,0 +1,97 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 AttributeFilter.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _API_ATTRIBUTE_FILTER_H_ +#define _API_ATTRIBUTE_FILTER_H_ + +#include <string> +#include <dpl/shared_ptr.h> +#include "AnyType.h" +#include "IFilter.h" +#include "FilterTypes.h" + +namespace DeviceAPI {
namespace Tizen { + +class AttributeFilter : public IFilter +{ +private: // fields + + /** + * attribute name object + */ + std::string m_attributeName; + + /** + * match value object. + */ + MatchFlag m_matchFlag; + + /** + * match value object. + */ + AnyPtr m_matchValue; + +protected: + +public: // methods + + /** + * constructor of abstraction filter + */ + explicit AttributeFilter(const std::string attributeName, + const MatchFlag& matchFlag, + const AnyPtr& matchValue); + + virtual ~AttributeFilter(); + + /** + * method used to identify filter type + */ + virtual FilterType getFilterType() const + { + return ATTRIBUTE_FILTER; + } + + virtual bool setFilterType(const FilterType& filterType) { return false; }; + + virtual bool validate(FilterValidatorPtr& validator, int depth = 0); + + virtual void travel(IFilterVisitorPtr& traversal, int depth = 0); + + std::string getAttributeName() const; + void setAttributeName(const std::string &value); + + AnyPtr getMatchValue() const; + void setMatchValue(const AnyPtr &value); + + MatchFlag getMatchFlag() const; + void setMatchFlag(const MatchFlag& value); +}; + +typedef DPL::SharedPtr<AttributeFilter> AttributeFilterPtr; + +} // Tizen +} // DeviceAPI + +#endif // _API_ATTRIBUTE_FILTER_H_ diff --git a/wearable_src/Tizen/AttributeRangeFilter.cpp b/wearable_src/Tizen/AttributeRangeFilter.cpp new file mode 100644 index 0000000..ed51dd7 --- /dev/null +++ b/wearable_src/Tizen/AttributeRangeFilter.cpp @@ -0,0 +1,85 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 AttributeRangeFilter.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include "AttributeRangeFilter.h" + +namespace DeviceAPI {
namespace Tizen { + +using namespace std; + +AttributeRangeFilter::AttributeRangeFilter(const string& attributeName, + const AnyPtr& initialValue, + const AnyPtr& endValue) : + m_attributeName(attributeName), + m_initialValue(initialValue), + m_endValue(endValue) +{ +} + +AttributeRangeFilter::~AttributeRangeFilter() +{ +} + +bool AttributeRangeFilter::validate(FilterValidatorPtr& validator, int depth) +{ + return validator->validateAttributeRange(m_attributeName, m_initialValue, m_endValue, depth); +} + +void AttributeRangeFilter::travel(IFilterVisitorPtr& visitor, int depth) +{ + visitor->visitAttributeRange(m_attributeName, m_initialValue, m_endValue, depth); +} + +string AttributeRangeFilter::getAttributeName() const +{ + return m_attributeName; +} + +AnyPtr AttributeRangeFilter::getInitialValue() const +{ + return m_initialValue; +} + +AnyPtr AttributeRangeFilter::getEndValue() const +{ + return m_endValue; +} + +void AttributeRangeFilter::setAttributeName(const string& attributeName) +{ + m_attributeName = attributeName; +} + +void AttributeRangeFilter::setInitialValue(const AnyPtr& initialValue) +{ + m_initialValue = initialValue; +} + +void AttributeRangeFilter::setEndValue(const AnyPtr& endValue) +{ + m_endValue = endValue; +} + +} // Tizen +} // DeviceAPI diff --git a/wearable_src/Tizen/AttributeRangeFilter.h b/wearable_src/Tizen/AttributeRangeFilter.h new file mode 100644 index 0000000..f0c1561 --- /dev/null +++ b/wearable_src/Tizen/AttributeRangeFilter.h @@ -0,0 +1,115 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 AttributeRangeFilter.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _API_ATTRIBUTE_RANGE_FILTER_H_ +#define _API_ATTRIBUTE_RANGE_FILTER_H_ + +#include <string> +#include <dpl/shared_ptr.h> +#include "AnyType.h" +#include "IFilter.h" +#include "FilterTypes.h" + +namespace DeviceAPI {
namespace Tizen { + +class AttributeRangeFilter : public IFilter +{ +private: // fields + /** + * attribute name + */ + std::string m_attributeName; + + /** + * initial value + */ + AnyPtr m_initialValue; + + /** + * end value + */ + AnyPtr m_endValue; + +protected: + +public: // methods + /** + * constructor of abstraction filter + */ + explicit AttributeRangeFilter(const std::string& attributeName, + const AnyPtr& initialValue, + const AnyPtr& endValue); + + virtual ~AttributeRangeFilter(); + + /** + * method used to identify filter type + */ + virtual FilterType getFilterType() const + { + return ATTRIBUTE_RANGE_FILTER; + } + virtual bool setFilterType(const FilterType& filterType) { return false; }; + + virtual bool validate(FilterValidatorPtr& validator, int depth = 0); + + virtual void travel(IFilterVisitorPtr& visitor, int depth = 0); + + /** + * method used to get attribute name + */ + std::string getAttributeName() const; + + /** + * method used to get initial value + */ + AnyPtr getInitialValue() const; + + /** + * method used to get end value + */ + AnyPtr getEndValue() const; + + /** + * method used to set attribute name + */ + void setAttributeName(const std::string& attributeName); + + /** + * method used to set initial value + */ + void setInitialValue(const AnyPtr& initialValue); + + /** + * method used to set end value + */ + void setEndValue(const AnyPtr& endValue); +}; + +typedef DPL::SharedPtr<AttributeRangeFilter> AttributeRangeFilterPtr; + +} // Tizen +} // DeviceAPI + +#endif // _API_ATTRIBUTE_RANGE_FILTER_H_ diff --git a/wearable_src/Tizen/CMakeLists.txt b/wearable_src/Tizen/CMakeLists.txt new file mode 100644 index 0000000..a488127 --- /dev/null +++ b/wearable_src/Tizen/CMakeLists.txt @@ -0,0 +1,75 @@ +SET(TARGET_NAME ${tizen_target}) +SET(DESTINATION_NAME ${tizen_dest}) +SET(TARGET_IMPL_NAME ${tizen_impl}) +SET(TARGET_CONFIG_NAME ${tizen_config}) + +PKG_CHECK_MODULES(platform_pkgs_tizen REQUIRED wrt-plugins-plugin-manager) + +INCLUDE_DIRECTORIES( + ${TOP}/Common + ${platform_pkgs_tizen_INCLUDE_DIRS} +) + +SET(CMAKE_INSTALL_RPATH + ${CMAKE_INSTALL_RPATH} + ${CMAKE_INSTALL_PREFIX}/${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME} +) + +SET(SRCS_IMPL + AnyType.cpp + AnyFactory.cpp + FilterFactory.cpp + IFilter.cpp + CompositeFilter.cpp + AttributeFilter.cpp + AttributeRangeFilter.cpp + SortMode.cpp + IFilterVisitor.cpp + IFilterProperties.cpp + FilterValidator.cpp + SimpleCoordinates.cpp + JSAttributeFilter.cpp + JSAttributeRangeFilter.cpp + JSCompositeFilter.cpp + JSSortMode.cpp + FilterConverter.cpp + JSSimpleCoordinates.cpp + PluginOnDemandPriv.cpp + JSTizen.cpp +) + +ADD_LIBRARY(${TARGET_IMPL_NAME} SHARED ${SRCS_IMPL}) + +TARGET_LINK_LIBRARIES(${TARGET_IMPL_NAME} + ${LIBS_COMMON} + ${LIBS_WIDGETDB} + ${platform_pkgs_tizen_LIBRARIES} +) + +SET(SRCS_CONFIG + plugin_config.cpp +) + +ADD_LIBRARY(${TARGET_CONFIG_NAME} SHARED ${SRCS_CONFIG}) + +TARGET_LINK_LIBRARIES(${TARGET_CONFIG_NAME} + ${LIBS_COMMON} +) + +SET(SRCS + plugin_initializer.cpp +) + +ADD_LIBRARY(${TARGET_NAME} SHARED ${SRCS}) + +TARGET_LINK_LIBRARIES(${TARGET_NAME} + ${TARGET_IMPL_NAME} + ${TARGET_CONFIG_NAME} +) + +INSTALL(TARGETS ${TARGET_NAME} ${TARGET_CONFIG_NAME} ${TARGET_IMPL_NAME} LIBRARY DESTINATION ${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME}) +INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/config.xml DESTINATION ${DESTINATION_LIB_PREFIX}/${DESTINATION_NAME}) +INSTALL( + DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/ DESTINATION ${DESTINATION_HEADER_PREFIX}/tizen + FILES_MATCHING PATTERN "*.h" PATTERN "CMakeFiles" EXCLUDE +) diff --git a/wearable_src/Tizen/CompositeFilter.cpp b/wearable_src/Tizen/CompositeFilter.cpp new file mode 100644 index 0000000..93ed396 --- /dev/null +++ b/wearable_src/Tizen/CompositeFilter.cpp @@ -0,0 +1,101 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 CompositeFilter.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include "CompositeFilter.h" + +namespace DeviceAPI {
namespace Tizen { + +CompositeFilter::CompositeFilter(const FilterType& type, const FilterArrayPtr& filters) : + m_filters(filters) +{ + if(type != UNION_FILTER && type != INTERSECTION_FILTER) + m_type = UNION_FILTER; + else + m_type = type; +} + +CompositeFilter::~CompositeFilter() +{ +} + +FilterType CompositeFilter::getFilterType() const +{ + return m_type; +} + +bool CompositeFilter::setFilterType(const FilterType& filterType) +{ + if(filterType != UNION_FILTER && filterType != INTERSECTION_FILTER) + return false; + + m_type = filterType; + return true; +} + +bool CompositeFilter::validate(FilterValidatorPtr& validator, int depth) +{ + FilterArray::iterator it; + + for(it=m_filters->begin(); it != m_filters->end(); it++) + { + if(!(*it)->validate(validator, depth+1)) + return false; + } + + return validator->validateComposite(depth); +} + +void CompositeFilter::travel(IFilterVisitorPtr& visitor, int depth) +{ + visitor->visitPreComposite(m_type, depth); + + FilterArray::iterator it = m_filters->begin(); + if(it != m_filters->end()) + { + while(1) + { + (*it)->travel(visitor, depth+1); + + if(++it == m_filters->end()) + break; + + visitor->visitInComposite(m_type, depth); + } + } + + visitor->visitPostComposite(m_type, depth); +} + +FilterArrayPtr CompositeFilter::getFilters() const +{ + return m_filters; +} + +void CompositeFilter::setFilters(const FilterArrayPtr& value) +{ + m_filters = value; +} + +} // Tizen +} // DeviceAPI diff --git a/wearable_src/Tizen/CompositeFilter.h b/wearable_src/Tizen/CompositeFilter.h new file mode 100644 index 0000000..88b41cd --- /dev/null +++ b/wearable_src/Tizen/CompositeFilter.h @@ -0,0 +1,79 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 CompositeFilter.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _API_COMPOSITE_FILTER_H_ +#define _API_COMPOSITE_FILTER_H_ + +#include <string> +#include <dpl/shared_ptr.h> +#include "IFilter.h" +#include "FilterTypes.h" + +namespace DeviceAPI {
namespace Tizen { + +class CompositeFilter : public IFilter +{ +private: // fields + /** + * filter type. UNION_FILTER(OR) or INTERSECTION_FILTER(AND) + */ + FilterType m_type; + + /** + * filter array. + */ + FilterArrayPtr m_filters; + +protected: + +public: // methods + /** + * constructor of abstraction filter + * @param[in] filterType - type of filter according to FilterType + */ + explicit CompositeFilter(const FilterType& type, const FilterArrayPtr& filters); + + virtual ~CompositeFilter(); + + /** + * method used to identify filter type + */ + virtual FilterType getFilterType() const; + + virtual bool setFilterType(const FilterType& filterType); + + virtual bool validate(FilterValidatorPtr& validator, int depth = 0); + + virtual void travel(IFilterVisitorPtr& visitor, int depth = 0); + + FilterArrayPtr getFilters() const; + void setFilters(const FilterArrayPtr& value); +}; + +typedef DPL::SharedPtr<CompositeFilter> CompositeFilterPtr; + +} // Tizen +} // DeviceAPI + +#endif // _API_COMPOSITE_FILTER_H_ diff --git a/wearable_src/Tizen/FilterConverter.cpp b/wearable_src/Tizen/FilterConverter.cpp new file mode 100644 index 0000000..7b168bb --- /dev/null +++ b/wearable_src/Tizen/FilterConverter.cpp @@ -0,0 +1,548 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 FilterConverter.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @description Reference from CalendarConverter.cpp + */ + +#include <CommonsJavaScript/ScopedJSStringRef.h> +#include <CommonsJavaScript/Validator.h> +#include <CommonsJavaScript/JSUtils.h> +#include "JSAttributeFilter.h" +#include "JSAttributeRangeFilter.h" +#include "JSCompositeFilter.h" +#include "JSSortMode.h" +#include "FilterConverter.h" +#include "AnyFactory.h" +#include <Logger.h> + +#define TIZEN_FILTER_CONVERTER_ATTRIBUTE_TYPE "type" +#define TIZEN_FILTER_CONVERTER_ATTRIBUTE_ORDER "order" +#define TIZEN_FILTER_CONVERTER_ATTRIBUTE_FILTERS "filters" +#define TIZEN_FILTER_CONVERTER_ATTRIBUTE_IDS "ids" +#define TIZEN_FILTER_CONVERTER_ATTRIBUTE_ATTRIBUTE_NAME "attributeName" +#define TIZEN_FILTER_CONVERTER_ATTRIBUTE_MATCH_FLAG "matchFlag" +#define TIZEN_FILTER_CONVERTER_ATTRIBUTE_MATCH_VALUE "matchValue" +#define TIZEN_FILTER_CONVERTER_ATTRIBUTE_INITIAL_VALUE "initialValue" +#define TIZEN_FILTER_CONVERTER_ATTRIBUTE_END_VALUE "endValue" + +namespace DeviceAPI { +namespace Tizen { + +using namespace DeviceAPI::Tizen; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +using namespace std; + +BaseFilterConverter::BaseFilterConverter(JSContextRef context) : Converter(context) +{ + LoggerD("entered"); +} + +BaseFilterConverter::~BaseFilterConverter() +{ + LoggerD("entered"); +} + +JSValueRef BaseFilterConverter::toJSValueRef(const SortModePtr& arg) +{ + if(arg == NULL) + ThrowMsg(NullPointerException, "SortMode is NULL."); + + return WrtDeviceApis::CommonsJavaScript::JSUtils::makeObject(m_context, JSSortMode::getClassRef(), arg); +} + +SortModePtr BaseFilterConverter::toSortMode(const JSValueRef& arg) +{ + if(arg == NULL) + ThrowMsg(NullPointerException, "JSValueRef is NULL."); + + if(!JSSortMode::isObjectOfClass(m_context, arg)) + ThrowMsg(WrtDeviceApis::Commons::ConversionException, "Wrong attribute"); + + return JSSortMode::getSortMode(m_context, arg); +} + +JSValueRef BaseFilterConverter::toJSValueRef(const SortModeArrayPtr& arg) +{ + // Not used any more. + if(arg == NULL) + ThrowMsg(NullPointerException, "SortModeArray is NULL."); + + int size = arg->size(); + + JSObjectRef resultObject = JSCreateArrayObject(m_context, 0, NULL); + if (!resultObject) + ThrowMsg(ConversionException, "Can not create array object."); + + for(int i = 0; i < size; i++) + { + JSValueRef jsvalue = toJSValueRef(arg->at(i)); + if (!JSSetArrayElement(m_context, resultObject, i, jsvalue)) + ThrowMsg(ConversionException, "Can not fill SortMode array."); + } + + return static_cast<JSValueRef>(resultObject); +} + +SortModeArrayPtr BaseFilterConverter::toSortModeArray(const JSValueRef& arg) +{ + // Not used any more. + if(arg == NULL) + ThrowMsg(NullPointerException, "JSValueRef is NULL."); + + if(!JSIsArrayValue(m_context, arg)) + ThrowMsg(InvalidArgumentException, "Not an array type."); + + SortModeArrayPtr sortModeArray = SortModeArrayPtr(new SortModeArray()); + JSObjectRef object = toJSObjectRef(arg); + + unsigned int length = JSGetArrayLength(m_context, object); + for(unsigned int i=0; i<length; i++) + { + JSValueRef value = JSGetArrayElement(m_context, object, i); + + if(JSValueIsNull(m_context, value) || JSValueIsUndefined(m_context, value)) { + ThrowMsg(InvalidArgumentException, "CompositeFilter.filters has null elements."); + } + + SortModePtr sortMode = toSortMode(value); + + sortModeArray->push_back(sortMode); + } + + return sortModeArray; +} + +JSValueRef BaseFilterConverter::toJSValueRef(const FilterType& arg) +{ + string compositeFilterTypeStr; + + if(arg == UNION_FILTER) + compositeFilterTypeStr = "UNION"; + else if(arg == INTERSECTION_FILTER) + compositeFilterTypeStr = "INTERSECTION"; + else + ThrowMsg(ConversionException, "Can not create CompositeFilterType."); + + return toJSValueRef(compositeFilterTypeStr); +} + +FilterType BaseFilterConverter::toCompositeFilterType(const JSValueRef& arg) +{ + if(arg == NULL) + ThrowMsg(NullPointerException, "JSValueRef is NULL."); + + if(!JSValueIsString(m_context, arg)) + ThrowMsg(InvalidArgumentException, "Value is not an string."); + + string compositeFilterTypeStr = toString(arg); + FilterType compositeFilterType; + + if(compositeFilterTypeStr == "UNION") + compositeFilterType = UNION_FILTER; + else if(compositeFilterTypeStr == "INTERSECTION") + compositeFilterType = INTERSECTION_FILTER; + else + ThrowMsg(InvalidArgumentException, "CompositeFilterType cannot have " << compositeFilterTypeStr); + + return compositeFilterType; +} + +JSValueRef BaseFilterConverter::toJSValueRef(const MatchFlag& arg) +{ + string matchFlagStr; + + if(arg == MATCH_EXACTLY) + matchFlagStr = "EXACTLY"; + else if(arg == MATCH_FULLSTRING) + matchFlagStr = "FULLSTRING"; + else if(arg == MATCH_CONTAINS) + matchFlagStr = "CONTAINS"; + else if(arg == MATCH_STARTSWITH) + matchFlagStr = "STARTSWITH"; + else if(arg == MATCH_ENDSWITH) + matchFlagStr = "ENDSWITH"; + else if(arg == MATCH_EXISTS) + matchFlagStr = "EXISTS"; + else + ThrowMsg(ConversionException, "Can not create MatchFlag."); + + return toJSValueRef(matchFlagStr); +} + +MatchFlag BaseFilterConverter::toMatchFlag(const JSValueRef& arg) +{ + if(arg == NULL) + ThrowMsg(NullPointerException, "JSValueRef is NULL."); + + if(!JSValueIsString(m_context, arg)) + ThrowMsg(InvalidArgumentException, "Value is not an string."); + + string matchFlagStr = toString(arg); + MatchFlag matchFlag; + + if(matchFlagStr == "EXACTLY") + matchFlag = MATCH_EXACTLY; + else if(matchFlagStr == "FULLSTRING") + matchFlag = MATCH_FULLSTRING; + else if(matchFlagStr == "CONTAINS") + matchFlag = MATCH_CONTAINS; + else if(matchFlagStr == "STARTSWITH") + matchFlag = MATCH_STARTSWITH; + else if(matchFlagStr == "ENDSWITH") + matchFlag = MATCH_ENDSWITH; + else if(matchFlagStr == "EXISTS") + matchFlag = MATCH_EXISTS; + else + ThrowMsg(InvalidArgumentException, "FilterMatchFlag cannot have " << matchFlagStr); + + return matchFlag; +} + +JSValueRef BaseFilterConverter::toJSValueRef(const SortOrder& arg) +{ + string sortOrderStr; + + if(arg == ASCENDING_SORT_ORDER) + sortOrderStr = "ASC"; + else if(arg == DESCENDING_SORT_ORDER) + sortOrderStr = "DESC"; + else + ThrowMsg(ConversionException, "Can not create SortModeOrder."); + + return toJSValueRef(sortOrderStr); +} + +SortOrder BaseFilterConverter::toSortOrder(const JSValueRef& arg) +{ + if(arg == NULL) + ThrowMsg(NullPointerException, "JSValueRef is NULL."); + + if(!JSValueIsString(m_context, arg)) + ThrowMsg(InvalidArgumentException, "Value is not an string."); + + string sortOrderStr = toString(arg); + SortOrder sortOrder; + + if(sortOrderStr == "ASC") + sortOrder = ASCENDING_SORT_ORDER; + else if(sortOrderStr == "DESC") + sortOrder = DESCENDING_SORT_ORDER; + else + ThrowMsg(InvalidArgumentException, "SortModeOrder cannot have " << sortOrderStr); + + return sortOrder; +} + +FilterConverter::FilterConverter(JSContextRef context, PropertyStructArray properties, bool exception) : + BaseFilterConverter(context), + IFilterProperties(properties), + m_exception(exception) +{ + LoggerD("entered"); +} + +FilterConverter::~FilterConverter() +{ + LoggerD("entered"); +} + +JSValueRef FilterConverter::toJSValueRef(FilterPtr arg) +{ + if(arg == NULL) + ThrowMsg(NullPointerException, "Filter is NULL."); + + JSValueRef result = NULL; + + if(arg->getFilterType() == UNION_FILTER || arg->getFilterType() == INTERSECTION_FILTER) + { + CompositeFilterPtr filter = DPL::DynamicPointerCast<CompositeFilter>(arg); + + result = toJSValueRef(filter); + } + else if(arg->getFilterType() == ATTRIBUTE_FILTER) + { + AttributeFilterPtr filter = DPL::DynamicPointerCast<AttributeFilter>(arg); + + result = toJSValueRef(filter); + } + else if(arg->getFilterType() == ATTRIBUTE_RANGE_FILTER) + { + AttributeRangeFilterPtr filter = DPL::DynamicPointerCast<AttributeRangeFilter>(arg); + + result = toJSValueRef(filter); + } + + return result; +} + +FilterPtr FilterConverter::toFilter(const JSValueRef& arg) +{ + if(arg == NULL) + ThrowMsg(NullPointerException, "JSValueRef is NULL."); + + if(!JSValueIsObject(m_context, arg)) + return FilterPtr(NULL); + //ThrowMsg(InvalidArgumentException, "Filter is not object."); + + if(JSCompositeFilter::isObjectOfClass(m_context, arg)) + return DPL::StaticPointerCast<IFilter>(toCompositeFilter(arg)); + + if(JSAttributeFilter::isObjectOfClass(m_context, arg)) + return DPL::StaticPointerCast<IFilter>(toAttributeFilter(arg)); + + if(JSAttributeRangeFilter::isObjectOfClass(m_context, arg)) + return DPL::StaticPointerCast<IFilter>(toAttributeRangeFilter(arg)); + + //ThrowMsg(WrtDeviceApis::Commons::ConversionException, "Wrong attribute"); + return FilterPtr(NULL); +} + +JSValueRef FilterConverter::toJSValueRef(const FilterArrayPtr& arg) +{ + if(arg == NULL) + ThrowMsg(NullPointerException, "FilterArray is NULL."); + + int size = arg->size(); + + JSObjectRef resultObject = JSCreateArrayObject(m_context, 0, NULL); + if (!resultObject) + ThrowMsg(ConversionException, "Can not create array object."); + + for(int i = 0; i < size; i++) + { + JSValueRef jsvalue = toJSValueRef(arg->at(i)); + if(jsvalue == NULL) + continue; + + if (!JSSetArrayElement(m_context, resultObject, i, jsvalue)) + ThrowMsg(ConversionException, "Can not fill Filter array."); + } + + return static_cast<JSValueRef>(resultObject); +} + +FilterArrayPtr FilterConverter::toFilterArray(const JSValueRef& arg) +{ + if(arg == NULL) + ThrowMsg(NullPointerException, "JSValueRef is NULL."); + + if(!JSIsArrayValue(m_context, arg)) + ThrowMsg(InvalidArgumentException, "JSValueRef is not Array."); + + FilterArrayPtr retVal; + + JSObjectRef obj = toJSObjectRef(arg); + retVal = FilterArrayPtr(new FilterArray()); + + unsigned int length = JSGetArrayLength(m_context, obj); + for(unsigned int i=0; i<length; i++) + { + JSValueRef value = JSGetArrayElement(m_context, obj, i); + if(value == NULL) + { + LoggerW("value is NULL (" << i << ")"); + continue; + } + + FilterPtr filter(NULL); + filter = toFilter(value); + if(filter == NULL) + { + LoggerW("Element is not an AbstractFilter (" << i << ")"); + continue; + } + + retVal->push_back(filter); + } + + return retVal; +} + +JSValueRef FilterConverter::toJSValueRef(const CompositeFilterPtr& arg) +{ + if(arg == NULL) + ThrowMsg(NullPointerException, "CompositeFilter is NULL."); + + const ScopedJSStringRef jsStrFilters(JSStringCreateWithUTF8CString(TIZEN_FILTER_CONVERTER_ATTRIBUTE_FILTERS)); + JSValueRef jsValueFilters = toJSValueRef(arg->getFilters()); + + JSObjectRef jsValueResult = WrtDeviceApis::CommonsJavaScript::JSUtils::makeObject(m_context, JSCompositeFilter::getClassRef(), arg); + + JSObjectSetProperty(m_context, jsValueResult, jsStrFilters.get(), jsValueFilters, kJSPropertyAttributeNone, NULL); + + return jsValueResult; +} + +CompositeFilterPtr FilterConverter::toCompositeFilter(const JSValueRef& arg) +{ + if(arg == NULL) + ThrowMsg(NullPointerException, "JSValueRef is NULL."); + + if(!JSCompositeFilter::isObjectOfClass(m_context, arg)) + ThrowMsg(WrtDeviceApis::Commons::ConversionException, "Wrong attribute"); + + CompositeFilterPtr compositeFilter = JSCompositeFilter::getCompositeFilter(m_context, arg); + + FilterArrayPtr filters = FilterArrayPtr(new FilterArray()); + + const ScopedJSStringRef jsStrFilters(JSStringCreateWithUTF8CString(TIZEN_FILTER_CONVERTER_ATTRIBUTE_FILTERS)); + JSObjectRef argObj = JSValueToObject(m_context, arg, NULL); + JSValueRef jsValueFilters = JSObjectGetProperty(m_context, argObj, jsStrFilters.get(), NULL); + filters = toFilterArray(jsValueFilters); + compositeFilter->setFilters(filters); + + return compositeFilter; +} + +JSValueRef FilterConverter::toJSValueRef(const AttributeFilterPtr& arg) +{ + if(arg == NULL) + ThrowMsg(NullPointerException, "AttributeFilter is NULL."); + + return JSAttributeFilter::createJSObject(m_context, arg, JSValueMakeUndefined(m_context)); +} + +AttributeFilterPtr FilterConverter::toAttributeFilter(const JSValueRef& arg) +{ + if(arg == NULL) + ThrowMsg(NullPointerException, "JSValueRef is NULL."); + + if(!JSAttributeFilter::isObjectOfClass(m_context, arg)) + ThrowMsg(WrtDeviceApis::Commons::ConversionException, "Wrong attribute"); + + AttributeFilterPtr attributeFilter = JSAttributeFilter::getAttributeFilter(m_context, arg); + + const ScopedJSStringRef jsStrMatchValue(JSStringCreateWithUTF8CString(TIZEN_FILTER_CONVERTER_ATTRIBUTE_MATCH_VALUE)); + JSObjectRef argObj = JSValueToObject(m_context, arg, NULL); + + JSValueRef jsValueMatchValue = JSObjectGetProperty(m_context, argObj, jsStrMatchValue.get(), NULL); + AnyPtr any = toAny(jsValueMatchValue, attributeFilter->getAttributeName()); + + toAnyCustom(jsValueMatchValue, attributeFilter->getAttributeName(), any); + + attributeFilter->setMatchValue(any); + + return attributeFilter; +} + +JSValueRef FilterConverter::toJSValueRef(const AttributeRangeFilterPtr& arg) +{ + if(arg == NULL) + ThrowMsg(NullPointerException, "AttributeRangeFilter is NULL."); + + return JSAttributeRangeFilter::createJSObject(m_context, arg, + JSValueMakeUndefined(m_context), JSValueMakeUndefined(m_context)); +} + +AttributeRangeFilterPtr FilterConverter::toAttributeRangeFilter(const JSValueRef& arg) +{ + if(arg == NULL) + ThrowMsg(NullPointerException, "JSValueRef is NULL."); + + if(!JSAttributeRangeFilter::isObjectOfClass(m_context, arg)) + ThrowMsg(WrtDeviceApis::Commons::ConversionException, "Wrong attribute"); + + AttributeRangeFilterPtr attributeRangeFilter = JSAttributeRangeFilter::getAttributeRangeFilter(m_context, arg); + + const ScopedJSStringRef jsStrInitialValue(JSStringCreateWithUTF8CString(TIZEN_FILTER_CONVERTER_ATTRIBUTE_INITIAL_VALUE)); + const ScopedJSStringRef jsStrEndValue(JSStringCreateWithUTF8CString(TIZEN_FILTER_CONVERTER_ATTRIBUTE_END_VALUE)); + + JSObjectRef argObj = JSValueToObject(m_context, arg, NULL); + + JSValueRef jsValueInitialValue = JSObjectGetProperty(m_context, argObj, jsStrInitialValue.get(), NULL); + AnyPtr anyInit = toAny(jsValueInitialValue, attributeRangeFilter->getAttributeName()); + toAnyCustom(jsValueInitialValue, attributeRangeFilter->getAttributeName(), anyInit); + attributeRangeFilter->setInitialValue(anyInit); + + JSValueRef jsValueEndValue = JSObjectGetProperty(m_context, argObj, jsStrEndValue.get(), NULL); + AnyPtr anyEnd = toAny(jsValueEndValue, attributeRangeFilter->getAttributeName()); + toAnyCustom(jsValueEndValue, attributeRangeFilter->getAttributeName(), anyEnd); + attributeRangeFilter->setEndValue(anyEnd); + + return attributeRangeFilter; +} + +JSValueRef FilterConverter::toJSValueRef(const AnyPtr &arg) +{ + PrimitiveType type = arg->getType(); + + switch(type) + { + case PrimitiveType_NoType: + case PrimitiveType_Null: + return JSValueMakeNull(m_context); + break; + case PrimitiveType_Boolean: + return toJSValueRef(arg->getBool()); + break; + case PrimitiveType_Long: + return toJSValueRef(arg->getLong()); + break; + case PrimitiveType_ULong: + return toJSValueRef(arg->getULong()); + break; + case PrimitiveType_LongLong: + return toJSValueRef(arg->getLongLong()); + break; + case PrimitiveType_ULongLong: + return toJSValueRef(static_cast<double>(arg->getULong())); + break; + case PrimitiveType_Double: + return toJSValueRef(arg->getDouble()); + break; + case PrimitiveType_String: + return toJSValueRef(arg->getString()); + break; + case PrimitiveType_Time: + return toJSValueRef(*arg->getDateTm()); + break; + case PrimitiveType_Object: + case PrimitiveType_PlatformObject: + default: + break; + } + return JSValueMakeUndefined(m_context); +} + +AnyPtr FilterConverter::toAny(const JSValueRef& arg, const string &attrName) +{ + PrimitiveType type = PrimitiveType_NoType; + PropertyPtr property = findProperty(attrName); + if(property != NULL) + type = property->type; + else if(m_exception) + ThrowMsg(InvalidArgumentException, "Filter cannot have attribute name : " << attrName); + + if(m_exception) + return AnyFactory::createAny(m_context, arg, type); + + return AnyFactory::createAnyNoException(m_context, arg, type); +} + +void FilterConverter::toAnyCustom(const JSValueRef& arg, const std::string &attrName, AnyPtr& any) const +{ +} + +} // Tizen +} // DeviceAPI + diff --git a/wearable_src/Tizen/FilterConverter.h b/wearable_src/Tizen/FilterConverter.h new file mode 100644 index 0000000..4b4ba87 --- /dev/null +++ b/wearable_src/Tizen/FilterConverter.h @@ -0,0 +1,103 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 FilterConverter.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @description Reference from CalendarConverter.h + */ + +#ifndef _TIZEN_FILTER_CONVERTER_H_ +#define _TIZEN_FILTER_CONVERTER_H_ + +#include <vector> +#include <string> +#include <CommonsJavaScript/Converter.h> +#include "IFilter.h" +#include "IFilterProperties.h" +#include "CompositeFilter.h" +#include "AttributeFilter.h" +#include "AttributeRangeFilter.h" +#include "SortMode.h" +#include "AnyType.h" + +namespace DeviceAPI { +namespace Tizen { + +class BaseFilterConverter : public WrtDeviceApis::CommonsJavaScript::Converter +{ +public: + using WrtDeviceApis::CommonsJavaScript::Converter::toJSValueRef; + + explicit BaseFilterConverter(JSContextRef context); + virtual ~BaseFilterConverter(); + + JSValueRef toJSValueRef(const SortModePtr& arg); + SortModePtr toSortMode(const JSValueRef& arg); + + JSValueRef toJSValueRef(const SortModeArrayPtr& arg); + SortModeArrayPtr toSortModeArray(const JSValueRef& arg); + + JSValueRef toJSValueRef(const FilterType& arg); + FilterType toCompositeFilterType(const JSValueRef& arg); + + JSValueRef toJSValueRef(const MatchFlag& arg); + MatchFlag toMatchFlag(const JSValueRef& arg); + + JSValueRef toJSValueRef(const SortOrder& arg); + SortOrder toSortOrder(const JSValueRef& arg); +}; + +class FilterConverter : public BaseFilterConverter, private IFilterProperties +{ +public: + using WrtDeviceApis::CommonsJavaScript::Converter::toJSValueRef; + + explicit FilterConverter(JSContextRef context, PropertyStructArray properties, bool exception=false); + virtual ~FilterConverter(); + + JSValueRef toJSValueRef(FilterPtr arg); + FilterPtr toFilter(const JSValueRef& arg); + + JSValueRef toJSValueRef(const FilterArrayPtr& arg); + FilterArrayPtr toFilterArray(const JSValueRef& arg); + + JSValueRef toJSValueRef(const CompositeFilterPtr& arg); + CompositeFilterPtr toCompositeFilter(const JSValueRef& arg); + + JSValueRef toJSValueRef(const AttributeFilterPtr& arg); + AttributeFilterPtr toAttributeFilter(const JSValueRef& arg); + + JSValueRef toJSValueRef(const AttributeRangeFilterPtr& arg); + AttributeRangeFilterPtr toAttributeRangeFilter(const JSValueRef& arg); + + JSValueRef toJSValueRef(const AnyPtr &arg); + AnyPtr toAny(const JSValueRef& arg, const std::string &attrName); + + virtual void toAnyCustom(const JSValueRef& arg, const std::string &attrName, AnyPtr& any) const; + +private: + bool m_exception; +}; + +typedef WrtDeviceApis::CommonsJavaScript::ConverterFactory<BaseFilterConverter> FilterConverterFactory; + +} // Tizen +} // DeviceAPI + +#endif // _TIZEN_FILTER_CONVERTER_H_ diff --git a/wearable_src/Tizen/FilterFactory.cpp b/wearable_src/Tizen/FilterFactory.cpp new file mode 100644 index 0000000..e8a269e --- /dev/null +++ b/wearable_src/Tizen/FilterFactory.cpp @@ -0,0 +1,67 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 FilterFactory.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include "FilterFactory.h" + +namespace DeviceAPI {
namespace Tizen { + +using namespace std; + +CompositeFilterPtr FilterFactory::createCompositeFilterObject(const FilterType& type, + const FilterArrayPtr& filters) +{ + CompositeFilterPtr result(new CompositeFilter(type, filters)); + return result; +} + +AttributeFilterPtr FilterFactory::createAttributeFilterObject(const string& attributeName, + const MatchFlag& matchFlag, + const AnyPtr& matchValue) +{ + AttributeFilterPtr result(new AttributeFilter(attributeName, matchFlag, matchValue)); + return result; +} + +AttributeRangeFilterPtr FilterFactory::createAttributeRangeFilterObject(const string& attributeName, + const AnyPtr& initialValue, + const AnyPtr& endValue) +{ + AttributeRangeFilterPtr result(new AttributeRangeFilter(attributeName, initialValue, endValue)); + return result; +} + +SortModePtr FilterFactory::createSortModeObject(const string& attributeName, const SortOrder& type) +{ + SortModePtr result(new SortMode(attributeName, type)); + return result; +} + +FilterFactory& FilterFactory::getInstance() +{ + static FilterFactory theInstance; + return theInstance; +} + +} // Tizen +} // DeviceAPI diff --git a/wearable_src/Tizen/FilterFactory.h b/wearable_src/Tizen/FilterFactory.h new file mode 100644 index 0000000..7d473c4 --- /dev/null +++ b/wearable_src/Tizen/FilterFactory.h @@ -0,0 +1,65 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 FilterFactory.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _API_FILTER_FACTORY_H_ +#define _API_FILTER_FACTORY_H_ + +#include <string> +#include "CompositeFilter.h" +#include "AttributeFilter.h" +#include "AttributeRangeFilter.h" +#include "SortMode.h" +#include "AnyType.h" + +namespace DeviceAPI {
namespace Tizen { + +class FilterFactory : private DPL::Noncopyable +{ +private: + FilterFactory() + { + } + +public: + static FilterFactory& getInstance(); + + CompositeFilterPtr createCompositeFilterObject(const FilterType& type, + const FilterArrayPtr& filters); + + AttributeFilterPtr createAttributeFilterObject(const std::string& attributeName, + const MatchFlag& matchFlag, + const AnyPtr& matchValue); + + AttributeRangeFilterPtr createAttributeRangeFilterObject(const std::string& attributeName, + const AnyPtr& initialValue, + const AnyPtr& endValue); + + SortModePtr createSortModeObject(const std::string& attributeName, + const SortOrder& type = ASCENDING_SORT_ORDER); +}; + +} // Tizen +} // DeviceAPI + +#endif // _API_FILTER_FACTORY_H_ diff --git a/wearable_src/Tizen/FilterTypes.h b/wearable_src/Tizen/FilterTypes.h new file mode 100644 index 0000000..a09cef7 --- /dev/null +++ b/wearable_src/Tizen/FilterTypes.h @@ -0,0 +1,59 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 FilterTypes.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _API_FILTER_TYPES_H_ +#define _API_FILTER_TYPES_H_ + +namespace DeviceAPI {
namespace Tizen { + +enum FilterType +{ + UNION_FILTER, + INTERSECTION_FILTER, + ATTRIBUTE_FILTER, + ATTRIBUTE_RANGE_FILTER, + FILTERTYPE_COUNT +}; + +enum MatchFlag +{ + MATCH_NONE, + MATCH_EXACTLY, + MATCH_FULLSTRING, + MATCH_CONTAINS, + MATCH_STARTSWITH, + MATCH_ENDSWITH, + MATCH_EXISTS +}; + +enum SortOrder +{ + ASCENDING_SORT_ORDER = 1, + DESCENDING_SORT_ORDER = 2 +}; + +} // TizenApis +} // DeviceAPI +#endif // _API_FILTER_TYPES_H_ + diff --git a/wearable_src/Tizen/FilterValidator.cpp b/wearable_src/Tizen/FilterValidator.cpp new file mode 100644 index 0000000..c5e6b39 --- /dev/null +++ b/wearable_src/Tizen/FilterValidator.cpp @@ -0,0 +1,124 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 IFilterTracer.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include <algorithm> +#include "FilterValidator.h" + +namespace DeviceAPI { +namespace Tizen { + +using namespace std; + +FilterValidator::FilterValidator(PropertyStructArray properties) : + IFilterProperties(properties) +{ +} + +FilterValidator::~FilterValidator() +{ +} + +bool FilterValidator::validateAttribute(std::string& attrName, + MatchFlag& matchFlag, AnyPtr& matchValue, int depth) +{ + PropertyPtr prop = findProperty(attrName); + if(prop == NULL) + return false; + + if(matchValue == NULL) + return false; + + if(matchFlag == MATCH_EXISTS) + return true; + + if(prop->type == PrimitiveType_PlatformObject) + { + if(matchValue->getPriv() == NULL) + return false; + + return validateAttributeCustom(attrName, matchFlag, matchValue, depth); + } + + if(!matchValue->isType(prop->type)) + return false; + + return true; +} + +bool FilterValidator::validateAttributeRange(std::string& attrName, + AnyPtr& initialValue, AnyPtr& endValue, int depth) +{ + PropertyPtr prop = findProperty(attrName); + if(prop == NULL) + return false; + + if(initialValue == NULL || endValue == NULL) + return false; + + bool initialValueIsNull = initialValue->isNullOrUndefined(); + bool endValueIsNull = endValue->isNullOrUndefined(); + + // Invalid if both values are null + if(initialValueIsNull && endValueIsNull) + return false; + + if(prop->type == PrimitiveType_PlatformObject) + { + if(!initialValueIsNull && initialValue->getPriv() == NULL) + return false; + + if(!endValue && endValue->getPriv() == NULL) + return false; + + return validateAttributeRangeCustom(attrName, initialValue, endValue, depth); + } + + if(!initialValueIsNull && !initialValue->isType(prop->type)) + return false; + + if(!endValueIsNull && !endValue->isType(prop->type)) + return false; + + return true; +} + +bool FilterValidator::validateComposite(int depth) +{ + return true; +} + +bool FilterValidator::validateAttributeCustom(std::string& attrName, + MatchFlag& matchFlag, AnyPtr& matchValue, int depth) +{ + return true; +} + +bool FilterValidator::validateAttributeRangeCustom(std::string& attrName, + AnyPtr& initialValue, AnyPtr& endValue, int depth) +{ + return true; +} + +} // Tizen +} // DeviceAPI diff --git a/wearable_src/Tizen/FilterValidator.h b/wearable_src/Tizen/FilterValidator.h new file mode 100644 index 0000000..1110cd7 --- /dev/null +++ b/wearable_src/Tizen/FilterValidator.h @@ -0,0 +1,82 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 FilterValidator.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _API_FILTER_VALIDATOR_H_ +#define _API_FILTER_VALIDATOR_H_ + +#include <map> +#include <vector> +#include <string> +#include <dpl/shared_ptr.h> +#include "IFilterProperties.h" +#include "FilterTypes.h" +#include "AnyType.h" + +namespace DeviceAPI { +namespace Tizen { + +class IFilter; +typedef DPL::SharedPtr<IFilter> FilterPtr; +typedef std::vector<std::string> MatchFlagArray; +typedef DPL::SharedPtr<MatchFlagArray> MatchFlagArrayPtr; + +// GoF Visitor Pattern +class FilterValidator : private IFilterProperties +{ +public: + FilterValidator(PropertyStructArray properties); + + virtual ~FilterValidator(); + + // validate AttributeFilter + bool validateAttribute(std::string& attrName, + MatchFlag& matchFlag, AnyPtr& matchValue, int depth=0); + + // validate AttributeRangeFilter + bool validateAttributeRange(std::string& attrName, + AnyPtr& initialValue, AnyPtr& endValue, int depth=0); + + // validate CompositeFilter + bool validateComposite(int depth=0); + +protected: + // If type is PrimitiveType_PlatformObject or PrimitiveType_Custom, + // validateAttributeCustom function would be called to validate the attribute. + // Developer can override this function to validate the attribute. + virtual bool validateAttributeCustom(std::string& attrName, + MatchFlag& matchFlag, AnyPtr& matchValue, int depth); + + // If type is PrimitiveType_PlatformObject or PrimitiveType_Custom, + // validateAttributeRangeCustom function would be called to validate the attribute. + // Developer can override this function to validate the attribute. + virtual bool validateAttributeRangeCustom(std::string& attrName, + AnyPtr& initialValue, AnyPtr& endValue, int depth); +}; + +typedef DPL::SharedPtr<FilterValidator> FilterValidatorPtr; + +} // Tizen +} // DeviceAPI + +#endif // _API_FILTER_VALIDATOR_H_ diff --git a/wearable_src/Tizen/IFilter.cpp b/wearable_src/Tizen/IFilter.cpp new file mode 100644 index 0000000..f3fc8da --- /dev/null +++ b/wearable_src/Tizen/IFilter.cpp @@ -0,0 +1,38 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 IFilter.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include "IFilter.h" + +namespace DeviceAPI {
namespace Tizen { + +IFilter::IFilter() +{ +} + +IFilter::~IFilter() +{ +} + +} // Tizen +} // DeviceAPI diff --git a/wearable_src/Tizen/IFilter.h b/wearable_src/Tizen/IFilter.h new file mode 100644 index 0000000..29d4fe4 --- /dev/null +++ b/wearable_src/Tizen/IFilter.h @@ -0,0 +1,74 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 IFilter.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief Represents tizen AbstractFilter + */ + +#ifndef _API_IFILTER_H_ +#define _API_IFILTER_H_ + +#include <vector> +#include <dpl/shared_ptr.h> +#include "FilterTypes.h" +#include "IFilterVisitor.h" +#include "FilterValidator.h" + +namespace DeviceAPI {
namespace Tizen { + +class IFilter; +typedef DPL::SharedPtr<IFilter> FilterPtr; + +typedef std::vector<FilterPtr> FilterArray; +typedef DPL::SharedPtr<FilterArray> FilterArrayPtr; + +class IFilter +{ +private: // fields + +protected: + +public: // methods + + /** + * constructor of abstraction filter + */ + explicit IFilter(); + + virtual ~IFilter(); + + /** + * method used to identify filter type + */ + virtual FilterType getFilterType() const = 0; + + virtual bool setFilterType(const FilterType& filterType) = 0; + + // validator uses GoF visitor patter. + virtual bool validate(FilterValidatorPtr& validator, int depth = 0) = 0; + + // GoF visitor patter. + virtual void travel(IFilterVisitorPtr& visitor, int depth = 0) = 0; +}; + +} // Tizen +} // DeviceAPI + +#endif // _API_IFILTER_H_ diff --git a/wearable_src/Tizen/IFilterProperties.cpp b/wearable_src/Tizen/IFilterProperties.cpp new file mode 100644 index 0000000..cdad694 --- /dev/null +++ b/wearable_src/Tizen/IFilterProperties.cpp @@ -0,0 +1,54 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 IFilterProperties.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include "IFilterProperties.h" + +namespace DeviceAPI { +namespace Tizen { + +using namespace std; + +IFilterProperties::IFilterProperties(PropertyStructArray properties) +{ + int i; + for(i=0; properties[i].attributeName != 0 ; i++) + m_properties[properties[i].attributeName] = + PropertyPtr(new Property(properties[i].type)); +} + +IFilterProperties::~IFilterProperties() +{ +} + +IFilterProperties::PropertyPtr IFilterProperties::findProperty(const std::string& attrName) const +{ + PropertyMap::const_iterator iter = m_properties.find(attrName); + if(iter == m_properties.end()) + return PropertyPtr(NULL); + + return iter->second; +} + +} // Tizen +} // DeviceAPI diff --git a/wearable_src/Tizen/IFilterProperties.h b/wearable_src/Tizen/IFilterProperties.h new file mode 100644 index 0000000..5ddd6e0 --- /dev/null +++ b/wearable_src/Tizen/IFilterProperties.h @@ -0,0 +1,71 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 IFilterProperties.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _API_IFILTER_PROPERTIES_H_ +#define _API_IFILTER_PROPERTIES_H_ + +#include <map> +#include <vector> +#include <string> +#include <dpl/shared_ptr.h> +#include "AnyType.h" + +namespace DeviceAPI { +namespace Tizen { + +struct PropertyStruct +{ + const char * attributeName; + const PrimitiveType type; +}; +typedef PropertyStruct PropertyStructArray[]; + +class IFilterProperties +{ +protected: + class Property + { + public: + Property(PrimitiveType pType) : + type(pType) {} + PrimitiveType type; + }; + typedef DPL::SharedPtr<Property> PropertyPtr; + +private: + typedef std::map<std::string, PropertyPtr> PropertyMap; + PropertyMap m_properties; + +public: + IFilterProperties(PropertyStructArray properties); + virtual ~IFilterProperties(); + +protected: + PropertyPtr findProperty(const std::string &attrName) const; +}; + +} // Tizen +} // DeviceAPI + +#endif // _API_IFILTER_PROPERTIES_H_ diff --git a/wearable_src/Tizen/IFilterVisitor.cpp b/wearable_src/Tizen/IFilterVisitor.cpp new file mode 100644 index 0000000..9f97752 --- /dev/null +++ b/wearable_src/Tizen/IFilterVisitor.cpp @@ -0,0 +1,41 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 IFilterVisitor.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include <algorithm> +#include <Commons/Exception.h> +#include "IFilterVisitor.h" +#include <Logger.h> + +namespace DeviceAPI {
namespace Tizen { + +IFilterVisitor::IFilterVisitor() +{ +} + +IFilterVisitor::~IFilterVisitor() +{ +} + +} // Tizen +} // DeviceAPI diff --git a/wearable_src/Tizen/IFilterVisitor.h b/wearable_src/Tizen/IFilterVisitor.h new file mode 100644 index 0000000..d87b025 --- /dev/null +++ b/wearable_src/Tizen/IFilterVisitor.h @@ -0,0 +1,61 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 IFilterVisitor.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _API_IFILTER_VISITOR_H_ +#define _API_IFILTER_VISITOR_H_ + +#include <vector> +#include <string> +#include <dpl/shared_ptr.h> +#include "AnyType.h" +#include "FilterTypes.h" + +namespace DeviceAPI {
namespace Tizen { + +class IFilter; +typedef DPL::SharedPtr<IFilter> FilterPtr; +typedef std::vector<std::string> MatchFlagArray; +typedef DPL::SharedPtr<MatchFlagArray> MatchFlagArrayPtr; + +// GoF Visitor Pattern +class IFilterVisitor +{ +public: + IFilterVisitor(); + virtual ~IFilterVisitor(); + + virtual void visitPreComposite(FilterType& type, int depth) = 0; + virtual void visitInComposite(FilterType& type, int depth) = 0; + virtual void visitPostComposite(FilterType& type, int depth) = 0; + virtual void visitAttribute(std::string& attrName, + MatchFlag& matchFlag, AnyPtr& matchValue, int depth) = 0; + virtual void visitAttributeRange(std::string& attrName, AnyPtr& initialValue, AnyPtr& endValue, int depth) = 0; +}; + +typedef DPL::SharedPtr<IFilterVisitor> IFilterVisitorPtr; + +} // Tizen +} // DeviceAPI + +#endif // _API_IFILTER_VISITOR_H_ diff --git a/wearable_src/Tizen/JSAttributeFilter.cpp b/wearable_src/Tizen/JSAttributeFilter.cpp new file mode 100644 index 0000000..2e6c167 --- /dev/null +++ b/wearable_src/Tizen/JSAttributeFilter.cpp @@ -0,0 +1,371 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 JSAttributeFilter.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief Implementation of the JSAttributeFilter class + */ + +#include "JSAttributeFilter.h" + +#include <string> +#include <dpl/shared_ptr.h> +#include <CommonsJavaScript/ScopedJSStringRef.h> +#include <JSUtil.h> +#include <ArgumentValidator.h> +#include <JSWebAPIErrorFactory.h> +#include "AnyFactory.h" +#include <Logger.h> + +#define ATTRIBUTE_FILTER_CLASS_NAME "AttributeFilter" +#define ATTRIBUTE_FILTER_ATTR_ATTRIBUTE_NAME "attributeName" +#define ATTRIBUTE_FILTER_ATTR_MATCH_FLAG "matchFlag" +#define ATTRIBUTE_FILTER_ATTR_MATCH_VALUE "matchValue" + +namespace DeviceAPI { +namespace Tizen { + +using namespace DeviceAPI::Common; +using namespace DeviceAPI::Tizen; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +JSClassRef JSAttributeFilter::m_classRef = NULL; + +JSClassDefinition JSAttributeFilter::m_classInfo = +{ + 0, + kJSClassAttributeNone, + ATTRIBUTE_FILTER_CLASS_NAME, + NULL, + m_property, + m_functions, + Initialize, + Finalize, + NULL, //hasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //getPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL, //ConvertToType, +}; + +JSStaticValue JSAttributeFilter::m_property[] = { + { ATTRIBUTE_FILTER_ATTR_ATTRIBUTE_NAME, getAttributeName, setAttributeName, kJSPropertyAttributeNone }, + { ATTRIBUTE_FILTER_ATTR_MATCH_FLAG, getMatchFlag, setMatchFlag, kJSPropertyAttributeNone }, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSAttributeFilter::m_functions[] = +{ + { 0, 0, 0 } +}; + +JSClassRef JSAttributeFilter::getClassRef() { + if (!m_classRef) + m_classRef = JSClassCreate(&m_classInfo); + + return m_classRef; +} + +bool JSAttributeFilter::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +AttributeFilterPtr JSAttributeFilter::getAttributeFilter(JSContextRef context, JSValueRef value) +{ + if (!isObjectOfClass(context, value)) + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + + JSAttributeFilterPriv *priv = static_cast<JSAttributeFilterPriv*>(JSObjectGetPrivate(object)); + if (!priv) + Throw(WrtDeviceApis::Commons::NullPointerException); + + return priv->getObject(); +} + +JSObjectRef JSAttributeFilter::createJSObject(JSContextRef context, + AttributeFilterPtr privateData, + JSValueRef jsValueMatchValue) +{ + JSAttributeFilterPriv *priv = new JSAttributeFilterPriv(context, privateData); + JSObjectRef jsObjectRef = JSObjectMake(context, getClassRef(), static_cast<void*>(priv)); + if (NULL == jsObjectRef) + { + LoggerE("object creation error"); + return NULL; + } + + const ScopedJSStringRef jsStrMatchValue(JSStringCreateWithUTF8CString(ATTRIBUTE_FILTER_ATTR_MATCH_VALUE)); + + JSObjectSetProperty(context, jsObjectRef, jsStrMatchValue.get(), + jsValueMatchValue, kJSPropertyAttributeNone, NULL); + + return jsObjectRef; +} + +JSObjectRef JSAttributeFilter::constructor(JSContextRef context, + JSObjectRef constructor, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("entered"); + + std::string attributeName; + MatchFlag matchFlag; + AnyPtr matchValue(NULL); + JSValueRef jsValueMatchValue = NULL; + + ArgumentValidator validator(context, argumentCount, arguments); + + try + { + attributeName = validator.toString(0, false); + } + catch(BasePlatformException &e) + { + LoggerW("Failed to convert 1st parameter to string. Using default value."); + attributeName = ""; + } + + try + { + std::string matchFlagStr; + if(argumentCount < 2 || + JSValueIsUndefined(context, arguments[1]) || + JSValueIsNull(context, arguments[1])) + matchFlagStr = "EXACTLY"; + else + matchFlagStr = validator.toString(1, true); + + if(matchFlagStr == "EXACTLY") + matchFlag = MATCH_EXACTLY; + else if(matchFlagStr == "FULLSTRING") + matchFlag = MATCH_FULLSTRING; + else if(matchFlagStr == "CONTAINS") + matchFlag = MATCH_CONTAINS; + else if(matchFlagStr == "STARTSWITH") + matchFlag = MATCH_STARTSWITH; + else if(matchFlagStr == "ENDSWITH") + matchFlag = MATCH_ENDSWITH; + else if(matchFlagStr == "EXISTS") + matchFlag = MATCH_EXISTS; + else + throw TypeMismatchException("Property is not valid FilterMatchFlag value"); + } + catch(BasePlatformException &e) + { + LoggerW("Failed to convert 2nd parameter to match flag. Using default value."); + matchFlag = MATCH_EXACTLY; + } + + matchValue = AnyFactory::createAnyEmpty(context); + + if(argumentCount >= 3) + jsValueMatchValue = arguments[2]; + else + jsValueMatchValue = JSValueMakeNull(context); + + AttributeFilterPtr attributeFilter(new AttributeFilter(attributeName, matchFlag, matchValue)); + + JSObjectRef jsobject = NULL; + + Try + { + jsobject = createJSObject(context, attributeFilter, jsValueMatchValue); + } + Catch(Exception) + { + LoggerE("Argument type mismatch : " << _rethrown_exception.GetMessage()); + } + + if(jsobject == NULL) + return JSObjectMake(context, NULL, NULL); + + return jsobject; +} + +void JSAttributeFilter::Initialize(JSContextRef context, JSObjectRef object) +{ + if (!JSObjectGetPrivate(object)) + { + AttributeFilterPtr filter(new AttributeFilter("", MATCH_NONE, AnyPtr(NULL))); + JSAttributeFilterPriv *priv = new JSAttributeFilterPriv(context, AttributeFilterPtr(filter)); + if (!JSObjectSetPrivate(object, priv)) + { + delete priv; + } + } +} + +void JSAttributeFilter::Finalize(JSObjectRef object) +{ + JSAttributeFilterPriv *priv = static_cast<JSAttributeFilterPriv*>(JSObjectGetPrivate(object)); + + if (priv != NULL) + { + delete (priv); + } + + priv = NULL; +} + +AttributeFilterPtr JSAttributeFilter::getPrivData(JSObjectRef object) +{ + LoggerD("entered"); + JSAttributeFilterPriv *priv = static_cast<JSAttributeFilterPriv*>(JSObjectGetPrivate(object)); + if (!priv) + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Private object is null"); + + AttributeFilterPtr result = priv->getObject(); + if (!result) + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Private object is null"); + + return result; +} + +JSValueRef JSAttributeFilter::getAttributeName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LoggerD("entered"); + + try + { + AttributeFilterPtr attributeFilter = getPrivData(object); + return JSUtil::toJSValueRef(context, attributeFilter->getAttributeName()); + } + catch(BasePlatformException &e) + { + LoggerW("trying to get incorrect value [" << e.getName() << "] " << e.getMessage()); + } + + return JSValueMakeUndefined(context); +} + +bool JSAttributeFilter::setAttributeName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + LoggerD("entered"); + + try + { + AttributeFilterPtr attributeFilter = getPrivData(object); + attributeFilter->setAttributeName(JSUtil::JSValueToString(context, value)); + } + catch(BasePlatformException &e) + { + LoggerW("trying to set incorrect value [" << e.getName() << "] " << e.getMessage()); + } + + return true; +} + +JSValueRef JSAttributeFilter::getMatchFlag(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LoggerD("entered"); + + try + { + AttributeFilterPtr attributeFilter = getPrivData(object); + MatchFlag matchFlag = attributeFilter->getMatchFlag(); + std::string matchFlagStr; + if(matchFlag == MATCH_EXACTLY) + matchFlagStr = "EXACTLY"; + else if(matchFlag == MATCH_FULLSTRING) + matchFlagStr = "FULLSTRING"; + else if(matchFlag == MATCH_CONTAINS) + matchFlagStr = "CONTAINS"; + else if(matchFlag == MATCH_STARTSWITH) + matchFlagStr = "STARTSWITH"; + else if(matchFlag == MATCH_ENDSWITH) + matchFlagStr = "ENDSWITH"; + else if(matchFlag == MATCH_EXISTS) + matchFlagStr = "EXISTS"; + else + matchFlagStr = "EXACTLY"; + + return JSUtil::toJSValueRef(context, matchFlagStr); + } + catch(BasePlatformException &e) + { + LoggerW("trying to get incorrect value [" << e.getName() << "] " << e.getMessage()); + } + + return JSValueMakeUndefined(context); +} + +bool JSAttributeFilter::setMatchFlag(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + LoggerD("entered"); + + try + { + AttributeFilterPtr attributeFilter = getPrivData(object); + + MatchFlag matchFlag; + std::string matchFlagStr = JSUtil::JSValueToString(context, value); + + if(matchFlagStr == "EXACTLY") + matchFlag = MATCH_EXACTLY; + else if(matchFlagStr == "FULLSTRING") + matchFlag = MATCH_FULLSTRING; + else if(matchFlagStr == "CONTAINS") + matchFlag = MATCH_CONTAINS; + else if(matchFlagStr == "STARTSWITH") + matchFlag = MATCH_STARTSWITH; + else if(matchFlagStr == "ENDSWITH") + matchFlag = MATCH_ENDSWITH; + else if(matchFlagStr == "EXISTS") + matchFlag = MATCH_EXISTS; + else + throw TypeMismatchException("Property is not valid FilterMatchFlag value"); + + attributeFilter->setMatchFlag(matchFlag); + } + catch(BasePlatformException &e) + { + LoggerW("trying to set incorrect value [" << e.getName() << "] " << e.getMessage()); + } + + return true; +} + +} // Tizen +} // DeviceAPI diff --git a/wearable_src/Tizen/JSAttributeFilter.h b/wearable_src/Tizen/JSAttributeFilter.h new file mode 100644 index 0000000..2090ab6 --- /dev/null +++ b/wearable_src/Tizen/JSAttributeFilter.h @@ -0,0 +1,118 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 JSAttributeFilter.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief Declaration of the JSAttributeFilter class + */ + +#ifndef _TIZEN_TIZEN_JS_ATTRIBUTE_FILTER_H_ +#define _TIZEN_TIZEN_JS_ATTRIBUTE_FILTER_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <dpl/shared_ptr.h> +#include <CommonsJavaScript/PrivateObject.h> +#include <Commons/IEvent.h> +#include "AttributeFilter.h" + +namespace DeviceAPI { +namespace Tizen { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject<DeviceAPI::Tizen::AttributeFilterPtr, WrtDeviceApis::CommonsJavaScript::NoOwnership> JSAttributeFilterPriv; + +class JSAttributeFilter { +public: + /* + * This initializes this JS class in the JS Engine. + */ + static JSClassRef getClassRef(); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + static DeviceAPI::Tizen::AttributeFilterPtr getAttributeFilter(JSContextRef context, JSValueRef value); + + static JSObjectRef createJSObject(JSContextRef context, + DeviceAPI::Tizen::AttributeFilterPtr privateData, + JSValueRef jsValueMatchValue); + + static JSObjectRef constructor(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 contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_functions[]; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; + + static JSClassRef m_classRef; + + static DeviceAPI::Tizen::AttributeFilterPtr getPrivData(JSObjectRef object); + + static JSValueRef getAttributeName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setAttributeName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef getMatchFlag(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setMatchFlag(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); +}; + +} // Tizen +} // DeviceAPI + + +#endif // _TIZEN_TIZEN_JS_ATTRIBUTE_FILTER_H_ diff --git a/wearable_src/Tizen/JSAttributeRangeFilter.cpp b/wearable_src/Tizen/JSAttributeRangeFilter.cpp new file mode 100644 index 0000000..3856afc --- /dev/null +++ b/wearable_src/Tizen/JSAttributeRangeFilter.cpp @@ -0,0 +1,272 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 JSAttributeRangeFilter.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief Implementation of the JSAttributeRangeFilter class + */ + +#include "JSAttributeRangeFilter.h" +#include <dpl/shared_ptr.h> +#include <CommonsJavaScript/ScopedJSStringRef.h> +#include <JSUtil.h> +#include <ArgumentValidator.h> +#include <JSWebAPIErrorFactory.h> +#include "AnyFactory.h" +#include <Logger.h> + +#define ATTRIBUTE_RANGE_FILTER_CLASS_NAME "AttributeRangeFilter" + +#define ATTRIBUTE_FILTER_ATTR_ATTRIBUTE_NAME "attributeName" +#define ATTRIBUTE_FILTER_ATTR_INITIAL_VALUE "initialValue" +#define ATTRIBUTE_FILTER_ATTR_END_VALUE "endValue" + +namespace DeviceAPI { +namespace Tizen { + +using namespace DeviceAPI::Common; +using namespace DeviceAPI::Tizen; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +JSClassRef JSAttributeRangeFilter::m_classRef = NULL; + +JSClassDefinition JSAttributeRangeFilter::m_classInfo = +{ + 0, + kJSClassAttributeNone, + ATTRIBUTE_RANGE_FILTER_CLASS_NAME, + NULL, + m_property, + m_functions, + Initialize, + Finalize, + NULL, //hasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //getPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL, //ConvertToType, +}; + +JSStaticValue JSAttributeRangeFilter::m_property[] = { + { ATTRIBUTE_FILTER_ATTR_ATTRIBUTE_NAME, getAttributeName, setAttributeName, kJSPropertyAttributeNone }, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSAttributeRangeFilter::m_functions[] = +{ + { 0, 0, 0 } +}; + +JSClassRef JSAttributeRangeFilter::getClassRef() { + if (!m_classRef) + m_classRef = JSClassCreate(&m_classInfo); + + return m_classRef; +} + +bool JSAttributeRangeFilter::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +AttributeRangeFilterPtr JSAttributeRangeFilter::getAttributeRangeFilter(JSContextRef context, JSValueRef value) +{ + if (!isObjectOfClass(context, value)) + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + + JSAttributeRangeFilterPriv *priv = static_cast<JSAttributeRangeFilterPriv*>(JSObjectGetPrivate(object)); + if (!priv) + Throw(WrtDeviceApis::Commons::NullPointerException); + + return priv->getObject(); +} + +JSObjectRef JSAttributeRangeFilter::createJSObject(JSContextRef context, + AttributeRangeFilterPtr privateData, + JSValueRef jsValueInitialValue, + JSValueRef jsValueEndValue) +{ + JSAttributeRangeFilterPriv *priv = new JSAttributeRangeFilterPriv(context, privateData); + JSObjectRef jsObjectRef = JSObjectMake(context, getClassRef(), static_cast<void*>(priv)); + if (NULL == jsObjectRef) + { + LoggerE("object creation error"); + return NULL; + } + + const ScopedJSStringRef jsStrInitialValue(JSStringCreateWithUTF8CString(ATTRIBUTE_FILTER_ATTR_INITIAL_VALUE)); + const ScopedJSStringRef jsStrEndValue(JSStringCreateWithUTF8CString(ATTRIBUTE_FILTER_ATTR_END_VALUE)); + + JSObjectSetProperty(context, jsObjectRef, jsStrInitialValue.get(), jsValueInitialValue, kJSPropertyAttributeNone, NULL); + JSObjectSetProperty(context, jsObjectRef, jsStrEndValue.get(), jsValueEndValue, kJSPropertyAttributeNone, NULL); + + return jsObjectRef; +} + +JSObjectRef JSAttributeRangeFilter::constructor(JSContextRef context, + JSObjectRef constructor, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("entered"); + + std::string attributeName; + AnyPtr initialValue(NULL); + JSValueRef jsValueInitialValue = NULL; + AnyPtr endValue(NULL); + JSValueRef jsValueEndValue = NULL; + + ArgumentValidator validator(context, argumentCount, arguments); + + try + { + attributeName = validator.toString(0, false); + } + catch(BasePlatformException &e) + { + LoggerW("Failed to convert 1st parameter to string. Using default value."); + attributeName = ""; + } + + initialValue = AnyFactory::createAnyEmpty(context); + + if(argumentCount >= 2) + jsValueInitialValue = arguments[1]; + else + jsValueInitialValue = JSValueMakeNull(context); + + endValue = AnyFactory::createAnyEmpty(context); + + if(argumentCount >= 3) + jsValueEndValue = arguments[2]; + else + jsValueEndValue = JSValueMakeNull(context); + + AttributeRangeFilterPtr attributeRangeFilter(new AttributeRangeFilter(attributeName, initialValue, endValue)); + + JSObjectRef jsobject = NULL; + + Try + { + jsobject = createJSObject(context, attributeRangeFilter, jsValueInitialValue, jsValueEndValue); + } + Catch(Exception) + { + LoggerE("Argument type mismatch : " << _rethrown_exception.GetMessage()); + } + + if(jsobject == NULL) + return JSObjectMake(context, NULL, NULL); + + return jsobject; +} + +void JSAttributeRangeFilter::Initialize(JSContextRef context, JSObjectRef object) +{ + if (!JSObjectGetPrivate(object)) + { + AttributeRangeFilterPtr filter(new AttributeRangeFilter("", AnyPtr(NULL), AnyPtr(NULL))); + JSAttributeRangeFilterPriv *priv = + new JSAttributeRangeFilterPriv(context, AttributeRangeFilterPtr(filter)); + if (!JSObjectSetPrivate(object, priv)) + { + delete priv; + } + } +} + +void JSAttributeRangeFilter::Finalize(JSObjectRef object) +{ + JSAttributeRangeFilterPriv *priv = static_cast<JSAttributeRangeFilterPriv*>(JSObjectGetPrivate(object)); + + if (priv != NULL) + { + delete (priv); + } + + priv = NULL; +} + +AttributeRangeFilterPtr JSAttributeRangeFilter::getPrivData(JSObjectRef object) +{ + LoggerD("entered"); + JSAttributeRangeFilterPriv *priv = static_cast<JSAttributeRangeFilterPriv*>(JSObjectGetPrivate(object)); + if (!priv) + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Private object is null"); + + AttributeRangeFilterPtr result = priv->getObject(); + if (!result) + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Private object is null"); + + return result; +} + +JSValueRef JSAttributeRangeFilter::getAttributeName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LoggerD("entered"); + + try + { + AttributeRangeFilterPtr attributeRangeFilter = getPrivData(object); + return JSUtil::toJSValueRef(context, attributeRangeFilter->getAttributeName()); + } + catch(BasePlatformException &e) + { + LoggerW("trying to get incorrect value [" << e.getName() << "] " << e.getMessage()); + } + + return JSValueMakeUndefined(context); +} + +bool JSAttributeRangeFilter::setAttributeName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + LoggerD("entered"); + + try + { + AttributeRangeFilterPtr attributeRangeFilter = getPrivData(object); + attributeRangeFilter->setAttributeName(JSUtil::JSValueToString(context, value)); + } + catch(BasePlatformException &e) + { + LoggerW("trying to set incorrect value [" << e.getName() << "] " << e.getMessage()); + } + + return true; +} + +} // Tizen +} // DeviceAPI diff --git a/wearable_src/Tizen/JSAttributeRangeFilter.h b/wearable_src/Tizen/JSAttributeRangeFilter.h new file mode 100644 index 0000000..8c1c0da --- /dev/null +++ b/wearable_src/Tizen/JSAttributeRangeFilter.h @@ -0,0 +1,108 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 JSAttributeRangeFilter.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief Declaration of the JSAttributeRangeFilter class + */ + +#ifndef _TIZEN_TIZEN_JS_ATTRIBUTE_RANGE_FILTER_H_ +#define _TIZEN_TIZEN_JS_ATTRIBUTE_RANGE_FILTER_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <dpl/shared_ptr.h> +#include <CommonsJavaScript/PrivateObject.h> +#include <Commons/IEvent.h> +#include "AttributeRangeFilter.h" + +namespace DeviceAPI { +namespace Tizen { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject<DeviceAPI::Tizen::AttributeRangeFilterPtr, WrtDeviceApis::CommonsJavaScript::NoOwnership> JSAttributeRangeFilterPriv; + +class JSAttributeRangeFilter { +public: + /* + * This initializes this JS class in the JS Engine. + */ + static JSClassRef getClassRef(); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + static DeviceAPI::Tizen::AttributeRangeFilterPtr getAttributeRangeFilter(JSContextRef context, JSValueRef value); + + static JSObjectRef createJSObject(JSContextRef context, + DeviceAPI::Tizen::AttributeRangeFilterPtr privateData, + JSValueRef jsValueInitialValue, + JSValueRef jsValueEndValue); + + static JSObjectRef constructor(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 contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_functions[]; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; + + static JSClassRef m_classRef; + + static DeviceAPI::Tizen::AttributeRangeFilterPtr getPrivData(JSObjectRef object); + + static JSValueRef getAttributeName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setAttributeName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); +}; + +} // Tizen +} // DeviceAPI + + +#endif // _TIZEN_TIZEN_JS_ATTRIBUTE_RANGE_FILTER_H_ diff --git a/wearable_src/Tizen/JSCompositeFilter.cpp b/wearable_src/Tizen/JSCompositeFilter.cpp new file mode 100644 index 0000000..51e11a1 --- /dev/null +++ b/wearable_src/Tizen/JSCompositeFilter.cpp @@ -0,0 +1,321 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 JSCompositeFilter.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief Implementation of the JSCompositeFilter class + */ + +#include "JSCompositeFilter.h" +#include <string> +#include <dpl/shared_ptr.h> +#include <CommonsJavaScript/ScopedJSStringRef.h> +#include <JSUtil.h> +#include <ArgumentValidator.h> +#include <JSWebAPIErrorFactory.h> +#include <Logger.h> + +#define ATTRIBUTE_FILTER_CLASS_NAME "CompositeFilter" +#define ATTRIBUTE_FILTER_ATTR_TYPE "type" +#define ATTRIBUTE_FILTER_ATTR_FILTERS "filters" + +namespace DeviceAPI { +namespace Tizen { + +using namespace DeviceAPI::Common; +using namespace DeviceAPI::Tizen; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +JSClassRef JSCompositeFilter::m_classRef = NULL; + +JSClassDefinition JSCompositeFilter::m_classInfo = +{ + 0, + kJSClassAttributeNone, + ATTRIBUTE_FILTER_CLASS_NAME, + NULL, + m_property, + m_functions, + Initialize, + Finalize, + NULL,//hasProperty, + NULL,//getProperty, + setProperty, + NULL,//deleteProperty, + NULL,//getPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL, //ConvertToType, +}; + +JSStaticValue JSCompositeFilter::m_property[] = { + { ATTRIBUTE_FILTER_ATTR_TYPE, getType, setType, kJSPropertyAttributeNone }, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSCompositeFilter::m_functions[] = +{ + { 0, 0, 0 } +}; + +JSClassRef JSCompositeFilter::getClassRef() { + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +bool JSCompositeFilter::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +CompositeFilterPtr JSCompositeFilter::getCompositeFilter(JSContextRef context, JSValueRef value) +{ + if (!isObjectOfClass(context, value)) + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + + JSCompositeFilterPriv *priv = static_cast<JSCompositeFilterPriv*>(JSObjectGetPrivate(object)); + if (!priv) + Throw(WrtDeviceApis::Commons::NullPointerException); + + return priv->getObject(); +} + +JSObjectRef JSCompositeFilter::createJSObject(JSContextRef context, + CompositeFilterPtr privateData, + JSValueRef jsValueFilters) +{ + JSCompositeFilterPriv *priv = new JSCompositeFilterPriv(context, privateData); + JSObjectRef jsObjectRef = JSObjectMake(context, getClassRef(), static_cast<void*>(priv)); + if (NULL == jsObjectRef) + { + LoggerE("object creation error"); + return NULL; + } + + const ScopedJSStringRef jsStrFilters(JSStringCreateWithUTF8CString(ATTRIBUTE_FILTER_ATTR_FILTERS)); + + JSObjectSetProperty(context, jsObjectRef, jsStrFilters.get(), jsValueFilters, kJSPropertyAttributeNone, NULL); + + return jsObjectRef; +} + +JSObjectRef JSCompositeFilter::constructor(JSContextRef context, + JSObjectRef constructor, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("entered"); + + FilterType type; + JSValueRef jsValueFilters = NULL; + + ArgumentValidator validator(context, argumentCount, arguments); + + try + { + std::string typeStr = validator.toString(0, false); + + if(typeStr == "UNION") + type = UNION_FILTER; + else if(typeStr == "INTERSECTION") + type = INTERSECTION_FILTER; + else + throw TypeMismatchException("Property is not valid CompositeFilterType value"); + } + catch(BasePlatformException &e) + { + LoggerW("Failed to convert 1st parameter to filter type. Using default value."); + type = UNION_FILTER; + } + + try + { + if(argumentCount < 2 || + JSValueIsUndefined(context, arguments[1]) || + JSValueIsNull(context, arguments[1])) + jsValueFilters = JSCreateArrayObject(context, 0, NULL); + else if(JSIsArrayValue(context, arguments[1])) + jsValueFilters = arguments[1]; + else + throw TypeMismatchException("Property is not valid Array value"); + } + catch(BasePlatformException &e) + { + LoggerW("Failed to convert 2nd parameter to filter array. Using default value."); + jsValueFilters = JSCreateArrayObject(context, 0, NULL); + } + + CompositeFilterPtr compositeFilter(new CompositeFilter(type, FilterArrayPtr(new FilterArray()))); + + JSObjectRef jsobject = NULL; + + Try + { + jsobject = createJSObject(context, compositeFilter, jsValueFilters); + } + Catch(Exception) + { + LoggerE("Argument type mismatch : " << _rethrown_exception.GetMessage()); + } + + if(jsobject == NULL) + return JSObjectMake(context, NULL, NULL); + + return jsobject; +} + +void JSCompositeFilter::Initialize(JSContextRef context, JSObjectRef object) +{ + if (!JSObjectGetPrivate(object)) + { + CompositeFilterPtr filter(new CompositeFilter(UNION_FILTER, FilterArrayPtr(NULL))); + JSCompositeFilterPriv *priv = new JSCompositeFilterPriv(context, CompositeFilterPtr(filter)); + if (!JSObjectSetPrivate(object, priv)) + { + delete priv; + } + } +} + +void JSCompositeFilter::Finalize(JSObjectRef object) +{ + JSCompositeFilterPriv *priv = static_cast<JSCompositeFilterPriv*>(JSObjectGetPrivate(object)); + + if (priv != NULL) + { + delete (priv); + } + + priv = NULL; +} + +CompositeFilterPtr JSCompositeFilter::getPrivData(JSObjectRef object) +{ + LoggerD("entered"); + JSCompositeFilterPriv *priv = static_cast<JSCompositeFilterPriv*>(JSObjectGetPrivate(object)); + if (!priv) + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Private object is null"); + + CompositeFilterPtr result = priv->getObject(); + if (!result) + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Private object is null"); + + return result; +} + +bool JSCompositeFilter::setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + LoggerD("entered"); + + try + { + CompositeFilterPtr compositeFilter = getPrivData(object); + std::string name = JSUtil::JSStringToString(context, propertyName); + if(name == ATTRIBUTE_FILTER_ATTR_FILTERS) + { + if(!JSIsArrayValue(context, value)) + return true; + + return false; + } + } + catch(BasePlatformException &e) + { + LoggerW("trying to set incorrect value [" << e.getName() << "] " << e.getMessage()); + } + + return false; +} + +JSValueRef JSCompositeFilter::getType(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LoggerD("entered"); + + try + { + CompositeFilterPtr compositeFilter = getPrivData(object); + FilterType type = compositeFilter->getFilterType(); + std::string typeStr; + if(type == UNION_FILTER) + typeStr = "UNION"; + else if(type == INTERSECTION_FILTER) + typeStr = "INTERSECTION"; + else + typeStr = "UNION"; + + return JSUtil::toJSValueRef(context, typeStr); + } + catch(BasePlatformException &e) + { + LoggerW("trying to get incorrect value [" << e.getName() << "] " << e.getMessage()); + } + + return JSValueMakeUndefined(context); +} + +bool JSCompositeFilter::setType(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + LoggerD("entered"); + + try + { + CompositeFilterPtr compositeFilter = getPrivData(object); + + FilterType type; + std::string typeStr = JSUtil::JSValueToString(context, value); + + if(typeStr == "UNION") + type = UNION_FILTER; + else if(typeStr == "INTERSECTION") + type = INTERSECTION_FILTER; + else + throw TypeMismatchException("Property is not valid CompositeFilterType value"); + + compositeFilter->setFilterType(type); + } + catch(BasePlatformException &e) + { + LoggerW("trying to set incorrect value [" << e.getName() << "] " << e.getMessage()); + } + + return true; +} + +} // Tizen +} // DeviceAPI diff --git a/wearable_src/Tizen/JSCompositeFilter.h b/wearable_src/Tizen/JSCompositeFilter.h new file mode 100644 index 0000000..68cef4d --- /dev/null +++ b/wearable_src/Tizen/JSCompositeFilter.h @@ -0,0 +1,113 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 JSCompositeFilter.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief Declaration of the JSCompositeFilter class + */ + +#ifndef _TIZEN_TIZEN_JS_COMPOSITE_FILTER_H_ +#define _TIZEN_TIZEN_JS_COMPOSITE_FILTER_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <dpl/shared_ptr.h> +#include <CommonsJavaScript/PrivateObject.h> +#include <Commons/IEvent.h> +#include "CompositeFilter.h" + +namespace DeviceAPI { +namespace Tizen { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject<DeviceAPI::Tizen::CompositeFilterPtr, WrtDeviceApis::CommonsJavaScript::NoOwnership> JSCompositeFilterPriv; + +class JSCompositeFilter { +public: + /* + * This initializes this JS class in the JS Engine. + */ + static JSClassRef getClassRef(); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + static DeviceAPI::Tizen::CompositeFilterPtr getCompositeFilter(JSContextRef context, JSValueRef value); + + static JSObjectRef createJSObject(JSContextRef context, + DeviceAPI::Tizen::CompositeFilterPtr privateData, + JSValueRef jsValueFilters); + + static JSObjectRef constructor(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 contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_functions[]; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; + + static JSClassRef m_classRef; + + static DeviceAPI::Tizen::CompositeFilterPtr getPrivData(JSObjectRef object); + + static bool setProperty(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef getType(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setType(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); +}; + +} // Tizen +} // DeviceAPI + + +#endif // _TIZEN_TIZEN_JS_COMPOSITE_FILTER_H_ diff --git a/wearable_src/Tizen/JSSimpleCoordinates.cpp b/wearable_src/Tizen/JSSimpleCoordinates.cpp new file mode 100644 index 0000000..4fcd71a --- /dev/null +++ b/wearable_src/Tizen/JSSimpleCoordinates.cpp @@ -0,0 +1,294 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 JSSimpleCoordinates.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief Implementation of the JSSimpleCoordinates class + */ + +#include "JSSimpleCoordinates.h" + +#include <string> +#include <dpl/shared_ptr.h> +#include <JSUtil.h> +#include <ArgumentValidator.h> +#include <JSWebAPIErrorFactory.h> +#include <Logger.h> + +#define ATTRIBUTE_FILTER_CLASS_NAME "SimpleCoordinates" + +#define ATTRIBUTE_FILTER_ATTR_LATITUDE "latitude" +#define ATTRIBUTE_FILTER_ATTR_LONGITUDE "longitude" + +namespace DeviceAPI {
namespace Tizen { + +using namespace DeviceAPI::Common; +using namespace DeviceAPI::Tizen; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +JSClassRef JSSimpleCoordinates::m_classRef = NULL; + +JSClassDefinition JSSimpleCoordinates::m_classInfo = +{ + 0, + kJSClassAttributeNone, + ATTRIBUTE_FILTER_CLASS_NAME, + NULL, + m_property, + m_functions, + Initialize, + Finalize, + NULL, //hasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //getPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL, //ConvertToType, +}; + +JSStaticValue JSSimpleCoordinates::m_property[] = { + { ATTRIBUTE_FILTER_ATTR_LATITUDE, getLatitude, setLatitude, kJSPropertyAttributeNone }, + { ATTRIBUTE_FILTER_ATTR_LONGITUDE, getLongitude, setLongitude, kJSPropertyAttributeNone }, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSSimpleCoordinates::m_functions[] = +{ + { 0, 0, 0 } +}; + +JSClassRef JSSimpleCoordinates::getClassRef() { + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +bool JSSimpleCoordinates::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +SimpleCoordinatesPtr JSSimpleCoordinates::getSimpleCoordinates(JSContextRef context, JSValueRef value) +{ + if (!isObjectOfClass(context, value)) + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + + JSSimpleCoordinatesPriv *priv = static_cast<JSSimpleCoordinatesPriv*>(JSObjectGetPrivate(object)); + if (!priv) + Throw(WrtDeviceApis::Commons::NullPointerException); + + return priv->getObject(); +} + +JSObjectRef JSSimpleCoordinates::createJSObject(JSContextRef context, SimpleCoordinatesPtr privateData) +{ + JSSimpleCoordinatesPriv *priv = new JSSimpleCoordinatesPriv(context, privateData); + JSObjectRef jsObjectRef = JSObjectMake(context, getClassRef(), static_cast<void*>(priv)); + if (NULL == jsObjectRef) + { + LoggerE("object creation error"); + return NULL; + } + return jsObjectRef; +} + +JSObjectRef JSSimpleCoordinates::constructor(JSContextRef context, + JSObjectRef constructor, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("entered"); + + ArgumentValidator validator(context, argumentCount, arguments); + + double latitude; + double longitude; + + try + { + latitude = validator.toDouble(0, false); + } + catch(BasePlatformException &e) + { + LoggerW("Failed to convert 1st parameter to double. Using default value."); + latitude = 0.0; + } + + try + { + longitude = validator.toDouble(1, false); + } + catch(BasePlatformException &e) + { + LoggerW("Failed to convert 2nd parameter to double. Using default value."); + longitude = 0.0; + } + + SimpleCoordinatesPtr simpleCoordinates(new SimpleCoordinates(latitude, longitude)); + + JSObjectRef jsobject = NULL; + + Try + { + jsobject = createJSObject(context, simpleCoordinates); + } + Catch(Exception) + { + LoggerE("Argument type mismatch : " << _rethrown_exception.GetMessage()); + } + + if(jsobject == NULL) + return JSObjectMake(context, NULL, NULL); + + return jsobject; +} + +void JSSimpleCoordinates::Initialize(JSContextRef context, JSObjectRef object) +{ + if (!JSObjectGetPrivate(object)) + { + SimpleCoordinatesPtr coord(new SimpleCoordinates(0.0, 0.0)); + JSSimpleCoordinatesPriv *priv = new JSSimpleCoordinatesPriv(context, SimpleCoordinatesPtr(coord)); + if (!JSObjectSetPrivate(object, priv)) + { + delete priv; + } + } +} + +void JSSimpleCoordinates::Finalize(JSObjectRef object) +{ + JSSimpleCoordinatesPriv *priv = static_cast<JSSimpleCoordinatesPriv*>(JSObjectGetPrivate(object)); + + if (priv != NULL) + { + delete (priv); + } + + priv = NULL; +} + +SimpleCoordinatesPtr JSSimpleCoordinates::getPrivData(JSObjectRef object) +{ + LoggerD("entered"); + JSSimpleCoordinatesPriv *priv = static_cast<JSSimpleCoordinatesPriv*>(JSObjectGetPrivate(object)); + if (!priv) + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Private object is null"); + + SimpleCoordinatesPtr result = priv->getObject(); + if (!result) + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Private object is null"); + + return result; +} + +JSValueRef JSSimpleCoordinates::getLatitude(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LoggerD("entered"); + + try + { + SimpleCoordinatesPtr simpleCoordinates = getPrivData(object); + return JSUtil::toJSValueRef(context, simpleCoordinates->getLatitude()); + } + catch(BasePlatformException &e) + { + LoggerW("trying to get incorrect value [" << e.getName() << "] " << e.getMessage()); + } + + return JSValueMakeUndefined(context); +} + +bool JSSimpleCoordinates::setLatitude(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + LoggerD("entered"); + + try + { + SimpleCoordinatesPtr simpleCoordinates = getPrivData(object); + simpleCoordinates->setLatitude(JSUtil::JSValueToDouble(context, value)); + } + catch(BasePlatformException &e) + { + LoggerW("trying to set incorrect value [" << e.getName() << "] " << e.getMessage()); + } + + return true; +} + +JSValueRef JSSimpleCoordinates::getLongitude(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LoggerD("entered"); + + try + { + SimpleCoordinatesPtr simpleCoordinates = getPrivData(object); + return JSUtil::toJSValueRef(context, simpleCoordinates->getLongitude()); + } + catch(BasePlatformException &e) + { + LoggerW("trying to get incorrect value [" << e.getName() << "] " << e.getMessage()); + } + + return JSValueMakeUndefined(context); +} + +bool JSSimpleCoordinates::setLongitude(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + LoggerD("entered"); + + try + { + SimpleCoordinatesPtr simpleCoordinates = getPrivData(object); + simpleCoordinates->setLongitude(JSUtil::JSValueToDouble(context, value)); + } + catch(BasePlatformException &e) + { + LoggerW("trying to set incorrect value [" << e.getName() << "] " << e.getMessage()); + } + + return true; +} + +} // Tizen +} // DeviceAPI diff --git a/wearable_src/Tizen/JSSimpleCoordinates.h b/wearable_src/Tizen/JSSimpleCoordinates.h new file mode 100644 index 0000000..4b9f8de --- /dev/null +++ b/wearable_src/Tizen/JSSimpleCoordinates.h @@ -0,0 +1,115 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 JSSimpleCoordinates.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief Declaration of the JSSimpleCoordinates class + */ + +#ifndef _TIZEN_TIZEN_JS_SIMPLE_COORDINATES_H_ +#define _TIZEN_TIZEN_JS_SIMPLE_COORDINATES_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <dpl/shared_ptr.h> +#include <CommonsJavaScript/PrivateObject.h> +#include <Commons/IEvent.h> +#include "SimpleCoordinates.h" + +namespace DeviceAPI {
namespace Tizen { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject<DeviceAPI::Tizen::SimpleCoordinatesPtr, WrtDeviceApis::CommonsJavaScript::NoOwnership> JSSimpleCoordinatesPriv; + +class JSSimpleCoordinates { +public: + /* + * This initializes this JS class in the JS Engine. + */ + static JSClassRef getClassRef(); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + static DeviceAPI::Tizen::SimpleCoordinatesPtr getSimpleCoordinates(JSContextRef context, JSValueRef value); + + static JSObjectRef createJSObject(JSContextRef context, DeviceAPI::Tizen::SimpleCoordinatesPtr privateData); + + static JSObjectRef constructor(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 contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_functions[]; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; + + static JSClassRef m_classRef; + + static DeviceAPI::Tizen::SimpleCoordinatesPtr getPrivData(JSObjectRef object); + + static JSValueRef getLatitude(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setLatitude(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef getLongitude(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setLongitude(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); +}; + +} // Tizen +} // DeviceAPI + + +#endif // _TIZEN_TIZEN_JS_SIMPLE_COORDINATES_H_ diff --git a/wearable_src/Tizen/JSSortMode.cpp b/wearable_src/Tizen/JSSortMode.cpp new file mode 100644 index 0000000..3d6e41d --- /dev/null +++ b/wearable_src/Tizen/JSSortMode.cpp @@ -0,0 +1,327 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 JSSortMode.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief Implementation of the JSSortMode class + */ + +#include "JSSortMode.h" +#include <string> +#include <dpl/shared_ptr.h> +#include <JSUtil.h> +#include <ArgumentValidator.h> +#include <JSWebAPIErrorFactory.h> +#include <Logger.h> + +#define ATTRIBUTE_FILTER_CLASS_NAME "SortMode" + +#define ATTRIBUTE_FILTER_ATTR_ATTRIBUTE_NAME "attributeName" +#define ATTRIBUTE_FILTER_ATTR_ORDER "order" + +namespace DeviceAPI {
namespace Tizen { + +using namespace DeviceAPI::Common; +using namespace DeviceAPI::Tizen; +using namespace WrtDeviceApis::Commons; +using namespace WrtDeviceApis::CommonsJavaScript; + +JSClassRef JSSortMode::m_classRef = NULL; + +JSClassDefinition JSSortMode::m_classInfo = +{ + 0, + kJSClassAttributeNone, + ATTRIBUTE_FILTER_CLASS_NAME, + NULL, + m_property, + m_functions, + Initialize, + Finalize, + NULL, //hasProperty, + NULL, //GetProperty, + NULL, //SetProperty, + NULL, //DeleteProperty, + NULL, //getPropertyNames, + NULL, //CallAsFunction, + NULL, //CallAsConstructor, + NULL, //HasInstance, + NULL, //ConvertToType, +}; + +JSStaticValue JSSortMode::m_property[] = { + { ATTRIBUTE_FILTER_ATTR_ATTRIBUTE_NAME, getAttributeName, setAttributeName, kJSPropertyAttributeNone }, + { ATTRIBUTE_FILTER_ATTR_ORDER, getOrder, setOrder, kJSPropertyAttributeNone }, + { 0, 0, 0, 0 } +}; + +JSStaticFunction JSSortMode::m_functions[] = +{ + { 0, 0, 0 } +}; + +JSClassRef JSSortMode::getClassRef() +{ + if (!m_classRef) + m_classRef = JSClassCreate(&m_classInfo); + + return m_classRef; +} + +bool JSSortMode::isObjectOfClass(JSContextRef context, JSValueRef value) +{ + return JSValueIsObjectOfClass(context, value, getClassRef()); +} + +SortModePtr JSSortMode::getSortMode(JSContextRef context, JSValueRef value) +{ + if (!isObjectOfClass(context, value)) + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + + JSObjectRef object = JSValueToObject(context, value, NULL); + if (!object) + Throw(WrtDeviceApis::Commons::InvalidArgumentException); + + JSSortModePriv *priv = static_cast<JSSortModePriv*>(JSObjectGetPrivate(object)); + if (!priv) + Throw(WrtDeviceApis::Commons::NullPointerException); + + return priv->getObject(); +} + +JSObjectRef JSSortMode::createJSObject(JSContextRef context, SortModePtr privateData) +{ + JSSortModePriv *priv = new JSSortModePriv(context, privateData); + JSObjectRef jsObjectRef = JSObjectMake(context, getClassRef(), static_cast<void*>(priv)); + if (NULL == jsObjectRef) { + LoggerE("object creation error"); + return NULL; + } + return jsObjectRef; +} + +JSObjectRef JSSortMode::constructor(JSContextRef context, + JSObjectRef constructor, + size_t argumentCount, + const JSValueRef arguments[], + JSValueRef* exception) +{ + LoggerD("entered"); + + std::string attributeName; + SortOrder sortOrder; + + ArgumentValidator validator(context, argumentCount, arguments); + + try + { + attributeName = validator.toString(0, false); + } + catch(BasePlatformException &e) + { + LoggerW("Failed to convert 1st parameter to string. Using default value."); + attributeName = ""; + } + + try + { + std::string sortOrderStr; + if(argumentCount < 2 || + JSValueIsUndefined(context, arguments[1]) || + JSValueIsNull(context, arguments[1])) + sortOrderStr = "ASC"; + else + sortOrderStr = validator.toString(1, true); + + if(sortOrderStr == "ASC") + sortOrder = ASCENDING_SORT_ORDER; + else if(sortOrderStr == "DESC") + sortOrder = DESCENDING_SORT_ORDER; + else + throw TypeMismatchException("Property is not valid SortModeOrder value"); + } + catch(BasePlatformException &e) + { + LoggerW("Failed to convert 2nd parameter to sort order. Using default value."); + sortOrder = ASCENDING_SORT_ORDER; + } + + SortModePtr sortMode(new SortMode(attributeName, sortOrder)); + + JSObjectRef jsobject = NULL; + + Try + { + jsobject = createJSObject(context, sortMode); + } + Catch(Exception) + { + LoggerE("Argument type mismatch : " << _rethrown_exception.GetMessage()); + } + + if(jsobject == NULL) + return JSObjectMake(context, NULL, NULL); + + return jsobject; +} + +void JSSortMode::Initialize(JSContextRef context, JSObjectRef object) +{ + if (!JSObjectGetPrivate(object)) + { + SortModePtr sortMode(new SortMode("")); + JSSortModePriv *priv = new JSSortModePriv(context, SortModePtr(sortMode)); + if (!JSObjectSetPrivate(object, priv)) + { + delete priv; + } + } +} + +void JSSortMode::Finalize(JSObjectRef object) +{ + JSSortModePriv *priv = static_cast<JSSortModePriv*>(JSObjectGetPrivate(object)); + + if (priv != NULL) + { + delete (priv); + } + + priv = NULL; +} + +SortModePtr JSSortMode::getPrivData(JSObjectRef object) +{ + LoggerD("entered"); + JSSortModePriv *priv = static_cast<JSSortModePriv*>(JSObjectGetPrivate(object)); + if (!priv) + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Private object is null"); + + SortModePtr result = priv->getObject(); + if (!result) + ThrowMsg(WrtDeviceApis::Commons::NullPointerException, "Private object is null"); + + return result; +} + +JSValueRef JSSortMode::getAttributeName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LoggerD("entered"); + + try + { + SortModePtr sortMode = getPrivData(object); + return JSUtil::toJSValueRef(context, sortMode->getAttributeName()); + } + catch(BasePlatformException &e) + { + LoggerW("trying to get incorrect value [" << e.getName() << "] " << e.getMessage()); + } + + return JSValueMakeUndefined(context); +} + +bool JSSortMode::setAttributeName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + LoggerD("entered"); + + try + { + SortModePtr sortMode = getPrivData(object); + sortMode->setAttributeName(JSUtil::JSValueToString(context, value)); + } + catch(BasePlatformException &e) + { + LoggerW("trying to set incorrect value [" << e.getName() << "] " << e.getMessage()); + } + + return true; +} + +JSValueRef JSSortMode::getOrder(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception) +{ + LoggerD("entered"); + + try + { + SortModePtr sortMode = getPrivData(object); + SortOrder order = sortMode->getOrder(); + std::string orderStr; + if(order == ASCENDING_SORT_ORDER) + orderStr = "ASC"; + else if(order == DESCENDING_SORT_ORDER) + orderStr = "DESC"; + else + orderStr = "ASC"; + + return JSUtil::toJSValueRef(context, orderStr); + } + catch(BasePlatformException &e) + { + LoggerW("trying to get incorrect value [" << e.getName() << "] " << e.getMessage()); + } + + return JSValueMakeUndefined(context); +} + +bool JSSortMode::setOrder(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception) +{ + LoggerD("entered"); + + try + { + SortModePtr sortMode = getPrivData(object); + + SortOrder order; + std::string orderStr = JSUtil::JSValueToString(context, value); + + if(orderStr == "ASC") + order = ASCENDING_SORT_ORDER; + else if(orderStr == "DESC") + order = DESCENDING_SORT_ORDER; + else + throw TypeMismatchException("Property is not valid SortModeOrder value"); + + sortMode->setOrder(order); + } + catch(BasePlatformException &e) + { + LoggerW("trying to set incorrect value [" << e.getName() << "] " << e.getMessage()); + } + + return true; +} + +} // Tizen +} // DeviceAPI + diff --git a/wearable_src/Tizen/JSSortMode.h b/wearable_src/Tizen/JSSortMode.h new file mode 100644 index 0000000..22d7b91 --- /dev/null +++ b/wearable_src/Tizen/JSSortMode.h @@ -0,0 +1,115 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 JSSortMode.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief Declaration of the JSSortMode class + */ + +#ifndef _TIZEN_TIZEN_JS_SORT_MODE_H_ +#define _TIZEN_TIZEN_JS_SORT_MODE_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <dpl/shared_ptr.h> +#include <CommonsJavaScript/PrivateObject.h> +#include <Commons/IEvent.h> +#include "SortMode.h" + +namespace DeviceAPI {
namespace Tizen { + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObject<DeviceAPI::Tizen::SortModePtr, WrtDeviceApis::CommonsJavaScript::NoOwnership> JSSortModePriv; + +class JSSortMode { +public: + /* + * This initializes this JS class in the JS Engine. + */ + static JSClassRef getClassRef(); + + static bool isObjectOfClass(JSContextRef context, JSValueRef value); + + static DeviceAPI::Tizen::SortModePtr getSortMode(JSContextRef context, JSValueRef value); + + static JSObjectRef createJSObject(JSContextRef context, DeviceAPI::Tizen::SortModePtr privateData); + + static JSObjectRef constructor(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 contains properties and callbacks that define a type of object. + */ + static JSClassDefinition m_classInfo; + + /** + * This structure describes a statically declared function property. + */ + static JSStaticFunction m_functions[]; + + /** + * This member variable contains the initialization values for the static properties of this class. + * The values are given according to the data structure JSPropertySpec + */ + static JSStaticValue m_property[]; + + static JSClassRef m_classRef; + + static DeviceAPI::Tizen::SortModePtr getPrivData(JSObjectRef object); + + static JSValueRef getAttributeName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setAttributeName(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); + + static JSValueRef getOrder(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef* exception); + + static bool setOrder(JSContextRef context, + JSObjectRef object, + JSStringRef propertyName, + JSValueRef value, + JSValueRef* exception); +}; + +} // Tizen +} // DeviceAPI + + +#endif // _TIZEN_TIZEN_JS_SORT_MODE_H_ diff --git a/wearable_src/Tizen/JSTizen.cpp b/wearable_src/Tizen/JSTizen.cpp new file mode 100644 index 0000000..6909a26 --- /dev/null +++ b/wearable_src/Tizen/JSTizen.cpp @@ -0,0 +1,246 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 JSTizen.cpp + * @author + * @version 0.1 + * @brief + */ + +#include <vector> +#include <CommonsJavaScript/PrivateObject.h> +#include <CommonsJavaScript/Converter.h> +#include <Commons/WrtAccess/WrtAccess.h> +#include <CommonsJavaScript/JSDOMExceptionFactory.h> +#include "FilterTypes.h" +#include "AnyType.h" +#include "JSTizen.h" +#include "plugin_config.h" +#include <WidgetDB/WidgetDBMgr.h> +#include <WidgetDB/IWidgetDB.h> +#include <PluginManager/PluginManagerFactory.h> +#include <iostream> +#include <Logger.h> + +#define PLUGIN_NAME "tizen" + +namespace DeviceAPI {
namespace Tizen { + +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; +using namespace DeviceAPI::Tizen; +using namespace WrtDeviceApis::PluginManager::Api; + +JSClassDefinition JSTizen::m_classInfo = +{ + 0, + kJSClassAttributeNone, + PLUGIN_NAME, + 0, + m_properties, + m_functions, + initialize, + finalize, + hasProperty, + getProperty, + setProperty, + NULL, //deleteProperty, + getPropertyNames, + NULL, + NULL, + hasInstance, + convertToType +}; + +JSStaticValue JSTizen::m_properties[] = { + { 0, 0, 0 } +}; + +JSStaticFunction JSTizen::m_functions[] = { + { 0, 0, 0 } +}; + +const JSClassDefinition* JSTizen::getClassInfo() +{ + return &m_classInfo; +} + +JSClassRef JSTizen::m_classRef = JSClassCreate(JSTizen::getClassInfo()); + +void JSTizen::initialize(JSContextRef context, JSObjectRef object) +{ + LoggerD("entered"); + TizenPrivate* priv = static_cast<TizenPrivate*>(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + if (priv) { + delete priv; + } + + int widgetId = WrtAccessSingleton::Instance().getWidgetId(); + PluginOnDemandPrivPtr privObject( + new PluginOnDemandPriv( + PluginManagerFactory::getInstance().getPluginManager( + widgetId, + PLUGIN_NAME, + object, + context))); + + priv = new TizenPrivate(context, privObject); + if (!JSObjectSetPrivate(object, static_cast<void*>(priv))) { + JSObjectSetPrivate(object, NULL); + delete priv; + } +} + +void JSTizen::finalize(JSObjectRef object) +{ + LoggerD("entered"); + TizenPrivate* priv = static_cast<TizenPrivate*>(JSObjectGetPrivate(object)); + JSObjectSetPrivate(object, NULL); + delete priv; +} + +JSClassRef JSTizen::getClassRef() +{ + if (!m_classRef) { + m_classRef = JSClassCreate(&m_classInfo); + } + return m_classRef; +} + +//bool JSTizen::deleteProperty(JSContextRef context, JSObjectRef object, +// JSStringRef propertyName, JSValueRef* exception) +//{ +// return true; +//} + +void JSTizen::getPropertyNames(JSContextRef context, JSObjectRef object, + JSPropertyNameAccumulatorRef propertyNames) +{ + Try + { + TizenPrivate* priv = + static_cast<TizenPrivate*>(JSObjectGetPrivate(object)); + if (!priv || !priv->getObject()) { + LoggerE("No private obejct"); + return; + } + PluginOnDemandPrivPtr privObj = priv->getObject(); + privObj->getPluginManager()->addPropertiesToList(propertyNames); + + } + Catch(Commons::Exception) + { + LoggerE("Error occured"); + } +} + +bool JSTizen::hasInstance(JSContextRef context, JSObjectRef constructor, + JSValueRef possibleInstance, JSValueRef* exception) +{ + return true; +} + +JSValueRef JSTizen::convertToType(JSContextRef context, JSObjectRef object, + JSType type, JSValueRef* exception) +{ + return JSValueMakeUndefined(context); +} + +bool JSTizen::hasProperty(JSContextRef context, + JSObjectRef object, JSStringRef propertyName) +{ + Try + { + TizenPrivate* priv = static_cast<TizenPrivate*>(JSObjectGetPrivate(object)); + + if (!priv || !priv->getObject()) { + LoggerE("No private obejct"); + return false; + } + + return priv->getObject()->getPluginManager()->hasChild( + CommonsJavaScript::Converter(context).toString(propertyName)); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LoggerE("Error occured"); + } + + //let JSCore to handle this property + return false; +} + +JSValueRef JSTizen::getProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception) +{ + Try + { + TizenPrivate* priv = + static_cast<TizenPrivate*>(JSObjectGetPrivate(object)); + if (!priv || !priv->getObject()) { + LoggerE("No private obejct"); + return JSValueMakeUndefined(context); + } + + return priv->getObject()->getPluginManager()->getProperty( + CommonsJavaScript::Converter(context).toString(propertyName)); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LoggerE("Error occured"); + } + + /* During normal operation flow should not reach here, + but wrt may fail with loading plugin. */ + return JSValueMakeUndefined(context); +} + +bool JSTizen::setProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + Try + { + TizenPrivate* priv = + static_cast<TizenPrivate*>(JSObjectGetPrivate(object)); + if (!priv || !priv->getObject()) { + LoggerE("No private obejct"); + return false; + } + std::string strPropertyName = CommonsJavaScript::Converter(context).toString(propertyName); + if(!priv->getObject()->propertyInited(strPropertyName)) + { + priv->getObject()->getPluginManager()->setProperty( + strPropertyName, + value); + } + } + Catch(WrtDeviceApis::Commons::Exception) + { + LoggerE("Error occured"); + } + + //this code should not be reached. setProperty is not called when + //hasProperty returns false. Anyway, if we didn't set value then we + //return false. + return false; +} + +} // Tizen +} // DeviceAPI + diff --git a/wearable_src/Tizen/JSTizen.h b/wearable_src/Tizen/JSTizen.h new file mode 100644 index 0000000..ae93ce4 --- /dev/null +++ b/wearable_src/Tizen/JSTizen.h @@ -0,0 +1,131 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 JSTizen.h + * @author + * @version 0.1 + * @brief + */ + +#ifndef _WRT_PLUGIN_JS_DEVICE_APIS_H_ +#define _WRT_PLUGIN_JS_DEVICE_APIS_H_ + +#include <JavaScriptCore/JavaScript.h> +#include <CommonsJavaScript/PrivateObject.h> +#include "PluginOnDemandPriv.h" + + +namespace DeviceAPI {
namespace Tizen { + +/** + * @class JSBondi + * @brief This class is javascript extenstion + * + */ + +typedef WrtDeviceApis::CommonsJavaScript::PrivateObjectT<PluginOnDemandPrivPtr>::Type TizenPrivate; + + +class JSTizen { +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); + + /** + * The callback invoked when determining whether an object has a property. + */ + 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 setting a property's value. + */ + static bool setProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef value, JSValueRef* exception); + + /** + * The callback invoked when deleting a property. + */ + static bool deleteProperty(JSContextRef context, JSObjectRef object, + JSStringRef propertyName, JSValueRef* exception); + + /** + * The callback invoked when collecting the names of an object's properties. + */ + static void getPropertyNames(JSContextRef ctx, JSObjectRef object, + JSPropertyNameAccumulatorRef propertyNames); + + /** + * The callback invoked when an object is used as the target of an 'instanceof' expression. + */ + static bool hasInstance(JSContextRef ctx, JSObjectRef constructor, + JSValueRef possibleInstance, JSValueRef* exception); + + /** + * The callback invoked when converting an object to a particular JavaScript type. + */ + static JSValueRef convertToType(JSContextRef ctx, JSObjectRef object, + JSType type, JSValueRef* exception); + + /** + * This structure describes a statically declared value property. + */ + static JSStaticValue m_properties[]; + + /** + * 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_functions[]; + + static JSClassRef m_classRef; +}; + +} // Tizen +} // DeviceAPI + + +#endif // _WRT_PLUGIN_JS_XXX_H_ diff --git a/wearable_src/Tizen/PluginOnDemandPriv.cpp b/wearable_src/Tizen/PluginOnDemandPriv.cpp new file mode 100644 index 0000000..3d9027e --- /dev/null +++ b/wearable_src/Tizen/PluginOnDemandPriv.cpp @@ -0,0 +1,57 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 PluginOnDemandPriv.cpp + * @author + * @version 0.1 + * @brief + */ + +#include "PluginOnDemandPriv.h" + +namespace DeviceAPI {
namespace Tizen { + +using namespace WrtDeviceApis::PluginManager::Api; + +PluginOnDemandPriv::PluginOnDemandPriv(const IPluginManagerPtr &pluginManager) : + m_pluginManager(pluginManager) +{ +} + +PluginOnDemandPriv::~PluginOnDemandPriv() +{ +} + +IPluginManagerPtr PluginOnDemandPriv::getPluginManager() const +{ + return m_pluginManager; +} + +bool PluginOnDemandPriv::propertyInited(std::string &propertyName) +{ + if(m_initedProperties.find(propertyName) == m_initedProperties.end()) + { + m_initedProperties.insert(propertyName); + return false; + } + + return true; +} + +} +} diff --git a/wearable_src/Tizen/PluginOnDemandPriv.h b/wearable_src/Tizen/PluginOnDemandPriv.h new file mode 100644 index 0000000..8c2c322 --- /dev/null +++ b/wearable_src/Tizen/PluginOnDemandPriv.h @@ -0,0 +1,60 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 PluginOnDemandPriv.h + * @author + * @version 0.1 + * @brief + */ + +#ifndef _WRT_PLUGIN_STANDARDS_TIZEN_DEVICEAPIS_PLUGIN_ON_DEMAND_PRIV +#define _WRT_PLUGIN_STANDARDS_TIZEN_DEVICEAPIS_PLUGIN_ON_DEMAND_PRIV + +#include <map> +#include <set> +#include <string> +#include <dpl/shared_ptr.h> +#include <JavaScriptCore/JavaScript.h> +#include <PluginManager/IPluginManager.h> + +namespace DeviceAPI {
namespace Tizen { + +class PluginOnDemandPriv +{ + public: + PluginOnDemandPriv( + const WrtDeviceApis::PluginManager::Api::IPluginManagerPtr &pluginManager); + + virtual ~PluginOnDemandPriv(); + + WrtDeviceApis::PluginManager::Api::IPluginManagerPtr getPluginManager() const; + + bool propertyInited(std::string &propertyName); + + private: + WrtDeviceApis::PluginManager::Api::IPluginManagerPtr m_pluginManager; + + std::set<std::string> m_initedProperties; +}; + +typedef DPL::SharedPtr<PluginOnDemandPriv> PluginOnDemandPrivPtr; + +} +} + +#endif diff --git a/wearable_src/Tizen/SimpleCoordinates.cpp b/wearable_src/Tizen/SimpleCoordinates.cpp new file mode 100644 index 0000000..b02ec03 --- /dev/null +++ b/wearable_src/Tizen/SimpleCoordinates.cpp @@ -0,0 +1,63 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 SimpleCoordinates.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include "SimpleCoordinates.h" + +namespace DeviceAPI {
namespace Tizen { + +using namespace std; + +SimpleCoordinates::SimpleCoordinates(const double latitude, + const double longitude) : + m_latitude(latitude), + m_longitude(longitude) +{ +} + +SimpleCoordinates::~SimpleCoordinates() +{ +} + +double SimpleCoordinates::getLatitude() const +{ + return m_latitude; +} + +void SimpleCoordinates::setLatitude(const double value) +{ + m_latitude = value; +} + +double SimpleCoordinates::getLongitude() const +{ + return m_longitude; +} + +void SimpleCoordinates::setLongitude(const double value) +{ + m_longitude = value; +} + +} // Tizen +} // DeviceAPI diff --git a/wearable_src/Tizen/SimpleCoordinates.h b/wearable_src/Tizen/SimpleCoordinates.h new file mode 100644 index 0000000..563be92 --- /dev/null +++ b/wearable_src/Tizen/SimpleCoordinates.h @@ -0,0 +1,71 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 SimpleCoordinates.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _API_SIMPLE_CORDINATES_H_ +#define _API_SIMPLE_CORDINATES_H_ + +#include <string> +#include <dpl/shared_ptr.h> + +namespace DeviceAPI {
namespace Tizen { + +class SimpleCoordinates +{ +private: // fields + + /** + * attribute latitude object + */ + double m_latitude; + + /** + * match value object. + */ + double m_longitude; + +protected: + +public: // methods + + /** + * constructor of SimpleCoorindates + */ + explicit SimpleCoordinates(const double latitude, + const double longitude); + + virtual ~SimpleCoordinates(); + + double getLatitude() const; + void setLatitude(const double value); + + double getLongitude() const; + void setLongitude(const double value); +}; + +typedef DPL::SharedPtr<SimpleCoordinates> SimpleCoordinatesPtr; + +} // Tizen +} // DeviceAPI + +#endif // _API_SIMPLE_CORDINATES_H_ diff --git a/wearable_src/Tizen/SortMode.cpp b/wearable_src/Tizen/SortMode.cpp new file mode 100644 index 0000000..de05708 --- /dev/null +++ b/wearable_src/Tizen/SortMode.cpp @@ -0,0 +1,59 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 SortMode.cpp + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#include "SortMode.h" + +namespace DeviceAPI {
namespace Tizen { +SortMode::SortMode(const std::string& attributeName, const SortOrder& order) : + m_attributeName(attributeName), + m_order(order) +{ +} + +SortMode::~SortMode() +{ +} + +SortOrder SortMode::getOrder() const +{ + return m_order; +} + +void SortMode::setOrder(SortOrder value) +{ + m_order = value; +} + +std::string SortMode::getAttributeName() const +{ + return m_attributeName; +} + +void SortMode::setAttributeName(const std::string &value) +{ + m_attributeName = value; +} + +} // Tizen +} // DeviceAPI diff --git a/wearable_src/Tizen/SortMode.h b/wearable_src/Tizen/SortMode.h new file mode 100644 index 0000000..800d07f --- /dev/null +++ b/wearable_src/Tizen/SortMode.h @@ -0,0 +1,64 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 SortMode.h + * @author Kisub Song (kisubs.song@samsung.com) + * @version 0.1 + * @brief + */ + +#ifndef _API_SORT_MODE_H_ +#define _API_SORT_MODE_H_ + +#include <string> +#include <vector> +#include <dpl/shared_ptr.h> + +#include "FilterTypes.h" + +namespace DeviceAPI {
namespace Tizen { + +class SortMode; +typedef DPL::SharedPtr<SortMode> SortModePtr; + +typedef std::vector<SortModePtr> SortModeArray; +typedef DPL::SharedPtr<SortModeArray> SortModeArrayPtr; + +class SortMode +{ +public: + SortMode(const std::string& attributeName, const SortOrder& order = ASCENDING_SORT_ORDER); + virtual ~SortMode(); + + SortOrder getOrder() const; + void setOrder(SortOrder value); + + std::string getAttributeName() const; + void setAttributeName(const std::string &value); + +protected: + std::string m_attributeName; + SortOrder m_order; +}; + +typedef DPL::SharedPtr<SortMode> SortModePtr; + +} // Tizen +} // DeviceAPI + +#endif // _API_SORT_MODE_H_ diff --git a/wearable_src/Tizen/config.xml b/wearable_src/Tizen/config.xml new file mode 100644 index 0000000..6bf9d83 --- /dev/null +++ b/wearable_src/Tizen/config.xml @@ -0,0 +1,22 @@ +<?xml version="1.0" ?> +<!DOCTYPE plugin-properties SYSTEM "/usr/etc/tizen-apis/config.dtd"> +<plugin-properties> + <library-name>libwrt-plugins-tizen-tizen.so</library-name> + <feature-install-uri>tizen.install.uri</feature-install-uri> + + <api-feature> + <name>http://tizen.org/privilege/tizen</name> + <Object name="tizen"> + <!-- + <Function name="listAvailableFeatures"/> + <Function name="listActivatedFeatures"/> + <Function name="createCompositeFilter"/> + <Function name="createAttributeFilter"/> + <Function name="createAttributeRangeFilter"/> + <Function name="createIDFilter"/> + <Function name="createSortMode"/> + --> + </Object> + </api-feature> +</plugin-properties> + diff --git a/wearable_src/Tizen/plugin_config.cpp b/wearable_src/Tizen/plugin_config.cpp new file mode 100644 index 0000000..95045f0 --- /dev/null +++ b/wearable_src/Tizen/plugin_config.cpp @@ -0,0 +1,98 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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_config.cpp + * @author + * @version 0.1 + * @brief + */ + +#include <map> +#include <utility> +#include <Commons/FunctionDefinition.h> +#include <Commons/FunctionDeclaration.h> +#include <Commons/Exception.h> + +#define TIZEN_FEATURE_API "http://tizen.org/privilege/tizen" + +namespace DeviceAPI {
namespace Tizen { + +const char* TIZEN_FUNCTION_API_LIST_AVAIL_FEATURES = + "listAvailableFeatures"; +const char* TIZEN_FUNCTION_API_LIST_ACTIV_FEATURES = + "listActivatedFeatures"; + +static WrtDeviceApis::Commons::FunctionMapping createDeviceApisFunctions(); + +static WrtDeviceApis::Commons::FunctionMapping DeviceApisFunctions = + createDeviceApisFunctions(); + +DEFINE_FUNCTION_GETTER(DeviceApis, DeviceApisFunctions); + +static WrtDeviceApis::Commons::FunctionMapping createDeviceApisFunctions() +{ + ACE_CREATE_DEVICE_CAPS_LIST(EMPTY_DEVICE_LIST); + + // + // --- features ---- + // + + ACE_CREATE_FEATURE(FEATURE_TIZEN,TIZEN_FEATURE_API); + + ACE_CREATE_FEATURE_LIST(FEATURE_LIST_TIZEN); + ACE_ADD_API_FEATURE(FEATURE_LIST_TIZEN,FEATURE_TIZEN); + + // + // --- functions --- + // + + WrtDeviceApis::Commons::FunctionMapping DeviceApisMapping; + + //LIST_AVAIL + WrtDeviceApis::Commons::AceFunction listAvailableFeaturesFuncs = ACE_CREATE_FUNCTION( + FUNCTION_LIST_AVAILABLE_FEATURES, + TIZEN_FUNCTION_API_LIST_AVAIL_FEATURES, + FEATURE_LIST_TIZEN, + EMPTY_DEVICE_LIST); + + DeviceApisMapping.insert( + std::make_pair( + TIZEN_FUNCTION_API_LIST_AVAIL_FEATURES, + listAvailableFeaturesFuncs)); + + //LIST_ACTIV + WrtDeviceApis::Commons::AceFunction listActivatedFeaturesFunc = ACE_CREATE_FUNCTION( + FUNCTION_LIST_ACTIVATED_FEATURES, + TIZEN_FUNCTION_API_LIST_ACTIV_FEATURES, + FEATURE_LIST_TIZEN, + EMPTY_DEVICE_LIST); + + DeviceApisMapping.insert( + std::make_pair( + TIZEN_FUNCTION_API_LIST_ACTIV_FEATURES, + listActivatedFeaturesFunc)); + + return DeviceApisMapping; +} + +} // Tizen +} // DeviceAPI + +#undef TIZEN_FEATURE_API +#undef TIZEN_FUNCTION_API_LIST_ACTIV_FEATURES +#undef TIZEN_FUNCTION_API_LIST_AVAIL_FEATURES diff --git a/wearable_src/Tizen/plugin_config.h b/wearable_src/Tizen/plugin_config.h new file mode 100644 index 0000000..df16776 --- /dev/null +++ b/wearable_src/Tizen/plugin_config.h @@ -0,0 +1,43 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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_config.h + * @author + * @version 0.1 + * @brief + */ + +#ifndef _TIZEN_PLUGIN_CONFIG_H_ +#define _TIZEN_PLUGIN_CONFIG_H_ + +#include <Commons/FunctionDeclaration.h> + +namespace DeviceAPI {
namespace Tizen { + +extern const char* TIZEN_FUNCTION_API_LIST_AVAIL_FEATURES; +extern const char* TIZEN_FUNCTION_API_LIST_ACTIV_FEATURES; +extern const char* TIZEN_FUNCTION_API_CREATE_COMPOSITE_FILTER; +extern const char* TIZEN_FUNCTION_API_CREATE_ATTRIBUTE_FILTER; +extern const char* TIZEN_FUNCTION_API_CREATE_ATTRIBUTE_RANGE_FILTER; +extern const char* TIZEN_FUNCTION_API_CREATE_ID_FILTER; +extern const char* TIZEN_FUNCTION_API_CREATE_SORT_MODE; + +} +} + +#endif // _TIZEN_PLUGIN_CONFIG_H_ diff --git a/wearable_src/Tizen/plugin_initializer.cpp b/wearable_src/Tizen/plugin_initializer.cpp new file mode 100644 index 0000000..f2f7a63 --- /dev/null +++ b/wearable_src/Tizen/plugin_initializer.cpp @@ -0,0 +1,132 @@ +// +// Tizen Web Device API +// Copyright (c) 2012 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 Karol Majewski (k.majewski@samsung.com) + * @version 0.1 + * @brief + */ + +#include <Commons/plugin_initializer_def.h> +#include <Commons/WrtAccess/WrtAccess.h> +#include <Commons/Exception.h> +#include "JSTizen.h" +#include "JSAttributeFilter.h" +#include "JSAttributeRangeFilter.h" +#include "JSCompositeFilter.h" +#include "JSSortMode.h" +#include "JSSimpleCoordinates.h" +#include <Logger.h> + +#define OBJECT_TIZEN "tizen" + +namespace Options{ + +class_definition_options_t TizenOptions = +{ + JS_CLASS, + CREATE_INSTANCE, + NONE_NOTICE, + USE_OVERLAYED, //ignored + NULL, + NULL +}; + +class_definition_options_t TizenInterfaceOptions = { + JS_INTERFACE, + CREATE_INSTANCE, + NONE_NOTICE, + USE_OVERLAYED, //ignored + NULL, // JSWidget::acquireGlobalContext, + NULL, + NULL +}; + +} + +namespace DeviceAPI { +namespace Tizen { + +using namespace WrtDeviceApis; +using namespace WrtDeviceApis::Commons; + +void on_widget_start_callback(int widgetId) +{ + LoggerD("[Tizen\\xxx] on_widget_start_callback ("<<widgetId<<")"); + Try + { + WrtAccessSingleton::Instance().initialize(widgetId); + } + Catch(Commons::Exception) + { + LoggerE("WrtAccess initialization failed"); + } +} + +void on_widget_stop_callback(int widgetId) +{ + LoggerD("[Tizen\\xxx] on_widget_stop_callback ("<<widgetId<<")"); + Try + { + WrtAccessSingleton::Instance().deinitialize(widgetId); + } + Catch(WrtDeviceApis::Commons::Exception) + { + LoggerE("WrtAccess deinitialization failed"); + } +} + +PLUGIN_ON_WIDGET_START(on_widget_start_callback) +PLUGIN_ON_WIDGET_STOP(on_widget_stop_callback) + +PLUGIN_CLASS_MAP_BEGIN + PLUGIN_CLASS_MAP_ADD_CLASS(WRT_JS_EXTENSION_OBJECT_GLOBAL, + OBJECT_TIZEN, + (js_class_template_getter)DeviceAPI::Tizen::JSTizen::getClassRef, + &Options::TizenOptions) + PLUGIN_CLASS_MAP_ADD_INTERFACE(OBJECT_TIZEN, + "AttributeFilter", + (js_class_template_getter)DeviceAPI::Tizen::JSAttributeFilter::getClassRef, + (js_class_constructor_cb_t)DeviceAPI::Tizen::JSAttributeFilter::constructor, + &Options::TizenInterfaceOptions) + PLUGIN_CLASS_MAP_ADD_INTERFACE(OBJECT_TIZEN, + "AttributeRangeFilter", + (js_class_template_getter)DeviceAPI::Tizen::JSAttributeRangeFilter::getClassRef, + (js_class_constructor_cb_t)DeviceAPI::Tizen::JSAttributeRangeFilter::constructor, + &Options::TizenInterfaceOptions) + PLUGIN_CLASS_MAP_ADD_INTERFACE(OBJECT_TIZEN, + "CompositeFilter", + (js_class_template_getter)DeviceAPI::Tizen::JSCompositeFilter::getClassRef, + (js_class_constructor_cb_t)DeviceAPI::Tizen::JSCompositeFilter::constructor, + &Options::TizenInterfaceOptions) + PLUGIN_CLASS_MAP_ADD_INTERFACE(OBJECT_TIZEN, + "SortMode", + (js_class_template_getter)DeviceAPI::Tizen::JSSortMode::getClassRef, + (js_class_constructor_cb_t)DeviceAPI::Tizen::JSSortMode::constructor, + &Options::TizenInterfaceOptions) + PLUGIN_CLASS_MAP_ADD_INTERFACE(OBJECT_TIZEN, + "SimpleCoordinates", + (js_class_template_getter)DeviceAPI::Tizen::JSSimpleCoordinates::getClassRef, + (js_class_constructor_cb_t)DeviceAPI::Tizen::JSSimpleCoordinates::constructor, + &Options::TizenInterfaceOptions) +PLUGIN_CLASS_MAP_END + +#undef OBJECT_TIZEN + +} // Tizen +} // DeviceAPI |